File: CSFix.cpp

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 (2664 lines) | stat: -rw-r--r-- 104,775 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
//===--- CSFix.cpp - Constraint Fixes -------------------------------------===//
//
// 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 implements the \c ConstraintFix class and its related types,
// which is used by constraint solver to attempt to fix constraints to be
// able to produce a solution which is easily diagnosable.
//
//===----------------------------------------------------------------------===//

#include "CSDiagnostics.h"
#include "TypeCheckConcurrency.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Type.h"
#include "swift/AST/Types.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/RequirementSignature.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Sema/ConstraintLocator.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/CSFix.h"
#include "swift/Sema/OverloadChoice.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/raw_ostream.h"
#include <string>

using namespace swift;
using namespace constraints;

ConstraintFix::~ConstraintFix() {}

std::optional<ScoreKind> ConstraintFix::impact() const {
  switch (fixBehavior) {
  case FixBehavior::AlwaysWarning:
    return std::nullopt;

  case FixBehavior::Error:
    return SK_Fix;

  case FixBehavior::DowngradeToWarning:
    return SK_DisfavoredOverload;

  case FixBehavior::Suppress:
    return std::nullopt;
  }
}

ASTNode ConstraintFix::getAnchor() const { return getLocator()->getAnchor(); }

void ConstraintFix::print(llvm::raw_ostream &Out) const {
  Out << "[fix: ";
  Out << getName();
  Out << ']';
  Out << " @ ";
  getLocator()->dump(&CS.getASTContext().SourceMgr, Out);
}

void ConstraintFix::dump() const {print(llvm::errs()); }

std::string ForceDowncast::getName() const {
  llvm::SmallString<16> name;
  name += "force downcast (";
  name += getFromType()->getString();
  name += " as! ";
  name += getToType()->getString();
  name += ")";
  return name.c_str();
}

bool ForceDowncast::diagnose(const Solution &solution, bool asNote) const {
  MissingExplicitConversionFailure failure(solution, getFromType(), getToType(),
                                           getLocator());
  return failure.diagnose(asNote);
}

ForceDowncast *ForceDowncast::create(ConstraintSystem &cs, Type fromType,
                                     Type toType, ConstraintLocator *locator) {
  return new (cs.getAllocator()) ForceDowncast(cs, fromType, toType, locator);
}

bool ForceOptional::diagnose(const Solution &solution, bool asNote) const {
  MissingOptionalUnwrapFailure failure(solution, getFromType(), getToType(),
                                       getLocator());
  return failure.diagnose(asNote);
}

ForceOptional *ForceOptional::create(ConstraintSystem &cs, Type fromType,
                                     Type toType, ConstraintLocator *locator) {
  return new (cs.getAllocator()) ForceOptional(cs, fromType, toType, locator);
}

bool UnwrapOptionalBase::diagnose(const Solution &solution, bool asNote) const {
  bool resultIsOptional =
      getKind() == FixKind::UnwrapOptionalBaseWithOptionalResult;
  MemberAccessOnOptionalBaseFailure failure(solution, getLocator(), MemberName,
                                            MemberBaseType, resultIsOptional);
  return failure.diagnose(asNote);
}

UnwrapOptionalBase *UnwrapOptionalBase::create(ConstraintSystem &cs,
                                               DeclNameRef member,
                                               Type memberBaseType,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator()) UnwrapOptionalBase(
      cs, FixKind::UnwrapOptionalBase, member, memberBaseType, locator);
}

UnwrapOptionalBase *UnwrapOptionalBase::createWithOptionalResult(
    ConstraintSystem &cs, DeclNameRef member, Type memberBaseType,
    ConstraintLocator *locator) {
  return new (cs.getAllocator())
      UnwrapOptionalBase(cs, FixKind::UnwrapOptionalBaseWithOptionalResult,
                         member, memberBaseType, locator);
}

bool AddAddressOf::diagnose(const Solution &solution, bool asNote) const {
  MissingAddressOfFailure failure(solution, getFromType(), getToType(),
                                  getLocator());
  return failure.diagnose(asNote);
}

AddAddressOf *AddAddressOf::create(ConstraintSystem &cs, Type argTy,
                                   Type paramTy, ConstraintLocator *locator) {
  return new (cs.getAllocator()) AddAddressOf(cs, argTy, paramTy, locator);
}

bool TreatRValueAsLValue::diagnose(const Solution &solution,
                                   bool asNote) const {
  RValueTreatedAsLValueFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

TreatRValueAsLValue *TreatRValueAsLValue::create(ConstraintSystem &cs,
                                   ConstraintLocator *locator) {
  if (locator->isLastElement<LocatorPathElt::ApplyArgToParam>())
    locator = cs.getConstraintLocator(
        locator, LocatorPathElt::ArgumentAttribute::forInOut());

  return new (cs.getAllocator()) TreatRValueAsLValue(cs, locator);
}

bool CoerceToCheckedCast::diagnose(const Solution &solution,
                                   bool asNote) const {
  InvalidCoercionFailure failure(solution, getFromType(), getToType(),
                                 UseConditionalCast, getLocator());
  return failure.diagnose(asNote);
}

CoerceToCheckedCast *CoerceToCheckedCast::attempt(ConstraintSystem &cs,
                                                  Type fromType, Type toType,
                                                  bool useConditionalCast,
                                                  ConstraintLocator *locator) {
  // If any of the types has a type variable, don't add the fix.
  if (fromType->hasTypeVariable() || toType->hasTypeVariable())
    return nullptr;

  auto anchor = locator->getAnchor();
  if (auto *assignExpr = getAsExpr<AssignExpr>(anchor))
    anchor = assignExpr->getSrc();
  auto *coerceExpr = getAsExpr<CoerceExpr>(anchor);
  if (!coerceExpr)
    return nullptr;

  const auto castKind = TypeChecker::typeCheckCheckedCast(
      fromType, toType, CheckedCastContextKind::Coercion, cs.DC);

  // Invalid cast.
  if (castKind == CheckedCastKind::Unresolved)
    return nullptr;

  return new (cs.getAllocator())
      CoerceToCheckedCast(cs, fromType, toType, useConditionalCast, locator);
}

bool TreatArrayLiteralAsDictionary::diagnose(const Solution &solution,
                                             bool asNote) const {
  ArrayLiteralToDictionaryConversionFailure failure(solution,
                                                    getToType(), getFromType(),
                                                    getLocator());
  return failure.diagnose(asNote);
}

TreatArrayLiteralAsDictionary *
TreatArrayLiteralAsDictionary::attempt(ConstraintSystem &cs, Type dictionaryTy,
                                       Type arrayTy,
                                       ConstraintLocator *locator) {
  if (!arrayTy->isArrayType())
    return nullptr;

  // Determine the ArrayExpr from the locator.
  auto *expr = getAsExpr(simplifyLocatorToAnchor(locator));
  if (!expr)
    return nullptr;

  if (auto *AE = dyn_cast<AssignExpr>(expr))
    expr = AE->getSrc();

  auto *arrayExpr = dyn_cast<ArrayExpr>(expr);
  if (!arrayExpr)
    return nullptr;

  // This fix only applies if the array is used as a dictionary.
  auto unwrappedDict = dictionaryTy->lookThroughAllOptionalTypes();
  if (unwrappedDict->isTypeVariableOrMember())
    return nullptr;

  auto &ctx = cs.getASTContext();

  if (auto *proto = ctx.getProtocol(KnownProtocolKind::ExpressibleByDictionaryLiteral))
      if (!cs.DC->getParentModule()->lookupConformance(unwrappedDict, proto))
        return nullptr;

  auto arrayLoc = cs.getConstraintLocator(arrayExpr);
  return new (cs.getAllocator())
      TreatArrayLiteralAsDictionary(cs, dictionaryTy, arrayTy, arrayLoc);
}

bool MarkExplicitlyEscaping::diagnose(const Solution &solution,
                                      bool asNote) const {
  AttributedFuncToTypeConversionFailure failure(
      solution, getFromType(), getToType(), getLocator(),
      AttributedFuncToTypeConversionFailure::Escaping);
  return failure.diagnose(asNote);
}

MarkExplicitlyEscaping *
MarkExplicitlyEscaping::create(ConstraintSystem &cs, Type lhs, Type rhs,
                               ConstraintLocator *locator) {
  if (locator->isLastElement<LocatorPathElt::ApplyArgToParam>())
    locator = cs.getConstraintLocator(
        locator, LocatorPathElt::ArgumentAttribute::forEscaping());

  return new (cs.getAllocator()) MarkExplicitlyEscaping(cs, lhs, rhs, locator);
}

bool MarkGlobalActorFunction::diagnose(const Solution &solution,
                                       bool asNote) const {
  DroppedGlobalActorFunctionAttr failure(
      solution, getFromType(), getToType(), getLocator(), fixBehavior);
  return failure.diagnose(asNote);
}

/// The fix behavior to apply to a concurrency-related diagnostic.
static std::optional<FixBehavior>
getConcurrencyFixBehavior(ConstraintSystem &cs, ConstraintKind constraintKind,
                          ConstraintLocatorBuilder locator, bool forSendable) {
  // We can only handle the downgrade for conversions.
  switch (constraintKind) {
  case ConstraintKind::Conversion:
  case ConstraintKind::ArgumentConversion:
  case ConstraintKind::Subtype:
    break;

  default:
    if (!cs.shouldAttemptFixes())
      return std::nullopt;

    return FixBehavior::Error;
  }

  // For a @preconcurrency callee outside of a strict concurrency
  // context, ignore.
  if (cs.hasPreconcurrencyCallee(locator)) {
    // Preconcurrency failures are always downgraded to warnings, even in
    // Swift 6 mode.
    if (contextRequiresStrictConcurrencyChecking(
            cs.DC, GetClosureType{cs}, ClosureIsolatedByPreconcurrency{cs})) {
      return FixBehavior::DowngradeToWarning;
    }

    return FixBehavior::Suppress;
  }

  // Otherwise, warn until Swift 6.
  if (!cs.getASTContext().LangOpts.isSwiftVersionAtLeast(6))
    return FixBehavior::DowngradeToWarning;

  return FixBehavior::Error;
}

MarkGlobalActorFunction *
MarkGlobalActorFunction::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                ConstraintLocator *locator,
                                FixBehavior fixBehavior) {
  if (locator->isLastElement<LocatorPathElt::ApplyArgToParam>())
    locator = cs.getConstraintLocator(
        locator, LocatorPathElt::ArgumentAttribute::forGlobalActor());

  return new (cs.getAllocator()) MarkGlobalActorFunction(
      cs, lhs, rhs, locator, fixBehavior);
}

bool MarkGlobalActorFunction::attempt(ConstraintSystem &cs,
                                      ConstraintKind constraintKind,
                                      FunctionType *fromType,
                                      FunctionType *toType,
                                      ConstraintLocatorBuilder locator) {
  auto fixBehavior = getConcurrencyFixBehavior(
      cs, constraintKind, locator, /*forSendable=*/false);
  if (!fixBehavior)
    return true;

  auto *fix = MarkGlobalActorFunction::create(
      cs, fromType, toType, cs.getConstraintLocator(locator),
      *fixBehavior);

  return cs.recordFix(fix);
}

bool AddSendableAttribute::diagnose(const Solution &solution,
                                      bool asNote) const {
  AttributedFuncToTypeConversionFailure failure(
      solution, getFromType(), getToType(), getLocator(),
      AttributedFuncToTypeConversionFailure::Concurrent, fixBehavior);
  return failure.diagnose(asNote);
}

AddSendableAttribute *
AddSendableAttribute::create(ConstraintSystem &cs,
                             FunctionType *fromType,
                             FunctionType *toType,
                             ConstraintLocator *locator,
                             FixBehavior fixBehavior) {
  if (locator->isLastElement<LocatorPathElt::ApplyArgToParam>())
    locator = cs.getConstraintLocator(
        locator, LocatorPathElt::ArgumentAttribute::forConcurrent());

  return new (cs.getAllocator()) AddSendableAttribute(
      cs, fromType, toType, locator, fixBehavior);
}

