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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
use crate::scope::{IdentType, ScopeKind};
use std::{cell::RefCell, collections::HashSet};
use swc_atoms::JsWord;
use swc_common::{Mark, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith};

#[cfg(test)]
mod tests;

const LOG: bool = false;

/// See [resolver_with_mark] for docs.
pub fn resolver() -> impl 'static + Fold {
    resolver_with_mark(Mark::fresh(Mark::root()))
}

/// # 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.
pub fn resolver_with_mark(top_level_mark: Mark) -> impl 'static + Fold {
    assert_ne!(
        top_level_mark,
        Mark::root(),
        "Marker provided to resolver should not be the root mark"
    );
    as_folder(Resolver::new(
        top_level_mark,
        Scope::new(ScopeKind::Fn, None),
        None,
        false,
    ))
}

/// [resolver_with_mark] with typescript support enabled.
pub fn ts_resolver(top_level_mark: Mark) -> impl 'static + Fold {
    assert_ne!(
        top_level_mark,
        Mark::root(),
        "Marker provided to resolver should not be the root mark"
    );
    as_folder(Resolver::new(
        top_level_mark,
        Scope::new(ScopeKind::Fn, None),
        None,
        true,
    ))
}

#[derive(Debug, Clone)]
struct Scope<'a> {
    /// Parent scope of the scope
    parent: Option<&'a Scope<'a>>,

    /// Kind of the scope.
    kind: ScopeKind,

    /// All declarations in the scope
    declared_symbols: HashSet<JsWord>,
    hoisted_symbols: RefCell<HashSet<JsWord>>,

    /// All types declared in the scope
    declared_types: HashSet<JsWord>,
}

impl<'a> Default for Scope<'a> {
    fn default() -> Self {
        Scope::new(ScopeKind::Fn, None)
    }
}

impl<'a> Scope<'a> {
    pub fn new(kind: ScopeKind, parent: Option<&'a Scope<'a>>) -> Self {
        Scope {
            parent,
            kind,
            declared_symbols: Default::default(),
            hoisted_symbols: Default::default(),
            declared_types: Default::default(),
        }
    }
}

/// # Phases
///
/// ## Hoisting phase
///
/// ## Resolving phase
struct Resolver<'a> {
    hoist: bool,
    mark: Mark,
    current: Scope<'a>,
    cur_defining: Option<(JsWord, Mark)>,
    ident_type: IdentType,
    handle_types: bool,
    in_type: bool,
}

impl<'a> Resolver<'a> {
    fn new(
        mark: Mark,
        current: Scope<'a>,
        cur_defining: Option<(JsWord, Mark)>,
        handle_types: bool,
    ) -> Self {
        Resolver {
            hoist: false,
            mark,
            current,
            cur_defining,
            ident_type: IdentType::Ref,
            handle_types,
            in_type: false,
        }
    }

    fn visit_mut_stmt_within_same_scope(&mut self, s: &mut Stmt) {
        match s {
            Stmt::Block(s) => {
                s.visit_mut_children_with(self);
            }
            _ => s.visit_mut_with(self),
        }
    }

