packages.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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. package packages
  5. // See doc.go for package documentation and implementation notes.
  6. import (
  7. "context"
  8. "encoding/json"
  9. "fmt"
  10. "go/ast"
  11. "go/parser"
  12. "go/scanner"
  13. "go/token"
  14. "go/types"
  15. "io"
  16. "log"
  17. "os"
  18. "path/filepath"
  19. "runtime"
  20. "strings"
  21. "sync"
  22. "time"
  23. "golang.org/x/tools/go/gcexportdata"
  24. "golang.org/x/tools/internal/gocommand"
  25. "golang.org/x/tools/internal/packagesinternal"
  26. "golang.org/x/tools/internal/typeparams"
  27. "golang.org/x/tools/internal/typesinternal"
  28. )
  29. // A LoadMode controls the amount of detail to return when loading.
  30. // The bits below can be combined to specify which fields should be
  31. // filled in the result packages.
  32. // The zero value is a special case, equivalent to combining
  33. // the NeedName, NeedFiles, and NeedCompiledGoFiles bits.
  34. // ID and Errors (if present) will always be filled.
  35. // Load may return more information than requested.
  36. type LoadMode int
  37. const (
  38. // NeedName adds Name and PkgPath.
  39. NeedName LoadMode = 1 << iota
  40. // NeedFiles adds GoFiles and OtherFiles.
  41. NeedFiles
  42. // NeedCompiledGoFiles adds CompiledGoFiles.
  43. NeedCompiledGoFiles
  44. // NeedImports adds Imports. If NeedDeps is not set, the Imports field will contain
  45. // "placeholder" Packages with only the ID set.
  46. NeedImports
  47. // NeedDeps adds the fields requested by the LoadMode in the packages in Imports.
  48. NeedDeps
  49. // NeedExportFile adds ExportFile.
  50. NeedExportFile
  51. // NeedTypes adds Types, Fset, and IllTyped.
  52. NeedTypes
  53. // NeedSyntax adds Syntax.
  54. NeedSyntax
  55. // NeedTypesInfo adds TypesInfo.
  56. NeedTypesInfo
  57. // NeedTypesSizes adds TypesSizes.
  58. NeedTypesSizes
  59. // needInternalDepsErrors adds the internal deps errors field for use by gopls.
  60. needInternalDepsErrors
  61. // needInternalForTest adds the internal forTest field.
  62. // Tests must also be set on the context for this field to be populated.
  63. needInternalForTest
  64. // typecheckCgo enables full support for type checking cgo. Requires Go 1.15+.
  65. // Modifies CompiledGoFiles and Types, and has no effect on its own.
  66. typecheckCgo
  67. // NeedModule adds Module.
  68. NeedModule
  69. // NeedEmbedFiles adds EmbedFiles.
  70. NeedEmbedFiles
  71. // NeedEmbedPatterns adds EmbedPatterns.
  72. NeedEmbedPatterns
  73. )
  74. const (
  75. // Deprecated: LoadFiles exists for historical compatibility
  76. // and should not be used. Please directly specify the needed fields using the Need values.
  77. LoadFiles = NeedName | NeedFiles | NeedCompiledGoFiles
  78. // Deprecated: LoadImports exists for historical compatibility
  79. // and should not be used. Please directly specify the needed fields using the Need values.
  80. LoadImports = LoadFiles | NeedImports
  81. // Deprecated: LoadTypes exists for historical compatibility
  82. // and should not be used. Please directly specify the needed fields using the Need values.
  83. LoadTypes = LoadImports | NeedTypes | NeedTypesSizes
  84. // Deprecated: LoadSyntax exists for historical compatibility
  85. // and should not be used. Please directly specify the needed fields using the Need values.
  86. LoadSyntax = LoadTypes | NeedSyntax | NeedTypesInfo
  87. // Deprecated: LoadAllSyntax exists for historical compatibility
  88. // and should not be used. Please directly specify the needed fields using the Need values.
  89. LoadAllSyntax = LoadSyntax | NeedDeps
  90. // Deprecated: NeedExportsFile is a historical misspelling of NeedExportFile.
  91. NeedExportsFile = NeedExportFile
  92. )
  93. // A Config specifies details about how packages should be loaded.
  94. // The zero value is a valid configuration.
  95. // Calls to Load do not modify this struct.
  96. type Config struct {
  97. // Mode controls the level of information returned for each package.
  98. Mode LoadMode
  99. // Context specifies the context for the load operation.
  100. // If the context is cancelled, the loader may stop early
  101. // and return an ErrCancelled error.
  102. // If Context is nil, the load cannot be cancelled.
  103. Context context.Context
  104. // Logf is the logger for the config.
  105. // If the user provides a logger, debug logging is enabled.
  106. // If the GOPACKAGESDEBUG environment variable is set to true,
  107. // but the logger is nil, default to log.Printf.
  108. Logf func(format string, args ...interface{})
  109. // Dir is the directory in which to run the build system's query tool
  110. // that provides information about the packages.
  111. // If Dir is empty, the tool is run in the current directory.
  112. Dir string
  113. // Env is the environment to use when invoking the build system's query tool.
  114. // If Env is nil, the current environment is used.
  115. // As in os/exec's Cmd, only the last value in the slice for
  116. // each environment key is used. To specify the setting of only
  117. // a few variables, append to the current environment, as in:
  118. //
  119. // opt.Env = append(os.Environ(), "GOOS=plan9", "GOARCH=386")
  120. //
  121. Env []string
  122. // gocmdRunner guards go command calls from concurrency errors.
  123. gocmdRunner *gocommand.Runner
  124. // BuildFlags is a list of command-line flags to be passed through to
  125. // the build system's query tool.
  126. BuildFlags []string
  127. // modFile will be used for -modfile in go command invocations.
  128. modFile string
  129. // modFlag will be used for -modfile in go command invocations.
  130. modFlag string
  131. // Fset provides source position information for syntax trees and types.
  132. // If Fset is nil, Load will use a new fileset, but preserve Fset's value.
  133. Fset *token.FileSet
  134. // ParseFile is called to read and parse each file
  135. // when preparing a package's type-checked syntax tree.
  136. // It must be safe to call ParseFile simultaneously from multiple goroutines.
  137. // If ParseFile is nil, the loader will uses parser.ParseFile.
  138. //
  139. // ParseFile should parse the source from src and use filename only for
  140. // recording position information.
  141. //
  142. // An application may supply a custom implementation of ParseFile
  143. // to change the effective file contents or the behavior of the parser,
  144. // or to modify the syntax tree. For example, selectively eliminating
  145. // unwanted function bodies can significantly accelerate type checking.
  146. ParseFile func(fset *token.FileSet, filename string, src []byte) (*ast.File, error)
  147. // If Tests is set, the loader includes not just the packages
  148. // matching a particular pattern but also any related test packages,
  149. // including test-only variants of the package and the test executable.
  150. //
  151. // For example, when using the go command, loading "fmt" with Tests=true
  152. // returns four packages, with IDs "fmt" (the standard package),
  153. // "fmt [fmt.test]" (the package as compiled for the test),
  154. // "fmt_test" (the test functions from source files in package fmt_test),
  155. // and "fmt.test" (the test binary).
  156. //
  157. // In build systems with explicit names for tests,
  158. // setting Tests may have no effect.
  159. Tests bool
  160. // Overlay provides a mapping of absolute file paths to file contents.
  161. // If the file with the given path already exists, the parser will use the
  162. // alternative file contents provided by the map.
  163. //
  164. // Overlays provide incomplete support for when a given file doesn't
  165. // already exist on disk. See the package doc above for more details.
  166. Overlay map[string][]byte
  167. }
  168. // driver is the type for functions that query the build system for the
  169. // packages named by the patterns.
  170. type driver func(cfg *Config, patterns ...string) (*driverResponse, error)
  171. // driverResponse contains the results for a driver query.
  172. type driverResponse struct {
  173. // NotHandled is returned if the request can't be handled by the current
  174. // driver. If an external driver returns a response with NotHandled, the
  175. // rest of the driverResponse is ignored, and go/packages will fallback
  176. // to the next driver. If go/packages is extended in the future to support
  177. // lists of multiple drivers, go/packages will fall back to the next driver.
  178. NotHandled bool
  179. // Compiler and Arch are the arguments pass of types.SizesFor
  180. // to get a types.Sizes to use when type checking.
  181. Compiler string
  182. Arch string
  183. // Roots is the set of package IDs that make up the root packages.
  184. // We have to encode this separately because when we encode a single package
  185. // we cannot know if it is one of the roots as that requires knowledge of the
  186. // graph it is part of.
  187. Roots []string `json:",omitempty"`
  188. // Packages is the full set of packages in the graph.
  189. // The packages are not connected into a graph.
  190. // The Imports if populated will be stubs that only have their ID set.
  191. // Imports will be connected and then type and syntax information added in a
  192. // later pass (see refine).
  193. Packages []*Package
  194. // GoVersion is the minor version number used by the driver
  195. // (e.g. the go command on the PATH) when selecting .go files.
  196. // Zero means unknown.
  197. GoVersion int
  198. }
  199. // Load loads and returns the Go packages named by the given patterns.
  200. //
  201. // Config specifies loading options;
  202. // nil behaves the same as an empty Config.
  203. //
  204. // Load returns an error if any of the patterns was invalid
  205. // as defined by the underlying build system.
  206. // It may return an empty list of packages without an error,
  207. // for instance for an empty expansion of a valid wildcard.
  208. // Errors associated with a particular package are recorded in the
  209. // corresponding Package's Errors list, and do not cause Load to
  210. // return an error. Clients may need to handle such errors before
  211. // proceeding with further analysis. The PrintErrors function is
  212. // provided for convenient display of all errors.
  213. func Load(cfg *Config, patterns ...string) ([]*Package, error) {
  214. l := newLoader(cfg)
  215. response, err := defaultDriver(&l.Config, patterns...)
  216. if err != nil {
  217. return nil, err
  218. }
  219. l.sizes = types.SizesFor(response.Compiler, response.Arch)
  220. return l.refine(response)
  221. }
  222. // defaultDriver is a driver that implements go/packages' fallback behavior.
  223. // It will try to request to an external driver, if one exists. If there's
  224. // no external driver, or the driver returns a response with NotHandled set,
  225. // defaultDriver will fall back to the go list driver.
  226. func defaultDriver(cfg *Config, patterns ...string) (*driverResponse, error) {
  227. driver := findExternalDriver(cfg)
  228. if driver == nil {
  229. driver = goListDriver
  230. }
  231. response, err := driver(cfg, patterns...)
  232. if err != nil {
  233. return response, err
  234. } else if response.NotHandled {
  235. return goListDriver(cfg, patterns...)
  236. }
  237. return response, nil
  238. }
  239. // A Package describes a loaded Go package.
  240. type Package struct {
  241. // ID is a unique identifier for a package,
  242. // in a syntax provided by the underlying build system.
  243. //
  244. // Because the syntax varies based on the build system,
  245. // clients should treat IDs as opaque and not attempt to
  246. // interpret them.
  247. ID string
  248. // Name is the package name as it appears in the package source code.
  249. Name string
  250. // PkgPath is the package path as used by the go/types package.
  251. PkgPath string
  252. // Errors contains any errors encountered querying the metadata
  253. // of the package, or while parsing or type-checking its files.
  254. Errors []Error
  255. // TypeErrors contains the subset of errors produced during type checking.
  256. TypeErrors []types.Error
  257. // GoFiles lists the absolute file paths of the package's Go source files.
  258. // It may include files that should not be compiled, for example because
  259. // they contain non-matching build tags, are documentary pseudo-files such as
  260. // unsafe/unsafe.go or builtin/builtin.go, or are subject to cgo preprocessing.
  261. GoFiles []string
  262. // CompiledGoFiles lists the absolute file paths of the package's source
  263. // files that are suitable for type checking.
  264. // This may differ from GoFiles if files are processed before compilation.
  265. CompiledGoFiles []string
  266. // OtherFiles lists the absolute file paths of the package's non-Go source files,
  267. // including assembly, C, C++, Fortran, Objective-C, SWIG, and so on.
  268. OtherFiles []string
  269. // EmbedFiles lists the absolute file paths of the package's files
  270. // embedded with go:embed.
  271. EmbedFiles []string
  272. // EmbedPatterns lists the absolute file patterns of the package's
  273. // files embedded with go:embed.
  274. EmbedPatterns []string
  275. // IgnoredFiles lists source files that are not part of the package
  276. // using the current build configuration but that might be part of
  277. // the package using other build configurations.
  278. IgnoredFiles []string
  279. // ExportFile is the absolute path to a file containing type
  280. // information for the package as provided by the build system.
  281. ExportFile string
  282. // Imports maps import paths appearing in the package's Go source files
  283. // to corresponding loaded Packages.
  284. Imports map[string]*Package
  285. // Types provides type information for the package.
  286. // The NeedTypes LoadMode bit sets this field for packages matching the
  287. // patterns; type information for dependencies may be missing or incomplete,
  288. // unless NeedDeps and NeedImports are also set.
  289. Types *types.Package
  290. // Fset provides position information for Types, TypesInfo, and Syntax.
  291. // It is set only when Types is set.
  292. Fset *token.FileSet
  293. // IllTyped indicates whether the package or any dependency contains errors.
  294. // It is set only when Types is set.
  295. IllTyped bool
  296. // Syntax is the package's syntax trees, for the files listed in CompiledGoFiles.
  297. //
  298. // The NeedSyntax LoadMode bit populates this field for packages matching the patterns.
  299. // If NeedDeps and NeedImports are also set, this field will also be populated
  300. // for dependencies.
  301. //
  302. // Syntax is kept in the same order as CompiledGoFiles, with the caveat that nils are
  303. // removed. If parsing returned nil, Syntax may be shorter than CompiledGoFiles.
  304. Syntax []*ast.File
  305. // TypesInfo provides type information about the package's syntax trees.
  306. // It is set only when Syntax is set.
  307. TypesInfo *types.Info
  308. // TypesSizes provides the effective size function for types in TypesInfo.
  309. TypesSizes types.Sizes
  310. // forTest is the package under test, if any.
  311. forTest string
  312. // depsErrors is the DepsErrors field from the go list response, if any.
  313. depsErrors []*packagesinternal.PackageError
  314. // module is the module information for the package if it exists.
  315. Module *Module
  316. }
  317. // Module provides module information for a package.
  318. type Module struct {
  319. Path string // module path
  320. Version string // module version
  321. Replace *Module // replaced by this module
  322. Time *time.Time // time version was created
  323. Main bool // is this the main module?
  324. Indirect bool // is this module only an indirect dependency of main module?
  325. Dir string // directory holding files for this module, if any
  326. GoMod string // path to go.mod file used when loading this module, if any
  327. GoVersion string // go version used in module
  328. Error *ModuleError // error loading module
  329. }
  330. // ModuleError holds errors loading a module.
  331. type ModuleError struct {
  332. Err string // the error itself
  333. }
  334. func init() {
  335. packagesinternal.GetForTest = func(p interface{}) string {
  336. return p.(*Package).forTest
  337. }
  338. packagesinternal.GetDepsErrors = func(p interface{}) []*packagesinternal.PackageError {
  339. return p.(*Package).depsErrors
  340. }
  341. packagesinternal.GetGoCmdRunner = func(config interface{}) *gocommand.Runner {
  342. return config.(*Config).gocmdRunner
  343. }
  344. packagesinternal.SetGoCmdRunner = func(config interface{}, runner *gocommand.Runner) {
  345. config.(*Config).gocmdRunner = runner
  346. }
  347. packagesinternal.SetModFile = func(config interface{}, value string) {
  348. config.(*Config).modFile = value
  349. }
  350. packagesinternal.SetModFlag = func(config interface{}, value string) {
  351. config.(*Config).modFlag = value
  352. }
  353. packagesinternal.TypecheckCgo = int(typecheckCgo)
  354. packagesinternal.DepsErrors = int(needInternalDepsErrors)
  355. packagesinternal.ForTest = int(needInternalForTest)
  356. }
  357. // An Error describes a problem with a package's metadata, syntax, or types.
  358. type Error struct {
  359. Pos string // "file:line:col" or "file:line" or "" or "-"
  360. Msg string
  361. Kind ErrorKind
  362. }
  363. // ErrorKind describes the source of the error, allowing the user to
  364. // differentiate between errors generated by the driver, the parser, or the
  365. // type-checker.
  366. type ErrorKind int
  367. const (
  368. UnknownError ErrorKind = iota
  369. ListError
  370. ParseError
  371. TypeError
  372. )
  373. func (err Error) Error() string {
  374. pos := err.Pos
  375. if pos == "" {
  376. pos = "-" // like token.Position{}.String()
  377. }
  378. return pos + ": " + err.Msg
  379. }
  380. // flatPackage is the JSON form of Package
  381. // It drops all the type and syntax fields, and transforms the Imports
  382. //
  383. // TODO(adonovan): identify this struct with Package, effectively
  384. // publishing the JSON protocol.
  385. type flatPackage struct {
  386. ID string
  387. Name string `json:",omitempty"`
  388. PkgPath string `json:",omitempty"`
  389. Errors []Error `json:",omitempty"`
  390. GoFiles []string `json:",omitempty"`
  391. CompiledGoFiles []string `json:",omitempty"`
  392. OtherFiles []string `json:",omitempty"`
  393. EmbedFiles []string `json:",omitempty"`
  394. EmbedPatterns []string `json:",omitempty"`
  395. IgnoredFiles []string `json:",omitempty"`
  396. ExportFile string `json:",omitempty"`
  397. Imports map[string]string `json:",omitempty"`
  398. }
  399. // MarshalJSON returns the Package in its JSON form.
  400. // For the most part, the structure fields are written out unmodified, and
  401. // the type and syntax fields are skipped.
  402. // The imports are written out as just a map of path to package id.
  403. // The errors are written using a custom type that tries to preserve the
  404. // structure of error types we know about.
  405. //
  406. // This method exists to enable support for additional build systems. It is
  407. // not intended for use by clients of the API and we may change the format.
  408. func (p *Package) MarshalJSON() ([]byte, error) {
  409. flat := &flatPackage{
  410. ID: p.ID,
  411. Name: p.Name,
  412. PkgPath: p.PkgPath,
  413. Errors: p.Errors,
  414. GoFiles: p.GoFiles,
  415. CompiledGoFiles: p.CompiledGoFiles,
  416. OtherFiles: p.OtherFiles,
  417. EmbedFiles: p.EmbedFiles,
  418. EmbedPatterns: p.EmbedPatterns,
  419. IgnoredFiles: p.IgnoredFiles,
  420. ExportFile: p.ExportFile,
  421. }
  422. if len(p.Imports) > 0 {
  423. flat.Imports = make(map[string]string, len(p.Imports))
  424. for path, ipkg := range p.Imports {
  425. flat.Imports[path] = ipkg.ID
  426. }
  427. }
  428. return json.Marshal(flat)
  429. }
  430. // UnmarshalJSON reads in a Package from its JSON format.
  431. // See MarshalJSON for details about the format accepted.
  432. func (p *Package) UnmarshalJSON(b []byte) error {
  433. flat := &flatPackage{}
  434. if err := json.Unmarshal(b, &flat); err != nil {
  435. return err
  436. }
  437. *p = Package{
  438. ID: flat.ID,
  439. Name: flat.Name,
  440. PkgPath: flat.PkgPath,
  441. Errors: flat.Errors,
  442. GoFiles: flat.GoFiles,
  443. CompiledGoFiles: flat.CompiledGoFiles,
  444. OtherFiles: flat.OtherFiles,
  445. EmbedFiles: flat.EmbedFiles,
  446. EmbedPatterns: flat.EmbedPatterns,
  447. ExportFile: flat.ExportFile,
  448. }
  449. if len(flat.Imports) > 0 {
  450. p.Imports = make(map[string]*Package, len(flat.Imports))
  451. for path, id := range flat.Imports {
  452. p.Imports[path] = &Package{ID: id}
  453. }
  454. }
  455. return nil
  456. }
  457. func (p *Package) String() string { return p.ID }
  458. // loaderPackage augments Package with state used during the loading phase
  459. type loaderPackage struct {
  460. *Package
  461. importErrors map[string]error // maps each bad import to its error
  462. loadOnce sync.Once
  463. color uint8 // for cycle detection
  464. needsrc bool // load from source (Mode >= LoadTypes)
  465. needtypes bool // type information is either requested or depended on
  466. initial bool // package was matched by a pattern
  467. goVersion int // minor version number of go command on PATH
  468. }
  469. // loader holds the working state of a single call to load.
  470. type loader struct {
  471. pkgs map[string]*loaderPackage
  472. Config
  473. sizes types.Sizes
  474. parseCache map[string]*parseValue
  475. parseCacheMu sync.Mutex
  476. exportMu sync.Mutex // enforces mutual exclusion of exportdata operations
  477. // Config.Mode contains the implied mode (see impliedLoadMode).
  478. // Implied mode contains all the fields we need the data for.
  479. // In requestedMode there are the actually requested fields.
  480. // We'll zero them out before returning packages to the user.
  481. // This makes it easier for us to get the conditions where
  482. // we need certain modes right.
  483. requestedMode LoadMode
  484. }
  485. type parseValue struct {
  486. f *ast.File
  487. err error
  488. ready chan struct{}
  489. }
  490. func newLoader(cfg *Config) *loader {
  491. ld := &loader{
  492. parseCache: map[string]*parseValue{},
  493. }
  494. if cfg != nil {
  495. ld.Config = *cfg
  496. // If the user has provided a logger, use it.
  497. ld.Config.Logf = cfg.Logf
  498. }
  499. if ld.Config.Logf == nil {
  500. // If the GOPACKAGESDEBUG environment variable is set to true,
  501. // but the user has not provided a logger, default to log.Printf.
  502. if debug {
  503. ld.Config.Logf = log.Printf
  504. } else {
  505. ld.Config.Logf = func(format string, args ...interface{}) {}
  506. }
  507. }
  508. if ld.Config.Mode == 0 {
  509. ld.Config.Mode = NeedName | NeedFiles | NeedCompiledGoFiles // Preserve zero behavior of Mode for backwards compatibility.
  510. }
  511. if ld.Config.Env == nil {
  512. ld.Config.Env = os.Environ()
  513. }
  514. if ld.Config.gocmdRunner == nil {
  515. ld.Config.gocmdRunner = &gocommand.Runner{}
  516. }
  517. if ld.Context == nil {
  518. ld.Context = context.Background()
  519. }
  520. if ld.Dir == "" {
  521. if dir, err := os.Getwd(); err == nil {
  522. ld.Dir = dir
  523. }
  524. }
  525. // Save the actually requested fields. We'll zero them out before returning packages to the user.
  526. ld.requestedMode = ld.Mode
  527. ld.Mode = impliedLoadMode(ld.Mode)
  528. if ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 {
  529. if ld.Fset == nil {
  530. ld.Fset = token.NewFileSet()
  531. }
  532. // ParseFile is required even in LoadTypes mode
  533. // because we load source if export data is missing.
  534. if ld.ParseFile == nil {
  535. ld.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
  536. const mode = parser.AllErrors | parser.ParseComments
  537. return parser.ParseFile(fset, filename, src, mode)
  538. }
  539. }
  540. }
  541. return ld
  542. }
  543. // refine connects the supplied packages into a graph and then adds type
  544. // and syntax information as requested by the LoadMode.
  545. func (ld *loader) refine(response *driverResponse) ([]*Package, error) {
  546. roots := response.Roots
  547. rootMap := make(map[string]int, len(roots))
  548. for i, root := range roots {
  549. rootMap[root] = i
  550. }
  551. ld.pkgs = make(map[string]*loaderPackage)
  552. // first pass, fixup and build the map and roots
  553. var initial = make([]*loaderPackage, len(roots))
  554. for _, pkg := range response.Packages {
  555. rootIndex := -1
  556. if i, found := rootMap[pkg.ID]; found {
  557. rootIndex = i
  558. }
  559. // Overlays can invalidate export data.
  560. // TODO(matloob): make this check fine-grained based on dependencies on overlaid files
  561. exportDataInvalid := len(ld.Overlay) > 0 || pkg.ExportFile == "" && pkg.PkgPath != "unsafe"
  562. // This package needs type information if the caller requested types and the package is
  563. // either a root, or it's a non-root and the user requested dependencies ...
  564. needtypes := (ld.Mode&NeedTypes|NeedTypesInfo != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0))
  565. // This package needs source if the call requested source (or types info, which implies source)
  566. // and the package is either a root, or itas a non- root and the user requested dependencies...
  567. needsrc := ((ld.Mode&(NeedSyntax|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) ||
  568. // ... or if we need types and the exportData is invalid. We fall back to (incompletely)
  569. // typechecking packages from source if they fail to compile.
  570. (ld.Mode&(NeedTypes|NeedTypesInfo) != 0 && exportDataInvalid)) && pkg.PkgPath != "unsafe"
  571. lpkg := &loaderPackage{
  572. Package: pkg,
  573. needtypes: needtypes,
  574. needsrc: needsrc,
  575. goVersion: response.GoVersion,
  576. }
  577. ld.pkgs[lpkg.ID] = lpkg
  578. if rootIndex >= 0 {
  579. initial[rootIndex] = lpkg
  580. lpkg.initial = true
  581. }
  582. }
  583. for i, root := range roots {
  584. if initial[i] == nil {
  585. return nil, fmt.Errorf("root package %v is missing", root)
  586. }
  587. }
  588. // Materialize the import graph.
  589. const (
  590. white = 0 // new
  591. grey = 1 // in progress
  592. black = 2 // complete
  593. )
  594. // visit traverses the import graph, depth-first,
  595. // and materializes the graph as Packages.Imports.
  596. //
  597. // Valid imports are saved in the Packages.Import map.
  598. // Invalid imports (cycles and missing nodes) are saved in the importErrors map.
  599. // Thus, even in the presence of both kinds of errors, the Import graph remains a DAG.
  600. //
  601. // visit returns whether the package needs src or has a transitive
  602. // dependency on a package that does. These are the only packages
  603. // for which we load source code.
  604. var stack []*loaderPackage
  605. var visit func(lpkg *loaderPackage) bool
  606. var srcPkgs []*loaderPackage
  607. visit = func(lpkg *loaderPackage) bool {
  608. switch lpkg.color {
  609. case black:
  610. return lpkg.needsrc
  611. case grey:
  612. panic("internal error: grey node")
  613. }
  614. lpkg.color = grey
  615. stack = append(stack, lpkg) // push
  616. stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports
  617. // If NeedImports isn't set, the imports fields will all be zeroed out.
  618. if ld.Mode&NeedImports != 0 {
  619. lpkg.Imports = make(map[string]*Package, len(stubs))
  620. for importPath, ipkg := range stubs {
  621. var importErr error
  622. imp := ld.pkgs[ipkg.ID]
  623. if imp == nil {
  624. // (includes package "C" when DisableCgo)
  625. importErr = fmt.Errorf("missing package: %q", ipkg.ID)
  626. } else if imp.color == grey {
  627. importErr = fmt.Errorf("import cycle: %s", stack)
  628. }
  629. if importErr != nil {
  630. if lpkg.importErrors == nil {
  631. lpkg.importErrors = make(map[string]error)
  632. }
  633. lpkg.importErrors[importPath] = importErr
  634. continue
  635. }
  636. if visit(imp) {
  637. lpkg.needsrc = true
  638. }
  639. lpkg.Imports[importPath] = imp.Package
  640. }
  641. }
  642. if lpkg.needsrc {
  643. srcPkgs = append(srcPkgs, lpkg)
  644. }
  645. if ld.Mode&NeedTypesSizes != 0 {
  646. lpkg.TypesSizes = ld.sizes
  647. }
  648. stack = stack[:len(stack)-1] // pop
  649. lpkg.color = black
  650. return lpkg.needsrc
  651. }
  652. if ld.Mode&NeedImports == 0 {
  653. // We do this to drop the stub import packages that we are not even going to try to resolve.
  654. for _, lpkg := range initial {
  655. lpkg.Imports = nil
  656. }
  657. } else {
  658. // For each initial package, create its import DAG.
  659. for _, lpkg := range initial {
  660. visit(lpkg)
  661. }
  662. }
  663. if ld.Mode&NeedImports != 0 && ld.Mode&NeedTypes != 0 {
  664. for _, lpkg := range srcPkgs {
  665. // Complete type information is required for the
  666. // immediate dependencies of each source package.
  667. for _, ipkg := range lpkg.Imports {
  668. imp := ld.pkgs[ipkg.ID]
  669. imp.needtypes = true
  670. }
  671. }
  672. }
  673. // Load type data and syntax if needed, starting at
  674. // the initial packages (roots of the import DAG).
  675. if ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 {
  676. var wg sync.WaitGroup
  677. for _, lpkg := range initial {
  678. wg.Add(1)
  679. go func(lpkg *loaderPackage) {
  680. ld.loadRecursive(lpkg)
  681. wg.Done()
  682. }(lpkg)
  683. }
  684. wg.Wait()
  685. }
  686. result := make([]*Package, len(initial))
  687. for i, lpkg := range initial {
  688. result[i] = lpkg.Package
  689. }
  690. for i := range ld.pkgs {
  691. // Clear all unrequested fields,
  692. // to catch programs that use more than they request.
  693. if ld.requestedMode&NeedName == 0 {
  694. ld.pkgs[i].Name = ""
  695. ld.pkgs[i].PkgPath = ""
  696. }
  697. if ld.requestedMode&NeedFiles == 0 {
  698. ld.pkgs[i].GoFiles = nil
  699. ld.pkgs[i].OtherFiles = nil
  700. ld.pkgs[i].IgnoredFiles = nil
  701. }
  702. if ld.requestedMode&NeedEmbedFiles == 0 {
  703. ld.pkgs[i].EmbedFiles = nil
  704. }
  705. if ld.requestedMode&NeedEmbedPatterns == 0 {
  706. ld.pkgs[i].EmbedPatterns = nil
  707. }
  708. if ld.requestedMode&NeedCompiledGoFiles == 0 {
  709. ld.pkgs[i].CompiledGoFiles = nil
  710. }
  711. if ld.requestedMode&NeedImports == 0 {
  712. ld.pkgs[i].Imports = nil
  713. }
  714. if ld.requestedMode&NeedExportFile == 0 {
  715. ld.pkgs[i].ExportFile = ""
  716. }
  717. if ld.requestedMode&NeedTypes == 0 {
  718. ld.pkgs[i].Types = nil
  719. ld.pkgs[i].Fset = nil
  720. ld.pkgs[i].IllTyped = false
  721. }
  722. if ld.requestedMode&NeedSyntax == 0 {
  723. ld.pkgs[i].Syntax = nil
  724. }
  725. if ld.requestedMode&NeedTypesInfo == 0 {
  726. ld.pkgs[i].TypesInfo = nil
  727. }
  728. if ld.requestedMode&NeedTypesSizes == 0 {
  729. ld.pkgs[i].TypesSizes = nil
  730. }
  731. if ld.requestedMode&NeedModule == 0 {
  732. ld.pkgs[i].Module = nil
  733. }
  734. }
  735. return result, nil
  736. }
  737. // loadRecursive loads the specified package and its dependencies,
  738. // recursively, in parallel, in topological order.
  739. // It is atomic and idempotent.
  740. // Precondition: ld.Mode&NeedTypes.
  741. func (ld *loader) loadRecursive(lpkg *loaderPackage) {
  742. lpkg.loadOnce.Do(func() {
  743. // Load the direct dependencies, in parallel.
  744. var wg sync.WaitGroup
  745. for _, ipkg := range lpkg.Imports {
  746. imp := ld.pkgs[ipkg.ID]
  747. wg.Add(1)
  748. go func(imp *loaderPackage) {
  749. ld.loadRecursive(imp)
  750. wg.Done()
  751. }(imp)
  752. }
  753. wg.Wait()
  754. ld.loadPackage(lpkg)
  755. })
  756. }
  757. // loadPackage loads the specified package.
  758. // It must be called only once per Package,
  759. // after immediate dependencies are loaded.
  760. // Precondition: ld.Mode & NeedTypes.
  761. func (ld *loader) loadPackage(lpkg *loaderPackage) {
  762. if lpkg.PkgPath == "unsafe" {
  763. // Fill in the blanks to avoid surprises.
  764. lpkg.Types = types.Unsafe
  765. lpkg.Fset = ld.Fset
  766. lpkg.Syntax = []*ast.File{}
  767. lpkg.TypesInfo = new(types.Info)
  768. lpkg.TypesSizes = ld.sizes
  769. return
  770. }
  771. // Call NewPackage directly with explicit name.
  772. // This avoids skew between golist and go/types when the files'
  773. // package declarations are inconsistent.
  774. lpkg.Types = types.NewPackage(lpkg.PkgPath, lpkg.Name)
  775. lpkg.Fset = ld.Fset
  776. // Subtle: we populate all Types fields with an empty Package
  777. // before loading export data so that export data processing
  778. // never has to create a types.Package for an indirect dependency,
  779. // which would then require that such created packages be explicitly
  780. // inserted back into the Import graph as a final step after export data loading.
  781. // (Hence this return is after the Types assignment.)
  782. // The Diamond test exercises this case.
  783. if !lpkg.needtypes && !lpkg.needsrc {
  784. return
  785. }
  786. if !lpkg.needsrc {
  787. if err := ld.loadFromExportData(lpkg); err != nil {
  788. lpkg.Errors = append(lpkg.Errors, Error{
  789. Pos: "-",
  790. Msg: err.Error(),
  791. Kind: UnknownError, // e.g. can't find/open/parse export data
  792. })
  793. }
  794. return // not a source package, don't get syntax trees
  795. }
  796. appendError := func(err error) {
  797. // Convert various error types into the one true Error.
  798. var errs []Error
  799. switch err := err.(type) {
  800. case Error:
  801. // from driver
  802. errs = append(errs, err)
  803. case *os.PathError:
  804. // from parser
  805. errs = append(errs, Error{
  806. Pos: err.Path + ":1",
  807. Msg: err.Err.Error(),
  808. Kind: ParseError,
  809. })
  810. case scanner.ErrorList:
  811. // from parser
  812. for _, err := range err {
  813. errs = append(errs, Error{
  814. Pos: err.Pos.String(),
  815. Msg: err.Msg,
  816. Kind: ParseError,
  817. })
  818. }
  819. case types.Error:
  820. // from type checker
  821. lpkg.TypeErrors = append(lpkg.TypeErrors, err)
  822. errs = append(errs, Error{
  823. Pos: err.Fset.Position(err.Pos).String(),
  824. Msg: err.Msg,
  825. Kind: TypeError,
  826. })
  827. default:
  828. // unexpected impoverished error from parser?
  829. errs = append(errs, Error{
  830. Pos: "-",
  831. Msg: err.Error(),
  832. Kind: UnknownError,
  833. })
  834. // If you see this error message, please file a bug.
  835. log.Printf("internal error: error %q (%T) without position", err, err)
  836. }
  837. lpkg.Errors = append(lpkg.Errors, errs...)
  838. }
  839. // If the go command on the PATH is newer than the runtime,
  840. // then the go/{scanner,ast,parser,types} packages from the
  841. // standard library may be unable to process the files
  842. // selected by go list.
  843. //
  844. // There is currently no way to downgrade the effective
  845. // version of the go command (see issue 52078), so we proceed
  846. // with the newer go command but, in case of parse or type
  847. // errors, we emit an additional diagnostic.
  848. //
  849. // See:
  850. // - golang.org/issue/52078 (flag to set release tags)
  851. // - golang.org/issue/50825 (gopls legacy version support)
  852. // - golang.org/issue/55883 (go/packages confusing error)
  853. //
  854. // Should we assert a hard minimum of (currently) go1.16 here?
  855. var runtimeVersion int
  856. if _, err := fmt.Sscanf(runtime.Version(), "go1.%d", &runtimeVersion); err == nil && runtimeVersion < lpkg.goVersion {
  857. defer func() {
  858. if len(lpkg.Errors) > 0 {
  859. appendError(Error{
  860. Pos: "-",
  861. Msg: fmt.Sprintf("This application uses version go1.%d of the source-processing packages but runs version go1.%d of 'go list'. It may fail to process source files that rely on newer language features. If so, rebuild the application using a newer version of Go.", runtimeVersion, lpkg.goVersion),
  862. Kind: UnknownError,
  863. })
  864. }
  865. }()
  866. }
  867. if ld.Config.Mode&NeedTypes != 0 && len(lpkg.CompiledGoFiles) == 0 && lpkg.ExportFile != "" {
  868. // The config requested loading sources and types, but sources are missing.
  869. // Add an error to the package and fall back to loading from export data.
  870. appendError(Error{"-", fmt.Sprintf("sources missing for package %s", lpkg.ID), ParseError})
  871. _ = ld.loadFromExportData(lpkg) // ignore any secondary errors
  872. return // can't get syntax trees for this package
  873. }
  874. files, errs := ld.parseFiles(lpkg.CompiledGoFiles)
  875. for _, err := range errs {
  876. appendError(err)
  877. }
  878. lpkg.Syntax = files
  879. if ld.Config.Mode&NeedTypes == 0 {
  880. return
  881. }
  882. lpkg.TypesInfo = &types.Info{
  883. Types: make(map[ast.Expr]types.TypeAndValue),
  884. Defs: make(map[*ast.Ident]types.Object),
  885. Uses: make(map[*ast.Ident]types.Object),
  886. Implicits: make(map[ast.Node]types.Object),
  887. Scopes: make(map[ast.Node]*types.Scope),
  888. Selections: make(map[*ast.SelectorExpr]*types.Selection),
  889. }
  890. typeparams.InitInstanceInfo(lpkg.TypesInfo)
  891. lpkg.TypesSizes = ld.sizes
  892. importer := importerFunc(func(path string) (*types.Package, error) {
  893. if path == "unsafe" {
  894. return types.Unsafe, nil
  895. }
  896. // The imports map is keyed by import path.
  897. ipkg := lpkg.Imports[path]
  898. if ipkg == nil {
  899. if err := lpkg.importErrors[path]; err != nil {
  900. return nil, err
  901. }
  902. // There was skew between the metadata and the
  903. // import declarations, likely due to an edit
  904. // race, or because the ParseFile feature was
  905. // used to supply alternative file contents.
  906. return nil, fmt.Errorf("no metadata for %s", path)
  907. }
  908. if ipkg.Types != nil && ipkg.Types.Complete() {
  909. return ipkg.Types, nil
  910. }
  911. log.Fatalf("internal error: package %q without types was imported from %q", path, lpkg)
  912. panic("unreachable")
  913. })
  914. // type-check
  915. tc := &types.Config{
  916. Importer: importer,
  917. // Type-check bodies of functions only in initial packages.
  918. // Example: for import graph A->B->C and initial packages {A,C},
  919. // we can ignore function bodies in B.
  920. IgnoreFuncBodies: ld.Mode&NeedDeps == 0 && !lpkg.initial,
  921. Error: appendError,
  922. Sizes: ld.sizes,
  923. }
  924. if lpkg.Module != nil && lpkg.Module.GoVersion != "" {
  925. typesinternal.SetGoVersion(tc, "go"+lpkg.Module.GoVersion)
  926. }
  927. if (ld.Mode & typecheckCgo) != 0 {
  928. if !typesinternal.SetUsesCgo(tc) {
  929. appendError(Error{
  930. Msg: "typecheckCgo requires Go 1.15+",
  931. Kind: ListError,
  932. })
  933. return
  934. }
  935. }
  936. types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax)
  937. lpkg.importErrors = nil // no longer needed
  938. // If !Cgo, the type-checker uses FakeImportC mode, so
  939. // it doesn't invoke the importer for import "C",
  940. // nor report an error for the import,
  941. // or for any undefined C.f reference.
  942. // We must detect this explicitly and correctly
  943. // mark the package as IllTyped (by reporting an error).
  944. // TODO(adonovan): if these errors are annoying,
  945. // we could just set IllTyped quietly.
  946. if tc.FakeImportC {
  947. outer:
  948. for _, f := range lpkg.Syntax {
  949. for _, imp := range f.Imports {
  950. if imp.Path.Value == `"C"` {
  951. err := types.Error{Fset: ld.Fset, Pos: imp.Pos(), Msg: `import "C" ignored`}
  952. appendError(err)
  953. break outer
  954. }
  955. }
  956. }
  957. }
  958. // Record accumulated errors.
  959. illTyped := len(lpkg.Errors) > 0
  960. if !illTyped {
  961. for _, imp := range lpkg.Imports {
  962. if imp.IllTyped {
  963. illTyped = true
  964. break
  965. }
  966. }
  967. }
  968. lpkg.IllTyped = illTyped
  969. }
  970. // An importFunc is an implementation of the single-method
  971. // types.Importer interface based on a function value.
  972. type importerFunc func(path string) (*types.Package, error)
  973. func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
  974. // We use a counting semaphore to limit
  975. // the number of parallel I/O calls per process.
  976. var ioLimit = make(chan bool, 20)
  977. func (ld *loader) parseFile(filename string) (*ast.File, error) {
  978. ld.parseCacheMu.Lock()
  979. v, ok := ld.parseCache[filename]
  980. if ok {
  981. // cache hit
  982. ld.parseCacheMu.Unlock()
  983. <-v.ready
  984. } else {
  985. // cache miss
  986. v = &parseValue{ready: make(chan struct{})}
  987. ld.parseCache[filename] = v
  988. ld.parseCacheMu.Unlock()
  989. var src []byte
  990. for f, contents := range ld.Config.Overlay {
  991. if sameFile(f, filename) {
  992. src = contents
  993. }
  994. }
  995. var err error
  996. if src == nil {
  997. ioLimit <- true // wait
  998. src, err = os.ReadFile(filename)
  999. <-ioLimit // signal
  1000. }
  1001. if err != nil {
  1002. v.err = err
  1003. } else {
  1004. v.f, v.err = ld.ParseFile(ld.Fset, filename, src)
  1005. }
  1006. close(v.ready)
  1007. }
  1008. return v.f, v.err
  1009. }
  1010. // parseFiles reads and parses the Go source files and returns the ASTs
  1011. // of the ones that could be at least partially parsed, along with a
  1012. // list of I/O and parse errors encountered.
  1013. //
  1014. // Because files are scanned in parallel, the token.Pos
  1015. // positions of the resulting ast.Files are not ordered.
  1016. func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) {
  1017. var wg sync.WaitGroup
  1018. n := len(filenames)
  1019. parsed := make([]*ast.File, n)
  1020. errors := make([]error, n)
  1021. for i, file := range filenames {
  1022. if ld.Config.Context.Err() != nil {
  1023. parsed[i] = nil
  1024. errors[i] = ld.Config.Context.Err()
  1025. continue
  1026. }
  1027. wg.Add(1)
  1028. go func(i int, filename string) {
  1029. parsed[i], errors[i] = ld.parseFile(filename)
  1030. wg.Done()
  1031. }(i, file)
  1032. }
  1033. wg.Wait()
  1034. // Eliminate nils, preserving order.
  1035. var o int
  1036. for _, f := range parsed {
  1037. if f != nil {
  1038. parsed[o] = f
  1039. o++
  1040. }
  1041. }
  1042. parsed = parsed[:o]
  1043. o = 0
  1044. for _, err := range errors {
  1045. if err != nil {
  1046. errors[o] = err
  1047. o++
  1048. }
  1049. }
  1050. errors = errors[:o]
  1051. return parsed, errors
  1052. }
  1053. // sameFile returns true if x and y have the same basename and denote
  1054. // the same file.
  1055. func sameFile(x, y string) bool {
  1056. if x == y {
  1057. // It could be the case that y doesn't exist.
  1058. // For instance, it may be an overlay file that
  1059. // hasn't been written to disk. To handle that case
  1060. // let x == y through. (We added the exact absolute path
  1061. // string to the CompiledGoFiles list, so the unwritten
  1062. // overlay case implies x==y.)
  1063. return true
  1064. }
  1065. if strings.EqualFold(filepath.Base(x), filepath.Base(y)) { // (optimisation)
  1066. if xi, err := os.Stat(x); err == nil {
  1067. if yi, err := os.Stat(y); err == nil {
  1068. return os.SameFile(xi, yi)
  1069. }
  1070. }
  1071. }
  1072. return false
  1073. }
  1074. // loadFromExportData ensures that type information is present for the specified
  1075. // package, loading it from an export data file on the first request.
  1076. // On success it sets lpkg.Types to a new Package.
  1077. func (ld *loader) loadFromExportData(lpkg *loaderPackage) error {
  1078. if lpkg.PkgPath == "" {
  1079. log.Fatalf("internal error: Package %s has no PkgPath", lpkg)
  1080. }
  1081. // Because gcexportdata.Read has the potential to create or
  1082. // modify the types.Package for each node in the transitive
  1083. // closure of dependencies of lpkg, all exportdata operations
  1084. // must be sequential. (Finer-grained locking would require
  1085. // changes to the gcexportdata API.)
  1086. //
  1087. // The exportMu lock guards the lpkg.Types field and the
  1088. // types.Package it points to, for each loaderPackage in the graph.
  1089. //
  1090. // Not all accesses to Package.Pkg need to be protected by exportMu:
  1091. // graph ordering ensures that direct dependencies of source
  1092. // packages are fully loaded before the importer reads their Pkg field.
  1093. ld.exportMu.Lock()
  1094. defer ld.exportMu.Unlock()
  1095. if tpkg := lpkg.Types; tpkg != nil && tpkg.Complete() {
  1096. return nil // cache hit
  1097. }
  1098. lpkg.IllTyped = true // fail safe
  1099. if lpkg.ExportFile == "" {
  1100. // Errors while building export data will have been printed to stderr.
  1101. return fmt.Errorf("no export data file")
  1102. }
  1103. f, err := os.Open(lpkg.ExportFile)
  1104. if err != nil {
  1105. return err
  1106. }
  1107. defer f.Close()
  1108. // Read gc export data.
  1109. //
  1110. // We don't currently support gccgo export data because all
  1111. // underlying workspaces use the gc toolchain. (Even build
  1112. // systems that support gccgo don't use it for workspace
  1113. // queries.)
  1114. r, err := gcexportdata.NewReader(f)
  1115. if err != nil {
  1116. return fmt.Errorf("reading %s: %v", lpkg.ExportFile, err)
  1117. }
  1118. // Build the view.
  1119. //
  1120. // The gcexportdata machinery has no concept of package ID.
  1121. // It identifies packages by their PkgPath, which although not
  1122. // globally unique is unique within the scope of one invocation
  1123. // of the linker, type-checker, or gcexportdata.
  1124. //
  1125. // So, we must build a PkgPath-keyed view of the global
  1126. // (conceptually ID-keyed) cache of packages and pass it to
  1127. // gcexportdata. The view must contain every existing
  1128. // package that might possibly be mentioned by the
  1129. // current package---its transitive closure.
  1130. //
  1131. // In loadPackage, we unconditionally create a types.Package for
  1132. // each dependency so that export data loading does not
  1133. // create new ones.
  1134. //
  1135. // TODO(adonovan): it would be simpler and more efficient
  1136. // if the export data machinery invoked a callback to
  1137. // get-or-create a package instead of a map.
  1138. //
  1139. view := make(map[string]*types.Package) // view seen by gcexportdata
  1140. seen := make(map[*loaderPackage]bool) // all visited packages
  1141. var visit func(pkgs map[string]*Package)
  1142. visit = func(pkgs map[string]*Package) {
  1143. for _, p := range pkgs {
  1144. lpkg := ld.pkgs[p.ID]
  1145. if !seen[lpkg] {
  1146. seen[lpkg] = true
  1147. view[lpkg.PkgPath] = lpkg.Types
  1148. visit(lpkg.Imports)
  1149. }
  1150. }
  1151. }
  1152. visit(lpkg.Imports)
  1153. viewLen := len(view) + 1 // adding the self package
  1154. // Parse the export data.
  1155. // (May modify incomplete packages in view but not create new ones.)
  1156. tpkg, err := gcexportdata.Read(r, ld.Fset, view, lpkg.PkgPath)
  1157. if err != nil {
  1158. return fmt.Errorf("reading %s: %v", lpkg.ExportFile, err)
  1159. }
  1160. if _, ok := view["go.shape"]; ok {
  1161. // Account for the pseudopackage "go.shape" that gets
  1162. // created by generic code.
  1163. viewLen++
  1164. }
  1165. if viewLen != len(view) {
  1166. log.Panicf("golang.org/x/tools/go/packages: unexpected new packages during load of %s", lpkg.PkgPath)
  1167. }
  1168. lpkg.Types = tpkg
  1169. lpkg.IllTyped = false
  1170. return nil
  1171. }
  1172. // impliedLoadMode returns loadMode with its dependencies.
  1173. func impliedLoadMode(loadMode LoadMode) LoadMode {
  1174. if loadMode&(NeedDeps|NeedTypes|NeedTypesInfo) != 0 {
  1175. // All these things require knowing the import graph.
  1176. loadMode |= NeedImports
  1177. }
  1178. return loadMode
  1179. }
  1180. func usesExportData(cfg *Config) bool {
  1181. return cfg.Mode&NeedExportFile != 0 || cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedDeps == 0
  1182. }
  1183. var _ interface{} = io.Discard // assert build toolchain is go1.16 or later