-
Notifications
You must be signed in to change notification settings - Fork 123
/
Parser.cs
2322 lines (1955 loc) · 107 KB
/
Parser.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Jurassic.Compiler
{
/// <summary>
/// Converts a series of tokens into an abstract syntax tree.
/// </summary>
internal sealed class Parser
{
private Lexer lexer;
private SourceCodePosition positionBeforeWhitespace, positionAfterWhitespace;
private Token nextToken;
private bool consumedLineTerminator;
private ParserExpressionState expressionState;
private Scope initialScope;
private Scope currentScope;
private MethodOptimizationHints methodOptimizationHints;
private List<string> labelsForCurrentStatement = new List<string>();
private Token endToken;
private CompilerOptions options;
private CodeContext context;
private bool strictMode;
// INITIALIZATION
//_________________________________________________________________________________________
/// <summary>
/// Creates a Parser instance with the given lexer supplying the tokens.
/// </summary>
/// <param name="lexer"> The lexical analyser that provides the tokens. </param>
/// <param name="options"> Options that influence the compiler. </param>
/// <param name="scope"> The initial scope. </param>
/// <param name="context"> The context of the code (global, function or eval). </param>
/// <param name="methodOptimizationHints"> Hints about whether optimization is possible. </param>
public Parser(Lexer lexer, CompilerOptions options, Scope scope, CodeContext context, MethodOptimizationHints methodOptimizationHints = null)
{
this.lexer = lexer ?? throw new ArgumentNullException(nameof(lexer));
this.lexer.ParserExpressionState = ParserExpressionState.Literal;
this.lexer.CompatibilityMode = options.CompatibilityMode;
SetInitialScope(scope);
this.methodOptimizationHints = methodOptimizationHints ?? new MethodOptimizationHints();
this.options = options;
this.context = context;
this.StrictMode = options.ForceStrictMode;
this.Consume();
}
/// <summary>
/// Creates a parser that can read the body of a function.
/// </summary>
/// <param name="parser"> The parser for the parent context. </param>
/// <param name="scope"> The function scope. </param>
/// <param name="optimizationHints"> Hints about whether optimization is possible. </param>
/// <param name="codeContext"> Indicates the parsing context. </param>
/// <returns> A new parser. </returns>
private static Parser CreateFunctionBodyParser(Parser parser, Scope scope, MethodOptimizationHints optimizationHints, CodeContext codeContext)
{
var result = (Parser)parser.MemberwiseClone();
result.SetInitialScope(scope);
result.methodOptimizationHints = optimizationHints;
result.context = codeContext;
result.endToken = PunctuatorToken.RightBrace;
return result;
}
// PROPERTIES
//_________________________________________________________________________________________
/// <summary>
/// Gets the line number of the next token.
/// </summary>
public int LineNumber
{
get { return this.positionAfterWhitespace.Line; }
}
/// <summary>
/// Gets the position just after the last character of the previously consumed token.
/// </summary>
public SourceCodePosition PositionBeforeWhitespace
{
get { return this.positionBeforeWhitespace; }
}
/// <summary>
/// Gets the position of the first character of the next token.
/// </summary>
public SourceCodePosition PositionAfterWhitespace
{
get { return this.positionAfterWhitespace; }
}
/// <summary>
/// Gets the path or URL of the source file. Can be <c>null</c>.
/// </summary>
public string SourcePath
{
get { return this.lexer.Source.Path; }
}
/// <summary>
/// Gets or sets a value that indicates whether the parser is operating in strict mode.
/// </summary>
public bool StrictMode
{
get { return this.strictMode; }
set
{
this.strictMode = value;
this.lexer.StrictMode = value;
}
}
/// <summary>
/// The top-level scope.
/// </summary>
public Scope BaseScope
{
get { return this.initialScope; }
}
/// <summary>
/// Gets optimization information about the code that was parsed (Parse() must be called
/// first).
/// </summary>
public MethodOptimizationHints MethodOptimizationHints
{
get { return this.methodOptimizationHints; }
}
/// <summary>
/// Indicates whether we are parsing in a function context (including constructors and class functions).
/// </summary>
public bool IsInFunctionContext
{
get { return this.context == CodeContext.Function ||
this.context == CodeContext.ObjectLiteralFunction ||
this.context == CodeContext.ClassFunction ||
this.context == CodeContext.Constructor ||
this.context == CodeContext.DerivedConstructor; }
}
// VARIABLES
//_________________________________________________________________________________________
/// <summary>
/// Throws an exception if the variable name is invalid.
/// </summary>
/// <param name="name"> The name of the variable to check. </param>
private void ValidateVariableName(string name)
{
// In strict mode, the variable name cannot be "eval" or "arguments".
if (this.StrictMode == true && (name == "eval" || name == "arguments"))
throw new SyntaxErrorException(string.Format("The variable name cannot be '{0}' in strict mode.", name), this.LineNumber, this.SourcePath);
// Record each occurance of a variable name.
this.methodOptimizationHints.EncounteredVariable(name);
}
// TOKEN HELPERS
//_________________________________________________________________________________________
/// <summary>
/// Discards the current token and reads the next one.
/// </summary>
/// <param name="expressionState"> Indicates whether the next token can be a literal or an
/// operator. </param>
private void Consume(ParserExpressionState expressionState = ParserExpressionState.Literal)
{
this.expressionState = expressionState;
this.lexer.ParserExpressionState = expressionState;
this.consumedLineTerminator = false;
this.positionBeforeWhitespace = new SourceCodePosition(this.lexer.LineNumber, this.lexer.ColumnNumber);
this.positionAfterWhitespace = this.positionBeforeWhitespace;
while (true)
{
if (expressionState == ParserExpressionState.TemplateContinuation)
this.nextToken = this.lexer.ReadStringLiteral('`');
else
this.nextToken = this.lexer.NextToken();
if ((this.nextToken is WhiteSpaceToken) == false)
break;
if (((WhiteSpaceToken)this.nextToken).LineTerminatorCount > 0)
this.consumedLineTerminator = true;
this.positionAfterWhitespace = new SourceCodePosition(this.lexer.LineNumber, this.lexer.ColumnNumber);
}
}
/// <summary>
/// Indicates that the next token is identical to the given one. Throws an exception if
/// this is not the case. Consumes the token.
/// </summary>
/// <param name="token"> The expected token. </param>
private void Expect(Token token)
{
if (this.nextToken == token)
Consume();
else
throw new SyntaxErrorException(string.Format("Expected '{0}' but found {1}", token.Text, Token.ToText(this.nextToken)), this.LineNumber, this.SourcePath);
}
/// <summary>
/// Indicates that the next token should be an identifier. Throws an exception if this is
/// not the case. Consumes the token.
/// </summary>
/// <returns> The identifier name. </returns>
private string ExpectIdentifier()
{
var token = this.nextToken;
if (token is IdentifierToken)
{
Consume();
return ((IdentifierToken)token).Name;
}
else
{
throw new SyntaxErrorException(string.Format("Expected identifier but found {0}", Token.ToText(this.nextToken)), this.LineNumber, this.SourcePath);
}
}
/// <summary>
/// Returns a value that indicates whether the current position is a valid position to end
/// a statement.
/// </summary>
/// <returns> <c>true</c> if the current position is a valid position to end a statement;
/// <c>false</c> otherwise. </returns>
private bool AtValidEndOfStatement()
{
// A statement can be terminator in four ways: by a semi-colon (;), by a right brace (}),
// by the end of a line or by the end of the program.
return this.nextToken == PunctuatorToken.Semicolon ||
this.nextToken == PunctuatorToken.RightBrace ||
this.consumedLineTerminator == true ||
this.nextToken == null;
}
/// <summary>
/// Indicates that the next token should end the current statement. This implies that the
/// next token is a semicolon, right brace or a line terminator.
/// </summary>
private void ExpectEndOfStatement()
{
if (this.nextToken == PunctuatorToken.Semicolon)
Consume();
else
{
// Automatic semi-colon insertion.
// If an illegal token is found then a semicolon is automatically inserted before
// the offending token if one or more of the following conditions is true:
// 1. The offending token is separated from the previous token by at least one LineTerminator.
// 2. The offending token is '}'.
if (this.consumedLineTerminator == true || this.nextToken == PunctuatorToken.RightBrace)
return;
// If the end of the input stream of tokens is encountered and the parser is unable
// to parse the input token stream as a single complete ECMAScript Program, then a
// semicolon is automatically inserted at the end of the input stream.
if (this.nextToken == null)
return;
// Otherwise, throw an error.
throw new SyntaxErrorException(string.Format("Expected ';' but found {0}", Token.ToText(this.nextToken)), this.LineNumber, this.SourcePath);
}
}
// SCOPE HELPERS
//_________________________________________________________________________________________
/// <summary>
/// Sets the initial scope.
/// </summary>
/// <param name="initialScope"> The initial scope </param>
private void SetInitialScope(Scope initialScope)
{
if (initialScope == null)
throw new ArgumentNullException(nameof(initialScope));
this.currentScope = this.initialScope = initialScope;
}
/// <summary>
/// Helper class to help manage scopes.
/// </summary>
private class ScopeContext : IDisposable
{
private readonly Parser parser;
private readonly Scope previousScope;
public ScopeContext(Parser parser)
{
this.parser = parser;
previousScope = parser.currentScope;
}
public void Dispose()
{
parser.currentScope = previousScope;
}
}
/// <summary>
/// Sets the current scope and returns an object which can be disposed to restore the
/// previous scope.
/// </summary>
/// <param name="scope"> The new scope. </param>
/// <returns> An object which can be disposed to restore the previous scope. </returns>
private ScopeContext CreateScopeContext(Scope scope)
{
var result = new ScopeContext(this);
this.currentScope = scope ?? throw new ArgumentNullException(nameof(scope));
return result;
}
// PARSE METHODS
//_________________________________________________________________________________________
/// <summary>
/// Parses javascript source code.
/// </summary>
/// <returns> An expression that can be executed to run the program represented by the
/// source code. </returns>
public Statement Parse()
{
// Read the directive prologue.
var result = new BlockStatement(new string[0], this.initialScope);
while (true)
{
// Check if we should stop parsing.
if (this.nextToken == this.endToken)
break;
// A directive must start with a string literal token. Record it now so that the
// escape sequence and line continuation information is not lost.
var directiveToken = this.nextToken as StringLiteralToken;
if (directiveToken == null)
break;
// Directives cannot have escape sequences or line continuations.
if (directiveToken.EscapeSequenceCount != 0 || directiveToken.LineContinuationCount != 0)
break;
// If the statement starts with a string literal, it must be an expression.
var beforeInitialToken = this.PositionAfterWhitespace;
var expression = ParseExpression(PunctuatorToken.Semicolon);
// The statement must be added to the AST so that eval("'test'") works.
var initialStatement = new ExpressionStatement(this.labelsForCurrentStatement, expression);
initialStatement.SourceSpan = new SourceCodeSpan(beforeInitialToken, this.PositionBeforeWhitespace);
result.Statements.Add(initialStatement);
// In order for the expression to be part of the directive prologue, it must
// consist solely of a string literal.
if ((expression is LiteralExpression) == false)
break;
// Strict mode directive.
if (directiveToken.Value == "use strict")
this.StrictMode = true;
// Read the end of the statement. This must happen last so that the lexer has a
// chance to act on the strict mode flag.
ExpectEndOfStatement();
}
// If this is an eval, and strict mode is on, redefine the scope.
if (this.StrictMode == true)
this.initialScope.ConvertToStrictMode();
// Read zero or more regular statements.
while (true)
{
// Check if we should stop parsing.
if (this.nextToken == this.endToken)
break;
// Parse a single statement.
result.Statements.Add(ParseStatement(addingToExistingBlock: true));
}
return result;
}
/// <summary>
/// Parses any statement other than a function declaration.
/// </summary>
/// <param name="addingToExistingBlock"> <c>true</c> if the statement is being added to an
/// existing block statement, <c>false</c> if the statement represents a new block. </param>
/// <returns> An expression that represents the statement. </returns>
private Statement ParseStatement(bool addingToExistingBlock)
{
// This is a new statement so clear any labels.
this.labelsForCurrentStatement.Clear();
// Parse the statement.
Statement statement = ParseStatementNoNewContext();
// Let and const statements are disallowed in single-statement contexts.
if (!addingToExistingBlock &&
statement is VarLetOrConstStatement varLetOrConstStatement &&
varLetOrConstStatement.Keyword != KeywordToken.Var)
throw new SyntaxErrorException("Lexical declaration cannot appear in a single-statement context.", this.LineNumber, this.SourcePath);
return statement;
}
/// <summary>
/// Parses any statement other than a function declaration, without beginning a new
/// statement context.
/// </summary>
/// <returns> An expression that represents the statement. </returns>
private Statement ParseStatementNoNewContext()
{
if (this.nextToken == PunctuatorToken.LeftBrace)
return ParseBlock();
if (this.nextToken == KeywordToken.Var || this.nextToken == KeywordToken.Let || this.nextToken == KeywordToken.Const)
return ParseVarLetOrConst((KeywordToken)this.nextToken);
if (this.nextToken == PunctuatorToken.Semicolon)
return ParseEmpty();
if (this.nextToken == KeywordToken.If)
return ParseIf();
if (this.nextToken == KeywordToken.Do)
return ParseDo();
if (this.nextToken == KeywordToken.While)
return ParseWhile();
if (this.nextToken == KeywordToken.For)
return ParseFor();
if (this.nextToken == KeywordToken.Continue)
return ParseContinue();
if (this.nextToken == KeywordToken.Break)
return ParseBreak();
if (this.nextToken == KeywordToken.Return)
return ParseReturn();
if (this.nextToken == KeywordToken.With)
return ParseWith();
if (this.nextToken == KeywordToken.Switch)
return ParseSwitch();
if (this.nextToken == KeywordToken.Throw)
return ParseThrow();
if (this.nextToken == KeywordToken.Try)
return ParseTry();
if (this.nextToken == KeywordToken.Debugger)
return ParseDebugger();
if (this.nextToken == KeywordToken.Function)
return ParseFunctionDeclaration();
if (this.nextToken == KeywordToken.Class)
return ParseClassDeclaration();
if (this.nextToken == null)
throw new SyntaxErrorException("Unexpected end of input", this.LineNumber, this.SourcePath);
// The statement is either a label or an expression.
return ParseLabelOrExpressionStatement();
}
/// <summary>
/// Parses a block of statements.
/// </summary>
/// <returns> A BlockStatement containing the statements. </returns>
/// <remarks> The value of a block statement is the value of the last statement in the block,
/// or undefined if there are no statements in the block. </remarks>
private BlockStatement ParseBlock()
{
var scope = Scope.CreateBlockScope(this.currentScope);
using (CreateScopeContext(scope))
{
// Consume the start brace ({).
this.Expect(PunctuatorToken.LeftBrace);
// Read zero or more statements.
var result = new BlockStatement(this.labelsForCurrentStatement, scope);
while (true)
{
// Check for the end brace (}).
if (this.nextToken == PunctuatorToken.RightBrace)
break;
// Parse a single statement.
result.Statements.Add(ParseStatement(addingToExistingBlock: true));
}
// Consume the end brace.
this.Expect(PunctuatorToken.RightBrace);
return result;
}
}
/// <summary>
/// Parses a var, let or const statement.
/// </summary>
/// <param name="keyword"> Indicates which type of statement is being parsed. Must be var,
/// let or const. </param>
/// <param name="consumeKeyword"> Indicates whether the keyword token needs to be consumed. </param>
/// <param name="insideForLoop"> Indicates whether we are parsing the initial declaration
/// inside a for() statement. </param>
/// <returns> A variable declaration statement. </returns>
private VarLetOrConstStatement ParseVarLetOrConst(KeywordToken keyword, bool consumeKeyword = true, bool insideForLoop = false)
{
var result = new VarLetOrConstStatement(this.labelsForCurrentStatement, this.currentScope);
result.Keyword = keyword;
// Read past the first token (var, let or const).
if (consumeKeyword)
this.Expect(keyword);
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// There can be multiple declarations.
while (true)
{
// The next token must be a variable name.
var declaration = new VariableDeclaration(keyword, ExpectIdentifier());
ValidateVariableName(declaration.VariableName);
if (keyword == KeywordToken.Let && declaration.VariableName == "let")
throw new SyntaxErrorException("'let' is not allowed here.", this.LineNumber, this.SourcePath);
// Add the variable to the current function's list of local variables.
if (keyword != KeywordToken.Var && this.currentScope.HasDeclaredVariable(declaration.VariableName))
throw new SyntaxErrorException($"Identifier '{declaration.VariableName}' has already been declared.", this.LineNumber, this.SourcePath);
this.currentScope.DeclareVariable(keyword, declaration.VariableName);
// The next token is either an equals sign (=), a semi-colon or a comma.
if (this.nextToken == PunctuatorToken.Assignment)
{
// Read past the equals token (=).
this.Expect(PunctuatorToken.Assignment);
// Read the setter expression.
declaration.InitExpression = ParseExpression(PunctuatorToken.Semicolon, PunctuatorToken.Comma);
}
// Record the portion of the source document that will be highlighted when debugging.
declaration.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
// Add the declaration to the result.
result.Declarations.Add(declaration);
// If we are inside a for loop, then 'in' and 'of' are valid terminators.
// Also, to match ParseExpression(), we don't consume the final semi-colon.
if (insideForLoop && (this.nextToken == KeywordToken.In || this.nextToken == IdentifierToken.Of ||
(this.AtValidEndOfStatement() == true && this.nextToken != PunctuatorToken.Comma)))
return result;
// const declarations must have an initializer, unless they are part of a
// for-of/for-in statement.
if (keyword == KeywordToken.Const && declaration.InitExpression == null)
throw new SyntaxErrorException("Missing initializer in const declaration.", this.LineNumber, this.SourcePath);
// Check if we are at the end of the statement.
if (this.AtValidEndOfStatement() == true && this.nextToken != PunctuatorToken.Comma)
break;
// Read past the comma token.
this.Expect(PunctuatorToken.Comma);
// Keep track of the start of the statement so that source debugging works correctly.
start = this.PositionAfterWhitespace;
}
// Consume the end of the statement.
this.ExpectEndOfStatement();
return result;
}
/// <summary>
/// Parses an empty statement.
/// </summary>
/// <returns> An empty statement. </returns>
private Statement ParseEmpty()
{
var result = new EmptyStatement(this.labelsForCurrentStatement);
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// Read past the semicolon.
this.Expect(PunctuatorToken.Semicolon);
// Record the portion of the source document that will be highlighted when debugging.
result.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
return result;
}
/// <summary>
/// Parses an if statement.
/// </summary>
/// <returns> An expression representing the if statement. </returns>
private IfStatement ParseIf()
{
var result = new IfStatement(this.labelsForCurrentStatement);
// Consume the if keyword.
this.Expect(KeywordToken.If);
// Read the left parenthesis.
this.Expect(PunctuatorToken.LeftParenthesis);
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// Parse the condition.
result.Condition = ParseExpression(PunctuatorToken.RightParenthesis);
// Record the portion of the source document that will be highlighted when debugging.
result.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
// Read the right parenthesis.
this.Expect(PunctuatorToken.RightParenthesis);
// Read the statements that will be executed when the condition is true.
result.IfClause = ParseStatement(addingToExistingBlock: false);
// Optionally, read the else statement.
if (this.nextToken == KeywordToken.Else)
{
// Consume the else keyword.
this.Consume();
// Read the statements that will be executed when the condition is false.
result.ElseClause = ParseStatement(addingToExistingBlock: false);
}
return result;
}
/// <summary>
/// Parses a do statement.
/// </summary>
/// <returns> An expression representing the do statement. </returns>
private DoWhileStatement ParseDo()
{
var result = new DoWhileStatement(this.labelsForCurrentStatement);
// Consume the do keyword.
this.Expect(KeywordToken.Do);
// Read the statements that will be executed in the loop body.
result.Body = ParseStatement(addingToExistingBlock: false);
// Read the while keyword.
this.Expect(KeywordToken.While);
// Read the left parenthesis.
this.Expect(PunctuatorToken.LeftParenthesis);
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// Parse the condition.
start = this.PositionAfterWhitespace;
result.ConditionStatement = new ExpressionStatement(ParseExpression(PunctuatorToken.RightParenthesis));
result.ConditionStatement.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
// Record the portion of the source document that will be highlighted when debugging.
result.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
// Read the right parenthesis.
this.Expect(PunctuatorToken.RightParenthesis);
// Consume the end of the statement. Note this doesn't use ExpectEndOfStatement()
// because a semi-colon is not required here.
if (this.nextToken == PunctuatorToken.Semicolon)
Consume();
return result;
}
/// <summary>
/// Parses a while statement.
/// </summary>
/// <returns> A while statement. </returns>
private WhileStatement ParseWhile()
{
var result = new WhileStatement(this.labelsForCurrentStatement);
// Consume the while keyword.
this.Expect(KeywordToken.While);
// Read the left parenthesis.
this.Expect(PunctuatorToken.LeftParenthesis);
// Parse the condition.
var start = this.PositionAfterWhitespace;
result.ConditionStatement = new ExpressionStatement(ParseExpression(PunctuatorToken.RightParenthesis));
result.ConditionStatement.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
// Read the right parenthesis.
this.Expect(PunctuatorToken.RightParenthesis);
// Read the statements that will be executed in the loop body.
result.Body = ParseStatement(addingToExistingBlock: false);
return result;
}
/// <summary>
/// When parsing a for statement, used to keep track of what type it is.
/// </summary>
private enum ForStatementType
{
Unknown,
For,
ForIn,
ForOf,
}
/// <summary>
/// Parses a for statement, for-in statement, or a for-of statement.
/// </summary>
/// <returns> A for statement, for-in statement, or a for-of statement. </returns>
private Statement ParseFor()
{
// Consume the for keyword.
this.Expect(KeywordToken.For);
// Read the left parenthesis.
this.Expect(PunctuatorToken.LeftParenthesis);
// 'let' variables should have their own scope.
using (CreateScopeContext(Scope.CreateBlockScope(this.currentScope)))
{
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// There are lots of possibilities for the initialization statement:
// i = 0;
// var i = 0, j = 1;
// var i in
// var i of
// let i in
// let i of
Statement initStatement = null;
if (this.nextToken == KeywordToken.Var || this.nextToken == KeywordToken.Let || this.nextToken == KeywordToken.Const)
{
// If the next token is var or const then we know we are parsing a declaration.
// This doesn't always work for 'let' unfortunately, because 'let' is only a
// reserved word in strict mode.
initStatement = ParseVarLetOrConst((KeywordToken)this.nextToken, consumeKeyword: true, insideForLoop: true);
}
else if (this.nextToken != PunctuatorToken.Semicolon)
{
// Parse the init statement as an expression.
var initExpression = ParseExpression(PunctuatorToken.Semicolon, KeywordToken.In, IdentifierToken.Of);
if (this.nextToken is IdentifierToken && initExpression is NameExpression nameExpression && nameExpression.Name == "let")
{
initStatement = ParseVarLetOrConst(KeywordToken.Let, consumeKeyword: false, insideForLoop: true);
}
else
{
initStatement = new ExpressionStatement(initExpression);
initStatement.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
}
}
// The for-in and for-of expressions need a variable to assign to. Is null for a regular for statement.
IReferenceExpression forInOfReference = null;
if (this.nextToken == KeywordToken.In || this.nextToken == IdentifierToken.Of)
{
// This is a for-in statement or a for-of statement.
if (initStatement is ExpressionStatement initExpressionStatement)
{
if ((initExpressionStatement.Expression is IReferenceExpression) == false)
throw new SyntaxErrorException("Invalid left-hand side in for loop.", this.LineNumber, this.SourcePath);
forInOfReference = (IReferenceExpression)initExpressionStatement.Expression;
}
else if (initStatement is VarLetOrConstStatement initVarLetOrConstStatement)
{
if (initVarLetOrConstStatement.Declarations.Count != 1)
throw new SyntaxErrorException("Invalid left-hand side in for loop; must have a single binding.", this.LineNumber, this.SourcePath);
forInOfReference = new NameExpression(this.currentScope, initVarLetOrConstStatement.Declarations[0].VariableName);
}
}
if (this.nextToken == KeywordToken.In)
{
// for (x in y)
// for (var x in y)
// for (let x in y)
var result = new ForInStatement(this.labelsForCurrentStatement);
result.Scope = this.currentScope;
result.Variable = forInOfReference;
result.VariableSourceSpan = initStatement.SourceSpan;
// Consume the "in".
this.Expect(KeywordToken.In);
// Parse the right-hand-side expression.
start = this.PositionAfterWhitespace;
result.TargetObject = ParseExpression(PunctuatorToken.RightParenthesis);
result.TargetObjectSourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
// Read the right parenthesis.
this.Expect(PunctuatorToken.RightParenthesis);
// Read the statements that will be executed in the loop body.
result.Body = ParseStatement(addingToExistingBlock: false);
return result;
}
else if (this.nextToken == IdentifierToken.Of)
{
// for (x of y)
// for (var x of y)
// for (let x of y)
var result = new ForOfStatement(this.labelsForCurrentStatement);
result.Scope = this.currentScope;
result.Variable = forInOfReference;
result.VariableSourceSpan = initStatement.SourceSpan;
// Consume the "of".
this.Expect(IdentifierToken.Of);
// Parse the right-hand-side expression.
start = this.PositionAfterWhitespace;
result.TargetObject = ParseExpression(PunctuatorToken.RightParenthesis, PunctuatorToken.Comma); // Comma is not allowed.
result.TargetObjectSourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
// Read the right parenthesis.
this.Expect(PunctuatorToken.RightParenthesis);
// Read the statements that will be executed in the loop body.
result.Body = ParseStatement(addingToExistingBlock: false);
return result;
}
else
{
var result = new ForStatement(this.labelsForCurrentStatement);
result.Scope = this.currentScope;
// Set the initialization statement.
if (initStatement != null)
result.InitStatement = initStatement;
// Read the semicolon.
this.Expect(PunctuatorToken.Semicolon);
// Parse the optional condition expression.
// Note: if the condition is omitted then it is considered to always be true.
if (this.nextToken != PunctuatorToken.Semicolon)
{
start = this.PositionAfterWhitespace;
result.ConditionStatement = new ExpressionStatement(ParseExpression(PunctuatorToken.Semicolon));
result.ConditionStatement.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
}
// Read the semicolon.
// Note: automatic semicolon insertion never inserts a semicolon in the header of a
// for statement.
this.Expect(PunctuatorToken.Semicolon);
// Parse the optional increment expression.
if (this.nextToken != PunctuatorToken.RightParenthesis)
{
start = this.PositionAfterWhitespace;
result.IncrementStatement = new ExpressionStatement(ParseExpression(PunctuatorToken.RightParenthesis));
result.IncrementStatement.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
}
// Read the right parenthesis.
this.Expect(PunctuatorToken.RightParenthesis);
// Read the statements that will be executed in the loop body.
result.Body = ParseStatement(addingToExistingBlock: false);
return result;
}
}
}
/// <summary>
/// Parses a continue statement.
/// </summary>
/// <returns> A continue statement. </returns>
private ContinueStatement ParseContinue()
{
var result = new ContinueStatement(this.labelsForCurrentStatement);
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// Consume the continue keyword.
this.Expect(KeywordToken.Continue);
// The continue statement can have an optional label to jump to.
if (this.AtValidEndOfStatement() == false)
{
// continue [label]
// Read the label name.
result.Label = this.ExpectIdentifier();
}
// Consume the semi-colon, if there was one.
this.ExpectEndOfStatement();
// Record the portion of the source document that will be highlighted when debugging.
result.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
return result;
}
/// <summary>
/// Parses a break statement.
/// </summary>
/// <returns> A break statement. </returns>
private BreakStatement ParseBreak()
{
var result = new BreakStatement(this.labelsForCurrentStatement);
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// Consume the break keyword.
this.Expect(KeywordToken.Break);
// The break statement can have an optional label to jump to.
if (this.AtValidEndOfStatement() == false)
{
// break [label]
// Read the label name.
result.Label = this.ExpectIdentifier();
}
// Consume the semi-colon, if there was one.
this.ExpectEndOfStatement();
// Record the portion of the source document that will be highlighted when debugging.
result.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
return result;
}
/// <summary>
/// Parses a return statement.
/// </summary>
/// <returns> A return statement. </returns>
private ReturnStatement ParseReturn()
{
if (!IsInFunctionContext)
throw new SyntaxErrorException("Return statements are only allowed inside functions", this.LineNumber, this.SourcePath);
var result = new ReturnStatement(this.labelsForCurrentStatement);
// Keep track of the start of the statement so that source debugging works correctly.
var start = this.PositionAfterWhitespace;
// Consume the return keyword.
this.Expect(KeywordToken.Return);
if (this.AtValidEndOfStatement() == false)
{
// Parse the return value expression.
result.Value = ParseExpression(PunctuatorToken.Semicolon);
}
// Consume the end of the statement.
this.ExpectEndOfStatement();
// Record the portion of the source document that will be highlighted when debugging.
result.SourceSpan = new SourceCodeSpan(start, this.PositionBeforeWhitespace);
return result;
}
/// <summary>
/// Parses a with statement.
/// </summary>
/// <returns> An expression representing the with statement. </returns>
private WithStatement ParseWith()
{
// This statement is not allowed in strict mode.
if (this.StrictMode == true)
throw new SyntaxErrorException("The with statement is not supported in strict mode", this.LineNumber, this.SourcePath);
var result = new WithStatement(this.labelsForCurrentStatement);
// Read past the "with" token.
this.Expect(KeywordToken.With);
// Read a left parenthesis token "(".
this.Expect(PunctuatorToken.LeftParenthesis);
// Keep track of the start of the statement so that source debugging works correctly.