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
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
use std::{borrow::Cow, cmp::min, collections::hash_map::Entry, mem::take, time::Instant};

use fxhash::{FxHashMap, FxHashSet};
use itertools::{EitherOrBoth, Itertools};
use rnode::{Fold, FoldWith, VisitMut, VisitMutWith, VisitWith};
use stc_ts_ast_rnode::{RBindingIdent, RIdent, RNumber, RPat, RTsEntityName};
use stc_ts_errors::{
    debug::{dump_type_as_string, force_dump_type_as_string, print_backtrace, print_type},
    DebugExt,
};
use stc_ts_generics::{
    expander::InferTypeResult,
    type_param::{finder::TypeParamUsageFinder, remover::TypeParamRemover, renamer::TypeParamRenamer},
};
use stc_ts_type_ops::{generalization::prevent_generalize, Fix};
use stc_ts_types::{
    replace::replace_type, Array, ClassMember, FnParam, Function, Id, IdCtx, Index, IndexSignature, IndexedAccessType, Intersection, Key,
    KeywordType, KeywordTypeMetadata, Mapped, OptionalType, PropertySignature, Readonly, Ref, Tuple, TupleElement, TupleMetadata, Type,
    TypeElement, TypeLit, TypeOrSpread, TypeParam, TypeParamDecl, TypeParamInstantiation, TypeParamMetadata, Union, UnionMetadata,
};
use stc_ts_utils::MapWithMut;
use stc_utils::{
    cache::{Freeze, ALLOW_DEEP_CLONE},
    dev_span, stack,
};
use swc_atoms::js_word;
use swc_common::{EqIgnoreSpan, Span, Spanned, SyntaxContext, TypeEq, DUMMY_SP};
use swc_ecma_ast::*;
use tracing::{debug, error, info, trace, warn};

use self::inference::{InferenceInfo, InferencePriority};
pub(crate) use self::{expander::ExtendsOpts, inference::InferTypeOpts};
use super::{
    assign::get_tuple_subtract_count,
    expr::{AccessPropertyOpts, TypeOfMode},
};
use crate::{
    analyzer::{scope::ExpandOpts, Analyzer, Ctx, NormalizeTypeOpts},
    util::{unwrap_builtin_with_single_arg, RemoveTypes},
    VResult,
};

mod expander;
mod inference;
#[cfg(test)]
mod tests;

#[derive(Debug)]
pub(super) struct InferData {
    /// Inferred type parameters
    type_params: FxHashMap<Id, InferenceInfo>,

    errored: FxHashSet<Id>,

    /// For the code below, we can know that `T` defaults to `unknown` while
    /// inferring type of function parameters. We cannot know the type before
    /// it. So we store the default type while it.
    ///
    /// ```ts
    /// declare function one<T>(handler: (t: T) => void): T
    ///
    /// var empty = one(() => {
    /// });
    /// ```
    defaults: FxHashMap<Id, Type>,

    dejavu: Vec<(Type, Type)>,

    skip_generalization: bool,

    priority: InferencePriority,

    contravariant: bool,
}

impl Default for InferData {
    fn default() -> Self {
        Self {
            type_params: Default::default(),
            defaults: Default::default(),
            errored: Default::default(),
            dejavu: Default::default(),
            skip_generalization: Default::default(),
            priority: InferencePriority::MaxValue,
            contravariant: Default::default(),
        }
    }
}

/// Type inference for arguments.
impl Analyzer<'_, '_> {
    /// This method accepts Option<&[TypeParamInstantiation]> because user may
    /// provide only some of type arguments.
    pub(super) fn infer_arg_types(
        &mut self,
        span: Span,
        base: Option<&TypeParamInstantiation>,
        type_params: &[TypeParam],
        params: &[FnParam],
        args: &[TypeOrSpread],
        default_ty: Option<&Type>,
        ret_ty: Option<&Type>,
        ret_ty_type_ann: Option<&Type>,
        opts: InferTypeOpts,
    ) -> VResult<InferTypeResult> {
        #[cfg(debug_assertions)]
        let _tracing = dev_span!("infer_arg_types");

        warn!(
            "infer_arg_types: {:?}",
            type_params.iter().map(|p| format!("{}, ", p.name)).collect::<String>()
        );

        let start = Instant::now();

        let mut inferred = InferData::default();

        if let Some(base) = base {
            for (param, type_param) in base.params.iter().zip(type_params) {
                info!("User provided `{:?} = {:?}`", type_param.name, param.clone());
                inferred.type_params.insert(
                    type_param.name.clone(),
                    InferenceInfo {
                        type_param: type_param.name.clone(),
                        candidates: Default::default(),
                        contra_candidates: Default::default(),
                        inferred_type: param.clone().freezed(),
                        priority: Default::default(),
                        top_level: Default::default(),
                        is_fixed: true,
                        implied_arity: Default::default(),
                        rest_index: Default::default(),
                    },
                );
            }
        }

        // We allocate a new vector only if required.
        let mut actual_args;
        let args = if args.iter().any(|arg| arg.spread.is_some()) {
            actual_args = vec![];
            for arg in args {
                if arg.spread.is_some() {
                    match arg.ty.normalize_instance() {
                        Type::Tuple(Tuple { elems, .. }) => {
                            actual_args.extend(elems.iter().map(|elem| TypeOrSpread {
                                span: arg.spread.unwrap(),
                                spread: None,
                                ty: elem.ty.clone(),
                            }));
                        }
                        _ => {
                            actual_args.push(arg.clone());
                        }
                    }
                } else {
                    actual_args.push(arg.clone());
                }
            }
            &*actual_args
        } else {
            args
        };

        let skip = if params.is_empty() {
            0
        } else {
            match &params[0].pat {
                RPat::Ident(RBindingIdent {
                    id: RIdent { sym: js_word!("this"), .. },
                    ..
                }) => 1,
                _ => 0,
            }
        };

        for (idx, p) in params.iter().skip(skip).enumerate() {
            let is_rest = matches!(&p.pat, RPat::Rest(_));
            let opts = InferTypeOpts {
                rest_type_index: Some(idx),
                ..opts
            };

            if !is_rest {
                if let Some(arg) = args.get(idx) {
                    self.infer_type(span, &mut inferred, &p.ty, &arg.ty, opts)?;
                }
            } else {
                let stop_idx = args
                    .iter()
                    .skip(idx)
                    .position(|arg| arg.spread.is_some())
                    .map(|v| v + idx)
                    .unwrap_or({
                        // No spread means all arguments are used.
                        args.len()
                    });

                match p.ty.normalize_instance() {
                    Type::Param(param) => {
                        self.infer_type(
                            span,
                            &mut inferred,
                            &p.ty,
                            &Type::Tuple(Tuple {
                                span: p.ty.span(),
                                elems: args[idx..stop_idx]
                                    .iter()
                                    .map(|arg| &arg.ty)
                                    .cloned()
                                    .map(|ty| TupleElement {
                                        span: DUMMY_SP,
                                        label: None,
                                        ty,
                                        tracker: Default::default(),
                                    })
                                    .collect(),
                                metadata: TupleMetadata {
                                    common: p.ty.metadata(),
                                    ..Default::default()
                                },
                                tracker: Default::default(),
                            })
                            .freezed(),
                            opts,
                        )?;
                    }
                    Type::Array(p_ty) => {
                        // Handle varargs. This result in union of all types.
                        for arg in &args[idx..stop_idx] {
                            self.infer_type(span, &mut inferred, &p_ty.elem_type, &arg.ty, opts)?;
                        }
                        if let Some(arg) = args.get(stop_idx) {
                            self.infer_type(span, &mut inferred, &p_ty.elem_type, &arg.ty, opts)?;
                        }
                    }
                    _ => {
                        // Handle varargs
                        for arg in &args[idx..stop_idx] {
                            self.infer_type(span, &mut inferred, &p.ty, &arg.ty, opts)?;
                        }
                    }
                }
            }
        }

        if let Some(ret_ty) = ret_ty {
            if let Some(ret_type_ann) = ret_ty_type_ann {
                let _tracing = dev_span!("infer_arg_types: return type annotation");

                self.infer_type(
                    span,
                    &mut inferred,
                    ret_ty,
                    ret_type_ann,
                    InferTypeOpts {
                        priority: InferencePriority::ReturnType,
                        ..Default::default()
                    },
                )?;
            }
        }

        info!("infer_type is finished:\n{:?}", &inferred.type_params);

        // Defaults
        for type_param in type_params {
            if inferred.type_params.contains_key(&type_param.name) {
                continue;
            }

            if let Some(Type::Param(ref p)) = type_param.constraint.as_deref().map(Type::normalize) {
                // TODO(kdy1): Handle complex inheritance like
                //      function foo<A extends B, B extends C>(){ }

                if let Some(actual) = inferred.type_params.remove(&p.name) {
                    info!(
                        "infer_arg_type: {} => {} => {:?} because of the extends clause",
                        type_param.name, p.name, actual
                    );
                    inferred.type_params.insert(p.name.clone(), actual.clone());
                    inferred.type_params.insert(type_param.name.clone(), actual);
                } else {
                    info!("infer_arg_type: {} => {} because of the extends clause", type_param.name, p.name);
                    self.insert_inferred(span, &mut inferred, type_param, Cow::Owned(Type::Param(p.clone())), opts)?;
                }
                continue;
            }

            if type_param.constraint.is_some() && is_literals(type_param.constraint.as_ref().unwrap()) {
                self.insert_inferred(
                    span,
                    &mut inferred,
                    type_param,
                    Cow::Borrowed(type_param.constraint.as_deref().unwrap()),
                    opts,
                )?;
                continue;
            }

            if matches!(
                type_param.constraint.as_deref().map(Type::normalize),
                Some(Type::Interface(..) | Type::Keyword(..) | Type::Ref(..) | Type::TypeLit(..))
            ) {
                let ty = self
                    .expand(
                        span,
                        *type_param.constraint.clone().unwrap(),
                        ExpandOpts {
                            full: true,
                            expand_union: false,
                            ..Default::default()
                        },
                    )?
                    .freezed();
                if !inferred.type_params.contains_key(&type_param.name) {
                    self.insert_inferred(span, &mut inferred, type_param, Cow::Owned(ty), opts)?;
                }
                continue;
            }
            if !inferred.type_params.contains_key(&type_param.name) {
                if let Some(default_ty) = inferred.defaults.remove(&type_param.name) {
                    self.insert_inferred(span, &mut inferred, type_param, Cow::Owned(default_ty), opts)?;
                } else {
                    if let Some(default) = &type_param.default {
                        self.insert_inferred(span, &mut inferred, type_param, Cow::Borrowed(default), opts)?;
                        continue;
                    }

                    if let Some(default_ty) = default_ty {
                        error!("infer: A type parameter {} defaults to {:?}", type_param.name, default_ty);

                        self.insert_inferred(span, &mut inferred, type_param, Cow::Borrowed(default_ty), opts)?;
                    }
                }
            }
        }

        self.prevent_generalization_of_top_level_types(type_params, ret_ty, &mut inferred, opts.is_type_ann);

        self.prevent_generalization_of_inferred_types(type_params, &mut inferred, opts.is_type_ann);

        let map = self.finalize_inference(span, type_params, inferred);

        let end = Instant::now();

        warn!("infer_arg_types is finished. (time = {:?})", end - start);

        Ok(map)
    }

