forked from swc-project/swc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
1484 lines (1276 loc) · 43.7 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::{collections::HashSet, hash::BuildHasherDefault};
use indexmap::IndexSet;
use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
use swc_atoms::{js_word, JsWord};
use swc_common::{
collections::{AHashMap, AHashSet},
SyntaxContext,
};
use swc_ecma_ast::*;
use swc_ecma_utils::{find_pat_ids, ident::IdentLike, IsEmpty, StmtExt};
use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
use swc_timer::timer;
use self::{
ctx::Ctx,
storage::{Storage, *},
};
use crate::{
alias::{collect_infects_from, AliasConfig},
marks::Marks,
util::can_end_conditionally,
};
mod ctx;
pub(crate) mod storage;
#[derive(Debug, Default)]
pub(crate) struct ModuleInfo {
/// Imported identifiers which should be treated as a black box.
///
/// Imports from `@swc/helpers` are excluded as helpers are not modified by
/// accessing/calling other modules.
pub blackbox_imports: AHashSet<Id>,
}
pub(crate) fn analyze<N>(n: &N, _module_info: &ModuleInfo, marks: Option<Marks>) -> ProgramData
where
N: VisitWith<UsageAnalyzer>,
{
analyze_with_storage::<ProgramData, _>(n, marks)
}
/// TODO: Track assignments to variables via `arguments`.
/// TODO: Scope-local. (Including block)
///
/// If `marks` is [None], markers are ignored.
pub(crate) fn analyze_with_storage<S, N>(n: &N, marks: Option<Marks>) -> S
where
S: Storage,
N: VisitWith<UsageAnalyzer<S>>,
{
let _timer = timer!("analyze");
let mut v = UsageAnalyzer {
data: Default::default(),
marks,
scope: Default::default(),
ctx: Default::default(),
used_recursively: AHashMap::default(),
};
n.visit_with(&mut v);
let top_scope = v.scope;
v.data.top_scope().merge(top_scope.clone(), false);
v.data.scope(SyntaxContext::empty()).merge(top_scope, false);
v.data
}
#[derive(Debug, Default, Clone)]
pub(crate) struct VarUsageInfo {
pub inline_prevented: bool,
/// The number of direct reference to this identifier.
pub ref_count: u32,
/// `true` if a variable is conditionally initialized.
pub cond_init: bool,
/// `false` if it's only used.
pub declared: bool,
pub declared_count: u32,
/// `true` if the enclosing function defines this variable as a parameter.
pub declared_as_fn_param: bool,
pub declared_as_fn_expr: bool,
pub assign_count: u32,
pub mutation_by_call_count: u32,
/// The number of direct and indirect reference to this identifier.
/// ## Things to note
///
/// - Update is counted as usage
pub usage_count: u32,
/// The variable itself is modified.
reassigned_with_assignment: bool,
reassigned_with_var_decl: bool,
/// The variable itself or a property of it is modified.
pub mutated: bool,
pub has_property_access: bool,
pub has_property_mutation: bool,
pub exported: bool,
/// True if used **above** the declaration or in init. (Not eval order).
pub used_above_decl: bool,
/// `true` if it's declared by function parameters or variables declared in
/// a closest function and used only within it and not used by child
/// functions.
pub is_fn_local: bool,
pub executed_multiple_time: bool,
pub used_in_cond: bool,
pub var_kind: Option<VarDeclKind>,
pub var_initialized: bool,
pub declared_as_catch_param: bool,
pub no_side_effect_for_member_access: bool,
pub used_as_callee: bool,
pub used_as_arg: bool,
pub indexed_with_dynamic_key: bool,
pub pure_fn: bool,
/// `infects_to`. This should be renamed, but it will be done with another
/// PR. (because it's hard to review)
infects: Vec<Id>,
pub used_in_non_child_fn: bool,
pub accessed_props: Box<AHashMap<JsWord, u32>>,
pub used_recursively: bool,
}
impl VarUsageInfo {
pub fn is_mutated_only_by_one_call(&self) -> bool {
self.assign_count == 0 && self.mutation_by_call_count == 1
}
pub fn is_infected(&self) -> bool {
!self.infects.is_empty()
}
pub fn reassigned(&self) -> bool {
self.reassigned_with_assignment
|| self.reassigned_with_var_decl
|| (u32::from(self.var_initialized)
+ u32::from(self.declared_as_catch_param)
+ u32::from(self.declared_as_fn_param)
+ self.assign_count)
> 1
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ScopeKind {
Fn,
Block,
}
#[derive(Debug, Default, Clone)]
pub(crate) struct ScopeData {
pub has_with_stmt: bool,
pub has_eval_call: bool,
pub used_arguments: bool,
}
#[derive(Debug, Clone)]
enum RecursiveUsage {
FnOrClass,
Var { can_ignore: bool },
}
/// Analyzed info of a whole program we are working on.
#[derive(Debug, Default)]
pub(crate) struct ProgramData {
pub vars: FxHashMap<Id, VarUsageInfo>,
pub top: ScopeData,
pub scopes: FxHashMap<SyntaxContext, ScopeData>,
initialized_vars: IndexSet<Id, ahash::RandomState>,
}
impl ProgramData {
pub(crate) fn expand_infected(
&self,
module_info: &ModuleInfo,
ids: FxHashSet<Id>,
max_num: usize,
) -> Result<FxHashSet<Id>, ()> {
let init =
HashSet::with_capacity_and_hasher(max_num, BuildHasherDefault::<FxHasher>::default());
ids.into_iter().try_fold(init, |mut res, id| {
let mut ids = Vec::with_capacity(max_num);
ids.push(id);
let mut ranges = vec![0..1usize];
loop {
let range = ranges.remove(0);
for index in range {
let iid = ids.get(index).unwrap();
// Abort on imported variables, because we can't analyze them
if module_info.blackbox_imports.contains(iid) {
return Err(());
}
if !res.insert(iid.clone()) {
continue;
}
if res.len() >= max_num {
return Err(());
}
if let Some(info) = self.vars.get(iid) {
let infects = &info.infects;
if !infects.is_empty() {
let old_len = ids.len();
ids.extend_from_slice(infects.as_slice());
let new_len = ids.len();
ranges.push(old_len..new_len);
}
}
}
if ranges.is_empty() {
break;
}
}
Ok(res)
})
}
pub(crate) fn contains_unresolved(&self, e: &Expr) -> bool {
match e {
Expr::Ident(i) => {
if let Some(v) = self.vars.get(&i.to_id()) {
return !v.declared;
}
true
}
Expr::Member(MemberExpr { obj, prop, .. }) => {
if self.contains_unresolved(obj) {
return true;
}
if let MemberProp::Computed(prop) = prop {
if self.contains_unresolved(&prop.expr) {
return true;
}
}
false
}
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) => {
if self.contains_unresolved(callee) {
return true;
}
if args.iter().any(|arg| self.contains_unresolved(&arg.expr)) {
return true;
}
false
}
_ => false,
}
}
}
/// This assumes there are no two variable with same name and same span hygiene.
#[derive(Debug)]
pub(crate) struct UsageAnalyzer<S = ProgramData>
where
S: Storage,
{
data: S,
marks: Option<Marks>,
scope: S::ScopeData,
ctx: Ctx,
used_recursively: AHashMap<Id, RecursiveUsage>,
}
impl<S> UsageAnalyzer<S>
where
S: Storage,
{
fn with_child<F, Ret>(&mut self, child_ctxt: SyntaxContext, kind: ScopeKind, op: F) -> Ret
where
F: FnOnce(&mut UsageAnalyzer<S>) -> Ret,
{
let mut child = UsageAnalyzer {
data: Default::default(),
marks: self.marks,
ctx: self.ctx,
scope: Default::default(),
used_recursively: self.used_recursively.clone(),
};
let ret = op(&mut child);
{
let child_scope = child.data.scope(child_ctxt);
child_scope.merge(child.scope.clone(), false);
}
self.scope.merge(child.scope, true);
self.data.merge(kind, child.data);
ret
}
fn visit_pat_id(&mut self, i: &Ident) {
let Ctx {
in_left_of_for_loop,
in_pat_of_param,
..
} = self.ctx;
if self.ctx.in_pat_of_var_decl || self.ctx.in_pat_of_param || self.ctx.in_catch_param {
let v = self.declare_decl(
i,
self.ctx.in_pat_of_var_decl_with_init,
self.ctx.var_decl_kind_of_pat,
false,
);
if in_pat_of_param {
v.mark_declared_as_fn_param();
}
if in_left_of_for_loop {
v.mark_reassigned_with_assign();
v.mark_mutated();
}
} else {
self.report_usage(i, true);
}
}
fn report_usage(&mut self, i: &Ident, is_assign: bool) {
if i.sym == js_word!("arguments") {
self.scope.mark_used_arguments();
}
if !is_assign {
if let Some(recr) = self.used_recursively.get(&i.to_id()) {
if let RecursiveUsage::Var { can_ignore: false } = recr {
self.data.report_usage(self.ctx, i, is_assign);
self.data.var_or_default(i.to_id()).mark_used_above_decl()
}
self.data.var_or_default(i.to_id()).mark_used_recursively();
return;
}
}
self.data.report_usage(self.ctx, i, is_assign)
}
fn declare_decl(
&mut self,
i: &Ident,
has_init: bool,
kind: Option<VarDeclKind>,
_is_fn_decl: bool,
) -> &mut S::VarData {
self.scope.add_declared_symbol(i);
self.data.declare_decl(self.ctx, i, has_init, kind)
}
fn visit_in_cond<T: VisitWith<Self>>(&mut self, t: &T) {
let cnt = self.data.get_initialized_cnt();
t.visit_with(self);
self.data.truncate_initialized_cnt(cnt)
}
fn visit_children_in_cond<T: VisitWith<Self>>(&mut self, t: &T) {
let cnt = self.data.get_initialized_cnt();
t.visit_children_with(self);
self.data.truncate_initialized_cnt(cnt)
}
}
impl<S> Visit for UsageAnalyzer<S>
where
S: Storage,
{
noop_visit_type!();
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_arrow_expr(&mut self, n: &ArrowExpr) {
self.with_child(n.span.ctxt, ScopeKind::Fn, |child| {
{
let ctx = Ctx {
in_pat_of_param: true,
is_delete_arg: false,
..child.ctx
};
n.params.visit_with(&mut *child.with_ctx(ctx));
}
match &n.body {
BlockStmtOrExpr::BlockStmt(body) => {
body.visit_with(child);
}
BlockStmtOrExpr::Expr(body) => {
body.visit_with(child);
}
}
})
}
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn visit_constructor(&mut self, n: &Constructor) {
self.with_child(n.span.ctxt, ScopeKind::Fn, |child| {
{
let ctx = Ctx {
in_pat_of_param: true,
is_delete_arg: false,
..child.ctx
};
n.params.visit_with(&mut *child.with_ctx(ctx));
}
// Bypass visit_block_stmt
if let Some(body) = &n.body {
body.visit_with(child);
}
})
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_assign_expr(&mut self, n: &AssignExpr) {
let ctx = Ctx {
in_assign_lhs: true,
is_exact_reassignment: true,
is_op_assign: n.op != op!("="),
is_delete_arg: false,
..self.ctx
};
n.left.visit_with(&mut *self.with_ctx(ctx));
let ctx = Ctx {
in_assign_lhs: false,
is_exact_reassignment: false,
is_delete_arg: false,
..self.ctx
};
n.right.visit_with(&mut *self.with_ctx(ctx));
if n.op == op!("=") {
let left = match &n.left {
PatOrExpr::Expr(left) => leftmost(left),
PatOrExpr::Pat(left) => match &**left {
Pat::Ident(p) => Some(p.to_id()),
Pat::Expr(p) => leftmost(p),
_ => None,
},
};
if let Some(left) = left {
for id in collect_infects_from(
&n.right,
AliasConfig {
marks: self.marks,
..Default::default()
},
) {
self.data
.var_or_default(left.clone())
.add_infects_to(id.clone());
}
}
}
}
fn visit_assign_pat(&mut self, p: &AssignPat) {
p.left.visit_with(self);
{
let ctx = Ctx {
in_pat_of_param: false,
is_delete_arg: false,
var_decl_kind_of_pat: None,
..self.ctx
};
p.right.visit_with(&mut *self.with_ctx(ctx))
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_await_expr(&mut self, n: &AwaitExpr) {
let ctx = Ctx {
in_await_arg: true,
is_delete_arg: false,
..self.ctx
};
n.visit_children_with(&mut *self.with_ctx(ctx));
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_block_stmt(&mut self, n: &BlockStmt) {
self.with_child(n.span.ctxt, ScopeKind::Block, |child| {
n.visit_children_with(child);
})
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_call_expr(&mut self, n: &CallExpr) {
let inline_prevented = self.ctx.inline_prevented
|| self
.marks
.map(|marks| n.span.has_mark(marks.noinline))
.unwrap_or_default();
{
let ctx = Ctx {
inline_prevented,
is_callee: true,
..self.ctx
};
n.callee.visit_with(&mut *self.with_ctx(ctx));
}
if let Callee::Expr(callee) = &n.callee {
if let Expr::Ident(callee) = &**callee {
self.data
.var_or_default(callee.to_id())
.mark_used_as_callee();
}
match &**callee {
Expr::Fn(callee) => {
for (idx, p) in callee.function.params.iter().enumerate() {
if let Some(arg) = n.args.get(idx) {
if arg.spread.is_some() {
break;
}
if is_safe_to_access_prop(&arg.expr) {
if let Pat::Ident(id) = &p.pat {
self.data
.var_or_default(id.to_id())
.mark_initialized_with_safe_value();
}
}
}
}
}
Expr::Arrow(callee) => {
for (idx, p) in callee.params.iter().enumerate() {
if let Some(arg) = n.args.get(idx) {
if arg.spread.is_some() {
break;
}
if is_safe_to_access_prop(&arg.expr) {
if let Pat::Ident(id) = &p {
self.data
.var_or_default(id.to_id())
.mark_initialized_with_safe_value();
}
}
}
}
}
_ => {}
}
}
{
let ctx = Ctx {
inline_prevented,
in_call_arg: true,
is_delete_arg: false,
is_exact_arg: true,
is_exact_reassignment: false,
is_callee: false,
..self.ctx
};
n.args.visit_with(&mut *self.with_ctx(ctx));
}
for arg in &n.args {
if let Expr::Ident(arg) = &*arg.expr {
self.data.var_or_default(arg.to_id()).mark_used_as_arg();
}
}
if let Callee::Expr(callee) = &n.callee {
match &**callee {
Expr::Ident(Ident { sym, .. }) if *sym == *"eval" => {
self.scope.mark_eval_called();
}
_ => {}
}
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_catch_clause(&mut self, n: &CatchClause) {
{
let ctx = Ctx {
in_cond: true,
is_delete_arg: false,
in_catch_param: true,
..self.ctx
};
n.param.visit_with(&mut *self.with_ctx(ctx));
}
{
let ctx = Ctx {
in_cond: true,
is_delete_arg: false,
..self.ctx
};
self.with_ctx(ctx).visit_in_cond(&n.body);
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_class(&mut self, n: &Class) {
n.decorators.visit_with(self);
{
let ctx = Ctx {
inline_prevented: true,
is_delete_arg: false,
..self.ctx
};
n.super_class.visit_with(&mut *self.with_ctx(ctx));
}
self.with_child(n.span.ctxt, ScopeKind::Fn, |child| n.body.visit_with(child))
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_class_decl(&mut self, n: &ClassDecl) {
self.declare_decl(&n.ident, true, None, false);
n.visit_children_with(self);
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_class_expr(&mut self, n: &ClassExpr) {
n.visit_children_with(self);
if let Some(id) = &n.ident {
self.declare_decl(id, true, None, false);
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_cond_expr(&mut self, n: &CondExpr) {
n.test.visit_with(self);
{
let ctx = Ctx {
in_cond: true,
..self.ctx
};
self.with_ctx(ctx).visit_in_cond(&n.cons);
self.with_ctx(ctx).visit_in_cond(&n.alt);
}
}
fn visit_default_decl(&mut self, d: &DefaultDecl) {
d.visit_children_with(self);
match d {
DefaultDecl::Class(c) => {
if let Some(i) = &c.ident {
self.data.var_or_default(i.to_id()).prevent_inline();
}
}
DefaultDecl::Fn(f) => {
if let Some(i) = &f.ident {
self.data.var_or_default(i.to_id()).prevent_inline();
}
}
_ => {}
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_do_while_stmt(&mut self, n: &DoWhileStmt) {
n.body.visit_with(&mut *self.with_ctx(Ctx {
is_delete_arg: false,
executed_multiple_time: true,
..self.ctx
}));
n.test.visit_with(&mut *self.with_ctx(Ctx {
is_delete_arg: false,
executed_multiple_time: true,
..self.ctx
}));
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_export_decl(&mut self, n: &ExportDecl) {
n.visit_children_with(self);
match &n.decl {
Decl::Class(c) => {
self.data.var_or_default(c.ident.to_id()).prevent_inline();
}
Decl::Fn(f) => {
self.data.var_or_default(f.ident.to_id()).prevent_inline();
}
Decl::Var(v) => {
let ids = find_pat_ids(v);
for id in ids {
self.data.var_or_default(id).prevent_inline();
}
}
_ => {}
}
}
fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) {
match &n.orig {
ModuleExportName::Ident(orig) => {
self.report_usage(orig, false);
self.data.var_or_default(orig.to_id()).prevent_inline();
}
ModuleExportName::Str(..) => {}
};
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, e)))]
fn visit_expr(&mut self, e: &Expr) {
let ctx = Ctx {
in_pat_of_var_decl: false,
in_pat_of_param: false,
in_catch_param: false,
var_decl_kind_of_pat: None,
in_pat_of_var_decl_with_init: false,
..self.ctx
};
e.visit_children_with(&mut *self.with_ctx(ctx));
if let Expr::Ident(i) = e {
#[cfg(feature = "debug")]
{
// debug!(
// "Usage: `{}``; update = {:?}, assign_lhs = {:?} ",
// i,
// self.ctx.in_update_arg,
// self.ctx.in_assign_lhs
// );
}
if self.ctx.in_update_arg {
self.with_ctx(ctx).report_usage(i, true);
self.with_ctx(ctx).report_usage(i, false);
} else {
let is_assign = self.ctx.in_update_arg || self.ctx.in_assign_lhs;
self.with_ctx(ctx).report_usage(i, is_assign);
}
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn visit_expr_or_spread(&mut self, e: &ExprOrSpread) {
e.visit_children_with(self);
if e.spread.is_some() {
if let Expr::Ident(i) = &*e.expr {
self.data
.var_or_default(i.to_id())
.mark_indexed_with_dynamic_key();
}
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn visit_spread_element(&mut self, e: &SpreadElement) {
e.visit_children_with(self);
if let Expr::Ident(i) = &*e.expr {
self.data
.var_or_default(i.to_id())
.mark_indexed_with_dynamic_key();
}
}
fn visit_bin_expr(&mut self, e: &BinExpr) {
if e.op.may_short_circuit() {
e.left.visit_with(self);
let ctx = Ctx {
in_cond: true,
is_delete_arg: false,
..self.ctx
};
self.with_ctx(ctx).visit_in_cond(&e.right);
} else {
if e.op == op!("in") {
if let Expr::Ident(obj) = &*e.right {
let var = self.data.var_or_default(obj.to_id());
match &*e.left {
Expr::Lit(Lit::Str(prop)) => {
var.add_accessed_property(prop.value.clone());
}
_ => {
var.mark_indexed_with_dynamic_key();
}
}
}
}
e.visit_children_with(self);
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_fn_decl(&mut self, n: &FnDecl) {
let ctx = Ctx {
in_decl_with_no_side_effect_for_member_access: true,
is_delete_arg: false,
..self.ctx
};
self.with_ctx(ctx).declare_decl(&n.ident, true, None, true);
if n.function.body.is_empty() {
self.data.var_or_default(n.ident.to_id()).mark_as_pure_fn();
}
let id = n.ident.to_id();
self.used_recursively
.insert(id.clone(), RecursiveUsage::FnOrClass);
n.visit_children_with(self);
self.used_recursively.remove(&id);
{
for id in collect_infects_from(
&n.function,
AliasConfig {
marks: self.marks,
..Default::default()
},
) {
self.data
.var_or_default(n.ident.to_id())
.add_infects_to(id.clone());
}
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_fn_expr(&mut self, n: &FnExpr) {
if let Some(n_id) = &n.ident {
self.data
.var_or_default(n_id.to_id())
.mark_declared_as_fn_expr();
self.used_recursively
.insert(n_id.to_id(), RecursiveUsage::FnOrClass);
n.visit_children_with(self);
{
for id in collect_infects_from(
&n.function,
AliasConfig {
marks: self.marks,
..Default::default()
},
) {
self.data
.var_or_default(n_id.to_id())
.add_infects_to(id.to_id());
}
}
self.used_recursively.remove(&n_id.to_id());
} else {
n.visit_children_with(self);
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_for_in_stmt(&mut self, n: &ForInStmt) {
n.right.visit_with(self);
self.with_child(n.span.ctxt, ScopeKind::Block, |child| {
let ctx = Ctx {
is_exact_reassignment: true,
is_delete_arg: false,
in_left_of_for_loop: true,
..child.ctx
};
n.left.visit_with(&mut *child.with_ctx(ctx));
n.right.visit_with(child);
let ctx = Ctx {
is_delete_arg: false,
executed_multiple_time: true,
in_cond: true,
..child.ctx
};
child.with_ctx(ctx).visit_in_cond(&n.body);
});
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_for_of_stmt(&mut self, n: &ForOfStmt) {
n.right.visit_with(self);
self.with_child(n.span.ctxt, ScopeKind::Block, |child| {
let ctx = Ctx {
in_left_of_for_loop: true,
is_exact_reassignment: true,
is_delete_arg: false,
..child.ctx
};
n.left.visit_with(&mut *child.with_ctx(ctx));
let ctx = Ctx {
executed_multiple_time: true,
in_cond: true,
is_delete_arg: false,
..child.ctx
};
child.with_ctx(ctx).visit_in_cond(&n.body);
});
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_for_stmt(&mut self, n: &ForStmt) {
n.init.visit_with(self);
let ctx = Ctx {
executed_multiple_time: true,
in_cond: true,
is_delete_arg: false,
..self.ctx
};
self.with_ctx(ctx).visit_in_cond(&n.test);
self.with_ctx(ctx).visit_in_cond(&n.update);
self.with_ctx(ctx).visit_in_cond(&n.body);
}
#[cfg_attr(feature = "debug", tracing::instrument(skip(self, n)))]
fn visit_function(&mut self, n: &Function) {
n.decorators.visit_with(self);
let is_standalone = self
.marks
.map(|marks| n.span.has_mark(marks.standalone))
.unwrap_or_default();
// We don't dig into standalone function, as it does not share any variable with
// outer scope.
if self.ctx.skip_standalone && is_standalone {
return;
}
let ctx = Ctx {
skip_standalone: self.ctx.skip_standalone || is_standalone,
in_update_arg: false,
..self.ctx
};
self.with_ctx(ctx)
.with_child(n.span.ctxt, ScopeKind::Fn, |child| {
n.params.visit_with(child);
match &n.body {
Some(body) => {
// We use visit_children_with instead of visit_with to bypass block scope
// handler.
body.visit_children_with(child);
}
None => {}
}