/src/serenity/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org> |
3 | | * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org> |
4 | | * |
5 | | * SPDX-License-Identifier: BSD-2-Clause |
6 | | */ |
7 | | |
8 | | #include <AK/Debug.h> |
9 | | #include <AK/Function.h> |
10 | | #include <LibJS/AST.h> |
11 | | #include <LibJS/Bytecode/BasicBlock.h> |
12 | | #include <LibJS/Bytecode/Generator.h> |
13 | | #include <LibJS/Bytecode/Interpreter.h> |
14 | | #include <LibJS/Interpreter.h> |
15 | | #include <LibJS/Runtime/AbstractOperations.h> |
16 | | #include <LibJS/Runtime/Array.h> |
17 | | #include <LibJS/Runtime/AsyncFunctionDriverWrapper.h> |
18 | | #include <LibJS/Runtime/ECMAScriptFunctionObject.h> |
19 | | #include <LibJS/Runtime/Error.h> |
20 | | #include <LibJS/Runtime/ExecutionContext.h> |
21 | | #include <LibJS/Runtime/FunctionEnvironment.h> |
22 | | #include <LibJS/Runtime/GeneratorObject.h> |
23 | | #include <LibJS/Runtime/GlobalObject.h> |
24 | | #include <LibJS/Runtime/NativeFunction.h> |
25 | | #include <LibJS/Runtime/PromiseConstructor.h> |
26 | | #include <LibJS/Runtime/PromiseReaction.h> |
27 | | #include <LibJS/Runtime/Value.h> |
28 | | |
29 | | namespace JS { |
30 | | |
31 | | ECMAScriptFunctionObject* ECMAScriptFunctionObject::create(GlobalObject& global_object, FlyString name, String source_text, Statement const& ecmascript_code, Vector<FunctionNode::Parameter> parameters, i32 m_function_length, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function, Variant<PropertyKey, PrivateName, Empty> class_field_initializer_name) |
32 | 342k | { |
33 | 342k | Object* prototype = nullptr; |
34 | 342k | switch (kind) { |
35 | 342k | case FunctionKind::Normal: |
36 | 342k | prototype = global_object.function_prototype(); |
37 | 342k | break; |
38 | 0 | case FunctionKind::Generator: |
39 | 0 | prototype = global_object.generator_function_prototype(); |
40 | 0 | break; |
41 | 0 | case FunctionKind::Async: |
42 | 0 | prototype = global_object.async_function_prototype(); |
43 | 0 | break; |
44 | 0 | case FunctionKind::AsyncGenerator: |
45 | 0 | prototype = global_object.async_generator_function_prototype(); |
46 | 0 | break; |
47 | 342k | } |
48 | 342k | return global_object.heap().allocate<ECMAScriptFunctionObject>(global_object, move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, parent_environment, private_environment, *prototype, kind, is_strict, might_need_arguments_object, contains_direct_call_to_eval, is_arrow_function, move(class_field_initializer_name)); |
49 | 342k | } |
50 | | |
51 | | ECMAScriptFunctionObject* ECMAScriptFunctionObject::create(GlobalObject& global_object, FlyString name, Object& prototype, String source_text, Statement const& ecmascript_code, Vector<FunctionNode::Parameter> parameters, i32 m_function_length, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function, Variant<PropertyKey, PrivateName, Empty> class_field_initializer_name) |
52 | 0 | { |
53 | 0 | return global_object.heap().allocate<ECMAScriptFunctionObject>(global_object, move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, parent_environment, private_environment, prototype, kind, is_strict, might_need_arguments_object, contains_direct_call_to_eval, is_arrow_function, move(class_field_initializer_name)); |
54 | 0 | } |
55 | | |
56 | | ECMAScriptFunctionObject::ECMAScriptFunctionObject(FlyString name, String source_text, Statement const& ecmascript_code, Vector<FunctionNode::Parameter> formal_parameters, i32 function_length, Environment* parent_environment, PrivateEnvironment* private_environment, Object& prototype, FunctionKind kind, bool strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function, Variant<PropertyKey, PrivateName, Empty> class_field_initializer_name) |
57 | | : FunctionObject(prototype) |
58 | | , m_name(move(name)) |
59 | | , m_function_length(function_length) |
60 | | , m_environment(parent_environment) |
61 | | , m_private_environment(private_environment) |
62 | | , m_formal_parameters(move(formal_parameters)) |
63 | | , m_ecmascript_code(ecmascript_code) |
64 | | , m_realm(global_object().associated_realm()) |
65 | | , m_source_text(move(source_text)) |
66 | | , m_class_field_initializer_name(move(class_field_initializer_name)) |
67 | | , m_strict(strict) |
68 | | , m_might_need_arguments_object(might_need_arguments_object) |
69 | | , m_contains_direct_call_to_eval(contains_direct_call_to_eval) |
70 | | , m_is_arrow_function(is_arrow_function) |
71 | | , m_kind(kind) |
72 | 342k | { |
73 | | // NOTE: This logic is from OrdinaryFunctionCreate, https://tc39.es/ecma262/#sec-ordinaryfunctioncreate |
74 | | |
75 | | // 9. If thisMode is lexical-this, set F.[[ThisMode]] to lexical. |
76 | 342k | if (m_is_arrow_function) |
77 | 342k | m_this_mode = ThisMode::Lexical; |
78 | | // 10. Else if Strict is true, set F.[[ThisMode]] to strict. |
79 | 0 | else if (m_strict) |
80 | 0 | m_this_mode = ThisMode::Strict; |
81 | 0 | else |
82 | | // 11. Else, set F.[[ThisMode]] to global. |
83 | 0 | m_this_mode = ThisMode::Global; |
84 | | |
85 | | // 15. Set F.[[ScriptOrModule]] to GetActiveScriptOrModule(). |
86 | 342k | m_script_or_module = vm().get_active_script_or_module(); |
87 | | |
88 | | // 15.1.3 Static Semantics: IsSimpleParameterList, https://tc39.es/ecma262/#sec-static-semantics-issimpleparameterlist |
89 | 342k | m_has_simple_parameter_list = all_of(m_formal_parameters, [&](auto& parameter) { |
90 | 342k | if (parameter.is_rest) |
91 | 0 | return false; |
92 | 342k | if (parameter.default_value) |
93 | 0 | return false; |
94 | 342k | if (!parameter.binding.template has<FlyString>()) |
95 | 0 | return false; |
96 | 342k | return true; |
97 | 342k | }); |
98 | 342k | } |
99 | | |
100 | | void ECMAScriptFunctionObject::initialize(GlobalObject& global_object) |
101 | 342k | { |
102 | 342k | auto& vm = this->vm(); |
103 | 342k | Base::initialize(global_object); |
104 | | // Note: The ordering of these properties must be: length, name, prototype which is the order |
105 | | // they are defined in the spec: https://tc39.es/ecma262/#sec-function-instances . |
106 | | // This is observable through something like: https://tc39.es/ecma262/#sec-ordinaryownpropertykeys |
107 | | // which must give the properties in chronological order which in this case is the order they |
108 | | // are defined in the spec. |
109 | | |
110 | 342k | MUST(define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true })); |
111 | 342k | MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name.is_null() ? "" : m_name), .writable = false, .enumerable = false, .configurable = true })); |
112 | | |
113 | 342k | if (!m_is_arrow_function) { |
114 | 0 | Object* prototype = nullptr; |
115 | 0 | switch (m_kind) { |
116 | 0 | case FunctionKind::Normal: |
117 | 0 | prototype = vm.heap().allocate<Object>(global_object, *global_object.new_ordinary_function_prototype_object_shape()); |
118 | 0 | MUST(prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true })); |
119 | 0 | break; |
120 | 0 | case FunctionKind::Generator: |
121 | | // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png) |
122 | 0 | prototype = Object::create(global_object, global_object.generator_function_prototype_prototype()); |
123 | 0 | break; |
124 | 0 | case FunctionKind::Async: |
125 | 0 | break; |
126 | 0 | case FunctionKind::AsyncGenerator: |
127 | 0 | prototype = Object::create(global_object, global_object.async_generator_function_prototype_prototype()); |
128 | 0 | break; |
129 | 0 | } |
130 | | // 27.7.4 AsyncFunction Instances, https://tc39.es/ecma262/#sec-async-function-instances |
131 | | // AsyncFunction instances do not have a prototype property as they are not constructible. |
132 | 0 | if (m_kind != FunctionKind::Async) |
133 | 0 | define_direct_property(vm.names.prototype, prototype, Attribute::Writable); |
134 | 0 | } |
135 | 342k | } |
136 | | |
137 | | // 10.2.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist |
138 | | ThrowCompletionOr<Value> ECMAScriptFunctionObject::internal_call(Value this_argument, MarkedVector<Value> arguments_list) |
139 | 0 | { |
140 | 0 | auto& vm = this->vm(); |
141 | | |
142 | | // 1. Let callerContext be the running execution context. |
143 | | // NOTE: No-op, kept by the VM in its execution context stack. |
144 | |
|
145 | 0 | ExecutionContext callee_context(heap()); |
146 | | |
147 | | // Non-standard |
148 | 0 | callee_context.arguments.extend(move(arguments_list)); |
149 | 0 | if (auto* interpreter = vm.interpreter_if_exists()) |
150 | 0 | callee_context.current_node = interpreter->current_node(); |
151 | | |
152 | | // 2. Let calleeContext be PrepareForOrdinaryCall(F, undefined). |
153 | | // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check. |
154 | 0 | TRY(prepare_for_ordinary_call(callee_context, nullptr)); |
155 | | |
156 | | // 3. Assert: calleeContext is now the running execution context. |
157 | 0 | VERIFY(&vm.running_execution_context() == &callee_context); |
158 | | |
159 | | // 4. If F.[[IsClassConstructor]] is true, then |
160 | 0 | if (m_is_class_constructor) { |
161 | | // a. Let error be a newly created TypeError object. |
162 | | // b. NOTE: error is created in calleeContext with F's associated Realm Record. |
163 | 0 | auto throw_completion = vm.throw_completion<TypeError>(global_object(), ErrorType::ClassConstructorWithoutNew, m_name); |
164 | | |
165 | | // c. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. |
166 | 0 | vm.pop_execution_context(); |
167 | | |
168 | | // d. Return ThrowCompletion(error). |
169 | 0 | return throw_completion; |
170 | 0 | } |
171 | | |
172 | | // 5. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument). |
173 | 0 | ordinary_call_bind_this(callee_context, this_argument); |
174 | | |
175 | | // 6. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)). |
176 | 0 | auto result = ordinary_call_evaluate_body(); |
177 | | |
178 | | // 7. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. |
179 | 0 | vm.pop_execution_context(); |
180 | | |
181 | | // 8. If result.[[Type]] is return, return result.[[Value]]. |
182 | 0 | if (result.type() == Completion::Type::Return) |
183 | 0 | return result.value(); |
184 | | |
185 | | // 9. ReturnIfAbrupt(result). |
186 | 0 | if (result.is_abrupt()) { |
187 | 0 | VERIFY(result.is_error()); |
188 | 0 | return result; |
189 | 0 | } |
190 | | |
191 | | // 10. Return undefined. |
192 | 0 | return js_undefined(); |
193 | 0 | } |
194 | | |
195 | | // 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget |
196 | | ThrowCompletionOr<Object*> ECMAScriptFunctionObject::internal_construct(MarkedVector<Value> arguments_list, FunctionObject& new_target) |
197 | 0 | { |
198 | 0 | auto& vm = this->vm(); |
199 | 0 | auto& global_object = this->global_object(); |
200 | | |
201 | | // 1. Let callerContext be the running execution context. |
202 | | // NOTE: No-op, kept by the VM in its execution context stack. |
203 | | |
204 | | // 2. Let kind be F.[[ConstructorKind]]. |
205 | 0 | auto kind = m_constructor_kind; |
206 | |
|
207 | 0 | Object* this_argument = nullptr; |
208 | | |
209 | | // 3. If kind is base, then |
210 | 0 | if (kind == ConstructorKind::Base) { |
211 | | // a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%"). |
212 | 0 | this_argument = TRY(ordinary_create_from_constructor<Object>(global_object, new_target, &GlobalObject::object_prototype)); |
213 | 0 | } |
214 | | |
215 | 0 | ExecutionContext callee_context(heap()); |
216 | | |
217 | | // Non-standard |
218 | 0 | callee_context.arguments.extend(move(arguments_list)); |
219 | 0 | if (auto* interpreter = vm.interpreter_if_exists()) |
220 | 0 | callee_context.current_node = interpreter->current_node(); |
221 | | |
222 | | // 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget). |
223 | | // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check. |
224 | 0 | TRY(prepare_for_ordinary_call(callee_context, &new_target)); |
225 | | |
226 | | // 5. Assert: calleeContext is now the running execution context. |
227 | 0 | VERIFY(&vm.running_execution_context() == &callee_context); |
228 | | |
229 | | // 6. If kind is base, then |
230 | 0 | if (kind == ConstructorKind::Base) { |
231 | | // a. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument). |
232 | 0 | ordinary_call_bind_this(callee_context, this_argument); |
233 | | |
234 | | // b. Let initializeResult be Completion(InitializeInstanceElements(thisArgument, F)). |
235 | 0 | auto initialize_result = vm.initialize_instance_elements(*this_argument, *this); |
236 | | |
237 | | // c. If initializeResult is an abrupt completion, then |
238 | 0 | if (initialize_result.is_throw_completion()) { |
239 | | // i. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. |
240 | 0 | vm.pop_execution_context(); |
241 | | |
242 | | // ii. Return ? initializeResult. |
243 | 0 | return initialize_result.throw_completion(); |
244 | 0 | } |
245 | 0 | } |
246 | | |
247 | | // 7. Let constructorEnv be the LexicalEnvironment of calleeContext. |
248 | 0 | auto* constructor_env = callee_context.lexical_environment; |
249 | | |
250 | | // 8. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)). |
251 | 0 | auto result = ordinary_call_evaluate_body(); |
252 | | |
253 | | // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context. |
254 | 0 | vm.pop_execution_context(); |
255 | | |
256 | | // 10. If result.[[Type]] is return, then |
257 | 0 | if (result.type() == Completion::Type::Return) { |
258 | | // FIXME: This is leftover from untangling the call/construct mess - doesn't belong here in any way, but removing it breaks derived classes. |
259 | | // Likely fixed by making ClassDefinitionEvaluation fully spec compliant. |
260 | 0 | if (kind == ConstructorKind::Derived && result.value()->is_object()) { |
261 | 0 | auto prototype = TRY(new_target.get(vm.names.prototype)); |
262 | 0 | if (prototype.is_object()) |
263 | 0 | TRY(result.value()->as_object().internal_set_prototype_of(&prototype.as_object())); |
264 | 0 | } |
265 | | // EOF (End of FIXME) |
266 | | |
267 | | // a. If Type(result.[[Value]]) is Object, return result.[[Value]]. |
268 | 0 | if (result.value()->is_object()) |
269 | 0 | return &result.value()->as_object(); |
270 | | |
271 | | // b. If kind is base, return thisArgument. |
272 | 0 | if (kind == ConstructorKind::Base) |
273 | 0 | return this_argument; |
274 | | |
275 | | // c. If result.[[Value]] is not undefined, throw a TypeError exception. |
276 | 0 | if (!result.value()->is_undefined()) |
277 | 0 | return vm.throw_completion<TypeError>(global_object, ErrorType::DerivedConstructorReturningInvalidValue); |
278 | 0 | } |
279 | | // 11. Else, ReturnIfAbrupt(result). |
280 | 0 | else if (result.is_abrupt()) { |
281 | 0 | VERIFY(result.is_error()); |
282 | 0 | return result; |
283 | 0 | } |
284 | | |
285 | | // 12. Let thisBinding be ? constructorEnv.GetThisBinding(). |
286 | 0 | auto this_binding = TRY(constructor_env->get_this_binding(global_object)); |
287 | | |
288 | | // 13. Assert: Type(thisBinding) is Object. |
289 | 0 | VERIFY(this_binding.is_object()); |
290 | | |
291 | | // 14. Return thisBinding. |
292 | 0 | return &this_binding.as_object(); |
293 | 0 | } |
294 | | |
295 | | void ECMAScriptFunctionObject::visit_edges(Visitor& visitor) |
296 | 340 | { |
297 | 340 | Base::visit_edges(visitor); |
298 | 340 | visitor.visit(m_environment); |
299 | 340 | visitor.visit(m_private_environment); |
300 | 340 | visitor.visit(m_realm); |
301 | 340 | visitor.visit(m_home_object); |
302 | | |
303 | 340 | for (auto& field : m_fields) { |
304 | 0 | if (auto* property_key_ptr = field.name.get_pointer<PropertyKey>(); property_key_ptr && property_key_ptr->is_symbol()) |
305 | 0 | visitor.visit(property_key_ptr->as_symbol()); |
306 | 0 | } |
307 | 340 | } |
308 | | |
309 | | // 10.2.7 MakeMethod ( F, homeObject ), https://tc39.es/ecma262/#sec-makemethod |
310 | | void ECMAScriptFunctionObject::make_method(Object& home_object) |
311 | 0 | { |
312 | | // 1. Set F.[[HomeObject]] to homeObject. |
313 | 0 | m_home_object = &home_object; |
314 | | |
315 | | // 2. Return unused. |
316 | 0 | } |
317 | | |
318 | | // 10.2.11 FunctionDeclarationInstantiation ( func, argumentsList ), https://tc39.es/ecma262/#sec-functiondeclarationinstantiation |
319 | | ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantiation(Interpreter* interpreter) |
320 | 0 | { |
321 | 0 | auto& vm = this->vm(); |
322 | |
|
323 | 0 | auto& callee_context = vm.running_execution_context(); |
324 | | |
325 | | // Needed to extract declarations and functions |
326 | 0 | ScopeNode const* scope_body = nullptr; |
327 | 0 | if (is<ScopeNode>(*m_ecmascript_code)) |
328 | 0 | scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr()); |
329 | |
|
330 | 0 | bool has_parameter_expressions = false; |
331 | | |
332 | | // FIXME: Maybe compute has duplicates at parse time? (We need to anyway since it's an error in some cases) |
333 | |
|
334 | 0 | bool has_duplicates = false; |
335 | 0 | HashTable<FlyString> parameter_names; |
336 | 0 | for (auto& parameter : m_formal_parameters) { |
337 | 0 | if (parameter.default_value) |
338 | 0 | has_parameter_expressions = true; |
339 | |
|
340 | 0 | parameter.binding.visit( |
341 | 0 | [&](FlyString const& name) { |
342 | 0 | if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry) |
343 | 0 | has_duplicates = true; |
344 | 0 | }, |
345 | 0 | [&](NonnullRefPtr<BindingPattern> const& pattern) { |
346 | 0 | if (pattern->contains_expression()) |
347 | 0 | has_parameter_expressions = true; |
348 | |
|
349 | 0 | pattern->for_each_bound_name([&](auto& name) { |
350 | 0 | if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry) |
351 | 0 | has_duplicates = true; |
352 | 0 | }); |
353 | 0 | }); |
354 | 0 | } |
355 | |
|
356 | 0 | auto arguments_object_needed = m_might_need_arguments_object; |
357 | |
|
358 | 0 | if (this_mode() == ThisMode::Lexical) |
359 | 0 | arguments_object_needed = false; |
360 | |
|
361 | 0 | if (parameter_names.contains(vm.names.arguments.as_string())) |
362 | 0 | arguments_object_needed = false; |
363 | |
|
364 | 0 | HashTable<FlyString> function_names; |
365 | 0 | Vector<FunctionDeclaration const&> functions_to_initialize; |
366 | |
|
367 | 0 | if (scope_body) { |
368 | 0 | scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) { |
369 | 0 | if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry) |
370 | 0 | functions_to_initialize.append(function); |
371 | 0 | }); |
372 | |
|
373 | 0 | auto const& arguments_name = vm.names.arguments.as_string(); |
374 | |
|
375 | 0 | if (!has_parameter_expressions && function_names.contains(arguments_name)) |
376 | 0 | arguments_object_needed = false; |
377 | |
|
378 | 0 | if (!has_parameter_expressions && arguments_object_needed) { |
379 | 0 | scope_body->for_each_lexically_declared_name([&](auto const& name) { |
380 | 0 | if (name == arguments_name) |
381 | 0 | arguments_object_needed = false; |
382 | 0 | }); |
383 | 0 | } |
384 | 0 | } else { |
385 | 0 | arguments_object_needed = false; |
386 | 0 | } |
387 | |
|
388 | 0 | Environment* environment; |
389 | |
|
390 | 0 | if (is_strict_mode() || !has_parameter_expressions) { |
391 | 0 | environment = callee_context.lexical_environment; |
392 | 0 | } else { |
393 | 0 | environment = new_declarative_environment(*callee_context.lexical_environment); |
394 | 0 | VERIFY(callee_context.variable_environment == callee_context.lexical_environment); |
395 | 0 | callee_context.lexical_environment = environment; |
396 | 0 | } |
397 | | |
398 | 0 | for (auto const& parameter_name : parameter_names) { |
399 | 0 | if (MUST(environment->has_binding(parameter_name))) |
400 | 0 | continue; |
401 | | |
402 | 0 | MUST(environment->create_mutable_binding(global_object(), parameter_name, false)); |
403 | 0 | if (has_duplicates) |
404 | 0 | MUST(environment->initialize_binding(global_object(), parameter_name, js_undefined())); |
405 | 0 | } |
406 | |
|
407 | 0 | if (arguments_object_needed) { |
408 | 0 | Object* arguments_object; |
409 | 0 | if (is_strict_mode() || !has_simple_parameter_list()) |
410 | 0 | arguments_object = create_unmapped_arguments_object(global_object(), vm.running_execution_context().arguments); |
411 | 0 | else |
412 | 0 | arguments_object = create_mapped_arguments_object(global_object(), *this, formal_parameters(), vm.running_execution_context().arguments, *environment); |
413 | |
|
414 | 0 | if (is_strict_mode()) |
415 | 0 | MUST(environment->create_immutable_binding(global_object(), vm.names.arguments.as_string(), false)); |
416 | 0 | else |
417 | 0 | MUST(environment->create_mutable_binding(global_object(), vm.names.arguments.as_string(), false)); |
418 | | |
419 | 0 | MUST(environment->initialize_binding(global_object(), vm.names.arguments.as_string(), arguments_object)); |
420 | 0 | parameter_names.set(vm.names.arguments.as_string()); |
421 | 0 | } |
422 | | |
423 | | // We now treat parameterBindings as parameterNames. |
424 | | |
425 | | // The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually |
426 | 0 | auto& execution_context_arguments = vm.running_execution_context().arguments; |
427 | |
|
428 | 0 | size_t default_parameter_index = 0; |
429 | 0 | for (size_t i = 0; i < m_formal_parameters.size(); ++i) { |
430 | 0 | auto& parameter = m_formal_parameters[i]; |
431 | 0 | if (parameter.default_value) |
432 | 0 | ++default_parameter_index; |
433 | |
|
434 | 0 | TRY(parameter.binding.visit( |
435 | 0 | [&](auto const& param) -> ThrowCompletionOr<void> { |
436 | 0 | Value argument_value; |
437 | 0 | if (parameter.is_rest) { |
438 | 0 | auto* array = MUST(Array::create(global_object(), 0)); |
439 | 0 | for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index) |
440 | 0 | array->indexed_properties().append(execution_context_arguments[rest_index]); |
441 | 0 | argument_value = array; |
442 | 0 | } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) { |
443 | 0 | argument_value = execution_context_arguments[i]; |
444 | 0 | } else if (parameter.default_value) { |
445 | 0 | if (auto* bytecode_interpreter = Bytecode::Interpreter::current()) { |
446 | 0 | auto value_and_frame = bytecode_interpreter->run_and_return_frame(*m_default_parameter_bytecode_executables[default_parameter_index - 1], nullptr); |
447 | 0 | if (value_and_frame.value.is_error()) |
448 | 0 | return value_and_frame.value.release_error(); |
449 | | // Resulting value is in the accumulator. |
450 | 0 | argument_value = value_and_frame.frame->registers.at(0); |
451 | 0 | } else if (interpreter) { |
452 | 0 | argument_value = TRY(parameter.default_value->execute(*interpreter, global_object())).release_value(); |
453 | 0 | } |
454 | 0 | } else { |
455 | 0 | argument_value = js_undefined(); |
456 | 0 | } |
457 | |
|
458 | 0 | Environment* used_environment = has_duplicates ? nullptr : environment; |
459 | |
|
460 | 0 | if constexpr (IsSame<FlyString const&, decltype(param)>) { |
461 | 0 | Reference reference = TRY(vm.resolve_binding(param, used_environment)); |
462 | | // Here the difference from hasDuplicates is important |
463 | 0 | if (has_duplicates) |
464 | 0 | return reference.put_value(global_object(), argument_value); |
465 | 0 | else |
466 | 0 | return reference.initialize_referenced_binding(global_object(), argument_value); |
467 | 0 | } else if (IsSame<NonnullRefPtr<BindingPattern> const&, decltype(param)>) { |
468 | | // Here the difference from hasDuplicates is important |
469 | 0 | return vm.binding_initialization(param, argument_value, used_environment, global_object()); |
470 | 0 | } |
471 | 0 | })); |
472 | 0 | } |
473 | | |
474 | 0 | Environment* var_environment; |
475 | |
|
476 | 0 | HashTable<FlyString> instantiated_var_names; |
477 | 0 | if (scope_body) |
478 | 0 | instantiated_var_names.ensure_capacity(scope_body->var_declaration_count()); |
479 | |
|
480 | 0 | if (!has_parameter_expressions) { |
481 | 0 | if (scope_body) { |
482 | 0 | scope_body->for_each_var_declared_name([&](auto const& name) { |
483 | 0 | if (!parameter_names.contains(name) && instantiated_var_names.set(name) == AK::HashSetResult::InsertedNewEntry) { |
484 | 0 | MUST(environment->create_mutable_binding(global_object(), name, false)); |
485 | 0 | MUST(environment->initialize_binding(global_object(), name, js_undefined())); |
486 | 0 | } |
487 | 0 | }); |
488 | 0 | } |
489 | 0 | var_environment = environment; |
490 | 0 | } else { |
491 | 0 | var_environment = new_declarative_environment(*environment); |
492 | 0 | callee_context.variable_environment = var_environment; |
493 | |
|
494 | 0 | if (scope_body) { |
495 | 0 | scope_body->for_each_var_declared_name([&](auto const& name) { |
496 | 0 | if (instantiated_var_names.set(name) != AK::HashSetResult::InsertedNewEntry) |
497 | 0 | return; |
498 | 0 | MUST(var_environment->create_mutable_binding(global_object(), name, false)); |
499 | | |
500 | 0 | Value initial_value; |
501 | 0 | if (!parameter_names.contains(name) || function_names.contains(name)) |
502 | 0 | initial_value = js_undefined(); |
503 | 0 | else |
504 | 0 | initial_value = MUST(environment->get_binding_value(global_object(), name, false)); |
505 | | |
506 | 0 | MUST(var_environment->initialize_binding(global_object(), name, initial_value)); |
507 | 0 | }); |
508 | 0 | } |
509 | 0 | } |
510 | | |
511 | | // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation |
512 | 0 | if (!m_strict && scope_body) { |
513 | 0 | scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) { |
514 | 0 | auto& function_name = function_declaration.name(); |
515 | 0 | if (parameter_names.contains(function_name)) |
516 | 0 | return; |
517 | | // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'. |
518 | 0 | if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) { |
519 | 0 | MUST(var_environment->create_mutable_binding(global_object(), function_name, false)); |
520 | 0 | MUST(var_environment->initialize_binding(global_object(), function_name, js_undefined())); |
521 | 0 | instantiated_var_names.set(function_name); |
522 | 0 | } |
523 | | |
524 | 0 | function_declaration.set_should_do_additional_annexB_steps(); |
525 | 0 | }); |
526 | 0 | } |
527 | |
|
528 | 0 | Environment* lex_environment; |
529 | | |
530 | | // 30. If strict is false, then |
531 | 0 | if (!is_strict_mode()) { |
532 | | // Optimization: We avoid creating empty top-level declarative environments in non-strict mode, if both of these conditions are true: |
533 | | // 1. there is no direct call to eval() within this function |
534 | | // 2. there are no lexical declarations that would go into the environment |
535 | 0 | bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations()); |
536 | 0 | if (can_elide_declarative_environment) { |
537 | 0 | lex_environment = var_environment; |
538 | 0 | } else { |
539 | | // a. Let lexEnv be NewDeclarativeEnvironment(varEnv). |
540 | | // b. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval |
541 | | // can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level |
542 | | // lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places |
543 | | // all declarations into a new Environment Record. |
544 | 0 | lex_environment = new_declarative_environment(*var_environment); |
545 | 0 | } |
546 | 0 | } else { |
547 | | // 31. Else, let lexEnv be varEnv. |
548 | 0 | lex_environment = var_environment; |
549 | 0 | } |
550 | | |
551 | | // 32. Set the LexicalEnvironment of calleeContext to lexEnv. |
552 | 0 | callee_context.lexical_environment = lex_environment; |
553 | |
|
554 | 0 | if (!scope_body) |
555 | 0 | return {}; |
556 | | |
557 | 0 | if (!Bytecode::Interpreter::current()) { |
558 | 0 | scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) { |
559 | 0 | declaration.for_each_bound_name([&](auto const& name) { |
560 | 0 | if (declaration.is_constant_declaration()) |
561 | 0 | MUST(lex_environment->create_immutable_binding(global_object(), name, true)); |
562 | 0 | else |
563 | 0 | MUST(lex_environment->create_mutable_binding(global_object(), name, false)); |
564 | 0 | }); |
565 | 0 | }); |
566 | 0 | } |
567 | |
|
568 | 0 | auto* private_environment = callee_context.private_environment; |
569 | 0 | for (auto& declaration : functions_to_initialize) { |
570 | 0 | auto* function = ECMAScriptFunctionObject::create(global_object(), declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), lex_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval()); |
571 | 0 | MUST(var_environment->set_mutable_binding(global_object(), declaration.name(), function, false)); |
572 | 0 | } |
573 | |
|
574 | 0 | return {}; |
575 | 0 | } |
576 | | |
577 | | // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall |
578 | | ThrowCompletionOr<void> ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target) |
579 | 0 | { |
580 | 0 | auto& vm = this->vm(); |
581 | | |
582 | | // Non-standard |
583 | 0 | callee_context.is_strict_mode = m_strict; |
584 | | |
585 | | // 1. Let callerContext be the running execution context. |
586 | | // 2. Let calleeContext be a new ECMAScript code execution context. |
587 | | |
588 | | // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context. |
589 | | // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead. |
590 | | // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`. |
591 | | |
592 | | // 3. Set the Function of calleeContext to F. |
593 | 0 | callee_context.function = this; |
594 | 0 | callee_context.function_name = m_name; |
595 | | |
596 | | // 4. Let calleeRealm be F.[[Realm]]. |
597 | 0 | auto* callee_realm = m_realm; |
598 | | // NOTE: This non-standard fallback is needed until we can guarantee that literally |
599 | | // every function has a realm - especially in LibWeb that's sometimes not the case |
600 | | // when a function is created while no JS is running, as we currently need to rely on |
601 | | // that (:acid2:, I know - see set_event_handler_attribute() for an example). |
602 | | // If there's no 'current realm' either, we can't continue and crash. |
603 | 0 | if (!callee_realm) |
604 | 0 | callee_realm = vm.current_realm(); |
605 | 0 | VERIFY(callee_realm); |
606 | | |
607 | | // 5. Set the Realm of calleeContext to calleeRealm. |
608 | 0 | callee_context.realm = callee_realm; |
609 | | |
610 | | // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]]. |
611 | 0 | callee_context.script_or_module = m_script_or_module; |
612 | | |
613 | | // 7. Let localEnv be NewFunctionEnvironment(F, newTarget). |
614 | 0 | auto* local_environment = new_function_environment(*this, new_target); |
615 | | |
616 | | // 8. Set the LexicalEnvironment of calleeContext to localEnv. |
617 | 0 | callee_context.lexical_environment = local_environment; |
618 | | |
619 | | // 9. Set the VariableEnvironment of calleeContext to localEnv. |
620 | 0 | callee_context.variable_environment = local_environment; |
621 | | |
622 | | // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]]. |
623 | 0 | callee_context.private_environment = m_private_environment; |
624 | | |
625 | | // 11. If callerContext is not already suspended, suspend callerContext. |
626 | | // FIXME: We don't have this concept yet. |
627 | | |
628 | | // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context. |
629 | 0 | TRY(vm.push_execution_context(callee_context, global_object())); |
630 | | |
631 | | // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm. |
632 | | // 14. Return calleeContext. |
633 | | // NOTE: See the comment after step 2 above about how contexts are allocated on the C++ stack. |
634 | 0 | return {}; |
635 | 0 | } |
636 | | |
637 | | // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis |
638 | | void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_context, Value this_argument) |
639 | 0 | { |
640 | 0 | auto& vm = this->vm(); |
641 | | |
642 | | // 1. Let thisMode be F.[[ThisMode]]. |
643 | 0 | auto this_mode = m_this_mode; |
644 | | |
645 | | // If thisMode is lexical, return unused. |
646 | 0 | if (this_mode == ThisMode::Lexical) |
647 | 0 | return; |
648 | | |
649 | | // 3. Let calleeRealm be F.[[Realm]]. |
650 | 0 | auto* callee_realm = m_realm; |
651 | | // NOTE: This non-standard fallback is needed until we can guarantee that literally |
652 | | // every function has a realm - especially in LibWeb that's sometimes not the case |
653 | | // when a function is created while no JS is running, as we currently need to rely on |
654 | | // that (:acid2:, I know - see set_event_handler_attribute() for an example). |
655 | | // If there's no 'current realm' either, we can't continue and crash. |
656 | 0 | if (!callee_realm) |
657 | 0 | callee_realm = vm.current_realm(); |
658 | 0 | VERIFY(callee_realm); |
659 | | |
660 | | // 4. Let localEnv be the LexicalEnvironment of calleeContext. |
661 | 0 | auto* local_env = callee_context.lexical_environment; |
662 | |
|
663 | 0 | Value this_value; |
664 | | |
665 | | // 5. If thisMode is strict, let thisValue be thisArgument. |
666 | 0 | if (this_mode == ThisMode::Strict) { |
667 | 0 | this_value = this_argument; |
668 | 0 | } |
669 | | // 6. Else, |
670 | 0 | else { |
671 | | // a. If thisArgument is undefined or null, then |
672 | 0 | if (this_argument.is_nullish()) { |
673 | | // i. Let globalEnv be calleeRealm.[[GlobalEnv]]. |
674 | | // ii. Assert: globalEnv is a global Environment Record. |
675 | 0 | auto& global_env = callee_realm->global_environment(); |
676 | | |
677 | | // iii. Let thisValue be globalEnv.[[GlobalThisValue]]. |
678 | 0 | this_value = &global_env.global_this_value(); |
679 | 0 | } |
680 | | // b. Else, |
681 | 0 | else { |
682 | | // i. Let thisValue be ! ToObject(thisArgument). |
683 | 0 | this_value = MUST(this_argument.to_object(global_object())); |
684 | | |
685 | | // ii. NOTE: ToObject produces wrapper objects using calleeRealm. |
686 | | // FIXME: It currently doesn't, as we pass the function's global object. |
687 | 0 | } |
688 | 0 | } |
689 | | |
690 | | // 7. Assert: localEnv is a function Environment Record. |
691 | | // 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized. |
692 | | // 9. Perform ! localEnv.BindThisValue(thisValue). |
693 | 0 | MUST(verify_cast<FunctionEnvironment>(local_env)->bind_this_value(global_object(), this_value)); |
694 | | |
695 | | // 10. Return unused. |
696 | 0 | } |
697 | | |
698 | | // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start |
699 | | void ECMAScriptFunctionObject::async_function_start(PromiseCapability const& promise_capability) |
700 | 0 | { |
701 | 0 | auto& vm = this->vm(); |
702 | | |
703 | | // 1. Let runningContext be the running execution context. |
704 | 0 | auto& running_context = vm.running_execution_context(); |
705 | | |
706 | | // 2. Let asyncContext be a copy of runningContext. |
707 | 0 | auto async_context = running_context.copy(); |
708 | | |
709 | | // 3. NOTE: Copying the execution state is required for AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context. |
710 | | |
711 | | // 4. Perform AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext). |
712 | 0 | async_block_start(vm, m_ecmascript_code, promise_capability, async_context); |
713 | | |
714 | | // 5. Return unused. |
715 | 0 | } |
716 | | |
717 | | // 27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/ecma262/#sec-asyncblockstart |
718 | | void async_block_start(VM& vm, NonnullRefPtr<Statement> const& async_body, PromiseCapability const& promise_capability, ExecutionContext& async_context) |
719 | 0 | { |
720 | 0 | auto& global_object = vm.current_realm()->global_object(); |
721 | | // 1. Assert: promiseCapability is a PromiseCapability Record. |
722 | | |
723 | | // 2. Let runningContext be the running execution context. |
724 | 0 | auto& running_context = vm.running_execution_context(); |
725 | | |
726 | | // 3. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed: |
727 | 0 | auto* execution_steps = NativeFunction::create(global_object, "", [&async_body, &promise_capability](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> { |
728 | | // a. Let result be the result of evaluating asyncBody. |
729 | 0 | auto result = async_body->execute(vm.interpreter(), global_object); |
730 | | |
731 | | // b. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done. |
732 | | |
733 | | // c. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context. |
734 | 0 | vm.pop_execution_context(); |
735 | | |
736 | | // d. If result.[[Type]] is normal, then |
737 | 0 | if (result.type() == Completion::Type::Normal) { |
738 | | // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »). |
739 | 0 | MUST(call(global_object, promise_capability.resolve, js_undefined(), js_undefined())); |
740 | 0 | } |
741 | | // e. Else if result.[[Type]] is return, then |
742 | 0 | else if (result.type() == Completion::Type::Return) { |
743 | | // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »). |
744 | 0 | MUST(call(global_object, promise_capability.resolve, js_undefined(), *result.value())); |
745 | 0 | } |
746 | | // f. Else, |
747 | 0 | else { |
748 | | // i. Assert: result.[[Type]] is throw. |
749 | 0 | VERIFY(result.type() == Completion::Type::Throw); |
750 | | |
751 | | // ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »). |
752 | 0 | MUST(call(global_object, promise_capability.reject, js_undefined(), *result.value())); |
753 | 0 | } |
754 | | // g. Return unused. |
755 | | // NOTE: We don't support returning an empty/optional/unused value here. |
756 | 0 | return js_undefined(); |
757 | 0 | }); |
758 | | |
759 | | // 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context. |
760 | 0 | auto push_result = vm.push_execution_context(async_context, global_object); |
761 | 0 | if (push_result.is_error()) |
762 | 0 | return; |
763 | | |
764 | | // 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation. |
765 | 0 | auto result = call(global_object, *execution_steps, async_context.this_value.is_empty() ? js_undefined() : async_context.this_value); |
766 | | |
767 | | // 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context. |
768 | 0 | VERIFY(&vm.running_execution_context() == &running_context); |
769 | | |
770 | | // 7. Assert: result is a normal completion with a value of unused. The possible sources of this value are Await or, if the async function doesn't await anything, step 3.g above. |
771 | 0 | VERIFY(result.has_value() && result.value().is_undefined()); |
772 | | |
773 | | // 8. Return unused. |
774 | 0 | } |
775 | | |
776 | | // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody |
777 | | // 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody |
778 | | Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body() |
779 | 0 | { |
780 | 0 | auto& vm = this->vm(); |
781 | 0 | auto* bytecode_interpreter = Bytecode::Interpreter::current(); |
782 | |
|
783 | 0 | if (m_kind == FunctionKind::AsyncGenerator) |
784 | 0 | return vm.throw_completion<InternalError>(global_object(), ErrorType::NotImplemented, "Async Generator function execution"); |
785 | | |
786 | 0 | if (bytecode_interpreter) { |
787 | 0 | if (!m_bytecode_executable) { |
788 | 0 | auto compile = [&](auto& node, auto kind, auto name) -> ThrowCompletionOr<NonnullOwnPtr<Bytecode::Executable>> { |
789 | 0 | auto executable_result = Bytecode::Generator::generate(node, kind); |
790 | 0 | if (executable_result.is_error()) |
791 | 0 | return vm.throw_completion<InternalError>(bytecode_interpreter->global_object(), ErrorType::NotImplemented, executable_result.error().to_string()); |
792 | | |
793 | 0 | auto bytecode_executable = executable_result.release_value(); |
794 | 0 | bytecode_executable->name = name; |
795 | 0 | auto& passes = Bytecode::Interpreter::optimization_pipeline(); |
796 | 0 | passes.perform(*bytecode_executable); |
797 | 0 | if constexpr (JS_BYTECODE_DEBUG) { |
798 | 0 | dbgln("Optimisation passes took {}us", passes.elapsed()); |
799 | 0 | dbgln("Compiled Bytecode::Block for function '{}':", m_name); |
800 | 0 | } |
801 | 0 | if (Bytecode::g_dump_bytecode) |
802 | 0 | bytecode_executable->dump(); |
803 | |
|
804 | 0 | return bytecode_executable; |
805 | 0 | }; Unexecuted instantiation: ECMAScriptFunctionObject.cpp:JS::ThrowCompletionOr<AK::NonnullOwnPtr<JS::Bytecode::Executable> > JS::ECMAScriptFunctionObject::ordinary_call_evaluate_body()::$_11::operator()<JS::Statement, JS::FunctionKind, AK::FlyString>(JS::Statement&, JS::FunctionKind, AK::FlyString) const Unexecuted instantiation: ECMAScriptFunctionObject.cpp:JS::ThrowCompletionOr<AK::NonnullOwnPtr<JS::Bytecode::Executable> > JS::ECMAScriptFunctionObject::ordinary_call_evaluate_body()::$_11::operator()<JS::Expression const, JS::FunctionKind, AK::String>(JS::Expression const&, JS::FunctionKind, AK::String) const |
806 | |
|
807 | 0 | m_bytecode_executable = TRY(compile(*m_ecmascript_code, m_kind, m_name)); |
808 | | |
809 | 0 | size_t default_parameter_index = 0; |
810 | 0 | for (auto& parameter : m_formal_parameters) { |
811 | 0 | if (!parameter.default_value) |
812 | 0 | continue; |
813 | 0 | auto executable = TRY(compile(*parameter.default_value, FunctionKind::Normal, String::formatted("default parameter #{} for {}", default_parameter_index, m_name))); |
814 | 0 | m_default_parameter_bytecode_executables.append(move(executable)); |
815 | 0 | } |
816 | 0 | } |
817 | 0 | TRY(function_declaration_instantiation(nullptr)); |
818 | 0 | auto result_and_frame = bytecode_interpreter->run_and_return_frame(*m_bytecode_executable, nullptr); |
819 | |
|
820 | 0 | VERIFY(result_and_frame.frame != nullptr); |
821 | 0 | if (result_and_frame.value.is_error()) |
822 | 0 | return result_and_frame.value.release_error(); |
823 | | |
824 | 0 | auto result = result_and_frame.value.release_value(); |
825 | | |
826 | | // NOTE: Running the bytecode should eventually return a completion. |
827 | | // Until it does, we assume "return" and include the undefined fallback from the call site. |
828 | 0 | if (m_kind == FunctionKind::Normal) |
829 | 0 | return { Completion::Type::Return, result.value_or(js_undefined()), {} }; |
830 | | |
831 | 0 | auto generator_object = TRY(GeneratorObject::create(global_object(), result, this, vm.running_execution_context().copy(), move(*result_and_frame.frame))); |
832 | | |
833 | | // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise |
834 | | // See AwaitExpression::generate_bytecode() for the transformation. |
835 | 0 | if (m_kind == FunctionKind::Async) |
836 | 0 | return { Completion::Type::Return, TRY(AsyncFunctionDriverWrapper::create(global_object(), generator_object)), {} }; |
837 | | |
838 | 0 | VERIFY(m_kind == FunctionKind::Generator); |
839 | 0 | return { Completion::Type::Return, generator_object, {} }; |
840 | 0 | } else { |
841 | 0 | if (m_kind == FunctionKind::Generator) |
842 | 0 | return vm.throw_completion<InternalError>(global_object(), ErrorType::NotImplemented, "Generator function execution in AST interpreter"); |
843 | 0 | OwnPtr<Interpreter> local_interpreter; |
844 | 0 | Interpreter* ast_interpreter = vm.interpreter_if_exists(); |
845 | |
|
846 | 0 | if (!ast_interpreter) { |
847 | 0 | local_interpreter = Interpreter::create_with_existing_realm(*realm()); |
848 | 0 | ast_interpreter = local_interpreter.ptr(); |
849 | 0 | } |
850 | |
|
851 | 0 | VM::InterpreterExecutionScope scope(*ast_interpreter); |
852 | | |
853 | | // FunctionBody : FunctionStatementList |
854 | 0 | if (m_kind == FunctionKind::Normal) { |
855 | | // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList). |
856 | 0 | TRY(function_declaration_instantiation(ast_interpreter)); |
857 | | |
858 | | // 2. Return the result of evaluating FunctionStatementList. |
859 | 0 | return m_ecmascript_code->execute(*ast_interpreter, global_object()); |
860 | 0 | } |
861 | | // AsyncFunctionBody : FunctionBody |
862 | 0 | else if (m_kind == FunctionKind::Async) { |
863 | | // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%). |
864 | 0 | auto promise_capability = MUST(new_promise_capability(global_object(), global_object().promise_constructor())); |
865 | | |
866 | | // 2. Let declResult be Completion(FunctionDeclarationInstantiation(functionObject, argumentsList)). |
867 | 0 | auto declaration_result = function_declaration_instantiation(ast_interpreter); |
868 | | |
869 | | // 3. If declResult is an abrupt completion, then |
870 | 0 | if (declaration_result.is_throw_completion()) { |
871 | | // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « declResult.[[Value]] »). |
872 | 0 | MUST(call(global_object(), promise_capability.reject, js_undefined(), *declaration_result.throw_completion().value())); |
873 | 0 | } |
874 | | // 4. Else, |
875 | 0 | else { |
876 | | // a. Perform AsyncFunctionStart(promiseCapability, FunctionBody). |
877 | 0 | async_function_start(promise_capability); |
878 | 0 | } |
879 | | |
880 | | // 5. Return Completion Record { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }. |
881 | 0 | return Completion { Completion::Type::Return, promise_capability.promise, {} }; |
882 | 0 | } |
883 | 0 | } |
884 | 0 | VERIFY_NOT_REACHED(); |
885 | 0 | } |
886 | | |
887 | | void ECMAScriptFunctionObject::set_name(FlyString const& name) |
888 | 0 | { |
889 | 0 | VERIFY(!name.is_null()); |
890 | 0 | auto& vm = this->vm(); |
891 | 0 | m_name = name; |
892 | 0 | MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name), .writable = false, .enumerable = false, .configurable = true })); |
893 | 0 | } |
894 | | |
895 | | } |