Skip to content

Commit 07aa646

Browse files
committed
automatically mark "RegExp.escape()" calls as pure
1 parent 9039c46 commit 07aa646

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

internal/js_parser/js_parser.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15266,6 +15266,17 @@ func (p *parser) visitExprInOut(expr js_ast.Expr, in exprIn) (js_ast.Expr, exprO
1526615266
}
1526715267
}
1526815268
}
15269+
15270+
case "escape":
15271+
// Recognize "RegExp.escape()" calls
15272+
if id, ok := t.Target.Data.(*js_ast.EIdentifier); ok {
15273+
if symbol := &p.symbols[id.Ref.InnerIndex]; symbol.Kind == ast.SymbolUnbound && symbol.OriginalName == "RegExp" {
15274+
if js_ast.KnownPrimitiveType(e.Args[0].Data) == js_ast.PrimitiveString {
15275+
// Mark "RegExp.escape" with a string literal as pure
15276+
e.CanBeUnwrappedIfUnused = true
15277+
}
15278+
}
15279+
}
1526915280
}
1527015281
}
1527115282

internal/js_parser/js_parser_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6751,6 +6751,18 @@ func TestAutoPureForDate(t *testing.T) {
67516751
expectPrinted(t, "new Date(foo ? x : y)", "new Date(foo ? x : y);\n")
67526752
}
67536753

6754+
func TestAutoPureForRegExpEscape(t *testing.T) {
6755+
expectPrinted(t, "RegExp.escape('x')", "/* @__PURE__ */ RegExp.escape(\"x\");\n")
6756+
expectPrinted(t, "RegExp.escape(`${x}`)", "/* @__PURE__ */ RegExp.escape(`${x}`);\n")
6757+
expectPrinted(t, "RegExp.escape(x ? 'y' : 'z')", "/* @__PURE__ */ RegExp.escape(x ? \"y\" : \"z\");\n")
6758+
6759+
expectPrinted(t, "RegExp.escape()", "RegExp.escape();\n")
6760+
expectPrinted(t, "RegExp.escape(x`y`)", "RegExp.escape(x`y`);\n")
6761+
expectPrinted(t, "RegExp.escape('x', 'y')", "RegExp.escape(\"x\", \"y\");\n")
6762+
expectPrinted(t, "RegExp.escape(x ? 'y' : z)", "RegExp.escape(x ? \"y\" : z);\n")
6763+
expectPrinted(t, "RegExp.escape(x ? y : 'z')", "RegExp.escape(x ? y : \"z\");\n")
6764+
}
6765+
67546766
// See: https://github.com/tc39/proposal-explicit-resource-management
67556767
func TestUsing(t *testing.T) {
67566768
expectPrinted(t, "using x = y", "using x = y;\n")

0 commit comments

Comments
 (0)