    /// Handles `infer U`.
    pub(super) fn infer_ts_infer_types(
        &mut self,
        span: Span,
        base: &Type,
        concrete: &Type,
        opts: InferTypeOpts,
    ) -> VResult<FxHashMap<Id, Type>> {
        let _tracing = dev_span!("infer_ts_infer_types");

        let mut inferred = InferData::default();
        self.infer_type(span, &mut inferred, base, concrete, opts)?;
        let mut map = self.finalize_inference(span, &[], inferred);

        for ty in map.types.values_mut() {
            prevent_generalize(ty);
        }

        Ok(map.types)
    }

    /// # Inference rule
    ///
    /// 1. We iterate over parameters and arguments in order.
    ///
    /// 2. If newly inferred type is not compatible with the previous one, we
    /// don't store it. `compatible` here means the previous type is
    /// assignable to the newly inferred type.
    ///
    /// 3. If there's `any` or `unknown`, those are used because all types are
    /// `compatible` with them.
    ///
    /// If `any` and `unknown` co-exist, the last one is selected.
    ///
    /// 4. `{}` and an empty interface work just like `any` or `unknown`. It's
    /// because almost all types are `compatible` with it, so the same rule
    /// applies. But `any` or `unknown` is preferred over `{}`.
    ///
    /// 5. If a parameter of a closure has an explicit type, the `compatibility`
    /// rule applies. But some types like the built-in `Object`  are exceptions
    /// and those are ignored. i.e. The inferred types are not changed to
    /// `Object`.
    ///
    /// 6. The return type of a closure does not have effect on the inference,
    /// iff it's a direct function expression.
    ///
    ///
    /// # Postprocess
    ///
    /// 1. If there was noe error and if there's no constraints like `extends
    /// string` nor `extends number`, the inferred types are generalized.
    ///
    /// ---
    ///
    /// ```ts
    /// function foo<T>(x: { bar: T; baz: T }) {
    ///     return x;
    /// }
    ///
    /// declare function fn1(): void;
    /// declare function f2(): string;
    ///
    /// declare class C1 {
    ///     prop: string
    /// }
    ///
    /// declare class C2 {
    ///     c2prop: number
    /// }
    ///
    /// interface I1 {
    ///     s: string
    /// }
    ///
    /// declare const us: unique symbol
    /// declare var i1: I1
    ///
    /// declare var c1: C1
    /// declare var c2: C2
    ///
    ///
    /// declare var n: number
    ///
    /// foo({ bar: 1, baz: '' }); // Error on baz (number is selected)
    /// foo({ bar: '', baz: 1 }); // Error on baz (string is selected)
    /// foo({ bar: '', baz: n }); // Error on baz (string is selected)
    /// foo({ bar: Symbol.iterator, baz: 5 }) // Error on baz (symbol is selected)
    /// foo({ bar: us, baz: 5 }) // Error on baz (unique symbol is selected)
    ///
    ///
    /// foo({ bar: [], baz: '' }); // Error on bar (string is selected)
    /// foo({ bar: {}, baz: '' }); // Error on bar (string is selected)
    ///
    /// declare var u: string | number
    /// foo({ bar: 1, baz: u }) // Ok
    /// foo({ bar: {}, baz: u }) // Error on bar (string | number is selected)
    ///
    /// foo({ bar: i1, baz: 5 }) // Error on baz (I1 is selected)
    /// foo({ bar: 5, baz: i1 }) // Error on baz (number is selected)
    ///
    ///
    /// foo({ bar: 5, baz: fn1 }) // Error on baz (number is selected)
    /// foo({ bar: 5, baz: i1 }) // Error on baz (number is selected)
    ///
    /// foo({ bar: 1, baz: c2 }) // Error on baz (number is selected)
    /// foo({ bar: c1, baz: 1 }) // Error on baz (C1 is selected)
    /// foo({ bar: c1, baz: c2 }) // Error on baz (C1 is selected)
    /// foo({ bar: i1, baz: c1 }) // Error on baz (I1 is selected)
    /// foo({ bar: c1, baz: i1 }) // Error on baz (C1 is selected)
    ///
    ///
    /// function arr<T>(x: T[]) {
    ///     return x;
    /// }
    ///
    /// arr([1, '']); // Ok
    /// arr(['', 1]); // Ok
    /// arr([Symbol.iterator, 5]) // Ok
    /// arr([us, 5]) // Ok
    ///
    ///
    /// arr([[], '']); // Ok
    /// arr([{}, '']); // Ok
    ///
    /// arr([1, u]) // Ok
    /// arr([{}, u]) // Ok
    /// ```
    fn infer_type(&mut self, span: Span, inferred: &mut InferData, param: &Type, arg: &Type, opts: InferTypeOpts) -> VResult<()> {
        if self.config.is_builtin {
            return Ok(());
        }

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

        let _tracing = if cfg!(debug_assertions) {
            let param_str = force_dump_type_as_string(param);
            let arg_str = force_dump_type_as_string(arg);

            Some(dev_span!("infer_type", param = &*param_str, arg = &*arg_str))
        } else {
            None
        };

        debug!("Start");

        let res = self.infer_type_inner(span, inferred, param, arg, opts);

        debug!("End");

        res
    }

