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
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
//! The main typechecking interface which is responsible for typechecking expressions, patterns,
//! etc. Only checks which need to be aware of expressions are handled here the actual unifying and
//! checking of types are done in the `unify_type` and `kindcheck` modules.
use std::{
    borrow::{BorrowMut, Cow},
    mem,
    sync::Arc,
};

use crate::base::{
    ast::{
        self, Argument, AstType, DisplayEnv, Do, Expr, IdentEnv, KindedIdent, Literal, MutVisitor,
        Pattern, PatternField, SpannedExpr, SpannedIdent, SpannedPattern, TypeBinding, Typed,
        TypedIdent, ValueBinding, ValueBindings,
    },
    error::Errors,
    fnv::{FnvMap, FnvSet},
    kind::{ArcKind, Kind, KindCache, KindEnv},
    merge,
    metadata::{Metadata, MetadataEnv},
    pos::{self, BytePos, Span, Spanned},
    resolve,
    scoped_map::{self, ScopedMap},
    symbol::{Symbol, SymbolModule, SymbolRef, Symbols},
    types::{
        self, Alias, AliasRef, AppVec, ArcType, ArgType, Field, Flags, Generic, PrimitiveEnv, Type,
        TypeCache, TypeContext, TypeEnv, TypeExt, TypePtr, Walker,
    },
};

use crate::{
    implicits,
    kindcheck::KindCheck,
    substitution::{self, Substitution},
    typ::RcType,
    unify, unify_type, TypecheckEnv,
};

use self::{
    generalize::TypeGeneralizer,
    mod_type::{ModType, ModTypeRef, TypeModifier},
};

pub use self::error::{Help, HelpError, SpannedTypeError, TypeError};

mod error;
mod generalize;
mod mod_type;

pub(crate) type TcResult<T> = Result<T, TypeError<Symbol, RcType<Symbol>>>;

enum ErrorOrder {
    ExpectedActual,
    ActualExpected,
}

#[derive(Clone, Debug)]
struct StackBinding {
    typ: ModType,
}

pub(crate) struct Environment<'a> {
    /// The global environment which the typechecker extracts types from
    environment: &'a (dyn TypecheckEnv<Type = RcType> + 'a),
    /// Stack allocated variables
    stack: ScopedMap<Symbol, StackBinding>,
    /// Types which exist in some scope (`type Test = ... in ...`)
    stack_types: ScopedMap<Symbol, (RcType, Alias<Symbol, RcType>)>,
    kind_cache: KindCache,
    type_variables: ScopedMap<Symbol, RcType>,
    skolem_variables: ScopedMap<Symbol, RcType>,
}

impl<'a> KindEnv for Environment<'a> {
    fn find_kind(&self, type_name: &SymbolRef) -> Option<ArcKind> {
        self.stack_types
            .get(type_name)
            .map(|&(_, ref alias)| alias.kind(&self.kind_cache).into_owned())
            .or_else(|| {
                self.type_variables
                    .get(type_name)
                    .map(|t| t.kind(&self.kind_cache).into_owned())
            })
            .or_else(|| self.environment.find_kind(type_name))
    }
}

impl<'a> TypeEnv for Environment<'a> {
    type Type = RcType;

    fn find_type(&self, id: &SymbolRef) -> Option<RcType> {
        self.stack
            .get(id)
            .map(|bind| bind.typ.concrete.clone())
            .or_else(|| self.environment.find_type(id))
    }

    fn find_type_info(&self, id: &SymbolRef) -> Option<Alias<Symbol, RcType>> {
        self.stack_types
            .get(id)
            .map(|&(_, ref alias)| alias.clone())
            .or_else(|| self.environment.find_type_info(id))
    }
}

impl<'a> PrimitiveEnv for Environment<'a> {
    fn get_bool(&self) -> ArcType {
        self.environment.get_bool()
    }
}

impl<'a> MetadataEnv for Environment<'a> {
    fn get_metadata(&self, id: &SymbolRef) -> Option<Arc<Metadata>> {
        self.environment.get_metadata(id)
    }
}

impl Environment<'_> {
    fn find_mod_type(&self, id: &SymbolRef) -> Option<ModType> {
        self.stack
            .get(id)
            .map(|bind| bind.typ.clone())
            .or_else(|| self.environment.find_type(id).map(ModType::rigid))
    }
}

/// Struct which provides methods to typecheck expressions.
pub struct Typecheck<'a, 'ast> {
    pub(crate) environment: Environment<'a>,
    symbols: SymbolModule<'a>,
    pub(crate) subs: Substitution<RcType>,
    named_variables: FnvMap<Symbol, RcType>,
    pub(crate) errors: Errors<SpannedTypeError<Symbol, RcType<Symbol>>>,
    /// Type variables `let test: a -> b` (`a` and `b`)
    kind_cache: KindCache,

    pub(crate) implicit_resolver: implicits::ImplicitResolver<'a>,
    unbound_variables: ScopedMap<Symbol, ArcKind>,
    refined_variables: ScopedMap<u32, ()>,
    pub(crate) ast_arena: ast::ArenaRef<'a, 'ast, Symbol>,
}

impl<'a> TypeContext<Symbol, RcType> for Typecheck<'a, '_> {
    gluon_base::forward_type_interner_methods!(Symbol, RcType, self_, &self_.subs);
}

/// Error returned when unsuccessfully typechecking an expression
pub type Error = Errors<SpannedTypeError<Symbol>>;

pub use implicits::{Error as ImplicitError, ErrorKind as ImplicitErrorKind};

