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