/
mod.rs
1944 lines (1604 loc) · 55.4 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 rustc_hash::FxHashSet;
use swc_atoms::{js_word, JsWord};
use swc_common::{
collections::{AHashMap, AHashSet},
Mark, Span, SyntaxContext,
};
use swc_ecma_ast::*;
use swc_ecma_utils::{find_pat_ids, IsDirective};
use swc_ecma_visit::{
as_folder, noop_visit_mut_type, visit_mut_obj_and_computed, Fold, VisitMut, VisitMutWith,
};
use tracing::{debug, span, Level};
use crate::scope::{DeclKind, IdentType, ScopeKind};
#[cfg(test)]
mod tests;
const LOG: bool = false && cfg!(debug_assertions);
/// See [Ident] for know how does swc manages identifiers.
///
/// # When to run
///
/// The resolver expects 'clean' ast. You can get clean ast by parsing, or by
/// removing all syntax context in ast nodes.
///
/// # What does it do
///
/// Firstly all scopes (fn, block) has it's own SyntaxContext.
/// Resolver visits all identifiers in module, and look for binding identifies
/// in the scope. Those identifiers now have the SyntaxContext of scope (fn,
/// block). While doing so, resolver tries to resolve normal identifiers (no
/// hygiene info) as a reference to identifier of scope. If the resolver find
/// suitable variable, the identifier reference will have same context as the
/// variable.
///
///
/// # Panics
///
/// `top_level_mark` should not be root.
///
/// # Example
///
/// ```js
/// let a = 1;
/// {
/// let a = 2;
/// use(a);
/// }
/// use(a)
/// ```
///
/// resolver does
///
/// 1. Define `a` with top level context.
///
/// 2. Found a block, so visit block with a new syntax context.
///
/// 3. Defined `a` with syntax context of the block statement.
////
/// 4. Found usage of `a`, and determines that it's reference to `a` in the
/// block. So the reference to `a` will have same syntax context as `a` in the
/// block.
///
/// 5. Found usage of `a` (last line), and determines that it's a
/// reference to top-level `a`, and change syntax context of `a` on last line to
/// top-level syntax context.
///
///
/// # Parameters
///
/// ## `unresolved_mark`
///
/// [Mark] applied to unresolved references.
///
/// A pass should accept this [Mark] if it's going to generate a refernce to
/// globals like `require`.
///
/// e.g. `common_js` pass generates calls to `require`, and this should not
/// be shadowed by a declaration named `require` in the same file.
/// So it uses this value.
///
/// ## `top_level_mark`
///
/// [Mark] applied to top-level bindings.
///
/// **NOTE**: This is **not** globals. This is for top level items declared by
/// users.
///
/// A pass should accept this [Mark] if it requires user-defined top-level
/// items.
///
/// e.g. `jsx` pass requires to call `React` imported by the user.
///
/// ```js
/// import React from 'react';
/// ```
///
/// In the code above, `React` has this [Mark]. `jsx` passes need to
/// reference this [Mark], so it accpets this.
///
/// This [Mark] should be used for referencing top-level bindings written by
/// user. If you are going to create a binding, use `private_ident`
/// instead.
///
/// In other words, **this [Mark] should not be used for determining if a
/// variable is top-level.** This is simply a configuration of the `resolver`
/// pass.
///
///
/// ## `typescript`
///
/// Enable this only if you are going to strip types or apply type-aware
/// passes like decorators pass.
///
///
/// # FAQ
///
/// ## Does a pair `(JsWord, SyntaxContext)` always uniquely identifiers a
/// variable binding?
///
/// Yes, but multiple variables can have the exactly same name.
///
/// In the code below,
///
/// ```js
/// var a = 1, a = 2;
/// ```
///
/// both of them have the same name, so the `(JsWord, SyntaxContext)` pair will
/// be also identical.
pub fn resolver(
unresolved_mark: Mark,
top_level_mark: Mark,
typescript: bool,
) -> impl 'static + Fold + VisitMut {
assert_ne!(
unresolved_mark,
Mark::root(),
"Marker provided to resolver should not be the root mark"
);
let _ = SyntaxContext::empty().apply_mark(unresolved_mark);
let _ = SyntaxContext::empty().apply_mark(top_level_mark);
as_folder(Resolver {
current: Scope::new(ScopeKind::Fn, top_level_mark, None),
ident_type: IdentType::Ref,
in_type: false,
in_ts_module: false,
decl_kind: DeclKind::Lexical,
strict_mode: false,
config: InnerConfig {
handle_types: typescript,
unresolved_mark,
top_level_mark,
},
})
}
#[derive(Debug, Clone)]
struct Scope<'a> {
/// Parent scope of the scope
parent: Option<&'a Scope<'a>>,
/// Kind of the scope.
kind: ScopeKind,
/// [Mark] of the current scope.
mark: Mark,
/// All declarations in the scope
declared_symbols: AHashMap<JsWord, DeclKind>,
/// All types declared in the scope
declared_types: AHashSet<JsWord>,
}
impl<'a> Scope<'a> {
pub fn new(kind: ScopeKind, mark: Mark, parent: Option<&'a Scope<'a>>) -> Self {
Scope {
parent,
kind,
mark,
declared_symbols: Default::default(),
declared_types: Default::default(),
}
}
fn is_declared(&self, symbol: &JsWord) -> Option<&DeclKind> {
self.declared_symbols
.get(symbol)
.or_else(|| self.parent?.is_declared(symbol))
}
}
/// # Phases
///
/// ## Hoisting phase
///
/// ## Resolving phase
struct Resolver<'a> {
current: Scope<'a>,
ident_type: IdentType,
in_type: bool,
in_ts_module: bool,
decl_kind: DeclKind,
strict_mode: bool,
config: InnerConfig,
}
#[derive(Debug, Clone, Copy)]
struct InnerConfig {
handle_types: bool,
unresolved_mark: Mark,
top_level_mark: Mark,
}
impl<'a> Resolver<'a> {
#[cfg(test)]
fn new(current: Scope<'a>, config: InnerConfig) -> Self {
Resolver {
current,
ident_type: IdentType::Ref,
in_type: false,
in_ts_module: false,
config,
decl_kind: DeclKind::Lexical,
strict_mode: false,
}
}
fn with_child<F>(&self, kind: ScopeKind, op: F)
where
F: for<'aa> FnOnce(&mut Resolver<'aa>),
{
let mut child = Resolver {
current: Scope::new(
kind,
Mark::fresh(self.config.top_level_mark),
Some(&self.current),
),
ident_type: IdentType::Ref,
config: self.config,
in_type: self.in_type,
in_ts_module: self.in_ts_module,
decl_kind: self.decl_kind,
strict_mode: self.strict_mode,
};
op(&mut child);
}
fn visit_mut_stmt_within_child_scope(&mut self, s: &mut Stmt) {
self.with_child(ScopeKind::Block, |child| match s {
Stmt::Block(s) => {
child.mark_block(&mut s.span);
s.visit_mut_children_with(child);
}
_ => s.visit_mut_with(child),
});
}
/// Returns a [Mark] for an identifier reference.
fn mark_for_ref(&self, sym: &JsWord) -> Option<Mark> {
self.mark_for_ref_inner(sym, false)
}
fn mark_for_ref_inner(&self, sym: &JsWord, stop_an_fn_scope: bool) -> Option<Mark> {
// NaN always points the globals
if *sym == js_word!("NaN") {
return Some(self.config.unresolved_mark);
}
if self.config.handle_types && self.in_type {
let mut mark = self.current.mark;
let mut scope = Some(&self.current);
while let Some(cur) = scope {
// if cur.declared_types.contains(sym) ||
// cur.hoisted_symbols.borrow().contains(sym) {
if cur.declared_types.contains(sym) {
if mark == Mark::root() {
break;
}
return Some(mark);
}
if cur.kind == ScopeKind::Fn && stop_an_fn_scope {
return None;
}
if let Some(parent) = &cur.parent {
mark = parent.mark;
}
scope = cur.parent;
}
}
let mut mark = self.current.mark;
let mut scope = Some(&self.current);
while let Some(cur) = scope {
if cur.declared_symbols.contains_key(sym) {
if mark == Mark::root() {
return None;
}
return Some(mark);
}
if cur.kind == ScopeKind::Fn && stop_an_fn_scope {
return None;
}
if let Some(parent) = &cur.parent {
mark = parent.mark;
}
scope = cur.parent;
}
None
}
/// Modifies a binding identifier.
fn modify(&mut self, ident: &mut Ident, kind: DeclKind) {
if cfg!(debug_assertions) && LOG {
debug!(
"Binding (type = {}) {}{:?} {:?}",
self.in_type,
ident.sym,
ident.span.ctxt(),
kind
);
}
if ident.span.ctxt() != SyntaxContext::empty() {
return;
}
if self.in_type {
self.current.declared_types.insert(ident.sym.clone());
let mark = self.current.mark;
ident.span = if mark == Mark::root() {
ident.span
} else {
let span = ident.span.apply_mark(mark);
if cfg!(debug_assertions) && LOG {
debug!("\t-> {:?}", span.ctxt());
}
span
};
return;
}
let mark = self.current.mark;
self.current
.declared_symbols
.insert(ident.sym.clone(), kind);
ident.span = if mark == Mark::root() {
ident.span
} else {
let span = ident.span.apply_mark(mark);
if cfg!(debug_assertions) && LOG {
debug!("\t-> {:?}", span.ctxt());
}
span
};
}
fn mark_block(&mut self, span: &mut Span) {
if span.ctxt() != SyntaxContext::empty() {
return;
}
let mark = self.current.mark;
if mark != Mark::root() {
*span = span.apply_mark(mark)
}
}
fn try_resolving_as_type(&mut self, i: &mut Ident) {
if i.span.ctxt.outer() == self.config.unresolved_mark {
i.span.ctxt = SyntaxContext::empty()
}
self.in_type = true;
i.visit_mut_with(self);
self.in_type = false;
}
}
macro_rules! typed {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
node.visit_mut_children_with(self)
}
}
};
}
macro_rules! typed_ref {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
let in_type = self.in_type;
let ident_type = self.ident_type;
self.in_type = true;
node.visit_mut_children_with(self);
self.ident_type = ident_type;
self.in_type = in_type;
}
}
};
}
macro_rules! typed_ref_init {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
let in_type = self.in_type;
let ident_type = self.ident_type;
self.ident_type = IdentType::Ref;
self.in_type = true;
node.visit_mut_children_with(self);
self.ident_type = ident_type;
self.in_type = in_type;
}
}
};
}
macro_rules! typed_decl {
($name:ident, $T:ty) => {
fn $name(&mut self, node: &mut $T) {
if self.config.handle_types {
let in_type = self.in_type;
self.ident_type = IdentType::Binding;
self.in_type = true;
node.visit_mut_children_with(self);
self.in_type = in_type;
}
}
};
}
macro_rules! noop {
($name:ident, $T:ty) => {
#[inline]
fn $name(&mut self, _: &mut $T) {}
};
}
impl<'a> VisitMut for Resolver<'a> {
noop!(visit_mut_accessibility, Accessibility);
noop!(visit_mut_true_plus_minus, TruePlusMinus);
noop!(visit_mut_ts_keyword_type, TsKeywordType);
noop!(visit_mut_ts_keyword_type_kind, TsKeywordTypeKind);
noop!(visit_mut_ts_type_operator_op, TsTypeOperatorOp);
noop!(visit_mut_ts_enum_member_id, TsEnumMemberId);
noop!(visit_mut_ts_external_module_ref, TsExternalModuleRef);
noop!(visit_mut_ts_module_name, TsModuleName);
noop!(visit_mut_ts_this_type, TsThisType);
typed_ref!(visit_mut_ts_array_type, TsArrayType);
typed_ref!(visit_mut_ts_conditional_type, TsConditionalType);
typed_ref_init!(
visit_mut_ts_type_param_instantiation,
TsTypeParamInstantiation
);
typed_ref!(visit_mut_ts_type_query, TsTypeQuery);
typed_ref!(visit_mut_ts_type_query_expr, TsTypeQueryExpr);
typed_ref!(visit_mut_ts_type_operator, TsTypeOperator);
typed_ref_init!(visit_mut_ts_type, TsType);
typed_ref_init!(visit_mut_ts_type_ann, TsTypeAnn);
typed!(
visit_mut_ts_union_or_intersection_type,
TsUnionOrIntersectionType
);
typed!(visit_mut_ts_fn_or_constructor_type, TsFnOrConstructorType);
typed_ref!(visit_mut_ts_union_type, TsUnionType);
typed_ref!(visit_mut_ts_infer_type, TsInferType);
typed_ref!(visit_mut_ts_import_type, TsImportType);
typed_ref!(visit_mut_ts_tuple_type, TsTupleType);
typed_ref!(visit_mut_ts_intersection_type, TsIntersectionType);
typed_ref!(visit_mut_ts_type_ref, TsTypeRef);
typed_decl!(visit_mut_ts_type_param_decl, TsTypeParamDecl);
typed!(visit_mut_ts_fn_param, TsFnParam);
typed!(visit_mut_ts_indexed_access_type, TsIndexedAccessType);
typed!(visit_mut_ts_index_signature, TsIndexSignature);
typed!(visit_mut_ts_interface_body, TsInterfaceBody);
typed!(visit_mut_ts_parenthesized_type, TsParenthesizedType);
typed!(visit_mut_ts_type_lit, TsTypeLit);
typed!(visit_mut_ts_type_element, TsTypeElement);
typed!(visit_mut_ts_optional_type, TsOptionalType);
typed!(visit_mut_ts_rest_type, TsRestType);
typed!(visit_mut_ts_type_predicate, TsTypePredicate);
typed_ref!(visit_mut_ts_this_type_or_ident, TsThisTypeOrIdent);
visit_mut_obj_and_computed!();
// TODO: How should I handle this?
typed!(visit_mut_ts_namespace_export_decl, TsNamespaceExportDecl);
fn visit_mut_arrow_expr(&mut self, e: &mut ArrowExpr) {
self.with_child(ScopeKind::Fn, |child| {
e.type_params.visit_mut_with(child);
let old = child.ident_type;
child.ident_type = IdentType::Binding;
e.params.visit_mut_with(child);
child.ident_type = old;
match &mut *e.body {
BlockStmtOrExpr::BlockStmt(s) => {
child.mark_block(&mut s.span);
let old_strict_mode = child.strict_mode;
child.strict_mode = s
.stmts
.first()
.map(|stmt| stmt.is_use_strict())
.unwrap_or(false);
// Prevent creating new scope.
s.stmts.visit_mut_with(child);
child.strict_mode = old_strict_mode;
}
BlockStmtOrExpr::Expr(e) => e.visit_mut_with(child),
}
e.return_type.visit_mut_with(child);
});
}
fn visit_mut_assign_pat(&mut self, node: &mut AssignPat) {
// visit the type first so that it doesn't resolve any
// identifiers from the others
node.type_ann.visit_mut_with(self);
node.left.visit_mut_with(self);
node.right.visit_mut_with(self);
}
fn visit_mut_binding_ident(&mut self, i: &mut BindingIdent) {
let ident_type = self.ident_type;
let in_type = self.in_type;
self.ident_type = IdentType::Ref;
i.type_ann.visit_mut_with(self);
self.ident_type = ident_type;
i.id.visit_mut_with(self);
self.in_type = in_type;
self.ident_type = ident_type;
}
fn visit_mut_block_stmt(&mut self, block: &mut BlockStmt) {
self.with_child(ScopeKind::Block, |child| {
child.mark_block(&mut block.span);
block.visit_mut_children_with(child);
})
}
fn visit_mut_break_stmt(&mut self, s: &mut BreakStmt) {
let old = self.ident_type;
self.ident_type = IdentType::Label;
s.label.visit_mut_with(self);
self.ident_type = old;
}
fn visit_mut_catch_clause(&mut self, c: &mut CatchClause) {
// Child folder
self.with_child(ScopeKind::Fn, |child| {
child.ident_type = IdentType::Binding;
c.param.visit_mut_with(child);
child.ident_type = IdentType::Ref;
child.mark_block(&mut c.body.span);
c.body.visit_mut_children_with(child);
});
}
fn visit_mut_class(&mut self, c: &mut Class) {
let old_strict_mode = self.strict_mode;
self.strict_mode = true;
let old = self.ident_type;
self.ident_type = IdentType::Ref;
c.decorators.visit_mut_with(self);
self.ident_type = IdentType::Ref;
c.super_class.visit_mut_with(self);
self.ident_type = IdentType::Binding;
c.type_params.visit_mut_with(self);
self.ident_type = IdentType::Ref;
c.super_type_params.visit_mut_with(self);
self.ident_type = IdentType::Ref;
c.implements.visit_mut_with(self);
self.ident_type = old;
c.body.visit_mut_with(self);
self.strict_mode = old_strict_mode;
}
fn visit_mut_class_decl(&mut self, n: &mut ClassDecl) {
self.modify(&mut n.ident, DeclKind::Lexical);
n.class.decorators.visit_mut_with(self);
// Create a child scope. The class name is only accessible within the class.
self.with_child(ScopeKind::Fn, |child| {
child.ident_type = IdentType::Ref;
n.class.visit_mut_with(child);
});
}
fn visit_mut_class_expr(&mut self, n: &mut ClassExpr) {
// Create a child scope. The class name is only accessible within the class.
self.with_child(ScopeKind::Fn, |child| {
child.ident_type = IdentType::Binding;
n.ident.visit_mut_with(child);
child.ident_type = IdentType::Ref;
n.class.visit_mut_with(child);
});
}
fn visit_mut_class_method(&mut self, m: &mut ClassMethod) {
m.key.visit_mut_with(self);
for p in m.function.params.iter_mut() {
p.decorators.visit_mut_with(self);
}
self.with_child(ScopeKind::Fn, |child| m.function.visit_mut_with(child));
}
fn visit_mut_class_prop(&mut self, p: &mut ClassProp) {
p.decorators.visit_mut_with(self);
if let PropName::Computed(key) = &mut p.key {
let old = self.ident_type;
self.ident_type = IdentType::Binding;
key.expr.visit_mut_with(self);
self.ident_type = old;
}
let old = self.ident_type;
self.ident_type = IdentType::Ref;
p.value.visit_mut_with(self);
self.ident_type = old;
p.type_ann.visit_mut_with(self);
}
fn visit_mut_constructor(&mut self, c: &mut Constructor) {
for p in c.params.iter_mut() {
match p {
ParamOrTsParamProp::TsParamProp(p) => {
p.decorators.visit_mut_with(self);
}
ParamOrTsParamProp::Param(p) => {
p.decorators.visit_mut_with(self);
}
}
}
self.with_child(ScopeKind::Fn, |child| {
let old = child.ident_type;
child.ident_type = IdentType::Binding;
c.params.visit_mut_with(child);
child.ident_type = old;
match &mut c.body {
Some(body) => {
child.mark_block(&mut body.span);
body.visit_mut_children_with(child);
}
None => {}
}
});
}
fn visit_mut_continue_stmt(&mut self, s: &mut ContinueStmt) {
let old = self.ident_type;
self.ident_type = IdentType::Label;
s.label.visit_mut_with(self);
self.ident_type = old;
}
fn visit_mut_export_default_decl(&mut self, e: &mut ExportDefaultDecl) {
// Treat default exported functions and classes as declarations
// even though they are parsed as expressions.
match &mut e.decl {
DefaultDecl::Fn(f) => {
if f.ident.is_some() {
self.with_child(ScopeKind::Fn, |child| {
f.function.visit_mut_with(child);
});
} else {
f.visit_mut_with(self)
}
}
DefaultDecl::Class(c) => {
// Skip class expression visitor to treat as a declaration.
c.class.visit_mut_with(self)
}
_ => e.visit_mut_children_with(self),
}
}
fn visit_mut_export_default_expr(&mut self, node: &mut ExportDefaultExpr) {
node.expr.visit_mut_with(self);
if self.config.handle_types {
if let Expr::Ident(i) = &mut *node.expr {
self.try_resolving_as_type(i);
}
}
}
fn visit_mut_export_named_specifier(&mut self, e: &mut ExportNamedSpecifier) {
e.visit_mut_children_with(self);
if self.config.handle_types {
match &mut e.orig {
ModuleExportName::Ident(orig) => {
self.try_resolving_as_type(orig);
}
ModuleExportName::Str(_) => {}
}
}
}
fn visit_mut_export_specifier(&mut self, s: &mut ExportSpecifier) {
let old = self.ident_type;
self.ident_type = IdentType::Ref;
s.visit_mut_children_with(self);
self.ident_type = old;
}
fn visit_mut_expr(&mut self, expr: &mut Expr) {
let _span = if LOG {
Some(span!(Level::ERROR, "visit_mut_expr").entered())
} else {
None
};
let old = self.ident_type;
self.ident_type = IdentType::Ref;
expr.visit_mut_children_with(self);
self.ident_type = old;
}
fn visit_mut_fn_decl(&mut self, node: &mut FnDecl) {
// We don't fold ident as Hoister handles this.
node.function.decorators.visit_mut_with(self);
self.with_child(ScopeKind::Fn, |child| node.function.visit_mut_with(child));
}
fn visit_mut_fn_expr(&mut self, e: &mut FnExpr) {
e.function.decorators.visit_mut_with(self);
if let Some(ident) = &mut e.ident {
self.with_child(ScopeKind::Fn, |child| {
child.modify(ident, DeclKind::Function);
child.with_child(ScopeKind::Fn, |child| {
e.function.visit_mut_with(child);
});
});
} else {
self.with_child(ScopeKind::Fn, |child| {
e.function.visit_mut_with(child);
});
}
}
fn visit_mut_for_in_stmt(&mut self, n: &mut ForInStmt) {
self.with_child(ScopeKind::Block, |child| {
n.left.visit_mut_with(child);
n.right.visit_mut_with(child);
child.visit_mut_stmt_within_child_scope(&mut n.body);
});
}
fn visit_mut_for_of_stmt(&mut self, n: &mut ForOfStmt) {
self.with_child(ScopeKind::Block, |child| {
n.left.visit_mut_with(child);
n.right.visit_mut_with(child);
child.visit_mut_stmt_within_child_scope(&mut n.body);
});
}
fn visit_mut_for_stmt(&mut self, n: &mut ForStmt) {
self.with_child(ScopeKind::Block, |child| {
child.ident_type = IdentType::Binding;
n.init.visit_mut_with(child);
child.ident_type = IdentType::Ref;
n.test.visit_mut_with(child);
child.ident_type = IdentType::Ref;
n.update.visit_mut_with(child);
child.visit_mut_stmt_within_child_scope(&mut n.body);
});
}
fn visit_mut_function(&mut self, f: &mut Function) {
self.mark_block(&mut f.span);
f.type_params.visit_mut_with(self);
self.ident_type = IdentType::Ref;
f.decorators.visit_mut_with(self);
{
let params = f
.params
.iter()
.filter(|p| !p.pat.is_rest())
.flat_map(find_pat_ids)
.collect::<Vec<Id>>();
for id in params {
self.current.declared_symbols.insert(id.0, DeclKind::Param);
}
}
self.ident_type = IdentType::Binding;
f.params.visit_mut_with(self);
f.return_type.visit_mut_with(self);
self.ident_type = IdentType::Ref;
match &mut f.body {
Some(body) => {
self.mark_block(&mut body.span);
let old_strict_mode = self.strict_mode;
self.strict_mode = body
.stmts
.first()
.map(|stmt| stmt.is_use_strict())
.unwrap_or(false);
// Prevent creating new scope.
body.visit_mut_children_with(self);
self.strict_mode = old_strict_mode;
}
None => {}
}
}
fn visit_mut_getter_prop(&mut self, f: &mut GetterProp) {
let old = self.ident_type;
self.ident_type = IdentType::Ref;
f.key.visit_mut_with(self);
self.ident_type = old;
f.type_ann.visit_mut_with(self);
f.body.visit_mut_with(self);
}
fn visit_mut_ident(&mut self, i: &mut Ident) {
if i.span.ctxt != SyntaxContext::empty() {
return;
}
match self.ident_type {
IdentType::Binding => self.modify(i, self.decl_kind),
IdentType::Ref => {
let Ident { span, sym, .. } = i;
if cfg!(debug_assertions) && LOG {
debug!(
"IdentRef (type = {}) {}{:?}",
self.in_type,
sym,
span.ctxt()
);
}
if span.ctxt() != SyntaxContext::empty() {
return;
}
if let Some(mark) = self.mark_for_ref(sym) {
let span = span.apply_mark(mark);
if cfg!(debug_assertions) && LOG {
debug!("\t -> {:?}", span.ctxt());
}
i.span = span;
} else {
if cfg!(debug_assertions) && LOG {
debug!("\t -> Unresolved");
}
let span = span.apply_mark(self.config.unresolved_mark);
if cfg!(debug_assertions) && LOG {
debug!("\t -> {:?}", span.ctxt());
}
i.span = span;
// Support hoisting
self.modify(i, self.decl_kind)
}
}
// We currently does not touch labels
IdentType::Label => {}
}
}
fn visit_mut_import_decl(&mut self, n: &mut ImportDecl) {
// Always resolve the import declaration identifiers even if it's type only.
// We need to analyze these identifiers for type stripping purposes.
self.ident_type = IdentType::Binding;
let old_in_type = self.in_type;
self.in_type = n.type_only;
n.visit_mut_children_with(self);
self.in_type = old_in_type;
}
fn visit_mut_import_named_specifier(&mut self, s: &mut ImportNamedSpecifier) {
let old = self.ident_type;
self.ident_type = IdentType::Binding;
s.local.visit_mut_with(self);
if self.config.handle_types {
self.current.declared_types.insert(s.local.sym.clone());
}
self.ident_type = old;
}
fn visit_mut_import_specifier(&mut self, s: &mut ImportSpecifier) {
let old = self.ident_type;
self.ident_type = IdentType::Binding;
match s {
ImportSpecifier::Named(ImportNamedSpecifier { imported: None, .. })
| ImportSpecifier::Namespace(..)
| ImportSpecifier::Default(..) => s.visit_mut_children_with(self),
ImportSpecifier::Named(s) => s.local.visit_mut_with(self),
}
self.ident_type = old;
}
/// Ignore.
///
/// See https://github.com/swc-project/swc/issues/2854
fn visit_mut_jsx_attr_name(&mut self, _: &mut JSXAttrName) {}