@@ -2,7 +2,7 @@ use std::iter::repeat_with;
22
33use oxc_allocator:: { CloneIn , TakeIn , Vec } ;
44use oxc_ast:: { NONE , ast:: * } ;
5- use oxc_ecmascript:: constant_evaluation:: DetermineValueType ;
5+ use oxc_ecmascript:: constant_evaluation:: { ConstantEvaluation , ConstantValue , DetermineValueType } ;
66use oxc_ecmascript:: { ToJsString , ToNumber , side_effects:: MayHaveSideEffects } ;
77use oxc_span:: GetSpan ;
88use 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