File: CSBindings.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 (2685 lines) | stat: -rw-r--r-- 97,473 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
//===--- CSBindings.cpp - Constraint Solver -------------------------------===//
//
// 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 selection of bindings for type variables.
//
//===----------------------------------------------------------------------===//
#include "swift/Sema/CSBindings.h"
#include "TypeChecker.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/Sema/ConstraintGraph.h"
#include "swift/Sema/ConstraintSystem.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/raw_ostream.h"
#include <tuple>

using namespace swift;
using namespace constraints;
using namespace inference;

static std::optional<Type> checkTypeOfBinding(TypeVariableType *typeVar,
                                              Type type);

bool BindingSet::forClosureResult() const {
  return Info.TypeVar->getImpl().isClosureResultType();
}

bool BindingSet::forGenericParameter() const {
  return bool(Info.TypeVar->getImpl().getGenericParameter());
}

bool BindingSet::canBeNil() const {
  auto &ctx = CS.getASTContext();
  return Literals.count(
      ctx.getProtocol(KnownProtocolKind::ExpressibleByNilLiteral));
}

bool BindingSet::isDirectHole() const {
  // Direct holes are only allowed in "diagnostic mode".
  if (!CS.shouldAttemptFixes())
    return false;

  return Bindings.empty() && getNumViableLiteralBindings() == 0 &&
         Defaults.empty() && Info.TypeVar->getImpl().canBindToHole();
}

bool PotentialBindings::isGenericParameter() const {
  auto *locator = TypeVar->getImpl().getLocator();
  return locator && locator->isLastElement<LocatorPathElt::GenericParameter>();
}

bool PotentialBinding::isViableForJoin() const {
  return Kind == AllowedBindingKind::Supertypes &&
         !BindingType->hasLValueType() &&
         !BindingType->hasUnresolvedType() &&
         !BindingType->hasTypeVariable() &&
         !BindingType->hasPlaceholder() &&
         !BindingType->hasUnboundGenericType() &&
         !hasDefaultedLiteralProtocol() &&
         !isDefaultableBinding();
}

bool BindingSet::isDelayed() const {
  if (auto *locator = TypeVar->getImpl().getLocator()) {
    if (locator->isLastElement<LocatorPathElt::MemberRefBase>()) {
      // If first binding is a "fallback" to a protocol type,
      // it means that this type variable should be delayed
      // until it either gains more contextual information, or
      // there are no other type variables to attempt to make
      // forward progress.
      if (Bindings.empty())
        return true;


      if (Bindings[0].BindingType->is<ProtocolType>())
        return true;
    }

    // Since force unwrap preserves l-valueness, resulting
    // type variable has to be delayed until either l-value
    // binding becomes available or there are no other
    // variables to attempt.
    if (locator->directlyAt<ForceValueExpr>() &&
        TypeVar->getImpl().canBindToLValue()) {
      return llvm::none_of(Bindings, [](const PotentialBinding &binding) {
        return binding.BindingType->is<LValueType>();
      });
    }
  }

  // Delay key path literal type binding until there is at least
  // one contextual binding (or default is promoted into a binding).
  if (TypeVar->getImpl().isKeyPathType() && !Defaults.empty())
    return true;

  if (isHole()) {
    auto *locator = TypeVar->getImpl().getLocator();
    assert(locator && "a hole without locator?");

    // Delay resolution of the code completion expression until
    // the very end to give it a chance to be bound to some
    // contextual type even if it's a hole.
    if (locator->directlyAt<CodeCompletionExpr>())
      return true;

    // Delay resolution of the `nil` literal to a hole until
    // the very end to give it a change to be bound to some
    // other type, just like code completion expression which
    // relies solely on contextual information.
    if (locator->directlyAt<NilLiteralExpr>())
      return true;

    // When inferring the type of a variable in a pattern, delay its resolution
    // so that we resolve type variables inside the expression as placeholders
    // instead of marking the type of the variable itself as a placeholder. This
    // allows us to produce more specific errors because the type variable in
    // the expression that introduced the placeholder might be diagnosable using
    // fixForHole.
    if (locator->isLastElement<LocatorPathElt::PatternDecl>()) {
      return true;
    }

    // It's possible that type of member couldn't be determined,
    // and if so it would be beneficial to bind member to a hole
    // early to propagate that information down to arguments,
    // result type of a call that references such a member.
    //
    // Note: This is done here instead of during binding inference,
    // because it's possible that variable is marked as a "hole"
    // (or that status is propagated to it) after constraints
    // mentioned below are recorded.
    return llvm::any_of(Info.DelayedBy, [&](Constraint *constraint) {
      switch (constraint->getKind()) {
      case ConstraintKind::ApplicableFunction:
      case ConstraintKind::DynamicCallableApplicableFunction:
      case ConstraintKind::BindOverload: {
        return !ConstraintSystem::typeVarOccursInType(
            TypeVar, CS.simplifyType(constraint->getSecondType()));
      }

      default:
        return true;
      }
    });
  }

  return !Info.DelayedBy.empty();
}

bool BindingSet::involvesTypeVariables() const {
  // This type variable always depends on a pack expansion variable
  // which should be inferred first if possible.
  if (TypeVar->getImpl().getGenericParameter() &&
      TypeVar->getImpl().canBindToPack())
    return true;

  // This is effectively O(1) right now since bindings are re-computed
  // on each step of the solver, but once bindings are computed
  // incrementally it becomes more important to double-check that
  // any adjacent type variables found previously are still unresolved.
  return llvm::any_of(AdjacentVars, [](TypeVariableType *typeVar) {
    return !typeVar->getImpl().getFixedType(/*record=*/nullptr);
  });
}

bool BindingSet::isPotentiallyIncomplete() const {
  // Generic parameters are always potentially incomplete.
  if (Info.isGenericParameter())
    return true;

  // Key path literal type is incomplete until there is a
  // contextual type or key path is resolved enough to infer
  // capability and promote default into a binding.
  if (TypeVar->getImpl().isKeyPathType())
    return !Defaults.empty();

  // If current type variable is associated with a code completion token
  // it's possible that it doesn't have enough contextual information
  // to be resolved to anything so let's delay considering it until everything
  // else is resolved.
  if (Info.AssociatedCodeCompletionToken)
    return true;

  auto *locator = TypeVar->getImpl().getLocator();
  if (!locator)
    return false;

  if (locator->isLastElement<LocatorPathElt::MemberRefBase>() &&
      !Bindings.empty()) {
    // If the base of the unresolved member reference like `.foo`
    // couldn't be resolved we'd want to bind it to a hole at the
    // very last moment possible, just like generic parameters.
    if (isHole())
      return true;

    auto &binding = Bindings.front();
    // If base type of a member chain is inferred to be a protocol type,
    // let's consider this binding set to be potentially incomplete since
    // that's done as a last resort effort at resolving first member.
    if (auto *constraint = binding.getSource()) {
      if (binding.BindingType->is<ProtocolType>() &&
          constraint->getKind() == ConstraintKind::ConformsTo)
        return true;
    }
  }

  if (locator->isLastElement<LocatorPathElt::UnresolvedMemberChainResult>()) {
    // If subtyping is allowed and this is a result of an implicit member chain,
    // let's delay binding it to an optional until its object type resolved too or
    // it has been determined that there is no possibility to resolve it. Otherwise
    // we might end up missing solutions since it's allowed to implicitly unwrap
    // base type of the chain but it can't be done early - type variable
    // representing chain's result type has a different l-valueness comparing
    // to generic parameter of the optional.
    if (llvm::any_of(Bindings, [&](const PotentialBinding &binding) {
          if (binding.Kind != AllowedBindingKind::Subtypes)
            return false;

          auto objectType = binding.BindingType->getOptionalObjectType();
          return objectType && objectType->isTypeVariableOrMember();
        }))
      return true;
  }

  if (isHole()) {
    // Delay resolution of the code completion expression until
    // the very end to give it a chance to be bound to some
    // contextual type even if it's a hole.
    if (locator->directlyAt<CodeCompletionExpr>())
      return true;

    // Delay resolution of the `nil` literal to a hole until
    // the very end to give it a change to be bound to some
    // other type, just like code completion expression which
    // relies solely on contextual information.
    if (locator->directlyAt<NilLiteralExpr>())
      return true;
  }

  // If there is a `bind param` constraint associated with
  // current type variable, result should be aware of that
  // fact. Binding set might be incomplete until
  // this constraint is resolved, because we currently don't
  // look-through constraints expect to `subtype` to try and
  // find related bindings.
  // This only affects type variable that appears one the
  // right-hand side of the `bind param` constraint and
  // represents result type of the closure body, because
  // left-hand side gets types from overload choices.
  if (llvm::any_of(
          Info.EquivalentTo,
          [&](const std::pair<TypeVariableType *, Constraint *> &equivalence) {
            auto *constraint = equivalence.second;
            return constraint->getKind() == ConstraintKind::BindParam &&
                   constraint->getSecondType()->isEqual(TypeVar);
          }))
    return true;

  return false;
}

