forked from swc-project/swc
/
mod.rs
3084 lines (2597 loc) · 95.2 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::iter::once;
use rustc_hash::{FxHashMap, FxHashSet};
use swc_atoms::{js_word, JsWord};
use swc_common::{
collections::AHashMap, iter::IdentifyLast, pass::Repeated, util::take::Take, Spanned,
SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_transforms_optimization::debug_assert_valid;
use swc_ecma_usage_analyzer::{analyzer::UsageAnalyzer, marks::Marks};
use swc_ecma_utils::{
prepend_stmts, undefined, ExprCtx, ExprExt, ExprFactory, IsEmpty, ModuleItemLike, StmtLike,
Type, Value,
};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith};
#[cfg(feature = "debug")]
use tracing::{debug, span, Level};
use Value::Known;
use self::{
unused::PropertyAccessOpts,
util::{extract_class_side_effect, Finalizer, NormalMultiReplacer, SynthesizedStmts},
};
use super::util::{drop_invalid_stmts, is_fine_for_if_cons};
#[cfg(feature = "debug")]
use crate::debug::dump;
use crate::{
compress::util::is_pure_undefined,
debug::AssertValid,
maybe_par,
mode::Mode,
option::CompressOptions,
program_data::{ModuleInfo, ProgramData},
util::{
contains_eval, contains_leaping_continue_with_label, make_number, ExprOptExt, ModuleItemExt,
},
};
mod arguments;
mod bools;
mod collapse_vars;
mod conditionals;
mod dead_code;
mod evaluate;
mod if_return;
mod iife;
mod inline;
mod loops;
mod ops;
mod props;
mod sequences;
mod strings;
mod switches;
mod unused;
mod util;
/// This pass is similar to `node.optimize` of terser.
pub(super) fn optimizer<'a, M>(
marks: Marks,
options: &'a CompressOptions,
module_info: &'a ModuleInfo,
data: &'a mut ProgramData,
mode: &'a M,
debug_infinite_loop: bool,
) -> impl 'a + VisitMut + Repeated
where
M: Mode,
{
assert!(
options.top_retain.iter().all(|s| s.trim() != ""),
"top_retain should not contain empty string"
);
Optimizer {
marks,
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(marks.unresolved_mark),
is_unresolved_ref_safe: false,
},
changed: false,
options,
module_info,
prepend_stmts: Default::default(),
append_stmts: Default::default(),
vars: Default::default(),
vars_for_prop_hoisting: Default::default(),
simple_props: Default::default(),
typeofs: Default::default(),
data,
ctx: Default::default(),
label: Default::default(),
mode,
debug_infinite_loop,
functions: Default::default(),
}
}
/// Syntactic context.
///
/// This should not be modified directly. Use `.with_ctx()` instead.
#[derive(Debug, Default, Clone, Copy)]
struct Ctx {
/// See [crate::marks::Marks]
skip_standalone: bool,
/// `true` if the [VarDecl] has const annotation.
#[allow(dead_code)]
has_const_ann: bool,
dont_use_prepend_nor_append: bool,
in_bool_ctx: bool,
in_asm: bool,
/// `true` only for [Callee::Expr].
is_callee: bool,
in_call_arg: bool,
var_kind: Option<VarDeclKind>,
/// `true` if we are in the strict mode. This will be set to `true` for
/// statements **after** `'use strict'`
in_strict: bool,
/// `true` if we are try block. `true` means we cannot be sure about control
/// flow.
in_try_block: bool,
/// `true` while handling `test` of if / while / for.
in_cond: bool,
/// `true` if we are in `arg` of `delete arg`.
is_delete_arg: bool,
/// `true` if we are in `arg` of `++arg` or `--arg`.
is_update_arg: bool,
is_lhs_of_assign: bool,
/// `false` for `d` in `d[0] = foo`.
is_exact_lhs_of_assign: bool,
/// `true` for loop bodies and conditions of loops.
executed_multiple_time: bool,
/// `true` while handling `expr` of `!expr`
in_bang_arg: bool,
in_var_decl_of_for_in_or_of_loop: bool,
dont_use_negated_iife: bool,
/// `true` while handling top-level export decls.
is_exported: bool,
/// `true` while handling top level items.
top_level: bool,
/// `true` while we are in a function or something similar.
in_fn_like: bool,
in_block: bool,
in_obj_of_non_computed_member: bool,
#[allow(dead_code)]
in_tpl_expr: bool,
/// True while handling callee, except an arrow expression in callee.
is_this_aware_callee: bool,
is_nested_if_return_merging: bool,
dont_invoke_iife: bool,
in_with_stmt: bool,
/// Current scope.
scope: SyntaxContext,
}
impl Ctx {
pub fn is_top_level_for_block_level_vars(self) -> bool {
if self.top_level {
return true;
}
if self.in_fn_like || self.in_block {
return false;
}
true
}
pub fn in_top_level(self) -> bool {
self.top_level || !self.in_fn_like
}
}
struct Optimizer<'a, M> {
marks: Marks,
expr_ctx: ExprCtx,
changed: bool,
options: &'a CompressOptions,
module_info: &'a ModuleInfo,
/// Statements prepended to the current statement.
prepend_stmts: SynthesizedStmts,
/// Statements appended to the current statement.
append_stmts: SynthesizedStmts,
vars: Vars,
/// Used for `hoist_props`.
vars_for_prop_hoisting: Box<FxHashMap<Id, Box<Expr>>>,
/// Used for `hoist_props`.
simple_props: Box<FxHashMap<(Id, JsWord), Box<Expr>>>,
typeofs: Box<AHashMap<Id, JsWord>>,
/// This information is created by analyzing identifier usages.
///
/// This is calculated multiple time, but only once per one
/// `visit_mut_module`.
data: &'a mut ProgramData,
ctx: Ctx,
/// Closest label.
///
/// Setting this to `None` means the label should be removed.
label: Option<Id>,
mode: &'a M,
#[allow(unused)]
debug_infinite_loop: bool,
functions: Box<FxHashMap<Id, FnMetadata>>,
}
#[derive(Default)]
struct Vars {
/// Cheap to clone.
///
/// Used for inlining.
lits: FxHashMap<Id, Box<Expr>>,
/// Literals which are cheap to clone, but not sure if we can inline without
/// making output bigger.
///
/// https://github.com/swc-project/swc/issues/4415
lits_for_cmp: FxHashMap<Id, Box<Expr>>,
/// This stores [Expr::Array] if all elements are literals.
lits_for_array_access: FxHashMap<Id, Box<Expr>>,
/// Used for copying functions.
///
/// We use this to distinguish [Callee::Expr] from other [Expr]s.
simple_functions: FxHashMap<Id, Box<Expr>>,
vars_for_inlining: FxHashMap<Id, Box<Expr>>,
/// Variables which should be removed by [Finalizer] because of the order of
/// visit.
removed: FxHashSet<Id>,
}
impl Vars {
fn has_pending_inline_for(&self, id: &Id) -> bool {
self.lits.contains_key(id) || self.vars_for_inlining.contains_key(id)
}
/// Returns true if something is changed.
fn inline_with_multi_replacer<N>(&mut self, n: &mut N) -> bool
where
N: for<'aa> VisitMutWith<NormalMultiReplacer<'aa>>,
N: for<'aa> VisitMutWith<Finalizer<'aa>>,
{
let mut changed = false;
if !self.simple_functions.is_empty()
|| !self.lits_for_cmp.is_empty()
|| !self.lits_for_array_access.is_empty()
|| !self.removed.is_empty()
{
let mut v = Finalizer {
simple_functions: &self.simple_functions,
lits_for_cmp: &self.lits_for_cmp,
lits_for_array_access: &self.lits_for_array_access,
vars_to_remove: &self.removed,
changed: false,
};
n.visit_mut_with(&mut v);
changed |= v.changed;
}
if !self.vars_for_inlining.is_empty() {
let mut v = NormalMultiReplacer::new(&mut self.vars_for_inlining);
n.visit_mut_with(&mut v);
changed |= v.changed;
}
changed
}
}
impl<M> Repeated for Optimizer<'_, M> {
fn changed(&self) -> bool {
self.changed
}
fn reset(&mut self) {
self.changed = false;
}
}
#[derive(Debug, Clone, Copy)]
struct FnMetadata {
len: usize,
}
impl From<&Function> for FnMetadata {
fn from(f: &Function) -> Self {
FnMetadata {
len: f
.params
.iter()
.filter(|p| matches!(&p.pat, Pat::Ident(..) | Pat::Array(..) | Pat::Object(..)))
.count(),
}
}
}
impl<M> Optimizer<'_, M>
where
M: Mode,
{
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn handle_stmt_likes<T>(&mut self, stmts: &mut Vec<T>)
where
T: StmtLike + ModuleItemLike + ModuleItemExt + VisitMutWith<Self> + VisitWith<AssertValid>,
Vec<T>: VisitMutWith<Self> + VisitWith<UsageAnalyzer<ProgramData>> + VisitWith<AssertValid>,
{
let mut use_asm = false;
let prepend_stmts = self.prepend_stmts.take();
let append_stmts = self.append_stmts.take();
{
let mut child_ctx = Ctx { ..self.ctx };
let mut directive_count = 0;
if !stmts.is_empty() {
// TODO: Handle multiple directives.
if let Some(Stmt::Expr(ExprStmt { expr, .. })) = stmts[0].as_stmt() {
if let Expr::Lit(Lit::Str(v)) = &**expr {
directive_count += 1;
match &v.raw {
Some(value) if value == "\"use strict\"" || value == "'use strict'" => {
child_ctx.in_strict = true;
}
Some(value) if value == "\"use asm\"" || value == "'use asm'" => {
child_ctx.in_asm = true;
self.ctx.in_asm = true;
use_asm = true;
}
_ => {}
}
}
}
}
let mut new = Vec::with_capacity(stmts.len() * 11 / 10);
for (i, mut stmt) in stmts.take().into_iter().enumerate() {
// debug_assert_eq!(self.prepend_stmts, vec![]);
// debug_assert_eq!(self.append_stmts, vec![]);
if i < directive_count {
// Don't set in_strict for directive itself.
stmt.visit_mut_with(self);
} else {
let child_optimizer = &mut *self.with_ctx(child_ctx);
stmt.visit_mut_with(child_optimizer);
}
#[cfg(debug_assertions)]
{
stmt.visit_with(&mut AssertValid);
}
new.extend(self.prepend_stmts.drain(..).map(T::from_stmt));
match stmt.try_into_stmt() {
Ok(Stmt::Block(s)) if s.span.has_mark(self.marks.fake_block) => {
new.extend(s.stmts.into_iter().map(T::from_stmt));
}
Ok(s) => {
new.push(T::from_stmt(s));
}
Err(stmt) => {
new.push(stmt);
}
}
new.extend(self.append_stmts.drain(..).map(T::from_stmt));
}
*stmts = new;
}
self.ctx.in_asm |= use_asm;
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.merge_sequences_in_stmts(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.merge_similar_ifs(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.make_sequences(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.drop_else_token(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.break_assignments_in_seqs(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
// stmts.extend(self.append_stmts.drain(..).map(T::from_stmt));
drop_invalid_stmts(stmts);
// debug_assert_eq!(self.prepend_stmts, vec![]);
self.prepend_stmts = prepend_stmts;
self.append_stmts = append_stmts;
}
/// `a = a + 1` => `a += 1`.
fn compress_bin_assignment_to_left(&mut self, e: &mut AssignExpr) {
if e.op != op!("=") {
return;
}
// TODO: Handle pure properties.
let lhs = match &e.left {
PatOrExpr::Expr(e) => match &**e {
Expr::Ident(i) => i,
_ => return,
},
PatOrExpr::Pat(p) => match &**p {
Pat::Ident(i) => &i.id,
_ => return,
},
};
// If left operand of a binary expression is not same as lhs, this method has
// nothing to do.
let (op, right) = match &mut *e.right {
Expr::Bin(BinExpr {
left, op, right, ..
}) => match &**left {
Expr::Ident(r) if lhs.sym == r.sym && lhs.span.ctxt == r.span.ctxt => (op, right),
_ => return,
},
_ => return,
};
// Don't break code for old browsers.
match op {
BinaryOp::LogicalOr => return,
BinaryOp::LogicalAnd => return,
BinaryOp::Exp => return,
BinaryOp::NullishCoalescing => return,
_ => {}
}
let op = match op {
BinaryOp::In | BinaryOp::InstanceOf => return,
BinaryOp::EqEq | BinaryOp::NotEq | BinaryOp::EqEqEq | BinaryOp::NotEqEq => {
// TODO(kdy1): Check if this is optimizable.
return;
}
BinaryOp::Lt | BinaryOp::LtEq | BinaryOp::Gt | BinaryOp::GtEq => return,
BinaryOp::LShift => op!("<<="),
BinaryOp::RShift => {
op!(">>=")
}
BinaryOp::ZeroFillRShift => {
op!(">>>=")
}
BinaryOp::Add => {
op!("+=")
}
BinaryOp::Sub => {
op!("-=")
}
BinaryOp::Mul => {
op!("*=")
}
BinaryOp::Div => {
op!("/=")
}
BinaryOp::Mod => {
op!("%=")
}
BinaryOp::BitOr => {
op!("|=")
}
BinaryOp::BitXor => {
op!("^=")
}
BinaryOp::BitAnd => {
op!("&=")
}
BinaryOp::LogicalOr => {
op!("||=")
}
BinaryOp::LogicalAnd => {
op!("&&=")
}
BinaryOp::Exp => {
op!("**=")
}
BinaryOp::NullishCoalescing => {
op!("??=")
}
};
e.op = op;
e.right = right.take();
// Now we can compress it to an assignment
}
///
/// - `undefined` => `void 0`
fn compress_undefined(&mut self, e: &mut Expr) {
if let Expr::Ident(Ident {
span,
sym: js_word!("undefined"),
..
}) = e
{
*e = *undefined(*span);
}
}
///
/// - `true` => `!1`
/// - `false` => `!0`
fn compress_lits(&mut self, e: &mut Expr) {
let lit = match e {
Expr::Lit(lit) => lit,
_ => return,
};
if self.options.bools_as_ints || self.options.bools {
if let Lit::Bool(v) = lit {
self.changed = true;
report_change!("Compressing boolean literal");
*e = Expr::Unary(UnaryExpr {
span: v.span,
op: op!("!"),
arg: Box::new(Expr::Lit(Lit::Num(Number {
span: v.span,
value: if v.value { 0.0 } else { 1.0 },
raw: None,
}))),
});
}
}
}
fn remove_invalid(&mut self, e: &mut Expr) {
if let Expr::Bin(BinExpr { left, right, .. }) = e {
self.remove_invalid(left);
self.remove_invalid(right);
if left.is_invalid() {
*e = *right.take();
self.remove_invalid(e);
} else if right.is_invalid() {
*e = *left.take();
self.remove_invalid(e);
}
}
}
/// Returns [None] if expression is side-effect-free.
/// If an expression has a side effect, only side effects are returned.
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn ignore_return_value(&mut self, e: &mut Expr) -> Option<Expr> {
self.optimize_bang_within_logical_ops(e, true);
self.compress_cond_to_logical_ignoring_return_value(e);
self.drop_unused_update(e);
self.drop_unused_op_assign(e);
match e {
Expr::This(_) | Expr::Invalid(_) | Expr::Lit(..) => {
report_change!(
"ignore_return_value: Dropping unused expr: {}",
dump(&*e, false)
);
// We don't need to run this again
// self.changed = true;
return None;
}
Expr::Tpl(t) if t.exprs.is_empty() => {
report_change!("ignore_return_value: Dropping tpl expr without expr");
self.changed = true;
return None;
}
// Function expression cannot have a side effect.
Expr::Fn(_) => {
report_change!(
"ignore_return_value: Dropping unused fn expr as it does not have any side \
effect"
);
self.changed = true;
return None;
}
Expr::Class(cls) => {
let exprs: Vec<Box<Expr>> =
extract_class_side_effect(&self.expr_ctx, *cls.class.take())
.into_iter()
.filter_map(|mut e| self.ignore_return_value(&mut e))
.map(Box::new)
.collect();
if exprs.is_empty() {
return None;
}
return Some(Expr::Seq(SeqExpr {
span: cls.class.span,
exprs,
}));
}
Expr::Paren(e) => return self.ignore_return_value(&mut e.expr),
Expr::Bin(BinExpr {
op, left, right, ..
}) if op.may_short_circuit() => {
let ctx = Ctx {
dont_use_negated_iife: self.ctx.dont_use_negated_iife
|| self.options.side_effects,
..self.ctx
};
let new_r = self.with_ctx(ctx).ignore_return_value(right);
match new_r {
Some(r) => {
*right = Box::new(r);
}
None => return self.ignore_return_value(left),
}
return Some(e.take());
}
Expr::Unary(UnaryExpr {
op: op!("delete"), ..
}) => return Some(e.take()),
Expr::Unary(UnaryExpr {
op: op!("void"), ..
}) if !self.options.unused => return Some(e.take()),
// We optimize binary expressions if operation is side-effect-free and lhs and rhs is
// evaluated regardless of value of lhs.
Expr::Bin(
bin @ BinExpr {
op:
op!(bin, "+")
| op!(bin, "-")
| op!("*")
| op!("%")
| op!("**")
| op!("^")
| op!("&")
| op!("|")
| op!(">>")
| op!("<<")
| op!(">>>")
| op!("===")
| op!("!==")
| op!("==")
| op!("!=")
| op!("<")
| op!("<=")
| op!(">")
| op!(">="),
..
},
) => {
let left = self.ignore_return_value(&mut bin.left);
let right = self.ignore_return_value(&mut bin.right);
let span = bin.span;
if left.is_none() && right.is_none() {
return None;
} else if right.is_none() {
return left;
} else if left.is_none() {
return right;
}
self.changed = true;
report_change!("ignore_return_value: Compressing binary as seq");
return Some(Expr::Seq(SeqExpr {
span,
exprs: vec![Box::new(left.unwrap()), Box::new(right.unwrap())],
}));
}
// Pure calls can be removed
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) if match &**callee {
Expr::Fn(f) => f
.function
.body
.as_ref()
.map(|body| body.stmts.is_empty())
.unwrap_or(false),
Expr::Arrow(f) => match &f.body {
BlockStmtOrExpr::BlockStmt(body) => body.stmts.is_empty(),
BlockStmtOrExpr::Expr(_) => false,
},
_ => false,
} && args.is_empty() =>
{
report_change!("ignore_return_value: Dropping a pure call");
self.changed = true;
return None;
}
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) => {
if let Expr::Fn(FnExpr {
ident: None,
function,
}) = &mut **callee
{
if args.is_empty() {
for param in &mut function.params {
self.drop_unused_param(&mut param.pat, true);
}
function.params.retain(|p| !p.pat.is_invalid());
}
}
if args.is_empty() {
if let Expr::Fn(f) = &mut **callee {
if f.function.body.is_empty() {
return None;
}
}
}
if let Expr::Ident(callee) = &**callee {
if self.options.reduce_vars && self.options.side_effects {
if let Some(usage) = self.data.vars.get(&callee.to_id()) {
if !usage.reassigned() && usage.pure_fn {
self.changed = true;
report_change!("Reducing function call to a variable");
if args.iter().any(|arg| arg.spread.is_some()) {
let elems = args
.take()
.into_iter()
.filter_map(|mut arg| {
if arg.spread.is_some() {
return Some(arg);
}
self.ignore_return_value(&mut arg.expr)
.map(Box::new)
.map(|expr| ExprOrSpread { expr, spread: None })
})
.map(Some)
.collect::<Vec<_>>();
if elems.is_empty() {
return None;
}
return Some(Expr::Array(ArrayLit {
span: callee.span,
elems,
}));
}
let args = args
.take()
.into_iter()
.filter_map(|mut arg| self.ignore_return_value(&mut arg.expr))
.map(Box::new)
.collect::<Vec<_>>();
if args.is_empty() {
return None;
}
return Some(Expr::Seq(SeqExpr {
span: callee.span,
exprs: args,
}));
}
}
}
}
return Some(e.take());
}
Expr::Assign(AssignExpr {
op, left, right, ..
}) if left.is_expr() && !op.may_short_circuit() => {
if let PatOrExpr::Expr(expr) = left {
if let Expr::Member(m) = &**expr {
if !expr.may_have_side_effects(&self.expr_ctx)
&& (m.obj.is_object()
|| m.obj.is_fn_expr()
|| m.obj.is_arrow()
|| m.obj.is_class())
{
if self.should_preserve_property_access(
&m.obj,
PropertyAccessOpts {
allow_getter: true,
only_ident: false,
},
) {
return Some(e.take());
} else {
report_change!(
"ignore_return_value: Dropping unused assign target: {}",
dump(&*expr, false)
);
return Some(*right.take());
}
}
}
}
return Some(e.take());
}
Expr::Assign(AssignExpr {
op: op!("="),
left: PatOrExpr::Pat(pat),
right,
..
}) => {
if let Pat::Ident(i) = &mut **pat {
let old = i.id.to_id();
self.store_var_for_inlining(&mut i.id, right, false, true);
if i.is_dummy() && self.options.unused {
report_change!("inline: Removed variable ({}{:?})", old.0, old.1);
self.vars.removed.insert(old);
}
if right.is_invalid() {
return None;
}
}
}
// We drop `f.g` in
//
// function f() {
// return f.g, 1
// }
Expr::Member(MemberExpr { obj, prop, .. })
if !prop.is_computed()
&& (self.options.top_level() || !self.ctx.in_top_level()) =>
{
if self.should_preserve_property_access(
obj,
PropertyAccessOpts {
allow_getter: true,
only_ident: true,
},
) {
return Some(e.take());
} else {
return None;
}
}
// TODO: Check if it is a pure property access.
Expr::Member(_) => return Some(e.take()),
Expr::MetaProp(_)
| Expr::Await(_)
| Expr::New(..)
| Expr::Call(..)
| Expr::Yield(_)
| Expr::Assign(_)
| Expr::PrivateName(_)
| Expr::Update(_) => return Some(e.take()),
// Not supported. (At least at the moment)
Expr::JSXMember(_)
| Expr::JSXNamespacedName(_)
| Expr::JSXEmpty(_)
| Expr::JSXElement(_)
| Expr::JSXFragment(_)
| Expr::TsTypeAssertion(_)
| Expr::TsConstAssertion(_)
| Expr::TsNonNull(_)
| Expr::TsAs(_) => return Some(e.take()),
Expr::Array(arr) => {
if arr.elems.iter().any(|e| match e {
Some(ExprOrSpread {
spread: Some(..), ..
}) => true,
_ => false,
}) {
return Some(Expr::Array(ArrayLit {
elems: arr
.elems
.take()
.into_iter()
.flatten()
.filter_map(|mut e| {
if e.spread.is_some() {
return Some(e);
}
self.ignore_return_value(&mut e.expr)
.map(Box::new)
.map(|expr| ExprOrSpread { expr, spread: None })
})
.map(Some)
.collect(),
..*arr
}));
}
let mut exprs = vec![];
self.changed = true;
report_change!("ignore_return_value: Inverting an array literal");
exprs.extend(
arr.elems
.take()
.into_iter()
.flatten()
.map(|e| e.expr)
.filter_map(|mut e| self.ignore_return_value(&mut e))
.map(Box::new),
);
if exprs.is_empty() {
return None;
}
return Some(Expr::Seq(SeqExpr {
span: arr.span,
exprs,
}));
}
Expr::Object(obj) => {
let mut exprs = vec![];
self.changed = true;
report_change!("ignore_return_value: Inverting an object literal");
for prop in obj.props.take() {