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