Debian Codegraph @

parser/parser.go

raw symbols SCIP
1 /*
2 Package parser implements a parser for JavaScript.
3
4 import (
5 "github.com/robertkrimen/otto/parser"
6 )
7
8 Parse and return an AST
9
10 filename := "" // A filename is optional
11 src := `
12 // Sample xyzzy example
13 (function(){
14 if (3.14159 > 0) {
15 console.log("Hello, World.");
16 return;
17 }
18
19 var xyzzy = NaN;
20 console.log("Nothing happens.");
21 return xyzzy;
22 })();
23 `
24
25 // Parse some JavaScript, yielding a *ast.Program and/or an ErrorList
26 program, err := parser.ParseFile(nil, filename, src, 0)
27
28 # Warning
29
30 The parser and AST interfaces are still works-in-progress (particularly where
31 node types are concerned) and may change in the future.
32 */
33 package parser
34
35 import (
36 "bytes"
37 "encoding/base64"
38 "fmt"
39 "io"
40 "os"
41
42 "github.com/robertkrimen/otto/ast"
43 "github.com/robertkrimen/otto/file"
44 "github.com/robertkrimen/otto/token"
45 "gopkg.in/sourcemap.v1"
46 )
47
48 // A Mode value is a set of flags (or 0). They control optional parser functionality.
49 type Mode uint
50
51 const (
52 // IgnoreRegExpErrors ignores RegExp compatibility errors (allow backtracking).
53 IgnoreRegExpErrors Mode = 1 << iota
54
55 // StoreComments stores the comments from source to the comments map.
56 StoreComments
57 )
58
59 type parser struct {
60 comments *ast.Comments
61 file *file.File
62 scope *scope
63 literal string
64 str string
65 errors ErrorList
66 recover struct {
67 idx file.Idx
68 count int
69 }
70 idx file.Idx
71 token token.Token
72 offset int
73 chrOffset int
74 mode Mode
75 base int
76 length int
77 chr rune
78 insertSemicolon bool
79 implicitSemicolon bool // Scratch when trying to seek to the next statement, etc.
80 }
81
82 // Parser is implemented by types which can parse JavaScript Code.
83 type Parser interface {
84 Scan() (tkn token.Token, literal string, idx file.Idx)
85 }
86
87 func newParser(filename, src string, base int, sm *sourcemap.Consumer) *parser {
88 return &parser{
89 chr: ' ', // This is set so we can start scanning by skipping whitespace
90 str: src,
91 length: len(src),
92 base: base,
93 file: file.NewFile(filename, src, base).WithSourceMap(sm),
94 comments: ast.NewComments(),
95 }
96 }
97
98 // NewParser returns a new Parser.
99 func NewParser(filename, src string) Parser {
100 return newParser(filename, src, 1, nil)
101 }
102
103 // ReadSource reads code from src if not nil, otherwise reads from filename.
104 func ReadSource(filename string, src interface{}) ([]byte, error) {
105 if src != nil {
106 switch src := src.(type) {
107 case string:
108 return []byte(src), nil
109 case []byte:
110 return src, nil
111 case *bytes.Buffer:
112 if src != nil {
113 return src.Bytes(), nil
114 }
115 case io.Reader:
116 var bfr bytes.Buffer
117 if _, err := io.Copy(&bfr, src); err != nil {
118 return nil, err
119 }
120 return bfr.Bytes(), nil
121 default:
122 return nil, fmt.Errorf("invalid src type %T", src)
123 }
124 }
125 return os.ReadFile(filename) //nolint:gosec
126 }
127
128 // ReadSourceMap reads the source map from src if not nil, otherwise is a noop.
129 func ReadSourceMap(filename string, src interface{}) (*sourcemap.Consumer, error) {
130 if src == nil {
131 return nil, nil //nolint:nilnil
132 }
133
134 switch src := src.(type) {
135 case string:
136 return sourcemap.Parse(filename, []byte(src))
137 case []byte:
138 return sourcemap.Parse(filename, src)
139 case *bytes.Buffer:
140 return sourcemap.Parse(filename, src.Bytes())
141 case io.Reader:
142 var bfr bytes.Buffer
143 if _, err := io.Copy(&bfr, src); err != nil {
144 return nil, err
145 }
146 return sourcemap.Parse(filename, bfr.Bytes())
147 case *sourcemap.Consumer:
148 return src, nil
149 default:
150 return nil, fmt.Errorf("invalid sourcemap type %T", src)
151 }
152 }
153
154 // ParseFileWithSourceMap parses the sourcemap returning the resulting Program.
155 func ParseFileWithSourceMap(fileSet *file.FileSet, filename string, javascriptSource, sourcemapSource interface{}, mode Mode) (*ast.Program, error) {
156 src, err := ReadSource(filename, javascriptSource)
157 if err != nil {
158 return nil, err
159 }
160
161 if sourcemapSource == nil {
162 lines := bytes.Split(src, []byte("\n"))
163 lastLine := lines[len(lines)-1]
164 if bytes.HasPrefix(lastLine, []byte("//# sourceMappingURL=data:application/json")) {
165 bits := bytes.SplitN(lastLine, []byte(","), 2)
166 if len(bits) == 2 {
167 if d, errDecode := base64.StdEncoding.DecodeString(string(bits[1])); errDecode == nil {
168 sourcemapSource = d
169 }
170 }
171 }
172 }
173
174 sm, err := ReadSourceMap(filename, sourcemapSource)
175 if err != nil {
176 return nil, err
177 }
178
179 base := 1
180 if fileSet != nil {
181 base = fileSet.AddFile(filename, string(src))
182 }
183
184 p := newParser(filename, string(src), base, sm)
185 p.mode = mode
186 program, err := p.parse()
187 program.Comments = p.comments.CommentMap
188
189 return program, err
190 }
191
192 // ParseFile parses the source code of a single JavaScript/ECMAScript source file and returns
193 // the corresponding ast.Program node.
194 //
195 // If fileSet == nil, ParseFile parses source without a FileSet.
196 // If fileSet != nil, ParseFile first adds filename and src to fileSet.
197 //
198 // The filename argument is optional and is used for labelling errors, etc.
199 //
200 // src may be a string, a byte slice, a bytes.Buffer, or an io.Reader, but it MUST always be in UTF-8.
201 //
202 // // Parse some JavaScript, yielding a *ast.Program and/or an ErrorList
203 // program, err := parser.ParseFile(nil, "", `if (abc > 1) {}`, 0)
204 func ParseFile(fileSet *file.FileSet, filename string, src interface{}, mode Mode) (*ast.Program, error) {
205 return ParseFileWithSourceMap(fileSet, filename, src, nil, mode)
206 }
207
208 // ParseFunction parses a given parameter list and body as a function and returns the
209 // corresponding ast.FunctionLiteral node.
210 //
211 // The parameter list, if any, should be a comma-separated list of identifiers.
212 func ParseFunction(parameterList, body string) (*ast.FunctionLiteral, error) {
213 src := "(function(" + parameterList + ") {\n" + body + "\n})"
214
215 p := newParser("", src, 1, nil)
216 program, err := p.parse()
217 if err != nil {
218 return nil, err
219 }
220
221 return program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral), nil
222 }
223
224 // Scan reads a single token from the source at the current offset, increments the offset and
225 // returns the token.Token token, a string literal representing the value of the token (if applicable)
226 // and it's current file.Idx index.
227 func (p *parser) Scan() (token.Token, string, file.Idx) {
228 return p.scan()
229 }
230
231 func (p *parser) slice(idx0, idx1 file.Idx) string {
232 from := int(idx0) - p.base
233 to := int(idx1) - p.base
234 if from >= 0 && to <= len(p.str) {
235 return p.str[from:to]
236 }
237
238 return ""
239 }
240
241 func (p *parser) parse() (*ast.Program, error) {
242 p.next()
243 program := p.parseProgram()
244 if false {
245 p.errors.Sort()
246 }
247
248 if p.mode&StoreComments != 0 {
249 p.comments.CommentMap.AddComments(program, p.comments.FetchAll(), ast.TRAILING)
250 }
251
252 return program, p.errors.Err()
253 }
254
255 func (p *parser) next() {
256 p.token, p.literal, p.idx = p.scan()
257 }
258
259 func (p *parser) optionalSemicolon() {
260 if p.token == token.SEMICOLON {
261 p.next()
262 return
263 }
264
265 if p.implicitSemicolon {
266 p.implicitSemicolon = false
267 return
268 }
269
270 if p.token != token.EOF && p.token != token.RIGHT_BRACE {
271 p.expect(token.SEMICOLON)
272 }
273 }
274
275 func (p *parser) semicolon() {
276 if p.token != token.RIGHT_PARENTHESIS && p.token != token.RIGHT_BRACE {
277 if p.implicitSemicolon {
278 p.implicitSemicolon = false
279 return
280 }
281
282 p.expect(token.SEMICOLON)
283 }
284 }
285
286 func (p *parser) idxOf(offset int) file.Idx {
287 return file.Idx(p.base + offset)
288 }
289
290 func (p *parser) expect(value token.Token) file.Idx {
291 idx := p.idx
292 if p.token != value {
293 p.errorUnexpectedToken(p.token)
294 }
295 p.next()
296 return idx
297 }
298
299 func lineCount(str string) (int, int) {
300 line, last := 0, -1
301 pair := false
302 for index, chr := range str {
303 switch chr {
304 case '\r':
305 line++
306 last = index
307 pair = true
308 continue
309 case '\n':
310 if !pair {
311 line++
312 }
313 last = index
314 case '\u2028', '\u2029':
315 line++
316 last = index + 2
317 }
318 pair = false
319 }
320 return line, last
321 }
322
323 func (p *parser) position(idx file.Idx) file.Position {
324 position := file.Position{}
325 offset := int(idx) - p.base
326 str := p.str[:offset]
327 position.Filename = p.file.Name()
328 line, last := lineCount(str)
329 position.Line = 1 + line
330 if last >= 0 {
331 position.Column = offset - last
332 } else {
333 position.Column = 1 + len(str)
334 }
335
336 return position
337 }