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