-
Notifications
You must be signed in to change notification settings - Fork 583
/
Copy pathparser.go
6646 lines (6196 loc) · 253 KB
/
parser.go
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package parser
import (
"strings"
"sync"
"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/diagnostics"
"github.com/microsoft/typescript-go/internal/scanner"
"github.com/microsoft/typescript-go/internal/tspath"
)
type ParsingContext int
const (
PCSourceElements ParsingContext = iota // Elements in source file
PCBlockStatements // Statements in block
PCSwitchClauses // Clauses in switch statement
PCSwitchClauseStatements // Statements in switch clause
PCTypeMembers // Members in interface or type literal
PCClassMembers // Members in class declaration
PCEnumMembers // Members in enum declaration
PCHeritageClauseElement // Elements in a heritage clause
PCVariableDeclarations // Variable declarations in variable statement
PCObjectBindingElements // Binding elements in object binding list
PCArrayBindingElements // Binding elements in array binding list
PCArgumentExpressions // Expressions in argument list
PCObjectLiteralMembers // Members in object literal
PCJsxAttributes // Attributes in jsx element
PCJsxChildren // Things between opening and closing JSX tags
PCArrayLiteralMembers // Members in array literal
PCParameters // Parameters in parameter list
PCJSDocParameters // JSDoc parameters in parameter list of JSDoc function type
PCRestProperties // Property names in a rest type list
PCTypeParameters // Type parameters in type parameter list
PCTypeArguments // Type arguments in type argument list
PCTupleElementTypes // Element types in tuple element type list
PCHeritageClauses // Heritage clauses for a class or interface declaration.
PCImportOrExportSpecifiers // Named import clause's import specifier list
PCImportAttributes // Import attributes
PCJSDocComment // Parsing via JSDocParser
PCCount // Number of parsing contexts
)
type ParsingContexts int
type Parser struct {
scanner *scanner.Scanner
factory ast.NodeFactory
fileName string
path tspath.Path
sourceText string
languageVersion core.ScriptTarget
scriptKind core.ScriptKind
languageVariant core.LanguageVariant
diagnostics []*ast.Diagnostic
jsdocDiagnostics []*ast.Diagnostic
token ast.Kind
sourceFlags ast.NodeFlags
contextFlags ast.NodeFlags
parsingContexts ParsingContexts
statementHasAwaitIdentifier bool
hasDeprecatedTag bool
hasParseError bool
identifiers map[string]string
identifierCount int
notParenthesizedArrow core.Set[int]
nodeSlicePool core.Pool[*ast.Node]
jsdocCache map[*ast.Node][]*ast.Node
possibleAwaitSpans []int
jsdocCommentsSpace []string
jsdocCommentRangesSpace []ast.CommentRange
jsdocTagCommentsSpace []string
reparseList []*ast.Node
}
var viableKeywordSuggestions = scanner.GetViableKeywordSuggestions()
var parserPool = sync.Pool{
New: func() any {
return &Parser{}
},
}
func getParser() *Parser {
return parserPool.Get().(*Parser)
}
func putParser(p *Parser) {
*p = Parser{scanner: p.scanner}
parserPool.Put(p)
}
func ParseSourceFile(fileName string, path tspath.Path, sourceText string, languageVersion core.ScriptTarget, jsdocParsingMode scanner.JSDocParsingMode) *ast.SourceFile {
p := getParser()
defer putParser(p)
p.initializeState(fileName, path, sourceText, languageVersion, core.ScriptKindUnknown, jsdocParsingMode)
p.nextToken()
return p.parseSourceFileWorker()
}
func ParseJSONText(fileName string, path tspath.Path, sourceText string) *ast.SourceFile {
p := getParser()
defer putParser(p)
p.initializeState(fileName, path, sourceText, core.ScriptTargetES2015, core.ScriptKindJSON, scanner.JSDocParsingModeParseAll)
p.nextToken()
pos := p.nodePos()
var statements *ast.NodeList
if p.token == ast.KindEndOfFile {
statements = p.newNodeList(core.NewTextRange(pos, p.nodePos()), nil)
p.parseTokenNode()
} else {
var expressions any // []*ast.Expression | *ast.Expression
for p.token != ast.KindEndOfFile {
var expression *ast.Expression
switch p.token {
case ast.KindOpenBracketToken:
expression = p.parseArrayLiteralExpression()
case ast.KindTrueKeyword, ast.KindFalseKeyword, ast.KindNullKeyword:
expression = p.parseTokenNode()
case ast.KindMinusToken:
if p.lookAhead(func(p *Parser) bool {
return p.nextToken() == ast.KindNumericLiteral && p.nextToken() != ast.KindColonToken
}) {
expression = p.parsePrefixUnaryExpression()
} else {
expression = p.parseObjectLiteralExpression()
}
case ast.KindNumericLiteral, ast.KindStringLiteral:
if p.lookAhead(func(p *Parser) bool { return p.nextToken() != ast.KindColonToken }) {
expression = p.parseLiteralExpression(false /*intern*/)
break
}
fallthrough
default:
expression = p.parseObjectLiteralExpression()
}
// Error recovery: collect multiple top-level expressions
if expressions != nil {
if es, ok := expressions.([]*ast.Expression); ok {
expressions = append(es, expression)
} else {
expressions = []*ast.Expression{expressions.(*ast.Expression), expression}
}
} else {
expressions = expression
if p.token != ast.KindEndOfFile {
p.parseErrorAtCurrentToken(diagnostics.Unexpected_token)
}
}
}
var expression *ast.Expression
if es, ok := expressions.([]*ast.Expression); ok {
expression = p.factory.NewArrayLiteralExpression(p.newNodeList(core.NewTextRange(pos, p.nodePos()), es), false)
} else {
expression = expressions.(*ast.Expression)
}
statement := p.factory.NewExpressionStatement(expression)
p.finishNode(statement, pos)
statements = p.newNodeList(core.NewTextRange(pos, p.nodePos()), []*ast.Node{statement})
p.parseExpectedToken(ast.KindEndOfFile)
}
node := p.factory.NewSourceFile(p.sourceText, p.fileName, p.path, statements)
p.finishNode(node, pos)
result := node.AsSourceFile()
result.ScriptKind = core.ScriptKindJSON
result.LanguageVersion = core.ScriptTargetES2015
result.Flags |= p.sourceFlags
result.SetDiagnostics(attachFileToDiagnostics(p.diagnostics, result))
result.SetJSDocDiagnostics(attachFileToDiagnostics(p.jsdocDiagnostics, result))
return result
}
func ParseIsolatedEntityName(text string, languageVersion core.ScriptTarget) *ast.EntityName {
p := getParser()
defer putParser(p)
p.initializeState("", "", text, languageVersion, core.ScriptKindJS, scanner.JSDocParsingModeParseAll)
p.nextToken()
entityName := p.parseEntityName(true, nil)
return core.IfElse(p.token == ast.KindEndOfFile && len(p.diagnostics) == 0, entityName, nil)
}
func (p *Parser) initializeState(fileName string, path tspath.Path, sourceText string, languageVersion core.ScriptTarget, scriptKind core.ScriptKind, jsdocParsingMode scanner.JSDocParsingMode) {
if p.scanner == nil {
p.scanner = scanner.NewScanner()
} else {
p.scanner.Reset()
}
p.fileName = fileName
p.path = path
p.sourceText = sourceText
p.languageVersion = languageVersion
p.scriptKind = ensureScriptKind(fileName, scriptKind)
p.languageVariant = getLanguageVariant(p.scriptKind)
switch p.scriptKind {
case core.ScriptKindJS, core.ScriptKindJSX:
p.contextFlags = ast.NodeFlagsJavaScriptFile
case core.ScriptKindJSON:
p.contextFlags = ast.NodeFlagsJavaScriptFile | ast.NodeFlagsJsonFile
default:
p.contextFlags = ast.NodeFlagsNone
}
p.hasParseError = false
p.scanner.SetText(p.sourceText)
p.scanner.SetOnError(p.scanError)
p.scanner.SetScriptTarget(p.languageVersion)
p.scanner.SetLanguageVariant(p.languageVariant)
p.scanner.SetScriptKind(p.scriptKind)
p.scanner.SetJSDocParsingMode(jsdocParsingMode)
}
func (p *Parser) scanError(message *diagnostics.Message, pos int, length int, args ...any) {
p.parseErrorAtRange(core.NewTextRange(pos, pos+length), message, args...)
}
func (p *Parser) parseErrorAt(pos int, end int, message *diagnostics.Message, args ...any) *ast.Diagnostic {
return p.parseErrorAtRange(core.NewTextRange(pos, end), message, args...)
}
func (p *Parser) parseErrorAtCurrentToken(message *diagnostics.Message, args ...any) *ast.Diagnostic {
return p.parseErrorAtRange(p.scanner.TokenRange(), message, args...)
}
func (p *Parser) parseErrorAtRange(loc core.TextRange, message *diagnostics.Message, args ...any) *ast.Diagnostic {
// Don't report another error if it would just be at the same location as the last error
var result *ast.Diagnostic
if len(p.diagnostics) == 0 || p.diagnostics[len(p.diagnostics)-1].Pos() != loc.Pos() {
result = ast.NewDiagnostic(nil, loc, message, args...)
p.diagnostics = append(p.diagnostics, result)
}
p.hasParseError = true
return result
}
type ParserState struct {
scannerState scanner.ScannerState
contextFlags ast.NodeFlags
diagnosticsLen int
statementHasAwaitIdentifier bool
hasParseError bool
}
func (p *Parser) mark() ParserState {
return ParserState{
scannerState: p.scanner.Mark(),
contextFlags: p.contextFlags,
diagnosticsLen: len(p.diagnostics),
statementHasAwaitIdentifier: p.statementHasAwaitIdentifier,
hasParseError: p.hasParseError,
}
}
func (p *Parser) rewind(state ParserState) {
p.scanner.Rewind(state.scannerState)
p.token = p.scanner.Token()
p.contextFlags = state.contextFlags
p.diagnostics = p.diagnostics[0:state.diagnosticsLen]
p.statementHasAwaitIdentifier = state.statementHasAwaitIdentifier
p.hasParseError = state.hasParseError
}
func (p *Parser) lookAhead(callback func(p *Parser) bool) bool {
state := p.mark()
result := callback(p)
p.rewind(state)
return result
}
func (p *Parser) nextToken() ast.Kind {
// if the keyword had an escape
if isKeyword(p.token) && (p.scanner.HasUnicodeEscape() || p.scanner.HasExtendedUnicodeEscape()) {
// issue a parse error for the escape
p.parseErrorAtCurrentToken(diagnostics.Keywords_cannot_contain_escape_characters)
}
p.token = p.scanner.Scan()
return p.token
}
func (p *Parser) nextTokenWithoutCheck() ast.Kind {
p.token = p.scanner.Scan()
return p.token
}
func (p *Parser) nextTokenJSDoc() ast.Kind {
p.token = p.scanner.ScanJSDocToken()
return p.token
}
func (p *Parser) nextJSDocCommentTextToken(inBackticks bool) ast.Kind {
p.token = p.scanner.ScanJSDocCommentTextToken(inBackticks)
return p.token
}
func (p *Parser) nodePos() int {
return p.scanner.TokenFullStart()
}
func (p *Parser) hasPrecedingLineBreak() bool {
return p.scanner.HasPrecedingLineBreak()
}
func (p *Parser) hasPrecedingJSDocComment() bool {
return p.scanner.HasPrecedingJSDocComment()
}
func (p *Parser) parseSourceFileWorker() *ast.SourceFile {
isDeclarationFile := tspath.IsDeclarationFileName(p.fileName)
if isDeclarationFile {
p.contextFlags |= ast.NodeFlagsAmbient
}
pos := p.nodePos()
statements := p.parseListIndex(PCSourceElements, (*Parser).parseToplevelStatement)
eof := p.parseTokenNode()
if eof.Kind != ast.KindEndOfFile {
panic("Expected end of file token from scanner.")
}
node := p.factory.NewSourceFile(p.sourceText, p.fileName, p.path, statements)
p.finishNode(node, pos)
result := node.AsSourceFile()
p.finishSourceFile(result, isDeclarationFile)
if !result.IsDeclarationFile && result.ExternalModuleIndicator != nil && len(p.possibleAwaitSpans) > 0 {
reparse := p.reparseTopLevelAwait(result)
if node != reparse {
p.finishNode(reparse, pos)
result = reparse.AsSourceFile()
p.finishSourceFile(result, isDeclarationFile)
}
}
p.jsdocCache = nil
p.possibleAwaitSpans = []int{}
collectExternalModuleReferences(result)
return result
}
func (p *Parser) finishSourceFile(result *ast.SourceFile, isDeclarationFile bool) {
result.CommentDirectives = p.scanner.CommentDirectives()
result.Pragmas = getCommentPragmas(&p.factory, p.sourceText)
p.processPragmasIntoFields(result)
result.SetDiagnostics(attachFileToDiagnostics(p.diagnostics, result))
result.ExternalModuleIndicator = isFileProbablyExternalModule(result) // !!!
result.IsDeclarationFile = isDeclarationFile
result.LanguageVersion = p.languageVersion
result.LanguageVariant = p.languageVariant
result.ScriptKind = p.scriptKind
result.Flags |= p.sourceFlags
result.Identifiers = p.identifiers
result.NodeCount = p.factory.NodeCount()
result.TextCount = p.factory.TextCount()
result.IdentifierCount = p.identifierCount
result.SetJSDocCache(p.jsdocCache)
p.jsdocCache = nil
p.identifiers = nil
}
func (p *Parser) parseToplevelStatement(i int) *ast.Node {
p.statementHasAwaitIdentifier = false
statement := p.parseStatement()
if p.statementHasAwaitIdentifier && statement.Flags&ast.NodeFlagsAwaitContext == 0 {
if len(p.possibleAwaitSpans) == 0 || p.possibleAwaitSpans[len(p.possibleAwaitSpans)-1] != i {
p.possibleAwaitSpans = append(p.possibleAwaitSpans, i, i+1)
} else {
p.possibleAwaitSpans[len(p.possibleAwaitSpans)-1] = i + 1
}
}
return statement
}
func (p *Parser) reparseTopLevelAwait(sourceFile *ast.SourceFile) *ast.Node {
if len(p.possibleAwaitSpans)%2 == 1 {
panic("possibleAwaitSpans malformed: odd number of indices, not paired into spans.")
}
statements := []*ast.Statement{}
savedParseDiagnostics := p.diagnostics
p.diagnostics = []*ast.Diagnostic{}
afterAwaitStatement := 0
for i := 0; i < len(p.possibleAwaitSpans); i += 2 {
nextAwaitStatement := p.possibleAwaitSpans[i]
// append all non-await statements between afterAwaitStatement and nextAwaitStatement
prevStatement := sourceFile.Statements.Nodes[afterAwaitStatement]
nextStatement := sourceFile.Statements.Nodes[nextAwaitStatement]
statements = append(statements, sourceFile.Statements.Nodes[afterAwaitStatement:nextAwaitStatement]...)
// append all diagnostics associated with the copied range
diagnosticStart := core.FindIndex(savedParseDiagnostics, func(diagnostic *ast.Diagnostic) bool {
return diagnostic.Pos() >= prevStatement.Pos()
})
var diagnosticEnd int
if diagnosticStart >= 0 {
diagnosticEnd = core.FindIndex(savedParseDiagnostics[:diagnosticStart], func(diagnostic *ast.Diagnostic) bool {
return diagnostic.Pos() >= nextStatement.Pos()
})
} else {
diagnosticEnd = -1
}
if diagnosticStart >= 0 {
var slice []*ast.Diagnostic
if diagnosticEnd >= 0 {
slice = savedParseDiagnostics[diagnosticStart : diagnosticStart+diagnosticEnd]
} else {
slice = savedParseDiagnostics[diagnosticStart:]
}
p.diagnostics = append(p.diagnostics, slice...)
}
state := p.mark()
// reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones.
p.contextFlags |= ast.NodeFlagsAwaitContext
p.scanner.ResetPos(nextStatement.Pos())
p.nextToken()
afterAwaitStatement = p.possibleAwaitSpans[i+1]
for p.token != ast.KindEndOfFile {
startPos := p.scanner.TokenFullStart()
statement := p.parseStatement()
statements = append(statements, statement)
if startPos == p.scanner.TokenFullStart() {
p.nextToken()
}
if afterAwaitStatement < len(sourceFile.Statements.Nodes) {
nonAwaitStatement := sourceFile.Statements.Nodes[afterAwaitStatement]
if statement.End() == nonAwaitStatement.Pos() {
// done reparsing this section
break
}
if statement.End() > nonAwaitStatement.Pos() {
// we ate into the next statement, so we must continue reparsing the next span
i += 2
if i < len(p.possibleAwaitSpans) {
afterAwaitStatement = p.possibleAwaitSpans[i+1]
} else {
afterAwaitStatement = len(sourceFile.Statements.Nodes)
}
}
}
}
// Keep diagnostics from the reparse
state.diagnosticsLen = len(p.diagnostics)
p.rewind(state)
}
// append all statements between pos and the end of the list
if afterAwaitStatement < len(sourceFile.Statements.Nodes) {
prevStatement := sourceFile.Statements.Nodes[afterAwaitStatement]
statements = append(statements, sourceFile.Statements.Nodes[afterAwaitStatement:]...)
// append all diagnostics associated with the copied range
diagnosticStart := core.FindIndex(savedParseDiagnostics, func(diagnostic *ast.Diagnostic) bool {
return diagnostic.Pos() >= prevStatement.Pos()
})
if diagnosticStart >= 0 {
p.diagnostics = append(p.diagnostics, savedParseDiagnostics[diagnosticStart:]...)
}
}
return p.factory.NewSourceFile(sourceFile.Text(), sourceFile.FileName(), sourceFile.Path(), p.newNodeList(sourceFile.Statements.Loc, statements))
}
func (p *Parser) parseListIndex(kind ParsingContext, parseElement func(p *Parser, index int) *ast.Node) *ast.NodeList {
pos := p.nodePos()
saveParsingContexts := p.parsingContexts
p.parsingContexts |= 1 << kind
list := make([]*ast.Node, 0, 16)
for i := 0; !p.isListTerminator(kind); i++ {
if p.isListElement(kind, false /*inErrorRecovery*/) {
elt := parseElement(p, i)
if len(p.reparseList) > 0 {
list = append(list, p.reparseList...)
p.reparseList = nil
}
list = append(list, elt)
continue
}
if p.abortParsingListOrMoveToNextToken(kind) {
break
}
}
p.parsingContexts = saveParsingContexts
slice := p.nodeSlicePool.NewSlice(len(list))
copy(slice, list)
return p.newNodeList(core.NewTextRange(pos, p.nodePos()), slice)
}
func (p *Parser) parseList(kind ParsingContext, parseElement func(p *Parser) *ast.Node) *ast.NodeList {
return p.parseListIndex(kind, func(p *Parser, _ int) *ast.Node { return parseElement(p) })
}
// Return a non-nil (but possibly empty) slice if parsing was successful, or nil if parseElement returned nil
func (p *Parser) parseDelimitedList(kind ParsingContext, parseElement func(p *Parser) *ast.Node) *ast.NodeList {
pos := p.nodePos()
saveParsingContexts := p.parsingContexts
p.parsingContexts |= 1 << kind
list := make([]*ast.Node, 0, 16)
for {
if p.isListElement(kind, false /*inErrorRecovery*/) {
startPos := p.nodePos()
element := parseElement(p)
if element == nil {
p.parsingContexts = saveParsingContexts
// Return nil to indicate parseElement failed
return nil
}
list = append(list, element)
if p.parseOptional(ast.KindCommaToken) {
// No need to check for a zero length node since we know we parsed a comma
continue
}
if p.isListTerminator(kind) {
break
}
// We didn't get a comma, and the list wasn't terminated, explicitly parse
// out a comma so we give a good error message.
if p.token != ast.KindCommaToken && kind == PCEnumMembers {
p.parseErrorAtCurrentToken(diagnostics.An_enum_member_name_must_be_followed_by_a_or)
} else {
p.parseExpected(ast.KindCommaToken)
}
// If the token was a semicolon, and the caller allows that, then skip it and
// continue. This ensures we get back on track and don't result in tons of
// parse errors. For example, this can happen when people do things like use
// a semicolon to delimit object literal members. Note: we'll have already
// reported an error when we called parseExpected above.
if (kind == PCObjectLiteralMembers || kind == PCImportAttributes) && p.token == ast.KindSemicolonToken && !p.hasPrecedingLineBreak() {
p.nextToken()
}
if startPos == p.nodePos() {
// What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
// Consume a token to advance the parser in some way and avoid an infinite loop
// This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
// or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
p.nextToken()
}
continue
}
if p.isListTerminator(kind) {
break
}
if p.abortParsingListOrMoveToNextToken(kind) {
break
}
}
p.parsingContexts = saveParsingContexts
slice := p.nodeSlicePool.NewSlice(len(list))
copy(slice, list)
return p.newNodeList(core.NewTextRange(pos, p.nodePos()), slice)
}
// Return a non-nil (but possibly empty) NodeList if parsing was successful, or nil if opening token wasn't found
// or parseElement returned nil.
func (p *Parser) parseBracketedList(kind ParsingContext, parseElement func(p *Parser) *ast.Node, opening ast.Kind, closing ast.Kind) *ast.NodeList {
if p.parseExpected(opening) {
result := p.parseDelimitedList(kind, parseElement)
p.parseExpected(closing)
return result
}
return p.parseEmptyNodeList()
}
func (p *Parser) parseEmptyNodeList() *ast.NodeList {
return p.newNodeList(core.NewTextRange(p.nodePos(), p.nodePos()), nil)
}
// Returns true if we should abort parsing.
func (p *Parser) abortParsingListOrMoveToNextToken(kind ParsingContext) bool {
p.parsingContextErrors(kind)
if p.isInSomeParsingContext() {
return true
}
p.nextToken()
return false
}
// True if positioned at element or terminator of the current list or any enclosing list
func (p *Parser) isInSomeParsingContext() bool {
// We should be in at least one parsing context, be it SourceElements while parsing
// a SourceFile, or JSDocComment when lazily parsing JSDoc.
// Debug.assert(parsingContext, "Missing parsing context")
for kind := ParsingContext(0); kind < PCCount; kind++ {
if p.parsingContexts&(1<<kind) != 0 {
if p.isListElement(kind, true /*inErrorRecovery*/) || p.isListTerminator(kind) {
return true
}
}
}
return false
}
func (p *Parser) parsingContextErrors(context ParsingContext) {
switch context {
case PCSourceElements:
if p.token == ast.KindDefaultKeyword {
p.parseErrorAtCurrentToken(diagnostics.X_0_expected, "export")
} else {
p.parseErrorAtCurrentToken(diagnostics.Declaration_or_statement_expected)
}
case PCBlockStatements:
p.parseErrorAtCurrentToken(diagnostics.Declaration_or_statement_expected)
case PCSwitchClauses:
p.parseErrorAtCurrentToken(diagnostics.X_case_or_default_expected)
case PCSwitchClauseStatements:
p.parseErrorAtCurrentToken(diagnostics.Statement_expected)
case PCRestProperties, PCTypeMembers:
p.parseErrorAtCurrentToken(diagnostics.Property_or_signature_expected)
case PCClassMembers:
p.parseErrorAtCurrentToken(diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected)
case PCEnumMembers:
p.parseErrorAtCurrentToken(diagnostics.Enum_member_expected)
case PCHeritageClauseElement:
p.parseErrorAtCurrentToken(diagnostics.Expression_expected)
case PCVariableDeclarations:
if isKeyword(p.token) {
p.parseErrorAtCurrentToken(diagnostics.X_0_is_not_allowed_as_a_variable_declaration_name, scanner.TokenToString(p.token))
} else {
p.parseErrorAtCurrentToken(diagnostics.Variable_declaration_expected)
}
case PCObjectBindingElements:
p.parseErrorAtCurrentToken(diagnostics.Property_destructuring_pattern_expected)
case PCArrayBindingElements:
p.parseErrorAtCurrentToken(diagnostics.Array_element_destructuring_pattern_expected)
case PCArgumentExpressions:
p.parseErrorAtCurrentToken(diagnostics.Argument_expression_expected)
case PCObjectLiteralMembers:
p.parseErrorAtCurrentToken(diagnostics.Property_assignment_expected)
case PCArrayLiteralMembers:
p.parseErrorAtCurrentToken(diagnostics.Expression_or_comma_expected)
case PCJSDocParameters:
p.parseErrorAtCurrentToken(diagnostics.Parameter_declaration_expected)
case PCParameters:
if isKeyword(p.token) {
p.parseErrorAtCurrentToken(diagnostics.X_0_is_not_allowed_as_a_parameter_name, scanner.TokenToString(p.token))
} else {
p.parseErrorAtCurrentToken(diagnostics.Parameter_declaration_expected)
}
case PCTypeParameters:
p.parseErrorAtCurrentToken(diagnostics.Type_parameter_declaration_expected)
case PCTypeArguments:
p.parseErrorAtCurrentToken(diagnostics.Type_argument_expected)
case PCTupleElementTypes:
p.parseErrorAtCurrentToken(diagnostics.Type_expected)
case PCHeritageClauses:
p.parseErrorAtCurrentToken(diagnostics.Unexpected_token_expected)
case PCImportOrExportSpecifiers:
if p.token == ast.KindFromKeyword {
p.parseErrorAtCurrentToken(diagnostics.X_0_expected, "}")
} else {
p.parseErrorAtCurrentToken(diagnostics.Identifier_expected)
}
case PCJsxAttributes, PCJsxChildren, PCJSDocComment:
p.parseErrorAtCurrentToken(diagnostics.Identifier_expected)
case PCImportAttributes:
p.parseErrorAtCurrentToken(diagnostics.Identifier_or_string_literal_expected)
default:
panic("Unhandled case in parsingContextErrors")
}
}
func (p *Parser) isListElement(parsingContext ParsingContext, inErrorRecovery bool) bool {
switch parsingContext {
case PCSourceElements, PCBlockStatements, PCSwitchClauseStatements:
// If we're in error recovery, then we don't want to treat ';' as an empty statement.
// The problem is that ';' can show up in far too many contexts, and if we see one
// and assume it's a statement, then we may bail out inappropriately from whatever
// we're parsing. For example, if we have a semicolon in the middle of a class, then
// we really don't want to assume the class is over and we're on a statement in the
// outer module. We just want to consume and move on.
return !(p.token == ast.KindSemicolonToken && inErrorRecovery) && p.isStartOfStatement()
case PCSwitchClauses:
return p.token == ast.KindCaseKeyword || p.token == ast.KindDefaultKeyword
case PCTypeMembers:
return p.lookAhead((*Parser).scanTypeMemberStart)
case PCClassMembers:
// We allow semicolons as class elements (as specified by ES6) as long as we're
// not in error recovery. If we're in error recovery, we don't want an errant
// semicolon to be treated as a class member (since they're almost always used
// for statements.
return p.lookAhead((*Parser).scanClassMemberStart) || p.token == ast.KindSemicolonToken && !inErrorRecovery
case PCEnumMembers:
// Include open bracket computed properties. This technically also lets in indexers,
// which would be a candidate for improved error reporting.
return p.token == ast.KindOpenBracketToken || p.isLiteralPropertyName()
case PCObjectLiteralMembers:
switch p.token {
case ast.KindOpenBracketToken, ast.KindAsteriskToken, ast.KindDotDotDotToken, ast.KindDotToken: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
return true
default:
return p.isLiteralPropertyName()
}
case PCRestProperties:
return p.isLiteralPropertyName()
case PCObjectBindingElements:
return p.token == ast.KindOpenBracketToken || p.token == ast.KindDotDotDotToken || p.isLiteralPropertyName()
case PCImportAttributes:
return p.isImportAttributeName()
case PCHeritageClauseElement:
// If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
// That way we won't consume the body of a class in its heritage clause.
if p.token == ast.KindOpenBraceToken {
return p.isValidHeritageClauseObjectLiteral()
}
if !inErrorRecovery {
return p.isStartOfLeftHandSideExpression() && !p.isHeritageClauseExtendsOrImplementsKeyword()
}
// If we're in error recovery we tighten up what we're willing to match.
// That way we don't treat something like "this" as a valid heritage clause
// element during recovery.
return p.isIdentifier() && !p.isHeritageClauseExtendsOrImplementsKeyword()
case PCVariableDeclarations:
return p.isBindingIdentifierOrPrivateIdentifierOrPattern()
case PCArrayBindingElements:
return p.token == ast.KindCommaToken || p.token == ast.KindDotDotDotToken || p.isBindingIdentifierOrPrivateIdentifierOrPattern()
case PCTypeParameters:
return p.token == ast.KindInKeyword || p.token == ast.KindConstKeyword || p.isIdentifier()
case PCArrayLiteralMembers:
// Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
if p.token == ast.KindCommaToken || p.token == ast.KindDotToken {
return true
}
fallthrough
case PCArgumentExpressions:
return p.token == ast.KindDotDotDotToken || p.isStartOfExpression()
case PCParameters:
return p.isStartOfParameter(false /*isJSDocParameter*/)
case PCJSDocParameters:
return p.isStartOfParameter(true /*isJSDocParameter*/)
case PCTypeArguments, PCTupleElementTypes:
return p.token == ast.KindCommaToken || p.isStartOfType(false /*inStartOfParameter*/)
case PCHeritageClauses:
return p.isHeritageClause()
case PCImportOrExportSpecifiers:
// bail out if the next token is [FromKeyword StringLiteral].
// That means we're in something like `import { from "mod"`. Stop here can give better error message.
if p.token == ast.KindFromKeyword && p.lookAhead((*Parser).nextTokenIsTokenStringLiteral) {
return false
}
if p.token == ast.KindStringLiteral {
return true // For "arbitrary module namespace identifiers"
}
return tokenIsIdentifierOrKeyword(p.token)
case PCJsxAttributes:
return tokenIsIdentifierOrKeyword(p.token) || p.token == ast.KindOpenBraceToken
case PCJsxChildren:
return true
case PCJSDocComment:
return true
}
panic("Unhandled case in isListElement")
}
func (p *Parser) isListTerminator(kind ParsingContext) bool {
if p.token == ast.KindEndOfFile {
return true
}
switch kind {
case PCBlockStatements, PCSwitchClauses, PCTypeMembers, PCClassMembers, PCEnumMembers, PCObjectLiteralMembers,
PCObjectBindingElements, PCImportOrExportSpecifiers, PCImportAttributes:
return p.token == ast.KindCloseBraceToken
case PCSwitchClauseStatements:
return p.token == ast.KindCloseBraceToken || p.token == ast.KindCaseKeyword || p.token == ast.KindDefaultKeyword
case PCHeritageClauseElement:
return p.token == ast.KindOpenBraceToken || p.token == ast.KindExtendsKeyword || p.token == ast.KindImplementsKeyword
case PCVariableDeclarations:
// If we can consume a semicolon (either explicitly, or with ASI), then consider us done
// with parsing the list of variable declarators.
// In the case where we're parsing the variable declarator of a 'for-in' statement, we
// are done if we see an 'in' keyword in front of us. Same with for-of
// ERROR RECOVERY TWEAK:
// For better error recovery, if we see an '=>' then we just stop immediately. We've got an
// arrow function here and it's going to be very unlikely that we'll resynchronize and get
// another variable declaration.
return p.canParseSemicolon() || p.token == ast.KindInKeyword || p.token == ast.KindOfKeyword || p.token == ast.KindEqualsGreaterThanToken
case PCTypeParameters:
// Tokens other than '>' are here for better error recovery
return p.token == ast.KindGreaterThanToken || p.token == ast.KindOpenParenToken || p.token == ast.KindOpenBraceToken || p.token == ast.KindExtendsKeyword || p.token == ast.KindImplementsKeyword
case PCArgumentExpressions:
// Tokens other than ')' are here for better error recovery
return p.token == ast.KindCloseParenToken || p.token == ast.KindSemicolonToken
case PCArrayLiteralMembers, PCTupleElementTypes, PCArrayBindingElements:
return p.token == ast.KindCloseBracketToken
case PCJSDocParameters, PCParameters, PCRestProperties:
// Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
return p.token == ast.KindCloseParenToken || p.token == ast.KindCloseBracketToken /*|| token == ast.KindOpenBraceToken*/
case PCTypeArguments:
// All other tokens should cause the type-argument to terminate except comma token
return p.token != ast.KindCommaToken
case PCHeritageClauses:
return p.token == ast.KindOpenBraceToken || p.token == ast.KindCloseBraceToken
case PCJsxAttributes:
return p.token == ast.KindGreaterThanToken || p.token == ast.KindSlashToken
case PCJsxChildren:
return p.token == ast.KindLessThanToken && p.lookAhead((*Parser).nextTokenIsSlash)
}
return false
}
func (p *Parser) parseExpectedJSDoc(kind ast.Kind) bool {
if p.token == kind {
p.nextTokenJSDoc()
return true
}
if !isKeywordOrPunctuation(kind) {
panic("Invalid JSDoc kind: expected keyword or punctuation")
}
p.parseErrorAtCurrentToken(diagnostics.X_0_expected, scanner.TokenToString(kind))
return false
}
func (p *Parser) parseExpectedMatchingBrackets(openKind ast.Kind, closeKind ast.Kind, openParsed bool, openPosition int) {
if p.token == closeKind {
p.nextToken()
return
}
lastError := p.parseErrorAtCurrentToken(diagnostics.X_0_expected, scanner.TokenToString(closeKind))
if !openParsed {
return
}
if lastError != nil {
related := ast.NewDiagnostic(nil, core.NewTextRange(openPosition, openPosition+1), diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, scanner.TokenToString(openKind), scanner.TokenToString(closeKind))
lastError.AddRelatedInfo(related)
}
}
func (p *Parser) parseOptional(token ast.Kind) bool {
if p.token == token {
p.nextToken()
return true
}
return false
}
func (p *Parser) parseExpected(kind ast.Kind) bool {
return p.parseExpectedWithDiagnostic(kind, nil, true)
}
func (p *Parser) parseExpectedWithoutAdvancing(kind ast.Kind) bool {
return p.parseExpectedWithDiagnostic(kind, nil, false)
}
func (p *Parser) parseExpectedWithDiagnostic(kind ast.Kind, message *diagnostics.Message, shouldAdvance bool) bool {
if p.token == kind {
if shouldAdvance {
p.nextToken()
}
return true
}
// Report specific message if provided with one. Otherwise, report generic fallback message.
if message != nil {
p.parseErrorAtCurrentToken(message)
} else {
p.parseErrorAtCurrentToken(diagnostics.X_0_expected, scanner.TokenToString(kind))
}
return false
}
func (p *Parser) parseTokenNode() *ast.Node {
pos := p.nodePos()
kind := p.token
p.nextToken()
result := p.factory.NewToken(kind)
p.finishNode(result, pos)
return result
}
func (p *Parser) parseExpectedToken(kind ast.Kind) *ast.Node {
token := p.parseOptionalToken(kind)
if token == nil {
p.parseErrorAtCurrentToken(diagnostics.X_0_expected, scanner.TokenToString(kind))
token = p.factory.NewToken(kind)
p.finishNode(token, p.nodePos())
}
return token
}
func (p *Parser) parseOptionalToken(kind ast.Kind) *ast.Node {
if p.token == kind {
return p.parseTokenNode()
}
return nil
}
func (p *Parser) parseExpectedTokenJSDoc(kind ast.Kind) *ast.Node {
optional := p.parseOptionalTokenJSDoc(kind)
if optional == nil {
if !isKeywordOrPunctuation(kind) {
panic("expected keyword or punctuation")
}
p.parseErrorAtCurrentToken(diagnostics.X_0_expected, scanner.TokenToString(kind))
optional = p.factory.NewToken(kind)
p.finishNode(optional, p.nodePos())
}
return optional
}
func (p *Parser) parseOptionalTokenJSDoc(kind ast.Kind) *ast.Node {
if p.token == kind {
return p.parseTokenNode()
}
return nil
}
func (p *Parser) parseStatement() *ast.Statement {
switch p.token {
case ast.KindSemicolonToken:
return p.parseEmptyStatement()
case ast.KindOpenBraceToken:
return p.parseBlock(false /*ignoreMissingOpenBrace*/, nil)
case ast.KindVarKeyword:
return p.parseVariableStatement(p.nodePos(), p.hasPrecedingJSDocComment(), nil /*modifiers*/)
case ast.KindLetKeyword:
if p.isLetDeclaration() {
return p.parseVariableStatement(p.nodePos(), p.hasPrecedingJSDocComment(), nil /*modifiers*/)
}
case ast.KindAwaitKeyword:
if p.isAwaitUsingDeclaration() {
return p.parseVariableStatement(p.nodePos(), p.hasPrecedingJSDocComment(), nil /*modifiers*/)
}
case ast.KindUsingKeyword:
if p.isUsingDeclaration() {
return p.parseVariableStatement(p.nodePos(), p.hasPrecedingJSDocComment(), nil /*modifiers*/)
}
case ast.KindFunctionKeyword:
return p.parseFunctionDeclaration(p.nodePos(), p.hasPrecedingJSDocComment(), nil /*modifiers*/)
case ast.KindClassKeyword:
return p.parseClassDeclaration(p.nodePos(), p.hasPrecedingJSDocComment(), nil /*modifiers*/)
case ast.KindIfKeyword:
return p.parseIfStatement()
case ast.KindDoKeyword:
return p.parseDoStatement()
case ast.KindWhileKeyword:
return p.parseWhileStatement()
case ast.KindForKeyword:
return p.parseForOrForInOrForOfStatement()
case ast.KindContinueKeyword:
return p.parseContinueStatement()
case ast.KindBreakKeyword:
return p.parseBreakStatement()
case ast.KindReturnKeyword:
return p.parseReturnStatement()
case ast.KindWithKeyword:
return p.parseWithStatement()
case ast.KindSwitchKeyword:
return p.parseSwitchStatement()
case ast.KindThrowKeyword:
return p.parseThrowStatement()
case ast.KindTryKeyword, ast.KindCatchKeyword, ast.KindFinallyKeyword:
return p.parseTryStatement()
case ast.KindDebuggerKeyword:
return p.parseDebuggerStatement()
case ast.KindAtToken:
return p.parseDeclaration()
case ast.KindAsyncKeyword, ast.KindInterfaceKeyword, ast.KindTypeKeyword, ast.KindModuleKeyword, ast.KindNamespaceKeyword,
ast.KindDeclareKeyword, ast.KindConstKeyword, ast.KindEnumKeyword, ast.KindExportKeyword, ast.KindImportKeyword,
ast.KindPrivateKeyword, ast.KindProtectedKeyword, ast.KindPublicKeyword, ast.KindAbstractKeyword, ast.KindAccessorKeyword,
ast.KindStaticKeyword, ast.KindReadonlyKeyword, ast.KindGlobalKeyword:
if p.isStartOfDeclaration() {
return p.parseDeclaration()
}
}
return p.parseExpressionOrLabeledStatement()
}
func (p *Parser) parseDeclaration() *ast.Statement {
// `parseListElement` attempted to get the reused node at this position,
// but the ambient context flag was not yet set, so the node appeared
// not reusable in that context.
pos := p.nodePos()
hasJSDoc := p.hasPrecedingJSDocComment()
modifiers := p.parseModifiersEx( /*allowDecorators*/ true, false /*permitConstAsModifier*/, false /*stopOnStartOfClassStaticBlock*/)
isAmbient := modifiers != nil && core.Some(modifiers.Nodes, isDeclareModifier)
if isAmbient {
// !!! incremental parsing
// node := p.tryReuseAmbientDeclaration(pos)
// if node {
// return node
// }
for _, m := range modifiers.Nodes {
m.Flags |= ast.NodeFlagsAmbient
}
saveContextFlags := p.contextFlags
p.setContextFlags(ast.NodeFlagsAmbient, true)
result := p.parseDeclarationWorker(pos, hasJSDoc, modifiers)
p.contextFlags = saveContextFlags
return result
} else {
return p.parseDeclarationWorker(pos, hasJSDoc, modifiers)
}
}
func (p *Parser) parseDeclarationWorker(pos int, hasJSDoc bool, modifiers *ast.ModifierList) *ast.Statement {
switch p.token {
case ast.KindVarKeyword, ast.KindLetKeyword, ast.KindConstKeyword, ast.KindUsingKeyword, ast.KindAwaitKeyword:
return p.parseVariableStatement(pos, hasJSDoc, modifiers)