void BindingSet::inferTransitiveProtocolRequirements(
    llvm::SmallDenseMap<TypeVariableType *, BindingSet> &inferredBindings) {
  if (TransitiveProtocols)
    return;

  llvm::SmallVector<std::pair<TypeVariableType *, TypeVariableType *>, 4>
      workList;
  llvm::SmallPtrSet<TypeVariableType *, 4> visitedRelations;

  llvm::SmallDenseMap<TypeVariableType *, SmallPtrSet<Constraint *, 4>, 4>
      protocols;

  auto addToWorkList = [&](TypeVariableType *parent,
                           TypeVariableType *typeVar) {
    if (visitedRelations.insert(typeVar).second)
      workList.push_back({parent, typeVar});
  };

  auto propagateProtocolsTo =
      [&protocols](TypeVariableType *dstVar,
                   const ArrayRef<Constraint *> &direct,
                   const SmallPtrSetImpl<Constraint *> &transitive) {
        auto &destination = protocols[dstVar];

        if (direct.size() > 0)
          destination.insert(direct.begin(), direct.end());

        if (transitive.size() > 0)
          destination.insert(transitive.begin(), transitive.end());
      };

  addToWorkList(nullptr, TypeVar);

  do {
    auto *currentVar = workList.back().second;

    auto cachedBindings = inferredBindings.find(currentVar);
    if (cachedBindings == inferredBindings.end()) {
      workList.pop_back();
      continue;
    }

    auto &bindings = cachedBindings->getSecond();

    // If current variable already has transitive protocol
    // conformances inferred, there is no need to look deeper
    // into subtype/equivalence chain.
    if (bindings.TransitiveProtocols) {
      TypeVariableType *parent = nullptr;
      std::tie(parent, currentVar) = workList.pop_back_val();
      assert(parent);
      propagateProtocolsTo(parent, bindings.getConformanceRequirements(),
                           *bindings.TransitiveProtocols);
      continue;
    }

    for (const auto &entry : bindings.Info.SubtypeOf)
      addToWorkList(currentVar, entry.first);

    // If current type variable is part of an equivalence
    // class, make it a "representative" and let it infer
    // supertypes and direct protocol requirements from
    // other members and their equivalence classes.
    llvm::SmallSetVector<TypeVariableType *, 4> equivalenceClass;
    {
      SmallVector<TypeVariableType *, 4> workList;
      workList.push_back(currentVar);

      do {
        auto *typeVar = workList.pop_back_val();

        if (!equivalenceClass.insert(typeVar))
          continue;

        auto bindingSet = inferredBindings.find(typeVar);
        if (bindingSet == inferredBindings.end())
          continue;

        auto &equivalences = bindingSet->getSecond().Info.EquivalentTo;
        for (const auto &eqVar : equivalences) {
          workList.push_back(eqVar.first);
        }
      } while (!workList.empty());
    }

    for (const auto &memberVar : equivalenceClass) {
      if (memberVar == currentVar)
        continue;

      auto eqBindings = inferredBindings.find(memberVar);
      if (eqBindings == inferredBindings.end())
        continue;

      const auto &bindings = eqBindings->getSecond();

      llvm::SmallPtrSet<Constraint *, 2> placeholder;
      // Add any direct protocols from members of the
      // equivalence class, so they could be propagated
      // to all of the members.
      propagateProtocolsTo(currentVar, bindings.getConformanceRequirements(),
                           placeholder);

      // Since type variables are equal, current type variable
      // becomes a subtype to any supertype found in the current
      // equivalence  class.
      for (const auto &eqEntry : bindings.Info.SubtypeOf)
        addToWorkList(currentVar, eqEntry.first);
    }

    // More subtype/equivalences relations have been added.
    if (workList.back().second != currentVar)
      continue;

    TypeVariableType *parent = nullptr;
    std::tie(parent, currentVar) = workList.pop_back_val();

    // At all of the protocols associated with current type variable
    // are transitive to its parent, propagate them down the subtype/equivalence
    // chain.
    if (parent) {
      propagateProtocolsTo(parent, bindings.getConformanceRequirements(),
                           protocols[currentVar]);
    }

    auto &inferredProtocols = protocols[currentVar];

    llvm::SmallPtrSet<Constraint *, 4> protocolsForEquivalence;

    // Equivalence class should contain both:
    // - direct protocol requirements of the current type
    //   variable;
    // - all of the transitive protocols inferred through
    //   the members of the equivalence class.
    {
      auto directRequirements = bindings.getConformanceRequirements();
      protocolsForEquivalence.insert(directRequirements.begin(),
                                     directRequirements.end());

      protocolsForEquivalence.insert(inferredProtocols.begin(),
                                     inferredProtocols.end());
    }

    // Propagate inferred protocols to all of the members of the
    // equivalence class.
    for (const auto &equivalence : bindings.Info.EquivalentTo) {
      auto eqBindings = inferredBindings.find(equivalence.first);
      if (eqBindings != inferredBindings.end()) {
        auto &bindings = eqBindings->getSecond();
        bindings.TransitiveProtocols.emplace(protocolsForEquivalence.begin(),
                                             protocolsForEquivalence.end());
      }
    }

    // Update the bindings associated with current type variable,
    // to avoid repeating this inference process.
    bindings.TransitiveProtocols.emplace(inferredProtocols.begin(),
                                         inferredProtocols.end());
  } while (!workList.empty());
}

void BindingSet::inferTransitiveBindings(
    const llvm::SmallDenseMap<TypeVariableType *, BindingSet>
        &inferredBindings) {
  using BindingKind = AllowedBindingKind;

  // If the current type variable represents a key path root type
  // let's try to transitively infer its type through bindings of
  // a key path type.
  if (TypeVar->getImpl().isKeyPathRoot()) {
    auto *locator = TypeVar->getImpl().getLocator();
    if (auto *keyPathTy =
            CS.getType(locator->getAnchor())->getAs<TypeVariableType>()) {
      auto keyPathBindings = inferredBindings.find(keyPathTy);
      if (keyPathBindings != inferredBindings.end()) {
        auto &bindings = keyPathBindings->getSecond();

        for (auto &binding : bindings.Bindings) {
          auto bindingTy = binding.BindingType->lookThroughAllOptionalTypes();

          Type inferredRootTy;
          if (isKnownKeyPathType(bindingTy)) {
            // AnyKeyPath doesn't have a root type.
            if (bindingTy->isAnyKeyPath())
              continue;

            auto *BGT = bindingTy->castTo<BoundGenericType>();
            inferredRootTy = BGT->getGenericArgs()[0];
          } else if (auto *fnType = bindingTy->getAs<FunctionType>()) {
            if (fnType->getNumParams() == 1)
              inferredRootTy = fnType->getParams()[0].getParameterType();
          }

          if (inferredRootTy) {
            // If contextual root is not yet resolved, let's try to see if
            // there are any bindings in its set. The bindings could be
            // transitively used because conversions between generic arguments
            // are not allowed.
            if (auto *contextualRootVar = inferredRootTy->getAs<TypeVariableType>()) {
              auto rootBindings = inferredBindings.find(contextualRootVar);
              if (rootBindings != inferredBindings.end()) {
                auto &bindings = rootBindings->getSecond();

                // Don't infer if root is not yet fully resolved.
                if (bindings.isDelayed())
                  continue;

                // Copy the bindings over to the root.
                for (const auto &binding : bindings.Bindings)
                  addBinding(binding, /*isTransitive=*/true);

                // Make a note that the key path root is transitively adjacent
                // to contextual root type variable and all of its variables.
                // This is important for ranking.
                AdjacentVars.insert(contextualRootVar);
                AdjacentVars.insert(bindings.AdjacentVars.begin(),
                                    bindings.AdjacentVars.end());
              }
            } else {
              addBinding(
                  binding.withSameSource(inferredRootTy, BindingKind::Exact),
                  /*isTransitive=*/true);
            }
          }
        }
      }
    }
  }

  for (const auto &entry : Info.SupertypeOf) {
    auto relatedBindings = inferredBindings.find(entry.first);
    if (relatedBindings == inferredBindings.end())
      continue;

    auto &bindings = relatedBindings->getSecond();

    // FIXME: This is a workaround necessary because solver doesn't filter
    // bindings based on protocol requirements placed on a type variable.
    //
    // Forward propagate (subtype -> supertype) only literal conformance
    // requirements since that helps solver to infer more types at
    // parameter positions.
    //
    // \code
    // func foo<T: ExpressibleByStringLiteral>(_: String, _: T) -> T {
    //   fatalError()
    // }
    //
    // func bar(_: Any?) {}
    //
    // func test() {
    //   bar(foo("", ""))
    // }
    // \endcode
    //
    // If one of the literal arguments doesn't propagate its
    // `ExpressibleByStringLiteral` conformance, we'd end up picking
    // `T` with only one type `Any?` which is incorrect.
    for (const auto &literal : bindings.Literals)
      addLiteralRequirement(literal.second.getSource());

    // Infer transitive defaults.
    for (const auto &def : bindings.Defaults) {
      if (def.getSecond()->getKind() == ConstraintKind::FallbackType)
        continue;

      addDefault(def.second);
    }

    // TODO: We shouldn't need this in the future.
    if (entry.second->getKind() != ConstraintKind::Subtype)
      continue;

    for (auto &binding : bindings.Bindings) {
      // We need the binding kind for the potential binding to
      // either be Exact or Supertypes in order for it to make sense
      // to add Supertype bindings based on the relationship between
      // our type variables.
      if (binding.Kind != BindingKind::Exact &&
          binding.Kind != BindingKind::Supertypes)
        continue;

      auto type = binding.BindingType;

      if (type->isPlaceholder())
        continue;

      if (ConstraintSystem::typeVarOccursInType(TypeVar, type))
        continue;

      addBinding(binding.withSameSource(type, BindingKind::Supertypes),
                 /*isTransitive=*/true);
    }
  }
}

static Type getKeyPathType(ASTContext &ctx, KeyPathCapability capability,
                           Type rootType, Type valueType) {
  KeyPathMutability mutability;
  bool isSendable;

  std::tie(mutability, isSendable) = capability;

  Type keyPathTy;
  switch (mutability) {
  case KeyPathMutability::ReadOnly:
    keyPathTy = BoundGenericType::get(ctx.getKeyPathDecl(), /*parent=*/Type(),
                                      {rootType, valueType});
    break;

  case KeyPathMutability::Writable:
    keyPathTy = BoundGenericType::get(ctx.getWritableKeyPathDecl(),
                                      /*parent=*/Type(), {rootType, valueType});
    break;

  case KeyPathMutability::ReferenceWritable:
    keyPathTy = BoundGenericType::get(ctx.getReferenceWritableKeyPathDecl(),
                                      /*parent=*/Type(), {rootType, valueType});
    break;
  }

  if (isSendable &&
      ctx.LangOpts.hasFeature(Feature::InferSendableFromCaptures)) {
    auto *sendable = ctx.getProtocol(KnownProtocolKind::Sendable);
    keyPathTy = ProtocolCompositionType::get(
        ctx, {keyPathTy, sendable->getDeclaredInterfaceType()},
        /*inverses=*/{}, /*hasExplicitAnyObject=*/false);
    return ExistentialType::get(keyPathTy);
  }

  return keyPathTy;
}