impl<'a, 'ast> Typecheck<'a, 'ast> {
    /// Create a new typechecker which typechecks expressions in `module`
    pub fn new(
        module: String,
        symbols: &'a mut Symbols,
        environment: &'a (dyn TypecheckEnv<Type = ArcType> + 'a),
        interner: &TypeCache<Symbol, ArcType>,
        metadata: &'a mut FnvMap<Symbol, Arc<Metadata>>,
        ast_arena: ast::ArenaRef<'a, 'ast, Symbol>,
    ) -> Self {
        let symbols = SymbolModule::new(module, symbols);
        let subs = Substitution::new(interner.kind_cache.typ(), interner.clone());
        Typecheck {
            environment: Environment {
                environment,
                stack: ScopedMap::new(),
                stack_types: ScopedMap::new(),
                kind_cache: interner.kind_cache.clone(),
                skolem_variables: ScopedMap::new(),
                type_variables: ScopedMap::new(),
            },
            symbols: symbols,
            named_variables: FnvMap::default(),
            errors: Errors::new(),
            kind_cache: interner.kind_cache.clone(),
            implicit_resolver: crate::implicits::ImplicitResolver::new(environment, metadata),
            unbound_variables: ScopedMap::new(),
            refined_variables: ScopedMap::new(),
            subs,
            ast_arena,
        }
    }

    pub(crate) fn error<E>(&mut self, span: Span<BytePos>, error: E) -> RcType
    where
        E: Into<HelpError<Symbol, RcType>>,
    {
        let error = error.into();
        debug!("Error: {}", error);
        self.errors.push(Spanned {
            span: span,
            value: error,
        });
        self.subs.error()
    }

    fn bool(&mut self) -> RcType {
        let typ = self.environment.get_bool().clone();
        self.translate_arc_type(&typ)
    }

    fn find_at(&mut self, span: Span<BytePos>, id: &Symbol) -> ModType {
        match self.find(id) {
            Ok(typ) => typ,
            Err(err) => ModType::wobbly(self.error(span, err)),
        }
    }

    fn find(&mut self, id: &Symbol) -> TcResult<ModType> {
        match self.environment.find_mod_type(id).map(|t| t.to_owned()) {
            Some(typ) => {
                self.named_variables.clear();
                debug!("Find {} : {}", self.symbols.string(id), typ);
                Ok(typ)
            }
            None => {
                // Don't report global variables inserted by the `import!` macro as undefined
                // (if they don't exist the error will already have been reported by the macro)
                if id.is_global() {
                    Ok(ModType::wobbly(self.subs.new_var()))
                } else {
                    info!("Undefined variable {}", id);
                    Err(TypeError::UndefinedVariable(id.clone()))
                }
            }
        }
    }

    fn find_type_info_at(&mut self, span: Span<BytePos>, id: &Symbol) -> Alias<Symbol, RcType> {
        match self.find_type_info(id).map(|alias| alias.clone()) {
            Ok(alias) => alias,
            Err(err) => {
                self.errors.push(Spanned {
                    span: span,
                    value: err.into(),
                });
                let hole = self.subs.hole();
                self.subs.new_alias(id.clone(), Vec::new(), hole)
            }
        }
    }

    fn find_type_info(&self, id: &Symbol) -> TcResult<Alias<Symbol, RcType>> {
        self.environment
            .find_type_info(id)
            .ok_or_else(|| TypeError::UndefinedType(id.clone()))
    }

    fn stack_var(&mut self, id: Symbol, typ: RcType) {
        let modifier = if typ
            .flags()
            .intersects(Flags::HAS_VARIABLES | Flags::HAS_FORALL)
        {
            TypeModifier::Wobbly
        } else {
            TypeModifier::Rigid
        };
        debug!("Insert {} : {:?} {}", id, modifier, typ);

        self.implicit_resolver.on_stack_var(&self.subs, &id, &typ);

        self.environment.stack.insert(
            id,
            StackBinding {
                typ: ModType::new(modifier, typ),
            },
        );
    }

    fn stack_type(&mut self, id: Symbol, alias: &Alias<Symbol, RcType>) {
        // Insert variant constructors into the local scope
        //

        // We want to prevent the constructors of more specialized aliases from shadowing the more
        // general ones so we get the canonical alias and then take its inner type without applying
        // any types to always get the most general type of the constructors
        //
        // ```
        // type Option a = | None | Some a
        // type OptionInt = Option Int
        // // Should work
        // Some ""
        // ```
        let aliased_type = alias.typ(&mut &self.subs);
        let canonical_alias_type = resolve::AliasRemover::new()
            .canonical_alias(&self.environment, &mut &self.subs, &aliased_type, |alias| {
                match **alias.unresolved_type() {
                    Type::Variant(_) => true,
                    _ => false,
                }
            })
            .unwrap_or_else(|_err| {
                // The error is reported in unification
                aliased_type.clone()
            });

        let (outer_params, canonical_alias, inner_type) =
            alias.unpack_canonical_alias(&canonical_alias_type, |a| a.typ(&mut &self.subs));

        if let Type::Variant(ref variants) = **inner_type {
            for field in variants.row_iter().cloned() {
                let a = self.intern(Type::Alias(canonical_alias.clone()));
                let params = canonical_alias
                    .params()
                    .iter()
                    .map(|g| self.generic(g.clone()))
                    .collect();
                let variant_type = self.app(a.clone(), params);

                let ctor_type =
                    types::walk_move_type(field.typ.clone(), &mut |typ: &ArcType| match &**typ {
                        Type::Function(ArgType::Constructor, arg, ret) => {
                            Some(Type::function(Some(arg.clone()), ret.clone()))
                        }
                        Type::Ident(id) if canonical_alias.name == id.name => Some(a.clone()),
                        Type::Opaque => Some(variant_type.clone()),
                        _ => None,
                    });

                let typ = self.forall(
                    canonical_alias
                        .params()
                        .iter()
                        .chain(outer_params.iter())
                        .cloned()
                        .collect(),
                    ctor_type,
                );

                let symbol = self.symbols.symbols().simple_symbol(field.name.as_str());
                self.stack_var(symbol, typ);
            }
        }

        let generic_args = alias
            .params()
            .iter()
            .cloned()
            .map(|g| self.generic(g))
            .collect();
        let typ = self.subs.app(alias.as_ref().clone(), generic_args);
        {
            // FIXME: Workaround so that both the types name in this module and its global
            // name are imported. Without this aliases may not be traversed properly
            self.environment
                .stack_types
                .insert(alias.name.clone(), (typ.clone(), alias.clone()));
        }
        self.environment
            .stack_types
            .insert(id, (typ, alias.clone()));
    }

    fn enter_scope(&mut self) {
        self.environment.stack.enter_scope();
        self.environment.stack_types.enter_scope();
        self.implicit_resolver.enter_scope();
    }

    fn exit_scope(&mut self) {
        self.environment.stack.exit_scope();
        self.environment.stack_types.exit_scope();
        self.implicit_resolver.exit_scope();
    }

    fn generalize_binding(
        &mut self,
        level: u32,
        resolved_type: &mut RcType,
        binding: &mut ValueBinding<'ast, Symbol>,
    ) {
        let mut generalizer = TypeGeneralizer::new(level, self, resolved_type, binding.name.span);
        generalize_binding(&mut generalizer, resolved_type, binding);
    }

    fn generalize_variables<'i>(
        &mut self,
        level: u32,
        args: &mut dyn Iterator<Item = &'i mut SpannedIdent<Symbol>>,
        expr: &mut SpannedExpr<Symbol>,
    ) {
        let typ = self.subs.hole();
        TypeGeneralizer::new(level, self, &typ, expr.span).generalize_variables(args, expr)
    }

    fn generalize_type_errors(&mut self, errors: &mut Errors<SpannedTypeError<Symbol, RcType>>) {
        self.environment.skolem_variables.enter_scope();

        for err in errors {
            use self::TypeError::*;

            match err.value.error {
                UndefinedVariable(_)
                | UndefinedType(_)
                | DuplicateTypeDefinition(_)
                | DuplicateField(_)
                | UndefinedRecord { .. }
                | EmptyCase
                | KindError(_)
                | RecursionCheck(_)
                | Message(_) => (),
                NotAFunction(ref mut typ)
                | UndefinedField(ref mut typ, _)
                | PatternError {
                    constructor_type: ref mut typ,
                    ..
                }
                | InvalidProjection(ref mut typ)
                | TypeConstructorReturnsWrongType {
                    actual: ref mut typ,
                    ..
                } => self.generalize_type(0, typ, err.span),
                UnableToResolveImplicit(ref mut inner_err) => {
                    use crate::implicits::ErrorKind::*;
                    match inner_err.kind {
                        MissingImplicit(ref mut typ) => {
                            self.generalize_type(0, typ, err.span);
                        }
                        AmbiguousImplicit(ref mut xs) => {
                            for entry in xs {
                                self.generalize_type(0, &mut entry.typ, err.span);
                            }
                        }
                        LoopInImplicitResolution(..) => (),
                    }
                    let err_span = err.span;
                    inner_err.reason = inner_err
                        .reason
                        .iter()
                        .map(|typ| {
                            let mut typ = typ.clone();
                            self.generalize_type(0, &mut typ, err_span);
                            typ
                        })
                        .collect();
                }
                Unification(ref mut expected, ref mut actual, ref mut errors) => {
                    self.generalize_type_without_forall(0, expected, err.span);
                    self.generalize_type_without_forall(0, actual, err.span);
                    for unify_err in errors {
                        match *unify_err {
                            unify::Error::TypeMismatch(ref mut l, ref mut r) => {
                                self.generalize_type_without_forall(0, l, err.span);
                                self.generalize_type_without_forall(0, r, err.span);
                            }
                            unify::Error::Substitution(ref mut occurs_err) => match *occurs_err {
                                substitution::Error::Occurs(_, ref mut typ) => {
                                    self.generalize_type_without_forall(0, typ, err.span);
                                }
                            },
                            unify::Error::Other(ref mut other_err) => {
                                if let unify_type::TypeError::MissingFields(ref mut typ, _) =
                                    *other_err
                                {
                                    self.generalize_type_without_forall(0, typ, err.span);
                                }
                            }
                        }
                    }
                }
            }
        }

        self.environment.skolem_variables.exit_scope();
    }

    /// Typecheck `expr`. If successful the type of the expression will be returned and all
    /// identifiers in `expr` will be filled with the inferred type
    pub fn typecheck_expr(
        &mut self,
        expr: &mut SpannedExpr<'ast, Symbol>,
    ) -> Result<ArcType, Error> {
        self.typecheck_expr_expected(expr, None)
    }

    pub fn typecheck_expr_expected(
        &mut self,
        expr: &mut SpannedExpr<'ast, Symbol>,
        expected_type: Option<&ArcType>,
    ) -> Result<ArcType, Error> {
        let expected_type = expected_type.map(|t| self.translate_arc_type(t));

        self.typecheck_expr_expected_(expr, expected_type.as_ref())
            .map(|t| self.translate_rc_type(&t))
    }

    fn typecheck_expr_expected_(
        &mut self,
        expr: &mut SpannedExpr<'ast, Symbol>,
        expected_type: Option<&RcType>,
    ) -> Result<RcType, Error> {
        fn tail_expr<'e, 'ast>(
            e: &'e mut SpannedExpr<'ast, Symbol>,
        ) -> &'e mut SpannedExpr<'ast, Symbol> {
            match e.value {
                Expr::LetBindings(_, ref mut b) | Expr::TypeBindings(_, ref mut b) => tail_expr(b),
                _ => e,
            }
        }
        info!("Typechecking {}", self.symbols.module());
        // FIXME self.subs.clear();
        self.environment.stack.clear();

        if let Err(err) = crate::recursion_check::check_expr(expr) {
            self.errors.extend(
                err.into_iter()
                    .map(|err| pos::spanned(err.span, TypeError::from(err.value).into())),
            );
        }

        let temp = expected_type.and_then(|expected| self.create_unifiable_signature(expected));
        let expected_type = temp.as_ref().or(expected_type);

        let mut typ = if let Some(expected_type) = expected_type {
            self.skolemize_in(
                expr.span,
                ModType::rigid(&expected_type),
                |self_, expected_type| {
                    self_.typecheck_bindings(true, expr, Some(ModType::rigid(&expected_type)))
                },
            )
        } else {
            self.typecheck_bindings(true, expr, None)
        };

        {
            if let Some(expected_type) = expected_type {
                let mut type_cache = &self.subs;
                self.environment.skolem_variables.extend(
                    expected_type
                        .forall_params()
                        .map(|param| (param.id.clone(), type_cache.hole())),
                );
            }
            // Only the 'tail' expression need to be generalized at this point as all bindings
            // will have already been generalized
            let tail = tail_expr(expr);
            crate::implicits::resolve(self, tail);
            self.generalize_type(0, &mut typ, tail.span);
            self.generalize_variables(0, &mut [].iter_mut(), tail);
        }

        {
            struct ReplaceVisitor<'a: 'b, 'b, 'ast> {
                tc: &'b mut Typecheck<'a, 'ast>,
            }

            impl<'a, 'b, 'd> MutVisitor<'d, '_> for ReplaceVisitor<'a, 'b, '_> {
                type Ident = Symbol;

                fn visit_typ(&mut self, typ: &mut ArcType) {
                    *typ = if let Type::Variable(var) = &**typ {
                        let typ = self
                            .tc
                            .subs
                            .find_type_for_var(var.id)
                            .cloned()
                            .unwrap_or_else(|| self.tc.subs.error());

                        self.tc.translate_rc_type(&typ)
                    } else {
                        return;
                    }
                }
            }

            {
                let mut visitor = ReplaceVisitor { tc: self };
                visitor.visit_expr(expr);
            }
        }

        if self.errors.has_errors() {
            let mut errors = mem::replace(&mut self.errors, Errors::new());
            let l = errors.len();
            debug!("Generalize type errors");
            self.generalize_type_errors(&mut errors);
            // FIXME We shouldn't even generate errors here
            while errors.len() > l {
                errors.pop();
            }

            Err(errors
                .into_iter()
                .map(|spanned| {
                    spanned.map(|err| crate::base::error::Help {
                        error: err.error.map_t(&mut |t| self.translate_rc_type(&t)),
                        help: err.help,
                    })
                })
                .collect())
        } else {
            debug!("Typecheck result: {}", typ);
            Ok(typ.concrete)
        }
    }

    fn infer_expr(&mut self, expr: &mut SpannedExpr<'ast, Symbol>) -> ModType {
        self.typecheck_opt(expr, None)
    }

    fn typecheck(
        &mut self,
        expr: &mut SpannedExpr<'ast, Symbol>,
        expected_type: ModTypeRef,
    ) -> ModType {
        self.typecheck_opt(expr, Some(expected_type))
    }

    /// Main typechecking function. Returns the type of the expression if typechecking was
    /// successful
    fn typecheck_opt(
        &mut self,
        expr: &mut SpannedExpr<'ast, Symbol>,
        mut expected_type: Option<ModTypeRef>,
    ) -> ModType {
        let returned_type;

        match self.typecheck_(expr, &mut expected_type) {
            Ok((typ, args)) => {
                if !args.is_empty() {
                    match expr.value {
                        Expr::App {
                            ref mut implicit_args,
                            ..
                        } => {
                            if implicit_args.is_empty() {
                                *implicit_args = self.ast_arena.alloc_extend(args);
                            } else {
                                *implicit_args = self.ast_arena.alloc_extend(
                                    implicit_args.iter_mut().map(mem::take).chain(args),
                                );
                            }
                        }
                        _ => {
                            let func = mem::take(&mut expr.value);
                            expr.value = Expr::App {
                                func: self.ast_arena.alloc(pos::spanned(expr.span, func)),
                                implicit_args: self.ast_arena.alloc_extend(args),
                                args: &mut [],
                            }
                        }
                    }
                }

                returned_type = match expected_type {
                    Some(expected_type) => ModType::new(
                        expected_type.modifier,
                        self.subsumes_expr(expr.span, &typ, expected_type.concrete.clone(), expr),
                    ),
                    None => typ,
                };
            }
            Err(err) => {
                returned_type = ModType::wobbly(self.subs.error());
                self.errors.push(Spanned {
                    span: expr_check_span(expr),
                    value: err.into(),
                });
            }
        }
        returned_type
    }

    /// `expected_type` should be set to `None` if subsumption is done with it (to prevent us from
    /// doing it twice)
    fn typecheck_(
        &mut self,
        expr: &mut SpannedExpr<'ast, Symbol>,
        expected_type: &mut Option<ModTypeRef>,
    ) -> TcResult<(ModType, Vec<SpannedExpr<'ast, Symbol>>)> {
        if let Some(result) = self.check_macro(expr) {
            return Ok((result?, Vec::new()));
        }
        match expr.value {
            Expr::Ident(ref mut id) => {
                let typ = self.find(&id.name)?;
                let modifier = typ.modifier;
                let (args, typ) = self.instantiate_sigma(
                    expr.span,
                    &typ,
                    &mut expected_type.take().map(|t| t.concrete),
                );
                id.typ = self.subs.bind_arc(&typ);
                Ok((ModType::new(modifier, typ), args))
            }
            Expr::Literal(ref lit) => Ok((
                ModType::rigid(match *lit {
                    Literal::Int(_) => self.subs.int(),
                    Literal::Byte(_) => self.subs.byte(),
                    Literal::Float(_) => self.subs.float(),
                    Literal::String(_) => self.subs.string(),
                    Literal::Char(_) => self.subs.char(),
                }),
                Vec::new(),
            )),
            Expr::App {
                ref mut func,
                ref mut implicit_args,
                ref mut args,
            } => {
                let func_type = self.infer_expr(func);
                let mut implicit_vec = CowVec::Borrowed(implicit_args);
                let typ = self.typecheck_application(
                    expr.span,
                    func_type,
                    &mut implicit_vec,
                    &mut **args,
                );
                if let CowVec::Owned(implicit_vec) = implicit_vec {
                    *implicit_args = self.ast_arena.alloc_extend(implicit_vec);
                }

                typ
            }
            Expr::IfElse(ref mut pred, ref mut if_true, ref mut if_false) => {
                let bool_type = self.bool();
                let pred_type = self.typecheck(&mut **pred, ModType::rigid(&bool_type));
                self.unify_span(expr_check_span(pred), &bool_type, pred_type.concrete);

                // Both branches must unify to the same type
                let true_type = self.typecheck_opt(&mut **if_true, expected_type.clone());
                let false_type = self.typecheck_opt(&mut **if_false, expected_type.take());

                let modifier = true_type.modifier | false_type.modifier;

                let true_type = self.instantiate_generics(&true_type);
                let false_type = self.instantiate_generics(&false_type);

                self.unify(&true_type, false_type)
                    .map(|t| (ModType::new(modifier, t), Vec::new()))
            }
            Expr::Infix {
                ref mut lhs,
                ref mut op,
                ref mut rhs,
                ref mut implicit_args,
            } => {
                let op_name = String::from(self.symbols.string(&op.value.name));
                let func_type = if op_name.starts_with('#') {
                    // Handle primitives
                    let op_type = op_name.trim_matches(|c: char| !c.is_alphabetic());
                    let builtin_type = op_type.parse().map_err(|_| {
                        TypeError::Message("Invalid builtin type for operator".to_string())
                    })?;
                    let prim_type = self.subs.builtin_type(builtin_type);
                    let return_type = match &op_name[1 + op_type.len()..] {
                        "+" | "-" | "*" | "/" => prim_type.clone(),
                        "==" | "<" => self.bool(),
                        _ => return Err(TypeError::UndefinedVariable(op.value.name.clone())),
                    };
                    ModType::rigid(self.subs.function(
                        vec![prim_type.clone(), prim_type.clone()],
                        return_type.clone(),
                    ))
                } else {
                    match &*op_name {
                        "&&" | "||" => {
                            let b = self.bool();
                            ModType::rigid(self.subs.function(vec![b.clone(), b.clone()], b))
                        }
                        _ => self.find_at(op.span, &op.value.name),
                    }
                };

                let func_type =
                    ModType::new(func_type.modifier, self.instantiate_generics(&func_type));

                op.value.typ = self.subs.bind_arc(&func_type);

                let mut implicit_vec = CowVec::Borrowed(implicit_args);
                let typ = self.typecheck_application(
                    op.span,
                    func_type,
                    &mut implicit_vec,
                    [&mut **lhs, &mut **rhs].iter_mut().map(|expr| &mut **expr),
                );
                if let CowVec::Owned(implicit_vec) = implicit_vec {
                    *implicit_args = self.ast_arena.alloc_extend(implicit_vec);
                }
                typ
            }
            Expr::Tuple {
                ref mut typ,
                elems: ref mut exprs,
            } => {
                let new_type = match exprs.len() {
                    0 => ModType::rigid(self.unit()),
                    1 => self.typecheck_opt(&mut exprs[0], expected_type.take()),
                    _ => {
                        let mut modifier = TypeModifier::Rigid;
                        let fields = exprs
                            .iter_mut()
                            .enumerate()
                            .map(|(i, expr)| {
                                let typ = self.infer_expr(expr);
                                modifier |= typ.modifier;
                                Field {
                                    name: self.symbols.simple_symbol(format!("_{}", i)),
                                    typ: typ.concrete,
                                }
                            })
                            .collect();
                        ModType::new(modifier, self.record(vec![], fields))
                    }
                };
                *typ = self.subs.bind_arc(&new_type);
                Ok((new_type, Vec::new()))
            }
            Expr::Match(ref mut expr, ref mut alts) => {
                let mut scrutinee_type = self.infer_expr(&mut **expr);
                let modifier = scrutinee_type.modifier;
                let expected_type = expected_type.take().map(|t| t.to_owned());

                let mut unaliased_scrutinee_type = match alts.first().map(|alt| &alt.pattern.value)
                {
                    Some(Pattern::Constructor(..)) => {
                        let typ = self.remove_aliases(scrutinee_type.concrete.clone());
                        ModType::new(modifier, self.instantiate_generics(&typ))
                    }
                    _ => scrutinee_type.clone(),
                };

                let mut expr_type: Option<ModType> = None;

                let original_scrutinee_type = scrutinee_type.clone();

                for alt in alts.iter_mut() {
                    self.enter_scope();
                    self.refined_variables.enter_scope();

                    self.typecheck_pattern(
                        &mut alt.pattern,
                        original_scrutinee_type.clone(),
                        scrutinee_type.concrete.clone(),
                    );

                    let mut alt_type = self
                        .typecheck_opt(&mut alt.expr, expected_type.as_ref().map(|t| t.as_ref()));
                    alt_type.concrete = self.instantiate_generics(&alt_type);
                    match expr_type {
                        Some(ref expr_type) if expected_type.is_none() => {
                            alt_type.concrete =
                                self.unify_span(alt.expr.span, expr_type, alt_type.concrete);
                        }
                        _ => (),
                    }

                    for (var, _) in self.refined_variables.exit_scope() {
                        self.subs.reset(var);
                    }
                    self.exit_scope();

                    // The variant we matched on will not appear in any followup bindings so remove
                    // this variant from the type we are matching on
                    //
                    // TODO Make this more general so it can error when not matching on all the
                    // variants
                    {
                        *unaliased_scrutinee_type = self.subs.zonk(&unaliased_scrutinee_type);
                        let replaced = match (&alt.pattern.value, &**unaliased_scrutinee_type) {
                            (Pattern::Constructor(id, _), Type::Variant(row)) => {
                                let mut variant_iter = row.row_iter();
                                let variants = variant_iter
                                    .by_ref()
                                    .filter(|variant| variant.name != id.name)
                                    .cloned()
                                    .collect();

                                // Don't remove constructors on closed records as they may fail to
                                // unify when checking against the pattern
                                if let Type::EmptyRow = **variant_iter.current_type() {
                                    false
                                } else {
                                    let rest = self.subs.new_var();
                                    scrutinee_type.concrete = self.poly_variant(variants, rest);
                                    true
                                }
                            }
                            _ => false,
                        };
                        if replaced {
                            unaliased_scrutinee_type = scrutinee_type.clone();
                        }
                    }

                    expr_type = Some(alt_type);
                }
                expr_type
                    .ok_or(TypeError::EmptyCase)
                    .map(|typ| (typ, Vec::new()))
            }

            Expr::TypeBindings(..) | Expr::LetBindings(..) => Ok((
                self.typecheck_bindings(false, expr, expected_type.take()),
                Vec::new(),
            )),

            Expr::Projection(ref mut expr, ref field_id, ref mut ast_field_typ) => {
                let mut expr_typ = self.infer_expr(&mut **expr);
                let modifier = expr_typ.modifier;
                debug!(
                    "Projection {} . {:?}",
                    &expr_typ,
                    self.symbols.string(field_id)
                );
                self.subs.make_real(&mut expr_typ);
                expr_typ.concrete = self.instantiate_generics(&expr_typ);
                let record = self.remove_aliases(expr_typ.concrete.clone());
                match *record {
                    Type::Variable(_) | Type::Record(_) => {
                        let field_type = record
                            .row_iter()
                            .find(|field| field.name.name_eq(field_id))
                            .map(|field| field.typ.clone());
                        let mut implicit_args = Vec::new();
                        let new_ast_field_type = match field_type {
                            Some(typ) => {
                                let (args, typ) = self.instantiate_sigma(
                                    expr.span,
                                    &typ,
                                    &mut expected_type.take().map(|t| t.concrete),
                                );
                                implicit_args = args;
                                typ
                            }
                            None => {
                                // FIXME As the polymorphic `record_type` do not have the type
                                // fields which `typ` this unification is only done after we
                                // checked if the field exists which lets field accesses on
                                // types with type fields still work
                                let field_var = self.subs.new_var();
                                let field = Field::new(field_id.clone(), field_var.clone());
                                let record_type =
                                    self.poly_record(vec![], vec![field], self.subs.new_var());
                                self.unify(&record_type, record)?;
                                field_var
                            }
                        };
                        *ast_field_typ = self.subs.bind_arc(&new_ast_field_type);
                        Ok((ModType::new(modifier, new_ast_field_type), implicit_args))
                    }
                    Type::Error => Ok((ModType::new(modifier, record.clone()), Vec::new())),
                    _ => Err(TypeError::InvalidProjection(record)),
                }
            }
            Expr::Array(ref mut array) => {
                let mut expected_element_type = ModType::rigid(self.subs.new_var());

                let array_type = self.subs.array(expected_element_type.concrete.clone());
                array.typ = self.subs.bind_arc(&array_type);
                if let Some(expected_type) = expected_type.take() {
                    self.unify_span(expr.span, &expected_type, array_type.clone());
                }

                for expr in &mut *array.exprs {
                    expected_element_type |=
                        self.typecheck(expr, ModType::wobbly(&expected_element_type));
                }

                Ok((ModType::wobbly(array_type), Vec::new()))
            }
            Expr::Lambda(ref mut lambda) => {
                let level = self.subs.var_id();
                let function_type = expected_type
                    .take()
                    .map(|t| t.to_owned())
                    .unwrap_or_else(|| ModType::wobbly(self.subs.new_var()));

                let start = expr.span.start();
                let mut typ =
                    self.skolemize_in(expr.span, function_type.as_ref(), |self_, function_type| {
                        self_.typecheck_lambda(
                            function_type,
                            start,
                            &mut lambda.args,
                            &mut lambda.body,
                        )
                    });

                self.generalize_type(level, &mut typ, expr.span);
                lambda.id.typ = self.subs.bind_arc(&typ);
                Ok((typ.clone(), Vec::new()))
            }
            Expr::Record {
                ref mut typ,
                ref mut types,
                exprs: ref mut fields,
                ref mut base,
            } => {
                let level = self.subs.var_id();

                let mut modifier = expected_type
                    .as_ref()
                    .map(|t| t.modifier)
                    .unwrap_or_default();

                let expected_record_type = expected_type.and_then(|expected_type| {
                    let expected_type = self.subs.real(&expected_type).clone();
                    let typ = resolve::remove_aliases_cow(
                        &self.environment,
                        &mut &self.subs,
                        &expected_type,
                    );
                    match **typ {
                        Type::Record(_) => Some(typ.into_owned()),
                        _ => None,
                    }
                });

                let expected_type = match &expected_record_type {
                    Some(expected_record_type) => {
                        let mut expected_fields: FnvSet<_> = expected_record_type
                            .row_iter()
                            .map(|f| &f.name)
                            .chain(expected_record_type.type_field_iter().map(|f| &f.name))
                            .collect();

                        let expected_fields_matches = fields
                            .iter()
                            .map(|f| &f.name.value)
                            .chain(types.iter().map(|f| &f.name.value))
                            .all(|name| expected_fields.remove(&name))
                            && expected_fields.is_empty();

                        if expected_fields_matches {
                            // No need to do subsumption checking against the expected type as all the
                            // fields will be matched against anyway
                            expected_type.take();
                        }

                        Some(expected_record_type)
                    }
                    None => None,
                };

                let mut base_record_types = FnvMap::default();
                let mut base_record_fields = FnvMap::default();
                let mut base_types: Vec<Field<_, _>> = Vec::new();
                let mut base_fields: Vec<Field<_, RcType>> = Vec::new();
                if let Some(ref mut base) = *base {
                    let base_type = self.infer_expr(base);
                    let base_type = self.remove_aliases(base_type.concrete);

                    let record_type = self.poly_record(vec![], vec![], self.subs.new_var());
                    let base_type = self.unify_span(base.span, &record_type, base_type);
                    let base_type = self.subs.zonk(&base_type);

                    base_types.extend(base_type.type_field_iter().cloned());
                    base_fields.extend(base_type.row_iter().cloned());

                    base_record_types.extend(
                        base_types
                            .iter()
                            .map(|field| field.name.declared_name().to_string())
                            .enumerate()
                            .map(|(i, n)| (n, i)),
                    );
                    base_record_fields.extend(
                        base_fields
                            .iter()
                            .map(|field| field.name.declared_name().to_string())
                            .enumerate()
                            .map(|(i, n)| (n, i)),
                    );
                }

                let mut duplicated_fields = FnvSet::default();

                let mut new_types: Vec<Field<_, _>> = Vec::with_capacity(types.len());
                for field in &mut **types {
                    if let Some(ref mut typ) = field.value {
                        let rc_type = self.translate_arc_type(typ);
                        if let Some(new_type) = self.create_unifiable_signature(&rc_type) {
                            *typ = self.translate_rc_type(&new_type);
                        }
                    }

                    let alias = self.find_type_info_at(field.name.span, &field.name.value);
                    if self.error_on_duplicated_field(&mut duplicated_fields, &field.name) {
                        match base_record_types.get(field.name.value.declared_name()) {
                            Some(&i) => base_types[i].typ = alias,
                            None => new_types.push(Field::new(field.name.value.clone(), alias)),
                        }
                    }
                }

                let mut new_fields: Vec<Field<_, RcType>> = Vec::with_capacity(fields.len());
                for field in &mut **fields {
                    let name = &field.name.value;
                    let expected_field_type = expected_type
                        .as_ref()
                        .and_then(|expected_type| {
                            expected_type
                                .row_iter()
                                .find(|expected_field| expected_field.name.name_eq(&name))
                        })
                        .map(|field| ModType::new(modifier, &field.typ));

                    let mut typ = match field.value {
                        Some(ref mut expr) => self.typecheck_opt(expr, expected_field_type),
                        None => {
                            let typ = self.find_at(field.name.span, &field.name.value);
                            let modifier = typ.modifier;
                            match expected_field_type {
                                Some(expected_field_type) => {
                                    let mut implicit_args = Vec::new();
                                    let typ = self.subsumes_implicit(
                                        field.name.span,
                                        ErrorOrder::ExpectedActual,
                                        &expected_field_type.concrete,
                                        typ.concrete,
                                        &mut |implicit_arg| {
                                            implicit_args
                                                .push(pos::spanned(field.name.span, implicit_arg));
                                        },
                                    );

                                    if !implicit_args.is_empty() {
                                        field.value = Some(pos::spanned(
                                            field.name.span,
                                            Expr::App {
                                                func: self.ast_arena.alloc(pos::spanned(
                                                    field.name.span,
                                                    Expr::Ident(TypedIdent {
                                                        name: field.name.value.clone(),
                                                        typ: self.subs.bind_arc(&typ),
                                                    }),
                                                )),
                                                implicit_args: self
                                                    .ast_arena
                                                    .alloc_extend(implicit_args),
                                                args: &mut [],
                                            },
                                        ));
                                    }

                                    ModType::new(modifier, typ)
                                }
                                None => typ,
                            }
                        }
                    };
                    self.generalize_type(level, &mut typ, field.name.span);

                    if self.error_on_duplicated_field(&mut duplicated_fields, &field.name) {
                        match base_record_fields.get(field.name.value.declared_name()) {
                            Some(&i) => base_fields[i].typ = typ.concrete,
                            None => {
                                new_fields.push(Field::new(field.name.value.clone(), typ.concrete))
                            }
                        }
                    }

                    modifier |= typ.modifier;
                }

                new_types.extend(base_types);
                new_fields.extend(base_fields);
                let new_type = self.subs.record(new_types, new_fields);
                *typ = self.subs.bind_arc(&new_type);

                Ok((ModType::new(modifier, new_type), Vec::new()))
            }
            Expr::Block(ref mut exprs) => {
                let (last, exprs) = exprs.split_last_mut().expect("Expr in block");
                for expr in exprs {
                    self.infer_expr(expr);
                }
                Ok((self.typecheck_opt(last, expected_type.take()), Vec::new()))
            }
            Expr::Do(Do {
                ref mut id,
                ref mut typ,
                ref mut bound,
                ref mut body,
                ref mut flat_map_id,
            }) => {
                let do_span = expr.span.subspan(0.into(), 2.into());
                let flat_map_type = match flat_map_id
                    .as_mut()
                    .expect("flat_map inserted during renaming")
                    .value
                {
                    Expr::Ident(ref mut flat_map) => match self.find(&flat_map.name) {
                        Ok(x) => x,
                        Err(error) => {
                            self.error(
                                do_span,
                                crate::base::error::Help {
                                    error,
                                    help: Some(Help::UndefinedFlatMapInDo),
                                },
                            );
                            ModType::wobbly(self.subs.error())
                        }
                    },
                    _ => ice!("flat_map_id not inserted during renaming"),
                };

                let flat_map_type = self.instantiate_generics(&flat_map_type);

                let flat_map_type = match *flat_map_type {
                    Type::Function(ArgType::Implicit, ref arg_type, ref r) => {
                        let name = self.implicit_resolver.make_implicit_ident(arg_type);
                        *flat_map_id = Some(self.ast_arena.alloc(pos::spanned(
                            do_span,
                            Expr::App {
                                func: flat_map_id.take().unwrap(),
                                args: self.ast_arena.alloc_extend(Some(pos::spanned(
                                    do_span,
                                    Expr::Ident(TypedIdent {
                                        name,
                                        typ: self.subs.bind_arc(&arg_type),
                                    }),
                                ))),
                                implicit_args: &mut [],
                            },
                        )));
                        r.clone()
                    }
                    _ => flat_map_type.clone(),
                };

                let id_type = self.resolve_type_signature(typ.as_mut());
                let arg1 = self
                    .subs
                    .function(Some(id_type.concrete.clone()), self.subs.new_var());
                let arg2 = self.subs.new_var();

                let ret = expected_type
                    .as_ref()
                    .map(|t| t.to_owned())
                    .unwrap_or_else(|| ModType::wobbly(self.subs.new_var()));
                let func_type = self
                    .subs
                    .function(vec![arg1.clone(), arg2.clone()], ret.concrete.clone());

                self.typecheck(bound, ModType::wobbly(&arg2));

                self.unify_span(do_span, &flat_map_type, func_type);

                if let Some(ref mut id) = *id {
                    self.typecheck_pattern(id, id_type.clone(), id_type.concrete);
                }

                let body_type = self.typecheck(body, ret.as_ref());

                let ret = self.unify_span(body.span, &ret, body_type.concrete.clone());

                Ok((ModType::wobbly(ret), Vec::new()))
            }
            Expr::MacroExpansion {
                ref mut replacement,
                ..
            } => self.typecheck_(replacement, expected_type),

            Expr::Annotated(ref mut expr, ref mut typ) => {
                let mut typ = self.translate_arc_type(typ);
                if let Some(new) = self.create_unifiable_signature(&typ) {
                    typ = new;
                }
                self.typecheck_(expr, &mut Some(ModType::rigid(&typ)))
            }

            Expr::Error(ref typ) => Ok((
                ModType::wobbly(
                    typ.as_ref()
                        .map(|typ| self.translate_arc_type(typ))
                        .unwrap_or_else(|| self.subs.new_var()),
                ),
                Vec::new(),
            )),
        }
    }

    fn typecheck_application<'e, I>(
        &mut self,
        span: Span<BytePos>,
        func_type: ModType,
        implicit_args: &mut CowVec<SpannedExpr<'ast, Symbol>>,
        args: I,
    ) -> TcResult<(ModType, Vec<SpannedExpr<'ast, Symbol>>)>
    where
        I: IntoIterator<Item = &'e mut SpannedExpr<'ast, Symbol>>,
        I::IntoIter: ExactSizeIterator,
        'ast: 'e,
    {
        self.typecheck_application_(span, func_type, implicit_args, &mut args.into_iter())
            .map(|typ| (typ, Vec::new()))
    }

    fn typecheck_application_<'e>(
        &mut self,
        span: Span<BytePos>,
        func_type: ModType,
        implicit_args: &mut CowVec<SpannedExpr<'ast, Symbol>>,
        args: &mut dyn ExactSizeIterator<Item = &'e mut SpannedExpr<'ast, Symbol>>,
    ) -> TcResult<ModType>
    where
        'ast: 'e,
    {
        fn attach_extra_argument_help<F, R>(self_: &mut Typecheck, actual: u32, f: F) -> R
        where
            F: FnOnce(&mut Typecheck) -> R,
        {
            let errors_before = self_.errors.len();
            let t = f(self_);
            if errors_before != self_.errors.len() {
                let len = self_.errors.len();
                let expected_type = match self_.errors[len - 1].value.error {
                    TypeError::Unification(ref expected_type, ..) => expected_type.clone(),
                    _ => return t,
                };
                let extra = function_arg_iter(self_, expected_type).count() as u32;
                self_.errors[len - 1].value.help =
                    Some(Help::ExtraArgument(actual - extra, actual));
            }
            t
        }

        let args_len = args.len() as u32;

        let original_func_type = func_type.concrete.clone();
        let mut func_type = self.instantiate_generics(&func_type);

        let mut return_variables = FnvSet::default();

        for arg in &mut **implicit_args {
            let (arg_typ, ret_typ) = self.subsume_function(
                arg.span.start(),
                arg.span,
                ArgType::Implicit,
                func_type.clone(),
                &mut |_| unreachable!(),
            );

            let arg_typ = self.typecheck(arg, ModType::wobbly(&arg_typ));

            if arg_typ.modifier == TypeModifier::Rigid {
                types::walk_type(&self.subs.zonk(&arg_typ), &mut |typ: &RcType| {
                    if let Type::Variable(var) = &**typ {
                        return_variables.insert(var.id);
                    }
                });
            }

            func_type = ret_typ;
        }

        let mut not_a_function_index = None;

        let mut prev_arg_end = implicit_args.last().map_or(span, |arg| arg.span).end();
        for arg in args.map(|arg| arg.borrow_mut()) {
            let errors_before = self.errors.len();
            let (arg_ty, ret_ty) = self.subsume_function(
                prev_arg_end,
                arg.span,
                ArgType::Explicit,
                func_type.clone(),
                &mut |expr| implicit_args.as_owned().push(expr),
            );

            if errors_before != self.errors.len() {
                self.errors.pop();
                not_a_function_index = Some(arg);
                break;
            }

            let arg_ty = self.typecheck(arg, ModType::wobbly(&arg_ty));

            if arg_ty.modifier == TypeModifier::Rigid {
                types::walk_type(&self.subs.zonk(&arg_ty), &mut |typ: &RcType| {
                    if let Type::Variable(var) = &**typ {
                        return_variables.insert(var.id);
                    }
                });
            }

            func_type = ret_ty;

            prev_arg_end = arg.span.end();
        }

        if let Some(arg) = not_a_function_index {
            let span_start = arg.span.start();

            let extra_args = Some(arg).into_iter().chain(args);

            let mut span_end = BytePos::default();
            let arg_types = extra_args
                .map(|arg| {
                    span_end = arg.span.end();
                    self.infer_expr(arg.borrow_mut()).concrete
                })
                .collect::<Vec<_>>();
            let expected = self.subs.function(arg_types, self.subs.new_var());

            let span = Span::new(span_start, span_end);
            attach_extra_argument_help(self, args_len, |self_| {
                self_.subsumes(
                    span,
                    ErrorOrder::ExpectedActual,
                    &expected,
                    func_type.clone(),
                )
            });

            func_type = expected;
        }

        let mut modifier = TypeModifier::Rigid;
        types::FlagsVisitor(Flags::HAS_VARIABLES, |typ: &RcType| {
            if modifier == TypeModifier::Rigid {
                if let Type::Variable(var) = &**typ {
                    if !return_variables.contains(&var.id) {
                        modifier = TypeModifier::Wobbly;
                    }
                }
            }
        })
        .walk(&self.subs.zonk(&original_func_type));

        Ok(ModType::new(modifier, func_type))
    }

    fn typecheck_lambda(
        &mut self,
        function_type: ModType,
        before_args_pos: BytePos,
        args_ref: &mut &'ast mut [Argument<SpannedIdent<Symbol>>],
        body: &mut SpannedExpr<'ast, Symbol>,
    ) -> ModType {
        debug!("Checking lambda {}", function_type);
        debug!("Checking lambda {:#?}", self.environment.skolem_variables);
        self.enter_scope();

        let mut args = CowVec::Borrowed(*args_ref);

        let mut arg_types = Vec::new();

        let body_type = {
            let mut return_type = function_type.clone();

            let mut i = 0;

            while i < args.len()
                || return_type
                    .as_function_with_type()
                    .map_or(false, |(arg_type, _, _)| arg_type == ArgType::Implicit)
            {
                let span = args
                    .get(i)
                    .map(|a| a.name.span)
                    .unwrap_or_else(|| pos::Span::new(before_args_pos, before_args_pos));
                let (type_implicit, arg_type, ret_type) =
                    self.unify_function(span, return_type.concrete.clone());

                match type_implicit {
                    ArgType::Implicit => {
                        let arg = match args.get(i).map(|t| t.arg_type) {
                            Some(ArgType::Implicit) => {
                                i += 1;
                                &mut args[i - 1].name.value
                            }
                            _ => {
                                let id = Symbol::from("__implicit_arg");
                                let pos = if i == 0 {
                                    before_args_pos
                                } else {
                                    args.get(i - 1)
                                        .map(|arg| arg.name.span.end())
                                        .unwrap_or(before_args_pos)
                                };
                                args.as_owned().insert(
                                    i,
                                    Argument::implicit(pos::spanned2(
                                        pos,
                                        pos,
                                        TypedIdent {
                                            typ: self.subs.bind_arc(&arg_type),
                                            name: id.clone(),
                                        },
                                    )),
                                );
                                i += 1;
                                &mut args[i - 1].name.value
                            }
                        };
                        arg.typ = self.subs.bind_arc(&arg_type);
                        arg_types.push(arg_type.clone());
                        self.stack_var(arg.name.clone(), arg_type.clone());
                    }
                    ArgType::Explicit => match args.get_mut(i) {
                        Some(&mut Argument {
                            arg_type: ArgType::Implicit,
                            name: ref arg,
                        }) => {
                            i += 1;
                            self.error(
                                    arg.span,
                                    TypeError::Message(format!(
                                        "Expected implicit argument but an explicit argument was specified"
                                    )),
                                );
                        }
                        Some(&mut Argument {
                            arg_type: ArgType::Explicit,
                            name: ref mut arg,
                        }) => {
                            i += 1;
                            let arg = &mut arg.value;

                            arg.typ = self.subs.bind_arc(&arg_type);
                            arg_types.push(arg_type.clone());
                            self.stack_var(arg.name.clone(), arg_type);
                        }
                        _ => break,
                    },
                    ArgType::Constructor => unreachable!(),
                }
                return_type = ModType::new(function_type.modifier, ret_type);
            }

            return_type
        };

        if let CowVec::Owned(args) = args {
            *args_ref = self.ast_arena.alloc_extend(args);
        }

        let body_type = self.typecheck(body, body_type.as_ref());
        self.exit_scope();

        let f = self.subs.function(arg_types, body_type.concrete);
        let done = self.with_forall(&function_type, ModType::new(body_type.modifier, f));

        debug!("Checked lambda {}", done);
        done
    }

    fn typecheck_let_pattern(
        &mut self,
        pattern: &mut SpannedPattern<Symbol>,
        match_type: RcType,
    ) -> RcType {
        match pattern.value {
            Pattern::Constructor(ref id, _) | Pattern::Ident(ref id)
                if id.name.declared_name().starts_with(char::is_uppercase) =>
            {
                self.error(
                    pattern.span,
                    TypeError::Message(format!("Unexpected type constructor `{}`", id.name)),
                )
            }
            _ => self.typecheck_pattern(pattern, ModType::wobbly(match_type.clone()), match_type),
        }
    }

    fn typecheck_pattern(
        &mut self,
        pattern: &mut SpannedPattern<Symbol>,
        mut match_type: ModType,
        partial_match_type: RcType,
    ) -> RcType {
        let span = pattern.span;
        match &mut pattern.value {
            Pattern::As(id, pat) => {
                self.stack_var(id.value.clone(), partial_match_type.clone());
                self.typecheck_pattern(pat, match_type.clone(), partial_match_type.clone());
                partial_match_type
            }
            Pattern::Constructor(id, args) => {
                match_type.concrete = self.subs.real(&match_type).clone();
                match_type.concrete = self.instantiate_generics(&match_type);
                match_type.concrete = self.subs.zonk(&match_type);
                // Find the enum constructor and return the types for its arguments
                let ctor_type = self.find_at(span, &id.name);

                id.typ = self.subs.bind_arc(&ctor_type);

                debug!("Wobbly check {:?}: {}", match_type.modifier, match_type);
                let wobbly = match_type.modifier == TypeModifier::Wobbly;
                let ctor_type = if wobbly {
                    self.instantiate_generics(&ctor_type)
                } else {
                    self.skolemize(&ctor_type)
                };

                let return_type = ctor_return_type(&ctor_type);
                if wobbly {
                    self.subsumes(
                        span,
                        ErrorOrder::ExpectedActual,
                        &return_type,
                        match_type.concrete,
                    );
                } else {
                    self.refines(
                        span,
                        ErrorOrder::ExpectedActual,
                        &return_type,
                        match_type.concrete,
                    );
                }

                match self.typecheck_pattern_rec(args, &ctor_type) {
                    Ok(return_type) => return_type,
                    Err(err) => self.error(span, err),
                }
            }
            Pattern::Record {
                typ: curr_typ,
                fields,
                implicit_import,
            } => {
                let uninstantiated_match_type = match_type.clone();
                match_type.concrete = self.instantiate_generics(&match_type);
                *curr_typ = self.subs.bind_arc(&match_type);

                let mut pattern_fields = Vec::with_capacity(fields.len());

                let mut duplicated_fields = FnvSet::default();
                {
                    let all_fields = fields.iter().map(|field| match field {
                        PatternField::Type { name } | PatternField::Value { name, .. } => name,
                    });
                    for field in all_fields {
                        if self.error_on_duplicated_field(&mut duplicated_fields, &field) {
                            pattern_fields.push(field.value.clone());
                        }
                    }
                }

                let record_match_type = self.remove_alias(match_type.concrete.clone());

                let mut missing_fields_from_match_type = Vec::new();

                for (name, value) in ast::pattern_values_mut(fields) {
                    let name = &name.value;
                    // The field should always exist since the type was constructed from the pattern
                    let field_type = record_match_type
                        .row_iter()
                        .find(|f| f.name.name_eq(name))
                        .map(|f| f.typ.clone())
                        .unwrap_or_else(|| {
                            let typ = self.subs.new_var();
                            missing_fields_from_match_type.push(Field {
                                name: name.clone(),
                                typ: typ.clone(),
                            });
                            typ
                        });
                    match value {
                        Some(pattern) => {
                            self.typecheck_pattern(
                                pattern,
                                ModType::new(match_type.modifier, field_type.clone()),
                                field_type,
                            );
                        }
                        None => {
                            self.stack_var(name.clone(), field_type);
                        }
                    }
                }

                // Check that all types declared in the pattern exists
                for name in ast::pattern_types(fields) {
                    let span = name.span;
                    let name = name.value.clone();
                    // The `types` in the record type should have a type matching the
                    // `name`
                    let field_type = record_match_type
                        .type_field_iter()
                        .find(|field| field.name.name_eq(&name));

                    let alias;
                    let alias = match field_type {
                        Some(field_type) => {
                            if let Some(meta) = self.implicit_resolver.metadata.remove(&name) {
                                self.implicit_resolver
                                    .metadata
                                    .insert(field_type.typ.name.clone(), meta);
                            }
                            &field_type.typ
                        }
                        None => {
                            self.error(
                                span,
                                TypeError::UndefinedField(
                                    match_type.concrete.clone(),
                                    name.clone(),
                                ),
                            );
                            // We still define the type so that any uses later on in the program
                            // won't error on UndefinedType
                            let hole = self.subs.error();
                            alias = self.new_alias(name.clone(), Vec::new(), hole);
                            &alias
                        }
                    };

                    self.stack_type(name, &alias);
                }

                if !missing_fields_from_match_type.is_empty() {
                    let expected = self.subs.poly_record(
                        vec![],
                        missing_fields_from_match_type,
                        self.subs.new_var(),
                    );
                    self.unify_span(pattern.span, &expected, match_type.concrete.clone());
                }

                if let Some(ref implicit_import) = *implicit_import {
                    self.implicit_resolver.add_implicits_of_record(
                        &self.subs,
                        &implicit_import.value,
                        &uninstantiated_match_type,
                    );
                }

                match_type.concrete
            }
            Pattern::Tuple { typ, elems } => {
                let tuple_type = {
                    let subs = &mut self.subs;
                    (&*subs).tuple(&mut self.symbols, (0..elems.len()).map(|_| subs.new_var()))
                };
                let new_type = self.unify_span(span, &tuple_type, match_type.concrete);
                *typ = self.subs.bind_arc(&new_type);
                for (elem, field) in elems.iter_mut().zip(tuple_type.row_iter()) {
                    self.typecheck_pattern(
                        elem,
                        ModType::new(match_type.modifier, field.typ.clone()),
                        field.typ.clone(),
                    );
                }
                tuple_type
            }
            Pattern::Ident(id) => {
                self.stack_var(id.name.clone(), partial_match_type.clone());
                id.typ = self.subs.bind_arc(&partial_match_type);
                partial_match_type
            }
            Pattern::Literal(l) => {
                let typ = l.env_type_of(&self.environment);
                let typ = self.translate_arc_type(&typ);
                self.unify_span(span, &match_type, typ);
                match_type.concrete
            }
            Pattern::Error => self.subs.new_var(),
        }
    }

    fn typecheck_pattern_rec(
        &mut self,
        args: &mut [SpannedPattern<Symbol>],
        typ: &RcType,
    ) -> TcResult<RcType> {
        let pattern_args = args.len();
        let mut pattern_iter = args.iter_mut();
        let mut type_iter = typ.arg_iter();
        loop {
            match (pattern_iter.next(), type_iter.next()) {
                (Some(arg_pattern), Some(arg)) => {
                    self.typecheck_pattern(arg_pattern, ModType::wobbly(arg.clone()), arg.clone());
                }
                (None, Some(_)) | (Some(_), None) => {
                    return Err(TypeError::PatternError {
                        constructor_type: typ.clone(),
                        pattern_args,
                    })
                }
                (None, None) => break,
            }
        }
        Ok(typ.clone())
    }

    fn translate_projected_type(&mut self, id: &[Symbol]) -> TcResult<RcType> {
        translate_projected_type(&self.environment, &mut self.symbols, &mut &self.subs, id)
    }

    // Stub kept in case multiple types are attempted again
    fn translate_arc_type(&mut self, arc_type: &ArcType) -> RcType {
        arc_type.clone()
    }

    // Stub kept in case multiple types are attempted again
    fn translate_rc_type(&mut self, rc_type: &RcType) -> ArcType {
        rc_type.clone()
    }

    fn translate_ast_type(&mut self, ast_type: &AstType<Symbol>) -> RcType {
        use crate::base::pos::HasSpan;

        match **ast_type {
            // Undo the hack in kindchecking that inserts a dummy alias wrapping a generic
            Type::Alias(ref alias) => match **alias.unresolved_type() {
                Type::Generic(ref gen) if gen.id == alias.name => self.ident(KindedIdent {
                    name: alias.name.clone(),
                    typ: alias.kind(&self.kind_cache).into_owned(),
                }),
                _ => types::translate_type_with(self, ast_type, |self_, typ| {
                    self_.translate_ast_type(typ)
                }),
            },

            Type::ExtendTypeRow {
                ref types,
                ref rest,
            } => {
                let types = types
                    .iter()
                    .map(|field| Field {
                        name: field.name.value.clone(),
                        typ: if let Type::Hole = **field.typ.unresolved_type() {
                            self.find_type_info_at(
                                field.typ.unresolved_type().span(),
                                &field.name.value,
                            )
                        } else {
                            let alias_data =
                                types::translate_alias(self, &field.typ, |self_, typ| {
                                    self_.translate_ast_type(typ)
                                });
                            self.new_data_alias(alias_data)
                        },
                    })
                    .collect();

                let rest = self.translate_ast_type(rest);

                self.extend_type_row(types, rest)
            }

            Type::Projection(ref ids) => match self.translate_projected_type(ids) {
                Ok(typ) => typ,
                Err(err) => self.error(ast_type.span(), err),
            },

            _ => types::translate_type_with(self, ast_type, |self_, typ| {
                self_.translate_ast_type(typ)
            }),
        }
    }

    fn typecheck_bindings(
        &mut self,
        top_level: bool,
        mut expr: &mut SpannedExpr<'ast, Symbol>,
        expected_type: Option<ModTypeRef>,
    ) -> ModType {
        let mut scope_count = 0;

        let level = self.subs.var_id();

        loop {
            match expr.value {
                Expr::LetBindings(ref mut bindings, ref mut body) => {
                    self.typecheck_let_bindings(bindings);

                    scope_count += 1;

                    if top_level {
                        self.generalize_and_clear_subs(level, bindings);
                    }

                    expr = body
                }
                Expr::TypeBindings(ref mut bindings, ref mut body) => {
                    self.typecheck_type_bindings(bindings, body);

                    scope_count += 1;

                    expr = body;
                }
                _ => {
                    let typ = self.typecheck_opt(expr, expected_type);

                    for _ in 0..scope_count {
                        self.exit_scope();
                    }

                    return typ;
                }
            }
        }
    }

    fn resolve_type_signature(
        &mut self,
        mut signature: Option<&mut AstType<'_, Symbol>>,
    ) -> ModType {
        let mut mod_type = if let Some(ref mut typ) = signature {
            self.kindcheck(typ);
            let rc_type = self.translate_ast_type(typ);

            ModType::rigid(rc_type)
        } else {
            ModType::wobbly(self.subs.hole())
        };

        if let Some(typ) = self.create_unifiable_signature(&mod_type) {
            mod_type.concrete = typ;
        }
        mod_type
    }

    fn typecheck_let_bindings(&mut self, bindings: &mut ValueBindings<'ast, Symbol>) {
        self.enter_scope();
        self.environment.skolem_variables.enter_scope();
        self.environment.type_variables.enter_scope();
        let level = self.subs.var_id();

        let is_recursive = bindings.is_recursive();
        let mut resolved_types = AppVec::new();
        // When the definitions are allowed to be mutually recursive
        if is_recursive {
            for (i, bind) in bindings.iter_mut().enumerate() {
                let typ = {
                    resolved_types.push(self.resolve_type_signature(bind.typ.as_mut()));

                    resolved_types[i].concrete.clone()
                };
                self.typecheck_let_pattern(&mut bind.name, typ);
            }
        }

        let mut types = Vec::new();
        for (i, bind) in bindings.iter_mut().enumerate() {
            // Functions which are declared as `let f x = ...` are allowed to be self
            // recursive
            let typ = if !is_recursive {
                if let Some(ref mut typ) = bind.typ {
                    self.kindcheck(typ);
                    let rc_type = self.translate_ast_type(typ);

                    resolved_types.push(ModType::rigid(rc_type));
                } else {
                    resolved_types.push(ModType::wobbly(self.subs.hole()));
                }

                let typ = self.create_unifiable_signature(&resolved_types[i]);
                if let Some(typ) = typ {
                    resolved_types[i].concrete = typ;
                }

                let typ = resolved_types[i].as_ref();
                self.skolemize_in(bind.expr.span, typ, |self_, typ| {
                    self_
                        .environment
                        .type_variables
                        .extend(self_.named_variables.drain());

                    self_.typecheck_lambda(
                        typ,
                        bind.name.span.end(),
                        &mut bind.args,
                        &mut bind.expr,
                    )
                })
            } else {
                let typ = match bind.name.value {
                    Pattern::Ident(ref id) => {
                        let mut type_cache = &self.subs;
                        self.environment
                            .stack
                            .get(&id.name)
                            .map_or_else(|| ModType::wobbly(type_cache.error()), |b| b.typ.clone())
                    }
                    _ => ModType::wobbly(self.subs.error()),
                };

                self.skolemize_in_no_scope(bind.expr.span, typ.as_ref(), |self_, function_type| {
                    self_
                        .environment
                        .type_variables
                        .extend(self_.named_variables.drain());

                    self_.typecheck_lambda(
                        function_type,
                        bind.name.span.end(),
                        &mut bind.args,
                        &mut bind.expr,
                    )
                })
            };

            debug!("let {:?} : {}", bind.name, typ);

            if !is_recursive {
                let resolved_type = &mut resolved_types[i].concrete;
                bind.resolved_type = self.subs.bind_arc(&resolved_type);
                // Merge the type declaration and the actual type
                debug!("Generalize at {} = {}", level, resolved_type);
                self.generalize_binding(level, resolved_type, bind);
                debug!("Generalized mid {}", resolved_type);
                self.typecheck_let_pattern(&mut bind.name, resolved_type.clone());
                debug!("Generalized to {}", bind.resolved_type);
                self.finish_pattern(level, &mut bind.name, &resolved_type);
            } else {
                types.push(typ);
            }
        }

        if is_recursive {
            let hole = self.subs.hole();
            {
                let mut generalizer =
                    TypeGeneralizer::new(level, self, &hole, bindings[0].name.span);

                // Once all variables inside the let has been unified we can quantify them
                debug!("Generalize recursive at {}", level);
                for (bind, resolved_type) in bindings.iter_mut().zip(&mut resolved_types) {
                    bind.resolved_type = generalizer.tc.subs.bind_arc(&resolved_type);
                    debug!(
                        "Generalize {}: {}",
                        match bind.name.value {
                            ast::Pattern::Ident(ref id) => id.name.declared_name(),
                            _ => "",
                        },
                        resolved_type
                    );
                    generalize_binding(&mut generalizer, resolved_type, bind);
                    debug!("Generalize mid {}", resolved_type);
                    generalizer
                        .tc
                        .finish_pattern(level, &mut bind.name, &resolved_type);
                    debug!("Generalized to {}", resolved_type);
                }
            }

            debug!("End generalize recursive");
        }

        debug!("Typecheck `in`");
        self.environment.type_variables.exit_scope();
        self.environment.skolem_variables.exit_scope();
    }

    fn typecheck_type_bindings(
        &mut self,
        bindings: &mut [TypeBinding<Symbol>],
        expr: &SpannedExpr<'ast, Symbol>,
    ) {
        self.enter_scope();

        // Rename the types so they get a name which is distinct from types from other
        // modules
        for bind in bindings.iter_mut() {
            self.environment.skolem_variables.enter_scope();
            self.environment.type_variables.enter_scope();

            {
                let mut type_cache = &self.subs;
                for (k, v) in bind
                    .alias
                    .value
                    .params()
                    .iter()
                    .map(|param| (param.id.clone(), type_cache.hole()))
                {
                    self.environment
                        .skolem_variables
                        .insert(k.clone(), v.clone());
                    self.environment.type_variables.insert(k, v);
                }
            }
            self.check_type_binding(&bind.alias.value.name, bind.alias.value.unresolved_type());

            self.environment.type_variables.exit_scope();
            self.environment.skolem_variables.exit_scope();
        }

        {
            let mut check = KindCheck::new(
                &self.environment,
                &mut self.symbols,
                self.kind_cache.clone(),
            );

            // Setup kind variables for all holes and insert the types in the
            // the type expression into the kindcheck environment
            for bind in &mut *bindings {
                // Create the kind for this binding
                // Test a b : 2 -> 1 -> Type
                // and bind the same variables to the arguments of the type binding
                // ('a' and 'b' in the example)
                let mut id_kind = check.type_kind();
                for generic in bind.alias.value.params_mut().iter_mut().rev() {
                    check.instantiate_kinds(&mut generic.kind);
                    id_kind = Kind::function(generic.kind.clone(), id_kind);
                }
                check.add_local(bind.alias.value.name.clone(), id_kind);
            }

            // Kindcheck all the types in the environment
            for bind in &mut *bindings {
                check.enter_scope_with(
                    bind.alias
                        .value
                        .params()
                        .iter()
                        .map(|g| (g.id.clone(), g.kind.clone())),
                );

                let typ = bind
                    .alias
                    .value
                    .unresolved_type_mut()
                    .remove_single_forall();
                if let Err(errors) = check.kindcheck_type(typ) {
                    self.errors.extend(
                        errors
                            .into_iter()
                            .map(|err| pos::spanned(err.span, TypeError::from(err.value).into())),
                    );
                }
                check.exit_scope();
            }

            // All kinds are now inferred so replace the kinds store in the AST
            for bind in &mut *bindings {
                {
                    let typ = bind.alias.value.unresolved_type_mut();
                    check.finalize_type(typ);
                }
                for arg in bind.alias.value.params_mut() {
                    *arg = check.finalize_generic(arg);
                }
            }
        }

        let mut resolved_aliases = Vec::new();
        for bind in &mut *bindings {
            self.environment.skolem_variables.enter_scope();
            self.environment.type_variables.enter_scope();

            let mut alias = types::translate_alias(self, &bind.alias.value, |self_, typ| {
                self_.translate_ast_type(typ)
            });

            alias.is_implicit = bind.metadata.get_attribute("implicit").is_some();

            let replacement = self.create_unifiable_signature_with(
                // alias.unresolved_type() is a dummy in this context
                alias
                    .params()
                    .iter()
                    .map(|param| (param.id.clone(), alias.unresolved_type().clone())),
                alias.unresolved_type(),
            );

            if let Some(typ) = replacement {
                *alias.unresolved_type_mut() = typ;
            }
            resolved_aliases.push(alias);

            self.environment.type_variables.exit_scope();
            self.environment.skolem_variables.exit_scope();
        }

        let arc_alias_group = Alias::group(
            resolved_aliases
                .iter()
                .map(|a| types::translate_alias(self, &a, |self_, t| self_.translate_rc_type(t)))
                .collect(),
        );
        let alias_group = self.subs.alias_group(resolved_aliases);
        for (bind, alias) in bindings.iter_mut().zip(arc_alias_group) {
            bind.finalized_alias = Some(alias);
        }

        // Finally insert the declared types into the global scope
        for (bind, alias) in bindings.iter().zip(&alias_group) {
            if self.environment.stack_types.get(&bind.name.value).is_some() {
                self.errors.push(Spanned {
                    span: expr_check_span(expr),
                    // TODO Help to the position of the other field
                    value: TypeError::DuplicateTypeDefinition(bind.name.value.clone()).into(),
                });
            } else {
                self.stack_type(bind.name.value.clone(), alias);
            }
        }
    }

    fn kindcheck(&mut self, typ: &mut AstType<Symbol>) {
        let result = {
            let mut check = KindCheck::new(
                &self.environment,
                &mut self.symbols,
                self.kind_cache.clone(),
            );
            check.kindcheck_type(typ)
        };
        if let Err(errors) = result {
            self.errors.extend(
                errors
                    .into_iter()
                    .map(|err| pos::spanned(err.span, TypeError::from(err.value).into())),
            );
        }
    }

    fn check_type_binding(&mut self, alias_name: &Symbol, typ: &AstType<'_, Symbol>) {
        use crate::base::pos::HasSpan;
        match &**typ {
            Type::Generic(id) => {
                if !self.environment.type_variables.contains_key(&id.id) {
                    info!("Undefined type variable {}", id.id);
                    self.error(typ.span(), TypeError::UndefinedVariable(id.id.clone()));
                }
            }

            Type::Variant(row) => {
                for field in types::row_iter(row) {
                    let spine = ctor_return_type(&field.typ).spine();
                    match &**spine {
                        Type::Ident(id) if id.name == *alias_name => (),
                        Type::Opaque => (),
                        _ => {
                            let actual = self.translate_ast_type(spine);
                            self.error(
                                spine.span(),
                                TypeError::TypeConstructorReturnsWrongType {
                                    expected: alias_name.clone(),
                                    actual,
                                },
                            );
                        }
                    }
                    self.check_type_binding(alias_name, &field.typ);
                }
            }

            Type::Record(_) => {
                // Inside records variables are bound implicitly to the closest field
                // so variables are allowed to be undefined/implicit
            }

            _ => {
                if let Type::Forall(params, ..) = &**typ {
                    let mut type_cache = &self.subs;
                    self.environment
                        .type_variables
                        .extend(params.iter().map(|gen| (gen.id.clone(), type_cache.hole())));
                }
                types::walk_type_(
                    typ,
                    &mut types::ControlVisitation(|typ: &AstType<'_, _>| {
                        self.check_type_binding(alias_name, typ)
                    }),
                );
            }
        }
    }

    fn update_var(&mut self, id: &Symbol, typ: &RcType) {
        if let Some(bind) = self.environment.stack.get_mut(id) {
            if let Type::Variable(_) = **bind.typ {
                self.implicit_resolver.on_stack_var(&self.subs, id, typ);
            }
            bind.typ.concrete = typ.clone();
        }
        // HACK
        // For type projections
        let id = self.symbols.simple_symbol(id.declared_name());
        if let Some(bind) = self.environment.stack.get_mut(&id) {
            bind.typ.concrete = typ.clone();
        }
    }

    fn finish_pattern(
        &mut self,
        level: u32,
        pattern: &mut SpannedPattern<Symbol>,
        final_type: &RcType,
    ) {
        match pattern.value {
            Pattern::As(ref mut id, ref mut pat) => {
                self.finish_pattern(level, pat, &final_type);

                self.update_var(&id.value, &final_type);

                debug!("{}: {}", self.symbols.string(&id.value), final_type);
            }
            Pattern::Ident(ref mut id) => {
                id.typ = self.subs.bind_arc(&final_type);
                self.update_var(&id.name, &final_type);
                debug!("{}: {}", self.symbols.string(&id.name), id.typ);
            }
            Pattern::Record {
                ref mut typ,
                ref mut fields,
                ..
            } => {
                *typ = self.subs.bind_arc(final_type);
                let mut typ = final_type.clone();
                debug!("{{ .. }}: {}", final_type);

                self.generalize_type(level, &mut typ, pattern.span);
                let typ = self.instantiate_generics(&typ);
                let record_type = self.remove_alias(typ.clone());

                for (field_name, binding, field_type) in with_pattern_types(fields, &record_type) {
                    let mut field_type = field_type.cloned().unwrap_or_else(|| self.subs.error());
                    self.generalize_type(level, &mut field_type, field_name.span);
                    match *binding {
                        Some(ref mut pat) => {
                            self.finish_pattern(level, pat, &field_type);
                        }
                        None => {
                            self.update_var(&field_name.value, &field_type);
                            debug!("{}: {}", field_name.value, field_type);
                        }
                    }
                }
            }
            Pattern::Tuple {
                ref mut typ,
                ref mut elems,
            } => {
                *typ = self.subs.bind_arc(final_type);
                let typ = final_type.clone();

                let typ = self.instantiate_generics(&typ);
                for (elem, field) in elems.iter_mut().zip(typ.row_iter()) {
                    let mut field_type = field.typ.clone();
                    self.generalize_type(level, &mut field_type, elem.span);
                    self.finish_pattern(level, elem, &field_type);
                }
            }
            Pattern::Constructor(ref mut id, ref mut args) => {
                debug!("{}: {}", self.symbols.string(&id.name), final_type);
                let len = args.len();
                let iter = args.iter_mut().zip(
                    function_arg_iter(self, final_type.clone())
                        .map(|t| t.1)
                        .take(len)
                        .collect::<Vec<_>>(),
                );
                for (arg, arg_type) in iter {
                    self.finish_pattern(level, arg, &arg_type);
                }
            }
            Pattern::Literal(_) | Pattern::Error => (),
        }
    }

    // At the top level we know we can generalize all variables, letting us clear the substitution
    // and start fresh
    fn generalize_and_clear_subs(&mut self, level: u32, binds: &mut ValueBindings<Symbol>) {
        debug!("Clearing from: {}", level);
        {
            let hole = self.subs.hole();

            let mut generalizer = TypeGeneralizer::new(level, self, &hole, binds[0].span());
            for bind in &mut *binds {
                generalize::ReplaceVisitor {
                    generalizer: &mut generalizer,
                }
                .visit_pattern(&mut bind.name);

                generalizer.generalize_variables(
                    &mut bind.args.iter_mut().map(|arg| &mut arg.name),
                    &mut bind.expr,
                );
                generalizer.generalize_type_mut(&mut bind.resolved_type);
            }
        }

        let mut errors = mem::replace(&mut self.errors, Default::default());
        self.generalize_type_errors(&mut errors);
        self.errors = errors;

        // Clear any location which could have skolems or variables left in them
        self.named_variables.clear();
        self.implicit_resolver.implicit_vars.clear();

        self.subs.clear_from(level);
    }

    fn generalize_type(&mut self, level: u32, typ: &mut RcType, span: Span<BytePos>) {
        debug!("Start generalize {:#?}", self.environment.skolem_variables);
        debug!("Start generalize {} >> {}", level, typ);
        let mut generalizer = TypeGeneralizer::new(level, self, typ, span);
        generalizer.generalize_type_top(typ);
    }

    fn generalize_type_without_forall(
        &mut self,
        level: u32,
        typ: &mut RcType,
        span: Span<BytePos>,
    ) {
        self.environment.skolem_variables.enter_scope();

        let mut generalizer = TypeGeneralizer::new(level, self, typ, span);
        let result_type = generalizer.generalize_type(typ);

        generalizer.environment.skolem_variables.exit_scope();

        if let Some(finished) = result_type {
            *typ = finished;
        }
    }

    // Replaces `Type::Id` types with the actual `Type::Alias` type it refers to
    // Replaces variant names with the actual symbol they should refer to
    // Instantiates Type::Hole with a fresh type variable to ensure the hole only ever refers to a
    // single type variable.
    //
    // Also inserts a `forall` for any implicitly declared variables.
    fn create_unifiable_signature(&mut self, typ: &RcType) -> Option<RcType> {
        self.create_unifiable_signature_with(None, typ)
    }

    fn create_unifiable_signature_with(
        &mut self,
        scope: impl IntoIterator<Item = (Symbol, RcType)>,
        typ: &RcType,
    ) -> Option<RcType> {
        debug!("Creating signature: {:#?}", typ);

        for (k, v) in scope {
            self.environment
                .skolem_variables
                .insert(k.clone(), v.clone());
            self.environment.type_variables.insert(k, v);
        }

        let opt = self.create_unifiable_signature2(typ);
        debug!("Created signature: {:#?}", opt.as_ref().unwrap_or(typ));
        opt
    }

    fn create_unifiable_signature2(&mut self, typ: &RcType) -> Option<RcType> {
        debug!("Signature scope: {}", typ);

        self.unbound_variables.enter_scope();
        let result_type = self.create_unifiable_signature_(typ);

        let mut params = self
            .unbound_variables
            .exit_scope()
            .map(|(id, kind)| Generic::new(id, kind))
            .collect::<Vec<_>>();
        params.retain(|generic| !self.unbound_variables.contains_key(&generic.id));

        if params.is_empty() {
            result_type
        } else {
            let result = self.intern(Type::Forall(
                params,
                result_type.unwrap_or_else(|| typ.clone()),
            ));
            debug!("Signature scope END: {}", result);
            Some(result)
        }
    }

    fn create_unifiable_signature_(&mut self, typ: &RcType) -> Option<RcType> {
        match **typ {
            Type::Ident(ref id) => {
                // Substitute the Id by its alias if possible
                self.environment
                    .find_type_info(&id.name)
                    .map(|alias| alias.clone().into_type())
            }

            // Due to a hack in the kindchecker that inserts a dummy generic we need to replace aliases as well
            Type::Alias(ref alias) => {
                // Substitute the Id by its alias if possible
                self.environment
                    .find_type_info(&alias.name)
                    .map(|alias| alias.clone().into_type())
            }

            Type::Variant(ref row) => {
                let replacement = types::visit_type_opt(
                    row,
                    &mut types::InternerVisitor::control(self, |self_: &mut Self, typ: &RcType| {
                        self_.create_unifiable_signature_(typ)
                    }),
                );
                replacement
                    .clone()
                    .map(|row| self.intern(Type::Variant(row)))
            }

            Type::Hole => Some(self.subs.new_var()),

            Type::ExtendRow {
                ref fields,
                ref rest,
            } => {
                let new_fields = types::walk_move_types(&mut (), fields, |_, field| {
                    self.create_unifiable_signature2(&field.typ)
                        .map(|typ| Field::new(field.name.clone(), typ))
                });
                let new_rest = self.create_unifiable_signature_(rest);
                merge::merge(fields, new_fields, rest, new_rest, |fields, rest| {
                    self.intern(Type::ExtendRow { fields, rest })
                })
            }

            Type::ExtendTypeRow {
                ref types,
                ref rest,
            } => {
                let new_types = types::walk_move_types(&mut (), types, |_, field| {
                    let typ = self
                        .create_unifiable_signature_with(
                            field.typ.params().iter().map(|param| {
                                (param.id.clone(), field.typ.unresolved_type().clone())
                            }),
                            field.typ.unresolved_type(),
                        )
                        .unwrap_or_else(|| field.typ.unresolved_type().clone());
                    Some(Field::new(
                        field.name.clone(),
                        self.new_alias(field.typ.name.clone(), field.typ.params().to_owned(), typ),
                    ))
                });

                let new_rest = self.create_unifiable_signature_(rest);

                merge::merge(types, new_types, rest, new_rest, |types, rest| {
                    self.intern(Type::ExtendTypeRow { types, rest })
                })
            }

            Type::Forall(ref params, ref typ) => {
                self.environment.type_variables.enter_scope();

                let mut subs = &self.subs;
                self.environment
                    .type_variables
                    .extend(params.iter().map(|param| (param.id.clone(), subs.hole())));

                let result = self.create_unifiable_signature_(typ);

                self.environment.type_variables.exit_scope();

                result.map(|typ| self.intern(Type::Forall(params.clone(), typ)))
            }

            Type::Generic(ref generic) => {
                if let Some(typ) = self.environment.type_variables.get(&generic.id) {
                    match **typ {
                        Type::Skolem(_) => Some(typ.clone()),
                        _ => None,
                    }
                } else {
                    self.unbound_variables
                        .entry(generic.id.clone())
                        .or_insert_with(|| generic.kind.clone());
                    None
                }
            }

            _ => types::walk_move_type_opt(
                typ,
                &mut types::InternerVisitor::control(self, |self_: &mut Self, typ: &RcType| {
                    self_.create_unifiable_signature_(typ)
                }),
            ),
        }
    }

    fn subsumes_expr(
        &mut self,
        span: Span<BytePos>,
        l: &RcType,
        r: RcType,
        expr: &mut SpannedExpr<'ast, Symbol>,
    ) -> RcType {
        let mut implicit_args = match &mut expr.value {
            Expr::App { implicit_args, .. } => implicit_args.iter_mut().map(mem::take).collect(),
            _ => Vec::new(),
        };
        let new = self.subsumes_implicit(
            span,
            ErrorOrder::ExpectedActual,
            &r,
            l.clone(),
            &mut |arg| {
                implicit_args.push(pos::spanned(expr.span, arg));
            },
        );

        match &mut expr.value {
            Expr::App {
                implicit_args: current,
                ..
            } => *current = self.ast_arena.alloc_extend(implicit_args),
            _ => {
                if !implicit_args.is_empty() {
                    let func = mem::take(&mut expr.value);
                    expr.value = Expr::App {
                        func: self.ast_arena.alloc(pos::spanned(expr.span, func)),
                        implicit_args: self.ast_arena.alloc_extend(implicit_args),
                        args: &mut [],
                    }
                }
            }
        }

        // We ended up skolemizing r. To prevent the variables from looking like they
        // are escaping we need to bind the forall at this location
        if let Type::Forall(..) = *new {
            let temp = mem::replace(expr, Default::default());
            *expr = Expr::annotated(self.ast_arena, temp, self.subs.bind_arc(&new));
        }
        new
    }

    fn subsumes_implicit(
        &mut self,
        span: Span<BytePos>,
        error_order: ErrorOrder,
        expected: &RcType,
        actual: RcType,
        receiver: &mut dyn FnMut(Expr<'ast, Symbol>),
    ) -> RcType {
        debug!("Subsume expr {} <=> {}", expected, actual);

        self.environment.skolem_variables.enter_scope();

        let state = unify_type::State::new(&self.environment, &self.subs);

        let implicit_resolver = &mut self.implicit_resolver;
        let mut receiver = |implicit_type: &RcType| {
            let name = implicit_resolver.make_implicit_ident(implicit_type);

            receiver(Expr::Ident(TypedIdent {
                name,
                typ: implicit_type.clone(),
            }));
        };
        let typ = match unify_type::subsumes_implicit(
            &self.subs,
            state,
            &expected,
            &actual,
            &mut receiver,
        ) {
            Ok(typ) => typ,
            Err((typ, mut errors)) => {
                let expected = expected.clone();
                debug!(
                    "Error '{}' between:\n>> {}\n>> {}",
                    errors, expected, actual
                );
                let err = match error_order {
                    ErrorOrder::ExpectedActual => {
                        TypeError::Unification(expected, actual, errors.into())
                    }
                    ErrorOrder::ActualExpected => {
                        for err in &mut errors {
                            match err {
                                unify::Error::TypeMismatch(l, r) => mem::swap(l, r),
                                unify::Error::Other(unify_type::TypeError::FieldMismatch(l, r)) => {
                                    mem::swap(l, r)
                                }
                                _ => (),
                            }
                        }
                        TypeError::Unification(actual, expected, errors.into())
                    }
                };
                self.errors.push(Spanned {
                    span: span,
                    // TODO Help what caused this unification failure
                    value: err.into(),
                });
                typ
            }
        };

        self.environment.skolem_variables.exit_scope();

        typ
    }

    fn subsumes(
        &mut self,
        span: Span<BytePos>,
        error_order: ErrorOrder,
        expected: &RcType,
        actual: RcType,
    ) -> RcType {
        debug!("Merge {} : {}", expected, actual);
        let state = unify_type::State::new(&self.environment, &self.subs);
        match unify_type::subsumes(&self.subs, state, &expected, &actual) {
            Ok(typ) => typ,
            Err((typ, mut errors)) => {
                let expected = expected.clone();
                debug!(
                    "Error '{}' between:\n>> {}\n>> {}",
                    errors, expected, actual
                );
                let err = match error_order {
                    ErrorOrder::ExpectedActual => {
                        TypeError::Unification(expected, actual, errors.into())
                    }
                    ErrorOrder::ActualExpected => {
                        for err in &mut errors {
                            match err {
                                unify::Error::TypeMismatch(l, r) => mem::swap(l, r),
                                unify::Error::Other(unify_type::TypeError::FieldMismatch(l, r)) => {
                                    mem::swap(l, r)
                                }
                                _ => (),
                            }
                        }
                        TypeError::Unification(actual, expected, errors.into())
                    }
                };
                self.errors.push(Spanned {
                    span: span,
                    // TODO Help what caused this unification failure
                    value: err.into(),
                });
                typ
            }
        }
    }

    fn refines(
        &mut self,
        span: Span<BytePos>,
        error_order: ErrorOrder,
        expected: &RcType,
        actual: RcType,
    ) -> RcType {
        debug!("Refine {} : {}", expected, actual);
        types::walk_type(&actual, &mut |typ: &RcType| {
            if let Type::Skolem(skolem) = &**self.subs.real(typ) {
                self.refined_variables.entry(skolem.id).or_insert(());
            }
        });
        let state = unify_type::State::with_refinement(&self.environment, &self.subs, true);
        match unify_type::subsumes(&self.subs, state, &expected, &actual) {
            Ok(typ) => typ,
            Err((typ, mut errors)) => {
                let expected = expected.clone();
                debug!(
                    "Error '{}' between:\n>> {}\n>> {}",
                    errors, expected, actual
                );
                let err = match error_order {
                    ErrorOrder::ExpectedActual => {
                        TypeError::Unification(expected, actual, errors.into())
                    }
                    ErrorOrder::ActualExpected => {
                        for err in &mut errors {
                            match err {
                                unify::Error::TypeMismatch(l, r) => mem::swap(l, r),
                                unify::Error::Other(unify_type::TypeError::FieldMismatch(l, r)) => {
                                    mem::swap(l, r)
                                }
                                _ => (),
                            }
                        }
                        TypeError::Unification(actual, expected, errors.into())
                    }
                };
                self.errors.push(Spanned {
                    span: span,
                    // TODO Help what caused this unification failure
                    value: err.into(),
                });
                typ
            }
        }
    }

    fn instantiate_sigma(
        &mut self,
        span: Span<BytePos>,
        typ: &RcType,
        expected_type: &mut Option<&RcType>,
    ) -> (Vec<SpannedExpr<'ast, Symbol>>, RcType) {
        match expected_type.take() {
            Some(expected_type) => {
                debug!("Instantiate sigma: {} <> {}", expected_type, typ);
                let mut implicit_args = Vec::new();
                let t = self.subsumes_implicit(
                    span,
                    ErrorOrder::ExpectedActual,
                    &expected_type,
                    typ.clone(),
                    &mut |implicit_arg| {
                        implicit_args.push(pos::spanned(span, implicit_arg));
                    },
                );
                (implicit_args, t)
            }
            None => {
                debug!("Instantiate sigma: {}", typ);
                (Vec::new(), self.instantiate_generics(typ))
            }
        }
    }

    fn subsume_function(
        &mut self,
        prev_arg_end: BytePos,
        span: Span<BytePos>,
        arg_type: ArgType,
        actual: RcType,
        implicit_args: &mut dyn FnMut(SpannedExpr<'ast, Symbol>),
    ) -> (RcType, RcType) {
        let (_, a, r) = self.merge_function(Some(arg_type), actual, &mut |self_, f, actual| {
            self_.subsumes_implicit(
                span,
                ErrorOrder::ExpectedActual,
                &f,
                actual,
                &mut |implicit_arg| {
                    implicit_args(pos::spanned2(prev_arg_end, span.start(), implicit_arg))
                },
            );
        });
        (a, r)
    }

    fn unify_function(&mut self, span: Span<BytePos>, actual: RcType) -> (ArgType, RcType, RcType) {
        self.merge_function(None, actual, &mut |self_, f, actual| {
            self_.unify_span(span, &f, actual);
        })
    }

    fn merge_function(
        &mut self,
        function_arg_type: Option<ArgType>,
        actual: RcType,
        merge_fn: &mut dyn FnMut(&mut Self, &RcType, RcType),
    ) -> (ArgType, RcType, RcType) {
        let actual = self.remove_aliases(actual);
        match actual.as_function_with_type() {
            Some((found_arg_type, arg, ret))
                if function_arg_type == Some(found_arg_type) || function_arg_type == None =>
            {
                return (found_arg_type, arg.clone(), ret.clone());
            }
            _ => (),
        }
        let arg = self.subs.new_var();
        let ret = self.subs.new_var();
        let arg_type = function_arg_type.unwrap_or(ArgType::Explicit);
        let f = self
            .subs
            .function_type(arg_type, Some(arg.clone()), ret.clone());
        merge_fn(self, &f, actual);
        (arg_type, arg, ret)
    }

    fn unify_span(&mut self, span: Span<BytePos>, expected: &RcType, actual: RcType) -> RcType {
        match self.unify(expected, actual) {
            Ok(typ) => typ,
            Err(err) => {
                self.errors.push(Spanned {
                    span: span,
                    // TODO Help what caused this unification failure
                    value: err.into(),
                });
                self.subs.error()
            }
        }
    }

    fn unify(&self, expected: &RcType, actual: RcType) -> TcResult<RcType> {
        debug!("Unify start {} <=> {}", expected, actual);
        let state = unify_type::State::new(&self.environment, &self.subs);
        match unify::unify(&self.subs, state, expected, &actual) {
            Ok(typ) => Ok(typ),
            Err(errors) => {
                debug!(
                    "Error '{:?}' between:\n>> {}\n>> {}",
                    errors, expected, actual
                );
                Err(TypeError::Unification(
                    expected.clone(),
                    actual,
                    errors.into(),
                ))
            }
        }
    }

    fn remove_alias(&self, typ: RcType) -> RcType {
        resolve::remove_alias(&self.environment, &mut &self.subs, &typ)
            .unwrap_or(None)
            .unwrap_or(typ)
    }

    fn remove_aliases(&self, typ: RcType) -> RcType {
        resolve::remove_aliases(&self.environment, &mut &self.subs, typ)
    }

    fn with_forall(&mut self, from: &RcType, to: ModType) -> ModType {
        let mut params = Vec::new();
        for param in from.forall_params() {
            params.push(param.clone());
        }
        ModType::new(to.modifier, self.forall(params, to.concrete))
    }

    fn skolemize_in(
        &mut self,
        span: Span<BytePos>,
        original_type: ModTypeRef,
        f: impl FnOnce(&mut Self, ModType) -> ModType,
    ) -> ModType {
        self.environment.skolem_variables.enter_scope();
        self.environment.type_variables.enter_scope();
        let t = self.skolemize_in_no_scope(span, original_type, f);

        self.environment.type_variables.exit_scope();
        self.environment.skolem_variables.exit_scope();
        t
    }

    fn skolemize_in_no_scope(
        &mut self,
        span: Span<BytePos>,
        original_type: ModTypeRef,
        f: impl FnOnce(&mut Self, ModType) -> ModType,
    ) -> ModType {
        let skolemized = self.skolemize(&original_type);
        let new_type = f(self, ModType::new(original_type.modifier, skolemized));

        let original_type = self.subs.zonk(&original_type);
        types::FlagsVisitor(Flags::HAS_SKOLEMS, |typ: &RcType| {
            if let Type::Skolem(skolem) = &**typ {
                if !self.environment.skolem_variables.contains_key(&skolem.name) {
                    self.error(
                        span,
                        TypeError::Message(format!(
                            "Skolem variable `{}` would escape as it is not bound in `{}`",
                            skolem.name, original_type
                        )),
                    );
                }
            }
        })
        .walk(&original_type);

        self.with_forall(&original_type, new_type)
    }

    fn skolemize(&mut self, typ: &RcType) -> RcType {
        self.named_variables.clear();
        self.named_variables.extend(
            self.environment
                .skolem_variables
                .iter()
                .map(|(k, v)| (k.clone(), v.clone())),
        );
        let new_type = typ.skolemize(&mut &self.subs, &mut self.named_variables);
        for (id, typ) in self.named_variables.iter() {
            match self.environment.skolem_variables.entry(id.clone()) {
                scoped_map::Entry::Vacant(e) => {
                    e.insert(typ.clone());
                }
                scoped_map::Entry::Occupied(mut e) => {
                    if e.get() != typ {
                        e.insert(typ.clone());
                    }
                }
            }
        }
        new_type
    }

    pub(crate) fn instantiate_generics(&mut self, typ: &RcType) -> RcType {
        self.named_variables.clear();
        typ.instantiate_generics(&mut &self.subs, &mut self.named_variables)
    }

    fn error_on_duplicated_field<'s>(
        &mut self,
        duplicated_fields: &mut FnvSet<&'s str>,
        new_name: &'s Spanned<Symbol, BytePos>,
    ) -> bool {
        let span = new_name.span;
        duplicated_fields
            .replace(new_name.value.definition_name())
            .map_or(true, |name| {
                self.errors.push(Spanned {
                    span: span,
                    // TODO Help to the other fields location
                    value: TypeError::DuplicateField(self.symbols.symbols().simple_symbol(name))
                        .into(),
                });
                false
            })
    }

    fn check_macro(&mut self, expr: &mut SpannedExpr<'ast, Symbol>) -> Option<TcResult<ModType>> {
        let (replacement, typ) = match expr.value {
            Expr::App {
                ref mut func,
                ref mut args,
                ..
            } => match func.value {
                Expr::Ident(ref id) => match id.name.declared_name() {
                    "convert_effect!" => {
                        let (name, typ) = match args.len() {
                            1 => (None, self.infer_expr(&mut args[0]).concrete),
                            2 => (
                                Some(match args[0].value {
                                    Expr::Ident(ref id) => id.name.clone(),
                                    _ => unreachable!(),
                                }),
                                self.infer_expr(&mut args[1]).concrete,
                            ),
                            _ => unreachable!(),
                        };

                        let unaliased = self.remove_aliases(typ.clone());
                        let valid_type = match &*unaliased {
                            Type::Variant(variant) => {
                                let mut iter = variant.row_iter();
                                for _ in iter.by_ref() {}
                                match **iter.current_type() {
                                    Type::EmptyRow => false,
                                    _ => true,
                                }
                            }
                            _ => false,
                        };
                        if !valid_type {
                            return Some(Err(TypeError::Message(format!("Invalid form for the type. Expect the type to be of the form `type Effect r a = | Variant X | r` but found `{}`", unaliased))));
                        }

                        let f = self.subs.new_var();
                        let row_arg = self.subs.new_var();
                        let arg = self.subs.new_var();
                        let expected_shape =
                            self.app(f.clone(), collect![row_arg.clone(), arg.clone()]);
                        self.unify_span(expr.span, &expected_shape, typ);

                        let eff = self.poly_effect(
                            name.map(|name| Field {
                                name,
                                typ: self.subs.real(&f).clone(),
                            })
                            .into_iter()
                            .collect(),
                            row_arg,
                        );
                        (
                            mem::take(args.last_mut().unwrap()),
                            self.app(eff, collect![self.subs.real(&arg).clone()]),
                        )
                    }
                    "convert_variant!" => {
                        let typ = self.infer_expr(&mut args[0]).concrete;

                        let unaliased = self.remove_aliases(typ);
                        let variant_type = match *unaliased {
                            Type::App(ref f, ref type_args) if type_args.len() == 1 => {
                                let f = self.subs.real(f).clone();
                                match *f {
                                    Type::Effect(ref row) => {
                                        let variant_type = row.row_iter().fold(
                                            self.poly_variant(vec![], self.subs.new_var()),
                                            |variant, field| {
                                                let typ = self.app(
                                                    field.typ.clone(),
                                                    collect![
                                                        self.subs.new_var(),
                                                        type_args[0].clone()
                                                    ],
                                                );
                                                let typ = self.remove_alias(typ);
                                                let typ = self.instantiate_generics(&typ);

                                                self.subsumes(
                                                    args[0].span,
                                                    ErrorOrder::ActualExpected,
                                                    &variant,
                                                    typ,
                                                )
                                            },
                                        );
                                        let variant_type = self.subs.zonk(&variant_type);

                                        let effect_row_rest = {
                                            let mut iter = row.row_iter();
                                            for _ in &mut iter {}
                                            iter.current_type().clone()
                                        };

                                        let variant_row_rest = {
                                            let mut iter = variant_type.row_iter();
                                            for _ in &mut iter {}
                                            iter.current_type().clone()
                                        };

                                        self.subsumes(
                                            args[0].span,
                                            ErrorOrder::ActualExpected,
                                            &variant_row_rest,
                                            effect_row_rest,
                                        );

                                        variant_type
                                    }
                                    _ => {
                                        return Some(Err(TypeError::Message(format!(
                                            "Expected an effect type, found `{}`",
                                            unaliased
                                        ))));
                                    }
                                }
                            }
                            _ => {
                                return Some(Err(TypeError::Message(format!(
                                    "Expected an effect type, found `{}`",
                                    unaliased
                                ))));
                            }
                        };
                        (mem::take(args.last_mut().unwrap()), variant_type)
                    }

                    _ => return None,
                },

                _ => return None,
            },

            _ => return None,
        };

        *expr = Expr::annotated(self.ast_arena, replacement, self.subs.bind_arc(&typ));

        Some(Ok(ModType::wobbly(typ)))
    }
}

