ladybird/Userland/Libraries/LibJS/Runtime/AbstractOperations.h

80 lines
4.3 KiB
C
Raw Normal View History

/*
* Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Forward.h>
#include <LibJS/AST.h>
#include <LibJS/Forward.h>
#include <LibJS/Runtime/GlobalObject.h>
2021-10-11 21:29:31 +03:00
#include <LibJS/Runtime/PrivateEnvironment.h>
#include <LibJS/Runtime/Value.h>
namespace JS {
DeclarativeEnvironment* new_declarative_environment(Environment&);
ObjectEnvironment* new_object_environment(Object&, bool is_with_environment, Environment*);
FunctionEnvironment* new_function_environment(ECMAScriptFunctionObject&, Object* new_target);
2021-10-11 21:29:31 +03:00
PrivateEnvironment* new_private_environment(VM& vm, PrivateEnvironment* outer);
Environment& get_this_environment(VM&);
Object* get_super_constructor(VM&);
ThrowCompletionOr<Reference> make_super_property_reference(GlobalObject&, Value actual_this, PropertyKey const&, bool strict);
ThrowCompletionOr<Value> require_object_coercible(GlobalObject&, Value);
LibJS: Implement [[Call]] and [[Construct]] internal slots properly This patch implements: - Spec compliant [[Call]] and [[Construct]] internal slots, as virtual FunctionObject::internal_{call,construct}(). These effectively replace the old virtual FunctionObject::{call,construct}(), but with several advantages: - Clear and consistent naming, following the object internal methods - Use of completions - internal_construct() returns an Object, and not Value! This has been a source of confusion for a long time, since in the spec there's always an Object returned but the Value return type in LibJS meant that this could not be fully trusted and something could screw you over. - Arguments are passed explicitly in form of a MarkedValueList, allowing manipulation (BoundFunction). We still put them on the execution context as a lot of code depends on it (VM::arguments()), but not from the Call() / Construct() AOs anymore, which now allows for bypassing them and invoking [[Call]] / [[Construct]] directly. Nothing but Call() / Construct() themselves do that at the moment, but future additions to ECMA262 or already existing web specs might. - Spec compliant, standalone Call() and Construct() AOs: currently the closest we have is VM::{call,construct}(), but those try to cater to all the different function object subclasses at once, resulting in a horrible mess and calling AOs with functions they should never be called with; most prominently PrepareForOrdinaryCall and OrdinaryCallBindThis, which are only for ECMAScriptFunctionObject. As a result this also contains an implicit optimization: we no longer need to create a new function environment for NativeFunctions - which, worth mentioning, is what started this whole crusade in the first place :^)
2021-10-08 22:37:21 +03:00
ThrowCompletionOr<Value> call_impl(GlobalObject&, Value function, Value this_value, Optional<MarkedValueList> = {});
ThrowCompletionOr<Object*> construct(GlobalObject&, FunctionObject&, Optional<MarkedValueList> = {}, FunctionObject* new_target = nullptr);
ThrowCompletionOr<size_t> length_of_array_like(GlobalObject&, Object const&);
ThrowCompletionOr<MarkedValueList> create_list_from_array_like(GlobalObject&, Value, Function<ThrowCompletionOr<void>(Value)> = {});
ThrowCompletionOr<FunctionObject*> species_constructor(GlobalObject&, Object const&, FunctionObject& default_constructor);
ThrowCompletionOr<Realm*> get_function_realm(GlobalObject&, FunctionObject const&);
LibJS: Rewrite most of Object for spec compliance :^) This is a huge patch, I know. In hindsight this perhaps could've been done slightly more incremental, but I started and then fixed everything until it worked, and here we are. I tried splitting of some completely unrelated changes into separate commits, however. Anyway. This is a rewrite of most of Object, and by extension large parts of Array, Proxy, Reflect, String, TypedArray, and some other things. What we already had worked fine for about 90% of things, but getting the last 10% right proved to be increasingly difficult with the current code that sort of grew organically and is only very loosely based on the spec - this became especially obvious when we started fixing a large number of test262 failures. Key changes include: - 1:1 matching function names and parameters of all object-related functions, to avoid ambiguity. Previously we had things like put(), which the spec doesn't have - as a result it wasn't always clear which need to be used. - Better separation between object abstract operations and internal methods - the former are always the same, the latter can be overridden (and are therefore virtual). The internal methods (i.e. [[Foo]] in the spec) are now prefixed with 'internal_' for clarity - again, it was previously not always clear which AO a certain method represents, get() could've been both Get and [[Get]] (I don't know which one it was closer to right now). Note that some of the old names have been kept until all code relying on them is updated, but they are now simple wrappers around the closest matching standard abstract operation. - Simplifications of the storage layer: functions that write values to storage are now prefixed with 'storage_' to make their purpose clear, and as they are not part of the spec they should not contain any steps specified by it. Much functionality is now covered by the layers above it and was removed (e.g. handling of accessors, attribute checks). - PropertyAttributes has been greatly simplified, and is being replaced by PropertyDescriptor - a concept similar to the current implementation, but more aligned with the actual spec. See the commit message of the previous commit where it was introduced for details. - As a bonus, and since I had to look at the spec a whole lot anyway, I introduced more inline comments with the exact steps from the spec - this makes it super easy to verify correctness. - East-const all the things. As a result of all of this, things are much more correct but a bit slower now. Retaining speed wasn't a consideration at all, I have done no profiling of the new code - there might be low hanging fruits, which we can then harvest separately. Special thanks to Idan for helping me with this by tracking down bugs, updating everything outside of LibJS to work with these changes (LibWeb, Spreadsheet, HackStudio), as well as providing countless patches to fix regressions I introduced - there still are very few (we got it down to 5), but we also get many new passing test262 tests in return. :^) Co-authored-by: Idan Horowitz <idan.horowitz@gmail.com>
2021-07-04 20:14:16 +03:00
bool is_compatible_property_descriptor(bool extensible, PropertyDescriptor const&, Optional<PropertyDescriptor> const& current);
bool validate_and_apply_property_descriptor(Object*, PropertyKey const&, bool extensible, PropertyDescriptor const&, Optional<PropertyDescriptor> const& current);
ThrowCompletionOr<Object*> get_prototype_from_constructor(GlobalObject&, FunctionObject const& constructor, Object* (GlobalObject::*intrinsic_default_prototype)());
Object* create_unmapped_arguments_object(GlobalObject&, Span<Value> arguments);
Object* create_mapped_arguments_object(GlobalObject&, FunctionObject&, Vector<FunctionNode::Parameter> const&, Span<Value> arguments, Environment&);
Value canonical_numeric_index_string(GlobalObject&, PropertyKey const&);
ThrowCompletionOr<String> get_substitution(GlobalObject&, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement);
enum class CallerMode {
Strict,
NonStrict
};
enum class EvalMode {
Direct,
Indirect
};
ThrowCompletionOr<Value> perform_eval(Value, GlobalObject&, CallerMode, EvalMode);
2021-10-11 21:29:31 +03:00
ThrowCompletionOr<void> eval_declaration_instantiation(VM& vm, GlobalObject& global_object, Program const& program, Environment* variable_environment, Environment* lexical_environment, PrivateEnvironment* private_environment, bool strict);
LibJS: Make scoping follow the spec Before this we used an ad-hoc combination of references and 'variables' stored in a hashmap. This worked in most cases but is not spec like. Additionally hoisting, dynamically naming functions and scope analysis was not done properly. This patch fixes all of that by: - Implement BindingInitialization for destructuring assignment. - Implementing a new ScopePusher which tracks the lexical and var scoped declarations. This hoists functions to the top level if no lexical declaration name overlaps. Furthermore we do checking of redeclarations in the ScopePusher now requiring less checks all over the place. - Add methods for parsing the directives and statement lists instead of having that code duplicated in multiple places. This allows declarations to pushed to the appropriate scope more easily. - Remove the non spec way of storing 'variables' in DeclarativeEnvironment and make Reference follow the spec instead of checking both the bindings and 'variables'. - Remove all scoping related things from the Interpreter. And instead use environments as specified by the spec. This also includes fixing that NativeFunctions did not produce a valid FunctionEnvironment which could cause issues with callbacks and eval. All FunctionObjects now have a valid NewFunctionEnvironment implementation. - Remove execute_statements from Interpreter and instead use ASTNode::execute everywhere this simplifies AST.cpp as you no longer need to worry about which method to call. - Make ScopeNodes setup their own environment. This uses four different methods specified by the spec {Block, Function, Eval, Global}DeclarationInstantiation with the annexB extensions. - Implement and use NamedEvaluation where specified. Additionally there are fixes to things exposed by these changes to eval, {for, for-in, for-of} loops and assignment. Finally it also fixes some tests in test-js which where passing before but not now that we have correct behavior :^).
2021-09-22 13:44:56 +03:00
LibJS: Implement [[Call]] and [[Construct]] internal slots properly This patch implements: - Spec compliant [[Call]] and [[Construct]] internal slots, as virtual FunctionObject::internal_{call,construct}(). These effectively replace the old virtual FunctionObject::{call,construct}(), but with several advantages: - Clear and consistent naming, following the object internal methods - Use of completions - internal_construct() returns an Object, and not Value! This has been a source of confusion for a long time, since in the spec there's always an Object returned but the Value return type in LibJS meant that this could not be fully trusted and something could screw you over. - Arguments are passed explicitly in form of a MarkedValueList, allowing manipulation (BoundFunction). We still put them on the execution context as a lot of code depends on it (VM::arguments()), but not from the Call() / Construct() AOs anymore, which now allows for bypassing them and invoking [[Call]] / [[Construct]] directly. Nothing but Call() / Construct() themselves do that at the moment, but future additions to ECMA262 or already existing web specs might. - Spec compliant, standalone Call() and Construct() AOs: currently the closest we have is VM::{call,construct}(), but those try to cater to all the different function object subclasses at once, resulting in a horrible mess and calling AOs with functions they should never be called with; most prominently PrepareForOrdinaryCall and OrdinaryCallBindThis, which are only for ECMAScriptFunctionObject. As a result this also contains an implicit optimization: we no longer need to create a new function environment for NativeFunctions - which, worth mentioning, is what started this whole crusade in the first place :^)
2021-10-08 22:37:21 +03:00
// 7.3.13 Call ( F, V [ , argumentsList ] ), https://tc39.es/ecma262/#sec-call
template<typename... Args>
ALWAYS_INLINE ThrowCompletionOr<Value> call(GlobalObject& global_object, Value function, Value this_value, MarkedValueList arguments_list)
{
return call_impl(global_object, function, this_value, move(arguments_list));
}
template<typename... Args>
ALWAYS_INLINE ThrowCompletionOr<Value> call(GlobalObject& global_object, Value function, Value this_value, Args... args)
{
if constexpr (sizeof...(Args) > 0) {
MarkedValueList arguments_list { global_object.heap() };
(..., arguments_list.append(move(args)));
return call_impl(global_object, function, this_value, move(arguments_list));
}
return call_impl(global_object, function, this_value);
}
// 10.1.13 OrdinaryCreateFromConstructor ( constructor, intrinsicDefaultProto [ , internalSlotsList ] ), https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
template<typename T, typename... Args>
ThrowCompletionOr<T*> ordinary_create_from_constructor(GlobalObject& global_object, FunctionObject const& constructor, Object* (GlobalObject::*intrinsic_default_prototype)(), Args&&... args)
{
auto* prototype = TRY(get_prototype_from_constructor(global_object, constructor, intrinsic_default_prototype));
return global_object.heap().allocate<T>(global_object, forward<Args>(args)..., *prototype);
}
}