Skip to content

Commit 6e393ec

Browse files
authored
feat(minifier): evaluate String constructor (#12943)
1 parent ad4aeaf commit 6e393ec

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

crates/oxc_minifier/src/peephole/substitute_alternate_syntax.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::iter::repeat_with;
22

33
use oxc_allocator::{CloneIn, TakeIn, Vec};
44
use oxc_ast::{NONE, ast::*};
5-
use oxc_ecmascript::constant_evaluation::DetermineValueType;
5+
use oxc_ecmascript::constant_evaluation::{ConstantEvaluation, ConstantValue, DetermineValueType};
66
use oxc_ecmascript::{ToJsString, ToNumber, side_effects::MayHaveSideEffects};
77
use oxc_span::GetSpan;
88
use oxc_span::SPAN;
@@ -654,18 +654,10 @@ impl<'a> PeepholeOptimizations {
654654
match arg {
655655
// `String()` -> `''`
656656
None => Some(ctx.ast.expression_string_literal(span, "", None)),
657-
// `String(a)` -> `'' + (a)`
658-
Some(arg) => {
659-
if !arg.is_literal() {
660-
return None;
661-
}
662-
Some(ctx.ast.expression_binary(
663-
span,
664-
ctx.ast.expression_string_literal(call_expr.span, "", None),
665-
BinaryOperator::Addition,
666-
arg.take_in(ctx.ast),
667-
))
668-
}
657+
Some(arg) => arg
658+
.evaluate_value_to_string(ctx)
659+
.filter(|_| !arg.may_have_side_effects(ctx))
660+
.map(|s| ctx.value_to_expr(call_expr.span, ConstantValue::String(s))),
669661
}
670662
}
671663
"Number" => Some(ctx.ast.expression_numeric_literal(
@@ -1848,6 +1840,8 @@ mod test {
18481840
test_same("var a = String?.(23)");
18491841

18501842
test("var a = String('hello')", "var a = 'hello'");
1843+
test("var a = String(true)", "var a = 'true'");
1844+
test("var a = String(!0)", "var a = 'true'");
18511845
// Don't fold the existence check to preserve behavior
18521846
test_same("var a = String?.('hello')");
18531847

0 commit comments

Comments
 (0)