bool AddSendableAttribute::attempt(ConstraintSystem &cs,
                                   ConstraintKind constraintKind,
                                   FunctionType *fromType,
                                   FunctionType *toType,
                                   ConstraintLocatorBuilder locator) {
  auto fixBehavior = getConcurrencyFixBehavior(
      cs, constraintKind, locator, /*forSendable=*/true);
  if (!fixBehavior)
    return true;

  auto *fix = AddSendableAttribute::create(
      cs, fromType, toType, cs.getConstraintLocator(locator), *fixBehavior);
  return cs.recordFix(fix);
}

bool RelabelArguments::diagnose(const Solution &solution, bool asNote) const {
  LabelingFailure failure(solution, getLocator(), getLabels());
  return failure.diagnose(asNote);
}

bool RelabelArguments::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  SmallPtrSet<ValueDecl *, 4> overloadChoices;

  // First, let's find overload choice associated with each
  // re-labeling fix.
  for (const auto &fix : commonFixes) {
    auto &solution = *fix.first;

    auto calleeLocator = solution.getCalleeLocator(getLocator());
    if (!calleeLocator)
      return false;

    auto overloadChoice = solution.getOverloadChoiceIfAvailable(calleeLocator);
    if (!overloadChoice)
      return false;

    auto *decl = overloadChoice->choice.getDeclOrNull();
    if (!decl)
      return false;

    (void)overloadChoices.insert(decl);
  }

  // If all of the fixes point to the same overload choice then it's
  // exactly the same issue since the call site is static.
  if (overloadChoices.size() == 1)
    return diagnose(*commonFixes.front().first);

  return false;
}

RelabelArguments *
RelabelArguments::create(ConstraintSystem &cs,
                         llvm::ArrayRef<Identifier> correctLabels,
                         ConstraintLocator *locator) {
  unsigned size = totalSizeToAlloc<Identifier>(correctLabels.size());
  void *mem = cs.getAllocator().Allocate(size, alignof(RelabelArguments));
  return new (mem) RelabelArguments(cs, correctLabels, locator);
}

bool MissingConformance::diagnose(const Solution &solution, bool asNote) const {
  auto *locator = getLocator();

  if (IsContextual) {
    auto &cs = solution.getConstraintSystem();
    auto context = cs.getContextualTypePurpose(locator->getAnchor());
    MissingContextualConformanceFailure failure(
        solution, context, getNonConformingType(), getProtocolType(), locator);
    return failure.diagnose(asNote);
  }

  MissingConformanceFailure failure(
      solution, locator,
      std::make_pair(getNonConformingType(), getProtocolType()));
  return failure.diagnose(asNote);
}

bool RequirementFix::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  auto *primaryFix = commonFixes.front().second;
  assert(primaryFix);

  if (llvm::all_of(
          commonFixes,
          [&primaryFix](
              const std::pair<const Solution *, const ConstraintFix *> &entry) {
            return primaryFix->getLocator() == entry.second->getLocator();
          }))
    return diagnose(*commonFixes.front().first);

  // If the location is the same but there are different requirements
  // involved let's not attempt to diagnose that as an ambiguity.
  return false;
}

bool MissingConformance::isEqual(const ConstraintFix *other) const {
  auto *conformanceFix = other->getAs<MissingConformance>();
  if (!conformanceFix)
    return false;

  return IsContextual == conformanceFix->IsContextual &&
         getNonConformingType()->isEqual(
             conformanceFix->getNonConformingType()) &&
         getProtocolType()->isEqual(conformanceFix->getProtocolType());
}

MissingConformance *
MissingConformance::forContextual(ConstraintSystem &cs, Type type,
                                  Type protocolType,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator()) MissingConformance(
      cs, /*isContextual=*/true, type, protocolType, locator);
}

MissingConformance *
MissingConformance::forRequirement(ConstraintSystem &cs, Type type,
                                   Type protocolType,
                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) MissingConformance(
      cs, /*isContextual=*/false, type, protocolType, locator);
}

bool SkipSameTypeRequirement::diagnose(const Solution &solution,
                                       bool asNote) const {
  SameTypeRequirementFailure failure(solution, LHS, RHS, getLocator());
  return failure.diagnose(asNote);
}

SkipSameTypeRequirement *
SkipSameTypeRequirement::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                ConstraintLocator *locator) {
  return new (cs.getAllocator()) SkipSameTypeRequirement(cs, lhs, rhs, locator);
}

bool SkipSameShapeRequirement::diagnose(const Solution &solution,
                                       bool asNote) const {
  if (getLocator()->isLastElement<LocatorPathElt::PackShape>()) {
    SameShapeExpansionFailure failure(solution, LHS, RHS, getLocator());
    return failure.diagnose(asNote);
  }

  SameShapeRequirementFailure failure(solution, LHS, RHS, getLocator());
  return failure.diagnose(asNote);
}

SkipSameShapeRequirement *
SkipSameShapeRequirement::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                 ConstraintLocator *locator) {
  return new (cs.getAllocator()) SkipSameShapeRequirement(cs, lhs, rhs, locator);
}

bool SkipSuperclassRequirement::diagnose(const Solution &solution,
                                         bool asNote) const {
  SuperclassRequirementFailure failure(solution, LHS, RHS, getLocator());
  return failure.diagnose(asNote);
}

SkipSuperclassRequirement *
SkipSuperclassRequirement::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator())
      SkipSuperclassRequirement(cs, lhs, rhs, locator);
}

bool ContextualMismatch::diagnose(const Solution &solution, bool asNote) const {
  ContextualFailure failure(solution, getFromType(), getToType(), getLocator());
  return failure.diagnose(asNote);
}

bool ContextualMismatch::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  auto getTypes =
      [&](const std::pair<const Solution *, const ConstraintFix *> &entry)
      -> std::pair<Type, Type> {
    auto &solution = *entry.first;
    auto *fix = static_cast<const ContextualMismatch *>(entry.second);

    return {solution.simplifyType(fix->getFromType()),
            solution.simplifyType(fix->getToType())};
  };

  auto etalonTypes = getTypes(commonFixes.front());
  if (llvm::all_of(
          commonFixes,
          [&](const std::pair<const Solution *, const ConstraintFix *> &entry) {
            auto types = getTypes(entry);
            return etalonTypes.first->isEqual(types.first) &&
                   etalonTypes.second->isEqual(types.second);
          })) {
    const auto &primary = commonFixes.front();
    return primary.second->diagnose(*primary.first, /*asNote=*/false);
  }

  return false;
}

ContextualMismatch *ContextualMismatch::create(ConstraintSystem &cs, Type lhs,
                                               Type rhs,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator()) ContextualMismatch(
      cs, lhs, rhs, locator, FixBehavior::Error);
}

bool AllowWrappedValueMismatch::diagnose(const Solution &solution, bool asError) const {
  WrappedValueMismatch failure(solution, getFromType(), getToType(), getLocator());
  return failure.diagnoseAsError();
}

AllowWrappedValueMismatch *AllowWrappedValueMismatch::create(ConstraintSystem &cs,
                                                             Type lhs,
                                                             Type rhs,
                                                             ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowWrappedValueMismatch(cs, lhs, rhs, locator);
}

/// Computes the contextual type information for a type mismatch of a
/// component in a structural type (tuple or function type).
///
/// \returns A tuple containing the contextual type purpose, the source type,
/// and the contextual type.
static std::optional<std::tuple<ContextualTypePurpose, Type, Type>>
getStructuralTypeContext(const Solution &solution, ConstraintLocator *locator) {
  if (auto contextualTypeElt =
          locator->findLast<LocatorPathElt::ContextualType>()) {
    assert(locator->isLastElement<LocatorPathElt::ContextualType>() ||
           locator->isLastElement<LocatorPathElt::FunctionArgument>());

    auto &cs = solution.getConstraintSystem();
    auto anchor = locator->getAnchor();
    auto contextualType = cs.getContextualType(anchor, /*forConstraint=*/false);
    auto exprType = cs.getType(anchor);
    return std::make_tuple(contextualTypeElt->getPurpose(), exprType,
                           contextualType);
  } else if (auto argApplyInfo = solution.getFunctionArgApplyInfo(locator)) {
    Type fromType = argApplyInfo->getArgType();
    Type toType = argApplyInfo->getParamType();
    // In case locator points to the function result we want the
    // argument and param function types result.
    if (locator->isLastElement<LocatorPathElt::FunctionResult>()) {
      auto fromFnType = fromType->getAs<FunctionType>();
      auto toFnType = toType->getAs<FunctionType>();
      if (fromFnType && toFnType) {
        auto &cs = solution.getConstraintSystem();
        return std::make_tuple(
            cs.getContextualTypePurpose(locator->getAnchor()),
            fromFnType->getResult(), toFnType->getResult());
      }
    }
    return std::make_tuple(CTP_CallArgument, fromType, toType);
  } else if (auto *coerceExpr = getAsExpr<CoerceExpr>(locator->getAnchor())) {
    return std::make_tuple(CTP_CoerceOperand,
                           solution.getType(coerceExpr->getSubExpr()),
                           solution.getType(coerceExpr));
  } else if (auto *assignExpr = getAsExpr<AssignExpr>(locator->getAnchor())) {
    auto CTP = isa<SubscriptExpr>(assignExpr->getDest()) ? CTP_SubscriptAssignSource
                                                         : CTP_AssignSource;
    return std::make_tuple(CTP,
                           solution.getType(assignExpr->getSrc()),
                           solution.getType(assignExpr->getDest())->getRValueType());
  }
  return std::nullopt;
}

bool AllowTupleTypeMismatch::coalesceAndDiagnose(
    const Solution &solution, ArrayRef<ConstraintFix *> fixes,
    bool asNote) const {
  llvm::SmallVector<unsigned, 4> indices;
  if (isElementMismatch())
    indices.push_back(*Index);

  for (auto fix : fixes) {
    auto *tupleFix = fix->getAs<AllowTupleTypeMismatch>();
    if (!tupleFix || !tupleFix->isElementMismatch())
      continue;
    indices.push_back(*tupleFix->Index);
  }

  auto *locator = getLocator();
  ContextualTypePurpose purpose;
  if (isExpr<CoerceExpr>(locator->getAnchor())) {
    purpose = CTP_CoerceOperand;
  } else if (auto *assignExpr = getAsExpr<AssignExpr>(locator->getAnchor())) {
    purpose = isa<SubscriptExpr>(assignExpr->getDest()) ? CTP_SubscriptAssignSource
                                                        : CTP_AssignSource;
  } else {
    auto &cs = getConstraintSystem();
    purpose = cs.getContextualTypePurpose(locator->getAnchor());
  }

  if (!getFromType()->is<TupleType>() || !getToType()->is<TupleType>()) {
    return false;
  }

  TupleContextualFailure failure(solution, purpose, getFromType(), getToType(),
                                 indices, locator);
  return failure.diagnose(asNote);
}

bool AllowTupleTypeMismatch::diagnose(const Solution &solution,
                                      bool asNote) const {
  return coalesceAndDiagnose(solution, {}, asNote);
}

AllowTupleTypeMismatch *
AllowTupleTypeMismatch::create(ConstraintSystem &cs, Type lhs, Type rhs,
                               ConstraintLocator *locator,
                               std::optional<unsigned> index) {
  return new (cs.getAllocator())
      AllowTupleTypeMismatch(cs, lhs, rhs, locator, index);
}

bool AllowFunctionTypeMismatch::coalesceAndDiagnose(
    const Solution &solution, ArrayRef<ConstraintFix *> fixes,
    bool asNote) const {
  llvm::SmallVector<unsigned, 4> indices{ParamIndex};

  for (auto fix : fixes) {
    if (auto *fnFix = fix->getAs<AllowFunctionTypeMismatch>())
      indices.push_back(fnFix->ParamIndex);
  }

  auto *locator = getLocator();
  ContextualTypePurpose purpose;
  Type fromType;
  Type toType;

  auto contextualTypeInfo = getStructuralTypeContext(solution, locator);
  if (!contextualTypeInfo)
    return false;

  std::tie(purpose, fromType, toType) = *contextualTypeInfo;
  FunctionTypeMismatch failure(solution, purpose, fromType, toType, indices,
                               locator);
  return failure.diagnose(asNote);
}

