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
use std::borrow::Cow;

use itertools::Itertools;
use rnode::{FoldWith, NodeId};
use stc_ts_ast_rnode::{RBindingIdent, RExpr, RIdent, RNumber, RObjectPatProp, RPat, RStr, RTsEntityName, RTsLit};
use stc_ts_errors::{
    debug::{dump_type_as_string, force_dump_type_as_string},
    DebugExt, ErrorKind,
};
use stc_ts_type_ops::{tuple_to_array::TupleToArray, widen::Widen, Fix};
use stc_ts_types::{
    type_id::DestructureId, Array, CommonTypeMetadata, Instance, Key, KeywordType, LitType, OptionalType, PropertySignature, Ref, RestType,
    Tuple, TupleElement, TupleMetadata, Type, TypeElement, TypeLit, TypeLitMetadata, TypeParam, TypeParamInstantiation, Union,
};
use stc_ts_utils::{run, PatExt};
use stc_utils::{cache::Freeze, dev_span, TryOpt};
use swc_common::{Span, Spanned, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::{TsKeywordTypeKind, VarDeclKind};
use tracing::debug;

use crate::{
    analyzer::{
        assign::AssignOpts,
        expr::{AccessPropertyOpts, GetIteratorOpts, IdCtx, TypeOfMode},
        types::NormalizeTypeOpts,
        util::{opt_union, ResultExt},
        Analyzer, Ctx,
    },
    ty::TypeExt,
    validator::ValidateWith,
    VResult,
};

/// The kind of binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VarKind {
    Var(VarDeclKind),
    /// Function parameters.
    Param,
    Class,
    /// [stc_ts_ast_rnode::RFnDecl]
    Fn,
    Import,
    Enum,
    Error,
}

/// All bool fields default to `false`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct DeclareVarsOpts {
    pub kind: VarKind,
    pub use_iterator_for_array: bool,
}

impl Default for DeclareVarsOpts {
    fn default() -> Self {
        Self {
            kind: VarKind::Var(VarDeclKind::Var),
            use_iterator_for_array: false,
        }
    }
}

