packages.go 38 KB

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