-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Parser.cpp
5189 lines (4455 loc) Β· 228 KB
/
Parser.cpp
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) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
* Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
* Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
* Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
* Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
* Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "Parser.h"
#include <AK/Array.h>
#include <AK/CharacterTypes.h>
#include <AK/HashTable.h>
#include <AK/ScopeGuard.h>
#include <AK/StdLibExtras.h>
#include <AK/TemporaryChange.h>
#include <LibJS/Runtime/RegExpObject.h>
#include <LibRegex/Regex.h>
namespace JS {
class ScopePusher {
// NOTE: We really only need ModuleTopLevel and NotModuleTopLevel as the only
// difference seems to be in https://tc39.es/ecma262/#sec-static-semantics-varscopeddeclarations
// where ModuleItemList only does the VarScopedDeclaration and not the
// TopLevelVarScopedDeclarations.
enum class ScopeLevel {
NotTopLevel,
ScriptTopLevel,
ModuleTopLevel,
FunctionTopLevel,
StaticInitTopLevel
};
public:
enum class ScopeType {
Function,
Program,
Block,
ForLoop,
With,
Catch,
ClassStaticInit,
ClassField,
ClassDeclaration,
};
private:
ScopePusher(Parser& parser, ScopeNode* node, ScopeLevel scope_level, ScopeType type)
: m_parser(parser)
, m_scope_level(scope_level)
, m_type(type)
{
m_parent_scope = exchange(m_parser.m_state.current_scope_pusher, this);
if (type != ScopeType::Function) {
VERIFY(node || (m_parent_scope && scope_level == ScopeLevel::NotTopLevel));
if (!node)
m_node = m_parent_scope->m_node;
else
m_node = node;
}
if (!is_top_level())
m_top_level_scope = m_parent_scope->m_top_level_scope;
else
m_top_level_scope = this;
}
bool is_top_level()
{
return m_scope_level != ScopeLevel::NotTopLevel;
}
public:
static ScopePusher function_scope(Parser& parser, RefPtr<Identifier const> function_name = nullptr)
{
ScopePusher scope_pusher(parser, nullptr, ScopeLevel::FunctionTopLevel, ScopeType::Function);
if (function_name) {
scope_pusher.m_bound_names.set(function_name->string());
}
return scope_pusher;
}
static ScopePusher program_scope(Parser& parser, Program& program)
{
return ScopePusher(parser, &program, program.type() == Program::Type::Script ? ScopeLevel::ScriptTopLevel : ScopeLevel::ModuleTopLevel, ScopeType::Program);
}
static ScopePusher block_scope(Parser& parser, ScopeNode& node)
{
return ScopePusher(parser, &node, ScopeLevel::NotTopLevel, ScopeType::Block);
}
static ScopePusher for_loop_scope(Parser& parser, ScopeNode& node)
{
return ScopePusher(parser, &node, ScopeLevel::NotTopLevel, ScopeType::ForLoop);
}
static ScopePusher with_scope(Parser& parser, ScopeNode& node)
{
ScopePusher scope_pusher(parser, &node, ScopeLevel::NotTopLevel, ScopeType::With);
return scope_pusher;
}
static ScopePusher catch_scope(Parser& parser, RefPtr<BindingPattern const> const& pattern, DeprecatedFlyString const& parameter)
{
ScopePusher scope_pusher(parser, nullptr, ScopeLevel::NotTopLevel, ScopeType::Catch);
if (pattern) {
// NOTE: Nothing in the callback throws an exception.
MUST(pattern->for_each_bound_identifier([&](auto const& identifier) {
scope_pusher.m_forbidden_var_names.set(identifier.string());
scope_pusher.m_bound_names.set(identifier.string());
}));
} else if (!parameter.is_empty()) {
scope_pusher.m_var_names.set(parameter);
scope_pusher.m_bound_names.set(parameter);
}
return scope_pusher;
}
static ScopePusher static_init_block_scope(Parser& parser, ScopeNode& node)
{
ScopePusher scope_pusher(parser, &node, ScopeLevel::StaticInitTopLevel, ScopeType::ClassStaticInit);
return scope_pusher;
}
static ScopePusher class_field_scope(Parser& parser, ScopeNode& node)
{
ScopePusher scope_pusher(parser, &node, ScopeLevel::NotTopLevel, ScopeType::ClassField);
return scope_pusher;
}
static ScopePusher class_declaration_scope(Parser& parser, RefPtr<Identifier const> class_name)
{
ScopePusher scope_pusher(parser, nullptr, ScopeLevel::NotTopLevel, ScopeType::ClassDeclaration);
if (class_name) {
scope_pusher.m_bound_names.set(class_name->string());
}
return scope_pusher;
}
ScopeType type() const { return m_type; }
void add_declaration(NonnullRefPtr<Declaration const> declaration)
{
if (declaration->is_lexical_declaration()) {
// NOTE: Nothing in the callback throws an exception.
MUST(declaration->for_each_bound_identifier([&](auto const& identifier) {
auto const& name = identifier.string();
if (m_var_names.contains(name) || m_forbidden_lexical_names.contains(name) || m_function_names.contains(name))
throw_identifier_declared(name, declaration);
if (m_lexical_names.set(name) != AK::HashSetResult::InsertedNewEntry)
throw_identifier_declared(name, declaration);
}));
m_node->add_lexical_declaration(move(declaration));
} else if (!declaration->is_function_declaration()) {
// NOTE: Nothing in the callback throws an exception.
MUST(declaration->for_each_bound_identifier([&](auto const& identifier) {
auto const& name = identifier.string();
ScopePusher* pusher = this;
while (true) {
if (pusher->m_lexical_names.contains(name)
|| pusher->m_function_names.contains(name)
|| pusher->m_forbidden_var_names.contains(name))
throw_identifier_declared(name, declaration);
pusher->m_var_names.set(name);
if (pusher->is_top_level())
break;
VERIFY(pusher->m_parent_scope != nullptr);
pusher = pusher->m_parent_scope;
}
VERIFY(pusher->is_top_level() && pusher->m_node);
pusher->m_node->add_var_scoped_declaration(declaration);
}));
VERIFY(m_top_level_scope);
m_top_level_scope->m_node->add_var_scoped_declaration(move(declaration));
} else {
if (m_scope_level != ScopeLevel::NotTopLevel && m_scope_level != ScopeLevel::ModuleTopLevel) {
// Only non-top levels and Module don't var declare the top functions
// NOTE: Nothing in the callback throws an exception.
MUST(declaration->for_each_bound_identifier([&](auto const& identifier) {
m_var_names.set(identifier.string());
}));
m_node->add_var_scoped_declaration(move(declaration));
} else {
VERIFY(is<FunctionDeclaration>(*declaration));
auto& function_declaration = static_cast<FunctionDeclaration const&>(*declaration);
auto function_name = function_declaration.name();
if (m_var_names.contains(function_name) || m_lexical_names.contains(function_name))
throw_identifier_declared(function_name, declaration);
if (function_declaration.kind() != FunctionKind::Normal || m_parser.m_state.strict_mode) {
if (m_function_names.contains(function_name))
throw_identifier_declared(function_name, declaration);
m_lexical_names.set(function_name);
m_node->add_lexical_declaration(move(declaration));
return;
}
m_function_names.set(function_name);
if (!m_lexical_names.contains(function_name))
m_functions_to_hoist.append(static_ptr_cast<FunctionDeclaration const>(declaration));
m_node->add_lexical_declaration(move(declaration));
}
}
}
ScopePusher const* last_function_scope() const
{
for (auto scope_ptr = this; scope_ptr; scope_ptr = scope_ptr->m_parent_scope) {
if (scope_ptr->m_function_parameters.has_value())
return scope_ptr;
}
return nullptr;
}
Vector<FunctionParameter> const& function_parameters() const
{
return *m_function_parameters;
}
ScopePusher* parent_scope() { return m_parent_scope; }
ScopePusher const* parent_scope() const { return m_parent_scope; }
[[nodiscard]] bool has_declaration(DeprecatedFlyString const& name) const
{
return m_lexical_names.contains(name) || m_var_names.contains(name) || !m_functions_to_hoist.find_if([&name](auto& function) { return function->name() == name; }).is_end();
}
bool contains_direct_call_to_eval() const { return m_contains_direct_call_to_eval; }
bool contains_access_to_arguments_object() const { return m_contains_access_to_arguments_object; }
void set_contains_direct_call_to_eval()
{
m_contains_direct_call_to_eval = true;
m_screwed_by_eval_in_scope_chain = true;
}
void set_contains_access_to_arguments_object() { m_contains_access_to_arguments_object = true; }
void set_scope_node(ScopeNode* node) { m_node = node; }
void set_function_parameters(Vector<FunctionParameter> const& parameters)
{
m_function_parameters = parameters;
for (auto& parameter : parameters) {
parameter.binding.visit(
[&](Identifier const& identifier) {
register_identifier(identifier);
m_function_parameters_candidates_for_local_variables.set(identifier.string());
m_forbidden_lexical_names.set(identifier.string());
},
[&](NonnullRefPtr<BindingPattern const> const& binding_pattern) {
// NOTE: Nothing in the callback throws an exception.
MUST(binding_pattern->for_each_bound_identifier([&](auto const& identifier) {
m_forbidden_lexical_names.set(identifier.string());
}));
});
}
}
~ScopePusher()
{
VERIFY(is_top_level() || m_parent_scope);
if (m_parent_scope && !m_function_parameters.has_value()) {
m_parent_scope->m_contains_access_to_arguments_object |= m_contains_access_to_arguments_object;
m_parent_scope->m_contains_direct_call_to_eval |= m_contains_direct_call_to_eval;
m_parent_scope->m_contains_await_expression |= m_contains_await_expression;
}
if (!m_node) {
m_parser.m_state.current_scope_pusher = m_parent_scope;
return;
}
if (m_parent_scope && m_contains_direct_call_to_eval) {
m_parent_scope->m_screwed_by_eval_in_scope_chain = true;
}
for (auto& it : m_identifier_groups) {
auto const& identifier_group_name = it.key;
auto& identifier_group = it.value;
if (m_parser.m_state.in_catch_parameter_context) {
// NOTE: The parser currently cannot determine if an identifier captured by a function belongs to the environment created by a catch parameter.
// As a result, any identifiers used inside the catch parameter are not considered as candidates for optimization in local or global variable access.
continue;
}
bool scope_has_declaration = false;
if (is_top_level() && m_var_names.contains(identifier_group_name))
scope_has_declaration = true;
else if (m_lexical_names.contains(identifier_group_name) || m_function_names.contains(identifier_group_name))
scope_has_declaration = true;
if (m_type == ScopeType::Function && !m_is_arrow_function && identifier_group_name == "arguments"sv)
scope_has_declaration = true;
bool hoistable_function_declaration = false;
for (auto const& function_declaration : m_functions_to_hoist) {
if (function_declaration->name() == identifier_group_name)
hoistable_function_declaration = true;
}
if ((m_type == ScopeType::ClassDeclaration || m_type == ScopeType::Catch) && m_bound_names.contains(identifier_group_name)) {
// NOTE: Currently, the parser cannot recognize that assigning a named function expression creates a scope with a binding for the function name.
// As a result, function names are not considered as candidates for optimization in global variable access.
continue;
}
if (m_type == ScopeType::Function && m_bound_names.contains(identifier_group_name)) {
// NOTE: Currently parser can't determine that named function expression assigment creates scope with binding for funciton name so function names are not considered as candidates to be optmized in global variables access
identifier_group.might_be_variable_in_lexical_scope_in_named_function_assignment = true;
}
if (m_type == ScopeType::ClassDeclaration || m_type == ScopeType::Catch) {
// NOTE: Class declaration and catch scopes do not have own ScopeNode hence can't contain declaration of any variable
scope_has_declaration = false;
}
if (m_type == ScopeType::Function) {
if (!m_contains_access_to_arguments_object && m_function_parameters_candidates_for_local_variables.contains(identifier_group_name)) {
scope_has_declaration = true;
} else if (m_forbidden_lexical_names.contains(identifier_group_name)) {
// NOTE: If an identifier is used as a function parameter that cannot be optimized locally or globally, it is simply ignored.
continue;
}
}
if (m_type == ScopeType::Function && hoistable_function_declaration) {
// NOTE: Hoistable function declarations are currently not optimized into global or local variables, but future improvements may change that.
continue;
}
if (m_type == ScopeType::Program) {
auto can_use_global_for_identifier = !(identifier_group.used_inside_with_statement || identifier_group.might_be_variable_in_lexical_scope_in_named_function_assignment || identifier_group.used_inside_scope_with_eval || m_parser.m_state.initiated_by_eval);
if (can_use_global_for_identifier) {
for (auto& identifier : identifier_group.identifiers)
identifier->set_is_global();
}
} else if (scope_has_declaration) {
if (hoistable_function_declaration)
continue;
if (!identifier_group.captured_by_nested_function && !identifier_group.used_inside_with_statement) {
if (m_screwed_by_eval_in_scope_chain)
continue;
auto local_scope = last_function_scope();
if (!local_scope) {
// NOTE: If there is no function scope, we are in a *descendant* of the global program scope.
// While we cannot make `let` and `const` into locals in the topmost program scope,
// as that would break expected web behavior where subsequent <script> elements should see
// lexical bindings created by earlier <script> elements, we *can* promote them in descendant scopes.
// Of course, global `var` bindings can never be made into locals, as they get hoisted to the topmost program scope.
if (identifier_group.declaration_kind == DeclarationKind::Var)
continue;
// Add these locals to the top-level scope. (We only produce one executable for the entire program
// scope, so that's where the locals have to be stored.)
local_scope = m_top_level_scope;
}
auto local_variable_index = local_scope->m_node->add_local_variable(identifier_group_name);
for (auto& identifier : identifier_group.identifiers)
identifier->set_local_variable_index(local_variable_index);
}
} else {
if (m_function_parameters.has_value() || m_type == ScopeType::ClassField || m_type == ScopeType::ClassStaticInit) {
// NOTE: Class fields and class static initialization sections implicitly create functions
identifier_group.captured_by_nested_function = true;
}
if (m_type == ScopeType::With)
identifier_group.used_inside_with_statement = true;
if (m_contains_direct_call_to_eval)
identifier_group.used_inside_scope_with_eval = true;
if (m_parent_scope) {
if (auto maybe_parent_scope_identifier_group = m_parent_scope->m_identifier_groups.get(identifier_group_name); maybe_parent_scope_identifier_group.has_value()) {
maybe_parent_scope_identifier_group.value().identifiers.extend(identifier_group.identifiers);
if (identifier_group.captured_by_nested_function)
maybe_parent_scope_identifier_group.value().captured_by_nested_function = true;
if (identifier_group.used_inside_with_statement)
maybe_parent_scope_identifier_group.value().used_inside_with_statement = true;
if (identifier_group.might_be_variable_in_lexical_scope_in_named_function_assignment)
maybe_parent_scope_identifier_group.value().might_be_variable_in_lexical_scope_in_named_function_assignment = true;
if (identifier_group.used_inside_scope_with_eval)
maybe_parent_scope_identifier_group.value().used_inside_scope_with_eval = true;
} else {
m_parent_scope->m_identifier_groups.set(identifier_group_name, identifier_group);
}
}
}
}
for (size_t i = 0; i < m_functions_to_hoist.size(); i++) {
auto const& function_declaration = m_functions_to_hoist[i];
if (m_lexical_names.contains(function_declaration->name()) || m_forbidden_var_names.contains(function_declaration->name()))
continue;
if (is_top_level()) {
m_node->add_hoisted_function(move(m_functions_to_hoist[i]));
} else {
if (!m_parent_scope->m_lexical_names.contains(function_declaration->name()) && !m_parent_scope->m_function_names.contains(function_declaration->name()))
m_parent_scope->m_functions_to_hoist.append(move(m_functions_to_hoist[i]));
}
}
VERIFY(m_parser.m_state.current_scope_pusher == this);
m_parser.m_state.current_scope_pusher = m_parent_scope;
}
void set_contains_await_expression()
{
m_contains_await_expression = true;
}
bool contains_await_expression() const
{
return m_contains_await_expression;
}
bool can_have_using_declaration() const
{
return m_scope_level != ScopeLevel::ScriptTopLevel;
}
void register_identifier(NonnullRefPtr<Identifier> id, Optional<DeclarationKind> declaration_kind = {})
{
if (auto maybe_identifier_group = m_identifier_groups.get(id->string()); maybe_identifier_group.has_value()) {
maybe_identifier_group.value().identifiers.append(id);
} else {
m_identifier_groups.set(id->string(), IdentifierGroup {
.captured_by_nested_function = false,
.identifiers = { id },
.declaration_kind = declaration_kind,
});
}
}
bool uses_this() const { return m_uses_this; }
bool uses_this_from_environment() const { return m_uses_this_from_environment; }
void set_uses_this()
{
auto const* closest_function_scope = last_function_scope();
auto uses_this_from_environment = closest_function_scope && closest_function_scope->m_is_arrow_function;
for (auto* scope_ptr = this; scope_ptr; scope_ptr = scope_ptr->m_parent_scope) {
if (scope_ptr->m_type == ScopeType::Function) {
scope_ptr->m_uses_this = true;
if (uses_this_from_environment)
scope_ptr->m_uses_this_from_environment = true;
}
}
}
void set_uses_new_target()
{
for (auto* scope_ptr = this; scope_ptr; scope_ptr = scope_ptr->m_parent_scope) {
if (scope_ptr->m_type == ScopeType::Function) {
scope_ptr->m_uses_this = true;
scope_ptr->m_uses_this_from_environment = true;
}
}
}
void set_is_arrow_function()
{
m_is_arrow_function = true;
}
private:
void throw_identifier_declared(DeprecatedFlyString const& name, NonnullRefPtr<Declaration const> const& declaration)
{
m_parser.syntax_error(ByteString::formatted("Identifier '{}' already declared", name), declaration->source_range().start);
}
Parser& m_parser;
ScopeNode* m_node { nullptr };
ScopeLevel m_scope_level { ScopeLevel::NotTopLevel };
ScopeType m_type;
ScopePusher* m_parent_scope { nullptr };
ScopePusher* m_top_level_scope { nullptr };
HashTable<DeprecatedFlyString> m_lexical_names;
HashTable<DeprecatedFlyString> m_var_names;
HashTable<DeprecatedFlyString> m_function_names;
HashTable<DeprecatedFlyString> m_forbidden_lexical_names;
HashTable<DeprecatedFlyString> m_forbidden_var_names;
Vector<NonnullRefPtr<FunctionDeclaration const>> m_functions_to_hoist;
HashTable<DeprecatedFlyString> m_bound_names;
HashTable<DeprecatedFlyString> m_function_parameters_candidates_for_local_variables;
struct IdentifierGroup {
bool captured_by_nested_function { false };
bool used_inside_with_statement { false };
bool used_inside_scope_with_eval { false };
bool might_be_variable_in_lexical_scope_in_named_function_assignment { false };
Vector<NonnullRefPtr<Identifier>> identifiers;
Optional<DeclarationKind> declaration_kind;
};
HashMap<DeprecatedFlyString, IdentifierGroup> m_identifier_groups;
Optional<Vector<FunctionParameter>> m_function_parameters;
bool m_contains_access_to_arguments_object { false };
bool m_contains_direct_call_to_eval { false };
bool m_contains_await_expression { false };
bool m_screwed_by_eval_in_scope_chain { false };
// Function uses this binding from function environment if:
// 1. It's an arrow function or establish parent scope for an arrow function
// 2. Uses new.target
bool m_uses_this_from_environment { false };
bool m_uses_this { false };
bool m_is_arrow_function { false };
};
class OperatorPrecedenceTable {
public:
constexpr OperatorPrecedenceTable()
: m_token_precedence()
{
for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
auto& op = m_operator_precedence[i];
m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
}
}
constexpr int get(TokenType token) const
{
int p = m_token_precedence[static_cast<size_t>(token)];
if (p == 0) {
warnln("Internal Error: No precedence for operator {}", Token::name(token));
VERIFY_NOT_REACHED();
return -1;
}
return p;
}
constexpr int get_unary(TokenType token) const
{
constexpr int operator_precedence_unary_plus_minus = 17;
switch (token) {
case TokenType::Minus:
case TokenType::Plus:
return operator_precedence_unary_plus_minus;
default:
return get(token);
}
}
private:
int m_token_precedence[cs_num_of_js_tokens];
struct OperatorPrecedence {
TokenType token;
int precedence;
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
static constexpr OperatorPrecedence const m_operator_precedence[] = {
{ TokenType::Period, 20 },
{ TokenType::BracketOpen, 20 },
{ TokenType::ParenOpen, 20 },
{ TokenType::QuestionMarkPeriod, 20 },
{ TokenType::New, 19 },
{ TokenType::PlusPlus, 18 },
{ TokenType::MinusMinus, 18 },
{ TokenType::ExclamationMark, 17 },
{ TokenType::Tilde, 17 },
{ TokenType::Typeof, 17 },
{ TokenType::Void, 17 },
{ TokenType::Delete, 17 },
{ TokenType::Await, 17 },
{ TokenType::DoubleAsterisk, 16 },
{ TokenType::Asterisk, 15 },
{ TokenType::Slash, 15 },
{ TokenType::Percent, 15 },
{ TokenType::Plus, 14 },
{ TokenType::Minus, 14 },
{ TokenType::ShiftLeft, 13 },
{ TokenType::ShiftRight, 13 },
{ TokenType::UnsignedShiftRight, 13 },
{ TokenType::LessThan, 12 },
{ TokenType::LessThanEquals, 12 },
{ TokenType::GreaterThan, 12 },
{ TokenType::GreaterThanEquals, 12 },
{ TokenType::In, 12 },
{ TokenType::Instanceof, 12 },
{ TokenType::EqualsEquals, 11 },
{ TokenType::ExclamationMarkEquals, 11 },
{ TokenType::EqualsEqualsEquals, 11 },
{ TokenType::ExclamationMarkEqualsEquals, 11 },
{ TokenType::Ampersand, 10 },
{ TokenType::Caret, 9 },
{ TokenType::Pipe, 8 },
{ TokenType::DoubleQuestionMark, 7 },
{ TokenType::DoubleAmpersand, 6 },
{ TokenType::DoublePipe, 5 },
{ TokenType::QuestionMark, 4 },
{ TokenType::Equals, 3 },
{ TokenType::PlusEquals, 3 },
{ TokenType::MinusEquals, 3 },
{ TokenType::DoubleAsteriskEquals, 3 },
{ TokenType::AsteriskEquals, 3 },
{ TokenType::SlashEquals, 3 },
{ TokenType::PercentEquals, 3 },
{ TokenType::ShiftLeftEquals, 3 },
{ TokenType::ShiftRightEquals, 3 },
{ TokenType::UnsignedShiftRightEquals, 3 },
{ TokenType::AmpersandEquals, 3 },
{ TokenType::CaretEquals, 3 },
{ TokenType::PipeEquals, 3 },
{ TokenType::DoubleAmpersandEquals, 3 },
{ TokenType::DoublePipeEquals, 3 },
{ TokenType::DoubleQuestionMarkEquals, 3 },
{ TokenType::Yield, 2 },
{ TokenType::Comma, 1 },
};
};
constexpr OperatorPrecedenceTable g_operator_precedence;
Parser::ParserState::ParserState(Lexer l, Program::Type program_type)
: lexer(move(l))
{
if (program_type == Program::Type::Module)
lexer.disallow_html_comments();
current_token = lexer.next();
}
Parser::Parser(Lexer lexer, Program::Type program_type, Optional<EvalInitialState> initial_state_for_eval)
: m_source_code(SourceCode::create(lexer.filename(), String::from_byte_string(lexer.source()).release_value_but_fixme_should_propagate_errors()))
, m_state(move(lexer), program_type)
, m_program_type(program_type)
{
if (initial_state_for_eval.has_value()) {
m_state.initiated_by_eval = true;
m_state.in_eval_function_context = initial_state_for_eval->in_eval_function_context;
m_state.allow_super_property_lookup = initial_state_for_eval->allow_super_property_lookup;
m_state.allow_super_constructor_call = initial_state_for_eval->allow_super_constructor_call;
m_state.in_class_field_initializer = initial_state_for_eval->in_class_field_initializer;
}
}
Associativity Parser::operator_associativity(TokenType type) const
{
switch (type) {
case TokenType::Period:
case TokenType::BracketOpen:
case TokenType::ParenOpen:
case TokenType::QuestionMarkPeriod:
case TokenType::Asterisk:
case TokenType::Slash:
case TokenType::Percent:
case TokenType::Plus:
case TokenType::Minus:
case TokenType::ShiftLeft:
case TokenType::ShiftRight:
case TokenType::UnsignedShiftRight:
case TokenType::LessThan:
case TokenType::LessThanEquals:
case TokenType::GreaterThan:
case TokenType::GreaterThanEquals:
case TokenType::In:
case TokenType::Instanceof:
case TokenType::EqualsEquals:
case TokenType::ExclamationMarkEquals:
case TokenType::EqualsEqualsEquals:
case TokenType::ExclamationMarkEqualsEquals:
case TokenType::Typeof:
case TokenType::Void:
case TokenType::Delete:
case TokenType::Await:
case TokenType::Ampersand:
case TokenType::Caret:
case TokenType::Pipe:
case TokenType::DoubleQuestionMark:
case TokenType::DoubleAmpersand:
case TokenType::DoublePipe:
case TokenType::Comma:
return Associativity::Left;
default:
return Associativity::Right;
}
}
bool Parser::parse_directive(ScopeNode& body)
{
bool found_use_strict = false;
while (!done() && match(TokenType::StringLiteral)) {
auto raw_value = m_state.current_token.original_value();
// It cannot be a labelled function since we hit a string literal.
auto statement = parse_statement(AllowLabelledFunction::No);
body.append(statement);
VERIFY(is<ExpressionStatement>(*statement));
auto& expression = static_cast<ExpressionStatement const&>(*statement).expression();
if (!is<StringLiteral>(expression))
break;
if (raw_value.is_one_of("'use strict'"sv, "\"use strict\"")) {
found_use_strict = true;
if (m_state.string_legacy_octal_escape_sequence_in_scope)
syntax_error("Octal escape sequence in string literal not allowed in strict mode");
break;
}
}
m_state.string_legacy_octal_escape_sequence_in_scope = false;
return found_use_strict;
}
NonnullRefPtr<Program> Parser::parse_program(bool starts_in_strict_mode)
{
auto rule_start = push_start();
auto program = adopt_ref(*new Program({ m_source_code, rule_start.position(), position() }, m_program_type));
ScopePusher program_scope = ScopePusher::program_scope(*this, *program);
if (m_program_type == Program::Type::Script)
parse_script(program, starts_in_strict_mode);
else
parse_module(program);
program->set_end_offset({}, position().offset);
return program;
}
void Parser::parse_script(Program& program, bool starts_in_strict_mode)
{
bool strict_before = m_state.strict_mode;
if (starts_in_strict_mode)
m_state.strict_mode = true;
bool has_use_strict = parse_directive(program);
if (m_state.strict_mode || has_use_strict) {
program.set_strict_mode();
m_state.strict_mode = true;
}
parse_statement_list(program, AllowLabelledFunction::Yes);
if (!done()) {
expected("statement or declaration");
consume();
}
m_state.strict_mode = strict_before;
}
void Parser::parse_module(Program& program)
{
TemporaryChange strict_mode_rollback(m_state.strict_mode, true);
TemporaryChange await_expression_valid_rollback(m_state.await_expression_is_valid, true);
// Since strict mode is already enabled we skip any directive parsing.
while (!done()) {
parse_statement_list(program, AllowLabelledFunction::Yes);
if (done())
break;
if (match_export_or_import()) {
VERIFY(m_state.current_token.type() == TokenType::Export || m_state.current_token.type() == TokenType::Import);
if (m_state.current_token.type() == TokenType::Export)
program.append_export(parse_export_statement(program));
else
program.append_import(parse_import_statement(program));
} else {
expected("statement or declaration");
consume();
}
}
VERIFY(m_state.current_scope_pusher);
if (m_state.current_scope_pusher->contains_await_expression())
program.set_has_top_level_await();
for (auto& export_statement : program.exports()) {
if (export_statement->has_statement())
continue;
for (auto& entry : export_statement->entries()) {
if (entry.is_module_request() || entry.kind == ExportEntry::Kind::EmptyNamedExport)
return;
auto const& exported_name = entry.local_or_import_name;
bool found = false;
// NOTE: Nothing in the callback throws an exception.
MUST(program.for_each_lexically_declared_identifier([&](auto const& identifier) {
if (identifier.string() == exported_name)
found = true;
}));
if (found)
continue;
// NOTE: Nothing in the callback throws an exception.
MUST(program.for_each_var_declared_identifier([&](auto const& identifier) {
if (identifier.string() == exported_name)
found = true;
}));
for (auto& import : program.imports()) {
if (import->has_bound_name(exported_name.value())) {
found = true;
break;
}
}
if (!found)
syntax_error(ByteString::formatted("'{}' in export is not declared", exported_name), export_statement->source_range().start);
}
}
}
NonnullRefPtr<Declaration const> Parser::parse_declaration()
{
auto rule_start = push_start();
if (m_state.current_token.type() == TokenType::Async && next_token().type() == TokenType::Function)
return parse_function_node<FunctionDeclaration>();
switch (m_state.current_token.type()) {
case TokenType::Class:
return parse_class_declaration();
case TokenType::Function:
return parse_function_node<FunctionDeclaration>();
case TokenType::Let:
case TokenType::Const:
return parse_variable_declaration();
case TokenType::Identifier:
if (m_state.current_token.original_value() == "using"sv) {
if (!m_state.current_scope_pusher->can_have_using_declaration())
syntax_error("'using' not allowed outside of block, for loop or function");
return parse_using_declaration();
}
[[fallthrough]];
default:
expected("declaration");
consume();
return create_ast_node<ErrorDeclaration>({ m_source_code, rule_start.position(), position() });
}
}
NonnullRefPtr<Statement const> Parser::parse_statement(AllowLabelledFunction allow_labelled_function)
{
auto rule_start = push_start();
auto type = m_state.current_token.type();
switch (type) {
case TokenType::CurlyOpen:
return parse_block_statement();
case TokenType::Return:
return parse_return_statement();
case TokenType::Var: {
auto declaration = parse_variable_declaration();
m_state.current_scope_pusher->add_declaration(declaration);
return declaration;
}
case TokenType::For:
return parse_for_statement();
case TokenType::If:
return parse_if_statement();
case TokenType::Throw:
return parse_throw_statement();
case TokenType::Try:
return parse_try_statement();
case TokenType::Break:
return parse_break_statement();
case TokenType::Continue:
return parse_continue_statement();
case TokenType::Switch:
return parse_switch_statement();
case TokenType::Do:
return parse_do_while_statement();
case TokenType::While:
return parse_while_statement();
case TokenType::With:
if (m_state.strict_mode)
syntax_error("'with' statement not allowed in strict mode");
return parse_with_statement();
case TokenType::Debugger:
return parse_debugger_statement();
case TokenType::Semicolon:
consume();
return create_ast_node<EmptyStatement>({ m_source_code, rule_start.position(), position() });
case TokenType::Slash:
case TokenType::SlashEquals:
m_state.current_token = m_state.lexer.force_slash_as_regex();
[[fallthrough]];
default:
if (match_invalid_escaped_keyword())
syntax_error("Keyword must not contain escaped characters");
if (match_identifier_name()) {
auto result = try_parse_labelled_statement(allow_labelled_function);
if (!result.is_null())
return result.release_nonnull();
}
if (match_expression()) {
if (match(TokenType::Async)) {
auto lookahead_token = next_token();
if (lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator())
syntax_error("Async function declaration not allowed in single-statement context");
} else if (match(TokenType::Function) || match(TokenType::Class)) {
syntax_error(ByteString::formatted("{} declaration not allowed in single-statement context", m_state.current_token.name()));
} else if (match(TokenType::Let) && next_token().type() == TokenType::BracketOpen) {
syntax_error(ByteString::formatted("let followed by [ is not allowed in single-statement context"));
}
auto expr = parse_expression(0);
consume_or_insert_semicolon();
return create_ast_node<ExpressionStatement>({ m_source_code, rule_start.position(), position() }, move(expr));
}
expected("statement");
consume();
return create_ast_node<ErrorStatement>({ m_source_code, rule_start.position(), position() });
}
}
bool Parser::match_invalid_escaped_keyword() const
{
if (m_state.current_token.type() != TokenType::EscapedKeyword)
return false;
auto token_value = m_state.current_token.value();
if (token_value == "await"sv)
return m_program_type == Program::Type::Module || m_state.await_expression_is_valid;
if (token_value == "async"sv)
return false;
if (token_value == "yield"sv)
return m_state.in_generator_function_context;
if (m_state.strict_mode)
return true;
return token_value != "let"sv;
}
static constexpr AK::Array<StringView, 9> strict_reserved_words = { "implements"sv, "interface"sv, "let"sv, "package"sv, "private"sv, "protected"sv, "public"sv, "static"sv, "yield"sv };
static bool is_strict_reserved_word(StringView str)
{
return any_of(strict_reserved_words, [&str](StringView word) {
return word == str;
});
}
static bool is_simple_parameter_list(Vector<FunctionParameter> const& parameters)
{
return all_of(parameters, [](FunctionParameter const& parameter) {
return !parameter.is_rest && parameter.default_value.is_null() && parameter.binding.has<NonnullRefPtr<Identifier const>>();
});
}
RefPtr<FunctionExpression const> Parser::try_parse_arrow_function_expression(bool expect_parens, bool is_async)
{
if (is_async)
VERIFY(match(TokenType::Async));
if (!expect_parens && !is_async) {
// NOTE: This is a fast path where we try to fail early in case this can't possibly
// be a match. The idea is to avoid the expensive parser state save/load mechanism.
// The logic is duplicated below in the "real" !expect_parens branch.
if (!match_identifier() && !match(TokenType::Yield) && !match(TokenType::Await))
return nullptr;
auto token = next_token();
if (token.trivia_contains_line_terminator())
return nullptr;
if (token.type() != TokenType::Arrow)
return nullptr;
}