pub fn translate_projected_type(
    env: &dyn TypeEnv<Type = RcType>,
    symbols: &mut dyn IdentEnv<Ident = Symbol>,
    interner: &mut impl TypeContext<Symbol, RcType>,
    ids: &[Symbol],
) -> TcResult<RcType> {
    let mut lookup_type: Option<RcType> = None;
    for symbol in &ids[..ids.len() - 1] {
        lookup_type = match lookup_type {
            Some(typ) => {
                let aliased_type = resolve::remove_aliases(env, interner, typ.clone());
                Some(
                    aliased_type
                        .type_field_iter()
                        .filter_map(|field| {
                            if field.name.name_eq(&symbol) {
                                Some(field.typ.clone().into_type())
                            } else {
                                None
                            }
                        })
                        .chain(aliased_type.row_iter().filter_map(|field| {
                            if field.name.name_eq(&symbol) {
                                Some(field.typ.clone())
                            } else {
                                None
                            }
                        }))
                        .next()
                        .ok_or_else(|| TypeError::UndefinedField(typ, symbol.clone()))?,
                )
            }
            None => Some(
                env.find_type(&symbol)
                    .or_else(|| {
                        env.find_type_info(&symbol)
                            .map(|alias| alias.typ(interner).into_owned())
                    })
                    .ok_or_else(|| TypeError::UndefinedVariable(symbol.clone()))?,
            ),
        };
    }
    let typ = lookup_type.unwrap();
    let type_symbol = symbols.from_str(ids.last().expect("Non-empty ids").name().name().as_str());
    resolve::remove_aliases(env, interner, typ.clone())
        .type_field_iter()
        .find(|field| field.name.name_eq(&type_symbol))
        .map(|field| field.typ.clone().into_type())
        .ok_or_else(|| TypeError::UndefinedField(typ, type_symbol))
}

