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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
use std::{
    borrow::{Borrow, Cow},
    collections::hash_map::Entry,
    hash::Hash,
    mem::{replace, take},
    ops::{AddAssign, BitOr, Not},
};

use fxhash::FxHashMap;
use rnode::{NodeId, VisitWith};
use stc_ts_ast_rnode::{
    RBinExpr, RBindingIdent, RCondExpr, RExpr, RIdent, RIfStmt, RMemberExpr, RObjectPatProp, RPat, RPatOrExpr, RStmt, RSwitchCase,
    RSwitchStmt,
};
use stc_ts_errors::{DebugExt, ErrorKind};
use stc_ts_type_ops::{generalization::prevent_generalize, Fix};
use stc_ts_types::{name::Name, Array, ArrayMetadata, Id, Key, KeywordType, KeywordTypeMetadata, Union};
use stc_ts_utils::MapWithMut;
use stc_utils::{
    cache::Freeze,
    dev_span,
    ext::{SpanExt, TypeVecExt},
};
use swc_atoms::JsWord;
use swc_common::{Span, Spanned, SyntaxContext, TypeEq, DUMMY_SP};
use swc_ecma_ast::*;
use tracing::info;

use super::{generic::ExtendsOpts, types::NormalizeTypeOpts};
use crate::{
    analyzer::{
        assign::AssignOpts,
        expr::{optional_chaining::is_obj_opt_chaining, AccessPropertyOpts, IdCtx, TypeOfMode},
        scope::{ScopeKind, VarInfo},
        util::ResultExt,
        Analyzer, Ctx,
    },
    ty::Type,
    type_facts::TypeFacts,
    util::EndsWithRet,
    validator,
    validator::ValidateWith,
    VResult,
};

/// Conditional facts
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct CondFacts {
    pub facts: FxHashMap<Name, TypeFacts>,
    pub vars: FxHashMap<Name, Type>,
    pub excludes: FxHashMap<Name, Vec<Type>>,
    pub types: FxHashMap<Id, Type>,
}

impl CondFacts {
    #[inline]
    pub(crate) fn assert_valid(&self) {
        if !cfg!(debug_assertions) {
            return;
        }

        for ty in self.vars.values() {
            ty.assert_valid();
            ty.assert_clone_cheap();
        }

        for types in self.excludes.values() {
            for ty in types {
                ty.assert_valid();
            }
        }

        for ty in self.types.values() {
            ty.assert_valid();
            ty.assert_clone_cheap();
        }
    }

    #[inline]
    pub(crate) fn assert_clone_cheap(&self) {
        if !cfg!(debug_assertions) {
            return;
        }

        for ty in self.vars.values() {
            if !ty.is_union_type() {
                debug_assert!(ty.is_clone_cheap(), "ty.is_clone_cheap() should be true:\n{:?}", &self.vars);
            }
        }

        for types in self.excludes.values() {
            for ty in types {
                debug_assert!(ty.is_clone_cheap());
            }
        }

        for ty in self.types.values() {
            debug_assert!(ty.is_clone_cheap());
        }
    }

    pub fn override_vars_using(&mut self, r: &mut Self) {
        for (k, ty) in r.vars.drain() {
            ty.assert_valid();
            ty.assert_clone_cheap();

            match self.vars.entry(k) {
                Entry::Occupied(mut e) => {
                    *e.get_mut() = ty;
                }
                Entry::Vacant(e) => {
                    e.insert(ty);
                }
            }
        }
    }

    pub fn take(&mut self) -> Self {
        Self {
            facts: take(&mut self.facts),
            vars: take(&mut self.vars),
            excludes: take(&mut self.excludes),
            types: take(&mut self.types),
        }
    }

    fn or<K, T>(mut map: FxHashMap<K, T>, map2: FxHashMap<K, T>) -> FxHashMap<K, T>
    where
        K: Eq + Hash,
        T: Merge,
    {
        for (k, v) in map2 {
            match map.entry(k) {
                Entry::Occupied(mut e) => {
                    e.get_mut().or(v);
                }
                Entry::Vacant(e) => {
                    e.insert(v);
                }
            }
        }

        map
    }
}

#[derive(Debug, Default, Clone)]
pub(super) struct Facts {
    pub true_facts: CondFacts,
    pub false_facts: CondFacts,
}

impl Facts {
    #[inline]
    pub(crate) fn assert_valid(&self) {
        if !cfg!(debug_assertions) {
            return;
        }

        self.true_facts.assert_valid();
        self.false_facts.assert_valid();
    }

    #[inline]
    pub(crate) fn assert_clone_cheap(&self) {
        if !cfg!(debug_assertions) {
            return;
        }

        self.true_facts.assert_clone_cheap();
        self.false_facts.assert_clone_cheap();
    }

    pub fn take(&mut self) -> Self {
        self.assert_valid();

        Self {
            true_facts: self.true_facts.take(),
            false_facts: self.false_facts.take(),
        }
    }
}

impl Not for Facts {
    type Output = Self;

    #[inline]
    fn not(self) -> Self {
        Facts {
            true_facts: self.false_facts,
            false_facts: self.true_facts,
        }
    }
}

impl AddAssign for Facts {
    fn add_assign(&mut self, rhs: Self) {
        self.true_facts += rhs.true_facts;
        self.false_facts += rhs.false_facts;
    }
}

