OSDN Git Service

libgo: Update to weekly.2012-01-15.
[pf3gnuchains/gcc-fork.git] / libgo / go / go / parser / interface.go
1 // Copyright 2009 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
5 // This file contains the exported entry points for invoking the parser.
6
7 package parser
8
9 import (
10         "bytes"
11         "errors"
12         "go/ast"
13         "go/token"
14         "io"
15         "io/ioutil"
16         "os"
17         "path/filepath"
18 )
19
20 // If src != nil, readSource converts src to a []byte if possible;
21 // otherwise it returns an error. If src == nil, readSource returns
22 // the result of reading the file specified by filename.
23 //
24 func readSource(filename string, src interface{}) ([]byte, error) {
25         if src != nil {
26                 switch s := src.(type) {
27                 case string:
28                         return []byte(s), nil
29                 case []byte:
30                         return s, nil
31                 case *bytes.Buffer:
32                         // is io.Reader, but src is already available in []byte form
33                         if s != nil {
34                                 return s.Bytes(), nil
35                         }
36                 case io.Reader:
37                         var buf bytes.Buffer
38                         if _, err := io.Copy(&buf, s); err != nil {
39                                 return nil, err
40                         }
41                         return buf.Bytes(), nil
42                 }
43                 return nil, errors.New("invalid source")
44         }
45         return ioutil.ReadFile(filename)
46 }
47
48 // The mode parameter to the Parse* functions is a set of flags (or 0).
49 // They control the amount of source code parsed and other optional
50 // parser functionality.
51 //
52 const (
53         PackageClauseOnly uint = 1 << iota // parsing stops after package clause
54         ImportsOnly                        // parsing stops after import declarations
55         ParseComments                      // parse comments and add them to AST
56         Trace                              // print a trace of parsed productions
57         DeclarationErrors                  // report declaration errors
58         SpuriousErrors                     // report all (not just the first) errors per line
59 )
60
61 // ParseFile parses the source code of a single Go source file and returns
62 // the corresponding ast.File node. The source code may be provided via
63 // the filename of the source file, or via the src parameter.
64 //
65 // If src != nil, ParseFile parses the source from src and the filename is
66 // only used when recording position information. The type of the argument
67 // for the src parameter must be string, []byte, or io.Reader.
68 // If src == nil, ParseFile parses the file specified by filename.
69 //
70 // The mode parameter controls the amount of source text parsed and other
71 // optional parser functionality. Position information is recorded in the
72 // file set fset.
73 //
74 // If the source couldn't be read, the returned AST is nil and the error
75 // indicates the specific failure. If the source was read but syntax
76 // errors were found, the result is a partial AST (with ast.Bad* nodes
77 // representing the fragments of erroneous source code). Multiple errors
78 // are returned via a scanner.ErrorList which is sorted by file position.
79 //
80 func ParseFile(fset *token.FileSet, filename string, src interface{}, mode uint) (*ast.File, error) {
81         text, err := readSource(filename, src)
82         if err != nil {
83                 return nil, err
84         }
85         var p parser
86         p.init(fset, filename, text, mode)
87         return p.parseFile(), p.errors()
88 }
89
90 // ParseDir calls ParseFile for the files in the directory specified by path and
91 // returns a map of package name -> package AST with all the packages found. If
92 // filter != nil, only the files with os.FileInfo entries passing through the filter
93 // are considered. The mode bits are passed to ParseFile unchanged. Position
94 // information is recorded in the file set fset.
95 //
96 // If the directory couldn't be read, a nil map and the respective error are
97 // returned. If a parse error occurred, a non-nil but incomplete map and the
98 // first error encountered are returned.
99 //
100 func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode uint) (pkgs map[string]*ast.Package, first error) {
101         fd, err := os.Open(path)
102         if err != nil {
103                 return nil, err
104         }
105         defer fd.Close()
106
107         list, err := fd.Readdir(-1)
108         if err != nil {
109                 return nil, err
110         }
111
112         pkgs = make(map[string]*ast.Package)
113         for _, d := range list {
114                 if filter == nil || filter(d) {
115                         filename := filepath.Join(path, d.Name())
116                         if src, err := ParseFile(fset, filename, nil, mode); err == nil {
117                                 name := src.Name.Name
118                                 pkg, found := pkgs[name]
119                                 if !found {
120                                         pkg = &ast.Package{name, nil, nil, make(map[string]*ast.File)}
121                                         pkgs[name] = pkg
122                                 }
123                                 pkg.Files[filename] = src
124                         } else if first == nil {
125                                 first = err
126                         }
127                 }
128         }
129
130         return
131 }
132
133 // ParseExpr is a convenience function for obtaining the AST of an expression x.
134 // The position information recorded in the AST is undefined.
135 // 
136 func ParseExpr(x string) (ast.Expr, error) {
137         // parse x within the context of a complete package for correct scopes;
138         // use //line directive for correct positions in error messages
139         file, err := ParseFile(token.NewFileSet(), "", "package p;func _(){_=\n//line :1\n"+x+";}", 0)
140         if err != nil {
141                 return nil, err
142         }
143         return file.Decls[0].(*ast.FuncDecl).Body.List[0].(*ast.AssignStmt).Rhs[0], nil
144 }