bool AllowFunctionTypeMismatch::diagnose(const Solution &solution,
                                         bool asNote) const {
  return coalesceAndDiagnose(solution, {}, asNote);
}

bool AllowFunctionTypeMismatch::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  if (ContextualMismatch::diagnoseForAmbiguity(commonFixes))
    return true;

  auto *locator = getLocator();
  // If this is a mismatch between two function types at argument
  // position, there is a tailored diagnostic for that.
  if (auto argConv =
          locator->getLastElementAs<LocatorPathElt::ApplyArgToParam>()) {
    auto &cs = getConstraintSystem();
    auto &DE = cs.getASTContext().Diags;
    auto &solution = *commonFixes[0].first;

    auto info = getStructuralTypeContext(solution, locator);
    if (!info)
      return false;

    auto *argLoc = cs.getConstraintLocator(simplifyLocatorToAnchor(locator));

    auto overload = solution.getOverloadChoiceIfAvailable(
        solution.getCalleeLocator(argLoc));
    if (!overload)
      return false;

    auto name = overload->choice.getName().getBaseName();
    DE.diagnose(getLoc(getAnchor()), diag::no_candidates_match_argument_type,
                name.userFacingName(), std::get<2>(*info),
                argConv->getParamIdx());

    for (auto &entry : commonFixes) {
      auto &solution = *entry.first;
      auto overload = solution.getOverloadChoiceIfAvailable(
          solution.getCalleeLocator(argLoc));

      if (!(overload && overload->choice.isDecl()))
        continue;

      auto *decl = overload->choice.getDecl();
      if (decl->getLoc().isValid()) {
        DE.diagnose(decl, diag::found_candidate_type,
                    solution.simplifyType(overload->adjustedOpenedType));
      }
    }

    return true;
  }

  return false;
}

AllowFunctionTypeMismatch *
AllowFunctionTypeMismatch::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                  ConstraintLocator *locator, unsigned index) {
  return new (cs.getAllocator())
      AllowFunctionTypeMismatch(cs, lhs, rhs, locator, index);
}

bool GenericArgumentsMismatch::coalesceAndDiagnose(
    const Solution &solution, ArrayRef<ConstraintFix *> secondaryFixes,
    bool asNote) const {
  std::set<unsigned> scratch(getMismatches().begin(), getMismatches().end());

  for (auto *fix : secondaryFixes) {
    auto *genericArgsFix = fix->castTo<GenericArgumentsMismatch>();
    for (auto mismatchIdx : genericArgsFix->getMismatches())
      scratch.insert(mismatchIdx);
  }

  SmallVector<unsigned> mismatches(scratch.begin(), scratch.end());
  return diagnose(solution, mismatches, asNote);
}

bool GenericArgumentsMismatch::diagnose(const Solution &solution,
                                        bool asNote) const {
  return diagnose(solution, getMismatches(), asNote);
}

bool GenericArgumentsMismatch::diagnose(const Solution &solution,
                                        ArrayRef<unsigned> mismatches,
                                        bool asNote) const {
  GenericArgumentsMismatchFailure failure(solution, getFromType(), getToType(),
                                          mismatches, getLocator());
  return failure.diagnose(asNote);
}

GenericArgumentsMismatch *GenericArgumentsMismatch::create(
    ConstraintSystem &cs, Type actual, Type required,
    llvm::ArrayRef<unsigned> mismatches, ConstraintLocator *locator) {
  unsigned size = totalSizeToAlloc<unsigned>(mismatches.size());
  void *mem =
      cs.getAllocator().Allocate(size, alignof(GenericArgumentsMismatch));
  return new (mem)
      GenericArgumentsMismatch(cs, actual, required, mismatches, locator);
}

bool AutoClosureForwarding::diagnose(const Solution &solution,
                                     bool asNote) const {
  AutoClosureForwardingFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AutoClosureForwarding *AutoClosureForwarding::create(ConstraintSystem &cs,
                                                     ConstraintLocator *locator) {
  return new (cs.getAllocator()) AutoClosureForwarding(cs, locator);
}

bool AllowAutoClosurePointerConversion::diagnose(const Solution &solution,
                                                 bool asNote) const {
  AutoClosurePointerConversionFailure failure(solution, getFromType(),
                                              getToType(), getLocator());
  return failure.diagnose(asNote);
}

AllowAutoClosurePointerConversion *
AllowAutoClosurePointerConversion::create(ConstraintSystem &cs, Type pointeeType,
                                          Type pointerType,
                                          ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowAutoClosurePointerConversion(cs, pointeeType, pointerType, locator);
}

bool RemoveUnwrap::diagnose(const Solution &solution, bool asNote) const {
  NonOptionalUnwrapFailure failure(solution, BaseType, getLocator());
  return failure.diagnose(asNote);
}

RemoveUnwrap *RemoveUnwrap::create(ConstraintSystem &cs, Type baseType,
                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) RemoveUnwrap(cs, baseType, locator);
}

bool InsertExplicitCall::diagnose(const Solution &solution, bool asNote) const {
  MissingCallFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

InsertExplicitCall *InsertExplicitCall::create(ConstraintSystem &cs,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator()) InsertExplicitCall(cs, locator);
}

bool UsePropertyWrapper::diagnose(const Solution &solution, bool asNote) const {
  ExtraneousPropertyWrapperUnwrapFailure failure(
      solution, Wrapped, UsingProjection, Base, Wrapper, getLocator());
  return failure.diagnose(asNote);
}

UsePropertyWrapper *UsePropertyWrapper::create(ConstraintSystem &cs,
                                               VarDecl *wrapped,
                                               bool usingProjection,
                                               Type base, Type wrapper,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator()) UsePropertyWrapper(
      cs, wrapped, usingProjection, base, wrapper, locator);
}

bool UseWrappedValue::diagnose(const Solution &solution, bool asNote) const {
  MissingPropertyWrapperUnwrapFailure failure(solution, PropertyWrapper,
                                              usingProjection(), Base,
                                              Wrapper, getLocator());
  return failure.diagnose(asNote);
}

UseWrappedValue *UseWrappedValue::create(ConstraintSystem &cs,
                                         VarDecl *propertyWrapper, Type base,
                                         Type wrapper,
                                         ConstraintLocator *locator) {
  return new (cs.getAllocator())
      UseWrappedValue(cs, propertyWrapper, base, wrapper, locator);
}

bool AllowInvalidPropertyWrapperType::diagnose(const Solution &solution, bool asNote) const {
  InvalidPropertyWrapperType failure(solution, wrapperType, getLocator());
  return failure.diagnose(asNote);
}

AllowInvalidPropertyWrapperType *
AllowInvalidPropertyWrapperType::create(ConstraintSystem &cs, Type wrapperType,
                                        ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowInvalidPropertyWrapperType(cs, wrapperType, locator);
}

bool RemoveProjectedValueArgument::diagnose(const Solution &solution, bool asNote) const {
  InvalidProjectedValueArgument failure(solution, wrapperType, param, getLocator());
  return failure.diagnose(asNote);
}

RemoveProjectedValueArgument *
RemoveProjectedValueArgument::create(ConstraintSystem &cs, Type wrapperType,
                                      ParamDecl *param, ConstraintLocator *locator) {
  return new (cs.getAllocator()) RemoveProjectedValueArgument(cs, wrapperType, param, locator);
}

bool UseSubscriptOperator::diagnose(const Solution &solution,
                                    bool asNote) const {
  SubscriptMisuseFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

UseSubscriptOperator *UseSubscriptOperator::create(ConstraintSystem &cs,
                                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) UseSubscriptOperator(cs, locator);
}

bool DefineMemberBasedOnUse::diagnose(const Solution &solution,
                                      bool asNote) const {
  MissingMemberFailure failure(solution, BaseType, Name, getLocator());
  return AlreadyDiagnosed || failure.diagnose(asNote);
}

bool
DefineMemberBasedOnUse::diagnoseForAmbiguity(CommonFixesArray commonFixes) const {
  Type concreteBaseType;
  for (const auto &solutionAndFix : commonFixes) {
    const auto *solution = solutionAndFix.first;
    const auto *fix = solutionAndFix.second->getAs<DefineMemberBasedOnUse>();

    auto baseType = solution->simplifyType(fix->BaseType);
    if (!concreteBaseType)
      concreteBaseType = baseType;

    if (concreteBaseType->getCanonicalType() != baseType->getCanonicalType()) {
      auto &DE = getConstraintSystem().getASTContext().Diags;
      DE.diagnose(getLoc(getAnchor()), diag::unresolved_member_no_inference,
                  Name);
      return true;
    }
  }

  return diagnose(*commonFixes.front().first);
}

DefineMemberBasedOnUse *
DefineMemberBasedOnUse::create(ConstraintSystem &cs, Type baseType,
                               DeclNameRef member, bool alreadyDiagnosed,
                               ConstraintLocator *locator) {
  return new (cs.getAllocator())
      DefineMemberBasedOnUse(cs, baseType, member, alreadyDiagnosed, locator);
}

bool DefineMemberBasedOnUnintendedGenericParam::diagnose(
    const Solution &solution, bool asNote) const {
  UnintendedExtraGenericParamMemberFailure failure(solution, BaseType, Name,
                                                   ParamName, getLocator());
  return failure.diagnose(asNote);
}

DefineMemberBasedOnUnintendedGenericParam *
DefineMemberBasedOnUnintendedGenericParam::create(ConstraintSystem &cs,
                                                  Type baseType,
                                                  DeclNameRef member,
                                                  Identifier paramName,
                                                  ConstraintLocator *locator) {
  return new (cs.getAllocator()) DefineMemberBasedOnUnintendedGenericParam(
      cs, baseType, member, paramName, locator);
}

AllowMemberRefOnExistential *
AllowMemberRefOnExistential::create(ConstraintSystem &cs, Type baseType,
                                    ValueDecl *member, DeclNameRef memberName,
                                    ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowMemberRefOnExistential(cs, baseType, memberName, member, locator);
}

bool AllowMemberRefOnExistential::diagnose(const Solution &solution,
                                           bool asNote) const {
  InvalidMemberRefOnExistential failure(solution, getBaseType(),
                                        getMemberName(), getLocator());
  return failure.diagnose(asNote);
}

bool AllowInvalidMemberRef::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  auto *primaryFix =
      static_cast<const AllowInvalidMemberRef *>(commonFixes.front().second);

  Type baseTy = primaryFix->getBaseType();
  for (const auto &entry : commonFixes) {
    auto *memberFix = static_cast<const AllowInvalidMemberRef *>(entry.second);
    if (!baseTy->isEqual(memberFix->getBaseType()))
      return false;
  }

  return diagnose(*commonFixes.front().first);
}

bool AllowTypeOrInstanceMember::diagnose(const Solution &solution,
                                         bool asNote) const {
  AllowTypeOrInstanceMemberFailure failure(solution, getBaseType(), getMember(),
                                           getMemberName(), getLocator());
  return failure.diagnose(asNote);
}

AllowTypeOrInstanceMember *
AllowTypeOrInstanceMember::create(ConstraintSystem &cs, Type baseType,
                                  ValueDecl *member, DeclNameRef usedName,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowTypeOrInstanceMember(cs, baseType, member, usedName, locator);
}

bool AllowInvalidPartialApplication::diagnose(const Solution &solution,
                                              bool asNote) const {
  PartialApplicationFailure failure(isWarning, solution, getLocator());
  return failure.diagnose(asNote);
}

AllowInvalidPartialApplication *
AllowInvalidPartialApplication::create(bool isWarning, ConstraintSystem &cs,
                                       ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInvalidPartialApplication(isWarning, cs, locator);
}

bool AllowInvalidInitRef::diagnose(const Solution &solution,
                                   bool asNote) const {
  switch (Kind) {
  case RefKind::DynamicOnMetatype: {
    InvalidDynamicInitOnMetatypeFailure failure(solution, BaseType, Init,
                                                BaseRange, getLocator());
    return failure.diagnose(asNote);
  }

  case RefKind::ProtocolMetatype: {
    InitOnProtocolMetatypeFailure failure(
        solution, BaseType, Init, IsStaticallyDerived, BaseRange, getLocator());
    return failure.diagnose(asNote);
  }

  case RefKind::NonConstMetatype: {
    ImplicitInitOnNonConstMetatypeFailure failure(solution, BaseType, Init,
                                                  getLocator());
    return failure.diagnose(asNote);
  }
  }
  llvm_unreachable("covered switch");
}

