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