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

View as plain text