File: CSDiagnostics.h

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (3187 lines) | stat: -rw-r--r-- 107,166 bytes parent folder | download
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
//===--- CSDiagnostics.h - Constraint Diagnostics -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides necessary abstractions for constraint system diagnostics.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SEMA_CSDIAGNOSTICS_H
#define SWIFT_SEMA_CSDIAGNOSTICS_H

#include "TypeChecker.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/OperatorNameLookup.h"
#include "swift/AST/Types.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/FixBehavior.h"
#include "swift/Sema/OverloadChoice.h"
#include "llvm/ADT/ArrayRef.h"
#include <tuple>

namespace swift {
namespace constraints {

class FunctionArgApplyInfo;

/// Base class for all of the possible diagnostics,
/// provides most basic information such as location of
/// the problem, parent expression and some utility methods.
class FailureDiagnostic {
  const Solution &S;
  ConstraintLocator *Locator;
  FixBehavior fixBehavior;

public:
  FailureDiagnostic(const Solution &solution, ConstraintLocator *locator,
                    FixBehavior fixBehavior = FixBehavior::Error)
      : S(solution), Locator(locator), fixBehavior(fixBehavior) {}

  FailureDiagnostic(const Solution &solution, ASTNode anchor,
                    FixBehavior fixBehavior = FixBehavior::Error)
      : FailureDiagnostic(solution, solution.getConstraintLocator(anchor),
                          fixBehavior) { }

  virtual ~FailureDiagnostic();

  virtual SourceLoc getLoc() const { return constraints::getLoc(getAnchor()); }

  virtual SourceRange getSourceRange() const {
    return constraints::getSourceRange(getAnchor());
  }

  /// Try to diagnose a problem given affected expression,
  /// failure location, types and declarations deduced by
  /// constraint system, and other auxiliary information.
  ///
  /// \param asNote In ambiguity cases it's beneficial to
  /// produce diagnostic as a note instead of an error if possible.
  ///
  /// \returns true If the problem has been successfully diagnosed
  /// and diagnostic message emitted, false otherwise.
  bool diagnose(bool asNote = false);

  /// Try to produce an error diagnostic for the problem at hand.
  ///
  /// \returns true If anything was diagnosed, false otherwise.
  virtual bool diagnoseAsError() = 0;

  /// Instead of producing an error diagnostic, attempt to
  /// produce a "note" to complement some other diagnostic
  /// e.g. ambiguity error.
  virtual bool diagnoseAsNote();

  ASTNode getRawAnchor() const { return Locator->getAnchor(); }

  virtual ASTNode getAnchor() const;

  ConstraintLocator *getLocator() const { return Locator; }

  SourceLoc getBestAddImportFixItLocation(const Decl *Member,
                                          SourceFile *sourceFile) const {
    auto &engine = Member->getASTContext().Diags;
    return engine.getBestAddImportFixItLoc(Member, sourceFile);
  }

  Type getType(ASTNode node, bool wantRValue = true) const;

  /// Get type associated with a given ASTNode without resolving it,
  /// which means that returned type would have type variables.
  Type getRawType(ASTNode node) const;

  /// Resolve type variables present in the raw type, if any.
  Type resolveType(Type rawType, bool reconstituteSugar = false,
                   bool wantRValue = true) const;

  template <typename... ArgTypes>
  InFlightDiagnostic emitDiagnostic(ArgTypes &&... Args) const;

  template <typename... ArgTypes>
  InFlightDiagnostic emitDiagnosticAt(ArgTypes &&... Args) const;

protected:
  const Solution &getSolution() const { return S; }

  ConstraintSystem &getConstraintSystem() const {
    return S.getConstraintSystem();
  }

  Type getContextualType(ASTNode anchor) const {
    auto &cs = getConstraintSystem();
    return cs.getContextualType(anchor, /*forConstraint=*/false);
  }

  TypeLoc getContextualTypeLoc(ASTNode anchor) const {
    auto &cs = getConstraintSystem();
    return cs.getContextualTypeLoc(anchor);
  }

  ContextualTypePurpose getContextualTypePurpose(ASTNode anchor) const {
    auto &cs = getConstraintSystem();
    return cs.getContextualTypePurpose(anchor);
  }

  DeclContext *getDC() const {
    auto &cs = getConstraintSystem();
    return cs.DC;
  }

  ModuleDecl *getParentModule() const {
    return getDC()->getParentModule();
  }

  ASTContext &getASTContext() const {
    auto &cs = getConstraintSystem();
    return cs.getASTContext();
  }

  /// Retrieve overload choice resolved for a given locator
  /// by the constraint solver.
  std::optional<SelectedOverload>
  getOverloadChoiceIfAvailable(ConstraintLocator *locator) const {
    return S.getOverloadChoiceIfAvailable(locator);
  }

  /// Retrieve overload choice resolved for a callee for the anchor
  /// of a given locator.
  std::optional<SelectedOverload>
  getCalleeOverloadChoiceIfAvailable(ConstraintLocator *locator) const {
    return getOverloadChoiceIfAvailable(S.getCalleeLocator(locator));
  }

  ConstraintLocator *
  getConstraintLocator(ASTNode anchor,
                       ConstraintLocator::PathElement element) const {
    return S.getConstraintLocator(anchor, {element});
  }

  /// Retrieve the constraint locator for the given anchor and
  /// path, uniqued and automatically calculate the summary flags
  ConstraintLocator *getConstraintLocator(
      ASTNode anchor,
      ArrayRef<ConstraintLocator::PathElement> path = {}) const {
    return S.getConstraintLocator(anchor, path);
  }

  ConstraintLocator *
  getConstraintLocator(ConstraintLocator *baseLocator,
                       ConstraintLocator::PathElement element) const {
    return S.getConstraintLocator(baseLocator, element);
  }

  std::optional<FunctionArgApplyInfo>
  getFunctionArgApplyInfo(ConstraintLocator *locator) const {
    return S.getFunctionArgApplyInfo(locator);
  }

  /// \returns A parent expression if sub-expression is contained anywhere
  /// in the root expression or `nullptr` otherwise.
  Expr *findParentExpr(const Expr *subExpr) const;

  /// If given expression is some kind of a member reference e.g.
  /// `x.foo` or `x[0]` extract and return its base expression.
  Expr *getBaseExprFor(const Expr *anchor) const;

  /// For a given locator describing an argument application, or a constraint
  /// within an argument application, returns the argument list for that
  /// application. If the locator is not for an argument application, or
  /// the argument list cannot be found, returns \c nullptr.
  ArgumentList *getArgumentListFor(ConstraintLocator *locator) const;

  /// \returns A new type with all of the type variables associated with
  /// generic parameters substituted back into being generic parameter type.
  Type restoreGenericParameters(
      Type type,
      llvm::function_ref<void(GenericTypeParamType *, Type)> substitution =
          [](GenericTypeParamType *, Type) {});

  bool conformsToKnownProtocol(Type type, KnownProtocolKind protocol) const;
};

/// Base class for all of the diagnostics related to generic requirement
/// failures, provides common information like failed requirement,
/// declaration where such requirement comes from, etc.
class RequirementFailure : public FailureDiagnostic {
protected:
  using PathEltKind = ConstraintLocator::PathElementKind;
  using DiagOnDecl = Diag<const ValueDecl *, Type, Type>;
  using DiagInReference = Diag<const ValueDecl *, Type, Type, Type>;
  using DiagAsNote = Diag<Type, Type, Type, Type>;

  /// If this failure associated with one of the conditional requirements,
  /// this field would represent conformance where requirement comes from.
  const ProtocolConformance *Conformance = nullptr;

  /// The source of the requirement, if available. One exception
  /// is failure associated with conditional requirement where
  /// underlying conformance is specialized.
  GenericSignature Signature;

  const ValueDecl *AffectedDecl;
  /// If possible, find application expression associated
  /// with current generic requirement failure, that helps
  /// to diagnose failures related to arguments.
  const ApplyExpr *Apply = nullptr;

  /// Types associated with requirement constraint this
  /// failure originates from.
  Type LHS, RHS;

public:
  RequirementFailure(const Solution &solution, Type lhs, Type rhs,
                     ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        Conformance(getConformanceForConditionalReq(locator)),
        Signature(getSignature(locator)), AffectedDecl(getDeclRef()),
        LHS(resolveType(lhs)), RHS(resolveType(rhs)) {
    assert(locator);
    assert(isConditional() || Signature);
    assert(AffectedDecl);
    assert(getRequirementDC() &&
           "Couldn't find where the requirement came from?");
    assert(getGenericContext() &&
           "Affected decl not within a generic context?");

    if (auto *expr = getAsExpr(getRawAnchor()))
      if (auto *parentExpr = findParentExpr(expr))
        Apply = dyn_cast<ApplyExpr>(parentExpr);
  }

  unsigned getRequirementIndex() const {
    auto reqElt =
        getLocator()->castLastElementTo<LocatorPathElt::AnyRequirement>();
    return reqElt.getIndex();
  }

  /// The generic base type where failing requirement comes from.
  Type getOwnerType() const;

  /// Generic context associated with the failure.
  const GenericContext *getGenericContext() const;

  /// Generic requirement associated with the failure.
  const Requirement &getRequirement() const;

  Type getLHS() const { return LHS; }
  Type getRHS() const { return RHS; }

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

protected:
  /// Determine whether this is a conditional requirement failure.
  bool isConditional() const { return bool(Conformance); }

  /// Check whether this requirement comes from the contextual type
  /// that root expression is coerced/converted into.
  bool isFromContextualType() const;

  /// Retrieve declaration contextual where current
  /// requirement has been introduced.
  const DeclContext *getRequirementDC() const;

  virtual DiagOnDecl getDiagnosticOnDecl() const = 0;
  virtual DiagInReference getDiagnosticInRereference() const = 0;
  virtual DiagAsNote getDiagnosticAsNote() const = 0;

  static bool isOperator(const ApplyExpr *apply) {
    return isa<PrefixUnaryExpr>(apply) || isa<PostfixUnaryExpr>(apply) ||
           isa<BinaryExpr>(apply);
  }

  /// Determine whether given declaration represents a static
  /// or instance property/method, excluding operators.
  static bool isStaticOrInstanceMember(const ValueDecl *decl);

private:
  /// Retrieve declaration associated with failing generic requirement.
  ValueDecl *getDeclRef() const;

  /// Retrieve generic signature where this parameter originates from.
  GenericSignature getSignature(ConstraintLocator *locator);

  void maybeEmitRequirementNote(const Decl *anchor, Type lhs, Type rhs) const;

  /// If this is a failure in conditional requirement, retrieve
  /// conformance information.
  ProtocolConformance *
  getConformanceForConditionalReq(ConstraintLocator *locator);
};

/// Diagnostics for failed conformance checks originating from
/// generic requirements e.g.
/// ```swift
///   struct S {}
///   func foo<T: Hashable>(_ t: T) {}
///   foo(S())
/// ```
class MissingConformanceFailure final : public RequirementFailure {
public:
  MissingConformanceFailure(const Solution &solution,
                            ConstraintLocator *locator,
                            std::pair<Type, Type> conformance)
      : RequirementFailure(solution, conformance.first, conformance.second,
                           locator) {
#ifndef NDEBUG
    auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
    assert(reqElt.getRequirementKind() == RequirementKind::Conformance ||
           reqElt.getRequirementKind() == RequirementKind::Layout);
#endif
  }

  bool diagnoseAsError() override;

protected:
  /// Check whether this requirement is associated with one of the
  /// operator overloads, in cases like that sometimes it makes more
  /// sense to produce a generic diagnostic about operator reference
  /// instead of conformance, because it could be something like
  /// `true + true`, and it doesn't make much sense to suggest to
  /// add a conformance from one library type to another.
  bool diagnoseAsAmbiguousOperatorRef();

  DiagOnDecl getDiagnosticOnDecl() const override {
    return (getRequirement().getKind() == RequirementKind::Layout ?
            diag::type_does_not_conform_anyobject_decl_owner :
            diag::type_does_not_conform_decl_owner);
  }