impl AddAssign<Option<Self>> for Facts {
    fn add_assign(&mut self, rhs: Option<Self>) {
        if let Some(rhs) = rhs {
            *self += rhs;
        }
    }
}

impl BitOr for Facts {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        Facts {
            true_facts: self.true_facts | rhs.true_facts,
            false_facts: self.false_facts | rhs.false_facts,
        }
    }
}

trait Merge {
    fn or(&mut self, other: Self);
}

impl<T> Merge for Box<T>
where
    T: Merge,
{
    fn or(&mut self, other: Self) {
        T::or(&mut **self, *other)
    }
}

impl<T> Merge for Vec<T> {
    fn or(&mut self, other: Self) {
        self.extend(other)
    }
}

impl Merge for TypeFacts {
    fn or(&mut self, other: Self) {
        *self |= other
    }
}

impl Merge for VarInfo {
    fn or(&mut self, other: Self) {
        self.copied |= other.copied;
        self.initialized |= other.initialized;
        Merge::or(&mut self.ty, other.ty);
    }
}

impl Merge for Type {
    fn or(&mut self, r: Self) {
        let l_span = self.span();

        let l = replace(self, Type::never(l_span, Default::default()));

        *self = Type::new_union(l_span, vec![l, r]);
    }
}

impl<T> Merge for Option<T>
where
    T: Merge,
{
    fn or(&mut self, other: Self) {
        match *self {
            Some(ref mut v) => {
                if let Some(other) = other {
                    v.or(other)
                }
            }
            _ => *self = other,
        }
    }
}

impl AddAssign for CondFacts {
    #[allow(clippy::suspicious_op_assign_impl)]
    fn add_assign(&mut self, rhs: Self) {
        self.assert_valid();
        rhs.assert_valid();

        for (k, v) in rhs.facts {
            *self.facts.entry(k.clone()).or_insert(TypeFacts::None) |= v;
        }

        self.types.extend(rhs.types);

        for (k, v) in rhs.vars {
            match self.vars.entry(k) {
                Entry::Occupied(mut e) => {
                    match e.get_mut().normalize_mut() {
                        Type::Union(u) => {
                            u.types.push(v);
                        }
                        prev => {
                            let prev = prev.take();
                            *e.get_mut() = Type::new_union(DUMMY_SP, vec![prev, v]).freezed();
                        }
                    };
                    e.get_mut().fix();
                    e.get_mut().freeze();
                }
                Entry::Vacant(e) => {
                    e.insert(v);
                }
            }
        }

        for (k, v) in rhs.excludes {
            self.excludes.entry(k).or_default().extend(v);
        }
    }
}

impl AddAssign<Option<Self>> for CondFacts {
    fn add_assign(&mut self, rhs: Option<Self>) {
        self.assert_valid();

        if let Some(rhs) = rhs {
            *self += rhs;
        }
    }
}

impl BitOr for CondFacts {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        CondFacts {
            facts: CondFacts::or(self.facts, rhs.facts),
            vars: CondFacts::or(self.vars, rhs.vars),
            types: CondFacts::or(self.types, rhs.types),
            excludes: CondFacts::or(self.excludes, rhs.excludes),
        }
    }
}

#[validator]
impl Analyzer<'_, '_> {
    fn validate(&mut self, stmt: &RIfStmt) -> VResult<()> {
        let prev_facts = self.cur_facts.take();
        prev_facts.assert_clone_cheap();

        let facts_from_test: Facts = {
            let ctx = Ctx {
                in_cond: true,
                should_store_truthy_for_access: true,
                ..self.ctx
            };
            let facts = self
                .with_ctx(ctx)
                .with_child(ScopeKind::Flow, prev_facts.true_facts.clone(), |child: &mut Analyzer| {
                    let test = stmt.test.validate_with_default(child);
                    match test {
                        Ok(_) => {}
                        Err(err) => {
                            child.storage.report(err);
                        }
                    }

                    Ok(child.cur_facts.take())
                });

            facts.report(&mut self.storage).unwrap_or_default()
        };

        facts_from_test.assert_clone_cheap();

        let true_facts = facts_from_test.true_facts;
        let false_facts = facts_from_test.false_facts;

        let mut cons_ends_with_unreachable = false;

        let cons_ends_with_ret = stmt.cons.ends_with_ret();

        self.cur_facts = prev_facts.clone();
        let facts_from_cons = self
            .with_child(ScopeKind::Flow, true_facts, |child: &mut Analyzer| {
                stmt.cons.visit_with(child);

                cons_ends_with_unreachable = child.ctx.in_unreachable;

                Ok(child.cur_facts.true_facts.take())
            })
            .report(&mut self.storage);

        let mut alt_ends_with_unreachable = None;

        let facts_from_alt = if let Some(alt) = &stmt.alt {
            self.cur_facts = prev_facts.clone();
            self.with_child(ScopeKind::Flow, false_facts.clone(), |child: &mut Analyzer| {
                alt.visit_with(child);

                alt_ends_with_unreachable = Some(child.ctx.in_unreachable);

                Ok(child.cur_facts.true_facts.take())
            })
            .report(&mut self.storage)
        } else {
            None
        };

        self.cur_facts = prev_facts;

        if cons_ends_with_ret {
            self.cur_facts.true_facts += false_facts;
            return Ok(());
        }

        if let (Some(facts_from_cons), Some(facts_from_alt)) = (facts_from_cons, facts_from_alt) {
            // Intersect type facts from cons and alt

            for (k, v) in facts_from_cons.facts {
                if let Some(&v2) = facts_from_alt.facts.get(&k) {
                    *self.cur_facts.true_facts.facts.entry(k).or_insert(TypeFacts::None) |= v & v2;
                }
            }

            for (k, types1) in facts_from_cons.excludes {
                if let Some(types2) = facts_from_alt.excludes.get(&k) {
                    let types = types1
                        .into_iter()
                        .filter(|t1| types2.iter().any(|t2| t1.type_eq(t2)))
                        .collect::<Vec<_>>();

                    if !types.is_empty() {
                        self.cur_facts.true_facts.excludes.entry(k).or_default().extend(types);
                    }
                }
            }
        }

        if cons_ends_with_unreachable {
            if let Some(true) = alt_ends_with_unreachable {
                self.ctx.in_unreachable = true;
            } else {
                self.cur_facts.true_facts += false_facts;
            }
        }

        Ok(())
    }
}

