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