  DiagInReference getDiagnosticInRereference() const override {
    return (getRequirement().getKind() == RequirementKind::Layout ?
            diag::type_does_not_conform_anyobject_in_decl_ref :
            diag::type_does_not_conform_in_decl_ref);
  }

  DiagAsNote getDiagnosticAsNote() const override {
    return diag::candidate_types_conformance_requirement;
  }

private:
  bool diagnoseTypeCannotConform(Type nonConformingType,
                                 Type protocolType) const;
};

/// Diagnose failures related to same-type generic requirements, e.g.
/// ```swift
/// protocol P {
///   associatedtype T
/// }
///
/// struct S : P {
///   typealias T = String
/// }
///
/// func foo<U: P>(_ t: [U]) where U.T == Int {}
/// foo([S()])
/// ```
///
/// `S.T` is not the same type as `Int`, which is required by `foo`.
class SameTypeRequirementFailure final : public RequirementFailure {
public:
  SameTypeRequirementFailure(const Solution &solution, Type lhs, Type rhs,
                             ConstraintLocator *locator)
      : RequirementFailure(solution, lhs, rhs, locator) {
#ifndef NDEBUG
    auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
    assert(reqElt.getRequirementKind() == RequirementKind::SameType);
#endif
  }

protected:
  DiagOnDecl getDiagnosticOnDecl() const override {
    return diag::types_not_equal_decl;
  }

  DiagInReference getDiagnosticInRereference() const override {
    return diag::types_not_equal_in_decl_ref;
  }

  DiagAsNote getDiagnosticAsNote() const override {
    return diag::candidate_types_equal_requirement;
  }
};

/// Diagnose failures related to same-shape generic requirements, e.g.
/// ```swift
/// func foo<T..., U...>(t: T..., u: U...) -> (T, U)... {}
/// func bar<T..., U...>(t: T..., u: U...) {
///   foo(t: t..., u: u...)
/// }
/// ```
///
/// The generic parameter packs `T` and `U` are not known to have the same
/// shape, which is required by `foo()`.
class SameShapeRequirementFailure final : public RequirementFailure {
public:
  SameShapeRequirementFailure(const Solution &solution, Type lhs, Type rhs,
                              ConstraintLocator *locator)
      : RequirementFailure(solution, lhs, rhs, locator) {
#ifndef NDEBUG
    auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
    assert(reqElt.getRequirementKind() == RequirementKind::SameShape);
#endif
  }

protected:
  DiagOnDecl getDiagnosticOnDecl() const override {
    return diag::types_not_same_shape_decl;
  }

  DiagInReference getDiagnosticInRereference() const override {
    return diag::types_not_same_shape_in_decl_ref;
  }

  DiagAsNote getDiagnosticAsNote() const override {
    return diag::candidate_types_same_shape_requirement;
  }
};

class SameShapeExpansionFailure final : public FailureDiagnostic {
  Type lhs, rhs;

public:
  SameShapeExpansionFailure(const Solution &solution, Type lhs, Type rhs,
                            ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        lhs(resolveType(lhs)),
        rhs(resolveType(rhs)) {}

  bool diagnoseAsError() override;
};

/// Diagnose failures related to superclass generic requirements, e.g.
/// ```swift
/// class A {
/// }
///
/// class B {
/// }
///
/// func foo<T>(_ t: [T]) where T: A {}
/// foo([B()])
/// ```
///
/// `A` is not the superclass of `B`, which is required by `foo<T>`.
class SuperclassRequirementFailure final : public RequirementFailure {
public:
  SuperclassRequirementFailure(const Solution &solution, Type lhs, Type rhs,
                               ConstraintLocator *locator)
      : RequirementFailure(solution, lhs, rhs, locator) {
#ifndef NDEBUG
    auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
    assert(reqElt.getRequirementKind() == RequirementKind::Superclass);
#endif
  }

protected:
  DiagOnDecl getDiagnosticOnDecl() const override {
    return diag::types_not_inherited_decl;
  }

  DiagInReference getDiagnosticInRereference() const override {
    return diag::types_not_inherited_in_decl_ref;
  }

  DiagAsNote getDiagnosticAsNote() const override {
    return diag::candidate_types_inheritance_requirement;
  }
};

/// Diagnose errors associated with missing, extraneous
/// or incorrect labels supplied by arguments, e.g.
/// ```swift
///   func foo(q: String, _ a: Int) {}
///   foo("ultimate question", a: 42)
/// ```
/// Call to `foo` is going to be diagnosed as missing `q:`
/// and having extraneous `a:` labels, with appropriate fix-its added.
class LabelingFailure final : public FailureDiagnostic {
  ArrayRef<Identifier> CorrectLabels;

public:
  LabelingFailure(const Solution &solution, ConstraintLocator *locator,
                  ArrayRef<Identifier> labels)
      : FailureDiagnostic(solution, locator), CorrectLabels(labels) {}

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;
};

/// A diagnostic that will be emitted on the base if its locator points to a
/// member access.
class MemberReferenceFailure : public FailureDiagnostic {
public:
  MemberReferenceFailure(const Solution &solution, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  ASTNode getAnchor() const override;
};

/// Diagnose failures related to attempting member access on optional base
/// type without optional chaining or force-unwrapping it first.
class MemberAccessOnOptionalBaseFailure final : public MemberReferenceFailure {
  DeclNameRef Member;
  Type MemberBaseType;
  bool ResultTypeIsOptional;

public:
  MemberAccessOnOptionalBaseFailure(const Solution &solution,
                                    ConstraintLocator *locator,
                                    DeclNameRef memberName, Type memberBaseType,
                                    bool resultOptional)
      : MemberReferenceFailure(solution, locator), Member(memberName),
        MemberBaseType(resolveType(memberBaseType)),
        ResultTypeIsOptional(resultOptional) {}

  bool diagnoseAsError() override;

  Type getMemberBaseType() const {
    return MemberBaseType;
  }

  SourceLoc getLoc() const override {
    // The end location points to the dot in the member access.
    return getSourceRange().End;
  }

  SourceRange getSourceRange() const override;

};

/// Diagnose errors associated with rvalues in positions
/// where an lvalue is required, such as inout arguments.
class RValueTreatedAsLValueFailure final : public FailureDiagnostic {

public:
  RValueTreatedAsLValueFailure(const Solution &solution,
                               ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;
};

class TrailingClosureAmbiguityFailure final : public FailureDiagnostic {
  ArrayRef<OverloadChoice> Choices;

public:
  TrailingClosureAmbiguityFailure(ArrayRef<Solution> solutions, ASTNode anchor,
                                  ArrayRef<OverloadChoice> choices)
      : FailureDiagnostic(solutions.front(), anchor), Choices(choices) {}

  bool diagnoseAsError() override { return false; }

  bool diagnoseAsNote() override;
};

/// Diagnose errors related to assignment expressions e.g.
/// trying to assign something to immutable value, or trying
/// to access mutating member on immutable base.
class AssignmentFailure final : public FailureDiagnostic {
  Expr *DestExpr;
  SourceLoc Loc;
  Diag<StringRef> DeclDiagnostic;
  Diag<Type> TypeDiagnostic;

public:
  AssignmentFailure(Expr *destExpr, const Solution &solution,
                    SourceLoc diagnosticLoc);

  AssignmentFailure(Expr *destExpr, const Solution &solution,
                    SourceLoc diagnosticLoc, Diag<StringRef> declDiag,
                    Diag<Type> typeDiag)
      : FailureDiagnostic(solution, destExpr), DestExpr(destExpr),
        Loc(diagnosticLoc), DeclDiagnostic(declDiag), TypeDiagnostic(typeDiag) {
  }

  bool diagnoseAsError() override;

private:
  /// Given an expression that has a non-lvalue type, dig into it until
  /// we find the part of the expression that prevents the entire subexpression
  /// from being mutable.  For example, in a sequence like "x.v.v = 42" we want
  /// to complain about "x" being a let property if "v.v" are both mutable.
  ///
  /// \returns The base subexpression that looks immutable (or that can't be
  /// analyzed any further) along with an OverloadChoice extracted from it if we
  /// could.
  std::pair<Expr *, std::optional<OverloadChoice>>
  resolveImmutableBase(Expr *expr) const;

  std::pair<Expr *, std::optional<OverloadChoice>>
  resolveImmutableBase(const Expr *expr) const {
    return resolveImmutableBase(const_cast<Expr *>(expr));
  }

  static Diag<StringRef> findDeclDiagnostic(ASTContext &ctx,
                                            const Expr *destExpr);

  /// Retrieve an member reference associated with given member
  /// looking through dynamic member lookup on the way.
  std::optional<OverloadChoice> getMemberRef(ConstraintLocator *locator) const;
};

/// Intended to diagnose any possible contextual failure
/// e.g. argument/parameter, closure result, conversions etc.
class ContextualFailure : public FailureDiagnostic {
  ContextualTypePurpose CTP;
  Type RawFromType, RawToType;

public:
  ContextualFailure(const Solution &solution, Type lhs, Type rhs,
                    ConstraintLocator *locator,
                    FixBehavior fixBehavior = FixBehavior::Error)
      : ContextualFailure(
            solution,
            locator->isForContextualType()
                ? locator->castLastElementTo<LocatorPathElt::ContextualType>()
                      .getPurpose()
                : solution.getConstraintSystem().getContextualTypePurpose(
                      locator->getAnchor()),
            lhs, rhs, locator, fixBehavior) {}

  ContextualFailure(const Solution &solution, ContextualTypePurpose purpose,
                    Type lhs, Type rhs, ConstraintLocator *locator,
                    FixBehavior fixBehavior = FixBehavior::Error)
      : FailureDiagnostic(solution, locator, fixBehavior), CTP(purpose),
        RawFromType(lhs), RawToType(rhs) {
    assert(lhs && "Expected a valid 'from' type");
    assert(rhs && "Expected a valid 'to' type");
  }

  SourceLoc getLoc() const override;

  Type getFromType() const { return resolve(RawFromType); }

  Type getToType() const { return resolve(RawToType); }

  Type getRawFromType() const { return RawFromType; }

  Type getRawToType() const { return RawToType; }

  bool diagnoseAsError() override;

  bool diagnoseAsNote() override;

  /// If we're trying to convert something to `nil`.
  bool diagnoseConversionToNil() const;

  /// Diagnose failed conversion in a `CoerceExpr`.
  bool diagnoseCoercionToUnrelatedType() const;

  /// Produce a specialized diagnostic if this is an invalid conversion to Bool.
  bool diagnoseConversionToBool() const;

  /// Produce a specialized diagnostic if this is an attempt to throw
  /// something with doesn't conform to `Error`.
  bool diagnoseThrowsTypeMismatch() const;

  /// Produce a specialized diagnostic if this is an attempt to `yield`
  /// something of incorrect type.
  bool diagnoseYieldByReferenceMismatch() const;

  /// Attempt to attach any relevant fix-its to already produced diagnostic.
  void tryFixIts(InFlightDiagnostic &diagnostic) const;

  /// Attempts to add fix-its for these two mistakes:
  ///
  /// - Passing an integer with the right type but which is getting wrapped with
  ///   a different integer type unnecessarily. The fixit removes the cast.
  ///
  /// - Passing an integer but expecting different integer type. The fixit adds
  ///   a wrapping cast.
  ///
  /// - Return true on the fixit is added, false otherwise.
  ///
  /// This helps migration with SDK changes.
  bool tryIntegerCastFixIts(InFlightDiagnostic &diagnostic) const;

protected:
  /// Try to add a fix-it when converting between a collection and its slice
  /// type, such as String <-> Substring or (eventually) Array <-> ArraySlice
  bool trySequenceSubsequenceFixIts(InFlightDiagnostic &diagnostic) const;

  /// Try to add a fix-it that suggests to explicitly use `as` or `as!`
  /// to coerce one type to another if type-checker can prove that such
  /// conversion is possible.
  bool tryTypeCoercionFixIt(InFlightDiagnostic &diagnostic) const;

