github.com/goplus/gop@v1.2.6/ast/mod/deps.go (about)

     1  /*
     2   * Copyright (c) 2022 The GoPlus Authors (goplus.org). All rights reserved.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package mod
    18  
    19  import (
    20  	"strconv"
    21  	"strings"
    22  
    23  	goast "go/ast"
    24  	gotoken "go/token"
    25  
    26  	"github.com/goplus/gop/ast"
    27  	"github.com/goplus/gop/token"
    28  )
    29  
    30  // ----------------------------------------------------------------------------
    31  
    32  type Deps struct {
    33  	HandlePkg func(pkgPath string)
    34  }
    35  
    36  func (p Deps) Load(pkg *ast.Package, withGopStd bool) {
    37  	for _, f := range pkg.Files {
    38  		p.LoadFile(f, withGopStd)
    39  	}
    40  	for _, f := range pkg.GoFiles {
    41  		p.LoadGoFile(f)
    42  	}
    43  }
    44  
    45  func (p Deps) LoadGoFile(f *goast.File) {
    46  	for _, imp := range f.Imports {
    47  		path := imp.Path
    48  		if path.Kind == gotoken.STRING {
    49  			if s, err := strconv.Unquote(path.Value); err == nil {
    50  				if s == "C" {
    51  					continue
    52  				}
    53  				p.HandlePkg(s)
    54  			}
    55  		}
    56  	}
    57  }
    58  
    59  func (p Deps) LoadFile(f *ast.File, withGopStd bool) {
    60  	for _, imp := range f.Imports {
    61  		path := imp.Path
    62  		if path.Kind == token.STRING {
    63  			if s, err := strconv.Unquote(path.Value); err == nil {
    64  				p.gopPkgPath(s, withGopStd)
    65  			}
    66  		}
    67  	}
    68  }
    69  
    70  func (p Deps) gopPkgPath(s string, withGopStd bool) {
    71  	if strings.HasPrefix(s, "gop/") {
    72  		if !withGopStd {
    73  			return
    74  		}
    75  		s = "github.com/goplus/gop/" + s[4:]
    76  	} else if strings.HasPrefix(s, "C") {
    77  		if len(s) == 1 {
    78  			s = "github.com/goplus/libc"
    79  		} else if s[1] == '/' {
    80  			s = s[2:]
    81  			if strings.IndexByte(s, '/') < 0 {
    82  				s = "github.com/goplus/" + s
    83  			}
    84  		}
    85  	}
    86  	p.HandlePkg(s)
    87  }
    88  
    89  // ----------------------------------------------------------------------------