bool BindingSet::finalize(
    llvm::SmallDenseMap<TypeVariableType *, BindingSet> &inferredBindings) {
  inferTransitiveBindings(inferredBindings);

  determineLiteralCoverage();

  if (auto *locator = TypeVar->getImpl().getLocator()) {
    if (locator->isLastElement<LocatorPathElt::MemberRefBase>()) {
      // If this is a base of an unresolved member chain, as a last
      // resort effort let's infer base to be a protocol type based
      // on contextual conformance requirements.
      //
      // This allows us to find solutions in cases like this:
      //
      // \code
      // func foo<T: P>(_: T) {}
      // foo(.bar) <- `.bar` should be a static member of `P`.
      // \endcode
      if (!hasViableBindings()) {
        inferTransitiveProtocolRequirements(inferredBindings);

        if (TransitiveProtocols.has_value()) {
          for (auto *constraint : *TransitiveProtocols) {
            Type protocolTy = constraint->getSecondType();

            // Compiler-known marker protocols cannot be extended with members,
            // so do not consider them.
            if (auto p = protocolTy->getAs<ProtocolType>()) {
              if (ProtocolDecl *decl = p->getDecl())
                if (decl->getKnownProtocolKind() && decl->isMarkerProtocol())
                  continue;
            }

            addBinding({protocolTy, AllowedBindingKind::Exact, constraint},
                       /*isTransitive=*/false);
          }
        }
      }
    }

    if (TypeVar->getImpl().isKeyPathType()) {
      auto &ctx = CS.getASTContext();

      auto *keyPathLoc = TypeVar->getImpl().getLocator();
      auto *keyPath = castToExpr<KeyPathExpr>(keyPathLoc->getAnchor());

      bool isValid;
      std::optional<KeyPathCapability> capability;

      std::tie(isValid, capability) = CS.inferKeyPathLiteralCapability(TypeVar);

      // Key path literal is not yet sufficiently resolved, this binding
      // set is not viable.
      if (isValid && !capability)
        return false;

      // If the key path is sufficiently resolved we can add inferred binding
      // to the set.
      SmallSetVector<PotentialBinding, 4> updatedBindings;
      for (const auto &binding : Bindings) {
        auto bindingTy = binding.BindingType->lookThroughAllOptionalTypes();

        assert(isKnownKeyPathType(bindingTy) || bindingTy->is<FunctionType>());

        // Functions don't have capability so we can simply add them.
        if (auto *fnType = bindingTy->getAs<FunctionType>()) {
          auto extInfo = fnType->getExtInfo();

          bool isKeyPathSendable = capability && capability->second;
          if (!isKeyPathSendable && extInfo.isSendable()) {
            fnType = FunctionType::get(fnType->getParams(), fnType->getResult(),
                                       extInfo.withSendable(false));
          }

          updatedBindings.insert(binding.withType(fnType));
        }
      }

      // Note that even though key path literal maybe be invalid it's
      // still the best course of action to use contextual function type
      // bindings because they allow to propagate type information from
      // the key path into the context, so key path bindings are addded
      // only if there is absolutely no other choice.
      if (updatedBindings.empty()) {
        auto rootTy = CS.getKeyPathRootType(keyPath);

        // A valid key path literal.
        if (capability) {
          // Note that the binding is formed using root & value
          // type variables produced during constraint generation
          // because at this point root is already known (otherwise
          // inference wouldn't been able to determine key path's
          // capability) and we always want to infer value from
          // the key path and match it to a contextual type to produce
          // better diagnostics.
          auto keyPathTy = getKeyPathType(ctx, *capability, rootTy,
                                          CS.getKeyPathValueType(keyPath));
          updatedBindings.insert(
              {keyPathTy, AllowedBindingKind::Exact, keyPathLoc});
        } else if (CS.shouldAttemptFixes()) {
          auto fixedRootTy = CS.getFixedType(rootTy);
          // If key path is structurally correct and has a resolved root
          // type, let's promote the fallback type into a binding because
          // root would have been inferred from explicit type already and
          // it's benefitial for diagnostics to assign a non-placeholder
          // type to key path literal to propagate root/value to the context.
          if (!keyPath->hasSingleInvalidComponent() &&
              (keyPath->getParsedRoot() ||
               (fixedRootTy && !fixedRootTy->isTypeVariableOrMember()))) {
            auto fallback = llvm::find_if(Defaults, [](const auto &entry) {
              return entry.second->getKind() == ConstraintKind::FallbackType;
            });
            assert(fallback != Defaults.end());
            updatedBindings.insert(
                {fallback->first, AllowedBindingKind::Exact, fallback->second});
          } else {
            updatedBindings.insert(PotentialBinding::forHole(
                TypeVar, CS.getConstraintLocator(
                             keyPath, ConstraintLocator::FallbackType)));
          }
        }
      }

      Bindings = std::move(updatedBindings);
      Defaults.clear();

      return true;
    }

    if (CS.shouldAttemptFixes() &&
        locator->isLastElement<LocatorPathElt::UnresolvedMemberChainResult>()) {
      // Let's see whether this chain is valid, if it isn't then to avoid
      // diagnosing the same issue multiple different ways, let's infer
      // result of the chain to be a hole.
      auto *resultExpr =
          castToExpr<UnresolvedMemberChainResultExpr>(locator->getAnchor());
      auto *baseLocator = CS.getConstraintLocator(
          resultExpr->getChainBase(), ConstraintLocator::UnresolvedMember);

      if (CS.hasFixFor(
              baseLocator,
              FixKind::AllowInvalidStaticMemberRefOnProtocolMetatype)) {
        CS.recordPotentialHole(TypeVar);
        // Clear all of the previously collected bindings which are inferred
        // from inside of a member chain.
        Bindings.remove_if([](const PotentialBinding &binding) {
          return binding.Kind == AllowedBindingKind::Supertypes;
        });
      }
    }
  }

  return true;
}

void BindingSet::addBinding(PotentialBinding binding, bool isTransitive) {
  if (Bindings.count(binding))
    return;

  if (!isViable(binding, isTransitive))
    return;

  SmallPtrSet<TypeVariableType *, 4> referencedTypeVars;
  binding.BindingType->getTypeVariables(referencedTypeVars);

  // If type variable is not allowed to bind to `lvalue`,
  // let's check if type of potential binding has any
  // type variables, which are allowed to bind to `lvalue`,
  // and postpone such type from consideration.
  //
  // This check is done here and not in `checkTypeOfBinding`
  // because the l-valueness of the variable might change during
  // solving and that would not be reflected in the graph.
  if (!TypeVar->getImpl().canBindToLValue()) {
    for (auto *typeVar : referencedTypeVars) {
      if (typeVar->getImpl().canBindToLValue())
        return;
    }
  }

  // Since Double and CGFloat are effectively the same type due to an
  // implicit conversion between them, always prefer Double over CGFloat
  // when possible.
  //
  // Note: This optimization can't be performed for closure parameters
  //       because their type could be converted only at the point of
  //       use in the closure body.
  if (!TypeVar->getImpl().isClosureParameterType()) {
    auto type = binding.BindingType;

    if (type->isCGFloat() &&
        llvm::any_of(Bindings, [](const PotentialBinding &binding) {
          return binding.BindingType->isDouble();
        }))
      return;

    if (type->isDouble()) {
      auto inferredCGFloat =
          llvm::find_if(Bindings, [](const PotentialBinding &binding) {
            return binding.BindingType->isCGFloat();
          });

      if (inferredCGFloat != Bindings.end()) {
        Bindings.erase(inferredCGFloat);
        Bindings.insert(inferredCGFloat->withType(type));
        return;
      }
    }
  }

  // If this is a non-defaulted supertype binding,
  // check whether we can combine it with another
  // supertype binding by computing the 'join' of the types.
  if (binding.isViableForJoin()) {
    auto isAcceptableJoin = [](Type type) {
      return !type->isAny() && (!type->getOptionalObjectType() ||
                                !type->getOptionalObjectType()->isAny());
    };

    SmallVector<PotentialBinding, 4> joined;
    for (auto existingBinding = Bindings.begin();
         existingBinding != Bindings.end();) {
      if (existingBinding->isViableForJoin()) {
        auto join =
            Type::join(existingBinding->BindingType, binding.BindingType);

        if (join && isAcceptableJoin(*join)) {
          // Result of the join has to use new binding because it refers
          // to the constraint that triggered the join that replaced the
          // existing binding.
          joined.push_back(binding.withType(*join));
          // Remove existing binding from the set.
          // It has to be re-introduced later, since its type has been changed.
          existingBinding = Bindings.erase(existingBinding);
          continue;
        }
      }

      ++existingBinding;
    }

    for (const auto &binding : joined)
      (void)Bindings.insert(binding);

    // If new binding has been joined with at least one of existing
    // bindings, there is no reason to include it into the set.
    if (!joined.empty())
      return;
  }

  for (auto *adjacentVar : referencedTypeVars)
    AdjacentVars.insert(adjacentVar);

  (void)Bindings.insert(std::move(binding));
}

void BindingSet::determineLiteralCoverage() {
  if (Literals.empty())
    return;

  bool allowsNil = canBeNil();

  for (auto &entry : Literals) {
    auto &literal = entry.second;

    if (!literal.viableAsBinding())
      continue;

    for (auto binding = Bindings.begin(); binding != Bindings.end();
         ++binding) {
      bool isCovered = false;
      Type adjustedTy;

      std::tie(isCovered, adjustedTy) =
          literal.isCoveredBy(*binding, allowsNil, CS);

      if (!isCovered)
        continue;

      literal.setCoveredBy(binding->getSource());

      if (adjustedTy) {
        Bindings.erase(binding);
        Bindings.insert(binding->withType(adjustedTy));
      }

      break;
    }
  }
}

void BindingSet::addLiteralRequirement(Constraint *constraint) {
  auto isDirectRequirement = [&](Constraint *constraint) -> bool {
    if (auto *typeVar = constraint->getFirstType()->getAs<TypeVariableType>()) {
      auto *repr = CS.getRepresentative(typeVar);
      return repr == TypeVar;
    }

    return false;
  };

  auto *protocol = constraint->getProtocol();

  // Let's try to coalesce integer and floating point literal protocols
  // if they appear together because the only possible default type that
  // could satisfy both requirements is `Double`.
  {
    if (protocol->isSpecificProtocol(
            KnownProtocolKind::ExpressibleByIntegerLiteral)) {
      auto *floatLiteral = CS.getASTContext().getProtocol(
          KnownProtocolKind::ExpressibleByFloatLiteral);
      if (Literals.count(floatLiteral))
        return;
    }

    if (protocol->isSpecificProtocol(
            KnownProtocolKind::ExpressibleByFloatLiteral)) {
      auto *intLiteral = CS.getASTContext().getProtocol(
          KnownProtocolKind::ExpressibleByIntegerLiteral);
      Literals.erase(intLiteral);
    }
  }

  if (Literals.count(protocol) > 0)
    return;

  bool isDirect = isDirectRequirement(constraint);

  // Coverage is not applicable to `ExpressibleByNilLiteral` since it
  // doesn't have a default type.
  if (protocol->isSpecificProtocol(
          KnownProtocolKind::ExpressibleByNilLiteral)) {
    Literals.insert(
        {protocol, LiteralRequirement(constraint,
                                      /*DefaultType=*/Type(), isDirect)});
    return;
  }

  // Check whether any of the existing bindings covers this literal
  // protocol.
  LiteralRequirement literal(
      constraint, TypeChecker::getDefaultType(protocol, CS.DC), isDirect);

  Literals.insert({protocol, std::move(literal)});
}

BindingSet::BindingScore BindingSet::formBindingScore(const BindingSet &b) {
  // If there are no bindings available but this type
  // variable represents a closure - let's consider it
  // as having a single non-default binding - that would
  // be a type inferred based on context.
  // It's considered to be non-default for purposes of
  // ranking because we'd like to prioritize resolving
  // closures to gain more information from their bodies.
  unsigned numBindings = b.Bindings.size() + b.getNumViableLiteralBindings();
  auto numNonDefaultableBindings = numBindings > 0 ? numBindings
                                   : b.TypeVar->getImpl().isClosureType() ? 1
                                                                          : 0;

  return std::make_tuple(b.isHole(), numNonDefaultableBindings == 0,
                         b.isDelayed(), b.isSubtypeOfExistentialType(),
                         b.involvesTypeVariables(),
                         static_cast<unsigned char>(b.getLiteralForScore()),
                         -numNonDefaultableBindings);
}

std::optional<BindingSet> ConstraintSystem::determineBestBindings(
    llvm::function_ref<void(const BindingSet &)> onCandidate) {
  // Look for potential type variable bindings.
  std::optional<BindingSet> bestBindings;
  llvm::SmallDenseMap<TypeVariableType *, BindingSet> cache;

  // First, let's collect all of the possible bindings.
  for (auto *typeVar : getTypeVariables()) {
    if (!typeVar->getImpl().hasRepresentativeOrFixed()) {
      cache.insert({typeVar, getBindingsFor(typeVar, /*finalize=*/false)});
    }
  }

  // Determine whether given type variable with its set of bindings is
  // viable to be attempted on the next step of the solver. If type variable
  // has no "direct" bindings of any kind e.g. direct bindings to concrete
  // types, default types from "defaultable" constraints or literal
  // conformances, such type variable is not viable to be evaluated to be
  // attempted next.
  auto isViableForRanking = [this](const BindingSet &bindings) -> bool {
    auto *typeVar = bindings.getTypeVariable();

    // Key path root type variable is always viable because it can be
    // transitively inferred from key path type during binding set
    // finalization.
    if (typeVar->getImpl().isKeyPathRoot())
      return true;

    // Type variable representing a base of unresolved member chain should
    // always be considered viable for ranking since it's allow to infer
    // types from transitive protocol requirements.
    if (auto *locator = typeVar->getImpl().getLocator()) {
      if (locator->isLastElement<LocatorPathElt::MemberRefBase>())
        return true;
    }

    // If type variable is marked as a potential hole there is always going
    // to be at least one binding available for it.
    if (shouldAttemptFixes() && typeVar->getImpl().canBindToHole())
      return true;

    return bool(bindings);
  };

  // Now let's see if we could infer something for related type
  // variables based on other bindings.
  for (auto *typeVar : getTypeVariables()) {
    auto cachedBindings = cache.find(typeVar);
    if (cachedBindings == cache.end())
      continue;

    auto &bindings = cachedBindings->getSecond();
    // Before attempting to infer transitive bindings let's check
    // whether there are any viable "direct" bindings associated with
    // current type variable, if there are none - it means that this type
    // variable could only be used to transitively infer bindings for
    // other type variables and can't participate in ranking.
    //
    // Viable bindings include - any types inferred from constraints
    // associated with given type variable, any default constraints,
    // or any conformance requirements to literal protocols with can
    // produce a default type.
    bool isViable = isViableForRanking(bindings);

    if (!bindings.finalize(cache))
      continue;

    if (!bindings || !isViable)
      continue;

    onCandidate(bindings);

    // If these are the first bindings, or they are better than what
    // we saw before, use them instead.
    if (!bestBindings || bindings < *bestBindings)
      bestBindings.emplace(bindings);
  }

  return bestBindings;
}