impl Analyzer<'_, '_> {
    /// This method may remove `SafeSubscriber` from `Subscriber` |
    /// `SafeSubscriber` or downgrade the type, like converting `Subscriber` |
    /// `SafeSubscriber` into `SafeSubscriber`. This behavior is controlled by
    /// the mark applied while handling type facts related to call.
    fn adjust_ternary_type(&mut self, span: Span, mut types: Vec<Type>) -> VResult<Vec<Type>> {
        let _tracing = dev_span!("adjust_ternary_type");

        types.iter_mut().for_each(|ty| {
            // Tuple -> Array
            if let Some(tuple) = ty.as_tuple_mut() {
                let span = tuple.span;

                let mut elem_types: Vec<_> = tuple.elems.take().into_iter().map(|elem| *elem.ty).collect();
                elem_types.dedup_type();
                let elem_type = box Type::new_union(DUMMY_SP, elem_types);
                *ty = Type::Array(Array {
                    span,
                    elem_type,
                    metadata: ArrayMetadata {
                        common: tuple.metadata.common,
                        ..Default::default()
                    },
                    tracker: Default::default(),
                })
                .freezed();
            }
        });

        if types.iter().all(|ty| ty.normalize_instance().is_lit()) {
            types.iter_mut().for_each(|ty| {
                prevent_generalize(ty);
            });
            return Ok(types);
        }

        let should_preserve = types
            .iter()
            .flat_map(|ty| ty.iter_union())
            .all(|ty| !ty.metadata().prevent_converting_to_children);

        if should_preserve {
            return self.remove_child_types(span, types);
        }

        self.downcast_types(span, types)
    }

    fn downcast_types(&mut self, span: Span, types: Vec<Type>) -> VResult<Vec<Type>> {
        let _tracing = dev_span!("downcast_types");

        fn need_work(ty: &Type) -> bool {
            !matches!(
                ty.normalize(),
                Type::Lit(..)
                    | Type::Keyword(KeywordType {
                        kind: TsKeywordTypeKind::TsNullKeyword,
                        ..
                    })
            )
        }

        let mut new = vec![];

        'outer: for (ai, ty) in types.iter().flat_map(|ty| ty.iter_union()).enumerate() {
            if need_work(ty) {
                for (bi, b) in types.iter().flat_map(|ty| ty.iter_union()).enumerate() {
                    if ai == bi || !need_work(b) {
                        continue;
                    }

                    // If type is same, we need to add it.
                    if b.type_eq(ty) {
                        break;
                    }

                    // TODO:
                    // if self.is_type_related_to(b, ty, Relation::StrictSubtype) {
                    match self.extends(
                        span,
                        b,
                        ty,
                        ExtendsOpts {
                            strict: true,
                            ..Default::default()
                        },
                    ) {
                        Some(true) => {
                            // Remove ty.
                            continue 'outer;
                        }
                        res => {}
                    }
                    // }
                }
            }

            new.push(ty.clone());
        }
        if new.is_empty() {
            // All types can be merged

            return Ok(types);
        }

        Ok(new)
    }

    /// Remove `SafeSubscriber` from `Subscriber` | `SafeSubscriber`.
    fn remove_child_types(&mut self, span: Span, types: Vec<Type>) -> VResult<Vec<Type>> {
        let _tracing = dev_span!("remove_child_types");

        let mut new = vec![];

        'outer: for (ai, ty) in types.iter().flat_map(|ty| ty.iter_union()).enumerate() {
            for (bi, b) in types.iter().enumerate() {
                if ai == bi {
                    continue;
                }

                match self.extends(
                    span,
                    ty,
                    b,
                    ExtendsOpts {
                        strict: true,
                        ..Default::default()
                    },
                ) {
                    Some(true) => {
                        // Remove ty.
                        continue 'outer;
                    }
                    res => {}
                }
            }

            new.push(ty.clone());
        }
        if new.is_empty() {
            // All types can be merged

            return Ok(types);
        }

        Ok(new)
    }

    /// Returns the type of discriminant.
    ///
    /// TODO(kdy1): Implement this.
    fn report_errors_for_incomparable_switch_cases(&mut self, s: &RSwitchStmt) -> VResult<Type> {
        let discriminant_ty = s.discriminant.validate_with_default(self)?;
        for case in &s.cases {
            if let Some(test) = &case.test {
                let case_ty = test.validate_with_default(self)?;
                // self.assign(&discriminant_ty, &case_ty, test.span())
                //     .context("tried to assign the discriminant of switch to
                // the test of a case")     .report(&mut
                // self.storage);
            }
        }

        Ok(discriminant_ty)
    }
}

