本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1101 lines
33KB

  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 && ld.Mode&NeedDeps != 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 NeedTypesInfo we need dependencies (at least for the roots) to typecheck the package.
  478. // If NeedImports isn't set, the imports fields will all be zeroed out.
  479. // If NeedDeps isn't also set we want to keep the stubs.
  480. if ld.Mode&NeedTypesInfo != 0 || (ld.Mode&NeedImports != 0 && ld.Mode&NeedDeps != 0) {
  481. lpkg.Imports = make(map[string]*Package, len(stubs))
  482. for importPath, ipkg := range stubs {
  483. var importErr error
  484. imp := ld.pkgs[ipkg.ID]
  485. if imp == nil {
  486. // (includes package "C" when DisableCgo)
  487. importErr = fmt.Errorf("missing package: %q", ipkg.ID)
  488. } else if imp.color == grey {
  489. importErr = fmt.Errorf("import cycle: %s", stack)
  490. }
  491. if importErr != nil {
  492. if lpkg.importErrors == nil {
  493. lpkg.importErrors = make(map[string]error)
  494. }
  495. lpkg.importErrors[importPath] = importErr
  496. continue
  497. }
  498. // If !NeedDeps, just fill Imports for the root. No need to recurse further.
  499. if ld.Mode&NeedDeps != 0 {
  500. if visit(imp) {
  501. lpkg.needsrc = true
  502. }
  503. }
  504. lpkg.Imports[importPath] = imp.Package
  505. }
  506. }
  507. if lpkg.needsrc {
  508. srcPkgs = append(srcPkgs, lpkg)
  509. }
  510. if ld.Mode&NeedTypesSizes != 0 {
  511. lpkg.TypesSizes = ld.sizes
  512. }
  513. stack = stack[:len(stack)-1] // pop
  514. lpkg.color = black
  515. return lpkg.needsrc
  516. }
  517. if ld.Mode&(NeedImports|NeedDeps|NeedTypesInfo) == 0 {
  518. // We do this to drop the stub import packages that we are not even going to try to resolve.
  519. for _, lpkg := range initial {
  520. lpkg.Imports = nil
  521. }
  522. } else {
  523. // For each initial package, create its import DAG.
  524. for _, lpkg := range initial {
  525. visit(lpkg)
  526. }
  527. }
  528. if ld.Mode&NeedDeps != 0 { // TODO(matloob): This is only the case if NeedTypes is also set, right?
  529. for _, lpkg := range srcPkgs {
  530. // Complete type information is required for the
  531. // immediate dependencies of each source package.
  532. for _, ipkg := range lpkg.Imports {
  533. imp := ld.pkgs[ipkg.ID]
  534. imp.needtypes = true
  535. }
  536. }
  537. }
  538. // Load type data if needed, starting at
  539. // the initial packages (roots of the import DAG).
  540. if ld.Mode&NeedTypes != 0 {
  541. var wg sync.WaitGroup
  542. for _, lpkg := range initial {
  543. wg.Add(1)
  544. go func(lpkg *loaderPackage) {
  545. ld.loadRecursive(lpkg)
  546. wg.Done()
  547. }(lpkg)
  548. }
  549. wg.Wait()
  550. }
  551. result := make([]*Package, len(initial))
  552. importPlaceholders := make(map[string]*Package)
  553. for i, lpkg := range initial {
  554. result[i] = lpkg.Package
  555. }
  556. for i := range ld.pkgs {
  557. // Clear all unrequested fields, for extra de-Hyrum-ization.
  558. if ld.Mode&NeedName == 0 {
  559. ld.pkgs[i].Name = ""
  560. ld.pkgs[i].PkgPath = ""
  561. }
  562. if ld.Mode&NeedFiles == 0 {
  563. ld.pkgs[i].GoFiles = nil
  564. ld.pkgs[i].OtherFiles = nil
  565. }
  566. if ld.Mode&NeedCompiledGoFiles == 0 {
  567. ld.pkgs[i].CompiledGoFiles = nil
  568. }
  569. if ld.Mode&NeedImports == 0 {
  570. ld.pkgs[i].Imports = nil
  571. }
  572. if ld.Mode&NeedExportsFile == 0 {
  573. ld.pkgs[i].ExportFile = ""
  574. }
  575. if ld.Mode&NeedTypes == 0 {
  576. ld.pkgs[i].Types = nil
  577. ld.pkgs[i].Fset = nil
  578. ld.pkgs[i].IllTyped = false
  579. }
  580. if ld.Mode&NeedSyntax == 0 {
  581. ld.pkgs[i].Syntax = nil
  582. }
  583. if ld.Mode&NeedTypesInfo == 0 {
  584. ld.pkgs[i].TypesInfo = nil
  585. }
  586. if ld.Mode&NeedTypesSizes == 0 {
  587. ld.pkgs[i].TypesSizes = nil
  588. }
  589. if ld.Mode&NeedDeps == 0 {
  590. for j, pkg := range ld.pkgs[i].Imports {
  591. ph, ok := importPlaceholders[pkg.ID]
  592. if !ok {
  593. ph = &Package{ID: pkg.ID}
  594. importPlaceholders[pkg.ID] = ph
  595. }
  596. ld.pkgs[i].Imports[j] = ph
  597. }
  598. }
  599. }
  600. return result, nil
  601. }
  602. // loadRecursive loads the specified package and its dependencies,
  603. // recursively, in parallel, in topological order.
  604. // It is atomic and idempotent.
  605. // Precondition: ld.Mode&NeedTypes.
  606. func (ld *loader) loadRecursive(lpkg *loaderPackage) {
  607. lpkg.loadOnce.Do(func() {
  608. // Load the direct dependencies, in parallel.
  609. var wg sync.WaitGroup
  610. for _, ipkg := range lpkg.Imports {
  611. imp := ld.pkgs[ipkg.ID]
  612. wg.Add(1)
  613. go func(imp *loaderPackage) {
  614. ld.loadRecursive(imp)
  615. wg.Done()
  616. }(imp)
  617. }
  618. wg.Wait()
  619. ld.loadPackage(lpkg)
  620. })
  621. }
  622. // loadPackage loads the specified package.
  623. // It must be called only once per Package,
  624. // after immediate dependencies are loaded.
  625. // Precondition: ld.Mode & NeedTypes.
  626. func (ld *loader) loadPackage(lpkg *loaderPackage) {
  627. if lpkg.PkgPath == "unsafe" {
  628. // Fill in the blanks to avoid surprises.
  629. lpkg.Types = types.Unsafe
  630. lpkg.Fset = ld.Fset
  631. lpkg.Syntax = []*ast.File{}
  632. lpkg.TypesInfo = new(types.Info)
  633. lpkg.TypesSizes = ld.sizes
  634. return
  635. }
  636. // Call NewPackage directly with explicit name.
  637. // This avoids skew between golist and go/types when the files'
  638. // package declarations are inconsistent.
  639. lpkg.Types = types.NewPackage(lpkg.PkgPath, lpkg.Name)
  640. lpkg.Fset = ld.Fset
  641. // Subtle: we populate all Types fields with an empty Package
  642. // before loading export data so that export data processing
  643. // never has to create a types.Package for an indirect dependency,
  644. // which would then require that such created packages be explicitly
  645. // inserted back into the Import graph as a final step after export data loading.
  646. // The Diamond test exercises this case.
  647. if !lpkg.needtypes {
  648. return
  649. }
  650. if !lpkg.needsrc {
  651. ld.loadFromExportData(lpkg)
  652. return // not a source package, don't get syntax trees
  653. }
  654. appendError := func(err error) {
  655. // Convert various error types into the one true Error.
  656. var errs []Error
  657. switch err := err.(type) {
  658. case Error:
  659. // from driver
  660. errs = append(errs, err)
  661. case *os.PathError:
  662. // from parser
  663. errs = append(errs, Error{
  664. Pos: err.Path + ":1",
  665. Msg: err.Err.Error(),
  666. Kind: ParseError,
  667. })
  668. case scanner.ErrorList:
  669. // from parser
  670. for _, err := range err {
  671. errs = append(errs, Error{
  672. Pos: err.Pos.String(),
  673. Msg: err.Msg,
  674. Kind: ParseError,
  675. })
  676. }
  677. case types.Error:
  678. // from type checker
  679. errs = append(errs, Error{
  680. Pos: err.Fset.Position(err.Pos).String(),
  681. Msg: err.Msg,
  682. Kind: TypeError,
  683. })
  684. default:
  685. // unexpected impoverished error from parser?
  686. errs = append(errs, Error{
  687. Pos: "-",
  688. Msg: err.Error(),
  689. Kind: UnknownError,
  690. })
  691. // If you see this error message, please file a bug.
  692. log.Printf("internal error: error %q (%T) without position", err, err)
  693. }
  694. lpkg.Errors = append(lpkg.Errors, errs...)
  695. }
  696. files, errs := ld.parseFiles(lpkg.CompiledGoFiles)
  697. for _, err := range errs {
  698. appendError(err)
  699. }
  700. lpkg.Syntax = files
  701. lpkg.TypesInfo = &types.Info{
  702. Types: make(map[ast.Expr]types.TypeAndValue),
  703. Defs: make(map[*ast.Ident]types.Object),
  704. Uses: make(map[*ast.Ident]types.Object),
  705. Implicits: make(map[ast.Node]types.Object),
  706. Scopes: make(map[ast.Node]*types.Scope),
  707. Selections: make(map[*ast.SelectorExpr]*types.Selection),
  708. }
  709. lpkg.TypesSizes = ld.sizes
  710. importer := importerFunc(func(path string) (*types.Package, error) {
  711. if path == "unsafe" {
  712. return types.Unsafe, nil
  713. }
  714. // The imports map is keyed by import path.
  715. ipkg := lpkg.Imports[path]
  716. if ipkg == nil {
  717. if err := lpkg.importErrors[path]; err != nil {
  718. return nil, err
  719. }
  720. // There was skew between the metadata and the
  721. // import declarations, likely due to an edit
  722. // race, or because the ParseFile feature was
  723. // used to supply alternative file contents.
  724. return nil, fmt.Errorf("no metadata for %s", path)
  725. }
  726. if ipkg.Types != nil && ipkg.Types.Complete() {
  727. return ipkg.Types, nil
  728. }
  729. log.Fatalf("internal error: nil Pkg importing %q from %q", path, lpkg)
  730. panic("unreachable")
  731. })
  732. // type-check
  733. tc := &types.Config{
  734. Importer: importer,
  735. // Type-check bodies of functions only in non-initial packages.
  736. // Example: for import graph A->B->C and initial packages {A,C},
  737. // we can ignore function bodies in B.
  738. IgnoreFuncBodies: (ld.Mode&(NeedDeps|NeedTypesInfo) == 0) && !lpkg.initial,
  739. Error: appendError,
  740. Sizes: ld.sizes,
  741. }
  742. types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax)
  743. lpkg.importErrors = nil // no longer needed
  744. // If !Cgo, the type-checker uses FakeImportC mode, so
  745. // it doesn't invoke the importer for import "C",
  746. // nor report an error for the import,
  747. // or for any undefined C.f reference.
  748. // We must detect this explicitly and correctly
  749. // mark the package as IllTyped (by reporting an error).
  750. // TODO(adonovan): if these errors are annoying,
  751. // we could just set IllTyped quietly.
  752. if tc.FakeImportC {
  753. outer:
  754. for _, f := range lpkg.Syntax {
  755. for _, imp := range f.Imports {
  756. if imp.Path.Value == `"C"` {
  757. err := types.Error{Fset: ld.Fset, Pos: imp.Pos(), Msg: `import "C" ignored`}
  758. appendError(err)
  759. break outer
  760. }
  761. }
  762. }
  763. }
  764. // Record accumulated errors.
  765. illTyped := len(lpkg.Errors) > 0
  766. if !illTyped {
  767. for _, imp := range lpkg.Imports {
  768. if imp.IllTyped {
  769. illTyped = true
  770. break
  771. }
  772. }
  773. }
  774. lpkg.IllTyped = illTyped
  775. }
  776. // An importFunc is an implementation of the single-method
  777. // types.Importer interface based on a function value.
  778. type importerFunc func(path string) (*types.Package, error)
  779. func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
  780. // We use a counting semaphore to limit
  781. // the number of parallel I/O calls per process.
  782. var ioLimit = make(chan bool, 20)
  783. func (ld *loader) parseFile(filename string) (*ast.File, error) {
  784. ld.parseCacheMu.Lock()
  785. v, ok := ld.parseCache[filename]
  786. if ok {
  787. // cache hit
  788. ld.parseCacheMu.Unlock()
  789. <-v.ready
  790. } else {
  791. // cache miss
  792. v = &parseValue{ready: make(chan struct{})}
  793. ld.parseCache[filename] = v
  794. ld.parseCacheMu.Unlock()
  795. var src []byte
  796. for f, contents := range ld.Config.Overlay {
  797. if sameFile(f, filename) {
  798. src = contents
  799. }
  800. }
  801. var err error
  802. if src == nil {
  803. ioLimit <- true // wait
  804. src, err = ioutil.ReadFile(filename)
  805. <-ioLimit // signal
  806. }
  807. if err != nil {
  808. v.err = err
  809. } else {
  810. v.f, v.err = ld.ParseFile(ld.Fset, filename, src)
  811. }
  812. close(v.ready)
  813. }
  814. return v.f, v.err
  815. }
  816. // parseFiles reads and parses the Go source files and returns the ASTs
  817. // of the ones that could be at least partially parsed, along with a
  818. // list of I/O and parse errors encountered.
  819. //
  820. // Because files are scanned in parallel, the token.Pos
  821. // positions of the resulting ast.Files are not ordered.
  822. //
  823. func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) {
  824. var wg sync.WaitGroup
  825. n := len(filenames)
  826. parsed := make([]*ast.File, n)
  827. errors := make([]error, n)
  828. for i, file := range filenames {
  829. if ld.Config.Context.Err() != nil {
  830. parsed[i] = nil
  831. errors[i] = ld.Config.Context.Err()
  832. continue
  833. }
  834. wg.Add(1)
  835. go func(i int, filename string) {
  836. parsed[i], errors[i] = ld.parseFile(filename)
  837. wg.Done()
  838. }(i, file)
  839. }
  840. wg.Wait()
  841. // Eliminate nils, preserving order.
  842. var o int
  843. for _, f := range parsed {
  844. if f != nil {
  845. parsed[o] = f
  846. o++
  847. }
  848. }
  849. parsed = parsed[:o]
  850. o = 0
  851. for _, err := range errors {
  852. if err != nil {
  853. errors[o] = err
  854. o++
  855. }
  856. }
  857. errors = errors[:o]
  858. return parsed, errors
  859. }
  860. // sameFile returns true if x and y have the same basename and denote
  861. // the same file.
  862. //
  863. func sameFile(x, y string) bool {
  864. if x == y {
  865. // It could be the case that y doesn't exist.
  866. // For instance, it may be an overlay file that
  867. // hasn't been written to disk. To handle that case
  868. // let x == y through. (We added the exact absolute path
  869. // string to the CompiledGoFiles list, so the unwritten
  870. // overlay case implies x==y.)
  871. return true
  872. }
  873. if strings.EqualFold(filepath.Base(x), filepath.Base(y)) { // (optimisation)
  874. if xi, err := os.Stat(x); err == nil {
  875. if yi, err := os.Stat(y); err == nil {
  876. return os.SameFile(xi, yi)
  877. }
  878. }
  879. }
  880. return false
  881. }
  882. // loadFromExportData returns type information for the specified
  883. // package, loading it from an export data file on the first request.
  884. func (ld *loader) loadFromExportData(lpkg *loaderPackage) (*types.Package, error) {
  885. if lpkg.PkgPath == "" {
  886. log.Fatalf("internal error: Package %s has no PkgPath", lpkg)
  887. }
  888. // Because gcexportdata.Read has the potential to create or
  889. // modify the types.Package for each node in the transitive
  890. // closure of dependencies of lpkg, all exportdata operations
  891. // must be sequential. (Finer-grained locking would require
  892. // changes to the gcexportdata API.)
  893. //
  894. // The exportMu lock guards the Package.Pkg field and the
  895. // types.Package it points to, for each Package in the graph.
  896. //
  897. // Not all accesses to Package.Pkg need to be protected by exportMu:
  898. // graph ordering ensures that direct dependencies of source
  899. // packages are fully loaded before the importer reads their Pkg field.
  900. ld.exportMu.Lock()
  901. defer ld.exportMu.Unlock()
  902. if tpkg := lpkg.Types; tpkg != nil && tpkg.Complete() {
  903. return tpkg, nil // cache hit
  904. }
  905. lpkg.IllTyped = true // fail safe
  906. if lpkg.ExportFile == "" {
  907. // Errors while building export data will have been printed to stderr.
  908. return nil, fmt.Errorf("no export data file")
  909. }
  910. f, err := os.Open(lpkg.ExportFile)
  911. if err != nil {
  912. return nil, err
  913. }
  914. defer f.Close()
  915. // Read gc export data.
  916. //
  917. // We don't currently support gccgo export data because all
  918. // underlying workspaces use the gc toolchain. (Even build
  919. // systems that support gccgo don't use it for workspace
  920. // queries.)
  921. r, err := gcexportdata.NewReader(f)
  922. if err != nil {
  923. return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err)
  924. }
  925. // Build the view.
  926. //
  927. // The gcexportdata machinery has no concept of package ID.
  928. // It identifies packages by their PkgPath, which although not
  929. // globally unique is unique within the scope of one invocation
  930. // of the linker, type-checker, or gcexportdata.
  931. //
  932. // So, we must build a PkgPath-keyed view of the global
  933. // (conceptually ID-keyed) cache of packages and pass it to
  934. // gcexportdata. The view must contain every existing
  935. // package that might possibly be mentioned by the
  936. // current package---its transitive closure.
  937. //
  938. // In loadPackage, we unconditionally create a types.Package for
  939. // each dependency so that export data loading does not
  940. // create new ones.
  941. //
  942. // TODO(adonovan): it would be simpler and more efficient
  943. // if the export data machinery invoked a callback to
  944. // get-or-create a package instead of a map.
  945. //
  946. view := make(map[string]*types.Package) // view seen by gcexportdata
  947. seen := make(map[*loaderPackage]bool) // all visited packages
  948. var visit func(pkgs map[string]*Package)
  949. visit = func(pkgs map[string]*Package) {
  950. for _, p := range pkgs {
  951. lpkg := ld.pkgs[p.ID]
  952. if !seen[lpkg] {
  953. seen[lpkg] = true
  954. view[lpkg.PkgPath] = lpkg.Types
  955. visit(lpkg.Imports)
  956. }
  957. }
  958. }
  959. visit(lpkg.Imports)
  960. viewLen := len(view) + 1 // adding the self package
  961. // Parse the export data.
  962. // (May modify incomplete packages in view but not create new ones.)
  963. tpkg, err := gcexportdata.Read(r, ld.Fset, view, lpkg.PkgPath)
  964. if err != nil {
  965. return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err)
  966. }
  967. if viewLen != len(view) {
  968. log.Fatalf("Unexpected package creation during export data loading")
  969. }
  970. lpkg.Types = tpkg
  971. lpkg.IllTyped = false
  972. return tpkg, nil
  973. }
  974. func usesExportData(cfg *Config) bool {
  975. return cfg.Mode&NeedExportsFile != 0 ||
  976. // If NeedTypes but not NeedTypesInfo we won't typecheck using sources, so we need export data.
  977. (cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedTypesInfo == 0) ||
  978. // If NeedTypesInfo but not NeedDeps, we're typechecking a package using its sources plus its dependencies' export data
  979. (cfg.Mode&NeedTypesInfo != 0 && cfg.Mode&NeedDeps == 0)
  980. }
上海开阖软件有限公司 沪ICP备12045867号-1