    /// Returns a [Mark] for an identifier reference.
    fn mark_for_ref(&self, sym: &JsWord) -> Option<Mark> {
        if self.handle_types && self.in_type {
            let mut mark = self.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);
                }
                mark = mark.parent();
                scope = cur.parent;
            }
        }

        let mut mark = self.mark;
        let mut scope = Some(&self.current);

        while let Some(cur) = scope {
            if cur.declared_symbols.contains(sym) || cur.hoisted_symbols.borrow().contains(sym) {
                if mark == Mark::root() {
                    return None;
                }
                return Some(mark);
            }
            mark = mark.parent();
            scope = cur.parent;
        }

        if let Some((ref c, mark)) = self.cur_defining {
            if *c == *sym {
                return Some(mark);
            }
        }

        None
    }

    fn visit_mut_binding_ident(&mut self, ident: &mut Ident, kind: Option<VarDeclKind>) {
        if cfg!(debug_assertions) && LOG {
            eprintln!(
                "resolver: Binding {}{:?} {:?}",
                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.mark;

            ident.span = if mark == Mark::root() {
                ident.span
            } else {
                let span = ident.span.apply_mark(mark);
                if cfg!(debug_assertions) && LOG {
                    eprintln!("\t-> {:?}", span.ctxt());
                }
                span
            };
            return;
        }

        if self.hoist {
            // If there's no binding with same name, it means the code depends on hoisting
            //
            //   e.g.
            //
            //      function test() {
            //          if (typeof Missing == typeof EXTENDS) {
            //              console.log("missing")
            //          }
            //          var EXTENDS = "test";
            //      }
            let val = (|| {
                let mut cursor = Some(&self.current);
                let mut mark = self.mark;

                while let Some(c) = cursor {
                    if c.declared_symbols.contains(&ident.sym)
                        || c.hoisted_symbols.borrow().contains(&ident.sym)
                    {
                        c.hoisted_symbols.borrow_mut().insert(ident.sym.clone());
                        return None;
                    }
                    cursor = c.parent;
                    let m = mark.parent();
                    if m == Mark::root() {
                        return Some(mark);
                    }
                    mark = m;
                }

                None
            })();
            if let Some(mark) = val {
                ident.span = ident.span.apply_mark(mark);
                return;
            }
        }

        let (should_insert, mark) = match kind {
            None | Some(VarDeclKind::Var) => {
                if let Some((ref cur, override_mark)) = self.cur_defining {
                    if *cur != ident.sym {
                        (true, self.mark)
                    } else {
                        (false, override_mark)
                    }
                } else {
                    (true, self.mark)
                }
            }
            _ => (true, self.mark),
        };

        let mut mark = mark;

        if should_insert {
            if self.hoist {
                let mut cursor = Some(&self.current);

                match kind {
                    Some(VarDeclKind::Var) | None => {
                        while let Some(c) = cursor {
                            if c.kind == ScopeKind::Fn {
                                c.hoisted_symbols.borrow_mut().insert(ident.sym.clone());
                                break;
                            }
                            cursor = c.parent;
                            mark = mark.parent();
                        }
                    }
                    Some(VarDeclKind::Let) | Some(VarDeclKind::Const) => {
                        self.current
                            .hoisted_symbols
                            .borrow_mut()
                            .insert(ident.sym.clone());
                    }
                }
            } else {
                self.current.declared_symbols.insert(ident.sym.clone());
            }
        }

        ident.span = if mark == Mark::root() {
            ident.span
        } else {
            let span = ident.span.apply_mark(mark);
            if cfg!(debug_assertions) && LOG {
                eprintln!("\t-> {:?}", span.ctxt());
            }
            span
        };
    }
}

macro_rules! typed {
    ($name:ident, $T:ty) => {
        fn $name(&mut self, node: &mut $T) {
            if self.handle_types {
                self.in_type = true;
                node.visit_mut_children_with(self)
            }
        }
    };
}

macro_rules! typed_ref {
    ($name:ident, $T:ty) => {
        fn $name(&mut self, node: &mut $T) {
            if self.handle_types {
                self.ident_type = IdentType::Ref;
                self.in_type = true;
                node.visit_mut_children_with(self)
            }
        }
    };
}