/// Find the set of type variables that are inferable from the given type.
///
/// \param type The type to search.
/// \param typeVars Collects the type variables that are inferable from the
/// given type. This set is not cleared, so that multiple types can be explored
/// and introduce their results into the same set.
static void
findInferableTypeVars(Type type,
                      SmallPtrSetImpl<TypeVariableType *> &typeVars) {
  type = type->getCanonicalType();
  if (!type->hasTypeVariable())
    return;

  class Walker : public TypeWalker {
    SmallPtrSetImpl<TypeVariableType *> &typeVars;

  public:
    explicit Walker(SmallPtrSetImpl<TypeVariableType *> &typeVars)
        : typeVars(typeVars) {}

    Action walkToTypePre(Type ty) override {
      if (ty->is<DependentMemberType>())
        return Action::SkipNode;

      if (auto typeVar = ty->getAs<TypeVariableType>())
        typeVars.insert(typeVar);
      return Action::Continue;
    }
  };

  type.walk(Walker(typeVars));
}

void PotentialBindings::addDefault(Constraint *constraint) {
  Defaults.insert(constraint);
}

void BindingSet::addDefault(Constraint *constraint) {
  auto defaultTy = constraint->getSecondType();
  Defaults.insert({defaultTy->getCanonicalType(), constraint});
}

bool LiteralRequirement::isCoveredBy(Type type, ConstraintSystem &CS) const {
  auto coversDefaultType = [](Type type, Type defaultType) -> bool {
    if (!defaultType->hasUnboundGenericType())
      return type->isEqual(defaultType);

    // For generic literal types, check whether we already have a
    // specialization of this generic within our list.
    // FIXME: This assumes that, e.g., the default literal
    // int/float/char/string types are never generic.
    auto nominal = defaultType->getAnyNominal();
    if (!nominal)
      return false;

    // FIXME: Check parents?
    return nominal == type->getAnyNominal();
  };

  if (hasDefaultType() && coversDefaultType(type, getDefaultType()))
    return true;

  return bool(CS.lookupConformance(type, getProtocol()));
}

std::pair<bool, Type>
LiteralRequirement::isCoveredBy(const PotentialBinding &binding, bool canBeNil,
                                ConstraintSystem &CS) const {
  auto type = binding.BindingType;
  switch (binding.Kind) {
  case AllowedBindingKind::Exact:
    type = binding.BindingType;
    break;

  case AllowedBindingKind::Subtypes:
  case AllowedBindingKind::Supertypes:
    type = binding.BindingType->getRValueType();
    break;
  }

  bool requiresUnwrap = false;
  do {
    // Conformance check on type variable would always return true,
    // but type variable can't cover anything until it's bound.
    if (type->isTypeVariableOrMember() || type->isPlaceholder())
      return std::make_pair(false, Type());

    if (isCoveredBy(type, CS)) {
      return std::make_pair(true, requiresUnwrap ? type : binding.BindingType);
    }

    // Can't unwrap optionals if there is `ExpressibleByNilLiteral`
    // conformance requirement placed on the type variable.
    if (canBeNil)
      return std::make_pair(false, Type());

    // If this literal protocol is not a direct requirement it
    // would not be possible to change optionality while inferring
    // bindings for a supertype, so this hack doesn't apply.
    if (!isDirectRequirement())
      return std::make_pair(false, Type());

    // If we're allowed to bind to subtypes, look through optionals.
    // FIXME: This is really crappy special case of computing a reasonable
    // result based on the given constraints.
    if (binding.Kind == AllowedBindingKind::Subtypes) {
      if (auto objTy = type->getOptionalObjectType()) {
        requiresUnwrap = true;
        type = objTy;
        continue;
      }
    }

    return std::make_pair(false, Type());
  } while (true);
}

void PotentialBindings::addPotentialBinding(PotentialBinding binding) {
  assert(!binding.BindingType->is<ErrorType>());

  // If the type variable can't bind to an lvalue, make sure the
  // type we pick isn't an lvalue.
  if (!TypeVar->getImpl().canBindToLValue() &&
      binding.BindingType->hasLValueType()) {
    binding = binding.withType(binding.BindingType->getRValueType());
  }

  Bindings.push_back(std::move(binding));
}

void PotentialBindings::addLiteral(Constraint *constraint) {
  Literals.insert(constraint);
}

bool BindingSet::isViable(PotentialBinding &binding, bool isTransitive) {
  // Prevent against checking against the same opened nominal type
  // over and over again. Doing so means redundant work in the best
  // case. In the worst case, we'll produce lots of duplicate solutions
  // for this constraint system, which is problematic for overload
  // resolution.
  auto type = binding.BindingType;

  if (isTransitive && !checkTypeOfBinding(TypeVar, type))
    return false;

  auto *NTD = type->getAnyNominal();
  if (!NTD)
    return true;

  for (auto existing = Bindings.begin(); existing != Bindings.end();
       ++existing) {
    auto existingType = existing->BindingType;

    auto *existingNTD = existingType->getAnyNominal();
    if (!existingNTD || NTD != existingNTD)
      continue;

    // If new type has a type variable it shouldn't
    // be considered  viable.
    if (type->hasTypeVariable())
      return false;

    // If new type doesn't have any type variables,
    // but existing binding does, let's replace existing
    // binding with new one.
    if (existingType->hasTypeVariable()) {
      // First, let's remove all of the adjacent type
      // variables associated with this binding.
      {
        SmallPtrSet<TypeVariableType *, 4> referencedVars;
        existingType->getTypeVariables(referencedVars);
        for (auto *var : referencedVars)
          AdjacentVars.erase(var);
      }

      // And now let's remove the binding itself.
      Bindings.erase(existing);
      break;
    }
  }

  return true;
}

bool BindingSet::favoredOverDisjunction(Constraint *disjunction) const {
  if (isHole())
    return false;

  if (llvm::any_of(Bindings, [&](const PotentialBinding &binding) {
        if (binding.Kind == AllowedBindingKind::Supertypes)
          return false;

        auto type = binding.BindingType;

        if (CS.shouldAttemptFixes())
          return false;

        if (type->isAnyHashable() || type->isDouble() || type->isCGFloat())
          return false;

        {
          PointerTypeKind pointerKind;
          if (type->getAnyPointerElementType(pointerKind)) {
            switch (pointerKind) {
            case PTK_UnsafeRawPointer:
            case PTK_UnsafeMutableRawPointer:
              return false;

            default:
              break;
            }
          }
        }

        return type->is<StructType>() || type->is<EnumType>() ||
               type->is<BuiltinType>();
      })) {
    // Result type of subscript could be l-value so we can't bind it early.
    if (!TypeVar->getImpl().isSubscriptResultType() &&
        llvm::none_of(Info.DelayedBy, [](const Constraint *constraint) {
          return constraint->getKind() == ConstraintKind::Disjunction ||
                 constraint->getKind() == ConstraintKind::ValueMember;
        }))
      return true;
  }

  if (isDelayed())
    return false;

  // If this bindings are for a closure and there are no holes,
  // it shouldn't matter whether it there are any type variables
  // or not because e.g. parameter type can have type variables,
  // but we still want to resolve closure body early (instead of
  // attempting any disjunction) to gain additional contextual
  // information.
  if (TypeVar->getImpl().isClosureType()) {
    auto boundType = disjunction->getNestedConstraints()[0]->getFirstType();
    // If disjunction is attempting to bind a type variable, let's
    // favor closure because it would add additional context, otherwise
    // if it's something like a collection (where it has to pick
    // between a conversion and bridging conversion) or concrete
    // type let's prefer the disjunction.
    //
    // We are looking through optionals here because it could be
    // a situation where disjunction is formed to match optionals
    // either as deep equality or optional-to-optional conversion.
    // Such type variables might be connected to closure as well
    // e.g. when result type is optional, so it makes sense to
    // open closure before attempting such disjunction.
    return boundType->lookThroughAllOptionalTypes()->is<TypeVariableType>();
  }

  // If this is a collection literal type, it's preferrable to bind it
  // early (unless it's delayed) to connect all of its elements even
  // if it doesn't have any bindings.
  if (TypeVar->getImpl().isCollectionLiteralType())
    return !involvesTypeVariables();

  // Don't prioritize type variables that don't have any direct bindings.
  if (Bindings.empty())
    return false;

  // Always prefer key path type if it has bindings and is not delayed
  // because that means that it was possible to infer its capability.
  if (TypeVar->getImpl().isKeyPathType())
    return true;

  return !involvesTypeVariables();
}

bool BindingSet::favoredOverConjunction(Constraint *conjunction) const {
  if (CS.shouldAttemptFixes() && isHole()) {
    if (forClosureResult() || forGenericParameter())
      return false;
  }

  auto *locator = conjunction->getLocator();
  if (locator->directlyAt<ClosureExpr>()) {
    auto *closure = castToExpr<ClosureExpr>(locator->getAnchor());

    if (auto transform = CS.getAppliedResultBuilderTransform(closure)) {
      // Conjunctions that represent closures with result builder transformed
      // bodies could be attempted right after their resolution if they meet
      // all of the following criteria:
      //
      // - Builder type doesn't have any unresolved generic parameters;
      // - Closure doesn't have any parameters;
      // - The contextual result type is either concrete or opaque type.
      auto contextualType = transform->contextualType;
      if (!(contextualType && contextualType->is<FunctionType>()))
        return true;

      auto *contextualFnType =
          CS.simplifyType(contextualType)->castTo<FunctionType>();
      {
        auto resultType = contextualFnType->getResult();
        if (resultType->hasTypeVariable()) {
          auto *typeVar = resultType->getAs<TypeVariableType>();
          // If contextual result type is represented by an opaque type,
          // it's a strong indication that body is self-contained, otherwise
          // closure might rely on external types flowing into the body for
          // disambiguation of `build{Partial}Block` or `buildFinalResult`
          // calls.
          if (!(typeVar && typeVar->getImpl().isOpaqueType()))
            return true;
        }
      }

      // If some of the closure parameters are unresolved, the conjunction
      // has to be delayed to give them a chance to be inferred.
      if (llvm::any_of(contextualFnType->getParams(), [](const auto &param) {
            return param.getPlainType()->hasTypeVariable();
          }))
        return true;

      // Check whether conjunction has any unresolved type variables
      // besides the variable that represents the closure.
      //
      // Conjunction could refer to declarations from outer context
      // (i.e. a variable declared in the outer closure) or generic
      // parameters of the builder type), if any of such references
      // are not yet inferred the conjunction has to be delayed.
      auto *closureType = CS.getType(closure)->castTo<TypeVariableType>();
      return llvm::any_of(
          conjunction->getTypeVariables(), [&](TypeVariableType *typeVar) {
            return !(typeVar == closureType || CS.getFixedType(typeVar));
          });
    }
  }

  // If key path capability is not yet determined it cannot be favored
  // over a conjunction because:
  // 1. There could be no other bindings and that would mean that
  //    key path would be selected even though it's not yet ready.
  // 2. A conjunction could be the source of type context for the key path.
  if (TypeVar->getImpl().isKeyPathType() && isDelayed())
    return false;

  return true;
}