AllowInvalidInitRef *AllowInvalidInitRef::dynamicOnMetatype(
    ConstraintSystem &cs, Type baseTy, ConstructorDecl *init,
    SourceRange baseRange, ConstraintLocator *locator) {
  return create(RefKind::DynamicOnMetatype, cs, baseTy, init,
                /*isStaticallyDerived=*/false, baseRange, locator);
}

AllowInvalidInitRef *AllowInvalidInitRef::onProtocolMetatype(
    ConstraintSystem &cs, Type baseTy, ConstructorDecl *init,
    bool isStaticallyDerived, SourceRange baseRange,
    ConstraintLocator *locator) {
  return create(RefKind::ProtocolMetatype, cs, baseTy, init,
                isStaticallyDerived, baseRange, locator);
}

AllowInvalidInitRef *
AllowInvalidInitRef::onNonConstMetatype(ConstraintSystem &cs, Type baseTy,
                                        ConstructorDecl *init,
                                        ConstraintLocator *locator) {
  return create(RefKind::NonConstMetatype, cs, baseTy, init,
                /*isStaticallyDerived=*/false, SourceRange(), locator);
}

AllowInvalidInitRef *
AllowInvalidInitRef::create(RefKind kind, ConstraintSystem &cs, Type baseTy,
                            ConstructorDecl *init, bool isStaticallyDerived,
                            SourceRange baseRange, ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowInvalidInitRef(
      cs, kind, baseTy, init, isStaticallyDerived, baseRange, locator);
}

bool AllowClosureParamDestructuring::diagnose(const Solution &solution,
                                              bool asNote) const {
  ClosureParamDestructuringFailure failure(solution, ContextualType,
                                           getLocator());
  return failure.diagnose(asNote);
}

AllowClosureParamDestructuring *
AllowClosureParamDestructuring::create(ConstraintSystem &cs,
                                       FunctionType *contextualType,
                                       ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowClosureParamDestructuring(cs, contextualType, locator);
}

bool AddMissingArguments::diagnose(const Solution &solution,
                                   bool asNote) const {
  MissingArgumentsFailure failure(solution, getSynthesizedArguments(),
                                  getLocator());
  return failure.diagnose(asNote);
}

AddMissingArguments *
AddMissingArguments::create(ConstraintSystem &cs,
                            ArrayRef<SynthesizedArg> synthesizedArgs,
                            ConstraintLocator *locator) {
  unsigned size = totalSizeToAlloc<SynthesizedArg>(synthesizedArgs.size());
  void *mem = cs.getAllocator().Allocate(size, alignof(AddMissingArguments));
  return new (mem) AddMissingArguments(cs, synthesizedArgs, locator);
}

bool RemoveExtraneousArguments::diagnose(const Solution &solution,
                                         bool asNote) const {
  ExtraneousArgumentsFailure failure(solution, ContextualType,
                                     getExtraArguments(), getLocator());
  return failure.diagnose(asNote);
}

bool RemoveExtraneousArguments::isMinMaxNameShadowing(
    ConstraintSystem &cs, ConstraintLocatorBuilder locator) {
  auto *anchor = getAsExpr<CallExpr>(locator.getAnchor());
  if (!anchor)
    return false;

  if (auto *UDE = dyn_cast<UnresolvedDotExpr>(anchor->getFn())) {
    if (auto *baseExpr = dyn_cast<DeclRefExpr>(UDE->getBase())) {
      auto *decl = baseExpr->getDecl();
      if (baseExpr->isImplicit() && decl &&
          decl->getName() == cs.getASTContext().Id_self) {
        auto memberName = UDE->getName();
        return memberName.isSimpleName("min") || memberName.isSimpleName("max");
      }
    }
  }

  return false;
}

RemoveExtraneousArguments *RemoveExtraneousArguments::create(
    ConstraintSystem &cs, FunctionType *contextualType,
    llvm::ArrayRef<IndexedParam> extraArgs, ConstraintLocator *locator) {
  unsigned size = totalSizeToAlloc<IndexedParam>(extraArgs.size());
  void *mem = cs.getAllocator().Allocate(size, alignof(RemoveExtraneousArguments));
  return new (mem)
      RemoveExtraneousArguments(cs, contextualType, extraArgs, locator);
}

bool MoveOutOfOrderArgument::diagnose(const Solution &solution,
                                      bool asNote) const {
  OutOfOrderArgumentFailure failure(solution, ArgIdx, PrevArgIdx, Bindings,
                                    getLocator());
  return failure.diagnose(asNote);
}

bool MoveOutOfOrderArgument::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  auto *primaryFix =
      commonFixes.front().second->getAs<MoveOutOfOrderArgument>();
  assert(primaryFix);

  if (llvm::all_of(
          commonFixes,
          [&primaryFix](
              const std::pair<const Solution *, const ConstraintFix *> &entry) {
            return primaryFix->isEqual(entry.second);
          }))
    return diagnose(*commonFixes.front().first);

  return false;
}

bool MoveOutOfOrderArgument::isEqual(const ConstraintFix *other) const {
  auto OoOFix = other->getAs<MoveOutOfOrderArgument>();
  return OoOFix ? ArgIdx == OoOFix->ArgIdx && PrevArgIdx == OoOFix->PrevArgIdx
                : false;
}

MoveOutOfOrderArgument *MoveOutOfOrderArgument::create(
    ConstraintSystem &cs, unsigned argIdx, unsigned prevArgIdx,
    ArrayRef<ParamBinding> bindings, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      MoveOutOfOrderArgument(cs, argIdx, prevArgIdx, bindings, locator);
}

bool AllowInaccessibleMember::diagnose(const Solution &solution,
                                       bool asNote) const {
  InaccessibleMemberFailure failure(solution, getMember(), getLocator());
  return failure.diagnose(asNote);
}

AllowInaccessibleMember *
AllowInaccessibleMember::create(ConstraintSystem &cs, Type baseType,
                                ValueDecl *member, DeclNameRef name,
                                ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInaccessibleMember(cs, baseType, member, name, locator);
}

bool AllowAnyObjectKeyPathRoot::diagnose(const Solution &solution,
                                         bool asNote) const {
  AnyObjectKeyPathRootFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowAnyObjectKeyPathRoot *
AllowAnyObjectKeyPathRoot::create(ConstraintSystem &cs,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowAnyObjectKeyPathRoot(cs, locator);
}

bool AllowMultiArgFuncKeyPathMismatch::diagnose(const Solution &solution,
                                                bool asNote) const {
  MultiArgFuncKeyPathFailure failure(solution, functionType, getLocator());
  return failure.diagnose(asNote);
}

AllowMultiArgFuncKeyPathMismatch *
AllowMultiArgFuncKeyPathMismatch::create(ConstraintSystem &cs, Type fnType,
                                         ConstraintLocator *locator) {
  return new (cs.getAllocator())
  AllowMultiArgFuncKeyPathMismatch(cs, fnType, locator);
}

bool TreatKeyPathSubscriptIndexAsHashable::diagnose(const Solution &solution,
                                                    bool asNote) const {
  KeyPathSubscriptIndexHashableFailure failure(solution, NonConformingType,
                                               getLocator());
  return failure.diagnose(asNote);
}

TreatKeyPathSubscriptIndexAsHashable *
TreatKeyPathSubscriptIndexAsHashable::create(ConstraintSystem &cs, Type type,
                                             ConstraintLocator *locator) {
  return new (cs.getAllocator())
      TreatKeyPathSubscriptIndexAsHashable(cs, type, locator);
}

bool AllowInvalidRefInKeyPath::diagnose(const Solution &solution,
                                        bool asNote) const {
  switch (Kind) {
  case RefKind::StaticMember: {
    InvalidStaticMemberRefInKeyPath failure(solution, Member, getLocator());
    return failure.diagnose(asNote);
  }

  case RefKind::EnumCase: {
    InvalidEnumCaseRefInKeyPath failure(solution, Member, getLocator());
    return failure.diagnose(asNote);
  }

  case RefKind::MutatingGetter: {
    InvalidMemberWithMutatingGetterInKeyPath failure(solution, Member,
                                                     getLocator());
    return failure.diagnose(asNote);
  }

  case RefKind::Method:
  case RefKind::Initializer: {
    InvalidMethodRefInKeyPath failure(solution, Member, getLocator());
    return failure.diagnose(asNote);
  }
  }
  llvm_unreachable("covered switch");
}

bool AllowInvalidRefInKeyPath::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  auto *primaryFix =
      commonFixes.front().second->getAs<AllowInvalidRefInKeyPath>();
  assert(primaryFix);

  if (llvm::all_of(
          commonFixes,
          [&primaryFix](
              const std::pair<const Solution *, const ConstraintFix *> &entry) {
            return primaryFix->isEqual(entry.second);
          })) {
    return diagnose(*commonFixes.front().first);
  }

  return false;
}

bool AllowInvalidRefInKeyPath::isEqual(const ConstraintFix *other) const {
  auto *refFix = other->getAs<AllowInvalidRefInKeyPath>();
  return refFix ? Kind == refFix->Kind && Member == refFix->Member : false;
}

AllowInvalidRefInKeyPath *
AllowInvalidRefInKeyPath::forRef(ConstraintSystem &cs, ValueDecl *member,
                                 ConstraintLocator *locator) {
  // Referencing (instance or static) methods in key path is
  // not currently allowed.
  if (isa<FuncDecl>(member))
    return AllowInvalidRefInKeyPath::create(cs, RefKind::Method, member,
                                            locator);

  // Referencing enum cases in key path is not currently allowed.
  if (isa<EnumElementDecl>(member)) {
    return AllowInvalidRefInKeyPath::create(cs, RefKind::EnumCase, member,
                                            locator);
  }

  // Referencing initializers in key path is not currently allowed.
  if (isa<ConstructorDecl>(member))
    return AllowInvalidRefInKeyPath::create(cs, RefKind::Initializer,
                                            member, locator);

  // Referencing static members in key path is not currently allowed.
  if (member->isStatic())
    return AllowInvalidRefInKeyPath::create(cs, RefKind::StaticMember, member,
                                            locator);

  if (auto *storage = dyn_cast<AbstractStorageDecl>(member)) {
    // Referencing members with mutating getters in key path is not
    // currently allowed.
    if (storage->isGetterMutating())
      return AllowInvalidRefInKeyPath::create(cs, RefKind::MutatingGetter,
                                              member, locator);
  }

  return nullptr;
}

AllowInvalidRefInKeyPath *
AllowInvalidRefInKeyPath::create(ConstraintSystem &cs, RefKind kind,
                                 ValueDecl *member,
                                 ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInvalidRefInKeyPath(cs, kind, member, locator);
}

bool RemoveAddressOf::diagnose(const Solution &solution, bool asNote) const {
  InvalidUseOfAddressOf failure(solution, getFromType(), getToType(),
                                getLocator());
  return failure.diagnose(asNote);
}

RemoveAddressOf *RemoveAddressOf::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                         ConstraintLocator *locator) {
  return new (cs.getAllocator()) RemoveAddressOf(cs, lhs, rhs, locator);
}

RemoveReturn::RemoveReturn(ConstraintSystem &cs, Type resultTy,
                           ConstraintLocator *locator)
    : ContextualMismatch(cs, FixKind::RemoveReturn, resultTy,
                         cs.getASTContext().TheEmptyTupleType, locator) {}

bool RemoveReturn::diagnose(const Solution &solution, bool asNote) const {
  ExtraneousReturnFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

RemoveReturn *RemoveReturn::create(ConstraintSystem &cs, Type resultTy,
                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) RemoveReturn(cs, resultTy, locator);
}

NotCompileTimeConst::NotCompileTimeConst(ConstraintSystem &cs, Type paramTy,
                                         ConstraintLocator *locator):
  ContextualMismatch(cs, FixKind::NotCompileTimeConst, paramTy,
                     cs.getASTContext().TheEmptyTupleType, locator,
                     FixBehavior::AlwaysWarning) {}