impl Analyzer<'_, '_> {
    /// TODO(kdy1): Rename to declare_vars
    ///
    /// # Parameters
    ///
    ///
    /// ## actual
    ///
    /// The type of actual value.
    ///
    ///
    /// ## default
    ///
    /// The type of default value specified by an assignment pattern.
    pub(crate) fn add_vars(
        &mut self,
        pat: &RPat,
        ty: Option<Type>,
        actual: Option<Type>,
        default: Option<Type>,
        opts: DeclareVarsOpts,
    ) -> VResult<Option<Type>> {
        if let Some(ty) = &ty {
            ty.assert_valid();
            if !self.config.is_builtin {
                ty.assert_clone_cheap();
            }
        }
        if let Some(ty) = &actual {
            ty.assert_valid();
            if !self.config.is_builtin {
                ty.assert_clone_cheap();
            }
        }
        if let Some(ty) = &default {
            ty.assert_valid();
            if !self.config.is_builtin {
                ty.assert_clone_cheap();
            }
        }

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

        match pat {
            RPat::Ident(i) => {
                if let Some(ty) = &ty {
                    if cfg!(debug_assertions) {
                        debug!("[vars]: Declaring {} as {}", i.id.sym, dump_type_as_string(ty));
                    }
                } else {
                    if cfg!(debug_assertions) {
                        debug!("[vars]: Declaring {} without type", i.id.sym);
                    }
                }

                let mut ty = match (default, ty) {
                    (Some(default), Some(ty)) => {
                        if let Some(true) = self.extends(span, &default, &ty, Default::default()) {
                            Some(ty)
                        } else {
                            opt_union(span, Some(ty), Some(default))
                        }
                    }
                    (default, ty) => opt_union(span, ty, default),
                };

                ty.freeze();

                if let Some(ty) = &ty {
                    if let Some(m) = &mut self.mutations {
                        m.for_pats.entry(i.node_id).or_default().ty = Some(ty.clone());
                    }
                }

                self.declare_var(
                    span,
                    opts.kind,
                    i.id.clone().into(),
                    ty,
                    actual,
                    // initialized
                    true,
                    // let/const declarations does not allow multiple declarations with
                    // same name
                    opts.kind == VarKind::Var(VarDeclKind::Var),
                    false,
                    false,
                )
            }

            RPat::Assign(p) => {
                let type_ann = p.left.get_ty();
                let type_ann: Option<Type> = match type_ann {
                    Some(v) => v.validate_with(self).report(&mut self.storage),
                    None => None,
                };
                let is_typed = type_ann.is_some();
                let mut type_ann = type_ann.or(default);
                type_ann.freeze();

                let mut right = p
                    .right
                    .validate_with_args(self, (TypeOfMode::RValue, None, type_ann.as_ref().or(ty.as_ref())))
                    .report(&mut self.storage)
                    .unwrap_or_else(|| Type::any(span, Default::default()));

                if self.ctx.is_fn_param && type_ann.is_none() {
                    // If the declaration includes an initializer expression (which is permitted
                    // only when the parameter list occurs in conjunction with a
                    // function body), the parameter type is the widened form (section
                    // 3.11) of the type of the initializer expression.
                    match &*p.left {
                        RPat::Array(p_left) => {
                            right = right.fold_with(&mut Widen { tuple_to_array: false });
                        }
                        _ => {
                            right = right.fold_with(&mut Widen { tuple_to_array: true });
                        }
                    }
                }

                right.freeze();

                if let Some(type_ann) = &type_ann {
                    self.assign_with_opts(
                        &mut Default::default(),
                        type_ann,
                        &right,
                        AssignOpts {
                            span: p.right.span(),
                            allow_assignment_to_param_constraint: false,
                            ..Default::default()
                        },
                    )
                    .context("tried to assign a value to a variable with an assignment pattern")
                    .report(&mut self.storage);
                }

                let default = if is_typed {
                    type_ann
                } else {
                    opt_union(span, type_ann, Some(right))
                }
                .freezed();

                self.add_vars(
                    &p.left,
                    ty,
                    actual,
                    default,
                    DeclareVarsOpts {
                        use_iterator_for_array: true,
                        ..opts
                    },
                )
                .context("tried to declare a variable with an assignment pattern")
            }

            RPat::Array(arr) => {
                if opts.use_iterator_for_array {
                    // Handle tuple
                    //
                    //      const [a , setA] = useState();
                    //

                    let ty = ty
                        .map(|ty| {
                            self.get_iterator(
                                span,
                                Cow::Owned(ty),
                                GetIteratorOpts {
                                    disallow_str: true,
                                    ..Default::default()
                                },
                            )
                            .context("tried to convert a type to an iterator to assign with an array pattern.")
                            .unwrap_or_else(|err| {
                                self.storage.report(err);
                                Cow::Owned(Type::any(span, Default::default()))
                            })
                        })
                        .freezed()
                        .map(Cow::into_owned);

                    let default_ty = default;
                    let default = default_ty
                        .as_ref()
                        .map(|ty| {
                            self.get_iterator(
                                span,
                                Cow::Borrowed(ty),
                                GetIteratorOpts {
                                    disallow_str: true,
                                    ..Default::default()
                                },
                            )
                            .context("tried to convert a type to an iterator to assign with an array pattern (default value)")
                            .unwrap_or_else(|err| {
                                self.storage.report(err);
                                Cow::Owned(Type::any(span, Default::default()))
                            })
                        })
                        .freezed()
                        .map(Cow::into_owned);

                    for (idx, 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 = match &ty {
                                    Some(ty) => self
                                        .get_rest_elements(Some(span), Cow::Borrowed(ty), idx)
                                        .context("tried to get left elements of an iterator to declare variables using a rest pattern")
                                        .map(Cow::into_owned)
                                        .report(&mut self.storage),
                                    None => None,
                                }
                                .freezed();

                                let default = match default {
                                    Some(ty) => self
                                        .get_rest_elements(Some(span), Cow::Borrowed(&ty), idx)
                                        .context("tried to get left elements of an iterator to declare variables using a rest pattern")
                                        .map(Cow::into_owned)
                                        .report(&mut self.storage),
                                    None => None,
                                }
                                .freezed();

                                self.add_vars(&elem.arg, type_for_rest_arg, None, default, DeclareVarsOpts { ..opts })
                                    .context("tried to declare left elements to the argument of a rest pattern")
                                    .report(&mut self.storage);
                                break;
                            }

                            let elem_ty = ty
                                .as_ref()
                                .try_map(|ty| -> VResult<Type> {
                                    let result = self.get_element_from_iterator(span, Cow::Borrowed(ty), idx).with_context(|| {
                                        format!(
                                            "tried to get the type of {}th element from iterator to declare vars with an array pattern",
                                            idx
                                        )
                                    });

                                    match result {
                                        Ok(ty) => Ok(ty.into_owned().generalize_lit()),
                                        Err(err) => match &*err {
                                            ErrorKind::TupleIndexError { .. } => match elem {
                                                RPat::Assign(p) => {
                                                    let type_ann = p.left.get_ty();
                                                    let type_ann: Option<Type> =
                                                        type_ann.and_then(|v| v.validate_with(self).report(&mut self.storage));
                                                    let type_ann = type_ann.or_else(|| default_ty.clone());

                                                    let right = p
                                                        .right
                                                        .validate_with_args(
                                                            self,
                                                            (TypeOfMode::RValue, None, type_ann.as_ref().or(Some(ty))),
                                                        )
                                                        .report(&mut self.storage)
                                                        .unwrap_or_else(|| Type::any(span, Default::default()));

                                                    Ok(right)
                                                }
                                                RPat::Rest(p) => {
                                                    // [a, ...b] = [1]
                                                    // b should be an empty tuple
                                                    Ok(Type::Tuple(Tuple {
                                                        span: p.span,
                                                        elems: vec![],
                                                        metadata: Default::default(),
                                                        tracker: Default::default(),
                                                    }))
                                                }
                                                _ => Err(err),
                                            },
                                            _ => Err(err),
                                        },
                                    }
                                })?
                                .freezed();

                            let default_elem_ty = default
                                .as_ref()
                                .and_then(|ty| {
                                    self.get_element_from_iterator(span, Cow::Borrowed(ty), idx)
                                        .with_context(|| {
                                            format!(
                                                "tried to get the type of {}th element from iterator to declare vars with an array \
                                                 pattern (default value)",
                                                idx
                                            )
                                        })
                                        .ok()
                                })
                                .map(Cow::into_owned)
                                .map(|ty| ty.generalize_lit())
                                .freezed();

                            // TODO(kdy1): actual_ty

                            self.add_vars(elem, elem_ty, None, default_elem_ty, opts)?;
                        }
                    }
                    // Type inference for functions
                    let default_ty = match default_ty {
                        Some(d_ty) => {
                            let d_ty = d_ty.fold_with(&mut Widen { tuple_to_array: false });

                            match d_ty {
                                Type::Tuple(mut ty) => {
                                    let right_type_len = ty.elems.len();

                                    for (i, left_element) in arr.elems.iter().enumerate() {
                                        let is_not_assigned_type = i + 1 > right_type_len;

                                        if let Some(r_pat) = left_element {
                                            match r_pat {
                                                RPat::Assign(p) => {
                                                    if is_not_assigned_type {
                                                        let mut elem_ty = p
                                                            .right
                                                            .as_ref()
                                                            .validate_with_default(self)?
                                                            .fold_with(&mut Widen { tuple_to_array: false });

                                                        let convert_ty = match elem_ty.as_union_type_mut() {
                                                            Some(union_obj) => {
                                                                let mut has_undefined = false;

                                                                for union_ty in union_obj.types.iter() {
                                                                    if let Type::Keyword(a) = union_ty {
                                                                        if TsKeywordTypeKind::TsUndefinedKeyword == a.kind {
                                                                            has_undefined = true
                                                                        }
                                                                    }
                                                                }

                                                                if !has_undefined {
                                                                    union_obj.types.push(Type::undefined(span, Default::default()));
                                                                }

                                                                box Type::Union(union_obj.clone())
                                                            }
                                                            None => match elem_ty.normalize() {
                                                                Type::Keyword(KeywordType {
                                                                    kind: TsKeywordTypeKind::TsAnyKeyword,
                                                                    ..
                                                                })
                                                                | Type::Keyword(KeywordType {
                                                                    kind: TsKeywordTypeKind::TsUnknownKeyword,
                                                                    ..
                                                                }) => box elem_ty,

                                                                Type::Keyword(KeywordType {
                                                                    kind: TsKeywordTypeKind::TsNeverKeyword,
                                                                    ..
                                                                }) => box Type::undefined(span, Default::default()),

                                                                _ => box Type::Union(Union {
                                                                    span,
                                                                    types: vec![elem_ty, Type::undefined(span, Default::default())],
                                                                    metadata: Default::default(),
                                                                    tracker: Default::default(),
                                                                }),
                                                            },
                                                        };

                                                        ty.elems.push(TupleElement {
                                                            span,
                                                            label: None,
                                                            ty: box Type::Optional(OptionalType {
                                                                span,
                                                                ty: convert_ty,
                                                                metadata: Default::default(),
                                                                tracker: Default::default(),
                                                            }),

                                                            tracker: Default::default(),
                                                        });
                                                    }
                                                }
                                                _ => {
                                                    if is_not_assigned_type {
                                                        ty.elems.push(TupleElement {
                                                            span,
                                                            label: None,
                                                            ty: box Type::Optional(OptionalType {
                                                                span,
                                                                ty: box Type::any(span, Default::default()),
                                                                metadata: Default::default(),
                                                                tracker: Default::default(),
                                                            }),
                                                            tracker: Default::default(),
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    Some(Type::Tuple(ty))
                                }

                                Type::Array(..) => {
                                    let any_len = arr.elems.len();

                                    let mut elems: Vec<TupleElement> = vec![];

                                    for i in 0..any_len {
                                        elems.push(TupleElement {
                                            span,
                                            label: None,
                                            ty: box Type::Optional(OptionalType {
                                                span,
                                                ty: box Type::any(span, Default::default()),
                                                metadata: Default::default(),
                                                tracker: Default::default(),
                                            }),
                                            tracker: Default::default(),
                                        });
                                    }

                                    Some(Type::Tuple(Tuple {
                                        span,
                                        elems,
                                        metadata: Default::default(),
                                        tracker: Default::default(),
                                    }))
                                }
                                _ => Some(d_ty),
                            }
                        }
                        None => None,
                    };

                    Ok(ty.or(default_ty))
                } else {
                    let mut elems = vec![];

                    let destructure_key = self.get_destructor_unique_key();

                    let mut has_rest = false;
                    for (idx, elem) in arr.elems.iter().enumerate() {
                        match elem {
                            Some(elem) => {
                                if let RPat::Rest(elem) = elem {
                                    has_rest = true;
                                    // Rest element is special.
                                    let type_for_rest_arg = match &ty {
                                        Some(ty) => self
                                            .get_rest_elements(Some(span), Cow::Borrowed(ty), idx)
                                            .context("tried to get left elements of an iterator to declare variables using a rest pattern")
                                            .map(Cow::into_owned)
                                            .report(&mut self.storage),
                                        None => None,
                                    }
                                    .freezed();

                                    let default = match &default {
                                        Some(ty) => self
                                            .get_rest_elements(Some(span), Cow::Borrowed(ty), idx)
                                            .context("tried to get left elements of an iterator to declare variables using a rest pattern")
                                            .map(Cow::into_owned)
                                            .report(&mut self.storage),
                                        None => None,
                                    }
                                    .freezed();

                                    let rest_ty = self
                                        .add_vars(&elem.arg, type_for_rest_arg, None, default, DeclareVarsOpts { ..opts })
                                        .context("tried to declare left elements to the argument of a rest pattern")
                                        .report(&mut self.storage)
                                        .flatten();

                                    elems.push(TupleElement {
                                        span: elem.span(),
                                        label: Some(*elem.arg.clone()),
                                        ty: box Type::Rest(RestType {
                                            span: elem.span,
                                            ty: box rest_ty.unwrap_or_else(|| Type::any(elem.span, Default::default())),
                                            metadata: Default::default(),
                                            tracker: Default::default(),
                                        })
                                        .freezed(),
                                        tracker: Default::default(),
                                    });

                                    break;
                                }

                                let mut elem_ty = match &ty {
                                    Some(ty) => self
                                        .access_property(
                                            elem.span(),
                                            ty,
                                            &Key::Num(RNumber {
                                                span: elem.span(),
                                                value: idx as f64,
                                                raw: None,
                                            }),
                                            TypeOfMode::RValue,
                                            IdCtx::Var,
                                            Default::default(),
                                        )
                                        .map(|ty| ty.generalize_lit())
                                        .context("tried to access property to declare variables using an array pattern")
                                        .report(&mut self.storage),
                                    None => None,
                                }
                                .freezed();

                                let default = match &default {
                                    Some(ty) => self
                                        .access_property(
                                            elem.span(),
                                            ty,
                                            &Key::Num(RNumber {
                                                span: elem.span(),
                                                value: idx as f64,
                                                raw: None,
                                            }),
                                            TypeOfMode::RValue,
                                            IdCtx::Var,
                                            Default::default(),
                                        )
                                        .map(|ty| ty.generalize_lit())
                                        .context("tried to access property to declare variables using an array pattern")
                                        .report(&mut self.storage),
                                    None => None,
                                }
                                .freezed();

                                if let Some(ty) = &mut elem_ty {
                                    add_destructure_sign(ty, destructure_key);
                                }

                                // TODO(kdy1): actual_ty
                                let elem_ty = self
                                    .add_vars(elem, elem_ty, None, default, opts)
                                    .report(&mut self.storage)
                                    .flatten();

                                elems.push(TupleElement {
                                    span: elem.span(),
                                    label: Some(elem.clone()),
                                    ty: box elem_ty.unwrap_or_else(|| Type::any(elem.span(), Default::default())).freezed(),
                                    tracker: Default::default(),
                                });
                            }
                            // Skip
                            None => {}
                        }
                    }

                    let save_ty = ty.clone().map(|ty| {
                        if let Ok(ty) = self.normalize(Some(span), Cow::Borrowed(&ty), Default::default()) {
                            let mut ty = ty.into_owned();
                            if let Type::Union(Union { types, .. }) = ty.normalize_mut() {
                                'outer: for member in types.iter_mut() {
                                    if let Type::Tuple(tuple) = member.normalize_mut() {
                                        for (idx, (inner, outer)) in tuple.elems.iter_mut().zip(elems.iter()).enumerate() {
                                            if has_rest && elems.len() - 1 == idx {
                                                break 'outer;
                                            }
                                            inner.label = outer.label.clone();
                                        }
                                    }
                                }
                            }
                            return ty;
                        }
                        ty
                    });

                    let mut real_ty = Type::Tuple(Tuple {
                        span,
                        elems,
                        metadata: TupleMetadata {
                            common: CommonTypeMetadata {
                                destructure_key,
                                ..Default::default()
                            },
                            ..Default::default()
                        },
                        tracker: Default::default(),
                    });

                    if let Some(ty) = &ty {
                        let t = ty.normalize_instance();

                        if t.is_array() || (t.is_tuple() && arr.type_ann.is_none() && self.ctx.is_calling_iife) {
                            real_ty = real_ty.fold_with(&mut TupleToArray);
                            real_ty.fix();
                        }
                    }

                    real_ty.freeze();
                    self.regist_destructure(span, save_ty, Some(destructure_key));
                    Ok(Some(real_ty))
                }
            }

            RPat::Object(obj) => {
                let normalize_ty = ty.as_ref().map(Type::normalize);
                let should_use_no_such_property = !matches!(normalize_ty, Some(Type::TypeLit(..)));
                let destructure_key = self.regist_destructure(span, ty.clone(), None);

                let mut real = Type::TypeLit(TypeLit {
                    span,
                    members: vec![],
                    metadata: TypeLitMetadata {
                        common: CommonTypeMetadata {
                            destructure_key,
                            ..Default::default()
                        },
                        ..Default::default()
                    },
                    tracker: Default::default(),
                });

                // TODO(kdy1): Normalize static
                //
                let mut used_keys = vec![];

                for (idx, prop) in obj.props.iter().enumerate() {
                    let is_last = idx == obj.props.len() - 1;

                    match prop {
                        RObjectPatProp::KeyValue(prop) => {
                            let key = prop.key.validate_with(self)?;
                            used_keys.push(key.clone());

                            let ctx = Ctx {
                                disallow_unknown_object_property: true,
                                ..self.ctx
                            };
                            let prop_ty = ty.as_ref().try_map(|ty| {
                                self.with_ctx(ctx)
                                    .access_property(
                                        span,
                                        ty,
                                        &key,
                                        TypeOfMode::RValue,
                                        IdCtx::Var,
                                        AccessPropertyOpts {
                                            disallow_indexing_array_with_string: true,
                                            disallow_creating_indexed_type_from_ty_els: true,
                                            disallow_inexact: true,
                                            ..Default::default()
                                        },
                                    )
                                    .map(|ty| ty.generalize_lit())
                                    .context("tried to access property to declare variables")
                            });

                            let default_prop_ty = default
                                .as_ref()
                                .and_then(|ty| {
                                    self.with_ctx(ctx)
                                        .access_property(
                                            span,
                                            ty,
                                            &key,
                                            TypeOfMode::RValue,
                                            IdCtx::Var,
                                            AccessPropertyOpts {
                                                disallow_indexing_array_with_string: true,
                                                disallow_creating_indexed_type_from_ty_els: true,
                                                disallow_inexact: true,
                                                ..Default::default()
                                            },
                                        )
                                        .ok()
                                })
                                .map(|ty| ty.generalize_lit())
                                .freezed();

                            let real_property_type = match prop_ty {
                                Ok(prop_ty) => {
                                    // TODO(kdy1): actual_ty
                                    self.add_vars(&prop.value, prop_ty.freezed(), None, default_prop_ty, opts)
                                        .report(&mut self.storage)
                                }

                                Err(err) => {
                                    match &*err {
                                        ErrorKind::NoSuchProperty { span, .. } | ErrorKind::NoSuchPropertyInClass { span, .. }
                                            if !should_use_no_such_property =>
                                        {
                                            if default_prop_ty.is_none() {
                                                self.storage.report(ErrorKind::NoInitAndNoDefault { span: *span }.into())
                                            }
                                        }
                                        _ => self.storage.report(err),
                                    }

                                    self.add_vars(&prop.value, None, None, default_prop_ty, opts)
                                        .report(&mut self.storage)
                                }
                            }
                            .flatten()
                            .map(|v| box v);

                            real = self.append_type_element(
                                real,
                                TypeElement::Property(PropertySignature {
                                    span,
                                    accessibility: None,
                                    readonly: false,
                                    key,
                                    optional: true,
                                    params: Vec::new(),
                                    type_ann: real_property_type,
                                    type_params: None,
                                    metadata: Default::default(),
                                    accessor: Default::default(),
                                }),
                            )?;
                        }
                        RObjectPatProp::Assign(prop) => {
                            let key = Key::Normal {
                                span: prop.key.span,
                                sym: prop.key.sym.clone(),
                            };
                            used_keys.push(key.clone());
                            let optional = default.is_some() || prop.value.is_some();

                            let ctx = Ctx {
                                disallow_unknown_object_property: true,
                                ..self.ctx
                            };

                            let prop_ty = ty.as_ref().try_map(|ty| {
                                self.with_ctx(ctx)
                                    .access_property(
                                        span,
                                        ty,
                                        &key,
                                        TypeOfMode::RValue,
                                        IdCtx::Var,
                                        AccessPropertyOpts {
                                            disallow_indexing_array_with_string: true,
                                            disallow_creating_indexed_type_from_ty_els: true,
                                            disallow_inexact: true,
                                            ..Default::default()
                                        },
                                    )
                                    .map(|ty| ty.generalize_lit())
                                    .context("tried to access property to declare variables")
                            });

                            let mut default_prop_ty = default
                                .as_ref()
                                .and_then(|ty| {
                                    self.with_ctx(ctx)
                                        .access_property(
                                            span,
                                            ty,
                                            &key,
                                            TypeOfMode::RValue,
                                            IdCtx::Var,
                                            AccessPropertyOpts {
                                                disallow_indexing_array_with_string: true,
                                                disallow_creating_indexed_type_from_ty_els: true,
                                                disallow_inexact: true,
                                                ..Default::default()
                                            },
                                        )
                                        .ok()
                                })
                                .map(|ty| ty.generalize_lit())
                                .freezed();

                            let real_property_type = match prop_ty {
                                Ok(mut prop_ty) => {
                                    if let Some(ty) = &mut prop_ty {
                                        add_destructure_sign(ty, destructure_key);
                                    }

                                    let prop_ty = prop_ty.map(Type::freezed);

                                    match &prop.value {
                                        Some(default) => {
                                            let mut default_value_type = default
                                                .validate_with_args(
                                                    self,
                                                    (TypeOfMode::RValue, None, prop_ty.as_ref().or(default_prop_ty.as_ref())),
                                                )
                                                .context("tried to validate default value of an assignment pattern")
                                                .report(&mut self.storage);

                                            if self.ctx.is_fn_param && prop_ty.is_none() {
                                                default_value_type = default_value_type.fold_with(&mut Widen { tuple_to_array: true });
                                            }

                                            default_value_type.freeze();

                                            let mut default = opt_union(span, default_prop_ty, default_value_type).freezed();
                                            // TODO(kdy1): Pass default when it's possible.
                                            if prop_ty.is_some() {
                                                default = None;
                                            }

                                            let result = self
                                                .add_vars(
                                                    &RPat::Ident(RBindingIdent {
                                                        node_id: NodeId::invalid(),
                                                        id: prop.key.clone(),
                                                        type_ann: None,
                                                    }),
                                                    prop_ty.clone(),
                                                    None,
                                                    default,
                                                    opts,
                                                )
                                                .report(&mut self.storage);

                                            if let Some(prop_ty) = &prop_ty {
                                                self.try_assign_pat(
                                                    span,
                                                    &RPat::Ident(RBindingIdent {
                                                        node_id: NodeId::invalid(),
                                                        id: prop.key.clone(),
                                                        type_ann: None,
                                                    }),
                                                    prop_ty,
                                                )
                                                .context("tried to assign default values")
                                                .report(&mut self.storage);
                                            }

                                            result
                                        }
                                        None => {
                                            // TODO(kdy1): actual_ty
                                            self.add_vars(
                                                &RPat::Ident(RBindingIdent {
                                                    node_id: NodeId::invalid(),
                                                    id: prop.key.clone(),
                                                    type_ann: None,
                                                }),
                                                prop_ty,
                                                None,
                                                default_prop_ty,
                                                opts,
                                            )
                                            .report(&mut self.storage)
                                        }
                                    }
                                }
                                Err(err) => {
                                    match &*err {
                                        ErrorKind::NoSuchProperty { span, .. } | ErrorKind::NoSuchPropertyInClass { span, .. }
                                            if !should_use_no_such_property =>
                                        {
                                            if default_prop_ty.is_none() {
                                                self.storage.report(ErrorKind::NoInitAndNoDefault { span: *span }.into())
                                            }
                                        }
                                        _ => self.storage.report(err),
                                    }

                                    if let Some(ty) = &mut default_prop_ty {
                                        add_destructure_sign(ty, destructure_key);
                                    }

                                    self.add_vars(
                                        &RPat::Ident(RBindingIdent {
                                            node_id: NodeId::invalid(),
                                            id: prop.key.clone(),
                                            type_ann: None,
                                        }),
                                        None,
                                        None,
                                        default_prop_ty,
                                        opts,
                                    )
                                    .report(&mut self.storage)
                                }
                            };

                            real = self.append_type_element(
                                real,
                                TypeElement::Property(PropertySignature {
                                    span,
                                    accessibility: None,
                                    readonly: false,
                                    key,
                                    optional,
                                    params: Vec::new(),
                                    type_ann: real_property_type.flatten().map(|v| box v),
                                    type_params: None,
                                    metadata: Default::default(),
                                    accessor: Default::default(),
                                }),
                            )?;
                        }
                        RObjectPatProp::Rest(pat) => {
                            if !is_last {
                                return Err(ErrorKind::RestPropertyNotLast { span: pat.span }.into());
                            }

                            let mut rest_ty = ty
                                .as_ref()
                                .try_map(|ty| {
                                    self.exclude_props(pat.span(), ty, &used_keys)
                                        .context("tried to exclude keys for assignment with a object rest pattern")
                                })?
                                .freezed();

                            let mut default = default
                                .as_ref()
                                .and_then(|ty| self.exclude_props(pat.span(), ty, &used_keys).ok())
                                .freezed();

                            if let Some(ty) = &mut rest_ty {
                                remove_readonly(ty);
                                add_destructure_sign(ty, destructure_key);
                            }

                            if let Some(ty) = &mut default {
                                remove_readonly(ty);
                            }

                            let rest = self
                                .add_vars(&pat.arg, rest_ty, None, default, opts)
                                .context("tried to assign to an object rest pattern")?;

                            if let Some(rest) = rest {
                                real.freeze();
                                real = self.append_type(span, real, rest, Default::default())?;
                            }
                            break;
                        }
                    }
                }

                Ok(Some(real))
            }

            RPat::Rest(pat) => {
                let ty = ty.map(|ty| self.ensure_iterable(span, ty)).transpose()?;
                let actual = actual.map(|ty| self.ensure_iterable(span, ty)).transpose()?;
                let default = default.map(|ty| self.ensure_iterable(span, ty)).transpose()?;

                self.add_vars(&pat.arg, ty, actual, default, DeclareVarsOpts { ..opts })
            }
            RPat::Invalid(..) | RPat::Expr(box RExpr::Invalid(..)) => Ok(None),

            _ => {
                unimplemented!("declare_vars({:#?}, {:#?})", pat, ty)
            }
        }
    }

    pub(crate) fn exclude_props(&mut self, span: Span, ty: &Type, keys: &[Key]) -> VResult<Type> {
        let _tracing = dev_span!("exclude_props");

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

        let ty = (|| -> VResult<_> {
            let mut ty = self.normalize(
                Some(span),
                Cow::Borrowed(ty),
                NormalizeTypeOpts {
                    preserve_mapped: false,
                    ..Default::default()
                },
            )?;
            ty.freeze();

            if ty.is_any() || ty.is_unknown() || ty.is_kwd(TsKeywordTypeKind::TsObjectKeyword) {
                return Ok(ty.into_owned());
            }

            match ty.normalize() {
                Type::TypeLit(lit) => {
                    let mut new_members = vec![];
                    'outer: for m in &lit.members {
                        if let Some(key) = m.key() {
                            for prop in keys {
                                if self.key_matches(span, key, prop, false) {
                                    continue 'outer;
                                }
                            }

                            new_members.push(m.clone());
                        }
                    }

                    return Ok(Type::TypeLit(TypeLit {
                        span: lit.span,
                        members: new_members,
                        metadata: lit.metadata,
                        tracker: Default::default(),
                    }));
                }

                Type::Union(u) => {
                    let types = u
                        .types
                        .iter()
                        .map(|ty| self.exclude_props(span, ty, keys))
                        .collect::<Result<_, _>>()?;

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

                Type::Intersection(..) | Type::Class(..) | Type::Interface(..) | Type::ClassDef(..) => {
                    let ty = self
                        .convert_type_to_type_lit(ty.span(), Cow::Borrowed(&ty))?
                        .map(Cow::into_owned)
                        .map(Type::TypeLit);
                    if let Some(ty) = ty {
                        return self.exclude_props(span, &ty, keys);
                    }
                }
                // TODO
                Type::Function(..) | Type::Constructor(..) => {
                    return Ok(Type::TypeLit(TypeLit {
                        span: ty.span(),
                        members: vec![],
                        metadata: Default::default(),
                        tracker: Default::default(),
                    }))
                }

                // Create Omit<T, 'foo' | 'bar'>
                Type::Param(..) => {
                    let key_types = keys
                        .iter()
                        .filter_map(|key| match key {
                            Key::BigInt(v) => Some(Type::Lit(LitType {
                                span: v.span.with_ctxt(SyntaxContext::empty()),
                                lit: RTsLit::BigInt(v.clone()),
                                metadata: Default::default(),
                                tracker: Default::default(),
                            })),
                            Key::Num(v) => Some(Type::Lit(LitType {
                                span: v.span.with_ctxt(SyntaxContext::empty()),
                                lit: RTsLit::Number(v.clone()),
                                metadata: Default::default(),
                                tracker: Default::default(),
                            })),
                            Key::Normal { span, sym } => Some(Type::Lit(LitType {
                                span: span.with_ctxt(SyntaxContext::empty()),
                                lit: RTsLit::Str(RStr {
                                    span: *span,
                                    value: sym.clone(),
                                    raw: None,
                                }),
                                metadata: Default::default(),
                                tracker: Default::default(),
                            })),

                            // TODO
                            _ => None,
                        })
                        .collect_vec();
                    if key_types.is_empty() {
                        return Ok(ty.into_owned());
                    }
                    let keys = Type::Union(Union {
                        span,
                        types: key_types,
                        metadata: Default::default(),
                        tracker: Default::default(),
                    });

                    return Ok(Type::Ref(Ref {
                        span,
                        type_name: RTsEntityName::Ident(RIdent::new("Omit".into(), DUMMY_SP)),
                        type_args: Some(box TypeParamInstantiation {
                            span,
                            params: vec![ty.clone().into_owned(), keys],
                        }),
                        metadata: Default::default(),
                        tracker: Default::default(),
                    }));
                }
                _ => {}
            }

            Err(ErrorKind::Unimplemented {
                span,
                msg: format!("exclude_props: {}", force_dump_type_as_string(&ty)),
            }
            .into())
        })()?;

        Ok(ty.fixed())
    }

    fn ensure_iterable(&mut self, span: Span, ty: Type) -> VResult<Type> {
        run(|| {
            if let Ok(..) = self.get_iterator(
                span,
                Cow::Borrowed(&ty),
                GetIteratorOpts {
                    disallow_str: true,
                    ..Default::default()
                },
            ) {
                return Ok(ty.freezed());
            }

            Ok(Type::Array(Array {
                span,
                elem_type: box ty,
                metadata: Default::default(),
                tracker: Default::default(),
            })
            .freezed())
        })
        .context("tried to ensure iterator")
    }

    pub fn regist_destructure(&mut self, span: Span, ty: Option<Type>, des_key: Option<DestructureId>) -> DestructureId {
        match ty.as_ref().map(Type::normalize) {
            Some(real @ Type::Union(..)) => {
                let des_key = des_key.unwrap_or_else(|| self.get_destructor_unique_key());
                let destructure_key = des_key;
                if let Ok(result) = self.declare_destructor(span, real, des_key) {
                    if result {
                        return destructure_key;
                    }
                }
            }
            Some(Type::Param(TypeParam {
                constraint: Some(box result),
                ..
            })) => {
                if let Ok(result) = self.normalize(Some(span), Cow::Borrowed(result), Default::default()) {
                    return self.regist_destructure(span, Some(result.into_owned()), des_key);
                }
            }

            Some(Type::Instance(Instance { ty: box result, .. })) => {
                if let Ok(result) = self.normalize(Some(span), Cow::Borrowed(result), Default::default()) {
                    return self.regist_destructure(span, Some(result.into_owned()), des_key);
                }
            }

            Some(Type::Tuple(Tuple { elems, .. })) => {
                if elems.len() == 1 {
                    if let Some(TupleElement { ty: box ty, .. }) = elems.first() {
                        return self.regist_destructure(span, Some(ty.clone()), des_key);
                    }
                }
            }

            Some(Type::Rest(RestType { ty: box ty, .. })) => {
                return self.regist_destructure(span, Some(ty.clone()), des_key);
            }
            _ => {}
        }
        DestructureId(0)
    }
}

fn remove_readonly(ty: &mut Type) {
    if let Some(tl) = ty.as_type_lit_mut() {
        for m in &mut tl.members {
            if let TypeElement::Property(p) = m {
                p.readonly = false;
            }
        }

        ty.freeze();
    }
}

fn add_destructure_sign(ty: &mut Type, key: DestructureId) {
    ty.metadata_mut().destructure_key = key;
    ty.freeze();
}