1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-31 19:38:12 +00:00

LibJS: Implement spec-compliant OrdinaryToPrimitive

This renames Object::to_primitive() to Object::ordinary_to_primitive()
for two reasons:

- No confusion with Value::to_primitive()
- To match the spec's name

Also change existing uses of Object::to_primitive() to
Value::to_primitive() when the spec uses the latter (which will still
call Object::ordinary_to_primitive()). Object::to_string() has been
removed as it's not needed anymore (and nothing the spec uses).

This makes it possible to overwrite an object's toString and valueOf and
have them provide results for anything that uses to_primitive() - e.g.:

    const o = { toString: undefined, valueOf: () => 42 };
    Number(o) // 42, previously NaN
    ["foo", o].toString(); // "foo,42", previously "foo,[object Object]"
    ++o // 43, previously NaN

etc.
This commit is contained in:
Linus Groh 2020-11-03 19:52:21 +00:00 committed by Andreas Kling
parent e163db248d
commit fb89c324c5
4 changed files with 50 additions and 42 deletions

View file

@ -168,7 +168,7 @@ String Value::to_string(GlobalObject& global_object) const
case Type::BigInt:
return m_value.as_bigint->big_integer().to_base10();
case Type::Object: {
auto primitive_value = as_object().to_primitive(PreferredType::String);
auto primitive_value = to_primitive(PreferredType::String);
if (global_object.vm().exception())
return {};
return primitive_value.to_string(global_object);
@ -205,8 +205,12 @@ bool Value::to_boolean() const
Value Value::to_primitive(PreferredType preferred_type) const
{
if (is_object())
return as_object().to_primitive(preferred_type);
if (is_object()) {
// FIXME: Also support @@toPrimitive
if (preferred_type == PreferredType::Default)
preferred_type = PreferredType::Number;
return as_object().ordinary_to_primitive(preferred_type);
}
return *this;
}
@ -277,7 +281,7 @@ Value Value::to_number(GlobalObject& global_object) const
global_object.vm().throw_exception<TypeError>(global_object, ErrorType::Convert, "BigInt", "number");
return {};
case Type::Object: {
auto primitive = m_value.as_object->to_primitive(PreferredType::Number);
auto primitive = to_primitive(PreferredType::Number);
if (global_object.vm().exception())
return {};
return primitive.to_number(global_object);