macro_rules! typed_decl {
    ($name:ident, $T:ty) => {
        fn $name(&mut self, node: &mut $T) {
            if self.handle_types {
                self.ident_type = IdentType::Binding;
                self.in_type = true;
                node.visit_mut_children_with(self)
            }
        }
    };
}

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!(visit_mut_ts_entity_name, TsEntityName);
    typed_ref!(
        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!(visit_mut_ts_type, TsType);
    typed_ref!(visit_mut_ts_type_ann, TsTypeAnn);
    typed_ref!(visit_mut_ts_type_assertion, TsTypeAssertion);
    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_mapped_type, TsMappedType);
    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_enum_member, TsEnumMember);
    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_module_ref, TsModuleRef);
    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_signature_decl, TsSignatureDecl);
    typed!(visit_mut_ts_module_block, TsModuleBlock);
    typed!(visit_mut_ts_namespace_body, TsNamespaceBody);
    typed!(visit_mut_ts_optional_type, TsOptionalType);
    typed!(visit_mut_ts_param_prop, TsParamProp);
    typed!(visit_mut_ts_rest_type, TsRestType);
    typed!(visit_mut_ts_type_predicate, TsTypePredicate);
    typed_ref!(visit_mut_ts_this_type_or_ident, TsThisTypeOrIdent);

    fn visit_mut_ts_tuple_element(&mut self, e: &mut TsTupleElement) {
        if !self.handle_types {
            return;
        }
        self.ident_type = IdentType::Ref;
        e.ty.visit_mut_with(self);
    }

    fn visit_mut_ts_type_params(&mut self, params: &mut Vec<TsTypeParam>) {
        for param in params.iter_mut() {
            self.in_type = true;
            param.name.visit_mut_with(self);
        }

        params.visit_mut_children_with(self);
    }

    fn visit_mut_ts_type_param(&mut self, param: &mut TsTypeParam) {
        if !self.handle_types {
            return;
        }
        self.in_type = true;
        param.name.visit_mut_with(self);

        let ident_type = self.ident_type;
        param.default.visit_mut_with(self);
        param.constraint.visit_mut_with(self);
        self.ident_type = ident_type;
    }

    fn visit_mut_ts_construct_signature_decl(&mut self, decl: &mut TsConstructSignatureDecl) {
        if !self.handle_types {
            return;
        }
        self.in_type = true;
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        // order is important
        decl.type_params.visit_mut_with(&mut child);
        decl.params.visit_mut_with(&mut child);
        decl.type_ann.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_constructor_type(&mut self, ty: &mut TsConstructorType) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        ty.type_params.visit_mut_with(&mut child);
        ty.params.visit_mut_with(&mut child);
        ty.type_ann.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_enum_decl(&mut self, decl: &mut TsEnumDecl) {
        if !self.handle_types {
            return;
        }

        self.in_type = false;
        self.visit_mut_binding_ident(&mut decl.id, None);
        decl.members.visit_mut_with(self);
    }

    fn visit_mut_ts_fn_type(&mut self, ty: &mut TsFnType) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        ty.type_params.visit_mut_with(&mut child);
        ty.params.visit_mut_with(&mut child);
        ty.type_ann.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_call_signature_decl(&mut self, n: &mut TsCallSignatureDecl) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        n.type_params.visit_mut_with(&mut child);
        n.params.visit_mut_with(&mut child);
        n.type_ann.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_method_signature(&mut self, n: &mut TsMethodSignature) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        n.type_params.visit_mut_with(&mut child);
        if n.computed {
            n.key.visit_mut_with(&mut child);
        }
        n.params.visit_mut_with(&mut child);
        n.type_ann.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_property_signature(&mut self, n: &mut TsPropertySignature) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        if n.computed {
            n.key.visit_mut_with(self);
        }
        let child_mark = Mark::fresh(self.mark);
        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        n.type_params.visit_mut_with(&mut child);
        n.init.visit_mut_with(&mut child);
        n.params.visit_mut_with(&mut child);
        n.type_ann.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_interface_decl(&mut self, n: &mut TsInterfaceDecl) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        self.visit_mut_binding_ident(&mut n.id, None);
        let child_mark = Mark::fresh(self.mark);
        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        n.type_params.visit_mut_with(&mut child);
        n.extends.visit_mut_with(&mut child);
        n.body.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_type_alias_decl(&mut self, n: &mut TsTypeAliasDecl) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        self.visit_mut_binding_ident(&mut n.id, None);
        let child_mark = Mark::fresh(self.mark);
        // Child folder
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );
        child.in_type = true;

        n.type_params.visit_mut_with(&mut child);
        n.type_ann.visit_mut_with(&mut child);
    }

    fn visit_mut_ts_import_equals_decl(&mut self, n: &mut TsImportEqualsDecl) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        self.visit_mut_binding_ident(&mut n.id, None);

        n.module_ref.visit_mut_with(self);
    }

    fn visit_mut_ts_namespace_decl(&mut self, n: &mut TsNamespaceDecl) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        self.visit_mut_binding_ident(&mut n.id, None);

        n.body.visit_mut_with(self);
    }

    fn visit_mut_ts_param_prop_param(&mut self, n: &mut TsParamPropParam) {
        if !self.handle_types {
            return;
        }

        self.in_type = false;
        self.ident_type = IdentType::Binding;
        n.visit_mut_children_with(self)
    }

    fn visit_mut_ts_qualified_name(&mut self, n: &mut TsQualifiedName) {
        if !self.handle_types {
            return;
        }

        self.in_type = true;
        self.ident_type = IdentType::Ref;

        n.left.visit_mut_with(self)
    }

    // TODO: How should I handle this?
    typed!(visit_mut_ts_namespace_export_decl, TsNamespaceExportDecl);

    track_ident_mut!();

    fn visit_mut_arrow_expr(&mut self, e: &mut ArrowExpr) {
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut folder = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        e.type_params.visit_mut_with(&mut folder);

        let old_hoist = self.hoist;
        let old = folder.ident_type;
        folder.ident_type = IdentType::Binding;
        folder.hoist = false;
        e.params.visit_mut_with(&mut folder);
        folder.ident_type = old;
        folder.hoist = old_hoist;

        e.body.visit_mut_with(&mut folder);

        e.return_type.visit_mut_with(&mut folder);

        self.cur_defining = folder.cur_defining;
    }

    fn visit_mut_param(&mut self, param: &mut Param) {
        self.in_type = false;
        self.ident_type = IdentType::Binding;
        param.visit_mut_children_with(self);
    }

    fn visit_mut_for_stmt(&mut self, n: &mut ForStmt) {
        let child_mark = Mark::fresh(self.mark);
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Block, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        self.ident_type = IdentType::Binding;
        n.init.visit_mut_with(&mut child);
        self.ident_type = IdentType::Ref;
        n.test.visit_mut_with(&mut child);
        self.ident_type = IdentType::Ref;
        n.update.visit_mut_with(&mut child);

        child.visit_mut_stmt_within_same_scope(&mut *n.body);

        self.cur_defining = child.cur_defining;
    }

    fn visit_mut_for_of_stmt(&mut self, n: &mut ForOfStmt) {
        let child_mark = Mark::fresh(self.mark);
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Block, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        n.left.visit_mut_with(&mut child);
        n.right.visit_mut_with(&mut child);

        child.visit_mut_stmt_within_same_scope(&mut *n.body);

        self.cur_defining = child.cur_defining;
    }

    fn visit_mut_for_in_stmt(&mut self, n: &mut ForInStmt) {
        let child_mark = Mark::fresh(self.mark);
        let mut child = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Block, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        n.left.visit_mut_with(&mut child);
        n.right.visit_mut_with(&mut child);

        child.visit_mut_stmt_within_same_scope(&mut *n.body);

        self.cur_defining = child.cur_defining;
    }

    fn visit_mut_block_stmt(&mut self, block: &mut BlockStmt) {
        let child_mark = Mark::fresh(self.mark);

        let mut child_folder = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Block, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        block.visit_mut_children_with(&mut child_folder);
        self.cur_defining = child_folder.cur_defining;
    }

    /// Handle body of the arrow functions
    fn visit_mut_block_stmt_or_expr(&mut self, node: &mut BlockStmtOrExpr) {
        match node {
            BlockStmtOrExpr::BlockStmt(block) => block.visit_mut_children_with(self).into(),
            BlockStmtOrExpr::Expr(e) => e.visit_mut_with(self).into(),
        }
    }

    fn visit_mut_catch_clause(&mut self, c: &mut CatchClause) {
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut folder = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        folder.ident_type = IdentType::Binding;
        c.param.visit_mut_with(&mut folder);
        folder.ident_type = IdentType::Ref;

        c.body.visit_mut_with(&mut folder);

        self.cur_defining = folder.cur_defining;
    }

    fn visit_mut_private_method(&mut self, m: &mut PrivateMethod) {
        m.key.visit_mut_with(self);

        {
            let child_mark = Mark::fresh(self.mark);

            // Child folder
            let mut child = Resolver::new(
                child_mark,
                Scope::new(ScopeKind::Fn, Some(&self.current)),
                None,
                self.handle_types,
            );

            m.function.visit_mut_with(&mut child)
        }
    }

    fn visit_mut_class_method(&mut self, m: &mut ClassMethod) {
        m.key.visit_mut_with(self);

        {
            let child_mark = Mark::fresh(self.mark);

            // Child folder
            let mut child = Resolver::new(
                child_mark,
                Scope::new(ScopeKind::Fn, Some(&self.current)),
                None,
                self.handle_types,
            );

            m.function.visit_mut_with(&mut child)
        }
    }

    fn visit_mut_class_prop(&mut self, p: &mut ClassProp) {
        p.decorators.visit_mut_with(self);

        if p.computed {
            let old = self.ident_type;
            self.ident_type = IdentType::Binding;
            p.key.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) {
        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut folder = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            None,
            self.handle_types,
        );

        let old = self.ident_type;
        self.ident_type = IdentType::Binding;
        c.params.visit_mut_with(&mut folder);
        self.ident_type = old;

        match &mut c.body {
            Some(body) => {
                body.visit_mut_children_with(&mut folder);
            }
            None => {}
        }
    }

    /// Leftmost one of a member expression should be resolved.
    fn visit_mut_member_expr(&mut self, e: &mut MemberExpr) {
        e.obj.visit_mut_with(self);

        if e.computed {
            e.prop.visit_mut_with(self);
        }
    }

    fn visit_mut_expr(&mut self, expr: &mut Expr) {
        self.in_type = false;
        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 this as Hoister handles this.

        {
            let child_mark = Mark::fresh(self.mark);

            // Child folder
            let mut folder = Resolver::new(
                child_mark,
                Scope::new(ScopeKind::Fn, Some(&self.current)),
                None,
                self.handle_types,
            );

            folder.cur_defining =
                Some((node.ident.sym.clone(), node.ident.span.ctxt().remove_mark()));

            node.function.visit_mut_with(&mut folder)
        }
    }

    fn visit_mut_decl(&mut self, decl: &mut Decl) {
        self.in_type = false;
        decl.visit_mut_children_with(self)
    }

    fn visit_mut_fn_expr(&mut self, e: &mut FnExpr) {
        if let Some(ident) = &mut e.ident {
            self.visit_mut_binding_ident(ident, None)
        }

        let child_mark = Mark::fresh(self.mark);

        // Child folder
        let mut folder = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Fn, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );
        e.function.visit_mut_with(&mut folder);

        self.cur_defining = folder.cur_defining;
    }

    fn visit_mut_function(&mut self, f: &mut Function) {
        f.type_params.visit_mut_with(self);

        self.in_type = false;
        self.ident_type = IdentType::Ref;
        f.decorators.visit_mut_with(self);

        self.ident_type = IdentType::Binding;
        f.params.visit_mut_with(self);

        self.ident_type = IdentType::Ref;
        match &mut f.body {
            Some(body) => {
                // Prevent creating new scope.
                body.visit_mut_children_with(self);
            }
            None => {}
        }

        f.return_type.visit_mut_with(self);
    }

    fn visit_mut_private_name(&mut self, _: &mut PrivateName) {}

    fn visit_mut_binding_ident(&mut self, i: &mut BindingIdent) {
        let ident_type = self.ident_type;
        let in_type = self.in_type;
        i.type_ann.visit_mut_with(self);
        self.in_type = in_type;
        self.ident_type = ident_type;

        i.id.visit_mut_with(self);
    }

    fn visit_mut_ident(&mut self, i: &mut Ident) {
        let ident_type = self.ident_type;
        let in_type = self.in_type;
        i.visit_mut_children_with(self);
        self.in_type = in_type;
        self.ident_type = ident_type;

        match self.ident_type {
            IdentType::Binding => self.visit_mut_binding_ident(i, None),
            IdentType::Ref => {
                let Ident { span, sym, .. } = i;

                if cfg!(debug_assertions) && LOG {
                    eprintln!(
                        "resolver: 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 {
                        eprintln!("\t -> {:?}", span.ctxt());
                    }
                    i.span = span;
                } else {
                    if cfg!(debug_assertions) && LOG {
                        eprintln!("\t -> Unresolved");
                    }

                    let mark = {
                        let mut mark = self.mark;
                        let mut cur = Some(&self.current);
                        while let Some(scope) = cur {
                            cur = scope.parent;

                            if cur.is_none() {
                                break;
                            }
                            mark = mark.parent();
                        }

                        mark
                    };

                    let span = span.apply_mark(mark);

                    if cfg!(debug_assertions) && LOG {
                        eprintln!("\t -> {:?}", span.ctxt());
                    }

                    i.span = span;
                    // Support hoisting
                    self.visit_mut_binding_ident(i, None)
                }
            }
            // We currently does not touch labels
            IdentType::Label => {}
        }
    }

    fn visit_mut_import_named_specifier(&mut self, s: &mut ImportNamedSpecifier) {
        self.in_type = false;
        let old = self.ident_type;
        self.ident_type = IdentType::Binding;
        s.local.visit_mut_with(self);
        self.ident_type = old;
    }

    fn visit_mut_method_prop(&mut self, m: &mut MethodProp) {
        m.key.visit_mut_with(self);

        {
            let child_mark = Mark::fresh(self.mark);

            // Child folder
            let mut child = Resolver::new(
                child_mark,
                Scope::new(ScopeKind::Fn, Some(&self.current)),
                None,
                self.handle_types,
            );

            m.function.visit_mut_with(&mut child)
        };
    }

    fn visit_mut_object_lit(&mut self, o: &mut ObjectLit) {
        let child_mark = Mark::fresh(self.mark);

        let mut child_folder = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Block, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        o.visit_mut_children_with(&mut child_folder);
        self.cur_defining = child_folder.cur_defining;
    }

    fn visit_mut_pat(&mut self, p: &mut Pat) {
        self.in_type = false;
        let old = self.cur_defining.take();
        p.visit_mut_children_with(self);

        self.cur_defining = old;
    }

    fn visit_mut_var_decl(&mut self, decl: &mut VarDecl) {
        self.in_type = false;

        let old_hoist = self.hoist;

        self.hoist = VarDeclKind::Var == decl.kind;
        decl.decls.visit_mut_with(self);

        self.hoist = old_hoist;
    }

    fn visit_mut_var_declarator(&mut self, decl: &mut VarDeclarator) {
        // order is important

        let old_defining = self.cur_defining.take();

        let old_type = self.ident_type;
        self.ident_type = IdentType::Binding;
        decl.name.visit_mut_with(self);
        self.ident_type = old_type;

        let cur_name = match decl.name {
            Pat::Ident(BindingIdent {
                id: Ident { ref sym, .. },
                ..
            }) => Some((sym.clone(), self.mark)),
            _ => None,
        };

        self.cur_defining = cur_name;
        decl.init.visit_mut_children_with(self);
        self.cur_defining = old_defining;
    }

    fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) {
        if self.current.kind != ScopeKind::Fn {
            return stmts.visit_mut_children_with(self);
        }

        // Phase 1: Handle hoisting
        {
            let mut hoister = Hoister {
                resolver: self,
                kind: None,
                in_block: false,
            };
            stmts.visit_mut_children_with(&mut hoister)
        }

        // Phase 2.
        stmts.visit_mut_children_with(self)
    }

    fn visit_mut_stmts(&mut self, stmts: &mut Vec<Stmt>) {
        // Phase 1: Handle hoisting
        {
            let mut hoister = Hoister {
                resolver: self,
                kind: None,
                in_block: false,
            };
            stmts.visit_mut_children_with(&mut hoister)
        }

        // Phase 2.
        stmts.visit_mut_children_with(self)
    }

    fn visit_mut_ts_module_decl(&mut self, decl: &mut TsModuleDecl) {
        match &mut decl.id {
            TsModuleName::Ident(i) => {
                self.visit_mut_binding_ident(i, None);
            }
            TsModuleName::Str(_) => {}
        }

        let child_mark = Mark::fresh(self.mark);

        let mut child_folder = Resolver::new(
            child_mark,
            Scope::new(ScopeKind::Block, Some(&self.current)),
            self.cur_defining.take(),
            self.handle_types,
        );

        decl.body.visit_mut_children_with(&mut child_folder);
    }
}

