github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/cmd/go/internal/load/pkg.go (about)

     1  // Copyright 2011 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 load loads packages.
     6  package load
     7  
     8  import (
     9  	"github.com/shogo82148/std/context"
    10  	"github.com/shogo82148/std/go/build"
    11  	"github.com/shogo82148/std/go/token"
    12  
    13  	"github.com/shogo82148/std/runtime/debug"
    14  
    15  	"github.com/shogo82148/std/cmd/go/internal/modinfo"
    16  	"github.com/shogo82148/std/cmd/go/internal/modload"
    17  )
    18  
    19  // A Package describes a single package found in a directory.
    20  type Package struct {
    21  	PackagePublic
    22  	Internal PackageInternal
    23  }
    24  
    25  type PackagePublic struct {
    26  	// Note: These fields are part of the go command's public API.
    27  	// See list.go. It is okay to add fields, but not to change or
    28  	// remove existing ones. Keep in sync with ../list/list.go
    29  	Dir           string                `json:",omitempty"`
    30  	ImportPath    string                `json:",omitempty"`
    31  	ImportComment string                `json:",omitempty"`
    32  	Name          string                `json:",omitempty"`
    33  	Doc           string                `json:",omitempty"`
    34  	Target        string                `json:",omitempty"`
    35  	Shlib         string                `json:",omitempty"`
    36  	Root          string                `json:",omitempty"`
    37  	ConflictDir   string                `json:",omitempty"`
    38  	ForTest       string                `json:",omitempty"`
    39  	Export        string                `json:",omitempty"`
    40  	BuildID       string                `json:",omitempty"`
    41  	Module        *modinfo.ModulePublic `json:",omitempty"`
    42  	Match         []string              `json:",omitempty"`
    43  	Goroot        bool                  `json:",omitempty"`
    44  	Standard      bool                  `json:",omitempty"`
    45  	DepOnly       bool                  `json:",omitempty"`
    46  	BinaryOnly    bool                  `json:",omitempty"`
    47  	Incomplete    bool                  `json:",omitempty"`
    48  
    49  	DefaultGODEBUG string `json:",omitempty"`
    50  
    51  	// Stale and StaleReason remain here *only* for the list command.
    52  	// They are only initialized in preparation for list execution.
    53  	// The regular build determines staleness on the fly during action execution.
    54  	Stale       bool   `json:",omitempty"`
    55  	StaleReason string `json:",omitempty"`
    56  
    57  	// Source files
    58  	// If you add to this list you MUST add to p.AllFiles (below) too.
    59  	// Otherwise file name security lists will not apply to any new additions.
    60  	GoFiles           []string `json:",omitempty"`
    61  	CgoFiles          []string `json:",omitempty"`
    62  	CompiledGoFiles   []string `json:",omitempty"`
    63  	IgnoredGoFiles    []string `json:",omitempty"`
    64  	InvalidGoFiles    []string `json:",omitempty"`
    65  	IgnoredOtherFiles []string `json:",omitempty"`
    66  	CFiles            []string `json:",omitempty"`
    67  	CXXFiles          []string `json:",omitempty"`
    68  	MFiles            []string `json:",omitempty"`
    69  	HFiles            []string `json:",omitempty"`
    70  	FFiles            []string `json:",omitempty"`
    71  	SFiles            []string `json:",omitempty"`
    72  	SwigFiles         []string `json:",omitempty"`
    73  	SwigCXXFiles      []string `json:",omitempty"`
    74  	SysoFiles         []string `json:",omitempty"`
    75  
    76  	// Embedded files
    77  	EmbedPatterns []string `json:",omitempty"`
    78  	EmbedFiles    []string `json:",omitempty"`
    79  
    80  	// Cgo directives
    81  	CgoCFLAGS    []string `json:",omitempty"`
    82  	CgoCPPFLAGS  []string `json:",omitempty"`
    83  	CgoCXXFLAGS  []string `json:",omitempty"`
    84  	CgoFFLAGS    []string `json:",omitempty"`
    85  	CgoLDFLAGS   []string `json:",omitempty"`
    86  	CgoPkgConfig []string `json:",omitempty"`
    87  
    88  	// Dependency information
    89  	Imports   []string          `json:",omitempty"`
    90  	ImportMap map[string]string `json:",omitempty"`
    91  	Deps      []string          `json:",omitempty"`
    92  
    93  	// Error information
    94  	// Incomplete is above, packed into the other bools
    95  	Error      *PackageError   `json:",omitempty"`
    96  	DepsErrors []*PackageError `json:",omitempty"`
    97  
    98  	// Test information
    99  	// If you add to this list you MUST add to p.AllFiles (below) too.
   100  	// Otherwise file name security lists will not apply to any new additions.
   101  	TestGoFiles        []string `json:",omitempty"`
   102  	TestImports        []string `json:",omitempty"`
   103  	TestEmbedPatterns  []string `json:",omitempty"`
   104  	TestEmbedFiles     []string `json:",omitempty"`
   105  	XTestGoFiles       []string `json:",omitempty"`
   106  	XTestImports       []string `json:",omitempty"`
   107  	XTestEmbedPatterns []string `json:",omitempty"`
   108  	XTestEmbedFiles    []string `json:",omitempty"`
   109  }
   110  
   111  // AllFiles returns the names of all the files considered for the package.
   112  // This is used for sanity and security checks, so we include all files,
   113  // even IgnoredGoFiles, because some subcommands consider them.
   114  // The go/build package filtered others out (like foo_wrongGOARCH.s)
   115  // and that's OK.
   116  func (p *Package) AllFiles() []string
   117  
   118  // Desc returns the package "description", for use in b.showOutput.
   119  func (p *Package) Desc() string
   120  
   121  // IsTestOnly reports whether p is a test-only package.
   122  //
   123  // A “test-only” package is one that:
   124  //   - is a test-only variant of an ordinary package, or
   125  //   - is a synthesized "main" package for a test binary, or
   126  //   - contains only _test.go files.
   127  func (p *Package) IsTestOnly() bool
   128  
   129  type PackageInternal struct {
   130  	// Unexported fields are not part of the public API.
   131  	Build             *build.Package
   132  	Imports           []*Package
   133  	CompiledImports   []string
   134  	RawImports        []string
   135  	ForceLibrary      bool
   136  	CmdlineFiles      bool
   137  	CmdlinePkg        bool
   138  	CmdlinePkgLiteral bool
   139  	Local             bool
   140  	LocalPrefix       string
   141  	ExeName           string
   142  	FuzzInstrument    bool
   143  	Cover             CoverSetup
   144  	CoverVars         map[string]*CoverVar
   145  	OmitDebug         bool
   146  	GobinSubdir       bool
   147  	BuildInfo         *debug.BuildInfo
   148  	TestmainGo        *[]byte
   149  	Embed             map[string][]string
   150  	OrigImportPath    string
   151  	PGOProfile        string
   152  	ForMain           string
   153  
   154  	Asmflags   []string
   155  	Gcflags    []string
   156  	Ldflags    []string
   157  	Gccgoflags []string
   158  }
   159  
   160  // A NoGoError indicates that no Go files for the package were applicable to the
   161  // build for that package.
   162  //
   163  // That may be because there were no files whatsoever, or because all files were
   164  // excluded, or because all non-excluded files were test sources.
   165  type NoGoError struct {
   166  	Package *Package
   167  }
   168  
   169  func (e *NoGoError) Error() string
   170  
   171  // Resolve returns the resolved version of imports,
   172  // which should be p.TestImports or p.XTestImports, NOT p.Imports.
   173  // The imports in p.TestImports and p.XTestImports are not recursively
   174  // loaded during the initial load of p, so they list the imports found in
   175  // the source file, but most processing should be over the vendor-resolved
   176  // import paths. We do this resolution lazily both to avoid file system work
   177  // and because the eventual real load of the test imports (during 'go test')
   178  // can produce better error messages if it starts with the original paths.
   179  // The initial load of p loads all the non-test imports and rewrites
   180  // the vendored paths, so nothing should ever call p.vendored(p.Imports).
   181  func (p *Package) Resolve(imports []string) []string
   182  
   183  // CoverVar holds the name of the generated coverage variables targeting the named file.
   184  type CoverVar struct {
   185  	File string
   186  	Var  string
   187  }
   188  
   189  // CoverSetup holds parameters related to coverage setup for a given package (covermode, etc).
   190  type CoverSetup struct {
   191  	Mode    string
   192  	Cfg     string
   193  	GenMeta bool
   194  }
   195  
   196  // A PackageError describes an error loading information about a package.
   197  type PackageError struct {
   198  	ImportStack      []string
   199  	Pos              string
   200  	Err              error
   201  	IsImportCycle    bool
   202  	Hard             bool
   203  	alwaysPrintStack bool
   204  }
   205  
   206  func (p *PackageError) Error() string
   207  
   208  func (p *PackageError) Unwrap() error
   209  
   210  // PackageError implements MarshalJSON so that Err is marshaled as a string
   211  // and non-essential fields are omitted.
   212  func (p *PackageError) MarshalJSON() ([]byte, error)
   213  
   214  // ImportPathError is a type of error that prevents a package from being loaded
   215  // for a given import path. When such a package is loaded, a *Package is
   216  // returned with Err wrapping an ImportPathError: the error is attached to
   217  // the imported package, not the importing package.
   218  //
   219  // The string returned by ImportPath must appear in the string returned by
   220  // Error. Errors that wrap ImportPathError (such as PackageError) may omit
   221  // the import path.
   222  type ImportPathError interface {
   223  	error
   224  	ImportPath() string
   225  }
   226  
   227  var (
   228  	_ ImportPathError = (*importError)(nil)
   229  	_ ImportPathError = (*mainPackageError)(nil)
   230  	_ ImportPathError = (*modload.ImportMissingError)(nil)
   231  	_ ImportPathError = (*modload.ImportMissingSumError)(nil)
   232  	_ ImportPathError = (*modload.DirectImportFromImplicitDependencyError)(nil)
   233  )
   234  
   235  func ImportErrorf(path, format string, args ...any) ImportPathError
   236  
   237  // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
   238  // The import path of a test package is the import path of the corresponding
   239  // non-test package with the suffix "_test" added.
   240  type ImportStack []string
   241  
   242  func (s *ImportStack) Push(p string)
   243  
   244  func (s *ImportStack) Pop()
   245  
   246  func (s *ImportStack) Copy() []string
   247  
   248  func (s *ImportStack) Top() string
   249  
   250  // ClearPackageCache clears the in-memory package cache and the preload caches.
   251  // It is only for use by GOPATH-based "go get".
   252  // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
   253  func ClearPackageCache()
   254  
   255  // ClearPackageCachePartial clears packages with the given import paths from the
   256  // in-memory package cache and the preload caches. It is only for use by
   257  // GOPATH-based "go get".
   258  // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
   259  func ClearPackageCachePartial(args []string)
   260  
   261  // ReloadPackageNoFlags is like LoadImport but makes sure
   262  // not to use the package cache.
   263  // It is only for use by GOPATH-based "go get".
   264  // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
   265  func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package
   266  
   267  // Mode flags for loadImport and download (in get.go).
   268  const (
   269  	// ResolveImport means that loadImport should do import path expansion.
   270  	// That is, ResolveImport means that the import path came from
   271  	// a source file and has not been expanded yet to account for
   272  	// vendoring or possible module adjustment.
   273  	// Every import path should be loaded initially with ResolveImport,
   274  	// and then the expanded version (for example with the /vendor/ in it)
   275  	// gets recorded as the canonical import path. At that point, future loads
   276  	// of that package must not pass ResolveImport, because
   277  	// disallowVendor will reject direct use of paths containing /vendor/.
   278  	ResolveImport = 1 << iota
   279  
   280  	// ResolveModule is for download (part of "go get") and indicates
   281  	// that the module adjustment should be done, but not vendor adjustment.
   282  	ResolveModule
   283  
   284  	// GetTestDeps is for download (part of "go get") and indicates
   285  	// that test dependencies should be fetched too.
   286  	GetTestDeps
   287  )
   288  
   289  // LoadImport scans the directory named by path, which must be an import path,
   290  // but possibly a local import path (an absolute file system path or one beginning
   291  // with ./ or ../). A local relative path is interpreted relative to srcDir.
   292  // It returns a *Package describing the package found in that directory.
   293  // LoadImport does not set tool flags and should only be used by
   294  // this package, as part of a bigger load operation, and by GOPATH-based "go get".
   295  // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
   296  // The returned PackageError, if any, describes why parent is not allowed
   297  // to import the named package, with the error referring to importPos.
   298  // The PackageError can only be non-nil when parent is not nil.
   299  func LoadImport(ctx context.Context, opts PackageOpts, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError)
   300  
   301  // LoadPackage does Load import, but without a parent package load contezt
   302  func LoadPackage(ctx context.Context, opts PackageOpts, path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package
   303  
   304  // ResolveImportPath returns the true meaning of path when it appears in parent.
   305  // There are two different resolutions applied.
   306  // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
   307  // If vendor expansion doesn't trigger, then the path is also subject to
   308  // Go 1.11 module legacy conversion (golang.org/issue/25069).
   309  func ResolveImportPath(parent *Package, path string) (found string)
   310  
   311  // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
   312  // If there isn't one, FindVendor returns ok=false.
   313  // Otherwise, FindVendor returns ok=true and the index of the "vendor".
   314  //
   315  // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
   316  // not the vendored copy of an import "" (the empty import path).
   317  // This will allow people to have packages or commands named vendor.
   318  // This may help reduce breakage, or it may just be confusing. We'll see.
   319  func FindVendor(path string) (index int, ok bool)
   320  
   321  type TargetDir int
   322  
   323  const (
   324  	ToTool TargetDir = iota
   325  	ToBin
   326  	StalePath
   327  )
   328  
   329  // InstallTargetDir reports the target directory for installing the command p.
   330  func InstallTargetDir(p *Package) TargetDir
   331  
   332  // DefaultExecName returns the default executable name for a package
   333  func (p *Package) DefaultExecName() string
   334  
   335  // An EmbedError indicates a problem with a go:embed directive.
   336  type EmbedError struct {
   337  	Pattern string
   338  	Err     error
   339  }
   340  
   341  func (e *EmbedError) Error() string
   342  
   343  func (e *EmbedError) Unwrap() error
   344  
   345  // ResolveEmbed resolves //go:embed patterns and returns only the file list.
   346  // For use by go mod vendor to find embedded files it should copy into the
   347  // vendor directory.
   348  // TODO(#42504): Once go mod vendor uses load.PackagesAndErrors, just
   349  // call (*Package).ResolveEmbed
   350  func ResolveEmbed(dir string, patterns []string) ([]string, error)
   351  
   352  // SafeArg reports whether arg is a "safe" command-line argument,
   353  // meaning that when it appears in a command-line, it probably
   354  // doesn't have some special meaning other than its own name.
   355  // Obviously args beginning with - are not safe (they look like flags).
   356  // Less obviously, args beginning with @ are not safe (they look like
   357  // GNU binutils flagfile specifiers, sometimes called "response files").
   358  // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
   359  // We accept leading . _ and / as likely in file system paths.
   360  // There is a copy of this function in cmd/compile/internal/gc/noder.go.
   361  func SafeArg(name string) bool
   362  
   363  // LinkerDeps returns the list of linker-induced dependencies for main package p.
   364  func LinkerDeps(p *Package) ([]string, error)
   365  
   366  // InternalGoFiles returns the list of Go files being built for the package,
   367  // using absolute paths.
   368  func (p *Package) InternalGoFiles() []string
   369  
   370  // InternalXGoFiles returns the list of Go files being built for the XTest package,
   371  // using absolute paths.
   372  func (p *Package) InternalXGoFiles() []string
   373  
   374  // InternalAllGoFiles returns the list of all Go files possibly relevant for the package,
   375  // using absolute paths. "Possibly relevant" means that files are not excluded
   376  // due to build tags, but files with names beginning with . or _ are still excluded.
   377  func (p *Package) InternalAllGoFiles() []string
   378  
   379  // UsesSwig reports whether the package needs to run SWIG.
   380  func (p *Package) UsesSwig() bool
   381  
   382  // UsesCgo reports whether the package needs to run cgo
   383  func (p *Package) UsesCgo() bool
   384  
   385  // PackageList returns the list of packages in the dag rooted at roots
   386  // as visited in a depth-first post-order traversal.
   387  func PackageList(roots []*Package) []*Package
   388  
   389  // TestPackageList returns the list of packages in the dag rooted at roots
   390  // as visited in a depth-first post-order traversal, including the test
   391  // imports of the roots. This ignores errors in test packages.
   392  func TestPackageList(ctx context.Context, opts PackageOpts, roots []*Package) []*Package
   393  
   394  // LoadImportWithFlags loads the package with the given import path and
   395  // sets tool flags on that package. This function is useful loading implicit
   396  // dependencies (like sync/atomic for coverage).
   397  // TODO(jayconrod): delete this function and set flags automatically
   398  // in LoadImport instead.
   399  func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError)
   400  
   401  // LoadPackageWithFlags is the same as LoadImportWithFlags but without a parent.
   402  // It's then guaranteed to not return an error
   403  func LoadPackageWithFlags(path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package
   404  
   405  // PackageOpts control the behavior of PackagesAndErrors and other package
   406  // loading functions.
   407  type PackageOpts struct {
   408  	// IgnoreImports controls whether we ignore explicit and implicit imports
   409  	// when loading packages.  Implicit imports are added when supporting Cgo
   410  	// or SWIG and when linking main packages.
   411  	IgnoreImports bool
   412  
   413  	// ModResolveTests indicates whether calls to the module loader should also
   414  	// resolve test dependencies of the requested packages.
   415  	//
   416  	// If ModResolveTests is true, then the module loader needs to resolve test
   417  	// dependencies at the same time as packages; otherwise, the test dependencies
   418  	// of those packages could be missing, and resolving those missing dependencies
   419  	// could change the selected versions of modules that provide other packages.
   420  	ModResolveTests bool
   421  
   422  	// MainOnly is true if the caller only wants to load main packages.
   423  	// For a literal argument matching a non-main package, a stub may be returned
   424  	// with an error. For a non-literal argument (with "..."), non-main packages
   425  	// are not be matched, and their dependencies may not be loaded. A warning
   426  	// may be printed for non-literal arguments that match no main packages.
   427  	MainOnly bool
   428  
   429  	// AutoVCS controls whether we also load version-control metadata for main packages
   430  	// when -buildvcs=auto (the default).
   431  	AutoVCS bool
   432  
   433  	// SuppressBuildInfo is true if the caller does not need p.Stale, p.StaleReason, or p.Internal.BuildInfo
   434  	// to be populated on the package.
   435  	SuppressBuildInfo bool
   436  
   437  	// SuppressEmbedFiles is true if the caller does not need any embed files to be populated on the
   438  	// package.
   439  	SuppressEmbedFiles bool
   440  }
   441  
   442  // PackagesAndErrors returns the packages named by the command line arguments
   443  // 'patterns'. If a named package cannot be loaded, PackagesAndErrors returns
   444  // a *Package with the Error field describing the failure. If errors are found
   445  // loading imported packages, the DepsErrors field is set. The Incomplete field
   446  // may be set as well.
   447  //
   448  // To obtain a flat list of packages, use PackageList.
   449  // To report errors loading packages, use ReportPackageErrors.
   450  func PackagesAndErrors(ctx context.Context, opts PackageOpts, patterns []string) []*Package
   451  
   452  // CheckPackageErrors prints errors encountered loading pkgs and their
   453  // dependencies, then exits with a non-zero status if any errors were found.
   454  func CheckPackageErrors(pkgs []*Package)
   455  
   456  // GoFilesPackage creates a package for building a collection of Go files
   457  // (typically named on the command line). The target is named p.a for
   458  // package p or named after the first Go file for package main.
   459  func GoFilesPackage(ctx context.Context, opts PackageOpts, gofiles []string) *Package
   460  
   461  // PackagesAndErrorsOutsideModule is like PackagesAndErrors but runs in
   462  // module-aware mode and ignores the go.mod file in the current directory or any
   463  // parent directory, if there is one. This is used in the implementation of 'go
   464  // install pkg@version' and other commands that support similar forms.
   465  //
   466  // modload.ForceUseModules must be true, and modload.RootMode must be NoRoot
   467  // before calling this function.
   468  //
   469  // PackagesAndErrorsOutsideModule imposes several constraints to avoid
   470  // ambiguity. All arguments must have the same version suffix (not just a suffix
   471  // that resolves to the same version). They must refer to packages in the same
   472  // module, which must not be std or cmd. That module is not considered the main
   473  // module, but its go.mod file (if it has one) must not contain directives that
   474  // would cause it to be interpreted differently if it were the main module
   475  // (replace, exclude).
   476  func PackagesAndErrorsOutsideModule(ctx context.Context, opts PackageOpts, args []string) ([]*Package, error)
   477  
   478  // EnsureImport ensures that package p imports the named package.
   479  func EnsureImport(p *Package, pkg string)
   480  
   481  // PrepareForCoverageBuild is a helper invoked for "go install
   482  // -cover", "go run -cover", and "go build -cover" (but not used by
   483  // "go test -cover"). It walks through the packages being built (and
   484  // dependencies) and marks them for coverage instrumentation when
   485  // appropriate, and possibly adding additional deps where needed.
   486  func PrepareForCoverageBuild(pkgs []*Package)
   487  
   488  func SelectCoverPackages(roots []*Package, match []func(*Package) bool, op string) []*Package
   489  
   490  // DeclareCoverVars attaches the required cover variables names
   491  // to the files, to be used when annotating the files. This
   492  // function only called when using legacy coverage test/build
   493  // (e.g. GOEXPERIMENT=coverageredesign is off).
   494  func DeclareCoverVars(p *Package, files ...string) map[string]*CoverVar