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

View as plain text