fn with_pattern_types<'a: 'b, 'b, 'ast>(
    fields: &'a mut [PatternField<'ast, Symbol>],
    typ: &'b RcType,
) -> impl Iterator<
    Item = (
        &'a Spanned<Symbol, BytePos>,
        &'a mut Option<SpannedPattern<'ast, Symbol>>,
        Option<&'b RcType>,
    ),
>
where
    'ast: 'a,
{
    ast::pattern_values_mut(fields).map(move |(name, value)| {
        let opt = typ
            .row_iter()
            .find(|type_field| type_field.name.name_eq(&name.value));
        (
            &*name,
            value,
            opt.map(move |associated_type| &associated_type.typ),
        )
    })
}

pub fn extract_generics(args: &[RcType]) -> Vec<Generic<Symbol>> {
    args.iter()
        .map(|arg| match **arg {
            Type::Generic(ref gen) => gen.clone(),
            _ => ice!("The type on the lhs of a type binding did not have all generic arguments"),
        })
        .collect()
}

fn get_alias_app<'a>(
    env: &'a dyn TypeEnv<Type = RcType>,
    typ: &'a RcType,
) -> Option<(AliasRef<Symbol, RcType>, Cow<'a, [RcType]>)> {
    match **typ {
        Type::Alias(ref alias) => Some((alias.clone(), Cow::Borrowed(&[][..]))),
        Type::App(ref alias, ref args) => match **alias {
            Type::Alias(ref alias) => Some((alias.clone(), Cow::Borrowed(&args[..]))),
            _ => None,
        },
        _ => typ.alias_ident().and_then(|id| {
            env.find_type_info(id)
                .map(|alias| ((*alias).clone(), typ.unapplied_args()))
        }),
    }
}
struct FunctionArgIter<'a, 'b: 'a, 'ast> {
    tc: &'a mut Typecheck<'b, 'ast>,
    typ: RcType,
}