NotCompileTimeConst *
NotCompileTimeConst::create(ConstraintSystem &cs, Type paramTy,
                            ConstraintLocator *locator) {
  return new (cs.getAllocator()) NotCompileTimeConst(cs, paramTy, locator);
}

bool NotCompileTimeConst::diagnose(const Solution &solution, bool asNote) const {
  auto *locator = getLocator();
  if (auto *E = getAsExpr(locator->getAnchor())) {
    auto isAccepted = E->isSemanticallyConstExpr([&](Expr *E) {
      if (auto *UMC = dyn_cast<UnresolvedMemberChainResultExpr>(E)) {
        E = UMC->getSubExpr();
      }
      auto locator = solution.getConstraintSystem().getConstraintLocator(E);
      // Referencing an enum element directly is considered a compile-time literal.
      if (auto *d = solution.resolveLocatorToDecl(locator).getDecl()) {
        if (isa<EnumElementDecl>(d)) {
          if (!d->hasParameterList()) {
            return true;
          }
        }
      }
      return false;
    });
    if (isAccepted)
      return true;
  }

  NotCompileTimeConstFailure failure(solution, locator);
  return failure.diagnose(asNote);
}

bool AllowInvalidPackElement::diagnose(const Solution &solution,
                                       bool asNote) const {
  InvalidPackElement failure(solution, packElementType, getLocator());
  return failure.diagnose(asNote);
}

AllowInvalidPackElement *
AllowInvalidPackElement::create(ConstraintSystem &cs,
                                Type packElementType,
                                ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInvalidPackElement(cs, packElementType, locator);
}

bool AllowInvalidPackReference::diagnose(const Solution &solution,
                                         bool asNote) const {
  InvalidPackReference failure(solution, packType, getLocator());
  return failure.diagnose(asNote);
}

AllowInvalidPackReference *
AllowInvalidPackReference::create(ConstraintSystem &cs, Type packType,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInvalidPackReference(cs, packType, locator);
}

bool AllowInvalidPackExpansion::diagnose(const Solution &solution,
                                         bool asNote) const {
  InvalidPackExpansion failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowInvalidPackExpansion *
AllowInvalidPackExpansion::create(ConstraintSystem &cs,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowInvalidPackExpansion(cs, locator);
}

bool IgnoreWhereClauseInPackIteration::diagnose(const Solution &solution,
                                                bool asNote) const {
  InvalidWhereClauseInPackIteration failure(solution, getLocator());
  return failure.diagnose(asNote);
}

IgnoreWhereClauseInPackIteration *
IgnoreWhereClauseInPackIteration::create(ConstraintSystem &cs,
                                         ConstraintLocator *locator) {
  return new (cs.getAllocator()) IgnoreWhereClauseInPackIteration(cs, locator);
}

bool CollectionElementContextualMismatch::diagnose(const Solution &solution,
                                                   bool asNote) const {
  CollectionElementContextualFailure failure(
      solution, getElements(), getFromType(), getToType(), getLocator());
  return failure.diagnose(asNote);
}

CollectionElementContextualMismatch *
CollectionElementContextualMismatch::create(ConstraintSystem &cs, Type srcType,
                                            Type dstType,
                                            ConstraintLocator *locator) {
  // It's common for a single literal element to represent types of other
  // literal elements of the same kind, let's check whether that is the case
  // here and record all of the affected positions.

  SmallVector<Expr *, 4> affected;
  {
    if (auto *elementLoc = getAsExpr(simplifyLocatorToAnchor(locator))) {
      auto *typeVar = cs.getType(elementLoc)->getAs<TypeVariableType>();
      if (typeVar && typeVar->getImpl().getAtomicLiteralKind()) {
        const auto *node =
            cs.getRepresentative(typeVar)->getImpl().getGraphNode();
        for (auto *typeVar : node->getEquivalenceClass()) {
          auto *locator = typeVar->getImpl().getLocator();
          if (auto *eltLoc = getAsExpr(simplifyLocatorToAnchor(locator)))
            affected.push_back(eltLoc);
        }
      }
    }
  }

  unsigned size = totalSizeToAlloc<Expr *>(affected.size());
  void *mem = cs.getAllocator().Allocate(
      size, alignof(CollectionElementContextualMismatch));
  return new (mem) CollectionElementContextualMismatch(cs, affected, srcType,
                                                       dstType, locator);
}

bool DefaultGenericArgument::coalesceAndDiagnose(
    const Solution &solution, ArrayRef<ConstraintFix *> fixes,
    bool asNote) const {
  llvm::SmallVector<GenericTypeParamType *, 4> missingParams{Param};

  for (auto *otherFix : fixes) {
    if (auto *fix = otherFix->getAs<DefaultGenericArgument>())
      missingParams.push_back(fix->Param);
  }

  MissingGenericArgumentsFailure failure(solution, missingParams, getLocator());
  return failure.diagnose(asNote);
}

bool DefaultGenericArgument::diagnose(const Solution &solution,
                                      bool asNote) const {
  return coalesceAndDiagnose(solution, {}, asNote);
}

DefaultGenericArgument *
DefaultGenericArgument::create(ConstraintSystem &cs, GenericTypeParamType *param,
                               ConstraintLocator *locator) {
  return new (cs.getAllocator()) DefaultGenericArgument(cs, param, locator);
}

SkipUnhandledConstructInResultBuilder *
SkipUnhandledConstructInResultBuilder::create(ConstraintSystem &cs,
                                                UnhandledNode unhandled,
                                                NominalTypeDecl *builder,
                                                ConstraintLocator *locator) {
  return new (cs.getAllocator())
    SkipUnhandledConstructInResultBuilder(cs, unhandled, builder, locator);
}

bool SkipUnhandledConstructInResultBuilder::diagnose(const Solution &solution,
                                                       bool asNote) const {
  SkipUnhandledConstructInResultBuilderFailure failure(solution, unhandled,
                                                         builder, getLocator());
  return failure.diagnose(asNote);
}

bool AllowMutatingMemberOnRValueBase::diagnose(const Solution &solution,
                                               bool asNote) const {
  MutatingMemberRefOnImmutableBase failure(solution, getMember(), getLocator());
  return failure.diagnose(asNote);
}

AllowMutatingMemberOnRValueBase *
AllowMutatingMemberOnRValueBase::create(ConstraintSystem &cs, Type baseType,
                                        ValueDecl *member, DeclNameRef name,
                                        ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowMutatingMemberOnRValueBase(cs, baseType, member, name, locator);
}

bool AllowTupleSplatForSingleParameter::diagnose(const Solution &solution,
                                                 bool asNote) const {
  InvalidTupleSplatWithSingleParameterFailure failure(solution, ParamType,
                                                      getLocator());
  return failure.diagnose(asNote);
}

bool AllowTupleSplatForSingleParameter::attempt(
    ConstraintSystem &cs, SmallVectorImpl<Param> &args, ArrayRef<Param> params,
    SmallVectorImpl<SmallVector<unsigned, 1>> &bindings,
    ConstraintLocatorBuilder locator) {
  if (params.size() != 1 || args.size() <= 1)
    return true;

  const auto &param = params.front();

  if (param.isInOut() || param.isVariadic() || param.isAutoClosure())
    return true;

  auto paramTy = param.getOldType();

  // Parameter type has to be either a tuple (with the same arity as
  // argument list), or a type variable.
  if (!(paramTy->is<TupleType>() &&
        paramTy->castTo<TupleType>()->getNumElements() == args.size()))
    return true;

  SmallVector<TupleTypeElt, 4> argElts;

  for (unsigned index : indices(args)) {
    const auto &arg = args[index];

    auto label = arg.getLabel();
    auto flags = arg.getParameterFlags();

    // In situations where there is a single labeled parameter
    // we need to form a tuple which omits the label e.g.
    //
    // func foo<T>(x: (T, T)) {}
    // foo(x: 0, 1)
    //
    // We'd want to suggest argument list to be `x: (0, 1)` instead
    // of `(x: 0, 1)` which would be incorrect.
    if (param.hasLabel() && label == param.getLabel()) {
      if (index == 0) {
        label = Identifier();
      } else {
        // If label match anything other than first argument,
        // this can't be a tuple splat.
        return true;
      }
    }

    // Tuple can't have `inout` elements.
    if (flags.isInOut())
      return true;

    argElts.push_back({arg.getPlainType(), label});
  }

  bindings[0].clear();
  bindings[0].push_back(0);

  auto newArgType = TupleType::get(argElts, cs.getASTContext());

  args.clear();
  args.push_back(AnyFunctionType::Param(newArgType, param.getLabel()));

  auto *fix = new (cs.getAllocator()) AllowTupleSplatForSingleParameter(
      cs, paramTy, cs.getConstraintLocator(locator));

  return cs.recordFix(fix);
}

bool DropThrowsAttribute::diagnose(const Solution &solution,
                                   bool asNote) const {
  ThrowingFunctionConversionFailure failure(solution, getFromType(),
                                            getToType(), getLocator());
  return failure.diagnose(asNote);
}

DropThrowsAttribute *DropThrowsAttribute::create(ConstraintSystem &cs,
                                                 FunctionType *fromType,
                                                 FunctionType *toType,
                                                 ConstraintLocator *locator) {
  return new (cs.getAllocator())
      DropThrowsAttribute(cs, fromType, toType, locator);
}

bool IgnoreThrownErrorMismatch::diagnose(const Solution &solution,
                                   bool asNote) const {
  ThrownErrorTypeConversionFailure failure(solution, getFromType(),
                                           getToType(), getLocator());
  return failure.diagnose(asNote);
}

IgnoreThrownErrorMismatch *IgnoreThrownErrorMismatch::create(ConstraintSystem &cs,
                                                 Type fromErrorType,
                                                 Type toErrorType,
                                                 ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreThrownErrorMismatch(cs, fromErrorType, toErrorType, locator);
}

bool DropAsyncAttribute::diagnose(const Solution &solution,
                                   bool asNote) const {
  AsyncFunctionConversionFailure failure(solution, getFromType(),
                                         getToType(), getLocator());
  return failure.diagnose(asNote);
}

DropAsyncAttribute *DropAsyncAttribute::create(ConstraintSystem &cs,
                                               FunctionType *fromType,
                                               FunctionType *toType,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator())
      DropAsyncAttribute(cs, fromType, toType, locator);
}

bool IgnoreContextualType::diagnose(const Solution &solution,
                                    bool asNote) const {
  ContextualFailure failure(solution, getFromType(), getToType(), getLocator());
  return failure.diagnose(asNote);
}

IgnoreContextualType *IgnoreContextualType::create(ConstraintSystem &cs,
                                                   Type resultTy,
                                                   Type specifiedTy,
                                                   ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreContextualType(cs, resultTy, specifiedTy, locator);
}

bool IgnoreAssignmentDestinationType::diagnose(const Solution &solution,
                                               bool asNote) const {
  auto &cs = getConstraintSystem();
  auto *AE = getAsExpr<AssignExpr>(getAnchor());

  assert(AE);

  // Let's check whether this is a situation of chained assignment where
  // one of the steps in the chain is an assignment to self e.g.
  // `let _ = { $0 = $0 = 42 }`. Assignment chaining results in
  // type mismatch between result of the previous assignment and the next.
  {
    llvm::SaveAndRestore<AssignExpr *> anchor(AE);

    do {
      if (TypeChecker::diagnoseSelfAssignment(AE))
        return true;
    } while ((AE = dyn_cast_or_null<AssignExpr>(cs.getParentExpr(AE))));
  }

  auto CTP = isa<SubscriptExpr>(AE->getDest()) ? CTP_SubscriptAssignSource
                                               : CTP_AssignSource;

  AssignmentTypeMismatchFailure failure(
      solution, CTP, getFromType(), getToType(),
      cs.getConstraintLocator(AE->getSrc(),
                              LocatorPathElt::ContextualType(CTP)));
  return failure.diagnose(asNote);
}

