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.
7 // See doc.go for package documentation and implementation notes.
25 "golang.org/x/tools/go/gcexportdata"
28 // A LoadMode specifies the amount of detail to return when loading.
29 // Higher-numbered modes cause Load to return more information,
30 // but may be slower. Load may return more information than requested.
34 // The following constants are used to specify which fields of the Package
35 // should be filled when loading is done. As a special case to provide
36 // backwards compatibility, a LoadMode of 0 is equivalent to LoadFiles.
37 // For all other LoadModes, the bits below specify which fields will be filled
38 // in the result packages.
39 // WARNING: This part of the go/packages API is EXPERIMENTAL. It might
40 // be changed or removed up until April 15 2019. After that date it will
42 // TODO(matloob): Remove this comment on April 15.
44 // ID and Errors (if present) will always be filled.
46 // NeedName adds Name and PkgPath.
47 NeedName LoadMode = 1 << iota
49 // NeedFiles adds GoFiles and OtherFiles.
52 // NeedCompiledGoFiles adds CompiledGoFiles.
55 // NeedImports adds Imports. If NeedDeps is not set, the Imports field will contain
56 // "placeholder" Packages with only the ID set.
59 // NeedDeps adds the fields requested by the LoadMode in the packages in Imports. If NeedImports
60 // is not set NeedDeps has no effect.
63 // NeedExportsFile adds ExportsFile.
66 // NeedTypes adds Types, Fset, and IllTyped.
69 // NeedSyntax adds Syntax.
72 // NeedTypesInfo adds TypesInfo.
75 // NeedTypesSizes adds TypesSizes.
80 // LoadFiles finds the packages and computes their source file lists.
81 // Package fields: ID, Name, Errors, GoFiles, CompiledGoFiles, and OtherFiles.
82 LoadFiles = NeedName | NeedFiles | NeedCompiledGoFiles
84 // LoadImports adds import information for each package
85 // and its dependencies.
86 // Package fields added: Imports.
87 LoadImports = LoadFiles | NeedImports | NeedDeps
89 // LoadTypes adds type information for package-level
90 // declarations in the packages matching the patterns.
91 // Package fields added: Types, TypesSizes, Fset, and IllTyped.
92 // This mode uses type information provided by the build system when
93 // possible, and may fill in the ExportFile field.
94 LoadTypes = LoadImports | NeedTypes | NeedTypesSizes
96 // LoadSyntax adds typed syntax trees for the packages matching the patterns.
97 // Package fields added: Syntax, and TypesInfo, for direct pattern matches only.
98 LoadSyntax = LoadTypes | NeedSyntax | NeedTypesInfo
100 // LoadAllSyntax adds typed syntax trees for the packages matching the patterns
101 // and all dependencies.
102 // Package fields added: Types, Fset, IllTyped, Syntax, and TypesInfo,
103 // for all packages in the import graph.
104 LoadAllSyntax = LoadSyntax
107 // A Config specifies details about how packages should be loaded.
108 // The zero value is a valid configuration.
109 // Calls to Load do not modify this struct.
111 // Mode controls the level of information returned for each package.
114 // Context specifies the context for the load operation.
115 // If the context is cancelled, the loader may stop early
116 // and return an ErrCancelled error.
117 // If Context is nil, the load cannot be cancelled.
118 Context context.Context
120 // Dir is the directory in which to run the build system's query tool
121 // that provides information about the packages.
122 // If Dir is empty, the tool is run in the current directory.
125 // Env is the environment to use when invoking the build system's query tool.
126 // If Env is nil, the current environment is used.
127 // As in os/exec's Cmd, only the last value in the slice for
128 // each environment key is used. To specify the setting of only
129 // a few variables, append to the current environment, as in:
131 // opt.Env = append(os.Environ(), "GOOS=plan9", "GOARCH=386")
135 // BuildFlags is a list of command-line flags to be passed through to
136 // the build system's query tool.
139 // Fset provides source position information for syntax trees and types.
140 // If Fset is nil, Load will use a new fileset, but preserve Fset's value.
143 // ParseFile is called to read and parse each file
144 // when preparing a package's type-checked syntax tree.
145 // It must be safe to call ParseFile simultaneously from multiple goroutines.
146 // If ParseFile is nil, the loader will uses parser.ParseFile.
148 // ParseFile should parse the source from src and use filename only for
149 // recording position information.
151 // An application may supply a custom implementation of ParseFile
152 // to change the effective file contents or the behavior of the parser,
153 // or to modify the syntax tree. For example, selectively eliminating
154 // unwanted function bodies can significantly accelerate type checking.
155 ParseFile func(fset *token.FileSet, filename string, src []byte) (*ast.File, error)
157 // If Tests is set, the loader includes not just the packages
158 // matching a particular pattern but also any related test packages,
159 // including test-only variants of the package and the test executable.
161 // For example, when using the go command, loading "fmt" with Tests=true
162 // returns four packages, with IDs "fmt" (the standard package),
163 // "fmt [fmt.test]" (the package as compiled for the test),
164 // "fmt_test" (the test functions from source files in package fmt_test),
165 // and "fmt.test" (the test binary).
167 // In build systems with explicit names for tests,
168 // setting Tests may have no effect.
171 // Overlay provides a mapping of absolute file paths to file contents.
172 // If the file with the given path already exists, the parser will use the
173 // alternative file contents provided by the map.
175 // Overlays provide incomplete support for when a given file doesn't
176 // already exist on disk. See the package doc above for more details.
177 Overlay map[string][]byte
180 // driver is the type for functions that query the build system for the
181 // packages named by the patterns.
182 type driver func(cfg *Config, patterns ...string) (*driverResponse, error)
184 // driverResponse contains the results for a driver query.
185 type driverResponse struct {
186 // Sizes, if not nil, is the types.Sizes to use when type checking.
187 Sizes *types.StdSizes
189 // Roots is the set of package IDs that make up the root packages.
190 // We have to encode this separately because when we encode a single package
191 // we cannot know if it is one of the roots as that requires knowledge of the
192 // graph it is part of.
193 Roots []string `json:",omitempty"`
195 // Packages is the full set of packages in the graph.
196 // The packages are not connected into a graph.
197 // The Imports if populated will be stubs that only have their ID set.
198 // Imports will be connected and then type and syntax information added in a
199 // later pass (see refine).
203 // Load loads and returns the Go packages named by the given patterns.
205 // Config specifies loading options;
206 // nil behaves the same as an empty Config.
208 // Load returns an error if any of the patterns was invalid
209 // as defined by the underlying build system.
210 // It may return an empty list of packages without an error,
211 // for instance for an empty expansion of a valid wildcard.
212 // Errors associated with a particular package are recorded in the
213 // corresponding Package's Errors list, and do not cause Load to
214 // return an error. Clients may need to handle such errors before
215 // proceeding with further analysis. The PrintErrors function is
216 // provided for convenient display of all errors.
217 func Load(cfg *Config, patterns ...string) ([]*Package, error) {
219 response, err := defaultDriver(&l.Config, patterns...)
223 l.sizes = response.Sizes
224 return l.refine(response.Roots, response.Packages...)
227 // defaultDriver is a driver that looks for an external driver binary, and if
228 // it does not find it falls back to the built in go list driver.
229 func defaultDriver(cfg *Config, patterns ...string) (*driverResponse, error) {
230 driver := findExternalDriver(cfg)
232 driver = goListDriver
234 return driver(cfg, patterns...)
237 // A Package describes a loaded Go package.
238 type Package struct {
239 // ID is a unique identifier for a package,
240 // in a syntax provided by the underlying build system.
242 // Because the syntax varies based on the build system,
243 // clients should treat IDs as opaque and not attempt to
247 // Name is the package name as it appears in the package source code.
250 // PkgPath is the package path as used by the go/types package.
253 // Errors contains any errors encountered querying the metadata
254 // of the package, or while parsing or type-checking its files.
257 // GoFiles lists the absolute file paths of the package's Go source files.
260 // CompiledGoFiles lists the absolute file paths of the package's source
261 // files that were presented to the compiler.
262 // This may differ from GoFiles if files are processed before compilation.
263 CompiledGoFiles []string
265 // OtherFiles lists the absolute file paths of the package's non-Go source files,
266 // including assembly, C, C++, Fortran, Objective-C, SWIG, and so on.
269 // ExportFile is the absolute path to a file containing type
270 // information for the package as provided by the build system.
273 // Imports maps import paths appearing in the package's Go source files
274 // to corresponding loaded Packages.
275 Imports map[string]*Package
277 // Types provides type information for the package.
278 // Modes LoadTypes and above set this field for packages matching the
279 // patterns; type information for dependencies may be missing or incomplete.
280 // Mode LoadAllSyntax sets this field for all packages, including dependencies.
283 // Fset provides position information for Types, TypesInfo, and Syntax.
284 // It is set only when Types is set.
287 // IllTyped indicates whether the package or any dependency contains errors.
288 // It is set only when Types is set.
291 // Syntax is the package's syntax trees, for the files listed in CompiledGoFiles.
293 // Mode LoadSyntax sets this field for packages matching the patterns.
294 // Mode LoadAllSyntax sets this field for all packages, including dependencies.
297 // TypesInfo provides type information about the package's syntax trees.
298 // It is set only when Syntax is set.
299 TypesInfo *types.Info
301 // TypesSizes provides the effective size function for types in TypesInfo.
302 TypesSizes types.Sizes
305 // An Error describes a problem with a package's metadata, syntax, or types.
307 Pos string // "file:line:col" or "file:line" or "" or "-"
312 // ErrorKind describes the source of the error, allowing the user to
313 // differentiate between errors generated by the driver, the parser, or the
318 UnknownError ErrorKind = iota
324 func (err Error) Error() string {
327 pos = "-" // like token.Position{}.String()
329 return pos + ": " + err.Msg
332 // flatPackage is the JSON form of Package
333 // It drops all the type and syntax fields, and transforms the Imports
335 // TODO(adonovan): identify this struct with Package, effectively
336 // publishing the JSON protocol.
337 type flatPackage struct {
339 Name string `json:",omitempty"`
340 PkgPath string `json:",omitempty"`
341 Errors []Error `json:",omitempty"`
342 GoFiles []string `json:",omitempty"`
343 CompiledGoFiles []string `json:",omitempty"`
344 OtherFiles []string `json:",omitempty"`
345 ExportFile string `json:",omitempty"`
346 Imports map[string]string `json:",omitempty"`
349 // MarshalJSON returns the Package in its JSON form.
350 // For the most part, the structure fields are written out unmodified, and
351 // the type and syntax fields are skipped.
352 // The imports are written out as just a map of path to package id.
353 // The errors are written using a custom type that tries to preserve the
354 // structure of error types we know about.
356 // This method exists to enable support for additional build systems. It is
357 // not intended for use by clients of the API and we may change the format.
358 func (p *Package) MarshalJSON() ([]byte, error) {
359 flat := &flatPackage{
365 CompiledGoFiles: p.CompiledGoFiles,
366 OtherFiles: p.OtherFiles,
367 ExportFile: p.ExportFile,
369 if len(p.Imports) > 0 {
370 flat.Imports = make(map[string]string, len(p.Imports))
371 for path, ipkg := range p.Imports {
372 flat.Imports[path] = ipkg.ID
375 return json.Marshal(flat)
378 // UnmarshalJSON reads in a Package from its JSON format.
379 // See MarshalJSON for details about the format accepted.
380 func (p *Package) UnmarshalJSON(b []byte) error {
381 flat := &flatPackage{}
382 if err := json.Unmarshal(b, &flat); err != nil {
388 PkgPath: flat.PkgPath,
390 GoFiles: flat.GoFiles,
391 CompiledGoFiles: flat.CompiledGoFiles,
392 OtherFiles: flat.OtherFiles,
393 ExportFile: flat.ExportFile,
395 if len(flat.Imports) > 0 {
396 p.Imports = make(map[string]*Package, len(flat.Imports))
397 for path, id := range flat.Imports {
398 p.Imports[path] = &Package{ID: id}
404 func (p *Package) String() string { return p.ID }
406 // loaderPackage augments Package with state used during the loading phase
407 type loaderPackage struct {
409 importErrors map[string]error // maps each bad import to its error
411 color uint8 // for cycle detection
412 needsrc bool // load from source (Mode >= LoadTypes)
413 needtypes bool // type information is either requested or depended on
414 initial bool // package was matched by a pattern
417 // loader holds the working state of a single call to load.
419 pkgs map[string]*loaderPackage
422 exportMu sync.Mutex // enforces mutual exclusion of exportdata operations
424 // TODO(matloob): Add an implied mode here and use that instead of mode.
425 // Implied mode would contain all the fields we need the data for so we can
426 // get the actually requested fields. We'll zero them out before returning
427 // packages to the user. This will make it easier for us to get the conditions
428 // where we need certain modes right.
431 func newLoader(cfg *Config) *loader {
436 if ld.Config.Mode == 0 {
437 ld.Config.Mode = LoadFiles // Preserve zero behavior of Mode for backwards compatibility.
439 if ld.Config.Env == nil {
440 ld.Config.Env = os.Environ()
442 if ld.Context == nil {
443 ld.Context = context.Background()
446 if dir, err := os.Getwd(); err == nil {
451 if ld.Mode&NeedTypes != 0 {
453 ld.Fset = token.NewFileSet()
456 // ParseFile is required even in LoadTypes mode
457 // because we load source if export data is missing.
458 if ld.ParseFile == nil {
459 ld.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
464 const mode = parser.AllErrors | parser.ParseComments
465 return parser.ParseFile(fset, filename, isrc, mode)
472 // refine connects the supplied packages into a graph and then adds type and
473 // and syntax information as requested by the LoadMode.
474 func (ld *loader) refine(roots []string, list ...*Package) ([]*Package, error) {
475 rootMap := make(map[string]int, len(roots))
476 for i, root := range roots {
479 ld.pkgs = make(map[string]*loaderPackage)
480 // first pass, fixup and build the map and roots
481 var initial = make([]*loaderPackage, len(roots))
482 for _, pkg := range list {
484 if i, found := rootMap[pkg.ID]; found {
487 lpkg := &loaderPackage{
489 needtypes: (ld.Mode&(NeedTypes|NeedTypesInfo) != 0 && rootIndex < 0) || rootIndex >= 0,
490 needsrc: (ld.Mode&(NeedSyntax|NeedTypesInfo) != 0 && rootIndex < 0) || rootIndex >= 0 ||
491 len(ld.Overlay) > 0 || // Overlays can invalidate export data. TODO(matloob): make this check fine-grained based on dependencies on overlaid files
492 pkg.ExportFile == "" && pkg.PkgPath != "unsafe",
494 ld.pkgs[lpkg.ID] = lpkg
496 initial[rootIndex] = lpkg
500 for i, root := range roots {
501 if initial[i] == nil {
502 return nil, fmt.Errorf("root package %v is missing", root)
506 // Materialize the import graph.
510 grey = 1 // in progress
511 black = 2 // complete
514 // visit traverses the import graph, depth-first,
515 // and materializes the graph as Packages.Imports.
517 // Valid imports are saved in the Packages.Import map.
518 // Invalid imports (cycles and missing nodes) are saved in the importErrors map.
519 // Thus, even in the presence of both kinds of errors, the Import graph remains a DAG.
521 // visit returns whether the package needs src or has a transitive
522 // dependency on a package that does. These are the only packages
523 // for which we load source code.
524 var stack []*loaderPackage
525 var visit func(lpkg *loaderPackage) bool
526 var srcPkgs []*loaderPackage
527 visit = func(lpkg *loaderPackage) bool {
532 panic("internal error: grey node")
535 stack = append(stack, lpkg) // push
536 stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports
537 lpkg.Imports = make(map[string]*Package, len(stubs))
538 for importPath, ipkg := range stubs {
540 imp := ld.pkgs[ipkg.ID]
542 // (includes package "C" when DisableCgo)
543 importErr = fmt.Errorf("missing package: %q", ipkg.ID)
544 } else if imp.color == grey {
545 importErr = fmt.Errorf("import cycle: %s", stack)
547 if importErr != nil {
548 if lpkg.importErrors == nil {
549 lpkg.importErrors = make(map[string]error)
551 lpkg.importErrors[importPath] = importErr
558 lpkg.Imports[importPath] = imp.Package
561 srcPkgs = append(srcPkgs, lpkg)
563 if ld.Mode&NeedTypesSizes != 0 {
564 lpkg.TypesSizes = ld.sizes
566 stack = stack[:len(stack)-1] // pop
572 if ld.Mode&(NeedImports|NeedDeps) == 0 {
573 // We do this to drop the stub import packages that we are not even going to try to resolve.
574 for _, lpkg := range initial {
578 // For each initial package, create its import DAG.
579 for _, lpkg := range initial {
583 if ld.Mode&NeedDeps != 0 { // TODO(matloob): This is only the case if NeedTypes is also set, right?
584 for _, lpkg := range srcPkgs {
585 // Complete type information is required for the
586 // immediate dependencies of each source package.
587 for _, ipkg := range lpkg.Imports {
588 imp := ld.pkgs[ipkg.ID]
593 // Load type data if needed, starting at
594 // the initial packages (roots of the import DAG).
595 if ld.Mode&NeedTypes != 0 {
596 var wg sync.WaitGroup
597 for _, lpkg := range initial {
599 go func(lpkg *loaderPackage) {
600 ld.loadRecursive(lpkg)
607 result := make([]*Package, len(initial))
608 importPlaceholders := make(map[string]*Package)
609 for i, lpkg := range initial {
610 result[i] = lpkg.Package
612 for i := range ld.pkgs {
613 // Clear all unrequested fields, for extra de-Hyrum-ization.
614 if ld.Mode&NeedName == 0 {
616 ld.pkgs[i].PkgPath = ""
618 if ld.Mode&NeedFiles == 0 {
619 ld.pkgs[i].GoFiles = nil
620 ld.pkgs[i].OtherFiles = nil
622 if ld.Mode&NeedCompiledGoFiles == 0 {
623 ld.pkgs[i].CompiledGoFiles = nil
625 if ld.Mode&NeedImports == 0 {
626 ld.pkgs[i].Imports = nil
628 if ld.Mode&NeedExportsFile == 0 {
629 ld.pkgs[i].ExportFile = ""
631 if ld.Mode&NeedTypes == 0 {
632 ld.pkgs[i].Types = nil
633 ld.pkgs[i].Fset = nil
634 ld.pkgs[i].IllTyped = false
636 if ld.Mode&NeedSyntax == 0 {
637 ld.pkgs[i].Syntax = nil
639 if ld.Mode&NeedTypesInfo == 0 {
640 ld.pkgs[i].TypesInfo = nil
642 if ld.Mode&NeedTypesSizes == 0 {
643 ld.pkgs[i].TypesSizes = nil
645 if ld.Mode&NeedDeps == 0 {
646 for j, pkg := range ld.pkgs[i].Imports {
647 ph, ok := importPlaceholders[pkg.ID]
649 ph = &Package{ID: pkg.ID}
650 importPlaceholders[pkg.ID] = ph
652 ld.pkgs[i].Imports[j] = ph
659 // loadRecursive loads the specified package and its dependencies,
660 // recursively, in parallel, in topological order.
661 // It is atomic and idempotent.
662 // Precondition: ld.Mode&NeedTypes.
663 func (ld *loader) loadRecursive(lpkg *loaderPackage) {
664 lpkg.loadOnce.Do(func() {
665 // Load the direct dependencies, in parallel.
666 var wg sync.WaitGroup
667 for _, ipkg := range lpkg.Imports {
668 imp := ld.pkgs[ipkg.ID]
670 go func(imp *loaderPackage) {
671 ld.loadRecursive(imp)
681 // loadPackage loads the specified package.
682 // It must be called only once per Package,
683 // after immediate dependencies are loaded.
684 // Precondition: ld.Mode >= LoadTypes.
685 func (ld *loader) loadPackage(lpkg *loaderPackage) {
686 if lpkg.PkgPath == "unsafe" {
687 // Fill in the blanks to avoid surprises.
688 lpkg.Types = types.Unsafe
690 lpkg.Syntax = []*ast.File{}
691 lpkg.TypesInfo = new(types.Info)
692 lpkg.TypesSizes = ld.sizes
696 // Call NewPackage directly with explicit name.
697 // This avoids skew between golist and go/types when the files'
698 // package declarations are inconsistent.
699 lpkg.Types = types.NewPackage(lpkg.PkgPath, lpkg.Name)
702 // Subtle: we populate all Types fields with an empty Package
703 // before loading export data so that export data processing
704 // never has to create a types.Package for an indirect dependency,
705 // which would then require that such created packages be explicitly
706 // inserted back into the Import graph as a final step after export data loading.
707 // The Diamond test exercises this case.
712 ld.loadFromExportData(lpkg)
713 return // not a source package, don't get syntax trees
716 appendError := func(err error) {
717 // Convert various error types into the one true Error.
719 switch err := err.(type) {
722 errs = append(errs, err)
726 errs = append(errs, Error{
727 Pos: err.Path + ":1",
728 Msg: err.Err.Error(),
732 case scanner.ErrorList:
734 for _, err := range err {
735 errs = append(errs, Error{
736 Pos: err.Pos.String(),
744 errs = append(errs, Error{
745 Pos: err.Fset.Position(err.Pos).String(),
751 // unexpected impoverished error from parser?
752 errs = append(errs, Error{
758 // If you see this error message, please file a bug.
759 log.Printf("internal error: error %q (%T) without position", err, err)
762 lpkg.Errors = append(lpkg.Errors, errs...)
765 files, errs := ld.parseFiles(lpkg.CompiledGoFiles)
766 for _, err := range errs {
772 lpkg.TypesInfo = &types.Info{
773 Types: make(map[ast.Expr]types.TypeAndValue),
774 Defs: make(map[*ast.Ident]types.Object),
775 Uses: make(map[*ast.Ident]types.Object),
776 Implicits: make(map[ast.Node]types.Object),
777 Scopes: make(map[ast.Node]*types.Scope),
778 Selections: make(map[*ast.SelectorExpr]*types.Selection),
780 lpkg.TypesSizes = ld.sizes
782 importer := importerFunc(func(path string) (*types.Package, error) {
783 if path == "unsafe" {
784 return types.Unsafe, nil
787 // The imports map is keyed by import path.
788 ipkg := lpkg.Imports[path]
790 if err := lpkg.importErrors[path]; err != nil {
793 // There was skew between the metadata and the
794 // import declarations, likely due to an edit
795 // race, or because the ParseFile feature was
796 // used to supply alternative file contents.
797 return nil, fmt.Errorf("no metadata for %s", path)
800 if ipkg.Types != nil && ipkg.Types.Complete() {
801 return ipkg.Types, nil
803 log.Fatalf("internal error: nil Pkg importing %q from %q", path, lpkg)
811 // Type-check bodies of functions only in non-initial packages.
812 // Example: for import graph A->B->C and initial packages {A,C},
813 // we can ignore function bodies in B.
814 IgnoreFuncBodies: (ld.Mode&(NeedDeps|NeedTypesInfo) == 0) && !lpkg.initial,
819 types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax)
821 lpkg.importErrors = nil // no longer needed
823 // If !Cgo, the type-checker uses FakeImportC mode, so
824 // it doesn't invoke the importer for import "C",
825 // nor report an error for the import,
826 // or for any undefined C.f reference.
827 // We must detect this explicitly and correctly
828 // mark the package as IllTyped (by reporting an error).
829 // TODO(adonovan): if these errors are annoying,
830 // we could just set IllTyped quietly.
833 for _, f := range lpkg.Syntax {
834 for _, imp := range f.Imports {
835 if imp.Path.Value == `"C"` {
836 err := types.Error{Fset: ld.Fset, Pos: imp.Pos(), Msg: `import "C" ignored`}
844 // Record accumulated errors.
845 illTyped := len(lpkg.Errors) > 0
847 for _, imp := range lpkg.Imports {
854 lpkg.IllTyped = illTyped
857 // An importFunc is an implementation of the single-method
858 // types.Importer interface based on a function value.
859 type importerFunc func(path string) (*types.Package, error)
861 func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
863 // We use a counting semaphore to limit
864 // the number of parallel I/O calls per process.
865 var ioLimit = make(chan bool, 20)
867 // parseFiles reads and parses the Go source files and returns the ASTs
868 // of the ones that could be at least partially parsed, along with a
869 // list of I/O and parse errors encountered.
871 // Because files are scanned in parallel, the token.Pos
872 // positions of the resulting ast.Files are not ordered.
874 func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) {
875 var wg sync.WaitGroup
877 parsed := make([]*ast.File, n)
878 errors := make([]error, n)
879 for i, file := range filenames {
880 if ld.Config.Context.Err() != nil {
882 errors[i] = ld.Config.Context.Err()
886 go func(i int, filename string) {
887 ioLimit <- true // wait
888 // ParseFile may return both an AST and an error.
890 for f, contents := range ld.Config.Overlay {
891 if sameFile(f, filename) {
897 src, err = ioutil.ReadFile(filename)
900 parsed[i], errors[i] = nil, err
902 parsed[i], errors[i] = ld.ParseFile(ld.Fset, filename, src)
910 // Eliminate nils, preserving order.
912 for _, f := range parsed {
921 for _, err := range errors {
929 return parsed, errors
932 // sameFile returns true if x and y have the same basename and denote
935 func sameFile(x, y string) bool {
937 // It could be the case that y doesn't exist.
938 // For instance, it may be an overlay file that
939 // hasn't been written to disk. To handle that case
940 // let x == y through. (We added the exact absolute path
941 // string to the CompiledGoFiles list, so the unwritten
942 // overlay case implies x==y.)
945 if strings.EqualFold(filepath.Base(x), filepath.Base(y)) { // (optimisation)
946 if xi, err := os.Stat(x); err == nil {
947 if yi, err := os.Stat(y); err == nil {
948 return os.SameFile(xi, yi)
955 // loadFromExportData returns type information for the specified
956 // package, loading it from an export data file on the first request.
957 func (ld *loader) loadFromExportData(lpkg *loaderPackage) (*types.Package, error) {
958 if lpkg.PkgPath == "" {
959 log.Fatalf("internal error: Package %s has no PkgPath", lpkg)
962 // Because gcexportdata.Read has the potential to create or
963 // modify the types.Package for each node in the transitive
964 // closure of dependencies of lpkg, all exportdata operations
965 // must be sequential. (Finer-grained locking would require
966 // changes to the gcexportdata API.)
968 // The exportMu lock guards the Package.Pkg field and the
969 // types.Package it points to, for each Package in the graph.
971 // Not all accesses to Package.Pkg need to be protected by exportMu:
972 // graph ordering ensures that direct dependencies of source
973 // packages are fully loaded before the importer reads their Pkg field.
975 defer ld.exportMu.Unlock()
977 if tpkg := lpkg.Types; tpkg != nil && tpkg.Complete() {
978 return tpkg, nil // cache hit
981 lpkg.IllTyped = true // fail safe
983 if lpkg.ExportFile == "" {
984 // Errors while building export data will have been printed to stderr.
985 return nil, fmt.Errorf("no export data file")
987 f, err := os.Open(lpkg.ExportFile)
993 // Read gc export data.
995 // We don't currently support gccgo export data because all
996 // underlying workspaces use the gc toolchain. (Even build
997 // systems that support gccgo don't use it for workspace
999 r, err := gcexportdata.NewReader(f)
1001 return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err)
1006 // The gcexportdata machinery has no concept of package ID.
1007 // It identifies packages by their PkgPath, which although not
1008 // globally unique is unique within the scope of one invocation
1009 // of the linker, type-checker, or gcexportdata.
1011 // So, we must build a PkgPath-keyed view of the global
1012 // (conceptually ID-keyed) cache of packages and pass it to
1013 // gcexportdata. The view must contain every existing
1014 // package that might possibly be mentioned by the
1015 // current package---its transitive closure.
1017 // In loadPackage, we unconditionally create a types.Package for
1018 // each dependency so that export data loading does not
1021 // TODO(adonovan): it would be simpler and more efficient
1022 // if the export data machinery invoked a callback to
1023 // get-or-create a package instead of a map.
1025 view := make(map[string]*types.Package) // view seen by gcexportdata
1026 seen := make(map[*loaderPackage]bool) // all visited packages
1027 var visit func(pkgs map[string]*Package)
1028 visit = func(pkgs map[string]*Package) {
1029 for _, p := range pkgs {
1030 lpkg := ld.pkgs[p.ID]
1033 view[lpkg.PkgPath] = lpkg.Types
1040 viewLen := len(view) + 1 // adding the self package
1041 // Parse the export data.
1042 // (May modify incomplete packages in view but not create new ones.)
1043 tpkg, err := gcexportdata.Read(r, ld.Fset, view, lpkg.PkgPath)
1045 return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err)
1047 if viewLen != len(view) {
1048 log.Fatalf("Unexpected package creation during export data loading")
1052 lpkg.IllTyped = false
1057 func usesExportData(cfg *Config) bool {
1058 return cfg.Mode&NeedExportsFile != 0 || cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedTypesInfo == 0