impl<'a, 'b> Iterator for FunctionArgIter<'a, 'b, '_> {
    type Item = (ArgType, RcType);
    fn next(&mut self) -> Option<Self::Item> {
        let mut last_alias = None;
        loop {
            self.typ = self.tc.skolemize(&self.typ);
            let (arg, new) = match self.typ.as_function_with_type() {
                Some((arg_type, arg, ret)) => (Some((arg_type, arg.clone())), ret.clone()),
                None => match get_alias_app(&self.tc.environment, &self.typ) {
                    Some((alias, args)) => {
                        if Some(&alias.name) == last_alias.as_ref() {
                            return None;
                        }
                        last_alias = Some(alias.name.clone());
                        self.tc.named_variables.clear();
                        match alias.typ(&mut &self.tc.subs).apply_args(
                            alias.params(),
                            &args,
                            &mut &self.tc.subs,
                            &mut self.tc.named_variables,
                        ) {
                            Some(typ) => (None, typ.clone()),
                            None => return None,
                        }
                    }
                    None => return None,
                },
            };
            self.typ = new;
            if let Some(arg) = arg {
                return Some(arg);
            }
        }
    }
}

fn function_arg_iter<'a, 'b, 'ast>(
    tc: &'a mut Typecheck<'b, 'ast>,
    typ: RcType,
) -> FunctionArgIter<'a, 'b, 'ast> {
    FunctionArgIter { tc, typ }
}

