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.

1077 lines
33 KiB

  1. // Copyright 2013 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 loader
  5. // See doc.go for package documentation and implementation notes.
  6. import (
  7. "errors"
  8. "fmt"
  9. "go/ast"
  10. "go/build"
  11. "go/parser"
  12. "go/token"
  13. "go/types"
  14. "os"
  15. "path/filepath"
  16. "sort"
  17. "strings"
  18. "sync"
  19. "time"
  20. "golang.org/x/tools/go/ast/astutil"
  21. )
  22. var ignoreVendor build.ImportMode
  23. const trace = false // show timing info for type-checking
  24. // Config specifies the configuration for loading a whole program from
  25. // Go source code.
  26. // The zero value for Config is a ready-to-use default configuration.
  27. type Config struct {
  28. // Fset is the file set for the parser to use when loading the
  29. // program. If nil, it may be lazily initialized by any
  30. // method of Config.
  31. Fset *token.FileSet
  32. // ParserMode specifies the mode to be used by the parser when
  33. // loading source packages.
  34. ParserMode parser.Mode
  35. // TypeChecker contains options relating to the type checker.
  36. //
  37. // The supplied IgnoreFuncBodies is not used; the effective
  38. // value comes from the TypeCheckFuncBodies func below.
  39. // The supplied Import function is not used either.
  40. TypeChecker types.Config
  41. // TypeCheckFuncBodies is a predicate over package paths.
  42. // A package for which the predicate is false will
  43. // have its package-level declarations type checked, but not
  44. // its function bodies; this can be used to quickly load
  45. // dependencies from source. If nil, all func bodies are type
  46. // checked.
  47. TypeCheckFuncBodies func(path string) bool
  48. // If Build is non-nil, it is used to locate source packages.
  49. // Otherwise &build.Default is used.
  50. //
  51. // By default, cgo is invoked to preprocess Go files that
  52. // import the fake package "C". This behaviour can be
  53. // disabled by setting CGO_ENABLED=0 in the environment prior
  54. // to startup, or by setting Build.CgoEnabled=false.
  55. Build *build.Context
  56. // The current directory, used for resolving relative package
  57. // references such as "./go/loader". If empty, os.Getwd will be
  58. // used instead.
  59. Cwd string
  60. // If DisplayPath is non-nil, it is used to transform each
  61. // file name obtained from Build.Import(). This can be used
  62. // to prevent a virtualized build.Config's file names from
  63. // leaking into the user interface.
  64. DisplayPath func(path string) string
  65. // If AllowErrors is true, Load will return a Program even
  66. // if some of the its packages contained I/O, parser or type
  67. // errors; such errors are accessible via PackageInfo.Errors. If
  68. // false, Load will fail if any package had an error.
  69. AllowErrors bool
  70. // CreatePkgs specifies a list of non-importable initial
  71. // packages to create. The resulting packages will appear in
  72. // the corresponding elements of the Program.Created slice.
  73. CreatePkgs []PkgSpec
  74. // ImportPkgs specifies a set of initial packages to load.
  75. // The map keys are package paths.
  76. //
  77. // The map value indicates whether to load tests. If true, Load
  78. // will add and type-check two lists of files to the package:
  79. // non-test files followed by in-package *_test.go files. In
  80. // addition, it will append the external test package (if any)
  81. // to Program.Created.
  82. ImportPkgs map[string]bool
  83. // FindPackage is called during Load to create the build.Package
  84. // for a given import path from a given directory.
  85. // If FindPackage is nil, (*build.Context).Import is used.
  86. // A client may use this hook to adapt to a proprietary build
  87. // system that does not follow the "go build" layout
  88. // conventions, for example.
  89. //
  90. // It must be safe to call concurrently from multiple goroutines.
  91. FindPackage func(ctxt *build.Context, importPath, fromDir string, mode build.ImportMode) (*build.Package, error)
  92. // AfterTypeCheck is called immediately after a list of files
  93. // has been type-checked and appended to info.Files.
  94. //
  95. // This optional hook function is the earliest opportunity for
  96. // the client to observe the output of the type checker,
  97. // which may be useful to reduce analysis latency when loading
  98. // a large program.
  99. //
  100. // The function is permitted to modify info.Info, for instance
  101. // to clear data structures that are no longer needed, which can
  102. // dramatically reduce peak memory consumption.
  103. //
  104. // The function may be called twice for the same PackageInfo:
  105. // once for the files of the package and again for the
  106. // in-package test files.
  107. //
  108. // It must be safe to call concurrently from multiple goroutines.
  109. AfterTypeCheck func(info *PackageInfo, files []*ast.File)
  110. }
  111. // A PkgSpec specifies a non-importable package to be created by Load.
  112. // Files are processed first, but typically only one of Files and
  113. // Filenames is provided. The path needn't be globally unique.
  114. //
  115. // For vendoring purposes, the package's directory is the one that
  116. // contains the first file.
  117. type PkgSpec struct {
  118. Path string // package path ("" => use package declaration)
  119. Files []*ast.File // ASTs of already-parsed files
  120. Filenames []string // names of files to be parsed
  121. }
  122. // A Program is a Go program loaded from source as specified by a Config.
  123. type Program struct {
  124. Fset *token.FileSet // the file set for this program
  125. // Created[i] contains the initial package whose ASTs or
  126. // filenames were supplied by Config.CreatePkgs[i], followed by
  127. // the external test package, if any, of each package in
  128. // Config.ImportPkgs ordered by ImportPath.
  129. //
  130. // NOTE: these files must not import "C". Cgo preprocessing is
  131. // only performed on imported packages, not ad hoc packages.
  132. //
  133. // TODO(adonovan): we need to copy and adapt the logic of
  134. // goFilesPackage (from $GOROOT/src/cmd/go/build.go) and make
  135. // Config.Import and Config.Create methods return the same kind
  136. // of entity, essentially a build.Package.
  137. // Perhaps we can even reuse that type directly.
  138. Created []*PackageInfo
  139. // Imported contains the initially imported packages,
  140. // as specified by Config.ImportPkgs.
  141. Imported map[string]*PackageInfo
  142. // AllPackages contains the PackageInfo of every package
  143. // encountered by Load: all initial packages and all
  144. // dependencies, including incomplete ones.
  145. AllPackages map[*types.Package]*PackageInfo
  146. // importMap is the canonical mapping of package paths to
  147. // packages. It contains all Imported initial packages, but not
  148. // Created ones, and all imported dependencies.
  149. importMap map[string]*types.Package
  150. }
  151. // PackageInfo holds the ASTs and facts derived by the type-checker
  152. // for a single package.
  153. //
  154. // Not mutated once exposed via the API.
  155. //
  156. type PackageInfo struct {
  157. Pkg *types.Package
  158. Importable bool // true if 'import "Pkg.Path()"' would resolve to this
  159. TransitivelyErrorFree bool // true if Pkg and all its dependencies are free of errors
  160. Files []*ast.File // syntax trees for the package's files
  161. Errors []error // non-nil if the package had errors
  162. types.Info // type-checker deductions.
  163. dir string // package directory
  164. checker *types.Checker // transient type-checker state
  165. errorFunc func(error)
  166. }
  167. func (info *PackageInfo) String() string { return info.Pkg.Path() }
  168. func (info *PackageInfo) appendError(err error) {
  169. if info.errorFunc != nil {
  170. info.errorFunc(err)
  171. } else {
  172. fmt.Fprintln(os.Stderr, err)
  173. }
  174. info.Errors = append(info.Errors, err)
  175. }
  176. func (conf *Config) fset() *token.FileSet {
  177. if conf.Fset == nil {
  178. conf.Fset = token.NewFileSet()
  179. }
  180. return conf.Fset
  181. }
  182. // ParseFile is a convenience function (intended for testing) that invokes
  183. // the parser using the Config's FileSet, which is initialized if nil.
  184. //
  185. // src specifies the parser input as a string, []byte, or io.Reader, and
  186. // filename is its apparent name. If src is nil, the contents of
  187. // filename are read from the file system.
  188. //
  189. func (conf *Config) ParseFile(filename string, src interface{}) (*ast.File, error) {
  190. // TODO(adonovan): use conf.build() etc like parseFiles does.
  191. return parser.ParseFile(conf.fset(), filename, src, conf.ParserMode)
  192. }
  193. // FromArgsUsage is a partial usage message that applications calling
  194. // FromArgs may wish to include in their -help output.
  195. const FromArgsUsage = `
  196. <args> is a list of arguments denoting a set of initial packages.
  197. It may take one of two forms:
  198. 1. A list of *.go source files.
  199. All of the specified files are loaded, parsed and type-checked
  200. as a single package. All the files must belong to the same directory.
  201. 2. A list of import paths, each denoting a package.
  202. The package's directory is found relative to the $GOROOT and
  203. $GOPATH using similar logic to 'go build', and the *.go files in
  204. that directory are loaded, parsed and type-checked as a single
  205. package.
  206. In addition, all *_test.go files in the directory are then loaded
  207. and parsed. Those files whose package declaration equals that of
  208. the non-*_test.go files are included in the primary package. Test
  209. files whose package declaration ends with "_test" are type-checked
  210. as another package, the 'external' test package, so that a single
  211. import path may denote two packages. (Whether this behaviour is
  212. enabled is tool-specific, and may depend on additional flags.)
  213. A '--' argument terminates the list of packages.
  214. `
  215. // FromArgs interprets args as a set of initial packages to load from
  216. // source and updates the configuration. It returns the list of
  217. // unconsumed arguments.
  218. //
  219. // It is intended for use in command-line interfaces that require a
  220. // set of initial packages to be specified; see FromArgsUsage message
  221. // for details.
  222. //
  223. // Only superficial errors are reported at this stage; errors dependent
  224. // on I/O are detected during Load.
  225. //
  226. func (conf *Config) FromArgs(args []string, xtest bool) ([]string, error) {
  227. var rest []string
  228. for i, arg := range args {
  229. if arg == "--" {
  230. rest = args[i+1:]
  231. args = args[:i]
  232. break // consume "--" and return the remaining args
  233. }
  234. }
  235. if len(args) > 0 && strings.HasSuffix(args[0], ".go") {
  236. // Assume args is a list of a *.go files
  237. // denoting a single ad hoc package.
  238. for _, arg := range args {
  239. if !strings.HasSuffix(arg, ".go") {
  240. return nil, fmt.Errorf("named files must be .go files: %s", arg)
  241. }
  242. }
  243. conf.CreateFromFilenames("", args...)
  244. } else {
  245. // Assume args are directories each denoting a
  246. // package and (perhaps) an external test, iff xtest.
  247. for _, arg := range args {
  248. if xtest {
  249. conf.ImportWithTests(arg)
  250. } else {
  251. conf.Import(arg)
  252. }
  253. }
  254. }
  255. return rest, nil
  256. }
  257. // CreateFromFilenames is a convenience function that adds
  258. // a conf.CreatePkgs entry to create a package of the specified *.go
  259. // files.
  260. //
  261. func (conf *Config) CreateFromFilenames(path string, filenames ...string) {
  262. conf.CreatePkgs = append(conf.CreatePkgs, PkgSpec{Path: path, Filenames: filenames})
  263. }
  264. // CreateFromFiles is a convenience function that adds a conf.CreatePkgs
  265. // entry to create package of the specified path and parsed files.
  266. //
  267. func (conf *Config) CreateFromFiles(path string, files ...*ast.File) {
  268. conf.CreatePkgs = append(conf.CreatePkgs, PkgSpec{Path: path, Files: files})
  269. }
  270. // ImportWithTests is a convenience function that adds path to
  271. // ImportPkgs, the set of initial source packages located relative to
  272. // $GOPATH. The package will be augmented by any *_test.go files in
  273. // its directory that contain a "package x" (not "package x_test")
  274. // declaration.
  275. //
  276. // In addition, if any *_test.go files contain a "package x_test"
  277. // declaration, an additional package comprising just those files will
  278. // be added to CreatePkgs.
  279. //
  280. func (conf *Config) ImportWithTests(path string) { conf.addImport(path, true) }
  281. // Import is a convenience function that adds path to ImportPkgs, the
  282. // set of initial packages that will be imported from source.
  283. //
  284. func (conf *Config) Import(path string) { conf.addImport(path, false) }
  285. func (conf *Config) addImport(path string, tests bool) {
  286. if path == "C" {
  287. return // ignore; not a real package
  288. }
  289. if conf.ImportPkgs == nil {
  290. conf.ImportPkgs = make(map[string]bool)
  291. }
  292. conf.ImportPkgs[path] = conf.ImportPkgs[path] || tests
  293. }
  294. // PathEnclosingInterval returns the PackageInfo and ast.Node that
  295. // contain source interval [start, end), and all the node's ancestors
  296. // up to the AST root. It searches all ast.Files of all packages in prog.
  297. // exact is defined as for astutil.PathEnclosingInterval.
  298. //
  299. // The zero value is returned if not found.
  300. //
  301. func (prog *Program) PathEnclosingInterval(start, end token.Pos) (pkg *PackageInfo, path []ast.Node, exact bool) {
  302. for _, info := range prog.AllPackages {
  303. for _, f := range info.Files {
  304. if f.Pos() == token.NoPos {
  305. // This can happen if the parser saw
  306. // too many errors and bailed out.
  307. // (Use parser.AllErrors to prevent that.)
  308. continue
  309. }
  310. if !tokenFileContainsPos(prog.Fset.File(f.Pos()), start) {
  311. continue
  312. }
  313. if path, exact := astutil.PathEnclosingInterval(f, start, end); path != nil {
  314. return info, path, exact
  315. }
  316. }
  317. }
  318. return nil, nil, false
  319. }
  320. // InitialPackages returns a new slice containing the set of initial
  321. // packages (Created + Imported) in unspecified order.
  322. //
  323. func (prog *Program) InitialPackages() []*PackageInfo {
  324. infos := make([]*PackageInfo, 0, len(prog.Created)+len(prog.Imported))
  325. infos = append(infos, prog.Created...)
  326. for _, info := range prog.Imported {
  327. infos = append(infos, info)
  328. }
  329. return infos
  330. }
  331. // Package returns the ASTs and results of type checking for the
  332. // specified package.
  333. func (prog *Program) Package(path string) *PackageInfo {
  334. if info, ok := prog.AllPackages[prog.importMap[path]]; ok {
  335. return info
  336. }
  337. for _, info := range prog.Created {
  338. if path == info.Pkg.Path() {
  339. return info
  340. }
  341. }
  342. return nil
  343. }
  344. // ---------- Implementation ----------
  345. // importer holds the working state of the algorithm.
  346. type importer struct {
  347. conf *Config // the client configuration
  348. start time.Time // for logging
  349. progMu sync.Mutex // guards prog
  350. prog *Program // the resulting program
  351. // findpkg is a memoization of FindPackage.
  352. findpkgMu sync.Mutex // guards findpkg
  353. findpkg map[findpkgKey]*findpkgValue
  354. importedMu sync.Mutex // guards imported
  355. imported map[string]*importInfo // all imported packages (incl. failures) by import path
  356. // import dependency graph: graph[x][y] => x imports y
  357. //
  358. // Since non-importable packages cannot be cyclic, we ignore
  359. // their imports, thus we only need the subgraph over importable
  360. // packages. Nodes are identified by their import paths.
  361. graphMu sync.Mutex
  362. graph map[string]map[string]bool
  363. }
  364. type findpkgKey struct {
  365. importPath string
  366. fromDir string
  367. mode build.ImportMode
  368. }
  369. type findpkgValue struct {
  370. ready chan struct{} // closed to broadcast readiness
  371. bp *build.Package
  372. err error
  373. }
  374. // importInfo tracks the success or failure of a single import.
  375. //
  376. // Upon completion, exactly one of info and err is non-nil:
  377. // info on successful creation of a package, err otherwise.
  378. // A successful package may still contain type errors.
  379. //
  380. type importInfo struct {
  381. path string // import path
  382. info *PackageInfo // results of typechecking (including errors)
  383. complete chan struct{} // closed to broadcast that info is set.
  384. }
  385. // awaitCompletion blocks until ii is complete,
  386. // i.e. the info field is safe to inspect.
  387. func (ii *importInfo) awaitCompletion() {
  388. <-ii.complete // wait for close
  389. }
  390. // Complete marks ii as complete.
  391. // Its info and err fields will not be subsequently updated.
  392. func (ii *importInfo) Complete(info *PackageInfo) {
  393. if info == nil {
  394. panic("info == nil")
  395. }
  396. ii.info = info
  397. close(ii.complete)
  398. }
  399. type importError struct {
  400. path string // import path
  401. err error // reason for failure to create a package
  402. }
  403. // Load creates the initial packages specified by conf.{Create,Import}Pkgs,
  404. // loading their dependencies packages as needed.
  405. //
  406. // On success, Load returns a Program containing a PackageInfo for
  407. // each package. On failure, it returns an error.
  408. //
  409. // If AllowErrors is true, Load will return a Program even if some
  410. // packages contained I/O, parser or type errors, or if dependencies
  411. // were missing. (Such errors are accessible via PackageInfo.Errors. If
  412. // false, Load will fail if any package had an error.
  413. //
  414. // It is an error if no packages were loaded.
  415. //
  416. func (conf *Config) Load() (*Program, error) {
  417. // Create a simple default error handler for parse/type errors.
  418. if conf.TypeChecker.Error == nil {
  419. conf.TypeChecker.Error = func(e error) { fmt.Fprintln(os.Stderr, e) }
  420. }
  421. // Set default working directory for relative package references.
  422. if conf.Cwd == "" {
  423. var err error
  424. conf.Cwd, err = os.Getwd()
  425. if err != nil {
  426. return nil, err
  427. }
  428. }
  429. // Install default FindPackage hook using go/build logic.
  430. if conf.FindPackage == nil {
  431. conf.FindPackage = (*build.Context).Import
  432. }
  433. prog := &Program{
  434. Fset: conf.fset(),
  435. Imported: make(map[string]*PackageInfo),
  436. importMap: make(map[string]*types.Package),
  437. AllPackages: make(map[*types.Package]*PackageInfo),
  438. }
  439. imp := importer{
  440. conf: conf,
  441. prog: prog,
  442. findpkg: make(map[findpkgKey]*findpkgValue),
  443. imported: make(map[string]*importInfo),
  444. start: time.Now(),
  445. graph: make(map[string]map[string]bool),
  446. }
  447. // -- loading proper (concurrent phase) --------------------------------
  448. var errpkgs []string // packages that contained errors
  449. // Load the initially imported packages and their dependencies,
  450. // in parallel.
  451. // No vendor check on packages imported from the command line.
  452. infos, importErrors := imp.importAll("", conf.Cwd, conf.ImportPkgs, ignoreVendor)
  453. for _, ie := range importErrors {
  454. conf.TypeChecker.Error(ie.err) // failed to create package
  455. errpkgs = append(errpkgs, ie.path)
  456. }
  457. for _, info := range infos {
  458. prog.Imported[info.Pkg.Path()] = info
  459. }
  460. // Augment the designated initial packages by their tests.
  461. // Dependencies are loaded in parallel.
  462. var xtestPkgs []*build.Package
  463. for importPath, augment := range conf.ImportPkgs {
  464. if !augment {
  465. continue
  466. }
  467. // No vendor check on packages imported from command line.
  468. bp, err := imp.findPackage(importPath, conf.Cwd, ignoreVendor)
  469. if err != nil {
  470. // Package not found, or can't even parse package declaration.
  471. // Already reported by previous loop; ignore it.
  472. continue
  473. }
  474. // Needs external test package?
  475. if len(bp.XTestGoFiles) > 0 {
  476. xtestPkgs = append(xtestPkgs, bp)
  477. }
  478. // Consult the cache using the canonical package path.
  479. path := bp.ImportPath
  480. imp.importedMu.Lock() // (unnecessary, we're sequential here)
  481. ii, ok := imp.imported[path]
  482. // Paranoid checks added due to issue #11012.
  483. if !ok {
  484. // Unreachable.
  485. // The previous loop called importAll and thus
  486. // startLoad for each path in ImportPkgs, which
  487. // populates imp.imported[path] with a non-zero value.
  488. panic(fmt.Sprintf("imported[%q] not found", path))
  489. }
  490. if ii == nil {
  491. // Unreachable.
  492. // The ii values in this loop are the same as in
  493. // the previous loop, which enforced the invariant
  494. // that at least one of ii.err and ii.info is non-nil.
  495. panic(fmt.Sprintf("imported[%q] == nil", path))
  496. }
  497. if ii.info == nil {
  498. // Unreachable.
  499. // awaitCompletion has the postcondition
  500. // ii.info != nil.
  501. panic(fmt.Sprintf("imported[%q].info = nil", path))
  502. }
  503. info := ii.info
  504. imp.importedMu.Unlock()
  505. // Parse the in-package test files.
  506. files, errs := imp.conf.parsePackageFiles(bp, 't')
  507. for _, err := range errs {
  508. info.appendError(err)
  509. }
  510. // The test files augmenting package P cannot be imported,
  511. // but may import packages that import P,
  512. // so we must disable the cycle check.
  513. imp.addFiles(info, files, false)
  514. }
  515. createPkg := func(path, dir string, files []*ast.File, errs []error) {
  516. info := imp.newPackageInfo(path, dir)
  517. for _, err := range errs {
  518. info.appendError(err)
  519. }
  520. // Ad hoc packages are non-importable,
  521. // so no cycle check is needed.
  522. // addFiles loads dependencies in parallel.
  523. imp.addFiles(info, files, false)
  524. prog.Created = append(prog.Created, info)
  525. }
  526. // Create packages specified by conf.CreatePkgs.
  527. for _, cp := range conf.CreatePkgs {
  528. files, errs := parseFiles(conf.fset(), conf.build(), nil, conf.Cwd, cp.Filenames, conf.ParserMode)
  529. files = append(files, cp.Files...)
  530. path := cp.Path
  531. if path == "" {
  532. if len(files) > 0 {
  533. path = files[0].Name.Name
  534. } else {
  535. path = "(unnamed)"
  536. }
  537. }
  538. dir := conf.Cwd
  539. if len(files) > 0 && files[0].Pos().IsValid() {
  540. dir = filepath.Dir(conf.fset().File(files[0].Pos()).Name())
  541. }
  542. createPkg(path, dir, files, errs)
  543. }
  544. // Create external test packages.
  545. sort.Sort(byImportPath(xtestPkgs))
  546. for _, bp := range xtestPkgs {
  547. files, errs := imp.conf.parsePackageFiles(bp, 'x')
  548. createPkg(bp.ImportPath+"_test", bp.Dir, files, errs)
  549. }
  550. // -- finishing up (sequential) ----------------------------------------
  551. if len(prog.Imported)+len(prog.Created) == 0 {
  552. return nil, errors.New("no initial packages were loaded")
  553. }
  554. // Create infos for indirectly imported packages.
  555. // e.g. incomplete packages without syntax, loaded from export data.
  556. for _, obj := range prog.importMap {
  557. info := prog.AllPackages[obj]
  558. if info == nil {
  559. prog.AllPackages[obj] = &PackageInfo{Pkg: obj, Importable: true}
  560. } else {
  561. // finished
  562. info.checker = nil
  563. info.errorFunc = nil
  564. }
  565. }
  566. if !conf.AllowErrors {
  567. // Report errors in indirectly imported packages.
  568. for _, info := range prog.AllPackages {
  569. if len(info.Errors) > 0 {
  570. errpkgs = append(errpkgs, info.Pkg.Path())
  571. }
  572. }
  573. if errpkgs != nil {
  574. var more string
  575. if len(errpkgs) > 3 {
  576. more = fmt.Sprintf(" and %d more", len(errpkgs)-3)
  577. errpkgs = errpkgs[:3]
  578. }
  579. return nil, fmt.Errorf("couldn't load packages due to errors: %s%s",
  580. strings.Join(errpkgs, ", "), more)
  581. }
  582. }
  583. markErrorFreePackages(prog.AllPackages)
  584. return prog, nil
  585. }
  586. type byImportPath []*build.Package
  587. func (b byImportPath) Len() int { return len(b) }
  588. func (b byImportPath) Less(i, j int) bool { return b[i].ImportPath < b[j].ImportPath }
  589. func (b byImportPath) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
  590. // markErrorFreePackages sets the TransitivelyErrorFree flag on all
  591. // applicable packages.
  592. func markErrorFreePackages(allPackages map[*types.Package]*PackageInfo) {
  593. // Build the transpose of the import graph.
  594. importedBy := make(map[*types.Package]map[*types.Package]bool)
  595. for P := range allPackages {
  596. for _, Q := range P.Imports() {
  597. clients, ok := importedBy[Q]
  598. if !ok {
  599. clients = make(map[*types.Package]bool)
  600. importedBy[Q] = clients
  601. }
  602. clients[P] = true
  603. }
  604. }
  605. // Find all packages reachable from some error package.
  606. reachable := make(map[*types.Package]bool)
  607. var visit func(*types.Package)
  608. visit = func(p *types.Package) {
  609. if !reachable[p] {
  610. reachable[p] = true
  611. for q := range importedBy[p] {
  612. visit(q)
  613. }
  614. }
  615. }
  616. for _, info := range allPackages {
  617. if len(info.Errors) > 0 {
  618. visit(info.Pkg)
  619. }
  620. }
  621. // Mark the others as "transitively error-free".
  622. for _, info := range allPackages {
  623. if !reachable[info.Pkg] {
  624. info.TransitivelyErrorFree = true
  625. }
  626. }
  627. }
  628. // build returns the effective build context.
  629. func (conf *Config) build() *build.Context {
  630. if conf.Build != nil {
  631. return conf.Build
  632. }
  633. return &build.Default
  634. }
  635. // parsePackageFiles enumerates the files belonging to package path,
  636. // then loads, parses and returns them, plus a list of I/O or parse
  637. // errors that were encountered.
  638. //
  639. // 'which' indicates which files to include:
  640. // 'g': include non-test *.go source files (GoFiles + processed CgoFiles)
  641. // 't': include in-package *_test.go source files (TestGoFiles)
  642. // 'x': include external *_test.go source files. (XTestGoFiles)
  643. //
  644. func (conf *Config) parsePackageFiles(bp *build.Package, which rune) ([]*ast.File, []error) {
  645. if bp.ImportPath == "unsafe" {
  646. return nil, nil
  647. }
  648. var filenames []string
  649. switch which {
  650. case 'g':
  651. filenames = bp.GoFiles
  652. case 't':
  653. filenames = bp.TestGoFiles
  654. case 'x':
  655. filenames = bp.XTestGoFiles
  656. default:
  657. panic(which)
  658. }
  659. files, errs := parseFiles(conf.fset(), conf.build(), conf.DisplayPath, bp.Dir, filenames, conf.ParserMode)
  660. // Preprocess CgoFiles and parse the outputs (sequentially).
  661. if which == 'g' && bp.CgoFiles != nil {
  662. cgofiles, err := processCgoFiles(bp, conf.fset(), conf.DisplayPath, conf.ParserMode)
  663. if err != nil {
  664. errs = append(errs, err)
  665. } else {
  666. files = append(files, cgofiles...)
  667. }
  668. }
  669. return files, errs
  670. }
  671. // doImport imports the package denoted by path.
  672. // It implements the types.Importer signature.
  673. //
  674. // It returns an error if a package could not be created
  675. // (e.g. go/build or parse error), but type errors are reported via
  676. // the types.Config.Error callback (the first of which is also saved
  677. // in the package's PackageInfo).
  678. //
  679. // Idempotent.
  680. //
  681. func (imp *importer) doImport(from *PackageInfo, to string) (*types.Package, error) {
  682. if to == "C" {
  683. // This should be unreachable, but ad hoc packages are
  684. // not currently subject to cgo preprocessing.
  685. // See https://github.com/golang/go/issues/11627.
  686. return nil, fmt.Errorf(`the loader doesn't cgo-process ad hoc packages like %q; see Go issue 11627`,
  687. from.Pkg.Path())
  688. }
  689. bp, err := imp.findPackage(to, from.dir, 0)
  690. if err != nil {
  691. return nil, err
  692. }
  693. // The standard unsafe package is handled specially,
  694. // and has no PackageInfo.
  695. if bp.ImportPath == "unsafe" {
  696. return types.Unsafe, nil
  697. }
  698. // Look for the package in the cache using its canonical path.
  699. path := bp.ImportPath
  700. imp.importedMu.Lock()
  701. ii := imp.imported[path]
  702. imp.importedMu.Unlock()
  703. if ii == nil {
  704. panic("internal error: unexpected import: " + path)
  705. }
  706. if ii.info != nil {
  707. return ii.info.Pkg, nil
  708. }
  709. // Import of incomplete package: this indicates a cycle.
  710. fromPath := from.Pkg.Path()
  711. if cycle := imp.findPath(path, fromPath); cycle != nil {
  712. cycle = append([]string{fromPath}, cycle...)
  713. return nil, fmt.Errorf("import cycle: %s", strings.Join(cycle, " -> "))
  714. }
  715. panic("internal error: import of incomplete (yet acyclic) package: " + fromPath)
  716. }
  717. // findPackage locates the package denoted by the importPath in the
  718. // specified directory.
  719. func (imp *importer) findPackage(importPath, fromDir string, mode build.ImportMode) (*build.Package, error) {
  720. // We use a non-blocking duplicate-suppressing cache (gopl.io §9.7)
  721. // to avoid holding the lock around FindPackage.
  722. key := findpkgKey{importPath, fromDir, mode}
  723. imp.findpkgMu.Lock()
  724. v, ok := imp.findpkg[key]
  725. if ok {
  726. // cache hit
  727. imp.findpkgMu.Unlock()
  728. <-v.ready // wait for entry to become ready
  729. } else {
  730. // Cache miss: this goroutine becomes responsible for
  731. // populating the map entry and broadcasting its readiness.
  732. v = &findpkgValue{ready: make(chan struct{})}
  733. imp.findpkg[key] = v
  734. imp.findpkgMu.Unlock()
  735. ioLimit <- true
  736. v.bp, v.err = imp.conf.FindPackage(imp.conf.build(), importPath, fromDir, mode)
  737. <-ioLimit
  738. if _, ok := v.err.(*build.NoGoError); ok {
  739. v.err = nil // empty directory is not an error
  740. }
  741. close(v.ready) // broadcast ready condition
  742. }
  743. return v.bp, v.err
  744. }
  745. // importAll loads, parses, and type-checks the specified packages in
  746. // parallel and returns their completed importInfos in unspecified order.
  747. //
  748. // fromPath is the package path of the importing package, if it is
  749. // importable, "" otherwise. It is used for cycle detection.
  750. //
  751. // fromDir is the directory containing the import declaration that
  752. // caused these imports.
  753. //
  754. func (imp *importer) importAll(fromPath, fromDir string, imports map[string]bool, mode build.ImportMode) (infos []*PackageInfo, errors []importError) {
  755. // TODO(adonovan): opt: do the loop in parallel once
  756. // findPackage is non-blocking.
  757. var pending []*importInfo
  758. for importPath := range imports {
  759. bp, err := imp.findPackage(importPath, fromDir, mode)
  760. if err != nil {
  761. errors = append(errors, importError{
  762. path: importPath,
  763. err: err,
  764. })
  765. continue
  766. }
  767. pending = append(pending, imp.startLoad(bp))
  768. }
  769. if fromPath != "" {
  770. // We're loading a set of imports.
  771. //
  772. // We must record graph edges from the importing package
  773. // to its dependencies, and check for cycles.
  774. imp.graphMu.Lock()
  775. deps, ok := imp.graph[fromPath]
  776. if !ok {
  777. deps = make(map[string]bool)
  778. imp.graph[fromPath] = deps
  779. }
  780. for _, ii := range pending {
  781. deps[ii.path] = true
  782. }
  783. imp.graphMu.Unlock()
  784. }
  785. for _, ii := range pending {
  786. if fromPath != "" {
  787. if cycle := imp.findPath(ii.path, fromPath); cycle != nil {
  788. // Cycle-forming import: we must not await its
  789. // completion since it would deadlock.
  790. //
  791. // We don't record the error in ii since
  792. // the error is really associated with the
  793. // cycle-forming edge, not the package itself.
  794. // (Also it would complicate the
  795. // invariants of importPath completion.)
  796. if trace {
  797. fmt.Fprintf(os.Stderr, "import cycle: %q\n", cycle)
  798. }
  799. continue
  800. }
  801. }
  802. ii.awaitCompletion()
  803. infos = append(infos, ii.info)
  804. }
  805. return infos, errors
  806. }
  807. // findPath returns an arbitrary path from 'from' to 'to' in the import
  808. // graph, or nil if there was none.
  809. func (imp *importer) findPath(from, to string) []string {
  810. imp.graphMu.Lock()
  811. defer imp.graphMu.Unlock()
  812. seen := make(map[string]bool)
  813. var search func(stack []string, importPath string) []string
  814. search = func(stack []string, importPath string) []string {
  815. if !seen[importPath] {
  816. seen[importPath] = true
  817. stack = append(stack, importPath)
  818. if importPath == to {
  819. return stack
  820. }
  821. for x := range imp.graph[importPath] {
  822. if p := search(stack, x); p != nil {
  823. return p
  824. }
  825. }
  826. }
  827. return nil
  828. }
  829. return search(make([]string, 0, 20), from)
  830. }
  831. // startLoad initiates the loading, parsing and type-checking of the
  832. // specified package and its dependencies, if it has not already begun.
  833. //
  834. // It returns an importInfo, not necessarily in a completed state. The
  835. // caller must call awaitCompletion() before accessing its info field.
  836. //
  837. // startLoad is concurrency-safe and idempotent.
  838. //
  839. func (imp *importer) startLoad(bp *build.Package) *importInfo {
  840. path := bp.ImportPath
  841. imp.importedMu.Lock()
  842. ii, ok := imp.imported[path]
  843. if !ok {
  844. ii = &importInfo{path: path, complete: make(chan struct{})}
  845. imp.imported[path] = ii
  846. go func() {
  847. info := imp.load(bp)
  848. ii.Complete(info)
  849. }()
  850. }
  851. imp.importedMu.Unlock()
  852. return ii
  853. }
  854. // load implements package loading by parsing Go source files
  855. // located by go/build.
  856. func (imp *importer) load(bp *build.Package) *PackageInfo {
  857. info := imp.newPackageInfo(bp.ImportPath, bp.Dir)
  858. info.Importable = true
  859. files, errs := imp.conf.parsePackageFiles(bp, 'g')
  860. for _, err := range errs {
  861. info.appendError(err)
  862. }
  863. imp.addFiles(info, files, true)
  864. imp.progMu.Lock()
  865. imp.prog.importMap[bp.ImportPath] = info.Pkg
  866. imp.progMu.Unlock()
  867. return info
  868. }
  869. // addFiles adds and type-checks the specified files to info, loading
  870. // their dependencies if needed. The order of files determines the
  871. // package initialization order. It may be called multiple times on the
  872. // same package. Errors are appended to the info.Errors field.
  873. //
  874. // cycleCheck determines whether the imports within files create
  875. // dependency edges that should be checked for potential cycles.
  876. //
  877. func (imp *importer) addFiles(info *PackageInfo, files []*ast.File, cycleCheck bool) {
  878. // Ensure the dependencies are loaded, in parallel.
  879. var fromPath string
  880. if cycleCheck {
  881. fromPath = info.Pkg.Path()
  882. }
  883. // TODO(adonovan): opt: make the caller do scanImports.
  884. // Callers with a build.Package can skip it.
  885. imp.importAll(fromPath, info.dir, scanImports(files), 0)
  886. if trace {
  887. fmt.Fprintf(os.Stderr, "%s: start %q (%d)\n",
  888. time.Since(imp.start), info.Pkg.Path(), len(files))
  889. }
  890. // Don't call checker.Files on Unsafe, even with zero files,
  891. // because it would mutate the package, which is a global.
  892. if info.Pkg == types.Unsafe {
  893. if len(files) > 0 {
  894. panic(`"unsafe" package contains unexpected files`)
  895. }
  896. } else {
  897. // Ignore the returned (first) error since we
  898. // already collect them all in the PackageInfo.
  899. info.checker.Files(files)
  900. info.Files = append(info.Files, files...)
  901. }
  902. if imp.conf.AfterTypeCheck != nil {
  903. imp.conf.AfterTypeCheck(info, files)
  904. }
  905. if trace {
  906. fmt.Fprintf(os.Stderr, "%s: stop %q\n",
  907. time.Since(imp.start), info.Pkg.Path())
  908. }
  909. }
  910. func (imp *importer) newPackageInfo(path, dir string) *PackageInfo {
  911. var pkg *types.Package
  912. if path == "unsafe" {
  913. pkg = types.Unsafe
  914. } else {
  915. pkg = types.NewPackage(path, "")
  916. }
  917. info := &PackageInfo{
  918. Pkg: pkg,
  919. Info: types.Info{
  920. Types: make(map[ast.Expr]types.TypeAndValue),
  921. Defs: make(map[*ast.Ident]types.Object),
  922. Uses: make(map[*ast.Ident]types.Object),
  923. Implicits: make(map[ast.Node]types.Object),
  924. Scopes: make(map[ast.Node]*types.Scope),
  925. Selections: make(map[*ast.SelectorExpr]*types.Selection),
  926. },
  927. errorFunc: imp.conf.TypeChecker.Error,
  928. dir: dir,
  929. }
  930. // Copy the types.Config so we can vary it across PackageInfos.
  931. tc := imp.conf.TypeChecker
  932. tc.IgnoreFuncBodies = false
  933. if f := imp.conf.TypeCheckFuncBodies; f != nil {
  934. tc.IgnoreFuncBodies = !f(path)
  935. }
  936. tc.Importer = closure{imp, info}
  937. tc.Error = info.appendError // appendError wraps the user's Error function
  938. info.checker = types.NewChecker(&tc, imp.conf.fset(), pkg, &info.Info)
  939. imp.progMu.Lock()
  940. imp.prog.AllPackages[pkg] = info
  941. imp.progMu.Unlock()
  942. return info
  943. }
  944. type closure struct {
  945. imp *importer
  946. info *PackageInfo
  947. }
  948. func (c closure) Import(to string) (*types.Package, error) { return c.imp.doImport(c.info, to) }