@@ -5,7 +5,7 @@ use oxc_ecmascript::{constant_evaluation::ConstantEvaluation, side_effects::MayH
55use oxc_span:: GetSpan ;
66use oxc_traverse:: Ancestor ;
77
8- use crate :: { ctx:: Ctx , keep_var:: KeepVar } ;
8+ use crate :: { CompressOptionsUnused , ctx:: Ctx , keep_var:: KeepVar } ;
99
1010use super :: { LatePeepholeOptimizations , PeepholeOptimizations , State } ;
1111
@@ -47,16 +47,43 @@ impl<'a> PeepholeOptimizations {
4747 Expression :: ConditionalExpression ( e) => {
4848 self . try_fold_conditional_expression ( e, state, ctx)
4949 }
50- Expression :: SequenceExpression ( sequence_expression) => {
51- self . try_fold_sequence_expression ( sequence_expression, state, ctx)
52- }
50+ Expression :: SequenceExpression ( e) => self . try_fold_sequence_expression ( e, state, ctx) ,
51+ Expression :: AssignmentExpression ( e) => self . remove_dead_assignment_expression ( e, ctx) ,
5352 _ => None ,
5453 } {
5554 * expr = folded_expr;
5655 state. changed = true ;
5756 }
5857 }
5958
59+ fn remove_dead_assignment_expression (
60+ & self ,
61+ e : & mut AssignmentExpression < ' a > ,
62+ ctx : & mut Ctx < ' a , ' _ > ,
63+ ) -> Option < Expression < ' a > > {
64+ if matches ! (
65+ ctx. state. options. unused,
66+ CompressOptionsUnused :: Keep | CompressOptionsUnused :: KeepAssign
67+ ) {
68+ return None ;
69+ }
70+ let SimpleAssignmentTarget :: AssignmentTargetIdentifier ( ident) =
71+ e. left . as_simple_assignment_target ( ) ?
72+ else {
73+ return None ;
74+ } ;
75+ let reference_id = ident. reference_id . get ( ) ?;
76+ let symbol_id = ctx. scoping ( ) . get_reference ( reference_id) . symbol_id ( ) ?;
77+ // Keep error for assigning to `const foo = 1; foo = 2`.
78+ if ctx. scoping ( ) . symbol_flags ( symbol_id) . is_const_variable ( ) {
79+ return None ;
80+ }
81+ if !ctx. scoping ( ) . get_resolved_references ( symbol_id) . all ( |r| !r. flags ( ) . is_read ( ) ) {
82+ return None ;
83+ }
84+ Some ( e. right . take_in ( ctx. ast ) )
85+ }
86+
6087 /// Removes dead code thats comes after `return`, `throw`, `continue` and `break` statements.
6188 pub fn remove_dead_code_exit_statements (
6289 & self ,
0 commit comments