bool IgnoreAssignmentDestinationType::diagnoseForAmbiguity(
    CommonFixesArray commonFixes) const {
  auto &cs = getConstraintSystem();

  // If all of the types are the same let's try to diagnose
  // this as if there is no ambiguity.
  if (ContextualMismatch::diagnoseForAmbiguity(commonFixes))
    return true;

  auto *commonLocator = getLocator();
  auto *assignment = castToExpr<AssignExpr>(commonLocator->getAnchor());

  auto &solution = *commonFixes.front().first;
  auto *calleeLocator = solution.getCalleeLocator(
      solution.getConstraintLocator(assignment->getSrc()));
  auto overload = solution.getOverloadChoiceIfAvailable(calleeLocator);
  if (!overload)
    return false;

  auto memberName = overload->choice.getName().getBaseName();
  auto destType = solution.getType(assignment->getDest());

  auto &DE = cs.getASTContext().Diags;
  // TODO(diagnostics): It might be good to add a tailored diagnostic
  // for cases like this instead of using "contextual" one.
  DE.diagnose(assignment->getSrc()->getLoc(),
              diag::no_candidates_match_result_type,
              memberName.userFacingName(),
              solution.simplifyType(destType)->getRValueType());

  for (auto &entry : commonFixes) {
    entry.second->diagnose(*entry.first, /*asNote=*/true);
  }

  return true;
}

IgnoreAssignmentDestinationType *
IgnoreAssignmentDestinationType::create(ConstraintSystem &cs, Type sourceTy,
                                        Type destTy,
                                        ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreAssignmentDestinationType(cs, sourceTy, destTy, locator);
}

bool AllowInOutConversion::diagnose(const Solution &solution,
                                    bool asNote) const {
  InOutConversionFailure failure(solution, getFromType(), getToType(),
                                 getLocator());
  return failure.diagnose(asNote);
}

AllowInOutConversion *AllowInOutConversion::create(ConstraintSystem &cs,
                                                   Type argType, Type paramType,
                                                   ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInOutConversion(cs, argType, paramType, locator);
}

ExpandArrayIntoVarargs *
ExpandArrayIntoVarargs::attempt(ConstraintSystem &cs, Type argType,
                                Type paramType,
                                ConstraintLocatorBuilder builder) {
  auto *locator = cs.getConstraintLocator(builder);

  auto argLoc = locator->getLastElementAs<LocatorPathElt::ApplyArgToParam>();
  if (!(argLoc && argLoc->getParameterFlags().isVariadic()))
    return nullptr;

  auto elementType = argType->isArrayType();
  if (!elementType)
    return nullptr;

  ConstraintSystem::TypeMatchOptions options;
  options |= ConstraintSystem::TypeMatchFlags::TMF_ApplyingFix;
  options |= ConstraintSystem::TypeMatchFlags::TMF_GenerateConstraints;

  auto result = cs.matchTypes(elementType, paramType, ConstraintKind::Subtype,
                              options, builder);

  if (result.isFailure())
    return nullptr;

  return new (cs.getAllocator())
      ExpandArrayIntoVarargs(cs, argType, paramType, locator);
}

bool ExpandArrayIntoVarargs::diagnose(const Solution &solution,
                                      bool asNote) const {
  ExpandArrayIntoVarargsFailure failure(solution, getFromType(), getToType(),
                                        getLocator());
  return failure.diagnose(asNote);
}

bool ExplicitlyConstructRawRepresentable::diagnose(const Solution &solution,
                                                   bool asNote) const {
  MissingRawRepresentableInitFailure failure(solution, RawReprType,
                                             ExpectedType, getLocator());
  return failure.diagnose(asNote);
}

ExplicitlyConstructRawRepresentable *
ExplicitlyConstructRawRepresentable::create(ConstraintSystem &cs,
                                            Type rawReprType, Type expectedType,
                                            ConstraintLocator *locator) {
  return new (cs.getAllocator()) ExplicitlyConstructRawRepresentable(
      cs, rawReprType, expectedType, locator);
}

bool UseRawValue::diagnose(const Solution &solution, bool asNote) const {
  MissingRawValueFailure failure(solution, RawReprType, ExpectedType,
                                 getLocator());
  return failure.diagnose(asNote);
}

UseRawValue *UseRawValue::create(ConstraintSystem &cs, Type rawReprType,
                                 Type expectedType,
                                 ConstraintLocator *locator) {
  return new (cs.getAllocator())
      UseRawValue(cs, rawReprType, expectedType, locator);
}

unsigned AllowArgumentMismatch::getParamIdx() const {
  const auto *locator = getLocator();
  auto elt = locator->castLastElementTo<LocatorPathElt::ApplyArgToParam>();
  return elt.getParamIdx();
}

bool AllowArgumentMismatch::diagnose(const Solution &solution,
                                     bool asNote) const {
  ArgumentMismatchFailure failure(solution, getFromType(), getToType(),
                                  getLocator());
  return failure.diagnose(asNote);
}

AllowArgumentMismatch *
AllowArgumentMismatch::create(ConstraintSystem &cs, Type argType,
                              Type paramType, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowArgumentMismatch(cs, argType, paramType, locator);
}

bool RemoveInvalidCall::diagnose(const Solution &solution, bool asNote) const {
  ExtraneousCallFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

RemoveInvalidCall *RemoveInvalidCall::create(ConstraintSystem &cs,
                                             ConstraintLocator *locator) {
  return new (cs.getAllocator()) RemoveInvalidCall(cs, locator);
}

bool TreatEphemeralAsNonEphemeral::diagnose(const Solution &solution,
                                            bool asNote) const {
  NonEphemeralConversionFailure failure(solution, getLocator(), getFromType(),
                                        getToType(), ConversionKind,
                                        fixBehavior);
  return failure.diagnose(asNote);
}

TreatEphemeralAsNonEphemeral *TreatEphemeralAsNonEphemeral::create(
    ConstraintSystem &cs, ConstraintLocator *locator, Type srcType,
    Type dstType, ConversionRestrictionKind conversionKind,
    bool downgradeToWarning) {
  return new (cs.getAllocator()) TreatEphemeralAsNonEphemeral(
      cs, locator, srcType, dstType, conversionKind,
      downgradeToWarning ? FixBehavior::DowngradeToWarning
                         : FixBehavior::Error);
}

std::string TreatEphemeralAsNonEphemeral::getName() const {
  std::string name;
  name += "treat ephemeral as non-ephemeral for ";
  name += ::getName(ConversionKind);
  return name;
}

bool AllowSendingMismatch::diagnose(const Solution &solution,
                                    bool asNote) const {
  switch (kind) {
  case Kind::Parameter: {
    SendingOnFunctionParameterMismatchFail failure(
        solution, getFromType(), getToType(), getLocator(), fixBehavior);
    return failure.diagnose(asNote);
  }
  case Kind::Result: {
    SendingOnFunctionResultMismatchFailure failure(
        solution, getFromType(), getToType(), getLocator(), fixBehavior);
    return failure.diagnose(asNote);
  }
  }
  llvm_unreachable("Covered switch isn't covered?!");
}

AllowSendingMismatch *AllowSendingMismatch::create(ConstraintSystem &cs,
                                                   ConstraintLocator *locator,
                                                   Type srcType, Type dstType,
                                                   Kind kind) {
  auto fixBehavior = cs.getASTContext().LangOpts.isSwiftVersionAtLeast(6)
                         ? FixBehavior::Error
                         : FixBehavior::DowngradeToWarning;
  return new (cs.getAllocator())
      AllowSendingMismatch(cs, srcType, dstType, locator, kind, fixBehavior);
}

bool SpecifyBaseTypeForContextualMember::diagnose(const Solution &solution,
                                                  bool asNote) const {
  MissingContextualBaseInMemberRefFailure failure(solution, MemberName,
                                                  getLocator());
  return failure.diagnose(asNote);
}

SpecifyBaseTypeForContextualMember *SpecifyBaseTypeForContextualMember::create(
    ConstraintSystem &cs, DeclNameRef member, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      SpecifyBaseTypeForContextualMember(cs, member, locator);
}

std::string SpecifyClosureParameterType::getName() const {
  std::string name;
  llvm::raw_string_ostream OS(name);

  auto *closure = castToExpr<ClosureExpr>(getAnchor());
  auto paramLoc =
      getLocator()->castLastElementTo<LocatorPathElt::TupleElement>();

  auto *PD = closure->getParameters()->get(paramLoc.getIndex());

  OS << "specify type for parameter ";
  OS << "'" << PD->getParameterName() << "'";

  return OS.str();
}

bool SpecifyClosureParameterType::diagnose(const Solution &solution,
                                           bool asNote) const {
  UnableToInferClosureParameterType failure(solution, getLocator());
  return failure.diagnose(asNote);
}

SpecifyClosureParameterType *
SpecifyClosureParameterType::create(ConstraintSystem &cs,
                                    ConstraintLocator *locator) {
  return new (cs.getAllocator()) SpecifyClosureParameterType(cs, locator);
}

bool SpecifyClosureReturnType::diagnose(const Solution &solution,
                                        bool asNote) const {
  UnableToInferClosureReturnType failure(solution, getLocator());
  return failure.diagnose(asNote);
}

SpecifyClosureReturnType *
SpecifyClosureReturnType::create(ConstraintSystem &cs,
                                 ConstraintLocator *locator) {
  return new (cs.getAllocator()) SpecifyClosureReturnType(cs, locator);
}

bool SpecifyObjectLiteralTypeImport::diagnose(const Solution &solution,
                                              bool asNote) const {
  UnableToInferProtocolLiteralType failure(solution, getLocator());
  return failure.diagnose(asNote);
}

SpecifyObjectLiteralTypeImport *
SpecifyObjectLiteralTypeImport::create(ConstraintSystem &cs,
                                       ConstraintLocator *locator) {
  return new (cs.getAllocator()) SpecifyObjectLiteralTypeImport(cs, locator);
}

AllowNonClassTypeToConvertToAnyObject::AllowNonClassTypeToConvertToAnyObject(
    ConstraintSystem &cs, Type type, ConstraintLocator *locator)
    : ContextualMismatch(cs, FixKind::AllowNonClassTypeToConvertToAnyObject,
                         type, cs.getASTContext().getAnyObjectType(), locator) {
}

bool AllowNonClassTypeToConvertToAnyObject::diagnose(const Solution &solution,
                                                     bool asNote) const {
  auto *locator = getLocator();

  NonClassTypeToAnyObjectConversionFailure failure(solution, getFromType(),
                                                   getToType(), locator);

  return failure.diagnose(asNote);
}

AllowNonClassTypeToConvertToAnyObject *
AllowNonClassTypeToConvertToAnyObject::create(ConstraintSystem &cs, Type type,
                                              ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowNonClassTypeToConvertToAnyObject(cs, type, locator);
}


bool SpecifyPackElementType::diagnose(const Solution &solution,
                                      bool asNote) const {
  UnableToInferGenericPackElementType failure(solution, getLocator());
  return failure.diagnose(asNote);
}

SpecifyPackElementType *
SpecifyPackElementType::create(ConstraintSystem &cs,
                               ConstraintLocator *locator) {
  return new (cs.getAllocator()) SpecifyPackElementType(cs, locator);
}


bool AddQualifierToAccessTopLevelName::diagnose(const Solution &solution,
                                                bool asNote) const {
  MissingQualifierInMemberRefFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AddQualifierToAccessTopLevelName *
AddQualifierToAccessTopLevelName::create(ConstraintSystem &cs,
                                         ConstraintLocator *locator) {
  return new (cs.getAllocator()) AddQualifierToAccessTopLevelName(cs, locator);
}

bool AllowCoercionToForceCast::diagnose(const Solution &solution,
                                        bool asNote) const {
  CoercionAsForceCastFailure failure(solution, getFromType(), getToType(),
                                     getLocator());
  return failure.diagnose(asNote);
}

AllowCoercionToForceCast *
AllowCoercionToForceCast::create(ConstraintSystem &cs, Type fromType,
                                 Type toType, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowCoercionToForceCast(cs, fromType, toType, locator);
}

bool AllowKeyPathRootTypeMismatch::diagnose(const Solution &solution,
                                            bool asNote) const {
  KeyPathRootTypeMismatchFailure failure(solution, getFromType(), getToType(),
                                         getLocator());
  return failure.diagnose(asNote);
}

AllowKeyPathRootTypeMismatch *
AllowKeyPathRootTypeMismatch::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                     ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowKeyPathRootTypeMismatch(cs, lhs, rhs, locator);
}

SpecifyKeyPathRootType *
SpecifyKeyPathRootType::create(ConstraintSystem &cs,
                               ConstraintLocator *locator) {
  return new (cs.getAllocator())
      SpecifyKeyPathRootType(cs, locator);
}

bool SpecifyKeyPathRootType::diagnose(const Solution &solution,
                                      bool asNote) const {
  UnableToInferKeyPathRootFailure failure(solution, getLocator());
  
  return failure.diagnose(asNote);
}

bool UnwrapOptionalBaseKeyPathApplication::diagnose(const Solution &solution,
                                                    bool asNote) const {
  MissingOptionalUnwrapKeyPathFailure failure(solution, getFromType(),
                                              getToType(), getLocator());
  return failure.diagnose(asNote);
}

UnwrapOptionalBaseKeyPathApplication *
UnwrapOptionalBaseKeyPathApplication::attempt(ConstraintSystem &cs, Type baseTy,
                                              Type rootTy,
                                              ConstraintLocator *locator) {
  if(baseTy->hasTypeVariable() || rootTy->hasTypeVariable())
    return nullptr;

  if (!isExpr<SubscriptExpr>(locator->getAnchor()))
    return nullptr;
  
  // Only diagnose this if base is an optional type and we only have a
  // single level of optionality so we can safely suggest unwrapping.
  auto nonOptionalTy = baseTy->getOptionalObjectType();
  if (!nonOptionalTy || nonOptionalTy->getOptionalObjectType())
    return nullptr;

  auto result =
      cs.matchTypes(nonOptionalTy, rootTy, ConstraintKind::Subtype,
                    ConstraintSystem::TypeMatchFlags::TMF_ApplyingFix, locator);
  if (result.isFailure())
    return nullptr;

  return new (cs.getAllocator())
      UnwrapOptionalBaseKeyPathApplication(cs, baseTy, rootTy, locator);
}

bool SpecifyLabelToAssociateTrailingClosure::diagnose(const Solution &solution,
                                                      bool asNote) const {
  TrailingClosureRequiresExplicitLabel failure(solution, getLocator());
  return failure.diagnose(asNote);
}

SpecifyLabelToAssociateTrailingClosure *
SpecifyLabelToAssociateTrailingClosure::create(ConstraintSystem &cs,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator())
      SpecifyLabelToAssociateTrailingClosure(cs, locator);
}

