From 6f96f01171bc975de3edc432353fbd168a6e8346 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Sun, 6 Jun 2021 16:38:05 +0100 Subject: [PATCH] LibJS: Replace StringPrototype's typed_this() with this_string_value() This brings the code close to the spec with no trade-offs, which is always valuable. No functionality change. --- .../LibJS/Runtime/StringPrototype.cpp | 37 +++++++++---------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp index 81f0762274..1af489e334 100644 --- a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -22,18 +22,6 @@ namespace JS { -static StringObject* typed_this(VM& vm, GlobalObject& global_object) -{ - auto* this_object = vm.this_value(global_object).to_object(global_object); - if (!this_object) - return nullptr; - if (!is(this_object)) { - vm.throw_exception(global_object, ErrorType::NotA, "String"); - return nullptr; - } - return static_cast(this_object); -} - static String ak_string_from(VM& vm, GlobalObject& global_object) { auto this_value = require_object_coercible(global_object, vm.this_value(global_object)); @@ -111,6 +99,18 @@ StringPrototype::~StringPrototype() { } +// thisStringValue, https://tc39.es/ecma262/#thisstringvalue +static Value this_string_value(GlobalObject& global_object, Value value) +{ + if (value.is_string()) + return value; + if (value.is_object() && is(value.as_object())) + return static_cast(value.as_object()).value_of(); + auto& vm = global_object.vm(); + vm.throw_exception(global_object, ErrorType::NotA, "String"); + return {}; +} + JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_at) { auto string = ak_string_from(vm, global_object); @@ -274,20 +274,17 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::to_uppercase) return js_string(vm, string.to_uppercase()); } -JS_DEFINE_NATIVE_GETTER(StringPrototype::length_getter) +JS_DEFINE_NATIVE_FUNCTION(StringPrototype::length_getter) { - auto* string_object = typed_this(vm, global_object); - if (!string_object) + auto string_value = this_string_value(global_object, vm.this_value(global_object)); + if (vm.exception()) return {}; - return Value((i32)string_object->primitive_string().string().length()); + return Value((i32)string_value.as_string().string().length()); } JS_DEFINE_NATIVE_FUNCTION(StringPrototype::to_string) { - auto* string_object = typed_this(vm, global_object); - if (!string_object) - return {}; - return js_string(vm, string_object->primitive_string().string()); + return this_string_value(global_object, vm.this_value(global_object)); } enum class PadPlacement {