Source file src/cmd/go/internal/modload/load.go

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

View as plain text