Explorar o código

LibJS: Bring ArrayCreate and ArrayConstructor closer to spec

Specifically, this now explicitly takes the length, adds missing
exceptions checks to calls with user-supplied lengths, takes and uses
the prototype argument, and fixes some spec non-conformance in
ArrayConstructor and its native functions around the use of ArrayCreate
Idan Horowitz %!s(int64=4) %!d(string=hai) anos
pai
achega
e480d69130

+ 3 - 3
Userland/Libraries/LibJS/AST.cpp

@@ -1992,7 +1992,7 @@ Value ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_ob
 {
     InterpreterNodeScope node_scope { interpreter, *this };
 
-    auto* array = Array::create(global_object);
+    auto* array = Array::create(global_object, 0);
     for (auto& element : m_elements) {
         auto value = Value();
         if (element) {
@@ -2066,7 +2066,7 @@ Value TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& glo
     }
     auto& tag_function = tag.as_function();
     auto& expressions = m_template_literal->expressions();
-    auto* strings = Array::create(global_object);
+    auto* strings = Array::create(global_object, 0);
     MarkedValueList arguments(vm.heap());
     arguments.append(strings);
     for (size_t i = 0; i < expressions.size(); ++i) {
@@ -2082,7 +2082,7 @@ Value TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& glo
         }
     }
 
-    auto* raw_strings = Array::create(global_object);
+    auto* raw_strings = Array::create(global_object, 0);
     for (auto& raw_string : m_template_literal->raw_strings()) {
         auto value = raw_string.execute(interpreter, global_object);
         if (vm.exception())

+ 1 - 1
Userland/Libraries/LibJS/Bytecode/Op.cpp

@@ -134,7 +134,7 @@ void IteratorToArray::execute_impl(Bytecode::Interpreter& interpreter) const
     if (vm.exception())
         return;
 
-    auto array = Array::create(global_object);
+    auto array = Array::create(global_object, 0);
     size_t index = 0;
 
     while (true) {

+ 7 - 6
Userland/Libraries/LibJS/Runtime/Array.cpp

@@ -13,23 +13,24 @@
 namespace JS {
 
 // 10.4.2.2 ArrayCreate ( length [ , proto ] ), https://tc39.es/ecma262/#sec-arraycreate
-Array* Array::create(GlobalObject& global_object, size_t length)
+Array* Array::create(GlobalObject& global_object, size_t length, Object* prototype)
 {
-    // FIXME: Support proto parameter
+    auto& vm = global_object.vm();
     if (length > NumericLimits<u32>::max()) {
-        auto& vm = global_object.vm();
         vm.throw_exception<RangeError>(global_object, ErrorType::InvalidLength, "array");
         return nullptr;
     }
-    auto* array = global_object.heap().allocate<Array>(global_object, *global_object.array_prototype());
-    array->indexed_properties().set_array_like_size(length);
+    if (!prototype)
+        prototype = global_object.array_prototype();
+    auto* array = global_object.heap().allocate<Array>(global_object, *prototype);
+    array->put(vm.names.length, Value(length));
     return array;
 }
 
 // 7.3.17 CreateArrayFromList ( elements ), https://tc39.es/ecma262/#sec-createarrayfromlist
 Array* Array::create_from(GlobalObject& global_object, const Vector<Value>& elements)
 {
-    auto* array = Array::create(global_object);
+    auto* array = Array::create(global_object, 0);
     for (size_t i = 0; i < elements.size(); ++i)
         array->define_property(i, elements[i]);
     return array;

+ 1 - 1
Userland/Libraries/LibJS/Runtime/Array.h

@@ -14,7 +14,7 @@ class Array : public Object {
     JS_OBJECT(Array, Object);
 
 public:
-    static Array* create(GlobalObject&, size_t length = 0);
+    static Array* create(GlobalObject&, size_t length, Object* prototype = nullptr);
     static Array* create_from(GlobalObject&, const Vector<Value>&);
 
     explicit Array(Object& prototype);

+ 127 - 60
Userland/Libraries/LibJS/Runtime/ArrayConstructor.cpp

@@ -6,7 +6,7 @@
  */
 
 #include <AK/Function.h>
-#include <LibJS/Heap/Heap.h>
+#include <LibJS/Runtime/AbstractOperations.h>
 #include <LibJS/Runtime/Array.h>
 #include <LibJS/Runtime/ArrayConstructor.h>
 #include <LibJS/Runtime/Error.h>
@@ -47,42 +47,53 @@ void ArrayConstructor::initialize(GlobalObject& global_object)
 // 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array
 Value ArrayConstructor::call()
 {
-    if (vm().argument_count() <= 0)
-        return Array::create(global_object());
-
-    if (vm().argument_count() == 1 && vm().argument(0).is_number()) {
-        auto length = vm().argument(0);
-        auto int_length = length.to_u32(global_object());
-        if (int_length != length.as_double()) {
-            vm().throw_exception<RangeError>(global_object(), ErrorType::InvalidLength, "array");
-            return {};
+    return construct(*this);
+}
+
+// 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array
+Value ArrayConstructor::construct(FunctionObject& new_target)
+{
+    auto& vm = this->vm();
+
+    auto* proto = get_prototype_from_constructor(global_object(), new_target, &GlobalObject::array_prototype);
+    if (vm.exception())
+        return {};
+
+    if (vm.argument_count() == 0)
+        return Array::create(global_object(), 0, proto);
+
+    if (vm.argument_count() == 1) {
+        auto length = vm.argument(0);
+        auto* array = Array::create(global_object(), 0, proto);
+        size_t int_length;
+        if (!length.is_number()) {
+            array->define_property(0, length);
+            int_length = 1;
+        } else {
+            int_length = length.to_u32(global_object());
+            if (int_length != length.as_double()) {
+                vm.throw_exception<RangeError>(global_object(), ErrorType::InvalidLength, "array");
+                return {};
+            }
         }
-        auto* array = Array::create(global_object());
-        array->indexed_properties().set_array_like_size(int_length);
+        array->put(vm.names.length, Value(int_length));
         return array;
     }
 
-    auto* array = Array::create(global_object());
-    for (size_t i = 0; i < vm().argument_count(); ++i)
-        array->indexed_properties().append(vm().argument(i));
-    return array;
-}
+    auto* array = Array::create(global_object(), vm.argument_count(), proto);
+    if (vm.exception())
+        return {};
 
-// 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array
-Value ArrayConstructor::construct(FunctionObject&)
-{
-    return call();
+    for (size_t k = 0; k < vm.argument_count(); ++k)
+        array->define_property(k, vm.argument(k));
+
+    return array;
 }
 
 // 23.1.2.1 Array.from ( items [ , mapfn [ , thisArg ] ] ), https://tc39.es/ecma262/#sec-array.from
 JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from)
 {
-    auto value = vm.argument(0);
-    auto object = value.to_object(global_object);
-    if (!object)
-        return {};
-
-    auto* array = Array::create(global_object);
+    auto constructor = vm.this_value(global_object);
 
     FunctionObject* map_fn = nullptr;
     if (!vm.argument(1).is_undefined()) {
@@ -96,53 +107,107 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from)
 
     auto this_arg = vm.argument(2);
 
-    // Array.from() lets you create Arrays from:
-    if (auto size = object->indexed_properties().array_like_size()) {
-        // * array-like objects (objects with a length property and indexed elements)
-        MarkedValueList elements(vm.heap());
-        elements.ensure_capacity(size);
-        for (size_t i = 0; i < size; ++i) {
-            if (map_fn) {
-                auto element = object->get(i);
-                if (vm.exception())
-                    return {};
+    auto items = vm.argument(0);
+    auto using_iterator = items.get_method(global_object, *vm.well_known_symbol_iterator());
+    if (vm.exception())
+        return {};
+    if (using_iterator) {
+        Value array;
+        if (constructor.is_constructor()) {
+            array = vm.construct(constructor.as_function(), constructor.as_function(), {});
+            if (vm.exception())
+                return {};
+        } else {
+            array = Array::create(global_object, 0);
+        }
+        auto iterator = get_iterator(global_object, items, IteratorHint::Sync, using_iterator);
+        if (vm.exception())
+            return {};
 
-                auto map_fn_result = vm.call(*map_fn, this_arg, element, Value((i32)i));
-                if (vm.exception())
-                    return {};
+        auto& array_object = array.as_object();
 
-                elements.append(map_fn_result);
-            } else {
-                elements.append(object->get(i));
+        size_t k = 0;
+        while (true) {
+            if (k >= MAX_ARRAY_LIKE_INDEX) {
+                vm.throw_exception<TypeError>(global_object, ErrorType::ArrayMaxSize);
+                iterator_close(*iterator);
+                return {};
+            }
+
+            auto next = iterator_step(global_object, *iterator);
+            if (vm.exception())
+                return {};
+
+            if (!next) {
+                array_object.put(vm.names.length, Value(k));
                 if (vm.exception())
                     return {};
+                return array;
             }
-        }
-        array->set_indexed_property_elements(move(elements));
-    } else {
-        // * iterable objects
-        i32 i = 0;
-        get_iterator_values(global_object, value, [&](Value element) {
+
+            auto next_value = iterator_value(global_object, *next);
             if (vm.exception())
-                return IterationDecision::Break;
+                return {};
 
+            Value mapped_value;
             if (map_fn) {
-                auto map_fn_result = vm.call(*map_fn, this_arg, element, Value(i));
-                i++;
-                if (vm.exception())
-                    return IterationDecision::Break;
-
-                array->indexed_properties().append(map_fn_result);
+                mapped_value = vm.call(*map_fn, this_arg, next_value, Value(k));
+                if (vm.exception()) {
+                    iterator_close(*iterator);
+                    return {};
+                }
             } else {
-                array->indexed_properties().append(element);
+                mapped_value = next_value;
             }
 
-            return IterationDecision::Continue;
-        });
+            array_object.define_property(k, mapped_value);
+            if (vm.exception()) {
+                iterator_close(*iterator);
+                return {};
+            }
+
+            ++k;
+        }
+    }
+
+    auto* array_like = items.to_object(global_object);
+
+    auto length = length_of_array_like(global_object, *array_like);
+    if (vm.exception())
+        return {};
+
+    Value array;
+    if (constructor.is_constructor()) {
+        MarkedValueList arguments(vm.heap());
+        arguments.empend(length);
+        array = vm.construct(constructor.as_function(), constructor.as_function(), move(arguments));
+        if (vm.exception())
+            return {};
+    } else {
+        array = Array::create(global_object, length);
         if (vm.exception())
             return {};
     }
 
+    auto& array_object = array.as_object();
+
+    for (size_t k = 0; k < length; ++k) {
+        auto k_value = array_like->get(k);
+        Value mapped_value;
+        if (map_fn) {
+            mapped_value = vm.call(*map_fn, this_arg, k_value, Value(k));
+            if (vm.exception())
+                return {};
+        } else {
+            mapped_value = k_value;
+        }
+        array_object.define_property(k, mapped_value);
+    }
+
+    array_object.put(vm.names.length, Value(length));
+    if (vm.exception())
+        return {};
+
     return array;
 }
 
@@ -165,7 +230,9 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::of)
         if (vm.exception())
             return {};
     } else {
-        array = Array::create(global_object);
+        array = Array::create(global_object, vm.argument_count());
+        if (vm.exception())
+            return {};
     }
     auto& array_object = array.as_object();
     for (size_t k = 0; k < vm.argument_count(); ++k) {

+ 1 - 1
Userland/Libraries/LibJS/Runtime/ArrayIteratorPrototype.cpp

@@ -87,7 +87,7 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayIteratorPrototype::next)
     if (iteration_kind == Object::PropertyKind::Value)
         return create_iterator_result_object(global_object, value, false);
 
-    auto* entry_array = Array::create(global_object);
+    auto* entry_array = Array::create(global_object, 0);
     entry_array->define_property(0, Value(static_cast<i32>(index)));
     entry_array->define_property(1, value);
     return create_iterator_result_object(global_object, entry_array, false);

+ 12 - 4
Userland/Libraries/LibJS/Runtime/ArrayPrototype.cpp

@@ -151,8 +151,12 @@ static Object* array_species_create(GlobalObject& global_object, Object& origina
 {
     auto& vm = global_object.vm();
 
-    if (!Value(&original_array).is_array(global_object))
-        return Array::create(global_object, length);
+    if (!Value(&original_array).is_array(global_object)) {
+        auto array = Array::create(global_object, length);
+        if (vm.exception())
+            return {};
+        return array;
+    }
 
     auto constructor = original_array.get(vm.names.constructor).value_or(js_undefined());
     if (vm.exception())
@@ -176,8 +180,12 @@ static Object* array_species_create(GlobalObject& global_object, Object& origina
             constructor = js_undefined();
     }
 
-    if (constructor.is_undefined())
-        return Array::create(global_object, length);
+    if (constructor.is_undefined()) {
+        auto array = Array::create(global_object, length);
+        if (vm.exception())
+            return {};
+        return array;
+    }
 
     if (!constructor.is_constructor()) {
         vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());

+ 1 - 1
Userland/Libraries/LibJS/Runtime/JSONObject.cpp

@@ -467,7 +467,7 @@ Object* JSONObject::parse_json_object(GlobalObject& global_object, const JsonObj
 
 Array* JSONObject::parse_json_array(GlobalObject& global_object, const JsonArray& json_array)
 {
-    auto* array = Array::create(global_object);
+    auto* array = Array::create(global_object, 0);
     size_t index = 0;
     json_array.for_each([&](auto& value) {
         array->define_property(index++, parse_json_value(global_object, value));

+ 1 - 1
Userland/Libraries/LibJS/Runtime/MapIteratorPrototype.cpp

@@ -59,7 +59,7 @@ JS_DEFINE_NATIVE_FUNCTION(MapIteratorPrototype::next)
     else if (iteration_kind == Object::PropertyKind::Value)
         return create_iterator_result_object(global_object, entry.value, false);
 
-    auto* entry_array = Array::create(global_object);
+    auto* entry_array = Array::create(global_object, 0);
     entry_array->define_property(0, entry.key);
     entry_array->define_property(1, entry.value);
     return create_iterator_result_object(global_object, entry_array, false);

+ 3 - 3
Userland/Libraries/LibJS/Runtime/Object.cpp

@@ -297,7 +297,7 @@ MarkedValueList Object::get_own_properties(PropertyKind kind, bool only_enumerab
             } else if (kind == PropertyKind::Value) {
                 properties.append(js_string(vm(), String::formatted("{:c}", str[i])));
             } else {
-                auto* entry_array = Array::create(global_object());
+                auto* entry_array = Array::create(global_object(), 0);
                 entry_array->define_property(0, js_string(vm(), String::number(i)));
                 entry_array->define_property(1, js_string(vm(), String::formatted("{:c}", str[i])));
                 properties.append(entry_array);
@@ -318,7 +318,7 @@ MarkedValueList Object::get_own_properties(PropertyKind kind, bool only_enumerab
             } else if (kind == PropertyKind::Value) {
                 properties.append(value_and_attributes.value);
             } else {
-                auto* entry_array = Array::create(global_object());
+                auto* entry_array = Array::create(global_object(), 0);
                 entry_array->define_property(0, js_string(vm(), String::number(entry.index())));
                 entry_array->define_property(1, value_and_attributes.value);
                 properties.append(entry_array);
@@ -341,7 +341,7 @@ MarkedValueList Object::get_own_properties(PropertyKind kind, bool only_enumerab
             if (val.is_empty())
                 return;
 
-            auto* entry_array = Array::create(global_object());
+            auto* entry_array = Array::create(global_object(), 0);
             entry_array->define_property(0, property.key.to_value(vm()));
             entry_array->define_property(1, val);
             properties.append(entry_array);

+ 1 - 1
Userland/Libraries/LibJS/Runtime/OrdinaryFunctionObject.cpp

@@ -166,7 +166,7 @@ Value OrdinaryFunctionObject::execute_function_body()
                 [&](const auto& param) {
                     Value argument_value;
                     if (parameter.is_rest) {
-                        auto* array = Array::create(global_object());
+                        auto* array = Array::create(global_object(), 0);
                         for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
                             array->indexed_properties().append(execution_context_arguments[rest_index]);
                         argument_value = move(array);

+ 2 - 2
Userland/Libraries/LibJS/Runtime/ProxyObject.cpp

@@ -431,7 +431,7 @@ Value ProxyObject::call()
     arguments.append(Value(&m_target));
     arguments.append(Value(&m_handler));
     // FIXME: Pass global object
-    auto arguments_array = Array::create(global_object());
+    auto arguments_array = Array::create(global_object(), 0);
     vm.for_each_argument([&](auto& argument) {
         arguments_array->indexed_properties().append(argument);
     });
@@ -458,7 +458,7 @@ Value ProxyObject::construct(FunctionObject& new_target)
         return static_cast<FunctionObject&>(m_target).construct(new_target);
     MarkedValueList arguments(vm.heap());
     arguments.append(Value(&m_target));
-    auto arguments_array = Array::create(global_object());
+    auto arguments_array = Array::create(global_object(), 0);
     vm.for_each_argument([&](auto& argument) {
         arguments_array->indexed_properties().append(argument);
     });

+ 1 - 1
Userland/Libraries/LibJS/Runtime/SetIteratorPrototype.cpp

@@ -61,7 +61,7 @@ JS_DEFINE_NATIVE_FUNCTION(SetIteratorPrototype::next)
     if (iteration_kind == Object::PropertyKind::Value)
         return create_iterator_result_object(global_object, value, false);
 
-    auto* entry_array = Array::create(global_object);
+    auto* entry_array = Array::create(global_object, 0);
     entry_array->define_property(0, value);
     entry_array->define_property(1, value);
     return create_iterator_result_object(global_object, entry_array, false);

+ 1 - 1
Userland/Libraries/LibJS/Runtime/StringPrototype.cpp

@@ -592,7 +592,7 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::split)
 
     auto string = this_value.to_string(global_object);
 
-    auto* result = Array::create(global_object);
+    auto* result = Array::create(global_object, 0);
     size_t result_len = 0;
 
     auto limit = NumericLimits<u32>::max();

+ 1 - 1
Userland/Libraries/LibJS/Runtime/VM.cpp

@@ -218,7 +218,7 @@ void VM::assign(const NonnullRefPtr<BindingPattern>& target, Value value, Global
             if (entry.is_rest) {
                 VERIFY(i == binding.entries.size() - 1);
 
-                auto* array = Array::create(global_object);
+                auto* array = Array::create(global_object, 0);
                 for (;;) {
                     auto next_object = iterator_next(*iterator);
                     if (!next_object)

+ 1 - 1
Userland/Libraries/LibWeb/Bindings/NavigatorObject.cpp

@@ -21,7 +21,7 @@ NavigatorObject::NavigatorObject(JS::GlobalObject& global_object)
 void NavigatorObject::initialize(JS::GlobalObject& global_object)
 {
     auto& heap = this->heap();
-    auto* languages = JS::Array::create(global_object);
+    auto* languages = JS::Array::create(global_object, 0);
     languages->indexed_properties().append(js_string(heap, "en-US"));
 
     define_property("appCodeName", js_string(heap, "Mozilla"));

+ 1 - 1
Userland/Libraries/LibWeb/CodeGenerators/WrapperGenerator.cpp

@@ -1401,7 +1401,7 @@ static @fully_qualified_name@* impl_from(JS::VM& vm, JS::GlobalObject& global_ob
             // FIXME: Remove this fake type hack once it's no longer needed.
             //        Basically once we have NodeList we can throw this out.
             scoped_generator.append(R"~~~(
-    auto* new_array = JS::Array::create(global_object);
+    auto* new_array = JS::Array::create(global_object, 0);
     for (auto& element : retval)
         new_array->indexed_properties().append(wrap(global_object, element));