LibJS: Implement RegExp.prototype.toString() as standalone function

This should not just inherit Object.prototype.toString() (and override
Object::to_string()) but be its own function, i.e.
'RegExp.prototype.toString !== Object.prototype.toString'.
This commit is contained in:
Linus Groh 2020-11-03 19:39:02 +00:00 committed by Andreas Kling
parent 41837f548d
commit e163db248d
Notes: sideshowbarker 2024-07-19 01:33:58 +09:00
5 changed files with 38 additions and 10 deletions

View file

@ -49,9 +49,4 @@ RegExpObject::~RegExpObject()
{
}
Value RegExpObject::to_string() const
{
return js_string(heap(), String::formatted("/{}/{}", content(), flags()));
}
}

View file

@ -43,8 +43,6 @@ public:
const String& content() const { return m_content; }
const String& flags() const { return m_flags; }
Value to_string() const override;
private:
virtual bool is_regexp_object() const override { return true; }

View file

@ -25,10 +25,8 @@
*/
#include <AK/Function.h>
#include <AK/StringBuilder.h>
#include <LibJS/Heap/Heap.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/RegExpObject.h>
#include <LibJS/Runtime/RegExpPrototype.h>
@ -39,8 +37,36 @@ RegExpPrototype::RegExpPrototype(GlobalObject& global_object)
{
}
void RegExpPrototype::initialize(GlobalObject& global_object)
{
auto& vm = this->vm();
Object::initialize(global_object);
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function(vm.names.toString, to_string, 0, attr);
}
RegExpPrototype::~RegExpPrototype()
{
}
static RegExpObject* regexp_object_from(VM& vm, GlobalObject& global_object)
{
auto* this_object = vm.this_value(global_object).to_object(global_object);
if (!this_object)
return nullptr;
if (!this_object->is_regexp_object()) {
vm.throw_exception<TypeError>(global_object, ErrorType::NotA, "RegExp");
return nullptr;
}
return static_cast<RegExpObject*>(this_object);
}
JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::to_string)
{
auto* regexp_object = regexp_object_from(vm, global_object);
if (!regexp_object)
return {};
return js_string(vm, String::formatted("/{}/{}", regexp_object->content(), regexp_object->flags()));
}
}

View file

@ -35,7 +35,11 @@ class RegExpPrototype final : public RegExpObject {
public:
explicit RegExpPrototype(GlobalObject&);
virtual void initialize(GlobalObject&) override;
virtual ~RegExpPrototype() override;
private:
JS_DECLARE_NATIVE_FUNCTION(to_string);
};
}

View file

@ -0,0 +1,5 @@
test("basic functionality", () => {
expect(RegExp.prototype.toString).toHaveLength(0);
expect(/test/g.toString()).toBe("/test/g");
});