    /// Infer types, so that `param` has same type as `arg`.
    ///
    ///
    /// TODO(kdy1): Optimize
    fn infer_type_inner(&mut self, span: Span, inferred: &mut InferData, param: &Type, arg: &Type, mut opts: InferTypeOpts) -> VResult<()> {
        if self.config.is_builtin {
            return Ok(());
        }

        let marks = self.marks();

        let _stack = match stack::track(span) {
            Ok(v) => v,
            Err(_) => return Ok(()),
        };

        if !opts.skip_initial_union_check {
            if inferred
                .dejavu
                .iter()
                .any(|(prev_param, prev_arg)| prev_param.type_eq(param) && prev_arg.type_eq(arg))
            {
                return Ok(());
            }
            inferred.dejavu.push((param.clone(), arg.clone()));
        }

        debug_assert!(!span.is_dummy(), "infer_type: `span` should not be dummy");

        if param.is_keyword() || param.type_eq(arg) {
            return Ok(());
        }

        let param_normalized = param.normalize();
        let arg_normalized = arg.normalize();

        param.assert_clone_cheap();
        arg.assert_clone_cheap();

        /// Returns true if we can unconditionally delegate to `infer_type`.
        fn should_delegate(ty: &Type) -> bool {
            match ty.normalize() {
                Type::Instance(..) => true,
                Type::IndexedAccessType(t) => matches!(t.index_type.normalize(), Type::Lit(..)),
                _ => false,
            }
        }

        if should_delegate(param_normalized) {
            let mut param = self.normalize(Some(span), Cow::Borrowed(param_normalized), Default::default())?;
            param.freeze();
            return self.infer_type(span, inferred, &param, arg, opts);
        }

        if should_delegate(arg_normalized) {
            let mut arg = self.normalize(Some(span), Cow::Borrowed(arg_normalized), Default::default())?;
            arg.freeze();

            return self.infer_type(span, inferred, param, &arg, opts);
        }

        let p;
        let param = match param.normalize() {
            Type::Mapped(..) => {
                // TODO(kdy1): PERF
                p = box param_normalized
                    .clone()
                    .foldable()
                    .fold_with(&mut MappedIndexedSimplifier)
                    .freezed();
                &p
            }
            _ => param,
        };
        let param_normalized = param.normalize();

        {
            // Handle array-like types
            let opts = InferTypeOpts {
                append_type_as_union: true,
                ..opts
            };

            if let (Some(p), Some(a)) = (array_elem_type(param_normalized), array_elem_type(arg_normalized)) {
                return self.infer_type(span, inferred, p, a, opts);
            }
        }

        match (param_normalized.normalize(), arg.normalize()) {
            (Type::Union(p), _) => {
                if !opts.skip_initial_union_check {
                    self.infer_type_using_union(
                        span,
                        inferred,
                        p,
                        arg,
                        InferTypeOpts {
                            append_type_as_union: true,
                            ..opts
                        },
                    )?;

                    return Ok(());
                } else {
                    opts.skip_initial_union_check = false;
                }
            }

            (Type::Intersection(param), _) => {
                for param in &param.types {
                    self.infer_type(span, inferred, param, arg, opts)?;
                }

                return Ok(());
            }

            _ => {}
        }

        let p = param_normalized;
        let a = arg_normalized;

        if let Some(res) = self.infer_builtin(span, inferred, param, arg, opts) {
            return res;
        }

        if self.infer_type_by_converting_to_type_lit(span, inferred, param, arg, opts)? {
            return Ok(());
        }

        if opts.for_fn_assignment {
            if let Type::Param(arg) = arg_normalized.normalize() {
                if !param_normalized.is_type_param() {
                    self.insert_inferred(span, inferred, arg, Cow::Borrowed(param), opts)?;
                    return Ok(());
                }
            }
        }

        match (param.normalize(), arg.normalize()) {
            (_, Type::Enum(..)) => {
                let arg = self
                    .normalize(
                        Some(arg_normalized.span()),
                        Cow::Borrowed(arg),
                        NormalizeTypeOpts {
                            expand_enum_def: true,
                            preserve_global_this: true,
                            ..Default::default()
                        },
                    )
                    .context("tried to normalize enum")?
                    .freezed()
                    .into_owned()
                    .freezed();
                return self.infer_type_inner(span, inferred, param, &arg, opts);
            }

            (Type::Index(Index { ty: param, .. }), Type::Index(Index { ty: arg, .. })) => {
                return self.infer_from_contravariant_types(span, inferred, arg, param, opts)
            }

            (Type::Conditional(target), Type::Conditional(source)) => {
                self.infer_from_types(span, inferred, &source.check_type, &target.check_type, opts)?;
                self.infer_from_types(span, inferred, &source.extends_type, &target.extends_type, opts)?;
                self.infer_from_types(span, inferred, &source.true_type, &target.true_type, opts)?;
                self.infer_from_types(span, inferred, &source.false_type, &target.false_type, opts)?;

                return Ok(());
            }
            (Type::Conditional(target), ..) => {
                return self.infer_to_multiple_types_with_priority(
                    span,
                    inferred,
                    arg,
                    &[*target.true_type.clone(), *target.false_type.clone()],
                    if inferred.contravariant {
                        InferencePriority::ContravariantConditional
                    } else {
                        InferencePriority::None
                    },
                    false,
                    opts,
                )
            }

            (Type::Tpl(target), _) => {
                return self.infer_to_tpl_lit_type(span, inferred, arg, target, opts);
            }

            _ => {}
        }

        match param_normalized.normalize() {
            Type::Param(TypeParam {
                ref name, ref constraint, ..
            }) => {
                let constraint = constraint.as_ref().map(|ty| ty.normalize());
                if !opts.for_fn_assignment && !self.ctx.skip_identical_while_inference {
                    if let Some(prev) = inferred.type_params.get(name).cloned() {
                        let ctx = Ctx {
                            skip_identical_while_inference: true,
                            ..self.ctx
                        };
                        prev.inferred_type.assert_clone_cheap();

                        self.with_ctx(ctx).infer_type(span, inferred, &prev.inferred_type, arg, opts)?;
                        self.with_ctx(ctx).infer_type(span, inferred, arg, &prev.inferred_type, opts)?;
                    }
                }

                trace!("infer_type: type parameter: {} = {:?}", name, constraint);

                if constraint.is_some() && is_literals(constraint.as_ref().unwrap()) {
                    info!("infer from literal constraint: {} = {:?}", name, constraint);
                    if let Some(orig) = inferred.type_params.get(name) {
                        if !orig.inferred_type.eq_ignore_span(constraint.as_ref().unwrap()) {
                            print_backtrace();
                            unreachable!(
                                "Cannot override T in `T extends <literal>`\nOrig: {:?}\nConstraints: {:?}",
                                orig, constraint
                            )
                        }
                    }

                    return Ok(());
                }

                if let Some(constraint) = constraint {
                    if constraint.is_str() || constraint.is_num() {
                        match arg.normalize() {
                            // We use `default`
                            Type::TypeLit(..) | Type::Interface(..) | Type::Class(..) => return Ok(()),
                            _ => {}
                        }
                    }

                    // TODO(kdy1): Infer only if constraints are matched
                    //
                    // if let Some(false) = self.extends(span, ExtendsOpts {
                    // ..Default::default() }, arg, constraint) {
                    //     return Ok(());
                    // }
                }

                if self.ctx.skip_identical_while_inference {
                    if let Type::Param(arg) = arg_normalized {
                        if *name == arg.name {
                            return Ok(());
                        }
                    }
                }

                if arg_normalized.is_any() && self.is_implicitly_typed(arg_normalized) {
                    if inferred.type_params.contains_key(&name.clone()) {
                        return Ok(());
                    }

                    match inferred.defaults.entry(name.clone()) {
                        Entry::Occupied(..) => {}
                        Entry::Vacant(e) => {
                            e.insert(Type::Param(TypeParam {
                                span: arg_normalized.span(),
                                name: name.clone(),
                                constraint: None,
                                default: None,
                                metadata: TypeParamMetadata {
                                    common: arg_normalized.metadata(),
                                    ..Default::default()
                                },
                                tracker: Default::default(),
                            }));
                        }
                    }

                    //
                    return Ok(());
                }

                debug!(
                    "({}): Inferred `{}` as {}",
                    self.scope.depth(),
                    name,
                    dump_type_as_string(arg_normalized)
                );

                self.upsert_inferred(span, inferred, name.clone(), arg, opts)?;

                return Ok(());
            }

            Type::Interface(param) => match arg.normalize() {
                Type::Interface(..) => self.infer_type_using_interface(span, inferred, param, arg, opts)?,
                Type::TypeLit(..) | Type::Tuple(..) => return self.infer_type_using_interface(span, inferred, param, arg, opts),
                _ => {}
            },

            Type::Infer(param) => {
                self.insert_inferred(span, inferred, &param.type_param, Cow::Borrowed(arg), opts)?;
                return Ok(());
            }

            Type::Array(param_arr @ Array { .. }) => {
                let opts = InferTypeOpts {
                    append_type_as_union: true,
                    ..opts
                };

                match arg_normalized {
                    Type::Array(Array {
                        elem_type: arg_elem_type, ..
                    }) => return self.infer_type(span, inferred, &param_arr.elem_type, arg_elem_type, opts),

                    Type::Tuple(arg) => {
                        let arg = Type::new_union(span, arg.elems.iter().map(|element| *element.ty.clone())).freezed();
                        return self.infer_type(span, inferred, &param_arr.elem_type, &arg, opts);
                    }

                    _ => {}
                }
            }

            // // TODO(kdy1): Check if index type extends `keyof obj_type`
            // Type::IndexedAccessType(IndexedAccessType {
            //     obj_type: box Type::Param(param_obj),
            //     index_type:
            //         box Type::Param(TypeParam {
            //             constraint: Some(..),
            //             ..
            //         }),
            //     ..
            // }) => {
            //     match inferred.type_elements.entry(param_obj.name.clone()) {
            //         Entry::Occupied(mut e) => {
            //             let (name, prev_ty) = e.remove_entry();
            //
            //             inferred
            //                 .type_elements
            //                 .insert(name, Type::new_union(span, vec![prev_ty, box arg.clone()]))
            //                 .expect_none("Cannot override");
            //         }
            //         Entry::Vacant(e) => {
            //             e.insert(box arg.clone());
            //         }
            //     }
            //     return Ok(());
            // }
            Type::Function(p) => match arg_normalized {
                Type::Function(a) => {
                    self.infer_type_of_fn_params(
                        span,
                        inferred,
                        &p.params,
                        &a.params,
                        InferTypeOpts {
                            ignore_builtin_object_interface: true,
                            ..opts
                        },
                    )?;
                    self.infer_type(
                        span,
                        inferred,
                        &p.ret_ty,
                        &a.ret_ty,
                        InferTypeOpts {
                            ignore_builtin_object_interface: true,
                            ..opts
                        },
                    )?;

                    if !opts.for_fn_assignment {
                        if let Some(arg_type_params) = &a.type_params {
                            let mut data = InferData {
                                dejavu: inferred.dejavu.clone(),
                                ..Default::default()
                            };
                            self.infer_type_of_fn_params(span, &mut data, &a.params, &p.params, InferTypeOpts { use_error: true, ..opts })?;

                            for name in data.errored {
                                if !inferred.type_params.contains_key(&name) {
                                    inferred.errored.insert(name);
                                }
                            }

                            for (name, ty) in data.type_params {
                                inferred.type_params.entry(name).or_insert(ty);
                            }
                        }
                    }

                    if let Some(arg_type_params) = &a.type_params {
                        self.rename_inferred(span, inferred, arg_type_params)?;
                    }
                    return Ok(());
                }
                _ => {
                    dbg!();
                }
            },

            Type::TypeLit(param) => match arg_normalized {
                Type::TypeLit(arg) => return self.infer_type_using_type_lit_and_type_lit(span, inferred, param, arg, opts),

                Type::IndexedAccessType(arg_iat) => {
                    let arg_obj_ty = self.expand(
                        arg_iat.span,
                        *arg_iat.obj_type.clone(),
                        ExpandOpts {
                            full: true,
                            expand_union: true,
                            ..Default::default()
                        },
                    )?;

                    if let Some(arg_obj_ty) = arg_obj_ty.mapped() {
                        if let TypeParam {
                            constraint:
                                Some(box Type::Index(Index {
                                    ty: box Type::Param(param_ty),
                                    ..
                                })),
                            ..
                        } = &arg_obj_ty.type_param
                        {
                            let mut new_lit = TypeLit {
                                span: arg_iat.span,
                                members: vec![],
                                metadata: Default::default(),
                                tracker: Default::default(),
                            };
                            for member in &param.members {
                                match member {
                                    TypeElement::Property(p) => {
                                        let p = p.clone();
                                        if let Some(type_ann) = &p.type_ann {
                                            // TODO(kdy1): Change p.ty

                                            self.infer_type(span, inferred, type_ann, arg, opts)?;
                                        }

                                        new_lit.members.push(TypeElement::Property(p));
                                    }
                                    // TODO(kdy1): Handle IndexSignature
                                    _ => {
                                        unimplemented!("calculating IndexAccessType for member other than property: member = {:?}", member)
                                    }
                                }
                            }
                            self.insert_inferred(span, inferred, param_ty, Cow::Owned(Type::TypeLit(new_lit)), opts)?;

                            return Ok(());
                        }
                    }
                }

                Type::Interface(..) | Type::Alias(..) => {
                    if let Some(arg) = self.convert_type_to_type_lit(span, Cow::Borrowed(arg))? {
                        return self.infer_type_using_type_lit_and_type_lit(span, inferred, param, &arg, opts);
                    }
                }

                _ => {}
            },

            Type::Tuple(param) => match arg_normalized {
                Type::Array(arg) => {
                    for elem in &param.elems {
                        match elem.ty.normalize() {
                            Type::Rest(rest) => {
                                self.infer_type(span, inferred, &rest.ty, &arg.elem_type, opts)?;
                            }
                            _ => {
                                self.infer_type(span, inferred, &elem.ty, &arg.elem_type, opts)?;
                            }
                        }
                    }
                }
                Type::Tuple(arg) => return self.infer_type_using_tuple_and_tuple(span, inferred, param, p, arg, a, opts),
                _ => {
                    dbg!();
                }
            },

            Type::Keyword(..) => {
                if let Type::Keyword(..) = arg_normalized {
                    return Ok(());
                }

                dbg!();
            }

            Type::Predicate(..) => {
                dbg!();
            }

            Type::Rest(param_rest) => {
                if let Type::Rest(arg_rest) = arg_normalized {
                    return self.infer_type(span, inferred, &param_rest.ty, &arg_rest.ty, opts);
                }

                return self.infer_type(
                    span,
                    inferred,
                    &param_rest.ty,
                    &Type::Tuple(Tuple {
                        span,
                        elems: vec![TupleElement {
                            span,
                            label: None,
                            ty: box arg.clone(),
                            tracker: Default::default(),
                        }],
                        metadata: Default::default(),
                        tracker: Default::default(),
                    })
                    .freezed(),
                    InferTypeOpts {
                        is_inferring_rest_type: true,
                        append_type_as_union: true,
                        ..opts
                    },
                );
            }

            Type::Ref(param) => match arg_normalized {
                Type::Ref(arg)
                    if param.type_name.eq_ignore_span(&arg.type_name)
                        && param.type_args.as_ref().map(|v| v.params.len()) == arg.type_args.as_ref().map(|v| v.params.len()) =>
                {
                    if param.type_args.is_none() && arg.type_args.is_none() {
                        return Ok(());
                    }
                    if param.type_args.is_none() || arg.type_args.is_none() {
                        unimplemented!("Comparing `Ref<T>` (with type args) and `Ref` (without type args)");
                    }

                    for pa in param
                        .type_args
                        .as_ref()
                        .unwrap()
                        .params
                        .iter()
                        .zip_longest(arg.type_args.as_ref().unwrap().params.iter())
                    {
                        match pa {
                            EitherOrBoth::Both(param, arg) => {
                                self.infer_type(span, inferred, param, arg, opts)?;
                            }
                            _ => {
                                unreachable!("type inference: Comparison of Ref<Arg1, Arg2> and Ref<Arg1> (different length)");
                            }
                        }
                    }
                    return Ok(());
                }
                // Type::Param(arg) => match &param.type_name {
                //     RTsEntityName::TsQualifiedName(_) => {}
                //     RTsEntityName::Ident(param) => {
                //         inferred
                //             .type_params
                //             .insert(param.clone().into(), box Type::Param(arg.clone()));
                //         return Ok(());
                //     }
                // },
                _ => {
                    // TODO(kdy1): Expand children first or add expansion information to inferred.
                    if cfg!(debug_assertions) {
                        debug!("infer_type: expanding param");
                    }
                    let mut param = self.expand(
                        span,
                        Type::Ref(param.clone()),
                        ExpandOpts {
                            full: true,
                            expand_union: true,
                            preserve_ref: false,
                            ignore_expand_prevention_for_top: true,
                            ignore_expand_prevention_for_all: false,
                            ..Default::default()
                        },
                    )?;
                    param.freeze();
                    match param.normalize() {
                        Type::Ref(..) => {
                            dbg!();

                            info!("Ref: {:?}", param);
                        }
                        _ => return self.infer_type(span, inferred, &param, arg, opts),
                    }
                }
            },

            Type::Lit(..) => {
                if let Type::Lit(..) = arg_normalized {
                    return Ok(());
                }
            }

            Type::Alias(param) => {
                self.infer_type(span, inferred, &param.ty, arg, opts)?;
                if let Some(type_params) = &param.type_params {
                    self.rename_inferred(span, inferred, type_params)?;
                }
                return Ok(());
            }

            Type::Mapped(param) => {
                if self.infer_type_using_mapped_type(span, inferred, param, arg, opts)? {
                    dbg!();
                    return Ok(());
                }
            }

            Type::IndexedAccessType(param) => {
                if let Type::IndexedAccessType(arg) = arg_normalized {
                    if param.obj_type.eq_ignore_span(&arg.obj_type) {
                        self.infer_type(span, inferred, &param.index_type, &arg.index_type, opts)?;
                        return Ok(());
                    }
                }

                match param {
                    IndexedAccessType {
                        obj_type: box Type::Param(obj_type),
                        ..
                    } if self.mapped_type_param_name.contains(&obj_type.name) => {
                        self.insert_inferred(span, inferred, obj_type, Cow::Borrowed(arg), opts)?;
                        return Ok(());
                    }

                    IndexedAccessType {
                        obj_type: box Type::Intersection(Intersection { types, .. }),
                        ..
                    } if types.iter().all(|ty| match ty.normalize() {
                        Type::Param(obj_type) => self.mapped_type_param_name.contains(&obj_type.name),
                        _ => false,
                    }) =>
                    {
                        for ty in types {
                            if let Type::Param(obj_type) = ty.normalize() {
                                self.insert_inferred(span, inferred, obj_type, Cow::Borrowed(arg), opts)?;
                            }
                        }
                        return Ok(());
                    }
                    _ => {}
                }

                if opts.index_tuple_with_param {
                    if let (
                        Type::Param(obj_param),
                        Type::Param(TypeParam {
                            constraint: Some(index_param_constraint),
                            ..
                        }),
                    ) = (param.obj_type.normalize(), param.index_type.normalize())
                    {
                        // param  = [string, number, ...T][P];
                        // arg = true;
                        //
                        // where P is keyof T
                        //
                        // =>
                        //
                        // T = true

                        if let Type::Index(Index { ty: keyof_ty, .. }) = index_param_constraint.normalize() {
                            return self.infer_type(
                                span,
                                inferred,
                                &param.obj_type,
                                arg,
                                InferTypeOpts {
                                    append_type_as_union: true,
                                    ..Default::default()
                                },
                            );
                        }
                    }
                }
            }

            Type::Constructor(param) => {
                if let Type::Class(arg_class) = arg_normalized {
                    for member in &arg_class.def.body {
                        match member {
                            ClassMember::Constructor(constructor) => {
                                self.infer_type_of_fn_params(span, inferred, &param.params, &constructor.params, opts)?;

                                if let Some(ret_ty) = &constructor.ret_ty {
                                    return self.infer_type(span, inferred, &param.type_ann, ret_ty, opts);
                                }
                            }
                            ClassMember::Method(_) => {}
                            ClassMember::Property(_) => {}
                            ClassMember::IndexSignature(_) => {}
                        }
                    }

                    return self.infer_type(span, inferred, &param.type_ann, arg, opts);
                }
            }

            Type::Class(param) => {
                if let Type::Class(arg) = arg_normalized {
                    return self.infer_types_using_class(span, inferred, param, arg, opts);
                }
            }

            Type::ClassDef(param) => {
                if let Type::ClassDef(arg) = arg_normalized {
                    return self.infer_types_using_class_def(span, inferred, param, arg, opts);
                }
            }

            Type::Readonly(param) => {
                self.infer_type_using_readonly(span, inferred, param, arg, opts)?;

                // We need to check parents
                if let Type::Interface(..) = arg.normalize() {
                } else {
                    return Ok(());
                }
            }

            _ => {}
        }

        match (param.normalize(), arg.normalize()) {
            (Type::Union(Union { types: param_types, .. }), _) => {
                return self.infer_to_multiple_types(span, inferred, arg, param_types, true, opts);
            }
            (Type::Intersection(Intersection { types: param_types, .. }), _) => {
                return self.infer_to_multiple_types(span, inferred, arg, param_types, false, opts);
            }

            (_, Type::Union(arg_union)) => {
                // Source is a union or intersection type, infer from each constituent type
                for source_type in arg_union.types.iter() {
                    self.infer_from_types(span, inferred, source_type, param, opts)?;
                }
                return Ok(());
            }

            _ => {}
        }

        match arg_normalized {
            // Handled by generic expander, so let's return it as-is.
            Type::Mapped(..) => {}

            Type::Readonly(Readonly { ty: arg, .. }) => return self.infer_type(span, inferred, param, arg, opts),

            Type::Array(arr) => {
                debug_assert_eq!(span.ctxt, SyntaxContext::empty());

                let params = vec![*arr.elem_type.clone()];
                return self.infer_type(
                    span,
                    inferred,
                    param,
                    &Type::Ref(Ref {
                        span,
                        type_name: RTsEntityName::Ident(RIdent::new("Array".into(), DUMMY_SP)),
                        type_args: Some(box TypeParamInstantiation { span, params }),
                        metadata: Default::default(),
                        tracker: Default::default(),
                    })
                    .freezed(),
                    opts,
                );
            }

            Type::Keyword(KeywordType {
                kind: TsKeywordTypeKind::TsAnyKeyword,
                ..
            }) => return Ok(()),
            Type::Keyword(..) => {}
            Type::Ref(..) => {
                let arg = self
                    .expand(
                        span,
                        arg.clone(),
                        ExpandOpts {
                            full: true,
                            expand_union: true,
                            preserve_ref: false,
                            ignore_expand_prevention_for_top: true,
                            ignore_expand_prevention_for_all: false,
                            ..Default::default()
                        },
                    )?
                    .freezed();
                match arg.normalize() {
                    Type::Ref(..) => {}
                    _ => {
                        return self.infer_type(span, inferred, param, &arg, opts);
                    }
                }
            }
            Type::Alias(arg) => return self.infer_type(span, inferred, param, &arg.ty, opts),

            Type::Interface(arg) => {
                // Body should be handled by the match expression above.

                for parent in &arg.extends {
                    let parent = self
                        .type_of_ts_entity_name(span, &parent.expr, parent.type_args.as_deref())?
                        .freezed();
                    self.infer_type(span, inferred, param, &parent, opts)?;
                }

                // Check to print unimplemented error message
                match param_normalized {
                    Type::Index(..) | Type::Interface(..) => return Ok(()),
                    _ => {}
                }
            }

            Type::Intersection(arg) => {
                // Infer each type, and then intersect each type parameters.

                let mut data = vec![];

                for ty in &arg.types {
                    let mut inferred = InferData {
                        dejavu: inferred.dejavu.clone(),
                        ..Default::default()
                    };
                    self.infer_type(span, &mut inferred, param, ty, opts)
                        .context("failed to in infer element type of an intersection type")?;
                    data.push(inferred);
                }

                let mut map = FxHashMap::<_, Vec<_>>::default();
                for item in data {
                    for (name, ty) in item.type_params {
                        map.entry(name).or_default().push(ty.inferred_type);
                    }
                }

                for (name, types) in map {
                    self.upsert_inferred(span, inferred, name, &Type::new_intersection(span, types).freezed(), opts)?;
                }

                return Ok(());
            }

            _ => {}
        }

        // Prevent logging
        match arg.normalize() {
            Type::Keyword(KeywordType {
                kind: TsKeywordTypeKind::TsNullKeyword,
                ..
            })
            | Type::Keyword(KeywordType {
                kind: TsKeywordTypeKind::TsUndefinedKeyword,
                ..
            })
            | Type::Keyword(KeywordType {
                kind: TsKeywordTypeKind::TsVoidKeyword,
                ..
            }) => {
                return Ok(());
            }

            _ => {}
        }

        // Prevent logging
        let ignore = |ty: &Type| {
            matches!(
                ty,
                Type::Enum(..)
                    | Type::EnumVariant(..)
                    | Type::Keyword(KeywordType {
                        kind: TsKeywordTypeKind::TsNumberKeyword
                            | TsKeywordTypeKind::TsStringKeyword
                            | TsKeywordTypeKind::TsBigIntKeyword
                            | TsKeywordTypeKind::TsBooleanKeyword,
                        ..
                    })
                    | Type::Lit(..)
            )
        };
        if ignore(param_normalized) && ignore(arg_normalized) {
            return Ok(());
        }

        if param_normalized.is_str_lit() || param_normalized.is_bool_lit() || param_normalized.is_num_lit() {
            // Prevent logging
            return Ok(());
        }

        if param_normalized.is_predicate() && arg_normalized.is_bool() {
            // Prevent logging
            return Ok(());
        }

        error!(
            "unimplemented: infer_type\nparam  = {}\narg = {}",
            force_dump_type_as_string(param_normalized),
            force_dump_type_as_string(arg_normalized),
        );
        Ok(())
    }