BindingSet ConstraintSystem::getBindingsFor(TypeVariableType *typeVar,
                                            bool finalize) {
  assert(typeVar->getImpl().getRepresentative(nullptr) == typeVar &&
         "not a representative");
  assert(!typeVar->getImpl().getFixedType(nullptr) && "has a fixed type");

  BindingSet bindings{CG[typeVar].getCurrentBindings()};

  if (finalize) {
    llvm::SmallDenseMap<TypeVariableType *, BindingSet> cache;
    bindings.finalize(cache);
  }

  return bindings;
}

/// Check whether the given type can be used as a binding for the given
/// type variable.
///
/// \returns the type to bind to, if the binding is okay.
static std::optional<Type> checkTypeOfBinding(TypeVariableType *typeVar,
                                              Type type) {
  // If the type references the type variable, don't permit the binding.
  if (type->hasTypeVariable()) {
    SmallPtrSet<TypeVariableType *, 4> referencedTypeVars;
    type->getTypeVariables(referencedTypeVars);
    if (referencedTypeVars.count(typeVar))
      return std::nullopt;
  }

  {
    auto objType = type->getWithoutSpecifierType();

    // If the type is a type variable itself, don't permit the binding.
    if (objType->is<TypeVariableType>())
      return std::nullopt;

    // Don't bind to a dependent member type, even if it's currently
    // wrapped in any number of optionals, because binding producer
    // might unwrap and try to attempt it directly later.
    if (objType->lookThroughAllOptionalTypes()->is<DependentMemberType>())
      return std::nullopt;
  }

  // Okay, allow the binding (with the simplified type).
  return type;
}

std::optional<PotentialBinding>
PotentialBindings::inferFromRelational(Constraint *constraint) {
  assert(constraint->getClassification() ==
             ConstraintClassification::Relational &&
         "only relational constraints handled here");

  auto first = CS.simplifyType(constraint->getFirstType());
  auto second = CS.simplifyType(constraint->getSecondType());

  if (first->is<TypeVariableType>() && first->isEqual(second))
    return std::nullopt;

  Type type;
  AllowedBindingKind kind;
  if (first->getAs<TypeVariableType>() == TypeVar) {
    // Upper bound for this type variable.
    type = second;
    kind = AllowedBindingKind::Subtypes;
  } else if (second->getAs<TypeVariableType>() == TypeVar) {
    // Lower bound for this type variable.
    type = first;
    kind = AllowedBindingKind::Supertypes;
  } else {
    // If the left-hand side of a relational constraint is a
    // type variable representing a closure type, let's delay
    // attempting any bindings related to any type variables
    // on the other side since it could only be either a closure
    // parameter or a result type, and we can't get a full set
    // of bindings for them until closure's body is opened.
    if (auto *typeVar = first->getAs<TypeVariableType>()) {
      if (typeVar->getImpl().isClosureType()) {
        DelayedBy.push_back(constraint);
        return std::nullopt;
      }
    }

    // Check whether both this type and another type variable are
    // inferable.
    SmallPtrSet<TypeVariableType *, 4> typeVars;
    findInferableTypeVars(first, typeVars);
    findInferableTypeVars(second, typeVars);

    if (typeVars.erase(TypeVar)) {
      for (auto *typeVar : typeVars)
        AdjacentVars.insert({typeVar, constraint});
    }

    return std::nullopt;
  }

  // Do not attempt to bind to ErrorType.
  if (type->hasError())
    return std::nullopt;

  if (TypeVar->getImpl().isKeyPathType()) {
    auto objectTy = type->lookThroughAllOptionalTypes();

    // If contextual type is an existential with a superclass
    // constraint, let's try to infer a key path type from it.
    if (kind == AllowedBindingKind::Subtypes) {
      if (type->isExistentialType()) {
        auto layout = type->getExistentialLayout();
        if (auto superclass = layout.explicitSuperclass) {
          if (isKnownKeyPathType(superclass)) {
            type = superclass;
            objectTy = superclass;
          }
        }
      }
    }

    if (!(isKnownKeyPathType(objectTy) || objectTy->is<AnyFunctionType>()))
      return std::nullopt;
  }

  if (TypeVar->getImpl().isKeyPathSubscriptIndex()) {
    // Key path subscript index can only be a r-value non-optional
    // type that is a subtype of a known KeyPath type.
    type = type->getRValueType()->lookThroughAllOptionalTypes();

    // If argument to a key path subscript is an existential,
    // we can erase it to superclass (if any) here and solver
    // will perform the opening if supertype turns out to be
    // a valid key path type of its subtype.
    if (kind == AllowedBindingKind::Supertypes) {
      if (type->isExistentialType()) {
        auto layout = type->getExistentialLayout();
        if (auto superclass = layout.explicitSuperclass) {
          type = superclass;
        } else if (!CS.shouldAttemptFixes()) {
          return std::nullopt;
        }
      }
    }
  }

  if (auto *locator = TypeVar->getImpl().getLocator()) {
    // Don't allow a protocol type to get propagated from the base to the result
    // type of a chain, Result should always be a concrete type which conforms
    // to the protocol inferred for the base.
    if (constraint->getKind() == ConstraintKind::UnresolvedMemberChainBase &&
        kind == AllowedBindingKind::Subtypes && type->is<ProtocolType>())
      return std::nullopt;
  }

  // If the source of the binding is 'OptionalObject' constraint
  // and type variable is on the left-hand side, that means
  // that it _has_ to be of optional type, since the right-hand
  // side of the constraint is object type of the optional.
  if (constraint->getKind() == ConstraintKind::OptionalObject &&
      kind == AllowedBindingKind::Subtypes) {
    type = OptionalType::get(type);
  }

  // If the type we'd be binding to is a dependent member, don't try to
  // resolve this type variable yet.
  if (type->getWithoutSpecifierType()
          ->lookThroughAllOptionalTypes()
          ->is<DependentMemberType>()) {
    llvm::SmallPtrSet<TypeVariableType *, 4> referencedVars;
    type->getTypeVariables(referencedVars);

    bool containsSelf = false;
    for (auto *var : referencedVars) {
      // Add all type variables encountered in the type except
      // to the current type variable.
      if (var != TypeVar) {
        AdjacentVars.insert({var, constraint});
        continue;
      }

      containsSelf = true;
    }

    // If inferred type doesn't contain the current type variable,
    // let's mark bindings as delayed until dependent member type
    // is resolved.
    if (!containsSelf)
      DelayedBy.push_back(constraint);

    return std::nullopt;
  }

  // If our binding choice is a function type and we're attempting
  // to bind to a type variable that is the result of opening a
  // generic parameter, strip the noescape bit so that we only allow
  // bindings of escaping functions in this position. We do this
  // because within the generic function we have no indication of
  // whether the parameter is a function type and if so whether it
  // should be allowed to escape. As a result we allow anything
  // passed in to escape.
  if (auto *fnTy = type->getAs<AnyFunctionType>()) {
    // Since inference now happens during constraint generation,
    // this hack should be allowed in both `Solving`
    // (during non-diagnostic mode) and `ConstraintGeneration` phases.
    if (isGenericParameter() &&
        (!CS.shouldAttemptFixes() ||
         CS.getPhase() == ConstraintSystemPhase::ConstraintGeneration)) {
      type = fnTy->withExtInfo(fnTy->getExtInfo().withNoEscape(false));
    }
  }

  // Check whether we can perform this binding.
  if (auto boundType = checkTypeOfBinding(TypeVar, type)) {
    type = *boundType;
  } else {
    auto *bindingTypeVar = type->getRValueType()->getAs<TypeVariableType>();

    if (!bindingTypeVar)
      return std::nullopt;

    // If current type variable is associated with a code completion token
    // it's possible that it doesn't have enough contextual information
    // to be resolved to anything, so let's note that fact in the potential
    // bindings and use it when forming a hole if there are no other bindings
    // available.
    if (auto *locator = bindingTypeVar->getImpl().getLocator()) {
      if (locator->directlyAt<CodeCompletionExpr>())
        AssociatedCodeCompletionToken = locator->getAnchor();
    }

    switch (constraint->getKind()) {
    case ConstraintKind::Subtype:
    case ConstraintKind::SubclassOf:
    case ConstraintKind::Conversion:
    case ConstraintKind::ArgumentConversion:
    case ConstraintKind::OperatorArgumentConversion: {
      if (kind == AllowedBindingKind::Subtypes) {
        SubtypeOf.insert({bindingTypeVar, constraint});
      } else {
        assert(kind == AllowedBindingKind::Supertypes);
        SupertypeOf.insert({bindingTypeVar, constraint});
      }

      AdjacentVars.insert({bindingTypeVar, constraint});
      break;
    }

    case ConstraintKind::Bind:
    case ConstraintKind::BindParam:
    case ConstraintKind::Equal: {
      EquivalentTo.insert({bindingTypeVar, constraint});
      AdjacentVars.insert({bindingTypeVar, constraint});
      break;
    }

    case ConstraintKind::UnresolvedMemberChainBase: {
      EquivalentTo.insert({bindingTypeVar, constraint});

      // Don't record adjacency between base and result types,
      // this is just an auxiliary constraint to enforce ordering.
      break;
    }

    case ConstraintKind::OptionalObject: {
      // Type variable that represents an object type of
      // an un-inferred optional is adjacent to a type
      // variable that presents such optional (`bindingTypeVar`
      // in this case).
      if (kind == AllowedBindingKind::Supertypes)
        AdjacentVars.insert({bindingTypeVar, constraint});
      break;
    }

    default:
      break;
    }

    return std::nullopt;
  }

  // Make sure we aren't trying to equate type variables with different
  // lvalue-binding rules.
  if (auto otherTypeVar = type->getAs<TypeVariableType>()) {
    if (TypeVar->getImpl().canBindToLValue() !=
        otherTypeVar->getImpl().canBindToLValue())
      return std::nullopt;
  }

  if (type->is<InOutType>() && !TypeVar->getImpl().canBindToInOut())
    type = LValueType::get(type->getInOutObjectType());
  if (type->is<LValueType>() && !TypeVar->getImpl().canBindToLValue())
    type = type->getRValueType();

  // BindParam constraints are not reflexive and must be treated specially.
  if (constraint->getKind() == ConstraintKind::BindParam) {
    if (kind == AllowedBindingKind::Subtypes) {
      if (auto *lvt = type->getAs<LValueType>()) {
        type = InOutType::get(lvt->getObjectType());
      }
    } else if (kind == AllowedBindingKind::Supertypes) {
      if (auto *iot = type->getAs<InOutType>()) {
        type = LValueType::get(iot->getObjectType());
      }
    }
    kind = AllowedBindingKind::Exact;
  }

  return PotentialBinding{type, kind, constraint};
}

