Skip to content

Commit

Permalink
NativeRegExp: fix RegExp.prototype.toString throwing TypeError on Nat…
Browse files Browse the repository at this point in the history
…iveObject
  • Loading branch information
duonglaiquang committed Jan 4, 2024
1 parent abb8edc commit a9ccd92
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/org/mozilla/javascript/regexp/NativeRegExp.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import org.mozilla.javascript.IdFunctionObject;
import org.mozilla.javascript.IdScriptableObject;
import org.mozilla.javascript.Kit;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
Expand Down Expand Up @@ -2716,6 +2717,14 @@ public Object execIdCall(
return realThis(thisObj, f).compile(cx, scope, args);

case Id_toString:
if (thisObj instanceof NativeObject) {
Object sourceObj = thisObj.get("source", thisObj);
String source = sourceObj.equals(NOT_FOUND) ? "undefined" : escapeRegExp(sourceObj);
Object flagsObj = thisObj.get("flags", thisObj);
String flags = flagsObj.equals(NOT_FOUND) ? "undefined" : flagsObj.toString();

return "/" + source + "/" + flags;
}
case Id_toSource:
return realThis(thisObj, f).toString();

Expand Down
10 changes: 10 additions & 0 deletions testsrc/org/mozilla/javascript/tests/NativeRegExpTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,16 @@ public void flagsPropery() throws Exception {
test("0-undefined-true-false-undefined", script);
}

/** @throws Exception if an error occurs */
@Test
public void objectToString() throws Exception {
test("/undefined/undefined", "RegExp.prototype.toString.call({})");
test("/Foo/undefined", "RegExp.prototype.toString.call({source: 'Foo'})");
test("/undefined/gy", "RegExp.prototype.toString.call({flags: 'gy'})");
test("/Foo/g", "RegExp.prototype.toString.call({source: 'Foo', flags: 'g'})");
test("/Foo/g", "RegExp.prototype.toString.call({source: 'Foo', flags: 'g', sticky: true})");
}

private static void test(final String expected, final String script) {
Utils.runWithAllOptimizationLevels(
cx -> {
Expand Down

0 comments on commit a9ccd92

Please sign in to comment.