-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast_parser.go
More file actions
416 lines (318 loc) · 7.25 KB
/
ast_parser.go
File metadata and controls
416 lines (318 loc) · 7.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package javascript
import (
"fmt"
"slices"
"strings"
"vimagination.zapto.org/parser"
)
// Token represents a single parsed token with source positioning.
type Token struct {
parser.Token
Pos, Line, LinePos uint64
}
func (t *Token) hasSingleLineComment() bool {
return t != nil && t.Type == TokenSingleLineComment
}
// IsTypescript returns true when the token was processed as part of a
// Typescript section.
func (t Token) IsTypescript() bool {
return t.Type&tokenTypescript != 0
}
// Tokens is a collection of Token values.
type Tokens []Token
// Comments is a collection of Comment Tokens.
type Comments []*Token
func (c Comments) hasSingleLineComment() bool {
for _, tk := range c {
if tk.hasSingleLineComment() {
return true
}
}
return false
}
func hasSingleLineComment[T any, PT interface {
*T
hasSingleLineComment() bool
}](vs []T) bool {
for n := range vs {
if PT(&vs[n]).hasSingleLineComment() {
return true
}
}
return false
}
func tokeniserFlags(t Tokeniser) (bool, bool) {
if hf, ok := t.(interface{ hasFlags() (bool, bool) }); ok {
return hf.hasFlags()
}
return false, false
}
type jsParser Tokens
// Tokeniser is an interface representing a tokeniser.
type Tokeniser interface {
TokeniserState(parser.TokenFunc)
Iter(func(parser.Token) bool)
GetToken() (parser.Token, error)
GetError() error
}
func newJSParser(t Tokeniser) (jsParser, error) {
ts, jsx := tokeniserFlags(t)
if !ts && !jsx {
t.TokeniserState(new(jsTokeniser).inputElement)
}
var (
tokens jsParser
pos, line, linePos uint64
err error
)
for tk := range t.Iter {
typ := tk.Type
if typ >= tokenTypescript {
typ = typ &^ tokenTypescript
}
tokens = append(tokens, Token{
Token: parser.Token{
Type: typ,
Data: tk.Data,
},
Pos: pos,
Line: line,
LinePos: linePos,
})
switch typ {
case parser.TokenError:
err = Error{
Err: t.GetError(),
Parsing: "Tokens",
Token: tokens[len(tokens)-1],
}
case TokenLineTerminator:
var lastChar rune
for _, c := range tk.Data {
if lastChar != '\r' || c != '\n' {
line++
}
lastChar = c
}
linePos = 0
case TokenNoSubstitutionTemplate, TokenTemplateHead, TokenTemplateMiddle, TokenTemplateTail, TokenMultiLineComment:
var (
lastLT int
lastChar rune
)
for n, c := range tk.Data {
if strings.ContainsRune(lineTerminators, c) {
lastLT = n + 1
linePos = 0
if lastChar != '\r' || c != '\n' {
line++
}
}
lastChar = c
}
linePos += uint64(len(tk.Data) - lastLT)
default:
linePos += uint64(len(tk.Data))
}
pos += uint64(len(tk.Data))
}
return tokens[0:0:len(tokens)], err
}
func (j jsParser) NewGoal() jsParser {
return j[len(j):]
}
func (j *jsParser) Score(k jsParser) {
*j = (*j)[:len(*j)+len(k)]
}
func (j *jsParser) next() *Token {
l := len(*j)
if l == cap(*j) {
return &(*j)[l-1]
}
*j = (*j)[:l+1]
tk := (*j)[l]
return &tk
}
func (j *jsParser) backup() {
*j = (*j)[:len(*j)-1]
}
func (j *jsParser) Peek() parser.Token {
tk := j.next().Token
j.backup()
return tk
}
func (j *jsParser) Accept(ts ...parser.TokenType) bool {
tt := j.next().Type
if slices.Contains(ts, tt) {
return true
}
j.backup()
return false
}
func (j *jsParser) AcceptRun(ts ...parser.TokenType) parser.TokenType {
Loop:
for {
tt := j.next().Type
for _, pt := range ts {
if pt == tt {
continue Loop
}
}
j.backup()
return tt
}
}
func (j *jsParser) Skip() {
j.next()
}
func (j *jsParser) Next() *Token {
return j.next()
}
var depths = [...][2]parser.Token{
{{Type: TokenPunctuator, Data: "["}, {Type: TokenPunctuator, Data: "]"}},
{{Type: TokenPunctuator, Data: "("}, {Type: TokenPunctuator, Data: ")"}},
{{Type: TokenPunctuator, Data: "{"}, {Type: TokenRightBracePunctuator, Data: "}"}},
}
func (j *jsParser) SkipDepth() bool {
var (
on = -1
depth = 1
)
for n, d := range depths {
if j.AcceptToken(d[0]) {
on = n
break
}
}
if on == -1 {
return false
}
for depth > 0 {
if j.AcceptToken(depths[on][0]) {
depth++
} else if j.AcceptToken(depths[on][1]) {
depth--
} else {
j.Skip()
}
}
return true
}
func (j *jsParser) AcceptToken(tk parser.Token) bool {
if j.next().Token == tk {
return true
}
j.backup()
return false
}
func (j *jsParser) ToTokens() Tokens {
return Tokens((*j)[:len(*j):len(*j)])
}
func (j jsParser) ToTypescriptComments() Comments {
if len(j) == 0 {
return nil
}
c := make(Comments, len(j))
for n := range j {
c[n] = &(j)[n]
c[n].Type |= tokenTypescript
}
return c
}
func (j *jsParser) AcceptRunWhitespace() parser.TokenType {
return j.AcceptRun(TokenWhitespace, TokenLineTerminator, TokenSingleLineComment, TokenMultiLineComment)
}
func (j *jsParser) AcceptRunWhitespaceNoNewLine() parser.TokenType {
var tt parser.TokenType
for {
if tt = j.AcceptRun(TokenWhitespace); tt != TokenMultiLineComment {
return tt
} else if strings.ContainsAny(j.Peek().Data, lineTerminators) {
return tt
}
j.Skip()
}
}
func (j *jsParser) AcceptRunWhitespaceNoComment() parser.TokenType {
return j.AcceptRun(TokenWhitespace, TokenLineTerminator)
}
func (j *jsParser) AcceptRunWhitespaceComments() Comments {
var c Comments
g := j.NewGoal()
Loop:
for {
switch g.AcceptRunWhitespaceNoComment() {
case TokenSingleLineComment, TokenMultiLineComment:
default:
break Loop
}
c = append(c, g.Next())
j.Score(g)
g = j.NewGoal()
}
return c
}
func (j *jsParser) AcceptRunWhitespaceNoNewLineNoComment() parser.TokenType {
return j.AcceptRun(TokenWhitespace)
}
func (j *jsParser) AcceptRunWhitespaceNoNewlineComments() Comments {
var c Comments
g := j.NewGoal()
Loop:
for {
switch g.AcceptRunWhitespaceNoNewLineNoComment() {
case TokenSingleLineComment, TokenMultiLineComment:
default:
break Loop
}
c = append(c, g.Next())
j.Score(g)
g = j.NewGoal()
g.AcceptRunWhitespaceNoNewLineNoComment()
if g.Accept(TokenLineTerminator) {
if l := g.GetLastToken().Data; l != "\n" && l != "\r\n" {
break
}
}
}
return c
}
func (j *jsParser) AcceptRunWhitespaceCommentsInList() Comments {
g := j.NewGoal()
g.AcceptRunWhitespace()
if g.Accept(TokenPunctuator, TokenKeyword) {
switch g.GetLastToken().Data {
case ",", ".", "+", "-", "++", "--", "*", "**", "/", "%", "|", "||", "&", "&&", "^", "=", "==", "!=", "===", "!==", "in", "instanceof", "<<", "<", ">", "<=", "??", "?.", "?", ":", "(", "[", "else":
return j.AcceptRunWhitespaceComments()
}
} else if g.Accept(TokenTemplateMiddle, TokenTemplateTail) {
return j.AcceptRunWhitespaceComments()
}
return j.AcceptRunWhitespaceNoNewlineComments()
}
func (j *jsParser) GetLastToken() *Token {
return &(*j)[len(*j)-1]
}
// Error is a parsing error with trace details.
type Error struct {
Err error
Parsing string
Token Token
}
// Error returns the error string.
func (e Error) Error() string {
return fmt.Sprintf("%s: error at position %d (%d:%d):\n%s", e.Parsing, e.Token.Pos+1, e.Token.Line+1, e.Token.LinePos+1, e.Err)
}
// Unwrap returns the wrapped error.
func (e Error) Unwrap() error {
return e.Err
}
func (j *jsParser) Error(parsingFunc string, err error) error {
tk := j.next()
j.backup()
return Error{
Err: err,
Parsing: parsingFunc,
Token: *tk,
}
}