bool AllowKeyPathWithoutComponents::diagnose(const Solution &solution,
                                             bool asNote) const {
  InvalidEmptyKeyPathFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowKeyPathWithoutComponents *
AllowKeyPathWithoutComponents::create(ConstraintSystem &cs,
                                      ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowKeyPathWithoutComponents(cs, locator);
}

bool IgnoreInvalidResultBuilderBody::diagnose(const Solution &solution,
                                              bool asNote) const {
  return true; // Already diagnosed by `matchResultBuilder`.
}

IgnoreInvalidResultBuilderBody *
IgnoreInvalidResultBuilderBody::create(ConstraintSystem &cs,
                                       ConstraintLocator *locator) {
  return new (cs.getAllocator()) IgnoreInvalidResultBuilderBody(cs, locator);
}

bool IgnoreInvalidASTNode::diagnose(const Solution &solution,
                                    bool asNote) const {
  return true; // Already diagnosed by the producer of ErrorExpr or ErrorType.
}

IgnoreInvalidASTNode *IgnoreInvalidASTNode::create(ConstraintSystem &cs,
                                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) IgnoreInvalidASTNode(cs, locator);
}

bool IgnoreInvalidPatternInExpr::diagnose(const Solution &solution,
                                          bool asNote) const {
  InvalidPatternInExprFailure failure(solution, P, getLocator());
  return failure.diagnose(asNote);
}

IgnoreInvalidPatternInExpr *
IgnoreInvalidPatternInExpr::create(ConstraintSystem &cs, Pattern *pattern,
                                   ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreInvalidPatternInExpr(cs, pattern, locator);
}

bool SpecifyContextualTypeForNil::diagnose(const Solution &solution,
                                           bool asNote) const {
  MissingContextualTypeForNil failure(solution, getLocator());
  return failure.diagnose(asNote);
}

SpecifyContextualTypeForNil *
SpecifyContextualTypeForNil::create(ConstraintSystem &cs,
                                    ConstraintLocator *locator) {
  return new (cs.getAllocator()) SpecifyContextualTypeForNil(cs, locator);
}

bool SpecifyTypeForPlaceholder::diagnose(const Solution &solution,
                                           bool asNote) const {
  CouldNotInferPlaceholderType failure(solution, getLocator());
  return failure.diagnose(asNote);
}

SpecifyTypeForPlaceholder *
SpecifyTypeForPlaceholder::create(ConstraintSystem &cs,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator()) SpecifyTypeForPlaceholder(cs, locator);
}