/// The folder which handles var / function hoisting.
struct Hoister<'a, 'b> {
    resolver: &'a mut Resolver<'b>,
    kind: Option<VarDeclKind>,
    /// Hoister should not touch let / const in the block.
    in_block: bool,
}

impl VisitMut for Hoister<'_, '_> {
    noop_visit_mut_type!();

    fn visit_mut_fn_decl(&mut self, node: &mut FnDecl) {
        self.resolver.in_type = false;
        self.resolver
            .visit_mut_binding_ident(&mut node.ident, Some(VarDeclKind::Var));
    }

    #[inline]
    fn visit_mut_expr(&mut self, _: &mut Expr) {}

    #[inline]
    fn visit_mut_arrow_expr(&mut self, _: &mut ArrowExpr) {}

    #[inline]
    fn visit_mut_tagged_tpl(&mut self, _: &mut TaggedTpl) {}

    #[inline]
    fn visit_mut_tpl(&mut self, _: &mut Tpl) {}

    #[inline]
    fn visit_mut_function(&mut self, _: &mut Function) {}

    fn visit_mut_var_decl(&mut self, node: &mut VarDecl) {
        if self.in_block {
            match node.kind {
                VarDeclKind::Const | VarDeclKind::Let => return,
                _ => {}
            }
        }

        let old_kind = self.kind;
        self.kind = Some(node.kind);

        self.resolver.hoist = false;

        node.visit_mut_children_with(self);

        self.kind = old_kind;
    }

