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.
17 "golang.org/x/tools/go/buildutil"
20 // We use a counting semaphore to limit
21 // the number of parallel I/O calls per process.
22 var ioLimit = make(chan bool, 10)
24 // parseFiles parses the Go source files within directory dir and
25 // returns the ASTs of the ones that could be at least partially parsed,
26 // along with a list of I/O and parse errors encountered.
28 // I/O is done via ctxt, which may specify a virtual file system.
29 // displayPath is used to transform the filenames attached to the ASTs.
31 func parseFiles(fset *token.FileSet, ctxt *build.Context, displayPath func(string) string, dir string, files []string, mode parser.Mode) ([]*ast.File, []error) {
32 if displayPath == nil {
33 displayPath = func(path string) string { return path }
37 parsed := make([]*ast.File, n)
38 errors := make([]error, n)
39 for i, file := range files {
40 if !buildutil.IsAbsPath(ctxt, file) {
41 file = buildutil.JoinPath(ctxt, dir, file)
44 go func(i int, file string) {
45 ioLimit <- true // wait
52 if ctxt.OpenFile != nil {
53 rd, err = ctxt.OpenFile(file)
55 rd, err = os.Open(file)
58 errors[i] = err // open failed
62 // ParseFile may return both an AST and an error.
63 parsed[i], errors[i] = parser.ParseFile(fset, displayPath(file), rd, mode)
69 // Eliminate nils, preserving order.
71 for _, f := range parsed {
80 for _, err := range errors {
91 // scanImports returns the set of all import paths from all
92 // import specs in the specified files.
93 func scanImports(files []*ast.File) map[string]bool {
94 imports := make(map[string]bool)
95 for _, f := range files {
96 for _, decl := range f.Decls {
97 if decl, ok := decl.(*ast.GenDecl); ok && decl.Tok == token.IMPORT {
98 for _, spec := range decl.Specs {
99 spec := spec.(*ast.ImportSpec)
101 // NB: do not assume the program is well-formed!
102 path, err := strconv.Unquote(spec.Path.Value)
104 continue // quietly ignore the error
107 continue // skip pseudopackage
117 // ---------- Internal helpers ----------
119 // TODO(adonovan): make this a method: func (*token.File) Contains(token.Pos)
120 func tokenFileContainsPos(f *token.File, pos token.Pos) bool {
123 return base <= p && p < base+f.Size()