loader.go 33 KB

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