/// Retrieve the set of potential type bindings for the given
/// representative type variable, along with flags indicating whether
/// those types should be opened.
void PotentialBindings::infer(Constraint *constraint) {
  switch (constraint->getKind()) {
  case ConstraintKind::Bind:
  case ConstraintKind::Equal:
  case ConstraintKind::BindParam:
  case ConstraintKind::BindToPointerType:
  case ConstraintKind::Subtype:
  case ConstraintKind::SubclassOf:
  case ConstraintKind::Conversion:
  case ConstraintKind::ArgumentConversion:
  case ConstraintKind::OperatorArgumentConversion:
  case ConstraintKind::OptionalObject:
  case ConstraintKind::UnresolvedMemberChainBase: {
    auto binding = inferFromRelational(constraint);
    if (!binding)
      break;

    addPotentialBinding(*binding);
    break;
  }
  case ConstraintKind::KeyPathApplication: {
    // If this variable is in the application projected result type, delay
    // binding until we've bound other type variables in the key-path
    // application constraint. This ensures we try to bind the key path type
    // first, which can allow us to discover additional bindings for the result
    // type.
    SmallPtrSet<TypeVariableType *, 4> typeVars;
    findInferableTypeVars(CS.simplifyType(constraint->getThirdType()),
                          typeVars);
    if (typeVars.count(TypeVar)) {
      DelayedBy.push_back(constraint);
    }

    break;
  }

  case ConstraintKind::BridgingConversion:
  case ConstraintKind::CheckedCast:
  case ConstraintKind::EscapableFunctionOf:
  case ConstraintKind::OpenedExistentialOf:
  case ConstraintKind::KeyPath:
  case ConstraintKind::SyntacticElement:
  case ConstraintKind::Conjunction:
  case ConstraintKind::BindTupleOfFunctionParams:
  case ConstraintKind::ShapeOf:
  case ConstraintKind::ExplicitGenericArguments:
  case ConstraintKind::PackElementOf:
  case ConstraintKind::SameShape:
  case ConstraintKind::MaterializePackExpansion:
    // Constraints from which we can't do anything.
    break;

  // For now let's avoid inferring protocol requirements from
  // this constraint, but in the future we could do that to
  // to filter bindings.
  case ConstraintKind::TransitivelyConformsTo:
    break;

  case ConstraintKind::DynamicTypeOf: {
    // Direct binding of the left-hand side could result
    // in `DynamicTypeOf` failure if right-hand side is
    // bound (because 'Bind' requires equal types to
    // succeed), or left is bound to Any which is not an
    // [existential] metatype.
    auto dynamicType = constraint->getFirstType();
    if (auto *tv = dynamicType->getAs<TypeVariableType>()) {
      if (tv->getImpl().getRepresentative(nullptr) == TypeVar) {
        DelayedBy.push_back(constraint);
        break;
      }
    }

    // This is right-hand side, let's continue.
    break;
  }

  case ConstraintKind::Defaultable:
  case ConstraintKind::FallbackType:
    // Do these in a separate pass.
    if (CS.getFixedTypeRecursive(constraint->getFirstType(), true)
            ->getAs<TypeVariableType>() == TypeVar) {
      addDefault(constraint);
    }
    break;

  case ConstraintKind::Disjunction:
    // If there is additional context available via disjunction
    // associated with closure literal (e.g. coercion to some other
    // type) let's delay resolving the closure until the disjunction
    // is attempted.
    DelayedBy.push_back(constraint);
    break;

  case ConstraintKind::ConformsTo:
  case ConstraintKind::SelfObjectOfProtocol: {
    auto protocolTy = constraint->getSecondType();
    if (protocolTy->is<ProtocolType>())
      Protocols.push_back(constraint);
    break;
  }

  case ConstraintKind::LiteralConformsTo: {
    // Record constraint where protocol requirement originated
    // this is useful to use for the binding later.
    addLiteral(constraint);
    break;
  }

  case ConstraintKind::ApplicableFunction:
  case ConstraintKind::DynamicCallableApplicableFunction: {
    auto overloadTy = constraint->getSecondType();
    // If current type variable represents an overload set
    // being applied to the arguments, it can't be delayed
    // by application constraints, because it doesn't
    // depend on argument/result types being resolved first.
    if (overloadTy->isEqual(TypeVar))
      break;

    LLVM_FALLTHROUGH;
  }

  case ConstraintKind::BindOverload: {
    DelayedBy.push_back(constraint);
    break;
  }

  case ConstraintKind::ValueMember:
  case ConstraintKind::UnresolvedValueMember:
  case ConstraintKind::ValueWitness:
  case ConstraintKind::PropertyWrapper: {
    // If current type variable represents a member type of some reference,
    // it would be bound once member is resolved either to a actual member
    // type or to a hole if member couldn't be found.
    auto memberTy = constraint->getSecondType()->castTo<TypeVariableType>();

    if (memberTy->getImpl().hasRepresentativeOrFixed()) {
      if (auto type = memberTy->getImpl().getFixedType(/*record=*/nullptr)) {
        // It's possible that member has been bound to some other type variable
        // instead of merged with it because it's wrapped in an l-value type.
        if (type->getWithoutSpecifierType()->isEqual(TypeVar)) {
          DelayedBy.push_back(constraint);
          break;
        }
      } else {
        memberTy = memberTy->getImpl().getRepresentative(/*record=*/nullptr);
      }
    }

    if (memberTy == TypeVar)
      DelayedBy.push_back(constraint);

    break;
  }

  case ConstraintKind::OneWayEqual:
  case ConstraintKind::OneWayBindParam: {
    // Don't produce any bindings if this type variable is on the left-hand
    // side of a one-way binding.
    auto firstType = constraint->getFirstType();
    if (auto *tv = firstType->getAs<TypeVariableType>()) {
      if (tv->getImpl().getRepresentative(nullptr) == TypeVar) {
        DelayedBy.push_back(constraint);
        break;
      }
    }

    break;
  }
  }
}

void PotentialBindings::retract(Constraint *constraint) {
  Bindings.erase(
      llvm::remove_if(Bindings,
                      [&constraint](const PotentialBinding &binding) {
                        return binding.getSource() == constraint;
                      }),
      Bindings.end());

  auto isMatchingConstraint = [&constraint](Constraint *existing) {
    return existing == constraint;
  };

  auto hasMatchingSource =
      [&constraint](
          const std::pair<TypeVariableType *, Constraint *> &adjacency) {
        return adjacency.second == constraint;
      };

  switch (constraint->getKind()) {
  case ConstraintKind::ConformsTo:
  case ConstraintKind::SelfObjectOfProtocol:
    Protocols.erase(llvm::remove_if(Protocols, isMatchingConstraint),
                    Protocols.end());
    break;

  case ConstraintKind::LiteralConformsTo:
    Literals.erase(constraint);
    break;

  case ConstraintKind::Defaultable:
  case ConstraintKind::FallbackType: {
    Defaults.erase(constraint);
    break;
  }

  default:
    break;
  }

  {
    llvm::SmallPtrSet<TypeVariableType *, 2> unviable;
    for (const auto &adjacent : AdjacentVars) {
      if (adjacent.second == constraint)
        unviable.insert(adjacent.first);
    }

    for (auto *adjacentVar : unviable)
      AdjacentVars.erase(std::make_pair(adjacentVar, constraint));
  }

  DelayedBy.erase(llvm::remove_if(DelayedBy, isMatchingConstraint),
                  DelayedBy.end());

  SubtypeOf.remove_if(hasMatchingSource);
  SupertypeOf.remove_if(hasMatchingSource);
  EquivalentTo.remove_if(hasMatchingSource);
}

void BindingSet::forEachLiteralRequirement(
    llvm::function_ref<void(KnownProtocolKind)> callback) const {
  for (const auto &literal : Literals) {
    auto *protocol = literal.first;
    const auto &info = literal.second;

    // Only uncovered defaultable literal protocols participate.
    if (!info.viableAsBinding())
      continue;
    
    if (auto protocolKind = protocol->getKnownProtocolKind())
      callback(*protocolKind);
  }
}

LiteralBindingKind BindingSet::getLiteralForScore() const {
  LiteralBindingKind kind = LiteralBindingKind::None;

  forEachLiteralRequirement([&](KnownProtocolKind protocolKind) {
    switch (protocolKind) {
    case KnownProtocolKind::ExpressibleByDictionaryLiteral:
    case KnownProtocolKind::ExpressibleByArrayLiteral:
    case KnownProtocolKind::ExpressibleByStringInterpolation:
      kind = LiteralBindingKind::Collection;
      break;

    case KnownProtocolKind::ExpressibleByFloatLiteral:
      kind = LiteralBindingKind::Float;
      break;

    default:
      if (kind != LiteralBindingKind::Collection)
        kind = LiteralBindingKind::Atom;
      break;
    }
  });
  return kind;
}

unsigned BindingSet::getNumViableLiteralBindings() const {
  return llvm::count_if(Literals, [&](const auto &literal) {
    return literal.second.viableAsBinding();
  });
}

/// Return string for atomic literal kinds (integer, string, & boolean) for
/// printing in debug output.
static std::string getAtomLiteralAsString(ExprKind EK) {
#define ENTRY(Kind, String)                                                    \
  case ExprKind::Kind:                                                         \
    return String
  switch (EK) {
    ENTRY(IntegerLiteral, "integer");
    ENTRY(StringLiteral, "string");
    ENTRY(BooleanLiteral, "boolean");
    ENTRY(NilLiteral, "nil");
  default:
    return "";
  }
#undef ENTRY
}

/// Return string for collection literal kinds (interpolated string, array,
/// dictionary) for printing in debug output.
static std::string getCollectionLiteralAsString(KnownProtocolKind KPK) {
#define ENTRY(Kind, String)                                                    \
  case KnownProtocolKind::Kind:                                                \
    return String
  switch (KPK) {
    ENTRY(ExpressibleByDictionaryLiteral, "dictionary");
    ENTRY(ExpressibleByArrayLiteral, "array");
    ENTRY(ExpressibleByStringInterpolation, "interpolated string");
  default:
    return "";
  }
#undef ENTRY
}

