Debian Codegraph @

internal/imports/fix.go

raw symbols SCIP
1 // Copyright 2013 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 imports
6
7 import (
8 "bytes"
9 "context"
10 "encoding/json"
11 "fmt"
12 "go/ast"
13 "go/build"
14 "go/parser"
15 "go/token"
16 "go/types"
17 "io/fs"
18 "io/ioutil"
19 "maps"
20 "os"
21 "path"
22 "path/filepath"
23 "reflect"
24 "sort"
25 "strconv"
26 "strings"
27 "sync"
28 "unicode"
29 "unicode/utf8"
30
31 "golang.org/x/tools/go/ast/astutil"
32 "golang.org/x/tools/internal/event"
33 "golang.org/x/tools/internal/gocommand"
34 "golang.org/x/tools/internal/gopathwalk"
35 "golang.org/x/tools/internal/stdlib"
36 )
37
38 // importToGroup is a list of functions which map from an import path to
39 // a group number.
40 var importToGroup = []func(localPrefix, importPath string) (num int, ok bool){
41 func(localPrefix, importPath string) (num int, ok bool) {
42 if localPrefix == "" {
43 return
44 }
45 for p := range strings.SplitSeq(localPrefix, ",") {
46 if strings.HasPrefix(importPath, p) || strings.TrimSuffix(p, "/") == importPath {
47 return 3, true
48 }
49 }
50 return
51 },
52 func(_, importPath string) (num int, ok bool) {
53 if strings.HasPrefix(importPath, "appengine") {
54 return 2, true
55 }
56 return
57 },
58 func(_, importPath string) (num int, ok bool) {
59 firstComponent := strings.Split(importPath, "/")[0]
60 if strings.Contains(firstComponent, ".") {
61 return 1, true
62 }
63 return
64 },
65 }
66
67 func importGroup(localPrefix, importPath string) int {
68 for _, fn := range importToGroup {
69 if n, ok := fn(localPrefix, importPath); ok {
70 return n
71 }
72 }
73 return 0
74 }
75
76 type ImportFixType int
77
78 const (
79 AddImport ImportFixType = iota
80 DeleteImport
81 SetImportName
82 )
83
84 type ImportFix struct {
85 // StmtInfo represents the import statement this fix will add, remove, or change.
86 StmtInfo ImportInfo
87 // IdentName is the identifier that this fix will add or remove.
88 IdentName string
89 // FixType is the type of fix this is (AddImport, DeleteImport, SetImportName).
90 FixType ImportFixType
91 Relevance float64 // see pkg
92 }
93
94 // parseOtherFiles parses all the Go files in srcDir except filename, including
95 // test files if filename looks like a test.
96 //
97 // It returns an error only if ctx is cancelled. Files with parse errors are
98 // ignored.
99 func parseOtherFiles(ctx context.Context, fset *token.FileSet, srcDir, filename string) ([]*ast.File, error) {
100 // This could use go/packages but it doesn't buy much, and it fails
101 // with https://golang.org/issue/26296 in LoadFiles mode in some cases.
102 considerTests := strings.HasSuffix(filename, "_test.go")
103
104 fileBase := filepath.Base(filename)
105 packageFileInfos, err := os.ReadDir(srcDir)
106 if err != nil {
107 return nil, ctx.Err()
108 }
109
110 var files []*ast.File
111 for _, fi := range packageFileInfos {
112 if ctx.Err() != nil {
113 return nil, ctx.Err()
114 }
115 if fi.Name() == fileBase || !strings.HasSuffix(fi.Name(), ".go") {
116 continue
117 }
118 if !considerTests && strings.HasSuffix(fi.Name(), "_test.go") {
119 continue
120 }
121
122 f, err := parser.ParseFile(fset, filepath.Join(srcDir, fi.Name()), nil, parser.SkipObjectResolution)
123 if err != nil {
124 continue
125 }
126
127 files = append(files, f)
128 }
129
130 return files, ctx.Err()
131 }
132
133 // addGlobals puts the names of package vars into the provided map.
134 func addGlobals(f *ast.File, globals map[string]bool) {
135 for _, decl := range f.Decls {
136 genDecl, ok := decl.(*ast.GenDecl)
137 if !ok {
138 continue
139 }
140
141 for _, spec := range genDecl.Specs {
142 valueSpec, ok := spec.(*ast.ValueSpec)
143 if !ok {
144 continue
145 }
146 globals[valueSpec.Names[0].Name] = true
147 }
148 }
149 }
150
151 // collectReferences builds a map of selector expressions, from
152 // left hand side (X) to a set of right hand sides (Sel).
153 func collectReferences(f *ast.File) References {
154 refs := References{}
155
156 var visitor visitFn
157 visitor = func(node ast.Node) ast.Visitor {
158 if node == nil {
159 return visitor
160 }
161 switch v := node.(type) {
162 case *ast.SelectorExpr:
163 xident, ok := v.X.(*ast.Ident)
164 if !ok {
165 break
166 }
167 if xident.Obj != nil {
168 // If the parser can resolve it, it's not a package ref.
169 break
170 }
171 if !ast.IsExported(v.Sel.Name) {
172 // Whatever this is, it's not exported from a package.
173 break
174 }
175 pkgName := xident.Name
176 r := refs[pkgName]
177 if r == nil {
178 r = make(map[string]bool)
179 refs[pkgName] = r
180 }
181 r[v.Sel.Name] = true
182 }
183 return visitor
184 }
185 ast.Walk(visitor, f)
186 return refs
187 }
188
189 // collectImports returns all the imports in f.
190 // Unnamed imports (., _) and "C" are ignored.
191 func collectImports(f *ast.File) []*ImportInfo {
192 var imports []*ImportInfo
193 for _, imp := range f.Imports {
194 var name string
195 if imp.Name != nil {
196 name = imp.Name.Name
197 }
198 if imp.Path.Value == `"C"` || name == "_" || name == "." {
199 continue
200 }
201 path := strings.Trim(imp.Path.Value, `"`)
202 imports = append(imports, &ImportInfo{
203 Name: name,
204 ImportPath: path,
205 })
206 }
207 return imports
208 }
209
210 // findMissingImport searches pass's candidates for an import that provides
211 // pkg, containing all of syms.
212 func (p *pass) findMissingImport(pkg string, syms map[string]bool) *ImportInfo {
213 for _, candidate := range p.candidates {
214 pkgInfo, ok := p.knownPackages[candidate.ImportPath]
215 if !ok {
216 continue
217 }
218 if p.importIdentifier(candidate) != pkg {
219 continue
220 }
221
222 allFound := true
223 for right := range syms {
224 if !pkgInfo.Exports[right] {
225 allFound = false
226 break
227 }
228 }
229
230 if allFound {
231 return candidate
232 }
233 }
234 return nil
235 }
236
237 // A pass contains all the inputs and state necessary to fix a file's imports.
238 // It can be modified in some ways during use; see comments below.
239 type pass struct {
240 // Inputs. These must be set before a call to load, and not modified after.
241 fset *token.FileSet // fset used to parse f and its siblings.
242 f *ast.File // the file being fixed.
243 srcDir string // the directory containing f.
244 logf func(string, ...any)
245 source Source // the environment to use for go commands, etc.
246 loadRealPackageNames bool // if true, load package names from disk rather than guessing them.
247 otherFiles []*ast.File // sibling files.
248 goroot string
249
250 // Intermediate state, generated by load.
251 existingImports map[string][]*ImportInfo
252 allRefs References
253 missingRefs References
254
255 // Inputs to fix. These can be augmented between successive fix calls.
256 lastTry bool // indicates that this is the last call and fix should clean up as best it can.
257 candidates []*ImportInfo // candidate imports in priority order.
258 knownPackages map[string]*PackageInfo // information about all known packages.
259 }
260
261 // loadPackageNames saves the package names for everything referenced by imports.
262 func (p *pass) loadPackageNames(ctx context.Context, imports []*ImportInfo) error {
263 if p.logf != nil {
264 p.logf("loading package names for %v packages", len(imports))
265 defer func() {
266 p.logf("done loading package names for %v packages", len(imports))
267 }()
268 }
269 var unknown []string
270 for _, imp := range imports {
271 if _, ok := p.knownPackages[imp.ImportPath]; ok {
272 continue
273 }
274 unknown = append(unknown, imp.ImportPath)
275 }
276 names, err := p.source.LoadPackageNames(ctx, p.srcDir, unknown)
277 if err != nil {
278 return err
279 }
280
281 // TODO(rfindley): revisit this. Why do we need to store known packages with
282 // no exports? The inconsistent data is confusing.
283 for path, name := range names {
284 p.knownPackages[path] = &PackageInfo{
285 Name: name,
286 Exports: map[string]bool{},
287 }
288 }
289 return nil
290 }
291
292 // WithoutVersion removes a trailing major version, if there is one.
293 func WithoutVersion(nm string) string {
294 if v := path.Base(nm); len(v) > 0 && v[0] == 'v' {
295 if _, err := strconv.Atoi(v[1:]); err == nil {
296 // this is, for instance, called with rand/v2 and returns rand
297 if len(v) < len(nm) {
298 xnm := nm[:len(nm)-len(v)-1]
299 return path.Base(xnm)
300 }
301 }
302 }
303 return nm
304 }
305
306 // importIdentifier returns the identifier that imp will introduce. It will
307 // guess if the package name has not been loaded, e.g. because the source
308 // is not available.
309 func (p *pass) importIdentifier(imp *ImportInfo) string {
310 if imp.Name != "" {
311 return imp.Name
312 }
313 known := p.knownPackages[imp.ImportPath]
314 if known != nil && known.Name != "" {
315 return WithoutVersion(known.Name)
316 }
317 return ImportPathToAssumedName(imp.ImportPath)
318 }
319
320 // load reads in everything necessary to run a pass, and reports whether the
321 // file already has all the imports it needs. It fills in p.missingRefs with the
322 // file's missing symbols, if any, or removes unused imports if not.
323 func (p *pass) load(ctx context.Context) ([]*ImportFix, bool) {
324 p.knownPackages = map[string]*PackageInfo{}
325 p.missingRefs = References{}
326 p.existingImports = map[string][]*ImportInfo{}
327
328 // Load basic information about the file in question.
329 p.allRefs = collectReferences(p.f)
330
331 // Load stuff from other files in the same package:
332 // global variables so we know they don't need resolving, and imports
333 // that we might want to mimic.
334 globals := map[string]bool{}
335 for _, otherFile := range p.otherFiles {
336 // Don't load globals from files that are in the same directory
337 // but a different package. Using them to suggest imports is OK.
338 if p.f.Name.Name == otherFile.Name.Name {
339 addGlobals(otherFile, globals)
340 }
341 p.candidates = append(p.candidates, collectImports(otherFile)...)
342 }
343
344 // Resolve all the import paths we've seen to package names, and store
345 // f's imports by the identifier they introduce.
346 imports := collectImports(p.f)
347 if p.loadRealPackageNames {
348 err := p.loadPackageNames(ctx, append(imports, p.candidates...))
349 if err != nil {
350 if p.logf != nil {
351 p.logf("loading package names: %v", err)
352 }
353 return nil, false
354 }
355 }
356 for _, imp := range imports {
357 p.existingImports[p.importIdentifier(imp)] = append(p.existingImports[p.importIdentifier(imp)], imp)
358 }
359
360 // Find missing references.
361 for left, rights := range p.allRefs {
362 if globals[left] {
363 continue
364 }
365 _, ok := p.existingImports[left]
366 if !ok {
367 p.missingRefs[left] = rights
368 continue
369 }
370 }
371 if len(p.missingRefs) != 0 {
372 return nil, false
373 }
374
375 return p.fix()
376 }
377
378 // fix attempts to satisfy missing imports using p.candidates. If it finds
379 // everything, or if p.lastTry is true, it updates fixes to add the imports it found,
380 // delete anything unused, and update import names, and returns true.
381 func (p *pass) fix() ([]*ImportFix, bool) {
382 // Find missing imports.
383 var selected []*ImportInfo
384 for left, rights := range p.missingRefs {
385 if imp := p.findMissingImport(left, rights); imp != nil {
386 selected = append(selected, imp)
387 }
388 }
389
390 if !p.lastTry && len(selected) != len(p.missingRefs) {
391 return nil, false
392 }
393
394 // Found everything, or giving up. Add the new imports and remove any unused.
395 var fixes []*ImportFix
396 for _, identifierImports := range p.existingImports {
397 for _, imp := range identifierImports {
398 // We deliberately ignore globals here, because we can't be sure
399 // they're in the same package. People do things like put multiple
400 // main packages in the same directory, and we don't want to
401 // remove imports if they happen to have the same name as a var in
402 // a different package.
403 if _, ok := p.allRefs[p.importIdentifier(imp)]; !ok {
404 fixes = append(fixes, &ImportFix{
405 StmtInfo: *imp,
406 IdentName: p.importIdentifier(imp),
407 FixType: DeleteImport,
408 })
409 continue
410 }
411
412 // An existing import may need to update its import name to be correct.
413 if name := p.importSpecName(imp); name != imp.Name {
414 fixes = append(fixes, &ImportFix{
415 StmtInfo: ImportInfo{
416 Name: name,
417 ImportPath: imp.ImportPath,
418 },
419 IdentName: p.importIdentifier(imp),
420 FixType: SetImportName,
421 })
422 }
423 }
424 }
425 // Collecting fixes involved map iteration, so sort for stability. See
426 // golang/go#59976.
427 sortFixes(fixes)
428
429 // collect selected fixes in a separate slice, so that it can be sorted
430 // separately. Note that these fixes must occur after fixes to existing
431 // imports. TODO(rfindley): figure out why.
432 var selectedFixes []*ImportFix
433 for _, imp := range selected {
434 selectedFixes = append(selectedFixes, &ImportFix{
435 StmtInfo: ImportInfo{
436 Name: p.importSpecName(imp),
437 ImportPath: imp.ImportPath,
438 },
439 IdentName: p.importIdentifier(imp),
440 FixType: AddImport,
441 })
442 }
443 sortFixes(selectedFixes)
444
445 return append(fixes, selectedFixes...), true
446 }
447
448 func sortFixes(fixes []*ImportFix) {
449 sort.Slice(fixes, func(i, j int) bool {
450 fi, fj := fixes[i], fixes[j]
451 if fi.StmtInfo.ImportPath != fj.StmtInfo.ImportPath {
452 return fi.StmtInfo.ImportPath < fj.StmtInfo.ImportPath
453 }
454 if fi.StmtInfo.Name != fj.StmtInfo.Name {
455 return fi.StmtInfo.Name < fj.StmtInfo.Name
456 }
457 if fi.IdentName != fj.IdentName {
458 return fi.IdentName < fj.IdentName
459 }
460 return fi.FixType < fj.FixType
461 })
462 }
463
464 // importSpecName gets the import name of imp in the import spec.
465 //
466 // When the import identifier matches the assumed import name, the import name does
467 // not appear in the import spec.
468 func (p *pass) importSpecName(imp *ImportInfo) string {
469 // If we did not load the real package names, or the name is already set,
470 // we just return the existing name.
471 if !p.loadRealPackageNames || imp.Name != "" {
472 return imp.Name
473 }
474
475 ident := p.importIdentifier(imp)
476 if ident == ImportPathToAssumedName(imp.ImportPath) {
477 return "" // ident not needed since the assumed and real names are the same.
478 }
479 return ident
480 }
481
482 // apply will perform the fixes on f in order.
483 func apply(fset *token.FileSet, f *ast.File, fixes []*ImportFix) {
484 for _, fix := range fixes {
485 switch fix.FixType {
486 case DeleteImport:
487 astutil.DeleteNamedImport(fset, f, fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
488 case AddImport:
489 astutil.AddNamedImport(fset, f, fix.StmtInfo.Name, fix.StmtInfo.ImportPath)
490 case SetImportName:
491 // Find the matching import path and change the name.
492 for _, spec := range f.Imports {
493 path := strings.Trim(spec.Path.Value, `"`)
494 if path == fix.StmtInfo.ImportPath {
495 spec.Name = &ast.Ident{
496 Name: fix.StmtInfo.Name,
497 NamePos: spec.Pos(),
498 }
499 }
500 }
501 }
502 }
503 }
504
505 // assumeSiblingImportsValid assumes that siblings' use of packages is valid,
506 // adding the exports they use.
507 func (p *pass) assumeSiblingImportsValid() {
508 for _, f := range p.otherFiles {
509 refs := collectReferences(f)
510 imports := collectImports(f)
511 importsByName := map[string]*ImportInfo{}
512 for _, imp := range imports {
513 importsByName[p.importIdentifier(imp)] = imp
514 }
515 for left, rights := range refs {
516 if imp, ok := importsByName[left]; ok {
517 if m, ok := stdlib.PackageSymbols[imp.ImportPath]; ok {
518 // We have the stdlib in memory; no need to guess.
519 rights = symbolNameSet(m)
520 }
521 // TODO(rfindley): we should set package name here, for consistency.
522 p.addCandidate(imp, &PackageInfo{
523 // no name; we already know it.
524 Exports: rights,
525 })
526 }
527 }
528 }
529 }
530
531 // addCandidate adds a candidate import to p, and merges in the information
532 // in pkg.
533 func (p *pass) addCandidate(imp *ImportInfo, pkg *PackageInfo) {
534 p.candidates = append(p.candidates, imp)
535 if existing, ok := p.knownPackages[imp.ImportPath]; ok {
536 if existing.Name == "" {
537 existing.Name = pkg.Name
538 }
539 for export := range pkg.Exports {
540 existing.Exports[export] = true
541 }
542 } else {
543 p.knownPackages[imp.ImportPath] = pkg
544 }
545 }
546
547 // fixImports adds and removes imports from f so that all its references are
548 // satisfied and there are no unused imports.
549 //
550 // This is declared as a variable rather than a function so goimports can
551 // easily be extended by adding a file with an init function.
552 //
553 // DO NOT REMOVE: used internally at Google.
554 var fixImports = fixImportsDefault
555
556 func fixImportsDefault(fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) error {
557 fixes, err := getFixes(context.Background(), fset, f, filename, env)
558 if err != nil {
559 return err
560 }
561 apply(fset, f, fixes)
562 return nil
563 }
564
565 // getFixes gets the import fixes that need to be made to f in order to fix the imports.
566 // It does not modify the ast.
567 func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) ([]*ImportFix, error) {
568 source, err := NewProcessEnvSource(env, filename, f.Name.Name)
569 if err != nil {
570 return nil, err
571 }
572 goEnv, err := env.goEnv()
573 if err != nil {
574 return nil, err
575 }
576 return getFixesWithSource(ctx, fset, f, filename, goEnv["GOROOT"], env.logf, source)
577 }
578
579 func getFixesWithSource(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, goroot string, logf func(string, ...any), source Source) ([]*ImportFix, error) {
580 // This logic is defensively duplicated from getFixes.
581 abs, err := filepath.Abs(filename)
582 if err != nil {
583 return nil, err
584 }
585 srcDir := filepath.Dir(abs)
586
587 if logf != nil {
588 logf("fixImports(filename=%q), srcDir=%q ...", filename, srcDir)
589 }
590
591 // First pass: looking only at f, and using the naive algorithm to
592 // derive package names from import paths, see if the file is already
593 // complete. We can't add any imports yet, because we don't know
594 // if missing references are actually package vars.
595 p := &pass{
596 fset: fset,
597 f: f,
598 srcDir: srcDir,
599 logf: logf,
600 goroot: goroot,
601 source: source,
602 }
603 if fixes, done := p.load(ctx); done {
604 return fixes, nil
605 }
606
607 otherFiles, err := parseOtherFiles(ctx, fset, srcDir, filename)
608 if err != nil {
609 return nil, err
610 }
611
612 // Second pass: add information from other files in the same package,
613 // like their package vars and imports.
614 p.otherFiles = otherFiles
615 if fixes, done := p.load(ctx); done {
616 return fixes, nil
617 }
618
619 // Now we can try adding imports from the stdlib.
620 p.assumeSiblingImportsValid()
621 addStdlibCandidates(p, p.missingRefs)
622 if fixes, done := p.fix(); done {
623 return fixes, nil
624 }
625
626 // Third pass: get real package names where we had previously used
627 // the naive algorithm.
628 p = &pass{
629 fset: fset,
630 f: f,
631 srcDir: srcDir,
632 logf: logf,
633 goroot: goroot,
634 source: p.source, // safe to reuse, as it's just a wrapper around env
635 }
636 p.loadRealPackageNames = true
637 p.otherFiles = otherFiles
638 if fixes, done := p.load(ctx); done {
639 return fixes, nil
640 }
641
642 if err := addStdlibCandidates(p, p.missingRefs); err != nil {
643 return nil, err
644 }
645 p.assumeSiblingImportsValid()
646 if fixes, done := p.fix(); done {
647 return fixes, nil
648 }
649
650 // Go look for candidates in $GOPATH, etc. We don't necessarily load
651 // the real exports of sibling imports, so keep assuming their contents.
652 if err := addExternalCandidates(ctx, p, p.missingRefs, filename); err != nil {
653 return nil, err
654 }
655
656 p.lastTry = true
657 fixes, _ := p.fix()
658 return fixes, nil
659 }
660
661 // MaxRelevance is the highest relevance, used for the standard library.
662 // Chosen arbitrarily to match pre-existing gopls code.
663 const MaxRelevance = 7.0
664
665 // getCandidatePkgs works with the passed callback to find all acceptable packages.
666 // It deduplicates by import path, and uses a cached stdlib rather than reading
667 // from disk.
668 func getCandidatePkgs(ctx context.Context, wrappedCallback *scanCallback, filename, filePkg string, env *ProcessEnv) error {
669 notSelf := func(p *pkg) bool {
670 return p.packageName != filePkg || p.dir != filepath.Dir(filename)
671 }
672 goenv, err := env.goEnv()
673 if err != nil {
674 return err
675 }
676
677 var mu sync.Mutex // to guard asynchronous access to dupCheck
678 dupCheck := map[string]struct{}{}
679
680 // Start off with the standard library.
681 for importPath, symbols := range stdlib.PackageSymbols {
682 p := &pkg{
683 dir: filepath.Join(goenv["GOROOT"], "src", importPath),
684 importPathShort: importPath,
685 packageName: path.Base(importPath),
686 relevance: MaxRelevance,
687 }
688 dupCheck[importPath] = struct{}{}
689 if notSelf(p) && wrappedCallback.dirFound(p) && wrappedCallback.packageNameLoaded(p) {
690 var exports []stdlib.Symbol
691 for _, sym := range symbols {
692 switch sym.Kind {
693 case stdlib.Func, stdlib.Type, stdlib.Var, stdlib.Const:
694 exports = append(exports, sym)
695 }
696 }
697 wrappedCallback.exportsLoaded(p, exports)
698 }
699 }
700
701 scanFilter := &scanCallback{
702 rootFound: func(root gopathwalk.Root) bool {
703 // Exclude goroot results -- getting them is relatively expensive, not cached,
704 // and generally redundant with the in-memory version.
705 return root.Type != gopathwalk.RootGOROOT && wrappedCallback.rootFound(root)
706 },
707 dirFound: wrappedCallback.dirFound,
708 packageNameLoaded: func(pkg *pkg) bool {
709 mu.Lock()
710 defer mu.Unlock()
711 if _, ok := dupCheck[pkg.importPathShort]; ok {
712 return false
713 }
714 dupCheck[pkg.importPathShort] = struct{}{}
715 return notSelf(pkg) && wrappedCallback.packageNameLoaded(pkg)
716 },
717 exportsLoaded: func(pkg *pkg, exports []stdlib.Symbol) {
718 // If we're an x_test, load the package under test's test variant.
719 if strings.HasSuffix(filePkg, "_test") && pkg.dir == filepath.Dir(filename) {
720 var err error
721 _, exports, err = loadExportsFromFiles(ctx, env, pkg.dir, true)
722 if err != nil {
723 return
724 }
725 }
726 wrappedCallback.exportsLoaded(pkg, exports)
727 },
728 }
729 resolver, err := env.GetResolver()
730 if err != nil {
731 return err
732 }
733 return resolver.scan(ctx, scanFilter)
734 }
735
736 func ScoreImportPaths(ctx context.Context, env *ProcessEnv, paths []string) (map[string]float64, error) {
737 result := make(map[string]float64)
738 resolver, err := env.GetResolver()
739 if err != nil {
740 return nil, err
741 }
742 for _, path := range paths {
743 result[path] = resolver.scoreImportPath(ctx, path)
744 }
745 return result, nil
746 }
747
748 func PrimeCache(ctx context.Context, resolver Resolver) error {
749 // Fully scan the disk for directories, but don't actually read any Go files.
750 callback := &scanCallback{
751 rootFound: func(root gopathwalk.Root) bool {
752 // See getCandidatePkgs: walking GOROOT is apparently expensive and
753 // unnecessary.
754 return root.Type != gopathwalk.RootGOROOT
755 },
756 dirFound: func(pkg *pkg) bool {
757 return false
758 },
759 // packageNameLoaded and exportsLoaded must never be called.
760 }
761
762 return resolver.scan(ctx, callback)
763 }
764
765 func candidateImportName(pkg *pkg) string {
766 if ImportPathToAssumedName(pkg.importPathShort) != pkg.packageName {
767 return pkg.packageName
768 }
769 return ""
770 }
771
772 // GetAllCandidates calls wrapped for each package whose name starts with
773 // searchPrefix, and can be imported from filename with the package name filePkg.
774 //
775 // Beware that the wrapped function may be called multiple times concurrently.
776 // TODO(adonovan): encapsulate the concurrency.
777 func GetAllCandidates(ctx context.Context, wrapped func(ImportFix), searchPrefix, filename, filePkg string, env *ProcessEnv) error {
778 callback := &scanCallback{
779 rootFound: func(gopathwalk.Root) bool {
780 return true
781 },
782 dirFound: func(pkg *pkg) bool {
783 if !CanUse(filename, pkg.dir) {
784 return false
785 }
786 // Try the assumed package name first, then a simpler path match
787 // in case of packages named vN, which are not uncommon.
788 return strings.HasPrefix(ImportPathToAssumedName(pkg.importPathShort), searchPrefix) ||
789 strings.HasPrefix(path.Base(pkg.importPathShort), searchPrefix)
790 },
791 packageNameLoaded: func(pkg *pkg) bool {
792 if !strings.HasPrefix(pkg.packageName, searchPrefix) {
793 return false
794 }
795 wrapped(ImportFix{
796 StmtInfo: ImportInfo{
797 ImportPath: pkg.importPathShort,
798 Name: candidateImportName(pkg),
799 },
800 IdentName: pkg.packageName,
801 FixType: AddImport,
802 Relevance: pkg.relevance,
803 })
804 return false
805 },
806 }
807 return getCandidatePkgs(ctx, callback, filename, filePkg, env)
808 }
809
810 // GetImportPaths calls wrapped for each package whose import path starts with
811 // searchPrefix, and can be imported from filename with the package name filePkg.
812 func GetImportPaths(ctx context.Context, wrapped func(ImportFix), searchPrefix, filename, filePkg string, env *ProcessEnv) error {
813 callback := &scanCallback{
814 rootFound: func(gopathwalk.Root) bool {
815 return true
816 },
817 dirFound: func(pkg *pkg) bool {
818 if !CanUse(filename, pkg.dir) {
819 return false
820 }
821 return strings.HasPrefix(pkg.importPathShort, searchPrefix)
822 },
823 packageNameLoaded: func(pkg *pkg) bool {
824 wrapped(ImportFix{
825 StmtInfo: ImportInfo{
826 ImportPath: pkg.importPathShort,
827 Name: candidateImportName(pkg),
828 },
829 IdentName: pkg.packageName,
830 FixType: AddImport,
831 Relevance: pkg.relevance,
832 })
833 return false
834 },
835 }
836 return getCandidatePkgs(ctx, callback, filename, filePkg, env)
837 }
838
839 // A PackageExport is a package and its exports.
840 type PackageExport struct {
841 Fix *ImportFix
842 Exports []stdlib.Symbol
843 }
844
845 // GetPackageExports returns all known packages with name pkg and their exports.
846 func GetPackageExports(ctx context.Context, wrapped func(PackageExport), searchPkg, filename, filePkg string, env *ProcessEnv) error {
847 callback := &scanCallback{
848 rootFound: func(gopathwalk.Root) bool {
849 return true
850 },
851 dirFound: func(pkg *pkg) bool {
852 return pkgIsCandidate(filename, References{searchPkg: nil}, pkg)
853 },
854 packageNameLoaded: func(pkg *pkg) bool {
855 return pkg.packageName == searchPkg
856 },
857 exportsLoaded: func(pkg *pkg, exports []stdlib.Symbol) {
858 sortSymbols(exports)
859 wrapped(PackageExport{
860 Fix: &ImportFix{
861 StmtInfo: ImportInfo{
862 ImportPath: pkg.importPathShort,
863 Name: candidateImportName(pkg),
864 },
865 IdentName: pkg.packageName,
866 FixType: AddImport,
867 Relevance: pkg.relevance,
868 },
869 Exports: exports,
870 })
871 },
872 }
873 return getCandidatePkgs(ctx, callback, filename, filePkg, env)
874 }
875
876 // TODO(rfindley): we should depend on GOOS and GOARCH, to provide accurate
877 // imports when doing cross-platform development.
878 var requiredGoEnvVars = []string{
879 "GO111MODULE",
880 "GOFLAGS",
881 "GOINSECURE",
882 "GOMOD",
883 "GOMODCACHE",
884 "GONOPROXY",
885 "GONOSUMDB",
886 "GOPATH",
887 "GOPROXY",
888 "GOROOT",
889 "GOSUMDB",
890 "GOWORK",
891 }
892
893 // ProcessEnv contains environment variables and settings that affect the use of
894 // the go command, the go/build package, etc.
895 //
896 // ...a ProcessEnv *also* overwrites its Env along with derived state in the
897 // form of the resolver. And because it is lazily initialized, an env may just
898 // be broken and unusable, but there is no way for the caller to detect that:
899 // all queries will just fail.
900 //
901 // TODO(rfindley): refactor this package so that this type (perhaps renamed to
902 // just Env or Config) is an immutable configuration struct, to be exchanged
903 // for an initialized object via a constructor that returns an error. Perhaps
904 // the signature should be `func NewResolver(*Env) (*Resolver, error)`, where
905 // resolver is a concrete type used for resolving imports. Via this
906 // refactoring, we can avoid the need to call ProcessEnv.init and
907 // ProcessEnv.GoEnv everywhere, and implicitly fix all the places where this
908 // these are misused. Also, we'd delegate the caller the decision of how to
909 // handle a broken environment.
910 type ProcessEnv struct {
911 GocmdRunner *gocommand.Runner
912
913 BuildFlags []string
914 ModFlag string
915
916 // SkipPathInScan returns true if the path should be skipped from scans of
917 // the RootCurrentModule root type. The function argument is a clean,
918 // absolute path.
919 SkipPathInScan func(string) bool
920
921 // Env overrides the OS environment, and can be used to specify
922 // GOPROXY, GO111MODULE, etc. PATH cannot be set here, because
923 // exec.Command will not honor it.
924 // Specifying all of requiredGoEnvVars avoids a call to `go env`.
925 Env map[string]string
926
927 WorkingDir string
928
929 // If Logf is non-nil, debug logging is enabled through this function.
930 Logf func(format string, args ...any)
931
932 // If set, ModCache holds a shared cache of directory info to use across
933 // multiple ProcessEnvs.
934 ModCache *DirInfoCache
935
936 initialized bool // see TODO above
937
938 // resolver and resolverErr are lazily evaluated (see GetResolver).
939 // This is unclean, but see the big TODO in the docstring for ProcessEnv
940 // above: for now, we can't be sure that the ProcessEnv is fully initialized.
941 resolver Resolver
942 resolverErr error
943 }
944
945 func (e *ProcessEnv) goEnv() (map[string]string, error) {
946 if err := e.init(); err != nil {
947 return nil, err
948 }
949 return e.Env, nil
950 }
951
952 func (e *ProcessEnv) matchFile(dir, name string) (bool, error) {
953 bctx, err := e.buildContext()
954 if err != nil {
955 return false, err
956 }
957 return bctx.MatchFile(dir, name)
958 }
959
960 // CopyConfig copies the env's configuration into a new env.
961 func (e *ProcessEnv) CopyConfig() *ProcessEnv {
962 copy := &ProcessEnv{
963 GocmdRunner: e.GocmdRunner,
964 initialized: e.initialized,
965 BuildFlags: e.BuildFlags,
966 Logf: e.Logf,
967 WorkingDir: e.WorkingDir,
968 resolver: nil,
969 Env: map[string]string{},
970 }
971 maps.Copy(copy.Env, e.Env)
972 return copy
973 }
974
975 func (e *ProcessEnv) init() error {
976 if e.initialized {
977 return nil
978 }
979
980 foundAllRequired := true
981 for _, k := range requiredGoEnvVars {
982 if _, ok := e.Env[k]; !ok {
983 foundAllRequired = false
984 break
985 }
986 }
987 if foundAllRequired {
988 e.initialized = true
989 return nil
990 }
991
992 if e.Env == nil {
993 e.Env = map[string]string{}
994 }
995
996 goEnv := map[string]string{}
997 stdout, err := e.invokeGo(context.TODO(), "env", append([]string{"-json"}, requiredGoEnvVars...)...)
998 if err != nil {
999 return err
1000 }
1001 if err := json.Unmarshal(stdout.Bytes(), &goEnv); err != nil {
1002 return err
1003 }
1004 maps.Copy(e.Env, goEnv)
1005 e.initialized = true
1006 return nil
1007 }
1008
1009 func (e *ProcessEnv) env() []string {
1010 var env []string // the gocommand package will prepend os.Environ.
1011 for k, v := range e.Env {
1012 env = append(env, k+"="+v)
1013 }
1014 return env
1015 }
1016
1017 func (e *ProcessEnv) GetResolver() (Resolver, error) {
1018 if err := e.init(); err != nil {
1019 return nil, err
1020 }
1021
1022 if e.resolver == nil && e.resolverErr == nil {
1023 // TODO(rfindley): we should only use a gopathResolver here if the working
1024 // directory is actually *in* GOPATH. (I seem to recall an open gopls issue
1025 // for this behavior, but I can't find it).
1026 //
1027 // For gopls, we can optionally explicitly choose a resolver type, since we
1028 // already know the view type.
1029 if e.Env["GOMOD"] == "" && (e.Env["GOWORK"] == "" || e.Env["GOWORK"] == "off") {
1030 e.resolver = newGopathResolver(e)
1031 e.logf("created gopath resolver")
1032 } else if r, err := newModuleResolver(e, e.ModCache); err != nil {
1033 e.resolverErr = err
1034 e.logf("failed to create module resolver: %v", err)
1035 } else {
1036 e.resolver = Resolver(r)
1037 e.logf("created module resolver")
1038 }
1039 }
1040
1041 return e.resolver, e.resolverErr
1042 }
1043
1044 // logf logs if e.Logf is non-nil.
1045 func (e *ProcessEnv) logf(format string, args ...any) {
1046 if e.Logf != nil {
1047 e.Logf(format, args...)
1048 }
1049 }
1050
1051 // buildContext returns the build.Context to use for matching files.
1052 //
1053 // TODO(rfindley): support dynamic GOOS, GOARCH here, when doing cross-platform
1054 // development.
1055 func (e *ProcessEnv) buildContext() (*build.Context, error) {
1056 ctx := build.Default
1057 goenv, err := e.goEnv()
1058 if err != nil {
1059 return nil, err
1060 }
1061 ctx.GOROOT = goenv["GOROOT"]
1062 ctx.GOPATH = goenv["GOPATH"]
1063
1064 // As of Go 1.14, build.Context has a Dir field
1065 // (see golang.org/issue/34860).
1066 // Populate it only if present.
1067 rc := reflect.ValueOf(&ctx).Elem()
1068 dir := rc.FieldByName("Dir")
1069 if dir.IsValid() && dir.Kind() == reflect.String {
1070 dir.SetString(e.WorkingDir)
1071 }
1072
1073 // Since Go 1.11, go/build.Context.Import may invoke 'go list' depending on
1074 // the value in GO111MODULE in the process's environment. We always want to
1075 // run in GOPATH mode when calling Import, so we need to prevent this from
1076 // happening. In Go 1.16, GO111MODULE defaults to "on", so this problem comes
1077 // up more frequently.
1078 //
1079 // HACK: setting any of the Context I/O hooks prevents Import from invoking
1080 // 'go list', regardless of GO111MODULE. This is undocumented, but it's
1081 // unlikely to change before GOPATH support is removed.
1082 ctx.ReadDir = ioutil.ReadDir
1083
1084 return &ctx, nil
1085 }
1086
1087 func (e *ProcessEnv) invokeGo(ctx context.Context, verb string, args ...string) (*bytes.Buffer, error) {
1088 inv := gocommand.Invocation{
1089 Verb: verb,
1090 Args: args,
1091 BuildFlags: e.BuildFlags,
1092 Env: e.env(),
1093 Logf: e.Logf,
1094 WorkingDir: e.WorkingDir,
1095 }
1096 return e.GocmdRunner.Run(ctx, inv)
1097 }
1098
1099 func addStdlibCandidates(pass *pass, refs References) error {
1100 localbase := func(nm string) string {
1101 ans := path.Base(nm)
1102 if ans[0] == 'v' {
1103 // this is called, for instance, with math/rand/v2 and returns rand/v2
1104 if _, err := strconv.Atoi(ans[1:]); err == nil {
1105 ix := strings.LastIndex(nm, ans)
1106 more := path.Base(nm[:ix])
1107 ans = path.Join(more, ans)
1108 }
1109 }
1110 return ans
1111 }
1112 add := func(pkg string) {
1113 // Prevent self-imports.
1114 if path.Base(pkg) == pass.f.Name.Name && filepath.Join(pass.goroot, "src", pkg) == pass.srcDir {
1115 return
1116 }
1117 exports := symbolNameSet(stdlib.PackageSymbols[pkg])
1118 pass.addCandidate(
1119 &ImportInfo{ImportPath: pkg},
1120 &PackageInfo{Name: localbase(pkg), Exports: exports})
1121 }
1122 for left := range refs {
1123 if left == "rand" {
1124 // Make sure we try crypto/rand before any version of math/rand as both have Int()
1125 // and our policy is to recommend crypto
1126 add("crypto/rand")
1127 // if the user's no later than go1.21, this should be "math/rand"
1128 // but we have no way of figuring out what the user is using
1129 // TODO: investigate using the toolchain version to disambiguate in the stdlib
1130 add("math/rand/v2")
1131 // math/rand has an overlapping API
1132 // TestIssue66407 fails without this
1133 add("math/rand")
1134 continue
1135 }
1136 for importPath := range stdlib.PackageSymbols {
1137 if path.Base(importPath) == left {
1138 add(importPath)
1139 }
1140 }
1141 }
1142 return nil
1143 }
1144
1145 // A Resolver does the build-system-specific parts of goimports.
1146 type Resolver interface {
1147 // loadPackageNames loads the package names in importPaths.
1148 loadPackageNames(importPaths []string, srcDir string) (map[string]string, error)
1149
1150 // scan works with callback to search for packages. See scanCallback for details.
1151 scan(ctx context.Context, callback *scanCallback) error
1152
1153 // loadExports returns the package name and set of exported symbols in the
1154 // package at dir. loadExports may be called concurrently.
1155 loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error)
1156
1157 // scoreImportPath returns the relevance for an import path.
1158 scoreImportPath(ctx context.Context, path string) float64
1159
1160 // ClearForNewScan returns a new Resolver based on the receiver that has
1161 // cleared its internal caches of directory contents.
1162 //
1163 // The new resolver should be primed and then set via
1164 // [ProcessEnv.UpdateResolver].
1165 ClearForNewScan() Resolver
1166 }
1167
1168 // A scanCallback controls a call to scan and receives its results.
1169 // In general, minor errors will be silently discarded; a user should not
1170 // expect to receive a full series of calls for everything.
1171 type scanCallback struct {
1172 // rootFound is called before scanning a new root dir. If it returns true,
1173 // the root will be scanned. Returning false will not necessarily prevent
1174 // directories from that root making it to dirFound.
1175 rootFound func(gopathwalk.Root) bool
1176 // dirFound is called when a directory is found that is possibly a Go package.
1177 // pkg will be populated with everything except packageName.
1178 // If it returns true, the package's name will be loaded.
1179 dirFound func(pkg *pkg) bool
1180 // packageNameLoaded is called when a package is found and its name is loaded.
1181 // If it returns true, the package's exports will be loaded.
1182 packageNameLoaded func(pkg *pkg) bool
1183 // exportsLoaded is called when a package's exports have been loaded.
1184 exportsLoaded func(pkg *pkg, exports []stdlib.Symbol)
1185 }
1186
1187 func addExternalCandidates(ctx context.Context, pass *pass, refs References, filename string) error {
1188 ctx, done := event.Start(ctx, "imports.addExternalCandidates")
1189 defer done()
1190
1191 results, err := pass.source.ResolveReferences(ctx, filename, refs)
1192 if err != nil {
1193 return err
1194 }
1195
1196 for _, result := range results {
1197 if result == nil {
1198 continue
1199 }
1200 // Don't offer completions that would shadow predeclared
1201 // names, such as github.com/coreos/etcd/error.
1202 if types.Universe.Lookup(result.Package.Name) != nil { // predeclared
1203 // Ideally we would skip this candidate only
1204 // if the predeclared name is actually
1205 // referenced by the file, but that's a lot
1206 // trickier to compute and would still create
1207 // an import that is likely to surprise the
1208 // user before long.
1209 continue
1210 }
1211 pass.addCandidate(result.Import, result.Package)
1212 }
1213 return nil
1214 }
1215
1216 // notIdentifier reports whether ch is an invalid identifier character.
1217 func notIdentifier(ch rune) bool {
1218 return !('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' ||
1219 '0' <= ch && ch <= '9' ||
1220 ch == '_' ||
1221 ch >= utf8.RuneSelf && (unicode.IsLetter(ch) || unicode.IsDigit(ch)))
1222 }
1223
1224 // ImportPathToAssumedName returns the assumed package name of an import path.
1225 // It does this using only string parsing of the import path.
1226 // It picks the last element of the path that does not look like a major
1227 // version, and then picks the valid identifier off the start of that element.
1228 // It is used to determine if a local rename should be added to an import for
1229 // clarity.
1230 // This function could be moved to a standard package and exported if we want
1231 // for use in other tools.
1232 func ImportPathToAssumedName(importPath string) string {
1233 base := path.Base(importPath)
1234 if strings.HasPrefix(base, "v") {
1235 if _, err := strconv.Atoi(base[1:]); err == nil {
1236 dir := path.Dir(importPath)
1237 if dir != "." {
1238 base = path.Base(dir)
1239 }
1240 }
1241 }
1242 base = strings.TrimPrefix(base, "go-")
1243 if i := strings.IndexFunc(base, notIdentifier); i >= 0 {
1244 base = base[:i]
1245 }
1246 return base
1247 }
1248
1249 // gopathResolver implements resolver for GOPATH workspaces.
1250 type gopathResolver struct {
1251 env *ProcessEnv
1252 cache *DirInfoCache
1253 scanSema chan struct{} // scanSema prevents concurrent scans.
1254 }
1255
1256 func newGopathResolver(env *ProcessEnv) *gopathResolver {
1257 r := &gopathResolver{
1258 env: env,
1259 cache: NewDirInfoCache(),
1260 scanSema: make(chan struct{}, 1),
1261 }
1262 r.scanSema <- struct{}{}
1263 return r
1264 }
1265
1266 func (r *gopathResolver) ClearForNewScan() Resolver {
1267 return newGopathResolver(r.env)
1268 }
1269
1270 func (r *gopathResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) {
1271 names := map[string]string{}
1272 bctx, err := r.env.buildContext()
1273 if err != nil {
1274 return nil, err
1275 }
1276 for _, path := range importPaths {
1277 names[path] = importPathToName(bctx, path, srcDir)
1278 }
1279 return names, nil
1280 }
1281
1282 // importPathToName finds out the actual package name, as declared in its .go files.
1283 func importPathToName(bctx *build.Context, importPath, srcDir string) string {
1284 // Fast path for standard library without going to disk.
1285 if stdlib.HasPackage(importPath) {
1286 return path.Base(importPath) // stdlib packages always match their paths.
1287 }
1288
1289 buildPkg, err := bctx.Import(importPath, srcDir, build.FindOnly)
1290 if err != nil {
1291 return ""
1292 }
1293 pkgName, err := packageDirToName(buildPkg.Dir)
1294 if err != nil {
1295 return ""
1296 }
1297 return pkgName
1298 }
1299
1300 // packageDirToName is a faster version of build.Import if
1301 // the only thing desired is the package name. Given a directory,
1302 // packageDirToName then only parses one file in the package,
1303 // trusting that the files in the directory are consistent.
1304 func packageDirToName(dir string) (packageName string, err error) {
1305 d, err := os.Open(dir)
1306 if err != nil {
1307 return "", err
1308 }
1309 names, err := d.Readdirnames(-1)
1310 d.Close()
1311 if err != nil {
1312 return "", err
1313 }
1314 sort.Strings(names) // to have predictable behavior
1315 var lastErr error
1316 var nfile int
1317 for _, name := range names {
1318 if !strings.HasSuffix(name, ".go") {
1319 continue
1320 }
1321 if strings.HasSuffix(name, "_test.go") {
1322 continue
1323 }
1324 nfile++
1325 fullFile := filepath.Join(dir, name)
1326
1327 fset := token.NewFileSet()
1328 f, err := parser.ParseFile(fset, fullFile, nil, parser.PackageClauseOnly)
1329 if err != nil {
1330 lastErr = err
1331 continue
1332 }
1333 pkgName := f.Name.Name
1334 if pkgName == "documentation" {
1335 // Special case from go/build.ImportDir, not
1336 // handled by ctx.MatchFile.
1337 continue
1338 }
1339 if pkgName == "main" {
1340 // Also skip package main, assuming it's a +build ignore generator or example.
1341 // Since you can't import a package main anyway, there's no harm here.
1342 continue
1343 }
1344 return pkgName, nil
1345 }
1346 if lastErr != nil {
1347 return "", lastErr
1348 }
1349 return "", fmt.Errorf("no importable package found in %d Go files", nfile)
1350 }
1351
1352 type pkg struct {
1353 dir string // absolute file path to pkg directory ("/usr/lib/go/src/net/http")
1354 importPathShort string // vendorless import path ("net/http", "a/b")
1355 packageName string // package name loaded from source if requested
1356 relevance float64 // a weakly-defined score of how relevant a package is. 0 is most relevant.
1357 }
1358
1359 type pkgDistance struct {
1360 pkg *pkg
1361 distance int // relative distance to target
1362 }
1363
1364 // byDistanceOrImportPathShortLength sorts by relative distance breaking ties
1365 // on the short import path length and then the import string itself.
1366 type byDistanceOrImportPathShortLength []pkgDistance
1367
1368 func (s byDistanceOrImportPathShortLength) Len() int { return len(s) }
1369 func (s byDistanceOrImportPathShortLength) Less(i, j int) bool {
1370 di, dj := s[i].distance, s[j].distance
1371 if di == -1 {
1372 return false
1373 }
1374 if dj == -1 {
1375 return true
1376 }
1377 if di != dj {
1378 return di < dj
1379 }
1380
1381 vi, vj := s[i].pkg.importPathShort, s[j].pkg.importPathShort
1382 if len(vi) != len(vj) {
1383 return len(vi) < len(vj)
1384 }
1385 return vi < vj
1386 }
1387 func (s byDistanceOrImportPathShortLength) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1388
1389 func distance(basepath, targetpath string) int {
1390 p, err := filepath.Rel(basepath, targetpath)
1391 if err != nil {
1392 return -1
1393 }
1394 if p == "." {
1395 return 0
1396 }
1397 return strings.Count(p, string(filepath.Separator)) + 1
1398 }
1399
1400 func (r *gopathResolver) scan(ctx context.Context, callback *scanCallback) error {
1401 add := func(root gopathwalk.Root, dir string) {
1402 // We assume cached directories have not changed. We can skip them and their
1403 // children.
1404 if _, ok := r.cache.Load(dir); ok {
1405 return
1406 }
1407
1408 importpath := filepath.ToSlash(dir[len(root.Path)+len("/"):])
1409 info := directoryPackageInfo{
1410 status: directoryScanned,
1411 dir: dir,
1412 rootType: root.Type,
1413 nonCanonicalImportPath: VendorlessPath(importpath),
1414 }
1415 r.cache.Store(dir, info)
1416 }
1417 processDir := func(info directoryPackageInfo) {
1418 // Skip this directory if we were not able to get the package information successfully.
1419 if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
1420 return
1421 }
1422
1423 p := &pkg{
1424 importPathShort: info.nonCanonicalImportPath,
1425 dir: info.dir,
1426 relevance: MaxRelevance - 1,
1427 }
1428 if info.rootType == gopathwalk.RootGOROOT {
1429 p.relevance = MaxRelevance
1430 }
1431
1432 if !callback.dirFound(p) {
1433 return
1434 }
1435 var err error
1436 p.packageName, err = r.cache.CachePackageName(info)
1437 if err != nil {
1438 return
1439 }
1440
1441 if !callback.packageNameLoaded(p) {
1442 return
1443 }
1444 if _, exports, err := r.loadExports(ctx, p, false); err == nil {
1445 callback.exportsLoaded(p, exports)
1446 }
1447 }
1448 stop := r.cache.ScanAndListen(ctx, processDir)
1449 defer stop()
1450
1451 goenv, err := r.env.goEnv()
1452 if err != nil {
1453 return err
1454 }
1455 var roots []gopathwalk.Root
1456 roots = append(roots, gopathwalk.Root{Path: filepath.Join(goenv["GOROOT"], "src"), Type: gopathwalk.RootGOROOT})
1457 for _, p := range filepath.SplitList(goenv["GOPATH"]) {
1458 roots = append(roots, gopathwalk.Root{Path: filepath.Join(p, "src"), Type: gopathwalk.RootGOPATH})
1459 }
1460 // The callback is not necessarily safe to use in the goroutine below. Process roots eagerly.
1461 roots = filterRoots(roots, callback.rootFound)
1462 // We can't cancel walks, because we need them to finish to have a usable
1463 // cache. Instead, run them in a separate goroutine and detach.
1464 scanDone := make(chan struct{})
1465 go func() {
1466 select {
1467 case <-ctx.Done():
1468 return
1469 case <-r.scanSema:
1470 }
1471 defer func() { r.scanSema <- struct{}{} }()
1472 gopathwalk.Walk(roots, add, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: false})
1473 close(scanDone)
1474 }()
1475 select {
1476 case <-ctx.Done():
1477 case <-scanDone:
1478 }
1479 return nil
1480 }
1481
1482 func (r *gopathResolver) scoreImportPath(ctx context.Context, path string) float64 {
1483 if stdlib.HasPackage(path) {
1484 return MaxRelevance
1485 }
1486 return MaxRelevance - 1
1487 }
1488
1489 func filterRoots(roots []gopathwalk.Root, include func(gopathwalk.Root) bool) []gopathwalk.Root {
1490 var result []gopathwalk.Root
1491 for _, root := range roots {
1492 if !include(root) {
1493 continue
1494 }
1495 result = append(result, root)
1496 }
1497 return result
1498 }
1499
1500 func (r *gopathResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) {
1501 if info, ok := r.cache.Load(pkg.dir); ok && !includeTest {
1502 return r.cache.CacheExports(ctx, r.env, info)
1503 }
1504 return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest)
1505 }
1506
1507 // VendorlessPath returns the devendorized version of the import path ipath.
1508 // For example, VendorlessPath("foo/bar/vendor/a/b") returns "a/b".
1509 func VendorlessPath(ipath string) string {
1510 // Devendorize for use in import statement.
1511 if i := strings.LastIndex(ipath, "/vendor/"); i >= 0 {
1512 return ipath[i+len("/vendor/"):]
1513 }
1514 if strings.HasPrefix(ipath, "vendor/") {
1515 return ipath[len("vendor/"):]
1516 }
1517 return ipath
1518 }
1519
1520 func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, includeTest bool) (string, []stdlib.Symbol, error) {
1521 // Look for non-test, buildable .go files which could provide exports.
1522 all, err := os.ReadDir(dir)
1523 if err != nil {
1524 return "", nil, err
1525 }
1526 var files []fs.DirEntry
1527 for _, fi := range all {
1528 name := fi.Name()
1529 if !strings.HasSuffix(name, ".go") || (!includeTest && strings.HasSuffix(name, "_test.go")) {
1530 continue
1531 }
1532 match, err := env.matchFile(dir, fi.Name())
1533 if err != nil || !match {
1534 continue
1535 }
1536 files = append(files, fi)
1537 }
1538
1539 if len(files) == 0 {
1540 return "", nil, fmt.Errorf("dir %v contains no buildable, non-test .go files", dir)
1541 }
1542
1543 var pkgName string
1544 var exports []stdlib.Symbol
1545 fset := token.NewFileSet()
1546 for _, fi := range files {
1547 select {
1548 case <-ctx.Done():
1549 return "", nil, ctx.Err()
1550 default:
1551 }
1552
1553 fullFile := filepath.Join(dir, fi.Name())
1554 // Legacy ast.Object resolution is needed here.
1555 f, err := parser.ParseFile(fset, fullFile, nil, 0)
1556 if err != nil {
1557 env.logf("error parsing %v: %v", fullFile, err)
1558 continue
1559 }
1560 if f.Name.Name == "documentation" {
1561 // Special case from go/build.ImportDir, not
1562 // handled by MatchFile above.
1563 continue
1564 }
1565 if includeTest && strings.HasSuffix(f.Name.Name, "_test") {
1566 // x_test package. We want internal test files only.
1567 continue
1568 }
1569 pkgName = f.Name.Name
1570 for name, obj := range f.Scope.Objects {
1571 if ast.IsExported(name) {
1572 var kind stdlib.Kind
1573 switch obj.Kind {
1574 case ast.Con:
1575 kind = stdlib.Const
1576 case ast.Typ:
1577 kind = stdlib.Type
1578 case ast.Var:
1579 kind = stdlib.Var
1580 case ast.Fun:
1581 kind = stdlib.Func
1582 }
1583 exports = append(exports, stdlib.Symbol{
1584 Name: name,
1585 Kind: kind,
1586 Version: 0, // unknown; be permissive
1587 })
1588 }
1589 }
1590 }
1591 sortSymbols(exports)
1592
1593 env.logf("loaded exports in dir %v (package %v): %v", dir, pkgName, exports)
1594 return pkgName, exports, nil
1595 }
1596
1597 func sortSymbols(syms []stdlib.Symbol) {
1598 sort.Slice(syms, func(i, j int) bool {
1599 return syms[i].Name < syms[j].Name
1600 })
1601 }
1602
1603 // A symbolSearcher searches for a package with a set of symbols, among a set
1604 // of candidates. See [symbolSearcher.search].
1605 //
1606 // The search occurs within the scope of a single file, with context captured
1607 // in srcDir and xtest.
1608 type symbolSearcher struct {
1609 logf func(string, ...any)
1610 srcDir string // directory containing the file
1611 xtest bool // if set, the file containing is an x_test file
1612 loadExports func(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error)
1613 }
1614
1615 // search searches the provided candidates for a package containing all
1616 // exported symbols.
1617 //
1618 // If successful, returns the resulting package.
1619 func (s *symbolSearcher) search(ctx context.Context, candidates []pkgDistance, pkgName string, symbols map[string]bool) (*pkg, error) {
1620 // Sort the candidates by their import package length,
1621 // assuming that shorter package names are better than long
1622 // ones. Note that this sorts by the de-vendored name, so
1623 // there's no "penalty" for vendoring.
1624 sort.Sort(byDistanceOrImportPathShortLength(candidates))
1625 if s.logf != nil {
1626 for i, c := range candidates {
1627 s.logf("%s candidate %d/%d: %v in %v", pkgName, i+1, len(candidates), c.pkg.importPathShort, c.pkg.dir)
1628 }
1629 }
1630
1631 // Arrange rescv so that we can we can await results in order of relevance
1632 // and exit as soon as we find the first match.
1633 //
1634 // Search with bounded concurrency, returning as soon as the first result
1635 // among rescv is non-nil.
1636 rescv := make([]chan *pkg, len(candidates))
1637 for i := range candidates {
1638 rescv[i] = make(chan *pkg, 1)
1639 }
1640 const maxConcurrentPackageImport = 4
1641 loadExportsSem := make(chan struct{}, maxConcurrentPackageImport)
1642
1643 // Ensure that all work is completed at exit.
1644 ctx, cancel := context.WithCancel(ctx)
1645 var wg sync.WaitGroup
1646 defer func() {
1647 cancel()
1648 wg.Wait()
1649 }()
1650
1651 // Start the search.
1652 wg.Go(func() {
1653 for i, c := range candidates {
1654 select {
1655 case loadExportsSem <- struct{}{}:
1656 case <-ctx.Done():
1657 return
1658 }
1659
1660 i := i
1661 c := c
1662 wg.Add(1)
1663 go func() {
1664 defer func() {
1665 <-loadExportsSem
1666 wg.Done()
1667 }()
1668 if s.logf != nil {
1669 s.logf("loading exports in dir %s (seeking package %s)", c.pkg.dir, pkgName)
1670 }
1671 pkg, err := s.searchOne(ctx, c, symbols)
1672 if err != nil {
1673 if s.logf != nil && ctx.Err() == nil {
1674 s.logf("loading exports in dir %s (seeking package %s): %v", c.pkg.dir, pkgName, err)
1675 }
1676 pkg = nil
1677 }
1678 rescv[i] <- pkg // may be nil
1679 }()
1680 }
1681 })
1682
1683 // Await the first (best) result.
1684 for _, resc := range rescv {
1685 select {
1686 case r := <-resc:
1687 if r != nil {
1688 return r, nil
1689 }
1690 case <-ctx.Done():
1691 return nil, ctx.Err()
1692 }
1693 }
1694 return nil, nil
1695 }
1696
1697 func (s *symbolSearcher) searchOne(ctx context.Context, c pkgDistance, symbols map[string]bool) (*pkg, error) {
1698 if ctx.Err() != nil {
1699 return nil, ctx.Err()
1700 }
1701 // If we're considering the package under test from an x_test, load the
1702 // test variant.
1703 includeTest := s.xtest && c.pkg.dir == s.srcDir
1704 _, exports, err := s.loadExports(ctx, c.pkg, includeTest)
1705 if err != nil {
1706 return nil, err
1707 }
1708
1709 exportsMap := make(map[string]bool, len(exports))
1710 for _, sym := range exports {
1711 exportsMap[sym.Name] = true
1712 }
1713 for symbol := range symbols {
1714 if !exportsMap[symbol] {
1715 return nil, nil // no match
1716 }
1717 }
1718 return c.pkg, nil
1719 }
1720
1721 // pkgIsCandidate reports whether pkg is a candidate for satisfying the
1722 // finding which package pkgIdent in the file named by filename is trying
1723 // to refer to.
1724 //
1725 // This check is purely lexical and is meant to be as fast as possible
1726 // because it's run over all $GOPATH directories to filter out poor
1727 // candidates in order to limit the CPU and I/O later parsing the
1728 // exports in candidate packages.
1729 //
1730 // filename is the file being formatted.
1731 // pkgIdent is the package being searched for, like "client" (if
1732 // searching for "client.New")
1733 func pkgIsCandidate(filename string, refs References, pkg *pkg) bool {
1734 // Check "internal" and "vendor" visibility:
1735 if !CanUse(filename, pkg.dir) {
1736 return false
1737 }
1738
1739 // Speed optimization to minimize disk I/O:
1740 //
1741 // Use the matchesPath heuristic to filter to package paths that could
1742 // reasonably match a dangling reference.
1743 //
1744 // This permits mismatch naming like directory "go-foo" being package "foo",
1745 // or "pkg.v3" being "pkg", or directory
1746 // "google.golang.org/api/cloudbilling/v1" being package "cloudbilling", but
1747 // doesn't permit a directory "foo" to be package "bar", which is strongly
1748 // discouraged anyway. There's no reason goimports needs to be slow just to
1749 // accommodate that.
1750 for pkgIdent := range refs {
1751 if matchesPath(pkgIdent, pkg.importPathShort) {
1752 return true
1753 }
1754 }
1755 return false
1756 }
1757
1758 // CanUse reports whether the package in dir is usable from filename,
1759 // respecting the Go "internal" and "vendor" visibility rules.
1760 func CanUse(filename, dir string) bool {
1761 // Fast path check, before any allocations. If it doesn't contain vendor
1762 // or internal, it's not tricky:
1763 // Note that this can false-negative on directories like "notinternal",
1764 // but we check it correctly below. This is just a fast path.
1765 if !strings.Contains(dir, "vendor") && !strings.Contains(dir, "internal") {
1766 return true
1767 }
1768
1769 dirSlash := filepath.ToSlash(dir)
1770 if !strings.Contains(dirSlash, "/vendor/") && !strings.Contains(dirSlash, "/internal/") && !strings.HasSuffix(dirSlash, "/internal") {
1771 return true
1772 }
1773 // Vendor or internal directory only visible from children of parent.
1774 // That means the path from the current directory to the target directory
1775 // can contain ../vendor or ../internal but not ../foo/vendor or ../foo/internal
1776 // or bar/vendor or bar/internal.
1777 // After stripping all the leading ../, the only okay place to see vendor or internal
1778 // is at the very beginning of the path.
1779 absfile, err := filepath.Abs(filename)
1780 if err != nil {
1781 return false
1782 }
1783 absdir, err := filepath.Abs(dir)
1784 if err != nil {
1785 return false
1786 }
1787 rel, err := filepath.Rel(absfile, absdir)
1788 if err != nil {
1789 return false
1790 }
1791 relSlash := filepath.ToSlash(rel)
1792 if i := strings.LastIndex(relSlash, "../"); i >= 0 {
1793 relSlash = relSlash[i+len("../"):]
1794 }
1795 return !strings.Contains(relSlash, "/vendor/") && !strings.Contains(relSlash, "/internal/") && !strings.HasSuffix(relSlash, "/internal")
1796 }
1797
1798 // matchesPath reports whether ident may match a potential package name
1799 // referred to by path, using heuristics to filter out unidiomatic package
1800 // names.
1801 //
1802 // Specifically, it checks whether either of the last two '/'- or '\'-delimited
1803 // path segments matches the identifier. The segment-matching heuristic must
1804 // allow for various conventions around segment naming, including go-foo,
1805 // foo-go, and foo.v3. To handle all of these, matching considers both (1) the
1806 // entire segment, ignoring '-' and '.', as well as (2) the last subsegment
1807 // separated by '-' or '.'. So the segment foo-go matches all of the following
1808 // identifiers: foo, go, and foogo. All matches are case insensitive (for ASCII
1809 // identifiers).
1810 //
1811 // See the docstring for [pkgIsCandidate] for an explanation of how this
1812 // heuristic filters potential candidate packages.
1813 func matchesPath(ident, path string) bool {
1814 // Ignore case, for ASCII.
1815 lowerIfASCII := func(b byte) byte {
1816 if 'A' <= b && b <= 'Z' {
1817 return b + ('a' - 'A')
1818 }
1819 return b
1820 }
1821
1822 // match reports whether path[start:end] matches ident, ignoring [.-].
1823 match := func(start, end int) bool {
1824 ii := len(ident) - 1 // current byte in ident
1825 pi := end - 1 // current byte in path
1826 for ; pi >= start && ii >= 0; pi-- {
1827 pb := path[pi]
1828 if pb == '-' || pb == '.' {
1829 continue
1830 }
1831 pb = lowerIfASCII(pb)
1832 ib := lowerIfASCII(ident[ii])
1833 if pb != ib {
1834 return false
1835 }
1836 ii--
1837 }
1838 return ii < 0 && pi < start // all bytes matched
1839 }
1840
1841 // segmentEnd and subsegmentEnd hold the end points of the current segment
1842 // and subsegment intervals.
1843 segmentEnd := len(path)
1844 subsegmentEnd := len(path)
1845
1846 // Count slashes; we only care about the last two segments.
1847 nslash := 0
1848
1849 for i := len(path) - 1; i >= 0; i-- {
1850 switch b := path[i]; b {
1851 // TODO(rfindley): we handle backlashes here only because the previous
1852 // heuristic handled backslashes. This is perhaps overly defensive, but is
1853 // the result of many lessons regarding Chesterton's fence and the
1854 // goimports codebase.
1855 //
1856 // However, this function is only ever called with something called an
1857 // 'importPath'. Is it possible that this is a real import path, and
1858 // therefore we need only consider forward slashes?
1859 case '/', '\\':
1860 if match(i+1, segmentEnd) || match(i+1, subsegmentEnd) {
1861 return true
1862 }
1863 nslash++
1864 if nslash == 2 {
1865 return false // did not match above
1866 }
1867 segmentEnd, subsegmentEnd = i, i // reset
1868 case '-', '.':
1869 if match(i+1, subsegmentEnd) {
1870 return true
1871 }
1872 subsegmentEnd = i
1873 }
1874 }
1875 return match(0, segmentEnd) || match(0, subsegmentEnd)
1876 }
1877
1878 type visitFn func(node ast.Node) ast.Visitor
1879
1880 func (fn visitFn) Visit(node ast.Node) ast.Visitor {
1881 return fn(node)
1882 }
1883
1884 func symbolNameSet(symbols []stdlib.Symbol) map[string]bool {
1885 names := make(map[string]bool)
1886 for _, sym := range symbols {
1887 switch sym.Kind {
1888 case stdlib.Const, stdlib.Var, stdlib.Type, stdlib.Func:
1889 names[sym.Name] = true
1890 }
1891 }
1892 return names
1893 }