packages.go 33 KB

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