/// Returns a span of the innermost expression of a group of nested `let` and `type` bindings.
/// This span is useful for more precisely marking the span of a type error.
///
/// ```ignore
/// let x: Int =
///     let y = 1.0
///     ~~~~~~~~~~~
///     y
///     ~
///     ^
/// x
/// ```
fn expr_check_span(e: &SpannedExpr<Symbol>) -> Span<BytePos> {
    match e.value {
        Expr::LetBindings(_, ref b) | Expr::TypeBindings(_, ref b) => expr_check_span(b),
        _ => e.span,
    }
}

fn generalize_binding<'ast>(
    generalizer: &mut TypeGeneralizer<'_, '_, 'ast>,
    resolved_type: &mut RcType,
    binding: &mut ValueBinding<'ast, Symbol>,
) {
    crate::implicits::resolve(generalizer.tc, &mut binding.expr);

    generalizer.generalize_type_top(resolved_type);
}

fn ctor_return_type<'a, Id, T>(typ: &'a T) -> &'a T
where
    T: TypePtr<Id = Id>,
    Id: 'a,
{
    match &**typ {
        Type::Forall(_, typ) | Type::Function(_, _, typ) => ctor_return_type(typ),
        _ => typ,
    }
}

enum CowVec<'a, T> {
    Borrowed(&'a mut [T]),
    Owned(Vec<T>),
}

impl<T> std::ops::Deref for CowVec<'_, T> {
    type Target = [T];
    fn deref(&self) -> &Self::Target {
        match self {
            CowVec::Owned(v) => v,
            CowVec::Borrowed(v) => v,
        }
    }
}

impl<T> std::ops::DerefMut for CowVec<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self {
            CowVec::Owned(v) => v,
            CowVec::Borrowed(v) => v,
        }
    }
}

impl<T> CowVec<'_, T>
where
    T: Default,
{
    fn as_owned(&mut self) -> &mut Vec<T> {
        let v = match self {
            CowVec::Owned(v) => return v,
            CowVec::Borrowed(b) => b.iter_mut().map(mem::take).collect(),
        };
        *self = CowVec::Owned(v);
        self.as_owned()
    }
}