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

View as plain text