#[validator]
impl Analyzer<'_, '_> {
    fn validate(&mut self, stmt: &RSwitchStmt) -> VResult<()> {
        let discriminant_ty = self.report_errors_for_incomparable_switch_cases(stmt).report(&mut self.storage);

        let mut false_facts = CondFacts::default();
        let mut base_true_facts = self.cur_facts.true_facts.take();
        // Declared at here as it's important to know if last one ends with return.
        let mut ends_with_ret = false;
        let len = stmt.cases.len();
        let stmt_span = stmt.span();

        let mut errored = false;
        // Check cases *in order*
        for (i, case) in stmt.cases.iter().enumerate() {
            if errored {
                break;
            }

            let span = case.test.as_ref().map(|v| v.span()).unwrap_or_else(|| stmt_span);

            let RSwitchCase { cons, .. } = case;
            let last = i == len - 1;

            ends_with_ret = cons.ends_with_ret();

            if let Some(ref test) = case.test {
                let binary_test_expr = RExpr::Bin(RBinExpr {
                    node_id: NodeId::invalid(),
                    op: op!("==="),
                    span,
                    left: stmt.discriminant.clone(),
                    right: test.clone(),
                });
                let ctx = Ctx {
                    in_cond: true,
                    in_switch_case_test: true,
                    should_store_truthy_for_access: true,
                    checking_switch_discriminant_as_bin: true,
                    ..self.ctx
                };
                let mut a = self.with_ctx(ctx);
                match binary_test_expr.validate_with_default(&mut *a) {
                    Ok(..) => {}
                    Err(err) => {
                        a.storage.report(err);
                        errored = true;
                        continue;
                    }
                }
            }

            let true_facts_created_by_case = self.cur_facts.true_facts.take();
            let false_facts_created_by_case = self.cur_facts.false_facts.take();

            let mut facts_for_body = base_true_facts.clone();
            facts_for_body += true_facts_created_by_case;

            self.with_child(ScopeKind::Flow, facts_for_body, |child| {
                cons.visit_with(child);
                Ok(())
            })?;

            if ends_with_ret || last {
                false_facts += false_facts_created_by_case.clone();
                base_true_facts += false_facts_created_by_case;
            }
        }

        if !errored {
            self.ctx.in_unreachable |= stmt
                .cases
                .iter()
                .all(|case| self.is_switch_case_body_unconditional_termination(&case.cons));
        }

        if ends_with_ret {
            self.cur_facts.true_facts += false_facts;
        }

        Ok(())
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct PatAssignOpts {
    pub assign: AssignOpts,
    pub ignore_lhs_errors: bool,
}

impl Analyzer<'_, '_> {
    /// Returns true if a body of switch always ends with `return`, `throw` or
    /// `continue`.
    ///
    /// TODO(kdy1): Support break with other label.
    fn is_switch_case_body_unconditional_termination<S>(&mut self, body: &[S]) -> bool
    where
        S: Borrow<RStmt>,
    {
        for stmt in body {
            match stmt.borrow() {
                RStmt::Return(..) | RStmt::Throw(..) | RStmt::Continue(..) => return true,
                RStmt::Break(..) => return false,

                RStmt::If(s) => match &s.alt {
                    Some(alt) => {
                        return self.is_switch_case_body_unconditional_termination(&[&*s.cons])
                            && self.is_switch_case_body_unconditional_termination(&[&**alt]);
                    }
                    None => return self.is_switch_case_body_unconditional_termination(&[&*s.cons]),
                },
                _ => {}
            }
        }

        false
    }

    pub(super) fn try_assign(&mut self, span: Span, op: AssignOp, lhs: &RPatOrExpr, rhs_ty: &Type) -> Type {
        rhs_ty.assert_valid();

        let res: VResult<Type> = try {
            match *lhs {
                RPatOrExpr::Expr(ref expr) | RPatOrExpr::Pat(box RPat::Expr(ref expr)) => {
                    let lhs_ty = expr.validate_with_args(self, (TypeOfMode::LValue, None, None));
                    let mut lhs_ty = match lhs_ty {
                        Ok(v) => v,
                        _ => Type::any(lhs.span(), Default::default()),
                    };
                    lhs_ty.freeze();

                    if op == op!("=") {
                        self.assign_with_opts(
                            &mut Default::default(),
                            &lhs_ty,
                            rhs_ty,
                            AssignOpts {
                                span,
                                left_ident_span: Some(lhs.span()),
                                ..Default::default()
                            },
                        )?
                    } else {
                        self.assign_with_operator(span, op, &lhs_ty, rhs_ty)?;
                    }

                    if let RExpr::Ident(left) = &**expr {
                        if op == op!("??=") || op == op!("||=") || op == op!("&&=") {
                            if let Ok(prev) = self.type_of_var(left, TypeOfMode::RValue, None) {
                                let new_actual_ty = self.apply_type_facts_to_type(TypeFacts::NEUndefinedOrNull, prev);

                                if let Some(var) = self.scope.vars.get_mut(&Id::from(left)) {
                                    var.actual_ty = Some(new_actual_ty.freezed());
                                }
                            }
                        }
                    }

                    match op {
                        op!("??=") | op!("||=") => {
                            lhs_ty = self.apply_type_facts_to_type(TypeFacts::NEUndefinedOrNull, lhs_ty);

                            Type::new_union(span, vec![lhs_ty, rhs_ty.clone()])
                        }
                        op!("&&=") => {
                            lhs_ty = self.apply_type_facts_to_type(TypeFacts::Falsy, lhs_ty);

                            Type::new_union(span, vec![lhs_ty, rhs_ty.clone()])
                        }
                        _ => rhs_ty.clone(),
                    }
                }

                RPatOrExpr::Pat(ref pat) => {
                    if op == op!("=") {
                        self.try_assign_pat_with_opts(
                            span,
                            pat,
                            rhs_ty,
                            PatAssignOpts {
                                ignore_lhs_errors: true,
                                ..Default::default()
                            },
                        )?;
                    } else {
                        // TODO
                        match &**pat {
                            RPat::Ident(left) => {
                                let lhs = self.type_of_var(&left.id, TypeOfMode::LValue, None);

                                if let Ok(lhs) = lhs {
                                    self.assign_with_operator(span, op, &lhs, rhs_ty)?;
                                }
                            }
                            _ => Err(ErrorKind::InvalidOperatorForLhs { span, op })?,
                        }
                    }

                    // TODO: Use the correct type
                    rhs_ty.clone()
                }
            }
        };

        match res {
            Ok(ty) => ty,
            Err(err) => {
                self.storage.report(err);
                rhs_ty.clone()
            }
        }
    }

    pub(super) fn try_assign_pat(&mut self, span: Span, lhs: &RPat, ty: &Type) -> VResult<()> {
        ty.assert_valid();

        self.try_assign_pat_with_opts(span, lhs, ty, Default::default())
    }

    fn try_assign_pat_with_opts(&mut self, span: Span, lhs: &RPat, ty: &Type, opts: PatAssignOpts) -> VResult<()> {
        ty.assert_valid();

        let span = span.with_ctxt(SyntaxContext::empty());

        let is_in_loop = self.scope.is_in_loop_body();
        let orig_ty = self
            .normalize(Some(ty.span().or_else(|| span)), Cow::Borrowed(ty), Default::default())
            .context("tried to normalize a type to assign it to a pattern")?
            .into_owned()
            .freezed();

        let ty = orig_ty.normalize();

        ty.assert_valid();

        // Update variable's type
        match lhs {
            // We emitted some parsing errors.
            RPat::Invalid(..) => Ok(()),

            RPat::Assign(assign) => {
                // TODO(kdy1): Use type annotation?
                let res = assign
                    .right
                    .validate_with_default(self)
                    .context("tried to validate type of default expression in an assignment pattern");

                self.try_assign_pat_with_opts(span, &assign.left, ty, opts)
                    .report(&mut self.storage);

                res.and_then(|default_value_type| self.try_assign_pat_with_opts(span, &assign.left, &default_value_type, opts))
                    .report(&mut self.storage);

                Ok(())
            }

            RPat::Ident(i) => {
                // Verify using immutable references.
                if let Some(var_info) = self.scope.get_var(&i.id.clone().into()) {
                    if let Some(mut var_ty) = var_info.ty.clone() {
                        var_ty.freeze();

                        self.assign_with_opts(
                            &mut Default::default(),
                            &var_ty,
                            ty,
                            AssignOpts {
                                span: i.id.span,
                                ..opts.assign
                            },
                        )?;
                    }
                }

                let mut actual_ty = None;
                if let Some(var_info) = self
                    .scope
                    .get_var(&i.id.clone().into())
                    .or_else(|| self.scope.search_parent(&i.id.clone().into()))
                {
                    if let Some(declared_ty) = &var_info.ty {
                        declared_ty.assert_valid();

                        if declared_ty.is_any()
                            || ty.is_kwd(TsKeywordTypeKind::TsNullKeyword)
                            || ty.is_kwd(TsKeywordTypeKind::TsUndefinedKeyword)
                        {
                            return Ok(());
                        }

                        let declared_ty = declared_ty.clone();

                        let ty = ty.clone();
                        let ty = self.apply_type_facts_to_type(TypeFacts::NEUndefined | TypeFacts::NENull, ty);

                        ty.assert_valid();

                        if ty.is_never() {
                            return Ok(());
                        }

                        let mut narrowed_ty = self.narrowed_type_of_assignment(span, declared_ty, &ty)?;
                        narrowed_ty.assert_valid();
                        narrowed_ty.freeze();
                        actual_ty = Some(narrowed_ty);
                    }
                } else {
                    if !opts.ignore_lhs_errors {
                        self.storage.report(
                            ErrorKind::NoSuchVar {
                                span,
                                name: i.id.clone().into(),
                            }
                            .into(),
                        );
                    }
                    return Ok(());
                }

                if let Some(ty) = &actual_ty {
                    ty.assert_valid();
                    ty.assert_clone_cheap();
                }

                // Update actual types.
                if let Some(var_info) = self.scope.get_var_mut(&i.id.clone().into()) {
                    var_info.is_actual_type_modified_in_loop |= is_in_loop;
                    let mut new_ty = actual_ty.unwrap_or_else(|| ty.clone());
                    new_ty.assert_valid();
                    new_ty.freeze();
                    var_info.actual_ty = Some(new_ty);
                    return Ok(());
                }

                let var_info = if let Some(var_info) = self.scope.search_parent(&i.id.clone().into()) {
                    let actual_ty = actual_ty.unwrap_or_else(|| orig_ty.clone());
                    actual_ty.assert_valid();
                    actual_ty.assert_clone_cheap();

                    VarInfo {
                        actual_ty: Some(actual_ty),
                        copied: true,
                        ..var_info.clone()
                    }
                } else {
                    if let Some(types) = self.find_type(&i.id.clone().into())? {
                        for ty in types {
                            if let Type::Module(..) = ty.normalize() {
                                return Err(ErrorKind::NotVariable {
                                    span: i.id.span,
                                    left: lhs.span(),
                                    ty: Some(box ty.normalize().clone()),
                                }
                                .into());
                            }
                        }
                    }

                    return if self.ctx.allow_ref_declaring && self.scope.declaring.contains(&i.id.clone().into()) {
                        Ok(())
                    } else {
                        // undefined symbol
                        Err(ErrorKind::UndefinedSymbol {
                            sym: i.id.clone().into(),
                            span: i.id.span,
                        }
                        .into())
                    };
                };

                // Variable is defined on parent scope.
                //
                // We copy var info with enhanced type.
                self.scope.insert_var(i.id.clone().into(), var_info);

                Ok(())
            }

            RPat::Array(ref arr) => {
                let ty = self
                    .get_iterator(span, Cow::Borrowed(ty), Default::default())
                    .context("tried to convert a type to an iterator to assign with an array pattern")
                    .report(&mut self.storage)
                    .unwrap_or_else(|| Cow::Owned(Type::any(span, Default::default())));
                //
                for (i, elem) in arr.elems.iter().enumerate() {
                    if let Some(elem) = elem {
                        if let RPat::Rest(elem) = elem {
                            // Rest element is special.
                            let type_for_rest_arg = self
                                .get_rest_elements(None, ty, i)
                                .context("tried to get left elements of an iterator to assign using a rest pattern")?;

                            self.try_assign_pat_with_opts(
                                span,
                                &elem.arg,
                                &type_for_rest_arg,
                                PatAssignOpts {
                                    assign: AssignOpts {
                                        allow_iterable_on_rhs: true,
                                        ..opts.assign
                                    },
                                    ..opts
                                },
                            )
                            .context("tried to assign left elements to the argument of a rest pattern")?;
                            break;
                        }

                        let elem_ty = self
                            .get_element_from_iterator(span, Cow::Borrowed(&ty), i)
                            .context("tried to get an element of type to assign with an array pattern")
                            .report(&mut self.storage)
                            .freezed();
                        if let Some(elem_ty) = elem_ty {
                            self.try_assign_pat_with_opts(span, elem, &elem_ty, opts)
                                .context("tried to assign an element of an array pattern")
                                .report(&mut self.storage);
                        }
                    }
                }
                Ok(())
            }

            RPat::Object(ref obj) => {
                //
                for prop in obj.props.iter() {
                    match prop {
                        RObjectPatProp::KeyValue(kv) => {
                            let key = kv.key.validate_with(self)?;
                            let prop_ty = self
                                .access_property(
                                    span,
                                    ty,
                                    &key,
                                    TypeOfMode::RValue,
                                    IdCtx::Var,
                                    AccessPropertyOpts {
                                        disallow_indexing_array_with_string: true,

                                        ..Default::default()
                                    },
                                )
                                .unwrap_or_else(|_| Type::any(span, Default::default()));

                            self.try_assign_pat_with_opts(span, &kv.value, &prop_ty, opts)
                                .report(&mut self.storage);
                        }
                        RObjectPatProp::Assign(a) => {
                            let key = Key::Normal {
                                span: a.key.span,
                                sym: a.key.sym.clone(),
                            };

                            let prop_ty = self
                                .access_property(
                                    span,
                                    ty,
                                    &key,
                                    TypeOfMode::RValue,
                                    IdCtx::Var,
                                    AccessPropertyOpts {
                                        disallow_indexing_array_with_string: true,
                                        ..Default::default()
                                    },
                                )
                                .unwrap_or_else(|_| Type::any(span, Default::default()))
                                .freezed();

                            self.try_assign_pat_with_opts(
                                span,
                                &RPat::Ident(RBindingIdent {
                                    node_id: NodeId::invalid(),
                                    id: a.key.clone(),
                                    type_ann: None,
                                }),
                                &prop_ty,
                                opts,
                            )
                            .report(&mut self.storage);
                        }
                        RObjectPatProp::Rest(r) => {
                            if r.type_ann.is_none() {
                                if let Some(m) = &mut self.mutations {
                                    m.for_pats.entry(r.node_id).or_default().ty = Some(Type::any(span, Default::default()));
                                }
                            }

                            match &*r.arg {
                                RPat::Ident(_) => {}

                                RPat::Array(_) => {
                                    self.storage.report(ErrorKind::NotArrayType { span: r.arg.span() }.into());
                                    self.storage
                                        .report(ErrorKind::BindingPatNotAllowedInRestPatArg { span: r.arg.span() }.into());
                                }

                                RPat::Object(_) => {
                                    self.storage
                                        .report(ErrorKind::BindingPatNotAllowedInRestPatArg { span: r.arg.span() }.into());
                                }

                                RPat::Expr(expr) => {
                                    // { ...obj?.a["b"] }
                                    if is_obj_opt_chaining(expr) {
                                        return Err(ErrorKind::InvalidRestPatternInOptionalChain { span: r.span }.into());
                                    }

                                    if !is_expr_correct_binding_pat(expr, true) {
                                        self.storage
                                            .report(ErrorKind::BindingPatNotAllowedInRestPatArg { span: r.arg.span() }.into());
                                    }
                                }

                                RPat::Invalid(_) => {
                                    // self.storage.report(Error::BindingPatNotAllowedInRestPatArg { span:
                                    // r.arg.span() });
                                    self.storage
                                        .report(ErrorKind::RestArgMustBeVarOrMemberAccess { span: r.arg.span() }.into());
                                }

                                _ => {}
                            }
                            // TODO
                            // self.try_assign_pat_with_opts(span, lhs,
                            // &prop_ty).report(&mut self.storage);
                        }
                    }
                }

                Ok(())
            }

            RPat::Rest(rest) => {
                // TODO(kdy1): Check if this is correct. (in object rest context)
                let ty = Type::Array(Array {
                    span,
                    elem_type: box ty.clone(),
                    metadata: Default::default(),
                    tracker: Default::default(),
                });
                self.try_assign_pat_with_opts(span, &rest.arg, &ty, opts)
            }

            RPat::Expr(lhs) => {
                if let RExpr::Lit(..) = &**lhs {
                    self.storage.report(ErrorKind::InvalidLhsOfAssign { span: lhs.span() }.into());
                    return Ok(());
                }
                let lhs_ty = lhs
                    .validate_with_args(self, (TypeOfMode::LValue, None, None))
                    .context("tried to validate type of the expression in lhs of assignment")
                    .report(&mut self.storage);

                if let Some(lhs_ty) = &lhs_ty {
                    self.assign_with_opts(&mut Default::default(), lhs_ty, ty, AssignOpts { span, ..opts.assign })?;
                }
                Ok(())
            }
        }
    }

    /// While this type fact is in scope, the var named `sym` will be treated as
    /// `ty`.
    pub(super) fn add_type_fact(&mut self, sym: &Id, ty: Type, exclude: Type) {
        info!("add_type_fact({}); ty = {:?}", sym, ty);

        ty.assert_clone_cheap();
        exclude.assert_clone_cheap();

        self.cur_facts.insert_var(sym, ty, exclude, false);
    }

    pub(super) fn add_deep_type_fact(&mut self, span: Span, name: Name, ty: Type, is_for_true: bool) {
        debug_assert!(!self.config.is_builtin);

        ty.assert_valid();
        ty.assert_clone_cheap();

        if let Some((name, mut ty)) = self
            .determine_type_fact_by_field_fact(span, &name, &ty)
            .report(&mut self.storage)
            .flatten()
        {
            ty.freeze();
            ty.assert_valid();

            if is_for_true {
                self.cur_facts.true_facts.vars.insert(name, ty);
            } else {
                self.cur_facts.false_facts.vars.insert(name, ty);
            }
            return;
        }

        if is_for_true {
            self.cur_facts.true_facts.vars.insert(name, ty);
        } else {
            self.cur_facts.false_facts.vars.insert(name, ty);
        }
    }

    /// If `type_facts` is [None], this method calculates type facts created by
    /// `'foo' in obj`.
    ///
    /// Otherwise, this method calculates type facts created by `if (a.foo) ;`.
    /// In this case, this method tests if `type_facts` matches the type of
    /// property and returns `never` if it does not.
    pub(super) fn narrow_types_with_property(
        &mut self,
        span: Span,
        src: &Type,
        property: &JsWord,
        type_facts: Option<TypeFacts>,
    ) -> VResult<Type> {
        src.assert_valid();

        let src = self.normalize(
            Some(span),
            Cow::Borrowed(src),
            NormalizeTypeOpts {
                preserve_union: true,
                preserve_global_this: true,
                ..Default::default()
            },
        )?;

        if let Type::Union(ty) = src.normalize() {
            let mut new_types = vec![];
            for ty in &ty.types {
                let ty = self.narrow_types_with_property(span, ty, property, type_facts)?;
                new_types.push(ty);
            }
            new_types.retain(|ty| !ty.is_never());
            new_types.dedup_type();

            if new_types.len() == 1 {
                return Ok(new_types.into_iter().next().unwrap());
            }

            return Ok(Type::Union(Union {
                span: ty.span(),
                types: new_types,
                metadata: ty.metadata,
                tracker: Default::default(),
            }));
        }

        let prop_res = self
            .access_property(
                src.span().or_else(|| span),
                &src,
                &Key::Normal {
                    span: DUMMY_SP,
                    sym: property.clone(),
                },
                TypeOfMode::RValue,
                IdCtx::Var,
                AccessPropertyOpts {
                    disallow_creating_indexed_type_from_ty_els: true,
                    ..Default::default()
                },
            )
            .map(Freeze::freezed);

        match prop_res {
            Ok(mut prop_ty) => {
                // Check if property matches the type fact.
                if let Some(type_facts) = type_facts {
                    let orig = prop_ty.clone();
                    prop_ty = self.apply_type_facts_to_type(type_facts, prop_ty);

                    // TODO(kdy1): See if which one is correct.
                    //
                    // if !orig.normalize().type_eq(prop_ty.normalize()) {
                    //     return Ok(Type::never(src.span()));
                    // }

                    if prop_ty.is_never() {
                        return Ok(Type::never(
                            src.span(),
                            KeywordTypeMetadata {
                                common: src.metadata(),
                                ..Default::default()
                            },
                        ));
                    }
                }
            }
            Err(err) => match *err {
                ErrorKind::NoSuchProperty { .. } | ErrorKind::NoSuchPropertyInClass { .. } => {
                    return Ok(Type::never(
                        src.span(),
                        KeywordTypeMetadata {
                            common: src.metadata(),
                            ..Default::default()
                        },
                    ))
                }
                _ => {}
            },
        }

        Ok(src.into_owned())
    }

    fn determine_type_fact_by_field_fact(&mut self, span: Span, name: &Name, ty: &Type) -> VResult<Option<(Name, Type)>> {
        ty.assert_valid();

        if name.len() == 1 {
            return Ok(None);
        }

        let (top, symbols) = name.inner();
        let mut id: RIdent = top.clone().into();
        id.span.lo = span.lo;
        id.span.hi = span.hi;

        let obj = self.type_of_var(&id, TypeOfMode::RValue, None)?;
        let obj = self.normalize(
            Some(span),
            Cow::Owned(obj),
            NormalizeTypeOpts {
                preserve_global_this: true,
                preserve_union: true,
                ..Default::default()
            },
        )?;

        if let Type::Union(u) = obj.normalize() {
            if name.len() == 2 {
                let mut new_obj_types = vec![];

                for obj in &u.types {
                    if let Ok(prop_ty) = self.access_property(
                        obj.span(),
                        obj,
                        &Key::Normal {
                            span: ty.span(),
                            sym: symbols[0].clone(),
                        },
                        TypeOfMode::RValue,
                        IdCtx::Var,
                        Default::default(),
                    ) {
                        if ty.type_eq(&prop_ty) {
                            new_obj_types.push(obj.clone());
                        }
                    }
                }

                if new_obj_types.is_empty() {
                    return Ok(None);
                }
                let mut ty = Type::new_union(span, new_obj_types);
                ty.fix();

                return Ok(Some((Name::from(top.clone()), ty)));
            }
        }

        Ok(None)
    }
}

fn is_expr_correct_binding_pat(e: &RExpr, is_top_level: bool) -> bool {
    match e {
        RExpr::This(..) => !is_top_level,
        RExpr::Ident(..) => true,
        RExpr::SuperProp(..) => true,
        RExpr::Member(RMemberExpr { obj, .. }) => is_expr_correct_binding_pat(obj, false),
        _ => false,
    }
}

#[validator]
impl Analyzer<'_, '_> {
    fn validate(&mut self, e: &RCondExpr, mode: TypeOfMode, type_ann: Option<&Type>) -> VResult<Type> {
        let RCondExpr {
            span,
            ref test,
            ref alt,
            ref cons,
            ..
        } = *e;

        self.validate_with(|a| {
            let ctx = Ctx {
                in_cond: true,
                should_store_truthy_for_access: true,
                ..a.ctx
            };
            test.validate_with_default(&mut *a.with_ctx(ctx))?;

            Ok(())
        });

        let true_facts = self.cur_facts.true_facts.take();
        let false_facts = self.cur_facts.false_facts.take();
        let mut cons = self.with_child(ScopeKind::Flow, true_facts, |child: &mut Analyzer| {
            let ty = cons.validate_with_args(child, (mode, None, type_ann)).report(&mut child.storage);

            Ok(ty.unwrap_or_else(|| Type::any(cons.span(), Default::default())))
        })?;
        cons.freeze();
        let mut alt = self.with_child(ScopeKind::Flow, false_facts, |child: &mut Analyzer| {
            let ty = alt.validate_with_args(child, (mode, None, type_ann)).report(&mut child.storage);

            Ok(ty.unwrap_or_else(|| Type::any(alt.span(), Default::default())))
        })?;
        alt.freeze();

        if cons.type_eq(&alt) {
            return Ok(cons);
        }

        let new_types = if type_ann.is_none() {
            self.adjust_ternary_type(span, vec![cons, alt])?
        } else {
            vec![cons, alt]
        };
        let ty = Type::new_union(span, new_types).fixed();
        ty.assert_valid();
        Ok(ty)
    }
}

impl Facts {
    fn insert_var<N: Into<Name>>(&mut self, name: N, ty: Type, exclude: Type, negate: bool) {
        ty.assert_valid();
        ty.assert_clone_cheap();

        let name = name.into();

        if negate {
            self.false_facts.vars.insert(name.clone(), ty);
            self.true_facts.excludes.entry(name).or_default().push(exclude);
        } else {
            self.true_facts.vars.insert(name.clone(), ty);
            self.false_facts.excludes.entry(name).or_default().push(exclude);
        }
    }
}