void BindingSet::dump(llvm::raw_ostream &out, unsigned indent) const {
  PrintOptions PO;
  PO.PrintTypesForDebugging = true;

  if (auto typeVar = getTypeVariable()) {
    typeVar->getImpl().print(out);
    out << " ";
  }

  std::vector<std::string> attributes;
  if (isDirectHole())
    attributes.push_back("hole");
  if (isPotentiallyIncomplete())
    attributes.push_back("potentially_incomplete");
  if (isDelayed())
    attributes.push_back("delayed");
  if (isSubtypeOfExistentialType())
    attributes.push_back("subtype_of_existential");
  if (!attributes.empty()) {
    out << "[attributes: ";
    interleave(attributes, out, ", ");
  }
  
  auto literalKind = getLiteralForScore();
  if (literalKind != LiteralBindingKind::None) {
    if (!attributes.empty()) {
      out << ", ";
    } else {
      out << "[attributes: ";
    }
    out << "[literal: ";
    switch (literalKind) {
    case LiteralBindingKind::Atom: {
      if (auto atomKind = TypeVar->getImpl().getAtomicLiteralKind()) {
        out << getAtomLiteralAsString(*atomKind);
      }
      break;
    }
    case LiteralBindingKind::Collection: {
      std::vector<std::string> collectionLiterals;
      forEachLiteralRequirement([&](KnownProtocolKind protocolKind) {
        collectionLiterals.push_back(
            getCollectionLiteralAsString(protocolKind));
      });
      interleave(collectionLiterals, out, ", ");
      break;
    }
    case LiteralBindingKind::Float:
    case LiteralBindingKind::None:
      out << getLiteralBindingKind(literalKind).str();
      break;
    }
    if (attributes.empty()) {
      out << "]] ";
    } else {
      out << "]";
    }
  }
  if (!attributes.empty())
    out << "] ";

  if (involvesTypeVariables()) {
    out << "[involves_type_vars: ";
    interleave(AdjacentVars,
               [&](const auto *typeVar) { out << typeVar->getString(PO); },
               [&out]() { out << ", "; });
    out << "] ";
  }

  auto numDefaultable = getNumViableDefaultableBindings();
  if (numDefaultable > 0)
    out << "[#defaultable_bindings: " << numDefaultable << "] ";

  struct PrintableBinding {
  private:
    enum class BindingKind { Exact, Subtypes, Supertypes, Literal };
    BindingKind Kind;
    Type BindingType;
    PrintableBinding(BindingKind kind, Type bindingType)
        : Kind(kind), BindingType(bindingType) {}

  public:
    static PrintableBinding supertypesOf(Type binding) {
      return PrintableBinding{BindingKind::Supertypes, binding};
    }
    
    static PrintableBinding subtypesOf(Type binding) {
      return PrintableBinding{BindingKind::Subtypes, binding};
    }
    
    static PrintableBinding exact(Type binding) {
      return PrintableBinding{BindingKind::Exact, binding};
    }
    
    static PrintableBinding literalDefaultType(Type binding) {
      return PrintableBinding{BindingKind::Literal, binding};
    }

    void print(llvm::raw_ostream &out, const PrintOptions &PO,
               unsigned indent = 0) const {
      switch (Kind) {
      case BindingKind::Exact:
        break;
      case BindingKind::Subtypes:
        out << "(subtypes of) ";
        break;
      case BindingKind::Supertypes:
        out << "(supertypes of) ";
        break;
      case BindingKind::Literal:
        out << "(default type of literal) ";
        break;
      }
      BindingType.print(out, PO);
    }
  };

  out << "[with possible bindings: ";
  SmallVector<PrintableBinding, 2> potentialBindings;
  for (const auto &binding : Bindings) {
    switch (binding.Kind) {
    case AllowedBindingKind::Exact:
      potentialBindings.push_back(PrintableBinding::exact(binding.BindingType));
      break;
    case AllowedBindingKind::Supertypes:
      potentialBindings.push_back(
          PrintableBinding::supertypesOf(binding.BindingType));
      break;
    case AllowedBindingKind::Subtypes:
      potentialBindings.push_back(
          PrintableBinding::subtypesOf(binding.BindingType));
      break;
    }
  }
  for (const auto &literal : Literals) {
    if (literal.second.viableAsBinding()) {
      potentialBindings.push_back(PrintableBinding::literalDefaultType(
          literal.second.getDefaultType()));
    }
  }
  if (potentialBindings.empty()) {
    out << "<empty>";
  } else {
    interleave(
        potentialBindings,
        [&](const PrintableBinding &binding) { binding.print(out, PO); },
        [&] { out << ", "; });
  }
  out << "]";

  if (!Defaults.empty()) {
    out << " [defaults: ";
    interleave(
        Defaults,
        [&](const auto &entry) {
          auto *constraint = entry.second;
          auto defaultBinding =
              PrintableBinding::exact(constraint->getSecondType());
          defaultBinding.print(out, PO);
        },
        [&] { out << ", "; });
    out << "]";
  }
  
}

// Given a possibly-Optional type, return the direct superclass of the
// (underlying) type wrapped in the same number of optional levels as
// type.
static Type getOptionalSuperclass(Type type) {
  int optionalLevels = 0;
  while (auto underlying = type->getOptionalObjectType()) {
    ++optionalLevels;
    type = underlying;
  }

  Type superclass;
  if (auto *existential = type->getAs<ExistentialType>()) {
    auto constraintTy = existential->getConstraintType();
    if (auto *compositionTy = constraintTy->getAs<ProtocolCompositionType>()) {
      SmallVector<Type, 2> members;
      bool found = false;
      // Preserve all of the protocol requirements of the type i.e.
      // if the type was `any B & P` where `B : A` the supertype is
      // going to be `any A & P`.
      //
      // This is especially important for Sendable key paths because
      // to reserve sendability of the original type.
      for (auto member : compositionTy->getMembers()) {
        if (member->getClassOrBoundGenericClass()) {
          member = member->getSuperclass();
          if (!member)
            return Type();
          found = true;
        }
        members.push_back(member);
      }

      if (!found)
        return Type();

      superclass = ExistentialType::get(
          ProtocolCompositionType::get(type->getASTContext(), members,
                                       compositionTy->getInverses(),
                                       compositionTy->hasExplicitAnyObject()));
    } else {
      // Avoid producing superclass for situations like `any P` where `P` is
      // `protocol P : C`.
      return Type();
    }
  } else {
    superclass = type->getSuperclass();
  }

  if (!superclass)
    return Type();

  while (optionalLevels--)
    superclass = OptionalType::get(superclass);

  return superclass;
}

/// Enumerates all of the 'direct' supertypes of the given type.
///
/// The direct supertype S of a type T is a supertype of T (e.g., T < S)
/// such that there is no type U where T < U and U < S.
static SmallVector<Type, 4> enumerateDirectSupertypes(Type type) {
  SmallVector<Type, 4> result;

  if (type->is<InOutType>() || type->is<LValueType>()) {
    type = type->getWithoutSpecifierType();
    result.push_back(type);
  }

  if (auto superclass = getOptionalSuperclass(type)) {
    // FIXME: Can also weaken to the set of protocol constraints, but only
    // if there are any protocols that the type conforms to but the superclass
    // does not.

    result.push_back(superclass);
  }

  // FIXME: lots of other cases to consider!
  return result;
}

bool TypeVarBindingProducer::computeNext() {
  SmallVector<Binding, 4> newBindings;
  auto addNewBinding = [&](Binding binding) {
    auto type = binding.BindingType;

    // If we've already tried this binding, move on.
    if (!BoundTypes.insert(type.getPointer()).second)
      return;

    if (!ExploredTypes.insert(type->getCanonicalType()).second)
      return;

    newBindings.push_back(std::move(binding));
  };

  // Let's attempt only directly inferrable bindings for
  // a type variable representing a closure type because
  // such type variables are handled specially and only
  // bound to a type inferred from their expression, having
  // contextual bindings is just a trigger for that to
  // happen.
  if (TypeVar->getImpl().isClosureType())
    return false;

  for (auto &binding : Bindings) {
    const auto type = binding.BindingType;
    assert(!type->hasError());

    // If we have a protocol with a default type, look for alternative
    // types to the default.
    if (NumTries == 0 && binding.hasDefaultedLiteralProtocol()) {
      auto knownKind =
          *(binding.getDefaultedLiteralProtocol()->getKnownProtocolKind());
      SmallVector<Type, 2> scratch;
      for (auto altType : CS.getAlternativeLiteralTypes(knownKind, scratch)) {
        addNewBinding(binding.withSameSource(altType, BindingKind::Subtypes));
      }
    }

    if (getLocator()->directlyAt<ForceValueExpr>() &&
        TypeVar->getImpl().canBindToLValue() &&
        !binding.BindingType->is<LValueType>()) {
      // Result of force unwrap is always connected to its base
      // optional type via `OptionalObject` constraint which
      // preserves l-valueness, so in case where object type got
      // inferred before optional type (because it got the
      // type from context e.g. parameter type of a function call),
      // we need to test type with and without l-value after
      // delaying bindings for as long as possible.
      addNewBinding(binding.withType(LValueType::get(binding.BindingType)));
    }

    // There is a tailored fix for optional key path root references,
    // let's not create ambiguity by attempting unwrap when it's
    // not allowed.
    if (binding.Kind != BindingKind::Subtypes &&
        getLocator()->isKeyPathRoot() && type->getOptionalObjectType())
      continue;

    // Allow solving for T even for a binding kind where that's invalid
    // if fixes are allowed, because that gives us the opportunity to
    // match T? values to the T binding by adding an unwrap fix.
    if (binding.Kind == BindingKind::Subtypes || CS.shouldAttemptFixes()) {
      // If we were unsuccessful solving for T?, try solving for T.
      if (auto objTy = type->getOptionalObjectType()) {
        // If T is a type variable, only attempt this if both the
        // type variable we are trying bindings for, and the type
        // variable we will attempt to bind, both have the same
        // polarity with respect to being able to bind lvalues.
        if (auto otherTypeVar = objTy->getAs<TypeVariableType>()) {
          if (TypeVar->getImpl().canBindToLValue() ==
              otherTypeVar->getImpl().canBindToLValue()) {
            addNewBinding(binding.withSameSource(objTy, binding.Kind));
          }
        } else {
          addNewBinding(binding.withSameSource(objTy, binding.Kind));
        }
      }
    }

    auto srcLocator = binding.getLocator();
    if (srcLocator &&
        (srcLocator->isLastElement<LocatorPathElt::ApplyArgToParam>() ||
         srcLocator->isLastElement<LocatorPathElt::AutoclosureResult>()) &&
        !type->hasTypeVariable() && type->isKnownStdlibCollectionType()) {
      // If the type binding comes from the argument conversion, let's
      // instead of binding collection types directly, try to bind
      // using temporary type variables substituted for element
      // types, that's going to ensure that subtype relationship is
      // always preserved.
      auto *BGT = type->castTo<BoundGenericType>();
      auto dstLocator = TypeVar->getImpl().getLocator();
      auto newType =
          CS.openUnboundGenericType(BGT->getDecl(), BGT->getParent(),
                                    dstLocator, /*isTypeResolution=*/false)
              ->reconstituteSugar(/*recursive=*/false);
      addNewBinding(binding.withType(newType));
    }

    if (binding.Kind == BindingKind::Supertypes) {
      // If this is a type variable representing closure result,
      // which is on the right-side of some relational constraint
      // let's have it try `Void` as well because there is an
      // implicit conversion `() -> T` to `() -> Void` and this
      // helps to avoid creating a thunk to support it.
      if (getLocator()->isLastElement<LocatorPathElt::ClosureResult>() &&
          binding.Kind == AllowedBindingKind::Supertypes) {
        auto voidType = CS.getASTContext().TheEmptyTupleType;
        addNewBinding(binding.withSameSource(voidType, BindingKind::Exact));
      }

      for (auto supertype : enumerateDirectSupertypes(type)) {
        // If we're not allowed to try this binding, skip it.
        if (auto simplifiedSuper = checkTypeOfBinding(TypeVar, supertype)) {
          auto supertype = *simplifiedSuper;
          // A key path type cannot be bound to type-erased key path variants.
          if (TypeVar->getImpl().isKeyPathType() &&
              isTypeErasedKeyPathType(supertype))
            continue;

          addNewBinding(binding.withType(supertype));
        }
      }
    }
  }

  if (newBindings.empty()) {
    // If key path type had contextual types, let's not attempt fallback.
    if (TypeVar->getImpl().isKeyPathType() && !ExploredTypes.empty())
      return false;

    // Add defaultable constraints (if any).
    for (auto *constraint : DelayedDefaults) {
      if (constraint->getKind() == ConstraintKind::FallbackType) {
        // If there are no other possible bindings for this variable
        // let's default it to the fallback type, otherwise we should
        // only attempt contextual types.
        if (!ExploredTypes.empty())
          continue;
      }

      addNewBinding(getDefaultBinding(constraint));
    }

    // Drop all of the default since we have converted them into bindings.
    DelayedDefaults.clear();
  }

  if (newBindings.empty())
    return false;

  Index = 0;
  ++NumTries;
  Bindings = std::move(newBindings);
  return true;
}

