1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152
|
//===--- CSSimplify.cpp - Constraint Simplification -----------------------===//
//
// 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 simplifications of constraints within the constraint
// system.
//
//===----------------------------------------------------------------------===//
#include "CSDiagnostics.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckEffects.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/PackExpansionMatcher.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Requirement.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Types.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Sema/CSFix.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace constraints;
MatchCallArgumentListener::~MatchCallArgumentListener() { }
bool MatchCallArgumentListener::extraArgument(unsigned argIdx) { return true; }
std::optional<unsigned>
MatchCallArgumentListener::missingArgument(unsigned paramIdx,
unsigned argInsertIdx) {
return std::nullopt;
}
bool MatchCallArgumentListener::missingLabel(unsigned paramIdx) { return true; }
bool MatchCallArgumentListener::extraneousLabel(unsigned paramIdx) {
return true;
}
bool MatchCallArgumentListener::incorrectLabel(unsigned paramIdx) {
return true;
}
bool MatchCallArgumentListener::outOfOrderArgument(
unsigned argIdx, unsigned prevArgIdx, ArrayRef<ParamBinding> bindings) {
return true;
}
bool MatchCallArgumentListener::relabelArguments(ArrayRef<Identifier> newNames){
return true;
}
bool MatchCallArgumentListener::shouldClaimArgDuringRecovery(unsigned argIdx) {
return true;
}
bool MatchCallArgumentListener::canClaimArgIgnoringNameMismatch(
const AnyFunctionType::Param &arg) {
return false;
}
/// Produce a score (smaller is better) comparing a parameter name and
/// potentially-typo'd argument name.
///
/// \param paramName The name of the parameter.
/// \param argName The name of the argument.
/// \param maxScore The maximum score permitted by this comparison, or
/// 0 if there is no limit.
///
/// \returns the score, if it is good enough to even consider this a match.
/// Otherwise, an empty optional.
///
static std::optional<unsigned> scoreParamAndArgNameTypo(StringRef paramName,
StringRef argName,
unsigned maxScore) {
using namespace camel_case;
// Compute the edit distance.
unsigned dist = argName.edit_distance(paramName, /*AllowReplacements=*/true,
/*MaxEditDistance=*/maxScore);
// If the edit distance would be too long, we're done.
if (maxScore != 0 && dist > maxScore)
return std::nullopt;
// The distance can be zero due to the "with" transformation above.
if (dist == 0)
return 1;
// If this is just a single character label on both sides,
// simply return distance.
if (paramName.size() == 1 && argName.size() == 1)
return dist;
// Only allow about one typo for every two properly-typed characters, which
// prevents completely-wacky suggestions in many cases.
if (dist > (argName.size() + 1) / 3)
return std::nullopt;
return dist;
}
bool constraints::isPackExpansionType(Type type) {
if (type->is<PackExpansionType>())
return true;
if (auto *typeVar = type->getAs<TypeVariableType>())
return typeVar->getImpl().isPackExpansion();
return false;
}
bool constraints::isSingleUnlabeledPackExpansionTuple(Type type) {
auto *tuple = type->getRValueType()->getAs<TupleType>();
return tuple && (tuple->getNumElements() == 1) &&
isPackExpansionType(tuple->getElementType(0)) &&
!tuple->getElement(0).hasName();
}
Type constraints::getPatternTypeOfSingleUnlabeledPackExpansionTuple(Type type) {
if (isSingleUnlabeledPackExpansionTuple(type)) {
auto tuple = type->getRValueType()->castTo<TupleType>();
const auto &tupleElement = tuple->getElementType(0);
if (auto *expansion = tupleElement->getAs<PackExpansionType>()) {
return expansion->getPatternType();
}
if (auto *typeVar = tupleElement->getAs<TypeVariableType>()) {
auto *locator = typeVar->getImpl().getLocator();
if (auto expansionElement =
locator->getLastElementAs<LocatorPathElt::PackExpansionType>()) {
return expansionElement->getOpenedType()->getPatternType();
}
}
}
return {};
}
bool constraints::containsPackExpansionType(ArrayRef<AnyFunctionType::Param> params) {
return llvm::any_of(params, [&](const auto ¶m) {
return isPackExpansionType(param.getPlainType());
});
}
bool constraints::containsPackExpansionType(TupleType *tuple) {
return llvm::any_of(tuple->getElements(), [&](const auto &elt) {
return isPackExpansionType(elt.getType());
});
}
bool constraints::doesMemberRefApplyCurriedSelf(Type baseTy,
const ValueDecl *decl) {
assert(decl->getDeclContext()->isTypeContext() &&
"Expected a member reference");
// For a reference to an instance method on a metatype, we want to keep the
// curried self.
if (decl->isInstanceMember()) {
assert(baseTy);
if (isa<AbstractFunctionDecl>(decl) &&
baseTy->getRValueType()->is<AnyMetatypeType>())
return false;
}
// Otherwise the reference applies self.
return true;
}
static bool areConservativelyCompatibleArgumentLabels(
ConstraintSystem &cs, OverloadChoice choice,
SmallVectorImpl<FunctionType::Param> &args,
MatchCallArgumentListener &listener,
std::optional<unsigned> unlabeledTrailingClosureArgIndex) {
ValueDecl *decl = nullptr;
switch (choice.getKind()) {
case OverloadChoiceKind::Decl:
case OverloadChoiceKind::DeclViaBridge:
case OverloadChoiceKind::DeclViaDynamic:
case OverloadChoiceKind::DeclViaUnwrappedOptional:
decl = choice.getDecl();
break;
// KeyPath application is not filtered in `performMemberLookup`.
case OverloadChoiceKind::KeyPathApplication:
case OverloadChoiceKind::DynamicMemberLookup:
case OverloadChoiceKind::KeyPathDynamicMemberLookup:
case OverloadChoiceKind::TupleIndex:
case OverloadChoiceKind::MaterializePack:
case OverloadChoiceKind::ExtractFunctionIsolation:
return true;
}
// If this is a member lookup, the call arguments (if we have any) will
// generally be applied to the second level of parameters, with the member
// lookup applying the curried self at the first level. But there are cases
// where we can get an unapplied declaration reference back.
auto hasAppliedSelf =
decl->hasCurriedSelf() &&
doesMemberRefApplyCurriedSelf(choice.getBaseType(), decl);
AnyFunctionType *fnType = nullptr;
if (decl->hasParameterList()) {
fnType = decl->getInterfaceType()->castTo<AnyFunctionType>();
if (hasAppliedSelf) {
fnType = fnType->getResult()->getAs<AnyFunctionType>();
assert(fnType && "Parameter list curry level does not match type");
}
} else if (auto *VD = dyn_cast<VarDecl>(decl)) {
// For variables, we can reject any type that we know cannot be callable.
auto varTy = VD->getValueInterfaceType()->lookThroughAllOptionalTypes();
if (!varTy->mayBeCallable(cs.DC))
return false;
fnType = varTy->getAs<AnyFunctionType>();
} else if (auto *MD = dyn_cast<MacroDecl>(decl)) {
fnType = MD->getInterfaceType()->getAs<AnyFunctionType>();
}
// Given we want to be conservative with this checking, if there's any case
// we can't match arguments for (e.g callable nominals, type parameters),
// default to returning true.
if (!fnType)
return true;
auto params = fnType->getParams();
ParameterListInfo paramInfo(params, decl, hasAppliedSelf);
return matchCallArguments(args, params, paramInfo,
unlabeledTrailingClosureArgIndex,
/*allow fixes*/ false, listener, std::nullopt)
.has_value();
}
Expr *constraints::getArgumentLabelTargetExpr(Expr *fn) {
// Dig out the function, looking through, parentheses, ?, and !.
do {
fn = fn->getSemanticsProvidingExpr();
if (auto force = dyn_cast<ForceValueExpr>(fn)) {
fn = force->getSubExpr();
continue;
}
if (auto bind = dyn_cast<BindOptionalExpr>(fn)) {
fn = bind->getSubExpr();
continue;
}
return fn;
} while (true);
}
/// Determine the default type-matching options to use when decomposing a
/// constraint into smaller constraints.
static ConstraintSystem::TypeMatchOptions getDefaultDecompositionOptions(
ConstraintSystem::TypeMatchOptions flags) {
return flags | ConstraintSystem::TMF_GenerateConstraints;
}
/// Whether the given parameter requires an argument.
bool swift::parameterRequiresArgument(
ArrayRef<AnyFunctionType::Param> params,
const ParameterListInfo ¶mInfo,
unsigned paramIdx) {
return !paramInfo.hasDefaultArgument(paramIdx)
&& !params[paramIdx].isVariadic();
}
/// Determine whether the given parameter can accept a trailing closure for the
/// "backward" logic.
static bool backwardScanAcceptsTrailingClosure(
const AnyFunctionType::Param ¶m) {
Type paramTy = param.getPlainType();
if (!paramTy)
return true;
paramTy = paramTy->lookThroughAllOptionalTypes();
return paramTy->isTypeParameter() ||
paramTy->is<ArchetypeType>() ||
paramTy->is<AnyFunctionType>() ||
paramTy->isTypeVariableOrMember() ||
paramTy->is<UnresolvedType>() ||
paramTy->isAny();
}
/// Determine whether any parameter from the given index up until the end
/// requires an argument to be provided.
///
/// \param params The parameters themselves.
/// \param paramInfo Declaration-provided information about the parameters.
/// \param firstParamIdx The first parameter to examine to determine whether any
/// parameter in the range \c [paramIdx, params.size()) requires an argument.
/// \param beforeLabel If non-empty, stop examining parameters when we reach
/// a parameter with this label.
static bool anyParameterRequiresArgument(
ArrayRef<AnyFunctionType::Param> params, const ParameterListInfo ¶mInfo,
unsigned firstParamIdx, std::optional<Identifier> beforeLabel) {
for (unsigned paramIdx : range(firstParamIdx, params.size())) {
// If have been asked to stop when we reach a parameter with a particular
// label, and we see a parameter with that label, we're done: no parameter
// requires an argument.
if (beforeLabel && *beforeLabel == params[paramIdx].getLabel())
break;
// If this parameter requires an argument, tell the caller.
if (parameterRequiresArgument(params, paramInfo, paramIdx))
return true;
}
// No parameters required arguments.
return false;
}
static bool isCodeCompletionTypeVar(Type type) {
if (auto *TVT = type->getAs<TypeVariableType>()) {
if (TVT->getImpl().isCodeCompletionToken()) {
return true;
}
}
return false;
}
static bool matchCallArgumentsImpl(
SmallVectorImpl<AnyFunctionType::Param> &args,
ArrayRef<AnyFunctionType::Param> params, const ParameterListInfo ¶mInfo,
std::optional<unsigned> unlabeledTrailingClosureArgIndex, bool allowFixes,
TrailingClosureMatching trailingClosureMatching,
MatchCallArgumentListener &listener,
SmallVectorImpl<ParamBinding> ¶meterBindings) {
assert(params.size() == paramInfo.size() && "Default map does not match");
assert(!unlabeledTrailingClosureArgIndex ||
*unlabeledTrailingClosureArgIndex < args.size());
// Keep track of the parameter we're matching and what argument indices
// got bound to each parameter.
unsigned numParams = params.size();
parameterBindings.clear();
parameterBindings.resize(numParams);
// Keep track of which arguments we have claimed from the argument tuple.
unsigned numArgs = args.size();
SmallVector<bool, 4> claimedArgs(numArgs, false);
SmallVector<Identifier, 4> actualArgNames;
unsigned numClaimedArgs = 0;
// Indicates whether any of the arguments are potentially out-of-order,
// requiring further checking at the end.
bool potentiallyOutOfOrder = false;
// Local function that claims the argument at \c argIdx, returning the
// index of the claimed argument. This is primarily a helper for
// \c claimNextNamed.
auto claim = [&](Identifier expectedName, unsigned argIdx,
bool ignoreNameClash = false) -> unsigned {
// Make sure we can claim this argument.
assert(argIdx != numArgs && "Must have a valid index to claim");
assert(!claimedArgs[argIdx] && "Argument already claimed");
if (!actualArgNames.empty()) {
// We're recording argument names; record this one.
actualArgNames[argIdx] = expectedName;
} else if (!ignoreNameClash && !args[argIdx].matchParameterLabel(expectedName)) {
// We have an argument name mismatch. Start recording argument names.
actualArgNames.resize(numArgs);
// Figure out previous argument names from the parameter bindings.
for (auto i : indices(params)) {
const auto ¶m = params[i];
bool firstArg = true;
for (auto argIdx : parameterBindings[i]) {
actualArgNames[argIdx] = firstArg ? param.getLabel() : Identifier();
firstArg = false;
}
}
// Record this argument name.
actualArgNames[argIdx] = expectedName;
}
claimedArgs[argIdx] = true;
++numClaimedArgs;
return argIdx;
};
// Local function that skips over any claimed arguments.
auto skipClaimedArgs = [&](unsigned &nextArgIdx) {
while (nextArgIdx != numArgs && claimedArgs[nextArgIdx])
++nextArgIdx;
return nextArgIdx;
};
// Local function that retrieves the next unclaimed argument with the given
// name (which may be empty). This routine claims the argument.
auto claimNextNamed =
[&](unsigned &nextArgIdx, Identifier paramLabel, bool ignoreNameMismatch,
bool forVariadic = false) -> std::optional<unsigned> {
// Skip over any claimed arguments.
skipClaimedArgs(nextArgIdx);
// If we've claimed all of the arguments, there's nothing more to do.
if (numClaimedArgs == numArgs)
return std::nullopt;
// Go hunting for an unclaimed argument whose name does match.
std::optional<unsigned> claimedWithSameName;
unsigned firstArgIdx = nextArgIdx;
for (unsigned i = nextArgIdx; i != numArgs; ++i) {
auto argLabel = args[i].getLabel();
bool claimIgnoringNameMismatch = false;
if (!args[i].matchParameterLabel(paramLabel)) {
// If this is an attempt to claim additional unlabeled arguments
// for variadic parameter, we have to stop at first labeled argument.
if (forVariadic)
return std::nullopt;
if ((i == firstArgIdx || ignoreNameMismatch) &&
listener.canClaimArgIgnoringNameMismatch(args[i])) {
// Avoid triggering relabelling fixes about the completion arg.
claimIgnoringNameMismatch = true;
} else {
// Otherwise we can continue trying to find argument which
// matches parameter with or without label.
continue;
}
}
// Skip claimed arguments.
if (claimedArgs[i]) {
assert(!forVariadic && "Cannot be for a variadic claim");
// Note that we have already claimed an argument with the same name.
if (!claimedWithSameName)
claimedWithSameName = i;
continue;
}
// We found a match. If the match wasn't the next one, we have
// potentially out of order arguments.
if (i != nextArgIdx) {
assert(!forVariadic && "Cannot be for a variadic claim");
// Avoid claiming un-labeled defaulted parameters
// by out-of-order un-labeled arguments or parts
// of variadic argument sequence, because that might
// be incorrect:
// ```swift
// func foo(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
// foo(1, c: 2, 3) // -> `3` will be claimed as '_ b:'.
// ```
if (argLabel.empty() && !claimIgnoringNameMismatch)
continue;
potentiallyOutOfOrder = true;
}
// Claim it.
return claim(paramLabel, i, claimIgnoringNameMismatch);
}
// If we're not supposed to attempt any fixes, we're done.
if (!allowFixes)
return std::nullopt;
// Several things could have gone wrong here, and we'll check for each
// of them at some point:
// - The keyword argument might be redundant, in which case we can point
// out the issue.
// - The argument might be unnamed, in which case we try to fix the
// problem by adding the name.
// - The argument might have extraneous label, in which case we try to
// fix the problem by removing such label.
// - The keyword argument might be a typo for an actual argument name, in
// which case we should find the closest match to correct to.
// Missing or extraneous label.
if (nextArgIdx != numArgs && ignoreNameMismatch) {
auto argLabel = args[nextArgIdx].getLabel();
// Claim this argument if we are asked to ignore labeling failure,
// only if argument doesn't have a label when parameter expected
// it to, or vice versa.
if (paramLabel.empty() || argLabel.empty())
return claim(paramLabel, nextArgIdx);
}
// Redundant keyword arguments.
if (claimedWithSameName) {
// FIXME: We can provide better diagnostics here.
return std::nullopt;
}
// Typo correction is handled in a later pass.
return std::nullopt;
};
// Local function that attempts to bind the given parameter to arguments in
// the list.
bool haveUnfulfilledParams = false;
auto bindNextParameter = [&](unsigned paramIdx, unsigned &nextArgIdx,
bool ignoreNameMismatch) {
const auto ¶m = params[paramIdx];
Identifier paramLabel = param.getLabel();
// If we have the trailing closure argument and are performing a forward
// match, look for the matching parameter.
if (trailingClosureMatching == TrailingClosureMatching::Forward &&
unlabeledTrailingClosureArgIndex &&
skipClaimedArgs(nextArgIdx) == *unlabeledTrailingClosureArgIndex) {
// If the parameter we are looking at does not support the (unlabeled)
// trailing closure argument, this parameter is unfulfilled.
if (!paramInfo.acceptsUnlabeledTrailingClosureArgument(paramIdx) &&
!ignoreNameMismatch) {
haveUnfulfilledParams = true;
return;
}
// Let's consider current closure to be extraneous if:
//
// - current parameter has a default value and doesn't accept a trailing
// closure; and
// - no other free parameter after this one accepts a trailing closure via
// forward or backward scan. This check makes sure that it's safe to
// reject and push it to the next parameter without affecting backward
// scan logic.
//
// In other words - let's push the closure argument through defaulted
// parameters until it can be considered extraneous if no parameters
// could possibly match it.
if (!paramInfo.acceptsUnlabeledTrailingClosureArgument(paramIdx) &&
!parameterRequiresArgument(params, paramInfo, paramIdx)) {
if (llvm::none_of(
range(paramIdx + 1, params.size()), [&](unsigned idx) {
return parameterBindings[idx].empty() &&
(paramInfo.acceptsUnlabeledTrailingClosureArgument(
idx) ||
backwardScanAcceptsTrailingClosure(params[idx]));
})) {
haveUnfulfilledParams = true;
return;
}
// If one or more parameters can match the closure, let's check
// whether backward scan is applicable here.
}
// If this parameter does not require an argument, consider applying a
// backward-match rule that skips this parameter if doing so is the only
// way to successfully match arguments to parameters.
if (!parameterRequiresArgument(params, paramInfo, paramIdx) &&
anyParameterRequiresArgument(
params, paramInfo, paramIdx + 1,
nextArgIdx + 1 < numArgs
? std::optional<Identifier>(args[nextArgIdx + 1].getLabel())
: std::optional<Identifier>(std::nullopt))) {
haveUnfulfilledParams = true;
return;
}
// The argument is unlabeled, so mark the parameter as unlabeled as
// well.
paramLabel = Identifier();
}
// Handle variadic parameters.
if (param.isVariadic() || isPackExpansionType(param.getPlainType())) {
// Claim the next argument with the name of this parameter.
auto claimed =
claimNextNamed(nextArgIdx, paramLabel, ignoreNameMismatch);
// If there was no such argument, leave the parameter unfulfilled.
if (!claimed) {
haveUnfulfilledParams = true;
return;
}
// Record the first argument for the variadic.
parameterBindings[paramIdx].push_back(*claimed);
auto currentNextArgIdx = nextArgIdx;
{
nextArgIdx = *claimed;
// Claim any additional unnamed arguments.
while (true) {
// If the next argument is the unlabeled trailing closure and the
// variadic parameter does not accept the unlabeled trailing closure
// argument, we're done.
if (trailingClosureMatching == TrailingClosureMatching::Forward &&
unlabeledTrailingClosureArgIndex &&
skipClaimedArgs(nextArgIdx)
== *unlabeledTrailingClosureArgIndex &&
!paramInfo.acceptsUnlabeledTrailingClosureArgument(paramIdx))
break;
if ((claimed = claimNextNamed(nextArgIdx, Identifier(), false, true)))
parameterBindings[paramIdx].push_back(*claimed);
else
break;
}
}
nextArgIdx = currentNextArgIdx;
return;
}
// Try to claim an argument for this parameter.
if (auto claimed =
claimNextNamed(nextArgIdx, paramLabel, ignoreNameMismatch)) {
parameterBindings[paramIdx].push_back(*claimed);
return;
}
// There was no argument to claim. Leave the argument unfulfilled.
haveUnfulfilledParams = true;
};
// If we have an unlabeled trailing closure and are matching backward, match
// the trailing closure argument near the end.
if (unlabeledTrailingClosureArgIndex &&
trailingClosureMatching == TrailingClosureMatching::Backward) {
assert(!claimedArgs[*unlabeledTrailingClosureArgIndex]);
// One past the next parameter index to look at.
unsigned prevParamIdx = numParams;
// Scan backwards from the end to match the unlabeled trailing closure.
std::optional<unsigned> unlabeledParamIdx;
if (prevParamIdx > 0) {
unsigned paramIdx = prevParamIdx - 1;
bool lastAcceptsTrailingClosure =
backwardScanAcceptsTrailingClosure(params[paramIdx]);
// If the last parameter is defaulted, this might be
// an attempt to use a trailing closure with previous
// parameter that accepts a function type e.g.
//
// func foo(_: () -> Int, _ x: Int = 0) {}
// foo { 42 }
if (!lastAcceptsTrailingClosure && paramIdx > 0 &&
paramInfo.hasDefaultArgument(paramIdx)) {
auto paramType = params[paramIdx - 1].getPlainType();
// If the parameter before defaulted last accepts.
if (paramType->is<AnyFunctionType>()) {
lastAcceptsTrailingClosure = true;
paramIdx -= 1;
}
}
if (lastAcceptsTrailingClosure)
unlabeledParamIdx = paramIdx;
}
// Trailing closure argument couldn't be matched to anything. Fail fast.
if (!unlabeledParamIdx) {
return true;
}
// Claim the parameter/argument pair.
claim(
params[*unlabeledParamIdx].getLabel(),
*unlabeledTrailingClosureArgIndex,
/*ignoreNameClash=*/true);
parameterBindings[*unlabeledParamIdx].push_back(
*unlabeledTrailingClosureArgIndex);
}
{
unsigned nextArgIdx = 0;
// Mark through the parameters, binding them to their arguments.
for (auto paramIdx : indices(params)) {
if (parameterBindings[paramIdx].empty())
bindNextParameter(paramIdx, nextArgIdx, false);
}
}
// If we have any unclaimed arguments, complain about those.
if (numClaimedArgs != numArgs) {
// Find all of the named, unclaimed arguments.
llvm::SmallVector<unsigned, 4> unclaimedNamedArgs;
for (auto argIdx : indices(args)) {
if (claimedArgs[argIdx]) continue;
if (!listener.shouldClaimArgDuringRecovery(argIdx))
continue;
if (!args[argIdx].getLabel().empty())
unclaimedNamedArgs.push_back(argIdx);
}
if (!unclaimedNamedArgs.empty()) {
// Find all of the named, unfulfilled parameters.
llvm::SmallVector<unsigned, 4> unfulfilledNamedParams;
bool hasUnfulfilledUnnamedParams = false;
for (auto paramIdx : indices(params)) {
if (parameterBindings[paramIdx].empty()) {
if (params[paramIdx].getLabel().empty())
hasUnfulfilledUnnamedParams = true;
else
unfulfilledNamedParams.push_back(paramIdx);
}
}
if (!unfulfilledNamedParams.empty()) {
// Use typo correction to find the best matches.
// FIXME: There is undoubtedly a good dynamic-programming algorithm
// to find the best assignment here.
for (auto argIdx : unclaimedNamedArgs) {
auto argName = args[argIdx].getLabel();
// Find the closest matching unfulfilled named parameter.
unsigned bestScore = 0;
unsigned best = 0;
for (auto i : indices(unfulfilledNamedParams)) {
unsigned param = unfulfilledNamedParams[i];
auto paramName = params[param].getLabel();
if (auto score = scoreParamAndArgNameTypo(paramName.str(),
argName.str(),
bestScore)) {
if (*score < bestScore || bestScore == 0) {
bestScore = *score;
best = i;
}
}
}
// If we found a parameter to fulfill, do it.
if (bestScore > 0) {
// Bind this parameter to the argument.
auto paramIdx = unfulfilledNamedParams[best];
auto paramLabel = params[paramIdx].getLabel();
parameterBindings[paramIdx].push_back(claim(paramLabel, argIdx));
// Erase this parameter from the list of unfulfilled named
// parameters, so we don't try to fulfill it again.
unfulfilledNamedParams.erase(unfulfilledNamedParams.begin() + best);
if (unfulfilledNamedParams.empty())
break;
}
}
// Update haveUnfulfilledParams, because we may have fulfilled some
// parameters above.
haveUnfulfilledParams = hasUnfulfilledUnnamedParams ||
!unfulfilledNamedParams.empty();
}
}
// Find all of the unfulfilled parameters, and match them up
// semi-positionally.
if (numClaimedArgs != numArgs) {
// Restart at the first argument/parameter.
unsigned nextArgIdx = 0;
haveUnfulfilledParams = false;
for (auto paramIdx : indices(params)) {
// Skip fulfilled parameters.
if (!parameterBindings[paramIdx].empty())
continue;
bindNextParameter(paramIdx, nextArgIdx, true);
if (!listener.shouldClaimArgDuringRecovery(nextArgIdx))
continue;
}
}
// If there are as many arguments as parameters but we still
// haven't claimed all of the arguments, it could mean that
// labels don't line up, if so let's try to claim arguments
// with incorrect labels, and let OoO/re-labeling logic diagnose that.
if (numArgs == numParams && numClaimedArgs != numArgs) {
for (auto i : indices(args)) {
if (claimedArgs[i] || !parameterBindings[i].empty())
continue;
// If parameter has a default value, we don't really
// know if label doesn't match because it's incorrect
// or argument belongs to some other parameter, so
// we just leave this parameter unfulfilled.
if (paramInfo.hasDefaultArgument(i))
continue;
if (!listener.shouldClaimArgDuringRecovery(i))
continue;
// Looks like there was no parameter claimed at the same
// position, it could only mean that label is completely
// different, because typo correction has been attempted already.
parameterBindings[i].push_back(claim(params[i].getLabel(), i));
}
}
// If we still haven't claimed all of the arguments,
// fail if there is no recovery.
if (numClaimedArgs != numArgs) {
for (auto index : indices(claimedArgs)) {
if (claimedArgs[index])
continue;
if (listener.extraArgument(index))
return true;
}
}
// FIXME: If we had the actual parameters and knew the body names, those
// matches would be best.
potentiallyOutOfOrder = true;
}
// If we have any unfulfilled parameters, check them now.
std::optional<unsigned> prevArgIdx;
if (haveUnfulfilledParams) {
for (auto paramIdx : indices(params)) {
// If we have a binding for this parameter, we're done.
if (!parameterBindings[paramIdx].empty()) {
prevArgIdx = parameterBindings[paramIdx].back();
continue;
}
const auto ¶m = params[paramIdx];
// Variadic parameters can be unfulfilled.
if (param.isVariadic() || isPackExpansionType(param.getPlainType()))
continue;
// Parameters with defaults can be unfulfilled.
if (paramInfo.hasDefaultArgument(paramIdx))
continue;
unsigned argInsertIdx = prevArgIdx ? *prevArgIdx + 1 : 0;
if (auto newArgIdx = listener.missingArgument(paramIdx, argInsertIdx)) {
parameterBindings[paramIdx].push_back(*newArgIdx);
continue;
}
return true;
}
}
// If any arguments were provided out-of-order, check whether we have
// violated any of the reordering rules.
if (potentiallyOutOfOrder) {
// If we've seen label failures and now there is an out-of-order
// parameter (or even worse - OoO parameter with label re-naming),
// we most likely have no idea what would be the best
// diagnostic for this situation, so let's just try to re-label.
auto isOutOfOrderArgument = [&](unsigned toParamIdx, unsigned fromArgIdx,
unsigned toArgIdx) {
if (fromArgIdx <= toArgIdx) {
return false;
}
auto newLabel = args[fromArgIdx].getLabel();
auto oldLabel = args[toArgIdx].getLabel();
if (newLabel != params[toParamIdx].getLabel()) {
return false;
}
auto paramIdx = toParamIdx + 1;
for (; paramIdx < params.size(); ++paramIdx) {
// Looks like new position (excluding defaulted parameters),
// has a valid label.
if (oldLabel == params[paramIdx].getLabel())
break;
// If we are moving the position with a different label
// and there is no default value for it, can't diagnose the
// problem as a simple re-ordering.
if (!paramInfo.hasDefaultArgument(paramIdx))
return false;
}
// label was not found
if (paramIdx == params.size()) {
return false;
}
return true;
};
SmallVector<unsigned, 4> paramToArgMap;
paramToArgMap.reserve(params.size());
{
unsigned argIdx = 0;
for (const auto &binding : parameterBindings) {
paramToArgMap.push_back(argIdx);
// Ignore argument bindings that were synthesized due to missing args.
argIdx += llvm::count_if(
binding, [numArgs](unsigned argIdx) { return argIdx < numArgs; });
}
}
// Enumerate the parameters and their bindings to see if any arguments are
// our of order
bool hadLabelMismatch = false;
for (const auto paramIdx : indices(params)) {
const auto toArgIdx = paramToArgMap[paramIdx];
const auto &binding = parameterBindings[paramIdx];
for (const auto paramBindIdx : indices(binding)) {
// We've found the parameter that has an out of order
// argument, and know the indices of the argument that
// needs to move (fromArgIdx) and the argument location
// it should move to (toArgIdx).
const auto fromArgIdx = binding[paramBindIdx];
// Ignore argument bindings that were synthesized due to missing args.
if (fromArgIdx >= numArgs)
continue;
// Does nothing for variadic tail.
if ((params[paramIdx].isVariadic() ||
isPackExpansionType(params[paramIdx].getPlainType())) &&
paramBindIdx > 0) {
assert(args[fromArgIdx].getLabel().empty());
continue;
}
// First let's double check if out-of-order argument is nothing
// more than a simple label mismatch, because in situation where
// one argument requires label and another one doesn't, but caller
// doesn't provide either, problem is going to be identified as
// out-of-order argument instead of label mismatch.
const auto expectedLabel =
fromArgIdx == unlabeledTrailingClosureArgIndex
? Identifier()
: params[paramIdx].getLabel();
const auto argumentLabel = args[fromArgIdx].getLabel();
if (argumentLabel != expectedLabel) {
// - The parameter is unnamed, in which case we try to fix the
// problem by removing the name.
if (expectedLabel.empty()) {
hadLabelMismatch = true;
if (listener.extraneousLabel(paramIdx))
return true;
// - The argument is unnamed, in which case we try to fix the
// problem by adding the name.
} else if (argumentLabel.empty()) {
hadLabelMismatch = true;
if (listener.missingLabel(paramIdx))
return true;
// - The argument label has a typo at the same position.
} else if (fromArgIdx == toArgIdx) {
hadLabelMismatch = true;
if (listener.incorrectLabel(paramIdx))
return true;
}
}
if (fromArgIdx == toArgIdx) {
// If the argument is in the right location, just continue
continue;
}
// This situation looks like out-of-order argument but it's hard
// to say exactly without considering other factors, because it
// could be invalid labeling too.
if (!hadLabelMismatch &&
isOutOfOrderArgument(paramIdx, fromArgIdx, toArgIdx)) {
return listener.outOfOrderArgument(
fromArgIdx, toArgIdx, parameterBindings);
}
SmallVector<Identifier, 8> expectedLabels;
llvm::transform(params, std::back_inserter(expectedLabels),
[](const AnyFunctionType::Param ¶m) {
return param.getLabel();
});
return listener.relabelArguments(expectedLabels);
}
}
}
// If no arguments were renamed, the call arguments match up with the
// parameters.
if (actualArgNames.empty())
return false;
// The arguments were relabeled; notify the listener.
return listener.relabelArguments(actualArgNames);
}
/// Determine whether call-argument matching requires us to try both the
/// forward and backward scanning directions to succeed.
static bool requiresBothTrailingClosureDirections(
ArrayRef<AnyFunctionType::Param> args,
ArrayRef<AnyFunctionType::Param> params, const ParameterListInfo ¶mInfo,
std::optional<unsigned> unlabeledTrailingClosureArgIndex) {
// If there's no unlabeled trailing closure, direction doesn't matter.
if (!unlabeledTrailingClosureArgIndex)
return false;
// If there are labeled trailing closure arguments, only scan forward.
if (*unlabeledTrailingClosureArgIndex < args.size() - 1)
return false;
// If there are no parameters, it doesn't matter; only scan forward.
if (params.empty())
return false;
// If backward matching is disabled, only scan forward.
ASTContext &ctx = params.front().getPlainType()->getASTContext();
if (ctx.LangOpts.hasFeature(Feature::ForwardTrailingClosures))
return false;
// If there are at least two parameters that meet the backward scan's
// definition of "accepts trailing closure", or there is one such parameter
// with a defaulted parameter after it, we'll need to do the scan
// in both directions.
bool sawAnyTrailingClosureParam = false;
for (unsigned paramIdx : indices(params)) {
const auto ¶m = params[paramIdx];
if (backwardScanAcceptsTrailingClosure(param)) {
if (sawAnyTrailingClosureParam)
return true;
sawAnyTrailingClosureParam = true;
continue;
}
if (sawAnyTrailingClosureParam && paramInfo.hasDefaultArgument(paramIdx))
return true;
}
// Only one parameter can match the trailing closure anyway, so don't bother
// scanning twice.
return false;
}
std::optional<MatchCallArgumentResult> constraints::matchCallArguments(
SmallVectorImpl<AnyFunctionType::Param> &args,
ArrayRef<AnyFunctionType::Param> params, const ParameterListInfo ¶mInfo,
std::optional<unsigned> unlabeledTrailingClosureArgIndex, bool allowFixes,
MatchCallArgumentListener &listener,
std::optional<TrailingClosureMatching> trailingClosureMatching) {
/// Perform a single call to the implementation of matchCallArguments,
/// invoking the listener and using the results from that match.
auto singleMatchCall = [&](TrailingClosureMatching scanDirection)
-> std::optional<MatchCallArgumentResult> {
SmallVector<ParamBinding, 4> paramBindings;
if (matchCallArgumentsImpl(
args, params, paramInfo, unlabeledTrailingClosureArgIndex,
allowFixes, scanDirection, listener, paramBindings))
return std::nullopt;
return MatchCallArgumentResult{scanDirection, std::move(paramBindings),
std::nullopt};
};
// If we know that we won't have to perform both forward and backward
// scanning for trailing closures, fast-path by performing just the
// appropriate scan.
if (trailingClosureMatching ||
!requiresBothTrailingClosureDirections(
args, params, paramInfo, unlabeledTrailingClosureArgIndex)) {
return singleMatchCall(
trailingClosureMatching.value_or(TrailingClosureMatching::Forward));
}
MatchCallArgumentListener noOpListener;
// Try the forward direction first.
SmallVector<ParamBinding, 4> forwardParamBindings;
bool forwardFailed = matchCallArgumentsImpl(
args, params, paramInfo, unlabeledTrailingClosureArgIndex, allowFixes,
TrailingClosureMatching::Forward, noOpListener, forwardParamBindings);
// Try the backward direction.
SmallVector<ParamBinding, 4> backwardParamBindings;
bool backwardFailed = matchCallArgumentsImpl(
args, params, paramInfo, unlabeledTrailingClosureArgIndex, allowFixes,
TrailingClosureMatching::Backward, noOpListener, backwardParamBindings);
// If at least one of them failed, or they produced the same results, run
// call argument matching again with the real visitor.
if (forwardFailed || backwardFailed ||
forwardParamBindings == backwardParamBindings) {
// Run the forward scan unless the backward scan is the only one that
// succeeded.
auto scanDirection = backwardFailed || !forwardFailed
? TrailingClosureMatching::Forward
: TrailingClosureMatching::Backward;
return singleMatchCall(scanDirection);
}
// Both forward and backward succeeded, and produced different results.
// Bundle them up and return both---without invoking the listener---so the
// solver can choose.
return MatchCallArgumentResult{
TrailingClosureMatching::Forward,
std::move(forwardParamBindings),
std::move(backwardParamBindings)
};
}
bool CompletionArgInfo::allowsMissingArgAt(unsigned argInsertIdx,
AnyFunctionType::Param param) {
// If the argument is before or at the index of the argument containing the
// completion, the user would likely have already written it if they
// intended this overload.
if (completionIdx >= argInsertIdx) {
return false;
}
// If the argument is after the first trailing closure, the user can only
// continue on to write more trailing arguments, so only allow this overload
// if the missing argument is of function type.
if (firstTrailingIdx && argInsertIdx > *firstTrailingIdx) {
if (param.isInOut()) {
return false;
}
Type expectedTy = param.getPlainType()->lookThroughAllOptionalTypes();
return expectedTy->is<FunctionType>() || expectedTy->isAny() ||
expectedTy->isTypeVariableOrMember();
}
return true;
}
std::optional<CompletionArgInfo>
constraints::getCompletionArgInfo(ASTNode anchor, ConstraintSystem &CS) {
auto *exprAnchor = getAsExpr(anchor);
if (!exprAnchor)
return std::nullopt;
auto *args = exprAnchor->getArgs();
if (!args)
return std::nullopt;
for (unsigned i : indices(*args)) {
if (CS.containsIDEInspectionTarget(args->getExpr(i)))
return CompletionArgInfo{i, args->getFirstTrailingClosureIndex(),
args->size()};
}
return std::nullopt;
}
class ArgumentFailureTracker : public MatchCallArgumentListener {
protected:
ConstraintSystem &CS;
NullablePtr<ValueDecl> Callee;
SmallVectorImpl<AnyFunctionType::Param> &Arguments;
ArrayRef<AnyFunctionType::Param> Parameters;
std::optional<unsigned> UnlabeledTrailingClosureArgIndex;
ConstraintLocatorBuilder Locator;
private:
SmallVector<SynthesizedArg, 4> MissingArguments;
SmallVector<std::pair<unsigned, AnyFunctionType::Param>, 4> ExtraArguments;
protected:
/// Synthesizes an argument that is intended to match against a missing
/// argument for the parameter at \p paramIdx.
/// \returns The index of the new argument in \c Arguments.
unsigned synthesizeArgument(unsigned paramIdx,
bool isAfterCodeCompletionLoc) {
const auto ¶m = Parameters[paramIdx];
unsigned newArgIdx = Arguments.size();
auto *argLoc = CS.getConstraintLocator(
Locator, {LocatorPathElt::ApplyArgToParam(newArgIdx, paramIdx,
param.getParameterFlags()),
LocatorPathElt::SynthesizedArgument(
newArgIdx, isAfterCodeCompletionLoc)});
auto *argType = CS.createTypeVariable(
argLoc, TVO_CanBindToInOut | TVO_CanBindToLValue |
TVO_CanBindToNoEscape | TVO_CanBindToHole);
auto synthesizedArg = param.withType(argType);
Arguments.push_back(synthesizedArg);
return newArgIdx;
}
public:
ArgumentFailureTracker(
ConstraintSystem &cs, ValueDecl *callee,
SmallVectorImpl<AnyFunctionType::Param> &args,
ArrayRef<AnyFunctionType::Param> params,
std::optional<unsigned> unlabeledTrailingClosureArgIndex,
ConstraintLocatorBuilder locator)
: CS(cs), Callee(callee), Arguments(args), Parameters(params),
UnlabeledTrailingClosureArgIndex(unlabeledTrailingClosureArgIndex),
Locator(locator) {}
~ArgumentFailureTracker() override {
if (!MissingArguments.empty()) {
auto *fix = AddMissingArguments::create(CS, MissingArguments,
CS.getConstraintLocator(Locator));
// Not having an argument is the same impact as having a type mismatch.
(void)CS.recordFix(fix, /*impact=*/MissingArguments.size() * 2);
}
}
std::optional<unsigned> missingArgument(unsigned paramIdx,
unsigned argInsertIdx) override {
if (!CS.shouldAttemptFixes())
return std::nullopt;
unsigned newArgIdx =
synthesizeArgument(paramIdx, /*isAfterCodeCompletionLoc=*/false);
auto synthesizedArg = Arguments[newArgIdx];
MissingArguments.push_back(SynthesizedArg{paramIdx, synthesizedArg});
return newArgIdx;
}
bool extraArgument(unsigned argIdx) override {
if (!CS.shouldAttemptFixes())
return true;
// If this is a trailing closure, let's check if the call is
// to an init of a callable type. If so, let's not record it
// as extraneous since it would be matched against implicitly
// injected `.callAsFunction` call.
if (UnlabeledTrailingClosureArgIndex &&
argIdx == *UnlabeledTrailingClosureArgIndex && Callee) {
if (auto *ctor = dyn_cast<ConstructorDecl>(Callee.get())) {
auto resultTy = ctor->getResultInterfaceType();
if (resultTy->isCallAsFunctionType(CS.DC))
return true;
}
}
ExtraArguments.push_back(std::make_pair(argIdx, Arguments[argIdx]));
return false;
}
bool missingLabel(unsigned paramIndex) override {
return !CS.shouldAttemptFixes();
}
bool extraneousLabel(unsigned paramIndex) override {
return !CS.shouldAttemptFixes();
}
bool incorrectLabel(unsigned paramIndex) override {
return !CS.shouldAttemptFixes();
}
bool outOfOrderArgument(
unsigned argIdx, unsigned prevArgIdx,
ArrayRef<ParamBinding> bindings) override {
if (CS.shouldAttemptFixes()) {
// If some of the arguments are missing/extraneous, no reason to
// record a fix for this, increase the score so there is a way
// to identify that there is something going on besides just missing
// arguments.
if (!MissingArguments.empty() || !ExtraArguments.empty()) {
CS.increaseScore(SK_Fix, Locator);
return false;
}
auto *fix = MoveOutOfOrderArgument::create(
CS, argIdx, prevArgIdx, bindings, CS.getConstraintLocator(Locator));
return CS.recordFix(fix);
}
return true;
}
bool relabelArguments(ArrayRef<Identifier> newLabels) override {
if (!CS.shouldAttemptFixes())
return true;
// TODO(diagnostics): If re-labeling is mixed with extra arguments,
// let's produce a fix only for extraneous arguments for now,
// because they'd share a locator path which (currently) means
// one fix would overwrite another.
if (!ExtraArguments.empty()) {
CS.increaseScore(SK_Fix, Locator);
return false;
}
auto anchor = Locator.getBaseLocator()->getAnchor();
if (!anchor)
return true;
unsigned numExtraneous = 0;
unsigned numRenames = 0;
unsigned numOutOfOrder = 0;
for (unsigned i : indices(newLabels)) {
// It's already known how many arguments are missing,
// it would be accounted for in the impact.
if (i >= Arguments.size())
continue;
auto argLabel = Arguments[i].getLabel();
auto paramLabel = newLabels[i];
if (argLabel == paramLabel)
continue;
if (!argLabel.empty()) {
// Instead of this being a label mismatch which requires
// re-labeling, this could be an out-of-order argument
// instead which has a completely different impact.
if (llvm::count(newLabels, argLabel) == 1) {
++numOutOfOrder;
} else if (paramLabel.empty()) {
++numExtraneous;
} else {
++numRenames;
}
}
}
auto *locator = CS.getConstraintLocator(Locator);
auto *fix = RelabelArguments::create(CS, newLabels, locator);
// Re-labeling fixes with extraneous/incorrect labels should be
// lower priority vs. other fixes on same/different overload(s)
// where labels did line up correctly.
//
// If there are not only labeling problems but also some of the
// arguments are missing, let's account of that in the impact.
auto impact = 1 + numOutOfOrder + numExtraneous * 2 + numRenames * 3 +
MissingArguments.size() * 2;
return CS.recordFix(fix, impact);
}
ArrayRef<std::pair<unsigned, AnyFunctionType::Param>>
getExtraneousArguments() const {
return ExtraArguments;
}
};
/// Ignores any failures after the code completion token.
class CompletionArgumentTracker : public ArgumentFailureTracker {
struct CompletionArgInfo ArgInfo;
public:
CompletionArgumentTracker(
ConstraintSystem &cs, ValueDecl *callee,
SmallVectorImpl<AnyFunctionType::Param> &args,
ArrayRef<AnyFunctionType::Param> params,
std::optional<unsigned> unlabeledTrailingClosureArgIndex,
ConstraintLocatorBuilder locator, struct CompletionArgInfo ArgInfo)
: ArgumentFailureTracker(cs, callee, args, params,
unlabeledTrailingClosureArgIndex, locator),
ArgInfo(ArgInfo) {}
std::optional<unsigned> missingArgument(unsigned paramIdx,
unsigned argInsertIdx) override {
// When solving for code completion, if any argument contains the
// completion location, later arguments shouldn't be considered missing
// (causing the solution to have a worse score) as the user just hasn't
// written them yet. Early exit to avoid recording them in this case.
if (ArgInfo.allowsMissingArgAt(argInsertIdx, Parameters[paramIdx])) {
return synthesizeArgument(paramIdx, /*isAfterCodeCompletionLoc=*/true);
}
return ArgumentFailureTracker::missingArgument(paramIdx, argInsertIdx);
}
bool extraArgument(unsigned argIdx) override {
if (ArgInfo.isBefore(argIdx)) {
return false;
}
if (argIdx == 0 && ArgInfo.completionIdx == 0) {
return false;
}
return ArgumentFailureTracker::extraArgument(argIdx);
}
bool outOfOrderArgument(unsigned argIdx, unsigned prevArgIdx,
ArrayRef<ParamBinding> bindings) override {
if (ArgInfo.isBefore(argIdx)) {
return false;
}
return ArgumentFailureTracker::outOfOrderArgument(argIdx, prevArgIdx,
bindings);
}
bool shouldClaimArgDuringRecovery(unsigned argIdx) override {
return !ArgInfo.isBefore(argIdx);
}
bool
canClaimArgIgnoringNameMismatch(const AnyFunctionType::Param &arg) override {
if (!isCodeCompletionTypeVar(arg.getPlainType())) {
return false;
}
if (!arg.getLabel().empty()) {
return false;
}
return true;
}
};
class AllowLabelMismatches : public MatchCallArgumentListener {
SmallVector<Identifier, 4> NewLabels;
bool HadLabelingIssues = false;
public:
bool missingLabel(unsigned paramIndex) override {
HadLabelingIssues = true;
return false;
}
bool relabelArguments(ArrayRef<Identifier> newLabels) override {
NewLabels.append(newLabels.begin(), newLabels.end());
HadLabelingIssues = true;
return false;
}
bool hadLabelingIssues() const { return HadLabelingIssues; }
std::optional<ArrayRef<Identifier>> getLabelReplacements() const {
if (!hadLabelingIssues() || NewLabels.empty())
return std::nullopt;
return {NewLabels};
}
};
namespace {
/// Flags that should be applied to the existential argument type after
/// opening.
enum class OpenedExistentialAdjustmentFlags {
/// The argument should be made inout after opening.
InOut = 0x01,
LValue = 0x02,
};
using OpenedExistentialAdjustments =
OptionSet<OpenedExistentialAdjustmentFlags>;
}
/// Determine whether we should open up the existential argument to the
/// given parameters.
///
/// \param callee The function or subscript being called.
/// \param paramIdx The index specifying which function parameter is being
/// initialized.
/// \param paramTy The type of the parameter as it was opened in the constraint
/// system.
/// \param argTy The type of the argument.
///
/// \returns If the argument type is existential and opening it can bind a
/// generic parameter in the callee, returns the generic parameter, type
/// variable (from the opened parameter type) the existential type that needs
/// to be opened (from the argument type), and the adjustments that need to be
/// applied to the existential type after it is opened.
static std::optional<std::tuple<GenericTypeParamType *, TypeVariableType *,
Type, OpenedExistentialAdjustments>>
shouldOpenExistentialCallArgument(ValueDecl *callee, unsigned paramIdx,
Type paramTy, Type argTy, Expr *argExpr,
ConstraintSystem &cs) {
if (!callee)
return std::nullopt;
// Only applies to functions and subscripts.
if (!isa<AbstractFunctionDecl>(callee) && !isa<SubscriptDecl>(callee))
return std::nullopt;
// Special semantics prohibit opening existentials.
switch (TypeChecker::getDeclTypeCheckingSemantics(callee)) {
case DeclTypeCheckingSemantics::OpenExistential:
case DeclTypeCheckingSemantics::TypeOf:
// type(of:) and _openExistential handle their own opening.
return std::nullopt;
case DeclTypeCheckingSemantics::Normal:
case DeclTypeCheckingSemantics::WithoutActuallyEscaping:
break;
}
// C++ function templates require specialization, which is not possible with
// opened existential archetypes, so do not open.
if (isa_and_nonnull<clang::FunctionTemplateDecl>(callee->getClangDecl()))
return std::nullopt;
// The actual parameter type needs to involve a type variable, otherwise
// type inference won't be possible.
if (!paramTy->hasTypeVariable())
return std::nullopt;
// An argument expression that explicitly coerces to an existential
// disables the implicit opening of the existential unless it's
// wrapped in parens.
if (argExpr) {
if (auto argCast = dyn_cast<ExplicitCastExpr>(
argExpr->getSemanticsProvidingExpr())) {
if (auto typeRepr = argCast->getCastTypeRepr()) {
if (auto toType = cs.getType(typeRepr)) {
if (!isa<ParenExpr>(argExpr) && toType->isAnyExistentialType())
return std::nullopt;
}
}
}
}
OpenedExistentialAdjustments adjustments;
// The argument may be a "var" instead of a "let".
if (auto lv = argTy->getAs<LValueType>()) {
argTy = lv->getObjectType();
adjustments |= OpenedExistentialAdjustmentFlags::LValue;
}
// If the argument is inout, strip it off and we can add it back.
if (auto inOutArg = argTy->getAs<InOutType>()) {
argTy = inOutArg->getObjectType();
adjustments |= OpenedExistentialAdjustmentFlags::InOut;
}
// The argument type needs to be an existential type or metatype thereof.
if (!argTy->isAnyExistentialType())
return std::nullopt;
auto param = getParameterAt(callee, paramIdx);
if (!param)
return std::nullopt;
// If the parameter is non-generic variadic, don't open.
if (param->isVariadic())
return std::nullopt;
// Look through an inout and optional types on the formal type of the
// parameter.
auto formalParamTy = param->getInterfaceType()->getInOutObjectType()
->lookThroughSingleOptionalType();
// If the argument is of an existential metatype, look through the
// metatype on the parameter.
if (argTy->is<AnyMetatypeType>()) {
formalParamTy = formalParamTy->getMetatypeInstanceType();
paramTy = paramTy->getMetatypeInstanceType();
}
// Look through an inout and optional types on the parameter.
paramTy = paramTy->getInOutObjectType()->lookThroughSingleOptionalType();
// The parameter type must be a type variable.
auto paramTypeVar = paramTy->getAs<TypeVariableType>();
if (!paramTypeVar)
return std::nullopt;
auto genericParam = formalParamTy->getAs<GenericTypeParamType>();
if (!genericParam)
return std::nullopt;
// Only allow opening the innermost generic parameters.
auto genericContext = callee->getAsGenericContext();
if (!genericContext || !genericContext->isGeneric())
return std::nullopt;
auto genericSig = callee->getInnermostDeclContext()
->getGenericSignatureOfContext().getCanonicalSignature();
if (genericParam->getDepth() <
genericSig.getGenericParams().back()->getDepth())
return std::nullopt;
// If the existential argument conforms to all of protocol requirements on
// the formal parameter's type, don't open unless ImplicitOpenExistentials is
// enabled.
// If all of the conformance requirements on the formal parameter's type
// are self-conforming, don't open.
ASTContext &ctx = argTy->getASTContext();
if (!ctx.LangOpts.hasFeature(Feature::ImplicitOpenExistentials)) {
Type existentialObjectType;
if (auto existentialMetaTy = argTy->getAs<ExistentialMetatypeType>())
existentialObjectType = existentialMetaTy->getInstanceType();
else
existentialObjectType = argTy;
auto module = cs.DC->getParentModule();
bool containsNonSelfConformance = false;
for (auto proto : genericSig->getRequiredProtocols(genericParam)) {
auto conformance = module->lookupExistentialConformance(
existentialObjectType, proto);
if (conformance.isInvalid()) {
containsNonSelfConformance = true;
break;
}
}
if (!containsNonSelfConformance)
return std::nullopt;
}
// Ensure that the formal parameter is only used in covariant positions,
// because it won't match anywhere else.
auto referenceInfo = findGenericParameterReferences(
callee, genericSig, genericParam,
/*treatNonResultCovarianceAsInvariant=*/false,
/*skipParamIdx=*/paramIdx);
if (referenceInfo.selfRef > TypePosition::Covariant ||
referenceInfo.assocTypeRef > TypePosition::Covariant)
return std::nullopt;
return std::make_tuple(genericParam, paramTypeVar, argTy, adjustments);
}
// Match the argument of a call to the parameter.
static ConstraintSystem::TypeMatchResult matchCallArguments(
ConstraintSystem &cs, FunctionType *contextualType, ArgumentList *argList,
ArrayRef<AnyFunctionType::Param> args,
ArrayRef<AnyFunctionType::Param> params, ConstraintKind subKind,
ConstraintLocatorBuilder locator,
std::optional<TrailingClosureMatching> trailingClosureMatching,
SmallVectorImpl<std::pair<TypeVariableType *, OpenedArchetypeType *>>
&openedExistentials) {
assert(subKind == ConstraintKind::OperatorArgumentConversion ||
subKind == ConstraintKind::ArgumentConversion);
auto *loc = cs.getConstraintLocator(locator);
assert(loc->isLastElement<LocatorPathElt::ApplyArgument>());
ValueDecl *callee = nullptr;
bool appliedSelf = false;
// Resolve the callee for the application.
auto *calleeLocator = cs.getCalleeLocator(loc);
if (auto overload = cs.findSelectedOverloadFor(calleeLocator)) {
callee = overload->choice.getDeclOrNull();
appliedSelf = hasAppliedSelf(cs, overload->choice);
}
ParameterListInfo paramInfo(params, callee, appliedSelf);
// Make sure that argument list is available.
assert(argList);
// Apply labels to arguments.
SmallVector<AnyFunctionType::Param, 8> argsWithLabels;
argsWithLabels.append(args.begin(), args.end());
AnyFunctionType::relabelParams(argsWithLabels, argList);
// Special case when a single tuple argument if used
// instead of N distinct arguments e.g.:
//
// func foo(_ x: Int, _ y: Int) {}
// foo((1, 2)) // expected 2 arguments, got a single tuple with 2 elements.
if (cs.shouldAttemptFixes() && argsWithLabels.size() == 1 &&
llvm::count_if(indices(params), [&](unsigned paramIdx) {
return !paramInfo.hasDefaultArgument(paramIdx);
}) > 1) {
const auto &arg = argsWithLabels.front();
auto argTuple = arg.getPlainType()->getRValueType()->getAs<TupleType>();
// Don't explode a tuple in cases where first parameter is a tuple as
// well. That is a regular "missing argument case" even if their arity
// is different e.g.
//
// func foo(_: (Int, Int), _: Int) {}
// foo((1, 2)) // call is missing an argument for parameter #1
if (argTuple && argTuple->getNumElements() == params.size() &&
!params.front().getPlainType()->is<TupleType>()) {
argsWithLabels.pop_back();
// Let's make sure that labels associated with tuple elements
// line up with what is expected by argument list.
SmallVector<SynthesizedArg, 4> synthesizedArgs;
for (unsigned i = 0, n = argTuple->getNumElements(); i != n; ++i) {
const auto &elt = argTuple->getElement(i);
// If tuple doesn't have a label for its first element
// and parameter does, let's assume parameter's label
// to aid argument matching. For example:
//
// \code
// func test(val: Int, _: String) {}
//
// test(val: (42, "")) // expands into `(val: 42, "")`
// \endcode
Identifier label = elt.getName();
if (i == 0 && !elt.hasName() && params[0].hasLabel()) {
label = params[0].getLabel();
}
AnyFunctionType::Param argument(elt.getType(), label);
synthesizedArgs.push_back(SynthesizedArg{i, argument});
argsWithLabels.push_back(argument);
}
(void)cs.recordFix(
AddMissingArguments::create(cs, synthesizedArgs,
cs.getConstraintLocator(locator)),
/*impact=*/synthesizedArgs.size() * 2);
}
}
// Match up the call arguments to the parameters.
SmallVector<ParamBinding, 4> parameterBindings;
TrailingClosureMatching selectedTrailingMatching =
TrailingClosureMatching::Forward;
{
std::unique_ptr<ArgumentFailureTracker> listener;
if (cs.isForCodeCompletion()) {
if (auto completionInfo = getCompletionArgInfo(locator.getAnchor(), cs)) {
listener = std::make_unique<CompletionArgumentTracker>(
cs, callee, argsWithLabels, params,
argList->getFirstTrailingClosureIndex(), locator, *completionInfo);
}
}
if (!listener) {
// We didn't create an argument tracker for code completion. Create a
// normal one.
listener = std::make_unique<ArgumentFailureTracker>(
cs, callee, argsWithLabels, params,
argList->getFirstTrailingClosureIndex(), locator);
}
auto callArgumentMatch = constraints::matchCallArguments(
argsWithLabels, params, paramInfo,
argList->getFirstTrailingClosureIndex(), cs.shouldAttemptFixes(),
*listener, trailingClosureMatching);
if (!callArgumentMatch)
return cs.getTypeMatchFailure(locator);
// If there are different results for both the forward and backward
// scans, return an ambiguity: the caller will need to build a
// disjunction.
if (callArgumentMatch->backwardParameterBindings) {
return cs.getTypeMatchAmbiguous();
}
selectedTrailingMatching = callArgumentMatch->trailingClosureMatching;
// Record the matching direction and parameter bindings used for this call.
cs.recordMatchCallArgumentResult(cs.getConstraintLocator(locator),
*callArgumentMatch);
// If there was a disjunction because both forward and backward were
// possible, increase the score for forward matches to bias toward the
// (source-compatible) backward matches. The compiler will produce a
// warning for such code.
if (trailingClosureMatching &&
*trailingClosureMatching == TrailingClosureMatching::Forward)
cs.increaseScore(SK_ForwardTrailingClosure, locator);
// Take the parameter bindings we selected.
parameterBindings = std::move(callArgumentMatch->parameterBindings);
auto extraArguments = listener->getExtraneousArguments();
if (!extraArguments.empty()) {
if (RemoveExtraneousArguments::isMinMaxNameShadowing(cs, locator))
return cs.getTypeMatchFailure(locator);
// First let's see whether this is a situation where a single
// parameter is a tuple, but N distinct arguments were passed in.
if (AllowTupleSplatForSingleParameter::attempt(
cs, argsWithLabels, params, parameterBindings, locator)) {
// Let's produce a generic "extraneous arguments"
// diagnostic otherwise.
auto *fix = RemoveExtraneousArguments::create(
cs, contextualType, extraArguments,
cs.getConstraintLocator(locator));
if (cs.recordFix(fix, /*impact=*/extraArguments.size() * 5))
return cs.getTypeMatchFailure(locator);
}
}
}
auto isSynthesizedArgument = [](const AnyFunctionType::Param &arg) -> bool {
if (auto *typeVar = arg.getPlainType()->getAs<TypeVariableType>()) {
auto *locator = typeVar->getImpl().getLocator();
return locator->isLastElement<LocatorPathElt::SynthesizedArgument>();
}
return false;
};
for (unsigned paramIdx = 0, numParams = parameterBindings.size();
paramIdx != numParams; ++paramIdx){
// Determine the parameter type.
const auto ¶m = params[paramIdx];
auto paramTy = param.getOldType();
// Type parameter packs ingest the entire set of argument bindings
// as a pack type.
//
// We pull these out special because variadic parameters ban lots of
// the more interesting typing constructs called out below like
// inout and @autoclosure.
if (paramInfo.isVariadicGenericParameter(paramIdx)) {
// If generic parameter comes from a variadic type declaration it's
// possible that it got specialized early and is no longer represented
// by a pack expansion type. For example, consider expression -
// `Test<Int>(42)` where `Test<each T>` and the initializer
// is declared as `init(_: repeat each T)`. Although declaration
// based information reports parameter at index 0 as variadic generic
// the call site specializes it to `Int`.
if (isPackExpansionType(paramTy)) {
SmallVector<Type, 2> argTypes;
for (auto argIdx : parameterBindings[paramIdx]) {
auto argType = argsWithLabels[argIdx].getPlainType();
argTypes.push_back(argType);
}
auto *argPack = PackType::get(cs.getASTContext(), argTypes);
auto argPackExpansion = [&]() {
if (argPack->getNumElements() == 1 &&
argPack->getElementType(0)->is<PackExpansionType>()) {
return argPack->getElementType(0)->castTo<PackExpansionType>();
}
return PackExpansionType::get(argPack, argPack);
}();
auto firstArgIdx =
argTypes.empty() ? paramIdx : parameterBindings[paramIdx].front();
cs.addConstraint(
subKind, argPackExpansion, paramTy,
locator.withPathElement(LocatorPathElt::ApplyArgToParam(
firstArgIdx, paramIdx, param.getParameterFlags())));
continue;
}
}
// If type inference from default arguments is enabled, let's
// add a constraint from the parameter if necessary, otherwise
// there is nothing to do but move to the next parameter.
if (parameterBindings[paramIdx].empty() && callee) {
// Type inference from default value expressions.
{
auto *paramList = getParameterList(callee);
if (!paramList)
continue;
// There is nothing to infer if parameter doesn't have any
// generic parameters in its type.
auto *PD = paramList->get(paramIdx);
if (!PD->getInterfaceType()->hasTypeParameter())
continue;
// The type of the default value is going to be determined
// based on a type deduced for the parameter at this call site.
if (PD->hasCallerSideDefaultExpr())
continue;
auto defaultExprType = PD->getTypeOfDefaultExpr();
// A caller side default.
if (!defaultExprType || defaultExprType->hasError())
continue;
// If this is just a regular default type that should
// work for all substitutions of generic parameter,
// let's continue.
if (defaultExprType->hasArchetype())
continue;
cs.addConstraint(
ConstraintKind::ArgumentConversion, paramTy, defaultExprType,
locator.withPathElement(LocatorPathElt::ApplyArgToParam(
paramIdx, paramIdx, param.getParameterFlags())));
}
continue;
}
// Compare each of the bound arguments for this parameter.
for (auto argIdx : parameterBindings[paramIdx]) {
auto loc = locator.withPathElement(LocatorPathElt::ApplyArgToParam(
argIdx, paramIdx, param.getParameterFlags()));
const auto &argument = argsWithLabels[argIdx];
auto argTy = argument.getOldType();
bool matchingAutoClosureResult = param.isAutoClosure();
auto *argExpr = getArgumentExpr(locator.getAnchor(), argIdx);
if (param.isAutoClosure() && !isSynthesizedArgument(argument)) {
auto &ctx = cs.getASTContext();
// If this is a call to a function with a closure argument and the
// parameter is an autoclosure, let's just increment the score here
// so situations like below are not ambiguous.
// func f<T>(_: () -> T) {}
// func f<T>(_: @autoclosure () -> T) {}
//
// f { } // OK
if (isExpr<ClosureExpr>(argExpr)) {
cs.increaseScore(SK_FunctionToAutoClosureConversion, loc);
}
// If the argument is not marked as @autoclosure or
// this is Swift version >= 5 where forwarding is not allowed,
// argument would always be wrapped into an implicit closure
// at the end, so we can safely match against result type.
if (ctx.isSwiftVersionAtLeast(5) || !isAutoClosureArgument(argExpr)) {
// In Swift >= 5 mode there is no @autoclosure forwarding,
// so let's match result types.
if (auto *fnType = paramTy->getAs<FunctionType>()) {
paramTy = fnType->getResult();
}
} else {
// Matching @autoclosure argument to @autoclosure parameter
// directly would mean introducing a function conversion
// in Swift <= 4 mode.
cs.increaseScore(SK_FunctionConversion, loc);
matchingAutoClosureResult = false;
}
}
// In case solver matched trailing based on the backward scan,
// let's produce a warning which would suggest to add a label
// to disambiguate in the future.
if (selectedTrailingMatching == TrailingClosureMatching::Backward &&
argIdx == *argList->getFirstTrailingClosureIndex()) {
cs.recordFix(SpecifyLabelToAssociateTrailingClosure::create(
cs, cs.getConstraintLocator(loc)));
}
// Type-erase any opened existentials from subsequent parameter types
// unless the argument itself is a generic function, which could handle
// the opened existentials.
if (!openedExistentials.empty() && paramTy->hasTypeVariable() &&
!cs.isArgumentGenericFunction(argTy, argExpr)) {
for (const auto &opened : openedExistentials) {
paramTy = typeEraseOpenedExistentialReference(
paramTy, opened.second->getExistentialType(), opened.first,
TypePosition::Contravariant);
}
}
// If the argument is an existential type and the parameter is generic,
// consider opening the existential type.
if (auto existentialArg = shouldOpenExistentialCallArgument(
callee, paramIdx, paramTy, argTy, argExpr, cs)) {
// My kingdom for a decent "if let" in C++.
GenericTypeParamType *openedGenericParam;
TypeVariableType *openedTypeVar;
Type existentialType;
OpenedExistentialAdjustments adjustments;
std::tie(openedGenericParam, openedTypeVar, existentialType,
adjustments) = *existentialArg;
OpenedArchetypeType *opened;
std::tie(argTy, opened) = cs.openExistentialType(
existentialType, cs.getConstraintLocator(loc));
if (adjustments.contains(OpenedExistentialAdjustmentFlags::LValue))
argTy = LValueType::get(argTy);
if (adjustments.contains(OpenedExistentialAdjustmentFlags::InOut))
argTy = InOutType::get(argTy);
openedExistentials.push_back({openedTypeVar, opened});
}
auto argLabel = argument.getLabel();
if (paramInfo.hasExternalPropertyWrapper(paramIdx) ||
argLabel.hasDollarPrefix()) {
auto *param = getParameterAt(callee, paramIdx);
assert(param);
if (cs.applyPropertyWrapperToParameter(paramTy, argTy,
const_cast<ParamDecl *>(param),
argLabel, subKind, loc)
.isFailure()) {
return cs.getTypeMatchFailure(loc);
}
continue;
}
// If argument comes for declaration it should loose
// `@autoclosure` flag, because in context it's used
// as a function type represented by autoclosure.
//
// Special case here are synthesized arguments because
// they mirror parameter flags to ease diagnosis.
assert(!argsWithLabels[argIdx].isAutoClosure() ||
isSynthesizedArgument(argument));
// If parameter is a generic parameter, let's copy its
// conformance requirements (if any), to the argument
// be able to filter mismatching choices earlier.
if (auto *typeVar = paramTy->getAs<TypeVariableType>()) {
auto *locator = typeVar->getImpl().getLocator();
if (locator->isForGenericParameter()) {
auto &CG = cs.getConstraintGraph();
auto isTransferableConformance = [&typeVar](Constraint *constraint) {
if (constraint->getKind() != ConstraintKind::ConformsTo)
return false;
auto requirementTy = constraint->getFirstType();
if (!requirementTy->isEqual(typeVar))
return false;
return constraint->getSecondType()->is<ProtocolType>();
};
for (auto *constraint : CG[typeVar].getConstraints()) {
if (isTransferableConformance(constraint))
cs.addConstraint(ConstraintKind::TransitivelyConformsTo, argTy,
constraint->getSecondType(),
constraint->getLocator());
}
}
}
// Detect that there is sync -> async mismatch early on for
// closure argument to avoid re-checking calls if there was
// an overload choice with synchronous parameter of the same
// shape e.g.
//
// func test(_: () -> Void) -> MyStruct {}
// func test(_: () async -> Void) -> MyStruct {}
//
// test({ ... }).<member>...
//
// Synchronous overload is always better in this case so there
// is no need to re-check follow-up `<member>`s and better
// to short-circuit this path early.
if (auto *fnType = paramTy->getAs<FunctionType>()) {
if (fnType->isAsync()) {
auto *typeVar = argTy->getAs<TypeVariableType>();
if (typeVar && typeVar->getImpl().isClosureType()) {
auto *locator = typeVar->getImpl().getLocator();
auto *closure = castToExpr<ClosureExpr>(locator->getAnchor());
if (!cs.getClosureType(closure)->isAsync())
cs.increaseScore(SK_SyncInAsync, locator);
}
}
}
if (!argument.isCompileTimeConst() && param.isCompileTimeConst()) {
auto *locator = cs.getConstraintLocator(loc);
SourceRange range;
// simplify locator so the anchor is the exact argument.
cs.recordFix(NotCompileTimeConst::create(cs, paramTy,
simplifyLocator(cs, locator, range)));
}
cs.addConstraint(
subKind, argTy, paramTy,
matchingAutoClosureResult
? loc.withPathElement(ConstraintLocator::AutoclosureResult)
: loc,
/*isFavored=*/false);
}
}
return cs.getTypeMatchSuccess();
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchFunctionResultTypes(Type expectedResult, Type fnResult,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// If we have a callee with an IUO return, add a disjunction that can either
// bind to the result or an unwrapped result.
auto *calleeLoc = getCalleeLocator(getConstraintLocator(locator));
auto *calleeResultLoc = getConstraintLocator(
calleeLoc, ConstraintLocator::FunctionResult);
auto selected = findSelectedOverloadFor(calleeLoc);
// If we don't have a direct callee, this might be the second application
// of a curried function reference, in which case we need to dig into the
// inner call to find the callee.
// FIXME: This is a bit of a hack. We should consider rewriting curried
// applies as regular applies in PreCheckExpr to eliminate the need to special
// case double applies in the solver.
bool isSecondApply = false;
if (!selected) {
auto anchor = locator.getAnchor();
if (auto *callExpr = getAsExpr<CallExpr>(anchor)) {
if (auto *innerCall = getAsExpr<CallExpr>(callExpr->getSemanticFn())) {
auto *innerCalleeLoc =
getCalleeLocator(getConstraintLocator(innerCall));
if (auto innerOverload = findSelectedOverloadFor(innerCalleeLoc)) {
auto choice = innerOverload->choice;
if (choice.getFunctionRefKind() == FunctionRefKind::DoubleApply) {
isSecondApply = true;
selected.emplace(*innerOverload);
}
}
}
}
}
if (selected) {
auto choice = selected->choice;
// Subscripts found through dynamic lookup need special treatment. Unlike
// other decls found through dynamic lookup, they cannot have an optional
// applied to their reference, instead it's applied to their result. As
// such, we may need to unwrap another level of optionality.
if (choice.getKind() == OverloadChoiceKind::DeclViaDynamic &&
isa<SubscriptDecl>(choice.getDecl())) {
// Introduce a type variable to record whether we needed to unwrap the
// outer optional.
auto outerTy = createTypeVariable(calleeResultLoc, TVO_CanBindToLValue);
buildDisjunctionForDynamicLookupResult(outerTy, fnResult,
calleeResultLoc);
fnResult = outerTy;
}
auto iuoKind = choice.getIUOReferenceKind(*this, isSecondApply);
if (iuoKind == IUOReferenceKind::ReturnValue) {
buildDisjunctionForImplicitlyUnwrappedOptional(expectedResult, fnResult,
calleeResultLoc);
return getTypeMatchSuccess();
}
}
return matchTypes(expectedResult, fnResult, ConstraintKind::Bind, flags,
locator);
}
static bool isInPatternMatchingContext(ConstraintLocatorBuilder locator) {
SmallVector<LocatorPathElt, 4> path;
(void)locator.getLocatorParts(path);
auto pathElement = llvm::find_if(path, [](LocatorPathElt &elt) {
return elt.is<LocatorPathElt::PatternMatch>();
});
return pathElement != path.end();
}
namespace {
class TupleMatcher {
TupleType *tuple1;
TupleType *tuple2;
public:
enum class MatchKind : uint8_t {
Equality,
Subtype,
Conversion,
};
SmallVector<MatchedPair, 4> pairs;
bool hasLabelMismatch = false;
TupleMatcher(TupleType *tuple1, TupleType *tuple2)
: tuple1(tuple1), tuple2(tuple2) {}
bool match(MatchKind kind, ConstraintLocatorBuilder locator) {
// FIXME: TuplePackMatcher should completely replace the non-variadic
// case too eventually.
if (containsPackExpansionType(tuple1) ||
containsPackExpansionType(tuple2)) {
TuplePackMatcher matcher(tuple1, tuple2, isPackExpansionType);
if (matcher.match())
return true;
pairs = matcher.pairs;
return false;
}
if (tuple1->getNumElements() != tuple2->getNumElements())
return true;
switch (kind) {
case MatchKind::Equality:
return matchEquality(isInPatternMatchingContext(locator));
case MatchKind::Subtype:
return matchSubtype();
case MatchKind::Conversion:
return matchConversion();
}
}
private:
bool matchEquality(bool inPatternMatchingContext) {
for (unsigned i = 0, n = tuple1->getNumElements(); i != n; ++i) {
const auto &elt1 = tuple1->getElement(i);
const auto &elt2 = tuple2->getElement(i);
if (inPatternMatchingContext) {
// FIXME: The fact that this isn't symmetric is wrong since this logic
// is called for bind and equal constraints...
if (elt2.hasName() && elt1.getName() != elt2.getName())
return true;
} else {
// If the names don't match, we have a conflict.
if (elt1.getName() != elt2.getName())
return true;
}
pairs.emplace_back(elt1.getType(), elt2.getType(), i, i);
}
return false;
}
bool matchSubtype() {
for (unsigned i = 0, n = tuple1->getNumElements(); i != n; ++i) {
const auto &elt1 = tuple1->getElement(i);
const auto &elt2 = tuple2->getElement(i);
// If the names don't match, we may have a conflict.
if (elt1.getName() != elt2.getName()) {
// Make sure that this name isn't used at some other position.
if (elt2.hasName() && tuple1->getNamedElementId(elt2.getName()) != -1)
return true;
// If both elements have names and they mismatch, make a note of it
// so we can emit a warning.
if (elt1.hasName() && elt2.hasName())
hasLabelMismatch = true;
}
pairs.emplace_back(elt1.getType(), elt2.getType(), i, i);
}
return false;
}
bool matchConversion() {
SmallVector<unsigned, 4> sources;
if (computeTupleShuffle(tuple1, tuple2, sources))
return true;
for (unsigned idx2 = 0, n = sources.size(); idx2 != n; ++idx2) {
unsigned idx1 = sources[idx2];
auto lhs = tuple1->getElementType(idx1);
auto rhs = tuple2->getElementType(idx2);
pairs.emplace_back(lhs, rhs, idx1, idx2);
}
return false;
}
};
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchTupleTypes(TupleType *tuple1, TupleType *tuple2,
ConstraintKind kind, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
using TupleMatchKind = TupleMatcher::MatchKind;
ConstraintKind subkind;
TupleMatchKind matchKind;
switch (kind) {
case ConstraintKind::Bind:
case ConstraintKind::Equal: {
subkind = kind;
matchKind = TupleMatchKind::Equality;
break;
}
// NOTE: It was probably a mistake that BindToPointerType is handled like
// Subtype; this was implicit in the old structure of the code due to bogus
// use of operator<= on enum cases.
case ConstraintKind::Subtype:
case ConstraintKind::BindToPointerType: {
subkind = kind;
matchKind = TupleMatchKind::Subtype;
break;
}
case ConstraintKind::Conversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion: {
subkind = ConstraintKind::Conversion;
matchKind = TupleMatchKind::Conversion;
break;
}
case ConstraintKind::BindParam:
case ConstraintKind::ApplicableFunction:
case ConstraintKind::DynamicCallableApplicableFunction:
case ConstraintKind::BindOverload:
case ConstraintKind::CheckedCast:
case ConstraintKind::SubclassOf:
case ConstraintKind::ConformsTo:
case ConstraintKind::TransitivelyConformsTo:
case ConstraintKind::Defaultable:
case ConstraintKind::Disjunction:
case ConstraintKind::Conjunction:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::OptionalObject:
case ConstraintKind::SelfObjectOfProtocol:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueMember:
case ConstraintKind::ValueWitness:
case ConstraintKind::BridgingConversion:
case ConstraintKind::OneWayEqual:
case ConstraintKind::OneWayBindParam:
case ConstraintKind::FallbackType:
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PropertyWrapper:
case ConstraintKind::SyntacticElement:
case ConstraintKind::BindTupleOfFunctionParams:
case ConstraintKind::PackElementOf:
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
llvm_unreachable("Bad constraint kind in matchTupleTypes()");
}
TupleMatcher matcher(tuple1, tuple2);
if (matcher.match(matchKind, locator))
return getTypeMatchFailure(locator);
if (matcher.hasLabelMismatch) {
// If we had a label mismatch, emit a warning. This is something we
// shouldn't permit, as it's more permissive than what a conversion would
// allow. Ideally we'd turn this into an error in Swift 6 mode.
recordFix(AllowTupleLabelMismatch::create(*this, tuple1, tuple2,
getConstraintLocator(locator)));
}
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
for (auto pair : matcher.pairs) {
auto result = matchTypes(pair.lhs, pair.rhs, subkind, subflags,
locator.withPathElement(
LocatorPathElt::TupleElement(pair.lhsIdx)));
if (result.isFailure())
return result;
}
return getTypeMatchSuccess();
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchPackTypes(PackType *pack1, PackType *pack2,
ConstraintKind kind, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
PackMatcher matcher(pack1->getElementTypes(), pack2->getElementTypes(),
getASTContext(), isPackExpansionType);
if (matcher.match())
return getTypeMatchFailure(locator);
for (auto pair : matcher.pairs) {
auto result = matchTypes(pair.lhs, pair.rhs, kind, subflags,
locator.withPathElement(
LocatorPathElt::PackElement(pair.lhsIdx)));
if (result.isFailure())
return result;
}
return getTypeMatchSuccess();
}
/// Utility function used when matching a pack expansion type against a
/// pack type.
///
/// Takes a pattern type and an original pack type, and returns an instantiated
/// pack type. The original pack type is then matched against the instantiated
/// pack type.
///
/// As a side effect, it binds each pack type variable occurring in the pattern
/// type to a new pack with the same shape as the original pack, but where the
/// elements are fresh type variables.
///
/// The instantiated pack has the same shape as the original pack, where the
/// ith element is the pattern type with each pack type variable replaced by the
/// ith element of its binding.
///
/// For example, given the pattern Foo<$T0> and the original pack
/// {Foo<Int>, Foo<String>...}, we're going to bind
///
/// $T0 := {$T1, $T2}
///
/// And return the new pack {Foo<$T1>, Foo<$T2>...}.
///
/// The caller will then match the original pack type against the instantiated
/// pack type, which will recover the bindings:
///
/// $T1 := Int
/// $T2 := String
///
static PackType *replaceTypeVariablesWithFreshPacks(ConstraintSystem &cs,
Type pattern,
PackType *pack,
ConstraintLocatorBuilder locator) {
llvm::SmallSetVector<TypeVariableType *, 2> typeVarSet;
llvm::MapVector<TypeVariableType *, SmallVector<Type, 2>> typeVars;
pattern->walkPackReferences([&](Type t) {
if (auto *typeVar = t->getAs<TypeVariableType>()) {
if (typeVar->getImpl().canBindToPack())
typeVarSet.insert(typeVar);
}
return false;
});
if (typeVarSet.empty())
return nullptr;
auto *loc = cs.getConstraintLocator(locator);
// For each pack type variable occurring in the pattern type, compute a
// binding pack type comprised of fresh type variables.
for (auto *typeVar : typeVarSet) {
auto &freshTypeVars = typeVars[typeVar];
for (unsigned i = 0, e = pack->getNumElements(); i < e; ++i) {
auto *packExpansionElt = pack->getElementType(i)->getAs<PackExpansionType>();
// Preserve the pack expansion structure of the original pack. If the ith
// element was a pack expansion type, create a new pack expansion type
// wrapping a pack type variable. Otherwise, create a new scalar
// type variable.
//
// FIXME: Other TVO_* flags for type variables?
auto elementLoc = cs.getConstraintLocator(loc,
LocatorPathElt::PackElement(freshTypeVars.size()));
if (packExpansionElt != nullptr) {
auto *freshTypeVar = cs.createTypeVariable(
elementLoc,
TVO_CanBindToPack |
(typeVar->getImpl().canBindToHole() ? TVO_CanBindToHole : 0));
freshTypeVars.push_back(PackExpansionType::get(
freshTypeVar, packExpansionElt->getCountType()));
} else {
freshTypeVars.push_back(cs.createTypeVariable(
elementLoc,
typeVar->getImpl().canBindToHole() ? TVO_CanBindToHole : 0));
}
}
}
SmallVector<Type, 2> elts;
// For each element of the original pack type, instantiate the pattern type by
// replacing each pack type variable with the corresponding element of the
// pack type variable's binding pack.
for (unsigned i = 0, e = pack->getNumElements(); i < e; ++i) {
auto *packExpansionElt = pack->getElementType(i)->getAs<PackExpansionType>();
auto instantiatedPattern = pattern.transformRec([&](Type t)
-> std::optional<Type> {
if (isPackExpansionType(t))
return t;
if (auto *typeVar = t->getAs<TypeVariableType>()) {
if (typeVar->getImpl().canBindToPack()) {
auto found = typeVars.find(typeVar);
assert(found != typeVars.end());
// The ith element of the binding pack is either a scalar type variable
// or a pack expansion type wrapping a pack type variable.
auto projectedType = (found->second)[i];
if (packExpansionElt != nullptr) {
projectedType = projectedType->castTo<PackExpansionType>()
->getPatternType();
assert(projectedType->castTo<TypeVariableType>()
->getImpl().canBindToPack());
} else {
assert(!projectedType->castTo<TypeVariableType>()
->getImpl().canBindToPack());
}
return projectedType;
}
}
return std::nullopt;
});
if (packExpansionElt != nullptr) {
elts.push_back(PackExpansionType::get(instantiatedPattern,
packExpansionElt->getCountType()));
} else {
elts.push_back(instantiatedPattern);
}
}
auto &ctx = cs.getASTContext();
// Bind each pack type variable occurring in the pattern type to its
// binding pack that was constructed above.
for (const auto &pair : typeVars) {
cs.addConstraint(ConstraintKind::Bind,
pair.first, PackType::get(ctx, pair.second), locator);
}
// Construct the instantiated pack type.
return PackType::get(cs.getASTContext(), elts);
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchPackExpansionTypes(PackExpansionType *expansion1,
PackExpansionType *expansion2,
ConstraintKind kind, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// The count types of two pack expansion types must have the same shape.
addConstraint(ConstraintKind::SameShape, expansion1->getCountType(),
expansion2->getCountType(),
locator.withPathElement(ConstraintLocator::PackShape));
auto pattern1 = expansion1->getPatternType();
auto pattern2 = expansion2->getPatternType();
// If both sides are expanded or neither side is, just match them
// directly.
if (pattern1->is<PackType>() == pattern2->is<PackType>()) {
return matchTypes(pattern1, pattern2, kind, flags, locator);
// If the right hand side is expanded, we have something like
// Foo<$T0>... vs Pack{Foo<Int>, Foo<String>}...; We're going to
// bind $T0 to Pack{Int, String}.
} else if (!pattern1->is<PackType>() && pattern2->is<PackType>()) {
if (auto *pack2 = pattern2->getAs<PackType>()) {
if (auto *pack1 = replaceTypeVariablesWithFreshPacks(
*this, pattern1, pack2, locator)) {
addConstraint(kind, pack1, pack2, locator);
return getTypeMatchSuccess();
}
}
return getTypeMatchFailure(locator);
// If the left hand side is expanded, we have something like
// Pack{Foo<Int>, Foo<String>}... vs Foo<$T0>...; We're going to
// bind $T0 to Pack{Int, String}.
} else {
assert(pattern1->is<PackType>() && !pattern2->is<PackType>());
if (auto *pack1 = pattern1->getAs<PackType>()) {
if (auto *pack2 = replaceTypeVariablesWithFreshPacks(
*this, pattern2, pack1, locator)) {
addConstraint(kind, pack1, pack2, locator);
return getTypeMatchSuccess();
}
}
return getTypeMatchFailure(locator);
}
}
/// Check where a representation is a subtype of another.
///
/// The subtype relationship is defined as:
/// 1. any representation R is a sub-type of itself.
/// 2. a thin representation is a subtype of any other representation.
/// 3. a thick representation is a subtype of any other thick representation.
///
/// For example, since `@convention(c)` is a thin representation, and
/// `@convention(swift)` is a thick representation,
/// `@convention(c) (A) -> B` is a sub-type of `(A) -> B`.
///
/// NOTE: Unlike typical subtyping relationships, this is not anti-symmetric.
/// For example, @convention(c) and @convention(thin) are subtypes of each other
/// but not equal.
static bool
isSubtypeOf(FunctionTypeRepresentation potentialSubRepr,
FunctionTypeRepresentation potentialSuperRepr) {
return (potentialSubRepr == potentialSuperRepr)
|| isThinRepresentation(potentialSubRepr)
|| isThickRepresentation(potentialSuperRepr);
}
/// Returns true if `constraint extInfo1 extInfo2` is satisfied.
static bool matchFunctionRepresentations(FunctionType::ExtInfo einfo1,
FunctionType::ExtInfo einfo2,
ConstraintKind kind,
ConstraintSystemOptions options) {
auto rep1 = einfo1.getRepresentation();
auto rep2 = einfo2.getRepresentation();
bool clangTypeMismatch =
(options.contains(ConstraintSystemFlags::UseClangFunctionTypes) &&
(einfo1.getClangTypeInfo() != einfo2.getClangTypeInfo()));
switch (kind) {
case ConstraintKind::Bind:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Equal:
return (rep1 == rep2) && !clangTypeMismatch;
case ConstraintKind::Subtype: {
// Breakdown of cases:
// 1. isSubtypeOf(rep1, rep2) == false (hence rep1 != rep2):
// In this case, this function will return false, indicating that we
// can't convert. E.g. you can't convert from @convention(swift) to
// @convention(c).
// 2. isSubtypeOf(rep1, rep2) == true and rep1 != rep2:
// In this case, this function will return true, indicating that we
// can convert, because the Clang type doesn't matter when converting
// between different representations. E.g. it is okay to convert from
// @convention(c) (regardless of cType) to @convention(swift).
// 3. isSubtypeOf(rep1, rep2) == true and rep1 == rep2:
// In this case, the function returns !clangTypeMismatch, as we forbid
// conversions between @convention(c) functions with different cTypes.
return isSubtypeOf(rep1, rep2) && ((rep1 != rep2) || !clangTypeMismatch);
}
// [NOTE: diagnose-swift-to-c-convention-change]: @convention(swift) ->
// @convention(c) conversions are permitted only in certain cases.
//
// var w = 3; func f() { print(w) }; func g(_ : @convention(c) () -> ()) {}
// g(f); // OK
// let h = f as @convention(c) () -> (); g(h) // OK
// let k = f; g(k) // error
// func m() { let x = 0; g({ print(x) }) } // error
// func n() { let y = 0; func p() { }; g(p); } // OK
// func q() { let z = 0; func r() { print(z) }; g(r); } // error
//
// Since checking for disallowed cases requires access to captures,
// it is simpler to defer diagnosing (to CSApply/SILGen) and return true here.
case ConstraintKind::Conversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion:
// For now, forbid conversion if representations match but cTypes differ.
//
// let f : @convention(c, cType: "id (*)(void) __attribute__((ns_returns_retained))")
// () -> AnyObject = ...
// let _ : @convention(c, cType: "id (*)(void)")
// () -> AnyObject = f // error
// let g : @convention(c, cType: "void (*)(void *)")
// (OpaquePointer?) -> () = ...
// let _ : @convention(c, cType: "void (*)(MyCtx *)")
// (OpaquePointer?) -> () = g // error
if ((rep1 == rep2) && clangTypeMismatch) {
return false;
}
return true;
case ConstraintKind::BridgingConversion:
case ConstraintKind::ApplicableFunction:
case ConstraintKind::DynamicCallableApplicableFunction:
case ConstraintKind::BindOverload:
case ConstraintKind::CheckedCast:
case ConstraintKind::SubclassOf:
case ConstraintKind::ConformsTo:
case ConstraintKind::TransitivelyConformsTo:
case ConstraintKind::Defaultable:
case ConstraintKind::Disjunction:
case ConstraintKind::Conjunction:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::OptionalObject:
case ConstraintKind::SelfObjectOfProtocol:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueMember:
case ConstraintKind::ValueWitness:
case ConstraintKind::OneWayEqual:
case ConstraintKind::OneWayBindParam:
case ConstraintKind::FallbackType:
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PropertyWrapper:
case ConstraintKind::SyntacticElement:
case ConstraintKind::BindTupleOfFunctionParams:
case ConstraintKind::PackElementOf:
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
return true;
}
llvm_unreachable("Unhandled ConstraintKind in switch.");
}
/// Check whether given parameter list represents a single tuple
/// or type variable which could be later resolved to tuple.
/// This is useful for SE-0110 related fixes in `matchFunctionTypes`.
static bool isSingleTupleParam(ASTContext &ctx,
ArrayRef<AnyFunctionType::Param> params) {
if (params.size() != 1)
return false;
const auto ¶m = params.front();
if ((param.isVariadic() || isPackExpansionType(param.getPlainType())) ||
param.isInOut() || param.hasLabel() || param.isIsolated())
return false;
auto paramType = param.getPlainType();
// Support following case which was allowed until 5:
//
// func bar(_: (Int, Int) -> Void) {}
// let foo: ((Int, Int)?) -> Void = { _ in }
//
// bar(foo) // Ok
if (!ctx.isSwiftVersionAtLeast(5))
paramType = paramType->lookThroughAllOptionalTypes();
// Parameter type should either a tuple or something that can become a
// tuple later on.
return (paramType->is<TupleType>() || paramType->isTypeVariableOrMember());
}
static ConstraintFix *fixRequirementFailure(ConstraintSystem &cs, Type type1,
Type type2, ASTNode anchor,
ArrayRef<LocatorPathElt> path);
static ConstraintFix *fixRequirementFailure(ConstraintSystem &cs, Type type1,
Type type2,
ConstraintLocatorBuilder locator) {
SmallVector<LocatorPathElt, 4> path;
auto anchor = locator.getLocatorParts(path);
return fixRequirementFailure(cs, type1, type2, anchor, path);
}
static unsigned
assessRequirementFailureImpact(ConstraintSystem &cs, Type requirementType,
ConstraintLocatorBuilder locator) {
assert(requirementType);
unsigned impact = 1;
auto anchor = locator.getAnchor();
if (!anchor)
return impact;
// If this requirement is associated with a member reference and it
// was possible to check it before overload choice is bound, that means
// types came from the context (most likely Self, or associated type(s))
// and failing this constraint makes member unrelated/inaccessible, so
// the impact has to be adjusted accordingly in order for this fix not to
// interfere with other overload choices.
//
// struct S<T> {}
// extension S where T == AnyObject { func foo() {} }
//
// func bar(_ s: S<Int>) { s.foo() }
//
// In this case `foo` is only accessible if T == `AnyObject`, which makes
// fix for same-type requirement higher impact vs. requirement associated
// with method itself e.g. `func foo<U>() -> U where U : P {}` because
// `foo` is accessible from any `S` regardless of what `T` is.
//
// Don't add this impact with the others, as we want to keep it consistent
// across requirement failures to present the user with a choice.
if (isExpr<UnresolvedDotExpr>(anchor) ||
isExpr<UnresolvedMemberExpr>(anchor)) {
auto *calleeLoc = cs.getCalleeLocator(cs.getConstraintLocator(locator));
if (!cs.findSelectedOverloadFor(calleeLoc))
return 10;
}
if (auto *UDE = getAsExpr<UnresolvedDotExpr>(anchor)) {
if (isResultBuilderMethodReference(cs.getASTContext(), UDE))
return 12;
}
auto resolvedTy = cs.simplifyType(requirementType);
// Increase the impact of a conformance fix for generic parameters on
// operators where such conformance failures are not as important as argument
// mismatches or contextual failures.
if (auto *ODRE = getAsExpr<OverloadedDeclRefExpr>(anchor)) {
if (locator.isForRequirement(RequirementKind::Conformance) &&
resolvedTy->is<ArchetypeType>() && ODRE->isForOperator()) {
++impact;
}
}
if (locator.isForRequirement(RequirementKind::Conformance)) {
// Increase the impact of a conformance fix for a standard library
// or foundation type, as it's unlikely to be a good suggestion.
{
if (resolvedTy->isStdlibType()) {
impact += 2;
}
if (auto *NTD = resolvedTy->getAnyNominal()) {
if (getKnownFoundationEntity(NTD->getNameStr()))
impact += 2;
}
}
// Also do the same for the builtin compiler types Any and AnyObject, but
// bump the impact even higher as they cannot conform to protocols at all.
if (resolvedTy->isAny() || resolvedTy->isAnyObject())
impact += 4;
}
// If this requirement is associated with an overload choice let's
// tie impact to how many times this requirement type is mentioned.
if (auto *ODRE = getAsExpr<OverloadedDeclRefExpr>(anchor)) {
if (auto *typeVar = requirementType->getAs<TypeVariableType>()) {
unsigned choiceImpact = 0;
if (auto choice = cs.findSelectedOverloadFor(ODRE)) {
choice->adjustedOpenedType.visit([&](Type type) {
if (type->isEqual(typeVar))
++choiceImpact;
});
}
// If the type is used multiple times in the signature, increase the
// impact for every additional use.
if (choiceImpact > 1)
impact += choiceImpact - 1;
}
}
// If this requirement is associated with a call that is itself
// incorrect, let's increase impact to indicate that this failure
// has a compounding effect on viability of the overload choice it
// comes from.
if (locator.endsWith<LocatorPathElt::AnyRequirement>()) {
if (auto *expr = getAsExpr(anchor)) {
if (auto *call = getAsExpr<ApplyExpr>(cs.getParentExpr(expr))) {
if (call->getFn() == expr &&
llvm::any_of(cs.getFixes(), [&](const auto &fix) {
return getAsExpr(fix->getAnchor()) == call;
}))
impact += 2;
}
}
}
return impact;
}
/// Attempt to fix missing arguments by introducing type variables
/// and inferring their types from parameters.
static bool fixMissingArguments(ConstraintSystem &cs, ASTNode anchor,
SmallVectorImpl<AnyFunctionType::Param> &args,
ArrayRef<AnyFunctionType::Param> params,
unsigned numMissing,
ConstraintLocatorBuilder locator) {
assert(args.size() < params.size());
auto &ctx = cs.getASTContext();
// If there are N parameters but a single closure argument
// (which might be anonymous), it's most likely used as a
// tuple e.g. `$0.0`.
std::optional<TypeBase *> argumentTuple;
if (isSingleTupleParam(ctx, args)) {
auto argType = args.back().getPlainType();
// Let's unpack argument tuple into N arguments, this corresponds
// to something like `foo { (bar: (Int, Int)) in }` where `foo`
// has a single parameter of type `(Int, Int) -> Void`.
if (auto *tuple = argType->getAs<TupleType>()) {
args.pop_back();
for (const auto &elt : tuple->getElements())
args.emplace_back(elt.getType(), elt.getName());
} else if (auto *typeVar = argType->getAs<TypeVariableType>()) {
auto isParam = [](const Expr *expr) {
if (auto *DRE = dyn_cast<DeclRefExpr>(expr)) {
if (auto *decl = DRE->getDecl())
return isa<ParamDecl>(decl);
}
return false;
};
// Something like `foo { x in }` or `foo { $0 }`
if (auto *closure = getAsExpr<ClosureExpr>(anchor)) {
cs.forEachExpr(closure, [&](Expr *expr) -> Expr * {
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(expr)) {
if (!isParam(UDE->getBase()))
return expr;
auto name = UDE->getName().getBaseIdentifier();
unsigned index = 0;
if (!name.str().getAsInteger(10, index) ||
llvm::any_of(params, [&](const AnyFunctionType::Param ¶m) {
return param.getLabel() == name;
})) {
argumentTuple.emplace(typeVar);
args.pop_back();
return nullptr;
}
}
return expr;
});
}
}
}
for (unsigned i = args.size(), n = params.size(); i != n; ++i) {
auto *argLoc = cs.getConstraintLocator(
anchor, LocatorPathElt::SynthesizedArgument(i));
args.push_back(params[i].withType(
cs.createTypeVariable(argLoc, TVO_CanBindToNoEscape)));
}
SmallVector<SynthesizedArg, 4> synthesizedArgs;
synthesizedArgs.reserve(numMissing);
for (unsigned i = args.size() - numMissing, n = args.size(); i != n; ++i) {
synthesizedArgs.push_back(SynthesizedArg{i, args[i]});
}
// Treat missing anonymous arguments as valid in closures containing the
// code completion location, since they may have just not been written yet.
if (cs.isForCodeCompletion()) {
if (auto *closure = getAsExpr<ClosureExpr>(anchor)) {
if (cs.containsIDEInspectionTarget(closure) &&
(closure->hasAnonymousClosureVars() ||
(args.empty() && closure->getInLoc().isInvalid())))
return false;
}
}
auto *fix = AddMissingArguments::create(cs, synthesizedArgs,
cs.getConstraintLocator(locator));
if (cs.recordFix(fix))
return true;
// If the argument was a single "tuple", let's bind newly
// synthesized arguments to it.
if (argumentTuple) {
// We can ignore parameter flags here as we're imploding a tuple for a
// simulated ((X, Y, Z)) -> R to (X, Y, Z) -> R conversion. As such, this is
// similar to e.g { x, y, z in fn((x, y, z)) }.
cs.addConstraint(ConstraintKind::Bind, *argumentTuple,
FunctionType::composeTuple(
ctx, args, ParameterFlagHandling::IgnoreNonEmpty),
cs.getConstraintLocator(anchor));
}
return false;
}
static bool fixExtraneousArguments(ConstraintSystem &cs,
FunctionType *contextualType,
ArrayRef<AnyFunctionType::Param> args,
int numExtraneous,
ConstraintLocatorBuilder locator) {
SmallVector<std::pair<unsigned, AnyFunctionType::Param>, 4> extraneous;
for (unsigned i = args.size() - numExtraneous, n = args.size(); i != n; ++i) {
extraneous.push_back({i, args[i]});
if (auto *typeVar = args[i].getPlainType()->getAs<TypeVariableType>()) {
cs.recordPotentialHole(typeVar);
}
}
return cs.recordFix(
RemoveExtraneousArguments::create(cs, contextualType, extraneous,
cs.getConstraintLocator(locator)),
/*impact=*/numExtraneous * 2);
}
bool ConstraintSystem::hasPreconcurrencyCallee(
ConstraintLocatorBuilder locator) {
auto calleeLocator = getCalleeLocator(getConstraintLocator(locator));
auto calleeOverload = findSelectedOverloadFor(calleeLocator);
if (!calleeOverload || !calleeOverload->choice.isDecl())
return false;
return calleeOverload->choice.getDecl()->preconcurrency();
}
/// Match the throwing specifier of the two function types.
static ConstraintSystem::TypeMatchResult
matchFunctionThrowing(ConstraintSystem &cs,
FunctionType *func1, FunctionType *func2,
ConstraintKind kind,
ConstraintSystem::TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// A function type that throws the error type E1 is a subtype of a function
// that throws error type E2 when E1 is a subtype of E2. For the purpose
// of this comparison, a non-throwing function has thrown error type 'Never',
// and an untyped throwing function has thrown error type 'any Error'.
Type thrownError1 = func1->getEffectiveThrownErrorTypeOrNever();
Type thrownError2 = func2->getEffectiveThrownErrorTypeOrNever();
if (!thrownError1 || !thrownError2)
return cs.getTypeMatchSuccess();
switch (compareThrownErrorsForSubtyping(thrownError1, thrownError2, cs.DC)) {
case ThrownErrorSubtyping::DropsThrows: {
// We need to drop 'throws' to make this work.
if (!cs.shouldAttemptFixes())
return cs.getTypeMatchFailure(locator);
auto *fix = DropThrowsAttribute::create(cs, func1, func2,
cs.getConstraintLocator(locator));
if (cs.recordFix(fix))
return cs.getTypeMatchFailure(locator);
return cs.getTypeMatchSuccess();
}
case ThrownErrorSubtyping::ExactMatch:
return cs.getTypeMatchSuccess();
case ThrownErrorSubtyping::Subtype:
// We know this is going to work, but we might still need to generate a
// constraint if one of the error types involves type variables.
if (thrownError1->hasTypeVariable() || thrownError2->hasTypeVariable()) {
// Fall through to the dependent case.
} else if (kind < ConstraintKind::Subtype) {
// We aren't allowed to have a subtype, so fail here.
return cs.getTypeMatchFailure(locator);
} else {
// We have a subtype. All set!
return cs.getTypeMatchSuccess();
}
LLVM_FALLTHROUGH;
case ThrownErrorSubtyping::Dependent: {
// The presence of type variables in the thrown error types require that
// we generate a constraint to unify the thrown error types, so do so now.
ConstraintKind subKind = (kind < ConstraintKind::Subtype)
? ConstraintKind::Equal
: ConstraintKind::Subtype;
const auto subflags = getDefaultDecompositionOptions(flags);
auto result = cs.matchTypes(
thrownError1, thrownError2,
subKind, subflags,
locator.withPathElement(LocatorPathElt::ThrownErrorType()));
if (result == ConstraintSystem::SolutionKind::Error)
return cs.getTypeMatchFailure(locator);
return cs.getTypeMatchSuccess();
}
case ThrownErrorSubtyping::Mismatch: {
auto thrownErrorLocator = cs.getConstraintLocator(
locator.withPathElement(LocatorPathElt::ThrownErrorType()));
if (!cs.shouldAttemptFixes())
return cs.getTypeMatchFailure(thrownErrorLocator);
auto *fix = IgnoreThrownErrorMismatch::create(
cs, thrownError1, thrownError2, thrownErrorLocator);
if (cs.recordFix(fix))
return cs.getTypeMatchFailure(thrownErrorLocator);
return cs.getTypeMatchSuccess();
}
}
}
static bool isWitnessMatching(ConstraintLocatorBuilder locator) {
SmallVector<LocatorPathElt, 4> path;
(void) locator.getLocatorParts(path);
return (path.size() == 1 &&
path[0].is<LocatorPathElt::Witness>());
}
bool
ConstraintSystem::matchFunctionIsolations(FunctionType *func1,
FunctionType *func2,
ConstraintKind kind,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto isolation1 = func1->getIsolation(), isolation2 = func2->getIsolation();
// If we have a difference in isolation kind, we need a conversion.
// Make sure that we're looking for a conversion, and increase the
// function-conversion score to make sure this solution is worse than
// an exact match.
// FIXME: there may be a better way. see https://github.com/apple/swift/pull/62514
auto matchIfConversion = [&](bool isErasure = false) -> bool {
// We generally require a conversion here, but allow some lassitude
// if we're doing witness-matching.
if (kind < ConstraintKind::Subtype &&
!(isErasure && isWitnessMatching(locator)))
return false;
increaseScore(SK_FunctionConversion, locator);
return true;
};
switch (isolation2.getKind()) {
// Converting to a non-isolated type.
case FunctionTypeIsolation::Kind::NonIsolated:
switch (isolation1.getKind()) {
// Exact match.
case FunctionTypeIsolation::Kind::NonIsolated:
return true;
// Erasing global-actor isolation to non-isolation can admit data
// races; such violations are diagnosed by the actor isolation checker.
// We deliberately do not allow actor isolation violations to influence
// overload resolution to preserve the property that an expression can
// be re-checked against a different isolation context for isolation
// violations.
//
// This also applies to @isolated(any) because we want to be able to
// decide that we contextually isolated to the function's dynamic
// isolation.
case FunctionTypeIsolation::Kind::GlobalActor:
case FunctionTypeIsolation::Kind::Erased:
return matchIfConversion();
// Parameter isolation is value-dependent and cannot be erased.
case FunctionTypeIsolation::Kind::Parameter:
return false;
}
llvm_unreachable("bad kind");
// Converting to a global-actor-isolated type.
case FunctionTypeIsolation::Kind::GlobalActor:
switch (isolation1.getKind()) {
// Both types are global-actor-isolated. We *could* allow this as a
// conversion even for different global actors if the destination type
// is async, but we've decided we don't want to as a policy.
case FunctionTypeIsolation::Kind::GlobalActor: {
const auto subflags = getDefaultDecompositionOptions(flags);
auto result = matchTypes(
isolation1.getGlobalActorType(), isolation2.getGlobalActorType(),
ConstraintKind::Equal, subflags,
locator.withPathElement(LocatorPathElt::GlobalActorType()));
return result != SolutionKind::Error;
}
// Adding global actor isolation to a non-isolated function is fine,
// whether synchronous or asynchronous.
case FunctionTypeIsolation::Kind::NonIsolated:
return matchIfConversion();
// Parameter isolation cannot be altered in the same way.
case FunctionTypeIsolation::Kind::Parameter:
return false;
// Don't allow dynamically-isolated function types to convert to
// any specific isolation for the same policy reasons that we don't
// want to allow global-actors to change.
case FunctionTypeIsolation::Kind::Erased:
return false;
}
llvm_unreachable("bad kind");
// Converting to a parameter-isolated type.
case FunctionTypeIsolation::Kind::Parameter:
switch (isolation1.getKind()) {
// Exact match. We'll check that the isolated parameters match up later,
// when we're looking at the parameters.
case FunctionTypeIsolation::Kind::Parameter:
return true;
// Adding global actor isolation to a non-isolated function is fine,
// whether synchronous or asynchronous.
case FunctionTypeIsolation::Kind::NonIsolated:
case FunctionTypeIsolation::Kind::GlobalActor:
return matchIfConversion();
// Don't allow dynamically-isolated function types to convert to
// any specific isolation for the same policy reasons that we don't
// want to allow global-actors to change.
case FunctionTypeIsolation::Kind::Erased:
return false;
}
llvm_unreachable("bad kind");
case FunctionTypeIsolation::Kind::Erased:
switch (isolation1.getKind()) {
// Exact match.
case FunctionTypeIsolation::Kind::Erased:
return true;
// We can statically erase any kind of static isolation to dynamic
// isolation as a conversion.
case FunctionTypeIsolation::Kind::NonIsolated:
case FunctionTypeIsolation::Kind::GlobalActor:
return matchIfConversion(/*erasure*/ true);
// Parameter isolation is value-dependent and can't be erased in the
// abstract, though. We need to be able to recover the isolation from
// a value.
case FunctionTypeIsolation::Kind::Parameter:
return false;
}
llvm_unreachable("bad kind");
}
llvm_unreachable("bad kind");
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchFunctionTypes(FunctionType *func1, FunctionType *func2,
ConstraintKind kind, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// Match the 'throws' effect.
TypeMatchResult throwsResult =
matchFunctionThrowing(*this, func1, func2, kind, flags, locator);
if (throwsResult.isFailure())
return throwsResult;
// A synchronous function can be a subtype of an 'async' function.
if (func1->isAsync() != func2->isAsync()) {
// Cannot drop 'async'.
if (func1->isAsync() || kind < ConstraintKind::Subtype) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);
auto *fix = DropAsyncAttribute::create(*this, func1, func2,
getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
}
bool forClosureInArgumentPosition =
locator.endsWith<LocatorPathElt::ApplyArgToParam>() &&
isa<ClosureExpr>(locator.trySimplifyToExpr());
// Since it's possible to infer `async` from the body of a
// closure, score for sync -> async mismatch is increased
// while solver is matching arguments to parameters to
// indicate than solution with such a mismatch is always
// worse than one with synchronous functions on both sides.
if (!forClosureInArgumentPosition)
increaseScore(SK_SyncInAsync, locator);
}
// A @Sendable function can be a subtype of a non-@Sendable function.
if (func1->isSendable() != func2->isSendable()) {
// Cannot add '@Sendable'.
if (func2->isSendable() || kind < ConstraintKind::Subtype) {
if (AddSendableAttribute::attempt(*this, kind, func1, func2, locator))
return getTypeMatchFailure(locator);
}
}
// A non-@noescape function type can be a subtype of a @noescape function
// type.
if (func1->isNoEscape() != func2->isNoEscape() &&
(func1->isNoEscape() || kind < ConstraintKind::Subtype)) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);
auto *fix = MarkExplicitlyEscaping::create(*this, func1, func2,
getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
}
// () -> sending T can be a subtype of () -> T... but not vis-a-versa.
if (func1->hasSendingResult() != func2->hasSendingResult() &&
(!func1->hasSendingResult() || kind < ConstraintKind::Subtype)) {
auto *fix = AllowSendingMismatch::create(
*this, getConstraintLocator(locator), func1, func2,
AllowSendingMismatch::Kind::Result);
if (recordFix(fix))
return getTypeMatchFailure(locator);
}
if (!matchFunctionIsolations(func1, func2, kind, flags, locator))
return getTypeMatchFailure(locator);
// To contextual type increase the score to avoid ambiguity when solver can
// find more than one viable binding different only in representation e.g.
// let _: (@convention(block) () -> Void)? = Bool.random() ? nil : {}
// so same representation should be always favored.
auto loc = getConstraintLocator(locator);
if (loc->findLast<LocatorPathElt::ContextualType>() &&
func1->getRepresentation() != func2->getRepresentation()) {
increaseScore(SK_FunctionConversion, locator);
}
if (!matchFunctionRepresentations(func1->getExtInfo(), func2->getExtInfo(),
kind, Options)) {
return getTypeMatchFailure(locator);
}
// Determine how we match up the input/result types.
ConstraintKind subKind;
switch (kind) {
case ConstraintKind::Bind:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Equal:
subKind = kind;
break;
case ConstraintKind::Subtype:
case ConstraintKind::Conversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion:
subKind = ConstraintKind::Subtype;
break;
case ConstraintKind::ApplicableFunction:
case ConstraintKind::DynamicCallableApplicableFunction:
case ConstraintKind::BindOverload:
case ConstraintKind::CheckedCast:
case ConstraintKind::SubclassOf:
case ConstraintKind::ConformsTo:
case ConstraintKind::TransitivelyConformsTo:
case ConstraintKind::Defaultable:
case ConstraintKind::Disjunction:
case ConstraintKind::Conjunction:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::OptionalObject:
case ConstraintKind::SelfObjectOfProtocol:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueMember:
case ConstraintKind::ValueWitness:
case ConstraintKind::BridgingConversion:
case ConstraintKind::OneWayEqual:
case ConstraintKind::OneWayBindParam:
case ConstraintKind::FallbackType:
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PropertyWrapper:
case ConstraintKind::SyntacticElement:
case ConstraintKind::BindTupleOfFunctionParams:
case ConstraintKind::PackElementOf:
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
llvm_unreachable("Not a relational constraint");
}
// Input types can be contravariant (or equal).
auto argumentLocator =
locator.withPathElement(ConstraintLocator::FunctionArgument);
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
SmallVector<AnyFunctionType::Param, 8> func1Params;
func1Params.append(func1->getParams().begin(), func1->getParams().end());
SmallVector<AnyFunctionType::Param, 8> func2Params;
func2Params.append(func2->getParams().begin(), func2->getParams().end());
// Add a very narrow exception to SE-0110 by allowing functions that
// take multiple arguments to be passed as an argument in places
// that expect a function that takes a single tuple (of the same
// arity);
auto canImplodeParams = [&](ArrayRef<AnyFunctionType::Param> params,
const FunctionType *destFn) {
if (params.size() == 1)
return false;
// We do not support imploding into a @differentiable function.
if (destFn->isDifferentiable())
return false;
for (auto ¶m : params) {
// We generally cannot handle parameter flags, though we can carve out an
// exception for ownership flags such as __owned, which we can thunk, and
// flags that can freely dropped from a function type such as
// @_nonEphemeral. Note that @noDerivative can also be freely dropped, as
// we've already ensured that the destination function is not
// @differentiable.
auto flags = param.getParameterFlags();
flags = flags.withOwnershipSpecifier(
param.isInOut() ? ParamSpecifier::InOut : ParamSpecifier::Default);
flags = flags.withNonEphemeral(false)
.withNoDerivative(false);
if (!flags.isNone())
return false;
}
return true;
};
auto implodeParams = [&](SmallVectorImpl<AnyFunctionType::Param> ¶ms) {
// Form an imploded tuple type, dropping the parameter flags as although
// canImplodeParams makes sure we're not dealing with vargs, inout, etc,
// we may still have e.g ownership flags left over, which we can drop.
auto input = AnyFunctionType::composeTuple(
getASTContext(), params, ParameterFlagHandling::IgnoreNonEmpty);
params.clear();
// If fixes are disabled let's do an easy thing and implode
// tuple directly into parameters list.
if (!shouldAttemptFixes()) {
params.emplace_back(input);
return;
}
// Synthesize new argument and bind it to tuple formed from existing
// arguments, this makes it easier to diagnose cases where we attempt
// a single tuple element formed when no arguments were present.
auto argLoc = argumentLocator.withPathElement(
LocatorPathElt::SynthesizedArgument(0));
auto *typeVar = createTypeVariable(getConstraintLocator(argLoc),
TVO_CanBindToNoEscape);
params.emplace_back(typeVar);
assignFixedType(typeVar, input);
};
{
SmallVector<LocatorPathElt, 4> path;
locator.getLocatorParts(path);
// Find the last path element, skipping OptionalPayload elements
// so that we allow this exception in cases of optional injection.
auto last = std::find_if(
path.rbegin(), path.rend(), [](LocatorPathElt &elt) -> bool {
return elt.getKind() != ConstraintLocator::OptionalPayload;
});
auto &ctx = getASTContext();
if (last != path.rend()) {
if (last->getKind() == ConstraintLocator::ApplyArgToParam) {
if (isSingleTupleParam(ctx, func2Params) &&
canImplodeParams(func1Params, /*destFn*/ func2)) {
implodeParams(func1Params);
increaseScore(SK_FunctionConversion, locator);
} else if (!ctx.isSwiftVersionAtLeast(5) &&
isSingleTupleParam(ctx, func1Params) &&
canImplodeParams(func2Params, /*destFn*/ func1)) {
auto *simplified = locator.trySimplifyToExpr();
// We somehow let tuple unsplatting function conversions
// through in some cases in Swift 4, so let's let that
// continue to work, but only for Swift 4.
if (simplified &&
(isa<DeclRefExpr>(simplified) ||
isa<OverloadedDeclRefExpr>(simplified) ||
isa<UnresolvedDeclRefExpr>(simplified))) {
implodeParams(func2Params);
increaseScore(SK_FunctionConversion, locator);
}
}
} else if (last->is<LocatorPathElt::PatternMatch>() &&
isa<EnumElementPattern>(
last->castTo<LocatorPathElt::PatternMatch>()
.getPattern())) {
// A single paren pattern becomes a labeled tuple pattern
// e.g. `case .test(let value):` should be able to match
// `case test(result: Int)`. Note that it also means that:
// `cast test(result: (String, Int))` would be matched against
// e.g. `case .test((let x, let y))` but that fails during
// pattern coercion (behavior consistent with what happens in
// `TypeCheckPattern`).
if (func1Params.size() == 1 && !func1Params.front().hasLabel() &&
func2Params.size() == 1 && func2Params.front().hasLabel()) {
auto param = func1Params.front();
auto label = func2Params.front().getLabel();
auto labeledParam = FunctionType::Param(param.getPlainType(), label,
param.getParameterFlags());
func1Params.clear();
func1Params.push_back(labeledParam);
}
// Consider following example:
//
// enum E {
// case foo((x: Int, y: Int))
// case bar(x: Int, y: Int)
// }
//
// func test(e: E) {
// if case .foo(let x, let y) = e {}
// if case .bar(let tuple) = e {}
// }
//
// Both of `if case` expressions have to be supported:
//
// 1. `case .foo(let x, let y) = e` allows a single tuple
// parameter to be "destructured" into multiple arguments.
//
// 2. `case .bar(let tuple) = e` allows to match multiple
// parameters with a single tuple argument.
if (isSingleTupleParam(ctx, func1Params) &&
canImplodeParams(func2Params, /*destFn*/ func1)) {
implodeParams(func2Params);
increaseScore(SK_FunctionConversion, locator);
} else if (isSingleTupleParam(ctx, func2Params) &&
canImplodeParams(func1Params, /*destFn*/ func2)) {
implodeParams(func1Params);
increaseScore(SK_FunctionConversion, locator);
}
}
}
if (shouldAttemptFixes()) {
auto *anchor = locator.trySimplifyToExpr();
if (isa_and_nonnull<ClosureExpr>(anchor) &&
isSingleTupleParam(ctx, func2Params) &&
canImplodeParams(func1Params, /*destFn*/ func2)) {
auto *fix = AllowClosureParamDestructuring::create(
*this, func2, getConstraintLocator(anchor));
if (recordFix(fix))
return getTypeMatchFailure(argumentLocator);
implodeParams(func1Params);
}
}
}
// https://github.com/apple/swift/issues/49345
// Add a super-narrow hack to allow '(()) -> T' to be passed in place
// of '() -> T'.
if (getASTContext().isSwiftVersionAtLeast(4) &&
!getASTContext().isSwiftVersionAtLeast(5)) {
SmallVector<LocatorPathElt, 4> path;
locator.getLocatorParts(path);
// Find the last path element, skipping GenericArgument elements
// so that we allow this exception in cases of optional types, and
// skipping OptionalPayload elements so that we allow this
// exception in cases of optional injection.
auto last = std::find_if(
path.rbegin(), path.rend(), [](LocatorPathElt &elt) -> bool {
return elt.getKind() != ConstraintLocator::GenericArgument &&
elt.getKind() != ConstraintLocator::OptionalPayload;
});
if (last != path.rend()) {
if (last->getKind() == ConstraintLocator::ApplyArgToParam) {
if (isSingleTupleParam(getASTContext(), func1Params) &&
func1Params[0].getOldType()->isVoid()) {
if (func2Params.empty()) {
func2Params.emplace_back(getASTContext().TheEmptyTupleType);
}
}
}
}
}
// FIXME: ParamPackMatcher should completely replace the non-variadic
// case too eventually.
if (containsPackExpansionType(func1Params) ||
containsPackExpansionType(func2Params)) {
ParamPackMatcher matcher(func1Params, func2Params, getASTContext(),
isPackExpansionType);
if (matcher.match())
return getTypeMatchFailure(locator);
for (auto pair : matcher.pairs) {
// Compare the parameter types, taking contravariance into account.
auto result = matchTypes(pair.rhs, pair.lhs, subKind, subflags,
(func1Params.size() == 1
? argumentLocator
: argumentLocator.withPathElement(
LocatorPathElt::TupleElement(pair.lhsIdx))));
if (result.isFailure())
return result;
}
} else {
int diff = func1Params.size() - func2Params.size();
if (diff != 0) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(argumentLocator);
auto *loc = getConstraintLocator(locator);
// If this is conversion between optional (or IUO) parameter
// and argument, let's drop the last path element so locator
// could be simplified down to an argument expression.
//
// func foo(_: ((Int, Int) -> Void)?) {}
// _ = foo { _ in } <- missing second closure parameter.
if (loc->isLastElement<LocatorPathElt::OptionalPayload>()) {
auto path = loc->getPath();
loc = getConstraintLocator(loc->getAnchor(), path.drop_back());
}
auto anchor = simplifyLocatorToAnchor(loc);
if (!anchor)
return getTypeMatchFailure(argumentLocator);
// The param diff is in a function type coercion context
//
// func fn(_: Int) {}
// let i: Int = 0
// (fn as (Int, Int) -> Void)(i, i)
//
// Since we are not in a function argument application, simply record
// a function type mismatch instead of an argument fix.
// Except for when a closure is a subexpr because closure expr parameters
// syntax can be added or removed by missing/extraneous arguments fix.
if (loc->isForCoercion() && !isExpr<ClosureExpr>(anchor)) {
auto *fix = ContextualMismatch::create(*this, func1, func2, loc);
if (recordFix(fix))
return getTypeMatchFailure(argumentLocator);
} else {
// If there are missing arguments, let's add them
// using parameter as a template.
if (diff < 0) {
if (fixMissingArguments(*this, anchor, func1Params, func2Params,
abs(diff), loc))
return getTypeMatchFailure(argumentLocator);
} else {
// If there are extraneous arguments, let's remove
// them from the list.
if (fixExtraneousArguments(*this, func2, func1Params, diff, loc))
return getTypeMatchFailure(argumentLocator);
}
}
if (diff > 0) {
// Drop all of the extraneous arguments.
auto numParams = func2Params.size();
func1Params.erase(func1Params.begin() + numParams, func1Params.end());
}
}
bool hasLabelingFailures = false;
for (unsigned i : indices(func1Params)) {
auto func1Param = func1Params[i];
auto func2Param = func2Params[i];
// Increase the score if matching an autoclosure parameter to an function
// type, so we enforce that non-autoclosure overloads are preferred.
//
// func autoclosure(f: () -> Int) { }
// func autoclosure(f: @autoclosure () -> Int) { }
//
// let _ = autoclosure as (() -> (Int)) -> () // non-autoclosure preferred
//
auto isAutoClosureFunctionMatch = [](AnyFunctionType::Param ¶m1,
AnyFunctionType::Param ¶m2) {
return param1.isAutoClosure() &&
(!param2.isAutoClosure() &&
param2.getPlainType()->is<FunctionType>());
};
if (isAutoClosureFunctionMatch(func1Param, func2Param) ||
isAutoClosureFunctionMatch(func2Param, func1Param)) {
increaseScore(SK_FunctionToAutoClosureConversion, locator);
}
// Variadic bit must match.
if (func1Param.isVariadic() != func2Param.isVariadic()) {
if (!(shouldAttemptFixes() && func2Param.isVariadic()))
return getTypeMatchFailure(argumentLocator);
auto argType =
getFixedTypeRecursive(func1Param.getPlainType(), /*wantRValue=*/true);
auto varargsType = func2Param.getPlainType();
// Delay solving this constraint until argument is resolved.
if (argType->is<TypeVariableType>()) {
addUnsolvedConstraint(Constraint::create(
*this, kind, func1, func2, getConstraintLocator(locator)));
return getTypeMatchSuccess();
}
auto *fix = ExpandArrayIntoVarargs::attempt(
*this, argType, varargsType,
argumentLocator.withPathElement(LocatorPathElt::ApplyArgToParam(
i, i, func2Param.getParameterFlags())));
if (!fix || recordFix(fix))
return getTypeMatchFailure(argumentLocator);
continue;
}
// Labels must match.
//
// FIXME: We should not end up with labels here at all, but we do
// from invalid code in diagnostics, and as a result of code completion
// directly building constraint systems.
if (func1Param.getLabel() != func2Param.getLabel()) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(argumentLocator);
// If we are allowed to attempt fixes, let's ignore labeling
// failures, and create a fix to re-label arguments if types
// line up correctly.
hasLabelingFailures = true;
}
// "isolated" can be added as a subtype relation, but otherwise must match.
if (func1Param.isIsolated() != func2Param.isIsolated() &&
!(func2Param.isIsolated() && subKind >= ConstraintKind::Subtype)) {
return getTypeMatchFailure(argumentLocator);
}
// If functions are differentiable, ensure that @noDerivative is not
// discarded.
if (func1->isDifferentiable() && func2->isDifferentiable() &&
func1Param.isNoDerivative() && !func2Param.isNoDerivative()) {
return getTypeMatchFailure(argumentLocator);
}
// Do not allow for functions that expect a sending parameter to match
// with a function that expects a non-sending parameter.
if (func1Param.getParameterFlags().isSending() &&
!func2Param.getParameterFlags().isSending()) {
auto *fix = AllowSendingMismatch::create(
*this, getConstraintLocator(argumentLocator), func1, func2,
AllowSendingMismatch::Kind::Parameter);
if (recordFix(fix))
return getTypeMatchFailure(argumentLocator);
}
// FIXME: We should check value ownership too, but it's not completely
// trivial because of inout-to-pointer conversions.
// Compare the parameter types, taking contravariance into account.
auto result = matchTypes(
func2Param.getOldType(), func1Param.getOldType(), subKind, subflags,
(func1Params.size() == 1 ? argumentLocator
: argumentLocator.withPathElement(
LocatorPathElt::TupleElement(i))));
if (result.isFailure())
return result;
}
if (hasLabelingFailures && !hasFixFor(loc)) {
ConstraintFix *fix =
loc->isLastElement<LocatorPathElt::ApplyArgToParam>()
? AllowArgumentMismatch::create(*this, func1, func2, loc)
: ContextualMismatch::create(*this, func1, func2, loc);
if (recordFix(fix))
return getTypeMatchFailure(argumentLocator);
}
}
// Result type can be covariant (or equal).
return matchTypes(func1->getResult(), func2->getResult(), subKind,
subflags,
locator.withPathElement(ConstraintLocator::FunctionResult));
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchSuperclassTypes(Type type1, Type type2,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
auto classDecl2 = type2->getClassOrBoundGenericClass();
SmallPtrSet<ClassDecl *, 4> superclasses1;
for (auto super1 = type1->getSuperclass();
super1;
super1 = super1->getSuperclass()) {
auto superclass1 = super1->getClassOrBoundGenericClass();
if (superclass1 != classDecl2) {
// Break if we have circular inheritance.
if (superclass1 && !superclasses1.insert(superclass1).second)
break;
continue;
}
return matchTypes(super1, type2, ConstraintKind::Bind,
subflags, locator);
}
return getTypeMatchFailure(locator);
}
static ConstraintSystem::TypeMatchResult matchDeepTypeArguments(
ConstraintSystem &cs, ConstraintSystem::TypeMatchOptions subflags,
ArrayRef<Type> args1, ArrayRef<Type> args2,
ConstraintLocatorBuilder locator,
llvm::function_ref<void(unsigned)> recordMismatch = [](unsigned) {}) {
if (args1.size() != args2.size()) {
return cs.getTypeMatchFailure(locator);
}
auto allMatch = cs.getTypeMatchSuccess();
for (unsigned i = 0, n = args1.size(); i != n; ++i) {
auto result = cs.matchTypes(
args1[i], args2[i], ConstraintKind::Bind, subflags,
locator.withPathElement(LocatorPathElt::GenericArgument(i)));
if (result.isFailure()) {
recordMismatch(i);
allMatch = result;
}
}
return allMatch;
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchDeepEqualityTypes(Type type1, Type type2,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = TMF_GenerateConstraints;
// Handle opaque archetypes.
if (auto arch1 = type1->getAs<ArchetypeType>()) {
auto arch2 = type2->castTo<ArchetypeType>();
auto opaque1 = cast<OpaqueTypeArchetypeType>(arch1);
auto opaque2 = cast<OpaqueTypeArchetypeType>(arch2);
assert(opaque1->getDecl() == opaque2->getDecl());
// It's possible to declare a generic requirement like Self == Self.Iterator
// where both types are going to be opaque.
if (!opaque1->getCanonicalInterfaceType(arch1->getInterfaceType())
->isEqual(
opaque2->getCanonicalInterfaceType(arch2->getInterfaceType())))
return getTypeMatchFailure(locator);
auto args1 = opaque1->getSubstitutions().getReplacementTypes();
auto args2 = opaque2->getSubstitutions().getReplacementTypes();
if (!shouldAttemptFixes()) {
// Match up the replacement types of the respective substitution maps.
return matchDeepTypeArguments(*this, subflags, args1, args2, locator);
}
unsigned numMismatches = 0;
auto result =
matchDeepTypeArguments(*this, subflags, args1, args2, locator,
[&numMismatches](unsigned) { ++numMismatches; });
if (numMismatches > 0) {
auto anchor = locator.getAnchor();
// TODO(diagnostics): Only assignments are supported at the moment.
if (!isExpr<AssignExpr>(anchor))
return getTypeMatchFailure(locator);
auto *fix = IgnoreAssignmentDestinationType::create(
*this, type1, type2, getConstraintLocator(locator));
if (recordFix(fix, /*impact=*/numMismatches))
return getTypeMatchFailure(locator);
return getTypeMatchSuccess();
}
return result;
}
// Handle existential types.
if (auto *existential1 = type1->getAs<ExistentialType>()) {
auto existential2 = type2->castTo<ExistentialType>();
auto result = matchTypes(existential1->getConstraintType(),
existential2->getConstraintType(),
ConstraintKind::Bind, subflags,
locator.withPathElement(
ConstraintLocator::ExistentialConstraintType));
if (result.isFailure())
return result;
return getTypeMatchSuccess();
}
// Arguments of parameterized protocol types have to match on the nose.
if (auto ppt1 = type1->getAs<ParameterizedProtocolType>()) {
auto ppt2 = type2->castTo<ParameterizedProtocolType>();
auto result = matchTypes(ppt1->getBaseType(),
ppt2->getBaseType(),
ConstraintKind::Bind, subflags,
locator.withPathElement(
ConstraintLocator::ParentType));
if (result.isFailure())
return result;
return matchDeepTypeArguments(*this, subflags,
ppt1->getArgs(),
ppt2->getArgs(),
locator);
}
if (type1->isExistentialType()) {
auto layout1 = type1->getExistentialLayout();
auto layout2 = type2->getExistentialLayout();
// Explicit AnyObject and protocols must match exactly.
if (layout1.hasExplicitAnyObject != layout2.hasExplicitAnyObject)
return getTypeMatchFailure(locator);
if (layout1.getProtocols().size() != layout2.getProtocols().size())
return getTypeMatchFailure(locator);
for (unsigned i: indices(layout1.getProtocols())) {
if (layout1.getProtocols()[i] != layout2.getProtocols()[i])
return getTypeMatchFailure(locator);
}
// This is the only interesting case. We might have type variables
// on either side of the superclass constraint, so make sure we
// recursively call matchTypes() here.
if (layout1.explicitSuperclass || layout2.explicitSuperclass) {
if (!layout1.explicitSuperclass || !layout2.explicitSuperclass)
return getTypeMatchFailure(locator);
auto subLocator = locator.withPathElement(
ConstraintLocator::ProtocolCompositionSuperclassType);
auto result = matchTypes(layout1.explicitSuperclass,
layout2.explicitSuperclass,
ConstraintKind::Bind, subflags,
subLocator);
if (result.isFailure())
return result;
}
return getTypeMatchSuccess();
}
// Handle nominal types that are not directly generic.
if (auto nominal1 = type1->getAs<NominalType>()) {
auto nominal2 = type2->castTo<NominalType>();
assert((bool)nominal1->getParent() == (bool)nominal2->getParent() &&
"Mismatched parents of nominal types");
if (!nominal1->getParent())
return getTypeMatchSuccess();
// Match up the parents, exactly.
return matchTypes(nominal1->getParent(), nominal2->getParent(),
ConstraintKind::Bind, subflags,
locator.withPathElement(ConstraintLocator::ParentType));
}
auto bound1 = type1->castTo<BoundGenericType>();
auto bound2 = type2->castTo<BoundGenericType>();
// Match up the parents, exactly, if there are parents.
assert((bool)bound1->getParent() == (bool)bound2->getParent() &&
"Mismatched parents of bound generics");
if (bound1->getParent()) {
auto result = matchTypes(bound1->getParent(), bound2->getParent(),
ConstraintKind::Bind, subflags,
locator.withPathElement(
ConstraintLocator::ParentType));
if (result.isFailure())
return result;
}
auto args1 = bound1->getGenericArgs();
auto args2 = bound2->getGenericArgs();
// Match up the generic arguments, exactly.
if (shouldAttemptFixes()) {
auto *baseLoc =
getConstraintLocator(locator, {LocatorPathElt::GenericType(bound1),
LocatorPathElt::GenericType(bound2)});
auto argMatchingFlags = subflags;
// Allow the solver to produce separate fixes while matching
// key path's root/value to a contextual type instead of the
// standard one fix for all mismatched generic arguments
// because at least one side of such a relation would be resolved.
if (!isExpr<KeyPathExpr>(locator.trySimplifyToExpr())) {
argMatchingFlags |= TMF_ApplyingFix;
argMatchingFlags |= TMF_MatchingGenericArguments;
}
// Optionals have a lot of special diagnostics and only one
// generic argument so if we' re dealing with one, don't produce generic
// arguments mismatch fixes.
if (bound1->getDecl()->isOptionalDecl())
return matchDeepTypeArguments(*this, argMatchingFlags, args1, args2,
baseLoc);
SmallVector<unsigned, 4> mismatches;
auto result = matchDeepTypeArguments(
*this, argMatchingFlags, args1, args2, baseLoc,
[&mismatches](unsigned position) { mismatches.push_back(position); });
if (mismatches.empty())
return result;
auto *loc = getConstraintLocator(locator);
auto path = loc->getPath();
if (!path.empty()) {
// If we have something like ... -> type req # -> pack element #, we're
// solving a requirement of the form T : P where T is a type parameter pack
if (path.back().is<LocatorPathElt::PackElement>())
path = path.drop_back();
if (path.back().is<LocatorPathElt::AnyRequirement>()) {
if (auto *fix = fixRequirementFailure(*this, type1, type2, locator)) {
if (recordFix(fix))
return getTypeMatchFailure(locator);
increaseScore(SK_Fix, loc, mismatches.size());
return getTypeMatchSuccess();
}
}
}
unsigned impact = 1;
if (type1->getAnyPointerElementType() &&
type2->getAnyPointerElementType()) {
// If this is a pointer <-> pointer conversion of different kind,
// there is a dedicated restriction/fix for that in some cases.
// To accommodate that, let's increase the impact of this fix.
impact += 2;
} else {
// Increase the solution's score for each mismatch this fixes.
impact += mismatches.size() - 1;
}
auto *fix = GenericArgumentsMismatch::create(
*this, type1, type2, mismatches, loc);
if (!recordFix(fix, impact))
return getTypeMatchSuccess();
return result;
}
return matchDeepTypeArguments(*this, subflags, args1, args2, locator);
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchExistentialTypes(Type type1, Type type2,
ConstraintKind kind,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// If the first type is a type variable or member thereof, there's nothing
// we can do now.
if (type1->isTypeVariableOrMember()) {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, kind, type1, type2,
getConstraintLocator(locator)));
return getTypeMatchSuccess();
}
return getTypeMatchAmbiguous();
}
// FIXME: Feels like a hack.
if (type1->is<InOutType>())
return getTypeMatchFailure(locator);
// FIXME; Feels like a hack...nothing actually "conforms" here, and
// we need to disallow conversions from types containing @noescape
// functions to Any.
// FIXME: special case for nonescaping functions and tuples containing them
// shouldn't be needed, as functions have conformances to Escapable/Copyable.
if (type2->isAny() && type1->isNoEscape()) {
if (shouldAttemptFixes()) {
auto *fix = MarkExplicitlyEscaping::create(*this, type1, type2,
getConstraintLocator(locator));
if (!recordFix(fix))
return getTypeMatchSuccess();
}
return getTypeMatchFailure(locator);
}
// ConformsTo constraints are generated when opening a generic
// signature with a RequirementKind::Conformance requirement, so
// we must handle pack types on the left by splitting up into
// smaller constraints.
if (auto *packType = type1->getAs<PackType>()) {
for (unsigned i = 0, e = packType->getNumElements(); i < e; ++i) {
addConstraint(kind, packType->getElementType(i), type2,
locator.withPathElement(LocatorPathElt::PackElement(i)));
}
return getTypeMatchSuccess();
}
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
// Handle existential metatypes.
if (auto meta1 = type1->getAs<MetatypeType>()) {
ExistentialMetatypeType *meta2;
if (auto existential = type2->getAs<ExistentialType>()) {
meta2 = existential->getConstraintType()->getAs<ExistentialMetatypeType>();
} else {
meta2 = type2->getAs<ExistentialMetatypeType>();
}
if (meta2) {
return matchExistentialTypes(meta1->getInstanceType(),
meta2->getInstanceType(), kind, subflags,
locator.withPathElement(
ConstraintLocator::InstanceType));
}
}
if (!type2->isExistentialType())
return getTypeMatchFailure(locator);
auto layout = type2->getExistentialLayout();
if (auto layoutConstraint = layout.getLayoutConstraint()) {
if (layoutConstraint->isClass()) {
if (kind == ConstraintKind::ConformsTo) {
if (!type1->satisfiesClassConstraint()) {
if (shouldAttemptFixes()) {
if (auto last = locator.last()) {
// If solver is in diagnostic mode and type1 is a hole, or if this
// is a superclass requirement, let's consider `AnyObject`
// conformance solved. The actual superclass requirement
// will also fail (because type can't satisfy it), and it's
// more interesting for diagnostics.
auto req = last->getAs<LocatorPathElt::AnyRequirement>();
if (!req)
return getTypeMatchFailure(locator);
// Superclass constraints are never satisfied by existentials,
// even those that contain the superclass a la `any C & P`.
if (!type1->isExistentialType() &&
(type1->isPlaceholder() ||
req->getRequirementKind() == RequirementKind::Superclass))
return getTypeMatchSuccess();
auto *fix = fixRequirementFailure(*this, type1, type2, locator);
if (fix && !recordFix(fix)) {
recordFixedRequirement(getConstraintLocator(locator), type2);
return getTypeMatchSuccess();
}
}
}
return getTypeMatchFailure(locator);
}
} else {
// Subtype relation to AnyObject also allows class-bound
// existentials that are not @objc and therefore carry
// witness tables.
if (!type1->isClassExistentialType() && !type1->mayHaveSuperclass()) {
if (shouldAttemptFixes()) {
llvm::SmallVector<LocatorPathElt, 4> path;
if (auto anchor = locator.getLocatorParts(path)) {
// Let's drop `optional` or `generic argument` bits from
// locator because that helps to diagnose reference equality
// operators ("===" and "!==") since there is always a
// `value-to-optional` or `optional-to-optional` conversion
// associated with them (expected argument is `AnyObject?`).
if (!path.empty() &&
(path.back().is<LocatorPathElt::OptionalPayload>() ||
path.back().is<LocatorPathElt::GenericArgument>()))
path.pop_back();
auto *fix = AllowNonClassTypeToConvertToAnyObject::create(
*this, type1, getConstraintLocator(anchor, path));
return recordFix(fix) ? getTypeMatchFailure(locator)
: getTypeMatchSuccess();
}
}
return getTypeMatchFailure(locator);
}
}
// Keep going.
}
}
if (layout.explicitSuperclass) {
auto subKind = std::min(ConstraintKind::Subtype, kind);
auto result = matchTypes(type1, layout.explicitSuperclass, subKind,
subflags, locator);
if (result.isFailure())
return result;
}
for (auto *protoDecl : layout.getProtocols()) {
switch (simplifyConformsToConstraint(type1, protoDecl, kind, locator,
subflags)) {
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
case SolutionKind::Error: {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);
SmallVector<LocatorPathElt, 4> path;
auto anchor = locator.getLocatorParts(path);
// If the path ends at `optional payload` it means that this
// check is part of an implicit value-to-optional conversion,
// and it could be safely dropped.
if (!path.empty() && path.back().is<LocatorPathElt::OptionalPayload>())
path.pop_back();
// Determine whether this conformance mismatch is
// associated with argument to a call, and if so
// produce a tailored fix.
if (!path.empty()) {
auto last = path.back();
if (last.is<LocatorPathElt::ApplyArgToParam>()) {
auto proto = protoDecl->getDeclaredInterfaceType();
// Impact is 2 here because there are two failures
// 1 - missing conformance and 2 - incorrect argument type.
//
// This would make sure that arguments with incorrect
// conformances are not prioritized over general argument
// mismatches.
if (type1->isOptional()) {
auto unwrappedType = type1->lookThroughAllOptionalTypes();
auto result = simplifyConformsToConstraint(
unwrappedType, protoDecl, kind, locator,
subflags | TMF_ApplyingFix);
if (result == SolutionKind::Solved) {
auto fix = ForceOptional::create(*this, type1, proto,
getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
break;
}
}
auto fix = AllowArgumentMismatch::create(
*this, type1, proto, getConstraintLocator(anchor, path));
if (recordFix(fix, /*impact=*/2))
return getTypeMatchFailure(locator);
break;
}
// TODO(diagnostics): If there are any requirement failures associated
// with result types which are part of a function type conversion,
// let's record general conversion mismatch in order for it to capture
// and display complete function types.
//
// Once either reacher locators or better diagnostic presentation for
// nested type failures is available this check could be removed.
if (last.is<LocatorPathElt::FunctionResult>())
return getTypeMatchFailure(locator);
// If instance types didn't line up correctly, let's produce a
// diagnostic which mentions them together with their metatypes.
if (last.is<LocatorPathElt::InstanceType>())
return getTypeMatchFailure(locator);
} else { // There are no elements in the path
if (!(isExpr<AssignExpr>(anchor) || isExpr<CoerceExpr>(anchor)))
return getTypeMatchFailure(locator);
}
if (isExpr<CoerceExpr>(anchor)) {
auto *fix = ContextualMismatch::create(
*this, type1, type2, getConstraintLocator(anchor, path));
if (recordFix(fix))
return getTypeMatchFailure(locator);
break;
}
auto proto = protoDecl->getDeclaredInterfaceType();
auto *fix = MissingConformance::forContextual(
*this, type1, proto, getConstraintLocator(anchor, path));
if (recordFix(fix))
return getTypeMatchFailure(locator);
break;
}
}
}
auto constraintType1 = type1;
if (auto existential = constraintType1->getAs<ExistentialType>())
constraintType1 = existential->getConstraintType();
auto constraintType2 = type2;
if (auto existential = constraintType2->getAs<ExistentialType>())
constraintType2 = existential->getConstraintType();
auto ppt1 = constraintType1->getAs<ParameterizedProtocolType>();
auto ppt2 = constraintType2->getAs<ParameterizedProtocolType>();
// With two parameterized protocols, we've already made sure conformance
// constraints are satisfied. Try to match the arguments!
if (ppt1 && ppt2) {
ArrayRef<Type> longerArgs = ppt1->getArgs();
ArrayRef<Type> shorterArgs = ppt2->getArgs();
// The more constrained of the two types had better be the first type -
// otherwise we're forgetting requirements.
if (longerArgs.size() < shorterArgs.size()) {
return getTypeMatchFailure(locator);
}
// Line up the arguments of the parameterized protocol.
// FIXME: Extend the locator path to point to the argument
// inducing the requirement.
for (const auto &pair : llvm::zip_first(shorterArgs, longerArgs)) {
auto result = matchTypes(std::get<0>(pair), std::get<1>(pair),
ConstraintKind::Bind,
subflags, locator);
if (result.isFailure())
return result;
}
} else if (ppt1 && type2->isExistentialType()) {
// P<T, U, V, ...> converts to (P & Q & ...) trivially...
return getTypeMatchSuccess();
} else if (ppt2 && type1->isExistentialType()) {
// But (P & Q & ...) does not convert to P<T, U, V, ...>
return getTypeMatchFailure(locator);
} else if (ppt1 || ppt2) {
auto parameterized = constraintType1;
auto base = constraintType2;
if (ppt2)
std::swap(parameterized, base);
// One of the two is parameterized, and the other is a concrete type.
// Substitute the base into the requirements of the parameterized type and
// discharge the requirements of the parameterized protocol.
// FIXME: Extend the locator path to point to the argument
// inducing the requirement.
SmallVector<Requirement, 2> reqs;
parameterized->castTo<ParameterizedProtocolType>()
->getRequirements(base, reqs);
for (const auto &req : reqs) {
assert(req.getKind() == RequirementKind::SameType);
auto result = matchTypes(req.getFirstType(), req.getSecondType(),
ConstraintKind::Bind,
subflags, locator);
if (result.isFailure())
return result;
}
}
return getTypeMatchSuccess();
}
static bool isStringCompatiblePointerBaseType(ASTContext &ctx,
Type baseType) {
// Allow strings to be passed to pointer-to-byte or pointer-to-void types.
if (baseType->isInt8())
return true;
if (baseType->isUInt8())
return true;
if (baseType->isVoid())
return true;
return false;
}
/// Determine whether the first type with the given number of optionals
/// is potentially more optional than the second type with its number of
/// optionals.
static bool isPotentiallyMoreOptionalThan(Type type1, Type type2) {
SmallVector<Type, 2> optionals1;
Type objType1 = type1->lookThroughAllOptionalTypes(optionals1);
auto numOptionals1 = optionals1.size();
SmallVector<Type, 2> optionals2;
type2->lookThroughAllOptionalTypes(optionals2);
auto numOptionals2 = optionals2.size();
if (numOptionals1 <= numOptionals2 && !objType1->isTypeVariableOrMember())
return false;
return true;
}
/// Enumerate all of the applicable optional conversion restrictions
static void enumerateOptionalConversionRestrictions(
Type type1, Type type2,
ConstraintKind kind, ConstraintLocatorBuilder locator,
llvm::function_ref<void(ConversionRestrictionKind)> fn) {
// Optional-to-optional.
if (type1->getOptionalObjectType() && type2->getOptionalObjectType())
fn(ConversionRestrictionKind::OptionalToOptional);
// Inject a value into an optional.
if (isPotentiallyMoreOptionalThan(type2, type1)) {
fn(ConversionRestrictionKind::ValueToOptional);
}
}
/// Determine whether we can bind the given type variable to the given
/// fixed type.
static bool isBindable(TypeVariableType *typeVar, Type type) {
// Disallow recursive bindings.
if (ConstraintSystem::typeVarOccursInType(typeVar, type))
return false;
// If type variable we are about to bind represents a pack
// expansion type, allow the binding to happen regardless of
// what the \c type is, because contextual type is just a hint
// in this situation and type variable would be bound to its
// opened type instead.
//
// Note that although inference doesn't allow direct bindings to
// type variables, they can still get through via `matchTypes`
// when type is a partially resolved pack expansion that simplifies
// down to a type variable.
return typeVar->getImpl().isPackExpansion() ||
!(type->is<TypeVariableType>() || type->is<DependentMemberType>());
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchTypesBindTypeVar(
TypeVariableType *typeVar, Type origType, ConstraintKind kind,
TypeMatchOptions flags, ConstraintLocatorBuilder locator,
llvm::function_ref<TypeMatchResult()> formUnsolvedResult) {
assert(typeVar->is<TypeVariableType>() && "Expected a type variable!");
assert(!origType->is<TypeVariableType>() && "Expected a non-type variable!");
// Simplify the right-hand type and perform the "occurs" check.
typeVar = getRepresentative(typeVar);
auto type = simplifyType(origType, flags);
if (!isBindable(typeVar, type)) {
if (shouldAttemptFixes()) {
// If type variable is allowed to be a hole and it can't be bound to
// a particular (full resolved) type, just ignore this binding
// instead of re-trying it and failing later.
if (typeVar->getImpl().canBindToHole() && !type->hasTypeVariable())
return getTypeMatchSuccess();
// Just like in cases where both sides are dependent member types
// with resolved base that can't be simplified to a concrete type
// let's ignore this mismatch and mark affected type variable as a hole
// because something else has to be fixed already for this to happen.
if (type->is<DependentMemberType>() && !type->hasTypeVariable()) {
// Since the binding couldn't be performed, the type variable is a
// hole regardless whether it would be bound later to some other
// type or not. If this is not reflected in constraint system
// it would let the solver to form a _valid_ solution as if the
// constraint between the type variable and the unresolved dependent
// member type never existed.
increaseScore(SK_Hole, locator);
recordPotentialHole(typeVar);
return getTypeMatchSuccess();
}
}
return formUnsolvedResult();
}
// Since member lookup doesn't check requirements
// it might sometimes return types which are not
// visible in the current context e.g. typealias
// defined in constrained extension, substitution
// of which might produce error type for base, so
// assignment should tread lightly and just fail
// if it encounters such types.
if (type->hasError())
return getTypeMatchFailure(locator);
// Equal constraints allow mixed LValue/RValue bindings, but
// if we bind a type to a type variable that can bind to
// LValues as part of simplifying the Equal constraint we may
// later block a binding of the opposite "LValue-ness" to the
// same type variable that happens as part of simplifying
// another constraint.
if (kind == ConstraintKind::Equal) {
if (typeVar->getImpl().canBindToLValue())
return formUnsolvedResult();
type = type->getRValueType();
}
// Attempt to fix situations where type variable can't be bound
// to a particular type e.g. `l-value` or `inout`.
auto fixReferenceMismatch = [&](TypeVariableType *typeVar,
Type type) -> bool {
if (locator.endsWith<LocatorPathElt::ContextualType>()) {
auto *fix = IgnoreContextualType::create(*this, typeVar, type,
getConstraintLocator(locator));
return !recordFix(fix);
}
return false;
};
// If the left-hand type variable cannot bind to an lvalue,
// but we still have an lvalue, fail.
if (!typeVar->getImpl().canBindToLValue() && type->hasLValueType()) {
if (shouldAttemptFixes() && fixReferenceMismatch(typeVar, type))
return getTypeMatchSuccess();
return getTypeMatchFailure(locator);
}
// If the left-hand type variable cannot bind to an inout,
// but we still have an inout, fail.
if (!typeVar->getImpl().canBindToInOut() && type->is<InOutType>()) {
if (shouldAttemptFixes() && fixReferenceMismatch(typeVar, type))
return getTypeMatchSuccess();
return getTypeMatchFailure(locator);
}
// If the left-hand type variable cannot bind to a non-escaping type,
// but we still have a non-escaping type, fail.
if (!typeVar->getImpl().canBindToNoEscape() && type->isNoEscape()) {
if (shouldAttemptFixes()) {
auto *fix = MarkExplicitlyEscaping::create(*this, typeVar, type,
getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
// Allow no-escape function to be bound with recorded fix.
} else {
return getTypeMatchFailure(locator);
}
}
if (typeVar->getImpl().isPackExpansion()) {
if (!flags.contains(TMF_BindingTypeVariable))
return formUnsolvedResult();
return resolvePackExpansion(typeVar, origType)
? getTypeMatchSuccess()
: getTypeMatchFailure(locator);
}
// If we're attempting to bind a PackType or PackArchetypeType to a type
// variable that doesn't support it, we have a pack reference outside of a
// pack expansion expression.
if (!typeVar->getImpl().canBindToPack() &&
(type->is<PackArchetypeType>() || type->is<PackType>())) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);
auto *fix = AllowInvalidPackReference::create(
*this, type, getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
// Don't allow the invalid pack reference to propagate to other
// bindings.
type = PlaceholderType::get(typeVar->getASTContext(), typeVar);
}
// Binding to a pack expansion type is always an error in Swift 6 mode.
// This indicates that a pack expansion expression was used in a context
// that doesn't support it.
//
// In Swift 5 and earlier initializer references are handled in a special
// way that uses a type variable to represent a type of the parameter
// list. Such type variables should be allowed to bind to a pack expansion
// type to support cases where initializer has a single unlabeled variadic
// generic parameter - `init(_ data: repeat each T)`.
//
// See BindTupleOfFunctionParams constraint for more details.
if (!typeVar->getImpl().isPackExpansion() && type->is<PackExpansionType>()) {
bool representsParameterList =
typeVar->getImpl()
.getLocator()
->isLastElement<LocatorPathElt::ApplyArgument>();
if (!(typeVar->getImpl().canBindToPack() && representsParameterList) ||
getASTContext().isSwiftVersionAtLeast(6)) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);
auto *fix = AllowInvalidPackExpansion::create(
*this, getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
// Don't allow the pack expansion type to propagate to other
// bindings.
type = PlaceholderType::get(typeVar->getASTContext(), typeVar);
}
}
// We do not allow keypaths to go through AnyObject. Let's create a fix
// so this can be diagnosed later.
if (auto loc = typeVar->getImpl().getLocator()) {
auto locPath = loc->getPath();
if (!locPath.empty() &&
locPath.back().getKind() == ConstraintLocator::KeyPathRoot &&
type->isAnyObject()) {
auto *fix = AllowAnyObjectKeyPathRoot::create(
*this, getConstraintLocator(locator));
if (recordFix(fix))
return getTypeMatchFailure(locator);
}
}
// Okay. Bind below.
// A constraint that binds any pointer to a void pointer is
// ineffective, since any pointer can be converted to a void pointer.
if (kind == ConstraintKind::BindToPointerType && type->isVoid()) {
// Bind type1 to Void only as a last resort.
addConstraint(ConstraintKind::Defaultable, typeVar, type,
getConstraintLocator(locator));
return getTypeMatchSuccess();
}
// When binding a fixed type to a type variable that cannot contain
// lvalues or noescape types, any type variables within the fixed
// type cannot contain lvalues or noescape types either.
if (type->hasTypeVariable()) {
type.visit([&](Type t) {
if (auto *tvt = dyn_cast<TypeVariableType>(t.getPointer())) {
if (!typeVar->getImpl().canBindToLValue()) {
tvt->getImpl().setCanBindToLValue(getSavedBindings(),
/*enabled=*/false);
}
if (!typeVar->getImpl().canBindToNoEscape()) {
tvt->getImpl().setCanBindToNoEscape(getSavedBindings(),
/*enabled=*/false);
}
}
});
}
if (typeVar->getImpl().isClosureType()) {
return resolveClosure(typeVar, type, locator)
? getTypeMatchSuccess()
: getTypeMatchFailure(locator);
}
if (typeVar->getImpl().isTapType()) {
return resolveTapBody(typeVar, type, locator)
? getTypeMatchSuccess()
: getTypeMatchFailure(locator);
}
assignFixedType(typeVar, type, /*updateState=*/true,
/*notifyInference=*/!flags.contains(TMF_BindingTypeVariable));
return getTypeMatchSuccess();
}
static ConstraintFix *fixRequirementFailure(ConstraintSystem &cs, Type type1,
Type type2, ASTNode anchor,
ArrayRef<LocatorPathElt> path) {
// Can't fix not yet properly resolved types.
if (type1->isTypeVariableOrMember() || type2->isTypeVariableOrMember())
return nullptr;
// If we have something like ... -> type req # -> pack element #, we're
// solving a requirement of the form T : P where T is a type parameter pack
if (path.back().is<LocatorPathElt::PackElement>())
path = path.drop_back();
auto req = path.back().castTo<LocatorPathElt::AnyRequirement>();
if (req.isConditionalRequirement()) {
// path is - ... -> open generic -> type req # -> cond req #,
// to identify type requirement we only need `open generic -> type req #`
// part, because that's how fixes for type requirements are recorded.
auto reqPath = path.drop_back();
// If underlying conformance requirement has been fixed,
// then there is no reason to fix up conditional requirements.
if (cs.hasFixFor(cs.getConstraintLocator(anchor, reqPath)))
return nullptr;
}
auto *reqLoc = cs.getConstraintLocator(anchor, path);
switch (req.getRequirementKind()) {
case RequirementKind::SameType:
return SkipSameTypeRequirement::create(cs, type1, type2, reqLoc);
case RequirementKind::SameShape:
return SkipSameShapeRequirement::create(cs, type1, type2, reqLoc);
case RequirementKind::Superclass:
return SkipSuperclassRequirement::create(cs, type1, type2, reqLoc);
case RequirementKind::Layout:
case RequirementKind::Conformance:
return MissingConformance::forRequirement(cs, type1, type2, reqLoc);
}
llvm_unreachable("covered switch");
}
static ConstraintFix *fixPropertyWrapperFailure(
ConstraintSystem &cs, Type baseTy, ConstraintLocator *locator,
llvm::function_ref<bool(SelectedOverload, VarDecl *, Type)> attemptFix,
std::optional<Type> toType = std::nullopt) {
// Don't attempt this fix if this is a key path dynamic member
// lookup which produced no results. Unwrapping or wrapping
// the base type is not going to produce desired results.
if (locator->isForKeyPathDynamicMemberLookup())
return nullptr;
Expr *baseExpr = nullptr;
if (auto *anchor = getAsExpr(locator->getAnchor())) {
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(anchor))
baseExpr = UDE->getBase();
else if (auto *SE = dyn_cast<SubscriptExpr>(anchor))
baseExpr = SE->getBase();
else if (auto *MRE = dyn_cast<MemberRefExpr>(anchor))
baseExpr = MRE->getBase();
else if (auto anchor = simplifyLocatorToAnchor(locator))
baseExpr = getAsExpr(anchor);
}
if (!baseExpr)
return nullptr;
auto resolvedOverload = cs.findSelectedOverloadFor(baseExpr);
if (!resolvedOverload)
return nullptr;
enum class Fix : uint8_t {
ProjectedValue,
PropertyWrapper,
WrappedValue,
};
auto applyFix = [&](Fix fix, VarDecl *decl, Type type) -> ConstraintFix * {
if (!decl->hasInterfaceType() || !type)
return nullptr;
if (baseTy->isEqual(type))
return nullptr;
if (baseTy->is<TypeVariableType>() || type->is<TypeVariableType>())
return nullptr;
if (!attemptFix(*resolvedOverload, decl, type))
return nullptr;
switch (fix) {
case Fix::ProjectedValue:
case Fix::PropertyWrapper:
return UsePropertyWrapper::create(cs, decl, fix == Fix::ProjectedValue,
baseTy, toType.value_or(type),
locator);
case Fix::WrappedValue:
return UseWrappedValue::create(cs, decl, baseTy, toType.value_or(type),
locator);
}
llvm_unreachable("Unhandled Fix type in switch");
};
if (auto projection =
cs.getPropertyWrapperProjectionInfo(*resolvedOverload)) {
if (auto *fix = applyFix(Fix::ProjectedValue, projection->first,
projection->second))
return fix;
}
if (auto wrapper = cs.getPropertyWrapperInformation(*resolvedOverload)) {
if (auto *fix =
applyFix(Fix::PropertyWrapper, wrapper->first, wrapper->second))
return fix;
}
if (auto wrappedProperty =
cs.getWrappedPropertyInformation(*resolvedOverload)) {
if (auto *fix = applyFix(Fix::WrappedValue, wrappedProperty->first,
wrappedProperty->second))
return fix;
}
return nullptr;
}
static bool canBridgeThroughCast(ConstraintSystem &cs, Type fromType,
Type toType) {
// If we have a value of type AnyObject that we're trying to convert to
// a class, force a downcast.
// FIXME: Also allow types bridged through Objective-C classes.
if (fromType->isAnyObject() && toType->getClassOrBoundGenericClass())
return true;
auto bridged = TypeChecker::getDynamicBridgedThroughObjCClass(cs.DC,
fromType, toType);
if (!bridged)
return false;
// Note: don't perform this recovery for NSNumber;
if (auto classType = bridged->getAs<ClassType>()) {
SmallString<16> scratch;
if (classType->getDecl()->isObjC() &&
classType->getDecl()->getObjCRuntimeName(scratch) == "NSNumber")
return false;
}
return true;
}
static bool
repairViaBridgingCast(ConstraintSystem &cs, Type fromType, Type toType,
SmallVectorImpl<RestrictionOrFix> &conversionsOrFixes,
ConstraintLocatorBuilder locator) {
if (fromType->hasTypeVariable() || toType->hasTypeVariable())
return false;
auto objectType1 = fromType->getOptionalObjectType();
auto objectType2 = toType->getOptionalObjectType();
if (objectType1 && !objectType2) {
auto *anchor = locator.trySimplifyToExpr();
if (!anchor)
return false;
if (auto overload = cs.findSelectedOverloadFor(anchor)) {
auto *decl = overload->choice.getDeclOrNull();
if (decl && decl->isImplicitlyUnwrappedOptional())
fromType = objectType1;
}
}
if (!canBridgeThroughCast(cs, fromType, toType))
return false;
if (!TypeChecker::checkedCastMaySucceed(fromType, toType, cs.DC))
return false;
conversionsOrFixes.push_back(ForceDowncast::create(
cs, fromType, toType, cs.getConstraintLocator(locator)));
return true;
}
/// Return tuple of type and number of optionals on that type.
static std::pair<Type, unsigned> getObjectTypeAndNumUnwraps(Type type) {
SmallVector<Type, 2> optionals;
Type objType = type->lookThroughAllOptionalTypes(optionals);
return std::make_pair(objType, optionals.size());
}
static bool
repairViaOptionalUnwrap(ConstraintSystem &cs, Type fromType, Type toType,
ConstraintKind matchKind,
SmallVectorImpl<RestrictionOrFix> &conversionsOrFixes,
ConstraintLocatorBuilder locator) {
fromType = fromType->getWithoutSpecifierType();
if (!fromType->getOptionalObjectType() || toType->is<TypeVariableType>())
return false;
// If we have an optional type, try to force-unwrap it.
// FIXME: Should we also try '?'?
auto *anchor = locator.trySimplifyToExpr();
if (!anchor)
return false;
// If this is a conversion to a non-optional contextual type e.g.
// `let _: Bool = try? foo()` and `foo()` produces `Int`
// we should diagnose it as type mismatch instead of missing unwrap.
bool possibleContextualMismatch = [&]() {
if (!locator.endsWith<LocatorPathElt::ContextualType>())
return false;
// If the contextual type is optional as well, it's definitely a
// missing unwrap.
if (toType->getOptionalObjectType())
return false;
// If this is a leading-dot syntax member chain with `?.`
// notation, it wouldn't be possible to infer the base type
// without the contextual type, so we have to treat it as
// a missing unwrap.
if (auto *OEE = getAsExpr<OptionalEvaluationExpr>(anchor)) {
if (isExpr<UnresolvedMemberChainResultExpr>(OEE->getSubExpr()))
return false;
}
return true;
}();
// `OptionalEvaluationExpr` doesn't add a new level of
// optionality but it could be hiding concrete types
// behind itself which we can use to better understand
// how many levels of optionality have to be unwrapped.
if (auto *OEE = dyn_cast<OptionalEvaluationExpr>(anchor)) {
auto *subExpr = OEE->getSubExpr();
// First, let's check whether it has been determined that
// it was incorrect to use `?` in this position.
if (cs.hasFixFor(cs.getConstraintLocator(subExpr), FixKind::RemoveUnwrap))
return true;
auto type = cs.getType(subExpr);
// If the type of sub-expression is optional, type of the
// `OptionalEvaluationExpr` could be safely ignored because
// it doesn't add any type information.
if (type->getOptionalObjectType())
fromType = type;
// Don't attempt the fix until sub-expression is resolved
// if chain is not using leading-dot syntax. This is better
// than attempting to propagate type information down optional
// chain which is hard to diagnose.
if (type->isTypeVariableOrMember() &&
!isa<UnresolvedMemberChainResultExpr>(subExpr))
return false;
// If this is a conversion from optional chain to some
// other type e.g. contextual type or a parameter type,
// let's use `Bind` to match object types because
// object type of the optional chain is a type variable.
//
// One exception is contextual conversion - in such cases
// let's give optional chain a chance to infer its inner type
// first, that makes it much easier to diagnose contextual
// mismatch vs. missing optional unwrap.
if (!possibleContextualMismatch && matchKind >= ConstraintKind::Conversion)
matchKind = ConstraintKind::Bind;
}
if (auto *DRE = dyn_cast<DeclRefExpr>(anchor)) {
if (DRE->getDecl()->isImplicit()) {
// The expression that provides the first type is implicit and never
// spelled out in source code, e.g. $match in an expression pattern.
// Thus we cannot force unwrap the first type
return false;
}
}
if (auto *optTryExpr = dyn_cast<OptionalTryExpr>(anchor)) {
auto subExprType = cs.getType(optTryExpr->getSubExpr());
const bool isSwift5OrGreater =
cs.getASTContext().LangOpts.isSwiftVersionAtLeast(5);
if (subExprType->getOptionalObjectType()) {
if (isSwift5OrGreater) {
// For 'try?' expressions, a ForceOptional fix converts 'try?'
// to 'try!'. If the sub-expression is optional, then a force-unwrap
// won't change anything in Swift 5+ because 'try?' already avoids
// adding an additional layer of Optional there.
return false;
}
} else {
// In cases when sub-expression isn't optional, 'try?'
// always adds one level of optionality regardless of
// language mode, so we can safely try to bind its
// object type to contextual type without risk of
// causing more optionality mismatches down the road.
//
// For contextual conversions let's give `try?` a chance to
// infer inner type which, if incorrect, should result in
// contextual conversion failure instead of optional unwrap.
matchKind = possibleContextualMismatch ? ConstraintKind::Conversion
: ConstraintKind::Bind;
}
}
Type fromObjectType, toObjectType;
unsigned fromUnwraps, toUnwraps;
std::tie(fromObjectType, fromUnwraps) = getObjectTypeAndNumUnwraps(fromType);
std::tie(toObjectType, toUnwraps) = getObjectTypeAndNumUnwraps(toType);
// Since equality is symmetric and it decays into a `Bind`, eagerly
// unwrapping optionals from either side might be incorrect since
// there is not enough information about what is expected e.g.
// `Int?? equal T0?` just like `T0? equal Int??` allows `T0` to be
// bound to `Int?` and there is no need to unwrap. Solver has to wait
// until more information becomes available about what `T0` is expected
// to be before taking action.
if (matchKind == ConstraintKind::Equal &&
(fromObjectType->is<TypeVariableType>() ||
toObjectType->is<TypeVariableType>())) {
return false;
}
// If `from` is not less optional than `to`, force unwrap is
// not going to help here. In case of object type of `from`
// is a type variable, let's assume that it might be optional.
if (fromUnwraps <= toUnwraps && !fromObjectType->is<TypeVariableType>())
return false;
// If the result of optional chaining is converted to
// an optional contextual type represented by a type
// variable e.g. `T?`, there can be no optional mismatch
// because `T` could be bound to an optional of any depth.
if (isa<OptionalEvaluationExpr>(anchor) && toUnwraps > 0) {
if (locator.endsWith<LocatorPathElt::ContextualType>() &&
toObjectType->is<TypeVariableType>())
return false;
}
auto result =
cs.matchTypes(fromObjectType, toObjectType, matchKind,
ConstraintSystem::TypeMatchFlags::TMF_ApplyingFix, locator);
if (!result.isSuccess())
return false;
conversionsOrFixes.push_back(ForceOptional::create(
cs, fromType, toType, cs.getConstraintLocator(locator)));
return true;
}
static bool repairArrayLiteralUsedAsDictionary(
ConstraintSystem &cs, Type arrayType, Type dictType,
ConstraintKind matchKind,
SmallVectorImpl<RestrictionOrFix> &conversionsOrFixes,
ConstraintLocator *loc) {
if (auto *fix = TreatArrayLiteralAsDictionary::attempt(cs, dictType,
arrayType, loc)) {
// Ignore any attempts at promoting the value to an optional as even after
// stripping off all optionals above the underlying types won't match (array
// vs dictionary).
conversionsOrFixes.erase(
llvm::remove_if(conversionsOrFixes,
[&](RestrictionOrFix &E) {
if (auto restriction = E.getRestriction())
return *restriction == ConversionRestrictionKind::
ValueToOptional ||
*restriction == ConversionRestrictionKind::
OptionalToOptional;
return false;
}),
conversionsOrFixes.end());
conversionsOrFixes.push_back(fix);
return true;
}
return false;
}
/// Let's check whether this is an out-of-order argument in binary
/// operator/function with concrete type parameters e.g.
/// `func ^^(x: Int, y: String)` called as `"" ^^ 42` instead of
/// `42 ^^ ""` and repair it by using out-of-order fix on the
/// parent locator.
static bool repairOutOfOrderArgumentsInBinaryFunction(
ConstraintSystem &cs, SmallVectorImpl<RestrictionOrFix> &conversionsOrFixes,
ConstraintLocator *locator) {
if (!locator->isLastElement<LocatorPathElt::ApplyArgToParam>())
return false;
auto path = locator->getPath();
auto *parentLoc =
cs.getConstraintLocator(locator->getAnchor(), path.drop_back());
if (cs.hasFixFor(parentLoc, FixKind::MoveOutOfOrderArgument))
return true;
auto *calleeLoc = cs.getCalleeLocator(locator);
if (!calleeLoc)
return false;
auto overload = cs.findSelectedOverloadFor(calleeLoc);
if (!(overload && overload->choice.isDecl()))
return false;
auto *fnType = overload->adjustedOpenedType->getAs<FunctionType>();
if (!(fnType && fnType->getNumParams() == 2))
return false;
auto argument = simplifyLocatorToAnchor(locator);
// Argument could be synthesized.
if (!argument)
return false;
auto argLoc = locator->castLastElementTo<LocatorPathElt::ApplyArgToParam>();
auto currArgIdx = argLoc.getArgIdx();
auto currParamIdx = argLoc.getParamIdx();
// Argument is extraneous and has been re-ordered to match one
// of two parameter types.
if (currArgIdx >= 2 || currArgIdx != currParamIdx)
return false;
auto otherArgIdx = currArgIdx == 0 ? 1 : 0;
auto argType = cs.getType(argument);
auto paramType = fnType->getParams()[otherArgIdx].getOldType();
bool isOperatorRef = overload->choice.getDecl()->isOperator();
// If one of the parameters is `inout`, we can't flip the arguments.
{
auto params = fnType->getParams();
if (params[0].isInOut() != params[1].isInOut())
return false;
}
auto getReorderedArgumentLocator = [&](unsigned argIdx) {
auto paramIdx = argIdx == 0 ? 1 : 0;
return cs.getConstraintLocator(
parentLoc, LocatorPathElt::ApplyArgToParam(
argIdx, paramIdx,
fnType->getParams()[paramIdx].getParameterFlags()));
};
auto matchArgToParam = [&](Type argType, Type paramType, unsigned argIdx) {
auto *loc = getReorderedArgumentLocator(argIdx);
// If argument (and/or parameter) is a generic type let's not even try this
// fix because it would be impossible to match given types without delaying
// until more context becomes available.
if (argType->hasTypeVariable() || paramType->hasTypeVariable())
return cs.getTypeMatchFailure(loc);
// FIXME: There is currently no easy way to avoid attempting
// fixes, matchTypes do not propagate `TMF_ApplyingFix` flag.
llvm::SaveAndRestore<ConstraintSystemOptions> options(
cs.Options, cs.Options - ConstraintSystemFlags::AllowFixes);
// Check optionality, if argument is more optional than parameter
// they are not going to match. This saves us one disjunction because
// optionals are matched as deep-equality and optional-to-optional.
{
unsigned numArgUnwraps;
unsigned numParamUnwraps;
std::tie(argType, numArgUnwraps) = getObjectTypeAndNumUnwraps(argType);
std::tie(paramType, numParamUnwraps) =
getObjectTypeAndNumUnwraps(paramType);
if (numArgUnwraps > numParamUnwraps)
return cs.getTypeMatchFailure(loc);
}
return cs.matchTypes(
argType, paramType,
isOperatorRef ? ConstraintKind::OperatorArgumentConversion
: ConstraintKind::ArgumentConversion,
ConstraintSystem::TypeMatchFlags::TMF_ApplyingFix, loc);
};
auto result = matchArgToParam(argType, paramType, currArgIdx);
if (result.isSuccess()) {
// Let's check whether other argument matches current parameter type,
// if it does - it's definitely out-of-order arguments issue.
auto *otherArgLoc = getReorderedArgumentLocator(otherArgIdx);
auto otherArg = simplifyLocatorToAnchor(otherArgLoc);
// Argument could be synthesized.
if (!otherArg)
return false;
argType = cs.getType(otherArg);
paramType = fnType->getParams()[currArgIdx].getOldType();
result = matchArgToParam(argType, paramType, otherArgIdx);
if (result.isSuccess()) {
conversionsOrFixes.push_back(MoveOutOfOrderArgument::create(
cs, otherArgIdx, currArgIdx, {{0}, {1}}, parentLoc));
return true;
}
}
return false;
}
/// Attempt to repair typing failures and record fixes if needed.
/// \return true if at least some of the failures has been repaired
/// successfully, which allows type matcher to continue.
bool ConstraintSystem::repairFailures(
Type lhs, Type rhs, ConstraintKind matchKind, TypeMatchOptions flags,
SmallVectorImpl<RestrictionOrFix> &conversionsOrFixes,
ConstraintLocatorBuilder locator) {
SmallVector<LocatorPathElt, 4> path;
auto anchor = locator.getLocatorParts(path);
// If there is a missing explicit call it could be:
//
// a). Contextual e.g. `let _: R = foo`
// b). Argument is a function value passed to parameter
// which expects its result type e.g. `foo(bar)`
// c). Assignment destination type matches return type of
// of the function value e.g. `foo = bar` or `foo = .bar`
auto repairByInsertingExplicitCall = [&](Type srcType, Type dstType) -> bool {
auto fnType = srcType->getAs<FunctionType>();
if (!fnType)
return false;
// If the locator isn't anchored at an expression, or the expression is
// implicit, don't try to insert an explicit call into the source code.
auto *loc = getConstraintLocator(locator);
auto *anchor = getAsExpr(simplifyLocatorToAnchor(loc));
if (!anchor || anchor->isImplicit())
return false;
if (isArgumentOfPatternMatchingOperator(loc))
return false;
// Don't attempt this fix for trailing closures.
if (auto elt = loc->getLastElementAs<LocatorPathElt::ApplyArgToParam>()) {
auto argumentList = getArgumentList(loc);
if (argumentList->isTrailingClosureIndex(elt->getArgIdx()))
return false;
}
// If argument is a function type and all of its parameters have
// default values, let's see whether error is related to missing
// explicit call.
if (fnType->getNumParams() > 0) {
auto overload = findSelectedOverloadFor(anchor);
if (!(overload && overload->choice.isDecl()))
return false;
const auto &choice = overload->choice;
ParameterListInfo info(fnType->getParams(), choice.getDecl(),
hasAppliedSelf(*this, choice));
if (llvm::any_of(indices(fnType->getParams()),
[&info](const unsigned idx) {
return !info.hasDefaultArgument(idx);
}))
return false;
}
auto resultType = fnType->getResult();
// If this is situation like `x = { ... }` where closure results in
// `Void`, let's not suggest to call the closure, because it's most
// likely not intended.
if (auto *assignment = getAsExpr<AssignExpr>(anchor)) {
if (isa<ClosureExpr>(assignment->getSrc()) && resultType->isVoid())
return false;
}
// If left-hand side is a function type but right-hand
// side isn't, let's check it would be possible to fix
// this by forming an explicit call.
auto convertTo = dstType->lookThroughAllOptionalTypes();
// Right-hand side can't be - a function, a type variable or dependent
// member, or `Any` (if function conversion to `Any` didn't succeed there
// is something else going on e.g. problem with escapiness).
if (convertTo->is<FunctionType>() || convertTo->isTypeVariableOrMember() ||
convertTo->isAny())
return false;
ConstraintKind matchKind;
if (resultType->is<TypeVariableType>()) {
matchKind = ConstraintKind::Equal;
} else {
matchKind = ConstraintKind::Conversion;
}
auto result = matchTypes(resultType, dstType, matchKind,
TypeMatchFlags::TMF_ApplyingFix, locator);
if (result.isSuccess()) {
conversionsOrFixes.push_back(
InsertExplicitCall::create(*this, getConstraintLocator(locator)));
return true;
}
return false;
};
auto repairByAnyToAnyObjectCast = [&](Type lhs, Type rhs) -> bool {
if (!(lhs->isAny() && rhs->isAnyObject()))
return false;
conversionsOrFixes.push_back(MissingConformance::forContextual(
*this, lhs, rhs, getConstraintLocator(locator)));
return true;
};
auto repairByTreatingRValueAsLValue = [&](Type lhs, Type rhs) -> bool {
if (!lhs->is<LValueType>() &&
(rhs->is<LValueType>() || rhs->is<InOutType>())) {
// Conversion from l-value to inout in an operator argument
// position (which doesn't require explicit `&`) decays into
// a `Bind` of involved object types, same goes for explicit
// `&` conversion from l-value to inout type.
//
// In case of regular argument conversion although explicit `&`
// is required we still want to diagnose the problem as one
// about mutability instead of suggesting to add `&` which wouldn't
// be correct.
auto kind = (isExpr<InOutExpr>(anchor) ||
(rhs->is<InOutType>() &&
(matchKind == ConstraintKind::ArgumentConversion ||
matchKind == ConstraintKind::OperatorArgumentConversion)))
? ConstraintKind::Bind
: matchKind;
auto result = matchTypes(lhs, rhs->getWithoutSpecifierType(), kind,
TMF_ApplyingFix, locator);
if (result.isSuccess()) {
// If left side is a hole, let's not record a fix since hole can
// assume any type and already represents a problem elsewhere in
// the expression.
if (lhs->isPlaceholder())
return true;
auto *loc = getConstraintLocator(locator);
// If this `inout` is in incorrect position, it should be diagnosed
// by other fixes.
if (loc->directlyAt<InOutExpr>()) {
if (!getArgumentLocator(castToExpr(anchor))) {
conversionsOrFixes.push_back(
RemoveAddressOf::create(*this, lhs, rhs, loc));
return true;
}
}
conversionsOrFixes.push_back(TreatRValueAsLValue::create(*this, loc));
return true;
}
}
return false;
};
// Check whether given `value` type matches a `RawValue` type of
// a given raw representable type.
auto isValueOfRawRepresentable = [&](Type valueType,
Type rawReprType) -> bool {
// diagnostic is going to suggest failable initializer anyway.
if (auto objType = rawReprType->getOptionalObjectType())
rawReprType = objType;
// If value is optional diagnostic would suggest using `Optional.map` in
// combination with `<Type>(rawValue: ...)` initializer.
if (auto objType = valueType->getOptionalObjectType())
valueType = objType;
if (rawReprType->isTypeVariableOrMember() || rawReprType->isPlaceholder())
return false;
auto rawValue = isRawRepresentable(*this, rawReprType);
if (!rawValue)
return false;
auto result = matchTypes(valueType, rawValue, ConstraintKind::Conversion,
TMF_ApplyingFix, locator);
return !result.isFailure();
};
// Check whether given `rawReprType` does indeed conform to `RawRepresentable`
// and if so check that given `expectedType` matches its `RawValue` type. If
// that condition holds add a tailored fix which is going to suggest to
// explicitly construct a raw representable type from a given value type.
auto repairByConstructingRawRepresentableType =
[&](Type expectedType, Type rawReprType) -> bool {
if (!isValueOfRawRepresentable(expectedType, rawReprType))
return false;
conversionsOrFixes.push_back(ExplicitlyConstructRawRepresentable::create(
*this, rawReprType, expectedType, getConstraintLocator(locator)));
return true;
};
// Check whether given `rawReprType` does indeed conform to `RawRepresentable`
// and if so check that given `expectedType` matches its `RawValue` type. If
// that condition holds add a tailored fix which is going to suggest to
// use `.rawValue` associated with given raw representable type to match
// given expected type.
auto repairByUsingRawValueOfRawRepresentableType =
[&](Type rawReprType, Type expectedType) -> bool {
if (!isValueOfRawRepresentable(expectedType, rawReprType))
return false;
conversionsOrFixes.push_back(UseRawValue::create(
*this, rawReprType, expectedType, getConstraintLocator(locator)));
return true;
};
auto hasConversionOrRestriction = [&](ConversionRestrictionKind kind) {
return llvm::any_of(conversionsOrFixes,
[kind](const RestrictionOrFix correction) {
if (auto restriction = correction.getRestriction())
return restriction == kind;
return false;
});
};
auto hasAnyRestriction = [&]() {
return llvm::any_of(conversionsOrFixes,
[](const RestrictionOrFix &correction) {
return bool(correction.getRestriction());
});
};
// Check whether this is a tuple with a single unlabeled element
// i.e. `(_: Int)` and return type of that element if so. Note that
// if the element is pack expansion type the tuple is significant.
auto isSingleUnlabeledElementTuple = [](Type type) -> Type {
if (auto *tuple = type->getAs<TupleType>()) {
if (tuple->getNumElements() == 1 && !tuple->getElement(0).hasName()) {
auto eltType = tuple->getElement(0).getType();
return isPackExpansionType(eltType) ? Type() : eltType;
}
}
return Type();
};
if (repairArrayLiteralUsedAsDictionary(*this, lhs, rhs, matchKind,
conversionsOrFixes,
getConstraintLocator(locator)))
return true;
if (locator.endsWith<LocatorPathElt::ThrownErrorType>()) {
conversionsOrFixes.push_back(
IgnoreThrownErrorMismatch::create(*this, lhs, rhs,
getConstraintLocator(locator)));
return true;
}
auto maybeRepairKeyPathResultFailure = [&](KeyPathExpr *kpExpr) {
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
if (lhs->isTypeVariableOrMember() || rhs->isTypeVariableOrMember())
return false;
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality) ||
hasConversionOrRestriction(ConversionRestrictionKind::ValueToOptional))
return false;
auto i = kpExpr->getComponents().size() - 1;
auto lastCompLoc =
getConstraintLocator(kpExpr, LocatorPathElt::KeyPathComponent(i));
if (hasFixFor(lastCompLoc, FixKind::AllowTypeOrInstanceMember))
return true;
auto *keyPathLoc = getConstraintLocator(anchor);
if (hasFixFor(keyPathLoc))
return true;
if (auto contextualInfo = getContextualTypeInfo(anchor)) {
if (hasFixFor(getConstraintLocator(
keyPathLoc,
LocatorPathElt::ContextualType(contextualInfo->purpose))))
return true;
}
conversionsOrFixes.push_back(IgnoreContextualType::create(
*this, lhs, rhs,
getConstraintLocator(keyPathLoc, ConstraintLocator::KeyPathValue)));
return true;
};
if (path.empty()) {
if (!anchor)
return false;
// This could be:
// - `InOutExpr` used with r-value e.g. `foo(&x)` where `x` is a `let`.
// - `ForceValueExpr` e.g. `foo.bar! = 42` where `bar` or `foo` are
// immutable or a subscript e.g. `foo["bar"]! = 42`.
if (repairByTreatingRValueAsLValue(lhs, rhs))
return true;
// If method reference forms a value type of the key path,
// there is going to be a constraint to match result of the
// member lookup to the generic parameter `V` of *KeyPath<R, V>
// type associated with key path expression, which we need to
// fix-up here unless last component has already a invalid type or
// instance fix recorded.
if (auto *kpExpr = getAsExpr<KeyPathExpr>(anchor)) {
if (isKnownKeyPathType(lhs) && isKnownKeyPathType(rhs)) {
// If we have a conversion happening here, we should let fix happen in
// simplifyRestrictedConstraint.
if (hasAnyRestriction())
return false;
}
conversionsOrFixes.push_back(IgnoreContextualType::create(
*this, lhs, rhs, getConstraintLocator(locator)));
return true;
}
if (auto *ODRE = getAsExpr<OverloadedDeclRefExpr>(anchor)) {
if (lhs->is<LValueType>()) {
conversionsOrFixes.push_back(
TreatRValueAsLValue::create(*this, getConstraintLocator(locator)));
return true;
}
}
if (auto *OEE = getAsExpr<OptionalEvaluationExpr>(anchor)) {
// If concrete type of the sub-expression can't be converted to the
// type associated with optional evaluation result it could only be
// contextual mismatch where type of the top-level expression
// comes from contextual type or its parent expression.
//
// Because result type of the optional evaluation is supposed to
// represent the type of its sub-expression with added level of
// optionality if needed.
auto contextualTy = simplifyType(rhs)->getOptionalObjectType();
if (!lhs->getOptionalObjectType() && !lhs->hasTypeVariable() &&
contextualTy && !contextualTy->isTypeVariableOrMember()) {
auto *fixLocator = getConstraintLocator(OEE->getSubExpr());
// If inner expression already has a fix, consider this two-way
// mismatch as un-salvageable.
if (hasFixFor(fixLocator))
return false;
conversionsOrFixes.push_back(
IgnoreContextualType::create(*this, lhs, rhs, fixLocator));
return true;
}
}
if (auto *AE = getAsExpr<AssignExpr>(anchor)) {
if (repairByInsertingExplicitCall(lhs, rhs))
return true;
if (auto *inoutExpr = dyn_cast<InOutExpr>(AE->getSrc())) {
auto *loc = getConstraintLocator(inoutExpr);
// Remove all of the restrictions because none of them
// are going to succeed.
conversionsOrFixes.erase(
llvm::remove_if(
conversionsOrFixes,
[](const auto &entry) { return bool(entry.getRestriction()); }),
conversionsOrFixes.end());
if (hasFixFor(loc, FixKind::RemoveAddressOf))
return true;
conversionsOrFixes.push_back(
RemoveAddressOf::create(*this, lhs, rhs, loc));
return true;
}
if (repairByAnyToAnyObjectCast(lhs, rhs))
return true;
if (repairViaBridgingCast(*this, lhs, rhs, conversionsOrFixes, locator))
return true;
// If destination is `AnyObject` it means that source doesn't conform.
if (rhs->getWithoutSpecifierType()
->lookThroughAllOptionalTypes()
->isAnyObject()) {
conversionsOrFixes.push_back(IgnoreAssignmentDestinationType::create(
*this, lhs, rhs, getConstraintLocator(locator)));
return true;
}
// If we are trying to assign e.g. `Array<Int>` to `Array<Float>` let's
// give solver a chance to determine which generic parameters are
// mismatched and produce a fix for that.
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality))
return false;
// An attempt to assign `Int?` to `String?`.
if (hasConversionOrRestriction(
ConversionRestrictionKind::OptionalToOptional)) {
conversionsOrFixes.push_back(IgnoreAssignmentDestinationType::create(
*this, lhs, rhs, getConstraintLocator(locator)));
return true;
}
// If the situation has to do with protocol composition types and
// destination doesn't have one of the conformances e.g. source is
// `X & Y` but destination is only `Y` or vice versa, there is a
// tailored "missing conformance" fix for that.
if (hasConversionOrRestriction(ConversionRestrictionKind::Existential))
return false;
if (hasConversionOrRestriction(
ConversionRestrictionKind::MetatypeToExistentialMetatype) ||
hasConversionOrRestriction(
ConversionRestrictionKind::ExistentialMetatypeToMetatype) ||
hasConversionOrRestriction(ConversionRestrictionKind::Superclass)) {
conversionsOrFixes.push_back(IgnoreAssignmentDestinationType::create(
*this, lhs, rhs, getConstraintLocator(locator)));
return true;
}
if (hasConversionOrRestriction(
ConversionRestrictionKind::ValueToOptional)) {
lhs = lhs->lookThroughAllOptionalTypes();
rhs = rhs->lookThroughAllOptionalTypes();
// If both object types are functions, let's allow the solver to
// structurally compare them before trying to fix anything.
if (lhs->is<FunctionType>() && rhs->is<FunctionType>())
return false;
// If either object type is a generic, nominal or existential type
// it means that follow-up to value-to-optional is going to be:
//
// 1. "deep equality" check, which is handled by generic argument(s)
// or contextual mismatch fix, or
// 2. "existential" check, which is handled by a missing conformance
// fix.
if ((lhs->is<BoundGenericType>() && rhs->is<BoundGenericType>()) ||
(lhs->is<NominalType>() && rhs->is<NominalType>()) ||
rhs->isAnyExistentialType())
return false;
}
auto *destExpr = AE->getDest();
// Literal expression as well as call/operator application can't be
// used as an assignment destination because resulting type is immutable.
if (isa<ApplyExpr>(destExpr) || isa<LiteralExpr>(destExpr)) {
conversionsOrFixes.push_back(
TreatRValueAsLValue::create(*this, getConstraintLocator(locator)));
return true;
}
// If destination has a function type, it might either be
// a property with a function type or a method reference,
// e.g. `foo.bar = 42` neither can be used if the destination
// is not l-value.
auto destType = getType(destExpr);
auto destTypeVar = destType->getAs<TypeVariableType>();
bool destIsOrCanBindToLValue =
destType->is<LValueType>() ||
(destTypeVar && destTypeVar->getImpl().canBindToLValue());
if (!destIsOrCanBindToLValue && rhs->is<FunctionType>()) {
conversionsOrFixes.push_back(
TreatRValueAsLValue::create(*this, getConstraintLocator(locator)));
return true;
}
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind,
conversionsOrFixes, locator))
return true;
// `rhs` - is an assignment destination and `lhs` is its source.
if (repairByConstructingRawRepresentableType(lhs, rhs))
return true;
if (repairByUsingRawValueOfRawRepresentableType(lhs, rhs))
return true;
// If either side is a placeholder then let's consider this
// assignment correctly typed.
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
// Let's try to match source and destination types one more
// time to see whether they line up, if they do - the problem is
// related to immutability, otherwise it's a type mismatch.
auto result = matchTypes(lhs, rhs, ConstraintKind::Conversion,
TMF_ApplyingFix, locator);
auto *loc = getConstraintLocator(locator);
if (destIsOrCanBindToLValue || result.isFailure()) {
// Let this assignment failure be diagnosed by the
// AllowTupleTypeMismatch fix already recorded.
if (hasFixFor(loc, FixKind::AllowTupleTypeMismatch))
return true;
conversionsOrFixes.push_back(
IgnoreAssignmentDestinationType::create(*this, lhs, rhs, loc));
} else {
conversionsOrFixes.push_back(TreatRValueAsLValue::create(*this, loc));
}
return true;
}
return false;
}
if (auto *VD = getAsDecl<ValueDecl>(anchor)) {
// Matching a witness to a ObjC protocol requirement.
if (VD->isObjC() && VD->isProtocolRequirement() &&
path[0].is<LocatorPathElt::Witness>() &&
// Note that the condition below is very important,
// we need to wait until the very last moment to strip
// the concurrency annotations from the inner most type.
conversionsOrFixes.empty()) {
// Allow requirements to introduce `swift_attr` annotations
// (note that `swift_attr` in type contexts weren't supported
// before) and for witnesses to adopt them gradually by matching
// with a warning in non-strict concurrency mode.
if (!(Context.isSwiftVersionAtLeast(6) ||
Context.LangOpts.StrictConcurrencyLevel ==
StrictConcurrency::Complete)) {
auto strippedLHS = lhs->stripConcurrency(/*resursive=*/true,
/*dropGlobalActor=*/true);
auto strippedRHS = rhs->stripConcurrency(/*resursive=*/true,
/*dropGlobalActor=*/true);
auto result = matchTypes(strippedLHS, strippedRHS, matchKind,
flags | TMF_ApplyingFix, locator);
if (!result.isFailure()) {
increaseScore(SK_MissingSynthesizableConformance, locator);
return true;
}
}
}
}
auto elt = path.back();
switch (elt.getKind()) {
case ConstraintLocator::LValueConversion: {
// Ignore l-value conversion element since it has already
// played its role.
path.pop_back();
// If this is a contextual mismatch between l-value types e.g.
// `@lvalue String vs. @lvalue Int`, let's pretend that it's okay.
if (!path.empty()) {
if (path.back().is<LocatorPathElt::ContextualType>()) {
auto *locator = getConstraintLocator(anchor, path.back());
conversionsOrFixes.push_back(
IgnoreContextualType::create(*this, lhs, rhs, locator));
break;
}
// If this is a problem with result type of a subscript setter,
// let's re-attempt to repair without l-value conversion in the
// locator to fix underlying type mismatch.
if (path.back().is<LocatorPathElt::FunctionResult>()) {
return repairFailures(lhs, rhs, matchKind, flags, conversionsOrFixes,
getConstraintLocator(anchor, path));
}
// If this is a function type param type mismatch in any position,
// the mismatch we want to report is for the whole structural type.
auto last = std::find_if(
path.rbegin(), path.rend(), [](LocatorPathElt &elt) -> bool {
return elt.is<LocatorPathElt::FunctionArgument>();
});
if (last != path.rend())
break;
}
LLVM_FALLTHROUGH;
}
case ConstraintLocator::ApplyArgToParam: {
auto loc = getConstraintLocator(locator);
// If this type mismatch is associated with a synthesized argument,
// let's just ignore it because the main problem is the absence of
// the argument.
if (auto applyLoc = elt.getAs<LocatorPathElt::ApplyArgToParam>()) {
if (auto *argumentList = getArgumentList(loc)) {
// This is either synthesized argument or a default value.
if (applyLoc->getArgIdx() >= argumentList->size()) {
auto *calleeLoc = getCalleeLocator(loc);
auto overload = findSelectedOverloadFor(calleeLoc);
// If this cannot be a default value matching, let's ignore.
if (!(overload && overload->choice.isDecl()))
return true;
// Ignore decls that don't have meaningful parameter lists - this
// matches variables and parameters with function types.
auto *paramList = getParameterList(overload->choice.getDecl());
if (!paramList)
return true;
if (!paramList->get(applyLoc->getParamIdx())->getTypeOfDefaultExpr())
return true;
}
}
}
// Don't attempt to fix an argument being passed to a
// _OptionalNilComparisonType parameter. Such an overload should only take
// effect when a nil literal is used in valid code, and doesn't offer any
// useful fixes for invalid code.
if (auto *nominal = rhs->getAnyNominal()) {
if (nominal->isStdlibDecl() &&
nominal->getName() == getASTContext().Id_OptionalNilComparisonType) {
return false;
}
}
if (isForCodeCompletion()) {
// If the argument contains the code completion location, the user has not
// finished typing out this argument yet. Treat the mismatch as valid so
// we don't penalize this solution.
if (auto *arg = getAsExpr(simplifyLocatorToAnchor(loc))) {
// Ignore synthesized args like $match in implicit pattern match
// operator calls. Their source location is usually the same as the
// other (explicit) argument's so source range containment alone isn't
// sufficient.
bool isSynthesizedArg = arg->isImplicit() && isa<DeclRefExpr>(arg);
if (!isSynthesizedArg && isForCodeCompletion() &&
containsIDEInspectionTarget(arg) && !lhs->isVoid() &&
!lhs->isUninhabited())
return true;
}
}
if (repairByInsertingExplicitCall(lhs, rhs))
break;
bool isPatternMatching = isArgumentOfPatternMatchingOperator(loc);
// Let's not suggest force downcasts in pattern-matching context.
if (!isPatternMatching &&
repairViaBridgingCast(*this, lhs, rhs, conversionsOrFixes, locator))
break;
// Argument is a r-value but parameter expects an l-value e.g.
//
// func foo(_ x: inout Int) {}
// let x: Int = 42
// foo(x) // `x` can't be converted to `inout Int`.
//
// This has to happen before checking for optionality mismatch
// because otherwise `Int? arg conv inout Int` is going to get
// fixed as 2 fixes - "force unwrap" + r-value -> l-value mismatch.
if (repairByTreatingRValueAsLValue(lhs, rhs))
break;
// If the problem is related to missing unwrap, there is a special
// fix for that.
if (lhs->getOptionalObjectType() && !rhs->getOptionalObjectType()) {
// If this is an attempt to check whether optional conforms to a
// particular protocol, let's do that before attempting to force
// unwrap the optional.
if (hasConversionOrRestriction(ConversionRestrictionKind::Existential))
break;
auto result = matchTypes(lhs->getOptionalObjectType(), rhs, matchKind,
TMF_ApplyingFix, locator);
if (result.isSuccess()) {
conversionsOrFixes.push_back(
ForceOptional::create(*this, lhs, rhs, loc));
break;
}
}
// There is no subtyping between object types of inout argument/parameter.
if (elt.getKind() == ConstraintLocator::LValueConversion) {
auto result = matchTypes(lhs, rhs, ConstraintKind::Conversion,
TMF_ApplyingFix, locator);
ConstraintFix *fix = nullptr;
if (result.isFailure()) {
// If this is a "destination" argument to a mutating operator
// like `+=`, let's consider it contextual and only attempt
// to fix type mismatch on the "source" right-hand side of
// such operators.
if (isOperatorArgument(loc) &&
loc->findLast<LocatorPathElt::ApplyArgToParam>()->getArgIdx() == 0)
break;
fix = AllowArgumentMismatch::create(*this, lhs, rhs, loc);
} else {
fix = AllowInOutConversion::create(*this, lhs, rhs, loc);
}
conversionsOrFixes.push_back(fix);
break;
}
if (elt.getKind() != ConstraintLocator::ApplyArgToParam)
break;
// If argument in l-value type and parameter is `inout` or a pointer,
// let's see if it's generic parameter matches and suggest adding explicit
// `&`.
if (lhs->is<LValueType>() &&
(rhs->is<InOutType>() || rhs->getAnyPointerElementType())) {
auto baseType = rhs->is<InOutType>() ? rhs->getInOutObjectType()
: rhs->getAnyPointerElementType();
// Let's use `BindToPointer` constraint here to match up base types
// of implied `inout` argument and `inout` or pointer parameter.
// This helps us to avoid implicit conversions associated with
// `ArgumentConversion` constraint.
auto result = matchTypes(lhs->getRValueType(), baseType,
ConstraintKind::BindToPointerType,
TypeMatchFlags::TMF_ApplyingFix, locator);
if (result.isSuccess()) {
conversionsOrFixes.push_back(AddAddressOf::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
}
// If the argument is inout and the parameter is not inout or a pointer,
// suggest removing the &.
if (lhs->is<InOutType>() && !rhs->is<InOutType>()) {
auto objectType = rhs->lookThroughAllOptionalTypes();
if (!objectType->getAnyPointerElementType()) {
auto result = matchTypes(lhs->getInOutObjectType(), rhs,
ConstraintKind::ArgumentConversion,
TypeMatchFlags::TMF_ApplyingFix, locator);
if (result.isSuccess()) {
conversionsOrFixes.push_back(RemoveAddressOf::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
}
}
// If parameter type is `Any` the problem might be related to
// invalid escapiness of the argument.
if (rhs->isAny())
break;
// If there are any restrictions here we need to wait and let
// `simplifyRestrictedConstraintImpl` handle them.
if (hasAnyRestriction())
break;
if (auto *fix = fixPropertyWrapperFailure(
*this, lhs, loc,
[&](SelectedOverload overload, VarDecl *decl, Type newBase) {
// FIXME: There is currently no easy way to avoid attempting
// fixes, matchTypes do not propagate `TMF_ApplyingFix` flag.
llvm::SaveAndRestore<ConstraintSystemOptions> options(
Options, Options - ConstraintSystemFlags::AllowFixes);
TypeMatchOptions flags;
return matchTypes(newBase, rhs, ConstraintKind::Subtype, flags,
getConstraintLocator(locator))
.isSuccess();
},
rhs)) {
conversionsOrFixes.push_back(fix);
break;
}
// If this is an implicit 'something-to-pointer' conversion
// it's going to be diagnosed by specialized fix which deals
// with generic argument mismatches.
if (matchKind == ConstraintKind::BindToPointerType) {
if (!rhs->isPlaceholder())
break;
}
// If this is a ~= operator implicitly generated by pattern matching
// let's not try to fix right-hand side of the operator because it's
// a correct contextual type.
if (isPatternMatching &&
elt.castTo<LocatorPathElt::ApplyArgToParam>().getParamIdx() == 1)
break;
if (auto *fix = ExpandArrayIntoVarargs::attempt(*this, lhs, rhs, locator)) {
conversionsOrFixes.push_back(fix);
break;
}
// If parameter is a collection but argument is not, let's try
// to try and match collection element type to the argument to
// produce better diagnostics e.g.:
//
// ```
// func foo<T>(_: [T]) {}
// foo(1) // expected '[Int]', got 'Int'
// ```
if (rhs->isKnownStdlibCollectionType()) {
std::function<Type(Type)> getArrayOrSetType = [&](Type type) -> Type {
if (auto eltTy = type->isArrayType())
return getArrayOrSetType(eltTy);
if (auto eltTy = isSetType(type))
return getArrayOrSetType(*eltTy);
return type;
};
// Let's ignore any optional types associated with element e.g. `[T?]`
auto rhsEltTy = getArrayOrSetType(rhs)->lookThroughAllOptionalTypes();
(void)matchTypes(lhs, rhsEltTy, ConstraintKind::Equal, TMF_ApplyingFix,
locator);
}
// If either type has a placeholder, consider this fixed.
if (lhs->hasPlaceholder() || rhs->hasPlaceholder())
return true;
// `lhs` - is an argument and `rhs` is a parameter type.
if (repairByConstructingRawRepresentableType(lhs, rhs))
break;
if (repairByUsingRawValueOfRawRepresentableType(lhs, rhs))
break;
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind, conversionsOrFixes,
locator))
break;
{
auto *calleeLocator = getCalleeLocator(loc);
if (hasFixFor(calleeLocator, FixKind::AddQualifierToAccessTopLevelName)) {
if (auto overload = findSelectedOverloadFor(calleeLocator)) {
if (auto choice = overload->choice.getDeclOrNull()) {
// If this is an argument of a symmetric function/operator let's
// not fix any position rather than first because we'd just end
// up with ambiguity instead of reporting an actual problem with
// mismatched type since each argument can have district bindings.
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(choice)) {
auto *paramList = AFD->getParameters();
auto firstParamType = paramList->get(0)->getInterfaceType();
if (elt.castTo<LocatorPathElt::ApplyArgToParam>().getParamIdx() >
0 &&
llvm::all_of(*paramList, [&](const ParamDecl *param) -> bool {
return param->getInterfaceType()->isEqual(firstParamType);
}))
return true;
}
}
}
}
}
if (repairOutOfOrderArgumentsInBinaryFunction(*this, conversionsOrFixes,
loc))
return true;
// There is already a remove extraneous arguments fix recorded for this
// apply arg to param locator, so let's skip the default argument mismatch.
if (hasFixFor(loc, FixKind::RemoveExtraneousArguments))
return true;
// If parameter is a pack, let's see if we have already recorded
// either synthesized or extraneous argument fixes.
if (rhs->is<PackType>()) {
ArrayRef tmpPath(path);
// Ignore argument/parameter type conversion mismatch if we already
// detected a tuple splat issue.
if (hasFixFor(loc,
FixKind::DestructureTupleToMatchPackExpansionParameter))
return true;
// Path would end with `ApplyArgument`.
auto *argsLoc = getConstraintLocator(anchor, tmpPath.drop_back());
if (hasFixFor(argsLoc, FixKind::RemoveExtraneousArguments) ||
hasFixFor(argsLoc, FixKind::AddMissingArguments))
return true;
}
// If the argument couldn't be found, this could be a default value
// type mismatch.
if (!simplifyLocatorToAnchor(loc)) {
auto *calleeLocator = getCalleeLocator(loc);
unsigned paramIdx =
loc->castLastElementTo<LocatorPathElt::ApplyArgToParam>()
.getParamIdx();
if (auto overload = findSelectedOverloadFor(calleeLocator)) {
if (auto *decl = overload->choice.getDeclOrNull()) {
if (auto paramList = getParameterList(decl)) {
if (paramList->get(paramIdx)->getTypeOfDefaultExpr()) {
conversionsOrFixes.push_back(
IgnoreDefaultExprTypeMismatch::create(*this, lhs, rhs, loc));
break;
}
}
}
}
}
conversionsOrFixes.push_back(
AllowArgumentMismatch::create(*this, lhs, rhs, loc));
break;
}
case ConstraintLocator::KeyPathRoot: {
// The root mismatch is from base U? to U or a subtype of U in keypath
// application so let's suggest an unwrap the optional fix.
if (auto unwrapFix = UnwrapOptionalBaseKeyPathApplication::attempt(
*this, lhs, rhs, getConstraintLocator(locator))) {
conversionsOrFixes.push_back(unwrapFix);
break;
}
conversionsOrFixes.push_back(AllowKeyPathRootTypeMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::WrappedValue: {
conversionsOrFixes.push_back(AllowWrappedValueMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::FunctionArgument: {
// Let's drop the last element which points to a single argument
// and see if this is a contextual mismatch.
path.pop_back();
if (path.empty() ||
!(path.back().getKind() == ConstraintLocator::ApplyArgToParam ||
path.back().getKind() == ConstraintLocator::ContextualType))
return false;
if (auto argToParamElt =
path.back().getAs<LocatorPathElt::ApplyArgToParam>()) {
auto loc = getConstraintLocator(anchor, path);
if (auto closure = getAsExpr<ClosureExpr>(simplifyLocatorToAnchor(loc))) {
auto closureTy = getClosureType(closure);
// What we have here is a form or tuple splat with no arguments
// demonstrated by following example:
//
// func foo<T: P>(_: T, _: (T.Element) -> Int) {}
// foo { 42 }
//
// In cases like this `T.Element` might be resolved to `Void`
// which means that we have to try a single empty tuple argument
// as a narrow exception to SE-0110, see `matchFunctionTypes`.
//
// But if `T.Element` didn't get resolved to `Void` we'd like
// to diagnose this as a missing argument which can't be ignored or
// a tuple is trying to be inferred as a tuple for destructuring but
// contextual argument does not match(in this case we remove the extra
// closure arguments).
if (closureTy->getNumParams() == 0) {
conversionsOrFixes.push_back(AddMissingArguments::create(
*this, {SynthesizedArg{0, AnyFunctionType::Param(lhs)}}, loc));
break;
}
// Since this is a problem with `FunctionArgument` we know that the
// contextual type only has one parameter, if closure has more than
// that the fix is to remove extraneous ones.
if (closureTy->getNumParams() > 1) {
auto callee = getCalleeLocator(loc);
if (auto overload = findSelectedOverloadFor(callee)) {
auto fnType = simplifyType(overload->adjustedOpenedType)
->castTo<FunctionType>();
auto paramIdx = argToParamElt->getParamIdx();
auto paramType = fnType->getParams()[paramIdx].getParameterType();
if (auto paramFnType = paramType->getAs<FunctionType>()) {
conversionsOrFixes.push_back(RemoveExtraneousArguments::create(
*this, paramFnType, {}, loc));
break;
}
}
}
}
}
auto *parentLoc = getConstraintLocator(anchor, path);
if (lhs->is<InOutType>() != rhs->is<InOutType>()) {
// Since `FunctionArgument` as a last locator element represents
// a single parameter of the function type involved in a conversion
// to another function type, see `matchFunctionTypes`. If there is already
// a fix for the this conversion, we can just ignore individual function
// argument in-out mismatch failure by considered this fixed.
if (hasFixFor(parentLoc))
return true;
// We want to call matchTypes with the default decomposition options
// in case there are type variables that we couldn't bind due to the
// inout attribute mismatch.
auto result = matchTypes(lhs->getInOutObjectType(),
rhs->getInOutObjectType(), matchKind,
getDefaultDecompositionOptions(TMF_ApplyingFix),
locator);
if (result.isSuccess()) {
conversionsOrFixes.push_back(AllowInOutConversion::create(*this, lhs,
rhs, getConstraintLocator(locator)));
break;
}
}
// In cases like this `FunctionArgument` as a last locator element
// represents a single parameter of the function type involved in
// a conversion to another function type, see `matchFunctionTypes`.
if (parentLoc->isForContextualType() ||
parentLoc->isLastElement<LocatorPathElt::ApplyArgToParam>()) {
// If either type has a placeholder, consider this fixed.
if (lhs->hasPlaceholder() || rhs->hasPlaceholder())
return true;
// If there is a fix associated with contextual conversion or
// a function type itself, let's ignore argument failure but
// increase a score.
if (hasFixFor(parentLoc)) {
increaseScore(SK_Fix, locator);
return true;
}
// Since there is only one parameter let's give it a chance to diagnose
// a more specific error in some situations.
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality) ||
hasConversionOrRestriction(ConversionRestrictionKind::Existential) ||
hasConversionOrRestriction(ConversionRestrictionKind::Superclass))
break;
conversionsOrFixes.push_back(AllowFunctionTypeMismatch::create(
*this, lhs, rhs, parentLoc, /*index=*/0));
break;
}
break;
}
case ConstraintLocator::TypeParameterRequirement:
case ConstraintLocator::ConditionalRequirement: {
// If either type has a placeholder, consider this fixed.
if (lhs->hasPlaceholder() || rhs->hasPlaceholder())
return true;
// If requirement is something like `T == [Int]` let's let
// type matcher a chance to match generic parameters before
// recording a fix, because then we'll know exactly how many
// generic parameters did not match.
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality))
break;
auto *reqLoc = getConstraintLocator(locator);
if (isFixedRequirement(reqLoc, rhs))
return true;
// If this is a requirement on sequence of for-in statement where one
// of the sides is a completely resolved dependent member, skip it
// since the issue is with the conformance to `Sequence`, otherwise
// dependent member would have been substituted.
if (auto *UDE = getAsExpr<UnresolvedDotExpr>(anchor)) {
if (UDE->isImplicit() &&
getContextualTypePurpose(UDE->getBase()) == CTP_ForEachSequence) {
if ((lhs->is<DependentMemberType>() && !lhs->hasTypeVariable()) ||
(rhs->is<DependentMemberType>() && !rhs->hasTypeVariable()))
return true;
}
}
if (auto *fix = fixRequirementFailure(*this, lhs, rhs, anchor, path)) {
recordFixedRequirement(reqLoc, rhs);
conversionsOrFixes.push_back(fix);
}
break;
}
case ConstraintLocator::ClosureBody:
case ConstraintLocator::ClosureResult: {
if (repairByInsertingExplicitCall(lhs, rhs))
break;
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind, conversionsOrFixes,
locator))
return true;
// If we could record a generic arguments mismatch instead of this fix,
// don't record a contextual type mismatch here.
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality))
break;
auto *fix = IgnoreContextualType::create(*this, lhs, rhs,
getConstraintLocator(locator));
conversionsOrFixes.push_back(fix);
break;
}
case ConstraintLocator::ContextualType: {
// If either type is a placeholder, consider this fixed
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
// If either side is not yet resolved, it's too early for this fix.
if (lhs->isTypeVariableOrMember() || rhs->isTypeVariableOrMember())
break;
// If there is already a fix for contextual failure, let's not
// record a duplicate one.
if (hasFixFor(getConstraintLocator(locator)))
return true;
auto purpose = getContextualTypePurpose(anchor);
if (rhs->isVoid() && purpose == CTP_ReturnStmt) {
conversionsOrFixes.push_back(
RemoveReturn::create(*this, lhs, getConstraintLocator(locator)));
return true;
}
if (repairByInsertingExplicitCall(lhs, rhs))
break;
if (repairByAnyToAnyObjectCast(lhs, rhs))
break;
if (repairViaBridgingCast(*this, lhs, rhs, conversionsOrFixes, locator))
break;
if (lhs->is<FunctionType>() && !rhs->is<AnyFunctionType>() &&
isExpr<ClosureExpr>(anchor)) {
auto *fix = ContextualMismatch::create(*this, lhs, rhs,
getConstraintLocator(locator));
conversionsOrFixes.push_back(fix);
}
// Solver can unwrap contextual type in an unlabeled one-element tuple
// while matching type to a tuple that contains one or more pack expansion
// types (because such tuples can loose their elements under substitution),
// if that's the case, let's just produce a regular contextual mismatch fix.
if (auto contextualType = isSingleUnlabeledElementTuple(rhs)) {
rhs = contextualType;
}
if (purpose == CTP_Initialization && lhs->is<TupleType>() &&
rhs->is<TupleType>()) {
auto *fix = AllowTupleTypeMismatch::create(*this, lhs, rhs,
getConstraintLocator(locator));
conversionsOrFixes.push_back(fix);
break;
}
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind, conversionsOrFixes,
locator))
return true;
// Let's wait until both sides are of the same optionality before
// attempting `.rawValue` fix.
if (hasConversionOrRestriction(ConversionRestrictionKind::ValueToOptional))
break;
if (repairByUsingRawValueOfRawRepresentableType(lhs, rhs))
break;
// If there are any restrictions here we need to wait and let
// `simplifyRestrictedConstraintImpl` handle them.
if (hasAnyRestriction())
break;
// `lhs` - is an result type and `rhs` is a contextual type.
if (repairByConstructingRawRepresentableType(lhs, rhs))
break;
conversionsOrFixes.push_back(IgnoreContextualType::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::FunctionResult: {
if (lhs->isPlaceholder() || rhs->isPlaceholder()) {
recordAnyTypeVarAsPotentialHole(lhs);
recordAnyTypeVarAsPotentialHole(rhs);
return true;
}
if (auto *kpExpr = getAsExpr<KeyPathExpr>(anchor)) {
return maybeRepairKeyPathResultFailure(kpExpr);
}
auto *loc = getConstraintLocator(anchor, {path.begin(), path.end() - 1});
// If this is a mismatch between contextual type and (trailing)
// closure with explicitly specified result type let's record it
// as contextual type mismatch.
if (loc->isLastElement<LocatorPathElt::ContextualType>() ||
loc->isLastElement<LocatorPathElt::ApplyArgToParam>()) {
auto argument = simplifyLocatorToAnchor(loc);
if (isExpr<ClosureExpr>(argument)) {
auto *locator =
getConstraintLocator(argument, ConstraintLocator::ClosureResult);
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind,
conversionsOrFixes, locator))
return true;
conversionsOrFixes.push_back(
IgnoreContextualType::create(*this, lhs, rhs, locator));
break;
}
}
// Handle function result coerce expression wrong type conversion.
if (isExpr<CoerceExpr>(anchor)) {
auto *fix =
ContextualMismatch::create(*this, lhs, rhs, loc);
conversionsOrFixes.push_back(fix);
break;
}
LLVM_FALLTHROUGH;
}
case ConstraintLocator::Member:
case ConstraintLocator::DynamicLookupResult: {
// Most likely this is an attempt to use get-only subscript as mutating,
// or assign a value of a result of function/member ref e.g. `foo() = 42`
// or `foo.bar = 42`, or `foo.bar()! = 42`.
if (repairByTreatingRValueAsLValue(rhs, lhs))
break;
// `apply argument` -> `arg/param compare` ->
// `@autoclosure result` -> `function result`
if (path.size() > 3) {
const auto &elt = path[path.size() - 2];
if (elt.getKind() == ConstraintLocator::AutoclosureResult &&
repairByInsertingExplicitCall(lhs, rhs))
return true;
}
break;
}
case ConstraintLocator::AutoclosureResult: {
if (repairByInsertingExplicitCall(lhs, rhs))
return true;
auto isPointerType = [](Type type) -> bool {
return bool(
type->lookThroughAllOptionalTypes()->getAnyPointerElementType());
};
// Let's see whether this is an implicit conversion to a pointer type
// which is invalid in @autoclosure context e.g. from `inout`, Array
// or String.
if (!isPointerType(lhs) && isPointerType(rhs)) {
auto result = matchTypes(
lhs, rhs, ConstraintKind::ArgumentConversion,
TypeMatchFlags::TMF_ApplyingFix,
locator.withPathElement(ConstraintLocator::FunctionArgument));
if (result.isSuccess())
conversionsOrFixes.push_back(AllowAutoClosurePointerConversion::create(
*this, lhs, rhs, getConstraintLocator(locator)));
}
// In situations like this:
//
// struct S<T> {}
// func foo(_: @autoclosure () -> S<Int>) {}
// foo(S<String>())
//
// Generic type conversion mismatch is a better fix which is going to
// point to the generic arguments that did not align properly.
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality))
break;
conversionsOrFixes.push_back(AllowArgumentMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::TupleElement: {
if (lhs->isPlaceholder() || rhs->isPlaceholder()) {
recordAnyTypeVarAsPotentialHole(lhs);
recordAnyTypeVarAsPotentialHole(rhs);
return true;
}
if (isExpr<ArrayExpr>(anchor) || isExpr<DictionaryExpr>(anchor)) {
// If we could record a generic arguments mismatch instead of this fix,
// don't record a ContextualMismatch here.
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality))
break;
// We already have a fix for trying to initialize/assign an array literal
// to a dictionary type. In this case elements mismatch only add extra
// verbosity to the diagnostic. So let's skip the fix and only increase
// the score to focus on suggesting using dictionary literal instead.
path.pop_back();
auto loc = getConstraintLocator(anchor, path);
if (hasFixFor(loc, FixKind::TreatArrayLiteralAsDictionary)) {
increaseScore(SK_Fix, loc);
return true;
}
conversionsOrFixes.push_back(CollectionElementContextualMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
// Drop the `tuple element` locator element so that all tuple element
// mismatches within the same tuple type can be coalesced later.
auto index = elt.getAs<LocatorPathElt::TupleElement>()->getIndex();
path.pop_back();
// Drop the tuple type path elements too, but extract each tuple type first.
if (!path.empty() && path.back().is<LocatorPathElt::TupleType>()) {
rhs = path.back().getAs<LocatorPathElt::TupleType>()->getType();
path.pop_back();
lhs = path.back().getAs<LocatorPathElt::TupleType>()->getType();
path.pop_back();
}
auto *tupleLocator = getConstraintLocator(locator.getAnchor(), path);
// Let this fail if it's a contextual mismatch with sequence element types,
// as there's a special fix for that.
if (tupleLocator->isLastElement<LocatorPathElt::SequenceElementType>())
break;
// Generic argument/requirement failures have a more general fix which
// is attached to a parent type and aggregates all argument failures
// into a single fix.
if (tupleLocator->isLastElement<LocatorPathElt::AnyRequirement>() ||
tupleLocator->isLastElement<LocatorPathElt::GenericArgument>())
break;
// If the mismatch is a part of either optional-to-optional or
// value-to-optional conversions, let's allow fix refer to a complete
// top level type and not just a part of it.
if (tupleLocator->findLast<LocatorPathElt::OptionalPayload>())
break;
if (tupleLocator->isForContextualType()) {
if (auto contextualTy = isSingleUnlabeledElementTuple(rhs)) {
return repairFailures(lhs, contextualTy, matchKind, flags,
conversionsOrFixes, tupleLocator);
}
}
ConstraintFix *fix;
if (tupleLocator->isLastElement<LocatorPathElt::FunctionArgument>()) {
fix = AllowFunctionTypeMismatch::create(*this, lhs, rhs, tupleLocator, index);
} else {
fix = AllowTupleTypeMismatch::create(*this, lhs, rhs, tupleLocator, index);
}
conversionsOrFixes.push_back(fix);
break;
}
case ConstraintLocator::PackElement: {
path.pop_back();
if (!path.empty() && path.back().is<LocatorPathElt::PackType>())
path.pop_back();
if (!path.empty() && path.back().is<LocatorPathElt::PackType>())
path.pop_back();
return repairFailures(lhs, rhs, matchKind, flags, conversionsOrFixes,
getConstraintLocator(anchor, path));
}
case ConstraintLocator::PackShape: {
auto *shapeLocator = getConstraintLocator(locator);
// FIXME: If the anchor isn't a pack expansion, this shape requirement
// came from a same-shape generic requirement, which will fail separately
// with an applied requirement fix. Currently, pack shapes can themselves be
// pack types with pack expansions, so matching shape types can recursively
// add ShapeOf constraints. For now, skip fixing the nested ones to avoid
// cascading diagnostics.
if (!isExpr<PackExpansionExpr>(shapeLocator->getAnchor()))
return true;
auto *fix = SkipSameShapeRequirement::create(*this, lhs, rhs, shapeLocator);
conversionsOrFixes.push_back(fix);
break;
}
case ConstraintLocator::SequenceElementType: {
if (lhs->isPlaceholder() || rhs->isPlaceholder()) {
recordAnyTypeVarAsPotentialHole(lhs);
recordAnyTypeVarAsPotentialHole(rhs);
return true;
}
// This is going to be diagnosed as `missing conformance`,
// so no need to create duplicate fixes.
if (rhs->isExistentialType())
break;
// If the types didn't line up, let's allow right-hand side
// of the conversion (or pattern match) to have holes. This
// helps when conversion if between a type and a tuple e.g.
// `Int` vs. `(_, _)`.
recordAnyTypeVarAsPotentialHole(rhs);
conversionsOrFixes.push_back(CollectionElementContextualMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::SubscriptMember: {
if (repairByTreatingRValueAsLValue(lhs, rhs))
break;
break;
}
case ConstraintLocator::Condition: {
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind, conversionsOrFixes,
locator))
return true;
conversionsOrFixes.push_back(IgnoreContextualType::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::UnresolvedMemberChainResult: {
// Ignore this mismatch if base or result is already a hole.
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind, conversionsOrFixes,
locator))
return true;
if (repairByTreatingRValueAsLValue(lhs, rhs))
break;
// If there is a type mismatch here it's contextual e.g.,
// `let x: E = .foo(42)`, where `.foo` is a member of `E`
// but produces an incorrect type.
auto *fix = IgnoreContextualType::create(*this, lhs, rhs,
getConstraintLocator(locator));
conversionsOrFixes.push_back(fix);
break;
}
case ConstraintLocator::ImplicitlyUnwrappedDisjunctionChoice: {
// If this is an attempt to use readonly IUO as a destination
// of an assignment e.g.
//
// let x: Int! = 0
// x = 42 <- `x` can be either `Int?` or `Int` but it can't be an l-value.
if (lhs->is<LValueType>() && !rhs->is<LValueType>()) {
auto result = matchTypes(lhs->getWithoutSpecifierType(), rhs, matchKind,
TMF_ApplyingFix, locator);
if (result.isSuccess()) {
conversionsOrFixes.push_back(
TreatRValueAsLValue::create(*this, getConstraintLocator(locator)));
}
}
break;
}
case ConstraintLocator::InstanceType: {
if (lhs->hasPlaceholder() || rhs->hasPlaceholder())
return true;
break;
}
case ConstraintLocator::OptionalPayload: {
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind, conversionsOrFixes,
locator))
return true;
if (path.size() > 1) {
path.pop_back();
if (path.back().is<LocatorPathElt::SequenceElementType>()) {
conversionsOrFixes.push_back(
CollectionElementContextualMismatch::create(
*this, lhs, rhs, getConstraintLocator(anchor, path)));
return true;
}
}
break;
}
case ConstraintLocator::TernaryBranch:
case ConstraintLocator::SingleValueStmtResult: {
recordAnyTypeVarAsPotentialHole(lhs);
recordAnyTypeVarAsPotentialHole(rhs);
if (lhs->hasPlaceholder() || rhs->hasPlaceholder())
return true;
// If there's a contextual type, let's consider it the source of truth and
// produce a contextual mismatch instead of per-branch failure, because
// it's a better pointer than potential then-to-else type mismatch.
if (auto contextualType =
getContextualType(anchor, /*forConstraint=*/false)) {
auto purpose = getContextualTypePurpose(anchor);
if (contextualType->isEqual(rhs)) {
auto *loc = getConstraintLocator(
anchor, LocatorPathElt::ContextualType(purpose));
if (hasFixFor(loc, FixKind::IgnoreContextualType))
return true;
if (contextualType->isVoid() && purpose == CTP_ReturnStmt) {
conversionsOrFixes.push_back(RemoveReturn::create(*this, lhs, loc));
break;
}
conversionsOrFixes.push_back(
IgnoreContextualType::create(*this, lhs, rhs, loc));
break;
}
}
// If there is no contextual type, this is most likely a contextual type
// mismatch between the branches.
conversionsOrFixes.push_back(ContextualMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::EnumPatternImplicitCastMatch: {
// If either type is a placeholder, consider this fixed.
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
conversionsOrFixes.push_back(ContextualMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::PatternMatch: {
auto *pattern = elt.castTo<LocatorPathElt::PatternMatch>().getPattern();
// TODO: We ought to introduce a new locator element for this.
bool isMemberMatch =
lhs->is<FunctionType>() && isa<EnumElementPattern>(pattern);
// If member reference couldn't be resolved, let's allow pattern
// to have holes.
if (rhs->isPlaceholder() && isMemberMatch) {
recordAnyTypeVarAsPotentialHole(lhs);
return true;
}
// If either type is a placeholder, consider this fixed.
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
if (isMemberMatch) {
recordAnyTypeVarAsPotentialHole(lhs);
recordAnyTypeVarAsPotentialHole(rhs);
conversionsOrFixes.push_back(AllowAssociatedValueMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
// `weak` declaration with an explicit non-optional type e.g.
// `weak x: X = ...` where `X` is a class.
if (auto *TP = dyn_cast<TypedPattern>(pattern)) {
if (auto *NP = dyn_cast<NamedPattern>(TP->getSubPattern())) {
auto *var = NP->getDecl();
auto ROK = ReferenceOwnership::Strong;
if (auto *OA = var->getAttrs().getAttribute<ReferenceOwnershipAttr>())
ROK = OA->get();
if (!lhs->getOptionalObjectType() &&
optionalityOf(ROK) == ReferenceOwnershipOptionality::Required) {
conversionsOrFixes.push_back(
AllowNonOptionalWeak::create(*this, getConstraintLocator(NP)));
break;
}
}
}
conversionsOrFixes.push_back(ContextualMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::GenericArgument: {
// If any of the types is a placeholder, consider it fixed.
if (lhs->isPlaceholder() || rhs->isPlaceholder())
return true;
// Ignoring the generic argument because we may have a generic requirement
// failure e.g. `String bind T.Element`, so let's drop the generic argument
// path element and recurse in repairFailures to check and potentially
// record the requirement failure fix.
auto genericArgElt =
path.pop_back_val().castTo<LocatorPathElt::GenericArgument>();
// If we have something like ... -> type req # -> pack element #, we're
// solving a requirement of the form T : P where T is a type parameter pack
if (!path.empty() && path.back().is<LocatorPathElt::PackElement>())
path.pop_back();
if (!path.empty() && path.back().is<LocatorPathElt::AnyRequirement>()) {
return repairFailures(lhs, rhs, matchKind, flags, conversionsOrFixes,
getConstraintLocator(anchor, path));
}
// When the solver sets `TMF_MatchingGenericArguments` it means
// that it's matching generic argument pairs to identify any mismatches
// as part of larger matching of two generic types. Letting this
// fail results in a single fix that aggregates all mismatch locations.
//
// Types are not always resolved enough to enable that which means
// that the comparison should be delayed, which brings us here - a
// standalone constraint that represents such a match, in such cases
// we create a fix per mismatch location and coalesce them during
// diagnostics.
if (flags.contains(TMF_MatchingGenericArguments))
break;
Type fromType;
Type toType;
if (path.size() >= 2) {
if (path[path.size() - 2].is<LocatorPathElt::GenericType>()) {
fromType = path[path.size() - 2]
.castTo<LocatorPathElt::GenericType>()
.getType();
}
if (path[path.size() - 1].is<LocatorPathElt::GenericType>()) {
toType = path[path.size() - 1]
.castTo<LocatorPathElt::GenericType>()
.getType();
}
}
if (!fromType || !toType)
break;
Type fromObjectType, toObjectType;
unsigned fromUnwraps, toUnwraps;
std::tie(fromObjectType, fromUnwraps) = getObjectTypeAndNumUnwraps(lhs);
std::tie(toObjectType, toUnwraps) = getObjectTypeAndNumUnwraps(rhs);
// If the bound contextual type is more optional than the binding type, then
// propogate binding type to contextual type and attempt to solve.
if (fromUnwraps < toUnwraps) {
(void)matchTypes(fromObjectType, toObjectType, ConstraintKind::Bind,
TMF_ApplyingFix, locator);
}
// Drop both `GenericType` elements.
path.pop_back();
path.pop_back();
ConstraintFix *fix = nullptr;
if (!path.empty() && path.back().is<LocatorPathElt::AnyRequirement>()) {
fix = fixRequirementFailure(*this, fromType, toType, anchor, path);
} else {
fix = GenericArgumentsMismatch::create(
*this, fromType, toType, {genericArgElt.getIndex()},
getConstraintLocator(anchor, path));
}
if (!fix)
break;
conversionsOrFixes.push_back(fix);
return true;
}
case ConstraintLocator::ResultBuilderBodyResult: {
// If result type of the body couldn't be determined
// there is going to be other fix available to diagnose
// the underlying issue.
if (lhs->isPlaceholder())
return true;
conversionsOrFixes.push_back(ContextualMismatch::create(
*this, lhs, rhs, getConstraintLocator(locator)));
break;
}
case ConstraintLocator::GlobalActorType: {
// Drop global actor element as it servers only to indentify the global
// actor matching.
path.pop_back();
conversionsOrFixes.push_back(AllowGlobalActorMismatch::create(
*this, lhs, rhs, getConstraintLocator(anchor, path)));
break;
}
case ConstraintLocator::CoercionOperand: {
auto *coercion = castToExpr<CoerceExpr>(anchor);
// Coercion from T.Type to T.Protocol.
if (hasConversionOrRestriction(
ConversionRestrictionKind::MetatypeToExistentialMetatype))
return false;
if (hasConversionOrRestriction(ConversionRestrictionKind::Superclass))
return false;
// Let's check whether the sub-expression is an optional type which
// is possible to unwrap (either by force or `??`) to satisfy the cast,
// otherwise we'd have to fallback to force downcast.
if (repairViaOptionalUnwrap(*this, lhs, rhs, matchKind,
conversionsOrFixes,
getConstraintLocator(coercion->getSubExpr())))
return true;
// If the result type of the coercion has an value to optional conversion
// we can instead suggest the conditional downcast as it is safer in
// situations like conditional binding.
auto useConditionalCast =
llvm::any_of(ConstraintRestrictions, [&](const auto &restriction) {
Type type1, type2;
std::tie(type1, type2) = restriction.first;
auto restrictionKind = restriction.second;
if (restrictionKind != ConversionRestrictionKind::ValueToOptional)
return false;
return rhs->isEqual(type1);
});
// Repair a coercion ('as') with a runtime checked cast ('as!' or 'as?').
if (auto *coerceToCheckCastFix =
CoerceToCheckedCast::attempt(*this, lhs, rhs, useConditionalCast,
getConstraintLocator(locator))) {
conversionsOrFixes.push_back(coerceToCheckCastFix);
return true;
}
// If it has a deep equality restriction, defer the diagnostic to
// GenericMismatch.
if (hasConversionOrRestriction(ConversionRestrictionKind::DeepEquality) &&
!hasConversionOrRestriction(
ConversionRestrictionKind::OptionalToOptional)) {
return false;
}
if (hasConversionOrRestriction(ConversionRestrictionKind::Existential))
return false;
auto *fix = ContextualMismatch::create(*this, lhs, rhs,
getConstraintLocator(locator));
conversionsOrFixes.push_back(fix);
return true;
}
case ConstraintLocator::KeyPathValue: {
if (maybeRepairKeyPathResultFailure(getAsExpr<KeyPathExpr>(anchor)))
return true;
break;
}
default:
break;
}
return !conversionsOrFixes.empty();
}
static bool isTupleWithUnresolvedPackExpansion(Type type) {
if (auto *tuple = type->getAs<TupleType>()) {
return llvm::any_of(tuple->getElements(), [&](const TupleTypeElt &elt) {
if (auto typeVar = elt.getType()->getAs<TypeVariableType>())
return typeVar->getImpl().isPackExpansion();
return false;
});
}
return false;
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchTypes(Type type1, Type type2, ConstraintKind kind,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto origType1 = type1;
auto origType2 = type2;
// If we have type variables that have been bound to fixed types, look through
// to the fixed type.
type1 = getFixedTypeRecursive(type1, flags, kind == ConstraintKind::Equal);
type2 = getFixedTypeRecursive(type2, flags, kind == ConstraintKind::Equal);
auto desugar1 = type1->getDesugaredType();
auto desugar2 = type2->getDesugaredType();
// If both sides are dependent members without type variables, it's
// possible that base type is incorrect e.g. `Foo.Element` where `Foo`
// is a concrete type substituted for generic parameter,
// so checking equality here would lead to incorrect behavior,
// let's defer it until later proper check.
if (!(desugar1->is<DependentMemberType>() &&
desugar2->is<DependentMemberType>())) {
// If the types are obviously equivalent, we're done.
if (desugar1->isEqual(desugar2) && !isa<InOutType>(desugar2)) {
return getTypeMatchSuccess();
}
}
// Local function that should be used to produce the return value whenever
// this function was unable to resolve the constraint. It should be used
// within \c matchTypes() as
//
// return formUnsolvedResult();
//
// along any unsolved path. No other returns should produce
// SolutionKind::Unsolved or inspect TMF_GenerateConstraints.
auto formUnsolvedResult = [&] {
// If we're supposed to generate constraints (i.e., this is a
// newly-generated constraint), do so now.
if (flags.contains(TMF_GenerateConstraints)) {
// Add a new constraint between these types. We consider the current
// type-matching problem to the "solved" by this addition, because
// this new constraint will be solved at a later point.
// Obviously, this must not happen at the top level, or the
// algorithm would not terminate.
addUnsolvedConstraint(Constraint::create(*this, kind, type1, type2,
getConstraintLocator(locator)));
return getTypeMatchSuccess();
}
return getTypeMatchAmbiguous();
};
auto *typeVar1 = dyn_cast<TypeVariableType>(desugar1);
auto *typeVar2 = dyn_cast<TypeVariableType>(desugar2);
// If either (or both) types are type variables, unify the type variables.
if (typeVar1 || typeVar2) {
// Handle the easy case of both being type variables, and being
// identical, first.
if (typeVar1 && typeVar2) {
auto rep1 = getRepresentative(typeVar1);
auto rep2 = getRepresentative(typeVar2);
if (rep1 == rep2) {
// We already merged these two types, so this constraint is
// trivially solved.
return getTypeMatchSuccess();
}
}
switch (kind) {
case ConstraintKind::Bind:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Equal: {
if (typeVar1 && typeVar2) {
auto rep1 = getRepresentative(typeVar1);
auto rep2 = getRepresentative(typeVar2);
// Pack expansion variables cannot be merged because
// they involve other type variables.
if (rep1->getImpl().isPackExpansion() ||
rep2->getImpl().isPackExpansion())
return formUnsolvedResult();
// If exactly one of the type variables can bind to an lvalue, we
// can't merge these two type variables.
if (kind == ConstraintKind::Equal &&
rep1->getImpl().canBindToLValue()
!= rep2->getImpl().canBindToLValue())
return formUnsolvedResult();
// Merge the equivalence classes corresponding to these two variables.
mergeEquivalenceClasses(rep1, rep2, /*updateWorkList=*/true);
return getTypeMatchSuccess();
}
// If type variable represents a key path value type, defer binding it to
// contextual type in diagnostic mode. We want it to be bound from the
// last key path component to help with diagnostics.
if (shouldAttemptFixes()) {
if (typeVar1 && typeVar1->getImpl().isKeyPathValue() &&
!flags.contains(TMF_BindingTypeVariable))
return formUnsolvedResult();
}
assert((type1->is<TypeVariableType>() != type2->is<TypeVariableType>()) &&
"Expected a type variable and a non type variable!");
auto *typeVar = typeVar1 ? typeVar1 : typeVar2;
auto type = typeVar1 ? type2 : type1;
return matchTypesBindTypeVar(typeVar, type, kind, flags, locator,
formUnsolvedResult);
}
case ConstraintKind::BindParam: {
if (typeVar2 && !typeVar1) {
// Simplify the left-hand type and perform the "occurs" check.
auto rep2 = getRepresentative(typeVar2);
type1 = simplifyType(type1, flags);
if (!isBindable(typeVar2, type1))
return formUnsolvedResult();
if (auto *iot = type1->getAs<InOutType>()) {
if (!rep2->getImpl().canBindToLValue())
return getTypeMatchFailure(locator);
assignFixedType(rep2, LValueType::get(iot->getObjectType()));
} else {
assignFixedType(rep2, type1);
}
return getTypeMatchSuccess();
} else if (typeVar1 && !typeVar2) {
// Simplify the right-hand type and perform the "occurs" check.
auto rep1 = getRepresentative(typeVar1);
type2 = simplifyType(type2, flags);
if (!isBindable(rep1, type2))
return formUnsolvedResult();
if (auto *lvt = type2->getAs<LValueType>()) {
if (!rep1->getImpl().canBindToInOut())
return getTypeMatchFailure(locator);
assignFixedType(rep1, InOutType::get(lvt->getObjectType()));
} else {
assignFixedType(rep1, type2);
}
return getTypeMatchSuccess();
} if (typeVar1 && typeVar2) {
auto rep1 = getRepresentative(typeVar1);
auto rep2 = getRepresentative(typeVar2);
// Pack expansion variables cannot be merged because
// they involve other type variables.
if (rep1->getImpl().isPackExpansion() ||
rep2->getImpl().isPackExpansion())
return formUnsolvedResult();
if (!rep1->getImpl().canBindToInOut() ||
!rep2->getImpl().canBindToLValue()) {
// Merge the equivalence classes corresponding to these two variables.
mergeEquivalenceClasses(rep1, rep2, /*updateWorkList=*/true);
return getTypeMatchSuccess();
}
}
return formUnsolvedResult();
}
case ConstraintKind::Subtype:
case ConstraintKind::Conversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion: {
if (typeVar1) {
// Performance optimization: Propagate fully or partially resolved
// contextual type down into the body of result builder transformed
// closure by eagerly binding intermediate body result type to the
// contextual one. This helps to determine when closure body could be
// solved early.
//
// TODO: This could be extended to cover all multi-statement closures.
//
// See \c BindingSet::favoredOverConjunction for more details.
if (!typeVar2 && locator.endsWith<LocatorPathElt::FunctionResult>()) {
SmallVector<LocatorPathElt> path;
auto anchor = locator.getLocatorParts(path);
// Drop `FunctionResult` element.
path.pop_back();
ClosureExpr *closure = nullptr;
{
// This avoids a new locator allocation.
SourceRange range;
ArrayRef<LocatorPathElt> scratchPath(path);
simplifyLocator(anchor, scratchPath, range);
if (scratchPath.empty())
closure = getAsExpr<ClosureExpr>(anchor);
}
if (closure && !closure->hasExplicitResultType() &&
getAppliedResultBuilderTransform(closure)) {
return matchTypesBindTypeVar(typeVar1, type2, ConstraintKind::Equal,
flags, locator, formUnsolvedResult);
}
}
}
return formUnsolvedResult();
}
case ConstraintKind::ApplicableFunction:
case ConstraintKind::DynamicCallableApplicableFunction:
case ConstraintKind::BindOverload:
case ConstraintKind::BridgingConversion:
case ConstraintKind::CheckedCast:
case ConstraintKind::SubclassOf:
case ConstraintKind::ConformsTo:
case ConstraintKind::TransitivelyConformsTo:
case ConstraintKind::Defaultable:
case ConstraintKind::Disjunction:
case ConstraintKind::Conjunction:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::OptionalObject:
case ConstraintKind::SelfObjectOfProtocol:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueMember:
case ConstraintKind::ValueWitness:
case ConstraintKind::OneWayEqual:
case ConstraintKind::OneWayBindParam:
case ConstraintKind::FallbackType:
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PropertyWrapper:
case ConstraintKind::SyntacticElement:
case ConstraintKind::BindTupleOfFunctionParams:
case ConstraintKind::PackElementOf:
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
llvm_unreachable("Not a relational constraint");
}
}
// If one of the types is a member type of a type variable type,
// there's nothing we can do.
if (desugar1->isTypeVariableOrMember() ||
desugar2->isTypeVariableOrMember()) {
return formUnsolvedResult();
}
// If the original type on one side consisted of a tuple type with
// unresolved pack expansion(s), let's make sure that both sides are
// tuples to enable proper pack matching for situations like:
//
// `Int <conversion> (_: $T3)`
// where `$T3` is pack expansion of pattern type `$T2`
//
// `Int` should be wrapped in a one-element tuple to make sure
// that tuple matcher can form a pack expansion type that would
// match `$T3` and propagate `Pack{Int}` to `$T2`.
//
// This is also important for situations like: `$T2 conv (Int, $T_exp)`
// becuase expansion could be defaulted to an empty pack which means
// that under substitution that element would disappear and the type
// would be just `(Int)`.
//
// Notable exception here is `Any` which doesn't require wrapping and
// would be handled by existental promotion in cases where it's allowed.
if (isTupleWithUnresolvedPackExpansion(origType1) ||
isTupleWithUnresolvedPackExpansion(origType2)) {
if (desugar1->is<TupleType>() != desugar2->is<TupleType>() &&
(!desugar1->isAny() && !desugar2->isAny())) {
return matchTypes(
desugar1->is<TupleType>() ? type1
: TupleType::get({type1}, getASTContext()),
desugar2->is<TupleType>() ? type2
: TupleType::get({type2}, getASTContext()),
kind, flags, locator);
}
}
llvm::SmallVector<RestrictionOrFix, 4> conversionsOrFixes;
// Decompose parallel structure.
TypeMatchOptions subflags =
getDefaultDecompositionOptions(flags) - TMF_ApplyingFix;
if (desugar1->getKind() == desugar2->getKind()) {
switch (desugar1->getKind()) {
#define SUGARED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("Type has not been desugared completely");
#define ARTIFICIAL_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("artificial type in constraint");
case TypeKind::BuiltinTuple:
llvm_unreachable("BuiltinTupleType in constraint");
// Note: Mismatched builtin types fall through to the TypeKind::Error
// case below.
#define BUILTIN_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::Error:
case TypeKind::Unresolved:
return getTypeMatchFailure(locator);
case TypeKind::Placeholder: {
// If it's allowed to attempt fixes, let's delegate
// decision to `repairFailures`, since depending on
// locator we might either ignore such a mismatch,
// or record a specialized fix.
if (shouldAttemptFixes())
break;
return getTypeMatchFailure(locator);
}
case TypeKind::GenericTypeParam:
llvm_unreachable("unmapped dependent type in type checker");
case TypeKind::TypeVariable:
llvm_unreachable("type variables should have already been handled by now");
case TypeKind::DependentMember: {
// If types are identical, let's consider this constraint solved
// even though they are dependent members, they would be resolved
// to the same concrete type.
if (desugar1->isEqual(desugar2))
return getTypeMatchSuccess();
if (shouldAttemptFixes()) {
if (!desugar1->hasTypeVariable() && !desugar2->hasTypeVariable()) {
auto *loc = getConstraintLocator(locator);
auto *fix =
loc->isLastElement<LocatorPathElt::TypeParameterRequirement>()
? fixRequirementFailure(*this, type1, type2, loc->getAnchor(),
loc->getPath())
: ContextualMismatch::create(*this, type1, type2, loc);
if (!fix || recordFix(fix))
return getTypeMatchFailure(locator);
return getTypeMatchSuccess();
}
}
// If one of the dependent member types has no type variables,
// this comparison is effectively illformed, because dependent
// member couldn't be simplified down to the actual type, and
// we wouldn't be able to solve this constraint, so let's just fail.
// This should only happen outside of diagnostic mode, as otherwise the
// member is replaced by a placeholder in simplifyType.
if (!desugar1->hasTypeVariable() || !desugar2->hasTypeVariable())
return getTypeMatchFailure(locator);
// Nothing we can solve yet, since we need to wait until
// type variables will get resolved.
return formUnsolvedResult();
}
case TypeKind::Module:
case TypeKind::PrimaryArchetype:
case TypeKind::OpenedArchetype:
case TypeKind::PackArchetype:
case TypeKind::ElementArchetype: {
// Give `repairFailures` a chance to fix the problem.
if (shouldAttemptFixes())
break;
// If two module types or archetypes were not already equal, there's
// nothing more we can do.
return getTypeMatchFailure(locator);
}
case TypeKind::Tuple: {
// FIXME: TuplePackMatcher doesn't correctly handle matching two
// abstract contextual tuple types in a generic context.
if (simplifyType(desugar1)->isEqual(simplifyType(desugar2)))
return getTypeMatchSuccess();
// If the tuple has consecutive pack expansions, packs must be
// resolved before matching.
auto delayMatching = [](TupleType *tuple) {
bool afterPack = false;
for (auto element : tuple->getElements()) {
if (afterPack && !element.hasName()) {
SmallPtrSet<TypeVariableType *, 2> typeVars;
element.getType()->getTypeVariables(typeVars);
bool hasUnresolvedPack = llvm::any_of(typeVars, [](auto *tv) {
return tv->getImpl().canBindToPack();
});
if (hasUnresolvedPack)
return true;
}
// Delay matching if one of the elements is unresolved pack
// expansion represented by a type variable.
if (auto *typeVar = element.getType()->getAs<TypeVariableType>()) {
if (typeVar->getImpl().isPackExpansion())
return true;
}
afterPack = element.getType()->is<PackExpansionType>();
}
return false;
};
auto *tuple1 = cast<TupleType>(desugar1);
auto *tuple2 = cast<TupleType>(desugar2);
if (delayMatching(tuple1) || delayMatching(tuple2)) {
return formUnsolvedResult();
}
// Closure result is allowed to convert to Void in certain circumstances,
// let's forego tuple matching because it is guaranteed to fail and jump
// to `() -> T` to `() -> Void` rule.
if (locator.endsWith<LocatorPathElt::ClosureBody>()) {
if (containsPackExpansionType(tuple1) && tuple2->isVoid())
break;
}
// Add each tuple type to the locator before matching the element types.
// This is useful for diagnostics, because the error message can use the
// full tuple type for several element mismatches. Use the original types
// to preserve sugar such as typealiases.
auto tmpTupleLoc = locator.withPathElement(LocatorPathElt::TupleType(type1));
auto tupleLoc = tmpTupleLoc.withPathElement(LocatorPathElt::TupleType(type2));
auto result = matchTupleTypes(cast<TupleType>(desugar1),
cast<TupleType>(desugar2),
kind, subflags, tupleLoc);
if (result != SolutionKind::Error)
return result;
// FIXME: All cases in this switch should go down to the fix logic
// to give repairFailures() a chance to run, but this breaks stuff
// right now.
break;
}
case TypeKind::Enum:
case TypeKind::Struct:
case TypeKind::Class: {
auto nominal1 = cast<NominalType>(desugar1);
auto nominal2 = cast<NominalType>(desugar2);
if (nominal1->getDecl() == nominal2->getDecl())
conversionsOrFixes.push_back(ConversionRestrictionKind::DeepEquality);
// Check for CF <-> ObjectiveC bridging.
if (isa<ClassType>(desugar1) &&
kind >= ConstraintKind::Subtype) {
auto class1 = cast<ClassDecl>(nominal1->getDecl());
auto class2 = cast<ClassDecl>(nominal2->getDecl());
// CF -> Objective-C via toll-free bridging.
if (class1->getForeignClassKind() == ClassDecl::ForeignKind::CFType &&
class2->getForeignClassKind() != ClassDecl::ForeignKind::CFType &&
class1->getAttrs().hasAttribute<ObjCBridgedAttr>()) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::CFTollFreeBridgeToObjC);
}
// Objective-C -> CF via toll-free bridging.
if (class2->getForeignClassKind() == ClassDecl::ForeignKind::CFType &&
class1->getForeignClassKind() != ClassDecl::ForeignKind::CFType &&
class2->getAttrs().hasAttribute<ObjCBridgedAttr>()) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::ObjCTollFreeBridgeToCF);
}
}
if (kind >= ConstraintKind::Subtype &&
nominal1->getDecl() != nominal2->getDecl() &&
((nominal1->isCGFloat() || nominal2->isCGFloat()) &&
(nominal1->isDouble() || nominal2->isDouble()))) {
ConstraintLocatorBuilder location{locator};
// Look through all value-to-optional promotions to allow
// conversions like Double -> CGFloat?? and vice versa.
// T -> Optional<T>
if (location.endsWith<LocatorPathElt::OptionalPayload>()) {
SmallVector<LocatorPathElt, 4> path;
auto anchor = location.getLocatorParts(path);
// An attempt at Double/CGFloat conversion through
// optional chaining. This is not supported at the
// moment because solution application doesn't know
// how to map Double to/from CGFloat through optionals.
if (isExpr<OptionalEvaluationExpr>(anchor)) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);
conversionsOrFixes.push_back(ContextualMismatch::create(
*this, nominal1, nominal2, getConstraintLocator(locator)));
break;
}
// Drop all of the applied `value-to-optional` promotions.
path.erase(llvm::remove_if(
path,
[](const LocatorPathElt &elt) {
return elt.is<LocatorPathElt::OptionalPayload>();
}),
path.end());
location = getConstraintLocator(anchor, path);
}
// Support implicit Double<->CGFloat conversions only for
// something which could be directly represented in the AST
// e.g. argument-to-parameter, contextual conversions etc.
if (!location.trySimplifyToExpr()) {
return getTypeMatchFailure(locator);
}
SmallVector<LocatorPathElt, 4> path;
auto anchor = location.getLocatorParts(path);
// Try implicit CGFloat conversion only if:
// - This is not:
// - an explicit call to a CGFloat initializer;
// - an explicit coercion;
// - a runtime type check (via `is` expression);
// - a checked or conditional cast;
// - This is a first type such conversion is attempted for
// for a given path (AST element).
auto isCGFloatInit = [&](ASTNode location) {
if (auto *call = getAsExpr<CallExpr>(location)) {
if (auto *typeExpr = dyn_cast<TypeExpr>(call->getFn())) {
return getInstanceType(typeExpr)->isCGFloat();
}
}
return false;
};
auto isCoercionOrCast = [](ASTNode anchor,
ArrayRef<LocatorPathElt> path) {
// E.g. contextual conversion from coercion/cast
// to some other type.
if (!(path.empty() ||
path.back().is<LocatorPathElt::CoercionOperand>()))
return false;
return isExpr<CoerceExpr>(anchor) || isExpr<IsExpr>(anchor) ||
isExpr<ConditionalCheckedCastExpr>(anchor) ||
isExpr<ForcedCheckedCastExpr>(anchor);
};
if (!isCGFloatInit(anchor) && !isCoercionOrCast(anchor, path) &&
llvm::none_of(path, [&](const LocatorPathElt &rawElt) {
if (auto elt =
rawElt.getAs<LocatorPathElt::ImplicitConversion>()) {
auto convKind = elt->getConversionKind();
return convKind == ConversionRestrictionKind::DoubleToCGFloat ||
convKind == ConversionRestrictionKind::CGFloatToDouble;
}
return false;
})) {
conversionsOrFixes.push_back(
desugar1->isCGFloat()
? ConversionRestrictionKind::CGFloatToDouble
: ConversionRestrictionKind::DoubleToCGFloat);
}
}
break;
}
case TypeKind::DynamicSelf:
// FIXME: Deep equality? What is the rule between two DynamicSelfs?
break;
case TypeKind::Protocol:
// Nothing to do here; try existential and user-defined conversions below.
break;
case TypeKind::Metatype:
case TypeKind::ExistentialMetatype: {
auto meta1 = cast<AnyMetatypeType>(desugar1);
auto meta2 = cast<AnyMetatypeType>(desugar2);
// A.Type < B.Type if A < B and both A and B are classes.
// P.Type < Q.Type if P < Q, both P and Q are protocols, and P.Type
// and Q.Type are both existential metatypes
auto subKind = std::min(kind, ConstraintKind::Subtype);
// If instance types can't have a subtype relationship
// it means that such types can be simply equated.
auto instanceType1 = meta1->getInstanceType();
auto instanceType2 = meta2->getInstanceType();
if (isa<MetatypeType>(meta1) &&
!(instanceType1->mayHaveSuperclass() &&
instanceType2->getClassOrBoundGenericClass())) {
subKind = ConstraintKind::Bind;
}
auto result =
matchTypes(instanceType1, instanceType2, subKind, subflags,
locator.withPathElement(ConstraintLocator::InstanceType));
// If matching of the instance types resulted in the failure make sure
// to give `repairFailure` a chance to run to attempt to fix the issue.
if (shouldAttemptFixes() && result.isFailure())
break;
return result;
}
case TypeKind::Function: {
auto func1 = cast<FunctionType>(desugar1);
auto func2 = cast<FunctionType>(desugar2);
auto result = matchFunctionTypes(func1, func2, kind, flags, locator);
if (shouldAttemptFixes() && result.isFailure())
break;
return result;
}
case TypeKind::GenericFunction:
llvm_unreachable("Polymorphic function type should have been opened");
case TypeKind::Existential:
case TypeKind::ProtocolComposition:
case TypeKind::ParameterizedProtocol:
switch (kind) {
case ConstraintKind::Equal:
case ConstraintKind::Bind:
case ConstraintKind::BindParam:
// If we are matching types for equality, we might still have
// type variables inside the protocol composition's superclass
// constraint.
if (desugar1->getKind() == desugar2->getKind())
conversionsOrFixes.push_back(ConversionRestrictionKind::DeepEquality);
break;
default:
// Subtype constraints where the RHS is an existential type are
// handled below.
break;
}
break;
case TypeKind::LValue:
if (kind == ConstraintKind::BindParam)
return getTypeMatchFailure(locator);
return matchTypes(cast<LValueType>(desugar1)->getObjectType(),
cast<LValueType>(desugar2)->getObjectType(),
ConstraintKind::Bind, subflags,
locator.withPathElement(
ConstraintLocator::LValueConversion));
case TypeKind::InOut:
if (kind == ConstraintKind::BindParam)
return getTypeMatchFailure(locator);
if (kind == ConstraintKind::OperatorArgumentConversion) {
conversionsOrFixes.push_back(
RemoveAddressOf::create(*this, type1, type2,
getConstraintLocator(locator)));
break;
}
return matchTypes(cast<InOutType>(desugar1)->getObjectType(),
cast<InOutType>(desugar2)->getObjectType(),
ConstraintKind::Bind, subflags,
locator.withPathElement(ConstraintLocator::LValueConversion));
case TypeKind::UnboundGeneric:
llvm_unreachable("Unbound generic type should have been opened");
case TypeKind::BoundGenericClass:
case TypeKind::BoundGenericEnum:
case TypeKind::BoundGenericStruct: {
auto bound1 = cast<BoundGenericType>(desugar1);
auto bound2 = cast<BoundGenericType>(desugar2);
if (bound1->getDecl() == bound2->getDecl())
conversionsOrFixes.push_back(ConversionRestrictionKind::DeepEquality);
break;
}
// Opaque archetypes are globally bound, so we can match them for deep
// equality.
case TypeKind::OpaqueTypeArchetype: {
auto opaque1 = cast<OpaqueTypeArchetypeType>(desugar1);
auto opaque2 = cast<OpaqueTypeArchetypeType>(desugar2);
if (opaque1->getDecl() == opaque2->getDecl()) {
conversionsOrFixes.push_back(ConversionRestrictionKind::DeepEquality);
}
break;
}
case TypeKind::Pack: {
auto tmpPackLoc = locator.withPathElement(LocatorPathElt::PackType(type1));
auto packLoc = tmpPackLoc.withPathElement(LocatorPathElt::PackType(type2));
auto result =
matchPackTypes(cast<PackType>(desugar1), cast<PackType>(desugar2),
kind, subflags, packLoc);
// Let `repairFailures` attempt to "fix" this.
if (shouldAttemptFixes() && result.isFailure())
break;
return result;
}
case TypeKind::PackExpansion: {
auto expansion1 = cast<PackExpansionType>(desugar1);
auto expansion2 = cast<PackExpansionType>(desugar2);
return matchPackExpansionTypes(expansion1, expansion2, kind, subflags,
locator);
}
case TypeKind::PackElement: {
auto pack1 = cast<PackElementType>(desugar1)->getPackType();
auto pack2 = cast<PackElementType>(desugar2)->getPackType();
return matchTypes(pack1, pack2, kind, subflags, locator);
}
case TypeKind::ErrorUnion:
break;
}
}
if (kind >= ConstraintKind::Conversion) {
// An lvalue of type T1 can be converted to a value of type T2 so long as
// T1 is convertible to T2 (by loading the value). Note that we cannot get
// a value of inout type as an lvalue though.
if (type1->is<LValueType>() && !type2->is<InOutType>()) {
auto result = matchTypes(type1->getWithoutSpecifierType(), type2, kind,
subflags, locator);
if (result.isSuccess() || !shouldAttemptFixes())
return result;
}
}
if (kind >= ConstraintKind::Subtype) {
// Subclass-to-superclass conversion.
if (type1->mayHaveSuperclass() &&
type2->getClassOrBoundGenericClass() &&
type1->getClassOrBoundGenericClass()
!= type2->getClassOrBoundGenericClass()) {
conversionsOrFixes.push_back(ConversionRestrictionKind::Superclass);
}
// Existential-to-superclass conversion.
if (type1->isClassExistentialType() &&
type2->getClassOrBoundGenericClass()) {
conversionsOrFixes.push_back(ConversionRestrictionKind::Superclass);
}
// Metatype-to-existential-metatype conversion.
//
// Equivalent to a conformance relation on the instance types.
if (type1->is<MetatypeType>() &&
type2->is<ExistentialMetatypeType>()) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::MetatypeToExistentialMetatype);
}
// Existential-metatype-to-superclass-metatype conversion.
if (type2->is<MetatypeType>()) {
if (auto *meta1 = type1->getAs<ExistentialMetatypeType>()) {
if (meta1->getInstanceType()->isClassExistentialType()) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::ExistentialMetatypeToMetatype);
}
}
}
// Concrete value to existential conversion.
if (!type1->is<LValueType>() &&
type2->isExistentialType()) {
// Penalize conversions to Any.
if (kind >= ConstraintKind::Conversion && type2->isAny())
increaseScore(ScoreKind::SK_EmptyExistentialConversion, locator);
conversionsOrFixes.push_back(ConversionRestrictionKind::Existential);
}
// T -> AnyHashable.
if (desugar2->isAnyHashable()) {
// Don't allow this in operator contexts or we'll end up allowing
// 'T() == U()' for unrelated T and U that just happen to be Hashable.
// We can remove this special case when we implement operator hiding.
if (!type1->is<LValueType>() &&
kind != ConstraintKind::OperatorArgumentConversion) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::HashableToAnyHashable);
}
}
// Metatype to object conversion.
//
// Class and protocol metatypes are interoperable with certain Objective-C
// runtime classes, but only when ObjC interop is enabled.
// Foreign reference types do *not* conform to AnyObject.
if (type1->isForeignReferenceType() && type2->isAnyObject())
return getTypeMatchFailure(locator);
if (getASTContext().LangOpts.EnableObjCInterop) {
// These conversions are between concrete types that don't need further
// resolution, so we can consider them immediately solved.
auto addSolvedRestrictedConstraint
= [&](ConversionRestrictionKind restriction) -> TypeMatchResult {
addRestrictedConstraint(ConstraintKind::Subtype, restriction,
type1, type2, locator);
return getTypeMatchSuccess();
};
if (auto meta1 = type1->getAs<MetatypeType>()) {
if (meta1->getInstanceType()->mayHaveSuperclass()
&& type2->isAnyObject()) {
increaseScore(ScoreKind::SK_UserConversion, locator);
return addSolvedRestrictedConstraint(
ConversionRestrictionKind::ClassMetatypeToAnyObject);
}
// Single @objc protocol value metatypes can be converted to the ObjC
// Protocol class type.
auto isProtocolClassType = [&](Type t) -> bool {
if (auto classDecl = t->getClassOrBoundGenericClass())
if (classDecl->getName() == getASTContext().Id_Protocol
&& classDecl->getModuleContext()->getName()
== getASTContext().Id_ObjectiveC)
return true;
return false;
};
auto constraintType = meta1->getInstanceType();
if (auto existential = constraintType->getAs<ExistentialType>())
constraintType = existential->getConstraintType();
if (auto protoTy = constraintType->getAs<ProtocolType>()) {
if (protoTy->getDecl()->isObjC()
&& isProtocolClassType(type2)) {
increaseScore(ScoreKind::SK_UserConversion, locator);
return addSolvedRestrictedConstraint(
ConversionRestrictionKind::ProtocolMetatypeToProtocolClass);
}
}
}
if (auto meta1 = type1->getAs<ExistentialMetatypeType>()) {
// Class-constrained existential metatypes can be converted to AnyObject.
if (meta1->getInstanceType()->isClassExistentialType()
&& type2->isAnyObject()) {
increaseScore(ScoreKind::SK_UserConversion, locator);
return addSolvedRestrictedConstraint(
ConversionRestrictionKind::ExistentialMetatypeToAnyObject);
}
}
}
// Special implicit nominal conversions.
if (!type1->is<LValueType>() && kind >= ConstraintKind::Subtype) {
// Array -> Array.
if (desugar1->isArrayType() && desugar2->isArrayType()) {
conversionsOrFixes.push_back(ConversionRestrictionKind::ArrayUpcast);
// Dictionary -> Dictionary.
} else if (isDictionaryType(desugar1) && isDictionaryType(desugar2)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::DictionaryUpcast);
// Set -> Set.
} else if (isSetType(desugar1) && isSetType(desugar2)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::SetUpcast);
}
}
}
if (kind == ConstraintKind::BindToPointerType) {
if (desugar2->isEqual(getASTContext().TheEmptyTupleType))
return getTypeMatchSuccess();
}
if (kind >= ConstraintKind::Conversion) {
// It is never legal to form an autoclosure that results in these
// implicit conversions to pointer types.
bool isAutoClosureArgument = locator.isForAutoclosureResult();
// Pointer arguments can be converted from pointer-compatible types.
if (kind >= ConstraintKind::ArgumentConversion) {
Type unwrappedType2 = type2;
bool type2IsOptional = false;
if (Type unwrapped = type2->getOptionalObjectType()) {
type2IsOptional = true;
unwrappedType2 = unwrapped;
}
PointerTypeKind pointerKind;
if (Type pointeeTy =
unwrappedType2->getAnyPointerElementType(pointerKind)) {
switch (pointerKind) {
case PTK_UnsafeRawPointer:
case PTK_UnsafeMutableRawPointer:
case PTK_UnsafePointer:
case PTK_UnsafeMutablePointer:
// UnsafeMutablePointer can be converted from an inout reference to a
// scalar or array.
if (auto inoutType1 = dyn_cast<InOutType>(desugar1)) {
if (!isAutoClosureArgument) {
auto inoutBaseType = inoutType1->getInOutObjectType();
auto baseIsArray =
getFixedTypeRecursive(inoutBaseType, /*wantRValue=*/true)
->isArrayType();
// FIXME: If the base is still a type variable, we can't tell
// what to do here. Might have to try \c ArrayToPointer and make
// it more robust.
if (baseIsArray)
conversionsOrFixes.push_back(
ConversionRestrictionKind::ArrayToPointer);
// Only try an inout-to-pointer conversion if we know it's not
// an array being converted to a raw pointer type. Such
// conversions can only use array-to-pointer.
if (!baseIsArray || !isRawPointerKind(pointerKind)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::InoutToPointer);
// If regular inout-to-pointer conversion doesn't work,
// let's try C pointer conversion that has special semantics
// for imported declarations.
if (isArgumentOfImportedDecl(locator)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::InoutToCPointer);
}
}
}
}
// Operators cannot use these implicit conversions.
if (kind == ConstraintKind::ArgumentConversion) {
// We can potentially convert from an UnsafeMutablePointer
// of a different type, if we're a void pointer.
Type unwrappedType1 = type1;
bool type1IsOptional = false;
if (Type unwrapped = type1->getOptionalObjectType()) {
type1IsOptional = true;
unwrappedType1 = unwrapped;
}
// Don't handle normal optional-related conversions here.
if (unwrappedType1->isEqual(unwrappedType2))
break;
PointerTypeKind type1PointerKind;
bool type1IsPointer{
unwrappedType1->getAnyPointerElementType(type1PointerKind)};
bool optionalityMatches = !type1IsOptional || type2IsOptional;
if (type1IsPointer && optionalityMatches) {
if (type1PointerKind == PTK_UnsafeMutablePointer) {
// Favor an UnsafeMutablePointer-to-UnsafeMutablePointer
// conversion.
if (type1PointerKind != pointerKind)
increaseScore(ScoreKind::SK_ValueToPointerConversion,
locator);
conversionsOrFixes.push_back(
ConversionRestrictionKind::PointerToPointer);
}
// UnsafeMutableRawPointer -> UnsafeRawPointer
else if (type1PointerKind == PTK_UnsafeMutableRawPointer &&
pointerKind == PTK_UnsafeRawPointer) {
if (type1PointerKind != pointerKind)
increaseScore(ScoreKind::SK_ValueToPointerConversion,
locator);
conversionsOrFixes.push_back(
ConversionRestrictionKind::PointerToPointer);
}
}
// UnsafePointer and UnsafeRawPointer can also be converted from an
// array or string value, or a UnsafePointer or
// AutoreleasingUnsafeMutablePointer.
if (pointerKind == PTK_UnsafePointer
|| pointerKind == PTK_UnsafeRawPointer) {
if (!isAutoClosureArgument) {
if (type1->isArrayType()) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::ArrayToPointer);
// If regular array-to-pointer conversion doesn't work,
// let's try C pointer conversion that has special semantics
// for imported declarations.
if (isArgumentOfImportedDecl(locator)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::ArrayToCPointer);
}
}
// The pointer can be converted from a string, if the element
// type is compatible.
auto &ctx = getASTContext();
if (type1->isString()) {
auto baseTy = getFixedTypeRecursive(pointeeTy, false);
if (baseTy->isTypeVariableOrMember() ||
isStringCompatiblePointerBaseType(ctx, baseTy))
conversionsOrFixes.push_back(
ConversionRestrictionKind::StringToPointer);
}
}
if (type1IsPointer && optionalityMatches &&
(type1PointerKind == PTK_UnsafePointer ||
type1PointerKind == PTK_AutoreleasingUnsafeMutablePointer)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::PointerToPointer);
}
}
// If both sides are non-optional pointers, let's check whether
// this argument supports Swift -> C pointer conversions.
//
// Do some light verification before recording restriction to
// avoid allocating constraints for obviously invalid cases.
if (type1IsPointer && !type1IsOptional && !type2IsOptional &&
(shouldAttemptFixes() || isArgumentOfImportedDecl(locator))) {
// UnsafeRawPointer -> UnsafePointer<[U]Int8>
if (type1PointerKind == PTK_UnsafeRawPointer &&
pointerKind == PTK_UnsafePointer) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::PointerToCPointer);
}
// UnsafeMutableRawPointer -> Unsafe[Mutable]Pointer<[U]Int8>
if (type1PointerKind == PTK_UnsafeMutableRawPointer &&
(pointerKind == PTK_UnsafePointer ||
pointerKind == PTK_UnsafeMutablePointer)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::PointerToCPointer);
}
// Unsafe[Mutable]Pointer -> Unsafe[Mutable]Pointer
if (type1PointerKind == PTK_UnsafePointer &&
pointerKind == PTK_UnsafePointer) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::PointerToCPointer);
}
if (type1PointerKind == PTK_UnsafeMutablePointer &&
(pointerKind == PTK_UnsafePointer ||
pointerKind == PTK_UnsafeMutablePointer)) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::PointerToCPointer);
}
}
}
break;
case PTK_AutoreleasingUnsafeMutablePointer:
// PTK_AutoreleasingUnsafeMutablePointer can be converted from an
// inout reference to a scalar.
if (!isAutoClosureArgument && type1->is<InOutType>()) {
conversionsOrFixes.push_back(
ConversionRestrictionKind::InoutToPointer);
}
break;
}
}
}
}
if (kind >= ConstraintKind::OperatorArgumentConversion) {
// If the RHS is an inout type, the LHS must be an @lvalue type.
if (auto *lvt = type1->getAs<LValueType>()) {
if (auto *iot = type2->getAs<InOutType>()) {
return matchTypes(lvt->getObjectType(), iot->getObjectType(),
ConstraintKind::Bind, subflags,
locator.withPathElement(
ConstraintLocator::LValueConversion));
}
}
}
// A value of type T! can be converted to type U if T is convertible
// to U by force-unwrapping the source value.
// A value of type T, T?, or T! can be converted to type U? or U! if
// T is convertible to U.
if (!type1->is<LValueType>() && kind >= ConstraintKind::Subtype) {
enumerateOptionalConversionRestrictions(
type1, type2, kind, locator,
[&](ConversionRestrictionKind restriction) {
conversionsOrFixes.push_back(restriction);
});
}
// Allow '() -> T' to '() -> ()' and '() -> Never' to '() -> T' for closure
// literals and expressions representing an implied result of closures and
// if/switch expressions.
if (auto elt = locator.last()) {
if (kind >= ConstraintKind::Subtype &&
(type1->isUninhabited() || type2->isVoid())) {
// Implied results can occur for closure bodies, returns, and if/switch
// expression branches.
//
// We only allow the Void conversion for implied results in a closure
// context. In the more general case, we only allow the Never conversion.
// For explicit branches, no conversions are allowed, unless this is for
// a single expression body closure, in which case we still allow the
// Never conversion.
auto *loc = getConstraintLocator(locator);
if (elt->is<LocatorPathElt::ClosureBody>() ||
loc->isForContextualType(CTP_ReturnStmt) ||
loc->isForContextualType(CTP_ClosureResult) ||
loc->isForSingleValueStmtBranch()) {
bool allowConversion = false;
if (auto *E = getAsExpr(simplifyLocatorToAnchor(loc))) {
if (auto kind = isImpliedResult(E)) {
switch (*kind) {
case ImpliedResultKind::Regular:
allowConversion = type1->isUninhabited();
break;
case ImpliedResultKind::ForClosure:
allowConversion = true;
break;
}
} else if (elt->is<LocatorPathElt::ClosureBody>()) {
// Even if explicit, we always allow uninhabited types in single
// expression closures.
allowConversion = type1->isUninhabited();
}
}
if (allowConversion) {
increaseScore(SK_FunctionConversion, locator);
return getTypeMatchSuccess();
}
}
}
}
if (kind == ConstraintKind::BindParam) {
if (auto *iot = dyn_cast<InOutType>(desugar1)) {
if (auto *lvt = dyn_cast<LValueType>(desugar2)) {
return matchTypes(iot->getObjectType(), lvt->getObjectType(),
ConstraintKind::Bind, subflags,
locator.withPathElement(
ConstraintLocator::LValueConversion));
}
}
}
// Matching types where one side is a pack expansion and the other is not
// means a pack expansion was used where it isn't supported.
if (type1->is<PackExpansionType>() != type2->is<PackExpansionType>()) {
if (!shouldAttemptFixes())
return getTypeMatchFailure(locator);
if (type1->isPlaceholder() || type2->isPlaceholder())
return getTypeMatchSuccess();
// If parameter pack expansion contains more than one element and the other
// side is a tuple, record a fix.
auto *loc = getConstraintLocator(locator);
if (loc->isLastElement<LocatorPathElt::ApplyArgToParam>()) {
if (auto packExpansion = type2->getAs<PackExpansionType>()) {
auto countType = simplifyType(packExpansion->getCountType(), flags);
if (auto paramPack = countType->getAs<PackType>()) {
if (type1->is<TupleType>() && paramPack->getNumElements() >= 1) {
if (recordFix(DestructureTupleToMatchPackExpansionParameter::create(
*this, paramPack, loc))) {
return getTypeMatchFailure(loc);
}
return getTypeMatchSuccess();
}
}
}
}
if (recordFix(AllowInvalidPackExpansion::create(*this, loc)))
return getTypeMatchFailure(locator);
return getTypeMatchSuccess();
}
// Attempt fixes iff it's allowed, both types are concrete and
// we are not in the middle of attempting one already.
if (shouldAttemptFixes() && !flags.contains(TMF_ApplyingFix)) {
if (repairFailures(type1, type2, kind, flags, conversionsOrFixes,
locator)) {
if (conversionsOrFixes.empty())
return getTypeMatchSuccess();
}
}
if (conversionsOrFixes.empty())
return getTypeMatchFailure(locator);
// Where there is more than one potential conversion, create a disjunction
// so that we'll explore all of the options.
if (conversionsOrFixes.size() > 1) {
auto fixedLocator = getConstraintLocator(locator);
SmallVector<Constraint *, 2> constraints;
for (auto potential : conversionsOrFixes) {
auto constraintKind = kind;
if (auto restriction = potential.getRestriction()) {
// Determine the constraint kind. For a deep equality constraint, only
// perform equality.
if (*restriction == ConversionRestrictionKind::DeepEquality)
constraintKind = ConstraintKind::Bind;
constraints.push_back(
Constraint::createRestricted(*this, constraintKind, *restriction,
type1, type2, fixedLocator));
if (constraints.back()->getKind() == ConstraintKind::Bind)
constraints.back()->setFavored();
continue;
}
auto fix = *potential.getFix();
constraints.push_back(
Constraint::createFixed(*this, constraintKind, fix, type1, type2,
fixedLocator));
}
// Sort favored constraints first.
std::sort(constraints.begin(), constraints.end(),
[&](Constraint *lhs, Constraint *rhs) -> bool {
if (lhs->isFavored() == rhs->isFavored())
return false;
return lhs->isFavored();
});
addDisjunctionConstraint(constraints, fixedLocator);
return getTypeMatchSuccess();
}
// For a single potential conversion, directly recurse, so that we
// don't allocate a new constraint or constraint locator.
auto formTypeMatchResult = [&](SolutionKind kind) {
switch (kind) {
case SolutionKind::Error:
return getTypeMatchFailure(locator);
case SolutionKind::Solved:
return getTypeMatchSuccess();
case SolutionKind::Unsolved:
return getTypeMatchAmbiguous();
}
llvm_unreachable("unhandled kind");
};
// Handle restrictions.
if (auto restriction = conversionsOrFixes[0].getRestriction()) {
return formTypeMatchResult(simplifyRestrictedConstraint(*restriction, type1,
type2, kind,
subflags, locator));
}
// Handle fixes.
auto fix = *conversionsOrFixes[0].getFix();
return formTypeMatchResult(simplifyFixConstraint(fix, type1, type2, kind,
subflags, locator));
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyConstructionConstraint(
Type valueType, FunctionType *fnType, TypeMatchOptions flags,
DeclContext *useDC,
FunctionRefKind functionRefKind, ConstraintLocator *locator) {
// Desugar the value type.
auto desugarValueType = valueType->getDesugaredType();
switch (desugarValueType->getKind()) {
#define SUGARED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("Type has not been desugared completely");
#define ARTIFICIAL_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("artificial type in constraint");
case TypeKind::BuiltinTuple:
llvm_unreachable("BuiltinTupleType in constraint");
case TypeKind::Unresolved:
case TypeKind::Error:
case TypeKind::Placeholder:
return SolutionKind::Error;
case TypeKind::GenericFunction:
case TypeKind::GenericTypeParam:
llvm_unreachable("unmapped dependent type");
case TypeKind::TypeVariable:
case TypeKind::DependentMember:
return SolutionKind::Unsolved;
case TypeKind::Tuple: {
// If this is an attempt to construct `Void` with arguments,
// let's diagnose it.
if (shouldAttemptFixes()) {
if (valueType->isVoid() && fnType->getNumParams() > 0) {
auto contextualType = FunctionType::get({}, fnType->getResult());
if (fixExtraneousArguments(
*this, contextualType, fnType->getParams(),
fnType->getNumParams(),
getConstraintLocator(locator,
ConstraintLocator::FunctionArgument)))
return SolutionKind::Error;
fnType = contextualType;
}
}
SmallVector<AnyFunctionType::Param, 4> args;
for (auto idx : indices(fnType->getParams())) {
auto &arg = fnType->getParams()[idx];
// We can disregard '_const', it's not applicable for tuple construction.
auto flags = arg.getParameterFlags().withCompileTimeConst(false);
// We cannot handle inout for tuple construction.
if (flags.isInOut()) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
auto *argLoc = getConstraintLocator(locator, {
LocatorPathElt::ApplyArgument(),
LocatorPathElt::ApplyArgToParam(idx, idx, ParameterTypeFlags())
});
auto argTy = arg.getParameterType();
if (recordFix(RemoveAddressOf::create(*this, argTy, argTy, argLoc)))
return SolutionKind::Error;
flags = flags.withInOut(false);
}
args.push_back(arg.withFlags(flags));
}
// Tuple construction is simply tuple conversion. We should have already
// handled the parameter flags. If any future parameter flags are added,
// they should also be verified above.
Type argType = AnyFunctionType::composeTuple(
getASTContext(), args, ParameterFlagHandling::AssertEmpty);
Type resultType = fnType->getResult();
ConstraintLocatorBuilder builder(locator);
if (matchTypes(resultType, desugarValueType, ConstraintKind::Bind, flags,
builder.withPathElement(ConstraintLocator::ApplyFunction))
.isFailure())
return SolutionKind::Error;
return matchTypes(argType, valueType, ConstraintKind::Conversion,
getDefaultDecompositionOptions(flags), locator);
}
case TypeKind::Enum:
case TypeKind::Struct:
case TypeKind::Class:
case TypeKind::BoundGenericClass:
case TypeKind::BoundGenericEnum:
case TypeKind::BoundGenericStruct:
case TypeKind::PrimaryArchetype:
case TypeKind::OpenedArchetype:
case TypeKind::OpaqueTypeArchetype:
case TypeKind::PackArchetype:
case TypeKind::ElementArchetype:
case TypeKind::DynamicSelf:
case TypeKind::ProtocolComposition:
case TypeKind::ParameterizedProtocol:
case TypeKind::Protocol:
case TypeKind::Existential:
case TypeKind::ErrorUnion:
// Break out to handle the actual construction below.
break;
case TypeKind::UnboundGeneric:
llvm_unreachable("Unbound generic type should have been opened");
#define BUILTIN_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::ExistentialMetatype:
case TypeKind::Metatype:
case TypeKind::Function:
case TypeKind::LValue:
case TypeKind::InOut:
case TypeKind::Module:
case TypeKind::Pack:
case TypeKind::PackExpansion:
case TypeKind::PackElement: {
// If solver is in the diagnostic mode and this is an invalid base,
// let's give solver a chance to repair it to produce a good diagnostic.
if (shouldAttemptFixes())
break;
return SolutionKind::Error;
}
}
auto fnLocator = getConstraintLocator(locator,
ConstraintLocator::ApplyFunction);
auto memberTypeLoc =
getConstraintLocator(fnLocator, LocatorPathElt::ConstructorMemberType(
/*shortFormOrSelfDelegating*/ true));
auto memberType = createTypeVariable(memberTypeLoc, TVO_CanBindToNoEscape);
// The constructor will have function type T -> T2, for a fresh type
// variable T. T2 is the result type provided via the construction
// constraint itself.
addValueMemberConstraint(MetatypeType::get(valueType, getASTContext()),
DeclNameRef::createConstructor(),
memberType,
useDC, functionRefKind,
/*outerAlternatives=*/{},
getConstraintLocator(
fnLocator,
ConstraintLocator::ConstructorMember));
// HACK: Bind the function's parameter list as a tuple to a type variable.
// This only exists to preserve compatibility with rdar://85263844, as it can
// affect the prioritization of bindings, which can affect behavior for tuple
// matching as tuple subtyping is currently a *weaker* constraint than tuple
// conversion.
if (!getASTContext().isSwiftVersionAtLeast(6)) {
auto paramTypeVar = createTypeVariable(
getConstraintLocator(locator, ConstraintLocator::ApplyArgument),
TVO_CanBindToLValue | TVO_CanBindToInOut | TVO_CanBindToNoEscape |
TVO_CanBindToPack);
addConstraint(ConstraintKind::BindTupleOfFunctionParams, memberType,
paramTypeVar, locator);
}
addConstraint(ConstraintKind::ApplicableFunction, fnType, memberType,
fnLocator);
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifySubclassOfConstraint(
Type type,
Type classType,
ConstraintLocatorBuilder locator,
TypeMatchOptions flags) {
if (!classType->getClassOrBoundGenericClass())
return SolutionKind::Error;
// Dig out the fixed type to which this type refers.
type = getFixedTypeRecursive(type, flags, /*wantRValue=*/true);
if (shouldAttemptFixes() && type->isPlaceholder()) {
// If the type associated with this subclass check is a "hole" in the
// constraint system, let's consider this check a success without recording
// a fix, because it's just a consequence of the other failure, e.g.
//
// func foo<T: NSObject>(_: T) {}
// foo(Foo.bar) <- if `Foo` doesn't have `bar` there is
// no reason to complain the subclass.
return SolutionKind::Solved;
}
auto formUnsolved = [&]() {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *subclassOf = Constraint::create(
*this, ConstraintKind::SubclassOf, type, classType,
getConstraintLocator(locator));
addUnsolvedConstraint(subclassOf);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// If we hit a type variable without a fixed type, we can't
// solve this yet.
if (type->isTypeVariableOrMember())
return formUnsolved();
// SubclassOf constraints are generated when opening a generic
// signature with a RequirementKind::Superclass requirement, so
// we must handle pack types on the left by splitting up into
// smaller constraints.
if (auto *packType = type->getAs<PackType>()) {
for (unsigned i = 0, e = packType->getNumElements(); i < e; ++i) {
auto eltType = packType->getElementType(i);
if (auto *packExpansionType = eltType->getAs<PackExpansionType>()) {
auto patternLoc =
locator.withPathElement(ConstraintLocator::PackExpansionPattern);
addConstraint(ConstraintKind::SubclassOf, packExpansionType->getPatternType(),
classType, patternLoc);
} else {
addConstraint(ConstraintKind::SubclassOf, eltType,
classType, locator.withPathElement(LocatorPathElt::PackElement(i)));
}
}
return SolutionKind::Solved;
}
// A class-constrained existential like 'C & P' does not satisfy an
// AnyObject requirement, if 'P' is not self-conforming.
//
// While matchSuperclassTypes() will still match here because 'C & P'
// satisfies a Subtype constraint with 'C', 'C & P' cannot satisfy a
// superclass requirement in a generic signature, so rule that out here.
if (type->satisfiesClassConstraint()) {
// If we have an exact match of class declarations, ensure the
// generic arguments match.
if (type->getClassOrBoundGenericClass() ==
classType->getClassOrBoundGenericClass()) {
auto result = matchTypes(type, classType, ConstraintKind::Bind,
flags, locator);
if (!result.isFailure())
return SolutionKind::Solved;
// Otherwise, ensure the left hand side is a proper subclass of the
// right hand side.
} else {
auto result = matchSuperclassTypes(type, classType, flags, locator);
if (!result.isFailure())
return SolutionKind::Solved;
}
}
// Record a fix if we didn't match one of the two cases above.
if (shouldAttemptFixes()) {
if (auto *fix = fixRequirementFailure(*this, type, classType, locator)) {
if (recordFix(fix))
return SolutionKind::Error;
return SolutionKind::Solved;
}
}
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyConformsToConstraint(
Type type,
Type protocol,
ConstraintKind kind,
ConstraintLocatorBuilder locator,
TypeMatchOptions flags) {
if (auto proto = protocol->getAs<ProtocolType>()) {
return simplifyConformsToConstraint(type, proto->getDecl(), kind,
locator, flags);
}
// Dig out the fixed type to which this type refers.
type = getFixedTypeRecursive(type, flags, /*wantRValue=*/true);
return matchExistentialTypes(type, protocol, kind, flags, locator);
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyConformsToConstraint(
Type type,
ProtocolDecl *protocol,
ConstraintKind kind,
ConstraintLocatorBuilder locator,
TypeMatchOptions flags) {
const auto rawType = type;
auto *typeVar = type->getAs<TypeVariableType>();
// Dig out the fixed type to which this type refers.
type = getFixedTypeRecursive(type, flags, /*wantRValue=*/true);
if (shouldAttemptFixes() && type->isPlaceholder()) {
// If the type associated with this conformance check is a "hole" in the
// constraint system, let's consider this check a success without recording
// a fix, because it's just a consequence of the other failure, e.g.
//
// func foo<T: BinaryInteger>(_: T) {}
// foo(Foo.bar) <- if `Foo` doesn't have `bar` there is
// no reason to complain about missing conformance.
return SolutionKind::Solved;
}
auto formUnsolved = [&](bool activate = false) {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *conformance = Constraint::create(
*this, kind, type, protocol->getDeclaredInterfaceType(),
getConstraintLocator(locator));
addUnsolvedConstraint(conformance);
if (activate)
activateConstraint(conformance);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// If we hit a type variable without a fixed type, we can't
// solve this yet.
if (type->isTypeVariableOrMember())
return formUnsolved();
// ConformsTo constraints are generated when opening a generic
// signature with a RequirementKind::Conformance requirement, so
// we must handle pack types on the left by splitting up into
// smaller constraints.
if (auto *packType = type->getAs<PackType>()) {
for (unsigned i = 0, e = packType->getNumElements(); i < e; ++i) {
auto eltType = packType->getElementType(i);
if (auto *packExpansionType = eltType->getAs<PackExpansionType>()) {
auto patternLoc =
locator.withPathElement(ConstraintLocator::PackExpansionPattern);
addConstraint(ConstraintKind::ConformsTo,
packExpansionType->getPatternType(),
protocol->getDeclaredInterfaceType(),
patternLoc);
} else {
addConstraint(ConstraintKind::ConformsTo, eltType,
protocol->getDeclaredInterfaceType(),
locator.withPathElement(LocatorPathElt::PackElement(i)));
}
}
return SolutionKind::Solved;
}
// We sometimes get a pack expansion type here.
if (auto *expansionType = type->getAs<PackExpansionType>()) {
// FIXME: Locator
addConstraint(ConstraintKind::ConformsTo,
expansionType->getPatternType(),
protocol->getDeclaredInterfaceType(),
locator);
return SolutionKind::Solved;
}
auto *loc = getConstraintLocator(locator);
/// Record the given conformance as the result, adding any conditional
/// requirements if necessary.
auto recordConformance = [&](ProtocolConformanceRef conformance) {
if (isConformanceUnavailable(conformance, loc))
increaseScore(SK_Unavailable, locator);
unsigned numMissing = 0;
conformance.forEachMissingConformance([&numMissing](auto *missing) {
++numMissing;
return false;
});
if (numMissing > 0)
increaseScore(SK_MissingSynthesizableConformance, locator, numMissing);
// This conformance may be conditional, in which case we need to consider
// those requirements as constraints too.
if (conformance.isConcrete()) {
unsigned index = 0;
auto *conformanceLoc = getConstraintLocator(
loc,
LocatorPathElt::ConformanceRequirement(conformance.getConcrete()));
for (const auto &req : conformance.getConditionalRequirements()) {
addConstraint(
req, getConstraintLocator(conformanceLoc,
LocatorPathElt::ConditionalRequirement(
index++, req.getKind())));
}
}
return SolutionKind::Solved;
};
// For purposes of argument type matching, existential types don't need to
// conform -- they only need to contain the protocol, so check that
// separately.
switch (kind) {
case ConstraintKind::SelfObjectOfProtocol: {
auto conformance = TypeChecker::containsProtocol(
type, protocol, DC->getParentModule(),
/*allowMissing=*/true);
if (conformance) {
return recordConformance(conformance);
}
} break;
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo: {
// If existential type is used as a for-in sequence, let's open it
// and check whether underlying type conforms to `Sequence`.
if (type->isExistentialType()) {
if (auto elt = loc->getLastElementAs<LocatorPathElt::ContextualType>()) {
if (elt->getPurpose() == CTP_ForEachSequence) {
type = openExistentialType(type, loc).first;
}
}
}
// Check whether this type conforms to the protocol.
auto conformance = lookupConformance(type, protocol);
if (conformance) {
return recordConformance(conformance);
}
// Account for ad-hoc requirements on some distributed actor
// requirements.
if (auto witnessInfo = locator.isForWitnessGenericParameterRequirement()) {
auto *GP = witnessInfo->second;
// Conformance requirement between on `Res` and `SerializationRequirement`
// of `DistributedActorSystem.remoteCall` are not expressible at the moment
// but they are verified by Sema so it's okay to omit them here and lookup
// dynamically during IRGen.
if (auto *witness = dyn_cast<FuncDecl>(witnessInfo->first)) {
auto synthesizeConformance = [&]() {
ProtocolConformanceRef synthesized(protocol);
auto witnessLoc = getConstraintLocator(
locator.getAnchor(), LocatorPathElt::Witness(witness));
SynthesizedConformances.insert({witnessLoc, synthesized});
return recordConformance(synthesized);
};
if (witness->isGeneric()) {
// `DistributedActorSystem.remoteCall`
if (witness->isDistributedActorSystemRemoteCall(/*isVoidReturn=*/false)) {
if (GP->isEqual(cast<FuncDecl>(witness)->getResultInterfaceType()))
return synthesizeConformance();
}
// `DistributedTargetInvocationEncoder.record{Argument, ResultType}`
// `DistributedTargetInvocationDecoder.decodeNextArgument`
// `DistributedTargetInvocationResultHandler.onReturn`
if (witness->isDistributedTargetInvocationEncoderRecordArgument() ||
witness->isDistributedTargetInvocationEncoderRecordReturnType() ||
witness
->isDistributedTargetInvocationDecoderDecodeNextArgument() ||
witness->isDistributedTargetInvocationResultHandlerOnReturn()) {
auto genericParams = witness->getGenericParams()->getParams();
if (GP->isEqual(genericParams.front()->getDeclaredInterfaceType()))
return synthesizeConformance();
}
}
}
}
} break;
default:
llvm_unreachable("bad constraint kind");
}
if (!shouldAttemptFixes())
return SolutionKind::Error;
auto protocolTy = protocol->getDeclaredInterfaceType();
// If this conformance has been fixed already, let's just consider this done.
if (isFixedRequirement(loc, protocolTy))
return SolutionKind::Solved;
// If this is a generic requirement let's try to record that
// conformance is missing and consider this a success, which
// makes it much easier to diagnose problems like that.
{
SmallVector<LocatorPathElt, 4> path;
auto anchor = locator.getLocatorParts(path);
// If this is a `nil` literal, it would be a contextual failure.
if (auto *Nil = getAsExpr<NilLiteralExpr>(anchor)) {
auto *fixLocator = getConstraintLocator(
getContextualType(Nil, /*forConstraint=*/false)
? locator.withPathElement(LocatorPathElt::ContextualType(
getContextualTypePurpose(Nil)))
: locator);
// Only requirement placed directly on `nil` literal is
// `ExpressibleByNilLiteral`, so if `nil` is an argument
// to an application, let's update locator accordingly to
// diagnose possible ambiguities with multiple mismatched
// overload choices.
if (fixLocator->directlyAt<NilLiteralExpr>()) {
if (auto *loc = getArgumentLocator(castToExpr(fixLocator->getAnchor())))
fixLocator = loc;
}
// Here the roles are reversed - `nil` is something we are trying to
// convert to `type` by making sure that it conforms to a specific
// protocol.
auto *fix =
ContextualMismatch::create(*this, protocolTy, type, fixLocator);
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
// If there is a missing conformance between source and destination
// of the assignment, let's ignore current the types and instead use
// source/destination types directly to make it possible to diagnose
// protocol compositions.
if (auto *assignment = getAsExpr<AssignExpr>(anchor)) {
// If the locator's last element points to the function result,
// let's check whether there is a problem with function argument
// as well, and if so, avoid producing a fix here, because
// contextual mismatch mentions the source/destination
// types of the assignment.
if (locator.endsWith<LocatorPathElt::FunctionResult>() &&
hasFixFor(
getConstraintLocator(anchor, LocatorPathElt::FunctionArgument())))
return SolutionKind::Solved;
auto srcType = getType(assignment->getSrc());
auto dstType = getType(assignment->getDest());
auto *fix = IgnoreAssignmentDestinationType::create(
*this, srcType, dstType, loc);
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
if (path.empty())
return SolutionKind::Error;
// If this is a conformance failure related to a contextual type
// let's record it as a "contextual mismatch" because diagnostic
// is going to be dependent on other contextual information.
if (path.back().is<LocatorPathElt::ContextualType>()) {
auto *fix = ContextualMismatch::create(*this, type, protocolTy, loc);
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
// If we have something like ... -> type req # -> pack element #, we're
// solving a requirement of the form T : P where T is a type parameter pack
if (path.back().is<LocatorPathElt::PackElement>())
path.pop_back();
// This is similar to `PackElement` but locator points to the requirement
// associted with pack expansion pattern (i.e. `repeat each T: P`) where
// the path is something like:
// `... -> type req # -> pack expansion pattern`.
if (path.back().is<LocatorPathElt::PackExpansionPattern>())
path.pop_back();
if (auto req = path.back().getAs<LocatorPathElt::AnyRequirement>()) {
// If this is a requirement associated with `Self` which is bound
// to `Any`, let's consider this "too incorrect" to continue.
//
// This helps us to filter out cases like operator overloads where
// `Self` type comes from e.g. default for collection element -
// `[1, "hello"].map { $0 + 1 }`. Main problem here is that
// collection type couldn't be determined without unification to
// `Any` and `+` failing for all numeric overloads is just a consequence.
if (typeVar && type->isAny()) {
if (auto *GP = typeVar->getImpl().getGenericParameter()) {
if (auto *GPD = GP->getDecl()) {
auto *DC = GPD->getDeclContext();
if (DC->isTypeContext() && DC->getSelfInterfaceType()->isEqual(GP))
return SolutionKind::Error;
}
}
}
if (auto rawValue = isRawRepresentable(*this, type)) {
if (!rawValue->isTypeVariableOrMember() &&
lookupConformance(rawValue, protocol)) {
auto *fix = UseRawValue::create(*this, type, protocolTy, loc);
// Since this is a conformance requirement failure (where the
// source is most likely an argument), let's increase its impact
// to disambiguate vs. conversion failure of the same kind.
return recordFix(fix, /*impact=*/2) ? SolutionKind::Error
: SolutionKind::Solved;
}
}
auto anchor = locator.getAnchor();
if (isExpr<UnresolvedMemberExpr>(anchor) &&
req->is<LocatorPathElt::TypeParameterRequirement>()) {
auto signature = path[path.size() - 2]
.castTo<LocatorPathElt::OpenedGeneric>()
.getSignature();
auto requirement = signature.getRequirements()[req->getIndex()];
auto *memberLoc = getConstraintLocator(anchor, path.front());
auto overload = findSelectedOverloadFor(memberLoc);
// To figure out what is going on here we need to wait until
// member overload is set in the constraint system.
if (!overload) {
// If it's not allowed to generate new constraints
// there is no way to control re-activation, so this
// check has to fail.
if (!flags.contains(TMF_GenerateConstraints))
return SolutionKind::Error;
return formUnsolved(/*activate=*/true);
}
auto *memberRef = overload->choice.getDeclOrNull();
if (!memberRef)
return SolutionKind::Error;
// If this is a `Self` conformance requirement from a static member
// reference on a protocol metatype, let's produce a tailored diagnostic.
if (memberRef->isStatic()) {
if (hasFixFor(memberLoc,
FixKind::AllowInvalidStaticMemberRefOnProtocolMetatype))
return SolutionKind::Solved;
if (auto *protocolDecl =
memberRef->getDeclContext()->getSelfProtocolDecl()) {
auto selfTy = protocolDecl->getSelfInterfaceType();
if (selfTy->isEqual(requirement.getFirstType())) {
auto *fix = AllowInvalidStaticMemberRefOnProtocolMetatype::create(
*this, memberLoc);
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
}
}
}
if (auto *fix =
fixRequirementFailure(*this, type, protocolTy, anchor, path)) {
auto impact = assessRequirementFailureImpact(*this, rawType, locator);
if (!recordFix(fix, impact)) {
// Record this conformance requirement as "fixed".
recordFixedRequirement(getConstraintLocator(anchor, path),
protocolTy);
return SolutionKind::Solved;
}
}
}
if (loc->isLastElement<LocatorPathElt::MemberRefBase>()) {
auto *fix = ContextualMismatch::create(*this, protocolTy, type, loc);
if (!recordFix(fix))
return SolutionKind::Solved;
}
// Conformance constraint that is introduced by an implicit conversion
// for example to `AnyHashable`.
if (kind == ConstraintKind::ConformsTo &&
loc->isLastElement<LocatorPathElt::ApplyArgToParam>()) {
auto *fix = AllowArgumentMismatch::create(*this, type, protocolTy, loc);
return recordFix(fix, /*impact=*/2) ? SolutionKind::Error
: SolutionKind::Solved;
}
// If this is an implicit Hashable conformance check generated for each
// index argument of the keypath subscript component, we could just treat
// it as though it conforms.
if (loc->isResultOfKeyPathDynamicMemberLookup() ||
loc->isKeyPathSubscriptComponent()) {
if (protocol ==
getASTContext().getProtocol(KnownProtocolKind::Hashable)) {
auto *fix =
TreatKeyPathSubscriptIndexAsHashable::create(*this, type, loc);
if (!recordFix(fix))
return SolutionKind::Solved;
}
}
}
// There's nothing more we can do; fail.
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyTransitivelyConformsTo(
Type type, Type protocolTy, ConstraintLocatorBuilder locator,
TypeMatchOptions flags) {
auto &ctx = getASTContext();
// Since this is a performance optimization, let's ignore it
// in diagnostic mode.
if (shouldAttemptFixes())
return SolutionKind::Solved;
auto formUnsolved = [&]() {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *conformance =
Constraint::create(*this, ConstraintKind::TransitivelyConformsTo,
type, protocolTy, getConstraintLocator(locator));
addUnsolvedConstraint(conformance);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
auto resolvedTy = getFixedTypeRecursive(type, /*wantRValue=*/true);
if (resolvedTy->isTypeVariableOrMember())
return formUnsolved();
// If the composition consists of a class + protocol,
// we can't check conformance of the argument because
// parameter could pick one of the components.
if (resolvedTy.findIf(
[](Type type) { return type->is<ProtocolCompositionType>(); }))
return SolutionKind::Solved;
// All bets are off for pointers, there are multiple combinations
// to check and it doesn't see worth to do that upfront.
{
PointerTypeKind pointerKind;
if (resolvedTy->getAnyPointerElementType(pointerKind))
return SolutionKind::Solved;
}
auto *protocol = protocolTy->castTo<ProtocolType>()->getDecl();
// First, let's check whether the type itself conforms,
// if it does - we are done.
if (lookupConformance(resolvedTy, protocol))
return SolutionKind::Solved;
// If the type doesn't conform, let's check whether
// an Optional or Unsafe{Mutable}Pointer from it would.
// If the current score is equal to the best score, fail without checking
// implicit conversions, because an implicit conversion would lead to a
// worse score anyway.
if (solverState && solverState->BestScore && CurrentScore == *solverState->BestScore)
return SolutionKind::Error;
SmallVector<Type, 4> typesToCheck;
// T -> Optional<T>
if (!resolvedTy->getOptionalObjectType())
typesToCheck.push_back(OptionalType::get(resolvedTy));
// AnyHashable
if (auto *anyHashable = ctx.getAnyHashableDecl())
typesToCheck.push_back(anyHashable->getDeclaredInterfaceType());
// Rest of the implicit conversions depend on the resolved type.
{
auto getPointerFor = [&ctx](PointerTypeKind ptrKind,
std::optional<Type> elementTy =
std::nullopt) -> Type {
switch (ptrKind) {
case PTK_UnsafePointer:
assert(elementTy);
return BoundGenericType::get(ctx.getUnsafePointerDecl(),
/*parent=*/Type(), {*elementTy});
case PTK_UnsafeMutablePointer:
assert(elementTy);
return BoundGenericType::get(ctx.getUnsafeMutablePointerDecl(),
/*parent=*/Type(), {*elementTy});
case PTK_UnsafeRawPointer:
return ctx.getUnsafeRawPointerDecl()->getDeclaredInterfaceType();
case PTK_UnsafeMutableRawPointer:
return ctx.getUnsafeMutableRawPointerDecl()->getDeclaredInterfaceType();
case PTK_AutoreleasingUnsafeMutablePointer:
llvm_unreachable("no implicit conversion");
}
};
// String -> UnsafePointer<Void>
if (auto *string = ctx.getStringDecl()) {
if (resolvedTy->isEqual(string->getDeclaredInterfaceType())) {
typesToCheck.push_back(
getPointerFor(PTK_UnsafePointer, ctx.TheEmptyTupleType));
}
}
// Array<T> -> Unsafe{Raw}Pointer<T>
if (auto elt = resolvedTy->isArrayType()) {
typesToCheck.push_back(getPointerFor(PTK_UnsafePointer, elt));
typesToCheck.push_back(getPointerFor(PTK_UnsafeRawPointer, elt));
}
// inout argument -> UnsafePointer<T>, UnsafeMutablePointer<T>,
// UnsafeRawPointer, UnsafeMutableRawPointer.
if (type->is<InOutType>()) {
typesToCheck.push_back(getPointerFor(PTK_UnsafePointer, resolvedTy));
typesToCheck.push_back(getPointerFor(PTK_UnsafeMutablePointer, resolvedTy));
typesToCheck.push_back(getPointerFor(PTK_UnsafeRawPointer));
typesToCheck.push_back(getPointerFor(PTK_UnsafeMutableRawPointer));
}
}
return llvm::any_of(
typesToCheck,
[&](Type type) { return bool(lookupConformance(type, protocol)); })
? SolutionKind::Solved
: SolutionKind::Error;
}
/// Determine the kind of checked cast to perform from the given type to
/// the given type.
///
/// This routine does not attempt to check whether the cast can actually
/// succeed; that's the caller's responsibility.
static CheckedCastKind getCheckedCastKind(ConstraintSystem *cs,
Type fromType,
Type toType) {
// Array downcasts are handled specially.
if (fromType->isArrayType() && toType->isArrayType()) {
return CheckedCastKind::ArrayDowncast;
}
// Dictionary downcasts are handled specially.
if (cs->isDictionaryType(fromType) && cs->isDictionaryType(toType)) {
return CheckedCastKind::DictionaryDowncast;
}
// Set downcasts are handled specially.
if (cs->isSetType(fromType) && cs->isSetType(toType)) {
return CheckedCastKind::SetDowncast;
}
return CheckedCastKind::ValueCast;
}
// Optional types always conform to `ExpressibleByNilLiteral`.
static bool isCastToExpressibleByNilLiteral(ConstraintSystem &cs, Type fromType,
Type toType) {
auto &ctx = cs.getASTContext();
auto *nilLiteral = ctx.getProtocol(KnownProtocolKind::ExpressibleByNilLiteral);
if (!nilLiteral)
return false;
return toType->isEqual(nilLiteral->getDeclaredExistentialType()) &&
fromType->getOptionalObjectType();
}
static ConstraintFix *maybeWarnAboutExtraneousCast(
ConstraintSystem &cs, Type origFromType, Type origToType, Type fromType,
Type toType, SmallVector<Type, 4> fromOptionals,
SmallVector<Type, 4> toOptionals,
ConstraintSystem::TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
if (locator.endsWith<LocatorPathElt::GenericArgument>())
return nullptr;
// Both types have to be fixed.
if (fromType->hasTypeVariable() || toType->hasTypeVariable() ||
fromType->hasPlaceholder() || toType->hasPlaceholder())
return nullptr;
SmallVector<LocatorPathElt, 4> path;
auto anchor = locator.getLocatorParts(path);
auto *castExpr = getAsExpr<ExplicitCastExpr>(anchor);
if (!castExpr)
return nullptr;
// "from" could be less optional than "to" e.g. `0 as Any?`, so
// we need to store the difference as a signed integer.
int extraOptionals = fromOptionals.size() - toOptionals.size();
// "from" expression could be a type variable wrapped in an optional e.g.
// Optional<$T0>. So when that is the case we have to add this additional
// optionality levels to from type.
const auto subExprType = cs.getType(castExpr->getSubExpr());
if (subExprType->getOptionalObjectType()) {
SmallVector<Type, 4> subExprOptionals;
const auto unwrappedSubExprType =
subExprType->lookThroughAllOptionalTypes(subExprOptionals);
if (unwrappedSubExprType->is<TypeVariableType>()) {
extraOptionals += subExprOptionals.size();
for (size_t i = 0; i != subExprOptionals.size(); ++i) {
origFromType = OptionalType::get(origFromType);
}
}
}
// Removing the optionality from to type when the force cast expr is an IUO.
const auto *const TR = castExpr->getCastTypeRepr();
if (isExpr<ForcedCheckedCastExpr>(anchor) && TR &&
TR->getKind() == TypeReprKind::ImplicitlyUnwrappedOptional) {
extraOptionals++;
}
// In cases of 'try?' where origFromType isn't optional that meaning
// sub-expression isn't optional, always adds one level of optionality
// because the result of the expression is always an optional type
// regardless of language mode.
auto *sub = castExpr->getSubExpr()->getSemanticsProvidingExpr();
if (isExpr<OptionalTryExpr>(sub) && !origFromType->getOptionalObjectType()) {
origFromType = OptionalType::get(fromType);
extraOptionals++;
}
// Except for forced cast expressions, if optionals are more than a single
// level difference or there is a single level between the types but an extra
// level of optional is added to subexpr via OptionalEvaluationExpr, we don't
// need to record any fix.
if (!isExpr<ForcedCheckedCastExpr>(anchor) &&
(extraOptionals > 1 ||
isExpr<OptionalEvaluationExpr>(castExpr->getSubExpr())))
return nullptr;
// Always succeed
if (isCastToExpressibleByNilLiteral(cs, origFromType, toType)) {
return AllowNoopCheckedCast::create(cs, fromType, toType,
CheckedCastKind::Coercion,
cs.getConstraintLocator(locator));
}
// If both original are metatypes we have to use them because most of the
// logic on how correctly handle metatypes casting is on
// typeCheckCheckedCast.
if (origFromType->is<AnyMetatypeType>() &&
origToType->is<AnyMetatypeType>()) {
fromType = origFromType;
toType = origToType;
}
auto castKind = TypeChecker::typeCheckCheckedCast(
fromType, toType, CheckedCastContextKind::None, cs.DC);
if (castKind == CheckedCastKind::Unresolved) {
return AllowCheckedCastToUnrelated::attempt(
cs, origFromType, origToType, castKind,
cs.getConstraintLocator(locator));
}
if (castKind == CheckedCastKind::ValueCast) {
// https://github.com/apple/swift/issues/44221
// Special 'is' case diagnostics for CFTypes.
return AllowNoopExistentialToCFTypeCheckedCast::attempt(
cs, origFromType, origToType, castKind,
cs.getConstraintLocator(locator));
}
if (!(castKind == CheckedCastKind::Coercion ||
castKind == CheckedCastKind::BridgingCoercion))
return nullptr;
if (auto *fix = AllowUnsupportedRuntimeCheckedCast::attempt(
cs, fromType, toType, castKind, cs.getConstraintLocator(locator))) {
return fix;
}
if (extraOptionals > 0) {
// Conditional cast in this case can be an attempt to just unwrap a nil
// value.
if (isExpr<ConditionalCheckedCastExpr>(anchor) &&
castKind == CheckedCastKind::BridgingCoercion) {
return nullptr;
}
return AllowCheckedCastCoercibleOptionalType::create(
cs, origFromType, origToType, castKind,
cs.getConstraintLocator(locator));
} else {
// No optionals, just a trivial cast that always succeeds.
return AllowNoopCheckedCast::create(cs, origFromType, origToType, castKind,
cs.getConstraintLocator(locator));
}
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyCheckedCastConstraint(
Type fromType, Type toType,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
/// Form an unresolved result.
auto formUnsolved = [&] {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::CheckedCast, fromType,
toType, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
Type origFromType =
getFixedTypeRecursive(fromType, flags, /*wantRValue=*/true);
Type origToType = getFixedTypeRecursive(toType, flags, /*wantRValue=*/true);
SmallVector<Type, 4> fromOptionals;
SmallVector<Type, 4> toOptionals;
do {
// Dig out the fixed type this type refers to.
fromType = getFixedTypeRecursive(fromType, flags, /*wantRValue=*/true);
// If we hit a type variable without a fixed type, we can't
// solve this yet.
if (fromType->isTypeVariableOrMember())
return formUnsolved();
// Dig out the fixed type this type refers to.
toType = getFixedTypeRecursive(toType, flags, /*wantRValue=*/true);
// If we hit a type variable without a fixed type, we can't
// solve this yet.
if (toType->isTypeVariableOrMember())
return formUnsolved();
Type origFromType = fromType;
Type origToType = toType;
// Peel off optionals metatypes from the types, because we might cast through
// them.
toType = toType->lookThroughAllOptionalTypes(toOptionals);
fromType = fromType->lookThroughAllOptionalTypes(fromOptionals);
// Peel off metatypes, since if we can cast two types, we can cast their
// metatypes.
while (auto toMetatype = toType->getAs<MetatypeType>()) {
auto fromMetatype = fromType->getAs<MetatypeType>();
if (!fromMetatype)
break;
toType = toMetatype->getInstanceType();
fromType = fromMetatype->getInstanceType();
}
// Peel off a potential layer of existential<->concrete metatype conversion.
if (auto toMetatype = toType->getAs<AnyMetatypeType>()) {
if (auto fromMetatype = fromType->getAs<MetatypeType>()) {
toType = toMetatype->getInstanceType();
fromType = fromMetatype->getInstanceType();
}
}
// Peel off marker protocol requirements if this is an existential->concrete
// cast. Handles cases like `WritableKeyPath<...> & Sendable as KeyPath`
// that require inference which is only attempted if both sides are classes.
if (fromType->isExistentialType() && !toType->isExistentialType()) {
if (auto *existential = fromType->getAs<ExistentialType>()) {
if (auto *PCT = existential->getConstraintType()
->getAs<ProtocolCompositionType>()) {
auto newConstraintTy = PCT->withoutMarkerProtocols();
if (!newConstraintTy->isEqual(PCT)) {
fromType = newConstraintTy->getClassOrBoundGenericClass()
? newConstraintTy
: ExistentialType::get(newConstraintTy);
}
}
}
}
// We've decomposed the types further, so adopt the subflags.
flags = subflags;
// If nothing changed, we're done.
if (fromType.getPointer() == origFromType.getPointer() &&
toType.getPointer() == origToType.getPointer())
break;
} while (true);
auto attemptRecordCastFixIfSolved = [&](SolutionKind result) {
if (result != SolutionKind::Solved)
return;
if (auto *fix = maybeWarnAboutExtraneousCast(
*this, origFromType, origToType, fromType, toType, fromOptionals,
toOptionals, flags, locator)) {
(void)recordFix(fix);
}
};
auto kind = getCheckedCastKind(this, fromType, toType);
switch (kind) {
case CheckedCastKind::ArrayDowncast: {
auto fromBaseType = fromType->isArrayType();
auto toBaseType = toType->isArrayType();
auto elementLocator =
locator.withPathElement(LocatorPathElt::GenericArgument(0));
auto result = simplifyCheckedCastConstraint(fromBaseType, toBaseType,
subflags, elementLocator);
attemptRecordCastFixIfSolved(result);
return result;
}
case CheckedCastKind::DictionaryDowncast: {
Type fromKeyType, fromValueType;
std::tie(fromKeyType, fromValueType) = *isDictionaryType(fromType);
Type toKeyType, toValueType;
std::tie(toKeyType, toValueType) = *isDictionaryType(toType);
auto keyLocator =
locator.withPathElement(LocatorPathElt::GenericArgument(0));
if (simplifyCheckedCastConstraint(fromKeyType, toKeyType, subflags,
keyLocator) == SolutionKind::Error)
return SolutionKind::Error;
auto valueLocator =
locator.withPathElement(LocatorPathElt::GenericArgument(1));
auto result = simplifyCheckedCastConstraint(fromValueType, toValueType,
subflags, valueLocator);
attemptRecordCastFixIfSolved(result);
return result;
}
case CheckedCastKind::SetDowncast: {
auto fromBaseType = *isSetType(fromType);
auto toBaseType = *isSetType(toType);
auto elementLocator =
locator.withPathElement(LocatorPathElt::GenericArgument(0));
auto result = simplifyCheckedCastConstraint(fromBaseType, toBaseType,
subflags, elementLocator);
attemptRecordCastFixIfSolved(result);
return result;
}
case CheckedCastKind::ValueCast: {
// If casting among classes, and there are open
// type variables remaining, introduce a subtype constraint to help resolve
// them.
if (fromType->getClassOrBoundGenericClass()
&& toType->getClassOrBoundGenericClass()
&& (fromType->hasTypeVariable() || toType->hasTypeVariable())) {
addConstraint(ConstraintKind::Subtype, toType, fromType,
getConstraintLocator(locator));
}
// Attempts to record warning fixes when both types are known by the
// compiler and we can infer that the runtime checked cast will always
// succeed or fail.
if (auto *fix = maybeWarnAboutExtraneousCast(
*this, origFromType, origToType, fromType, toType, fromOptionals,
toOptionals, flags, locator)) {
(void)recordFix(fix);
}
return SolutionKind::Solved;
}
case CheckedCastKind::Coercion:
case CheckedCastKind::BridgingCoercion:
case CheckedCastKind::Unresolved:
llvm_unreachable("Not a valid result");
}
llvm_unreachable("Unhandled CheckedCastKind in switch.");
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyOptionalObjectConstraint(
Type first, Type second,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// Resolve the optional type.
Type optLValueTy = getFixedTypeRecursive(first, flags, /*wantRValue=*/false);
Type optTy = optLValueTy->getRValueType();
if (optTy.getPointer() != optLValueTy.getPointer())
optTy = getFixedTypeRecursive(optTy, /*wantRValue=*/false);
if (optTy->isTypeVariableOrMember()) {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::OptionalObject, optLValueTy,
second, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
if (optTy->isPlaceholder()) {
if (auto *typeVar = second->getAs<TypeVariableType>())
recordPotentialHole(typeVar);
return SolutionKind::Solved;
}
Type objectTy = optTy->getOptionalObjectType();
// If the base type is not optional, let's attempt a fix (if possible)
// and assume that `!` is just not there.
if (!objectTy) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
// Let's see if we can apply a specific fix here.
if (optTy->isPlaceholder())
return SolutionKind::Solved;
auto fnType = optTy->getAs<FunctionType>();
if (fnType && fnType->getNumParams() == 0) {
// For function types with no parameters, let's try to
// offer a "make it a call" fix if possible.
auto optionalResultType = fnType->getResult()->getOptionalObjectType();
if (optionalResultType) {
if (matchTypes(optionalResultType, second, ConstraintKind::Bind,
flags | TMF_ApplyingFix, locator)
.isSuccess()) {
auto *fix =
InsertExplicitCall::create(*this, getConstraintLocator(locator));
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
}
}
auto *fix =
RemoveUnwrap::create(*this, optTy, getConstraintLocator(locator));
if (recordFix(fix))
return SolutionKind::Error;
// If the fix was successful let's record
// "fixed" object type and continue.
objectTy = optTy;
}
// The object type is an lvalue if the optional was.
if (optLValueTy->is<LValueType>())
objectTy = LValueType::get(objectTy);
// Equate it to the other type in the constraint.
addConstraint(ConstraintKind::Bind, objectTy, second, locator);
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyBindTupleOfFunctionParamsConstraint(
Type first, Type second, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto simplified = simplifyType(first);
auto simplifiedCopy = simplified;
unsigned unwrapCount = 0;
if (shouldAttemptFixes()) {
while (auto objectTy = simplified->getOptionalObjectType()) {
simplified = objectTy;
// Track how many times we do this so that we can record a fix for each.
++unwrapCount;
}
if (simplified->isPlaceholder()) {
if (auto *typeVar = second->getAs<TypeVariableType>())
recordPotentialHole(typeVar);
return SolutionKind::Solved;
}
}
if (simplified->isTypeVariableOrMember()) {
if (!flags.contains(TMF_GenerateConstraints))
return SolutionKind::Unsolved;
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::BindTupleOfFunctionParams,
simplified, second, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
auto *funcTy = simplified->getAs<FunctionType>();
if (!funcTy)
return SolutionKind::Error;
auto tupleTy =
AnyFunctionType::composeTuple(getASTContext(), funcTy->getParams(),
ParameterFlagHandling::IgnoreNonEmpty);
addConstraint(ConstraintKind::Bind, tupleTy, second,
locator.withPathElement(ConstraintLocator::FunctionArgument));
if (unwrapCount > 0) {
auto *fix = ForceOptional::create(*this, simplifiedCopy, second,
getConstraintLocator(locator));
if (recordFix(fix, /*impact=*/unwrapCount))
return SolutionKind::Error;
}
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyPackElementOfConstraint(Type first, Type second,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto elementType = simplifyType(first, flags);
auto patternType = simplifyType(second, flags);
auto formUnsolved = [&]() {
if (!flags.contains(TMF_GenerateConstraints))
return SolutionKind::Unsolved;
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::PackElementOf, first, second,
getConstraintLocator(locator)));
return SolutionKind::Solved;
};
// If neither side is fully resolved yet, there is nothing we can do.
if (elementType->hasTypeVariable() && patternType->hasTypeVariable())
return formUnsolved();
if (shouldAttemptFixes()) {
if (elementType->isPlaceholder() || patternType->isPlaceholder())
return SolutionKind::Solved;
}
if (isSingleUnlabeledPackExpansionTuple(patternType)) {
auto *packVar = addMaterializePackExpansionConstraint(patternType, locator);
addConstraint(ConstraintKind::PackElementOf, elementType, packVar, locator);
return SolutionKind::Solved;
}
// Let's try to resolve element type based on the pattern type.
if (!patternType->hasTypeVariable()) {
auto *loc = getConstraintLocator(locator);
auto shapeClass = patternType->getReducedShape();
auto *elementEnv = getPackElementEnvironment(loc, shapeClass);
// Without an opened element environment, we cannot derive the
// element binding.
if (!elementEnv) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
// `each` was applied to a concrete type.
if (!shapeClass->is<PackArchetypeType>()) {
if (recordFix(AllowInvalidPackElement::create(*this, patternType, loc)))
return SolutionKind::Error;
} else {
auto envShape = PackExpansionEnvironments.find(loc);
if (envShape == PackExpansionEnvironments.end()) {
return SolutionKind::Error;
}
auto *fix = SkipSameShapeRequirement::create(
*this, envShape->second.second, shapeClass,
getConstraintLocator(loc, ConstraintLocator::PackShape));
if (recordFix(fix)) {
return SolutionKind::Error;
}
}
recordAnyTypeVarAsPotentialHole(elementType);
return SolutionKind::Solved;
}
auto expectedElementTy =
elementEnv->mapContextualPackTypeIntoElementContext(patternType);
assert(!expectedElementTy->is<PackType>());
addConstraint(ConstraintKind::Equal, elementType, expectedElementTy,
locator);
return SolutionKind::Solved;
}
// Otherwise we are inferred or checking pattern type.
auto *packEnv = DC->getGenericEnvironmentOfContext();
// Map element archetypes to the pack context to check for equality.
if (elementType->hasElementArchetype())
elementType = packEnv->mapElementTypeIntoPackContext(elementType);
addConstraint(ConstraintKind::Equal, elementType, patternType, locator);
return SolutionKind::Solved;
}
static bool isForKeyPathSubscript(ConstraintSystem &cs,
ConstraintLocator *locator) {
if (!locator || !locator->getAnchor())
return false;
if (auto *SE = getAsExpr<SubscriptExpr>(locator->getAnchor())) {
return SE->getArgs()->isUnary() &&
SE->getArgs()->getLabel(0) == cs.getASTContext().Id_keyPath;
}
return false;
}
static bool mayBeForKeyPathSubscriptWithoutLabel(ConstraintSystem &cs,
ConstraintLocator *locator) {
if (!locator || !locator->getAnchor())
return false;
if (auto *SE = getAsExpr<SubscriptExpr>(locator->getAnchor())) {
if (auto *unary = SE->getArgs()->getUnlabeledUnaryExpr())
return isa<KeyPathExpr>(unary) || isa<CodeCompletionExpr>(unary);
}
return false;
}
/// Determine whether all of the given candidate overloads
/// found through conditional conformances of a given base type.
/// This is useful to figure out whether it makes sense to
/// perform dynamic member lookup or not.
static bool
allFromConditionalConformances(ConstraintSystem &cs, Type baseTy,
ArrayRef<OverloadChoice> candidates) {
auto *NTD = baseTy->getAnyNominal();
if (!NTD)
return false;
return llvm::all_of(candidates, [&](const OverloadChoice &choice) {
auto *decl = choice.getDeclOrNull();
if (!decl)
return false;
auto *candidateDC = decl->getDeclContext();
if (auto *extension = dyn_cast<ExtensionDecl>(candidateDC)) {
if (extension->isConstrainedExtension())
return true;
}
if (auto *protocol = candidateDC->getSelfProtocolDecl()) {
auto conformance = cs.lookupConformance(baseTy, protocol);
if (!conformance.isConcrete())
return false;
return !conformance.getConcrete()->getConditionalRequirements().empty();
}
return false;
});
}
// Check whether given key path dynamic member lookup is self-recursive,
// which happens when root type of the key path is the same as base type
// of the member and lookup is attempted on non-existing property e.g.
//
// @dynamicMemberLookup
// struct Recurse<T> {
// subscript<U>(dynamicMember member: KeyPath<Recurse<T>, U>) -> Int {
// return 1
// }
// }
//
// If we going to lookup any no-existent property or member on `Recursive`
// using key path dynamic member lookup it would attempt to lookup such
// member on root type which is also `Recursive` which leads to an infinite
// recursion.
static bool isSelfRecursiveKeyPathDynamicMemberLookup(
ConstraintSystem &cs, Type keyPathRootTy, ConstraintLocator *locator) {
// Let's check whether this is a recursive call to keypath
// dynamic member lookup on the same type.
if (!locator ||
!locator->isLastElement<LocatorPathElt::KeyPathDynamicMember>())
return false;
auto path = locator->getPath();
auto *choiceLoc =
cs.getConstraintLocator(locator->getAnchor(), path.drop_back());
if (auto overload = cs.findSelectedOverloadFor(choiceLoc)) {
auto baseTy = overload->choice.getBaseType();
// If it's `Foo<Int>` vs. `Foo<String>` it doesn't really matter
// for dynamic lookup because it's going to be performed on `Foo`.
if (baseTy->is<BoundGenericType>() &&
keyPathRootTy->is<BoundGenericType>()) {
auto *baseDecl = baseTy->castTo<BoundGenericType>()->getDecl();
auto *keyPathRootDecl =
keyPathRootTy->castTo<BoundGenericType>()->getDecl();
return baseDecl == keyPathRootDecl;
}
// Previous base type could be r-value because that could be
// a base type of subscript "as written" for which we attempt
// a dynamic member lookup.
auto baseTy1 = baseTy->getRValueType();
// Root type of key path is always wrapped in an l-value
// before lookup is performed, so we need to unwrap that.
auto baseTy2 = keyPathRootTy->getRValueType();
if (baseTy1->isEqual(baseTy2))
return true;
}
return false;
}
/// Given a ValueMember, UnresolvedValueMember, or TypeMember constraint,
/// perform a lookup into the specified base type to find a candidate list.
/// The list returned includes the viable candidates as well as the unviable
/// ones (along with reasons why they aren't viable).
///
/// If includeInaccessibleMembers is set to true, this burns compile time to
/// try to identify and classify inaccessible members that may be being
/// referenced.
MemberLookupResult ConstraintSystem::
performMemberLookup(ConstraintKind constraintKind, DeclNameRef memberName,
Type baseTy, FunctionRefKind functionRefKind,
ConstraintLocator *memberLocator,
bool includeInaccessibleMembers) {
Type baseObjTy = baseTy->getRValueType();
Type instanceTy = baseObjTy;
auto &ctx = getASTContext();
auto memberNode = simplifyLocatorToAnchor(memberLocator);
auto memberLoc = memberNode ? memberNode.getStartLoc() : SourceLoc();
if (auto baseObjMeta = baseObjTy->getAs<AnyMetatypeType>()) {
instanceTy = baseObjMeta->getInstanceType();
}
MemberLookupResult result;
if (instanceTy->isTypeVariableOrMember() ||
instanceTy->is<UnresolvedType>()) {
result.OverallResult = MemberLookupResult::Unsolved;
return result;
}
// Delay member lookup until single-element tuple with pack expansion
// is sufficiently resolved.
if (isSingleUnlabeledPackExpansionTuple(instanceTy)) {
auto elementTy = instanceTy->castTo<TupleType>()->getElementType(0);
if (elementTy->is<TypeVariableType>()) {
result.OverallResult = MemberLookupResult::Unsolved;
return result;
}
}
// Okay, start building up the result list.
result.OverallResult = MemberLookupResult::HasResults;
// Add key path result.
// If we are including inaccessible members, check for the use of a keypath
// subscript without a `keyPath:` label. Add it to the result so that it
// can be caught by the missing argument label checking later.
if (isForKeyPathSubscript(*this, memberLocator) ||
(mayBeForKeyPathSubscriptWithoutLabel(*this, memberLocator) &&
includeInaccessibleMembers)) {
if (baseTy->isAnyObject()) {
result.addUnviable(
OverloadChoice(baseTy, OverloadChoiceKind::KeyPathApplication),
MemberLookupResult::UR_KeyPathWithAnyObjectRootType);
} else {
result.ViableCandidates.push_back(
OverloadChoice(baseTy, OverloadChoiceKind::KeyPathApplication));
}
}
// If the base type is a tuple type, look for the named or indexed member
// of the tuple.
if (auto baseTuple = baseObjTy->getAs<TupleType>()) {
if (!memberName.isSpecial()) {
StringRef nameStr = memberName.getBaseIdentifier().str();
// Accessing `.element` on an abstract tuple materializes a pack.
// (deprecated behavior)
if (nameStr == "element" && baseTuple->getNumElements() == 1 &&
isPackExpansionType(baseTuple->getElementType(0))) {
auto elementType = baseTuple->getElementType(0);
if (elementType->is<PackExpansionType>()) {
result.ViableCandidates.push_back(
OverloadChoice(baseTy, OverloadChoiceKind::MaterializePack));
} else {
assert(elementType->is<TypeVariableType>());
result.OverallResult = MemberLookupResult::Unsolved;
}
return result;
}
int fieldIdx = -1;
// Resolve a number reference into the tuple type.
unsigned Value = 0;
if (!nameStr.getAsInteger(10, Value) &&
Value < baseTuple->getNumElements()) {
fieldIdx = Value;
} else {
fieldIdx = baseTuple->getNamedElementId(memberName.getBaseIdentifier());
}
if (fieldIdx != -1) {
// Add an overload set that selects this field.
result.ViableCandidates.push_back(OverloadChoice(baseTy, fieldIdx));
return result;
}
}
}
if (auto *selfTy = instanceTy->getAs<DynamicSelfType>())
instanceTy = selfTy->getSelfType();
// Dynamically isolated function types have a magic '.isolation'
// member that extracts the isolation value.
if (auto *fn = instanceTy->getAs<FunctionType>()) {
if (fn->getIsolation().isErased() &&
memberName.isSimpleName(Context.Id_isolation)) {
result.ViableCandidates.push_back(
OverloadChoice(baseTy, OverloadChoiceKind::ExtractFunctionIsolation));
}
}
if (!instanceTy->mayHaveMembers())
return result;
// If we have a simple name, determine whether there are argument
// labels we can use to restrict the set of lookup results.
if (baseObjTy->isAnyObject() && memberName.isSimpleName()) {
// If we're referencing AnyObject and we have argument labels, put
// the argument labels into the name: we don't want to look for
// anything else, because the cost of the general search is so
// high.
if (auto *args = getArgumentList(memberLocator)) {
SmallVector<Identifier, 4> scratch;
memberName.getFullName() = DeclName(ctx, memberName.getBaseName(),
args->getArgumentLabels(scratch));
}
}
DeclNameRef lookupName = memberName;
if (memberName.isCompoundName()) {
auto &context = getASTContext();
// Remove any $ prefixes for lookup
SmallVector<Identifier, 4> lookupLabels;
for (auto label : memberName.getArgumentNames()) {
if (label.hasDollarPrefix()) {
auto unprefixed = label.str().drop_front();
lookupLabels.push_back(context.getIdentifier(unprefixed));
} else {
lookupLabels.push_back(label);
}
}
DeclName unprefixedName(context, memberName.getBaseName(), lookupLabels);
lookupName = DeclNameRef(unprefixedName);
}
// Look for members within the base.
LookupResult &lookup = lookupMember(instanceTy, lookupName, memberLoc);
// If this is true, we're using type construction syntax (Foo()) rather
// than an explicit call to `init` (Foo.init()).
bool isImplicitInit = false;
TypeBase *favoredType = nullptr;
if (memberName.isSimpleName(DeclBaseName::createConstructor())) {
SmallVector<LocatorPathElt, 2> parts;
if (auto anchor = memberLocator->getAnchor()) {
auto path = memberLocator->getPath();
if (!path.empty())
if (path.back().getKind() == ConstraintLocator::ConstructorMember)
isImplicitInit = true;
if (auto *applyExpr = getAsExpr<ApplyExpr>(anchor)) {
if (auto *argExpr = applyExpr->getArgs()->getUnlabeledUnaryExpr()) {
favoredType = getFavoredType(argExpr);
if (!favoredType) {
optimizeConstraints(argExpr);
favoredType = getFavoredType(argExpr);
}
}
}
}
}
// If we are pattern-matching an enum element and we found any enum elements,
// ignore anything that isn't an enum element.
bool onlyAcceptEnumElements = false;
if (memberLocator &&
memberLocator->isLastElement<LocatorPathElt::PatternMatch>() &&
isa<EnumElementPattern>(
memberLocator->getLastElementAs<LocatorPathElt::PatternMatch>()
->getPattern())) {
for (const auto &result: lookup) {
if (isa<EnumElementDecl>(result.getValueDecl())) {
onlyAcceptEnumElements = true;
break;
}
}
}
// If the instance type is String bridged to NSString, compute
// the type we'll look in for bridging.
Type bridgedType;
if (baseObjTy->isString()) {
if (Type classType = ctx.getBridgedToObjC(DC, instanceTy)) {
bridgedType = classType;
}
}
// Exclude some of the dynamic member choices from results
// because using such choices would result in a self-recursive reference.
//
// This is required because if there are no viable/unviable choices
// `performMemberLookup` is going to attempt to lookup inaccessible
// members and results would include dynamic member subscripts which
// have already been excluded.
llvm::SmallPtrSet<ValueDecl *, 2> excludedDynamicMembers;
// Local function that adds the given declaration if it is a
// reasonable choice.
auto addChoice = [&](OverloadChoice candidate) {
auto decl = candidate.getDecl();
// Reject circular references immediately.
if (decl->isRecursiveValidation())
return;
// If the result is invalid, skip it unless solving for code completion
// For code completion include the result because we can partially match
// against function types that only have one parameter with error type.
if (decl->isInvalid() && !isForCodeCompletion()) {
result.markErrorAlreadyDiagnosed();
return;
}
// If we only accept enum elements but this isn't one, ignore it.
if (onlyAcceptEnumElements && !isa<EnumElementDecl>(decl))
return;
// Dig out the instance type and figure out what members of the instance type
// we are going to see.
auto baseTy = candidate.getBaseType();
const auto baseObjTy = baseTy->getRValueType();
bool hasInstanceMembers = false;
bool hasInstanceMethods = false;
bool hasStaticMembers = false;
Type instanceTy = baseObjTy;
if (baseObjTy->is<ModuleType>()) {
hasStaticMembers = true;
} else if (auto baseObjMeta = baseObjTy->getAs<AnyMetatypeType>()) {
instanceTy = baseObjMeta->getInstanceType();
if (baseObjMeta->is<ExistentialMetatypeType>()) {
// An instance of an existential metatype is a concrete type conforming
// to the existential, say Self. Instance members of the concrete type
// have type Self -> T -> U, but we don't know what Self is at compile
// time so we cannot refer to them. Static methods are fine, on the other
// hand -- we already know that they do not have Self or associated type
// requirements, since otherwise we would not be able to refer to the
// existential metatype in the first place.
hasStaticMembers = true;
} else if (instanceTy->isExistentialType()) {
// A protocol metatype has instance methods with type P -> T -> U, but
// not instance properties or static members, unless result type of a
// member conforms to this protocol -- the metatype value itself
// doesn't give us a witness so there's no static method to bind.
hasInstanceMethods = true;
hasStaticMembers |=
memberLocator->isLastElement<LocatorPathElt::UnresolvedMember>();
} else {
// Metatypes of nominal types and archetypes have instance methods and
// static members, but not instance properties.
// FIXME: partial application of properties
hasInstanceMethods = true;
hasStaticMembers = true;
}
// If we're at the root of an unevaluated context, we can
// reference instance members on the metatype.
if (memberLocator &&
UnevaluatedRootExprs.count(getAsExpr(memberLocator->getAnchor()))) {
hasInstanceMembers = true;
}
} else {
// Otherwise, we can access all instance members.
hasInstanceMembers = true;
hasInstanceMethods = true;
}
// If the invocation's argument expression has a favored type,
// use that information to determine whether a specific overload for
// the candidate should be favored.
if (isa<ConstructorDecl>(decl) && favoredType &&
result.FavoredChoice == ~0U) {
auto *ctor = cast<ConstructorDecl>(decl);
// Only try and favor monomorphic unary initializers.
if (!ctor->isGenericContext()) {
if (!ctor->getMethodInterfaceType()->hasError()) {
// The constructor might have an error type because we don't skip
// invalid decls for code completion
auto args = ctor->getMethodInterfaceType()
->castTo<FunctionType>()
->getParams();
if (args.size() == 1 && !args[0].hasLabel() &&
args[0].getPlainType()->isEqual(favoredType)) {
if (!isDeclUnavailable(decl, memberLocator))
result.FavoredChoice = result.ViableCandidates.size();
}
}
}
}
const auto isUnsupportedExistentialMemberAccess = [&] {
// We may not be able to derive a well defined type for an existential
// member access if the member's signature references 'Self'.
if (instanceTy->isExistentialType() &&
decl->getDeclContext()->getSelfProtocolDecl()) {
if (!isMemberAvailableOnExistential(instanceTy, decl)) {
return true;
}
}
return false;
};
// See if we have an instance method, instance member or static method,
// and check if it can be accessed on our base type.
if (decl->isInstanceMember()) {
if (baseObjTy->is<AnyMetatypeType>()) {
// `AnyObject` has special semantics, so let's just let it be.
// Otherwise adjust base type and reference kind to make it
// look as if lookup was done on the instance, that helps
// with diagnostics.
auto choice = instanceTy->isAnyObject()
? candidate
: OverloadChoice(instanceTy, decl,
FunctionRefKind::SingleApply);
const bool invalidMethodRef = isa<FuncDecl>(decl) && !hasInstanceMethods;
const bool invalidMemberRef = !isa<FuncDecl>(decl) && !hasInstanceMembers;
if (invalidMethodRef || invalidMemberRef) {
// If this is definitely an invalid way to reference a method or member
// on the metatype, let's stop here.
result.addUnviable(choice,
MemberLookupResult::UR_InstanceMemberOnType);
return;
} else if (isUnsupportedExistentialMemberAccess()) {
// If the member reference itself is legal, but it turns out to be an
// unsupported existential member access, do not make further
// assumptions about the correctness of a potential call -- let
// the unsupported member access error prevail.
result.addUnviable(candidate,
MemberLookupResult::UR_UnavailableInExistential);
return;
} else {
// Otherwise, still add an unviable result to the set, because it
// could be an invalid call that was supposed to be performed on an
// instance of the type.
//
// New candidate shouldn't affect performance because such
// choice would only be attempted when solver is in diagnostic mode.
result.addUnviable(choice,
MemberLookupResult::UR_InstanceMemberOnType);
}
}
if (auto *UDE =
getAsExpr<UnresolvedDotExpr>(memberLocator->getAnchor())) {
auto *base = UDE->getBase();
if (auto *accessor = DC->getInnermostPropertyAccessorContext()) {
if (accessor->isInitAccessor() && isa<DeclRefExpr>(base) &&
accessor->getImplicitSelfDecl() ==
cast<DeclRefExpr>(base)->getDecl()) {
bool isValidReference = false;
// If name doesn't appear in either `initializes` or `accesses`
// then it's invalid instance member.
isValidReference |= llvm::any_of(
accessor->getInitializedProperties(), [&](VarDecl *prop) {
return prop->createNameRef() == memberName;
});
isValidReference |= llvm::any_of(
accessor->getAccessedProperties(), [&](VarDecl *prop) {
return prop->createNameRef() == memberName;
});
if (!isValidReference) {
result.addUnviable(
candidate,
MemberLookupResult::UR_UnavailableWithinInitAccessor);
return;
}
}
}
}
// If the underlying type of a typealias is fully concrete, it is legal
// to access the type with a protocol metatype base.
} else if (instanceTy->isExistentialType() &&
isa<TypeAliasDecl>(decl) &&
!cast<TypeAliasDecl>(decl)
->getUnderlyingType()->getCanonicalType()
->hasTypeParameter()) {
/* We're OK */
} else if (hasStaticMembers && baseObjTy->is<MetatypeType>() &&
instanceTy->isExistentialType()) {
// Static member lookup on protocol metatype in generic context
// requires `Self` of the protocol to be bound to some concrete
// type via same-type requirement, otherwise it would be
// impossible to find a witness for this member.
if (!isa<ExtensionDecl>(decl->getDeclContext())) {
result.addUnviable(candidate,
MemberLookupResult::UR_TypeMemberOnInstance);
return;
}
// Cannot instantiate a protocol or reference a member on
// protocol composition type.
if (isa<ConstructorDecl>(decl) ||
instanceTy->is<ProtocolCompositionType>()) {
result.addUnviable(candidate,
MemberLookupResult::UR_TypeMemberOnInstance);
return;
}
if (getConcreteReplacementForProtocolSelfType(decl)) {
result.addViable(candidate);
} else {
result.addUnviable(
candidate,
MemberLookupResult::UR_InvalidStaticMemberOnProtocolMetatype);
}
return;
} else {
if (!hasStaticMembers) {
result.addUnviable(candidate,
MemberLookupResult::UR_TypeMemberOnInstance);
return;
}
}
if (isUnsupportedExistentialMemberAccess()) {
result.addUnviable(candidate,
MemberLookupResult::UR_UnavailableInExistential);
return;
}
// If we have an rvalue base, make sure that the result isn't 'mutating'
// (only valid on lvalues).
if (!baseTy->is<AnyMetatypeType>() &&
!baseTy->is<LValueType>() &&
decl->isInstanceMember()) {
if (auto *FD = dyn_cast<FuncDecl>(decl))
if (FD->isMutating()) {
result.addUnviable(candidate,
MemberLookupResult::UR_MutatingMemberOnRValue);
return;
}
// Subscripts and computed properties are ok on rvalues so long
// as the getter is nonmutating.
if (auto storage = dyn_cast<AbstractStorageDecl>(decl)) {
if (storage->isGetterMutating()) {
result.addUnviable(candidate,
MemberLookupResult::UR_MutatingGetterOnRValue);
return;
}
}
}
// Check whether this is overload choice found via keypath
// based dynamic member lookup. Since it's unknown upfront
// what kind of declaration lookup is going to find, let's
// double check here that given keypath is appropriate for it.
if (memberLocator) {
using KPDynamicMemberElt = LocatorPathElt::KeyPathDynamicMember;
if (auto kpElt = memberLocator->getLastElementAs<KPDynamicMemberElt>()) {
auto *keyPath = kpElt->getKeyPathDecl();
if (isSelfRecursiveKeyPathDynamicMemberLookup(*this, baseTy,
memberLocator)) {
excludedDynamicMembers.insert(candidate.getDecl());
return;
}
if (auto *storage = dyn_cast<AbstractStorageDecl>(decl)) {
// If this is an attempt to access read-only member via
// writable key path, let's fail this choice early.
auto &ctx = getASTContext();
if (isReadOnlyKeyPathComponent(storage, SourceLoc()) &&
(keyPath == ctx.getWritableKeyPathDecl() ||
keyPath == ctx.getReferenceWritableKeyPathDecl())) {
result.addUnviable(
candidate,
MemberLookupResult::UR_WritableKeyPathOnReadOnlyMember);
return;
}
// A nonmutating setter indicates a reference-writable base,
// on the other hand if setter is mutating there is no point
// of attempting `ReferenceWritableKeyPath` overload.
if (storage->isSetterMutating() &&
keyPath == ctx.getReferenceWritableKeyPathDecl()) {
result.addUnviable(candidate,
MemberLookupResult::
UR_ReferenceWritableKeyPathOnMutatingMember);
return;
}
}
}
}
// Otherwise, we're good, add the candidate to the list.
result.addViable(candidate);
};
// Local function that turns a ValueDecl into a properly configured
// OverloadChoice.
auto getOverloadChoice =
[&](ValueDecl *cand, bool isBridged, bool isUnwrappedOptional,
bool isFallbackUnwrap = false) -> OverloadChoice {
// If we're looking into an existential type, check whether this
// result was found via dynamic lookup.
if (instanceTy->isAnyObject()) {
assert(cand->getDeclContext()->isTypeContext() && "Dynamic lookup bug");
// We found this declaration via dynamic lookup, record it as such.
return OverloadChoice::getDeclViaDynamic(baseTy, cand, functionRefKind);
}
// If we have a bridged type, we found this declaration via bridging.
if (isBridged)
return OverloadChoice::getDeclViaBridge(bridgedType, cand,
functionRefKind);
// If we got the choice by unwrapping an optional type, unwrap the base
// type.
if (isUnwrappedOptional) {
auto ovlBaseTy = MetatypeType::get(baseTy->castTo<MetatypeType>()
->getInstanceType()
->getOptionalObjectType());
return OverloadChoice::getDeclViaUnwrappedOptional(
ovlBaseTy, cand,
/*isFallback=*/isFallbackUnwrap, functionRefKind);
}
// While looking for subscript choices it's possible to find
// `subscript(dynamicMember: {Writable}KeyPath)` on types
// marked as `@dynamicMemberLookup`, let's mark this candidate
// as representing "dynamic lookup" unless it's a direct call
// to such subscript (in that case label is expected to match).
if (auto *subscript = dyn_cast<SubscriptDecl>(cand)) {
if (memberLocator && instanceTy->hasDynamicMemberLookupAttribute() &&
isValidKeyPathDynamicMemberLookup(subscript)) {
auto *args = getArgumentList(memberLocator);
if (!(args && args->isUnary() &&
args->getLabel(0) == getASTContext().Id_dynamicMember)) {
return OverloadChoice::getDynamicMemberLookup(
baseTy, subscript, ctx.getIdentifier("subscript"),
/*isKeyPathBased=*/true);
}
}
}
return OverloadChoice(baseTy, cand, functionRefKind);
};
// Delay solving member constraint for unapplied methods
// where the base type has a conditional Sendable conformance
if (Context.LangOpts.hasFeature(Feature::InferSendableFromCaptures)) {
auto shouldCheckSendabilityOfBase = [&]() {
if (!Context.getProtocol(KnownProtocolKind::Sendable))
return false;
// Static members are always sendable because they only capture
// metatypes which are Sendable.
if (baseObjTy->is<AnyMetatypeType>())
return false;
return isPartialApplication(memberLocator) &&
llvm::any_of(lookup, [&](const auto &result) {
return isa_and_nonnull<FuncDecl>(result.getValueDecl());
});
};
if (shouldCheckSendabilityOfBase()) {
auto sendableProtocol = Context.getProtocol(KnownProtocolKind::Sendable);
auto baseConformance = DC->getParentModule()->lookupConformance(
instanceTy, sendableProtocol);
if (llvm::any_of(
baseConformance.getConditionalRequirements(),
[&](const auto &req) {
if (req.getKind() != RequirementKind::Conformance)
return false;
if (auto protocolTy =
req.getSecondType()->template getAs<ProtocolType>()) {
return req.getFirstType()->hasTypeVariable() &&
protocolTy->getDecl()->isSpecificProtocol(
KnownProtocolKind::Sendable);
}
return false;
})) {
result.OverallResult = MemberLookupResult::Unsolved;
return result;
}
}
}
// Add all results from this lookup.
for (auto result : lookup)
addChoice(getOverloadChoice(result.getValueDecl(),
/*isBridged=*/false,
/*isUnwrappedOptional=*/false));
// Backward compatibility hack. In Swift 4, `init` and init were
// the same name, so you could write "foo.init" to look up a
// method or property named `init`.
if (!ctx.isSwiftVersionAtLeast(5) &&
memberName.getBaseName().isConstructor() && !isImplicitInit) {
auto &compatLookup = lookupMember(instanceTy,
DeclNameRef(ctx.getIdentifier("init")),
memberLoc);
for (auto result : compatLookup)
addChoice(getOverloadChoice(result.getValueDecl(),
/*isBridged=*/false,
/*isUnwrappedOptional=*/false));
}
// If the instance type is a bridged to an Objective-C type, perform
// a lookup into that Objective-C type.
if (bridgedType) {
LookupResult &bridgedLookup = lookupMember(bridgedType, memberName,
memberLoc);
ModuleDecl *foundationModule = nullptr;
for (auto result : bridgedLookup) {
// Ignore results from the Objective-C "Foundation"
// module. Those core APIs are explicitly provided by the
// Foundation module overlay.
auto module = result.getValueDecl()->getModuleContext();
if (foundationModule) {
if (module == foundationModule)
continue;
} else if (ClangModuleUnit::hasClangModule(module) &&
module->getName().str() == "Foundation") {
// Cache the foundation module name so we don't need to look
// for it again.
foundationModule = module;
continue;
}
addChoice(getOverloadChoice(result.getValueDecl(),
/*isBridged=*/true,
/*isUnwrappedOptional=*/false));
}
}
// If we have candidates, and we're doing a member lookup for a pattern
// match, unwrap optionals and try again to allow implicit creation of
// optional "some" patterns (spelled "?").
if (result.ViableCandidates.empty() && result.UnviableCandidates.empty() &&
memberLocator &&
memberLocator->isLastElement<LocatorPathElt::PatternMatch>() &&
instanceTy->getOptionalObjectType() &&
baseObjTy->is<AnyMetatypeType>()) {
SmallVector<Type, 2> optionals;
Type instanceObjectTy = instanceTy->lookThroughAllOptionalTypes(optionals);
Type metaObjectType = MetatypeType::get(instanceObjectTy);
auto result = performMemberLookup(
constraintKind, memberName, metaObjectType,
functionRefKind, memberLocator, includeInaccessibleMembers);
result.numImplicitOptionalUnwraps = optionals.size();
result.actualBaseType = metaObjectType;
return result;
}
// If we're looking into a metatype for an unresolved member lookup, look
// through optional types.
//
// FIXME: Unify with the above code path.
if (baseObjTy->is<AnyMetatypeType>() &&
constraintKind == ConstraintKind::UnresolvedValueMember) {
if (auto objectType = instanceTy->getOptionalObjectType()) {
// If we don't have a wrapped type yet, we can't look through the optional
// type.
if (objectType->getAs<TypeVariableType>() && result.ViableCandidates.empty()) {
MemberLookupResult result;
result.OverallResult = MemberLookupResult::Unsolved;
return result;
}
if (objectType->mayHaveMembers()) {
// If there are viable members directly on `Optional`, let's
// prioritize them and mark any results found on wrapped type
// as a fallback results.
bool isFallback = !result.ViableCandidates.empty();
LookupResult &optionalLookup = lookupMember(objectType, memberName,
memberLoc);
for (auto result : optionalLookup)
addChoice(getOverloadChoice(result.getValueDecl(),
/*bridged*/ false,
/*isUnwrappedOptional=*/true,
/*isUnwrapFallback=*/isFallback));
}
}
}
// If we're about to fail lookup because there are no viable candidates
// or if all of the candidates come from conditional conformances (which
// might not be applicable), and we are looking for members in a type with
// the @dynamicMemberLookup attribute, then we resolve a reference to a
// `subscript(dynamicMember:)` method and pass the member name as a string
// parameter.
if (constraintKind == ConstraintKind::ValueMember &&
memberName.isSimpleName() && !memberName.isSpecial() &&
instanceTy->hasDynamicMemberLookupAttribute()) {
const auto &candidates = result.ViableCandidates;
if ((candidates.empty() ||
allFromConditionalConformances(*this, instanceTy, candidates)) &&
!isSelfRecursiveKeyPathDynamicMemberLookup(*this, baseTy,
memberLocator)) {
auto &ctx = getASTContext();
// Recursively look up `subscript(dynamicMember:)` methods in this type.
DeclNameRef subscriptName(
{ ctx, DeclBaseName::createSubscript(), { ctx.Id_dynamicMember } });
auto subscripts = performMemberLookup(
constraintKind, subscriptName, baseTy, functionRefKind, memberLocator,
includeInaccessibleMembers);
// Reflect the candidates found as `DynamicMemberLookup` results.
auto name = memberName.getBaseIdentifier();
for (const auto &candidate : subscripts.ViableCandidates) {
auto *SD = cast<SubscriptDecl>(candidate.getDecl());
bool isKeyPathBased = isValidKeyPathDynamicMemberLookup(SD);
if (isValidStringDynamicMemberLookup(SD, DC->getParentModule()) ||
isKeyPathBased)
result.addViable(OverloadChoice::getDynamicMemberLookup(
baseTy, SD, name, isKeyPathBased));
}
for (auto index : indices(subscripts.UnviableCandidates)) {
auto *SD =
cast<SubscriptDecl>(subscripts.UnviableCandidates[index].getDecl());
auto choice = OverloadChoice::getDynamicMemberLookup(
baseTy, SD, name, isValidKeyPathDynamicMemberLookup(SD));
result.addUnviable(choice, subscripts.UnviableReasons[index]);
}
}
}
// If we have no viable or unviable candidates, and we're generating,
// diagnostics, rerun the query with inaccessible members included, so we can
// include them in the unviable candidates list.
if (result.ViableCandidates.empty() && result.UnviableCandidates.empty() &&
includeInaccessibleMembers) {
NameLookupOptions lookupOptions = defaultMemberLookupOptions;
// Ignore access control so we get candidates that might have been missed
// before.
lookupOptions |= NameLookupFlags::IgnoreAccessControl;
auto lookup =
TypeChecker::lookupMember(DC, instanceTy, memberName,
memberLoc, lookupOptions);
for (auto entry : lookup) {
auto *cand = entry.getValueDecl();
// If the result is invalid, skip it.
if (cand->isInvalid()) {
result.markErrorAlreadyDiagnosed();
return result;
}
if (excludedDynamicMembers.count(cand))
continue;
result.addUnviable(getOverloadChoice(cand, /*isBridged=*/false,
/*isUnwrappedOptional=*/false),
MemberLookupResult::UR_Inaccessible);
}
}
return result;
}
/// Determine whether the given type refers to a non-final class (or
/// dynamic self of one).
static bool isNonFinalClass(Type type) {
if (auto dynamicSelf = type->getAs<DynamicSelfType>())
type = dynamicSelf->getSelfType();
if (auto classDecl = type->getClassOrBoundGenericClass())
return !classDecl->isSemanticallyFinal();
if (auto archetype = type->getAs<ArchetypeType>())
if (auto super = archetype->getSuperclass())
return isNonFinalClass(super);
return type->isExistentialType();
}
/// Determine whether given constructor reference is valid or does it require
/// any fixes e.g. when base is a protocol metatype.
static ConstraintFix *validateInitializerRef(ConstraintSystem &cs,
ConstructorDecl *init,
ConstraintLocator *locator) {
auto anchor = locator->getAnchor();
if (!anchor)
return nullptr;
// Avoid checking implicit conversions injected by the compiler.
if (locator->findFirst<LocatorPathElt::ImplicitConversion>())
return nullptr;
auto getType = [&cs](Expr *expr) -> Type {
return cs.simplifyType(cs.getType(expr))->getRValueType();
};
Expr *baseExpr = nullptr;
Type baseType;
// Explicit initializer reference e.g. `T.init(...)` or `T.init`.
if (auto *UDE = getAsExpr<UnresolvedDotExpr>(anchor)) {
baseExpr = UDE->getBase();
baseType = getType(baseExpr);
if (baseType->is<MetatypeType>()) {
auto instanceType = baseType->getAs<MetatypeType>()
->getInstanceType()
->getWithoutParens();
if (!cs.isTypeReference(baseExpr) && instanceType->isExistentialType()) {
return AllowInvalidInitRef::onProtocolMetatype(
cs, baseType, init, /*isStaticallyDerived=*/true,
baseExpr->getSourceRange(), locator);
}
}
// Initializer call e.g. `T(...)`
} else if (auto *CE = getAsExpr<CallExpr>(anchor)) {
baseExpr = CE->getFn();
baseType = getType(baseExpr);
// FIXME: Historically, UnresolvedMemberExprs have allowed implicit
// construction through a metatype value, but this should probably be
// illegal.
if (!isa<UnresolvedMemberExpr>(baseExpr)) {
// If this is an initializer call without explicit mention
// of `.init` on metatype value.
if (auto *AMT = baseType->getAs<AnyMetatypeType>()) {
auto instanceType = AMT->getInstanceType()->getWithoutParens();
if (!cs.isTypeReference(baseExpr)) {
if (baseType->is<MetatypeType>() &&
instanceType->isAnyExistentialType()) {
return AllowInvalidInitRef::onProtocolMetatype(
cs, baseType, init, cs.isStaticallyDerivedMetatype(baseExpr),
baseExpr->getSourceRange(), locator);
}
if (!instanceType->isExistentialType() ||
instanceType->isAnyExistentialType()) {
return AllowInvalidInitRef::onNonConstMetatype(cs, baseType, init,
locator);
}
}
}
}
// Initializer reference which requires contextual base type e.g.
// `.init(...)`. Could also be a nested type or typealias being constructed
// via implicit member syntax, e.g., `let _: Base = .Nested()` where
// `Base.Nested: Base`.
} else if (auto *UME = getAsExpr<UnresolvedMemberExpr>(anchor)) {
// If we're accessing a nested type to perform the construction implicitly,
// then the type we're constructing may not actually be the base of the
// UnresolvedMemberExpr--instead, it will be the type of the nested type
// member.
// We need to find type variable which represents contextual base.
auto *baseLocator = cs.getConstraintLocator(
UME, locator->isLastElement<LocatorPathElt::ConstructorMember>()
? ConstraintLocator::UnresolvedMember
: ConstraintLocator::MemberRefBase);
// FIXME: Type variables responsible for contextual base could be cached
// in the constraint system to speed up lookup.
auto result = llvm::find_if(
cs.getTypeVariables(), [&baseLocator](const TypeVariableType *typeVar) {
return typeVar->getImpl().getLocator() == baseLocator;
});
assert(result != cs.getTypeVariables().end());
baseType = cs.simplifyType(*result)->getRValueType();
// Constraint for member base is formed as '$T.Type[.<member] = ...`
// which means MetatypeType has to be added after finding a type variable.
if (baseLocator->isLastElement<LocatorPathElt::MemberRefBase>())
baseType = MetatypeType::get(baseType);
} else if (auto *keyPathExpr = getAsExpr<KeyPathExpr>(anchor)) {
// Key path can't refer to initializers e.g. `\Type.init`
return AllowInvalidRefInKeyPath::forRef(cs, init, locator);
}
if (!baseType)
return nullptr;
if (!baseType->is<AnyMetatypeType>()) {
bool applicable = false;
// Special case -- in a protocol extension initializer with a class
// constrained Self type, 'self' has archetype type, and only
// required initializers can be called.
if (baseExpr && !baseExpr->isSuperExpr()) {
auto &ctx = cs.getASTContext();
if (auto *DRE =
dyn_cast<DeclRefExpr>(baseExpr->getSemanticsProvidingExpr())) {
if (DRE->getDecl()->getName() == ctx.Id_self) {
if (getType(DRE)->is<ArchetypeType>())
applicable = true;
}
}
}
if (!applicable)
return nullptr;
}
auto instanceType = baseType->getMetatypeInstanceType();
bool isStaticallyDerived = true;
// If this is expression like `.init(...)` where base type is
// determined by a contextual type.
if (!baseExpr) {
isStaticallyDerived = !(instanceType->is<DynamicSelfType>() ||
instanceType->is<ArchetypeType>());
// Otherwise this is something like `T.init(...)`
} else {
isStaticallyDerived = cs.isStaticallyDerivedMetatype(baseExpr);
}
auto baseRange = baseExpr ? baseExpr->getSourceRange() : SourceRange();
// FIXME: The "hasClangNode" check here is a complete hack.
if (isNonFinalClass(instanceType) && !isStaticallyDerived &&
!init->hasClangNode() &&
!(init->isRequired() || init->getDeclContext()->getSelfProtocolDecl())) {
return AllowInvalidInitRef::dynamicOnMetatype(cs, baseType, init, baseRange,
locator);
// Constructors cannot be called on a protocol metatype, because there is no
// metatype to witness it.
} else if (baseType->is<MetatypeType>() &&
instanceType->isExistentialType()) {
return AllowInvalidInitRef::onProtocolMetatype(
cs, baseType, init, isStaticallyDerived, baseRange, locator);
}
return nullptr;
}
static ConstraintFix *fixMemberRef(
ConstraintSystem &cs, Type baseTy, DeclNameRef memberName,
const OverloadChoice &choice, ConstraintLocator *locator,
std::optional<MemberLookupResult::UnviableReason> reason = std::nullopt) {
// Not all of the choices handled here are going
// to refer to a declaration.
if (auto *decl = choice.getDeclOrNull()) {
if (auto *CD = dyn_cast<ConstructorDecl>(decl)) {
if (auto *fix = validateInitializerRef(cs, CD, locator))
return fix;
}
if (locator->isForKeyPathDynamicMemberLookup() ||
locator->isForKeyPathComponent() ||
locator->isKeyPathSubscriptComponent()) {
if (auto *fix = AllowInvalidRefInKeyPath::forRef(cs, decl, locator))
return fix;
}
}
if (reason) {
switch (*reason) {
case MemberLookupResult::UR_InstanceMemberOnType:
case MemberLookupResult::UR_TypeMemberOnInstance: {
return choice.isDecl()
? AllowTypeOrInstanceMember::create(
cs, baseTy, choice.getDecl(), memberName, locator)
: nullptr;
}
case MemberLookupResult::UR_Inaccessible:
assert(choice.isDecl());
return AllowInaccessibleMember::create(cs, baseTy, choice.getDecl(),
memberName, locator);
case MemberLookupResult::UR_UnavailableInExistential: {
return choice.isDecl()
? AllowMemberRefOnExistential::create(
cs, baseTy, choice.getDecl(), memberName, locator)
: nullptr;
}
case MemberLookupResult::UR_MutatingMemberOnRValue:
case MemberLookupResult::UR_MutatingGetterOnRValue: {
return choice.isDecl()
? AllowMutatingMemberOnRValueBase::create(
cs, baseTy, choice.getDecl(), memberName, locator)
: nullptr;
}
// TODO(diagnostics): Add a new fix that is suggests to
// add `subscript(dynamicMember: {Writable}KeyPath<T, U>)`
// overload here, that would help if such subscript has
// not been provided.
case MemberLookupResult::UR_WritableKeyPathOnReadOnlyMember:
return TreatRValueAsLValue::create(cs, cs.getConstraintLocator(locator));
case MemberLookupResult::UR_ReferenceWritableKeyPathOnMutatingMember:
break;
case MemberLookupResult::UR_KeyPathWithAnyObjectRootType:
return AllowAnyObjectKeyPathRoot::create(cs, locator);
case MemberLookupResult::UR_InvalidStaticMemberOnProtocolMetatype:
return AllowInvalidStaticMemberRefOnProtocolMetatype::create(cs, locator);
case MemberLookupResult::UR_UnavailableWithinInitAccessor:
return AllowInvalidMemberReferenceInInitAccessor::create(cs, memberName,
locator);
}
}
return nullptr;
}
/// Convert the given enum element pattern into an expression pattern
/// and synthesize ~= operator application to find the type of the
/// element.
static bool inferEnumMemberThroughTildeEqualsOperator(
ConstraintSystem &cs, EnumElementPattern *pattern, Type enumTy,
Type elementTy, ConstraintLocator *locator) {
if (!pattern->hasUnresolvedOriginalExpr())
return true;
auto &ctx = cs.getASTContext();
// Retrieve a corresponding ExprPattern which we can solve with ~=.
auto *EP = evaluateOrFatal(ctx.evaluator,
EnumElementExprPatternRequest{pattern});
auto target = SyntacticElementTarget::forExprPattern(EP);
DiagnosticTransaction diagnostics(ctx.Diags);
{
if (cs.preCheckTarget(target, /*replaceInvalidRefWithErrors=*/true)) {
// Skip diagnostics if they are disabled, otherwise it would result in
// duplicate diagnostics, since this operation is going to be repeated
// in diagnostic mode.
if (!cs.shouldAttemptFixes())
diagnostics.abort();
return true;
}
}
cs.setType(EP->getMatchVar(), enumTy);
cs.setType(EP, enumTy);
if (cs.generateConstraints(target))
return true;
// Sub-expression associated with expression pattern is the enum element
// access which needs to be connected to the provided element type.
cs.addConstraint(ConstraintKind::Conversion, cs.getType(EP->getSubExpr()),
elementTy, cs.getConstraintLocator(EP));
cs.setTargetFor(pattern, target);
return false;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyMemberConstraint(
ConstraintKind kind, Type baseTy, DeclNameRef member, Type memberTy,
DeclContext *useDC, FunctionRefKind functionRefKind,
ArrayRef<OverloadChoice> outerAlternatives, TypeMatchOptions flags,
ConstraintLocatorBuilder locatorB) {
// We'd need to record original base type because it might be a type
// variable representing another missing member.
auto origBaseTy = baseTy;
// Resolve the base type, if we can. If we can't resolve the base type,
// then we can't solve this constraint.
baseTy = simplifyType(baseTy, flags);
Type baseObjTy = baseTy->getRValueType();
auto locator = getConstraintLocator(locatorB);
auto formUnsolved = [&](bool activate = false) {
// If requested, generate a constraint.
if (flags.contains(TMF_GenerateConstraints)) {
auto *memberRef = Constraint::createMemberOrOuterDisjunction(
*this, kind, baseTy, memberTy, member, useDC, functionRefKind,
outerAlternatives, locator);
addUnsolvedConstraint(memberRef);
if (activate)
activateConstraint(memberRef);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// If the base type of this member lookup is a "hole" there is no
// reason to perform a lookup because it wouldn't return any results.
if (shouldAttemptFixes()) {
auto markMemberTypeAsPotentialHole = [&](Type memberTy) {
recordAnyTypeVarAsPotentialHole(simplifyType(memberTy));
};
// If this is an unresolved member ref e.g. `.foo` and its contextual base
// type has been determined to be a "hole", let's mark the resulting member
// type as a potential hole and continue solving.
if (kind == ConstraintKind::UnresolvedValueMember) {
// Let's look through all metatypes to find "underlying" type
// of this lookup.
Type underlyingType = baseObjTy;
while (auto *MT = underlyingType->getAs<AnyMetatypeType>()) {
underlyingType = MT->getInstanceType();
}
// Let's delay solving this constraint in diagnostic
// mode until it's certain that there is no way to
// find out what the base type is.
if (underlyingType->isTypeVariableOrMember())
return formUnsolved();
// Let's record a fix only if the hole originates either
// at the result of the chain (that could happen since solving
// of this constraint is delayed until base could be resolved),
// or it is certain that base type can't be bound to any other
// type but a hole.
auto shouldRecordFixForHole = [&](PlaceholderType *baseType) {
auto *originator =
baseType->getOriginator().dyn_cast<TypeVariableType *>();
if (!originator)
return false;
auto *originatorLoc = originator->getImpl().getLocator();
// It could either be a hole associated directly with the base
// or a hole which came from result type of the chain.
if (originatorLoc->isLastElement<
LocatorPathElt::UnresolvedMemberChainResult>()) {
auto *UMCR = castToExpr<UnresolvedMemberChainResultExpr>(
originatorLoc->getAnchor());
return UMCR->getChainBase() == getAsExpr(locator->getAnchor());
}
return originatorLoc == locator;
};
if (auto *hole = underlyingType->getAs<PlaceholderType>()) {
if (shouldRecordFixForHole(hole)) {
auto *fix = SpecifyBaseTypeForContextualMember::create(*this, member,
locator);
if (recordFix(fix))
return SolutionKind::Error;
}
markMemberTypeAsPotentialHole(memberTy);
return SolutionKind::Solved;
}
} else if ((kind == ConstraintKind::ValueMember ||
kind == ConstraintKind::ValueWitness) &&
baseObjTy->getMetatypeInstanceType()->isPlaceholder()) {
// If base type is a "hole" there is no reason to record any
// more "member not found" fixes for chained member references.
markMemberTypeAsPotentialHole(memberTy);
return SolutionKind::Solved;
}
}
// Special handling of injected references to `makeIterator` and `next`
// in for-in loops.
if (auto *expr = getAsExpr(locator->getAnchor())) {
// `next()` could be wrapped in `await` expression.
auto memberRef =
getAsExpr<UnresolvedDotExpr>(expr->getSemanticsProvidingExpr());
if (memberRef && memberRef->isImplicit() &&
locator->isLastElement<LocatorPathElt::Member>()) {
auto &ctx = getASTContext();
// Cannot simplify this constraint yet since we don't know whether
// the base type is going to be existential or not.
if (baseObjTy->isTypeVariableOrMember())
return formUnsolved();
// Check whether the given dot expression is a reference
// to the given name with the given set of argument labels
// (aka compound name).
auto isRefTo = [&](UnresolvedDotExpr *UDE, Identifier name,
ArrayRef<StringRef> labels) {
auto refName = UDE->getName().getFullName();
return refName.isCompoundName(name, labels);
};
auto *baseExpr = memberRef->getBase();
// Handle `makeIterator` reference.
if (getContextualTypePurpose(baseExpr) == CTP_ForEachSequence &&
isRefTo(memberRef, ctx.Id_makeIterator, /*lables=*/{})) {
auto *sequenceProto = cast<ProtocolDecl>(
getContextualType(baseExpr, /*forConstraint=*/false)
->getAnyNominal());
bool isAsync = sequenceProto->getKnownProtocolKind() ==
KnownProtocolKind::AsyncSequence;
auto *makeIterator = isAsync ? ctx.getAsyncSequenceMakeAsyncIterator()
: ctx.getSequenceMakeIterator();
return simplifyValueWitnessConstraint(
ConstraintKind::ValueWitness, baseTy, makeIterator, memberTy, useDC,
FunctionRefKind::Compound, flags, locator);
}
// Handle `next` reference.
if (getContextualTypePurpose(baseExpr) == CTP_ForEachSequence &&
(isRefTo(memberRef, ctx.Id_next, /*labels=*/{}) ||
isRefTo(memberRef, ctx.Id_next, /*labels=*/{ "isolation" }))) {
auto *iteratorProto = cast<ProtocolDecl>(
getContextualType(baseExpr, /*forConstraint=*/false)
->getAnyNominal());
bool isAsync = iteratorProto->getKnownProtocolKind() ==
KnownProtocolKind::AsyncIteratorProtocol;
auto loc = locator->getAnchor().getStartLoc();
auto *next = TypeChecker::getForEachIteratorNextFunction(DC, loc, isAsync);
return simplifyValueWitnessConstraint(
ConstraintKind::ValueWitness, baseTy, next, memberTy, useDC,
FunctionRefKind::Compound, flags, locator);
}
}
}
MemberLookupResult result =
performMemberLookup(kind, member, baseTy, functionRefKind, locator,
/*includeInaccessibleMembers*/ shouldAttemptFixes());
switch (result.OverallResult) {
case MemberLookupResult::Unsolved:
return formUnsolved();
case MemberLookupResult::ErrorAlreadyDiagnosed:
case MemberLookupResult::HasResults:
// Keep going!
break;
}
SmallVector<Constraint *, 4> candidates;
// If we found viable candidates, then we're done!
if (!result.ViableCandidates.empty()) {
// If we had to look in a different type, use that.
if (result.actualBaseType)
baseTy = result.actualBaseType;
// If only possible choice to refer to member is via keypath
// dynamic member dispatch, let's delay solving this constraint
// until constraint generation phase is complete, because
// subscript dispatch relies on presence of function application.
if (result.ViableCandidates.size() == 1) {
auto &choice = result.ViableCandidates.front();
if (Phase == ConstraintSystemPhase::ConstraintGeneration &&
choice.isKeyPathDynamicMemberLookup() &&
member.getBaseName().isSubscript()) {
// Let's move this constraint to the active
// list so it could be picked up right after
// constraint generation is done.
return formUnsolved(/*activate=*/true);
}
}
generateConstraints(
candidates, memberTy, result.ViableCandidates, useDC, locator,
result.getFavoredIndex(), /*requiresFix=*/false,
[&](unsigned, const OverloadChoice &choice) {
return fixMemberRef(*this, baseTy, member, choice, locator);
});
if (!outerAlternatives.empty()) {
// If local scope has a single choice,
// it should always be preferred.
if (candidates.size() == 1)
candidates.front()->setFavored();
// We *might* include any non-members that we found in outer contexts in
// some special cases, for backwards compatibility: first, we have to be
// looking for one of the special names ('min' or 'max'), and second, all
// of the inner (viable) results need to come from conditional
// conformances. The second condition is how the problem here was
// encountered: a type ('Range') was made to conditionally conform to a
// new protocol ('Sequence'), which introduced some extra methods
// ('min' and 'max') that shadowed global functions that people regularly
// called within extensions to that type (usually adding 'clamp').
bool treatAsViable =
(member.isSimpleName("min") || member.isSimpleName("max")) &&
allFromConditionalConformances(*this, baseTy,
result.ViableCandidates);
generateConstraints(
candidates, memberTy, outerAlternatives, useDC, locator, std::nullopt,
/*requiresFix=*/!treatAsViable,
[&](unsigned, const OverloadChoice &) {
return treatAsViable ? nullptr
: AddQualifierToAccessTopLevelName::create(
*this, locator);
});
}
}
if (!result.UnviableCandidates.empty()) {
// Generate constraints for unavailable choices if they have a fix,
// and disable them by default, they'd get picked up in the "salvage" mode.
generateConstraints(
candidates, memberTy, result.UnviableCandidates, useDC, locator,
/*favoredChoice=*/std::nullopt, /*requiresFix=*/true,
[&](unsigned idx, const OverloadChoice &choice) {
return fixMemberRef(*this, baseTy, member, choice, locator,
result.UnviableReasons[idx]);
});
}
// Attempt to record a warning where the unresolved member could be
// ambiguous with optional member. e.g.
// enum Foo {
// case none
// }
//
// let _: Foo? = .none // Although base is inferred as Optional.none
// it could be also Foo.none.
if (auto *fix = SpecifyBaseTypeForOptionalUnresolvedMember::attempt(
*this, kind, baseObjTy, member, functionRefKind, result, locator)) {
(void)recordFix(fix);
}
// If there were no results from a direct enum lookup, let's attempt
// to resolve this member via ~= operator application.
if (candidates.empty()) {
if (auto patternLoc =
locator->getLastElementAs<LocatorPathElt::PatternMatch>()) {
if (auto *enumElement =
dyn_cast<EnumElementPattern>(patternLoc->getPattern())) {
auto enumType = baseObjTy->getMetatypeInstanceType();
// Optional base type does not trigger `~=` synthesis, but it tries
// to find member on both `Optional` and its wrapped type.
if (!enumType->getOptionalObjectType()) {
// If the synthesis of ~= resulted in errors (i.e. broken stdlib)
// that would be diagnosed inline, so let's just fall through and
// let this situation be diagnosed as a missing member.
auto hadErrors = inferEnumMemberThroughTildeEqualsOperator(
*this, enumElement, enumType, memberTy, locator);
// Let's consider current member constraint solved because it's
// replaced by a new set of constraints that would resolve member
// type.
if (!hadErrors)
return SolutionKind::Solved;
}
}
}
}
if (!candidates.empty()) {
addOverloadSet(candidates, locator);
return SolutionKind::Solved;
}
// If the lookup found no hits at all (either viable or unviable), diagnose it
// as such and try to recover in various ways.
if (shouldAttemptFixes()) {
auto fixMissingMember = [&](Type baseTy, Type memberTy,
ConstraintLocator *locator) -> SolutionKind {
// Let's check whether there are any generic parameters associated with
// base type, and record potential holes if so.
simplifyType(baseTy).transform([&](Type type) -> Type {
if (auto *typeVar = type->getAs<TypeVariableType>()) {
if (typeVar->getImpl().hasRepresentativeOrFixed())
return type;
recordPotentialHole(typeVar);
}
return type;
});
auto success = [&]() -> SolutionKind {
// Record a hole for memberTy to make it possible to form solutions
// when contextual result type cannot be deduced e.g. `let _ = x.foo`.
if (auto *memberTypeVar = memberTy->getAs<TypeVariableType>()) {
if (getFixedType(memberTypeVar)) {
// If member has been bound before the base and the base was
// incorrect at that (e.g. fallback to default `Any` type),
// then we need to re-activate all of the constraints
// associated with this member reference otherwise some of
// the constraints could be left unchecked in inactive state.
// This is especially important for key path expressions because
// `key path` constraint can't be retired until all components
// are simplified.
addTypeVariableConstraintsToWorkList(memberTypeVar);
} else if (locator->isLastElement<LocatorPathElt::PatternMatch>()) {
// Let's handle member patterns specifically because they use
// equality instead of argument application constraint, so allowing
// them to bind member could mean missing valid hole positions in
// the pattern.
recordTypeVariablesAsHoles(memberTypeVar);
} else {
recordPotentialHole(memberTypeVar);
}
}
return SolutionKind::Solved;
};
bool alreadyDiagnosed = (result.OverallResult ==
MemberLookupResult::ErrorAlreadyDiagnosed);
auto *fix = DefineMemberBasedOnUse::create(*this, baseTy, member,
alreadyDiagnosed, locator);
auto instanceTy = baseObjTy->getMetatypeInstanceType();
auto impact = 2;
// Impact is higher if the base type is any function type
// because function types can't have any members other than self
if (instanceTy->is<AnyFunctionType>()) {
impact += 10;
}
if (instanceTy->isAny() || instanceTy->isAnyObject())
impact += 5;
auto *anchorExpr = getAsExpr(locator->getAnchor());
if (anchorExpr) {
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(anchorExpr)) {
// The issue is related to a missing `Sequence` protocol
// conformance if either `makeIterator` or `next` are missing.
if (UDE->isImplicit()) {
// Missing `makeIterator` since the base is sequence expression.
if (getContextualTypePurpose(UDE->getBase()) == CTP_ForEachSequence)
return success();
// Missing `next` where the base is result of `makeIterator`.
if (auto *base = dyn_cast<DeclRefExpr>(UDE->getBase())) {
if (auto var = dyn_cast_or_null<VarDecl>(base->getDecl())) {
if (var->getNameStr().contains("$generator") &&
(UDE->getName().getBaseIdentifier() == Context.Id_next))
return success();
}
}
}
}
// Increasing the impact for missing member in any argument position so
// it doesn't affect situations where there are another fixes involved.
if (getArgumentLocator(anchorExpr))
impact += 5;
}
if (recordFix(fix, impact))
return SolutionKind::Error;
return success();
};
if (baseObjTy->getOptionalObjectType()) {
// If the base type was an optional, look through it.
// If the base type is optional because we haven't chosen to force an
// implicit optional, don't try to fix it. The IUO will be forced instead.
if (auto dotExpr = getAsExpr<UnresolvedDotExpr>(locator->getAnchor())) {
auto baseExpr = dotExpr->getBase();
if (auto overload = findSelectedOverloadFor(baseExpr)) {
auto iuoKind = overload->choice.getIUOReferenceKind(*this);
if (iuoKind == IUOReferenceKind::Value)
return SolutionKind::Error;
}
}
// Let's check whether the problem is related to optionality of base
// type, or there is no member with a given name.
result =
performMemberLookup(kind, member, baseObjTy->getOptionalObjectType(),
functionRefKind, locator,
/*includeInaccessibleMembers*/ true);
// If unwrapped type still couldn't find anything for a given name,
// let's fallback to a "not such member" fix.
if (result.ViableCandidates.empty() && result.UnviableCandidates.empty())
return fixMissingMember(origBaseTy, memberTy, locator);
bool baseIsKeyPathRootType = [&]() {
auto keyPathComponent =
locator->getLastElementAs<LocatorPathElt::KeyPathComponent>();
return keyPathComponent && keyPathComponent->getIndex() == 0;
}();
// The result of the member access can either be the expected member type
// (for '!' or optional members with '?'), or the original member type
// with one extra level of optionality ('?' with non-optional members).
auto innerTV = createTypeVariable(locator,
TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
Type optTy = TypeChecker::getOptionalType(SourceLoc(), innerTV);
assert(!optTy->hasError());
SmallVector<Constraint *, 2> optionalities;
auto nonoptionalResult = Constraint::createFixed(
*this, ConstraintKind::Bind,
UnwrapOptionalBase::create(*this, member, baseObjTy, locator),
memberTy, innerTV, locator);
optionalities.push_back(nonoptionalResult);
if (!baseIsKeyPathRootType) {
auto optionalResult = Constraint::createFixed(
*this, ConstraintKind::Bind,
UnwrapOptionalBase::createWithOptionalResult(*this, member,
baseObjTy, locator),
optTy, memberTy, locator);
optionalities.push_back(optionalResult);
}
addDisjunctionConstraint(optionalities, locator);
// Look through one level of optional.
addValueMemberConstraint(baseObjTy->getOptionalObjectType(), member,
innerTV, useDC, functionRefKind,
outerAlternatives, locator);
return SolutionKind::Solved;
}
auto solveWithNewBaseOrName = [&](Type baseType,
DeclNameRef memberName) -> SolutionKind {
return simplifyMemberConstraint(kind, baseType, memberName, memberTy,
useDC, functionRefKind, outerAlternatives,
flags | TMF_ApplyingFix, locatorB);
};
// If this member reference is a result of a previous fix, let's not allow
// any more fixes expect when base is optional, because it could also be
// an IUO which requires a separate fix.
if (flags.contains(TMF_ApplyingFix))
return SolutionKind::Error;
// Check if any property wrappers on the base of the member lookup have
// matching members that we can fall back to, or if the type wraps any
// properties that have matching members.
if (auto *fix = fixPropertyWrapperFailure(
*this, baseTy, locator,
[&](SelectedOverload overload, VarDecl *decl, Type newBase) {
return solveWithNewBaseOrName(newBase, member) ==
SolutionKind::Solved;
})) {
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
// If base is an archetype or metatype of archetype, check for an unintended
// extra generic parameter.
if (auto archetype =
baseTy->getMetatypeInstanceType()->getAs<ArchetypeType>()) {
if (auto genericTy =
archetype->mapTypeOutOfContext()->getAs<GenericTypeParamType>()) {
for (auto param : DC->getGenericSignatureOfContext()
.getGenericParams()) {
// Find a param at the same depth and one index past the type we're
// dealing with
if (param->getDepth() != genericTy->getDepth() ||
param->getIndex() != genericTy->getIndex() + 1)
continue;
auto paramDecl = param->getDecl();
if (!paramDecl)
continue;
auto descriptor = UnqualifiedLookupDescriptor{
DeclNameRef(param->getName()),
paramDecl->getDeclContext()->getModuleScopeContext(),
SourceLoc(),
UnqualifiedLookupFlags::TypeLookup};
auto lookup = evaluateOrDefault(
Context.evaluator, UnqualifiedLookupRequest{descriptor}, {});
for (auto &result : lookup) {
if (auto proto =
dyn_cast_or_null<ProtocolDecl>(result.getValueDecl())) {
auto result =
baseTy->is<MetatypeType>()
? solveWithNewBaseOrName(ExistentialMetatypeType::get(
proto->getDeclaredInterfaceType()),
member)
: solveWithNewBaseOrName(proto->getDeclaredInterfaceType(),
member);
if (result == SolutionKind::Solved)
return recordFix(
DefineMemberBasedOnUnintendedGenericParam::create(
*this, baseTy, member, param->getName(),
locator))
? SolutionKind::Error
: SolutionKind::Solved;
}
}
}
}
}
if (auto *funcType = baseTy->getAs<FunctionType>()) {
// We can't really suggest anything useful unless
// function takes no arguments, otherwise it
// would make sense to report this a missing member.
if (funcType->getNumParams() == 0) {
auto result = solveWithNewBaseOrName(funcType->getResult(), member);
// If there is indeed a member with given name in result type
// let's return, otherwise let's fall-through and report
// this problem as a missing member.
if (result == SolutionKind::Solved)
return recordFix(InsertExplicitCall::create(
*this, getConstraintLocator(
locator, ConstraintLocator::MemberRefBase)))
? SolutionKind::Error
: SolutionKind::Solved;
}
}
// Instead of using subscript operator spelled out `subscript` directly.
if (member.getBaseName() == getTokenText(tok::kw_subscript)) {
auto result =
solveWithNewBaseOrName(baseTy, DeclNameRef::createSubscript());
// Looks like it was indeed meant to be a subscript operator.
if (result == SolutionKind::Solved)
return recordFix(UseSubscriptOperator::create(*this, locator))
? SolutionKind::Error
: SolutionKind::Solved;
}
// FIXME(diagnostics): This is more of a hack than anything.
// Let's not try to suggest that there is no member related to an
// obscure underscored type, the real problem would be somewhere
// else. This helps to diagnose pattern matching cases.
{
if (auto *metatype = baseTy->getAs<MetatypeType>()) {
auto instanceTy = metatype->getInstanceType();
if (auto *NTD = instanceTy->getAnyNominal()) {
if (NTD->getName() == getASTContext().Id_OptionalNilComparisonType)
return SolutionKind::Error;
}
}
}
result = performMemberLookup(kind, member, baseTy, functionRefKind, locator,
/*includeInaccessibleMembers*/ true);
// FIXME(diagnostics): If there were no viable results, but there are
// unviable ones, we'd have to introduce fix for each specific problem.
if (!result.UnviableCandidates.empty())
return SolutionKind::Error;
// Since member with given base and name doesn't exist, let's try to
// fake its presence based on use, that makes it possible to diagnose
// problems related to member lookup more precisely.
return fixMissingMember(origBaseTy, memberTy, locator);
}
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyValueWitnessConstraint(
ConstraintKind kind, Type baseType, ValueDecl *requirement, Type memberType,
DeclContext *useDC, FunctionRefKind functionRefKind,
TypeMatchOptions flags, ConstraintLocatorBuilder locator) {
// We'd need to record original base type because it might be a type
// variable representing another missing member.
auto origBaseType = baseType;
auto formUnsolved = [&] {
// If requested, generate a constraint.
if (flags.contains(TMF_GenerateConstraints)) {
auto *witnessConstraint = Constraint::createValueWitness(
*this, kind, origBaseType, memberType, requirement, useDC,
functionRefKind, getConstraintLocator(locator));
addUnsolvedConstraint(witnessConstraint);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
auto fail = [&] {
// The constraint failed, so mark the member type as a "hole".
// We cannot do anything further here.
if (!shouldAttemptFixes())
return SolutionKind::Error;
recordAnyTypeVarAsPotentialHole(memberType);
return SolutionKind::Solved;
};
// Resolve the base type, if we can. If we can't resolve the base type,
// then we can't solve this constraint.
Type baseObjectType = getFixedTypeRecursive(
baseType, flags, /*wantRValue=*/true);
if (baseObjectType->isTypeVariableOrMember()) {
return formUnsolved();
}
// If base type is an existential, let's open it before checking
// conformance.
if (baseObjectType->isExistentialType()) {
baseObjectType =
OpenedArchetypeType::get(baseObjectType->getCanonicalType(),
useDC->getGenericSignatureOfContext());
}
// Check conformance to the protocol. If it doesn't conform, this constraint
// fails. Don't attempt to fix it.
// FIXME: Look in the constraint system to see if we've resolved the
// conformance already?
auto proto = requirement->getDeclContext()->getSelfProtocolDecl();
assert(proto && "Value witness constraint for a non-requirement");
auto conformance = lookupConformance(baseObjectType, proto);
if (!conformance)
return fail();
// Reference the requirement.
Type resolvedBaseType = simplifyType(baseType, flags);
if (resolvedBaseType->isTypeVariableOrMember())
return formUnsolved();
auto witness =
conformance.getWitnessByName(baseObjectType, requirement->getName());
if (!witness)
return fail();
auto choice = OverloadChoice(resolvedBaseType, witness.getDecl(), functionRefKind);
resolveOverload(getConstraintLocator(locator), memberType, choice,
useDC);
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyDefaultableConstraint(
Type first, Type second, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
first = getFixedTypeRecursive(first, flags, true);
if (first->isTypeVariableOrMember()) {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::Defaultable, first, second,
getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
// Otherwise, any type is fine.
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyFallbackTypeConstraint(
Type defaultableType, Type fallbackType,
ArrayRef<TypeVariableType *> referencedVars, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
defaultableType =
getFixedTypeRecursive(defaultableType, flags, /*wantRValue=*/true);
if (defaultableType->isTypeVariableOrMember()) {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(Constraint::create(
*this, ConstraintKind::FallbackType, defaultableType, fallbackType,
getConstraintLocator(locator), referencedVars));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
// Otherwise, any type is fine.
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyPropertyWrapperConstraint(
Type wrapperType, Type wrappedValueType, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
wrapperType = getFixedTypeRecursive(wrapperType, flags, /*wantRValue=*/true);
auto *loc = getConstraintLocator(locator);
if (wrapperType->isTypeVariableOrMember()) {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(Constraint::create(
*this, ConstraintKind::PropertyWrapper, wrapperType, wrappedValueType, loc));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
// If the wrapper type is a hole or a dependent member with no type variables,
// don't record a fix, because this indicates that there was an error
// elsewhere in the constraint system.
if (wrapperType->isPlaceholder() || wrapperType->is<DependentMemberType>())
return SolutionKind::Solved;
auto *wrappedVar = getAsDecl<VarDecl>(locator.getAnchor());
assert(wrappedVar && wrappedVar->hasAttachedPropertyWrapper());
// The wrapper type must be a property wrapper.
auto *nominal = wrapperType->getDesugaredType()->getAnyNominal();
if (!(nominal && nominal->getAttrs().hasAttribute<PropertyWrapperAttr>())) {
if (shouldAttemptFixes()) {
auto *fix = AllowInvalidPropertyWrapperType::create(
*this, wrapperType, getConstraintLocator(locator));
if (!recordFix(fix))
return SolutionKind::Solved;
}
return SolutionKind::Error;
}
auto typeInfo = nominal->getPropertyWrapperTypeInfo();
// Implicit property wrappers must support projected-value initialization.
if (wrappedVar->hasImplicitPropertyWrapper() &&
!(typeInfo.projectedValueVar && typeInfo.hasProjectedValueInit)) {
if (shouldAttemptFixes()) {
auto *fix = RemoveProjectedValueArgument::create(
*this, wrapperType, cast<ParamDecl>(wrappedVar), getConstraintLocator(locator));
if (!recordFix(fix))
return SolutionKind::Solved;
}
return SolutionKind::Error;
}
auto resolvedType = wrapperType->getTypeOfMember(DC->getParentModule(), typeInfo.valueVar);
if (typeInfo.valueVar->isSettable(nullptr) && typeInfo.valueVar->isSetterAccessibleFrom(DC) &&
!typeInfo.valueVar->isSetterMutating()) {
resolvedType = LValueType::get(resolvedType);
}
addConstraint(ConstraintKind::Bind, wrappedValueType, resolvedType, locator);
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyOneWayConstraint(
ConstraintKind kind,
Type first, Type second, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// Determine whether the second type can be fully simplified. Only then
// will this constraint be resolved.
Type secondSimplified = simplifyType(second);
if (secondSimplified->hasTypeVariable()) {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, kind, first, second,
getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
// Propagate holes through one-way constraints.
if (secondSimplified->isPlaceholder()) {
recordAnyTypeVarAsPotentialHole(first);
return SolutionKind::Solved;
}
// Translate this constraint into an equality or bind-parameter constraint,
// as appropriate.
if (kind == ConstraintKind::OneWayEqual) {
return matchTypes(first, secondSimplified, ConstraintKind::Equal, flags,
locator);
}
assert(kind == ConstraintKind::OneWayBindParam);
return matchTypes(
secondSimplified, first, ConstraintKind::BindParam, flags, locator);
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyUnresolvedMemberChainBaseConstraint(
Type first, Type second, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto resultTy = getFixedTypeRecursive(first, flags, /*wantRValue=*/true);
auto baseTy = getFixedTypeRecursive(second, flags, /*wantRValue=*/true);
if (baseTy->isTypeVariableOrMember() || resultTy->isTypeVariableOrMember()) {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::UnresolvedMemberChainBase,
first, second, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
if (baseTy->is<ProtocolType>()) {
auto *baseExpr =
castToExpr<UnresolvedMemberChainResultExpr>(locator.getAnchor())
->getChainBase();
auto *memberLoc =
getConstraintLocator(baseExpr, ConstraintLocator::UnresolvedMember);
if (shouldAttemptFixes() && hasFixFor(memberLoc))
return SolutionKind::Solved;
auto *memberRef = findResolvedMemberRef(memberLoc);
if (memberRef && (memberRef->isStatic() || isa<TypeAliasDecl>(memberRef))) {
return simplifyConformsToConstraint(
resultTy, baseTy, ConstraintKind::ConformsTo,
getConstraintLocator(memberLoc, ConstraintLocator::MemberRefBase),
flags);
}
}
return matchTypes(baseTy, resultTy, ConstraintKind::Equal, flags, locator);
}
static Type getOpenedResultBuilderTypeFor(ConstraintSystem &cs,
ConstraintLocatorBuilder locator) {
auto lastElt = locator.last();
if (!lastElt)
return Type();
auto argToParamElt = lastElt->getAs<LocatorPathElt::ApplyArgToParam>();
if (!argToParamElt)
return Type();
auto *calleeLocator = cs.getCalleeLocator(cs.getConstraintLocator(locator));
auto selectedOverload = cs.findSelectedOverloadFor(calleeLocator);
if (!(selectedOverload &&
(selectedOverload->choice.getKind() == OverloadChoiceKind::Decl ||
selectedOverload->choice.getKind() ==
OverloadChoiceKind::DeclViaUnwrappedOptional)))
return Type();
auto *choice = selectedOverload->choice.getDecl();
bool skipCurriedSelf = hasAppliedSelf(cs, selectedOverload->choice);
if (choice->hasCurriedSelf() && !skipCurriedSelf)
return Type();
if (!choice->hasParameterList())
return Type();
auto *PD = getParameterAt(choice, argToParamElt->getParamIdx());
assert(PD);
auto builderType = PD->getResultBuilderType();
if (!builderType)
return Type();
// If the builder type has a type parameter, substitute in the type
// variables.
if (builderType->hasTypeParameter()) {
// Find the opened type for this callee and substitute in the type
// parameters.
auto substitutions = cs.getOpenedTypes(calleeLocator);
if (!substitutions.empty()) {
OpenedTypeMap replacements(substitutions.begin(), substitutions.end());
builderType = cs.openType(builderType, replacements, locator);
}
assert(!builderType->hasTypeParameter());
}
return builderType;
}
bool ConstraintSystem::resolveClosure(TypeVariableType *typeVar,
Type contextualType,
ConstraintLocatorBuilder locator) {
auto *closureLocator = typeVar->getImpl().getLocator();
auto *closure = castToExpr<ClosureExpr>(closureLocator->getAnchor());
auto *inferredClosureType = getClosureType(closure);
// Note if this closure is isolated by preconcurrency.
if (hasPreconcurrencyCallee(locator))
preconcurrencyClosures.insert(closure);
// Let's look through all optionals associated with contextual
// type to make it possible to infer parameter/result type of
// the closure faster e.g.:
//
// func test(_: ((Int) -> Void)?) {
// ...
// }
//
// test { $0 + ... }
//
// In this case dropping optionality from contextual type
// `((Int) -> Void)?` allows `resolveClosure` to infer type
// of `$0` directly (via `getContextualParamAt`) instead of
// having to use type variable inference mechanism.
contextualType = contextualType->lookThroughAllOptionalTypes();
auto getContextualParamAt =
[&contextualType, &inferredClosureType](
unsigned index) -> std::optional<AnyFunctionType::Param> {
auto *fnType = contextualType->getAs<FunctionType>();
if (!fnType)
return std::nullopt;
auto numContextualParams = fnType->getNumParams();
if (numContextualParams == 1) {
const auto ¶m = fnType->getParams()[0];
if (auto *tuple = param.getPlainType()->getAs<TupleType>()) {
// If arity is the same it's a tuple splat which is allowed
// for closures (see SE-0110 for more details):
//
// func test(_: ((Int, Int)) -> Void) {}
// test { (arg, _) in
// ...
// }
if (tuple->getNumElements() == inferredClosureType->getNumParams() &&
param.getParameterFlags().isNone()) {
const auto &elt = tuple->getElement(index);
return AnyFunctionType::Param(elt.getType(), elt.getName());
}
return std::nullopt;
}
}
if (numContextualParams != inferredClosureType->getNumParams() ||
numContextualParams <= index)
return std::nullopt;
return fnType->getParams()[index];
};
// Check whether given contextual parameter type could be
// used to bind external closure parameter type.
auto isSuitableContextualType = [](Type contextualTy) {
// We need to wait until contextual type
// is fully resolved before binding it.
if (contextualTy->isTypeVariableOrMember())
return false;
// Cannot propagate pack expansion type from context,
// it has to be handled by type matching logic.
if (isPackExpansionType(contextualTy))
return false;
// If contextual type has an error, let's wait for inference,
// otherwise contextual would interfere with diagnostics.
if (contextualTy->hasError())
return false;
if (isa<TypeAliasType>(contextualTy.getPointer())) {
auto underlyingTy = contextualTy->getDesugaredType();
// FIXME: typealias pointing to an existential type is special
// because if the typealias has type variables then we'd end up
// opening existential from a type with unresolved generic
// parameter(s), which CSApply can't currently simplify while
// building type-checked AST because `OpenedArchetypeType` doesn't
// propagate flags. Example is as simple as `{ $0.description }`
// where `$0` is `Error` that inferred from a (generic) typealias.
if (underlyingTy->isExistentialType() && contextualTy->hasTypeVariable())
return false;
}
return true;
};
// If contextual type is not a function type or `Any` and this
// closure is used as an argument, let's skip resolution.
//
// Doing so improves performance if closure is passed as an argument
// to a (heavily) overloaded declaration, avoid unrelated errors,
// propagate holes, and record a more impactful fix.
if (!contextualType->isTypeVariableOrMember() &&
!(contextualType->is<FunctionType>() || contextualType->isAny()) &&
locator.endsWith<LocatorPathElt::ApplyArgToParam>()) {
if (!shouldAttemptFixes())
return false;
assignFixedType(typeVar, PlaceholderType::get(getASTContext(), typeVar),
closureLocator);
recordTypeVariablesAsHoles(inferredClosureType);
return !recordFix(
AllowArgumentMismatch::create(*this, typeVar, contextualType,
getConstraintLocator(locator)),
/*impact=*/15);
}
// Determine whether a result builder will be applied.
auto resultBuilderType = getOpenedResultBuilderTypeFor(*this, locator);
// Determine whether to introduce one-way constraints between the parameter's
// type as seen in the body of the closure and the external parameter
// type.
bool oneWayConstraints =
getASTContext().LangOpts.hasFeature(Feature::OneWayClosureParameters);
auto *paramList = closure->getParameters();
SmallVector<AnyFunctionType::Param, 4> parameters;
bool hasIsolatedParam = false;
for (unsigned i = 0, n = paramList->size(); i != n; ++i) {
auto param = inferredClosureType->getParams()[i];
auto *paramDecl = paramList->get(i);
// In case of anonymous or name-only parameters, let's infer
// inout/variadic/isolated flags from context, that helps to propagate
// type information into the internal type of the parameter and reduces
// inference solver has to make.
if (!paramDecl->getTypeRepr()) {
if (auto contextualParam = getContextualParamAt(i)) {
auto flags = param.getParameterFlags();
// Note when a parameter is inferred to be isolated.
if (contextualParam->isIsolated() && !flags.isIsolated() && paramDecl)
isolatedParams.insert(paramDecl);
param = param.withFlags(flags.withInOut(contextualParam->isInOut())
.withVariadic(contextualParam->isVariadic())
.withIsolated(contextualParam->isIsolated())
.withSending(contextualParam->isSending()));
}
}
if (paramDecl->hasAttachedPropertyWrapper()) {
Type backingType;
Type wrappedValueType;
if (paramDecl->hasImplicitPropertyWrapper()) {
if (auto contextualType = getContextualParamAt(i)) {
backingType = contextualType->getPlainType();
} else {
// There may not be a contextual parameter type if the contextual
// type is not a function type or if closure body declares too many
// parameters.
auto *paramLoc =
getConstraintLocator(closure, LocatorPathElt::TupleElement(i));
backingType = createTypeVariable(paramLoc, TVO_CanBindToHole);
}
wrappedValueType = createTypeVariable(getConstraintLocator(paramDecl),
TVO_CanBindToHole | TVO_CanBindToLValue);
} else {
auto *wrapperAttr = paramDecl->getOutermostAttachedPropertyWrapper();
auto wrapperType = paramDecl->getAttachedPropertyWrapperType(0);
backingType = replaceInferableTypesWithTypeVars(
wrapperType, getConstraintLocator(wrapperAttr->getTypeRepr()));
wrappedValueType = computeWrappedValueType(paramDecl, backingType);
}
auto *backingVar = paramDecl->getPropertyWrapperBackingProperty();
setType(backingVar, backingType);
auto *localWrappedVar = paramDecl->getPropertyWrapperWrappedValueVar();
setType(localWrappedVar, wrappedValueType);
if (auto *projection = paramDecl->getPropertyWrapperProjectionVar()) {
setType(projection, computeProjectedValueType(paramDecl, backingType));
}
if (!paramDecl->getName().hasDollarPrefix()) {
if (generateWrappedPropertyTypeConstraints(paramDecl, backingType,
param.getParameterType()))
return false;
}
auto result = applyPropertyWrapperToParameter(backingType, param.getParameterType(),
paramDecl, paramDecl->getName(),
ConstraintKind::Equal,
getConstraintLocator(closure));
if (result.isFailure())
return false;
}
Type internalType;
if (paramDecl->getTypeRepr()) {
// Internal type is the type used in the body of the closure,
// so "external" type translates to it as follows:
// - `Int...` -> `[Int]`,
// - `inout Int` -> `@lvalue Int`.
internalType = param.getParameterType();
// When there are type variables in the type and we have enabled
// one-way constraints, create a fresh type variable to handle the
// binding.
if (oneWayConstraints && internalType->hasTypeVariable()) {
auto *paramLoc =
getConstraintLocator(closure, LocatorPathElt::TupleElement(i));
auto *typeVar = createTypeVariable(paramLoc, TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
addConstraint(
ConstraintKind::OneWayBindParam, typeVar, internalType, paramLoc);
internalType = typeVar;
}
} else {
auto *paramLoc =
getConstraintLocator(closure, LocatorPathElt::TupleElement(i));
auto *typeVar = createTypeVariable(paramLoc, TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
// If external parameter is variadic it translates into an array in
// the body of the closure.
internalType =
param.isVariadic() ? VariadicSequenceType::get(typeVar) : Type(typeVar);
auto externalType = param.getOldType();
// Performance optimization.
//
// If there is a concrete contextual type we could use, let's bind
// it to the external type right away because internal type has to
// be equal to that type anyway (through `BindParam` on external type
// i.e. <internal> bind param <external> conv <concrete contextual>).
//
// Note: it's correct to avoid doing this, but it would result
// in (a lot) more checking since solver would have to re-discover,
// re-attempt and fail parameter type while solving for overloaded
// choices in the body.
if (auto contextualParam = getContextualParamAt(i)) {
auto paramTy = simplifyType(contextualParam->getOldType());
if (isSuitableContextualType(paramTy))
addConstraint(ConstraintKind::Bind, externalType, paramTy, paramLoc);
}
if (oneWayConstraints) {
addConstraint(
ConstraintKind::OneWayBindParam, typeVar, externalType, paramLoc);
} else {
addConstraint(
ConstraintKind::BindParam, externalType, typeVar, paramLoc);
}
}
hasIsolatedParam |= param.isIsolated();
setType(paramDecl, internalType);
parameters.push_back(param);
}
// Propagate @Sendable from the contextual type to the closure.
auto closureExtInfo = inferredClosureType->getExtInfo();
if (auto contextualFnType = contextualType->getAs<FunctionType>()) {
if (contextualFnType->isSendable())
closureExtInfo = closureExtInfo.withSendable();
}
// Propagate sending result from the contextual type to the closure.
if (auto contextualFnType = contextualType->getAs<FunctionType>()) {
if (contextualFnType->hasExtInfo() && contextualFnType->hasSendingResult())
closureExtInfo = closureExtInfo.withSendingResult();
}
// Isolated parameters override any other kind of isolation we might infer.
if (hasIsolatedParam) {
closureExtInfo = closureExtInfo.withIsolation(
FunctionTypeIsolation::forParameter());
}
auto closureType =
FunctionType::get(parameters, inferredClosureType->getResult(),
closureExtInfo);
assignFixedType(typeVar, closureType, closureLocator);
// If there is a result builder to apply, do so now.
if (resultBuilderType) {
if (auto result = matchResultBuilder(
closure, resultBuilderType, closureType->getResult(),
ConstraintKind::Conversion, contextualType, locator)) {
return result->isSuccess();
}
}
SyntacticElementTarget target(closure, contextualType);
setTargetFor(closure, target);
// Generate constraints from the body of this closure.
return !generateConstraints(AnyFunctionRef{closure}, closure->getBody());
}
bool ConstraintSystem::resolvePackExpansion(TypeVariableType *typeVar,
Type contextualType) {
assert(typeVar->getImpl().isPackExpansion());
auto *locator = typeVar->getImpl().getLocator();
Type openedExpansionType =
locator->castLastElementTo<LocatorPathElt::PackExpansionType>()
.getOpenedType();
assignFixedType(typeVar, openedExpansionType, locator);
return true;
}
bool ConstraintSystem::resolveTapBody(TypeVariableType *typeVar,
Type contextualType,
ConstraintLocatorBuilder locator) {
auto *tapLoc = typeVar->getImpl().getLocator();
auto *tapExpr = castToExpr<TapExpr>(tapLoc->getAnchor());
// Assign a type to tap expression itself.
assignFixedType(typeVar, contextualType, getConstraintLocator(locator));
// Set type to `$interpolation` variable declared in the body of tap
// expression.
setType(tapExpr->getVar(), contextualType);
// With all of the contextual information recorded in the constraint system,
// it's time to generate constraints for the body of this tap expression.
return !generateConstraints(tapExpr);
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyDynamicTypeOfConstraint(
Type type1, Type type2,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
// Local function to form an unsolved result.
auto formUnsolved = [&] {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::DynamicTypeOf, type1, type2,
getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// Solve forward.
type2 = getFixedTypeRecursive(type2, flags, /*wantRValue=*/true);
if (!type2->isTypeVariableOrMember()) {
Type dynamicType2;
if (type2->isAnyExistentialType()) {
dynamicType2 = ExistentialMetatypeType::get(type2);
} else {
dynamicType2 = MetatypeType::get(type2);
}
return matchTypes(type1, dynamicType2, ConstraintKind::Bind, subflags,
locator);
}
// Okay, can't solve forward. See what we can do backwards.
type1 = getFixedTypeRecursive(type1, flags, /*wantRValue=*/true);
if (type1->isTypeVariableOrMember())
return formUnsolved();
// If we have an existential metatype, that's good enough to solve
// the constraint.
if (auto metatype1 = type1->getAs<ExistentialMetatypeType>())
return matchTypes(metatype1->getInstanceType(), type2,
ConstraintKind::Bind,
subflags, locator);
// If we have a normal metatype, we can't solve backwards unless we
// know what kind of object it is.
if (auto metatype1 = type1->getAs<MetatypeType>()) {
Type instanceType1 = getFixedTypeRecursive(metatype1->getInstanceType(),
true);
if (instanceType1->isTypeVariableOrMember())
return formUnsolved();
return matchTypes(instanceType1, type2, ConstraintKind::Bind, subflags,
locator);
}
// It's definitely not either kind of metatype, so we can
// report failure right away.
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyBridgingConstraint(Type type1,
Type type2,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
/// Form an unresolved result.
auto formUnsolved = [&] {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::BridgingConversion, type1,
type2, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// Local function to look through optional types. It produces the
// fully-unwrapped type and a count of the total # of optional types that were
// unwrapped.
auto unwrapType = [&](Type type) -> std::pair<Type, unsigned> {
unsigned count = 0;
while (Type objectType = type->getOptionalObjectType()) {
++count;
TypeMatchOptions unusedOptions;
type = getFixedTypeRecursive(objectType, unusedOptions, /*wantRValue=*/true);
}
return { type, count };
};
const auto rawType1 = type1;
type1 = getFixedTypeRecursive(type1, flags, /*wantRValue=*/true);
type2 = getFixedTypeRecursive(type2, flags, /*wantRValue=*/true);
if (type1->isTypeVariableOrMember() || type2->isTypeVariableOrMember())
return formUnsolved();
// Noncopyable & Nonescapable types can't be involved in bridging conversions
// since a bridged type assumes such abilities are granted.
if (!type1->hasTypeVariable()
&& (type1->isNoncopyable() || !type1->isEscapable())) {
return SolutionKind::Error;
}
Type unwrappedFromType;
unsigned numFromOptionals;
std::tie(unwrappedFromType, numFromOptionals) = unwrapType(type1);
Type unwrappedToType;
unsigned numToOptionals;
std::tie(unwrappedToType, numToOptionals) = unwrapType(type2);
if (unwrappedFromType->isTypeVariableOrMember() ||
unwrappedToType->isTypeVariableOrMember())
return formUnsolved();
// Update the score.
increaseScore(SK_UserConversion, locator); // FIXME: Use separate score kind?
if (worseThanBestSolution()) {
return SolutionKind::Error;
}
// Local function to count the optional injections that will be performed
// after the bridging conversion.
auto countOptionalInjections = [&] {
if (numToOptionals > numFromOptionals)
increaseScore(SK_ValueToOptional, locator,
numToOptionals - numFromOptionals);
};
// Anything can be explicitly converted to AnyObject using the universal
// bridging conversion. This allows both extraneous optionals in the source
// (because optionals themselves can be boxed for AnyObject) and in the
// destination (we'll perform the extra injections at the end).
if (unwrappedToType->isAnyObject()) {
countOptionalInjections();
return SolutionKind::Solved;
}
// In a previous version of Swift, we could accidentally drop the coercion
// constraint in certain cases. In most cases this led to either miscompiles
// or crashes later down the pipeline, but for coercions between collections
// we generated somewhat reasonable code that performed a force cast. To
// maintain compatibility with that behavior, allow the coercion between
// two collections, but add a warning fix telling the user to use as! or as?
// instead. In Swift 6 mode, this becomes an error.
//
// We only need to perform this compatibility logic if this is a coercion of
// something that isn't a collection expr (as collection exprs would have
// crashed in codegen due to CSApply peepholing them). Additionally, the LHS
// type must be a (potentially optional) type variable, as only such a
// constraint could have been previously been left unsolved.
auto canUseCompatFix = [&]() {
if (Context.isSwiftVersionAtLeast(6))
return false;
if (!rawType1->lookThroughAllOptionalTypes()->isTypeVariableOrMember())
return false;
SmallVector<LocatorPathElt, 4> elts;
auto anchor = locator.getLocatorParts(elts);
if (elts.empty() || !elts.back().is<LocatorPathElt::CoercionOperand>())
return false;
auto *coercion = getAsExpr<CoerceExpr>(anchor);
if (!coercion)
return false;
auto *subject = coercion->getSubExpr();
while (auto *paren = dyn_cast<ParenExpr>(subject))
subject = paren->getSubExpr();
return !isa<CollectionExpr>(subject);
}();
// Unless we're allowing the collection compatibility fix, the source cannot
// be more optional than the destination.
if (!canUseCompatFix && numFromOptionals > numToOptionals)
return SolutionKind::Error;
auto makeCollectionResult = [&](SolutionKind result) -> SolutionKind {
// If we encountered an error and can use the compatibility fix, do so.
if (canUseCompatFix) {
if (numFromOptionals > numToOptionals || result == SolutionKind::Error) {
auto *loc = getConstraintLocator(locator);
auto *fix = AllowCoercionToForceCast::create(*this, type1, type2, loc);
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
}
return result;
};
// Bridging the elements of an array.
if (auto fromElement = unwrappedFromType->isArrayType()) {
if (auto toElement = unwrappedToType->isArrayType()) {
countOptionalInjections();
auto result = simplifyBridgingConstraint(
fromElement, toElement, subflags,
locator.withPathElement(LocatorPathElt::GenericArgument(0)));
return makeCollectionResult(result);
}
}
// Bridging the keys/values of a dictionary.
if (auto fromKeyValue = isDictionaryType(unwrappedFromType)) {
if (auto toKeyValue = isDictionaryType(unwrappedToType)) {
ConstraintFix *compatFix = nullptr;
if (canUseCompatFix) {
compatFix = AllowCoercionToForceCast::create(
*this, type1, type2, getConstraintLocator(locator));
}
addExplicitConversionConstraint(fromKeyValue->first, toKeyValue->first,
ForgetChoice,
locator.withPathElement(
LocatorPathElt::GenericArgument(0)),
compatFix);
addExplicitConversionConstraint(fromKeyValue->second, toKeyValue->second,
ForgetChoice,
locator.withPathElement(
LocatorPathElt::GenericArgument(1)),
compatFix);
countOptionalInjections();
return makeCollectionResult(SolutionKind::Solved);
}
}
// Bridging the elements of a set.
if (auto fromElement = isSetType(unwrappedFromType)) {
if (auto toElement = isSetType(unwrappedToType)) {
countOptionalInjections();
auto result = simplifyBridgingConstraint(
*fromElement, *toElement, subflags,
locator.withPathElement(LocatorPathElt::GenericArgument(0)));
return makeCollectionResult(result);
}
}
// The source cannot be more optional than the destination, because bridging
// conversions don't allow us to implicitly check for a value in the optional.
if (numFromOptionals > numToOptionals) {
return SolutionKind::Error;
}
// Explicit bridging from a value type to an Objective-C class type.
auto &ctx = getASTContext();
if (unwrappedFromType->isPotentiallyBridgedValueType() &&
(unwrappedToType->isBridgeableObjectType() ||
(unwrappedToType->isExistentialType() &&
!unwrappedToType->isAny()))) {
countOptionalInjections();
if (Type classType = ctx.getBridgedToObjC(DC, unwrappedFromType)) {
return matchTypes(classType, unwrappedToType, ConstraintKind::Conversion,
subflags, locator);
}
}
// Bridging from an Objective-C class type to a value type.
// Note that specifically require a class or class-constrained archetype
// here, because archetypes cannot be bridged.
if (unwrappedFromType->mayHaveSuperclass() &&
unwrappedToType->isPotentiallyBridgedValueType()) {
Type bridgedValueType;
if (auto objcClass = ctx.getBridgedToObjC(DC, unwrappedToType,
&bridgedValueType)) {
// Bridging NSNumber to NSValue is one-way, since there are multiple Swift
// value types that bridge to those object types. It requires a checked
// cast to get back.
if (ctx.isObjCClassWithMultipleSwiftBridgedTypes(objcClass))
return SolutionKind::Error;
// If the bridged value type is generic, the generic arguments
// must either match or be bridged.
// FIXME: This should be an associated type of the protocol.
auto &ctx = getASTContext();
if (auto fromBGT = unwrappedToType->getAs<BoundGenericType>()) {
if (fromBGT->isArray()) {
// [AnyObject]
addConstraint(ConstraintKind::Bind, fromBGT->getGenericArgs()[0],
ctx.getAnyObjectType(),
getConstraintLocator(locator.withPathElement(
LocatorPathElt::GenericArgument(0))));
} else if (fromBGT->isDictionary()) {
// [NSObject : AnyObject]
auto nsObjectType = ctx.getNSObjectType();
if (!nsObjectType) {
// Not a bridging case. Should we detect this earlier?
return SolutionKind::Error;
}
addConstraint(ConstraintKind::Bind, fromBGT->getGenericArgs()[0],
nsObjectType,
getConstraintLocator(
locator.withPathElement(
LocatorPathElt::GenericArgument(0))));
addConstraint(ConstraintKind::Bind, fromBGT->getGenericArgs()[1],
ctx.getAnyObjectType(),
getConstraintLocator(
locator.withPathElement(
LocatorPathElt::GenericArgument(1))));
} else if (fromBGT->isSet()) {
auto nsObjectType = ctx.getNSObjectType();
if (!nsObjectType) {
// Not a bridging case. Should we detect this earlier?
return SolutionKind::Error;
}
addConstraint(ConstraintKind::Bind, fromBGT->getGenericArgs()[0],
nsObjectType,
getConstraintLocator(
locator.withPathElement(
LocatorPathElt::GenericArgument(0))));
} else {
// Nothing special to do; matchTypes will match generic arguments.
}
}
// Make sure we have the bridged value type.
if (matchTypes(unwrappedToType, bridgedValueType, ConstraintKind::Bind,
subflags, locator).isFailure())
return SolutionKind::Error;
countOptionalInjections();
return matchTypes(unwrappedFromType, objcClass, ConstraintKind::Subtype,
subflags, locator);
}
}
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyEscapableFunctionOfConstraint(
Type type1, Type type2,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
// Local function to form an unsolved result.
auto formUnsolved = [&] {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::EscapableFunctionOf,
type1, type2, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
type2 = getFixedTypeRecursive(type2, flags, /*wantRValue=*/true);
if (auto fn2 = type2->getAs<FunctionType>()) {
// Solve forward by binding the other type variable to the escapable
// variation of this type.
auto fn1 = fn2->withExtInfo(fn2->getExtInfo().withNoEscape(false));
return matchTypes(type1, fn1, ConstraintKind::Bind, subflags, locator);
}
if (!type2->isTypeVariableOrMember())
// We definitely don't have a function, so bail.
return SolutionKind::Error;
type1 = getFixedTypeRecursive(type1, flags, /*wantRValue=*/true);
if (auto fn1 = type1->getAs<FunctionType>()) {
// We should have the escaping end of the relation.
if (fn1->getExtInfo().isNoEscape())
return SolutionKind::Error;
// Solve backward by binding the other type variable to the noescape
// variation of this type.
auto fn2 = fn1->withExtInfo(fn1->getExtInfo().withNoEscape(true));
return matchTypes(type2, fn2, ConstraintKind::Bind, subflags, locator);
}
if (!type1->isTypeVariableOrMember())
// We definitely don't have a function, so bail.
return SolutionKind::Error;
return formUnsolved();
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyOpenedExistentialOfConstraint(
Type type1, Type type2,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
type2 = getFixedTypeRecursive(type2, flags, /*wantRValue=*/true);
if (type2->isAnyExistentialType()) {
// We have the existential side. Produce an opened archetype and bind
// type1 to it.
Type openedTy = openExistentialType(type2, getConstraintLocator(locator))
.first;
return matchTypes(type1, openedTy, ConstraintKind::Bind, subflags, locator);
}
if (!type2->isTypeVariableOrMember())
// We definitely don't have an existential, so bail.
return SolutionKind::Error;
// If type1 is constrained to anything concrete, the constraint fails.
// It can only be bound to a type we opened for it.
type1 = getFixedTypeRecursive(type1, flags, /*wantRValue=*/true);
if (!type1->isTypeVariableOrMember())
return SolutionKind::Error;
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this, ConstraintKind::OpenedExistentialOf,
type1, type2, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyKeyPathConstraint(
Type keyPathTy,
Type rootTy,
Type valueTy,
ArrayRef<TypeVariableType *> componentTypeVars,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto subflags = getDefaultDecompositionOptions(flags);
keyPathTy = getFixedTypeRecursive(keyPathTy, /*want rvalue*/ true);
auto formUnsolved = [&]() -> SolutionKind {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(Constraint::create(
*this, ConstraintKind::KeyPath, keyPathTy, rootTy, valueTy,
getConstraintLocator(locator), componentTypeVars));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
if (keyPathTy->isTypeVariableOrMember())
return formUnsolved();
auto tryMatchRootAndValueFromContextualType = [&](Type contextualTy) -> bool {
Type contextualRootTy = Type(), contextualValueTy = Type();
// Placeholders are only allowed in the diagnostic mode so it's
// okay to simply return `true` here.
if (contextualTy->isPlaceholder())
return true;
// Situations like `any KeyPath<...> & Sendable`.
if (contextualTy->isExistentialType()) {
contextualTy = contextualTy->getExistentialLayout().explicitSuperclass;
assert(contextualTy);
}
if (auto bgt = contextualTy->getAs<BoundGenericType>()) {
// We can get root and value from a concrete key path type.
assert(bgt->isKeyPath() || bgt->isWritableKeyPath() ||
bgt->isReferenceWritableKeyPath());
contextualRootTy = bgt->getGenericArgs()[0];
contextualValueTy = bgt->getGenericArgs()[1];
}
if (auto fnTy = contextualTy->getAs<FunctionType>()) {
assert(fnTy->getParams().size() == 1);
// Key paths may be converted to a function of compatible type. We will
// later form from this key path an implicit closure of the form
// `{ root in root[keyPath: kp] }` so any conversions that are valid with
// a source type of `(Root) -> Value` should be valid here too.
auto rootParam = AnyFunctionType::Param(rootTy);
auto kpFnTy = FunctionType::get(rootParam, valueTy, fnTy->getExtInfo());
// Note: because the keypath is applied to `root` as a parameter internal
// to the closure, we use the function parameter's "parameter type" rather
// than the raw type. This enables things like:
// ```
// let countKeyPath: (String...) -> Int = \.count
// ```
auto paramTy = fnTy->getParams()[0].getParameterType();
auto paramParam = AnyFunctionType::Param(paramTy);
auto paramFnTy = FunctionType::get(paramParam, fnTy->getResult(),
fnTy->getExtInfo());
return !matchTypes(kpFnTy, paramFnTy, ConstraintKind::Conversion,
subflags, locator).isFailure();
}
assert(contextualRootTy && contextualValueTy);
if (matchTypes(rootTy, contextualRootTy, ConstraintKind::Bind, subflags,
locator.withPathElement(ConstraintLocator::KeyPathRoot))
.isFailure())
return false;
if (matchTypes(valueTy, contextualValueTy, ConstraintKind::Bind, subflags,
locator.withPathElement(ConstraintLocator::KeyPathValue))
.isFailure())
return false;
return true;
};
// If key path has to be converted to a function, let's check that
// the contextual type has precisely one parameter.
if (auto *fnTy = keyPathTy->getAs<FunctionType>()) {
increaseScore(SK_FunctionConversion, locator);
// Key paths never throw, so if the function has a thrown error type
// that is a type variable, infer it to be Never.
if (auto thrownError = fnTy->getThrownError()) {
if (thrownError->isTypeVariableOrMember()) {
(void)matchTypes(thrownError, getASTContext().getNeverType(),
ConstraintKind::Equal, TMF_GenerateConstraints,
locator);
}
}
if (fnTy->getParams().size() != 1) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
recordAnyTypeVarAsPotentialHole(rootTy);
recordAnyTypeVarAsPotentialHole(valueTy);
auto *fix = AllowMultiArgFuncKeyPathMismatch::create(
*this, fnTy, getConstraintLocator(locator));
// Pretend the keypath type got resolved and move on.
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
}
// If we have a hole somewhere in the key path, the solver won't be able to
// infer the key path type. So let's just assume this is solved.
if (shouldAttemptFixes()) {
auto keyPath = castToExpr<KeyPathExpr>(locator.getAnchor());
if (hasFixFor(getConstraintLocator(keyPath),
FixKind::AllowKeyPathWithoutComponents))
return SolutionKind::Solved;
// If the root type has been bound to a hole, we cannot infer it.
if (getFixedTypeRecursive(rootTy, /*wantRValue*/ true)->isPlaceholder())
return SolutionKind::Solved;
}
return tryMatchRootAndValueFromContextualType(keyPathTy)
? SolutionKind::Solved
: SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyKeyPathApplicationConstraint(
Type keyPathTy,
Type rootTy,
Type valueTy,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
keyPathTy = getFixedTypeRecursive(keyPathTy, flags, /*wantRValue=*/true);
auto unsolved = [&]() -> SolutionKind {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(Constraint::create(*this,
ConstraintKind::KeyPathApplication,
keyPathTy, rootTy, valueTy, getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// When locator points to a KeyPathDynamicMemberLookup, reject the
// key path application.
if (locator.endsWith<LocatorPathElt::KeyPathDynamicMember>())
return SolutionKind::Error;
if (keyPathTy->isAnyKeyPath()) {
// Read-only keypath, whose projected value is upcast to `Any?`.
// The root type can be anything.
Type resultTy = getASTContext().getAnyExistentialType();
resultTy = OptionalType::get(resultTy);
return matchTypes(resultTy, valueTy, ConstraintKind::Bind,
subflags, locator);
}
if (keyPathTy->isPlaceholder()) {
if (rootTy->hasTypeVariable()) {
recordAnyTypeVarAsPotentialHole(rootTy);
}
if (valueTy->hasTypeVariable()) {
recordAnyTypeVarAsPotentialHole(valueTy);
}
return SolutionKind::Solved;
}
if (auto bgt = keyPathTy->getAs<BoundGenericType>()) {
// We have the key path type. Match it to the other ends of the constraint.
auto kpRootTy = bgt->getGenericArgs()[0];
// Try to match the root type.
rootTy = getFixedTypeRecursive(rootTy, flags, /*wantRValue=*/false);
auto matchRoot = [&](ConstraintKind kind) -> bool {
auto rootMatches =
matchTypes(rootTy, kpRootTy, kind, subflags,
locator.withPathElement(LocatorPathElt::KeyPathRoot()));
switch (rootMatches) {
case SolutionKind::Error:
return false;
case SolutionKind::Solved:
return true;
case SolutionKind::Unsolved:
llvm_unreachable("should have generated constraints");
}
llvm_unreachable("unhandled match");
};
if (bgt->isPartialKeyPath()) {
// Read-only keypath, whose projected value is upcast to `Any`.
auto resultTy = getASTContext().getAnyExistentialType();
if (!matchRoot(ConstraintKind::Conversion))
return SolutionKind::Error;
return matchTypes(resultTy, valueTy,
ConstraintKind::Bind, subflags, locator);
}
if (bgt->getGenericArgs().size() < 2)
return SolutionKind::Error;
auto kpValueTy = bgt->getGenericArgs()[1];
/// Solve for an rvalue base.
auto solveRValue = [&]() -> ConstraintSystem::SolutionKind {
// An rvalue base can be converted to a supertype.
return matchTypes(kpValueTy, valueTy,
ConstraintKind::Bind, subflags, locator);
};
/// Solve for a base whose lvalueness is to be determined.
auto solveUnknown = [&]() -> ConstraintSystem::SolutionKind {
if (matchTypes(kpValueTy, valueTy, ConstraintKind::Equal, subflags,
locator).isFailure())
return SolutionKind::Error;
return unsolved();
};
/// Solve for an lvalue base.
auto solveLValue = [&]() -> ConstraintSystem::SolutionKind {
return matchTypes(LValueType::get(kpValueTy), valueTy,
ConstraintKind::Bind, subflags, locator);
};
if (bgt->isKeyPath()) {
// Read-only keypath.
if (!matchRoot(ConstraintKind::Conversion))
return SolutionKind::Error;
return solveRValue();
}
if (bgt->isWritableKeyPath()) {
// Writable keypath. The result can be an lvalue if the root was.
// We can't convert the base without giving up lvalue-ness, though.
if (!matchRoot(ConstraintKind::Equal))
return SolutionKind::Error;
if (rootTy->is<LValueType>())
return solveLValue();
if (rootTy->isTypeVariableOrMember())
// We don't know whether the value is an lvalue yet.
return solveUnknown();
return solveRValue();
}
if (bgt->isReferenceWritableKeyPath()) {
if (!matchRoot(ConstraintKind::Conversion))
return SolutionKind::Error;
// Reference-writable keypath. The result can always be an lvalue.
return solveLValue();
}
// Otherwise, we don't have a key path type at all.
return SolutionKind::Error;
}
if (!keyPathTy->isTypeVariableOrMember()) {
if (shouldAttemptFixes()) {
auto *fix = IgnoreKeyPathSubscriptIndexMismatch::create(
*this, keyPathTy, getConstraintLocator(locator));
recordAnyTypeVarAsPotentialHole(valueTy);
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
return SolutionKind::Error;
}
return unsolved();
}
bool ConstraintSystem::simplifyAppliedOverloadsImpl(
Constraint *disjunction, TypeVariableType *fnTypeVar,
FunctionType *argFnType, unsigned numOptionalUnwraps,
ConstraintLocatorBuilder locator) {
// Don't attempt to filter overloads when solving for code completion
// because presence of code completion token means that any call
// could be malformed e.g. missing arguments e.g. `foo([.#^MEMBER^#`
if (isForCodeCompletion()) {
bool ArgContainsCCTypeVar = Type(argFnType).findIf(isCodeCompletionTypeVar);
if (ArgContainsCCTypeVar || isCodeCompletionTypeVar(fnTypeVar)) {
return false;
}
}
if (shouldAttemptFixes()) {
auto arguments = argFnType->getParams();
bool allHoles =
arguments.size() > 0 &&
llvm::all_of(arguments, [&](const AnyFunctionType::Param &arg) -> bool {
auto argType = arg.getPlainType();
if (argType->isPlaceholder())
return true;
if (auto *typeVar = argType->getAs<TypeVariableType>())
return hasFixFor(typeVar->getImpl().getLocator());
return false;
});
// If this is an operator application and all of the arguments are holes,
// let's disable all but one overload to make sure holes don't cause
// performance problems because hole could be bound to any type.
//
// Non-operator calls are exempted because they have fewer overloads,
// and it's possible to filter them based on labels.
if (allHoles && isOperatorDisjunction(disjunction)) {
auto choices = disjunction->getNestedConstraints();
for (auto *choice : choices.slice(1))
choice->setDisabled();
}
}
/// The common result type amongst all function overloads.
Type commonResultType;
auto updateCommonResultType = [&](Type choiceType) {
auto markFailure = [&] {
commonResultType = ErrorType::get(getASTContext());
};
auto choiceFnType = choiceType->getAs<FunctionType>();
if (!choiceFnType)
return markFailure();
// For now, don't attempt to establish a common result type when there
// are type parameters.
Type choiceResultType = choiceFnType->getResult();
if (choiceResultType->hasTypeParameter())
return markFailure();
// If we haven't seen a common result type yet, record what we found.
if (!commonResultType) {
commonResultType = choiceResultType;
return;
}
// If we found something different, fail.
if (!commonResultType->isEqual(choiceResultType))
return markFailure();
};
auto *argList = getArgumentList(getConstraintLocator(locator));
// If argument list has trailing closures and this is `init` call to
// a callable type, let's not filter anything since there is a possibility
// that it needs an implicit `.callAsFunction` to work.
if (argList && argList->hasAnyTrailingClosures()) {
if (disjunction->getLocator()
->isLastElement<LocatorPathElt::ConstructorMember>()) {
auto choice = disjunction->getNestedConstraints()[0]->getOverloadChoice();
if (auto *decl = choice.getDeclOrNull()) {
auto *dc = decl->getDeclContext();
if (auto *parent = dc->getSelfNominalTypeDecl()) {
auto type = parent->getDeclaredInterfaceType();
if (type->isCallAsFunctionType(DC))
return false;
}
}
}
}
// Consider each of the constraints in the disjunction.
retry_after_fail:
bool hasUnhandledConstraints = false;
bool labelMismatch = false;
auto filterResult =
filterDisjunction(disjunction, /*restoreOnFail=*/shouldAttemptFixes(),
[&](Constraint *constraint) {
assert(constraint->getKind() == ConstraintKind::BindOverload);
auto choice = constraint->getOverloadChoice();
// Determine whether the argument labels we have conflict with those of
// this overload choice.
if (argList) {
auto args = argFnType->getParams();
SmallVector<FunctionType::Param, 8> argsWithLabels;
argsWithLabels.append(args.begin(), args.end());
FunctionType::relabelParams(argsWithLabels, argList);
auto labelsMatch = [&](MatchCallArgumentListener &listener) {
if (areConservativelyCompatibleArgumentLabels(
*this, choice, argsWithLabels, listener,
argList->getFirstTrailingClosureIndex()))
return true;
labelMismatch = true;
return false;
};
AllowLabelMismatches listener;
// This overload has more problems than just missing/invalid labels.
if (!labelsMatch(listener))
return false;
// If overload did match, let's check if it needs to be disabled
// in "performance" mode because it has missing labels.
if (listener.hadLabelingIssues()) {
// In performance mode, let's just disable the choice,
// this decision could be rolled back for diagnostics.
if (!shouldAttemptFixes())
return false;
// Match expected vs. actual to see whether the only kind
// of problem here is missing label(s).
auto onlyMissingLabels =
[argList](ArrayRef<Identifier> expectedLabels) {
if (argList->size() != expectedLabels.size())
return false;
for (auto i : indices(*argList)) {
auto actual = argList->getLabel(i);
auto expected = expectedLabels[i];
if (actual.compare(expected) != 0 && !actual.empty())
return false;
}
return true;
};
auto replacementLabels = listener.getLabelReplacements();
// Either it's just one argument or all issues are missing labels.
if (!replacementLabels || onlyMissingLabels(*replacementLabels)) {
constraint->setDisabled(/*enableForDiagnostics=*/true);
// Don't include this overload in "common result" computation
// because it has issues.
return true;
}
}
}
// Determine the type that this choice will have.
Type choiceType = getEffectiveOverloadType(
constraint->getLocator(), choice, /*allowMembers=*/true,
constraint->getOverloadUseDC());
if (!choiceType) {
hasUnhandledConstraints = true;
return true;
}
// If types of arguments/parameters and result lined up exactly,
// let's favor this overload choice.
//
// Note this check ignores `ExtInfo` on purpose and only compares
// types, if there are overloads that differ only in effects then
// all of them are going to be considered and filtered as part of
// "favored" group after forming a valid partial solution.
if (auto *choiceFnType = choiceType->getAs<FunctionType>()) {
if (FunctionType::equalParams(argFnType->getParams(),
choiceFnType->getParams()) &&
argFnType->getResult()->isEqual(choiceFnType->getResult()))
constraint->setFavored();
}
// Account for any optional unwrapping/binding
for (unsigned i : range(numOptionalUnwraps)) {
(void)i;
if (Type objectType = choiceType->getOptionalObjectType())
choiceType = objectType;
}
// If we have a function type, we can compute a common result type.
updateCommonResultType(choiceType);
return true;
});
switch (filterResult) {
case SolutionKind::Error:
if (labelMismatch && shouldAttemptFixes()) {
argList = nullptr;
goto retry_after_fail;
}
return true;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
// If there was a constraint that we couldn't reason about, don't use the
// results of any common-type computations.
if (hasUnhandledConstraints)
return false;
// If we have a common result type, bind the expected result type to it.
if (commonResultType && !commonResultType->is<ErrorType>()) {
if (isDebugMode()) {
PrintOptions PO;
PO.PrintTypesForDebugging = true;
llvm::errs().indent(solverState ? solverState->getCurrentIndent() : 0)
<< "(common result type for $T" << fnTypeVar->getID() << " is "
<< commonResultType.getString(PO)
<< ")\n";
}
// Introduction of a `Bind` constraint here could result in the disconnect
// in the constraint system with unintended consequences because e.g.
// in case of key path application it could disconnect one of the
// components like subscript from the rest of the context.
addConstraint(ConstraintKind::Equal, argFnType->getResult(),
commonResultType, locator);
}
return false;
}
bool ConstraintSystem::simplifyAppliedOverloads(
Constraint *disjunction, ConstraintLocatorBuilder locator) {
auto choices = disjunction->getNestedConstraints();
assert(choices.size() >= 2);
assert(choices.front()->getKind() == ConstraintKind::BindOverload);
// If we've already bound the overload type var, bail.
auto *typeVar = choices.front()->getFirstType()->getAs<TypeVariableType>();
if (!typeVar || getFixedType(typeVar))
return false;
// Try to find an applicable fn constraint that applies the overload choice.
auto result = findConstraintThroughOptionals(
typeVar, OptionalWrappingDirection::Unwrap,
[&](Constraint *match, TypeVariableType *currentRep) {
// Check to see if we have an applicable fn with a type var RHS that
// matches the disjunction.
if (match->getKind() != ConstraintKind::ApplicableFunction)
return false;
auto *rhsTyVar = match->getSecondType()->getAs<TypeVariableType>();
return rhsTyVar && currentRep == getRepresentative(rhsTyVar);
});
if (!result)
return false;
auto *applicableFn = result->first;
auto *fnTypeVar = applicableFn->getSecondType()->castTo<TypeVariableType>();
auto argFnType = applicableFn->getFirstType()->castTo<FunctionType>();
AppliedDisjunctions[disjunction->getLocator()] = argFnType;
return simplifyAppliedOverloadsImpl(disjunction, fnTypeVar, argFnType,
/*numOptionalUnwraps*/ result->second,
applicableFn->getLocator());
}
bool ConstraintSystem::simplifyAppliedOverloads(
Type fnType, FunctionType *argFnType, ConstraintLocatorBuilder locator) {
// If we've already bound the function type, bail.
auto *fnTypeVar = fnType->getAs<TypeVariableType>();
if (!fnTypeVar || getFixedType(fnTypeVar))
return false;
// Try to find a corresponding bind overload disjunction.
unsigned numOptionalUnwraps = 0;
auto *disjunction =
getUnboundBindOverloadDisjunction(fnTypeVar, &numOptionalUnwraps);
if (!disjunction)
return false;
AppliedDisjunctions[disjunction->getLocator()] = argFnType;
return simplifyAppliedOverloadsImpl(disjunction, fnTypeVar, argFnType,
numOptionalUnwraps, locator);
}
/// Create an implicit dot-member reference expression to be used
/// as a root for injected `.callAsFunction` call.
static UnresolvedDotExpr *
createImplicitRootForCallAsFunction(ConstraintSystem &cs, Type refType,
ArgumentList *arguments,
ConstraintLocator *calleeLocator) {
auto &ctx = cs.getASTContext();
auto *baseExpr = castToExpr(calleeLocator->getAnchor());
SmallVector<Identifier, 2> closureLabelsScratch;
// Create implicit `.callAsFunction` expression to use as an anchor
// for new argument list that only has trailing closures in it.
auto *implicitRef = UnresolvedDotExpr::createImplicit(
ctx, baseExpr, {ctx.Id_callAsFunction},
arguments->getArgumentLabels(closureLabelsScratch));
{
// Record a type of the new reference in the constraint system.
cs.setType(implicitRef, refType);
// Record new `.callAsFunction` in the constraint system.
cs.recordCallAsFunction(implicitRef, arguments, calleeLocator);
}
return implicitRef;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyApplicableFnConstraint(
Type type1, Type type2,
std::optional<TrailingClosureMatching> trailingClosureMatching,
TypeMatchOptions flags, ConstraintLocatorBuilder locator) {
auto &ctx = getASTContext();
// By construction, the left hand side is a type that looks like the
// following: $T1 -> $T2.
auto func1 = type1->castTo<FunctionType>();
// Before stripping lvalue-ness and optional types, save the original second
// type for handling `func callAsFunction` and `@dynamicCallable`
// applications. This supports the following cases:
// - Generating constraints for `mutating func callAsFunction`. The nominal
// type (`type2`) should be an lvalue type.
// - Extending `Optional` itself with `func callAsFunction` or
// `@dynamicCallable` functionality. Optional types are stripped below if
// `shouldAttemptFixes()` is true.
auto origLValueType2 =
getFixedTypeRecursive(type2, flags, /*wantRValue=*/false);
// Drill down to the concrete type on the right hand side.
type2 = getFixedTypeRecursive(type2, flags, /*wantRValue=*/true);
auto desugar2 = type2->getDesugaredType();
// If a type variable representing "function type" is a hole
// or it could be bound to some concrete type with a help of
// a fix, let's propagate holes to the "input" type. Doing so
// provides more information to upcoming argument and result matching.
if (shouldAttemptFixes()) {
if (auto *typeVar = type2->getAs<TypeVariableType>()) {
auto *locator = typeVar->getImpl().getLocator();
if (hasFixFor(locator)) {
recordAnyTypeVarAsPotentialHole(func1);
}
}
Type underlyingType = desugar2;
while (auto *MT = underlyingType->getAs<AnyMetatypeType>()) {
underlyingType = MT->getInstanceType();
}
underlyingType =
getFixedTypeRecursive(underlyingType, flags, /*wantRValue=*/true);
if (underlyingType->isPlaceholder()) {
recordAnyTypeVarAsPotentialHole(func1);
return SolutionKind::Solved;
}
}
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
SmallVector<LocatorPathElt, 2> parts;
auto anchor = locator.getLocatorParts(parts);
bool isOperator =
(isExpr<PrefixUnaryExpr>(anchor) || isExpr<PostfixUnaryExpr>(anchor) ||
isExpr<BinaryExpr>(anchor));
auto hasInOut = [&]() {
for (auto param : func1->getParams())
if (param.isInOut())
return true;
return false;
};
// Local function to form an unsolved result.
auto formUnsolved = [&](bool activate = false) {
if (flags.contains(TMF_GenerateConstraints)) {
auto *application = Constraint::createApplicableFunction(
*this, type1, type2, trailingClosureMatching,
getConstraintLocator(locator));
addUnsolvedConstraint(application);
if (activate)
activateConstraint(application);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// If right-hand side is a type variable, the constraint is unsolved.
if (desugar2->isTypeVariableOrMember()) {
return formUnsolved();
}
// Strip the 'ApplyFunction' off the locator.
// FIXME: Perhaps ApplyFunction can go away entirely?
assert(!parts.empty() && "Nonsensical applicable-function locator");
assert(parts.back().getKind() == ConstraintLocator::ApplyFunction);
assert(parts.back().getNewSummaryFlags() == 0);
parts.pop_back();
ConstraintLocatorBuilder outerLocator =
getConstraintLocator(anchor, parts, locator.getSummaryFlags());
// If the types are obviously equivalent, we're done. This optimization
// is not valid for operators though, where an inout parameter does not
// have an explicit inout argument.
if (type1.getPointer() == desugar2) {
// Note that this could throw.
recordPotentialThrowSite(
PotentialThrowSite::Application, Type(desugar2), outerLocator);
if (!isOperator || !hasInOut()) {
recordMatchCallArgumentResult(
getConstraintLocator(
outerLocator.withPathElement(ConstraintLocator::ApplyArgument)),
MatchCallArgumentResult::forArity(func1->getNumParams()));
return SolutionKind::Solved;
}
}
// Handle applications of types with `callAsFunction` methods.
// Do this before stripping optional types below, when `shouldAttemptFixes()`
// is true.
if (desugar2->isCallAsFunctionType(DC)) {
auto memberLoc = getConstraintLocator(
locator.withPathElement(ConstraintLocator::ImplicitCallAsFunction));
// Add a `callAsFunction` member constraint, binding the member type to a
// type variable.
auto memberTy = createTypeVariable(memberLoc, /*options=*/0);
// TODO: Revisit this if `static func callAsFunction` is to be supported.
// Static member constraint requires `FunctionRefKind::DoubleApply`.
addValueMemberConstraint(origLValueType2,
DeclNameRef(ctx.Id_callAsFunction),
memberTy, DC, FunctionRefKind::SingleApply,
/*outerAlternatives*/ {}, memberLoc);
// Add new applicable function constraint based on the member type
// variable.
addConstraint(ConstraintKind::ApplicableFunction, func1, memberTy,
locator);
return SolutionKind::Solved;
}
// Record the second type before unwrapping optionals.
auto origType2 = desugar2;
unsigned unwrapCount = 0;
if (shouldAttemptFixes()) {
// If we have an optional type, try forcing it to see if that
// helps. Note that we only deal with function and metatype types
// below, so there is no reason not to attempt to strip these off
// immediately.
while (auto objectType2 = desugar2->getOptionalObjectType()) {
type2 = objectType2;
desugar2 = type2->getDesugaredType();
// Track how many times we do this so that we can record a fix for each.
++unwrapCount;
}
}
// For a function, bind the output and convert the argument to the input.
if (auto func2 = dyn_cast<FunctionType>(desugar2)) {
// Note that this could throw.
recordPotentialThrowSite(
PotentialThrowSite::Application, Type(desugar2), outerLocator);
ConstraintKind subKind = (isOperator
? ConstraintKind::OperatorArgumentConversion
: ConstraintKind::ArgumentConversion);
auto *argumentsLoc = getConstraintLocator(
outerLocator.withPathElement(ConstraintLocator::ApplyArgument));
auto *argumentList = getArgumentList(argumentsLoc);
// The argument type must be convertible to the input type.
SmallVector<std::pair<TypeVariableType *, OpenedArchetypeType *>, 2>
openedExistentials;
auto matchCallResult = ::matchCallArguments(
*this, func2, argumentList, func1->getParams(), func2->getParams(),
subKind, argumentsLoc, trailingClosureMatching, openedExistentials);
switch (matchCallResult) {
case SolutionKind::Error: {
auto resultTy = func2->getResult();
// If this is a call that constructs a callable type with
// trailing closure(s), closure(s) might not belong to
// the constructor but rather to implicit `callAsFunction`,
// there is no way to determine that without trying.
if (resultTy->isCallAsFunctionType(DC) &&
argumentList->hasAnyTrailingClosures()) {
auto *calleeLoc = getCalleeLocator(argumentsLoc);
bool isInit = false;
if (auto overload = findSelectedOverloadFor(calleeLoc)) {
isInit = bool(dyn_cast_or_null<ConstructorDecl>(
overload->choice.getDeclOrNull()));
}
if (!isInit)
return SolutionKind::Error;
auto &ctx = getASTContext();
auto numTrailing = argumentList->getNumTrailingClosures();
SmallVector<Argument, 4> newArguments(
argumentList->getNonTrailingArgs());
SmallVector<Argument, 4> trailingClosures(
argumentList->getTrailingClosures());
// Original argument list with all the trailing closures removed.
auto *newArgumentList = ArgumentList::createParsed(
ctx, argumentList->getLParenLoc(), newArguments,
argumentList->getRParenLoc(),
/*firstTrailingClosureIndex=*/std::nullopt);
auto trailingClosureTypes = func1->getParams().take_back(numTrailing);
// The original result type is going to become a result of
// implicit `.callAsFunction` instead since `.callAsFunction`
// is inserted between `.init` and trailing closures.
auto callAsFunctionResultTy = func1->getResult();
// The implicit replacement for original result type which
// represents a callable type produced by `.init` call.
auto callableType =
createTypeVariable(getConstraintLocator({}), /*flags=*/0);
// The original application type with all the trailing closures
// dropped from it and result replaced to the implicit variable.
func1 = FunctionType::get(func1->getParams().drop_back(numTrailing),
callableType, func1->getExtInfo());
auto matchCallResult = ::matchCallArguments(
*this, func2, newArgumentList, func1->getParams(),
func2->getParams(), subKind, argumentsLoc, trailingClosureMatching,
openedExistentials);
if (matchCallResult != SolutionKind::Solved)
return SolutionKind::Error;
auto *implicitCallArgumentList =
ArgumentList::createImplicit(ctx, trailingClosures,
/*firstTrailingClosureIndex=*/0);
auto *implicitRef = createImplicitRootForCallAsFunction(
*this, callAsFunctionResultTy, implicitCallArgumentList, calleeLoc);
auto callAsFunctionArguments =
FunctionType::get(trailingClosureTypes, callAsFunctionResultTy,
FunctionType::ExtInfo());
// Form an unsolved constraint to apply trailing closures to a
// callable type produced by `.init`. This constraint would become
// active when `callableType` is bound.
addUnsolvedConstraint(Constraint::create(
*this, ConstraintKind::ApplicableFunction, callAsFunctionArguments,
callableType,
getConstraintLocator(implicitRef,
ConstraintLocator::ApplyFunction)));
break;
}
return SolutionKind::Error;
}
case SolutionKind::Unsolved: {
// Only occurs when there is an ambiguity between forward scanning and
// backward scanning for the unlabeled trailing closure. Create a
// disjunction so that we explore both paths, and can diagnose
// ambiguities later.
assert(!trailingClosureMatching.has_value());
auto applyLocator = getConstraintLocator(locator);
auto forwardConstraint = Constraint::createApplicableFunction(
*this, type1, type2, TrailingClosureMatching::Forward, applyLocator);
auto backwardConstraint = Constraint::createApplicableFunction(
*this, type1, type2, TrailingClosureMatching::Backward,
applyLocator);
addDisjunctionConstraint(
{ forwardConstraint, backwardConstraint}, applyLocator);
break;
}
case SolutionKind::Solved:
// Keep going.
break;
}
// Erase all of the opened existentials.
Type result2 = func2->getResult();
if (result2->hasTypeVariable() && !openedExistentials.empty()) {
for (const auto &opened : openedExistentials) {
result2 = typeEraseOpenedExistentialReference(
result2, opened.second->getExistentialType(), opened.first,
TypePosition::Covariant);
}
}
// The result types are equivalent.
if (matchFunctionResultTypes(
func1->getResult(), result2, subflags,
locator.withPathElement(ConstraintLocator::FunctionResult))
.isFailure())
return SolutionKind::Error;
if (unwrapCount == 0)
return SolutionKind::Solved;
// Record any fixes we attempted to get to the correct solution.
auto *fix = ForceOptional::create(*this, origType2, func1,
getConstraintLocator(locator));
if (recordFix(fix, /*impact=*/unwrapCount))
return SolutionKind::Error;
return SolutionKind::Solved;
}
// For a metatype, perform a construction.
if (auto meta2 = dyn_cast<AnyMetatypeType>(desugar2)) {
auto instance2 = getFixedTypeRecursive(meta2->getInstanceType(), true);
if (instance2->isTypeVariableOrMember())
return formUnsolved();
auto *argumentsLoc = getConstraintLocator(
outerLocator.withPathElement(ConstraintLocator::ApplyArgument));
auto *argumentList = getArgumentList(argumentsLoc);
assert(argumentList);
// Cannot simplify construction of callable types during constraint
// generation when trailing closures are present because such calls
// have special trailing closure matching semantics. It's unclear
// whether trailing arguments belong to `.init` or implicit
// `.callAsFunction` in this case.
//
// Note that the constraint has to be activate so that solver attempts
// once constraint generation is done.
if (getPhase() == ConstraintSystemPhase::ConstraintGeneration &&
argumentList->hasAnyTrailingClosures() &&
instance2->isCallAsFunctionType(DC)) {
return formUnsolved(/*activate=*/true);
}
// Construct the instance from the input arguments.
auto simplified = simplifyConstructionConstraint(instance2, func1, subflags,
/*FIXME?*/ DC,
FunctionRefKind::SingleApply,
getConstraintLocator(outerLocator));
// Record any fixes we attempted to get to the correct solution.
if (simplified == SolutionKind::Solved) {
if (unwrapCount == 0)
return SolutionKind::Solved;
auto *fix = ForceOptional::create(*this, origType2, func1,
getConstraintLocator(locator));
if (recordFix(fix, /*impact=*/unwrapCount))
return SolutionKind::Error;
}
return simplified;
}
// Handle applications of @dynamicCallable types.
auto result = simplifyDynamicCallableApplicableFnConstraint(
type1, origType2, subflags, locator);
if (shouldAttemptFixes() && result == SolutionKind::Error) {
// Skip this fix if the type is not yet resolved or
// it's a function type/metatype which points to argument mismatches.
if (desugar2->is<TypeVariableType>() || desugar2->is<FunctionType>() ||
desugar2->is<AnyMetatypeType>())
return SolutionKind::Error;
// If there are any type variables associated with arguments/result
// they have to be marked as "holes".
recordAnyTypeVarAsPotentialHole(func1);
if (desugar2->isPlaceholder())
return SolutionKind::Solved;
auto *fix = RemoveInvalidCall::create(*this, getConstraintLocator(locator));
// Let's make this fix as high impact so if there is a function or member
// overload with e.g. argument-to-parameter type mismatches it would take
// a higher priority.
return recordFix(fix, /*impact=*/10) ? SolutionKind::Error
: SolutionKind::Solved;
}
return result;
}
/// Looks up and returns the @dynamicCallable required methods (if they exist)
/// implemented by a type.
static llvm::DenseSet<FuncDecl *>
lookupDynamicCallableMethods(NominalTypeDecl *decl, ConstraintSystem &CS,
const ConstraintLocatorBuilder &locator,
Identifier argumentName, bool hasKeywordArgs) {
auto &ctx = CS.getASTContext();
// The generic arguments don't matter because we only want the member decls,
// not concrete overload choices (we form those later when adding the overload
// set). We map into context here to avoid an OverloadChoice assertion for an
// interface type base.
// TODO: We really ought to separate out the actual lookup part of
// `performMemberLookup` from the choice construction. That would allow us to
// requestify the lookup of dynamicCallable members on a per-decl basis, and
// map them onto viable and unviable choices onto a given base type.
auto type = decl->getDeclaredTypeInContext();
DeclNameRef methodName({ ctx, ctx.Id_dynamicallyCall, { argumentName } });
auto matches = CS.performMemberLookup(
ConstraintKind::ValueMember, methodName, type,
FunctionRefKind::SingleApply, CS.getConstraintLocator(locator),
/*includeInaccessibleMembers*/ false);
// Filter valid candidates.
auto candidates = matches.ViableCandidates;
auto filter = [&](OverloadChoice choice) {
auto cand = cast<FuncDecl>(choice.getDecl());
return !isValidDynamicCallableMethod(cand, CS.DC->getParentModule(),
hasKeywordArgs);
};
candidates.erase(
std::remove_if(candidates.begin(), candidates.end(), filter),
candidates.end());
llvm::DenseSet<FuncDecl *> methods;
for (auto candidate : candidates)
methods.insert(cast<FuncDecl>(candidate.getDecl()));
return methods;
}
/// Looks up and returns the @dynamicCallable required methods (if they exist)
/// implemented by a given nominal type decl.
static DynamicCallableMethods
lookupDynamicCallableMethods(NominalTypeDecl *decl, ConstraintSystem &CS,
const ConstraintLocatorBuilder &locator) {
auto it = CS.DynamicCallableCache.find(decl);
if (it != CS.DynamicCallableCache.end())
return it->second;
// The decl must have @dynamicCallable.
auto &ctx = CS.getASTContext();
HasDynamicCallableAttributeRequest req(decl);
if (!evaluateOrDefault(ctx.evaluator, req, false))
return DynamicCallableMethods();
DynamicCallableMethods methods;
methods.argumentsMethods =
lookupDynamicCallableMethods(decl, CS, locator, ctx.Id_withArguments,
/*hasKeywordArgs*/ false);
methods.keywordArgumentsMethods =
lookupDynamicCallableMethods(decl, CS, locator,
ctx.Id_withKeywordArguments,
/*hasKeywordArgs*/ true);
CS.DynamicCallableCache[decl] = methods;
return methods;
}
/// Returns the @dynamicCallable required methods (if they exist) implemented
/// by a type.
static DynamicCallableMethods
getDynamicCallableMethods(Type type, ConstraintSystem &CS,
const ConstraintLocatorBuilder &locator) {
SmallVector<NominalTypeDecl *, 4> decls;
namelookup::tryExtractDirectlyReferencedNominalTypes(type, decls);
DynamicCallableMethods result;
for (auto *decl : decls)
result.addMethods(lookupDynamicCallableMethods(decl, CS, locator));
return result;
}
// TODO: Refactor/simplify this function.
// - It should perform less duplicate work with its caller
// `ConstraintSystem::simplifyApplicableFnConstraint`.
// - It should generate a member constraint instead of manually forming an
// overload set for `func dynamicallyCall` candidates.
// - It should support `mutating func dynamicallyCall`. This should fall out of
// using member constraints with an lvalue base type.
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyDynamicCallableApplicableFnConstraint(
Type type1,
Type type2,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto &ctx = getASTContext();
// By construction, the left hand side is a function type: $T1 -> $T2.
assert(type1->is<FunctionType>());
// Drill down to the concrete type on the right hand side.
type2 = getFixedTypeRecursive(type2, flags, /*wantRValue=*/true);
auto desugar2 = type2->getDesugaredType();
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
// If the types are obviously equivalent, we're done.
if (type1.getPointer() == desugar2)
return SolutionKind::Solved;
// Local function to form an unsolved result.
auto formUnsolved = [&] {
if (flags.contains(TMF_GenerateConstraints)) {
addUnsolvedConstraint(
Constraint::create(*this,
ConstraintKind::DynamicCallableApplicableFunction, type1, type2,
getConstraintLocator(locator)));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// If right-hand side is a type variable, the constraint is unsolved.
if (desugar2->isTypeVariableOrMember())
return formUnsolved();
// If right-hand side is a function type, it must be a valid
// `dynamicallyCall` method type. Bind the output and convert the argument
// to the input.
auto func1 = type1->castTo<FunctionType>();
if (auto func2 = dyn_cast<FunctionType>(desugar2)) {
// The argument type must be convertible to the input type.
assert(func1->getParams().size() == 1 && func2->getParams().size() == 1 &&
"Expected `dynamicallyCall` method with one parameter");
assert((func2->getParams()[0].getLabel() == ctx.Id_withArguments ||
func2->getParams()[0].getLabel() == ctx.Id_withKeywordArguments) &&
"Expected 'dynamicallyCall' method argument label 'withArguments' "
"or 'withKeywordArguments'");
if (matchTypes(func1->getParams()[0].getPlainType(),
func2->getParams()[0].getPlainType(),
ConstraintKind::ArgumentConversion,
subflags,
locator.withPathElement(
ConstraintLocator::ApplyArgument)).isFailure())
return SolutionKind::Error;
// The result types are equivalent.
if (matchFunctionResultTypes(
func1->getResult(), func2->getResult(), subflags,
locator.withPathElement(ConstraintLocator::FunctionResult))
.isFailure())
return SolutionKind::Error;
return SolutionKind::Solved;
}
// If the right-hand side is not a function type, it must be a valid
// @dynamicCallable type. Attempt to get valid `dynamicallyCall` methods.
auto methods = getDynamicCallableMethods(desugar2, *this, locator);
if (!methods.isValid()) return SolutionKind::Error;
// Determine whether to call a `withArguments` method or a
// `withKeywordArguments` method.
bool useKwargsMethod = methods.argumentsMethods.empty();
useKwargsMethod |= llvm::any_of(
func1->getParams(), [](AnyFunctionType::Param p) { return p.hasLabel(); });
auto candidates = useKwargsMethod ?
methods.keywordArgumentsMethods :
methods.argumentsMethods;
// Create a type variable for the `dynamicallyCall` method.
auto loc = getConstraintLocator(locator);
auto tv = createTypeVariable(loc,
TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
// Record the 'dynamicallyCall` method overload set.
SmallVector<OverloadChoice, 4> choices;
for (auto candidate : candidates) {
if (candidate->isInvalid()) continue;
choices.push_back(
OverloadChoice(type2, candidate, FunctionRefKind::SingleApply));
}
if (choices.empty()) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
// TODO(diagnostics): This is not going to be necessary once
// `@dynamicCallable` uses existing `member` machinery.
auto argLabel = useKwargsMethod ? ctx.Id_withKeywordArguments
: ctx.Id_withArguments;
DeclNameRef memberName({ ctx, ctx.Id_dynamicallyCall, {argLabel} });
auto *fix = DefineMemberBasedOnUse::create(
*this, desugar2, memberName, /*alreadyDiagnosed=*/false,
getConstraintLocator(loc, ConstraintLocator::DynamicCallable));
if (recordFix(fix))
return SolutionKind::Error;
recordPotentialHole(tv);
recordAnyTypeVarAsPotentialHole(func1);
return SolutionKind::Solved;
}
addOverloadSet(tv, choices, DC, loc);
// Create a type variable for the argument to the `dynamicallyCall` method.
auto tvParam = createTypeVariable(loc, TVO_CanBindToNoEscape);
AnyFunctionType *funcType =
FunctionType::get({ AnyFunctionType::Param(tvParam) }, func1->getResult());
addConstraint(ConstraintKind::DynamicCallableApplicableFunction,
funcType, tv, locator);
// Get argument type for the `dynamicallyCall` method.
Type argumentType;
if (!useKwargsMethod) {
auto arrayLitProto =
ctx.getProtocol(KnownProtocolKind::ExpressibleByArrayLiteral);
addConstraint(ConstraintKind::ConformsTo, tvParam,
arrayLitProto->getDeclaredInterfaceType(), locator);
auto elementAssocType = arrayLitProto->getAssociatedType(
ctx.Id_ArrayLiteralElement);
argumentType = DependentMemberType::get(tvParam, elementAssocType);
} else {
auto dictLitProto =
ctx.getProtocol(KnownProtocolKind::ExpressibleByDictionaryLiteral);
addConstraint(ConstraintKind::ConformsTo, tvParam,
dictLitProto->getDeclaredInterfaceType(), locator);
auto valueAssocType = dictLitProto->getAssociatedType(ctx.Id_Value);
argumentType = DependentMemberType::get(tvParam, valueAssocType);
}
// Argument type can default to `Any`.
addConstraint(ConstraintKind::Defaultable, argumentType,
ctx.getAnyExistentialType(), locator);
auto *baseArgLoc = getConstraintLocator(
loc->getAnchor(),
{ConstraintLocator::DynamicCallable, ConstraintLocator::ApplyArgument},
/*summaryFlags=*/0);
// All dynamic call parameter types must be convertible to the argument type.
for (auto i : indices(func1->getParams())) {
auto param = func1->getParams()[i];
auto paramType = param.getPlainType();
addConstraint(
ConstraintKind::ArgumentConversion, paramType, argumentType,
getConstraintLocator(baseArgLoc, LocatorPathElt::ApplyArgToParam(
i, 0, param.getParameterFlags())));
}
return SolutionKind::Solved;
}
static bool hasUnresolvedPackVars(Type type) {
// We can't compute a reduced shape if the input type still
// contains type variables that might bind to pack archetypes
// or pack expansions.
SmallPtrSet<TypeVariableType *, 2> typeVars;
type->getTypeVariables(typeVars);
return llvm::any_of(typeVars, [](const TypeVariableType *typeVar) {
return typeVar->getImpl().canBindToPack() ||
typeVar->getImpl().isPackExpansion();
});
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyShapeOfConstraint(
Type shapeTy, Type packTy, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
// Recursively replace all type variables with fixed bindings if
// possible.
packTy = simplifyType(packTy, flags);
auto formUnsolved = [&]() {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *shapeOf = Constraint::create(
*this, ConstraintKind::ShapeOf, shapeTy, packTy,
getConstraintLocator(locator));
addUnsolvedConstraint(shapeOf);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// Don't try computing the shape of a type variable.
if (packTy->isTypeVariableOrMember())
return formUnsolved();
// We can't compute a reduced shape if the input type still
// contains type variables that might bind to pack archetypes
// or pack expansions.
SmallPtrSet<TypeVariableType *, 2> typeVars;
packTy->getTypeVariables(typeVars);
for (auto *typeVar : typeVars) {
if (typeVar->getImpl().canBindToPack() ||
typeVar->getImpl().isPackExpansion())
return formUnsolved();
}
if (packTy->hasPlaceholder()) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
recordTypeVariablesAsHoles(shapeTy);
return SolutionKind::Solved;
}
if (isSingleUnlabeledPackExpansionTuple(packTy)) {
auto *packVar = addMaterializePackExpansionConstraint(packTy, locator);
addConstraint(ConstraintKind::ShapeOf, shapeTy, packVar, locator);
return SolutionKind::Solved;
}
// Map element archetypes to the pack context to check for equality.
if (packTy->hasElementArchetype()) {
auto *packEnv = DC->getGenericEnvironmentOfContext();
packTy = packEnv->mapElementTypeIntoPackContext(packTy);
}
auto shape = packTy->getReducedShape();
addConstraint(ConstraintKind::Bind, shapeTy, shape, locator);
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifySameShapeConstraint(
Type type1, Type type2, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
type1 = simplifyType(type1);
type2 = simplifyType(type2);
auto formUnsolved = [&]() {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *sameShape =
Constraint::create(*this, ConstraintKind::SameShape, type1, type2,
getConstraintLocator(locator));
addUnsolvedConstraint(sameShape);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
if (hasUnresolvedPackVars(type1) || hasUnresolvedPackVars(type2))
return formUnsolved();
auto shape1 = type1->getReducedShape();
auto shape2 = type2->getReducedShape();
if (shape1->isEqual(shape2))
return SolutionKind::Solved;
if (shouldAttemptFixes()) {
// If there are placeholders involved shape mismatches are most
// likely just a symptom of some other issue i.e. type mismatch.
if (type1->hasPlaceholder() || type2->hasPlaceholder())
return SolutionKind::Solved;
auto recordShapeFix = [&](ConstraintFix *fix,
unsigned impact) -> SolutionKind {
return recordFix(fix, impact) ? SolutionKind::Error
: SolutionKind::Solved;
};
auto recordShapeMismatchFix = [&]() -> SolutionKind {
unsigned impact = 1;
if (locator.endsWith<LocatorPathElt::AnyRequirement>())
impact = assessRequirementFailureImpact(*this, shape1, locator);
return recordShapeFix(
SkipSameShapeRequirement::create(*this, type1, type2,
getConstraintLocator(locator)),
impact);
};
// Let's check whether we can produce a tailored fix for argument/parameter
// mismatches.
if (locator.endsWith<LocatorPathElt::PackShape>()) {
SmallVector<LocatorPathElt> path;
auto anchor = locator.getLocatorParts(path);
// Drop `PackShape`
path.pop_back();
// Tailed diagnostics for argument/parameter mismatches - there
// are either missing or extra arguments.
if (path.size() > 0 &&
path[path.size() - 1].is<LocatorPathElt::ApplyArgToParam>()) {
auto &ctx = getASTContext();
auto *loc = getConstraintLocator(anchor, path);
auto argLoc =
loc->castLastElementTo<LocatorPathElt::ApplyArgToParam>();
if (type1->is<PackArchetypeType>() &&
type2->is<PackArchetypeType>())
return recordShapeMismatchFix();
auto numArgs = (shape1->is<PackType>()
? shape1->castTo<PackType>()->getNumElements()
: 1);
auto numParams = (shape2->is<PackType>()
? shape2->castTo<PackType>()->getNumElements()
: 1);
// Tailed diagnostic to explode tuples.
// FIXME: This is very similar to
// 'cannot_convert_single_tuple_into_multiple_arguments'; can we emit
// both of these in the same place?
if (numArgs == 1) {
if (type1->is<TupleType>() &&
numParams >= 1) {
return recordShapeFix(
DestructureTupleToMatchPackExpansionParameter::create(
*this,
(type2->is<PackType>()
? type2->castTo<PackType>()
: PackType::getSingletonPackExpansion(type2)), loc),
/*impact=*/2 * numParams);
}
}
// Drops `ApplyArgToParam` and left with `ApplyArgument`.
path.pop_back();
auto *argListLoc = getConstraintLocator(anchor, path);
// Missing arguments.
if (numParams > numArgs) {
SmallVector<SynthesizedArg> synthesizedArgs;
for (unsigned i = 0, n = numParams - numArgs; i != n; ++i) {
auto eltTy = shape2->castTo<PackType>()->getElementType(i);
synthesizedArgs.push_back(SynthesizedArg{
argLoc.getParamIdx(), AnyFunctionType::Param(eltTy)});
}
return recordShapeFix(
AddMissingArguments::create(*this, synthesizedArgs, argListLoc),
/*impact=*/2 * synthesizedArgs.size());
} else {
auto argIdx = argLoc.getArgIdx() + numParams;
SmallVector<std::pair<unsigned, AnyFunctionType::Param>, 4>
extraneousArgs;
for (unsigned i = 0, n = numArgs - numParams; i != n; ++i) {
extraneousArgs.push_back(
{argIdx + i, AnyFunctionType::Param(ctx.TheEmptyTupleType)});
}
auto overload = findSelectedOverloadFor(getCalleeLocator(argListLoc));
if (!overload)
return SolutionKind::Error;
return recordShapeFix(
RemoveExtraneousArguments::create(
*this, overload->openedType->castTo<FunctionType>(),
extraneousArgs, argListLoc),
/*impact=*/2 * extraneousArgs.size());
}
}
}
return recordShapeMismatchFix();
}
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyMaterializePackExpansionConstraint(
Type type1, Type type2, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto formUnsolved = [&]() {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *explictGenericArgs =
Constraint::create(*this, ConstraintKind::MaterializePackExpansion,
type1, type2, getConstraintLocator(locator));
addUnsolvedConstraint(explictGenericArgs);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
type1 = simplifyType(type1);
if (type1->hasTypeVariable()) {
return formUnsolved();
}
if (auto patternType =
getPatternTypeOfSingleUnlabeledPackExpansionTuple(type1)) {
addConstraint(ConstraintKind::Equal, patternType, type2, locator);
return SolutionKind::Solved;
}
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyExplicitGenericArgumentsConstraint(
Type type1, Type type2, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto formUnsolved = [&]() {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *explictGenericArgs =
Constraint::create(*this, ConstraintKind::ExplicitGenericArguments,
type1, type2, getConstraintLocator(locator));
addUnsolvedConstraint(explictGenericArgs);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
};
// Bail out if we haven't selected an overload yet.
auto simplifiedBoundType = simplifyType(type1, flags);
if (simplifiedBoundType->isTypeVariableOrMember())
return formUnsolved();
std::function<GenericParamList *(ValueDecl *)> getGenericParams =
[&](ValueDecl *decl) -> GenericParamList * {
auto genericContext = decl->getAsGenericContext();
if (!genericContext)
return nullptr;
auto genericParams = genericContext->getGenericParams();
if (!genericParams) {
// If declaration is a non-generic typealias, let's point
// to the underlying generic declaration.
if (auto *TA = dyn_cast<TypeAliasDecl>(decl)) {
if (auto *UGT = TA->getUnderlyingType()->getAs<AnyGenericType>())
return getGenericParams(UGT->getDecl());
}
}
return genericParams;
};
ValueDecl *decl;
SmallVector<OpenedType, 2> openedTypes;
if (auto *bound = dyn_cast<TypeAliasType>(type1.getPointer())) {
decl = bound->getDecl();
for (auto argType : bound->getDirectGenericArgs()) {
auto *typeVar = argType->getAs<TypeVariableType>();
auto *genericParam = typeVar->getImpl().getGenericParameter();
openedTypes.push_back({genericParam, typeVar});
}
} else if (locator.directlyAt<TypeExpr>()) {
auto *BGT = type1->getAs<BoundGenericType>();
if (!BGT)
return SolutionKind::Error;
decl = BGT->getDecl();
auto genericParams = BGT->getDecl()->getInnermostGenericParamTypes();
if (genericParams.size() != BGT->getGenericArgs().size())
return SolutionKind::Error;
for (unsigned i = 0, n = genericParams.size(); i != n; ++i) {
auto argType = BGT->getGenericArgs()[i];
if (auto *typeVar = argType->getAs<TypeVariableType>()) {
openedTypes.push_back({genericParams[i], typeVar});
} else {
// If we have a concrete substitution then we need to create
// a new type variable to be able to add it to the list as-if
// it is opened generic parameter type.
auto *GP = genericParams[i];
unsigned options = TVO_CanBindToNoEscape;
if (GP->isParameterPack())
options |= TVO_CanBindToPack;
auto *argVar = createTypeVariable(
getConstraintLocator(locator, LocatorPathElt::GenericArgument(i)),
options);
addConstraint(ConstraintKind::Bind, argVar, argType, locator);
openedTypes.push_back({GP, argVar});
}
}
} else {
// If the overload hasn't been resolved, we can't simplify this constraint.
auto overloadLocator = getCalleeLocator(getConstraintLocator(locator));
auto selectedOverload = findSelectedOverloadFor(overloadLocator);
if (!selectedOverload)
return formUnsolved();
auto overloadChoice = selectedOverload->choice;
if (!overloadChoice.isDecl()) {
return SolutionKind::Error;
}
decl = overloadChoice.getDecl();
auto openedOverloadTypes = getOpenedTypes(overloadLocator);
auto genericParams = getGenericParams(decl);
if (genericParams) {
for (auto gp : *genericParams) {
auto found = find_if(openedOverloadTypes, [&](auto entry) {
return entry.first->getDepth() == gp->getDepth() &&
entry.first->getIndex() == gp->getIndex();
});
assert(found != openedOverloadTypes.end());
openedTypes.push_back(*found);
}
}
}
if (!decl->getAsGenericContext())
return SolutionKind::Error;
auto genericParams = getGenericParams(decl);
if (!genericParams) {
// FIXME: Record an error here that we're ignoring the parameters.
return SolutionKind::Solved;
}
// Map the generic parameters we have over to their opened types.
bool hasParameterPack = false;
SmallVector<Type, 2> openedGenericParams;
auto genericParamDepth = genericParams->getParams()[0]->getDepth();
for (const auto &openedType : openedTypes) {
if (openedType.first->getDepth() == genericParamDepth) {
// A generic argument list containing pack references expects
// those packs to be wrapped in pack expansion types. If this
// opened type represents the generic argument for a parameter
// pack, wrap generate the appropriate shape constraints and
// add a pack expansion to the argument list.
if (openedType.first->isParameterPack()) {
auto patternType = openedType.second;
auto *shapeLoc = getConstraintLocator(
locator.withPathElement(ConstraintLocator::PackShape));
auto *shapeType = createTypeVariable(shapeLoc,
TVO_CanBindToPack |
TVO_CanBindToHole);
addConstraint(ConstraintKind::ShapeOf,
shapeType, patternType, shapeLoc);
auto *expansion = PackExpansionType::get(patternType, shapeType);
openedGenericParams.push_back(expansion);
hasParameterPack = true;
} else {
openedGenericParams.push_back(Type(openedType.second));
}
}
}
if (openedGenericParams.empty()) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
return recordFix(AllowConcreteTypeSpecialization::create(
*this, type1, getConstraintLocator(locator)))
? SolutionKind::Error
: SolutionKind::Solved;
}
assert(openedGenericParams.size() == genericParams->size());
// Match the opened generic parameters to the specialized arguments.
auto specializedArgs = type2->castTo<PackType>()->getElementTypes();
PackMatcher matcher(openedGenericParams, specializedArgs, getASTContext(),
isPackExpansionType);
if (matcher.match()) {
if (!shouldAttemptFixes())
return SolutionKind::Error;
auto *fix = IgnoreGenericSpecializationArityMismatch::create(
*this, decl, openedGenericParams.size(), specializedArgs.size(),
hasParameterPack, getConstraintLocator(locator));
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
// Bind the opened generic parameters to the specialization arguments.
for (const auto &pair : matcher.pairs) {
addConstraint(
ConstraintKind::Bind, pair.lhs, pair.rhs,
getConstraintLocator(
locator, LocatorPathElt::GenericArgument(pair.lhsIdx)));
}
return SolutionKind::Solved;
}
static llvm::PointerIntPair<Type, 3, unsigned>
getBaseTypeForPointer(TypeBase *type) {
unsigned unwrapCount = 0;
while (auto objectTy = type->getOptionalObjectType()) {
type = objectTy.getPointer();
++unwrapCount;
}
auto pointeeTy = type->getAnyPointerElementType();
assert(pointeeTy);
return {pointeeTy, unwrapCount};
}
void ConstraintSystem::addRestrictedConstraint(
ConstraintKind kind,
ConversionRestrictionKind restriction,
Type first, Type second,
ConstraintLocatorBuilder locator) {
(void)simplifyRestrictedConstraint(restriction, first, second, kind,
TMF_GenerateConstraints, locator);
}
/// Given that we have a conversion constraint between two types, and
/// that the given constraint-reduction rule applies between them at
/// the top level, apply it and generate any necessary recursive
/// constraints.
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyRestrictedConstraintImpl(
ConversionRestrictionKind restriction,
Type type1, Type type2,
ConstraintKind matchKind,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
assert(!type1->isTypeVariableOrMember() && !type2->isTypeVariableOrMember());
// Add to the score based on context.
auto addContextualScore = [&] {
// Okay, we need to perform one or more conversions. If this
// conversion will cause a function conversion, score it as worse.
// This induces conversions to occur within closures instead of
// outside of them wherever possible.
if (locator.isFunctionConversion()) {
increaseScore(SK_FunctionConversion, locator);
}
};
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
auto matchPointerBaseTypes =
[&](llvm::PointerIntPair<Type, 3, unsigned> baseType1,
llvm::PointerIntPair<Type, 3, unsigned> baseType2) -> SolutionKind {
if (restriction != ConversionRestrictionKind::PointerToPointer)
increaseScore(ScoreKind::SK_ValueToPointerConversion, locator);
auto result =
matchTypes(baseType1.getPointer(), baseType2.getPointer(),
ConstraintKind::BindToPointerType, subflags, locator);
if (!(result.isFailure() && shouldAttemptFixes()))
return result;
BoundGenericType *ptr1 = nullptr;
BoundGenericType *ptr2 = nullptr;
switch (restriction) {
case ConversionRestrictionKind::ArrayToPointer:
case ConversionRestrictionKind::InoutToPointer: {
ptr2 = type2->lookThroughAllOptionalTypes()->castTo<BoundGenericType>();
ptr1 = BoundGenericType::get(ptr2->getDecl(), ptr2->getParent(),
{baseType1.getPointer()});
break;
}
case ConversionRestrictionKind::PointerToPointer:
// Original types could be wrapped into a different number of optional.
ptr1 = type1->lookThroughAllOptionalTypes()->castTo<BoundGenericType>();
ptr2 = type2->lookThroughAllOptionalTypes()->castTo<BoundGenericType>();
break;
default:
return SolutionKind::Error;
}
auto *fix = GenericArgumentsMismatch::create(*this, ptr1, ptr2, {0},
getConstraintLocator(locator));
// Treat this as a contextual type mismatch.
unsigned baseImpact = 2;
// It's possible to implicitly promote pointer into an optional
// before matching base types if other side is an optional, so
// score needs to account for number of such promotions.
int optionalWraps = baseType2.getInt() - baseType1.getInt();
return recordFix(fix, baseImpact + std::abs(optionalWraps))
? SolutionKind::Error
: SolutionKind::Solved;
};
auto fixContextualFailure = [&](Type fromType, Type toType,
ConstraintLocatorBuilder locator) -> bool {
auto *loc = getConstraintLocator(locator);
// Since this is a contextual type mismatch, let's start from higher
// impact than regular fix to avoid ambiguities.
auto impact = 2;
if (loc->isForAssignment() || loc->isForCoercion() ||
loc->isForContextualType() ||
loc->isLastElement<LocatorPathElt::ApplyArgToParam>() ||
loc->isForOptionalTry()) {
if (restriction == ConversionRestrictionKind::Superclass) {
if (auto *fix = CoerceToCheckedCast::attempt(
*this, fromType, toType, /*useConditionalCast*/ false, loc))
return !recordFix(fix, impact);
}
// We already have a fix for this locator indicating a
// tuple mismatch.
if (hasFixFor(loc, FixKind::AllowTupleTypeMismatch))
return true;
if (restriction == ConversionRestrictionKind::ValueToOptional ||
restriction == ConversionRestrictionKind::OptionalToOptional)
++impact;
auto *fix =
loc->isLastElement<LocatorPathElt::ApplyArgToParam>()
? AllowArgumentMismatch::create(*this, fromType, toType, loc)
: ContextualMismatch::create(*this, fromType, toType, loc);
return !recordFix(fix, impact);
}
return false;
};
switch (restriction) {
// for $< in { <, <c, <oc }:
// T_i $< U_i ===> (T_i...) $< (U_i...)
case ConversionRestrictionKind::DeepEquality:
return matchDeepEqualityTypes(type1, type2, locator);
case ConversionRestrictionKind::Superclass: {
addContextualScore();
auto result = matchSuperclassTypes(type1, type2, subflags, locator);
if (!(shouldAttemptFixes() && result.isFailure()))
return result;
return fixContextualFailure(type1, type2, locator)
? getTypeMatchSuccess()
: getTypeMatchFailure(locator);
}
// for $< in { <, <c, <oc }:
// T $< U, U : P_i ===> T $< protocol<P_i...>
case ConversionRestrictionKind::Existential:
addContextualScore();
return matchExistentialTypes(type1, type2,
ConstraintKind::SelfObjectOfProtocol,
subflags, locator);
// for $< in { <, <c, <oc }:
// for P protocol, Q protocol,
// P : Q ===> T.Protocol $< Q.Type
// for P protocol, Q protocol,
// P $< Q ===> P.Type $< Q.Type
case ConversionRestrictionKind::MetatypeToExistentialMetatype: {
addContextualScore();
auto instanceTy1 = type1->getMetatypeInstanceType();
auto instanceTy2 = type2->getMetatypeInstanceType();
auto result = matchExistentialTypes(
instanceTy1, instanceTy2, ConstraintKind::ConformsTo, subflags,
locator.withPathElement(ConstraintLocator::InstanceType));
if (!(shouldAttemptFixes() && result.isFailure()))
return result;
return fixContextualFailure(type1, type2, locator)
? getTypeMatchSuccess()
: getTypeMatchFailure(locator);
}
// for $< in { <, <c, <oc }:
// for P protocol, C class, D class,
// (P & C) : D ===> (P & C).Type $< D.Type
case ConversionRestrictionKind::ExistentialMetatypeToMetatype: {
addContextualScore();
auto instance1 = type1->castTo<ExistentialMetatypeType>()->getInstanceType();
auto instance2 = type2->castTo<MetatypeType>()->getInstanceType();
auto superclass1 = instance1->getSuperclass();
if (!superclass1)
return SolutionKind::Error;
auto result =
matchTypes(superclass1, instance2, ConstraintKind::Subtype, subflags,
locator.withPathElement(ConstraintLocator::InstanceType));
if (!(shouldAttemptFixes() && result.isFailure()))
return result;
return fixContextualFailure(type1, type2, locator)
? getTypeMatchSuccess()
: getTypeMatchFailure(locator);
}
// for $< in { <, <c, <oc }:
// T $< U ===> T $< U?
case ConversionRestrictionKind::ValueToOptional: {
addContextualScore();
increaseScore(SK_ValueToOptional, locator);
assert(matchKind >= ConstraintKind::Subtype);
if (auto generic2 = type2->getAs<BoundGenericType>()) {
if (generic2->getDecl()->isOptionalDecl()) {
auto result = matchTypes(
type1, generic2->getGenericArgs()[0], matchKind, subflags,
locator.withPathElement(ConstraintLocator::OptionalPayload));
if (!(shouldAttemptFixes() && result.isFailure()))
return result;
}
}
return shouldAttemptFixes() && fixContextualFailure(type1, type2, locator)
? SolutionKind::Solved
: SolutionKind::Error;
}
// for $< in { <, <c, <oc }:
// T $< U ===> T? $< U?
// T $< U ===> T! $< U!
// T $< U ===> T! $< U?
// also:
// T <c U ===> T? <c U!
case ConversionRestrictionKind::OptionalToOptional: {
addContextualScore();
assert(matchKind >= ConstraintKind::Subtype);
if (auto generic1 = type1->getAs<BoundGenericType>()) {
if (auto generic2 = type2->getAs<BoundGenericType>()) {
if (generic1->getDecl()->isOptionalDecl() &&
generic2->getDecl()->isOptionalDecl()) {
auto result = matchTypes(
generic1->getGenericArgs()[0], generic2->getGenericArgs()[0],
matchKind, subflags,
locator.withPathElement(LocatorPathElt::GenericArgument(0)));
if (!(shouldAttemptFixes() && result.isFailure()))
return result;
}
}
}
return shouldAttemptFixes() && fixContextualFailure(type1, type2, locator)
? SolutionKind::Solved
: SolutionKind::Error;
}
case ConversionRestrictionKind::ClassMetatypeToAnyObject:
case ConversionRestrictionKind::ExistentialMetatypeToAnyObject:
case ConversionRestrictionKind::ProtocolMetatypeToProtocolClass: {
// Nothing more to solve.
addContextualScore();
return SolutionKind::Solved;
}
// T <p U ===> T[] <a UnsafeMutablePointer<U>
case ConversionRestrictionKind::ArrayToPointer: {
addContextualScore();
// Unwrap an inout type.
auto obj1 = type1->getInOutObjectType();
obj1 = getFixedTypeRecursive(obj1, false);
auto t2 = type2->getDesugaredType();
auto baseType1 = getFixedTypeRecursive(obj1->isArrayType(), false);
auto ptr2 = getBaseTypeForPointer(t2);
increaseScore(SK_ValueToOptional, locator, ptr2.getInt());
return matchPointerBaseTypes({baseType1, 0}, ptr2);
}
// String ===> UnsafePointer<[U]Int8>
case ConversionRestrictionKind::StringToPointer: {
addContextualScore();
auto ptr2 = getBaseTypeForPointer(type2->getDesugaredType());
increaseScore(SK_ValueToOptional, locator, ptr2.getInt());
// The pointer element type must be void or a byte-sized type.
// TODO: Handle different encodings based on pointer element type, such as
// UTF16 for [U]Int16 or UTF32 for [U]Int32. For now we only interop with
// Int8 pointers using UTF8 encoding.
auto baseType2 = getFixedTypeRecursive(ptr2.getPointer(), false);
// If we haven't resolved the element type, generate constraints.
if (baseType2->isTypeVariableOrMember()) {
if (flags.contains(TMF_GenerateConstraints)) {
increaseScore(ScoreKind::SK_ValueToPointerConversion, locator);
auto &ctx = getASTContext();
auto int8Con = Constraint::create(*this, ConstraintKind::Bind,
baseType2,
ctx.getInt8Type(),
getConstraintLocator(locator));
auto uint8Con = Constraint::create(*this, ConstraintKind::Bind,
baseType2,
ctx.getUInt8Type(),
getConstraintLocator(locator));
auto voidCon = Constraint::create(*this, ConstraintKind::Bind,
baseType2, ctx.TheEmptyTupleType,
getConstraintLocator(locator));
Constraint *disjunctionChoices[] = {int8Con, uint8Con, voidCon};
addDisjunctionConstraint(disjunctionChoices, locator);
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
if (!isStringCompatiblePointerBaseType(getASTContext(), baseType2)) {
return SolutionKind::Error;
}
increaseScore(ScoreKind::SK_ValueToPointerConversion, locator);
return SolutionKind::Solved;
}
// T <p U ===> inout T <a UnsafeMutablePointer<U>
case ConversionRestrictionKind::InoutToPointer: {
addContextualScore();
auto t2 = type2->getDesugaredType();
auto baseType1 = type1->getInOutObjectType();
auto ptr2 = getBaseTypeForPointer(t2);
increaseScore(SK_ValueToOptional, locator, ptr2.getInt());
return matchPointerBaseTypes({baseType1, 0}, ptr2);
}
// T <p U ===> UnsafeMutablePointer<T> <a UnsafeMutablePointer<U>
case ConversionRestrictionKind::PointerToPointer: {
auto t1 = type1->getDesugaredType();
auto t2 = type2->getDesugaredType();
auto ptr1 = getBaseTypeForPointer(t1);
auto ptr2 = getBaseTypeForPointer(t2);
return matchPointerBaseTypes(ptr1, ptr2);
}
case ConversionRestrictionKind::PointerToCPointer:
return simplifyPointerToCPointerRestriction(type1, type2, flags, locator);
case ConversionRestrictionKind::ArrayToCPointer: {
auto ptr2 = type2->getDesugaredType()->lookThroughAllOptionalTypes();
PointerTypeKind pointerKind;
auto cPtr = ptr2->getAnyPointerElementType(pointerKind);
// If the parameter is a raw pointer or its element type is not a
// supported (un-)signed integer it implies a regular ArrayToPointer
// conversion.
if (isRawPointerKind(pointerKind) ||
!(cPtr->isInt() || cPtr->isUInt() ||
cPtr->isInt8() || cPtr->isUInt8() ||
cPtr->isInt16() || cPtr->isUInt16() ||
cPtr->isInt32() || cPtr->isUInt32() ||
cPtr->isInt64() || cPtr->isUInt64())) {
return SolutionKind::Error;
}
increaseScore(SK_ValueToPointerConversion, locator);
type1 = getFixedTypeRecursive(type1->getInOutObjectType()->isArrayType(),
/*wantRValue=*/false);
LLVM_FALLTHROUGH;
}
case ConversionRestrictionKind::InoutToCPointer: {
SmallVector<Type, 2> optionals;
auto ptr2 =
type2->getDesugaredType()->lookThroughAllOptionalTypes(optionals);
increaseScore(SK_ValueToOptional, locator, optionals.size());
PointerTypeKind pointerKind;
(void)ptr2->getAnyPointerElementType(pointerKind);
auto baseType1 = type1->getInOutObjectType();
Type ptr1;
// The right-hand size is a raw pointer, so let's use `UnsafeMutablePointer`
// for the `inout` type.
if (pointerKind == PTK_UnsafeRawPointer ||
pointerKind == PTK_UnsafeMutableRawPointer) {
ptr1 = BoundGenericType::get(Context.getUnsafeMutablePointerDecl(),
/*parent=*/nullptr, {baseType1});
} else {
ptr1 = baseType1->wrapInPointer(pointerKind);
}
assert(ptr1);
return simplifyPointerToCPointerRestriction(ptr1, ptr2, flags, locator);
}
// T < U or T is bridged to V where V < U ===> Array<T> <c Array<U>
case ConversionRestrictionKind::ArrayUpcast: {
Type baseType1 = type1->isArrayType();
Type baseType2 = type2->isArrayType();
increaseScore(SK_CollectionUpcastConversion, locator);
return matchTypes(baseType1,
baseType2,
matchKind,
subflags,
locator.withPathElement(
LocatorPathElt::GenericArgument(0)));
}
// K1 < K2 && V1 < V2 || K1 bridges to K2 && V1 bridges to V2 ===>
// Dictionary<K1, V1> <c Dictionary<K2, V2>
case ConversionRestrictionKind::DictionaryUpcast: {
auto t1 = type1->getDesugaredType();
Type key1, value1;
std::tie(key1, value1) = *isDictionaryType(t1);
auto t2 = type2->getDesugaredType();
Type key2, value2;
std::tie(key2, value2) = *isDictionaryType(t2);
auto subMatchKind = matchKind; // TODO: Restrict this?
increaseScore(SK_CollectionUpcastConversion, locator);
// The source key and value types must be subtypes of the destination
// key and value types, respectively.
auto result =
matchTypes(key1, key2, subMatchKind, subflags,
locator.withPathElement(LocatorPathElt::GenericArgument(0)));
if (result.isFailure())
return result;
switch (matchTypes(
value1, value2, subMatchKind, subflags,
locator.withPathElement(LocatorPathElt::GenericArgument(1)))) {
case SolutionKind::Solved:
return result;
case SolutionKind::Unsolved:
return SolutionKind::Unsolved;
case SolutionKind::Error:
return SolutionKind::Error;
}
}
// T1 < T2 || T1 bridges to T2 ===> Set<T1> <c Set<T2>
case ConversionRestrictionKind::SetUpcast: {
Type baseType1 = *isSetType(type1);
Type baseType2 = *isSetType(type2);
increaseScore(SK_CollectionUpcastConversion, locator);
return matchTypes(baseType1,
baseType2,
matchKind,
subflags,
locator.withPathElement(LocatorPathElt::GenericArgument(0)));
}
// T1 <c T2 && T2 : Hashable ===> T1 <c AnyHashable
case ConversionRestrictionKind::HashableToAnyHashable: {
// We never want to do this if the LHS is already AnyHashable.
type1 = simplifyType(type1);
if (type1->getRValueType()->lookThroughAllOptionalTypes()->isAnyHashable()) {
return SolutionKind::Error;
}
addContextualScore();
increaseScore(SK_UserConversion,
locator); // FIXME: Use separate score kind?
if (worseThanBestSolution()) {
return SolutionKind::Error;
}
auto hashableProtocol =
getASTContext().getProtocol(KnownProtocolKind::Hashable);
if (!hashableProtocol)
return SolutionKind::Error;
auto constraintLocator = getConstraintLocator(locator);
auto tv = createTypeVariable(constraintLocator,
TVO_PrefersSubtypeBinding |
TVO_CanBindToNoEscape);
addConstraint(ConstraintKind::ConformsTo, tv,
hashableProtocol->getDeclaredInterfaceType(),
constraintLocator);
return matchTypes(type1, tv, ConstraintKind::Conversion, subflags,
locator);
}
// T' < U and T a toll-free-bridged to T' ===> T' <c U
case ConversionRestrictionKind::CFTollFreeBridgeToObjC: {
increaseScore(SK_UserConversion,
locator); // FIXME: Use separate score kind?
if (worseThanBestSolution()) {
return SolutionKind::Error;
}
auto nativeClass = type1->getClassOrBoundGenericClass();
auto bridgedObjCClass
= nativeClass->getAttrs().getAttribute<ObjCBridgedAttr>()->getObjCClass();
return matchTypes(bridgedObjCClass->getDeclaredInterfaceType(),
type2, ConstraintKind::Subtype, subflags, locator);
}
// T < U' and U a toll-free-bridged to U' ===> T <c U
case ConversionRestrictionKind::ObjCTollFreeBridgeToCF: {
increaseScore(SK_UserConversion,
locator); // FIXME: Use separate score kind?
if (worseThanBestSolution()) {
return SolutionKind::Error;
}
auto nativeClass = type2->getClassOrBoundGenericClass();
auto bridgedObjCClass
= nativeClass->getAttrs().getAttribute<ObjCBridgedAttr>()->getObjCClass();
return matchTypes(type1,
bridgedObjCClass->getDeclaredInterfaceType(),
ConstraintKind::Subtype, subflags, locator);
}
case ConversionRestrictionKind::DoubleToCGFloat:
case ConversionRestrictionKind::CGFloatToDouble: {
// Prefer CGFloat -> Double over other way araund.
auto impact =
restriction == ConversionRestrictionKind::CGFloatToDouble ? 1 : 10;
if (restriction == ConversionRestrictionKind::DoubleToCGFloat) {
if (auto *anchor = locator.trySimplifyToExpr()) {
if (auto depth = getExprDepth(anchor))
impact = (*depth + 1) * impact;
}
}
increaseScore(SK_ImplicitValueConversion, locator, impact);
if (worseThanBestSolution())
return SolutionKind::Error;
auto *conversionLoc =
getImplicitValueConversionLocator(locator, restriction);
auto *applicationLoc =
getConstraintLocator(conversionLoc, ConstraintLocator::ApplyFunction);
auto *memberLoc = getConstraintLocator(
applicationLoc, ConstraintLocator::ConstructorMember);
// Allocate a single argument info to cover all possible
// Double <-> CGFloat conversion locations.
auto *argumentsLoc =
getConstraintLocator(conversionLoc, ConstraintLocator::ApplyArgument);
if (!ArgumentLists.count(argumentsLoc)) {
auto *argList = ArgumentList::createImplicit(
getASTContext(), {Argument(SourceLoc(), Identifier(), nullptr)},
/*firstTrailingClosureIndex=*/std::nullopt,
AllocationArena::ConstraintSolver);
ArgumentLists.insert({argumentsLoc, argList});
}
auto *memberTypeLoc = getConstraintLocator(
applicationLoc, LocatorPathElt::ConstructorMemberType());
auto *memberTy = createTypeVariable(memberTypeLoc, TVO_CanBindToNoEscape);
addValueMemberConstraint(MetatypeType::get(type2, getASTContext()),
DeclNameRef(DeclBaseName::createConstructor()),
memberTy, DC, FunctionRefKind::DoubleApply,
/*outerAlternatives=*/{}, memberLoc);
addConstraint(ConstraintKind::ApplicableFunction,
FunctionType::get({FunctionType::Param(type1)}, type2),
memberTy, applicationLoc);
ImplicitValueConversions.insert(
{getConstraintLocator(locator), restriction});
return SolutionKind::Solved;
}
}
llvm_unreachable("bad conversion restriction");
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyRestrictedConstraint(
ConversionRestrictionKind restriction,
Type type1, Type type2,
ConstraintKind matchKind,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
switch (simplifyRestrictedConstraintImpl(restriction, type1, type2,
matchKind, flags, locator)) {
case SolutionKind::Solved: {
// If we have an application of a non-ephemeral parameter, then record a
// fix if we have to treat an ephemeral conversion as non-ephemeral. It's
// important that this is solved as an independent constraint, as the
// solving of this restriction may be required in order to evaluate it. For
// example, when solving `foo(&.x)`, we need to first match types for the
// inout-to-pointer conversion, which then allows us to resolve the overload
// of `x`, which may or may not produce an ephemeral pointer.
if (locator.isNonEphemeralParameterApplication()) {
bool downgradeToWarning =
!getASTContext().LangOpts.DiagnoseInvalidEphemeralnessAsError;
auto *fix = TreatEphemeralAsNonEphemeral::create(
*this, getConstraintLocator(locator), type1, type2, restriction,
downgradeToWarning);
addFixConstraint(fix, matchKind, type1, type2, locator);
}
ConstraintRestrictions.insert({
std::make_pair(type1.getPointer(), type2.getPointer()), restriction});
return SolutionKind::Solved;
}
case SolutionKind::Unsolved:
return SolutionKind::Unsolved;
case SolutionKind::Error:
return SolutionKind::Error;
}
llvm_unreachable("Unhandled SolutionKind in switch.");
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyPointerToCPointerRestriction(
Type type1, Type type2, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
bool inCorrectPosition = isArgumentOfImportedDecl(locator);
if (!inCorrectPosition) {
// If this is not an imported function, let's not proceed with
// the conversion, unless in diagnostic mode.
if (!shouldAttemptFixes())
return SolutionKind::Error;
// Let's attempt to convert the types and record a tailored
// fix if that succeeds.
}
auto &ctx = getASTContext();
PointerTypeKind swiftPtrKind, cPtrKind;
auto swiftPtr = type1->getAnyPointerElementType(swiftPtrKind);
auto cPtr = type2->getAnyPointerElementType(cPtrKind);
assert(swiftPtr);
assert(cPtr);
auto markSupported = [&]() -> SolutionKind {
// Make sure that solutions with implicit pointer conversions
// are always worse than the ones without them.
increaseScore(SK_ImplicitValueConversion, locator);
if (inCorrectPosition)
return SolutionKind::Solved;
// If conversion cannot be allowed on account of declaration,
// let's add a tailored fix.
auto *fix = AllowSwiftToCPointerConversion::create(
*this, getConstraintLocator(locator));
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
};
auto elementLoc = locator.withPathElement(LocatorPathElt::GenericArgument(0));
if (swiftPtr->isTypeVariableOrMember()) {
// Inference between the equivalent pointer kinds is
// handled by regular pointer conversions.
if (swiftPtrKind == cPtrKind)
return SolutionKind::Error;
addConstraint(ConstraintKind::BindToPointerType, swiftPtr, cPtr,
elementLoc);
return markSupported();
}
// If pointers have the same element type there is nothing to do.
if (swiftPtr->isEqual(cPtr))
return markSupported();
// Unsafe[Mutable]RawPointer -> Unsafe[Mutable]Pointer<[U]Int8>
if (swiftPtrKind == PTK_UnsafeRawPointer ||
swiftPtrKind == PTK_UnsafeMutableRawPointer) {
// Since it's a C pointer on parameter side it would always
// be fully resolved.
if (cPtr->isInt8() || cPtr->isUInt8())
return markSupported();
} else {
// Unsafe[Mutable]Pointer<T> -> Unsafe[Mutable]Pointer<[U]Int8>
if (cPtr->isInt8() || cPtr->isUInt8()) {
// <T> can default to the type of C pointer.
addConstraint(ConstraintKind::Defaultable, swiftPtr, cPtr, elementLoc);
return markSupported();
}
// Unsafe[Mutable]Pointer<Int{8, 16, ...}> <->
// Unsafe[Mutable]Pointer<UInt{8, 16, ...}>
if (swiftPtr->isInt() || swiftPtr->isUInt()) {
addConstraint(ConstraintKind::Equal, cPtr,
swiftPtr->isUInt() ? ctx.getIntType() : ctx.getUIntType(),
elementLoc);
return markSupported();
}
if (swiftPtr->isInt8() || swiftPtr->isUInt8()) {
addConstraint(ConstraintKind::Equal, cPtr,
swiftPtr->isUInt8() ? ctx.getInt8Type()
: ctx.getUInt8Type(),
elementLoc);
return markSupported();
}
if (swiftPtr->isInt16() || swiftPtr->isUInt16()) {
addConstraint(ConstraintKind::Equal, cPtr,
swiftPtr->isUInt16() ? ctx.getInt16Type()
: ctx.getUInt16Type(),
elementLoc);
return markSupported();
}
if (swiftPtr->isInt32() || swiftPtr->isUInt32()) {
addConstraint(ConstraintKind::Equal, cPtr,
swiftPtr->isUInt32() ? ctx.getInt32Type()
: ctx.getUInt32Type(),
elementLoc);
return markSupported();
}
if (swiftPtr->isInt64() || swiftPtr->isUInt64()) {
addConstraint(ConstraintKind::Equal, cPtr,
swiftPtr->isUInt64() ? ctx.getInt64Type()
: ctx.getUInt64Type(),
elementLoc);
return markSupported();
}
}
// If the conversion is unsupported, let's record a generic argument mismatch.
if (shouldAttemptFixes() && !inCorrectPosition) {
auto *fix = AllowArgumentMismatch::create(*this, type1, type2,
getConstraintLocator(locator));
return recordFix(fix, /*impact=*/2) ? SolutionKind::Error
: SolutionKind::Solved;
}
return SolutionKind::Error;
}
static bool isAugmentingFix(ConstraintFix *fix) {
switch (fix->getKind()) {
case FixKind::TreatRValueAsLValue:
return false;
default:
return true;
}
}
bool ConstraintSystem::recordFix(ConstraintFix *fix, unsigned impact) {
if (isDebugMode()) {
auto &log = llvm::errs();
log.indent(solverState ? solverState->getCurrentIndent() : 0)
<< "(attempting fix ";
fix->print(log);
log << ")\n";
}
if (hasArgumentsIgnoredForCodeCompletion()) {
// Avoid simplifying the locator if the constraint system didn't ignore any
// arguments.
auto argExpr = simplifyLocatorToAnchor(fix->getLocator());
if (isArgumentIgnoredForCodeCompletion(getAsExpr<Expr>(argExpr))) {
// The argument was ignored. Don't record any fixes for it.
return false;
}
}
// Record the fix.
// If this should affect the solution score, do so.
if (auto impactScoreKind = fix->impact())
increaseScore(*impactScoreKind, fix->getLocator(), impact);
// If we've made the current solution worse than the best solution we've seen
// already, stop now.
if (worseThanBestSolution())
return true;
if (isAugmentingFix(fix)) {
Fixes.insert(fix);
return false;
}
auto anchor = fix->getAnchor();
assert(bool(anchor) && "non-augmenting fix without an anchor?");
// Only useful to record if no pre-existing fix is associated with
// current anchor or, in case of anchor being an expression, any of
// its sub-expressions.
llvm::SmallDenseSet<ASTNode> anchors;
for (const auto *fix : Fixes) {
// Fixes that don't affect the score shouldn't be considered because even
// if such a fix is recorded at that anchor this should not
// have any affect in the recording of any other fix.
if (!fix->impact())
continue;
anchors.insert(fix->getAnchor());
}
bool found = false;
if (auto *expr = getAsExpr(anchor)) {
forEachExpr(expr, [&](Expr *subExpr) -> Expr * {
found |= anchors.count(subExpr);
return subExpr;
});
} else {
found = anchors.count(anchor);
}
if (!found)
Fixes.insert(fix);
return false;
}
void ConstraintSystem::recordPotentialHole(TypeVariableType *typeVar) {
typeVar->getImpl().enableCanBindToHole(getSavedBindings());
}
void ConstraintSystem::recordAnyTypeVarAsPotentialHole(Type type) {
if (!type->hasTypeVariable())
return;
type.visit([&](Type type) {
if (auto *typeVar = type->getAs<TypeVariableType>()) {
typeVar->getImpl().enableCanBindToHole(getSavedBindings());
}
});
}
void ConstraintSystem::recordTypeVariablesAsHoles(Type type) {
type.visit([&](Type componentTy) {
if (auto *typeVar = componentTy->getAs<TypeVariableType>()) {
// Ignore bound type variables. This can happen if a type variable
// occurs in multiple positions and/or if type hasn't been fully
// simplified before this call.
if (typeVar->getImpl().hasRepresentativeOrFixed())
return;
assignFixedType(typeVar,
PlaceholderType::get(getASTContext(), typeVar));
}
});
}
void ConstraintSystem::recordMatchCallArgumentResult(
ConstraintLocator *locator, MatchCallArgumentResult result) {
assert(locator->isLastElement<LocatorPathElt::ApplyArgument>());
argumentMatchingChoices.insert({locator, result});
}
void ConstraintSystem::recordCallAsFunction(UnresolvedDotExpr *root,
ArgumentList *arguments,
ConstraintLocator *locator) {
ImplicitCallAsFunctionRoots.insert({locator, root});
associateArgumentList(
getConstraintLocator(root, ConstraintLocator::ApplyArgument), arguments);
}
void ConstraintSystem::recordKeyPath(KeyPathExpr *keypath,
TypeVariableType *root,
TypeVariableType *value, DeclContext *dc) {
KeyPaths.insert(std::make_pair(keypath, std::make_tuple(root, value, dc)));
}
ConstraintSystem::SolutionKind ConstraintSystem::simplifyFixConstraint(
ConstraintFix *fix, Type type1, Type type2, ConstraintKind matchKind,
TypeMatchOptions flags, ConstraintLocatorBuilder locator) {
// Try with the fix.
TypeMatchOptions subflags =
getDefaultDecompositionOptions(flags) | TMF_ApplyingFix;
switch (fix->getKind()) {
case FixKind::ForceOptional: {
SmallVector<Type, 4> unwraps1;
type1->lookThroughAllOptionalTypes(unwraps1);
SmallVector<Type, 4> unwraps2;
type2->lookThroughAllOptionalTypes(unwraps2);
auto impact = unwraps1.size() != unwraps2.size()
? unwraps1.size() - unwraps2.size()
: 1;
return recordFix(fix, impact) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::UnwrapOptionalBase:
case FixKind::UnwrapOptionalBaseWithOptionalResult: {
if (recordFix(fix))
return SolutionKind::Error;
type1 = simplifyType(type1);
type2 = simplifyType(type2);
// Explicitly preserve l-valueness of an unwrapped member type.
if (!type1->is<LValueType>() && type2->is<LValueType>())
type1 = LValueType::get(type1);
// First type already appropriately set.
return matchTypes(type1, type2, matchKind, subflags, locator);
}
case FixKind::ForceDowncast:
// These work whenever they are suggested.
if (recordFix(fix))
return SolutionKind::Error;
return SolutionKind::Solved;
case FixKind::AddressOf: {
// Assume that '&' was applied to the first type, turning an lvalue into
// an inout.
auto result = matchTypes(InOutType::get(type1->getRValueType()), type2,
matchKind, subflags, locator);
if (result == SolutionKind::Solved)
if (recordFix(fix))
return SolutionKind::Error;
return result;
}
case FixKind::AutoClosureForwarding: {
if (recordFix(fix))
return SolutionKind::Error;
return matchTypes(type1, type2, matchKind, subflags, locator);
}
case FixKind::AllowTupleTypeMismatch: {
if (fix->getAs<AllowTupleTypeMismatch>()->isElementMismatch()) {
auto *locator = fix->getLocator();
if (recordFix(fix, /*impact*/locator->isForContextualType() ? 5 : 1))
return SolutionKind::Error;
return SolutionKind::Solved;
}
auto lhs = type1->castTo<TupleType>();
auto rhs = type2->castTo<TupleType>();
// Create a new tuple type the size of the smaller tuple with elements
// from the larger tuple whenever either side contains a type variable.
// For example (A, $0, B, $2) and (X, Y, $1) produces: (X, $0, B).
// This allows us to guarantee that the types will match, and all
// type variables will get bound to something as long as we default
// excess types in the larger tuple to Any. In the prior example,
// when the tuples (X, Y, $1) and (X, $0, B) get matched, $0 is equated
// to Y, $1 is equated to B, and $2 is defaulted to Any.
auto lhsLarger = lhs->getNumElements() >= rhs->getNumElements();
auto isLabelingFailure = lhs->getNumElements() == rhs->getNumElements();
auto larger = lhsLarger ? lhs : rhs;
auto smaller = lhsLarger ? rhs : lhs;
llvm::SmallVector<TupleTypeElt, 4> newTupleTypes;
// FIXME: For now, if either side contains pack expansion types, consider
// the fix constraint solved without trying to figure out which tuple
// elements were part of the pack.
{
if (containsPackExpansionType(lhs) ||
containsPackExpansionType(rhs)) {
if (recordFix(fix))
return SolutionKind::Error;
return SolutionKind::Solved;
}
}
for (unsigned i = 0; i < larger->getNumElements(); ++i) {
auto largerElt = larger->getElement(i);
if (i < smaller->getNumElements()) {
auto smallerElt = smaller->getElement(i);
if (isLabelingFailure)
newTupleTypes.push_back(TupleTypeElt(largerElt.getType()));
else if (largerElt.getType()->isTypeVariableOrMember() ||
smallerElt.getType()->isTypeVariableOrMember())
newTupleTypes.push_back(largerElt);
else
newTupleTypes.push_back(smallerElt);
} else {
if (largerElt.getType()->isTypeVariableOrMember())
recordAnyTypeVarAsPotentialHole(largerElt.getType());
}
}
auto matchingType =
TupleType::get(newTupleTypes, getASTContext());
if (recordFix(fix))
return SolutionKind::Error;
return matchTupleTypes(matchingType, smaller, matchKind, subflags, locator);
}
case FixKind::AllowFunctionTypeMismatch: {
if (recordFix(fix, /*impact=*/5))
return SolutionKind::Error;
return SolutionKind::Solved;
}
case FixKind::TreatEphemeralAsNonEphemeral: {
auto *theFix = static_cast<TreatEphemeralAsNonEphemeral *>(fix);
// If we have a non-ephemeral locator for an ephemeral conversion, make a
// note of the fix.
auto conversion = theFix->getConversionKind();
switch (isConversionEphemeral(conversion, locator)) {
case ConversionEphemeralness::Ephemeral:
// Record the fix with an impact of zero. This ensures that non-ephemeral
// diagnostics don't impact solver behavior.
if (recordFix(fix, /*impact*/ 0))
return SolutionKind::Error;
return SolutionKind::Solved;
case ConversionEphemeralness::Unresolved:
case ConversionEphemeralness::NonEphemeral:
// FIXME: The unresolved case should form an unsolved constraint rather
// than being treated as fully solved. This will require a way to connect
// the unsolved constraint to the type variable for the unresolved
// overload such that the fix gets re-activated when the overload is
// bound.
return SolutionKind::Solved;
}
}
case FixKind::AllowSendingMismatch:
case FixKind::InsertCall:
case FixKind::RemoveReturn:
case FixKind::RemoveAddressOf:
case FixKind::AddMissingArguments:
case FixKind::MoveOutOfOrderArgument:
case FixKind::SkipUnhandledConstructInResultBuilder:
case FixKind::UsePropertyWrapper:
case FixKind::UseWrappedValue:
case FixKind::AllowInvalidPropertyWrapperType:
case FixKind::RemoveProjectedValueArgument:
case FixKind::ExpandArrayIntoVarargs:
case FixKind::UseRawValue:
case FixKind::SpecifyBaseTypeForContextualMember:
case FixKind::CoerceToCheckedCast:
case FixKind::SpecifyObjectLiteralTypeImport:
case FixKind::AllowKeyPathRootTypeMismatch:
case FixKind::UnwrapOptionalBaseKeyPathApplication:
case FixKind::AllowCoercionToForceCast:
case FixKind::SpecifyKeyPathRootType:
case FixKind::SpecifyLabelToAssociateTrailingClosure:
case FixKind::AllowKeyPathWithoutComponents:
case FixKind::IgnoreInvalidResultBuilderBody:
case FixKind::IgnoreResultBuilderWithReturnStmts:
case FixKind::SpecifyContextualTypeForNil:
case FixKind::AllowRefToInvalidDecl:
case FixKind::SpecifyBaseTypeForOptionalUnresolvedMember:
case FixKind::SpecifyPackElementType:
case FixKind::AllowCheckedCastCoercibleOptionalType:
case FixKind::AllowNoopCheckedCast:
case FixKind::AllowNoopExistentialToCFTypeCheckedCast:
case FixKind::AllowUnsupportedRuntimeCheckedCast:
case FixKind::AllowCheckedCastToUnrelated:
case FixKind::AllowInvalidStaticMemberRefOnProtocolMetatype:
case FixKind::AllowWrappedValueMismatch:
case FixKind::RemoveExtraneousArguments:
case FixKind::SpecifyTypeForPlaceholder:
case FixKind::AllowAutoClosurePointerConversion:
case FixKind::NotCompileTimeConst:
case FixKind::RenameConflictingPatternVariables:
case FixKind::AllowInvalidPackElement:
case FixKind::AllowInvalidPackReference:
case FixKind::AllowInvalidPackExpansion:
case FixKind::IgnoreWhereClauseInPackIteration:
case FixKind::MacroMissingPound:
case FixKind::AllowGlobalActorMismatch:
case FixKind::AllowAssociatedValueMismatch:
case FixKind::GenericArgumentsMismatch:
case FixKind::AllowConcreteTypeSpecialization:
case FixKind::IgnoreGenericSpecializationArityMismatch:
case FixKind::IgnoreKeyPathSubscriptIndexMismatch: {
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::IgnoreThrownErrorMismatch: {
return recordFix(fix, 2) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::IgnoreInvalidASTNode: {
return recordFix(fix, 10) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::IgnoreUnresolvedPatternVar: {
return recordFix(fix, 100) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::AllowInvalidMemberReferenceInInitAccessor: {
return recordFix(fix, 5) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::ExplicitlyConstructRawRepresentable: {
// Let's increase impact of this fix for binary operators because
// it's possible to get both `.rawValue` and construction fixes for
// different overloads of a binary operator and `.rawValue` is a
// better fix because raw representable has a failable constructor.
return recordFix(fix,
/*impact=*/isExpr<BinaryExpr>(locator.getAnchor()) ? 2 : 1)
? SolutionKind::Error
: SolutionKind::Solved;
}
case FixKind::TreatRValueAsLValue: {
unsigned impact = 1;
// If this is an attempt to use result of a function/subscript call as
// an l-value, it has to have an increased impact because it's either
// a function - which is completely incorrect, or it's a get-only
// subscript, which requires changes to declaration to become mutable.
impact += (locator.endsWith<LocatorPathElt::FunctionResult>() ||
locator.endsWith<LocatorPathElt::SubscriptMember>())
? 1
: 0;
return recordFix(fix, impact) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::AddConformance:
case FixKind::SkipSameTypeRequirement:
case FixKind::SkipSameShapeRequirement:
case FixKind::SkipSuperclassRequirement: {
return recordFix(fix, assessRequirementFailureImpact(*this, type1,
fix->getLocator()))
? SolutionKind::Error
: SolutionKind::Solved;
}
case FixKind::AllowArgumentTypeMismatch:
case FixKind::IgnoreDefaultExprTypeMismatch: {
auto impact = 2;
// If there are any other argument mismatches already detected for this
// call, we increase the score even higher so more argument fixes means
// less viable is the overload.
if (llvm::any_of(getFixes(), [&](const ConstraintFix *fix) {
auto *fixLocator = fix->getLocator();
return fixLocator->findLast<LocatorPathElt::ApplyArgToParam>()
? fixLocator->getAnchor() == locator.getAnchor()
: false;
}))
impact += 3;
// Passing a closure to a parameter that doesn't expect one should
// be scored lower because there might be an overload that expects
// a closure but has other issues e.g. wrong number of parameters.
if (!type2->lookThroughAllOptionalTypes()->is<FunctionType>()) {
auto argument = simplifyLocatorToAnchor(fix->getLocator());
if (isExpr<ClosureExpr>(argument)) {
impact += 2;
}
}
// De-prioritize `Builtin.RawPointer` and `OpaquePointer` parameters
// because they usually clash with generic parameter mismatches e.g.
//
// let ptr: UnsafePointer<String> = ...
// _ = UnsafePointer<Int>(ups)
//
// Here initializer overloads have both `Builtin.RawPointer` and
// `OpaquePointer` variants, but the actual issue is that generic argument
// `String` doesn't match `Int`.
{
if (type2->is<BuiltinRawPointerType>())
impact += 1;
if (type2->getAnyNominal() == getASTContext().getOpaquePointerDecl())
impact += 1;
}
return recordFix(fix, impact) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::TreatArrayLiteralAsDictionary: {
ArrayExpr *AE = getAsExpr<ArrayExpr>(fix->getAnchor());
assert(AE);
// If the array was empty, there's nothing to do.
if (AE->getNumElements() == 0)
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
// For arrays with a single element, match the element type to the
// dictionary's key type.
SmallVector<Type, 2> optionals;
auto dictTy = type2->lookThroughAllOptionalTypes(optionals);
// If the fix is worse than the best solution, there's no point continuing.
if (recordFix(fix, optionals.size() + 1))
return SolutionKind::Error;
// Extract the dictionary key type.
ProtocolDecl *dictionaryProto =
Context.getProtocol(KnownProtocolKind::ExpressibleByDictionaryLiteral);
auto keyAssocTy = dictionaryProto->getAssociatedType(Context.Id_Key);
auto valueBaseTy = createTypeVariable(getConstraintLocator(locator),
TVO_CanBindToLValue |
TVO_CanBindToNoEscape |
TVO_CanBindToHole);
assignFixedType(valueBaseTy, dictTy);
auto dictionaryKeyTy = DependentMemberType::get(valueBaseTy, keyAssocTy);
// Extract the array element type.
auto elemTy = type1->isArrayType();
ConstraintLocator *elemLoc = getConstraintLocator(AE->getElement(0));
ConstraintKind kind = isDictionaryType(dictTy)
? ConstraintKind::Conversion
: ConstraintKind::Equal;
return matchTypes(elemTy, dictionaryKeyTy, kind, subflags, elemLoc);
}
case FixKind::ContextualMismatch:
case FixKind::IgnoreContextualType:
case FixKind::IgnoreAssignmentDestinationType:
case FixKind::AllowConversionThroughInOut:
case FixKind::IgnoreCollectionElementContextualMismatch: {
auto impact = 1;
auto locator = fix->getLocator();
if (auto branchElt =
locator->getLastElementAs<LocatorPathElt::TernaryBranch>()) {
// If this is `else` branch of a ternary operator, let's
// increase its impact to eliminate the chance of ambiguity.
//
// Branches are connected through two `subtype` constraints
// to a common type variable with represents their join, which
// means that result would attempt a type from each side if
// one is available and that would result in two fixes - one for
// each mismatched branch.
if (branchElt->forElse()) {
impact = 10;
} else {
// Also increase impact for `then` branch lower than `else` to still
// eliminate ambiguity, but slightly worst than the average fix to avoid
// so the solution which record this fix wouldn't be picked over one
// that has contextual mismatch fix on the result of ternary expression.
impact = 5;
}
}
using SingleValueStmtResult = LocatorPathElt::SingleValueStmtResult;
if (auto branchElt = locator->getLastElementAs<SingleValueStmtResult>()) {
// Similar to a ternary, except we have N branches. Let's prefer the fix
// on the first branch, and discount subsequent branches by index.
if (branchElt->getIndex() > 0)
impact = 9 + branchElt->getIndex();
}
// Increase impact of invalid conversions to `Any` and `AnyHashable`
// associated with collection elements (i.e. for-in sequence element)
// because it means that other side is structurally incompatible.
if (fix->getKind() == FixKind::IgnoreCollectionElementContextualMismatch) {
if (type2->isAny() || type2->isAnyHashable())
++impact;
}
if (recordFix(fix, impact))
return SolutionKind::Error;
if (auto *fnType1 = type1->getAs<FunctionType>()) {
// If this is a contextual mismatch between two
// function types which we couldn't find a more
// specific fix for. Let's assume that such types
// are completely disjoint and adjust impact of
// the fix accordingly.
if (auto *fnType2 = type2->getAs<FunctionType>()) {
increaseScore(SK_Fix, locator, 10);
} else {
// If type produced by expression is a function type
// with result type matching contextual, it should have
// been diagnosed as "missing explicit call", let's
// increase the score to make sure that we don't impede that.
auto result = matchTypes(fnType1->getResult(), type2, matchKind,
TMF_ApplyingFix, locator);
if (result == SolutionKind::Solved)
increaseScore(SK_Fix, locator);
}
}
return SolutionKind::Solved;
}
case FixKind::AllowNonOptionalWeak: {
if (recordFix(fix))
return SolutionKind::Error;
// NOTE: The order here is important! Pattern matching equality is
// not symmetric (we need to fix that either by using a different
// constraint, or actually making it symmetric).
(void)matchTypes(OptionalType::get(type1), type2, ConstraintKind::Equal,
TypeMatchFlags::TMF_ApplyingFix, locator);
return SolutionKind::Solved;
}
case FixKind::UseSubscriptOperator:
case FixKind::ExplicitlyEscaping:
case FixKind::MarkGlobalActorFunction:
case FixKind::RelabelArguments:
case FixKind::RemoveCall:
case FixKind::RemoveUnwrap:
case FixKind::DefineMemberBasedOnUse:
case FixKind::AllowMemberRefOnExistential:
case FixKind::AllowTypeOrInstanceMember:
case FixKind::AllowInvalidPartialApplication:
case FixKind::AllowInvalidInitRef:
case FixKind::AllowClosureParameterDestructuring:
case FixKind::AllowInaccessibleMember:
case FixKind::AllowAnyObjectKeyPathRoot:
case FixKind::AllowMultiArgFuncKeyPathMismatch:
case FixKind::TreatKeyPathSubscriptIndexAsHashable:
case FixKind::AllowInvalidRefInKeyPath:
case FixKind::DefaultGenericArgument:
case FixKind::AllowMutatingMemberOnRValueBase:
case FixKind::AllowTupleSplatForSingleParameter:
case FixKind::AllowNonClassTypeToConvertToAnyObject:
case FixKind::SpecifyClosureParameterType:
case FixKind::SpecifyClosureReturnType:
case FixKind::AddQualifierToAccessTopLevelName:
case FixKind::AddSendableAttribute:
case FixKind::DropThrowsAttribute:
case FixKind::DropAsyncAttribute:
case FixKind::AllowSwiftToCPointerConversion:
case FixKind::AllowTupleLabelMismatch:
case FixKind::AddExplicitExistentialCoercion:
case FixKind::DestructureTupleToMatchPackExpansionParameter:
case FixKind::AllowValueExpansionWithoutPackReferences:
case FixKind::IgnoreInvalidPatternInExpr:
case FixKind::IgnoreOutOfPlaceThenStmt:
case FixKind::IgnoreMissingEachKeyword:
llvm_unreachable("handled elsewhere");
}
llvm_unreachable("Unhandled FixKind in switch.");
}
ConstraintSystem::SolutionKind
ConstraintSystem::addConstraintImpl(ConstraintKind kind, Type first,
Type second,
ConstraintLocatorBuilder locator,
bool isFavored) {
assert(first && "Missing first type");
assert(second && "Missing second type");
TypeMatchOptions subflags = TMF_GenerateConstraints;
switch (kind) {
case ConstraintKind::Equal:
case ConstraintKind::Bind:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Subtype:
case ConstraintKind::Conversion:
return matchTypes(first, second, kind, subflags, locator);
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion:
return addArgumentConversionConstraintImpl(kind, first, second, locator);
case ConstraintKind::BridgingConversion:
return simplifyBridgingConstraint(first, second, subflags, locator);
case ConstraintKind::ApplicableFunction: {
// First try to simplify the overload set for the function being applied.
if (simplifyAppliedOverloads(second, first->castTo<FunctionType>(),
locator)) {
return SolutionKind::Error;
}
return simplifyApplicableFnConstraint(first, second, std::nullopt, subflags,
locator);
}
case ConstraintKind::DynamicCallableApplicableFunction:
return simplifyDynamicCallableApplicableFnConstraint(first, second,
subflags, locator);
case ConstraintKind::DynamicTypeOf:
return simplifyDynamicTypeOfConstraint(first, second, subflags, locator);
case ConstraintKind::EscapableFunctionOf:
return simplifyEscapableFunctionOfConstraint(first, second,
subflags, locator);
case ConstraintKind::OpenedExistentialOf:
return simplifyOpenedExistentialOfConstraint(first, second,
subflags, locator);
case ConstraintKind::SubclassOf:
return simplifySubclassOfConstraint(first, second, locator, subflags);
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::SelfObjectOfProtocol:
return simplifyConformsToConstraint(first, second, kind, locator,
subflags);
case ConstraintKind::TransitivelyConformsTo:
return simplifyTransitivelyConformsTo(first, second, locator,
subflags);
case ConstraintKind::CheckedCast:
return simplifyCheckedCastConstraint(first, second, subflags, locator);
case ConstraintKind::OptionalObject:
return simplifyOptionalObjectConstraint(first, second, subflags, locator);
case ConstraintKind::Defaultable:
return simplifyDefaultableConstraint(first, second, subflags, locator);
case ConstraintKind::PropertyWrapper:
return simplifyPropertyWrapperConstraint(first, second, subflags, locator);
case ConstraintKind::OneWayEqual:
case ConstraintKind::OneWayBindParam:
return simplifyOneWayConstraint(kind, first, second, subflags, locator);
case ConstraintKind::UnresolvedMemberChainBase:
return simplifyUnresolvedMemberChainBaseConstraint(first, second, subflags,
locator);
case ConstraintKind::BindTupleOfFunctionParams:
return simplifyBindTupleOfFunctionParamsConstraint(first, second, subflags,
locator);
case ConstraintKind::PackElementOf:
return simplifyPackElementOfConstraint(first, second, subflags, locator);
case ConstraintKind::ShapeOf:
return simplifyShapeOfConstraint(first, second, subflags, locator);
case ConstraintKind::SameShape:
return simplifySameShapeConstraint(first, second, subflags, locator);
case ConstraintKind::ExplicitGenericArguments:
return simplifyExplicitGenericArgumentsConstraint(
first, second, subflags, locator);
case ConstraintKind::MaterializePackExpansion:
return simplifyMaterializePackExpansionConstraint(first, second, subflags,
locator);
case ConstraintKind::ValueMember:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueWitness:
case ConstraintKind::BindOverload:
case ConstraintKind::Disjunction:
case ConstraintKind::Conjunction:
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
case ConstraintKind::FallbackType:
case ConstraintKind::SyntacticElement:
llvm_unreachable("Use the correct addConstraint()");
}
llvm_unreachable("Unhandled ConstraintKind in switch.");
}
ConstraintSystem::SolutionKind
ConstraintSystem::addArgumentConversionConstraintImpl(
ConstraintKind kind, Type first, Type second,
ConstraintLocatorBuilder locator) {
assert(kind == ConstraintKind::ArgumentConversion ||
kind == ConstraintKind::OperatorArgumentConversion);
// If we have an unresolved closure argument, form an unsolved argument
// conversion constraint, making sure to reference the type variables for
// a result builder if applicable. This ensures we properly connect the
// closure type variable with any type variables in the result builder, as
// such type variables will be accessible within the body of the closure when
// we open it.
first = getFixedTypeRecursive(first, /*rvalue*/ false);
if (auto *argTypeVar = first->getAs<TypeVariableType>()) {
if (argTypeVar->getImpl().isClosureType()) {
// Extract any type variables present in the parameter's result builder.
SmallPtrSet<TypeVariableType *, 4> typeVars;
if (auto builderTy = getOpenedResultBuilderTypeFor(*this, locator))
builderTy->getTypeVariables(typeVars);
SmallVector<TypeVariableType *, 4> referencedVars{typeVars.begin(),
typeVars.end()};
auto *loc = getConstraintLocator(locator);
addUnsolvedConstraint(
Constraint::create(*this, kind, first, second, loc, referencedVars));
return SolutionKind::Solved;
}
}
return matchTypes(first, second, kind, TMF_GenerateConstraints, locator);
}
void
ConstraintSystem::addKeyPathApplicationRootConstraint(Type root, ConstraintLocatorBuilder locator) {
// If this is a subscript with a KeyPath expression, add a constraint that
// connects the subscript's root type to the root type of the KeyPath.
SmallVector<LocatorPathElt, 4> path;
auto anchor = locator.getLocatorParts(path);
auto subscript = getAsExpr<SubscriptExpr>(anchor);
if (!subscript)
return;
assert((path.size() == 1 &&
path[0].getKind() == ConstraintLocator::SubscriptMember) ||
(path.size() == 2 &&
path[1].getKind() == ConstraintLocator::KeyPathDynamicMember));
// If a keypath subscript is used without the expected `keyPath:` label,
// continue with type-checking when attempting fixes so that it gets caught
// by the argument label checking.
auto *argList = subscript->getArgs();
auto *unaryArg = argList->getUnaryExpr();
assert(unaryArg && "Expected KeyPathExpr apply to have single argument");
auto *keyPathExpr = dyn_cast<KeyPathExpr>(unaryArg);
if (!keyPathExpr)
return;
auto typeVar = getType(keyPathExpr)->getAs<TypeVariableType>();
if (!typeVar)
return;
auto constraints = CG.gatherConstraints(
typeVar, ConstraintGraph::GatheringKind::EquivalenceClass,
[&keyPathExpr](Constraint *constraint) -> bool {
if (constraint->getKind() != ConstraintKind::KeyPath)
return false;
auto *locator = constraint->getLocator();
if (auto KPE = getAsExpr<KeyPathExpr>(locator->getAnchor()))
return KPE == keyPathExpr;
return false;
});
for (auto constraint : constraints) {
auto keyPathRootTy = constraint->getSecondType();
addConstraint(ConstraintKind::Subtype, root->getWithoutSpecifierType(),
keyPathRootTy, locator);
}
}
void
ConstraintSystem::addKeyPathApplicationConstraint(Type keypath,
Type root, Type value,
ConstraintLocatorBuilder locator,
bool isFavored) {
addKeyPathApplicationRootConstraint(root, locator);
switch (simplifyKeyPathApplicationConstraint(keypath, root, value,
TMF_GenerateConstraints,
locator)) {
case SolutionKind::Error:
if (shouldRecordFailedConstraint()) {
auto c = Constraint::create(*this, ConstraintKind::KeyPathApplication,
keypath, root, value,
getConstraintLocator(locator));
if (isFavored) c->setFavored();
recordFailedConstraint(c);
}
return;
case SolutionKind::Solved:
return;
case SolutionKind::Unsolved:
llvm_unreachable("should have generated constraints");
}
}
void
ConstraintSystem::addKeyPathConstraint(
Type keypath,
Type root, Type value,
ArrayRef<TypeVariableType *> componentTypeVars,
ConstraintLocatorBuilder locator,
bool isFavored) {
switch (simplifyKeyPathConstraint(keypath, root, value,
componentTypeVars,
TMF_GenerateConstraints,
locator)) {
case SolutionKind::Error:
if (shouldRecordFailedConstraint()) {
auto c = Constraint::create(*this, ConstraintKind::KeyPath,
keypath, root, value,
getConstraintLocator(locator),
componentTypeVars);
if (isFavored) c->setFavored();
recordFailedConstraint(c);
}
return;
case SolutionKind::Solved:
return;
case SolutionKind::Unsolved:
llvm_unreachable("should have generated constraints");
}
}
void ConstraintSystem::addConstraint(Requirement req,
ConstraintLocatorBuilder locator,
bool isFavored) {
bool conformsToAnyObject = false;
std::optional<ConstraintKind> kind;
switch (req.getKind()) {
case RequirementKind::SameShape: {
auto type1 = req.getFirstType();
auto type2 = req.getSecondType();
addConstraint(ConstraintKind::SameShape, type1, type2, locator);
return;
}
case RequirementKind::Conformance:
kind = ConstraintKind::ConformsTo;
break;
case RequirementKind::Superclass: {
// FIXME: Should always use ConstraintKind::SubclassOf, but that breaks
// a couple of diagnostics
if (auto *typeVar = req.getFirstType()->getAs<TypeVariableType>()) {
if (typeVar->getImpl().canBindToPack()) {
kind = ConstraintKind::SubclassOf;
break;
}
}
conformsToAnyObject = true;
kind = ConstraintKind::Subtype;
break;
}
case RequirementKind::SameType:
kind = ConstraintKind::Bind;
break;
case RequirementKind::Layout:
// Only a class constraint can be modeled as a constraint, and only that can
// appear outside of a @_specialize at the moment anyway.
if (req.getLayoutConstraint()->isClass()) {
conformsToAnyObject = true;
break;
} else {
llvm_unreachable("unexpected LayoutConstraint kind");
}
return;
}
auto firstType = req.getFirstType();
if (kind) {
addConstraint(*kind, req.getFirstType(), req.getSecondType(), locator,
isFavored);
}
if (conformsToAnyObject) {
auto anyObject = getASTContext().getAnyObjectConstraint();
addConstraint(ConstraintKind::ConformsTo, firstType, anyObject, locator);
}
}
void ConstraintSystem::addConstraint(ConstraintKind kind, Type first,
Type second,
ConstraintLocatorBuilder locator,
bool isFavored) {
switch (addConstraintImpl(kind, first, second, locator, isFavored)) {
case SolutionKind::Error:
// Add a failing constraint, if needed.
if (shouldRecordFailedConstraint()) {
auto c = Constraint::create(*this, kind, first, second,
getConstraintLocator(locator));
if (isFavored) c->setFavored();
recordFailedConstraint(c);
}
return;
case SolutionKind::Unsolved:
llvm_unreachable("should have generated constraints");
case SolutionKind::Solved:
return;
}
}
void ConstraintSystem::addContextualConversionConstraint(
Expr *expr, Type conversionType, ContextualTypePurpose purpose,
ConstraintLocator *locator) {
if (conversionType.isNull())
return;
// Determine the type of the constraint.
auto constraintKind = ConstraintKind::Conversion;
switch (purpose) {
case CTP_ReturnStmt:
case CTP_Initialization: {
if (conversionType->is<OpaqueTypeArchetypeType>())
constraintKind = ConstraintKind::Equal;
// Alternatively, we might have a nested opaque archetype, e.g. `(some P)?`.
// In that case, we want `ConstraintKind::Conversion`.
break;
}
case CTP_CallArgument:
constraintKind = ConstraintKind::ArgumentConversion;
break;
case CTP_YieldByReference:
// In a by-reference yield, we expect the contextual type to be an
// l-value type, so the result must be bound to that.
constraintKind = ConstraintKind::Bind;
break;
case CTP_DiscardStmt:
// For the 'discard X', we always expect the contextual type to be
// equal to the type of 'self'.
constraintKind = ConstraintKind::Equal;
break;
case CTP_ForEachSequence:
// Sequence expression associated with `for-in` loop has to conform
// to `Sequence` or `AsyncSequence` protocol depending on the context.
constraintKind = ConstraintKind::ConformsTo;
break;
case CTP_ArrayElement:
case CTP_AssignSource:
case CTP_CalleeResult:
case CTP_CannotFail:
case CTP_Condition:
case CTP_Unused:
case CTP_YieldByValue:
case CTP_CaseStmt:
case CTP_ThrowStmt:
case CTP_EnumCaseRawValue:
case CTP_DefaultParameter:
case CTP_AutoclosureDefaultParameter:
case CTP_ClosureResult:
case CTP_DictionaryKey:
case CTP_DictionaryValue:
case CTP_CoerceOperand:
case CTP_SubscriptAssignSource:
case CTP_ForEachStmt:
case CTP_WrappedProperty:
case CTP_ComposedPropertyWrapper:
case CTP_ExprPattern:
case CTP_SingleValueStmtBranch:
break;
}
// Add the constraint.
auto openedType = openOpaqueType(conversionType, purpose, locator);
addConstraint(constraintKind, getType(expr), openedType, locator,
/*isFavored*/ true);
}
void ConstraintSystem::addFixConstraint(ConstraintFix *fix, ConstraintKind kind,
Type first, Type second,
ConstraintLocatorBuilder locator,
bool isFavored) {
TypeMatchOptions subflags = TMF_GenerateConstraints;
switch (simplifyFixConstraint(fix, first, second, kind, subflags, locator)) {
case SolutionKind::Error:
// Add a failing constraint, if needed.
if (shouldRecordFailedConstraint()) {
auto c = Constraint::createFixed(*this, kind, fix, first, second,
getConstraintLocator(locator));
if (isFavored) c->setFavored();
recordFailedConstraint(c);
}
return;
case SolutionKind::Unsolved:
llvm_unreachable("should have generated constraints");
case SolutionKind::Solved:
return;
}
}
void ConstraintSystem::addExplicitConversionConstraint(
Type fromType, Type toType, RememberChoice_t rememberChoice,
ConstraintLocatorBuilder locator, ConstraintFix *compatFix) {
SmallVector<Constraint *, 3> constraints;
auto locatorPtr = getConstraintLocator(locator);
// Coercion (the common case).
Constraint *coerceConstraint =
Constraint::create(*this, ConstraintKind::Conversion,
fromType, toType, locatorPtr);
coerceConstraint->setFavored();
constraints.push_back(coerceConstraint);
// The source type can be explicitly converted to the destination type.
Constraint *bridgingConstraint =
Constraint::create(*this, ConstraintKind::BridgingConversion,
fromType, toType, locatorPtr);
constraints.push_back(bridgingConstraint);
// If we're allowed to use a compatibility fix that emits a warning on
// failure, add it to the disjunction so that it's recorded on failure.
if (compatFix) {
constraints.push_back(
Constraint::createFixed(*this, ConstraintKind::BridgingConversion,
compatFix, fromType, toType, locatorPtr));
}
addDisjunctionConstraint(constraints, locator, rememberChoice);
}
TypeVariableType *ConstraintSystem::addMaterializePackExpansionConstraint(
Type tupleType, ConstraintLocatorBuilder locator) {
assert(isSingleUnlabeledPackExpansionTuple(tupleType));
TypeVariableType *packVar =
createTypeVariable(getConstraintLocator(locator), TVO_CanBindToPack);
addConstraint(ConstraintKind::MaterializePackExpansion, tupleType, packVar,
getConstraintLocator(locator, {ConstraintLocator::Member}));
return packVar;
}
ConstraintSystem::SolutionKind
ConstraintSystem::simplifyConstraint(const Constraint &constraint) {
auto matchKind = constraint.getKind();
switch (matchKind) {
case ConstraintKind::Bind:
case ConstraintKind::Equal:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Subtype:
case ConstraintKind::Conversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion: {
// Relational constraints.
// If there is a fix associated with this constraint, apply it.
if (auto fix = constraint.getFix()) {
return simplifyFixConstraint(fix, constraint.getFirstType(),
constraint.getSecondType(), matchKind,
std::nullopt, constraint.getLocator());
}
// If there is a restriction on this constraint, apply it directly rather
// than going through the general \c matchTypes() machinery.
if (auto restriction = constraint.getRestriction()) {
return simplifyRestrictedConstraint(
*restriction, constraint.getFirstType(), constraint.getSecondType(),
matchKind, std::nullopt, constraint.getLocator());
}
return matchTypes(constraint.getFirstType(), constraint.getSecondType(),
matchKind, std::nullopt, constraint.getLocator());
}
case ConstraintKind::BridgingConversion:
// If there is a fix associated with this constraint, apply it.
if (auto fix = constraint.getFix()) {
return simplifyFixConstraint(fix, constraint.getFirstType(),
constraint.getSecondType(), matchKind,
std::nullopt, constraint.getLocator());
}
return simplifyBridgingConstraint(constraint.getFirstType(),
constraint.getSecondType(), std::nullopt,
constraint.getLocator());
case ConstraintKind::ApplicableFunction:
return simplifyApplicableFnConstraint(
constraint.getFirstType(), constraint.getSecondType(),
constraint.getTrailingClosureMatching(), std::nullopt,
constraint.getLocator());
case ConstraintKind::DynamicCallableApplicableFunction:
return simplifyDynamicCallableApplicableFnConstraint(
constraint.getFirstType(), constraint.getSecondType(), std::nullopt,
constraint.getLocator());
case ConstraintKind::DynamicTypeOf:
return simplifyDynamicTypeOfConstraint(
constraint.getFirstType(), constraint.getSecondType(), std::nullopt,
constraint.getLocator());
case ConstraintKind::EscapableFunctionOf:
return simplifyEscapableFunctionOfConstraint(
constraint.getFirstType(), constraint.getSecondType(), std::nullopt,
constraint.getLocator());
case ConstraintKind::OpenedExistentialOf:
return simplifyOpenedExistentialOfConstraint(
constraint.getFirstType(), constraint.getSecondType(), std::nullopt,
constraint.getLocator());
case ConstraintKind::KeyPath:
return simplifyKeyPathConstraint(
constraint.getFirstType(), constraint.getSecondType(),
constraint.getThirdType(), constraint.getTypeVariables(), std::nullopt,
constraint.getLocator());
case ConstraintKind::KeyPathApplication:
return simplifyKeyPathApplicationConstraint(
constraint.getFirstType(), constraint.getSecondType(),
constraint.getThirdType(), std::nullopt, constraint.getLocator());
case ConstraintKind::BindOverload:
if (auto *fix = constraint.getFix()) {
// TODO(diagnostics): Impact should be associated with a fix unless
// it's a contextual problem, then only solver can decide what the impact
// would be in each particular situation.
auto impact =
fix->getKind() == FixKind::AddQualifierToAccessTopLevelName ? 10 : 1;
if (recordFix(fix, impact))
return SolutionKind::Error;
}
resolveOverload(constraint.getLocator(), constraint.getFirstType(),
constraint.getOverloadChoice(),
constraint.getOverloadUseDC());
return SolutionKind::Solved;
case ConstraintKind::SubclassOf:
return simplifySubclassOfConstraint(constraint.getFirstType(),
constraint.getSecondType(),
constraint.getLocator(),
/*flags*/ std::nullopt);
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::SelfObjectOfProtocol:
return simplifyConformsToConstraint(
constraint.getFirstType(), constraint.getSecondType(),
constraint.getKind(), constraint.getLocator(), std::nullopt);
case ConstraintKind::TransitivelyConformsTo:
return simplifyTransitivelyConformsTo(
constraint.getFirstType(), constraint.getSecondType(),
constraint.getLocator(), std::nullopt);
case ConstraintKind::CheckedCast: {
auto result = simplifyCheckedCastConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
// NOTE: simplifyCheckedCastConstraint() may return Unsolved, e.g. if the
// subexpression's type is unresolved. Don't record the fix until we
// successfully simplify the constraint.
if (result == SolutionKind::Solved) {
if (auto *fix = constraint.getFix()) {
if (recordFix(fix)) {
return SolutionKind::Error;
}
}
}
return result;
}
case ConstraintKind::OptionalObject:
return simplifyOptionalObjectConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::ValueMember:
case ConstraintKind::UnresolvedValueMember:
return simplifyMemberConstraint(
constraint.getKind(), constraint.getFirstType(), constraint.getMember(),
constraint.getSecondType(), constraint.getMemberUseDC(),
constraint.getFunctionRefKind(),
/*outerAlternatives=*/{},
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::ValueWitness:
return simplifyValueWitnessConstraint(
constraint.getKind(), constraint.getFirstType(),
constraint.getRequirement(), constraint.getSecondType(),
constraint.getMemberUseDC(), constraint.getFunctionRefKind(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::Defaultable:
return simplifyDefaultableConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::FallbackType:
return simplifyFallbackTypeConstraint(
constraint.getFirstType(), constraint.getSecondType(),
constraint.getTypeVariables(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::PropertyWrapper:
return simplifyPropertyWrapperConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::Disjunction:
case ConstraintKind::Conjunction:
// See {Dis, Con}junctionStep class in CSStep.cpp for solving
return SolutionKind::Unsolved;
case ConstraintKind::OneWayEqual:
case ConstraintKind::OneWayBindParam:
return simplifyOneWayConstraint(
constraint.getKind(), constraint.getFirstType(),
constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::UnresolvedMemberChainBase:
return simplifyUnresolvedMemberChainBaseConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags=*/std::nullopt, constraint.getLocator());
case ConstraintKind::SyntacticElement:
return simplifySyntacticElementConstraint(
constraint.getSyntacticElement(), constraint.getElementContext(),
constraint.isDiscardedElement(),
/*flags=*/std::nullopt, constraint.getLocator());
case ConstraintKind::BindTupleOfFunctionParams:
return simplifyBindTupleOfFunctionParamsConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::PackElementOf:
return simplifyPackElementOfConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::ShapeOf:
return simplifyShapeOfConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::SameShape:
return simplifySameShapeConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::ExplicitGenericArguments:
return simplifyExplicitGenericArgumentsConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
case ConstraintKind::MaterializePackExpansion:
return simplifyMaterializePackExpansionConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ std::nullopt, constraint.getLocator());
}
llvm_unreachable("Unhandled ConstraintKind in switch.");
}
void ConstraintSystem::simplifyDisjunctionChoice(Constraint *choice) {
// Simplify this term in the disjunction.
switch (simplifyConstraint(*choice)) {
case ConstraintSystem::SolutionKind::Error:
recordFailedConstraint(choice);
break;
case ConstraintSystem::SolutionKind::Solved:
break;
case ConstraintSystem::SolutionKind::Unsolved:
addUnsolvedConstraint(choice);
break;
}
}
|