    #[inline]
    fn visit_mut_var_declarator(&mut self, node: &mut VarDeclarator) {
        node.name.visit_mut_with(self);
    }

    fn visit_mut_pat(&mut self, node: &mut Pat) {
        self.resolver.in_type = false;
        match node {
            Pat::Ident(i) => self.resolver.visit_mut_binding_ident(&mut i.id, self.kind),
            _ => node.visit_mut_children_with(self),
        }
    }

    fn visit_mut_class_decl(&mut self, node: &mut ClassDecl) {
        self.resolver.in_type = false;
        self.resolver
            .visit_mut_binding_ident(&mut node.ident, Some(VarDeclKind::Let));
    }

    #[inline]
    fn visit_mut_catch_clause(&mut self, _: &mut CatchClause) {}

    #[inline]
    fn visit_mut_pat_or_expr(&mut self, _: &mut PatOrExpr) {}

    #[inline]
    fn visit_mut_param(&mut self, _: &mut Param) {}

    #[inline]
    fn visit_mut_constructor(&mut self, _: &mut Constructor) {}

    fn visit_mut_var_decl_or_expr(&mut self, n: &mut VarDeclOrExpr) {
        match n {
            VarDeclOrExpr::VarDecl(VarDecl {
                kind: VarDeclKind::Let,
                ..
            })
            | VarDeclOrExpr::VarDecl(VarDecl {
                kind: VarDeclKind::Const,
                ..
            }) => {}
            _ => {
                n.visit_mut_children_with(self);
            }
        }
    }

    fn visit_mut_var_decl_or_pat(&mut self, n: &mut VarDeclOrPat) {
        match n {
            VarDeclOrPat::VarDecl(VarDecl {
                kind: VarDeclKind::Let,
                ..
            })
            | VarDeclOrPat::VarDecl(VarDecl {
                kind: VarDeclKind::Const,
                ..
            }) => {}
            // Hoister should not handle lhs of for in statement below
            //
            // const b = [];
            // {
            //   let a;
            //   for (a in b) {
            //     console.log(a);
            //   }
            // }
            VarDeclOrPat::Pat(..) => {}
            _ => {
                n.visit_mut_children_with(self);
            }
        }
    }

    fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) {
        let old_in_block = self.in_block;
        self.in_block = true;
        n.visit_mut_children_with(self);
        self.in_block = old_in_block;
    }
}