feat(minifier): fold (!0).toString() to true (#12938)

This commit is contained in:
Boshen committed 2025-08-09 14:46:21 +00:00
1 parent a13b3ee17c
commit 784796d869
3 files changed
+13 -9

No files matched your search

@@ -324,16 +324,14 @@ fn try_fold_to_string<'a>(
let result = format_radix(i, radix);
Some(ConstantValue::String(Cow::Owned(result)))
}
// `null` returns type errors
Expression::BooleanLiteral(_)
| Expression::NumericLiteral(_)
| Expression::BigIntLiteral(_)
| Expression::RegExpLiteral(_)
| Expression::StringLiteral(_)
if args.is_empty() =>
{
object.to_js_string(ctx).map(ConstantValue::String)
Expression::RegExpLiteral(lit) if args.is_empty() => {
lit.to_js_string(ctx).map(ConstantValue::String)
}
e if args.is_empty() => e
.evaluate_value(ctx)
// `null` and `undefined` returns type errors
.filter(|v| !v.is_undefined() && !v.is_null())
.and_then(|v| v.to_js_string(ctx).map(ConstantValue::String)),
_ => None,
}
}
@@ -36,6 +36,10 @@ impl<'a> ConstantValue<'a> {
matches!(self, Self::Undefined)
}
pub fn is_null(&self) -> bool {
matches!(self, Self::Null)
}
pub fn into_string(self) -> Option<Cow<'a, str>> {
match self {
Self::String(s) => Some(s),
@@ -1486,6 +1486,8 @@ mod test {
test("x = false['toString']()", "x = 'false';");
test("x = false.toString()", "x = 'false';");
test("x = true.toString()", "x = 'true';");
test("x = (!0).toString()", "x = 'true';");
test("x = (!1).toString()", "x = 'false';");
test("x = 'xy'.toString()", "x = 'xy';");
test("x = 0 .toString()", "x = '0';");
test("x = 123 .toString()", "x = '123';");