std::optional<std::pair<ConstraintFix *, unsigned>>
TypeVariableBinding::fixForHole(ConstraintSystem &cs) const {
  auto *dstLocator = TypeVar->getImpl().getLocator();
  auto *srcLocator = Binding.getLocator();

  // FIXME: This check could be turned into an assert once
  // all code completion kinds are ported to use
  // `TypeChecker::typeCheckForCodeCompletion` API.
  if (cs.isForCodeCompletion()) {
    // If the hole is originated from code completion expression
    // let's not try to fix this, anything connected to a
    // code completion is allowed to be a hole because presence
    // of a code completion token makes constraint system
    // under-constrained due to e.g. lack of expressions on the
    // right-hand side of the token, which are required for a
    // regular type-check.
    if (dstLocator->directlyAt<CodeCompletionExpr>() ||
        srcLocator->directlyAt<CodeCompletionExpr>())
      return std::nullopt;
  }

  unsigned defaultImpact = 1;

  if (auto *GP = TypeVar->getImpl().getGenericParameter()) {
    // If it is representative for a key path root, let's emit a more
    // specific diagnostic.
    auto *keyPathRoot =
        cs.isRepresentativeFor(TypeVar, ConstraintLocator::KeyPathRoot);
    if (keyPathRoot) {
      ConstraintFix *fix = SpecifyKeyPathRootType::create(
          cs, keyPathRoot->getImpl().getLocator());
      return std::make_pair(fix, defaultImpact);
    } else {
      auto path = dstLocator->getPath();
      // Drop `generic parameter` locator element so that all missing
      // generic parameters related to the same path can be coalesced later.
      ConstraintFix *fix = DefaultGenericArgument::create(
          cs, GP,
          cs.getConstraintLocator(dstLocator->getAnchor(), path.drop_back()));
      return std::make_pair(fix, defaultImpact);
    }
  }

  if (TypeVar->getImpl().isClosureParameterType()) {
    ConstraintFix *fix = SpecifyClosureParameterType::create(cs, dstLocator);
    return std::make_pair(fix, defaultImpact);
  }

  if (TypeVar->getImpl().isClosureResultType()) {
    auto *closure = castToExpr<ClosureExpr>(dstLocator->getAnchor());
    // If the whole body is being ignored due to a pre-check failure,
    // let's not record a fix about result type since there is
    // just not enough context to infer it without a body.
    auto *closureLoc = cs.getConstraintLocator(closure);
    if (cs.hasFixFor(closureLoc, FixKind::IgnoreInvalidResultBuilderBody) ||
        cs.hasFixFor(closureLoc, FixKind::IgnoreResultBuilderWithReturnStmts))
      return std::nullopt;

    ConstraintFix *fix = SpecifyClosureReturnType::create(cs, dstLocator);
    return std::make_pair(fix, defaultImpact);
  }

  if (srcLocator->directlyAt<ObjectLiteralExpr>()) {
    ConstraintFix *fix = SpecifyObjectLiteralTypeImport::create(cs, dstLocator);
    return std::make_pair(fix, defaultImpact);
  }

  if (srcLocator->isKeyPathRoot()) {
    // If we recorded an invalid key path fix, let's skip this specify root
    // type fix because it wouldn't produce a useful diagnostic.
    auto *kpLocator = cs.getConstraintLocator(srcLocator->getAnchor());
    if (cs.hasFixFor(kpLocator, FixKind::AllowKeyPathWithoutComponents))
      return std::nullopt;

    // If key path has any invalid component, let's just skip fix because the
    // invalid component would be already diagnosed.
    auto keyPath = castToExpr<KeyPathExpr>(srcLocator->getAnchor());
    if (llvm::any_of(keyPath->getComponents(),
                     [](KeyPathExpr::Component component) {
                       return !component.isValid();
                     }))
      return std::nullopt;

    ConstraintFix *fix = SpecifyKeyPathRootType::create(cs, dstLocator);
    return std::make_pair(fix, defaultImpact);
  }

  if (srcLocator->isLastElement<LocatorPathElt::PlaceholderType>()) {
    // When a 'nil' has a placeholder as contextual type there is not enough
    // information to resolve it, so let's record a specify contextual type for
    // nil fix.
    if (isExpr<NilLiteralExpr>(srcLocator->getAnchor())) {
      ConstraintFix *fix = SpecifyContextualTypeForNil::create(cs, dstLocator);
      return std::make_pair(fix, /*impact=*/(unsigned)10);
    }

    ConstraintFix *fix = SpecifyTypeForPlaceholder::create(cs, srcLocator);
    return std::make_pair(fix, defaultImpact);
  }

  if (dstLocator->directlyAt<NilLiteralExpr>()) {
    // This is a dramatic event, it means that there is absolutely
    // no contextual information to resolve type of `nil`.
    ConstraintFix *fix = SpecifyContextualTypeForNil::create(cs, dstLocator);
    return std::make_pair(fix, /*impact=*/(unsigned)10);
  }

  if (auto pattern = dstLocator->getPatternMatch()) {
    if (dstLocator->isLastElement<LocatorPathElt::PatternDecl>()) {
      // If this is the pattern in a for loop, and we have a mismatch of the
      // element type, then we don't have any useful contextual information
      // for the pattern, and can just bind to a hole without needing to penalize
      // the solution further.
      auto *seqLoc = cs.getConstraintLocator(
          dstLocator->getAnchor(), ConstraintLocator::SequenceElementType);
      if (cs.hasFixFor(seqLoc,
                       FixKind::IgnoreCollectionElementContextualMismatch)) {
        return std::nullopt;
      }
      if (dstLocator->getAnchor().isExpr(ExprKind::CodeCompletion)) {
        // Ignore the hole if it is because the right-hand-side of the pattern
        // match is a code completion token. Assigning a high fix score to this
        // mismatch won't help. In fact, it can harm because we might have a
        // different exploration path in the constraint system that gives up
        // earlier (eg. because code completion is in a closure that doesn't
        // match the expected parameter of a function call) and might thus get a
        // better score, despite not having any information about the code
        // completion token at all.
        return std::nullopt;
      }
      // Not being able to infer the type of a variable in a pattern binding
      // decl is more dramatic than anything that could happen inside the
      // expression because we want to preferrably point the diagnostic to a
      // part of the expression that caused us to be unable to infer the
      // variable's type.
      ConstraintFix *fix =
          IgnoreUnresolvedPatternVar::create(cs, pattern.get(), dstLocator);
      return std::make_pair(fix, /*impact=*/(unsigned)100);
    }
  }

  if (srcLocator->isLastElement<LocatorPathElt::MemberRefBase>()) {
    auto *baseExpr = castToExpr<UnresolvedMemberExpr>(srcLocator->getAnchor());
    ConstraintFix *fix = SpecifyBaseTypeForContextualMember::create(
        cs, baseExpr->getName(), srcLocator);
    return std::make_pair(fix, defaultImpact);
  }

  if (dstLocator->isLastElement<LocatorPathElt::PackElement>()) {
    // A hole appears as an element of generic pack params
    ConstraintFix *Fix = SpecifyPackElementType::create(cs, dstLocator);
    return std::make_pair(Fix, defaultImpact);
  }

  return std::nullopt;
}

bool TypeVariableBinding::attempt(ConstraintSystem &cs) const {
  auto type = Binding.BindingType;
  auto *srcLocator = Binding.getLocator();
  auto *dstLocator = TypeVar->getImpl().getLocator();

  if (Binding.hasDefaultedLiteralProtocol()) {
    type = cs.replaceInferableTypesWithTypeVars(type, dstLocator);
    type = type->reconstituteSugar(/*recursive=*/false);
  }

  // If type variable has been marked as a possible hole due to
  // e.g. reference to a missing member. Let's propagate that
  // information to the object type of the optional type it's
  // about to be bound to.
  //
  // In some situations like pattern bindings e.g. `if let x = base?.member`
  // - if `member` doesn't exist, `x` cannot be determined either, which
  // leaves `OptionalEvaluationExpr` representing outer type of `base?.member`
  // without any contextual information, so even though `x` would get
  // bound to result type of the chain, underlying type variable wouldn't
  // be resolved, so we need to propagate holes up the conversion chain.
  // Also propagate in code completion mode because in some cases code
  // completion relies on type variable being a potential hole.
  if (TypeVar->getImpl().canBindToHole()) {
    if (srcLocator->directlyAt<OptionalEvaluationExpr>() ||
        cs.isForCodeCompletion()) {
      if (auto objectTy = type->getOptionalObjectType()) {
        if (auto *typeVar = objectTy->getAs<TypeVariableType>()) {
          cs.recordPotentialHole(typeVar);
        }
      }
    }
  }

  ConstraintSystem::TypeMatchOptions options;

  options |= ConstraintSystem::TMF_GenerateConstraints;
  options |= ConstraintSystem::TMF_BindingTypeVariable;

  auto result =
      cs.matchTypes(TypeVar, type, ConstraintKind::Bind, options, srcLocator);

  if (result.isFailure()) {
    if (cs.isDebugMode()) {
      PrintOptions PO;
      PO.PrintTypesForDebugging = true;

      llvm::errs().indent(cs.solverState->getCurrentIndent())
          << "(failed to establish binding " << TypeVar->getString(PO)
          << " := " << type->getString(PO) << ")\n";
    }
    return false;
  }

  auto reportHole = [&]() {
    if (cs.isForCodeCompletion()) {
      // Don't penalize solutions with unresolved generics.
      if (TypeVar->getImpl().getGenericParameter())
        return false;

      // Don't penalize solutions if we couldn't determine the type of the code
      // completion token. We still want to examine the surrounding types in
      // that case.
      if (TypeVar->getImpl().isCodeCompletionToken())
        return false;

      // Don't penalize solutions with holes due to missing arguments after the
      // code completion position.
      auto argLoc = srcLocator->findLast<LocatorPathElt::SynthesizedArgument>();
      if (argLoc && argLoc->isAfterCodeCompletionLoc())
        return false;

      // Don't penalize solutions that have holes for ignored arguments.
      if (cs.hasArgumentsIgnoredForCodeCompletion()) {
        // Avoid simplifying the locator if the constraint system didn't ignore
        // any arguments.
        auto argExpr = simplifyLocatorToAnchor(TypeVar->getImpl().getLocator());
        if (cs.isArgumentIgnoredForCodeCompletion(argExpr.dyn_cast<Expr *>())) {
          return false;
        }
      }
    }
    // Reflect in the score that this type variable couldn't be
    // resolved and had to be bound to a placeholder "hole" type.
    cs.increaseScore(SK_Hole, srcLocator);

    if (auto fix = fixForHole(cs)) {
      if (cs.recordFix(/*fix=*/fix->first, /*impact=*/fix->second))
        return true;
    }
    return false;
  };

  // If this was from a defaultable binding note that.
  if (Binding.isDefaultableBinding()) {
    cs.DefaultedConstraints.insert(srcLocator);

    // Fail if hole reporting fails.
    if (type->isPlaceholder() && reportHole())
      return false;
  }

  if (cs.simplify())
    return false;

  // If all of the re-activated constraints where simplified,
  // let's notify binding inference about the fact that type
  // variable has been bound successfully.
  {
    auto &CG = cs.getConstraintGraph();
    CG[TypeVar].introduceToInference(type);
  }

  return true;
}