From b6e5442d55b5294fa8fc2c3728950dfb77b64a30 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Fri, 27 Nov 2020 23:10:19 +0000 Subject: [PATCH] LibJS: Make RegExp.prototype.toString() spec-compliant It should use the 'source' and 'flags' properties of the object, and therefore work with non-RegExp objects as well. --- Libraries/LibJS/Runtime/RegExpPrototype.cpp | 21 ++++++++++++++++--- .../RegExp/RegExp.prototype.toString.js | 1 + 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Libraries/LibJS/Runtime/RegExpPrototype.cpp b/Libraries/LibJS/Runtime/RegExpPrototype.cpp index d4eb4bd882f..c35b8f987fa 100644 --- a/Libraries/LibJS/Runtime/RegExpPrototype.cpp +++ b/Libraries/LibJS/Runtime/RegExpPrototype.cpp @@ -248,10 +248,25 @@ JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::test) JS_DEFINE_NATIVE_FUNCTION(RegExpPrototype::to_string) { - auto* regexp_object = regexp_object_from(vm, global_object); - if (!regexp_object) + auto this_object = this_object_from(vm, global_object); + if (!this_object) return {}; - return js_string(vm, String::formatted("/{}/{}", regexp_object->pattern(), regexp_object->flags())); + + auto source_attr = this_object->get(vm.names.source).value_or(js_undefined()); + if (vm.exception()) + return {}; + auto pattern = source_attr.to_string(global_object); + if (vm.exception()) + return {}; + + auto flags_attr = this_object->get(vm.names.flags).value_or(js_undefined()); + if (vm.exception()) + return {}; + auto flags = flags_attr.to_string(global_object); + if (vm.exception()) + return {}; + + return js_string(vm, String::formatted("/{}/{}", pattern, flags)); } } diff --git a/Libraries/LibJS/Tests/builtins/RegExp/RegExp.prototype.toString.js b/Libraries/LibJS/Tests/builtins/RegExp/RegExp.prototype.toString.js index 5185fcc036b..fcf132862dd 100644 --- a/Libraries/LibJS/Tests/builtins/RegExp/RegExp.prototype.toString.js +++ b/Libraries/LibJS/Tests/builtins/RegExp/RegExp.prototype.toString.js @@ -2,4 +2,5 @@ test("basic functionality", () => { expect(RegExp.prototype.toString).toHaveLength(0); expect(/test/g.toString()).toBe("/test/g"); + expect(RegExp.prototype.toString.call({ source: "test", flags: "g" })).toBe("/test/g"); });