-
Notifications
You must be signed in to change notification settings - Fork 181
/
Parser.java
7651 lines (6853 loc) · 309 KB
/
Parser.java
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
/*
* Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.js.parser;
import static com.oracle.js.parser.TokenType.ACCESSOR;
import static com.oracle.js.parser.TokenType.ARROW;
import static com.oracle.js.parser.TokenType.AS;
import static com.oracle.js.parser.TokenType.ASSERT;
import static com.oracle.js.parser.TokenType.ASSIGN;
import static com.oracle.js.parser.TokenType.ASSIGN_INIT;
import static com.oracle.js.parser.TokenType.ASYNC;
import static com.oracle.js.parser.TokenType.AT;
import static com.oracle.js.parser.TokenType.AWAIT;
import static com.oracle.js.parser.TokenType.CASE;
import static com.oracle.js.parser.TokenType.CATCH;
import static com.oracle.js.parser.TokenType.CLASS;
import static com.oracle.js.parser.TokenType.COLON;
import static com.oracle.js.parser.TokenType.COMMARIGHT;
import static com.oracle.js.parser.TokenType.COMMENT;
import static com.oracle.js.parser.TokenType.CONST;
import static com.oracle.js.parser.TokenType.DECPOSTFIX;
import static com.oracle.js.parser.TokenType.DECPREFIX;
import static com.oracle.js.parser.TokenType.ELLIPSIS;
import static com.oracle.js.parser.TokenType.ELSE;
import static com.oracle.js.parser.TokenType.EOF;
import static com.oracle.js.parser.TokenType.EOL;
import static com.oracle.js.parser.TokenType.EQ_STRICT;
import static com.oracle.js.parser.TokenType.ESCSTRING;
import static com.oracle.js.parser.TokenType.EXPORT;
import static com.oracle.js.parser.TokenType.EXTENDS;
import static com.oracle.js.parser.TokenType.FINALLY;
import static com.oracle.js.parser.TokenType.FROM;
import static com.oracle.js.parser.TokenType.FUNCTION;
import static com.oracle.js.parser.TokenType.GET;
import static com.oracle.js.parser.TokenType.IDENT;
import static com.oracle.js.parser.TokenType.IF;
import static com.oracle.js.parser.TokenType.IMPORT;
import static com.oracle.js.parser.TokenType.IN;
import static com.oracle.js.parser.TokenType.INCPOSTFIX;
import static com.oracle.js.parser.TokenType.INCPREFIX;
import static com.oracle.js.parser.TokenType.LBRACE;
import static com.oracle.js.parser.TokenType.LBRACKET;
import static com.oracle.js.parser.TokenType.LET;
import static com.oracle.js.parser.TokenType.LPAREN;
import static com.oracle.js.parser.TokenType.MUL;
import static com.oracle.js.parser.TokenType.OF;
import static com.oracle.js.parser.TokenType.PERIOD;
import static com.oracle.js.parser.TokenType.PRIVATE_IDENT;
import static com.oracle.js.parser.TokenType.RBRACE;
import static com.oracle.js.parser.TokenType.RBRACKET;
import static com.oracle.js.parser.TokenType.RPAREN;
import static com.oracle.js.parser.TokenType.SEMICOLON;
import static com.oracle.js.parser.TokenType.SET;
import static com.oracle.js.parser.TokenType.SPREAD_ARGUMENT;
import static com.oracle.js.parser.TokenType.SPREAD_ARRAY;
import static com.oracle.js.parser.TokenType.SPREAD_OBJECT;
import static com.oracle.js.parser.TokenType.STATIC;
import static com.oracle.js.parser.TokenType.STRING;
import static com.oracle.js.parser.TokenType.SUPER;
import static com.oracle.js.parser.TokenType.TEMPLATE;
import static com.oracle.js.parser.TokenType.TEMPLATE_HEAD;
import static com.oracle.js.parser.TokenType.TEMPLATE_MIDDLE;
import static com.oracle.js.parser.TokenType.TEMPLATE_TAIL;
import static com.oracle.js.parser.TokenType.TERNARY;
import static com.oracle.js.parser.TokenType.THIS;
import static com.oracle.js.parser.TokenType.VAR;
import static com.oracle.js.parser.TokenType.VOID;
import static com.oracle.js.parser.TokenType.WHILE;
import static com.oracle.js.parser.TokenType.WITH;
import static com.oracle.js.parser.TokenType.YIELD;
import static com.oracle.js.parser.TokenType.YIELD_STAR;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.graalvm.collections.Pair;
import com.oracle.js.parser.ir.AccessNode;
import com.oracle.js.parser.ir.BaseNode;
import com.oracle.js.parser.ir.BinaryNode;
import com.oracle.js.parser.ir.Block;
import com.oracle.js.parser.ir.BlockStatement;
import com.oracle.js.parser.ir.BreakNode;
import com.oracle.js.parser.ir.CallNode;
import com.oracle.js.parser.ir.CaseNode;
import com.oracle.js.parser.ir.CatchNode;
import com.oracle.js.parser.ir.ClassElement;
import com.oracle.js.parser.ir.ClassNode;
import com.oracle.js.parser.ir.ContinueNode;
import com.oracle.js.parser.ir.DebuggerNode;
import com.oracle.js.parser.ir.EmptyNode;
import com.oracle.js.parser.ir.ErrorNode;
import com.oracle.js.parser.ir.ExportNode;
import com.oracle.js.parser.ir.ExportSpecifierNode;
import com.oracle.js.parser.ir.Expression;
import com.oracle.js.parser.ir.ExpressionList;
import com.oracle.js.parser.ir.ExpressionStatement;
import com.oracle.js.parser.ir.ForNode;
import com.oracle.js.parser.ir.FromNode;
import com.oracle.js.parser.ir.FunctionNode;
import com.oracle.js.parser.ir.IdentNode;
import com.oracle.js.parser.ir.IfNode;
import com.oracle.js.parser.ir.ImportClauseNode;
import com.oracle.js.parser.ir.ImportNode;
import com.oracle.js.parser.ir.ImportSpecifierNode;
import com.oracle.js.parser.ir.IndexNode;
import com.oracle.js.parser.ir.JoinPredecessorExpression;
import com.oracle.js.parser.ir.LabelNode;
import com.oracle.js.parser.ir.LexicalContext;
import com.oracle.js.parser.ir.LiteralNode;
import com.oracle.js.parser.ir.LiteralNode.ArrayLiteralNode;
import com.oracle.js.parser.ir.Module;
import com.oracle.js.parser.ir.Module.ImportEntry;
import com.oracle.js.parser.ir.Module.ModuleRequest;
import com.oracle.js.parser.ir.NameSpaceImportNode;
import com.oracle.js.parser.ir.NamedExportsNode;
import com.oracle.js.parser.ir.NamedImportsNode;
import com.oracle.js.parser.ir.Node;
import com.oracle.js.parser.ir.ObjectNode;
import com.oracle.js.parser.ir.ParameterNode;
import com.oracle.js.parser.ir.PropertyKey;
import com.oracle.js.parser.ir.PropertyNode;
import com.oracle.js.parser.ir.ReturnNode;
import com.oracle.js.parser.ir.Scope;
import com.oracle.js.parser.ir.Statement;
import com.oracle.js.parser.ir.SwitchNode;
import com.oracle.js.parser.ir.Symbol;
import com.oracle.js.parser.ir.TemplateLiteralNode;
import com.oracle.js.parser.ir.TernaryNode;
import com.oracle.js.parser.ir.ThrowNode;
import com.oracle.js.parser.ir.TryNode;
import com.oracle.js.parser.ir.UnaryNode;
import com.oracle.js.parser.ir.VarNode;
import com.oracle.js.parser.ir.WhileNode;
import com.oracle.js.parser.ir.WithNode;
import com.oracle.js.parser.ir.visitor.NodeVisitor;
import com.oracle.truffle.api.strings.TruffleString;
/**
* Builds the IR.
*/
@SuppressWarnings("fallthrough")
public class Parser extends AbstractParser {
/** The arguments variable name. */
static final String ARGUMENTS_NAME = "arguments";
static final TruffleString ARGUMENTS_NAME_TS = ParserStrings.constant(ARGUMENTS_NAME);
/** The eval function variable name. */
private static final String EVAL_NAME = "eval";
private static final String CONSTRUCTOR_NAME = "constructor";
private static final TruffleString CONSTRUCTOR_NAME_TS = ParserStrings.constant(CONSTRUCTOR_NAME);
private static final String PRIVATE_CONSTRUCTOR_NAME = "#constructor";
private static final String PROTO_NAME = "__proto__";
static final String NEW_TARGET_NAME = "new.target";
static final TruffleString NEW_TARGET_NAME_TS = ParserStrings.constant(NEW_TARGET_NAME);
private static final TruffleString IMPORT_META_NAME = ParserStrings.constant("import.meta");
private static final String PROTOTYPE_NAME = "prototype";
/** Function.prototype.apply method name. */
private static final String APPLY_NAME = "apply";
/** EXEC name - special property used by $EXEC API. */
private static final TruffleString EXEC_NAME = ParserStrings.constant("$EXEC");
/** Function name for anonymous functions. */
private static final TruffleString ANONYMOUS_FUNCTION_NAME = ParserStrings.constant(":anonymous");
/** Function name for the program entry point. */
private static final TruffleString PROGRAM_NAME = ParserStrings.constant(":program");
/** Internal lexical binding name for {@code catch} error (destructuring). */
private static final TruffleString ERROR_BINDING_NAME = ParserStrings.constant(":error");
/** Internal lexical binding name for {@code switch} expression. */
private static final TruffleString SWITCH_BINDING_NAME = ParserStrings.constant(":switch");
/** Function name for arrow functions. */
private static final TruffleString ARROW_FUNCTION_NAME = ParserStrings.constant(":=>");
/** Internal function name for class field initializer. */
private static final TruffleString INITIALIZER_FUNCTION_NAME = ParserStrings.constant(":initializer");
private static final boolean ES6_FOR_OF = Options.getBooleanProperty("parser.for.of", true);
private static final boolean ES6_CLASS = Options.getBooleanProperty("parser.class", true);
private static final boolean ES6_ARROW_FUNCTION = Options.getBooleanProperty("parser.arrow.function", true);
private static final boolean ES6_REST_PARAMETER = Options.getBooleanProperty("parser.rest.parameter", true);
private static final boolean ES6_SPREAD_ARGUMENT = Options.getBooleanProperty("parser.spread.argument", true);
private static final boolean ES6_GENERATOR_FUNCTION = Options.getBooleanProperty("parser.generator.function", true);
private static final boolean ES6_DESTRUCTURING = Options.getBooleanProperty("parser.destructuring", true);
private static final boolean ES6_SPREAD_ARRAY = Options.getBooleanProperty("parser.spread.array", true);
private static final boolean ES6_COMPUTED_PROPERTY_NAME = Options.getBooleanProperty("parser.computed.property.name", true);
private static final boolean ES6_DEFAULT_PARAMETER = Options.getBooleanProperty("parser.default.parameter", true);
private static final boolean ES6_NEW_TARGET = Options.getBooleanProperty("parser.new.target", true);
private static final boolean ES8_TRAILING_COMMA = Options.getBooleanProperty("parser.trailing.comma", true);
private static final boolean ES8_ASYNC_FUNCTION = Options.getBooleanProperty("parser.async.function", true);
private static final boolean ES8_REST_SPREAD_PROPERTY = Options.getBooleanProperty("parser.rest.spread.property", true);
private static final boolean ES8_FOR_AWAIT_OF = Options.getBooleanProperty("parser.for.await.of", true);
private static final boolean ES2019_OPTIONAL_CATCH_BINDING = Options.getBooleanProperty("parser.optional.catch.binding", true);
private static final boolean ES2020_CLASS_FIELDS = Options.getBooleanProperty("parser.class.fields", true);
private static final boolean ES2022_TOP_LEVEL_AWAIT = Options.getBooleanProperty("parser.top.level.await", true);
private static final int REPARSE_IS_PROPERTY_ACCESSOR = 1 << 0;
private static final int REPARSE_IS_METHOD = 1 << 1;
/** Parsing eval. */
private static final int PARSE_EVAL = 1 << 2;
/** Parsing eval in a function (i.e. not script or module) context. */
private static final int PARSE_FUNCTION_CONTEXT_EVAL = 1 << 3;
private static final String USE_STRICT = "use strict";
private static final TruffleString ARGS = ParserStrings.constant("args");
private static final String GET_SPC = "get ";
private static final String SET_SPC = "set ";
private static final String META = "meta";
private static final TruffleString TARGET = ParserStrings.constant("target");
private static final String CONTEXT_ASSIGNMENT_TARGET = "assignment target";
private static final String CONTEXT_ASYNC_FUNCTION_DECLARATION = "async function declaration";
private static final String CONTEXT_CATCH_PARAMETER = "catch parameter";
private static final String CONTEXT_CLASS_DECLARATION = "class declaration";
private static final String CONTEXT_CLASS_NAME = "class name";
private static final String CONTEXT_CONST_DECLARATION = "const declaration";
private static final String CONTEXT_FOR_IN_ITERATOR = "for-in iterator";
private static final String CONTEXT_FOR_OF_ITERATOR = "for-of iterator";
private static final String CONTEXT_FUNCTION_DECLARATION = "function declaration";
private static final String CONTEXT_FUNCTION_NAME = "function name";
private static final String CONTEXT_FUNCTION_PARAMETER = "function parameter";
private static final String CONTEXT_GENERATOR_FUNCTION_DECLARATION = "generator function declaration";
private static final String CONTEXT_IDENTIFIER_REFERENCE = "IdentifierReference";
private static final String CONTEXT_IMPORTED_BINDING = "imported binding";
private static final String CONTEXT_IN = "in";
private static final String CONTEXT_LABEL_IDENTIFIER = "LabelIdentifier";
private static final String CONTEXT_LET_DECLARATION = "let declaration";
private static final String CONTEXT_OF = "of";
private static final String CONTEXT_OPERAND_FOR_DEC_OPERATOR = "operand for -- operator";
private static final String CONTEXT_OPERAND_FOR_INC_OPERATOR = "operand for ++ operator";
private static final String CONTEXT_VARIABLE_NAME = "variable name";
private static final String MSG_ACCESSOR_CONSTRUCTOR = "accessor.constructor";
private static final String MSG_ARGUMENTS_IN_FIELD_INITIALIZER = "arguments.in.field.initializer";
private static final String MSG_ASYNC_CONSTRUCTOR = "async.constructor";
private static final String MSG_CONSTRUCTOR_FIELD = "constructor.field";
private static final String MSG_DUPLICATE_DEFAULT_IN_SWITCH = "duplicate.default.in.switch";
private static final String MSG_DUPLICATE_IMPORT_ATTRIBUTE = "duplicate.import.attribute";
private static final String MSG_DUPLICATE_LABEL = "duplicate.label";
private static final String MSG_ESCAPED_KEYWORD = "escaped.keyword";
private static final String MSG_EXPECTED_ARROW_PARAMETER = "expected.arrow.parameter";
private static final String MSG_EXPECTED_BINDING = "expected.binding";
private static final String MSG_EXPECTED_BINDING_IDENTIFIER = "expected.binding.identifier";
private static final String MSG_EXPECTED_COMMA = "expected.comma";
private static final String MSG_EXPECTED_IMPORT = "expected.import";
private static final String MSG_EXPECTED_NAMED_IMPORT = "expected.named.import";
private static final String MSG_EXPECTED_OPERAND = "expected.operand";
private static final String MSG_EXPECTED_PROPERTY_ID = "expected.property.id";
private static final String MSG_EXPECTED_STMT = "expected.stmt";
private static final String MSG_EXPECTED_TARGET = "expected.target";
private static final String MSG_FOR_EACH_WITHOUT_IN = "for.each.without.in";
private static final String MSG_FOR_IN_LOOP_INITIALIZER = "for.in.loop.initializer";
private static final String MSG_GENERATOR_CONSTRUCTOR = "generator.constructor";
private static final String MSG_ILLEGAL_BREAK_STMT = "illegal.break.stmt";
private static final String MSG_ILLEGAL_CONTINUE_STMT = "illegal.continue.stmt";
private static final String MSG_INVALID_ARROW_PARAMETER = "invalid.arrow.parameter";
private static final String MSG_INVALID_EXPORT = "invalid.export";
private static final String MSG_INVALID_FOR_AWAIT_OF = "invalid.for.await.of";
private static final String MSG_INVALID_LVALUE = "invalid.lvalue";
private static final String MSG_INVALID_PRIVATE_IDENT = "invalid.private.ident";
private static final String MSG_INVALID_PROPERTY_INITIALIZER = "invalid.property.initializer";
private static final String MSG_INVALID_RETURN = "invalid.return";
private static final String MSG_INVALID_SUPER = "invalid.super";
private static final String MSG_LET_LEXICAL_BINDING = "let.lexical.binding";
private static final String MSG_MANY_VARS_IN_FOR_IN_LOOP = "many.vars.in.for.in.loop";
private static final String MSG_MISSING_CATCH_OR_FINALLY = "missing.catch.or.finally";
private static final String MSG_MISSING_CONST_ASSIGNMENT = "missing.const.assignment";
private static final String MSG_MISSING_DESTRUCTURING_ASSIGNMENT = "missing.destructuring.assignment";
private static final String MSG_MULTIPLE_CONSTRUCTORS = "multiple.constructors";
private static final String MSG_MULTIPLE_PROTO_KEY = "multiple.proto.key";
private static final String MSG_NEW_TARGET_IN_FUNCTION = "new.target.in.function";
private static final String MSG_NO_FUNC_DECL_HERE = "no.func.decl.here";
private static final String MSG_NO_FUNC_DECL_HERE_WARN = "no.func.decl.here.warn";
private static final String MSG_NOT_LVALUE_FOR_IN_LOOP = "not.lvalue.for.in.loop";
private static final String MSG_OPTIONAL_CHAIN_TEMPLATE = "optional.chain.template";
private static final String MSG_PRIVATE_CONSTRUCTOR_METHOD = "private.constructor.method";
private static final String MSG_PROPERTY_REDEFINITON = "property.redefinition";
private static final String MSG_STATIC_PROTOTYPE_FIELD = "static.prototype.field";
private static final String MSG_STATIC_PROTOTYPE_METHOD = "static.prototype.method";
private static final String MSG_STRICT_CANT_DELETE_IDENT = "strict.cant.delete.ident";
private static final String MSG_STRICT_CANT_DELETE_PRIVATE = "strict.cant.delete.private";
private static final String MSG_STRICT_NAME = "strict.name";
private static final String MSG_STRICT_NO_FUNC_DECL_HERE = "strict.no.func.decl.here";
private static final String MSG_STRICT_NO_NONOCTALDECIMAL = "strict.no.nonoctaldecimal";
private static final String MSG_STRICT_NO_OCTAL = "strict.no.octal";
private static final String MSG_STRICT_NO_WITH = "strict.no.with";
private static final String MSG_STRICT_PARAM_REDEFINITION = "strict.param.redefinition";
private static final String MSG_SYNTAX_ERROR_REDECLARE_VARIABLE = "syntax.error.redeclare.variable";
private static final String MSG_UNDEFINED_LABEL = "undefined.label";
private static final String MSG_UNEXPECTED_IDENT = "unexpected.ident";
private static final String MSG_UNEXPECTED_IMPORT_META = "unexpected.import.meta";
private static final String MSG_UNEXPECTED_TOKEN = "unexpected.token";
private static final String MSG_UNTERMINATED_TEMPLATE_EXPRESSION = "unterminated.template.expression";
private static final String MSG_USE_STRICT_NON_SIMPLE_PARAM = "use.strict.non.simple.param";
private static final String MSG_DECORATED_CONSTRUCTOR = "decorated.constructor";
private static final String MSG_DECORATED_STATIC_BLOCK = "decorated.static.block";
private static final String MSG_AUTO_ACCESSOR_NOT_FIELD = "auto.accessor.not.field";
/** Current env. */
private final ScriptEnvironment env;
/** Is scripting mode. */
private final boolean scripting;
/** Is shebang supported */
private final boolean shebang;
/** Is BigInt supported */
private final boolean allowBigInt;
private List<Statement> functionDeclarations;
private final ParserContext lc;
private final List<Object> defaultNames;
/** to receive line information from Lexer when scanning multiline literals. */
protected final Lexer.LineInfoReceiver lineInfoReceiver;
private RecompilableScriptFunctionData reparsedFunction;
private boolean isModule;
/**
* Used to pass (async) arrow function flags from head to body.
*
* Must be immediately consumed, i.e. before parsing the next expression, in order to avoid any
* nesting issues.
*/
private ParserContextFunctionNode coverArrowFunction;
private static final boolean PROFILE_PARSING = Options.getBooleanProperty("parser.profiling", false);
/**
* Constructor
*
* @param env script environment
* @param source source to parse
* @param errors error manager
*/
public Parser(final ScriptEnvironment env, final Source source, final ErrorManager errors) {
this(env, source, errors, env.strict);
}
/**
* Constructor
*
* @param env script environment
* @param source source to parse
* @param errors error manager
* @param strict strict
*/
public Parser(final ScriptEnvironment env, final Source source, final ErrorManager errors, final boolean strict) {
this(env, source, errors, strict, 0);
}
/**
* Construct a parser.
*
* @param env script environment
* @param source source to parse
* @param errors error manager
* @param strict parser created with strict mode enabled.
* @param lineOffset line offset to start counting lines from
*/
public Parser(final ScriptEnvironment env, final Source source, final ErrorManager errors, final boolean strict, final int lineOffset) {
super(source, errors, strict, lineOffset);
this.lc = new ParserContext();
this.defaultNames = new ArrayList<>();
this.env = env;
this.scripting = env.scripting && env.syntaxExtensions;
this.shebang = env.shebang || scripting;
this.allowBigInt = env.allowBigInt;
if (this.scripting) {
this.lineInfoReceiver = new Lexer.LineInfoReceiver() {
@Override
public void lineInfo(final int receiverLine, final int receiverLinePosition) {
// update the parser maintained line information
Parser.this.line = receiverLine;
Parser.this.linePosition = receiverLinePosition;
}
};
} else {
// non-scripting mode script can't have multi-line literals
this.lineInfoReceiver = null;
}
}
/**
* Execute parse and return the resulting function node. Errors will be thrown and the error
* manager will contain information if parsing should fail
*
* This is the default parse call, which will name the function node {@link #PROGRAM_NAME}.
*
* @return function node resulting from successful parse
*/
public FunctionNode parse() {
return parse(PROGRAM_NAME, 0, source.getLength(), 0, null, null);
}
/**
* Sets the @link RecompilableScriptFunctionData representing the function being reparsed (when
* this parser instance is used to reparse a previously parsed function, as part of its
* on-demand compilation). This will trigger various special behaviors, such as skipping nested
* function bodies.
*
* @param reparsedFunction the function being reparsed.
*/
public void setReparsedFunction(final RecompilableScriptFunctionData reparsedFunction) {
this.reparsedFunction = reparsedFunction;
}
/**
* Set up first token. Skips opening EOL.
*/
private void scanFirstToken() {
k = -1;
next();
}
/**
* Prepare {@link TokenStream} and {@link Lexer} for parsing.
*
* @param startPos source start position
* @param len source length
*/
private void prepareLexer(final int startPos, final int len) {
stream = new TokenStream();
lexer = new Lexer(source, startPos, len, stream, scripting, env.ecmaScriptVersion, shebang, isModule, reparsedFunction != null, allowBigInt);
lexer.line = lexer.pendingLine = lineOffset + 1;
line = lineOffset;
}
/**
* Peek ahead at the next token, skipping COMMENT and EOL tokens.
*/
private TokenType lookahead() {
for (int i = 1;; i++) {
TokenType t = T(k + i);
if (t == EOL || t == COMMENT) {
continue;
} else {
return t;
}
}
}
/**
* Peek ahead at the next 'accessor' token, skipping COMMENT but not EOL tokens.
*/
private TokenType lookaheadNoLineTerminator() {
for (int i = 1;; i++) {
TokenType t = T(k + i);
if (t == COMMENT) {
continue;
} else {
return t;
}
}
}
/**
* Execute parse and return the resulting function node. Errors will be thrown and the error
* manager will contain information if parsing should fail
*
* This should be used to create one and only one function node
*
* @param scriptName name for the script, given to the parsed FunctionNode
* @param startPos start position in source
* @param len length of parse
* @param reparseFlags flags provided by {@link RecompilableScriptFunctionData} as context for
* the code being reparsed. This allows us to recognize special forms of functions
* such as property getters and setters or instances of ES6 method shorthand in
* object literals.
* @param argumentNames optional names of arguments assumed by the parsed function node.
*
* @return function node resulting from successful parse
*/
public FunctionNode parse(final TruffleString scriptName, final int startPos, final int len, final int reparseFlags, Scope parentScope, List<String> argumentNames) {
long startTime = PROFILE_PARSING ? System.nanoTime() : 0L;
FunctionNode program;
try {
prepareLexer(startPos, len);
scanFirstToken();
program = program(scriptName, reparseFlags, parentScope, argumentNames);
} catch (final Exception e) {
handleParseException(e);
program = null;
}
if (PROFILE_PARSING) {
long duration = (System.nanoTime() - startTime);
System.out.println("Parsing: " + duration / 1_000_000);
}
return program;
}
/**
* Parse and return the resulting module. Errors will be thrown and the error manager will
* contain information if parsing should fail
*
* @param moduleName name for the module, given to the parsed FunctionNode
* @param startPos start position in source
* @param len length of parse
*
* @return function node resulting from successful parse
*/
public FunctionNode parseModule(final String moduleName, final int startPos, final int len) {
boolean oldModule = isModule;
boolean oldStrictMode = isStrictMode;
try {
isModule = true;
isStrictMode = true; // Module code is always strict mode code. (ES6 10.2.1)
prepareLexer(startPos, len);
scanFirstToken();
return module(moduleName);
} catch (final Exception e) {
handleParseException(e);
return null;
} finally {
isStrictMode = oldStrictMode;
isModule = oldModule;
}
}
public FunctionNode parseModule(final String moduleName) {
return parseModule(moduleName, 0, source.getLength());
}
/**
* Parse eval code.
*
* @param parentScope optional caller context scope (direct eval)
*/
public FunctionNode parseEval(boolean functionContext, Scope parentScope) {
return parse(PROGRAM_NAME, 0, source.getLength(), PARSE_EVAL | (functionContext ? PARSE_FUNCTION_CONTEXT_EVAL : 0), parentScope, null);
}
/**
* Parse code assuming a set of given arguments for the returned {@code FunctionNode}.
*
* @param argumentNames names of arguments assumed by the parsed function node.
*/
public FunctionNode parseWithArguments(List<String> argumentNames) {
return parse(PROGRAM_NAME, 0, source.getLength(), 0, null, argumentNames);
}
/**
* Parse and return the list of function parameter list. A comma separated list of function
* parameter identifiers is expected to be parsed. Errors will be thrown and the error manager
* will contain information if parsing should fail. This method is used to check if parameter
* Strings passed to "Function" constructor is a valid or not.
*
* @see #parseFunctionBody
*/
public void parseFormalParameterList() {
try {
stream = new TokenStream();
lexer = new Lexer(source, stream, scripting, env.ecmaScriptVersion, shebang, isModule, allowBigInt);
scanFirstToken();
assert lc.getCurrentScope() == null;
formalParameterList(TokenType.EOF, false, false);
} catch (final Exception e) {
handleParseException(e);
}
}
/**
* Execute parse and return the resulting function node. Errors will be thrown and the error
* manager will contain information if parsing should fail. This method is used to check if code
* String passed to "Function" constructor is a valid function body or not.
*
* @return function node resulting from successful parse
* @see #parseFormalParameterList
*/
public FunctionNode parseFunctionBody(boolean generator, boolean async) {
try {
stream = new TokenStream();
lexer = new Lexer(source, stream, scripting, env.ecmaScriptVersion, shebang, isModule, allowBigInt);
final int functionLine = line;
scanFirstToken();
// Make a fake token for the function.
final long functionToken = Token.toDesc(FUNCTION, 0, source.getLength());
// Set up the function to append elements.
final IdentNode ident = new IdentNode(functionToken, Token.descPosition(functionToken), lexer.stringIntern(PROGRAM_NAME));
final int functionFlags = (generator ? FunctionNode.IS_GENERATOR : 0) | (async ? FunctionNode.IS_ASYNC : 0);
final ParserContextFunctionNode function = createParserContextFunctionNode(ident, functionToken, functionFlags, functionLine, List.of(), 0);
function.clearFlag(FunctionNode.IS_PROGRAM);
assert lc.getCurrentScope() == null;
lc.push(function);
final ParserContextBlockNode body = newBlock(function.createBodyScope());
functionDeclarations = new ArrayList<>();
try {
sourceElements(generator, async, 0);
addFunctionDeclarations(function);
function.finishBodyScope(lexer);
} finally {
functionDeclarations = null;
restoreBlock(body);
lc.pop(function);
}
body.setFlag(Block.NEEDS_SCOPE);
final Block functionBody = new Block(functionToken, finish, body.getFlags() | Block.IS_SYNTHETIC | Block.IS_BODY, body.getScope(), body.getStatements());
expect(EOF);
final FunctionNode functionNode = createFunctionNode(
function,
functionToken,
ident,
functionLine,
functionBody);
return functionNode;
} catch (final Exception e) {
handleParseException(e);
return null;
}
}
private void handleParseException(final Exception e) {
// Issue message.
if (e instanceof ParserException) {
errors.error((ParserException) e);
} else {
// Extract message from exception. The message will be in error
// message format.
String message = e.getMessage();
// If empty message.
if (message == null) {
message = e.toString();
}
errors.error(message);
}
if (env.dumpOnError) {
e.printStackTrace(env.getErr());
}
}
/**
* Skip to a good parsing recovery point.
*/
private void recover(final Exception e) {
if (e != null) {
// Issue message.
if (e instanceof ParserException) {
errors.error((ParserException) e);
} else {
// Extract message from exception. The message will be in error
// message format.
String message = e.getMessage();
// If empty message.
if (message == null) {
message = e.toString();
}
errors.error(message);
}
if (env.dumpOnError) {
e.printStackTrace(env.getErr());
}
}
// Skip to a recovery point.
loop: while (true) {
switch (type) {
case EOF:
// Can not go any further.
break loop;
case EOL:
case SEMICOLON:
case RBRACE:
// Good recovery points.
next();
break loop;
default:
// So we can recover after EOL.
nextOrEOL();
break;
}
}
}
private Scope newBlockScope() {
return Scope.createBlock(lc.getCurrentScope());
}
/**
* Set up a new block.
*
* @return New block.
*/
private ParserContextBlockNode newBlock(Scope scope) {
return lc.push(new ParserContextBlockNode(token, scope));
}
private ParserContextFunctionNode createParserContextFunctionNode(final IdentNode ident, final long functionToken, final int functionFlags, final int functionLine) {
return createParserContextFunctionNode(ident, functionToken, functionFlags, functionLine, null, 0);
}
private ParserContextFunctionNode createParserContextFunctionNode(final IdentNode ident, final long functionToken, final int functionFlags, final int functionLine,
final List<IdentNode> parameters, int functionLength) {
return createParserContextFunctionNode(ident, functionToken, functionFlags, functionLine, parameters, functionLength, null);
}
private ParserContextFunctionNode createParserContextFunctionNode(final IdentNode ident, final long functionToken, final int functionFlags, final int functionLine,
final List<IdentNode> parameters, int functionLength, Scope functionTopScope) {
final ParserContextFunctionNode parentFunction = lc.getCurrentFunction();
final TruffleString name = ident == null ? TruffleString.Encoding.UTF_16.getEmpty() : ident.getNameTS();
int flags = functionFlags;
if (isStrictMode) {
flags |= FunctionNode.IS_STRICT;
}
if (parentFunction == null) {
flags |= FunctionNode.IS_PROGRAM;
flags |= FunctionNode.IS_ANONYMOUS;
}
final Scope parentScope = lc.getCurrentScope();
return new ParserContextFunctionNode(functionToken, ident, name, functionLine, flags, parameters, functionLength, parentScope, functionTopScope);
}
private FunctionNode createFunctionNode(final ParserContextFunctionNode function, final long startToken, final IdentNode ident,
final int functionLine, final Block body) {
assert body.isFunctionBody() || (body.isParameterBlock() && ((BlockStatement) body.getLastStatement()).getBlock().isFunctionBody());
VarNode varNode = function.verifyHoistedVarDeclarations();
if (varNode != null) {
throw error(ECMAErrors.getMessage(MSG_SYNTAX_ERROR_REDECLARE_VARIABLE, varNode.getName().getName()), varNode.getToken());
}
long lastTokenWithDelimiter = Token.withDelimiter(function.getLastToken());
// EOL uses length field to store the line number
int lastTokenFinish = Token.descPosition(lastTokenWithDelimiter) + (Token.descType(lastTokenWithDelimiter) == TokenType.EOL ? 0 : Token.descLength(lastTokenWithDelimiter));
final FunctionNode functionNode = new FunctionNode(
source,
functionLine,
body.getToken(),
lastTokenFinish,
startToken,
function.getLastToken(),
ident,
function.getNameTS(),
function.getLength(),
function.getParameterCount(),
function.getParameters(),
function.getFlags(),
body,
function.getEndParserState(),
function.getModule(),
function.getInternalNameTS());
return functionNode;
}
/**
* Restore the current block.
*/
private ParserContextBlockNode restoreBlock(final ParserContextBlockNode block) {
return lc.pop(block);
}
/**
* Get the statements in a block.
*
* @return Block statements.
*/
private Block getBlock(boolean yield, boolean await, boolean needsBraces) {
final long blockToken = token;
final ParserContextBlockNode newBlock = newBlock(newBlockScope());
try {
// Block opening brace.
if (needsBraces) {
expect(LBRACE);
}
// Accumulate block statements.
statementList(yield, await);
} finally {
restoreBlock(newBlock);
}
// Block closing brace.
int realFinish;
if (needsBraces) {
expectDontAdvance(RBRACE);
// otherwise in case block containing single braced block the inner
// block could end somewhere later after comments and spaces
realFinish = Token.descPosition(token) + Token.descLength(token);
expect(RBRACE);
} else {
realFinish = finish;
}
newBlock.getScope().close();
final int flags = newBlock.getFlags() | (needsBraces ? 0 : Block.IS_SYNTHETIC);
return new Block(blockToken, Math.max(realFinish, Token.descPosition(blockToken)), flags, newBlock.getScope(), newBlock.getStatements());
}
/**
* Get the statements in a case clause.
*/
private List<Statement> caseStatementList(boolean yield, boolean await) {
// case clauses share the same scope.
final ParserContextBlockNode newBlock = newBlock(lc.getCurrentScope());
try {
statementList(yield, await);
} finally {
lc.pop(newBlock);
}
return newBlock.getStatements();
}
/**
* Get all the statements generated by a single statement.
*
* @return Statements.
*/
private Block getStatement(boolean yield, boolean await) {
return getStatement(yield, await, false, false);
}
private Block getStatement(boolean yield, boolean await, boolean labelledStatement, boolean mayBeFunctionDeclaration) {
return getStatement(yield, await, labelledStatement, mayBeFunctionDeclaration, mayBeFunctionDeclaration);
}
private Block getStatement(boolean yield, boolean await, boolean labelledStatement, boolean mayBeFunctionDeclaration, boolean mayBeLabeledFunctionDeclaration) {
if (type == LBRACE) {
return getBlock(yield, await, true);
}
// Set up new block. Captures first token.
final ParserContextBlockNode newBlock = newBlock(newBlockScope());
newBlock.setFlag(Block.IS_SYNTHETIC);
try {
statement(yield, await, false, 0, true, labelledStatement, mayBeFunctionDeclaration, mayBeLabeledFunctionDeclaration);
} finally {
restoreBlock(newBlock);
}
newBlock.getScope().close();
return new Block(newBlock.getToken(), finish, newBlock.getFlags(), newBlock.getScope(), newBlock.getStatements());
}
/**
* Detect use of special properties.
*
* @param ident Referenced property.
*/
private IdentNode detectSpecialProperty(final IdentNode ident) {
if (isArguments(ident)) {
return markArguments(ident);
}
return ident;
}
private IdentNode markArguments(final IdentNode ident) {
Scope currentScope = lc.getCurrentScope();
if (currentScope.inClassFieldInitializer()) {
throw error(AbstractParser.message(MSG_ARGUMENTS_IN_FIELD_INITIALIZER), ident.getToken());
}
if (currentScope.isGlobalScope()) {
// arguments has no special meaning in the global scope
return ident;
}
// skip over arrow functions, e.g. function f() { return (() => arguments.length)(); }
lc.getCurrentNonArrowFunction().setFlag(FunctionNode.USES_ARGUMENTS);
return ident.setIsArguments();
}
private boolean useBlockScope() {
return isES6();
}
/**
* ES6 (a.k.a. ES2015) or newer.
*/
private boolean isES6() {
return env.ecmaScriptVersion >= 6;
}
/**
* ES2017 or newer.
*/
private boolean isES2017() {
return env.ecmaScriptVersion >= 8;
}
/**
* ES2020 or newer.
*/
private boolean isES2020() {
return env.ecmaScriptVersion >= 11;
}
/**
* ES2021 or newer.
*/
private boolean isES2021() {
return env.ecmaScriptVersion >= 12;
}
/**
* ES2022 or newer.
*/
private boolean isES2022() {
return env.ecmaScriptVersion >= 13;
}
/**
* ES2023 or newer.
*/
private boolean isES2023() {
return env.ecmaScriptVersion >= 14;
}
private boolean isClassFields() {
return ES2020_CLASS_FIELDS && env.classFields;
}
static boolean isArguments(final TruffleString name) {
return ARGUMENTS_NAME_TS.equals(name);
}
static boolean isArguments(final String name) {
return ARGUMENTS_NAME.equals(name);
}
static boolean isArguments(final IdentNode ident) {
return isArguments(ident.getName());
}
/**
* Tells whether a IdentNode can be used as L-value of an assignment
*
* @param ident IdentNode to be checked
* @return whether the ident can be used as L-value
*/
private static boolean checkIdentLValue(final IdentNode ident) {
return ident.tokenType().getKind() != TokenKind.KEYWORD;
}