]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/internal/modload/load.go
cmd/go/internal/modload: only check root-promotion during tidy for lazy modules
[gostls13.git] / src / cmd / go / internal / modload / load.go
1 // Copyright 2018 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 modload
6
7 // This file contains the module-mode package loader, as well as some accessory
8 // functions pertaining to the package import graph.
9 //
10 // There are two exported entry points into package loading — LoadPackages and
11 // ImportFromFiles — both implemented in terms of loadFromRoots, which itself
12 // manipulates an instance of the loader struct.
13 //
14 // Although most of the loading state is maintained in the loader struct,
15 // one key piece - the build list - is a global, so that it can be modified
16 // separate from the loading operation, such as during "go get"
17 // upgrades/downgrades or in "go mod" operations.
18 // TODO(#40775): It might be nice to make the loader take and return
19 // a buildList rather than hard-coding use of the global.
20 //
21 // Loading is an iterative process. On each iteration, we try to load the
22 // requested packages and their transitive imports, then try to resolve modules
23 // for any imported packages that are still missing.
24 //
25 // The first step of each iteration identifies a set of “root” packages.
26 // Normally the root packages are exactly those matching the named pattern
27 // arguments. However, for the "all" meta-pattern, the final set of packages is
28 // computed from the package import graph, and therefore cannot be an initial
29 // input to loading that graph. Instead, the root packages for the "all" pattern
30 // are those contained in the main module, and allPatternIsRoot parameter to the
31 // loader instructs it to dynamically expand those roots to the full "all"
32 // pattern as loading progresses.
33 //
34 // The pkgInAll flag on each loadPkg instance tracks whether that
35 // package is known to match the "all" meta-pattern.
36 // A package matches the "all" pattern if:
37 //      - it is in the main module, or
38 //      - it is imported by any test in the main module, or
39 //      - it is imported by another package in "all", or
40 //      - the main module specifies a go version ≤ 1.15, and the package is imported
41 //        by a *test of* another package in "all".
42 //
43 // When we implement lazy loading, we will record the modules providing packages
44 // in "all" even when we are only loading individual packages, so we set the
45 // pkgInAll flag regardless of the whether the "all" pattern is a root.
46 // (This is necessary to maintain the “import invariant” described in
47 // https://golang.org/design/36460-lazy-module-loading.)
48 //
49 // Because "go mod vendor" prunes out the tests of vendored packages, the
50 // behavior of the "all" pattern with -mod=vendor in Go 1.11–1.15 is the same
51 // as the "all" pattern (regardless of the -mod flag) in 1.16+.
52 // The loader uses the GoVersion parameter to determine whether the "all"
53 // pattern should close over tests (as in Go 1.11–1.15) or stop at only those
54 // packages transitively imported by the packages and tests in the main module
55 // ("all" in Go 1.16+ and "go mod vendor" in Go 1.11+).
56 //
57 // Note that it is possible for a loaded package NOT to be in "all" even when we
58 // are loading the "all" pattern. For example, packages that are transitive
59 // dependencies of other roots named on the command line must be loaded, but are
60 // not in "all". (The mod_notall test illustrates this behavior.)
61 // Similarly, if the LoadTests flag is set but the "all" pattern does not close
62 // over test dependencies, then when we load the test of a package that is in
63 // "all" but outside the main module, the dependencies of that test will not
64 // necessarily themselves be in "all". (That configuration does not arise in Go
65 // 1.11–1.15, but it will be possible in Go 1.16+.)
66 //
67 // Loading proceeds from the roots, using a parallel work-queue with a limit on
68 // the amount of active work (to avoid saturating disks, CPU cores, and/or
69 // network connections). Each package is added to the queue the first time it is
70 // imported by another package. When we have finished identifying the imports of
71 // a package, we add the test for that package if it is needed. A test may be
72 // needed if:
73 //      - the package matches a root pattern and tests of the roots were requested, or
74 //      - the package is in the main module and the "all" pattern is requested
75 //        (because the "all" pattern includes the dependencies of tests in the main
76 //        module), or
77 //      - the package is in "all" and the definition of "all" we are using includes
78 //        dependencies of tests (as is the case in Go ≤1.15).
79 //
80 // After all available packages have been loaded, we examine the results to
81 // identify any requested or imported packages that are still missing, and if
82 // so, which modules we could add to the module graph in order to make the
83 // missing packages available. We add those to the module graph and iterate,
84 // until either all packages resolve successfully or we cannot identify any
85 // module that would resolve any remaining missing package.
86 //
87 // If the main module is “tidy” (that is, if "go mod tidy" is a no-op for it)
88 // and all requested packages are in "all", then loading completes in a single
89 // iteration.
90 // TODO(bcmills): We should also be able to load in a single iteration if the
91 // requested packages all come from modules that are themselves tidy, regardless
92 // of whether those packages are in "all". Today, that requires two iterations
93 // if those packages are not found in existing dependencies of the main module.
94
95 import (
96         "bytes"
97         "context"
98         "errors"
99         "fmt"
100         "go/build"
101         "io/fs"
102         "os"
103         "path"
104         pathpkg "path"
105         "path/filepath"
106         "reflect"
107         "runtime"
108         "sort"
109         "strings"
110         "sync"
111         "sync/atomic"
112
113         "cmd/go/internal/base"
114         "cmd/go/internal/cfg"
115         "cmd/go/internal/fsys"
116         "cmd/go/internal/imports"
117         "cmd/go/internal/modfetch"
118         "cmd/go/internal/mvs"
119         "cmd/go/internal/par"
120         "cmd/go/internal/search"
121         "cmd/go/internal/str"
122
123         "golang.org/x/mod/module"
124         "golang.org/x/mod/semver"
125 )
126
127 // loaded is the most recently-used package loader.
128 // It holds details about individual packages.
129 //
130 // This variable should only be accessed directly in top-level exported
131 // functions. All other functions that require or produce a *loader should pass
132 // or return it as an explicit parameter.
133 var loaded *loader
134
135 // PackageOpts control the behavior of the LoadPackages function.
136 type PackageOpts struct {
137         // GoVersion is the Go version to which the go.mod file should be updated
138         // after packages have been loaded.
139         //
140         // An empty GoVersion means to use the Go version already specified in the
141         // main module's go.mod file, or the latest Go version if there is no main
142         // module.
143         GoVersion string
144
145         // Tags are the build tags in effect (as interpreted by the
146         // cmd/go/internal/imports package).
147         // If nil, treated as equivalent to imports.Tags().
148         Tags map[string]bool
149
150         // Tidy, if true, requests that the build list and go.sum file be reduced to
151         // the minimial dependencies needed to reproducibly reload the requested
152         // packages.
153         Tidy bool
154
155         // VendorModulesInGOROOTSrc indicates that if we are within a module in
156         // GOROOT/src, packages in the module's vendor directory should be resolved as
157         // actual module dependencies (instead of standard-library packages).
158         VendorModulesInGOROOTSrc bool
159
160         // ResolveMissingImports indicates that we should attempt to add module
161         // dependencies as needed to resolve imports of packages that are not found.
162         //
163         // For commands that support the -mod flag, resolving imports may still fail
164         // if the flag is set to "readonly" (the default) or "vendor".
165         ResolveMissingImports bool
166
167         // AllowPackage, if non-nil, is called after identifying the module providing
168         // each package. If AllowPackage returns a non-nil error, that error is set
169         // for the package, and the imports and test of that package will not be
170         // loaded.
171         //
172         // AllowPackage may be invoked concurrently by multiple goroutines,
173         // and may be invoked multiple times for a given package path.
174         AllowPackage func(ctx context.Context, path string, mod module.Version) error
175
176         // LoadTests loads the test dependencies of each package matching a requested
177         // pattern. If ResolveMissingImports is also true, test dependencies will be
178         // resolved if missing.
179         LoadTests bool
180
181         // UseVendorAll causes the "all" package pattern to be interpreted as if
182         // running "go mod vendor" (or building with "-mod=vendor").
183         //
184         // This is a no-op for modules that declare 'go 1.16' or higher, for which this
185         // is the default (and only) interpretation of the "all" pattern in module mode.
186         UseVendorAll bool
187
188         // AllowErrors indicates that LoadPackages should not terminate the process if
189         // an error occurs.
190         AllowErrors bool
191
192         // SilencePackageErrors indicates that LoadPackages should not print errors
193         // that occur while matching or loading packages, and should not terminate the
194         // process if such an error occurs.
195         //
196         // Errors encountered in the module graph will still be reported.
197         //
198         // The caller may retrieve the silenced package errors using the Lookup
199         // function, and matching errors are still populated in the Errs field of the
200         // associated search.Match.)
201         SilencePackageErrors bool
202
203         // SilenceMissingStdImports indicates that LoadPackages should not print
204         // errors or terminate the process if an imported package is missing, and the
205         // import path looks like it might be in the standard library (perhaps in a
206         // future version).
207         SilenceMissingStdImports bool
208
209         // SilenceNoGoErrors indicates that LoadPackages should not print
210         // imports.ErrNoGo errors.
211         // This allows the caller to invoke LoadPackages (and report other errors)
212         // without knowing whether the requested packages exist for the given tags.
213         //
214         // Note that if a requested package does not exist *at all*, it will fail
215         // during module resolution and the error will not be suppressed.
216         SilenceNoGoErrors bool
217
218         // SilenceUnmatchedWarnings suppresses the warnings normally emitted for
219         // patterns that did not match any packages.
220         SilenceUnmatchedWarnings bool
221 }
222
223 // LoadPackages identifies the set of packages matching the given patterns and
224 // loads the packages in the import graph rooted at that set.
225 func LoadPackages(ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string) {
226         if opts.Tags == nil {
227                 opts.Tags = imports.Tags()
228         }
229
230         patterns = search.CleanPatterns(patterns)
231         matches = make([]*search.Match, 0, len(patterns))
232         allPatternIsRoot := false
233         for _, pattern := range patterns {
234                 matches = append(matches, search.NewMatch(pattern))
235                 if pattern == "all" {
236                         allPatternIsRoot = true
237                 }
238         }
239
240         updateMatches := func(rs *Requirements, ld *loader) {
241                 for _, m := range matches {
242                         switch {
243                         case m.IsLocal():
244                                 // Evaluate list of file system directories on first iteration.
245                                 if m.Dirs == nil {
246                                         matchLocalDirs(ctx, m, rs)
247                                 }
248
249                                 // Make a copy of the directory list and translate to import paths.
250                                 // Note that whether a directory corresponds to an import path
251                                 // changes as the build list is updated, and a directory can change
252                                 // from not being in the build list to being in it and back as
253                                 // the exact version of a particular module increases during
254                                 // the loader iterations.
255                                 m.Pkgs = m.Pkgs[:0]
256                                 for _, dir := range m.Dirs {
257                                         pkg, err := resolveLocalPackage(ctx, dir, rs)
258                                         if err != nil {
259                                                 if !m.IsLiteral() && (err == errPkgIsBuiltin || err == errPkgIsGorootSrc) {
260                                                         continue // Don't include "builtin" or GOROOT/src in wildcard patterns.
261                                                 }
262
263                                                 // If we're outside of a module, ensure that the failure mode
264                                                 // indicates that.
265                                                 ModRoot()
266
267                                                 if ld != nil {
268                                                         m.AddError(err)
269                                                 }
270                                                 continue
271                                         }
272                                         m.Pkgs = append(m.Pkgs, pkg)
273                                 }
274
275                         case m.IsLiteral():
276                                 m.Pkgs = []string{m.Pattern()}
277
278                         case strings.Contains(m.Pattern(), "..."):
279                                 m.Errs = m.Errs[:0]
280                                 mg, err := rs.Graph(ctx)
281                                 if err != nil {
282                                         // The module graph is (or may be) incomplete — perhaps we failed to
283                                         // load the requirements of some module. This is an error in matching
284                                         // the patterns to packages, because we may be missing some packages
285                                         // or we may erroneously match packages in the wrong versions of
286                                         // modules. However, for cases like 'go list -e', the error should not
287                                         // necessarily prevent us from loading the packages we could find.
288                                         m.Errs = append(m.Errs, err)
289                                 }
290                                 matchPackages(ctx, m, opts.Tags, includeStd, mg.BuildList())
291
292                         case m.Pattern() == "all":
293                                 if ld == nil {
294                                         // The initial roots are the packages in the main module.
295                                         // loadFromRoots will expand that to "all".
296                                         m.Errs = m.Errs[:0]
297                                         matchPackages(ctx, m, opts.Tags, omitStd, []module.Version{Target})
298                                 } else {
299                                         // Starting with the packages in the main module,
300                                         // enumerate the full list of "all".
301                                         m.Pkgs = ld.computePatternAll()
302                                 }
303
304                         case m.Pattern() == "std" || m.Pattern() == "cmd":
305                                 if m.Pkgs == nil {
306                                         m.MatchPackages() // Locate the packages within GOROOT/src.
307                                 }
308
309                         default:
310                                 panic(fmt.Sprintf("internal error: modload missing case for pattern %s", m.Pattern()))
311                         }
312                 }
313         }
314
315         initialRS, _ := loadModFile(ctx) // Ignore needCommit — we're going to commit at the end regardless.
316
317         if opts.GoVersion == "" {
318                 opts.GoVersion = modFileGoVersion()
319         }
320
321         ld := loadFromRoots(ctx, loaderParams{
322                 PackageOpts:  opts,
323                 requirements: initialRS,
324
325                 allPatternIsRoot: allPatternIsRoot,
326
327                 listRoots: func(rs *Requirements) (roots []string) {
328                         updateMatches(rs, nil)
329                         for _, m := range matches {
330                                 roots = append(roots, m.Pkgs...)
331                         }
332                         return roots
333                 },
334         })
335
336         // One last pass to finalize wildcards.
337         updateMatches(ld.requirements, ld)
338
339         // List errors in matching patterns (such as directory permission
340         // errors for wildcard patterns).
341         if !ld.SilencePackageErrors {
342                 for _, match := range matches {
343                         for _, err := range match.Errs {
344                                 ld.errorf("%v\n", err)
345                         }
346                 }
347         }
348         base.ExitIfErrors()
349
350         if !opts.SilenceUnmatchedWarnings {
351                 search.WarnUnmatched(matches)
352         }
353
354         if opts.Tidy {
355                 if cfg.BuildV {
356                         mg, _ := ld.requirements.Graph(ctx)
357
358                         for _, m := range initialRS.rootModules {
359                                 var unused bool
360                                 if ld.requirements.depth == eager {
361                                         // m is unused if it was dropped from the module graph entirely. If it
362                                         // was only demoted from direct to indirect, it may still be in use via
363                                         // a transitive import.
364                                         unused = mg.Selected(m.Path) == "none"
365                                 } else {
366                                         // m is unused if it was dropped from the roots. If it is still present
367                                         // as a transitive dependency, that transitive dependency is not needed
368                                         // by any package or test in the main module.
369                                         _, ok := ld.requirements.rootSelected(m.Path)
370                                         unused = !ok
371                                 }
372                                 if unused {
373                                         fmt.Fprintf(os.Stderr, "unused %s\n", m.Path)
374                                 }
375                         }
376                 }
377
378                 modfetch.TrimGoSum(keepSums(ctx, ld, ld.requirements, loadedZipSumsOnly))
379         }
380
381         // Success! Update go.mod and go.sum (if needed) and return the results.
382         loaded = ld
383         commitRequirements(ctx, opts.GoVersion, loaded.requirements)
384
385         for _, pkg := range ld.pkgs {
386                 if !pkg.isTest() {
387                         loadedPackages = append(loadedPackages, pkg.path)
388                 }
389         }
390         sort.Strings(loadedPackages)
391         return matches, loadedPackages
392 }
393
394 // matchLocalDirs is like m.MatchDirs, but tries to avoid scanning directories
395 // outside of the standard library and active modules.
396 func matchLocalDirs(ctx context.Context, m *search.Match, rs *Requirements) {
397         if !m.IsLocal() {
398                 panic(fmt.Sprintf("internal error: resolveLocalDirs on non-local pattern %s", m.Pattern()))
399         }
400
401         if i := strings.Index(m.Pattern(), "..."); i >= 0 {
402                 // The pattern is local, but it is a wildcard. Its packages will
403                 // only resolve to paths if they are inside of the standard
404                 // library, the main module, or some dependency of the main
405                 // module. Verify that before we walk the filesystem: a filesystem
406                 // walk in a directory like /var or /etc can be very expensive!
407                 dir := filepath.Dir(filepath.Clean(m.Pattern()[:i+3]))
408                 absDir := dir
409                 if !filepath.IsAbs(dir) {
410                         absDir = filepath.Join(base.Cwd, dir)
411                 }
412                 if search.InDir(absDir, cfg.GOROOTsrc) == "" && search.InDir(absDir, ModRoot()) == "" && pathInModuleCache(ctx, absDir, rs) == "" {
413                         m.Dirs = []string{}
414                         m.AddError(fmt.Errorf("directory prefix %s outside available modules", base.ShortPath(absDir)))
415                         return
416                 }
417         }
418
419         m.MatchDirs()
420 }
421
422 // resolveLocalPackage resolves a filesystem path to a package path.
423 func resolveLocalPackage(ctx context.Context, dir string, rs *Requirements) (string, error) {
424         var absDir string
425         if filepath.IsAbs(dir) {
426                 absDir = filepath.Clean(dir)
427         } else {
428                 absDir = filepath.Join(base.Cwd, dir)
429         }
430
431         bp, err := cfg.BuildContext.ImportDir(absDir, 0)
432         if err != nil && (bp == nil || len(bp.IgnoredGoFiles) == 0) {
433                 // golang.org/issue/32917: We should resolve a relative path to a
434                 // package path only if the relative path actually contains the code
435                 // for that package.
436                 //
437                 // If the named directory does not exist or contains no Go files,
438                 // the package does not exist.
439                 // Other errors may affect package loading, but not resolution.
440                 if _, err := fsys.Stat(absDir); err != nil {
441                         if os.IsNotExist(err) {
442                                 // Canonicalize OS-specific errors to errDirectoryNotFound so that error
443                                 // messages will be easier for users to search for.
444                                 return "", &fs.PathError{Op: "stat", Path: absDir, Err: errDirectoryNotFound}
445                         }
446                         return "", err
447                 }
448                 if _, noGo := err.(*build.NoGoError); noGo {
449                         // A directory that does not contain any Go source files — even ignored
450                         // ones! — is not a Go package, and we can't resolve it to a package
451                         // path because that path could plausibly be provided by some other
452                         // module.
453                         //
454                         // Any other error indicates that the package “exists” (at least in the
455                         // sense that it cannot exist in any other module), but has some other
456                         // problem (such as a syntax error).
457                         return "", err
458                 }
459         }
460
461         if modRoot != "" && absDir == modRoot {
462                 if absDir == cfg.GOROOTsrc {
463                         return "", errPkgIsGorootSrc
464                 }
465                 return targetPrefix, nil
466         }
467
468         // Note: The checks for @ here are just to avoid misinterpreting
469         // the module cache directories (formerly GOPATH/src/mod/foo@v1.5.2/bar).
470         // It's not strictly necessary but helpful to keep the checks.
471         if modRoot != "" && strings.HasPrefix(absDir, modRoot+string(filepath.Separator)) && !strings.Contains(absDir[len(modRoot):], "@") {
472                 suffix := filepath.ToSlash(absDir[len(modRoot):])
473                 if strings.HasPrefix(suffix, "/vendor/") {
474                         if cfg.BuildMod != "vendor" {
475                                 return "", fmt.Errorf("without -mod=vendor, directory %s has no package path", absDir)
476                         }
477
478                         readVendorList()
479                         pkg := strings.TrimPrefix(suffix, "/vendor/")
480                         if _, ok := vendorPkgModule[pkg]; !ok {
481                                 return "", fmt.Errorf("directory %s is not a package listed in vendor/modules.txt", absDir)
482                         }
483                         return pkg, nil
484                 }
485
486                 if targetPrefix == "" {
487                         pkg := strings.TrimPrefix(suffix, "/")
488                         if pkg == "builtin" {
489                                 // "builtin" is a pseudo-package with a real source file.
490                                 // It's not included in "std", so it shouldn't resolve from "."
491                                 // within module "std" either.
492                                 return "", errPkgIsBuiltin
493                         }
494                         return pkg, nil
495                 }
496
497                 pkg := targetPrefix + suffix
498                 if _, ok, err := dirInModule(pkg, targetPrefix, modRoot, true); err != nil {
499                         return "", err
500                 } else if !ok {
501                         return "", &PackageNotInModuleError{Mod: Target, Pattern: pkg}
502                 }
503                 return pkg, nil
504         }
505
506         if sub := search.InDir(absDir, cfg.GOROOTsrc); sub != "" && sub != "." && !strings.Contains(sub, "@") {
507                 pkg := filepath.ToSlash(sub)
508                 if pkg == "builtin" {
509                         return "", errPkgIsBuiltin
510                 }
511                 return pkg, nil
512         }
513
514         pkg := pathInModuleCache(ctx, absDir, rs)
515         if pkg == "" {
516                 return "", fmt.Errorf("directory %s outside available modules", base.ShortPath(absDir))
517         }
518         return pkg, nil
519 }
520
521 var (
522         errDirectoryNotFound = errors.New("directory not found")
523         errPkgIsGorootSrc    = errors.New("GOROOT/src is not an importable package")
524         errPkgIsBuiltin      = errors.New(`"builtin" is a pseudo-package, not an importable package`)
525 )
526
527 // pathInModuleCache returns the import path of the directory dir,
528 // if dir is in the module cache copy of a module in our build list.
529 func pathInModuleCache(ctx context.Context, dir string, rs *Requirements) string {
530         tryMod := func(m module.Version) (string, bool) {
531                 var root string
532                 var err error
533                 if repl := Replacement(m); repl.Path != "" && repl.Version == "" {
534                         root = repl.Path
535                         if !filepath.IsAbs(root) {
536                                 root = filepath.Join(ModRoot(), root)
537                         }
538                 } else if repl.Path != "" {
539                         root, err = modfetch.DownloadDir(repl)
540                 } else {
541                         root, err = modfetch.DownloadDir(m)
542                 }
543                 if err != nil {
544                         return "", false
545                 }
546
547                 sub := search.InDir(dir, root)
548                 if sub == "" {
549                         return "", false
550                 }
551                 sub = filepath.ToSlash(sub)
552                 if strings.Contains(sub, "/vendor/") || strings.HasPrefix(sub, "vendor/") || strings.Contains(sub, "@") {
553                         return "", false
554                 }
555
556                 return path.Join(m.Path, filepath.ToSlash(sub)), true
557         }
558
559         if rs.depth == lazy {
560                 for _, m := range rs.rootModules {
561                         if v, _ := rs.rootSelected(m.Path); v != m.Version {
562                                 continue // m is a root, but we have a higher root for the same path.
563                         }
564                         if importPath, ok := tryMod(m); ok {
565                                 // checkMultiplePaths ensures that a module can be used for at most one
566                                 // requirement, so this must be it.
567                                 return importPath
568                         }
569                 }
570         }
571
572         // None of the roots contained dir, or we're in eager mode and want to load
573         // the full module graph more aggressively. Either way, check the full graph
574         // to see if the directory is a non-root dependency.
575         //
576         // If the roots are not consistent with the full module graph, the selected
577         // versions of root modules may differ from what we already checked above.
578         // Re-check those paths too.
579
580         mg, _ := rs.Graph(ctx)
581         var importPath string
582         for _, m := range mg.BuildList() {
583                 var found bool
584                 importPath, found = tryMod(m)
585                 if found {
586                         break
587                 }
588         }
589         return importPath
590 }
591
592 // ImportFromFiles adds modules to the build list as needed
593 // to satisfy the imports in the named Go source files.
594 //
595 // Errors in missing dependencies are silenced.
596 //
597 // TODO(bcmills): Silencing errors seems off. Take a closer look at this and
598 // figure out what the error-reporting actually ought to be.
599 func ImportFromFiles(ctx context.Context, gofiles []string) {
600         rs := LoadModFile(ctx)
601
602         tags := imports.Tags()
603         imports, testImports, err := imports.ScanFiles(gofiles, tags)
604         if err != nil {
605                 base.Fatalf("go: %v", err)
606         }
607
608         goVersion := modFileGoVersion()
609         loaded = loadFromRoots(ctx, loaderParams{
610                 PackageOpts: PackageOpts{
611                         GoVersion:             goVersion,
612                         Tags:                  tags,
613                         ResolveMissingImports: true,
614                         SilencePackageErrors:  true,
615                 },
616                 requirements: rs,
617                 listRoots: func(*Requirements) (roots []string) {
618                         roots = append(roots, imports...)
619                         roots = append(roots, testImports...)
620                         return roots
621                 },
622         })
623         commitRequirements(ctx, goVersion, loaded.requirements)
624 }
625
626 // DirImportPath returns the effective import path for dir,
627 // provided it is within the main module, or else returns ".".
628 func DirImportPath(ctx context.Context, dir string) string {
629         if !HasModRoot() {
630                 return "."
631         }
632         LoadModFile(ctx) // Sets targetPrefix.
633
634         if !filepath.IsAbs(dir) {
635                 dir = filepath.Join(base.Cwd, dir)
636         } else {
637                 dir = filepath.Clean(dir)
638         }
639
640         if dir == modRoot {
641                 return targetPrefix
642         }
643         if strings.HasPrefix(dir, modRoot+string(filepath.Separator)) {
644                 suffix := filepath.ToSlash(dir[len(modRoot):])
645                 if strings.HasPrefix(suffix, "/vendor/") {
646                         return strings.TrimPrefix(suffix, "/vendor/")
647                 }
648                 return targetPrefix + suffix
649         }
650         return "."
651 }
652
653 // TargetPackages returns the list of packages in the target (top-level) module
654 // matching pattern, which may be relative to the working directory, under all
655 // build tag settings.
656 func TargetPackages(ctx context.Context, pattern string) *search.Match {
657         // TargetPackages is relative to the main module, so ensure that the main
658         // module is a thing that can contain packages.
659         LoadModFile(ctx) // Sets Target.
660         ModRoot()        // Emits an error if Target cannot contain packages.
661
662         m := search.NewMatch(pattern)
663         matchPackages(ctx, m, imports.AnyTags(), omitStd, []module.Version{Target})
664         return m
665 }
666
667 // ImportMap returns the actual package import path
668 // for an import path found in source code.
669 // If the given import path does not appear in the source code
670 // for the packages that have been loaded, ImportMap returns the empty string.
671 func ImportMap(path string) string {
672         pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
673         if !ok {
674                 return ""
675         }
676         return pkg.path
677 }
678
679 // PackageDir returns the directory containing the source code
680 // for the package named by the import path.
681 func PackageDir(path string) string {
682         pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
683         if !ok {
684                 return ""
685         }
686         return pkg.dir
687 }
688
689 // PackageModule returns the module providing the package named by the import path.
690 func PackageModule(path string) module.Version {
691         pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
692         if !ok {
693                 return module.Version{}
694         }
695         return pkg.mod
696 }
697
698 // PackageImports returns the imports for the package named by the import path.
699 // Test imports will be returned as well if tests were loaded for the package
700 // (i.e., if "all" was loaded or if LoadTests was set and the path was matched
701 // by a command line argument). PackageImports will return nil for
702 // unknown package paths.
703 func PackageImports(path string) (imports, testImports []string) {
704         pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
705         if !ok {
706                 return nil, nil
707         }
708         imports = make([]string, len(pkg.imports))
709         for i, p := range pkg.imports {
710                 imports[i] = p.path
711         }
712         if pkg.test != nil {
713                 testImports = make([]string, len(pkg.test.imports))
714                 for i, p := range pkg.test.imports {
715                         testImports[i] = p.path
716                 }
717         }
718         return imports, testImports
719 }
720
721 // Lookup returns the source directory, import path, and any loading error for
722 // the package at path as imported from the package in parentDir.
723 // Lookup requires that one of the Load functions in this package has already
724 // been called.
725 func Lookup(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) {
726         if path == "" {
727                 panic("Lookup called with empty package path")
728         }
729
730         if parentIsStd {
731                 path = loaded.stdVendor(parentPath, path)
732         }
733         pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
734         if !ok {
735                 // The loader should have found all the relevant paths.
736                 // There are a few exceptions, though:
737                 //      - during go list without -test, the p.Resolve calls to process p.TestImports and p.XTestImports
738                 //        end up here to canonicalize the import paths.
739                 //      - during any load, non-loaded packages like "unsafe" end up here.
740                 //      - during any load, build-injected dependencies like "runtime/cgo" end up here.
741                 //      - because we ignore appengine/* in the module loader,
742                 //        the dependencies of any actual appengine/* library end up here.
743                 dir := findStandardImportPath(path)
744                 if dir != "" {
745                         return dir, path, nil
746                 }
747                 return "", "", errMissing
748         }
749         return pkg.dir, pkg.path, pkg.err
750 }
751
752 // A loader manages the process of loading information about
753 // the required packages for a particular build,
754 // checking that the packages are available in the module set,
755 // and updating the module set if needed.
756 type loader struct {
757         loaderParams
758
759         // allClosesOverTests indicates whether the "all" pattern includes
760         // dependencies of tests outside the main module (as in Go 1.11–1.15).
761         // (Otherwise — as in Go 1.16+ — the "all" pattern includes only the packages
762         // transitively *imported by* the packages and tests in the main module.)
763         allClosesOverTests bool
764
765         work *par.Queue
766
767         // reset on each iteration
768         roots    []*loadPkg
769         pkgCache *par.Cache // package path (string) → *loadPkg
770         pkgs     []*loadPkg // transitive closure of loaded packages and tests; populated in buildStacks
771 }
772
773 // loaderParams configure the packages loaded by, and the properties reported
774 // by, a loader instance.
775 type loaderParams struct {
776         PackageOpts
777         requirements *Requirements
778
779         allPatternIsRoot bool // Is the "all" pattern an additional root?
780
781         listRoots func(rs *Requirements) []string
782 }
783
784 func (ld *loader) reset() {
785         select {
786         case <-ld.work.Idle():
787         default:
788                 panic("loader.reset when not idle")
789         }
790
791         ld.roots = nil
792         ld.pkgCache = new(par.Cache)
793         ld.pkgs = nil
794 }
795
796 // errorf reports an error via either os.Stderr or base.Errorf,
797 // according to whether ld.AllowErrors is set.
798 func (ld *loader) errorf(format string, args ...interface{}) {
799         if ld.AllowErrors {
800                 fmt.Fprintf(os.Stderr, format, args...)
801         } else {
802                 base.Errorf(format, args...)
803         }
804 }
805
806 // A loadPkg records information about a single loaded package.
807 type loadPkg struct {
808         // Populated at construction time:
809         path   string // import path
810         testOf *loadPkg
811
812         // Populated at construction time and updated by (*loader).applyPkgFlags:
813         flags atomicLoadPkgFlags
814
815         // Populated by (*loader).load:
816         mod         module.Version // module providing package
817         dir         string         // directory containing source code
818         err         error          // error loading package
819         imports     []*loadPkg     // packages imported by this one
820         testImports []string       // test-only imports, saved for use by pkg.test.
821         inStd       bool
822
823         // Populated by (*loader).pkgTest:
824         testOnce sync.Once
825         test     *loadPkg
826
827         // Populated by postprocessing in (*loader).buildStacks:
828         stack *loadPkg // package importing this one in minimal import stack for this pkg
829 }
830
831 // loadPkgFlags is a set of flags tracking metadata about a package.
832 type loadPkgFlags int8
833
834 const (
835         // pkgInAll indicates that the package is in the "all" package pattern,
836         // regardless of whether we are loading the "all" package pattern.
837         //
838         // When the pkgInAll flag and pkgImportsLoaded flags are both set, the caller
839         // who set the last of those flags must propagate the pkgInAll marking to all
840         // of the imports of the marked package.
841         //
842         // A test is marked with pkgInAll if that test would promote the packages it
843         // imports to be in "all" (such as when the test is itself within the main
844         // module, or when ld.allClosesOverTests is true).
845         pkgInAll loadPkgFlags = 1 << iota
846
847         // pkgIsRoot indicates that the package matches one of the root package
848         // patterns requested by the caller.
849         //
850         // If LoadTests is set, then when pkgIsRoot and pkgImportsLoaded are both set,
851         // the caller who set the last of those flags must populate a test for the
852         // package (in the pkg.test field).
853         //
854         // If the "all" pattern is included as a root, then non-test packages in "all"
855         // are also roots (and must be marked pkgIsRoot).
856         pkgIsRoot
857
858         // pkgImportsLoaded indicates that the imports and testImports fields of a
859         // loadPkg have been populated.
860         pkgImportsLoaded
861 )
862
863 // has reports whether all of the flags in cond are set in f.
864 func (f loadPkgFlags) has(cond loadPkgFlags) bool {
865         return f&cond == cond
866 }
867
868 // An atomicLoadPkgFlags stores a loadPkgFlags for which individual flags can be
869 // added atomically.
870 type atomicLoadPkgFlags struct {
871         bits int32
872 }
873
874 // update sets the given flags in af (in addition to any flags already set).
875 //
876 // update returns the previous flag state so that the caller may determine which
877 // flags were newly-set.
878 func (af *atomicLoadPkgFlags) update(flags loadPkgFlags) (old loadPkgFlags) {
879         for {
880                 old := atomic.LoadInt32(&af.bits)
881                 new := old | int32(flags)
882                 if new == old || atomic.CompareAndSwapInt32(&af.bits, old, new) {
883                         return loadPkgFlags(old)
884                 }
885         }
886 }
887
888 // has reports whether all of the flags in cond are set in af.
889 func (af *atomicLoadPkgFlags) has(cond loadPkgFlags) bool {
890         return loadPkgFlags(atomic.LoadInt32(&af.bits))&cond == cond
891 }
892
893 // isTest reports whether pkg is a test of another package.
894 func (pkg *loadPkg) isTest() bool {
895         return pkg.testOf != nil
896 }
897
898 // fromExternalModule reports whether pkg was loaded from a module other than
899 // the main module.
900 func (pkg *loadPkg) fromExternalModule() bool {
901         if pkg.mod.Path == "" {
902                 return false // loaded from the standard library, not a module
903         }
904         if pkg.mod.Path == Target.Path {
905                 return false // loaded from the main module.
906         }
907         return true
908 }
909
910 var errMissing = errors.New("cannot find package")
911
912 // loadFromRoots attempts to load the build graph needed to process a set of
913 // root packages and their dependencies.
914 //
915 // The set of root packages is returned by the params.listRoots function, and
916 // expanded to the full set of packages by tracing imports (and possibly tests)
917 // as needed.
918 func loadFromRoots(ctx context.Context, params loaderParams) *loader {
919         ld := &loader{
920                 loaderParams: params,
921                 work:         par.NewQueue(runtime.GOMAXPROCS(0)),
922         }
923
924         if params.GoVersion != "" {
925                 if semver.Compare("v"+params.GoVersion, narrowAllVersionV) < 0 && !ld.UseVendorAll {
926                         // The module's go version explicitly predates the change in "all" for lazy
927                         // loading, so continue to use the older interpretation.
928                         // (If params.GoVersion is empty, we are probably not in any module at all
929                         // and should use the latest semantics.)
930                         ld.allClosesOverTests = true
931                 }
932
933                 var err error
934                 ld.requirements, err = convertDepth(ctx, ld.requirements, modDepthFromGoVersion(params.GoVersion))
935                 if err != nil {
936                         ld.errorf("go: %v\n", err)
937                 }
938         }
939
940         if ld.requirements.depth == eager {
941                 var err error
942                 ld.requirements, _, err = expandGraph(ctx, ld.requirements)
943                 if err != nil {
944                         ld.errorf("go: %v\n", err)
945                 }
946         }
947
948         for {
949                 ld.reset()
950
951                 // Load the root packages and their imports.
952                 // Note: the returned roots can change on each iteration,
953                 // since the expansion of package patterns depends on the
954                 // build list we're using.
955                 rootPkgs := ld.listRoots(ld.requirements)
956
957                 if ld.requirements.depth == lazy && cfg.BuildMod == "mod" {
958                         // Before we start loading transitive imports of packages, locate all of
959                         // the root packages and promote their containing modules to root modules
960                         // dependencies. If their go.mod files are tidy (the common case) and the
961                         // set of root packages does not change then we can select the correct
962                         // versions of all transitive imports on the first try and complete
963                         // loading in a single iteration.
964                         changedBuildList := ld.preloadRootModules(ctx, rootPkgs)
965                         if changedBuildList {
966                                 // The build list has changed, so the set of root packages may have also
967                                 // changed. Start over to pick up the changes. (Preloading roots is much
968                                 // cheaper than loading the full import graph, so we would rather pay
969                                 // for an extra iteration of preloading than potentially end up
970                                 // discarding the result of a full iteration of loading.)
971                                 continue
972                         }
973                 }
974
975                 inRoots := map[*loadPkg]bool{}
976                 for _, path := range rootPkgs {
977                         root := ld.pkg(ctx, path, pkgIsRoot)
978                         if !inRoots[root] {
979                                 ld.roots = append(ld.roots, root)
980                                 inRoots[root] = true
981                         }
982                 }
983
984                 // ld.pkg adds imported packages to the work queue and calls applyPkgFlags,
985                 // which adds tests (and test dependencies) as needed.
986                 //
987                 // When all of the work in the queue has completed, we'll know that the
988                 // transitive closure of dependencies has been loaded.
989                 <-ld.work.Idle()
990
991                 ld.buildStacks()
992
993                 changed, err := ld.updateRequirements(ctx)
994                 if err != nil {
995                         ld.errorf("go: %v\n", err)
996                         break
997                 }
998                 if changed {
999                         // Don't resolve missing imports until the module graph have stabilized.
1000                         // If the roots are still changing, they may turn out to specify a
1001                         // requirement on the missing package(s), and we would rather use a
1002                         // version specified by a new root than add a new dependency on an
1003                         // unrelated version.
1004                         continue
1005                 }
1006
1007                 if !ld.ResolveMissingImports || (!HasModRoot() && !allowMissingModuleImports) {
1008                         // We've loaded as much as we can without resolving missing imports.
1009                         break
1010                 }
1011
1012                 modAddedBy := ld.resolveMissingImports(ctx)
1013                 if len(modAddedBy) == 0 {
1014                         // The roots are stable, and we've resolved all of the missing packages
1015                         // that we can.
1016                         break
1017                 }
1018
1019                 toAdd := make([]module.Version, 0, len(modAddedBy))
1020                 for m, _ := range modAddedBy {
1021                         toAdd = append(toAdd, m)
1022                 }
1023                 module.Sort(toAdd) // to make errors deterministic
1024
1025                 // We ran updateRequirements before resolving missing imports and it didn't
1026                 // make any changes, so we know that the requirement graph is already
1027                 // consistent with ld.pkgs: we don't need to pass ld.pkgs to updateRoots
1028                 // again. (That would waste time looking for changes that we have already
1029                 // applied.)
1030                 var noPkgs []*loadPkg
1031                 // We also know that we're going to call updateRequirements again next
1032                 // iteration so we don't need to also update it here. (That would waste time
1033                 // computing a "direct" map that we'll have to recompute later anyway.)
1034                 direct := ld.requirements.direct
1035                 rs, err := updateRoots(ctx, direct, ld.requirements, noPkgs, toAdd)
1036                 if err != nil {
1037                         // If an error was found in a newly added module, report the package
1038                         // import stack instead of the module requirement stack. Packages
1039                         // are more descriptive.
1040                         if err, ok := err.(*mvs.BuildListError); ok {
1041                                 if pkg := modAddedBy[err.Module()]; pkg != nil {
1042                                         ld.errorf("go: %s: %v\n", pkg.stackText(), err.Err)
1043                                         break
1044                                 }
1045                         }
1046                         ld.errorf("go: %v\n", err)
1047                         break
1048                 }
1049                 if reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1050                         // Something is deeply wrong. resolveMissingImports gave us a non-empty
1051                         // set of modules to add to the graph, but adding those modules had no
1052                         // effect — either they were already in the graph, or updateRoots did not
1053                         // add them as requested.
1054                         panic(fmt.Sprintf("internal error: adding %v to module graph had no effect on root requirements (%v)", toAdd, rs.rootModules))
1055                 }
1056                 ld.requirements = rs
1057         }
1058         base.ExitIfErrors() // TODO(bcmills): Is this actually needed?
1059
1060         // Tidy the build list, if applicable, before we report errors.
1061         // (The process of tidying may remove errors from irrelevant dependencies.)
1062         if ld.Tidy {
1063                 rs, err := tidyRoots(ctx, ld.requirements, ld.pkgs)
1064                 if err != nil {
1065                         ld.errorf("go: %v\n", err)
1066                 }
1067
1068                 if ld.requirements.depth == lazy {
1069                         // We continuously add tidy roots to ld.requirements during loading, so at
1070                         // this point the tidy roots should be a subset of the roots of
1071                         // ld.requirements, ensuring that no new dependencies are brought inside
1072                         // the lazy-loading horizon.
1073                         // If that is not the case, there is a bug in the loading loop above.
1074                         for _, m := range rs.rootModules {
1075                                 if v, ok := ld.requirements.rootSelected(m.Path); !ok || v != m.Version {
1076                                         ld.errorf("go: internal error: a requirement on %v is needed but was not added during package loading\n", m)
1077                                         base.ExitIfErrors()
1078                                 }
1079                         }
1080                 }
1081                 ld.requirements = rs
1082         }
1083
1084         // Report errors, if any.
1085         for _, pkg := range ld.pkgs {
1086                 if pkg.err == nil {
1087                         continue
1088                 }
1089
1090                 // Add importer information to checksum errors.
1091                 if sumErr := (*ImportMissingSumError)(nil); errors.As(pkg.err, &sumErr) {
1092                         if importer := pkg.stack; importer != nil {
1093                                 sumErr.importer = importer.path
1094                                 sumErr.importerVersion = importer.mod.Version
1095                                 sumErr.importerIsTest = importer.testOf != nil
1096                         }
1097                 }
1098
1099                 if ld.SilencePackageErrors {
1100                         continue
1101                 }
1102                 if stdErr := (*ImportMissingError)(nil); errors.As(pkg.err, &stdErr) &&
1103                         stdErr.isStd && ld.SilenceMissingStdImports {
1104                         continue
1105                 }
1106                 if ld.SilenceNoGoErrors && errors.Is(pkg.err, imports.ErrNoGo) {
1107                         continue
1108                 }
1109
1110                 ld.errorf("%s: %v\n", pkg.stackText(), pkg.err)
1111         }
1112
1113         ld.checkMultiplePaths()
1114         return ld
1115 }
1116
1117 // updateRequirements ensures that ld.requirements is consistent with the
1118 // information gained from ld.pkgs and includes the modules in add as roots at
1119 // at least the given versions.
1120 //
1121 // In particular:
1122 //
1123 //      - Modules that provide packages directly imported from the main module are
1124 //        marked as direct, and are promoted to explicit roots. If a needed root
1125 //        cannot be promoted due to -mod=readonly or -mod=vendor, the importing
1126 //        package is marked with an error.
1127 //
1128 //      - If ld scanned the "all" pattern independent of build constraints, it is
1129 //        guaranteed to have seen every direct import. Module dependencies that did
1130 //        not provide any directly-imported package are then marked as indirect.
1131 //
1132 //      - Root dependencies are updated to their selected versions.
1133 //
1134 // The "changed" return value reports whether the update changed the selected
1135 // version of any module that either provided a loaded package or may now
1136 // provide a package that was previously unresolved.
1137 func (ld *loader) updateRequirements(ctx context.Context) (changed bool, err error) {
1138         rs := ld.requirements
1139
1140         // direct contains the set of modules believed to provide packages directly
1141         // imported by the main module.
1142         var direct map[string]bool
1143
1144         // If we didn't scan all of the imports from the main module, or didn't use
1145         // imports.AnyTags, then we didn't necessarily load every package that
1146         // contributes “direct” imports — so we can't safely mark existing direct
1147         // dependencies in ld.requirements as indirect-only. Propagate them as direct.
1148         loadedDirect := ld.allPatternIsRoot && reflect.DeepEqual(ld.Tags, imports.AnyTags())
1149         if loadedDirect {
1150                 direct = make(map[string]bool)
1151         } else {
1152                 // TODO(bcmills): It seems like a shame to allocate and copy a map here when
1153                 // it will only rarely actually vary from rs.direct. Measure this cost and
1154                 // maybe avoid the copy.
1155                 direct = make(map[string]bool, len(rs.direct))
1156                 for mPath := range rs.direct {
1157                         direct[mPath] = true
1158                 }
1159         }
1160
1161         for _, pkg := range ld.pkgs {
1162                 if pkg.mod != Target {
1163                         continue
1164                 }
1165                 for _, dep := range pkg.imports {
1166                         if !dep.fromExternalModule() {
1167                                 continue
1168                         }
1169
1170                         if pkg.err == nil && cfg.BuildMod != "mod" {
1171                                 if v, ok := rs.rootSelected(dep.mod.Path); !ok || v != dep.mod.Version {
1172                                         // dep.mod is not an explicit dependency, but needs to be.
1173                                         // Because we are not in "mod" mode, we will not be able to update it.
1174                                         // Instead, mark the importing package with an error.
1175                                         //
1176                                         // TODO(#41688): The resulting error message fails to include the file
1177                                         // position of the import statement (because that information is not
1178                                         // tracked by the module loader). Figure out how to plumb the import
1179                                         // position through.
1180                                         pkg.err = &DirectImportFromImplicitDependencyError{
1181                                                 ImporterPath: pkg.path,
1182                                                 ImportedPath: dep.path,
1183                                                 Module:       dep.mod,
1184                                         }
1185                                         // cfg.BuildMod does not allow us to change dep.mod to be a direct
1186                                         // dependency, so don't mark it as such.
1187                                         continue
1188                                 }
1189                         }
1190
1191                         // dep is a package directly imported by a package or test in the main
1192                         // module and loaded from some other module (not the standard library).
1193                         // Mark its module as a direct dependency.
1194                         direct[dep.mod.Path] = true
1195                 }
1196         }
1197
1198         var addRoots []module.Version
1199         if ld.Tidy {
1200                 // When we are tidying a lazy module, we may need to add roots to preserve
1201                 // the versions of indirect, test-only dependencies that are upgraded
1202                 // above or otherwise missing from the go.mod files of direct
1203                 // dependencies. (For example, the direct dependency might be a very
1204                 // stable codebase that predates modules and thus lacks a go.mod file, or
1205                 // the author of the direct dependency may have forgotten to commit a
1206                 // change to the go.mod file, or may have made an erroneous hand-edit that
1207                 // causes it to be untidy.)
1208                 //
1209                 // Promoting an indirect dependency to a root adds the next layer of its
1210                 // dependencies to the module graph, which may increase the selected
1211                 // versions of other modules from which we have already loaded packages.
1212                 // So after we promote an indirect dependency to a root, we need to reload
1213                 // packages, which means another iteration of loading.
1214                 //
1215                 // As an extra wrinkle, the upgrades due to promoting a root can cause
1216                 // previously-resolved packages to become unresolved. For example, the
1217                 // module providing an unstable package might be upgraded to a version
1218                 // that no longer contains that package. If we then resolve the missing
1219                 // package, we might add yet another root that upgrades away some other
1220                 // dependency. (The tests in mod_tidy_convergence*.txt illustrate some
1221                 // particularly worrisome cases.)
1222                 //
1223                 // To ensure that this process of promoting, adding, and upgrading roots
1224                 // eventually terminates, during iteration we only ever add modules to the
1225                 // root set — we only remove irrelevant roots at the very end of
1226                 // iteration, after we have already added every root that we plan to need
1227                 // in the (eventual) tidy root set.
1228                 //
1229                 // Since we do not remove any roots during iteration, even if they no
1230                 // longer provide any imported packages, the selected versions of the
1231                 // roots can only increase and the set of roots can only expand. The set
1232                 // of extant root paths is finite and the set of versions of each path is
1233                 // finite, so the iteration *must* reach a stable fixed-point.
1234                 tidy, err := tidyRoots(ctx, rs, ld.pkgs)
1235                 if err != nil {
1236                         return false, err
1237                 }
1238                 addRoots = tidy.rootModules
1239         }
1240
1241         rs, err = updateRoots(ctx, direct, rs, ld.pkgs, addRoots)
1242         if err != nil {
1243                 // We don't actually know what even the root requirements are supposed to be,
1244                 // so we can't proceed with loading. Return the error to the caller
1245                 return false, err
1246         }
1247
1248         if rs != ld.requirements && !reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1249                 // The roots of the module graph have changed in some way (not just the
1250                 // "direct" markings). Check whether the changes affected any of the loaded
1251                 // packages.
1252                 mg, err := rs.Graph(ctx)
1253                 if err != nil {
1254                         return false, err
1255                 }
1256                 for _, pkg := range ld.pkgs {
1257                         if pkg.fromExternalModule() && mg.Selected(pkg.mod.Path) != pkg.mod.Version {
1258                                 changed = true
1259                                 break
1260                         }
1261                         if pkg.err != nil {
1262                                 // Promoting a module to a root may resolve an import that was
1263                                 // previously missing (by pulling in a previously-prune dependency that
1264                                 // provides it) or ambiguous (by promoting exactly one of the
1265                                 // alternatives to a root and ignoring the second-level alternatives) or
1266                                 // otherwise errored out (by upgrading from a version that cannot be
1267                                 // fetched to one that can be).
1268                                 //
1269                                 // Instead of enumerating all of the possible errors, we'll just check
1270                                 // whether importFromModules returns nil for the package.
1271                                 // False-positives are ok: if we have a false-positive here, we'll do an
1272                                 // extra iteration of package loading this time, but we'll still
1273                                 // converge when the root set stops changing.
1274                                 //
1275                                 // In some sense, we can think of this as ‘upgraded the module providing
1276                                 // pkg.path from "none" to a version higher than "none"’.
1277                                 if _, _, err = importFromModules(ctx, pkg.path, rs, nil); err == nil {
1278                                         changed = true
1279                                         break
1280                                 }
1281                         }
1282                 }
1283         }
1284
1285         ld.requirements = rs
1286         return changed, nil
1287 }
1288
1289 // resolveMissingImports returns a set of modules that could be added as
1290 // dependencies in order to resolve missing packages from pkgs.
1291 //
1292 // The newly-resolved packages are added to the addedModuleFor map, and
1293 // resolveMissingImports returns a map from each new module version to
1294 // the first missing package that module would resolve.
1295 func (ld *loader) resolveMissingImports(ctx context.Context) (modAddedBy map[module.Version]*loadPkg) {
1296         type pkgMod struct {
1297                 pkg *loadPkg
1298                 mod *module.Version
1299         }
1300         var pkgMods []pkgMod
1301         for _, pkg := range ld.pkgs {
1302                 if pkg.err == nil {
1303                         continue
1304                 }
1305                 if pkg.isTest() {
1306                         // If we are missing a test, we are also missing its non-test version, and
1307                         // we should only add the missing import once.
1308                         continue
1309                 }
1310                 if !errors.As(pkg.err, new(*ImportMissingError)) {
1311                         // Leave other errors for Import or load.Packages to report.
1312                         continue
1313                 }
1314
1315                 pkg := pkg
1316                 var mod module.Version
1317                 ld.work.Add(func() {
1318                         var err error
1319                         mod, err = queryImport(ctx, pkg.path, ld.requirements)
1320                         if err != nil {
1321                                 // pkg.err was already non-nil, so we can reasonably attribute the error
1322                                 // for pkg to either the original error or the one returned by
1323                                 // queryImport. The existing error indicates only that we couldn't find
1324                                 // the package, whereas the query error also explains why we didn't fix
1325                                 // the problem — so we prefer the latter.
1326                                 pkg.err = err
1327                         }
1328
1329                         // err is nil, but we intentionally leave pkg.err non-nil and pkg.mod
1330                         // unset: we still haven't satisfied other invariants of a
1331                         // successfully-loaded package, such as scanning and loading the imports
1332                         // of that package. If we succeed in resolving the new dependency graph,
1333                         // the caller can reload pkg and update the error at that point.
1334                         //
1335                         // Even then, the package might not be loaded from the version we've
1336                         // identified here. The module may be upgraded by some other dependency,
1337                         // or by a transitive dependency of mod itself, or — less likely — the
1338                         // package may be rejected by an AllowPackage hook or rendered ambiguous
1339                         // by some other newly-added or newly-upgraded dependency.
1340                 })
1341
1342                 pkgMods = append(pkgMods, pkgMod{pkg: pkg, mod: &mod})
1343         }
1344         <-ld.work.Idle()
1345
1346         modAddedBy = map[module.Version]*loadPkg{}
1347         for _, pm := range pkgMods {
1348                 pkg, mod := pm.pkg, *pm.mod
1349                 if mod.Path == "" {
1350                         continue
1351                 }
1352
1353                 fmt.Fprintf(os.Stderr, "go: found %s in %s %s\n", pkg.path, mod.Path, mod.Version)
1354                 if modAddedBy[mod] == nil {
1355                         modAddedBy[mod] = pkg
1356                 }
1357         }
1358
1359         return modAddedBy
1360 }
1361
1362 // pkg locates the *loadPkg for path, creating and queuing it for loading if
1363 // needed, and updates its state to reflect the given flags.
1364 //
1365 // The imports of the returned *loadPkg will be loaded asynchronously in the
1366 // ld.work queue, and its test (if requested) will also be populated once
1367 // imports have been resolved. When ld.work goes idle, all transitive imports of
1368 // the requested package (and its test, if requested) will have been loaded.
1369 func (ld *loader) pkg(ctx context.Context, path string, flags loadPkgFlags) *loadPkg {
1370         if flags.has(pkgImportsLoaded) {
1371                 panic("internal error: (*loader).pkg called with pkgImportsLoaded flag set")
1372         }
1373
1374         pkg := ld.pkgCache.Do(path, func() interface{} {
1375                 pkg := &loadPkg{
1376                         path: path,
1377                 }
1378                 ld.applyPkgFlags(ctx, pkg, flags)
1379
1380                 ld.work.Add(func() { ld.load(ctx, pkg) })
1381                 return pkg
1382         }).(*loadPkg)
1383
1384         ld.applyPkgFlags(ctx, pkg, flags)
1385         return pkg
1386 }
1387
1388 // applyPkgFlags updates pkg.flags to set the given flags and propagate the
1389 // (transitive) effects of those flags, possibly loading or enqueueing further
1390 // packages as a result.
1391 func (ld *loader) applyPkgFlags(ctx context.Context, pkg *loadPkg, flags loadPkgFlags) {
1392         if flags == 0 {
1393                 return
1394         }
1395
1396         if flags.has(pkgInAll) && ld.allPatternIsRoot && !pkg.isTest() {
1397                 // This package matches a root pattern by virtue of being in "all".
1398                 flags |= pkgIsRoot
1399         }
1400
1401         old := pkg.flags.update(flags)
1402         new := old | flags
1403         if new == old || !new.has(pkgImportsLoaded) {
1404                 // We either didn't change the state of pkg, or we don't know anything about
1405                 // its dependencies yet. Either way, we can't usefully load its test or
1406                 // update its dependencies.
1407                 return
1408         }
1409
1410         if !pkg.isTest() {
1411                 // Check whether we should add (or update the flags for) a test for pkg.
1412                 // ld.pkgTest is idempotent and extra invocations are inexpensive,
1413                 // so it's ok if we call it more than is strictly necessary.
1414                 wantTest := false
1415                 switch {
1416                 case ld.allPatternIsRoot && pkg.mod == Target:
1417                         // We are loading the "all" pattern, which includes packages imported by
1418                         // tests in the main module. This package is in the main module, so we
1419                         // need to identify the imports of its test even if LoadTests is not set.
1420                         //
1421                         // (We will filter out the extra tests explicitly in computePatternAll.)
1422                         wantTest = true
1423
1424                 case ld.allPatternIsRoot && ld.allClosesOverTests && new.has(pkgInAll):
1425                         // This variant of the "all" pattern includes imports of tests of every
1426                         // package that is itself in "all", and pkg is in "all", so its test is
1427                         // also in "all" (as above).
1428                         wantTest = true
1429
1430                 case ld.LoadTests && new.has(pkgIsRoot):
1431                         // LoadTest explicitly requests tests of “the root packages”.
1432                         wantTest = true
1433                 }
1434
1435                 if wantTest {
1436                         var testFlags loadPkgFlags
1437                         if pkg.mod == Target || (ld.allClosesOverTests && new.has(pkgInAll)) {
1438                                 // Tests of packages in the main module are in "all", in the sense that
1439                                 // they cause the packages they import to also be in "all". So are tests
1440                                 // of packages in "all" if "all" closes over test dependencies.
1441                                 testFlags |= pkgInAll
1442                         }
1443                         ld.pkgTest(ctx, pkg, testFlags)
1444                 }
1445         }
1446
1447         if new.has(pkgInAll) && !old.has(pkgInAll|pkgImportsLoaded) {
1448                 // We have just marked pkg with pkgInAll, or we have just loaded its
1449                 // imports, or both. Now is the time to propagate pkgInAll to the imports.
1450                 for _, dep := range pkg.imports {
1451                         ld.applyPkgFlags(ctx, dep, pkgInAll)
1452                 }
1453         }
1454 }
1455
1456 // preloadRootModules loads the module requirements needed to identify the
1457 // selected version of each module providing a package in rootPkgs,
1458 // adding new root modules to the module graph if needed.
1459 func (ld *loader) preloadRootModules(ctx context.Context, rootPkgs []string) (changedBuildList bool) {
1460         needc := make(chan map[module.Version]bool, 1)
1461         needc <- map[module.Version]bool{}
1462         for _, path := range rootPkgs {
1463                 path := path
1464                 ld.work.Add(func() {
1465                         // First, try to identify the module containing the package using only roots.
1466                         //
1467                         // If the main module is tidy and the package is in "all" — or if we're
1468                         // lucky — we can identify all of its imports without actually loading the
1469                         // full module graph.
1470                         m, _, err := importFromModules(ctx, path, ld.requirements, nil)
1471                         if err != nil {
1472                                 var missing *ImportMissingError
1473                                 if errors.As(err, &missing) && ld.ResolveMissingImports {
1474                                         // This package isn't provided by any selected module.
1475                                         // If we can find it, it will be a new root dependency.
1476                                         m, err = queryImport(ctx, path, ld.requirements)
1477                                 }
1478                                 if err != nil {
1479                                         // We couldn't identify the root module containing this package.
1480                                         // Leave it unresolved; we will report it during loading.
1481                                         return
1482                                 }
1483                         }
1484                         if m.Path == "" {
1485                                 // The package is in std or cmd. We don't need to change the root set.
1486                                 return
1487                         }
1488
1489                         v, ok := ld.requirements.rootSelected(m.Path)
1490                         if !ok || v != m.Version {
1491                                 // We found the requested package in m, but m is not a root, so
1492                                 // loadModGraph will not load its requirements. We need to promote the
1493                                 // module to a root to ensure that any other packages this package
1494                                 // imports are resolved from correct dependency versions.
1495                                 //
1496                                 // (This is the “argument invariant” from the lazy loading design.)
1497                                 need := <-needc
1498                                 need[m] = true
1499                                 needc <- need
1500                         }
1501                 })
1502         }
1503         <-ld.work.Idle()
1504
1505         need := <-needc
1506         if len(need) == 0 {
1507                 return false // No roots to add.
1508         }
1509
1510         toAdd := make([]module.Version, 0, len(need))
1511         for m := range need {
1512                 toAdd = append(toAdd, m)
1513         }
1514         module.Sort(toAdd)
1515
1516         rs, err := updateRoots(ctx, ld.requirements.direct, ld.requirements, nil, toAdd)
1517         if err != nil {
1518                 // We are missing some root dependency, and for some reason we can't load
1519                 // enough of the module dependency graph to add the missing root. Package
1520                 // loading is doomed to fail, so fail quickly.
1521                 ld.errorf("go: %v\n", err)
1522                 base.ExitIfErrors()
1523                 return false
1524         }
1525         if reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1526                 // Something is deeply wrong. resolveMissingImports gave us a non-empty
1527                 // set of modules to add to the graph, but adding those modules had no
1528                 // effect — either they were already in the graph, or updateRoots did not
1529                 // add them as requested.
1530                 panic(fmt.Sprintf("internal error: adding %v to module graph had no effect on root requirements (%v)", toAdd, rs.rootModules))
1531         }
1532
1533         ld.requirements = rs
1534         return true
1535 }
1536
1537 // load loads an individual package.
1538 func (ld *loader) load(ctx context.Context, pkg *loadPkg) {
1539         if strings.Contains(pkg.path, "@") {
1540                 // Leave for error during load.
1541                 return
1542         }
1543         if build.IsLocalImport(pkg.path) || filepath.IsAbs(pkg.path) {
1544                 // Leave for error during load.
1545                 // (Module mode does not allow local imports.)
1546                 return
1547         }
1548
1549         if search.IsMetaPackage(pkg.path) {
1550                 pkg.err = &invalidImportError{
1551                         importPath: pkg.path,
1552                         err:        fmt.Errorf("%q is not an importable package; see 'go help packages'", pkg.path),
1553                 }
1554                 return
1555         }
1556
1557         var mg *ModuleGraph
1558         if ld.requirements.depth == eager {
1559                 var err error
1560                 mg, err = ld.requirements.Graph(ctx)
1561                 if err != nil {
1562                         // We already checked the error from Graph in loadFromRoots and/or
1563                         // updateRequirements, so we ignored the error on purpose and we should
1564                         // keep trying to push past it.
1565                         //
1566                         // However, because mg may be incomplete (and thus may select inaccurate
1567                         // versions), we shouldn't use it to load packages. Instead, we pass a nil
1568                         // *ModuleGraph, which will cause mg to first try loading from only the
1569                         // main module and root dependencies.
1570                         mg = nil
1571                 }
1572         }
1573
1574         pkg.mod, pkg.dir, pkg.err = importFromModules(ctx, pkg.path, ld.requirements, mg)
1575         if pkg.dir == "" {
1576                 return
1577         }
1578         if pkg.mod == Target {
1579                 // Go ahead and mark pkg as in "all". This provides the invariant that a
1580                 // package that is *only* imported by other packages in "all" is always
1581                 // marked as such before loading its imports.
1582                 //
1583                 // We don't actually rely on that invariant at the moment, but it may
1584                 // improve efficiency somewhat and makes the behavior a bit easier to reason
1585                 // about (by reducing churn on the flag bits of dependencies), and costs
1586                 // essentially nothing (these atomic flag ops are essentially free compared
1587                 // to scanning source code for imports).
1588                 ld.applyPkgFlags(ctx, pkg, pkgInAll)
1589         }
1590         if ld.AllowPackage != nil {
1591                 if err := ld.AllowPackage(ctx, pkg.path, pkg.mod); err != nil {
1592                         pkg.err = err
1593                 }
1594         }
1595
1596         pkg.inStd = (search.IsStandardImportPath(pkg.path) && search.InDir(pkg.dir, cfg.GOROOTsrc) != "")
1597
1598         var imports, testImports []string
1599
1600         if cfg.BuildContext.Compiler == "gccgo" && pkg.inStd {
1601                 // We can't scan standard packages for gccgo.
1602         } else {
1603                 var err error
1604                 imports, testImports, err = scanDir(pkg.dir, ld.Tags)
1605                 if err != nil {
1606                         pkg.err = err
1607                         return
1608                 }
1609         }
1610
1611         pkg.imports = make([]*loadPkg, 0, len(imports))
1612         var importFlags loadPkgFlags
1613         if pkg.flags.has(pkgInAll) {
1614                 importFlags = pkgInAll
1615         }
1616         for _, path := range imports {
1617                 if pkg.inStd {
1618                         // Imports from packages in "std" and "cmd" should resolve using
1619                         // GOROOT/src/vendor even when "std" is not the main module.
1620                         path = ld.stdVendor(pkg.path, path)
1621                 }
1622                 pkg.imports = append(pkg.imports, ld.pkg(ctx, path, importFlags))
1623         }
1624         pkg.testImports = testImports
1625
1626         ld.applyPkgFlags(ctx, pkg, pkgImportsLoaded)
1627 }
1628
1629 // pkgTest locates the test of pkg, creating it if needed, and updates its state
1630 // to reflect the given flags.
1631 //
1632 // pkgTest requires that the imports of pkg have already been loaded (flagged
1633 // with pkgImportsLoaded).
1634 func (ld *loader) pkgTest(ctx context.Context, pkg *loadPkg, testFlags loadPkgFlags) *loadPkg {
1635         if pkg.isTest() {
1636                 panic("pkgTest called on a test package")
1637         }
1638
1639         createdTest := false
1640         pkg.testOnce.Do(func() {
1641                 pkg.test = &loadPkg{
1642                         path:   pkg.path,
1643                         testOf: pkg,
1644                         mod:    pkg.mod,
1645                         dir:    pkg.dir,
1646                         err:    pkg.err,
1647                         inStd:  pkg.inStd,
1648                 }
1649                 ld.applyPkgFlags(ctx, pkg.test, testFlags)
1650                 createdTest = true
1651         })
1652
1653         test := pkg.test
1654         if createdTest {
1655                 test.imports = make([]*loadPkg, 0, len(pkg.testImports))
1656                 var importFlags loadPkgFlags
1657                 if test.flags.has(pkgInAll) {
1658                         importFlags = pkgInAll
1659                 }
1660                 for _, path := range pkg.testImports {
1661                         if pkg.inStd {
1662                                 path = ld.stdVendor(test.path, path)
1663                         }
1664                         test.imports = append(test.imports, ld.pkg(ctx, path, importFlags))
1665                 }
1666                 pkg.testImports = nil
1667                 ld.applyPkgFlags(ctx, test, pkgImportsLoaded)
1668         } else {
1669                 ld.applyPkgFlags(ctx, test, testFlags)
1670         }
1671
1672         return test
1673 }
1674
1675 // stdVendor returns the canonical import path for the package with the given
1676 // path when imported from the standard-library package at parentPath.
1677 func (ld *loader) stdVendor(parentPath, path string) string {
1678         if search.IsStandardImportPath(path) {
1679                 return path
1680         }
1681
1682         if str.HasPathPrefix(parentPath, "cmd") {
1683                 if !ld.VendorModulesInGOROOTSrc || Target.Path != "cmd" {
1684                         vendorPath := pathpkg.Join("cmd", "vendor", path)
1685                         if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
1686                                 return vendorPath
1687                         }
1688                 }
1689         } else if !ld.VendorModulesInGOROOTSrc || Target.Path != "std" || str.HasPathPrefix(parentPath, "vendor") {
1690                 // If we are outside of the 'std' module, resolve imports from within 'std'
1691                 // to the vendor directory.
1692                 //
1693                 // Do the same for importers beginning with the prefix 'vendor/' even if we
1694                 // are *inside* of the 'std' module: the 'vendor/' packages that resolve
1695                 // globally from GOROOT/src/vendor (and are listed as part of 'go list std')
1696                 // are distinct from the real module dependencies, and cannot import
1697                 // internal packages from the real module.
1698                 //
1699                 // (Note that although the 'vendor/' packages match the 'std' *package*
1700                 // pattern, they are not part of the std *module*, and do not affect
1701                 // 'go mod tidy' and similar module commands when working within std.)
1702                 vendorPath := pathpkg.Join("vendor", path)
1703                 if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
1704                         return vendorPath
1705                 }
1706         }
1707
1708         // Not vendored: resolve from modules.
1709         return path
1710 }
1711
1712 // computePatternAll returns the list of packages matching pattern "all",
1713 // starting with a list of the import paths for the packages in the main module.
1714 func (ld *loader) computePatternAll() (all []string) {
1715         for _, pkg := range ld.pkgs {
1716                 if pkg.flags.has(pkgInAll) && !pkg.isTest() {
1717                         all = append(all, pkg.path)
1718                 }
1719         }
1720         sort.Strings(all)
1721         return all
1722 }
1723
1724 // checkMultiplePaths verifies that a given module path is used as itself
1725 // or as a replacement for another module, but not both at the same time.
1726 //
1727 // (See https://golang.org/issue/26607 and https://golang.org/issue/34650.)
1728 func (ld *loader) checkMultiplePaths() {
1729         mods := ld.requirements.rootModules
1730         if cached := ld.requirements.graph.Load(); cached != nil {
1731                 if mg := cached.(cachedGraph).mg; mg != nil {
1732                         mods = mg.BuildList()
1733                 }
1734         }
1735
1736         firstPath := map[module.Version]string{}
1737         for _, mod := range mods {
1738                 src := resolveReplacement(mod)
1739                 if prev, ok := firstPath[src]; !ok {
1740                         firstPath[src] = mod.Path
1741                 } else if prev != mod.Path {
1742                         ld.errorf("go: %s@%s used for two different module paths (%s and %s)\n", src.Path, src.Version, prev, mod.Path)
1743                 }
1744         }
1745 }
1746
1747 // scanDir is like imports.ScanDir but elides known magic imports from the list,
1748 // so that we do not go looking for packages that don't really exist.
1749 //
1750 // The standard magic import is "C", for cgo.
1751 //
1752 // The only other known magic imports are appengine and appengine/*.
1753 // These are so old that they predate "go get" and did not use URL-like paths.
1754 // Most code today now uses google.golang.org/appengine instead,
1755 // but not all code has been so updated. When we mostly ignore build tags
1756 // during "go vendor", we look into "// +build appengine" files and
1757 // may see these legacy imports. We drop them so that the module
1758 // search does not look for modules to try to satisfy them.
1759 func scanDir(dir string, tags map[string]bool) (imports_, testImports []string, err error) {
1760         imports_, testImports, err = imports.ScanDir(dir, tags)
1761
1762         filter := func(x []string) []string {
1763                 w := 0
1764                 for _, pkg := range x {
1765                         if pkg != "C" && pkg != "appengine" && !strings.HasPrefix(pkg, "appengine/") &&
1766                                 pkg != "appengine_internal" && !strings.HasPrefix(pkg, "appengine_internal/") {
1767                                 x[w] = pkg
1768                                 w++
1769                         }
1770                 }
1771                 return x[:w]
1772         }
1773
1774         return filter(imports_), filter(testImports), err
1775 }
1776
1777 // buildStacks computes minimal import stacks for each package,
1778 // for use in error messages. When it completes, packages that
1779 // are part of the original root set have pkg.stack == nil,
1780 // and other packages have pkg.stack pointing at the next
1781 // package up the import stack in their minimal chain.
1782 // As a side effect, buildStacks also constructs ld.pkgs,
1783 // the list of all packages loaded.
1784 func (ld *loader) buildStacks() {
1785         if len(ld.pkgs) > 0 {
1786                 panic("buildStacks")
1787         }
1788         for _, pkg := range ld.roots {
1789                 pkg.stack = pkg // sentinel to avoid processing in next loop
1790                 ld.pkgs = append(ld.pkgs, pkg)
1791         }
1792         for i := 0; i < len(ld.pkgs); i++ { // not range: appending to ld.pkgs in loop
1793                 pkg := ld.pkgs[i]
1794                 for _, next := range pkg.imports {
1795                         if next.stack == nil {
1796                                 next.stack = pkg
1797                                 ld.pkgs = append(ld.pkgs, next)
1798                         }
1799                 }
1800                 if next := pkg.test; next != nil && next.stack == nil {
1801                         next.stack = pkg
1802                         ld.pkgs = append(ld.pkgs, next)
1803                 }
1804         }
1805         for _, pkg := range ld.roots {
1806                 pkg.stack = nil
1807         }
1808 }
1809
1810 // stackText builds the import stack text to use when
1811 // reporting an error in pkg. It has the general form
1812 //
1813 //      root imports
1814 //              other imports
1815 //              other2 tested by
1816 //              other2.test imports
1817 //              pkg
1818 //
1819 func (pkg *loadPkg) stackText() string {
1820         var stack []*loadPkg
1821         for p := pkg; p != nil; p = p.stack {
1822                 stack = append(stack, p)
1823         }
1824
1825         var buf bytes.Buffer
1826         for i := len(stack) - 1; i >= 0; i-- {
1827                 p := stack[i]
1828                 fmt.Fprint(&buf, p.path)
1829                 if p.testOf != nil {
1830                         fmt.Fprint(&buf, ".test")
1831                 }
1832                 if i > 0 {
1833                         if stack[i-1].testOf == p {
1834                                 fmt.Fprint(&buf, " tested by\n\t")
1835                         } else {
1836                                 fmt.Fprint(&buf, " imports\n\t")
1837                         }
1838                 }
1839         }
1840         return buf.String()
1841 }
1842
1843 // why returns the text to use in "go mod why" output about the given package.
1844 // It is less ornate than the stackText but contains the same information.
1845 func (pkg *loadPkg) why() string {
1846         var buf strings.Builder
1847         var stack []*loadPkg
1848         for p := pkg; p != nil; p = p.stack {
1849                 stack = append(stack, p)
1850         }
1851
1852         for i := len(stack) - 1; i >= 0; i-- {
1853                 p := stack[i]
1854                 if p.testOf != nil {
1855                         fmt.Fprintf(&buf, "%s.test\n", p.testOf.path)
1856                 } else {
1857                         fmt.Fprintf(&buf, "%s\n", p.path)
1858                 }
1859         }
1860         return buf.String()
1861 }
1862
1863 // Why returns the "go mod why" output stanza for the given package,
1864 // without the leading # comment.
1865 // The package graph must have been loaded already, usually by LoadPackages.
1866 // If there is no reason for the package to be in the current build,
1867 // Why returns an empty string.
1868 func Why(path string) string {
1869         pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
1870         if !ok {
1871                 return ""
1872         }
1873         return pkg.why()
1874 }
1875
1876 // WhyDepth returns the number of steps in the Why listing.
1877 // If there is no reason for the package to be in the current build,
1878 // WhyDepth returns 0.
1879 func WhyDepth(path string) int {
1880         n := 0
1881         pkg, _ := loaded.pkgCache.Get(path).(*loadPkg)
1882         for p := pkg; p != nil; p = p.stack {
1883                 n++
1884         }
1885         return n
1886 }