github.com/gmemcc/yaegi@v0.12.1-0.20221128122509-aa99124c5d16/internal/cmd/extract/srcimporter/srcimporter.go (about) 1 // Copyright 2017 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package srcimporter implements importing directly 6 // from source files rather than installed packages. 7 package srcimporter // import "go/internal/srcimporter" 8 9 import ( 10 "fmt" 11 exec "github.com/gmemcc/yaegi/internal/cmd/extract/execabs" 12 "github.com/gmemcc/yaegi/internal/cmd/extract/types" 13 "go/ast" 14 "go/build" 15 "go/parser" 16 "go/token" 17 "io" 18 "os" 19 "path/filepath" 20 "strings" 21 "sync" 22 _ "unsafe" // for go:linkname 23 ) 24 25 // An Importer provides the context for importing packages from source code. 26 type Importer struct { 27 ctxt *build.Context 28 fset *token.FileSet 29 sizes types.Sizes 30 packages map[string]*types.Package 31 } 32 33 // NewImporter returns a new Importer for the given context, file set, and map 34 // of packages. The context is used to resolve import paths to package paths, 35 // and identifying the files belonging to the package. If the context provides 36 // non-nil file system functions, they are used instead of the regular package 37 // os functions. The file set is used to track position information of package 38 // files; and imported packages are added to the packages map. 39 func New(ctxt *build.Context, fset *token.FileSet, packages map[string]*types.Package) *Importer { 40 return &Importer{ 41 ctxt: ctxt, 42 fset: fset, 43 sizes: types.SizesFor(ctxt.Compiler, ctxt.GOARCH), // uses go/types default if GOARCH not found 44 packages: packages, 45 } 46 } 47 48 // Importing is a sentinel taking the place in Importer.packages 49 // for a package that is in the process of being imported. 50 var importing types.Package 51 52 // Import(path) is a shortcut for ImportFrom(path, ".", 0). 53 func (p *Importer) Import(path string, depth int) (*types.Package, error) { 54 return p.ImportFrom(path, ".", 0, depth) // use "." rather than "" (see issue #24441) 55 } 56 57 // ImportFrom imports the package with the given import path resolved from the given srcDir, 58 // adds the new package to the set of packages maintained by the importer, and returns the 59 // package. Package path resolution and file system operations are controlled by the context 60 // maintained with the importer. The import mode must be zero but is otherwise ignored. 61 // Packages that are not comprised entirely of pure Go files may fail to import because the 62 // type checker may not be able to determine all exported entities (e.g. due to cgo dependencies). 63 func (p *Importer) ImportFrom(path, srcDir string, mode types.ImportMode, depth int) (*types.Package, error) { 64 if mode != 0 { 65 panic("non-zero import mode") 66 } 67 68 if abs, err := p.absPath(srcDir); err == nil { // see issue #14282 69 srcDir = abs 70 } 71 bp, err := p.ctxt.Import(path, srcDir, 0) 72 if err != nil { 73 return nil, err // err may be *build.NoGoError - return as is 74 } 75 76 // package unsafe is known to the type checker 77 if bp.ImportPath == "unsafe" { 78 return types.Unsafe, nil 79 } 80 81 // no need to re-import if the package was imported completely before 82 pkg := p.packages[bp.ImportPath] 83 if pkg != nil { 84 if pkg == &importing { 85 return nil, fmt.Errorf("import cycle through package %q", bp.ImportPath) 86 } 87 if !pkg.Complete() { 88 // Package exists but is not complete - we cannot handle this 89 // at the moment since the source importer replaces the package 90 // wholesale rather than augmenting it (see #19337 for details). 91 // Return incomplete package with error (see #16088). 92 return pkg, fmt.Errorf("reimported partially imported package %q", bp.ImportPath) 93 } 94 return pkg, nil 95 } 96 97 p.packages[bp.ImportPath] = &importing 98 defer func() { 99 // clean up in case of error 100 // TODO(gri) Eventually we may want to leave a (possibly empty) 101 // package in the map in all cases (and use that package to 102 // identify cycles). See also issue 16088. 103 if p.packages[bp.ImportPath] == &importing { 104 p.packages[bp.ImportPath] = nil 105 } 106 }() 107 108 var filenames []string 109 filenames = append(filenames, bp.GoFiles...) 110 filenames = append(filenames, bp.CgoFiles...) 111 112 files, err := p.parseFiles(bp.Dir, filenames) 113 if err != nil { 114 return nil, err 115 } 116 117 // type-check package files 118 var firstHardErr error 119 conf := types.Config{ 120 IgnoreFuncBodies: true, 121 // continue type-checking after the first error 122 Error: func(err error) { 123 if firstHardErr == nil && !err.(types.Error).Soft { 124 firstHardErr = err 125 } 126 }, 127 Importer: p, 128 Sizes: p.sizes, 129 } 130 if len(bp.CgoFiles) > 0 { 131 if p.ctxt.OpenFile != nil { 132 // cgo, gcc, pkg-config, etc. do not support 133 // build.Context's VFS. 134 conf.FakeImportC = true 135 } else { 136 setUsesCgo(&conf) 137 file, err := p.cgo(bp) 138 if err != nil { 139 return nil, err 140 } 141 files = append(files, file) 142 } 143 } 144 145 if depth <= 1 { 146 pkg, err = conf.Check(bp.ImportPath, p.fset, files, nil, depth) 147 p.packages[bp.ImportPath] = pkg 148 } 149 return pkg, nil 150 } 151 152 func (p *Importer) parseFiles(dir string, filenames []string) ([]*ast.File, error) { 153 // use build.Context's OpenFile if there is one 154 open := p.ctxt.OpenFile 155 if open == nil { 156 open = func(name string) (io.ReadCloser, error) { return os.Open(name) } 157 } 158 159 files := make([]*ast.File, len(filenames)) 160 errors := make([]error, len(filenames)) 161 162 var wg sync.WaitGroup 163 wg.Add(len(filenames)) 164 for i, filename := range filenames { 165 go func(i int, filepath string) { 166 defer wg.Done() 167 src, err := open(filepath) 168 if err != nil { 169 errors[i] = err // open provides operation and filename in error 170 return 171 } 172 files[i], errors[i] = parser.ParseFile(p.fset, filepath, src, 0) 173 src.Close() // ignore Close error - parsing may have succeeded which is all we need 174 }(i, p.joinPath(dir, filename)) 175 } 176 wg.Wait() 177 178 // if there are errors, return the first one for deterministic results 179 for _, err := range errors { 180 if err != nil { 181 return nil, err 182 } 183 } 184 185 return files, nil 186 } 187 188 func (p *Importer) cgo(bp *build.Package) (*ast.File, error) { 189 tmpdir, err := os.MkdirTemp("", "srcimporter") 190 if err != nil { 191 return nil, err 192 } 193 defer os.RemoveAll(tmpdir) 194 195 args := []string{"go", "tool", "cgo", "-objdir", tmpdir} 196 if bp.Goroot { 197 switch bp.ImportPath { 198 case "runtime/cgo": 199 args = append(args, "-import_runtime_cgo=false", "-import_syscall=false") 200 case "runtime/race": 201 args = append(args, "-import_syscall=false") 202 } 203 } 204 args = append(args, "--") 205 args = append(args, strings.Fields(os.Getenv("CGO_CPPFLAGS"))...) 206 args = append(args, bp.CgoCPPFLAGS...) 207 if len(bp.CgoPkgConfig) > 0 { 208 cmd := exec.Command("pkg-config", append([]string{"--cflags"}, bp.CgoPkgConfig...)...) 209 out, err := cmd.CombinedOutput() 210 if err != nil { 211 return nil, err 212 } 213 args = append(args, strings.Fields(string(out))...) 214 } 215 args = append(args, "-I", tmpdir) 216 args = append(args, strings.Fields(os.Getenv("CGO_CFLAGS"))...) 217 args = append(args, bp.CgoCFLAGS...) 218 args = append(args, bp.CgoFiles...) 219 220 cmd := exec.Command(args[0], args[1:]...) 221 cmd.Dir = bp.Dir 222 if err := cmd.Run(); err != nil { 223 return nil, err 224 } 225 226 return parser.ParseFile(p.fset, filepath.Join(tmpdir, "_cgo_gotypes.go"), nil, 0) 227 } 228 229 // context-controlled file system operations 230 231 func (p *Importer) absPath(path string) (string, error) { 232 // TODO(gri) This should be using p.ctxt.AbsPath which doesn't 233 // exist but probably should. See also issue #14282. 234 return filepath.Abs(path) 235 } 236 237 func (p *Importer) isAbsPath(path string) bool { 238 if f := p.ctxt.IsAbsPath; f != nil { 239 return f(path) 240 } 241 return filepath.IsAbs(path) 242 } 243 244 func (p *Importer) joinPath(elem ...string) string { 245 if f := p.ctxt.JoinPath; f != nil { 246 return f(elem...) 247 } 248 return filepath.Join(elem...) 249 } 250 251 func setUsesCgo(conf *types.Config) { 252 types.Srcimporter_setUsesCgo(conf) 253 }