bool AllowRefToInvalidDecl::diagnose(const Solution &solution,
                                     bool asNote) const {
  ReferenceToInvalidDeclaration failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowRefToInvalidDecl *
AllowRefToInvalidDecl::create(ConstraintSystem &cs,
                              ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowRefToInvalidDecl(cs, locator);
}

bool IgnoreResultBuilderWithReturnStmts::diagnose(const Solution &solution,
                                                  bool asNote) const {
  InvalidReturnInResultBuilderBody failure(solution, BuilderType, getLocator());
  return failure.diagnose(asNote);
}

IgnoreResultBuilderWithReturnStmts *
IgnoreResultBuilderWithReturnStmts::create(ConstraintSystem &cs, Type builderTy,
                                           ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreResultBuilderWithReturnStmts(cs, builderTy, locator);
}

bool IgnoreUnresolvedPatternVar::diagnose(const Solution &solution,
                                          bool asNote) const {
  // An unresolved AnyPatternDecl means there was some issue in the match
  // that means we couldn't infer the pattern. We don't have a diagnostic to
  // emit here, the failure should be diagnosed by the fix for expression.
  return false;
}

IgnoreUnresolvedPatternVar *
IgnoreUnresolvedPatternVar::create(ConstraintSystem &cs, Pattern *pattern,
                                   ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreUnresolvedPatternVar(cs, pattern, locator);
}

bool SpecifyBaseTypeForOptionalUnresolvedMember::diagnose(
    const Solution &solution, bool asNote) const {
  MemberMissingExplicitBaseTypeFailure failure(solution, MemberName,
                                               getLocator());
  return failure.diagnose(asNote);
}

SpecifyBaseTypeForOptionalUnresolvedMember *
SpecifyBaseTypeForOptionalUnresolvedMember::attempt(
    ConstraintSystem &cs, ConstraintKind kind, Type baseTy,
    DeclNameRef memberName, FunctionRefKind functionRefKind,
    MemberLookupResult result, ConstraintLocator *locator) {

  if (kind != ConstraintKind::UnresolvedValueMember)
    return nullptr;

  // None or only one viable candidate, there is no ambiguity.
  if (result.ViableCandidates.size() <= 1)
    return nullptr;

  // Only diagnose those situations for static members.
  if (!baseTy->is<MetatypeType>())
    return nullptr;

  // Don't diagnose for function members e.g. Foo? = .none(0).
  if (functionRefKind != FunctionRefKind::Unapplied)
    return nullptr;

  Type underlyingBaseType = baseTy->getMetatypeInstanceType();
  if (!underlyingBaseType->getNominalOrBoundGenericNominal())
    return nullptr;

  if (!underlyingBaseType->getOptionalObjectType())
    return nullptr;

  auto unwrappedType = underlyingBaseType->lookThroughAllOptionalTypes();
  bool allOptionalBaseCandidates = true;
  auto filterViableCandidates =
      [&](SmallVector<OverloadChoice, 4> &candidates,
          SmallVector<OverloadChoice, 4> &viableCandidates,
          bool &allOptionalBase) {
        for (OverloadChoice choice : candidates) {
          if (!choice.isDecl())
            continue;

          auto memberDecl = choice.getDecl();
          if (isa<FuncDecl>(memberDecl))
            continue;
          if (memberDecl->isInstanceMember())
            continue;

          // Disable this warning for ambiguities related to a
          // static member lookup in generic context because it's
          // possible to declare a member with the same name on
          // a concrete type and in an extension of a protocol
          // that type conforms to e.g.:
          //
          // struct S : P { static var test: S { ... }
          //
          // extension P where Self == S { static var test: { ... } }
          //
          // And use that in an optional context e.g. passing `.test`
          // to a parameter of expecting `S?`.
          if (auto *extension =
                  dyn_cast<ExtensionDecl>(memberDecl->getDeclContext())) {
            if (extension->getSelfProtocolDecl()) {
              allOptionalBase = false;
              break;
            }
          }

          allOptionalBase &= bool(choice.getBaseType()
                                      ->getMetatypeInstanceType()
                                      ->getOptionalObjectType());

          if (auto EED = dyn_cast<EnumElementDecl>(memberDecl)) {
            if (!EED->hasAssociatedValues())
              viableCandidates.push_back(choice);
          } else if (auto VD = dyn_cast<VarDecl>(memberDecl)) {
            if (unwrappedType->hasTypeVariable() ||
                VD->getInterfaceType()->isEqual(unwrappedType))
              viableCandidates.push_back(choice);
          }
        }
      };

  SmallVector<OverloadChoice, 4> viableCandidates;
  filterViableCandidates(result.ViableCandidates, viableCandidates,
                         allOptionalBaseCandidates);

  // Also none or only one viable candidate after filtering candidates, there is
  // no ambiguity.
  if (viableCandidates.size() <= 1)
    return nullptr;

  // Right now, name lookup only unwraps a single layer of optionality, which
  // for cases where base type is a multi-optional type e.g. Foo?? it only
  // finds optional base candidates. To produce the correct warning we perform
  // an extra lookup on unwrapped type.
  if (!allOptionalBaseCandidates)
    return new (cs.getAllocator())
        SpecifyBaseTypeForOptionalUnresolvedMember(cs, memberName, locator);

  MemberLookupResult unwrappedResult =
      cs.performMemberLookup(kind, memberName, MetatypeType::get(unwrappedType),
                             functionRefKind, locator,
                             /*includeInaccessibleMembers*/ false);
  SmallVector<OverloadChoice, 4> unwrappedViableCandidates;
  filterViableCandidates(unwrappedResult.ViableCandidates,
                         unwrappedViableCandidates, allOptionalBaseCandidates);
  if (unwrappedViableCandidates.empty())
    return nullptr;

  return new (cs.getAllocator())
      SpecifyBaseTypeForOptionalUnresolvedMember(cs, memberName, locator);
}

AllowCheckedCastCoercibleOptionalType *
AllowCheckedCastCoercibleOptionalType::create(ConstraintSystem &cs,
                                              Type fromType, Type toType,
                                              CheckedCastKind kind,
                                              ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowCheckedCastCoercibleOptionalType(
      cs, fromType, toType, kind, locator);
}

bool AllowCheckedCastCoercibleOptionalType::diagnose(const Solution &solution,
                                                     bool asNote) const {
  CoercibleOptionalCheckedCastFailure failure(
      solution, getFromType(), getToType(), CastKind, getLocator());
  return failure.diagnose(asNote);
}

AllowNoopCheckedCast *AllowNoopCheckedCast::create(ConstraintSystem &cs,
                                                   Type fromType, Type toType,
                                                   CheckedCastKind kind,
                                                   ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowNoopCheckedCast(cs, fromType, toType, kind, locator);
}

bool AllowNoopCheckedCast::diagnose(const Solution &solution,
                                    bool asNote) const {
  NoopCheckedCast warning(solution, getFromType(), getToType(), CastKind,
                          getLocator());
  return warning.diagnose(asNote);
}

AllowNoopExistentialToCFTypeCheckedCast *
AllowNoopExistentialToCFTypeCheckedCast::attempt(ConstraintSystem &cs,
                                                 Type fromType, Type toType,
                                                 CheckedCastKind kind,
                                                 ConstraintLocator *locator) {
  if (!isExpr<IsExpr>(locator->getAnchor()))
    return nullptr;

  if (!fromType->isExistentialType())
    return nullptr;

  const auto *cls = toType->getAs<ClassType>();
  if (!(cls && cls->getDecl()->getForeignClassKind() ==
                   ClassDecl::ForeignKind::CFType))
    return nullptr;

  return new (cs.getAllocator()) AllowNoopExistentialToCFTypeCheckedCast(
      cs, fromType, toType, kind, locator);
}

bool AllowNoopExistentialToCFTypeCheckedCast::diagnose(const Solution &solution,
                                                       bool asNote) const {
  NoopExistentialToCFTypeCheckedCast warning(
      solution, getFromType(), getToType(), CastKind, getLocator());
  return warning.diagnose(asNote);
}

// Although function types maybe compile-time convertible because
// compiler can emit thunks at SIL to handle the conversion when
// required, only conversions that are supported by the runtime are
// when types are trivially equal or non-throwing from type is equal
// to throwing to type without throwing clause conversions are not
// possible at runtime.
bool AllowUnsupportedRuntimeCheckedCast::runtimeSupportedFunctionTypeCast(
    FunctionType *fnFromType, FunctionType *fnToType) {
  if (fnFromType->isEqual(fnToType)) {
    return true;
  } else if (!fnFromType->isThrowing() && fnToType->isThrowing()) {
    return fnFromType->isEqual(
        fnToType->getWithoutThrowing()->castTo<FunctionType>());
  }
  // Runtime cannot perform such conversion.
  return false;
}

AllowUnsupportedRuntimeCheckedCast *
AllowUnsupportedRuntimeCheckedCast::attempt(ConstraintSystem &cs, Type fromType,
                                            Type toType, CheckedCastKind kind,
                                            ConstraintLocator *locator) {
  auto fnFromType = fromType->getAs<FunctionType>();
  auto fnToType = toType->getAs<FunctionType>();

  if (!(fnFromType && fnToType))
    return nullptr;

  if (runtimeSupportedFunctionTypeCast(fnFromType, fnToType))
    return nullptr;

  return new (cs.getAllocator())
      AllowUnsupportedRuntimeCheckedCast(cs, fromType, toType, kind, locator);
}

bool AllowUnsupportedRuntimeCheckedCast::diagnose(const Solution &solution,
                                                 bool asNote) const {
  UnsupportedRuntimeCheckedCastFailure failure(
      solution, getFromType(), getToType(), CastKind, getLocator());
  return failure.diagnose(asNote);
}

AllowCheckedCastToUnrelated *
AllowCheckedCastToUnrelated::attempt(ConstraintSystem &cs, Type fromType,
                                     Type toType, CheckedCastKind kind,
                                     ConstraintLocator *locator) {
  // Explicit optional-to-optional casts always succeed because a nil
  // value of any optional type can be cast to any other optional type.
  if (fromType->getOptionalObjectType() && toType->getOptionalObjectType()) {
    return nullptr;
  }
  return new (cs.getAllocator())
      AllowCheckedCastToUnrelated(cs, fromType, toType, kind, locator);
}

bool AllowCheckedCastToUnrelated::diagnose(const Solution &solution,
                                           bool asNote) const {
  CheckedCastToUnrelatedFailure warning(solution, getFromType(), getToType(),
                                        CastKind, getLocator());
  return warning.diagnose(asNote);
}

bool AllowInvalidStaticMemberRefOnProtocolMetatype::diagnose(
    const Solution &solution, bool asNote) const {
  InvalidMemberRefOnProtocolMetatype failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowInvalidStaticMemberRefOnProtocolMetatype *
AllowInvalidStaticMemberRefOnProtocolMetatype::create(
    ConstraintSystem &cs, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInvalidStaticMemberRefOnProtocolMetatype(cs, locator);
}

bool AllowNonOptionalWeak::diagnose(const Solution &solution,
                                    bool asNote) const {
  InvalidWeakAttributeUse failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowNonOptionalWeak *AllowNonOptionalWeak::create(ConstraintSystem &cs,
                                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowNonOptionalWeak(cs, locator);
}

AllowTupleLabelMismatch *
AllowTupleLabelMismatch::create(ConstraintSystem &cs, Type fromType,
                                Type toType, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowTupleLabelMismatch(cs, fromType, toType, locator);
}

bool AllowTupleLabelMismatch::diagnose(const Solution &solution,
                                       bool asNote) const {
  TupleLabelMismatchWarning warning(solution, getFromType(), getToType(),
                                    getLocator());
  return warning.diagnose(asNote);
}

AllowAssociatedValueMismatch *
AllowAssociatedValueMismatch::create(ConstraintSystem &cs, Type fromType,
                                     Type toType, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowAssociatedValueMismatch(cs, fromType, toType, locator);
}

bool AllowAssociatedValueMismatch::diagnose(const Solution &solution,
                                            bool asNote) const {
  AssociatedValueMismatchFailure failure(solution, getFromType(), getToType(),
                                         getLocator());
  return failure.diagnose(asNote);
}

bool AllowSwiftToCPointerConversion::diagnose(const Solution &solution,
                                              bool asNote) const {
  SwiftToCPointerConversionInInvalidContext failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowSwiftToCPointerConversion *
AllowSwiftToCPointerConversion::create(ConstraintSystem &cs,
                                       ConstraintLocator *locator) {
  return new (cs.getAllocator()) AllowSwiftToCPointerConversion(cs, locator);
}

bool IgnoreDefaultExprTypeMismatch::diagnose(const Solution &solution,
                                             bool asNote) const {
  DefaultExprTypeMismatch failure(solution, getFromType(), getToType(),
                                  getLocator());
  return failure.diagnose(asNote);
}

IgnoreDefaultExprTypeMismatch *
IgnoreDefaultExprTypeMismatch::create(ConstraintSystem &cs, Type argType,
                                      Type paramType,
                                      ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreDefaultExprTypeMismatch(cs, argType, paramType, locator);
}

bool RenameConflictingPatternVariables::diagnose(const Solution &solution,
                                                 bool asNote) const {
  ConflictingPatternVariables failure(solution, ExpectedType,
                                      getConflictingVars(), getLocator());
  return failure.diagnose(asNote);
}

RenameConflictingPatternVariables *
RenameConflictingPatternVariables::create(ConstraintSystem &cs, Type expectedTy,
                                          ArrayRef<VarDecl *> conflicts,
                                          ConstraintLocator *locator) {
  unsigned size = totalSizeToAlloc<VarDecl *>(conflicts.size());
  void *mem = cs.getAllocator().Allocate(
      size, alignof(RenameConflictingPatternVariables));
  return new (mem)
      RenameConflictingPatternVariables(cs, expectedTy, conflicts, locator);
}

bool MacroMissingPound::diagnose(const Solution &solution,
                                                 bool asNote) const {
  AddMissingMacroPound failure(solution, macro, getLocator());
  return failure.diagnose(asNote);
}

MacroMissingPound *
MacroMissingPound::create(ConstraintSystem &cs, MacroDecl *macro,
                          ConstraintLocator *locator) {
  return new (cs.getAllocator()) MacroMissingPound(cs, macro, locator);
}

bool AllowGlobalActorMismatch::diagnose(const Solution &solution,
                                        bool asNote) const {
  GlobalActorFunctionMismatchFailure failure(solution, getFromType(),
                                             getToType(), getLocator());
  return failure.diagnose(asNote);
}

AllowGlobalActorMismatch *
AllowGlobalActorMismatch::create(ConstraintSystem &cs, Type fromType,
                                 Type toType, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowGlobalActorMismatch(cs, fromType, toType, locator);
}

bool DestructureTupleToMatchPackExpansionParameter::diagnose(
    const Solution &solution, bool asNote) const {
  DestructureTupleToUseWithPackExpansionParameter failure(solution, ParamShape,
                                                          getLocator());
  return failure.diagnose(asNote);
}

DestructureTupleToMatchPackExpansionParameter *
DestructureTupleToMatchPackExpansionParameter::create(
    ConstraintSystem &cs, PackType *paramShapeTy, ConstraintLocator *locator) {
  return new (cs.getAllocator())
      DestructureTupleToMatchPackExpansionParameter(cs, paramShapeTy, locator);
}

bool AllowValueExpansionWithoutPackReferences::diagnose(
    const Solution &solution, bool asNote) const {
  ValuePackExpansionWithoutPackReferences failure(solution, getLocator());
  return failure.diagnose(asNote);
}

AllowValueExpansionWithoutPackReferences *
AllowValueExpansionWithoutPackReferences::create(ConstraintSystem &cs,
                                                 ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowValueExpansionWithoutPackReferences(cs, locator);
}

bool IgnoreMissingEachKeyword::diagnose(const Solution &solution,
                                        bool asNote) const {
  MissingEachForValuePackReference failure(solution, ValuePackType,
                                           getLocator());
  return failure.diagnose(asNote);
}

IgnoreMissingEachKeyword *
IgnoreMissingEachKeyword::create(ConstraintSystem &cs, Type valuePackTy,
                                 ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreMissingEachKeyword(cs, valuePackTy, locator);
}

bool AllowInvalidMemberReferenceInInitAccessor::diagnose(
    const Solution &solution, bool asNote) const {
  InvalidMemberReferenceWithinInitAccessor failure(solution, MemberName,
                                                   getLocator());
  return failure.diagnose(asNote);
}

AllowInvalidMemberReferenceInInitAccessor *
AllowInvalidMemberReferenceInInitAccessor::create(ConstraintSystem &cs,
                                                  DeclNameRef memberName,
                                                  ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowInvalidMemberReferenceInInitAccessor(cs, memberName, locator);
}

bool AllowConcreteTypeSpecialization::diagnose(const Solution &solution,
                                               bool asNote) const {
  ConcreteTypeSpecialization failure(solution, ConcreteType, getLocator());
  return failure.diagnose(asNote);
}

AllowConcreteTypeSpecialization *
AllowConcreteTypeSpecialization::create(ConstraintSystem &cs, Type concreteTy,
                                        ConstraintLocator *locator) {
  return new (cs.getAllocator())
      AllowConcreteTypeSpecialization(cs, concreteTy, locator);
}

bool IgnoreOutOfPlaceThenStmt::diagnose(const Solution &solution,
                                        bool asNote) const {
  OutOfPlaceThenStmtFailure failure(solution, getLocator());
  return failure.diagnose(asNote);
}

IgnoreOutOfPlaceThenStmt *
IgnoreOutOfPlaceThenStmt::create(ConstraintSystem &cs,
                                 ConstraintLocator *locator) {
  return new (cs.getAllocator()) IgnoreOutOfPlaceThenStmt(cs, locator);
}

bool IgnoreGenericSpecializationArityMismatch::diagnose(
    const Solution &solution, bool asNote) const {
  InvalidTypeSpecializationArity failure(solution, D, NumParams, NumArgs,
                                         HasParameterPack, getLocator());
  return failure.diagnose(asNote);
}

IgnoreGenericSpecializationArityMismatch *
IgnoreGenericSpecializationArityMismatch::create(ConstraintSystem &cs,
                                                 ValueDecl *decl,
                                                 unsigned numParams,
                                                 unsigned numArgs,
                                                 bool hasParameterPack,
                                                 ConstraintLocator *locator) {
  return new (cs.getAllocator()) IgnoreGenericSpecializationArityMismatch(
      cs, decl, numParams, numArgs, hasParameterPack, locator);
}

bool IgnoreKeyPathSubscriptIndexMismatch::diagnose(const Solution &solution,
                                                   bool asNote) const {
  InvalidTypeAsKeyPathSubscriptIndex failure(solution, ArgType, getLocator());
  return failure.diagnose(asNote);
}

IgnoreKeyPathSubscriptIndexMismatch *
IgnoreKeyPathSubscriptIndexMismatch::create(ConstraintSystem &cs, Type argType,
                                            ConstraintLocator *locator) {
  return new (cs.getAllocator())
      IgnoreKeyPathSubscriptIndexMismatch(cs, argType, locator);
}