    fn infer_type_using_mapped_type(
        &mut self,
        span: Span,
        inferred: &mut InferData,
        param: &Mapped,
        arg: &Type,
        opts: InferTypeOpts,
    ) -> VResult<bool> {
        let _tracing = dev_span!("infer_type_using_mapped_type");

        match arg.normalize() {
            Type::Ref(arg) => {
                let arg = self
                    .expand(
                        arg.span,
                        Type::Ref(arg.clone()),
                        ExpandOpts {
                            full: true,
                            expand_union: true,
                            preserve_ref: false,
                            ignore_expand_prevention_for_top: true,
                            ..Default::default()
                        },
                    )?
                    .freezed();

                match arg.normalize() {
                    Type::Ref(..) => return Ok(false),
                    _ => return self.infer_type_using_mapped_type(span, inferred, param, &arg, opts),
                }
            }
            Type::Mapped(arg) => {
                if param.type_param.name == arg.type_param.name {
                    if let Some(param_ty) = &param.ty {
                        if let Some(arg_ty) = &arg.ty {
                            self.infer_type(span, inferred, param_ty, arg_ty, opts)?;
                        }
                    }

                    return Ok(true);
                }
            }

            Type::Enum(..) | Type::Alias(..) | Type::Intersection(..) | Type::Class(..) | Type::Interface(..) => {
                let arg = self
                    .convert_type_to_type_lit(span, Cow::Borrowed(arg))
                    .context("tried to convert a type into a type literal to infer mapped type")?
                    .map(Cow::into_owned)
                    .map(Type::TypeLit);
                if let Some(arg) = arg {
                    return self.infer_type_using_mapped_type(span, inferred, param, &arg, opts);
                }
            }
            _ => {}
        }

        {
            struct Res {
                name: Id,
                key_name: Id,
                readonly: Option<TruePlusMinus>,
                optional: Option<TruePlusMinus>,
            }
            /// Matches with normalized types.
            /// type Boxed<R> = {
            ///     [P in keyof R]: Box<R[P]>;
            /// }
            fn matches(param: &Mapped) -> Option<Res> {
                match param {
                    Mapped {
                        type_param:
                            TypeParam {
                                name: key_name,
                                constraint: Some(constraint),
                                ..
                            },
                        readonly,
                        optional,
                        ..
                    } => match constraint.normalize() {
                        Type::Index(Index { ty: operator_arg, .. }) => match operator_arg.normalize() {
                            Type::Param(TypeParam { name, .. }) => Some(Res {
                                name: name.clone(),
                                key_name: key_name.clone(),
                                optional: *optional,
                                readonly: *readonly,
                            }),
                            _ => None,
                        },

                        Type::Param(TypeParam {
                            constraint: Some(constraint),
                            ..
                        }) => match constraint.normalize() {
                            Type::Param(TypeParam {
                                name: key_name,
                                constraint: Some(constraint),
                                ..
                            }) => match constraint.normalize() {
                                Type::Index(Index { ty, .. }) => match ty.normalize() {
                                    Type::Param(TypeParam { name, .. }) => Some(Res {
                                        name: name.clone(),
                                        key_name: key_name.clone(),
                                        optional: *optional,
                                        readonly: *readonly,
                                    }),
                                    _ => None,
                                },
                                _ => None,
                            },

                            _ => None,
                        },

                        _ => None,
                    },

                    _ => None,
                }
            }

            if let Some(Res {
                name,
                readonly,
                optional,
                key_name,
            }) = matches(param)
            {
                debug!(
                    "[generic/inference] Found form of `P in keyof T` where T = {}, P = {}",
                    name, key_name
                );

                match arg.normalize() {
                    Type::TypeLit(arg) => {
                        // We should make a new type literal, based on the information.
                        let mut key_types = vec![];
                        let mut new_members = Vec::<TypeElement>::with_capacity(arg.members.len());

                        // In the code below, we are given Box<R[P]> and keys of R.
                        // We have to deduce T is { a: Box<string> } from given facts.
                        //
                        // type Boxed<R> = {
                        //     [P in keyof R]: Box<R[P]>;
                        // }
                        //
                        // declare function unbox<T>(obj: Boxed<T>): T;
                        //
                        // declare let b: {
                        //     a: Box<string>,
                        // };
                        // let v = unbox(b);
                        for arg_member in &arg.members {
                            if let Some(key) = arg_member.key() {
                                match key {
                                    Key::Num(..) | Key::Normal { .. } => {
                                        key_types.push(key.ty().into_owned());
                                    }
                                    _ => {
                                        unimplemented!("Inference of keys except ident in mapped type.\nKey: {:?}", key)
                                    }
                                }
                            }

                            match arg_member {
                                TypeElement::Property(arg_prop) => {
                                    let type_ann: Option<_> = if let Some(arg_prop_ty) = &arg_prop.type_ann {
                                        if let Some(param_ty) = ALLOW_DEEP_CLONE.set(&(), || {
                                            let mut ty = param.ty.clone();
                                            ty.freeze();
                                            ty
                                        }) {
                                            let old = take(&mut self.mapped_type_param_name);
                                            self.mapped_type_param_name = vec![name.clone()];

                                            let mut data = InferData {
                                                dejavu: inferred.dejavu.clone(),
                                                ..Default::default()
                                            };
                                            self.infer_type(span, &mut data, &param_ty, arg_prop_ty, opts)?;
                                            let inferred_ty = data.type_params.remove(&name).map(|v| v.inferred_type).freezed();

                                            self.mapped_type_param_name = old;

                                            inferred_ty.or_else(|| data.defaults.remove(&name))
                                        } else {
                                            None
                                        }
                                    } else {
                                        None
                                    };
                                    let type_ann = type_ann
                                        .map(Box::new)
                                        .or_else(|| Some(box Type::any(arg_prop.span, Default::default())));

                                    new_members.push(TypeElement::Property(PropertySignature {
                                        optional: calc_true_plus_minus_in_param(optional, arg_prop.optional),
                                        readonly: calc_true_plus_minus_in_param(readonly, arg_prop.readonly),
                                        type_ann,
                                        ..arg_prop.clone()
                                    }));
                                }

                                TypeElement::Index(i) => {
                                    let type_ann = if let Some(arg_prop_ty) = &i.type_ann {
                                        if let Some(param_ty) = &param.ty {
                                            // TODO(kdy1): PERF

                                            let mut mapped_param_ty = arg_prop_ty.clone().foldable();

                                            replace_type(
                                                &mut mapped_param_ty,
                                                |ty| matches!(ty.normalize(), Type::Param(TypeParam { name: param_name, .. }) if name == *param_name),
                                                |ty| match ty.normalize() {
                                                    Type::Param(TypeParam { name: param_name, .. }) if name == *param_name => {
                                                        Some(*param_ty.clone())
                                                    }

                                                    _ => None,
                                                },
                                            );
                                            mapped_param_ty.freeze();

                                            self.infer_type(span, inferred, &mapped_param_ty, arg_prop_ty, opts)?;
                                        }

                                        // inferred.type_elements.remove(&name)
                                        None
                                    } else {
                                        Some(box Type::any(i.span, Default::default()))
                                    };
                                    new_members.push(TypeElement::Index(IndexSignature { type_ann, ..i.clone() }));
                                }

                                TypeElement::Method(arg_method) => {
                                    let mut arg_prop_ty = Type::Function(Function {
                                        span: arg_method.span,
                                        type_params: arg_method.type_params.clone(),
                                        params: arg_method.params.clone(),
                                        ret_ty: arg_method
                                            .ret_ty
                                            .clone()
                                            .unwrap_or_else(|| box Type::any(arg_method.span, Default::default())),
                                        metadata: Default::default(),
                                        tracker: Default::default(),
                                    });
                                    arg_prop_ty.freeze();
                                    let type_ann = if let Some(param_ty) = ALLOW_DEEP_CLONE.set(&(), || {
                                        let mut ty = param.ty.clone();
                                        ty.freeze();
                                        ty
                                    }) {
                                        let old = take(&mut self.mapped_type_param_name);
                                        self.mapped_type_param_name = vec![name.clone()];

                                        let mut data = InferData {
                                            dejavu: inferred.dejavu.clone(),
                                            ..Default::default()
                                        };
                                        self.infer_type(span, &mut data, &param_ty, &arg_prop_ty, opts)?;
                                        let mut defaults = take(&mut data.defaults);
                                        let mut map = self.finalize_inference(span, &[], data);
                                        let inferred_ty = map.types.remove(&name);

                                        self.mapped_type_param_name = old;

                                        inferred_ty.or_else(|| defaults.remove(&name))
                                    } else {
                                        None
                                    };
                                    let type_ann = type_ann
                                        .map(Box::new)
                                        .or_else(|| Some(box Type::any(arg_method.span, Default::default())));

                                    new_members.push(TypeElement::Property(PropertySignature {
                                        span: arg_method.span,
                                        accessibility: None,
                                        readonly: calc_true_plus_minus_in_param(readonly, arg_method.readonly),
                                        key: arg_method.key.clone(),
                                        optional: calc_true_plus_minus_in_param(optional, arg_method.optional),
                                        params: Default::default(),
                                        type_ann,
                                        type_params: Default::default(),
                                        metadata: Default::default(),
                                        accessor: Default::default(),
                                    }));
                                }

                                _ => {
                                    error!("unimplemented: infer_mapped: Mapped <- Assign: TypeElement({:#?})", arg_member);
                                    return Ok(true);
                                }
                            }
                        }

                        self.insert_inferred_raw(
                            span,
                            inferred,
                            name.clone(),
                            Cow::Owned(
                                Type::TypeLit(TypeLit {
                                    span: arg.span,
                                    members: new_members,
                                    metadata: arg.metadata,
                                    tracker: Default::default(),
                                })
                                .freezed(),
                            ),
                            opts,
                        )?;

                        let mut keys = Type::Union(Union {
                            span: param.span,
                            types: key_types,
                            metadata: UnionMetadata {
                                common: param.metadata.common,
                                ..Default::default()
                            },
                            tracker: Default::default(),
                        })
                        .fixed();
                        prevent_generalize(&mut keys);
                        keys.freeze();

                        self.insert_inferred_raw(span, inferred, key_name, Cow::Owned(keys), opts)?;

                        return Ok(true);
                    }

                    Type::Array(arg) => {
                        let new_ty = if let Some(param_ty) = &param.ty {
                            let old = take(&mut self.mapped_type_param_name);
                            self.mapped_type_param_name = vec![name.clone()];

                            let mut data = InferData {
                                dejavu: inferred.dejavu.clone(),
                                ..Default::default()
                            };
                            self.infer_type(span, &mut data, param_ty, &arg.elem_type, opts)?;
                            let mut map = self.finalize_inference(span, &[], data);
                            let mut inferred_ty = map.types.remove(&name);

                            self.mapped_type_param_name = old;

                            match &mut inferred_ty {
                                Some(ty) => {
                                    handle_optional_for_element(ty, optional);
                                }
                                None => {}
                            }

                            inferred_ty
                        } else {
                            None
                        };

                        self.insert_inferred_raw(
                            span,
                            inferred,
                            name.clone(),
                            Cow::Owned(
                                Type::Array(Array {
                                    span: arg.span,
                                    elem_type: box new_ty.unwrap_or_else(|| {
                                        Type::any(
                                            arg.span,
                                            KeywordTypeMetadata {
                                                common: arg.metadata.common,
                                                ..Default::default()
                                            },
                                        )
                                    }),
                                    metadata: arg.metadata,
                                    tracker: Default::default(),
                                })
                                .freezed(),
                            ),
                            opts,
                        )?;

                        return Ok(true);
                    }

                    Type::Tuple(arg) => {
                        let mut new_elems = vec![];
                        if let Some(param_ty) = &param.ty {
                            for elem in arg.elems.iter() {
                                let old = take(&mut self.mapped_type_param_name);
                                self.mapped_type_param_name = vec![name.clone()];

                                let mut data = InferData {
                                    dejavu: inferred.dejavu.clone(),
                                    ..Default::default()
                                };
                                self.infer_type(
                                    span,
                                    &mut data,
                                    param_ty,
                                    &elem.ty,
                                    InferTypeOpts {
                                        index_tuple_with_param: true,
                                        ..opts
                                    },
                                )?;
                                let mut map = self.finalize_inference(span, &[], data);
                                let mut inferred_ty = map.types.remove(&name);

                                self.mapped_type_param_name = old;

                                match &mut inferred_ty {
                                    Some(ty) => {
                                        handle_optional_for_element(ty, optional);
                                    }
                                    None => {}
                                }

                                new_elems.push(TupleElement {
                                    span: elem.span,
                                    label: elem.label.clone(),
                                    ty: box inferred_ty.unwrap_or_else(|| Type::any(elem.span, Default::default())),
                                    tracker: Default::default(),
                                });
                            }
                        }

                        self.insert_inferred_raw(
                            span,
                            inferred,
                            name.clone(),
                            Cow::Owned(
                                Type::Tuple(Tuple {
                                    span: arg.span,
                                    elems: new_elems,
                                    metadata: arg.metadata,
                                    tracker: Default::default(),
                                })
                                .freezed(),
                            ),
                            opts,
                        )?;

                        return Ok(true);
                    }

                    _ => {
                        dbg!();
                    }
                }
            }
        }

        {
            // Record<Key, Type> expands to
            //
            //
            // type Record<Key extends keyof any, Type> = {
            //     [P in Key]: Type;
            // };
            if let Some(constraint) = &param.type_param.constraint {
                if let Type::Param(type_param) = constraint.normalize() {
                    debug!(
                        "[generic/inference] Found form of `P in T` where T = {}, P = {}",
                        type_param.name, param.type_param.name
                    );

                    if let Type::TypeLit(arg) = arg.normalize() {
                        let key_ty = arg.members.iter().filter_map(|element| match element {
                            TypeElement::Property(p) => match &p.key {
                                Key::Private(..) | Key::Computed(..) => None,
                                _ => Some(p.key.ty().into_owned()),
                            }, // TODO(kdy1): Handle method element
                            _ => None,
                        });
                        let mut key_ty = Type::new_union(span, key_ty);
                        prevent_generalize(&mut key_ty);
                        key_ty.freeze();
                        self.insert_inferred(span, inferred, type_param, Cow::Owned(key_ty), opts)?;
                    }

                    let param_ty = param.ty.as_ref().unwrap();

                    let names = {
                        let mut tp = type_param;

                        loop {
                            match &tp.constraint.as_ref().map(|v| v.normalize()) {
                                Some(Type::Param(p)) => {
                                    tp = p;
                                }
                                Some(Type::Index(Index {
                                    ty: box Type::Param(p), ..
                                })) => {
                                    tp = p;
                                }
                                _ => {
                                    break;
                                }
                            }
                        }

                        match &tp.constraint {
                            Some(box Type::Union(ty))
                                if ty.types.iter().all(|ty| {
                                    matches!(
                                        ty.normalize(),
                                        Type::Index(Index {
                                            ty: box Type::Param(..),
                                            ..
                                        })
                                    )
                                }) =>
                            {
                                ty.types
                                    .iter()
                                    .map(|ty| match ty.normalize() {
                                        Type::Index(Index {
                                            ty: box Type::Param(p), ..
                                        }) => p.name.clone(),
                                        _ => unreachable!(),
                                    })
                                    .collect()
                            }

                            _ => vec![tp.name.clone()],
                        }
                    };

                    let old = take(&mut self.mapped_type_param_name);
                    self.mapped_type_param_name = names.clone();
                    {
                        let mut v = MappedReverser::default();
                        let reversed_param_ty = param_ty.clone().fold_with(&mut v);

                        if v.did_work {
                            self.infer_type(span, inferred, &reversed_param_ty, arg, opts)?;
                            self.mapped_type_param_name = old;

                            return Ok(true);
                        }
                    }

                    if let Type::TypeLit(arg) = arg.normalize() {
                        let mut type_elements = FxHashMap::<_, Vec<_>>::default();

                        if let Some(param_ty) = &param.ty {
                            for m in &arg.members {
                                match m {
                                    TypeElement::Property(p) => {
                                        //
                                        if let Some(ref type_ann) = p.type_ann {
                                            self.infer_type(span, inferred, param_ty, type_ann, opts)?;
                                        }

                                        for name in &names {
                                            if *name == type_param.name {
                                                continue;
                                            }

                                            let ty = inferred.type_params.remove(name).map(|v| box v.inferred_type);

                                            type_elements
                                                .entry(name.clone())
                                                .or_default()
                                                .push(TypeElement::Property(PropertySignature {
                                                    optional: calc_true_plus_minus_in_param(param.optional, p.optional),
                                                    readonly: calc_true_plus_minus_in_param(param.readonly, p.readonly),
                                                    type_ann: ty,
                                                    ..p.clone()
                                                }));
                                        }
                                    }

                                    _ => {
                                        unimplemented!("infer_type: Mapped <- Assign: TypeElement({:?})", m)
                                    }
                                }
                            }

                            for name in names {
                                if name == type_param.name {
                                    continue;
                                }

                                let list_ty = Type::TypeLit(TypeLit {
                                    span: arg.span,
                                    members: type_elements.remove(&name).unwrap_or_default(),
                                    metadata: arg.metadata,
                                    tracker: Default::default(),
                                })
                                .freezed();

                                self.insert_inferred_raw(span, inferred, name.clone(), Cow::Owned(list_ty), opts)?;
                            }
                        }

                        self.mapped_type_param_name = old;
                        return Ok(true);
                    }

                    self.mapped_type_param_name = old;
                }
            }
        }

        match &param.type_param.constraint {
            Some(constraint) => {
                if let Type::Index(operator) = constraint.normalize() {
                    if let Type::IndexedAccessType(
                        iat @ IndexedAccessType {
                            obj_type: box Type::Param(..),
                            index_type: box Type::Param(..),
                            ..
                        },
                    ) = operator.ty.normalize()
                    {
                        if let Type::Param(..) = iat.obj_type.normalize() {
                            if let Type::Param(..) = iat.index_type.normalize() {
                                let param_ty = param.ty.clone().unwrap();
                                let name = param.type_param.name.clone();
                                let (obj_ty, index_ty) = match &**param.type_param.constraint.as_ref().unwrap() {
                                    Type::Index(Index {
                                        ty:
                                            box Type::IndexedAccessType(IndexedAccessType {
                                                obj_type: box Type::Param(obj_ty),
                                                index_type: box Type::Param(index_ty),
                                                ..
                                            }),
                                        ..
                                    }) => (obj_ty, index_ty),
                                    _ => unreachable!(),
                                };
                                if name == index_ty.name {
                                    match arg.normalize() {
                                        Type::TypeLit(arg) => {
                                            let mut members = Vec::with_capacity(arg.members.len());

                                            for m in &arg.members {
                                                match m {
                                                    TypeElement::Property(p) => {
                                                        let optional = calc_true_plus_minus_in_param(param.optional, p.optional);
                                                        //
                                                        if let Some(ref type_ann) = p.type_ann {
                                                            self.infer_type(span, inferred, &param_ty, type_ann, opts)?;
                                                        }
                                                        members.push(TypeElement::Property(PropertySignature {
                                                            optional,
                                                            readonly: calc_true_plus_minus_in_param(param.readonly, p.readonly),
                                                            type_ann: None,
                                                            ..p.clone()
                                                        }));
                                                    }

                                                    _ => unimplemented!("infer_type: Mapped <- Assign: TypeElement({:?})", m),
                                                }
                                            }

                                            let list_ty = Type::TypeLit(TypeLit {
                                                span: arg.span,
                                                members,
                                                metadata: arg.metadata,
                                                tracker: Default::default(),
                                            });

                                            self.insert_inferred_raw(span, inferred, name, Cow::Owned(list_ty), opts)?;
                                            return Ok(true);
                                        }

                                        _ => {
                                            dbg!();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            None => {}
        }

        {
            match &param.type_param.constraint {
                Some(constraint) => {
                    if let Type::Index(
                        operator @ Index {
                            ty: box Type::Mapped(Mapped { ty: Some(..), .. }),
                            ..
                        },
                    ) = constraint.normalize()
                    {
                        if let Type::Mapped(..) = operator.ty.normalize() {
                            let reversed_param_ty = param.ty.as_ref().unwrap().clone().fold_with(&mut MappedReverser::default());

                            self.infer_type(span, inferred, &reversed_param_ty, arg, opts)?;

                            return Ok(true);
                        }
                    }
                }
                None => {}
            }
        }

        {
            // We handle all other mapped types at here.
            //
            //
            // In the code below,
            //
            // declare type Boxed<Pick<P, T>> = {
            //     [BoxedP in keyof Pick<P, K>[BoxedT]]: Box<Pick<P, K>[BoxedP]>;
            // };
            if let Some(constraint) = &param.type_param.constraint {
                if let Type::Index(Index { ty, .. }) = constraint.normalize() {
                    if let Some(param_ty) = &param.ty {
                        if let Type::TypeLit(arg_lit) = arg.normalize() {
                            let reversed_param_ty = param_ty.clone().fold_with(&mut MappedReverser::default()).freezed();
                            print_type("reversed", &reversed_param_ty);

                            self.infer_type(span, inferred, &reversed_param_ty, arg, opts)?;

                            return Ok(true);
                        }
                    }
                }
            }
        }

        Ok(false)
    }

    fn infer_type_using_tuple_and_tuple(
        &mut self,
        span: Span,
        inferred: &mut InferData,
        param: &Tuple,
        param_ty: &Type,
        arg: &Tuple,
        arg_ty: &Type,
        opts: InferTypeOpts,
    ) -> VResult<()> {
        let len = param.elems.len().max(arg.elems.len());

        let l_max = param.elems.len().saturating_sub(get_tuple_subtract_count(&arg.elems));
        let r_max = arg.elems.len().saturating_sub(get_tuple_subtract_count(&param.elems));

        let _tracing = dev_span!("infer_type_using_tuple_and_tuple", l_max = l_max, r_max = r_max);

        for index in 0..len {
            let li = min(index, l_max);
            let ri = min(index, r_max);

            let _tracing = dev_span!("infer_type_using_tuple_and_tuple", li = li, ri = ri);

            let l_elem_type = self.access_property(
                span,
                param_ty,
                &Key::Num(RNumber {
                    span,
                    value: li as _,
                    raw: None,
                }),
                TypeOfMode::RValue,
                IdCtx::Type,
                AccessPropertyOpts {
                    do_not_validate_type_of_computed_prop: true,
                    disallow_indexing_array_with_string: true,
                    disallow_creating_indexed_type_from_ty_els: true,
                    disallow_indexing_class_with_computed: true,
                    use_undefined_for_tuple_index_error: true,
                    return_rest_tuple_element_as_is: true,
                    ..Default::default()
                },
            )?;

            let r_elem_type = self.access_property(
                span,
                arg_ty,
                &Key::Num(RNumber {
                    span,
                    value: ri as _,
                    raw: None,
                }),
                TypeOfMode::RValue,
                IdCtx::Type,
                AccessPropertyOpts {
                    do_not_validate_type_of_computed_prop: true,
                    disallow_indexing_array_with_string: true,
                    disallow_creating_indexed_type_from_ty_els: true,
                    disallow_indexing_class_with_computed: true,
                    use_undefined_for_tuple_index_error: true,
                    return_rest_tuple_element_as_is: true,
                    ..Default::default()
                },
            )?;

            self.infer_type(
                span,
                inferred,
                &l_elem_type,
                &r_elem_type,
                InferTypeOpts {
                    append_type_as_union: true,
                    ..opts
                },
            )?;
        }

        Ok(())
    }

    fn infer_type_of_fn_param(
        &mut self,
        span: Span,
        inferred: &mut InferData,
        param: &FnParam,
        arg: &FnParam,
        opts: InferTypeOpts,
    ) -> VResult<()> {
        self.infer_type(
            span,
            inferred,
            &param.ty,
            &arg.ty,
            InferTypeOpts {
                append_type_as_union: opts.append_type_as_union || opts.for_fn_assignment,

                ..opts
            },
        )
    }

    fn infer_type_of_fn_params(
        &mut self,
        span: Span,
        inferred: &mut InferData,
        params: &[FnParam],
        args: &[FnParam],
        opts: InferTypeOpts,
    ) -> VResult<()> {
        for (param, arg) in params.iter().zip(args) {
            self.infer_type_of_fn_param(span, inferred, param, arg, opts)?
        }

        if params.len() > args.len() {
            for param in &params[args.len()..] {
                if let Type::Param(param) = &*param.ty {
                    // TODO: Union
                    inferred.defaults.insert(
                        param.name.clone(),
                        Type::unknown(param.span.with_ctxt(SyntaxContext::empty()), Default::default()),
                    );
                }
            }
        }

        Ok(())
    }

    fn rename_inferred(&mut self, span: Span, inferred: &mut InferData, arg_type_params: &TypeParamDecl) -> VResult<()> {
        info!("rename_inferred");

        if arg_type_params.params.iter().any(|v| inferred.errored.contains(&v.name)) {
            return Ok(());
        }

        //
        let mut fixed = FxHashMap::default();

        inferred.type_params.iter().for_each(|(param_name, ty)| {
            // Ignore unrelated type parameters
            if arg_type_params.params.iter().all(|v| *param_name != v.name) {
                return;
            }

            fixed.insert(param_name.clone(), ty.inferred_type.clone());
        });

        inferred.type_params.iter_mut().for_each(|(_, ty)| {
            replace_type(
                &mut ty.inferred_type,
                |node| match node.normalize() {
                    Type::Param(p) => fixed.contains_key(&p.name),
                    _ => false,
                },
                |node| {
                    //
                    match node.normalize() {
                        Type::Param(p) if fixed.contains_key(&p.name) => Some((*fixed.get(&p.name).unwrap()).clone()),
                        _ => None,
                    }
                },
            );

            ty.inferred_type.freeze();
        });

        Ok(())
    }
}

fn array_elem_type(t: &Type) -> Option<&Type> {
    if let Type::Array(a) = t.normalize() {
        return Some(&a.elem_type);
    }

    if let Some(elem) = unwrap_builtin_with_single_arg(t, "Array")
        .or_else(|| unwrap_builtin_with_single_arg(t, "ArrayLike"))
        .or_else(|| unwrap_builtin_with_single_arg(t, "ReadonlyArray"))
    {
        elem.assert_clone_cheap();
        return Some(elem);
    }

    None
}

/// Handles renaming of the type parameters.
impl Analyzer<'_, '_> {
    pub(super) fn rename_type_params(&mut self, span: Span, mut ty: Type, type_ann: Option<&Type>) -> VResult<Type> {
        if self.config.is_builtin {
            return Ok(ty);
        }

        ty.freeze();

        debug!(
            "rename_type_params(has_ann = {:?}, ty = {})",
            type_ann.is_some(),
            dump_type_as_string(&ty)
        );

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

        let mut usage_visitor = TypeParamUsageFinder::default();
        ty.normalize().visit_with(&mut usage_visitor);
        if usage_visitor.params.is_empty() {
            debug!("rename_type_param: No type parameter is used in type");

            if let Some(f) = ty.as_fn_type_mut() {
                f.type_params = None;
            }

            return Ok(ty);
        }

        if let Some(type_ann) = type_ann {
            let mut inferred = InferData::default();

            self.infer_type(span, &mut inferred, &ty, type_ann, Default::default())?;
            info!(
                "renaming type parameters based on type annotation provided by user\ntype_ann = {:?}",
                type_ann
            );

            let map = self.finalize_inference(span, &usage_visitor.params, inferred);

            // TODO(kdy1): PERF
            return Ok(ty
                .foldable()
                .fold_with(&mut TypeParamRenamer {
                    inferred: map.types,
                    declared: Default::default(),
                })
                .fixed());
        }

        let decl = Some(TypeParamDecl {
            span: DUMMY_SP,
            params: usage_visitor.params,
            tracker: Default::default(),
        });

        if let Some(ref mut f) = ty.as_fn_type_mut() {
            f.type_params = decl;
        } else if matches!(ty.normalize(), Type::ClassDef(..) | Type::Class(..)) {
            return Ok(ty);
        }

        Ok(ty.foldable().fold_with(&mut TypeParamRemover::new()).fixed())
    }
}

/// This method returns true for types like `'foo'` and `'foo' | 'bar'`.
pub(super) fn is_literals(ty: &Type) -> bool {
    match ty.normalize() {
        Type::Lit(_) => true,
        Type::Union(Union { ref types, .. }) => types.iter().all(is_literals),
        _ => false,
    }
}

struct SingleTypeParamReplacer<'a> {
    name: &'a Id,
    to: &'a Type,
}

impl Fold<Type> for SingleTypeParamReplacer<'_> {
    fn fold(&mut self, mut ty: Type) -> Type {
        // TODO(kdy1): PERF
        ty.normalize_mut();

        ty = ty.fold_children_with(self);

        match &ty {
            Type::Param(TypeParam { name, .. }) if *self.name == *name => return (*self.to).clone(),

            _ => {}
        }

        ty
    }
}

pub(crate) fn calc_true_plus_minus_in_param(param: Option<TruePlusMinus>, previous: bool) -> bool {
    match param {
        Some(v) => match v {
            TruePlusMinus::True => false,
            TruePlusMinus::Plus => true,
            TruePlusMinus::Minus => true,
        },
        None => previous,
    }
}

/// Replaces type parameters with name `from` to type `to`.
struct MappedKeyReplacer<'a> {
    /// The name of type parameter
    from: &'a Id,
    /// Type of key. This is typically literal.
    to: &'a Type,
}

impl VisitMut<Type> for MappedKeyReplacer<'_> {
    fn visit_mut(&mut self, ty: &mut Type) {
        match ty.normalize() {
            Type::Param(param) if *self.from == param.name => {
                *ty = self.to.clone();
            }
            _ => {
                // TODO(kdy1): PERF
                ty.normalize_mut();
                ty.visit_mut_children_with(self)
            }
        }
    }
}

struct MappedIndexTypeReplacer<'a> {
    obj_ty: &'a Type,
    /// The name of key
    index_param_name: &'a Id,

    to: &'a Type,
}

impl VisitMut<Type> for MappedIndexTypeReplacer<'_> {
    fn visit_mut(&mut self, ty: &mut Type) {
        // TODO(kdy1): PERF
        ty.normalize_mut();

        ty.visit_mut_children_with(self);

        if let Type::IndexedAccessType(IndexedAccessType { obj_type, index_type, .. }) = &*ty {
            if self.obj_ty.type_eq(&**obj_type) {
                match &**index_type {
                    Type::Param(key) if *self.index_param_name == key.name => {
                        *ty = self.to.clone();
                    }
                    _ => {}
                }
            }
        }
    }
}

/// This struct reverses the mapped type.
///
/// ===== ===== ===== Type (param_ty) ===== ===== =====
/// TYPE as {
//     value: {
///         [P in K]: T[P];
///     };
/// };
///
/// ===== ===== ===== Type (ty) ===== ===== =====
/// TYPE as {
///     [P in K]: T[P];
/// };
/// ===== ===== ===== Type (arg) ===== ===== =====
/// TYPE as {
///     foo: {
///         value: number;
///     };
///     bar: {
///         value: string;
///     };
/// };
#[derive(Default)]
struct MappedReverser {
    did_work: bool,
}

impl Fold<Type> for MappedReverser {
    fn fold(&mut self, mut ty: Type) -> Type {
        // TODO(kdy1): PERF
        ty.normalize_mut();

        ty = ty.fold_children_with(self);

        match ty {
            Type::TypeLit(TypeLit {
                span, members, metadata, ..
            }) if members.len() == 1
                && members.iter().any(|member| match member {
                    TypeElement::Property(p) => {
                        if let Some(ty) = &p.type_ann {
                            ty.is_mapped()
                        } else {
                            false
                        }
                    }
                    TypeElement::Method(_) => unimplemented!(),
                    TypeElement::Index(_) => unimplemented!(),
                    _ => false,
                }) =>
            {
                self.did_work = true;
                let member = members.into_iter().next().unwrap();

                match member {
                    TypeElement::Property(p) => {
                        let mapped: Mapped = p.type_ann.unwrap().mapped().unwrap();
                        let ty = box Type::TypeLit(TypeLit {
                            span,
                            members: vec![TypeElement::Property(PropertySignature { type_ann: mapped.ty, ..p })],
                            metadata,
                            tracker: Default::default(),
                        });

                        return Type::Mapped(Mapped { ty: Some(ty), ..mapped });
                    }
                    TypeElement::Method(_) => unimplemented!(),
                    TypeElement::Index(_) => unimplemented!(),
                    _ => unreachable!(),
                }
            }
            _ => {}
        }

        ty
    }
}

struct MappedIndexedSimplifier;

impl Fold<Type> for MappedIndexedSimplifier {
    fn fold(&mut self, mut ty: Type) -> Type {
        // TODO(kdy1): PERF
        ty.normalize_mut();

        ty = ty.fold_children_with(self);

        match ty {
            Type::IndexedAccessType(IndexedAccessType {
                obj_type,
                index_type:
                    box Type::Param(TypeParam {
                        name: index_name,
                        constraint: Some(box Type::Index(Index { ty: indexed_ty, .. })),
                        ..
                    }),
                ..
            }) if obj_type.type_eq(&indexed_ty) => {
                return *obj_type;
            }
            _ => {}
        }

        ty
    }
}

fn handle_optional_for_element(element_ty: &mut Type, optional: Option<TruePlusMinus>) {
    let v = match optional {
        Some(v) => v,
        None => return,
    };

    match v {
        TruePlusMinus::True => {
            if element_ty.is_optional() {
                match element_ty.normalize_mut() {
                    Type::Optional(ty) => {
                        let ty = ty.ty.take();
                        let ty = ty.remove_falsy();

                        *element_ty = ty;
                    }
                    _ => {
                        unreachable!()
                    }
                }
            } else {
                let new_ty = element_ty.take().remove_falsy();

                *element_ty = new_ty;
            }
        }
        TruePlusMinus::Plus => match element_ty.normalize() {
            Type::Optional(ty) => {}
            _ => {
                let ty = box element_ty.take();
                *element_ty = Type::Optional(OptionalType {
                    span: DUMMY_SP,
                    ty,
                    metadata: Default::default(),
                    tracker: Default::default(),
                });
            }
        },
        TruePlusMinus::Minus => {}
    }
}