  /// Try to add a fix-it to conform the decl context (if it's a type) to the
  /// protocol
  bool tryProtocolConformanceFixIt(InFlightDiagnostic &diagnostic) const;

private:
  Type resolve(Type rawType) const {
    return resolveType(rawType)->getWithoutSpecifierType();
  }

  bool isIntegerType(Type type) const {
    return conformsToKnownProtocol(
        type, KnownProtocolKind::ExpressibleByIntegerLiteral);
  }

  /// Return true if the conversion from fromType to toType is
  /// an invalid string index operation.
  bool isIntegerToStringIndexConversion() const;

protected:
  ContextualTypePurpose getContextualTypePurpose() const { return CTP; }

  static std::optional<Diag<Type, Type>>
  getDiagnosticFor(ContextualTypePurpose context, Type contextualType);

protected:
  bool exprNeedsParensBeforeAddingAs(const Expr *expr, DeclContext *DC) const {
    auto asPG = TypeChecker::lookupPrecedenceGroup(
                    DC, DC->getASTContext().Id_CastingPrecedence, SourceLoc())
                    .getSingle();
    if (!asPG)
      return true;
    return exprNeedsParensInsideFollowingOperator(DC, const_cast<Expr *>(expr),
                                                  asPG);
  }

  bool exprNeedsParensAfterAddingAs(const Expr *expr, DeclContext *DC) const {
    auto asPG = TypeChecker::lookupPrecedenceGroup(
                    DC, DC->getASTContext().Id_CastingPrecedence, SourceLoc())
                    .getSingle();
    if (!asPG)
      return true;

    return exprNeedsParensOutsideFollowingOperator(
        DC, const_cast<Expr *>(expr), asPG,
        [&](auto *E) { return findParentExpr(E); });
  }
};

class NonClassTypeToAnyObjectConversionFailure final
    : public ContextualFailure {

public:
  NonClassTypeToAnyObjectConversionFailure(const Solution &solution, Type lhs,
                                           Type rhs, ConstraintLocator *locator)
      : ContextualFailure(solution, lhs, rhs, locator, FixBehavior::Error) {}

  bool diagnoseAsError() override;

  bool diagnoseAsNote() override;
};

/// Diagnose errors related to using an array literal where a
/// dictionary is expected.
class ArrayLiteralToDictionaryConversionFailure final : public ContextualFailure {
public:
  ArrayLiteralToDictionaryConversionFailure(const Solution &solution,
                                            Type arrayTy, Type dictTy,
                                            ConstraintLocator *locator)
      : ContextualFailure(solution, arrayTy, dictTy, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose errors related to converting function type which
/// isn't explicitly '@escaping' or '@Sendable' to some other type.
class AttributedFuncToTypeConversionFailure final : public ContextualFailure {
public:
  enum AttributeKind {
    Escaping,
    Concurrent,
  };

  const AttributeKind attributeKind;

  AttributedFuncToTypeConversionFailure(const Solution &solution, Type fromType,
                                        Type toType, ConstraintLocator *locator,
                                        AttributeKind attributeKind,
                                        FixBehavior fixBehavior =
                                            FixBehavior::Error)
      : ContextualFailure(solution, fromType, toType, locator, fixBehavior),
        attributeKind(attributeKind) {}

  bool diagnoseAsError() override;

private:
  /// Emit tailored diagnostics for no-escape/non-sendable parameter
  /// conversions e.g. passing such parameter as an @escaping or @Sendable
  /// argument, or trying to assign it to a variable which expects @escaping
  /// or @Sendable function.
  bool diagnoseParameterUse() const;

  /// Emit a tailored diagnostic for a no-escape/espace mismatch for function
  /// arguments where the mismatch has to take into account that a
  /// function type subtype relation in the parameter position is contravariant.
  bool diagnoseFunctionParameterEscapenessMismatch(AssignExpr *) const;
};

/// Diagnose failure where a global actor attribute is dropped when
/// trying to convert one function type to another.
class DroppedGlobalActorFunctionAttr final : public ContextualFailure {
public:
  DroppedGlobalActorFunctionAttr(const Solution &solution, Type fromType,
                                 Type toType, ConstraintLocator *locator,
                                 FixBehavior fixBehavior)
    : ContextualFailure(solution, fromType, toType, locator, fixBehavior) { }

  bool diagnoseAsError() override;
};

/// Diagnose failures related to use of the unwrapped optional types,
/// which require some type of force-unwrap e.g. "!" or "try!".
class MissingOptionalUnwrapFailure final : public ContextualFailure {
public:
  MissingOptionalUnwrapFailure(const Solution &solution, Type fromType,
                               Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {}

  bool diagnoseAsError() override;

private:
  Type getBaseType() const {
    return resolveType(getFromType(), /*reconstituteSugar=*/true);
  }

  Type getUnwrappedType() const {
    return resolveType(getBaseType()->getOptionalObjectType(),
                       /*reconstituteSugar=*/true);
  }

  /// Suggest a default value via `?? <default value>`
  void offerDefaultValueUnwrapFixIt(DeclContext *DC, const Expr *expr) const;
  /// Suggest a force optional unwrap via `!`
  void offerForceUnwrapFixIt(const Expr *expr) const;
};

class WrappedValueMismatch final : public ContextualFailure {
public:
  WrappedValueMismatch(const Solution &solution, Type fromType,
                       Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {
  }

  bool diagnoseAsError() override;
};

/// Diagnostics for mismatched generic arguments e.g
/// ```swift
/// struct F<G> {}
/// let _:F<Int> = F<Bool>()
/// ```
class GenericArgumentsMismatchFailure final : public ContextualFailure {
  ArrayRef<unsigned> Mismatches;

public:
  GenericArgumentsMismatchFailure(const Solution &solution, Type actualType,
                                  Type requiredType,
                                  ArrayRef<unsigned> mismatches,
                                  ConstraintLocator *locator)
      : ContextualFailure(solution, actualType, requiredType, locator),
        Mismatches(mismatches) {
    assert(actualType->is<BoundGenericType>());
    assert(requiredType->is<BoundGenericType>());
  }

  bool diagnoseAsError() override;

private:
  void emitNotesForMismatches() {
    for (unsigned position : Mismatches) {
      emitNoteForMismatch(position);
    }
  }

  void emitNoteForMismatch(int mismatchPosition);

  std::optional<Diag<Type, Type>>
  getDiagnosticFor(ContextualTypePurpose context);

  /// The actual type being used.
  BoundGenericType *getActual() const {
    return getFromType()->castTo<BoundGenericType>();
  }

  /// The type needed by the generic requirement.
  BoundGenericType *getRequired() const {
    return getToType()->castTo<BoundGenericType>();
  }
};

/// Diagnose failures related to conversion between throwing function type
/// and non-throwing one e.g.
///
/// ```swift
/// func foo<T>(_ t: T) throws -> Void {}
/// let _: (Int) -> Void = foo // `foo` can't be implicitly converted to
///                            // non-throwing type `(Int) -> Void`
/// ```
class ThrowingFunctionConversionFailure final : public ContextualFailure {
public:
  ThrowingFunctionConversionFailure(const Solution &solution, Type fromType,
                                    Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {
#ifndef NDEBUG
    auto fnType1 = fromType->castTo<FunctionType>();
    auto fnType2 = toType->castTo<FunctionType>();
    assert(fnType1->isThrowing() != fnType2->isThrowing());
#endif
  }

  bool diagnoseAsError() override;
};

/// Diagnose failures related to conversion between the thrown error type
/// of two function types, e.g.,
///
/// ```swift
/// func foo<T>(_ t: T) throws(MyError) -> Void {}
/// let _: (Int) throws (OtherError)-> Void = foo
///   // `MyError` can't be implicitly converted to `OtherError`
/// ```
class ThrownErrorTypeConversionFailure final : public ContextualFailure {
public:
  ThrownErrorTypeConversionFailure(const Solution &solution, Type fromType,
                                    Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {
  }

  bool diagnoseAsError() override;
};

/// Diagnose failures related to conversion between 'async' function type
/// and a synchronous one e.g.
///
/// ```swift
/// func foo<T>(_ t: T) async -> Void {}
/// let _: (Int) -> Void = foo // `foo` can't be implicitly converted to
///                            // synchronous function type `(Int) -> Void`
/// ```
class AsyncFunctionConversionFailure final : public ContextualFailure {
public:
  AsyncFunctionConversionFailure(const Solution &solution, Type fromType,
                                 Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {
#ifndef NDEBUG
    auto fnType1 = fromType->castTo<FunctionType>();
    auto fnType2 = toType->castTo<FunctionType>();
    assert(fnType1->isAsync() != fnType2->isAsync());
#endif
  }

  bool diagnoseAsError() override;
};

/// Diagnose failures related attempt to implicitly convert types which
/// do not support such implicit conversion.
/// "as" or "as!" has to be specified explicitly in cases like that.
class MissingExplicitConversionFailure final : public ContextualFailure {
public:
  MissingExplicitConversionFailure(const Solution &solution, Type fromType,
                                   Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {}

  ASTNode getAnchor() const override;

  bool diagnoseAsError() override;
};

/// Diagnose failures related to passing value of some type
/// to `inout` or pointer parameter, without explicitly specifying `&`.
class MissingAddressOfFailure final : public ContextualFailure {
public:
  MissingAddressOfFailure(const Solution &solution, Type argTy, Type paramTy,
                          ConstraintLocator *locator)
      : ContextualFailure(solution, argTy, paramTy, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose extraneous use of address of (`&`) which could only be
/// associated with arguments to inout parameters e.g.
///
/// ```swift
/// struct S {}
///
/// var a: S = ...
/// var b: S = ...
///
/// a = &b
/// ```
class InvalidUseOfAddressOf final : public ContextualFailure {
public:
  InvalidUseOfAddressOf(const Solution &solution, Type lhs, Type rhs,
                        ConstraintLocator *locator)
      : ContextualFailure(solution, lhs, rhs, locator) {}

  bool diagnoseAsError() override;

protected:
  /// Compute location of the failure for diagnostic.
  SourceLoc getLoc() const override;
};

/// Diagnose mismatches relating to tuple destructuring.
class TupleContextualFailure final : public ContextualFailure {
  /// Indices of the tuple elements whose types do not match.
  llvm::SmallVector<unsigned, 4> Indices;

public:
  TupleContextualFailure(const Solution &solution,
                         ContextualTypePurpose purpose, Type lhs, Type rhs,
                         llvm::ArrayRef<unsigned> indices,
                         ConstraintLocator *locator)
      : ContextualFailure(solution, purpose, lhs, rhs, locator),
        Indices(indices.begin(), indices.end()) {
    std::sort(Indices.begin(), Indices.end());
    assert(getFromType()->is<TupleType>() && getToType()->is<TupleType>());
  }

  bool diagnoseAsError() override;

  bool isNumElementsMismatch() const {
    auto lhsTy = getFromType()->castTo<TupleType>();
    auto rhsTy = getToType()->castTo<TupleType>();
    return lhsTy->getNumElements() != rhsTy->getNumElements();
  }
};

class FunctionTypeMismatch final : public ContextualFailure {
  /// Indices of the parameters whose types do not match.
  llvm::SmallVector<unsigned, 4> Indices;

public:
  FunctionTypeMismatch(const Solution &solution, ContextualTypePurpose purpose,
                       Type lhs, Type rhs, llvm::ArrayRef<unsigned> indices,
                       ConstraintLocator *locator)
      : ContextualFailure(solution, purpose, lhs, rhs, locator),
        Indices(indices.begin(), indices.end()) {
    std::sort(Indices.begin(), Indices.end());
    assert(getFromType()->is<AnyFunctionType>() && getToType()->is<AnyFunctionType>());
  }

  bool diagnoseAsError() override;
};

/// Diagnose situations when @autoclosure argument is passed to @autoclosure
/// parameter directly without calling it first.
class AutoClosureForwardingFailure final : public FailureDiagnostic {
public:
  AutoClosureForwardingFailure(const Solution &solution,
                               ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose invalid pointer conversions for an autoclosure result type.
///
/// \code
/// func foo(_ x: @autoclosure () -> UnsafePointer<Int>) {}
///
/// var i = 0
/// foo(&i) // Invalid conversion to UnsafePointer
/// \endcode
class AutoClosurePointerConversionFailure final : public ContextualFailure {
public:
  AutoClosurePointerConversionFailure(const Solution &solution,
                                      Type pointeeType, Type pointerType,
                                      ConstraintLocator *locator)
      : ContextualFailure(solution, pointeeType, pointerType, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations when there was an attempt to unwrap entity
/// of non-optional type e.g.
///
/// ```swift
/// let i: Int = 0
/// _ = i!
///
/// struct A { func foo() {} }
/// func foo(_ a: A) {
///   a?.foo()
/// }
/// ```
class NonOptionalUnwrapFailure final : public FailureDiagnostic {
  Type BaseType;

public:
  NonOptionalUnwrapFailure(const Solution &solution, Type baseType,
                           ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), BaseType(baseType) {}

  bool diagnoseAsError() override;
};

class MissingCallFailure final : public FailureDiagnostic {
  /// Try to add a fix-it to convert a stored property into a computed
  /// property
  void tryComputedPropertyFixIts() const;

public:
  MissingCallFailure(const Solution &solution, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  ASTNode getAnchor() const override;

  bool diagnoseAsError() override;
};

class PropertyWrapperReferenceFailure : public ContextualFailure {
  VarDecl *Property;
  bool UsingProjection;

public:
  PropertyWrapperReferenceFailure(const Solution &solution, VarDecl *property,
                                  bool usingProjection, Type base,
                                  Type wrapper, ConstraintLocator *locator)
      : ContextualFailure(solution, base, wrapper, locator), Property(property),
        UsingProjection(usingProjection) {}

  ASTNode getAnchor() const override;

  VarDecl *getProperty() const { return Property; }

  Identifier getPropertyName() const { return Property->getName(); }

  bool usingProjection() const { return UsingProjection; }

  ValueDecl *getReferencedMember() const {
    auto *locator = getLocator();
    if (auto overload = getOverloadChoiceIfAvailable(locator))
      return overload->choice.getDeclOrNull();
    return nullptr;
  }
};

class ExtraneousPropertyWrapperUnwrapFailure final
    : public PropertyWrapperReferenceFailure {
public:
  ExtraneousPropertyWrapperUnwrapFailure(const Solution &solution,
                                         VarDecl *property,
                                         bool usingStorageWrapper, Type base,
                                         Type wrapper,
                                         ConstraintLocator *locator)
      : PropertyWrapperReferenceFailure(solution, property, usingStorageWrapper,
                                        base, wrapper, locator) {}

  bool diagnoseAsError() override;
};

class MissingPropertyWrapperUnwrapFailure final
    : public PropertyWrapperReferenceFailure {
public:
  MissingPropertyWrapperUnwrapFailure(const Solution &solution,
                                      VarDecl *property,
                                      bool usingStorageWrapper, Type base,
                                      Type wrapper, ConstraintLocator *locator)
      : PropertyWrapperReferenceFailure(solution, property, usingStorageWrapper,
                                        base, wrapper, locator) {}

  bool diagnoseAsError() override;
};

class InvalidPropertyWrapperType final : public FailureDiagnostic {
  Type wrapperType;

public:
  InvalidPropertyWrapperType(const Solution &solution, Type wrapper,
                             ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), wrapperType(resolveType(wrapper)) {}

  bool diagnoseAsError() override;
};

class InvalidProjectedValueArgument final : public FailureDiagnostic {
  Type wrapperType;
  ParamDecl *param;

public:
  InvalidProjectedValueArgument(const Solution &solution, Type wrapper,
                                ParamDecl *param, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), wrapperType(resolveType(wrapper)),
        param(param) {}

  bool diagnoseAsError() override;
};

class SubscriptMisuseFailure final : public FailureDiagnostic {
public:
  SubscriptMisuseFailure(const Solution &solution, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;
};

class InvalidMemberRefFailure : public MemberReferenceFailure {
  Type BaseType;
  DeclNameRef Name;

public:
  InvalidMemberRefFailure(const Solution &solution, Type baseType,
                          DeclNameRef memberName, ConstraintLocator *locator)
      : MemberReferenceFailure(solution, locator),
        BaseType(baseType->getRValueType()), Name(memberName) {}

protected:
  Type getBaseType() const { return BaseType; }
  DeclNameRef getName() const { return Name; }
};

/// Diagnose situations when member referenced by name is missing
/// from the associated base type, e.g.
///
/// ```swift
/// struct S {}
/// func foo(_ s: S) {
///   let _: Int = s.foo(1, 2) // expected type is `(Int, Int) -> Int`
/// }
/// ```
class MissingMemberFailure : public InvalidMemberRefFailure {
public:
  MissingMemberFailure(const Solution &solution, Type baseType,
                       DeclNameRef memberName, ConstraintLocator *locator)
      : InvalidMemberRefFailure(solution, baseType, memberName, locator) {}

  SourceLoc getLoc() const override {
    auto *locator = getLocator();

    if (locator->findLast<LocatorPathElt::SyntacticElement>()) {
      return constraints::getLoc(getAnchor());
    }

    // Diagnostic should point to the member instead of its base expression.
    return constraints::getLoc(getRawAnchor());
  }

  bool diagnoseAsError() override;

private:
  /// Tailored diagnostics for missing special `@dynamicCallable` methods
  /// e.g. if caller expects `dynamicallyCall(withKeywordArguments:)`
  /// overload to be present, but a class marked as `@dynamicCallable`
  /// defines only `dynamicallyCall(withArguments:)` variant.
  bool diagnoseForDynamicCallable() const;

  /// Diagnose methods that return unsafe projections and suggest fixits.
  /// For example, if Swift cannot find "vector::data" because it is unsafe, try
  /// to diagnose this and tell the user why we did not import "vector::data".
  ///
  /// Provides fixits for:
  /// at -> subscript
  /// begin, end -> makeIterator
  /// front, back -> first, last
  void diagnoseUnsafeCxxMethod(SourceLoc loc, ASTNode anchor, Type baseType,
                               DeclName name) const;

  /// Tailored diagnostics for collection literal with unresolved member expression
  /// that defaults the element type. e.g. _ = [.e]
  bool diagnoseInLiteralCollectionContext() const;

  /// Tailored diagnostics for missing subscript member on a tuple base type.
  /// e.g
  /// ```swift
  ///   let tuple: (Int, Int) = (0, 0)
  ///   _ = tuple[0] // -> tuple.0.
  ///  ```
  bool diagnoseForSubscriptMemberWithTupleBase() const;

  static DeclName findCorrectEnumCaseName(Type Ty,
                                          TypoCorrectionResults &corrections,
                                          DeclNameRef memberName);

  static ValueDecl *findImportedCaseWithMatchingSuffix(Type instanceTy,
                                                       DeclNameRef name);
};

class UnintendedExtraGenericParamMemberFailure final
    : public MissingMemberFailure {
  Identifier ParamName;

public:
  UnintendedExtraGenericParamMemberFailure(const Solution &solution,
                                           Type baseType,
                                           DeclNameRef memberName,
                                           Identifier paramName,
                                           ConstraintLocator *locator)
      : MissingMemberFailure(solution, baseType, memberName, locator),
        ParamName(paramName) {}

  bool diagnoseAsError() override;
};

/// Diagnose cases where a member only accessible on generic constraints
/// requiring conformance to a protocol is used on a value of the
/// existential protocol type e.g.
///
/// ```swift
/// protocol P {
///   var foo: Self { get }
/// }
///
/// func bar<X : P>(p: X) {
///   p.foo
/// }
/// ```
class InvalidMemberRefOnExistential final : public InvalidMemberRefFailure {
public:
  InvalidMemberRefOnExistential(const Solution &solution, Type baseType,
                                DeclNameRef memberName,
                                ConstraintLocator *locator)
      : InvalidMemberRefFailure(solution, baseType, memberName, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations when we use an instance member on a type
/// or a type member on an instance
///
/// ```swift
/// class Bar {}
///
/// enum Foo {
///
///   static func f() {
///     g(Bar())
///   }
///
///   func g(_: Bar) {}
///
/// }
/// ```
class AllowTypeOrInstanceMemberFailure final : public MemberReferenceFailure {
  Type BaseType;
  ValueDecl *Member;
  DeclNameRef Name;

public:
  AllowTypeOrInstanceMemberFailure(const Solution &solution, Type baseType,
                                   ValueDecl *member, DeclNameRef name,
                                   ConstraintLocator *locator)
      : MemberReferenceFailure(solution, locator),
        BaseType(baseType->getRValueType()), Member(member), Name(name) {
    assert(member);
  }

  bool diagnoseAsError() override;
};

class PartialApplicationFailure final : public FailureDiagnostic {
  enum RefKind : unsigned {
    MutatingMethod,
    SuperInit,
    SelfInit,
    SuperMethod,
  };

  bool CompatibilityWarning;

public:
  PartialApplicationFailure(bool warning, const Solution &solution,
                            ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), CompatibilityWarning(warning) {}

  bool diagnoseAsError() override;
};

class InvalidInitRefFailure : public FailureDiagnostic {
protected:
  Type BaseType;
  const ConstructorDecl *Init;
  SourceRange BaseRange;

  ASTNode getAnchor() const override { return getRawAnchor(); }

  InvalidInitRefFailure(const Solution &solution, Type baseTy,
                        const ConstructorDecl *init, SourceRange baseRange,
                        ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), BaseType(baseTy), Init(init),
        BaseRange(baseRange) {}

public:
  bool diagnoseAsError() override = 0;
};

/// Diagnose an attempt to construct an object of class type with a metatype
/// value without using 'required' initializer:
///
/// ```swift
///  class C {
///    init(value: Int) {}
///  }
///
///  func make<T: C>(type: T.Type) -> T {
///    return T.init(value: 42)
///  }
/// ```
class InvalidDynamicInitOnMetatypeFailure final : public InvalidInitRefFailure {
public:
  InvalidDynamicInitOnMetatypeFailure(const Solution &solution, Type baseTy,
                                      const ConstructorDecl *init,
                                      SourceRange baseRange,
                                      ConstraintLocator *locator)
      : InvalidInitRefFailure(solution, baseTy, init, baseRange, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to call initializer on protocol metatype:
///
/// ```swift
///  protocol P {
///    init(value: Int)
///  }
///
///  func make(type: P.Type) -> P {
///    return type.init(value: 42)
///  }
/// ```
class InitOnProtocolMetatypeFailure final : public InvalidInitRefFailure {
  bool IsStaticallyDerived;

public:
  InitOnProtocolMetatypeFailure(const Solution &solution, Type baseTy,
                                const ConstructorDecl *init,
                                bool isStaticallyDerived, SourceRange baseRange,
                                ConstraintLocator *locator)
      : InvalidInitRefFailure(solution, baseTy, init, baseRange, locator),
        IsStaticallyDerived(isStaticallyDerived) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to construct an instance using non-constant
/// metatype base without explicitly specifying `init`:
///
/// ```swift
/// let foo = Int.self
/// foo(0) // should be `foo.init(0)`
/// ```
class ImplicitInitOnNonConstMetatypeFailure final
    : public InvalidInitRefFailure {
public:
  ImplicitInitOnNonConstMetatypeFailure(const Solution &solution, Type baseTy,
                                        const ConstructorDecl *init,
                                        ConstraintLocator *locator)
      : InvalidInitRefFailure(solution, baseTy, init, SourceRange(), locator) {}

  SourceLoc getLoc() const override;

  bool diagnoseAsError() override;
};

class MissingArgumentsFailure final : public FailureDiagnostic {
  SmallVector<SynthesizedArg, 4> SynthesizedArgs;

public:
  MissingArgumentsFailure(const Solution &solution,
                          ArrayRef<SynthesizedArg> synthesizedArgs,
                          ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        SynthesizedArgs(synthesizedArgs.begin(), synthesizedArgs.end()) {
    assert(!SynthesizedArgs.empty() && "No missing arguments?!");
  }

  SourceLoc getLoc() const override;

  ASTNode getAnchor() const override;

  bool diagnoseAsError() override;

  bool diagnoseAsNote() override;

  bool diagnoseSingleMissingArgument() const;

private:
  /// If missing arguments come from a closure,
  /// let's produce tailored diagnostics.
  bool diagnoseClosure(const ClosureExpr *closure);

  /// Diagnose cases when instead of multiple distinct arguments
  /// call got a single tuple argument with expected arity/types.
  bool diagnoseInvalidTupleDestructuring() const;

  /// Determine whether missing arguments are associated with
  /// an implicit call to a property wrapper initializer e.g.
  /// `@Foo(answer: 42) var question = "ultimate question"`
  bool isPropertyWrapperInitialization() const;

  /// Gather information associated with expression that represents
  /// a call - function and argument list.
  std::optional<std::pair<Expr *, ArgumentList *>>
  getCallInfo(ASTNode anchor) const;

  /// Transform given argument into format suitable for a fix-it
  /// text e.g. `[<label>:]? <#<type#>`
  void forFixIt(llvm::raw_svector_ostream &out,
                const AnyFunctionType::Param &argument) const;

public:
  /// Due to the fact that `matchCallArgument` can't and
  /// doesn't take types into consideration while matching
  /// arguments to parameters, for cases where both arguments
  /// are un-labeled, it's impossible to say which one is missing:
  ///
  /// func foo(_: Int, _: String) {}
  /// foo("")
  ///
  /// In this case first argument is missing, but we end up with
  /// two fixes - argument mismatch (for #1) and missing argument
  /// (for #2), which is incorrect so it has to be handled specially.
  static bool isMisplacedMissingArgument(const Solution &solution,
                                         ConstraintLocator *locator);
};

class ExtraneousArgumentsFailure final : public FailureDiagnostic {
  FunctionType *ContextualType;
  SmallVector<std::pair<unsigned, AnyFunctionType::Param>, 4> ExtraArgs;

public:
  ExtraneousArgumentsFailure(
      const Solution &solution, FunctionType *contextualType,
      ArrayRef<std::pair<unsigned, AnyFunctionType::Param>> extraArgs,
      ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        ContextualType(resolveType(contextualType)->castTo<FunctionType>()),
        ExtraArgs(extraArgs.begin(), extraArgs.end()) {}

  SourceLoc getLoc() const override;

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

private:
  bool diagnoseSingleExtraArgument() const;

  unsigned getTotalNumArguments() const {
    return ContextualType->getNumParams() + ExtraArgs.size();
  }

  bool isContextualMismatch() const {
    auto *locator = getLocator();
    return locator->isLastElement<LocatorPathElt::ContextualType>() ||
           locator->isLastElement<LocatorPathElt::ApplyArgToParam>();
  }
};

class OutOfOrderArgumentFailure final : public FailureDiagnostic {
  using ParamBinding = SmallVector<unsigned, 1>;

  unsigned ArgIdx;
  unsigned PrevArgIdx;

  SmallVector<ParamBinding, 4> Bindings;

public:
  OutOfOrderArgumentFailure(const Solution &solution, unsigned argIdx,
                            unsigned prevArgIdx,
                            ArrayRef<ParamBinding> bindings,
                            ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), ArgIdx(argIdx),
        PrevArgIdx(prevArgIdx), Bindings(bindings.begin(), bindings.end()) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to destructure a single tuple closure parameter
/// into a multiple (possibly anonymous) arguments e.g.
///
/// ```swift
/// let _: ((Int, Int)) -> Void = { $0 + $1 }
/// ```
class ClosureParamDestructuringFailure final : public FailureDiagnostic {
  FunctionType *ContextualType;

public:
  ClosureParamDestructuringFailure(const Solution &solution,
                                   FunctionType *contextualType,
                                   ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), ContextualType(contextualType) {}

  SourceLoc getLoc() const override;
  SourceRange getSourceRange() const override;

  bool diagnoseAsError() override;

private:
  Type getParameterType() const {
    const auto &param = ContextualType->getParams().front();
    return resolveType(param.getPlainType());
  }
};

/// Diagnose an attempt to reference inaccessible member e.g.
///
/// ```swift
/// struct S {
///   var foo: String
///
///   private init(_ v: String) {
///     self.foo = v
///   }
/// }
/// _ = S("ultimate question")
/// ```
class InaccessibleMemberFailure final : public FailureDiagnostic {
  ValueDecl *Member;

public:
  InaccessibleMemberFailure(const Solution &solution, ValueDecl *member,
                            ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), Member(member) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to reference member marked as `mutating`
/// on immutable base e.g. `let` variable:
///
/// ```swift
/// struct S {
///   mutating func foo(_ i: Int) {}
///   func foo(_ f: Float) {}
/// }
///
/// func bar(_ s: S, _ answer: Int) {
///  s.foo(answer)
/// }
/// ```
class MutatingMemberRefOnImmutableBase final : public FailureDiagnostic {
  ValueDecl *Member;

public:
  MutatingMemberRefOnImmutableBase(const Solution &solution, ValueDecl *member,
                                   ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), Member(member) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to use AnyObject as the root type of a KeyPath
///
/// ```swift
/// let keyPath = \AnyObject.bar
/// ```
class AnyObjectKeyPathRootFailure final : public FailureDiagnostic {

public:
  AnyObjectKeyPathRootFailure(const Solution &solution,
                              ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  SourceLoc getLoc() const override;
  SourceRange getSourceRange() const override;

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to reference subscript as a keypath component
/// where at least one of the index arguments doesn't conform to Hashable e.g.
///
/// ```swift
/// protocol P {}
///
/// struct S {
///   subscript<T: P>(x: Int, _ y: T) -> Bool { return true }
/// }
///
/// func foo<T: P>(_ x: Int, _ y: T) {
///   _ = \S.[x, y]
/// }
/// ```
class KeyPathSubscriptIndexHashableFailure final : public FailureDiagnostic {
  Type NonConformingType;

public:
  KeyPathSubscriptIndexHashableFailure(const Solution &solution, Type type,
                                       ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), NonConformingType(type) {
    assert(locator->isResultOfKeyPathDynamicMemberLookup() ||
           locator->isKeyPathSubscriptComponent());
  }

  SourceLoc getLoc() const override;

  bool diagnoseAsError() override;
};

class InvalidMemberRefInKeyPath : public FailureDiagnostic {
  ValueDecl *Member;

public:
  InvalidMemberRefInKeyPath(const Solution &solution, ValueDecl *member,
                            ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), Member(member) {
    assert(member->hasName());
    assert(locator->isInKeyPathComponent() ||
           locator->isForKeyPathDynamicMemberLookup());
  }

  ValueDecl *getMember() const { return Member; }

  DescriptiveDeclKind getKind() const { return Member->getDescriptiveKind(); }

  DeclName getName() const { return Member->getName(); }

  bool diagnoseAsError() override = 0;

protected:
  /// Compute location of the failure for diagnostic.
  SourceLoc getLoc() const override;

  bool isForKeyPathDynamicMemberLookup() const {
    return getLocator()->isForKeyPathDynamicMemberLookup();
  }
};

/// Diagnose an attempt to reference a static member as a key path component
/// e.g.
///
/// ```swift
/// struct S {
///   static var foo: Int = 42
/// }
///
/// _ = \S.Type.foo
/// ```
class InvalidStaticMemberRefInKeyPath final : public InvalidMemberRefInKeyPath {
public:
  InvalidStaticMemberRefInKeyPath(const Solution &solution, ValueDecl *member,
                                  ConstraintLocator *locator)
      : InvalidMemberRefInKeyPath(solution, member, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to reference an enum case as a key path component
/// e.g.
///
/// ```swift
/// enum E {
///   case foo
/// }
///
/// _ = \E.Type.foo
/// ```
class InvalidEnumCaseRefInKeyPath final : public InvalidMemberRefInKeyPath {
public:
  InvalidEnumCaseRefInKeyPath(const Solution &solution, ValueDecl *member,
                              ConstraintLocator *locator)
      : InvalidMemberRefInKeyPath(solution, member, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to reference a member which has a mutating getter as a
/// key path component e.g.
///
/// ```swift
/// struct S {
///   var foo: Int {
///     mutating get { return 42 }
///   }
///
///   subscript(_: Int) -> Bool {
///     mutating get { return false }
///   }
/// }
///
/// _ = \S.foo
/// _ = \S.[42]
/// ```
class InvalidMemberWithMutatingGetterInKeyPath final
    : public InvalidMemberRefInKeyPath {
public:
  InvalidMemberWithMutatingGetterInKeyPath(const Solution &solution,
                                           ValueDecl *member,
                                           ConstraintLocator *locator)
      : InvalidMemberRefInKeyPath(solution, member, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to reference a method or initializer as a key path component
/// e.g.
///
/// ```swift
/// struct S {
///   init() { }
///   func foo() -> Int { return 42 }
///   static func bar() -> Int { return 0 }
/// }
///
/// _ = \S.foo
/// _ = \S.Type.bar
/// _ = \S.init
/// ```
class InvalidMethodRefInKeyPath final : public InvalidMemberRefInKeyPath {
public:
  InvalidMethodRefInKeyPath(const Solution &solution, ValueDecl *method,
                            ConstraintLocator *locator)
      : InvalidMemberRefInKeyPath(solution, method, locator) {
    assert(isa<FuncDecl>(method) || isa<ConstructorDecl>(method));
  }

  bool diagnoseAsError() override;
};

/// Diagnose an attempt return something from a function which
/// doesn't have a return type specified e.g.
///
/// ```swift
/// func foo() { return 42 }
/// ```
class ExtraneousReturnFailure final : public FailureDiagnostic {
public:
  ExtraneousReturnFailure(const Solution &solution, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

class NotCompileTimeConstFailure final : public FailureDiagnostic {
public:
  NotCompileTimeConstFailure(const Solution &solution, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose \c each applied to an expression that is not a pack type.
class InvalidPackElement final : public FailureDiagnostic {
  Type packElementType;

public:
  InvalidPackElement(const Solution &solution, Type packElementType,
                     ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        packElementType(packElementType) {}

  bool diagnoseAsError() override;
};

/// Diagnose pack references outside of pack expansion expressions.
class InvalidPackReference final : public FailureDiagnostic {
  Type packType;

public:
  InvalidPackReference(const Solution &solution, Type packType,
                       ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        packType(packType) {}

  bool diagnoseAsError() override;
};

/// Diagnose pack expansion expressions appearing in contexts that do not
/// accept a comma-separated list of values.
class InvalidPackExpansion final : public FailureDiagnostic {
public:
  InvalidPackExpansion(const Solution &solution,
                       ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose that a `where` clause is not supported with pack iteration.
class InvalidWhereClauseInPackIteration final : public FailureDiagnostic {
public:
  InvalidWhereClauseInPackIteration(const Solution &solution,
                                    ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose a contextual mismatch between expected collection element type
/// and the one provided (e.g. source of the assignment or argument to a call)
/// e.g.:
///
/// ```swift
/// let _: [Int] = ["hello"]
/// ```
class CollectionElementContextualFailure final : public ContextualFailure {
  SmallVector<Expr *, 4> AffectedElements;

public:
  CollectionElementContextualFailure(const Solution &solution,
                                     ArrayRef<Expr *> affectedElements,
                                     Type eltType, Type contextualType,
                                     ConstraintLocator *locator)
      : ContextualFailure(solution, eltType, contextualType, locator) {
    AffectedElements.append(affectedElements.begin(), affectedElements.end());
  }

  bool diagnoseAsError() override;
};

class MissingContextualConformanceFailure final : public ContextualFailure {
  ContextualTypePurpose Context;

public:
  MissingContextualConformanceFailure(const Solution &solution,
                                      ContextualTypePurpose context, Type type,
                                      Type protocolType,
                                      ConstraintLocator *locator)
      : ContextualFailure(solution, type, protocolType, locator),
        Context(context) {
    assert(protocolType->isExistentialType());
  }

  bool diagnoseAsError() override;
};

/// Diagnose a conversion mismatch between object types of `inout`
/// argument/parameter e.g. `'inout S' argument conv 'inout P'`.
///
/// Even if `S` conforms to `P` there is no subtyping rule for
/// argument type of `inout` parameter, they have to be equal.
class InOutConversionFailure final : public ContextualFailure {
public:
  InOutConversionFailure(const Solution &solution, Type argType, Type paramType,
                         ConstraintLocator *locator)
      : ContextualFailure(solution, argType, paramType, locator) {}

  bool diagnoseAsError() override;

protected:
  /// Suggest to change a type of the argument if possible.
  void fixItChangeArgumentType() const;
};

/// Diagnose generic argument omission e.g.
///
/// ```swift
/// struct S<T> {}
///
/// _ = S()
/// ```
class MissingGenericArgumentsFailure final : public FailureDiagnostic {
  SmallVector<GenericTypeParamType *, 4> Parameters;

public:
  MissingGenericArgumentsFailure(const Solution &solution,
                                 ArrayRef<GenericTypeParamType *> missingParams,
                                 ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {
    assert(!missingParams.empty());
    Parameters.append(missingParams.begin(), missingParams.end());
  }

  bool hasLoc(GenericTypeParamType *GP) const;

  DeclContext *getDeclContext() const {
    auto *GP = Parameters.front();
    auto *decl = GP->getDecl();

    return decl ? decl->getDeclContext() : nullptr;
  }

  bool diagnoseAsError() override;

  bool diagnoseForAnchor(ASTNode anchor,
                         ArrayRef<GenericTypeParamType *> params) const;

  bool diagnoseParameter(ASTNode anchor, GenericTypeParamType *GP) const;

private:
  void emitGenericSignatureNote(ASTNode anchor) const;

  /// Retrieve representative locations for associated generic parameters.
  ///
  /// \returns true if all of the parameters have been covered.
  bool findArgumentLocations(
      llvm::function_ref<void(TypeRepr *, GenericTypeParamType *)> callback);
};

class SkipUnhandledConstructInResultBuilderFailure final
    : public FailureDiagnostic {
public:
  using UnhandledNode = llvm::PointerUnion<Stmt *, Decl *>;

  UnhandledNode unhandled;
  NominalTypeDecl *builder;

  void diagnosePrimary(bool asNote);

public:
  SkipUnhandledConstructInResultBuilderFailure(const Solution &solution,
                                                 UnhandledNode unhandled,
                                                 NominalTypeDecl *builder,
                                                 ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), unhandled(unhandled),
        builder(builder) {}

  SourceLoc getLoc() const override;

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

private:
  /// Tailored diagnostics for an unsupported variable declaration.
  bool diagnosePatternBinding(PatternBindingDecl *PB) const;

  /// Tailored diagnostics for lazy/wrapped/computed variable declarations.
  bool diagnoseStorage(VarDecl *var) const;
};

/// Diagnose situation when a single "tuple" parameter is given N arguments e.g.
///
/// ```swift
/// func foo<T>(_ x: (T, Bool)) {}
/// foo(1, false) // foo expects a single argument of tuple type `(1, false)`
/// ```
class InvalidTupleSplatWithSingleParameterFailure final
    : public FailureDiagnostic {
  Type ParamType;

public:
  InvalidTupleSplatWithSingleParameterFailure(const Solution &solution,
                                              Type paramTy,
                                              ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), ParamType(paramTy) {}
  bool diagnoseAsError() override;
};

/// Diagnose situation when an array is passed instead of varargs.
///
/// ```swift
/// func foo(_ x: Int...) {}
/// foo([1,2,3]]) // foo expects varags like foo(1,2,3) instead.
/// ```
class ExpandArrayIntoVarargsFailure final : public ContextualFailure {
public:
  ExpandArrayIntoVarargsFailure(const Solution &solution, Type lhs, Type rhs,
                                ConstraintLocator *locator)
      : ContextualFailure(solution, lhs, rhs, locator) {}

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

  void tryDropArrayBracketsFixIt(const Expr *anchor) const;
};

/// Diagnose a situation there is a mismatch between argument and parameter
/// types e.g.:
///
/// ```swift
/// func foo(_: String) {}
/// func bar(_ v: Int) { foo(v) } // `Int` is not convertible to `String`
/// ```
class ArgumentMismatchFailure : public ContextualFailure {
  FunctionArgApplyInfo Info;

public:
  ArgumentMismatchFailure(const Solution &solution, Type argType,
                          Type paramType, ConstraintLocator *locator,
                          FixBehavior fixBehavior =
                              FixBehavior::Error)
      : ContextualFailure(solution, argType, paramType, locator, fixBehavior),
        Info(*getFunctionArgApplyInfo(getLocator())) {}

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

  /// If both argument and parameter are represented by `ArchetypeType`
  /// produce a special diagnostic in case their names match.
  bool diagnoseArchetypeMismatch() const;

  /// Tailored diagnostic for pattern matching with `~=` operator.
  bool diagnosePatternMatchingMismatch() const;

  /// Tailored diagnostics for argument mismatches associated with
  /// reference equality operators `===` and `!==`.
  bool diagnoseUseOfReferenceEqualityOperator() const;

  /// Tailored diagnostics for type mismatches associated with
  /// property wrapper initialization via implicit `init(wrappedValue:)`
  /// or now deprecated `init(initialValue:)`.
  bool diagnosePropertyWrapperMismatch() const;

  /// Tailored diagnostics for argument mismatches associated with (trailing)
  /// closures being passed to non-closure parameters.
  bool diagnoseClosureMismatch() const;

  /// Tailored key path as function diagnostics for argument mismatches where
  /// argument is a keypath expression that has a root type that matches a
  /// function parameter, but keypath value don't match the function parameter
  /// result value.
  bool diagnoseKeyPathAsFunctionResultMismatch() const;

  /// Situations like this:
  ///
  /// func foo(_: Int, _: String) {}
  /// foo("")
  ///
  /// Are currently impossible to fix correctly,
  /// so we have to attend to that in diagnostics.
  bool diagnoseMisplacedMissingArgument() const;

  /// Diagnose an attempt to pass a trailing closure to a Regex initializer
  /// without importing RegexBuilder.
  bool diagnoseAttemptedRegexBuilder() const;

protected:
  /// \returns The position of the argument being diagnosed, starting at 1.
  unsigned getArgPosition() const { return Info.getArgPosition(); }

  /// \returns The position of the parameter being diagnosed, starting at 1.
  unsigned getParamPosition() const { return Info.getParamPosition(); }

  /// Returns the argument expression being diagnosed.
  ///
  /// Note this may differ from \c getAnchor(), which will return a smaller
  /// sub-expression if the failed constraint is for a sub-expression within
  /// an argument. For example, in an argument conversion from (T, U) to (U, U),
  /// the conversion from T to U may fail. In this case, \c getArgExpr() will
  /// return the (T, U) expression, whereas \c getAnchor() will return the T
  /// expression.
  Expr *getArgExpr() const { return Info.getArgExpr(); }

  /// Returns the argument type for the conversion being diagnosed.
  ///
  /// \param withSpecifier Whether to keep the inout or @lvalue specifier of
  /// the argument, if any.
  ///
  /// Note this may differ from \c getFromType(), which will give the source
  /// type of a failed constraint for the argument conversion. For example in
  /// an argument conversion from T? to U?, the conversion from T to U may fail.
  /// In this case, \c getArgType() will return T?, whereas \c getFromType()
  /// will return T.
  Type getArgType(bool withSpecifier = false) const {
    return Info.getArgType(withSpecifier);
  }

  /// \returns A textual description of the argument suitable for diagnostics.
  /// For an argument with an unambiguous label, this will the label. Otherwise
  /// it will be its position in the argument list.
  StringRef getArgDescription(SmallVectorImpl<char> &scratch) const {
    return Info.getArgDescription(scratch);
  }

  /// \returns The interface type for the function being applied.
  Type getFnInterfaceType() const { return Info.getFnInterfaceType(); }

  /// \returns The function type being applied, including any generic
  /// substitutions.
  FunctionType *getFnType() const { return Info.getFnType(); }

  /// \returns The callee for the argument conversion, if any.
  const ValueDecl *getCallee() const { return Info.getCallee(); }

  /// \returns The full name of the callee, or a null decl name if there is no
  /// callee.
  DeclName getCalleeFullName() const {
    return getCallee() ? getCallee()->getName() : DeclName();
  }

  /// Returns the type of the parameter involved in the mismatch, including any
  /// generic substitutions.
  ///
  /// \param lookThroughAutoclosure Whether an @autoclosure () -> T parameter
  /// should be treated as being of type T.
  ///
  /// Note this may differ from \c getToType(), see the note on \c getArgType().
  Type getParamType(bool lookThroughAutoclosure = true) const {
    return Info.getParamType(lookThroughAutoclosure);
  }

  /// Returns the type of the parameter involved in the mismatch.
  ///
  /// \param lookThroughAutoclosure Whether an @autoclosure () -> T parameter
  /// should be treated as being of type T.
  ///
  /// Note this may differ from \c getToType(), see the note on \c getArgType().
  Type getParamInterfaceType(bool lookThroughAutoclosure = true) const {
    return Info.getParamInterfaceType(lookThroughAutoclosure);
  }

  /// \returns The flags of the parameter involved in the mismatch.
  ParameterTypeFlags getParameterFlags() const {
    return Info.getParameterFlags();
  }

  /// \returns The flags of a parameter at a given index.
  ParameterTypeFlags getParameterFlagsAtIndex(unsigned idx) const {
    return Info.getParameterFlagsAtIndex(idx);
  }
};

/// Replace a coercion ('as') with a runtime checked cast ('as!' or 'as?').
class InvalidCoercionFailure final : public ContextualFailure {
  bool UseConditionalCast;

public:
  InvalidCoercionFailure(const Solution &solution, Type fromType, Type toType,
                         bool useConditionalCast, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator),
        UseConditionalCast(useConditionalCast) {}

  ASTNode getAnchor() const override;

  SourceLoc getLoc() const override;

  bool diagnoseAsError() override;
};

class ExtraneousCallFailure final : public FailureDiagnostic {
public:
  ExtraneousCallFailure(const Solution &solution, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

class InvalidUseOfTrailingClosure final : public ArgumentMismatchFailure {
public:
  InvalidUseOfTrailingClosure(const Solution &solution, Type argType,
                              Type paramType, ConstraintLocator *locator)
      : ArgumentMismatchFailure(solution, argType, paramType, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose the invalid conversion of a temporary pointer argument generated
/// from an X-to-pointer conversion to an @_nonEphemeral parameter.
///
/// ```swift
/// func foo(@_nonEphemeral _ ptr: UnsafePointer<Int>) {}
///
/// foo([1, 2, 3])
/// ```
class NonEphemeralConversionFailure final : public ArgumentMismatchFailure {
  ConversionRestrictionKind ConversionKind;

public:
  NonEphemeralConversionFailure(const Solution &solution,
                                ConstraintLocator *locator, Type fromType,
                                Type toType,
                                ConversionRestrictionKind conversionKind,
                                FixBehavior fixBehavior)
      : ArgumentMismatchFailure(
            solution, fromType, toType, locator, fixBehavior),
        ConversionKind(conversionKind) {
  }

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

private:
  /// Attempts to emit a specialized diagnostic for
  /// Unsafe[Mutable][Raw]Pointer.init([mutating]:) &
  /// Unsafe[Mutable][Raw]BufferPointer.init(start:count:).
  bool diagnosePointerInit() const;

  /// Emits a note explaining to the user that an ephemeral conversion is only
  /// valid for the duration of the call, and suggests an alternative to use.
  void emitSuggestionNotes() const;
};

class SendingOnFunctionParameterMismatchFail final : public ContextualFailure {
public:
  SendingOnFunctionParameterMismatchFail(const Solution &solution, Type srcType,
                                         Type dstType,
                                         ConstraintLocator *locator,
                                         FixBehavior fixBehavior)
      : ContextualFailure(solution, srcType, dstType, locator, fixBehavior) {}

  bool diagnoseAsError() override;
};

class SendingOnFunctionResultMismatchFailure final : public ContextualFailure {
public:
  SendingOnFunctionResultMismatchFailure(const Solution &solution, Type srcType,
                                         Type dstType,
                                         ConstraintLocator *locator,
                                         FixBehavior fixBehavior)
      : ContextualFailure(solution, srcType, dstType, locator, fixBehavior) {}

  bool diagnoseAsError() override;
};

class AssignmentTypeMismatchFailure final : public ContextualFailure {
public:
  AssignmentTypeMismatchFailure(const Solution &solution,
                                ContextualTypePurpose context, Type srcType,
                                Type dstType, ConstraintLocator *locator)
      : ContextualFailure(solution, context, srcType, dstType, locator) {}

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

private:
  bool diagnoseMissingConformance() const;
};

class MissingContextualBaseInMemberRefFailure final : public FailureDiagnostic {
  DeclNameRef MemberName;

public:
  MissingContextualBaseInMemberRefFailure(const Solution &solution,
                                          DeclNameRef member,
                                          ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), MemberName(member) {}

  bool diagnoseAsError() override;
};

class UnableToInferClosureParameterType final : public FailureDiagnostic {
public:
  UnableToInferClosureParameterType(const Solution &solution,
                                    ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

class UnableToInferClosureReturnType final : public FailureDiagnostic {
public:
  UnableToInferClosureReturnType(const Solution &solution,
                                 ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

class UnableToInferGenericPackElementType final : public FailureDiagnostic {
public:
  UnableToInferGenericPackElementType(const Solution &solution,
                                      ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

class UnableToInferProtocolLiteralType final : public FailureDiagnostic {
public:
  UnableToInferProtocolLiteralType(const Solution &solution,
                                   ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  SourceLoc getLoc() const override;

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to reference a top-level name shadowed by a local
/// member e.g.
///
/// ```swift
/// extension Sequence {
///   func test() -> Int {
///     return max(1, 2)
///   }
/// }
/// ```
///
/// Here `max` refers to a global function `max<T>(_: T, _: T)` in `Swift`
/// module and can only be accessed by adding `Swift.` to it, because `Sequence`
/// has a member named `max` which accepts a single argument.
class MissingQualifierInMemberRefFailure final : public FailureDiagnostic {
public:
  MissingQualifierInMemberRefFailure(const Solution &solution,
                                      ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Emits a warning about an attempt to use the 'as' operator as the 'as!'
/// operator.
class CoercionAsForceCastFailure final : public ContextualFailure {
public:
  CoercionAsForceCastFailure(const Solution &solution, Type fromType,
                             Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose a key path root type that cannot be applied to an instance
/// base that has another type.
///
/// \code
/// func f(_ bar: Bar , keyPath: KeyPath<Foo, Int> ) {
///   bar[keyPath: keyPath]
/// }
/// \endcode
class KeyPathRootTypeMismatchFailure final : public ContextualFailure {
public:
  KeyPathRootTypeMismatchFailure(const Solution &solution, Type lhs, Type rhs,
                                 ConstraintLocator *locator)
      : ContextualFailure(solution, lhs, rhs, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose an attempt to use a KeyPath where a multi-argument function is expected
///
/// ```swift
/// [Item].sorted(\Item.name)
/// ```
class MultiArgFuncKeyPathFailure final : public FailureDiagnostic {
  Type functionType;
public:
  MultiArgFuncKeyPathFailure(const Solution &solution, Type functionType,
                             ConstraintLocator *locator)
  : FailureDiagnostic(solution, locator),
  functionType(functionType) {}

  bool diagnoseAsError() override;
};

/// Diagnose a failure to infer a KeyPath type by context.
///
/// ```swift
/// _ = \.x
/// let _ : AnyKeyPath = \.x
/// ```
class UnableToInferKeyPathRootFailure final : public FailureDiagnostic {
public:
  UnableToInferKeyPathRootFailure(const Solution &solution,
                                  ConstraintLocator *locator)
  : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

class AbstractRawRepresentableFailure : public FailureDiagnostic {
protected:
  Type RawReprType;
  Type ExpectedType;

  AbstractRawRepresentableFailure(const Solution &solution, Type rawReprType,
                                  Type expectedType, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        RawReprType(resolveType(rawReprType)),
        ExpectedType(resolveType(expectedType)) {}

public:
  virtual Type getFromType() const = 0;
  virtual Type getToType() const = 0;

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

protected:
  std::optional<Diag<Type, Type>> getDiagnostic() const;

  virtual void fixIt(InFlightDiagnostic &diagnostic) const = 0;
};

/// Diagnose an attempt to initialize raw representable type or convert to it
/// a value of some other type that matches its `RawValue` type.
///
/// ```swift
/// enum E : Int {
///   case a, b, c
/// }
///
/// let _: E = 0
/// ```
///
/// `0` has to be wrapped into `E(rawValue: 0)` and either defaulted via `??` or
/// force unwrapped to constitute a valid binding.
class MissingRawRepresentableInitFailure final
    : public AbstractRawRepresentableFailure {
public:
  MissingRawRepresentableInitFailure(const Solution &solution, Type rawReprType,
                                     Type expectedType,
                                     ConstraintLocator *locator)
      : AbstractRawRepresentableFailure(solution, rawReprType, expectedType,
                                        locator) {}

  Type getFromType() const override { return ExpectedType; }
  Type getToType() const override { return RawReprType; }

protected:
  void fixIt(InFlightDiagnostic &diagnostic) const override;
};

/// Diagnose an attempt to pass raw representable type where its raw value
/// is expected instead.
///
/// ```swift
/// enum E : Int {
///   case one = 1
/// }
///
/// let _: Int = E.one
/// ```
///
/// `E.one` has to use `.rawValue` to match `Int` expected by pattern binding.
class MissingRawValueFailure final : public AbstractRawRepresentableFailure {
public:
  MissingRawValueFailure(const Solution &solution, Type rawReprType,
                         Type expectedType, ConstraintLocator *locator)
      : AbstractRawRepresentableFailure(solution, rawReprType, expectedType,
                                        locator) {}

  Type getFromType() const override { return RawReprType; }
  Type getToType() const override { return ExpectedType; }

  bool diagnoseAsError() override;

private:
  void fixIt(InFlightDiagnostic &diagnostic) const override;
};

/// Diagnose a key path optional base that should be unwrapped in order to 
/// apply key path subscript.
///
/// \code
/// func f(_ bar: Bar? , keyPath: KeyPath<Bar, Int>) {
///   bar[keyPath: keyPath]
/// }
/// \endcode
class MissingOptionalUnwrapKeyPathFailure final : public ContextualFailure {
public:
  MissingOptionalUnwrapKeyPathFailure(const Solution &solution, Type lhs,
                                      Type rhs, ConstraintLocator *locator)
      : ContextualFailure(solution, lhs, rhs, locator) {}

  bool diagnoseAsError() override;
  SourceLoc getLoc() const override;
};

/// Diagnose situations when trailing closure has been matched to a specific
/// parameter via a deprecated backward scan.
///
/// \code
/// func multiple_trailing_with_defaults(
///   duration: Int,
///   animations: (() -> Void)? = nil,
///   completion: (() -> Void)? = nil) {}
///
/// multiple_trailing_with_defaults(duration: 42) {} // picks `completion:`
/// \endcode
class TrailingClosureRequiresExplicitLabel final : public FailureDiagnostic {
public:
  TrailingClosureRequiresExplicitLabel(const Solution &solution,
                                       ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;

private:
  void fixIt(InFlightDiagnostic &diagnostic,
             const FunctionArgApplyInfo &info) const;
};

/// Diagnose situations where we have a key path with no components.
///
/// \code
/// let _ : KeyPath<A, B> = \A
/// \endcode
class InvalidEmptyKeyPathFailure final : public FailureDiagnostic {
public:
  InvalidEmptyKeyPathFailure(const Solution &solution,
                             ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose an invalid Pattern node in an ExprPattern.
///
/// \code
/// if case foo(let x) = y {}
/// \endcode
class InvalidPatternInExprFailure final : public FailureDiagnostic {
  Pattern *P;

public:
  InvalidPatternInExprFailure(const Solution &solution, Pattern *pattern,
                              ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), P(pattern) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations where there is no context to determine a
/// type of `nil` literal e.g.
///
/// \code
/// let _ = nil
/// let _ = try nil
/// let _ = nil!
/// \endcode
class MissingContextualTypeForNil final : public FailureDiagnostic {
public:
  MissingContextualTypeForNil(const Solution &solution,
                              ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations where there is no context to determine the type of a
/// placeholder, e.g.,
///
/// \code
/// let _ = _.foo
/// \endcode
class CouldNotInferPlaceholderType final : public FailureDiagnostic {
public:
  CouldNotInferPlaceholderType(const Solution &solution,
                               ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnostic situations where AST node references an invalid declaration.
///
/// \code
/// let foo = doesntExist // or something invalid
/// foo(42)
/// \endcode
class ReferenceToInvalidDeclaration final : public FailureDiagnostic {
public:
  ReferenceToInvalidDeclaration(const Solution &solution,
                                ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose use of `return` statements in a body of a result builder.
///
/// \code
/// struct S : Builder {
///   var foo: some Builder {
///     return EmptyBuilder()
///   }
/// }
/// \endcode
class InvalidReturnInResultBuilderBody final : public FailureDiagnostic {
  Type BuilderType;

public:
  InvalidReturnInResultBuilderBody(const Solution &solution, Type builderTy,
                                   ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), BuilderType(builderTy) {}

  bool diagnoseAsError() override;
};

/// Diagnose if the base type is optional, we're referring to a nominal
/// type member via the dot syntax and the member name matches
/// Optional<T>.{member_name} or an unresolved `.none` inferred as a static
/// non-optional member  base but could be an Optional<T>.none. So we enforce
/// explicit type annotation to avoid ambiguity.
///
/// \code
///   enum Enum<T> {
///     case bar
///     static var none: Enum<Int> { .bar }
///   }
///   let _: Enum<Int>? = .none // Base inferred as Optional.none, suggest
///   // explicit type.
///   let _: Enum? = .none // Base inferred as static member Enum<Int>.none,
///   // emit warning suggesting explicit type.
///   let _: Enum = .none // Ok
/// \endcode
class MemberMissingExplicitBaseTypeFailure final : public FailureDiagnostic {
  DeclNameRef Member;

public:
  MemberMissingExplicitBaseTypeFailure(const Solution &solution,
                                       DeclNameRef member,
                                       ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), Member(member) {}

  bool diagnoseAsError() override;
};

class CheckedCastBaseFailure : public ContextualFailure {
protected:
  CheckedCastKind CastKind;
  CheckedCastExpr *CastExpr;

public:
  CheckedCastBaseFailure(const Solution &solution, Type fromType, Type toType,
                         CheckedCastKind kind, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator), CastKind(kind) {
    CastExpr = castToExpr<CheckedCastExpr>(locator->getAnchor());
  }

  bool isCastTypeIUO() const;

  SourceRange getCastRange() const;

protected:
  SourceRange getFromRange() const {
    return CastExpr->getSubExpr()->getSourceRange();
  }

  SourceRange getToRange() const {
    return CastExpr->getCastTypeRepr()->getSourceRange();
  }
};

/// Warn situations where the compiler can statically know a runtime
/// optional checked cast involved in checked cast are coercible.
class CoercibleOptionalCheckedCastFailure final
    : public CheckedCastBaseFailure {
public:
  CoercibleOptionalCheckedCastFailure(const Solution &solution, Type fromType,
                                      Type toType, CheckedCastKind kind,
                                      ConstraintLocator *locator)
      : CheckedCastBaseFailure(solution, fromType, toType, kind, locator) {}

  bool diagnoseAsError() override;

private:
  std::tuple<Type, Type, int> unwrappedTypes() const;

  bool diagnoseTernaryExpr() const;

  bool diagnoseForcedCastExpr() const;

  bool diagnoseConditionalCastExpr() const;
};

/// Warn situations where the compiler can statically know a runtime
/// checked cast always succeed.
class NoopCheckedCast final : public CheckedCastBaseFailure {
public:
  NoopCheckedCast(const Solution &solution, Type fromType, Type toType,
                  CheckedCastKind kind, ConstraintLocator *locator)
      : CheckedCastBaseFailure(solution, fromType, toType, kind, locator) {}

  bool diagnoseAsError() override;

private:
  bool diagnoseIsExpr() const;

  bool diagnoseForcedCastExpr() const;

  bool diagnoseConditionalCastExpr() const;
};

/// Warn situations where the compiler can statically know a runtime
/// checked cast always succeed.
class NoopExistentialToCFTypeCheckedCast final : public CheckedCastBaseFailure {
public:
  NoopExistentialToCFTypeCheckedCast(const Solution &solution, Type fromType,
                                     Type toType, CheckedCastKind kind,
                                     ConstraintLocator *locator)
      : CheckedCastBaseFailure(solution, fromType, toType, kind, locator) {}

  bool diagnoseAsError() override;
};

/// Warn situations where the compiler can statically know a runtime
/// check is not supported.
class UnsupportedRuntimeCheckedCastFailure final
    : public CheckedCastBaseFailure {
public:
  UnsupportedRuntimeCheckedCastFailure(const Solution &solution, Type fromType,
                                       Type toType, CheckedCastKind kind,
                                       ConstraintLocator *locator)
      : CheckedCastBaseFailure(solution, fromType, toType, kind, locator) {}

  bool diagnoseAsError() override;
};

/// Emit a warning when compiler can detect that checked cast would fail at
/// runtime based on statically known types.
class CheckedCastToUnrelatedFailure final : public CheckedCastBaseFailure {
public:
  CheckedCastToUnrelatedFailure(const Solution &solution, Type fromType,
                                Type toType, CheckedCastKind kind,
                                ConstraintLocator *locator)
      : CheckedCastBaseFailure(solution, fromType, toType, kind, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations when static member reference has invalid result
/// type which disqualifies it from being used on a protocol metatype base.
///
/// \code
/// protocol Foo {
///   static var bar: Int
/// }
///
/// _ = Foo.bar
/// \endcode
///
/// `bar` can't be referenced from `P.Protocol` base because its result type
/// `Int` doesn't conform to `Foo`.
class InvalidMemberRefOnProtocolMetatype final : public FailureDiagnostic {
public:
  InvalidMemberRefOnProtocolMetatype(const Solution &solution,
                                     ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations where `weak` attribute is used with a non-optional type
/// in declaration e.g. `weak var x: <Type>`:
///
/// \code
/// class X {
/// }
///
/// weak var x: X = ...
/// \endcode
///
/// `weak` declaration is required to use an optional type e.g. `X?`.
class InvalidWeakAttributeUse final : public FailureDiagnostic {
public:
  InvalidWeakAttributeUse(const Solution &solution, ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Emit a warning for mismatched tuple labels.
class TupleLabelMismatchWarning final : public ContextualFailure {
public:
  TupleLabelMismatchWarning(const Solution &solution, Type fromType,
                            Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {}

  bool diagnoseAsError() override;
};

class AssociatedValueMismatchFailure final : public ContextualFailure {
public:
  AssociatedValueMismatchFailure(const Solution &solution, Type fromType,
                                 Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations where Swift -> C pointer implicit conversion
/// is attempted on a Swift function instead of one imported from C header.
///
/// \code
/// func test(_: UnsafePointer<UInt8>) {}
///
/// func pass_ptr(ptr: UnsafeRawPointer) {
///   test(ptr) // Only okay if `test` was an imported C function.
/// }
/// \endcode
class SwiftToCPointerConversionInInvalidContext final
    : public FailureDiagnostic {
public:
  SwiftToCPointerConversionInInvalidContext(const Solution &solution,
                                            ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations where the type of default expression doesn't
/// match expected type of the argument i.e. generic parameter type
/// was inferred from result:
///
/// \code
/// func test<T>(_: T = 42) -> T { ... }
///
/// let _: String = test() // conflict between `String` and `Int`.
/// \endcode
class DefaultExprTypeMismatch final : public ContextualFailure {
public:
  DefaultExprTypeMismatch(const Solution &solution, Type argType,
                          Type paramType, ConstraintLocator *locator)
      : ContextualFailure(solution, argType, paramType, locator) {}

  SourceLoc getLoc() const override {
    return constraints::getLoc(getLocator()->getAnchor());
  }

  bool diagnoseAsError() override;
};

/// Diagnose situations where inferring existential type for result of
/// a call would result in loss of generic requirements.
///
/// \code
/// protocol P {
///  associatedtype A
/// }
///
/// protocol Q {
///  associatedtype B: P where B.A == Int
/// }
///
/// func getB<T: Q>(_: T) -> T.B { ... }
///
/// func test(v: any Q) {
///   let _ = getB(v) // <- produces `any P` which looses A == Int
/// }
/// \endcode
class MissingExplicitExistentialCoercion final : public FailureDiagnostic {
  Type ErasedResultType;

public:
  MissingExplicitExistentialCoercion(const Solution &solution,
                                     Type erasedResultTy,
                                     ConstraintLocator *locator,
                                     FixBehavior fixBehavior)
      : FailureDiagnostic(solution, locator, fixBehavior),
        ErasedResultType(resolveType(erasedResultTy)) {}

  SourceRange getSourceRange() const override {
    auto rawAnchor = getRawAnchor();
    return {rawAnchor.getStartLoc(), rawAnchor.getEndLoc()};
  }

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;

private:
  void fixIt(InFlightDiagnostic &diagnostic) const;

  /// Determine whether the fix-it to add `as any ...` requires parens.
  ///
  /// Parens are required to avoid suppressing existential opening
  /// if result of the call is passed as an argument to another call
  /// that requires such opening.
  bool fixItRequiresParens() const;
};

/// Diagnose situations where pattern variables with the same name
/// have conflicting types:
///
/// \code
/// enum E {
/// case a(Int)
/// case b(String)
/// }
///
/// func test(e: E) {
///   switch e {
///    case .a(let x), .b(let x): ...
///   }
/// }
/// \endcode
///
/// In this example `x` is bound to `Int` and `String` at the same
/// time which is incorrect.
class ConflictingPatternVariables final : public FailureDiagnostic {
  Type ExpectedType;
  SmallVector<VarDecl *, 4> Vars;

public:
  ConflictingPatternVariables(const Solution &solution, Type expectedTy,
                              ArrayRef<VarDecl *> conflicts,
                              ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        ExpectedType(resolveType(expectedTy)),
        Vars(conflicts.begin(), conflicts.end()) {
    assert(!Vars.empty());
  }

  bool diagnoseAsError() override;
};

/// Diagnose situations where we end up type checking a reference to a macro
/// that was not indicated as a missing # in the source.:
///
/// \code
/// func print(_ value: Any)
/// @expression macro print<Value...>(_ value: Value...)
///
/// func test(e: E) {
///   print(a, b, c) // missing # to use the macro
/// }
/// \endcode
class AddMissingMacroPound final : public FailureDiagnostic {
  MacroDecl *macro;

public:
  AddMissingMacroPound(const Solution &solution, MacroDecl *macro,
                       ConstraintLocator *locator)
    : FailureDiagnostic(solution, locator),
      macro(macro) { }

  bool diagnoseAsError() override;
};

/// Diagnose function types global actor mismatches
/// e.g.  `@MainActor () -> Void` vs.`@OtherActor () -> Void`
class GlobalActorFunctionMismatchFailure final : public ContextualFailure {
public:
  GlobalActorFunctionMismatchFailure(const Solution &solution, Type fromType,
                                     Type toType, ConstraintLocator *locator)
      : ContextualFailure(solution, fromType, toType, locator) {}

  bool diagnoseAsError() override;

private:
  Diag<Type, Type> getDiagnosticMessage() const;
  bool diagnoseTupleElement();
};

/// Diagnose situation when a single argument to tuple type is passed to
/// a value pack expansion parameter that expects distinct N elements:
///
/// ```swift
/// struct S<each T> {
///   func test(x: Int, _: repeat each T) {}
/// }
///
/// S<Int, String>().test(x: 42, (2, "b"))
/// ```
class DestructureTupleToUseWithPackExpansionParameter final
    : public FailureDiagnostic {
  PackType *ParamShape;

public:
  DestructureTupleToUseWithPackExpansionParameter(const Solution &solution,
                                                  PackType *paramShape,
                                                  ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), ParamShape(paramShape) {}

  bool diagnoseAsError() override;
  bool diagnoseAsNote() override;
};

/// Diagnose situations when value pack expansion doesn't have any pack
/// references i.e.:
///
/// ```swift
/// func test(x: Int) {
///   repeat x
/// }
/// ```
class ValuePackExpansionWithoutPackReferences final : public FailureDiagnostic {
public:
  ValuePackExpansionWithoutPackReferences(const Solution &solution,
                                          ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose situations where value pack is referenced without explicit 'each':
///
/// \code
/// func compute<each T>(_: repeat each T) {}
///
/// func test<each T>(v: repeat each T) {
///   repeat compute(v) // should be `repeat compute(each v)`
/// }
/// \endcode
class MissingEachForValuePackReference final : public FailureDiagnostic {
  Type ValuePackType;

public:
  MissingEachForValuePackReference(const Solution &solution, Type valuePackTy,
                                   ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        ValuePackType(resolveType(valuePackTy)) {}

  bool diagnoseAsError() override;
};

class InvalidMemberReferenceWithinInitAccessor final
    : public FailureDiagnostic {
  DeclNameRef MemberName;

public:
  InvalidMemberReferenceWithinInitAccessor(const Solution &solution,
                                           DeclNameRef memberName,
                                           ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), MemberName(memberName) {}

  bool diagnoseAsError() override;
};

/// Diagnose attempts to specialize a concrete type or its alias:
///
/// \code
/// struct Test {}
/// typealias X = Test
///
/// _ = X<Int>() // error
/// \endcode
class ConcreteTypeSpecialization final : public FailureDiagnostic {
  Type ConcreteType;

public:
  ConcreteTypeSpecialization(const Solution &solution, Type concreteTy,
                             ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator),
        ConcreteType(resolveType(concreteTy)) {}

  bool diagnoseAsError() override;
};

/// Diagnose an out-of-place ThenStmt.
class OutOfPlaceThenStmtFailure final : public FailureDiagnostic {
public:
  OutOfPlaceThenStmtFailure(const Solution &solution,
                            ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator) {}

  bool diagnoseAsError() override;
};

/// Diagnose attempts to specialize with invalid number of generic arguments:
///
/// \code
/// struct Test<T, U> {}
///
/// _ = Test<Int>() // error
/// \endcode
class InvalidTypeSpecializationArity final : public FailureDiagnostic {
  ValueDecl *D;
  unsigned NumParams;
  unsigned NumArgs;
  bool HasParameterPack;

public:
  InvalidTypeSpecializationArity(const Solution &solution, ValueDecl *decl,
                                 unsigned numParams, unsigned numArgs,
                                 bool hasParameterPack,
                                 ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), D(decl), NumParams(numParams),
        NumArgs(numArgs), HasParameterPack(hasParameterPack) {}

  bool diagnoseAsError() override;
};

/// Diagnose attempts to pass non-keypath as an argument to key path subscript:
///
/// \code
/// func test(data: Int) {
///   data[keyPath: 42] // error `42` is not a key path
/// }
/// \endcode
class InvalidTypeAsKeyPathSubscriptIndex final : public FailureDiagnostic {
  Type ArgType;

public:
  InvalidTypeAsKeyPathSubscriptIndex(const Solution &solution, Type argType,
                                     ConstraintLocator *locator)
      : FailureDiagnostic(solution, locator), ArgType(resolveType(argType)) {}

  bool diagnoseAsError() override;
};

} // end namespace constraints
} // end namespace swift

#endif // SWIFT_SEMA_CSDIAGNOSTICS_H