forked from SerenityOS/serenity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AST.cpp
4980 lines (4135 loc) Β· 200 KB
/
AST.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-2021, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
* Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Demangle.h>
#include <AK/HashMap.h>
#include <AK/HashTable.h>
#include <AK/QuickSort.h>
#include <AK/ScopeGuard.h>
#include <AK/StringBuilder.h>
#include <AK/TemporaryChange.h>
#include <LibCrypto/BigInt/SignedBigInteger.h>
#include <LibJS/AST.h>
#include <LibJS/Heap/MarkedVector.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Accessor.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/ECMAScriptFunctionObject.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionEnvironment.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/IteratorOperations.h>
#include <LibJS/Runtime/NativeFunction.h>
#include <LibJS/Runtime/ObjectEnvironment.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/PromiseCapability.h>
#include <LibJS/Runtime/PromiseConstructor.h>
#include <LibJS/Runtime/Reference.h>
#include <LibJS/Runtime/RegExpObject.h>
#include <LibJS/Runtime/Shape.h>
#include <typeinfo>
namespace JS {
class InterpreterNodeScope {
AK_MAKE_NONCOPYABLE(InterpreterNodeScope);
AK_MAKE_NONMOVABLE(InterpreterNodeScope);
public:
InterpreterNodeScope(Interpreter& interpreter, ASTNode const& node)
: m_interpreter(interpreter)
, m_chain_node { nullptr, node }
{
m_interpreter.vm().running_execution_context().current_node = &node;
m_interpreter.push_ast_node(m_chain_node);
}
~InterpreterNodeScope()
{
m_interpreter.pop_ast_node();
}
private:
Interpreter& m_interpreter;
ExecutingASTNodeChain m_chain_node;
};
ASTNode::ASTNode(SourceRange source_range)
: m_start_offset(source_range.start.offset)
, m_source_code(source_range.code)
, m_end_offset(source_range.end.offset)
{
}
SourceRange ASTNode::source_range() const
{
return m_source_code->range_from_offsets(m_start_offset, m_end_offset);
}
DeprecatedString ASTNode::class_name() const
{
// NOTE: We strip the "JS::" prefix.
auto const* typename_ptr = typeid(*this).name();
return demangle({ typename_ptr, strlen(typename_ptr) }).substring(4);
}
static void print_indent(int indent)
{
out("{}", DeprecatedString::repeated(' ', indent * 2));
}
static void update_function_name(Value value, DeprecatedFlyString const& name)
{
if (!value.is_function())
return;
auto& function = value.as_function();
if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
static_cast<ECMAScriptFunctionObject&>(function).set_name(name);
}
static ThrowCompletionOr<DeprecatedString> get_function_property_name(PropertyKey key)
{
if (key.is_symbol())
return DeprecatedString::formatted("[{}]", key.as_symbol()->description());
return key.to_string();
}
// 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
// StatementList : StatementList StatementListItem
Completion ScopeNode::evaluate_statements(Interpreter& interpreter) const
{
auto completion = normal_completion({});
for (auto const& node : children()) {
completion = node.execute(interpreter).update_empty(completion.value());
if (completion.is_abrupt())
break;
}
return completion;
}
// 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
// BreakableStatement : IterationStatement
static Completion labelled_evaluation(Interpreter& interpreter, IterationStatement const& statement, Vector<DeprecatedFlyString> const& label_set)
{
// 1. Let stmtResult be Completion(LoopEvaluation of IterationStatement with argument labelSet).
auto result = statement.loop_evaluation(interpreter, label_set);
// 2. If stmtResult.[[Type]] is break, then
if (result.type() == Completion::Type::Break) {
// a. If stmtResult.[[Target]] is empty, then
if (!result.target().has_value()) {
// i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
// ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
result = normal_completion(result.value().value_or(js_undefined()));
}
}
// 3. Return ? stmtResult.
return result;
}
// 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
// BreakableStatement : SwitchStatement
static Completion labelled_evaluation(Interpreter& interpreter, SwitchStatement const& statement, Vector<DeprecatedFlyString> const&)
{
// 1. Let stmtResult be the result of evaluating SwitchStatement.
auto result = statement.execute_impl(interpreter);
// 2. If stmtResult.[[Type]] is break, then
if (result.type() == Completion::Type::Break) {
// a. If stmtResult.[[Target]] is empty, then
if (!result.target().has_value()) {
// i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
// ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
result = normal_completion(result.value().value_or(js_undefined()));
}
}
// 3. Return ? stmtResult.
return result;
}
// 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
// LabelledStatement : LabelIdentifier : LabelledItem
static Completion labelled_evaluation(Interpreter& interpreter, LabelledStatement const& statement, Vector<DeprecatedFlyString> const& label_set)
{
auto const& labelled_item = *statement.labelled_item();
// 1. Let label be the StringValue of LabelIdentifier.
auto const& label = statement.label();
// 2. Let newLabelSet be the list-concatenation of labelSet and Β« label Β».
// Optimization: Avoid vector copy if possible.
Optional<Vector<DeprecatedFlyString>> new_label_set;
if (is<IterationStatement>(labelled_item) || is<SwitchStatement>(labelled_item) || is<LabelledStatement>(labelled_item)) {
new_label_set = label_set;
new_label_set->append(label);
}
// 3. Let stmtResult be Completion(LabelledEvaluation of LabelledItem with argument newLabelSet).
Completion result;
if (is<IterationStatement>(labelled_item))
result = labelled_evaluation(interpreter, static_cast<IterationStatement const&>(labelled_item), *new_label_set);
else if (is<SwitchStatement>(labelled_item))
result = labelled_evaluation(interpreter, static_cast<SwitchStatement const&>(labelled_item), *new_label_set);
else if (is<LabelledStatement>(labelled_item))
result = labelled_evaluation(interpreter, static_cast<LabelledStatement const&>(labelled_item), *new_label_set);
else
result = labelled_item.execute(interpreter);
// 4. If stmtResult.[[Type]] is break and SameValue(stmtResult.[[Target]], label) is true, then
if (result.type() == Completion::Type::Break && result.target() == label) {
// a. Set stmtResult to NormalCompletion(stmtResult.[[Value]]).
result = normal_completion(result.value());
}
// 5. Return ? stmtResult.
return result;
}
// 14.13.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-labelled-statements-runtime-semantics-evaluation
Completion LabelledStatement::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// 1. Return ? LabelledEvaluation of this LabelledStatement with argument Β« Β».
return labelled_evaluation(interpreter, *this, {});
}
void LabelledStatement::dump(int indent) const
{
ASTNode::dump(indent);
print_indent(indent + 1);
outln("(Label)");
print_indent(indent + 2);
outln("\"{}\"", m_label);
print_indent(indent + 1);
outln("(Labelled item)");
m_labelled_item->dump(indent + 2);
}
// 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
Completion FunctionBody::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// Note: Scoping should have already been set up by whoever is calling this FunctionBody.
// 1. Return ? EvaluateFunctionBody of FunctionBody with arguments functionObject and argumentsList.
return evaluate_statements(interpreter);
}
// 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
Completion BlockStatement::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
Environment* old_environment { nullptr };
// Optimization: We only need a new lexical environment if there are any lexical declarations. :^)
if (!has_lexical_declarations())
return evaluate_statements(interpreter);
old_environment = vm.running_execution_context().lexical_environment;
auto block_environment = new_declarative_environment(*old_environment);
block_declaration_instantiation(interpreter, block_environment);
vm.running_execution_context().lexical_environment = block_environment;
// 5. Let blockValue be the result of evaluating StatementList.
auto block_value = evaluate_statements(interpreter);
// 6. Set blockValue to DisposeResources(blockEnv, blockValue).
block_value = dispose_resources(vm, block_environment, block_value);
vm.running_execution_context().lexical_environment = old_environment;
return block_value;
}
Completion Program::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
return evaluate_statements(interpreter);
}
// 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
Completion FunctionDeclaration::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
if (m_is_hoisted) {
// Perform special annexB steps see step 3 of: https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
// i. Let genv be the running execution context's VariableEnvironment.
auto* variable_environment = interpreter.vm().running_execution_context().variable_environment;
// ii. Let benv be the running execution context's LexicalEnvironment.
auto* lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
// iii. Let fobj be ! benv.GetBindingValue(F, false).
auto function_object = MUST(lexical_environment->get_binding_value(vm, name(), false));
// iv. Perform ? genv.SetMutableBinding(F, fobj, false).
TRY(variable_environment->set_mutable_binding(vm, name(), function_object, false));
// v. Return unused.
return Optional<Value> {};
}
// 1. Return unused.
return Optional<Value> {};
}
// 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
Completion FunctionExpression::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// 1. Return InstantiateOrdinaryFunctionExpression of FunctionExpression.
return instantiate_ordinary_function_expression(interpreter, name());
}
// 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
Value FunctionExpression::instantiate_ordinary_function_expression(Interpreter& interpreter, DeprecatedFlyString given_name) const
{
auto& vm = interpreter.vm();
auto& realm = *vm.current_realm();
if (given_name.is_empty())
given_name = "";
auto has_own_name = !name().is_empty();
auto const& used_name = has_own_name ? name() : given_name;
auto environment = NonnullGCPtr { *interpreter.lexical_environment() };
if (has_own_name) {
VERIFY(environment);
environment = new_declarative_environment(*environment);
MUST(environment->create_immutable_binding(vm, name(), false));
}
auto* private_environment = vm.running_execution_context().private_environment;
auto closure = ECMAScriptFunctionObject::create(realm, used_name, source_text(), body(), parameters(), function_length(), environment, private_environment, kind(), is_strict_mode(), might_need_arguments_object(), contains_direct_call_to_eval(), is_arrow_function());
// FIXME: 6. Perform SetFunctionName(closure, name).
// FIXME: 7. Perform MakeConstructor(closure).
if (has_own_name)
MUST(environment->initialize_binding(vm, name(), closure, Environment::InitializeBindingHint::Normal));
return closure;
}
// 14.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-empty-statement-runtime-semantics-evaluation
Completion EmptyStatement::execute(Interpreter&) const
{
// 1. Return empty.
return Optional<Value> {};
}
// 14.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-expression-statement-runtime-semantics-evaluation
Completion ExpressionStatement::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// 1. Let exprRef be the result of evaluating Expression.
// 2. Return ? GetValue(exprRef).
return m_expression->execute(interpreter);
}
// TODO: This shouldn't exist. Refactor into EvaluateCall.
ThrowCompletionOr<CallExpression::ThisAndCallee> CallExpression::compute_this_and_callee(Interpreter& interpreter, Reference const& callee_reference) const
{
auto& vm = interpreter.vm();
if (callee_reference.is_property_reference()) {
auto this_value = callee_reference.get_this_value();
auto callee = TRY(callee_reference.get_value(vm));
return ThisAndCallee { this_value, callee };
}
Value this_value = js_undefined();
if (callee_reference.is_environment_reference()) {
if (Object* base_object = callee_reference.base_environment().with_base_object(); base_object != nullptr)
this_value = base_object;
}
// [[Call]] will handle that in non-strict mode the this value becomes the global object
return ThisAndCallee {
this_value,
callee_reference.is_unresolvable()
? TRY(m_callee->execute(interpreter)).release_value()
: TRY(callee_reference.get_value(vm))
};
}
// 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
static ThrowCompletionOr<void> argument_list_evaluation(Interpreter& interpreter, Span<CallExpression::Argument const> const arguments, MarkedVector<Value>& list)
{
auto& vm = interpreter.vm();
list.ensure_capacity(arguments.size());
for (auto& argument : arguments) {
auto value = TRY(argument.value->execute(interpreter)).release_value();
if (argument.is_spread) {
TRY(get_iterator_values(vm, value, [&](Value iterator_value) -> Optional<Completion> {
list.append(iterator_value);
return {};
}));
} else {
list.append(value);
}
}
return {};
}
// 13.3.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-new-operator-runtime-semantics-evaluation
// 13.3.5.1.1 EvaluateNew ( constructExpr, arguments ), https://tc39.es/ecma262/#sec-evaluatenew
Completion NewExpression::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
// 1. Let ref be the result of evaluating constructExpr.
// 2. Let constructor be ? GetValue(ref).
auto constructor = TRY(m_callee->execute(interpreter)).release_value();
// 3. If arguments is empty, let argList be a new empty List.
// 4. Else,
// a. Let argList be ? ArgumentListEvaluation of arguments.
MarkedVector<Value> arg_list(vm.heap());
TRY(argument_list_evaluation(interpreter, arguments(), arg_list));
// 5. If IsConstructor(constructor) is false, throw a TypeError exception.
if (!constructor.is_constructor())
return throw_type_error_for_callee(interpreter, constructor, "constructor"sv);
// 6. Return ? Construct(constructor, argList).
return Value { TRY(construct(vm, constructor.as_function(), move(arg_list))) };
}
Optional<DeprecatedString> CallExpression::expression_string() const
{
if (is<Identifier>(*m_callee))
return static_cast<Identifier const&>(*m_callee).string();
if (is<MemberExpression>(*m_callee))
return static_cast<MemberExpression const&>(*m_callee).to_string_approximation();
return {};
}
Completion CallExpression::throw_type_error_for_callee(Interpreter& interpreter, Value callee_value, StringView call_type) const
{
auto& vm = interpreter.vm();
if (auto expression_string = this->expression_string(); expression_string.has_value())
return vm.throw_completion<TypeError>(ErrorType::IsNotAEvaluatedFrom, callee_value.to_string_without_side_effects(), call_type, expression_string.release_value());
return vm.throw_completion<TypeError>(ErrorType::IsNotA, callee_value.to_string_without_side_effects(), call_type);
}
// 13.3.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation
Completion CallExpression::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
auto& realm = *vm.current_realm();
auto callee_reference = TRY(m_callee->to_reference(interpreter));
auto [this_value, callee] = TRY(compute_this_and_callee(interpreter, callee_reference));
VERIFY(!callee.is_empty());
MarkedVector<Value> arg_list(vm.heap());
TRY(argument_list_evaluation(interpreter, arguments(), arg_list));
if (!callee.is_function())
return throw_type_error_for_callee(interpreter, callee, "function"sv);
auto& function = callee.as_function();
if (&function == realm.intrinsics().eval_function()
&& callee_reference.is_environment_reference()
&& callee_reference.name().is_string()
&& callee_reference.name().as_string() == vm.names.eval.as_string()) {
auto script_value = arg_list.size() == 0 ? js_undefined() : arg_list[0];
return perform_eval(vm, script_value, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct);
}
return call(vm, function, this_value, move(arg_list));
}
// 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
// SuperCall : super Arguments
Completion SuperCall::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
// 1. Let newTarget be GetNewTarget().
auto new_target = vm.get_new_target();
// 2. Assert: Type(newTarget) is Object.
VERIFY(new_target.is_function());
// 3. Let func be GetSuperConstructor().
auto* func = get_super_constructor(interpreter.vm());
// 4. Let argList be ? ArgumentListEvaluation of Arguments.
MarkedVector<Value> arg_list(vm.heap());
if (m_is_synthetic == IsPartOfSyntheticConstructor::Yes) {
// NOTE: This is the case where we have a fake constructor(...args) { super(...args); } which
// shouldn't call @@iterator of %Array.prototype%.
VERIFY(m_arguments.size() == 1);
VERIFY(m_arguments[0].is_spread);
auto const& argument = m_arguments[0];
auto value = MUST(argument.value->execute(interpreter)).release_value();
VERIFY(value.is_object() && is<Array>(value.as_object()));
auto& array_value = static_cast<Array const&>(value.as_object());
auto length = MUST(length_of_array_like(vm, array_value));
for (size_t i = 0; i < length; ++i)
arg_list.append(array_value.get_without_side_effects(PropertyKey { i }));
} else {
TRY(argument_list_evaluation(interpreter, m_arguments, arg_list));
}
// 5. If IsConstructor(func) is false, throw a TypeError exception.
if (!func || !Value(func).is_constructor())
return vm.throw_completion<TypeError>(ErrorType::NotAConstructor, "Super constructor");
// 6. Let result be ? Construct(func, argList, newTarget).
auto result = TRY(construct(vm, static_cast<FunctionObject&>(*func), move(arg_list), &new_target.as_function()));
// 7. Let thisER be GetThisEnvironment().
auto& this_er = verify_cast<FunctionEnvironment>(*get_this_environment(vm));
// 8. Perform ? thisER.BindThisValue(result).
TRY(this_er.bind_this_value(vm, result));
// 9. Let F be thisER.[[FunctionObject]].
// 10. Assert: F is an ECMAScript function object.
// NOTE: This is implied by the strong C++ type.
[[maybe_unused]] auto& f = this_er.function_object();
// 11. Perform ? InitializeInstanceElements(result, F).
TRY(result->initialize_instance_elements(f));
// 12. Return result.
return Value { result };
}
// 15.5.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation
Completion YieldExpression::execute(Interpreter&) const
{
// This should be transformed to a return.
VERIFY_NOT_REACHED();
}
// 15.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-async-function-definitions-runtime-semantics-evaluation
Completion AwaitExpression::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
// 1. Let exprRef be the result of evaluating UnaryExpression.
// 2. Let value be ? GetValue(exprRef).
auto value = TRY(m_argument->execute(interpreter)).release_value();
// 3. Return ? Await(value).
return await(vm, value);
}
// 14.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-return-statement-runtime-semantics-evaluation
Completion ReturnStatement::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// ReturnStatement : return ;
if (!m_argument) {
// 1. Return Completion Record { [[Type]]: return, [[Value]]: undefined, [[Target]]: empty }.
return { Completion::Type::Return, js_undefined(), {} };
}
// ReturnStatement : return Expression ;
// 1. Let exprRef be the result of evaluating Expression.
// 2. Let exprValue be ? GetValue(exprRef).
auto value = TRY(m_argument->execute(interpreter));
// NOTE: Generators are not supported in the AST interpreter
// 3. If GetGeneratorKind() is async, set exprValue to ? Await(exprValue).
// 4. Return Completion Record { [[Type]]: return, [[Value]]: exprValue, [[Target]]: empty }.
return { Completion::Type::Return, value, {} };
}
// 14.6.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-if-statement-runtime-semantics-evaluation
Completion IfStatement::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// IfStatement : if ( Expression ) Statement else Statement
// 1. Let exprRef be the result of evaluating Expression.
// 2. Let exprValue be ToBoolean(? GetValue(exprRef)).
auto predicate_result = TRY(m_predicate->execute(interpreter)).release_value();
// 3. If exprValue is true, then
if (predicate_result.to_boolean()) {
// a. Let stmtCompletion be the result of evaluating the first Statement.
// 5. Return ? UpdateEmpty(stmtCompletion, undefined).
return m_consequent->execute(interpreter).update_empty(js_undefined());
}
// 4. Else,
if (m_alternate) {
// a. Let stmtCompletion be the result of evaluating the second Statement.
// 5. Return ? UpdateEmpty(stmtCompletion, undefined).
return m_alternate->execute(interpreter).update_empty(js_undefined());
}
// IfStatement : if ( Expression ) Statement
// 3. If exprValue is false, then
// a. Return undefined.
return js_undefined();
}
// 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation
// WithStatement : with ( Expression ) Statement
Completion WithStatement::execute(Interpreter& interpreter) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
// 1. Let value be the result of evaluating Expression.
auto value = TRY(m_object->execute(interpreter)).release_value();
// 2. Let obj be ? ToObject(? GetValue(value)).
auto* object = TRY(value.to_object(vm));
// 3. Let oldEnv be the running execution context's LexicalEnvironment.
auto* old_environment = vm.running_execution_context().lexical_environment;
// 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
auto new_environment = new_object_environment(*object, true, old_environment);
// 5. Set the running execution context's LexicalEnvironment to newEnv.
vm.running_execution_context().lexical_environment = new_environment;
// 6. Let C be the result of evaluating Statement.
auto result = m_body->execute(interpreter);
// 7. Set the running execution context's LexicalEnvironment to oldEnv.
vm.running_execution_context().lexical_environment = old_environment;
// 8. Return ? UpdateEmpty(C, undefined).
return result.update_empty(js_undefined());
}
// 14.7.1.1 LoopContinues ( completion, labelSet ), https://tc39.es/ecma262/#sec-loopcontinues
static bool loop_continues(Completion const& completion, Vector<DeprecatedFlyString> const& label_set)
{
// 1. If completion.[[Type]] is normal, return true.
if (completion.type() == Completion::Type::Normal)
return true;
// 2. If completion.[[Type]] is not continue, return false.
if (completion.type() != Completion::Type::Continue)
return false;
// 3. If completion.[[Target]] is empty, return true.
if (!completion.target().has_value())
return true;
// 4. If completion.[[Target]] is an element of labelSet, return true.
if (label_set.contains_slow(*completion.target()))
return true;
// 5. Return false.
return false;
}
// 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
// BreakableStatement : IterationStatement
Completion WhileStatement::execute(Interpreter& interpreter) const
{
// 1. Let newLabelSet be a new empty List.
// 2. Return ? LabelledEvaluation of this BreakableStatement with argument newLabelSet.
return labelled_evaluation(interpreter, *this, {});
}
// 14.7.3.2 Runtime Semantics: WhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-whileloopevaluation
Completion WhileStatement::loop_evaluation(Interpreter& interpreter, Vector<DeprecatedFlyString> const& label_set) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// 1. Let V be undefined.
auto last_value = js_undefined();
// 2. Repeat,
for (;;) {
// a. Let exprRef be the result of evaluating Expression.
// b. Let exprValue be ? GetValue(exprRef).
auto test_result = TRY(m_test->execute(interpreter)).release_value();
// c. If ToBoolean(exprValue) is false, return V.
if (!test_result.to_boolean())
return last_value;
// d. Let stmtResult be the result of evaluating Statement.
auto body_result = m_body->execute(interpreter);
// e. If LoopContinues(stmtResult, labelSet) is false, return ? UpdateEmpty(stmtResult, V).
if (!loop_continues(body_result, label_set))
return body_result.update_empty(last_value);
// f. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
if (body_result.value().has_value())
last_value = *body_result.value();
}
VERIFY_NOT_REACHED();
}
// 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
// BreakableStatement : IterationStatement
Completion DoWhileStatement::execute(Interpreter& interpreter) const
{
// 1. Let newLabelSet be a new empty List.
// 2. Return ? LabelledEvaluation of this BreakableStatement with argument newLabelSet.
return labelled_evaluation(interpreter, *this, {});
}
// 14.7.2.2 Runtime Semantics: DoWhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-dowhileloopevaluation
Completion DoWhileStatement::loop_evaluation(Interpreter& interpreter, Vector<DeprecatedFlyString> const& label_set) const
{
InterpreterNodeScope node_scope { interpreter, *this };
// 1. Let V be undefined.
auto last_value = js_undefined();
// 2. Repeat,
for (;;) {
// a. Let stmtResult be the result of evaluating Statement.
auto body_result = m_body->execute(interpreter);
// b. If LoopContinues(stmtResult, labelSet) is false, return ? UpdateEmpty(stmtResult, V).
if (!loop_continues(body_result, label_set))
return body_result.update_empty(last_value);
// c. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
if (body_result.value().has_value())
last_value = *body_result.value();
// d. Let exprRef be the result of evaluating Expression.
// e. Let exprValue be ? GetValue(exprRef).
auto test_result = TRY(m_test->execute(interpreter)).release_value();
// f. If ToBoolean(exprValue) is false, return V.
if (!test_result.to_boolean())
return last_value;
}
VERIFY_NOT_REACHED();
}
// 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
// BreakableStatement : IterationStatement
Completion ForStatement::execute(Interpreter& interpreter) const
{
// 1. Let newLabelSet be a new empty List.
// 2. Return ? LabelledEvaluation of this BreakableStatement with argument newLabelSet.
return labelled_evaluation(interpreter, *this, {});
}
// 14.7.4.2 Runtime Semantics: ForLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forloopevaluation
Completion ForStatement::loop_evaluation(Interpreter& interpreter, Vector<DeprecatedFlyString> const& label_set) const
{
InterpreterNodeScope node_scope { interpreter, *this };
auto& vm = interpreter.vm();
// Note we don't always set a new environment but to use RAII we must do this here.
auto* old_environment = interpreter.lexical_environment();
size_t per_iteration_bindings_size = 0;
GCPtr<DeclarativeEnvironment> loop_env;
if (m_init) {
Declaration const* declaration = nullptr;
if (is<VariableDeclaration>(*m_init) && static_cast<VariableDeclaration const&>(*m_init).declaration_kind() != DeclarationKind::Var)
declaration = static_cast<VariableDeclaration const*>(m_init.ptr());
else if (is<UsingDeclaration>(*m_init))
declaration = static_cast<UsingDeclaration const*>(m_init.ptr());
if (declaration) {
loop_env = new_declarative_environment(*old_environment);
auto is_const = declaration->is_constant_declaration();
declaration->for_each_bound_name([&](auto const& name) {
if (is_const) {
MUST(loop_env->create_immutable_binding(vm, name, true));
} else {
MUST(loop_env->create_mutable_binding(vm, name, false));
++per_iteration_bindings_size;
}
});
interpreter.vm().running_execution_context().lexical_environment = loop_env;
}
(void)TRY(m_init->execute(interpreter));
}
// 10. Let bodyResult be Completion(ForBodyEvaluation(the first Expression, the second Expression, Statement, perIterationLets, labelSet)).
auto body_result = for_body_evaluation(interpreter, label_set, per_iteration_bindings_size);
// 11. Set bodyResult to DisposeResources(loopEnv, bodyResult).
if (loop_env)
body_result = dispose_resources(vm, loop_env.ptr(), body_result);
// 12. Set the running execution context's LexicalEnvironment to oldEnv.
interpreter.vm().running_execution_context().lexical_environment = old_environment;
// 13. Return ? bodyResult.
return body_result;
}
// 14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet ), https://tc39.es/ecma262/#sec-forbodyevaluation
// 6.3.1.2 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet ), https://tc39.es/proposal-explicit-resource-management/#sec-forbodyevaluation
Completion ForStatement::for_body_evaluation(JS::Interpreter& interpreter, Vector<DeprecatedFlyString> const& label_set, size_t per_iteration_bindings_size) const
{
auto& vm = interpreter.vm();
// 14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings ), https://tc39.es/ecma262/#sec-createperiterationenvironment
// NOTE: Our implementation of this AO is heavily dependent on DeclarativeEnvironment using a Vector with constant indices.
// For performance, we can take advantage of the fact that the declarations of the initialization statement are created
// in the same order each time CreatePerIterationEnvironment is invoked.
auto create_per_iteration_environment = [&]() -> GCPtr<DeclarativeEnvironment> {
// 1. If perIterationBindings has any elements, then
if (per_iteration_bindings_size == 0) {
// 2. Return unused.
return nullptr;
}
// a. Let lastIterationEnv be the running execution context's LexicalEnvironment.
auto* last_iteration_env = verify_cast<DeclarativeEnvironment>(interpreter.lexical_environment());
// b. Let outer be lastIterationEnv.[[OuterEnv]].
// c. Assert: outer is not null.
VERIFY(last_iteration_env->outer_environment());
// d. Let thisIterationEnv be NewDeclarativeEnvironment(outer).
auto this_iteration_env = DeclarativeEnvironment::create_for_per_iteration_bindings({}, *last_iteration_env, per_iteration_bindings_size);
// e. For each element bn of perIterationBindings, do
// i. Perform ! thisIterationEnv.CreateMutableBinding(bn, false).
// ii. Let lastValue be ? lastIterationEnv.GetBindingValue(bn, true).
// iii. Perform ! thisIterationEnv.InitializeBinding(bn, lastValue).
//
// NOTE: This is handled by DeclarativeEnvironment::create_for_per_iteration_bindings. Step e.ii indicates it may throw,
// but that is not possible. The potential for throwing was added to accommodate support for do-expressions in the
// initialization statement, but that idea was dropped: https://github.com/tc39/ecma262/issues/299#issuecomment-172950045
// f. Set the running execution context's LexicalEnvironment to thisIterationEnv.
interpreter.vm().running_execution_context().lexical_environment = this_iteration_env;
// g. Return thisIterationEnv.
return this_iteration_env;
};
// 1. Let V be undefined.
auto last_value = js_undefined();
// 2. Let thisIterationEnv be ? CreatePerIterationEnvironment(perIterationBindings).
auto this_iteration_env = create_per_iteration_environment();
// 3. Repeat,
while (true) {
// a. If test is not [empty], then
if (m_test) {
// i. Let testRef be the result of evaluating test.
// ii. Let testValue be Completion(GetValue(testRef)).
auto test_value = m_test->execute(interpreter);
// iii. If testValue is an abrupt completion, then
if (test_value.is_abrupt()) {
// 1. Return ? DisposeResources(thisIterationEnv, testValue).
return TRY(dispose_resources(vm, this_iteration_env, test_value));
}
// iv. Else,
// 1. Set testValue to testValue.[[Value]].
VERIFY(test_value.value().has_value());
// iii. If ToBoolean(testValue) is false, return ? DisposeResources(thisIterationEnv, Completion(V)).
if (!test_value.release_value().value().to_boolean())
return TRY(dispose_resources(vm, this_iteration_env, test_value));
}
// b. Let result be the result of evaluating stmt.
auto result = m_body->execute(interpreter);
// c. Perform ? DisposeResources(thisIterationEnv, result).
TRY(dispose_resources(vm, this_iteration_env, result));
// d. If LoopContinues(result, labelSet) is false, return ? UpdateEmpty(result, V).
if (!loop_continues(result, label_set))
return result.update_empty(last_value);
// e. If result.[[Value]] is not empty, set V to result.[[Value]].
if (result.value().has_value())
last_value = *result.value();
// f. Set thisIterationEnv to ? CreatePerIterationEnvironment(perIterationBindings).
this_iteration_env = create_per_iteration_environment();
// g. If increment is not [empty], then
if (m_update) {
// i. Let incRef be the result of evaluating increment.
// ii. Let incrResult be Completion(GetValue(incrRef)).
auto inc_ref = m_update->execute(interpreter);
// ii. If incrResult is an abrupt completion, then
if (inc_ref.is_abrupt()) {
// 1. Return ? DisposeResources(thisIterationEnv, incrResult).
return TRY(dispose_resources(vm, this_iteration_env, inc_ref));
}
}
}
VERIFY_NOT_REACHED();
}
struct ForInOfHeadState {
explicit ForInOfHeadState(Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs)
{
lhs.visit(
[&](NonnullRefPtr<ASTNode>& ast_node) {
expression_lhs = ast_node.ptr();
},
[&](NonnullRefPtr<BindingPattern>& pattern) {
pattern_lhs = pattern.ptr();
destructuring = true;
lhs_kind = Assignment;
});
}
ASTNode* expression_lhs = nullptr;
BindingPattern* pattern_lhs = nullptr;
enum LhsKind {
Assignment,
VarBinding,
LexicalBinding
};
LhsKind lhs_kind = Assignment;
bool destructuring = false;
Value rhs_value;
// 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
// Note: This is only steps 6.g through 6.j of the method because we currently implement for-in without an iterator so to prevent duplicated code we do this part here.
ThrowCompletionOr<void> execute_head(Interpreter& interpreter, Value next_value) const
{
VERIFY(!next_value.is_empty());
auto& vm = interpreter.vm();
Optional<Reference> lhs_reference;
GCPtr<Environment> iteration_environment;
// g. If lhsKind is either assignment or varBinding, then
if (lhs_kind == Assignment || lhs_kind == VarBinding) {
if (!destructuring) {
VERIFY(expression_lhs);
if (is<VariableDeclaration>(*expression_lhs)) {
auto& declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
VERIFY(declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
lhs_reference = TRY(declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->to_reference(interpreter));
} else if (is<UsingDeclaration>(*expression_lhs)) {
auto& declaration = static_cast<UsingDeclaration const&>(*expression_lhs);
VERIFY(declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
lhs_reference = TRY(declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->to_reference(interpreter));
} else {
VERIFY(is<Identifier>(*expression_lhs) || is<MemberExpression>(*expression_lhs) || is<CallExpression>(*expression_lhs));
auto& expression = static_cast<Expression const&>(*expression_lhs);
lhs_reference = TRY(expression.to_reference(interpreter));
}
}
}
// h. Else,
else {
VERIFY(expression_lhs && (is<VariableDeclaration>(*expression_lhs) || is<UsingDeclaration>(*expression_lhs)));
iteration_environment = new_declarative_environment(*interpreter.lexical_environment());
auto& for_declaration = static_cast<Declaration const&>(*expression_lhs);
DeprecatedFlyString first_name;
// 14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation, https://tc39.es/ecma262/#sec-runtime-semantics-fordeclarationbindinginstantiation
// 1. For each element name of the BoundNames of ForBinding, do
for_declaration.for_each_bound_name([&](auto const& name) {
if (first_name.is_empty())
first_name = name;
// a. If IsConstantDeclaration of LetOrConst is true, then
if (for_declaration.is_constant_declaration()) {
// i. Perform ! environment.CreateImmutableBinding(name, true).
MUST(iteration_environment->create_immutable_binding(vm, name, true));
}
// b. Else,
else {
// i. Perform ! environment.CreateMutableBinding(name, false).
MUST(iteration_environment->create_mutable_binding(vm, name, false));
}
});
interpreter.vm().running_execution_context().lexical_environment = iteration_environment;
if (!destructuring) {
VERIFY(!first_name.is_empty());