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
|
//===--- TypeCheckConcurrency.cpp - Concurrency ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 type checking support for Swift's concurrency model.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckDistributed.h"
#include "TypeCheckInvertible.h"
#include "TypeChecker.h"
#include "TypeCheckType.h"
#include "swift/Strings.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/Sema/IDETypeChecking.h"
using namespace swift;
/// Determine whether it makes sense to infer an attribute in the given
/// context.
static bool shouldInferAttributeInContext(const DeclContext *dc) {
if (auto *file = dyn_cast<FileUnit>(dc->getModuleScopeContext())) {
switch (file->getKind()) {
case FileUnitKind::Source:
// Check what kind of source file we have.
if (auto sourceFile = dc->getParentSourceFile()) {
switch (sourceFile->Kind) {
case SourceFileKind::Interface:
// Interfaces have explicitly called-out Sendable conformances.
return false;
case SourceFileKind::DefaultArgument:
case SourceFileKind::Library:
case SourceFileKind::MacroExpansion:
case SourceFileKind::Main:
case SourceFileKind::SIL:
return true;
}
}
break;
case FileUnitKind::Builtin:
case FileUnitKind::SerializedAST:
case FileUnitKind::Synthesized:
return false;
case FileUnitKind::ClangModule:
case FileUnitKind::DWARFModule:
return true;
}
return true;
}
return false;
}
void swift::addAsyncNotes(AbstractFunctionDecl const* func) {
assert(func);
if (!isa<DestructorDecl>(func) && !isa<AccessorDecl>(func)) {
auto note =
func->diagnose(diag::note_add_async_to_function, func);
if (func->hasThrows()) {
auto replacement = func->getAttrs().hasAttribute<RethrowsAttr>()
? "async rethrows"
: "async throws";
note.fixItReplace(SourceRange(func->getThrowsLoc()), replacement);
} else if (func->getParameters()->getRParenLoc().isValid()) {
note.fixItInsert(func->getParameters()->getRParenLoc().getAdvancedLoc(1),
" async");
}
}
}
static bool requiresFlowIsolation(ActorIsolation typeIso,
ConstructorDecl const *ctor) {
assert(ctor->isDesignatedInit());
auto ctorIso = getActorIsolation(const_cast<ConstructorDecl *>(ctor));
// Regardless of async-ness, a mismatch in isolation means we need to be
// flow-sensitive.
if (typeIso != ctorIso)
return true;
// Otherwise, if it's an actor instance, then it depends on async-ness.
switch (typeIso.getKind()) {
case ActorIsolation::GlobalActor:
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
return false;
case ActorIsolation::Erased:
llvm_unreachable("constructor cannot have erased isolation");
case ActorIsolation::ActorInstance:
return !(ctor->hasAsync()); // need flow-isolation for non-async.
};
}
bool swift::usesFlowSensitiveIsolation(AbstractFunctionDecl const *fn) {
if (!fn)
return false;
// Only designated constructors or destructors use this kind of isolation.
if (auto const* ctor = dyn_cast<ConstructorDecl>(fn)) {
if (!ctor->isDesignatedInit())
return false;
} else if (!isa<DestructorDecl>(fn)) {
return false;
}
auto *dc = fn->getDeclContext();
if (!dc)
return false;
// Must be part of a nominal type.
auto *nominal = dc->getSelfNominalTypeDecl();
if (!nominal)
return false;
// If it's part of an actor type, then its deinit and some of its inits use
// flow-isolation.
if (nominal->isAnyActor()) {
if (isa<DestructorDecl>(fn))
return true;
// construct an isolation corresponding to the type.
auto actorTypeIso = ActorIsolation::forActorInstanceSelf(
const_cast<AbstractFunctionDecl *>(fn));
return requiresFlowIsolation(actorTypeIso, cast<ConstructorDecl>(fn));
}
// Otherwise, the type must be isolated to a global actor.
auto nominalIso = getActorIsolation(nominal);
if (!nominalIso.isGlobalActor())
return false;
// if it's a deinit, then it's flow-isolated.
if (isa<DestructorDecl>(fn))
return true;
return requiresFlowIsolation(nominalIso, cast<ConstructorDecl>(fn));
}
bool IsActorRequest::evaluate(
Evaluator &evaluator, NominalTypeDecl *nominal) const {
// Protocols are actors if they inherit from `Actor`.
if (auto protocol = dyn_cast<ProtocolDecl>(nominal)) {
auto &ctx = protocol->getASTContext();
auto *actorProtocol = ctx.getProtocol(KnownProtocolKind::Actor);
if (!actorProtocol)
return false;
return (protocol == actorProtocol ||
protocol->inheritsFrom(actorProtocol));
}
// Class declarations are actors if they were declared with "actor".
auto classDecl = dyn_cast<ClassDecl>(nominal);
if (!classDecl)
return false;
return classDecl->isExplicitActor();
}
bool IsDefaultActorRequest::evaluate(
Evaluator &evaluator, ClassDecl *classDecl, ModuleDecl *M,
ResilienceExpansion expansion) const {
// If the class isn't an actor, it's not a default actor.
if (!classDecl->isActor())
return false;
// Distributed actors were not able to have custom executors until Swift 5.9,
// so in order to avoid wrongly treating a resilient distributed actor from another
// module as not-default we need to handle this case explicitly.
if (classDecl->isDistributedActor()) {
ASTContext &ctx = classDecl->getASTContext();
auto customExecutorAvailability =
ctx.getConcurrencyDistributedActorWithCustomExecutorAvailability();
auto actorAvailability = TypeChecker::overApproximateAvailabilityAtLocation(
classDecl->getStartLoc(),
classDecl);
if (!actorAvailability.isContainedIn(customExecutorAvailability)) {
// Any 'distributed actor' declared with availability lower than the
// introduction of custom executors for distributed actors, must be treated as default actor,
// even if it were to declared the unowned executor property, as older compilers
// do not have the logic to handle that case.
return true;
}
}
// If the class is resilient from the perspective of the module
// module, it's not a default actor.
if (classDecl->isForeign() || classDecl->isResilient(M, expansion))
return false;
// Check whether the class has explicit custom-actor methods.
// If we synthesized the unownedExecutor property, we should've
// added a semantics attribute to it (if it was actually a default
// actor).
bool foundExecutorPropertyImpl = false;
bool isDefaultActor = false;
if (auto executorProperty = classDecl->getUnownedExecutorProperty()) {
foundExecutorPropertyImpl = true;
isDefaultActor = isDefaultActor ||
executorProperty->getAttrs().hasSemanticsAttr(SEMANTICS_DEFAULT_ACTOR);
}
// Only if we found one of the executor properties, do we return the status of default or not,
// based on the findings of the semantics attribute of that located property.
if (foundExecutorPropertyImpl) {
if (!isDefaultActor &&
classDecl->getASTContext().LangOpts.isConcurrencyModelTaskToThread() &&
!AvailableAttr::isUnavailable(classDecl)) {
classDecl->diagnose(
diag::concurrency_task_to_thread_model_custom_executor,
"task-to-thread concurrency model");
}
return isDefaultActor;
}
// Otherwise, we definitely are a default actor.
return true;
}
VarDecl *GlobalActorInstanceRequest::evaluate(
Evaluator &evaluator, NominalTypeDecl *nominal) const {
auto globalActorAttr = nominal->getAttrs().getAttribute<GlobalActorAttr>();
if (!globalActorAttr)
return nullptr;
// Ensure that the actor protocol has been loaded.
ASTContext &ctx = nominal->getASTContext();
auto actorProto = ctx.getProtocol(KnownProtocolKind::Actor);
if (!actorProto) {
nominal->diagnose(diag::concurrency_lib_missing, "Actor");
return nullptr;
}
// Non-final classes cannot be global actors.
if (auto classDecl = dyn_cast<ClassDecl>(nominal)) {
if (!classDecl->isSemanticallyFinal()) {
nominal->diagnose(diag::global_actor_non_final_class, nominal->getName())
.highlight(globalActorAttr->getRangeWithAt());
}
}
// Global actors have a static property "shared" that provides an actor
// instance. The value must be of Actor type, which is validated by
// conformance to the 'GlobalActor' protocol.
SmallVector<ValueDecl *, 4> decls;
nominal->lookupQualified(
nominal, DeclNameRef(ctx.Id_shared),
nominal->getLoc(), NL_QualifiedDefault, decls);
for (auto decl : decls) {
auto var = dyn_cast<VarDecl>(decl);
if (!var)
continue;
if (var->getDeclContext() == nominal && var->isStatic())
return var;
}
return nullptr;
}
std::optional<std::pair<CustomAttr *, NominalTypeDecl *>>
swift::checkGlobalActorAttributes(SourceLoc loc, DeclContext *dc,
ArrayRef<CustomAttr *> attrs) {
ASTContext &ctx = dc->getASTContext();
CustomAttr *globalActorAttr = nullptr;
NominalTypeDecl *globalActorNominal = nullptr;
for (auto attr : attrs) {
// Figure out which nominal declaration this custom attribute refers to.
auto *nominal = evaluateOrDefault(ctx.evaluator,
CustomAttrNominalRequest{attr, dc},
nullptr);
if (!nominal)
continue;
// We are only interested in global actor types.
if (!nominal->isGlobalActor())
continue;
// Only a single global actor can be applied to a given entity.
if (globalActorAttr) {
ctx.Diags.diagnose(
loc, diag::multiple_global_actors, globalActorNominal->getName(),
nominal->getName());
continue;
}
globalActorAttr = const_cast<CustomAttr *>(attr);
globalActorNominal = nominal;
}
if (!globalActorAttr)
return std::nullopt;
return std::make_pair(globalActorAttr, globalActorNominal);
}
std::optional<std::pair<CustomAttr *, NominalTypeDecl *>>
GlobalActorAttributeRequest::evaluate(
Evaluator &evaluator,
llvm::PointerUnion<Decl *, ClosureExpr *> subject) const {
DeclContext *dc = nullptr;
DeclAttributes *declAttrs = nullptr;
SourceLoc loc;
if (auto decl = subject.dyn_cast<Decl *>()) {
dc = decl->getDeclContext();
declAttrs = &decl->getAttrs();
// HACK: `getLoc`, when querying the attr from a serialized decl,
// depending on deserialization order, may launch into arbitrary
// type-checking when querying interface types of such decls. Which,
// in turn, may do things like query (to print) USRs. This ends up being
// prone to request evaluator cycles.
//
// Because this only applies to serialized decls, we can be confident
// that they already went through this type-checking as primaries, so,
// for now, to avoid cycles, we simply ignore the locs on serialized decls
// only.
// This is a workaround for rdar://79563942
loc = decl->getLoc(/* SerializedOK */ false);
} else {
auto closure = subject.get<ClosureExpr *>();
dc = closure;
declAttrs = &closure->getAttrs();
loc = closure->getLoc();
}
// Collect the attributes.
SmallVector<CustomAttr *, 2> attrs;
for (auto attr : declAttrs->getAttributes<CustomAttr>()) {
auto mutableAttr = const_cast<CustomAttr *>(attr);
attrs.push_back(mutableAttr);
}
// Look for a global actor attribute.
auto result = checkGlobalActorAttributes(loc, dc, attrs);
if (!result)
return std::nullopt;
// Closures can always have a global actor attached.
if (auto closure = subject.dyn_cast<ClosureExpr *>()) {
return result;
}
// Check that a global actor attribute makes sense on this kind of
// declaration.
auto decl = subject.get<Decl *>();
// no further checking required if it's from a serialized module.
if (decl->getDeclContext()->getParentSourceFile() == nullptr)
return result;
auto isStoredInstancePropertyOfStruct = [](VarDecl *var) {
if (var->isStatic() || !var->isOrdinaryStoredProperty())
return false;
auto *nominal = var->getDeclContext()->getSelfNominalTypeDecl();
return isa_and_nonnull<StructDecl>(nominal) &&
!isWrappedValueOfPropWrapper(var);
};
auto globalActorAttr = result->first;
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
// Nominal types are okay...
if (auto classDecl = dyn_cast<ClassDecl>(nominal)){
if (classDecl->isActor()) {
// ... except for actors.
nominal->diagnose(diag::global_actor_on_actor_class, nominal->getName())
.highlight(globalActorAttr->getRangeWithAt());
return std::nullopt;
}
}
} else if (auto storage = dyn_cast<AbstractStorageDecl>(decl)) {
// Subscripts and properties are fine...
if (auto var = dyn_cast<VarDecl>(storage)) {
// ... but not if it's an async-context top-level global
if (var->isTopLevelGlobal() &&
(var->getDeclContext()->isAsyncContext() ||
var->getASTContext().LangOpts.StrictConcurrencyLevel >=
StrictConcurrency::Complete)) {
var->diagnose(diag::global_actor_top_level_var)
.highlight(globalActorAttr->getRangeWithAt());
return std::nullopt;
}
// ... and not if it's local property
if (var->getDeclContext()->isLocalContext()) {
var->diagnose(diag::global_actor_on_local_variable, var->getName())
.highlight(globalActorAttr->getRangeWithAt());
return std::nullopt;
}
}
} else if (isa<ExtensionDecl>(decl)) {
// Extensions are okay.
} else if (isa<ConstructorDecl>(decl) || isa<FuncDecl>(decl)) {
// None of the accessors/addressors besides a getter are allowed
// to have a global actor attribute.
if (auto *accessor = dyn_cast<AccessorDecl>(decl)) {
if (!accessor->isGetter()) {
decl->diagnose(diag::global_actor_disallowed,
decl->getDescriptiveKind())
.warnUntilSwiftVersion(6)
.fixItRemove(globalActorAttr->getRangeWithAt());
auto &ctx = decl->getASTContext();
auto *storage = accessor->getStorage();
// Let's suggest to move the attribute to the storage if
// this is an accessor/addressor of a property of subscript.
if (storage->getDeclContext()->isTypeContext()) {
auto canMoveAttr = [&]() {
// If enclosing declaration has a global actor,
// skip the suggestion.
if (storage->getGlobalActorAttr())
return false;
// Global actor attribute cannot be applied to
// an instance stored property of a struct.
if (auto *var = dyn_cast<VarDecl>(storage)) {
return !isStoredInstancePropertyOfStruct(var);
}
return true;
};
if (canMoveAttr()) {
decl->diagnose(diag::move_global_actor_attr_to_storage_decl,
storage)
.fixItInsert(
storage->getAttributeInsertionLoc(/*forModifier=*/false),
llvm::Twine("@", result->second->getNameStr()).str());
}
}
// In Swift 6, once the diag above is an error, it is disallowed.
if (ctx.isSwiftVersionAtLeast(6))
return std::nullopt;
}
}
// Functions are okay.
} else {
// Everything else is disallowed.
decl->diagnose(diag::global_actor_disallowed, decl->getDescriptiveKind());
return std::nullopt;
}
return result;
}
Type swift::getExplicitGlobalActor(ClosureExpr *closure) {
// Look at the explicit attribute.
auto globalActorAttr =
evaluateOrDefault(closure->getASTContext().evaluator,
GlobalActorAttributeRequest{closure}, std::nullopt);
if (!globalActorAttr)
return Type();
Type globalActor = evaluateOrDefault(
closure->getASTContext().evaluator,
CustomAttrTypeRequest{
globalActorAttr->first, closure, CustomAttrTypeKind::GlobalActor},
Type());
if (!globalActor || globalActor->hasError())
return Type();
return globalActor;
}
/// A 'let' declaration is safe across actors if it is either
/// nonisolated or it is accessed from within the same module.
static bool varIsSafeAcrossActors(const ModuleDecl *fromModule,
VarDecl *var,
const ActorIsolation &varIsolation,
ActorReferenceResult::Options &options) {
bool accessWithinModule =
(fromModule == var->getDeclContext()->getParentModule());
if (varIsolation.getKind() == ActorIsolation::NonisolatedUnsafe)
return true;
if (!var->isLet()) {
// A mutable storage of a value type accessed from within the module is
// okay.
if (dyn_cast_or_null<StructDecl>(var->getDeclContext()->getAsDecl()) &&
!var->isStatic() && var->hasStorage() &&
var->getTypeInContext()->isSendableType()) {
if (accessWithinModule || varIsolation.isNonisolated())
return true;
}
// Otherwise, must be immutable.
return false;
}
switch (varIsolation) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
// if nonisolated, it's OK
return true;
case ActorIsolation::Erased:
llvm_unreachable("variable cannot have erased isolation");
case ActorIsolation::ActorInstance:
case ActorIsolation::GlobalActor:
// If it's explicitly 'nonisolated', it's okay.
if (var->getAttrs().hasAttribute<NonisolatedAttr>())
return true;
// Static 'let's are initialized upon first access, so they cannot be
// synchronously accessed across actors.
if (var->isGlobalStorage() && var->isLazilyInitializedGlobal()) {
// Compiler versions <= 5.9 accepted this code, so downgrade to a
// warning prior to Swift 6.
options = ActorReferenceResult::Flags::Preconcurrency;
return false;
}
// If it's distributed, generally variable access is not okay...
if (auto nominalParent = var->getDeclContext()->getSelfNominalTypeDecl()) {
if (nominalParent->isDistributedActor())
return false;
}
// If the type is not 'Sendable', it's unsafe
if (!var->getTypeInContext()->isSendableType()) {
// Compiler versions <= 5.10 treated this variable as nonisolated,
// so downgrade async access errors in the effects checker to
// warnings prior to Swift 6.
if (accessWithinModule)
options = ActorReferenceResult::Flags::Preconcurrency;
return false;
}
// If it's actor-isolated but in the same module, then it's OK too.
return accessWithinModule;
}
}
bool swift::isLetAccessibleAnywhere(const ModuleDecl *fromModule,
VarDecl *let,
ActorReferenceResult::Options &options) {
auto isolation = getActorIsolation(let);
return varIsSafeAcrossActors(fromModule, let, isolation, options);
}
bool swift::isLetAccessibleAnywhere(const ModuleDecl *fromModule,
VarDecl *let) {
ActorReferenceResult::Options options = std::nullopt;
return isLetAccessibleAnywhere(fromModule, let, options);
}
namespace {
/// Describes the important parts of a partial apply thunk.
struct PartialApplyThunkInfo {
Expr *base;
Expr *fn;
bool isEscaping;
};
}
/// Try to decompose a call that might be an invocation of a partial apply
/// thunk.
static std::optional<PartialApplyThunkInfo>
decomposePartialApplyThunk(ApplyExpr *apply, Expr *parent) {
// Check for a call to the outer closure in the thunk.
auto outerAutoclosure = dyn_cast<AutoClosureExpr>(apply->getFn());
if (!outerAutoclosure || outerAutoclosure->getThunkKind() !=
AutoClosureExpr::Kind::DoubleCurryThunk)
return std::nullopt;
auto *unarySelfArg = apply->getArgs()->getUnlabeledUnaryExpr();
assert(unarySelfArg &&
"Double curry should start with a unary (Self) -> ... arg");
auto memberFn = outerAutoclosure->getUnwrappedCurryThunkExpr();
if (!memberFn)
return std::nullopt;
// Determine whether the partial apply thunk was immediately converted to
// noescape.
bool isEscaping = true;
if (auto conversion = dyn_cast_or_null<FunctionConversionExpr>(parent)) {
auto fnType = conversion->getType()->getAs<FunctionType>();
isEscaping = fnType && !fnType->isNoEscape();
}
return PartialApplyThunkInfo{unarySelfArg, memberFn, isEscaping};
}
/// Find the immediate member reference in the given expression.
static std::optional<std::pair<ConcreteDeclRef, SourceLoc>>
findReference(Expr *expr) {
// Look through a function conversion.
if (auto fnConv = dyn_cast<FunctionConversionExpr>(expr))
expr = fnConv->getSubExpr();
if (auto declRef = dyn_cast<DeclRefExpr>(expr))
return std::make_pair(declRef->getDeclRef(), declRef->getLoc());
if (auto otherCtor = dyn_cast<OtherConstructorDeclRefExpr>(expr)) {
return std::make_pair(otherCtor->getDeclRef(), otherCtor->getLoc());
}
Expr *inner = expr->getValueProvidingExpr();
if (inner != expr)
return findReference(inner);
return std::nullopt;
}
/// Return true if the callee of an ApplyExpr is async
///
/// Note that this must be called after the implicitlyAsync flag has been set,
/// or implicitly async calls will not return the correct value.
static bool isAsyncCall(
llvm::PointerUnion<ApplyExpr *, LookupExpr *> call) {
if (auto *apply = call.dyn_cast<ApplyExpr *>()) {
if (apply->isImplicitlyAsync())
return true;
// Effectively the same as doing a
// `cast_or_null<FunctionType>(call->getFn()->getType())`, check the
// result of that and then checking `isAsync` if it's defined.
Type funcTypeType = apply->getFn()->getType();
if (!funcTypeType)
return false;
AnyFunctionType *funcType = funcTypeType->getAs<AnyFunctionType>();
if (!funcType)
return false;
return funcType->isAsync();
}
auto *lookup = call.get<LookupExpr *>();
if (lookup->isImplicitlyAsync())
return true;
return isAsyncDecl(lookup->getDecl());
}
/// Determine whether we should diagnose data races within the current context.
///
/// By default, we do this only in code that makes use of concurrency
/// features.
static bool shouldDiagnoseExistingDataRaces(const DeclContext *dc);
/// Determine whether this closure should be treated as Sendable.
///
/// \param forActorIsolation Whether this check is for the purposes of
/// determining whether the closure must be non-isolated.
static bool isSendableClosure(
const AbstractClosureExpr *closure, bool forActorIsolation) {
if (auto explicitClosure = dyn_cast<ClosureExpr>(closure)) {
if (forActorIsolation && explicitClosure->inheritsActorContext()) {
return false;
}
}
if (auto type = closure->getType()) {
if (auto fnType = type->getAs<AnyFunctionType>())
if (fnType->isSendable())
return true;
}
return false;
}
/// Returns true if this closure acts as an inference boundary in the AST. An
/// inference boundary is an expression in the AST where we newly infer
/// isolation different from our parent decl context.
///
/// Examples:
///
/// 1. a @Sendable closure.
/// 2. a closure literal passed to a sending parameter.
///
/// NOTE: This does not mean that it has nonisolated isolation since for
/// instance one could define an @MainActor closure in a nonisolated
/// function. That @MainActor closure would act as an Isolation Inference
/// Boundary.
///
/// \arg forActorIsolation we currently have two slightly varying semantics
/// here. If this is set, then we assuming that we are being called recursively
/// while walking up a decl context path to determine the actor isolation of a
/// closure. In such a case, we do not want to be a boundary if we should
/// inheritActorContext. In other contexts though, we want to determine if the
/// closure is part of an init or deinit. In such a case, we are walking up the
/// decl context chain and we want to stop if we see a sending parameter since
/// in such a case, the sending closure parameter is known to not be part of the
/// init or deinit.
static bool
isIsolationInferenceBoundaryClosure(const AbstractClosureExpr *closure,
bool forActorIsolation) {
if (auto *ce = dyn_cast<ClosureExpr>(closure)) {
if (!forActorIsolation) {
// For example, one would along this path see if for flow sensitive
// isolation the closure is part of an init or deinit.
if (ce->isPassedToSendingParameter())
return true;
} else {
// This is for actor isolation. If we have inheritActorContext though, we
// do not want to do anything since we are part of our parent's isolation.
if (!ce->inheritsActorContext() && ce->isPassedToSendingParameter())
return true;
}
}
// An autoclosure for an async let acts as a boundary. It is non-Sendable
// regardless of its context.
if (auto *autoclosure = dyn_cast<AutoClosureExpr>(closure)) {
if (autoclosure->getThunkKind() == AutoClosureExpr::Kind::AsyncLet)
return true;
}
return isSendableClosure(closure, forActorIsolation);
}
/// Add Fix-It text for the given nominal type to adopt Sendable.
static void addSendableFixIt(
const NominalTypeDecl *nominal, InFlightDiagnostic &diag, bool unchecked) {
if (nominal->getInherited().empty()) {
SourceLoc fixItLoc = nominal->getBraces().Start;
diag.fixItInsert(fixItLoc,
unchecked ? ": @unchecked Sendable" : ": Sendable");
} else {
auto fixItLoc = nominal->getInherited().getEndLoc();
diag.fixItInsertAfter(fixItLoc,
unchecked ? ", @unchecked Sendable" : ", Sendable");
}
}
/// Add Fix-It text for the given generic param declaration type to adopt
/// Sendable.
static void addSendableFixIt(const GenericTypeParamDecl *genericArgument,
InFlightDiagnostic &diag, bool unchecked) {
if (genericArgument->getInherited().empty()) {
auto fixItLoc = genericArgument->getLoc();
diag.fixItInsertAfter(fixItLoc,
unchecked ? ": @unchecked Sendable" : ": Sendable");
} else {
auto fixItLoc = genericArgument->getInherited().getEndLoc();
diag.fixItInsertAfter(fixItLoc,
unchecked ? ", @unchecked Sendable" : ", Sendable");
}
}
static bool shouldDiagnoseExistingDataRaces(const DeclContext *dc) {
return contextRequiresStrictConcurrencyChecking(dc, [](const AbstractClosureExpr *) {
return Type();
},
[](const ClosureExpr *closure) {
return closure->isIsolatedByPreconcurrency();
});
}
bool SendableCheckContext::warnInMinimalChecking() const {
if (preconcurrencyContext)
return false;
if (!conformanceCheck)
return false;
switch (*conformanceCheck) {
case SendableCheck::Explicit:
return true;
case SendableCheck::ImpliedByStandardProtocol:
case SendableCheck::Implicit:
case SendableCheck::ImplicitForExternallyVisible:
return false;
}
}
DiagnosticBehavior SendableCheckContext::defaultDiagnosticBehavior() const {
// If we're not supposed to diagnose existing data races from this context,
// ignore the diagnostic entirely.
if (!warnInMinimalChecking() &&
!shouldDiagnoseExistingDataRaces(fromDC))
return DiagnosticBehavior::Ignore;
return DiagnosticBehavior::Warning;
}
DiagnosticBehavior
SendableCheckContext::implicitSendableDiagnosticBehavior() const {
switch (fromDC->getASTContext().LangOpts.StrictConcurrencyLevel) {
case StrictConcurrency::Targeted:
// Limited checking only diagnoses implicit Sendable within contexts that
// have adopted concurrency.
if (shouldDiagnoseExistingDataRaces(fromDC))
return DiagnosticBehavior::Warning;
LLVM_FALLTHROUGH;
case StrictConcurrency::Minimal:
if (warnInMinimalChecking())
return DiagnosticBehavior::Warning;
return DiagnosticBehavior::Ignore;
case StrictConcurrency::Complete:
return defaultDiagnosticBehavior();
}
}
/// Determine whether the given nominal type has an explicit Sendable
/// conformance (regardless of its availability).
bool swift::hasExplicitSendableConformance(NominalTypeDecl *nominal,
bool applyModuleDefault) {
ASTContext &ctx = nominal->getASTContext();
auto nominalModule = nominal->getParentModule();
// In a concurrency-checked module, a missing conformance is equivalent to
// an explicitly unavailable one. If we want to apply this rule, do so now.
if (applyModuleDefault && nominalModule->isConcurrencyChecked())
return true;
// Look for any conformance to `Sendable`.
auto proto = ctx.getProtocol(KnownProtocolKind::Sendable);
if (!proto)
return false;
// Look for a conformance. If it's present and not (directly) missing,
// we're done.
auto conformance = nominalModule->lookupConformance(
nominal->getDeclaredInterfaceType(), proto, /*allowMissing=*/true);
return conformance &&
!(isa<BuiltinProtocolConformance>(conformance.getConcrete()) &&
cast<BuiltinProtocolConformance>(
conformance.getConcrete())->isMissing());
}
/// Determine the diagnostic behavior for a Sendable reference to the given
/// nominal type.
DiagnosticBehavior SendableCheckContext::diagnosticBehavior(
NominalTypeDecl *nominal) const {
// If we're in a preconcurrency context, don't override the default behavior
// based on explicit conformances. For example, a @preconcurrency @Sendable
// closure should not warn about an explicitly unavailable Sendable
// conformance in minimal checking.
if (preconcurrencyContext)
return defaultDiagnosticBehavior();
if (hasExplicitSendableConformance(nominal))
return DiagnosticBehavior::Warning;
DiagnosticBehavior defaultBehavior = implicitSendableDiagnosticBehavior();
// If we are checking an implicit Sendable conformance, don't suppress
// diagnostics for declarations in the same module. We want them to make
// enclosing inferred types non-Sendable.
if (defaultBehavior == DiagnosticBehavior::Ignore &&
nominal->getParentSourceFile() &&
conformanceCheck && isImplicitSendableCheck(*conformanceCheck))
return DiagnosticBehavior::Warning;
return defaultBehavior;
}
std::optional<DiagnosticBehavior>
swift::getConcurrencyDiagnosticBehaviorLimit(NominalTypeDecl *nominal,
const DeclContext *fromDC,
bool ignoreExplicitConformance) {
ModuleDecl *importedModule = nullptr;
if (nominal->getAttrs().hasAttribute<PreconcurrencyAttr>()) {
// If the declaration itself has the @preconcurrency attribute,
// respect it.
importedModule = nominal->getParentModule();
} else {
// Determine whether this nominal type is visible via a @preconcurrency
// import.
auto import = nominal->findImport(fromDC);
auto sourceFile = fromDC->getParentSourceFile();
if (!import || !import->options.contains(ImportFlags::Preconcurrency))
return std::nullopt;
if (sourceFile)
sourceFile->setImportUsedPreconcurrency(*import);
importedModule = import->module.importedModule;
}
// When the type is explicitly non-Sendable, @preconcurrency imports
// downgrade the diagnostic to a warning in Swift 6.
if (!ignoreExplicitConformance &&
hasExplicitSendableConformance(nominal))
return DiagnosticBehavior::Warning;
// When the type is implicitly non-Sendable, `@preconcurrency` suppresses
// diagnostics until the imported module enables Swift 6.
return importedModule->isConcurrencyChecked()
? DiagnosticBehavior::Warning
: DiagnosticBehavior::Ignore;
}
std::optional<DiagnosticBehavior>
SendableCheckContext::preconcurrencyBehavior(
Decl *decl,
bool ignoreExplicitConformance) const {
if (!decl)
return std::nullopt;
if (auto *nominal = dyn_cast<NominalTypeDecl>(decl)) {
return getConcurrencyDiagnosticBehaviorLimit(nominal, fromDC,
ignoreExplicitConformance);
}
return std::nullopt;
}
static bool shouldDiagnosePreconcurrencyImports(SourceFile &sf) {
switch (sf.Kind) {
case SourceFileKind::Interface:
case SourceFileKind::SIL:
return false;
case SourceFileKind::DefaultArgument:
case SourceFileKind::Library:
case SourceFileKind::Main:
case SourceFileKind::MacroExpansion:
return true;
}
}
bool swift::diagnoseSendabilityErrorBasedOn(
NominalTypeDecl *nominal, SendableCheckContext fromContext,
llvm::function_ref<bool(DiagnosticBehavior)> diagnose) {
auto behavior = DiagnosticBehavior::Unspecified;
if (nominal) {
behavior = fromContext.diagnosticBehavior(nominal);
} else {
behavior = fromContext.implicitSendableDiagnosticBehavior();
}
bool wasSuppressed = diagnose(behavior);
SourceFile *sourceFile = fromContext.fromDC->getParentSourceFile();
if (sourceFile && shouldDiagnosePreconcurrencyImports(*sourceFile)) {
bool emittedDiagnostics =
behavior != DiagnosticBehavior::Ignore && !wasSuppressed;
// When the type is explicitly Sendable *or* explicitly non-Sendable, we
// assume it has been audited and `@preconcurrency` is not recommended even
// though it would actually affect the diagnostic.
bool nominalIsImportedAndHasImplicitSendability =
nominal &&
nominal->getParentModule() != fromContext.fromDC->getParentModule() &&
!hasExplicitSendableConformance(nominal);
if (emittedDiagnostics && nominalIsImportedAndHasImplicitSendability) {
// This type was imported from another module; try to find the
// corresponding import.
std::optional<AttributedImport<swift::ImportedModule>> import =
nominal->findImport(fromContext.fromDC);
// If we found the import that makes this nominal type visible, remark
// that it can be @preconcurrency import.
// Only emit this remark once per source file, because it can happen a
// lot.
if (import && !import->options.contains(ImportFlags::Preconcurrency) &&
import->importLoc.isValid() && sourceFile &&
!sourceFile->hasImportUsedPreconcurrency(*import)) {
SourceLoc importLoc = import->importLoc;
ASTContext &ctx = nominal->getASTContext();
ctx.Diags
.diagnose(importLoc, diag::add_predates_concurrency_import,
ctx.LangOpts.isSwiftVersionAtLeast(6),
nominal->getParentModule()->getName())
.fixItInsert(importLoc, "@preconcurrency ");
sourceFile->setImportUsedPreconcurrency(*import);
}
}
}
return behavior == DiagnosticBehavior::Unspecified && !wasSuppressed;
}
void swift::diagnoseUnnecessaryPreconcurrencyImports(SourceFile &sf) {
// NOTE: Disabled in Swift 6.0.
return;
}
/// Produce a diagnostic for a single instance of a non-Sendable type where
/// a Sendable type is required.
static bool diagnoseSingleNonSendableType(
Type type, SendableCheckContext fromContext,
Type inDerivedConformance, SourceLoc loc,
llvm::function_ref<bool(Type, DiagnosticBehavior)> diagnose) {
if (type->hasError())
return false;
auto module = fromContext.fromDC->getParentModule();
auto nominal = type->getAnyNominal();
auto &ctx = module->getASTContext();
return diagnoseSendabilityErrorBasedOn(nominal, fromContext,
[&](DiagnosticBehavior behavior) {
bool wasSuppressed = diagnose(type, behavior);
// Don't emit the following notes if we didn't have any diagnostics to
// attach them to.
if (wasSuppressed || behavior == DiagnosticBehavior::Ignore)
return true;
if (inDerivedConformance) {
ctx.Diags.diagnose(loc, diag::in_derived_conformance,
inDerivedConformance);
}
if (type->is<FunctionType>()) {
ctx.Diags.diagnose(loc, diag::nonsendable_function_type);
} else if (nominal && nominal->getParentModule() == module) {
// If the nominal type is in the current module, suggest adding
// `Sendable` if it might make sense. Otherwise, just complain.
if (isa<StructDecl>(nominal) || isa<EnumDecl>(nominal)) {
auto note = nominal->diagnose(
diag::add_nominal_sendable_conformance, nominal);
addSendableFixIt(nominal, note, /*unchecked=*/false);
} else {
nominal->diagnose(diag::non_sendable_nominal, nominal);
}
} else if (nominal) {
// Note which nominal type does not conform to `Sendable`.
nominal->diagnose(diag::non_sendable_nominal, nominal);
} else if (auto genericArchetype = type->getAs<ArchetypeType>()) {
auto interfaceType = genericArchetype->getInterfaceType();
if (auto genericParamType =
interfaceType->getAs<GenericTypeParamType>()) {
auto *genericParamTypeDecl = genericParamType->getDecl();
if (genericParamTypeDecl &&
genericParamTypeDecl->getModuleContext() == module) {
auto diag = genericParamTypeDecl->diagnose(
diag::add_generic_parameter_sendable_conformance, type);
addSendableFixIt(genericParamTypeDecl, diag, /*unchecked=*/false);
}
}
}
return false;
});
}
bool swift::diagnoseNonSendableTypes(
Type type, SendableCheckContext fromContext,
Type inDerivedConformance, SourceLoc loc,
llvm::function_ref<bool(Type, DiagnosticBehavior)> diagnose) {
auto module = fromContext.fromDC->getParentModule();
// If the Sendable protocol is missing, do nothing.
auto proto = module->getASTContext().getProtocol(KnownProtocolKind::Sendable);
if (!proto)
return false;
// FIXME: More detail for unavailable conformances.
auto conformance = module->lookupConformance(type, proto, /*allowMissing=*/true);
if (conformance.isInvalid() || conformance.hasUnavailableConformance()) {
return diagnoseSingleNonSendableType(
type, fromContext, inDerivedConformance, loc, diagnose);
}
// Walk the conformance, diagnosing any missing Sendable conformances.
bool anyMissing = false;
conformance.forEachMissingConformance(
[&](BuiltinProtocolConformance *missing) {
if (diagnoseSingleNonSendableType(
missing->getType(), fromContext,
inDerivedConformance, loc, diagnose)) {
anyMissing = true;
}
return false;
});
return anyMissing;
}
bool swift::diagnoseNonSendableTypesInReference(
Expr *base, ConcreteDeclRef declRef, const DeclContext *fromDC,
SourceLoc refLoc, SendableCheckReason refKind,
std::optional<ActorIsolation> knownIsolation,
FunctionCheckOptions funcCheckOptions, SourceLoc diagnoseLoc) {
// Retrieve the actor isolation to use in diagnostics.
auto getActorIsolation = [&] {
if (knownIsolation)
return *knownIsolation;
return swift::getActorIsolation(declRef.getDecl());
};
// If the violation is in the implementation of a derived conformance,
// point to the location of the parent type instead.
Type derivedConformanceType;
if (refLoc.isInvalid()) {
auto *decl = fromDC->getAsDecl();
if (decl && decl->isImplicit()) {
if (auto *implements = decl->getAttrs().getAttribute<ImplementsAttr>()) {
auto *parentDC = decl->getDeclContext();
refLoc = parentDC->getAsDecl()->getLoc();
derivedConformanceType =
implements->getProtocol(parentDC)->getDeclaredInterfaceType();
}
}
}
// Check the 'self' argument.
if (base) {
if (diagnoseNonSendableTypes(
base->getType(),
fromDC, derivedConformanceType,
base->getStartLoc(),
diag::non_sendable_param_type,
(unsigned)refKind, declRef.getDecl(),
getActorIsolation()))
return true;
}
// For functions, check the parameter and result types.
SubstitutionMap subs = declRef.getSubstitutions();
if (auto function = dyn_cast<AbstractFunctionDecl>(declRef.getDecl())) {
if (funcCheckOptions.contains(FunctionCheckKind::Params)) {
// only check params if funcCheckKind specifies so
for (auto param : *function->getParameters()) {
Type paramType = param->getInterfaceType().subst(subs);
if (diagnoseNonSendableTypes(
paramType, fromDC, derivedConformanceType,
refLoc, diagnoseLoc.isInvalid() ? refLoc : diagnoseLoc,
diag::non_sendable_param_type,
(unsigned)refKind, function, getActorIsolation()))
return true;
}
}
// Check the result type of a function.
if (auto func = dyn_cast<FuncDecl>(function)) {
if (funcCheckOptions.contains(FunctionCheckKind::Results)) {
// only check results if funcCheckKind specifies so
Type resultType = func->getResultInterfaceType().subst(subs);
if (diagnoseNonSendableTypes(
resultType, fromDC, derivedConformanceType,
refLoc, diagnoseLoc.isInvalid() ? refLoc : diagnoseLoc,
diag::non_sendable_result_type,
(unsigned)refKind, func, getActorIsolation()))
return true;
}
}
return false;
}
if (auto var = dyn_cast<VarDecl>(declRef.getDecl())) {
Type propertyType = var->isLocalCapture()
? var->getTypeInContext()
: var->getValueInterfaceType().subst(subs);
if (diagnoseNonSendableTypes(
propertyType, fromDC,
derivedConformanceType, refLoc,
diag::non_sendable_property_type,
var,
var->isLocalCapture(),
(unsigned)refKind,
getActorIsolation()))
return true;
}
if (auto subscript = dyn_cast<SubscriptDecl>(declRef.getDecl())) {
for (auto param : *subscript->getIndices()) {
if (funcCheckOptions.contains(FunctionCheckKind::Params)) {
// Check params of this subscript override for sendability
Type paramType = param->getInterfaceType().subst(subs);
if (diagnoseNonSendableTypes(
paramType, fromDC, derivedConformanceType,
refLoc, diagnoseLoc.isInvalid() ? refLoc : diagnoseLoc,
diag::non_sendable_param_type,
(unsigned)refKind, subscript, getActorIsolation()))
return true;
}
}
if (funcCheckOptions.contains(FunctionCheckKind::Results)) {
// Check the element type of a subscript.
Type resultType = subscript->getElementInterfaceType().subst(subs);
if (diagnoseNonSendableTypes(
resultType, fromDC, derivedConformanceType,
refLoc, diagnoseLoc.isInvalid() ? refLoc : diagnoseLoc,
diag::non_sendable_result_type,
(unsigned)refKind, subscript, getActorIsolation()))
return true;
}
return false;
}
return false;
}
void swift::diagnoseMissingSendableConformance(
SourceLoc loc, Type type, const DeclContext *fromDC, bool preconcurrency) {
SendableCheckContext sendableContext(fromDC, preconcurrency);
diagnoseNonSendableTypes(
type, sendableContext, /*inDerivedConformance*/Type(),
loc, diag::non_sendable_type);
}
namespace {
/// Infer Sendable from the instance storage of the given nominal type.
/// \returns \c std::nullopt if there is no way to make the type \c Sendable,
/// \c true if \c Sendable needs to be @unchecked, \c false if it can be
/// \c Sendable without the @unchecked.
std::optional<bool>
inferSendableFromInstanceStorage(NominalTypeDecl *nominal,
SmallVectorImpl<Requirement> &requirements) {
// Raw storage is assumed not to be sendable.
if (auto sd = dyn_cast<StructDecl>(nominal)) {
if (sd->getAttrs().hasAttribute<RawLayoutAttr>()) {
return true;
}
}
class Visitor : public StorageVisitor {
public:
NominalTypeDecl *nominal;
SmallVectorImpl<Requirement> &requirements;
bool isUnchecked = false;
ProtocolDecl *sendableProto = nullptr;
Visitor(NominalTypeDecl *nominal,
SmallVectorImpl<Requirement> &requirements)
: StorageVisitor(), nominal(nominal), requirements(requirements) {
ASTContext &ctx = nominal->getASTContext();
sendableProto = ctx.getProtocol(KnownProtocolKind::Sendable);
}
bool operator()(VarDecl *var, Type propertyType) override {
// If we have a class with mutable state, only an @unchecked
// conformance will work.
if (isa<ClassDecl>(nominal) && var->supportsMutation())
isUnchecked = true;
return checkType(propertyType);
}
bool operator()(EnumElementDecl *element, Type elementType) override {
return checkType(elementType);
}
/// Check sendability of the given type, recording any requirements.
bool checkType(Type type) {
if (!sendableProto)
return true;
auto module = nominal->getParentModule();
auto conformance = module->checkConformance(type, sendableProto);
if (conformance.isInvalid())
return true;
// If there is an unavailable conformance here, fail.
if (conformance.hasUnavailableConformance())
return true;
// Look for missing Sendable conformances.
return conformance.forEachMissingConformance(
[&](BuiltinProtocolConformance *missing) {
// For anything other than Sendable, fail.
if (missing->getProtocol() != sendableProto)
return true;
// If we have an archetype, capture the requirement
// to make this type Sendable.
if (missing->getType()->is<ArchetypeType>()) {
requirements.push_back(
Requirement(RequirementKind::Conformance,
missing->getType()->mapTypeOutOfContext(),
sendableProto->getDeclaredType()));
return false;
}
return true;
});
}
} visitor(nominal, requirements);
return visitor.visit(nominal, nominal);
}
}
static bool checkSendableInstanceStorage(
NominalTypeDecl *nominal, DeclContext *dc, SendableCheck check);
void swift::diagnoseMissingExplicitSendable(NominalTypeDecl *nominal) {
// Only diagnose when explicitly requested.
ASTContext &ctx = nominal->getASTContext();
if (!ctx.LangOpts.RequireExplicitSendable)
return;
if (nominal->getLoc().isInvalid())
return;
// Protocols aren't checked.
if (isa<ProtocolDecl>(nominal))
return;
// Actors are always Sendable.
if (auto classDecl = dyn_cast<ClassDecl>(nominal))
if (classDecl->isActor())
return;
// Only public/open types have this check.
if (!nominal->getFormalAccessScope(
/*useDC=*/nullptr,
/*treatUsableFromInlineAsPublic=*/true).isPublic())
return;
// If the conformance is explicitly stated, do nothing.
if (hasExplicitSendableConformance(nominal, /*applyModuleDefault=*/false))
return;
// Diagnose it.
nominal->diagnose(diag::public_decl_needs_sendable, nominal);
// Note to add a Sendable conformance, possibly an unchecked one.
{
llvm::SmallVector<Requirement, 2> requirements;
auto canMakeSendable = inferSendableFromInstanceStorage(
nominal, requirements);
// Non-final classes can only have @unchecked.
bool isUnchecked = !canMakeSendable || *canMakeSendable;
if (auto classDecl = dyn_cast<ClassDecl>(nominal)) {
if (!classDecl->isFinal())
isUnchecked = true;
}
auto note = nominal->diagnose(
isUnchecked ? diag::explicit_unchecked_sendable
: diag::add_nominal_sendable_conformance,
nominal);
if (canMakeSendable && !requirements.empty()) {
// Produce a Fix-It containing a conditional conformance to Sendable,
// based on the requirements harvested from instance storage.
// Form the where clause containing all of the requirements.
std::string whereClause;
{
llvm::raw_string_ostream out(whereClause);
llvm::interleaveComma(
requirements, out,
[&](const Requirement &req) {
out << req.getFirstType().getString() << ": "
<< req.getSecondType().getString();
});
}
// Add a Fix-It containing the conditional extension text itself.
auto insertionLoc = nominal->getBraces().End;
note.fixItInsertAfter(
insertionLoc,
("\n\nextension " + nominal->getName().str() + ": "
+ (isUnchecked? "@unchecked " : "") + "Sendable where " +
whereClause + " { }\n").str());
} else {
addSendableFixIt(nominal, note, isUnchecked);
}
}
// Note to disable the warning.
{
auto note = nominal->diagnose(diag::explicit_disable_sendable, nominal);
auto insertionLoc = nominal->getBraces().End;
note.fixItInsertAfter(
insertionLoc,
("\n\n@available(*, unavailable)\nextension " + nominal->getName().str()
+ ": Sendable { }\n").str());
}
}
void swift::tryDiagnoseExecutorConformance(ASTContext &C,
const NominalTypeDecl *nominal,
ProtocolDecl *proto) {
assert(proto->isSpecificProtocol(KnownProtocolKind::Executor) ||
proto->isSpecificProtocol(KnownProtocolKind::SerialExecutor) ||
proto->isSpecificProtocol(KnownProtocolKind::TaskExecutor));
auto &diags = C.Diags;
auto module = nominal->getParentModule();
Type nominalTy = nominal->getDeclaredInterfaceType();
NominalTypeDecl *executorDecl = C.getExecutorDecl();
// enqueue(_:)
auto enqueueDeclName = DeclName(C, DeclBaseName(C.Id_enqueue), { Identifier() });
FuncDecl *moveOnlyEnqueueRequirement = nullptr;
FuncDecl *legacyMoveOnlyEnqueueRequirement = nullptr;
FuncDecl *unownedEnqueueRequirement = nullptr;
for (auto req: proto->getProtocolRequirements()) {
auto *funcDecl = dyn_cast<FuncDecl>(req);
if (!funcDecl)
continue;
if (funcDecl->getName() != enqueueDeclName)
continue;
// look for the first parameter being a Job or UnownedJob
if (funcDecl->getParameters()->size() != 1)
continue;
if (auto param = funcDecl->getParameters()->front()) {
StructDecl *executorJobDecl = C.getExecutorJobDecl();
StructDecl *legacyJobDecl = C.getJobDecl();
StructDecl *unownedJobDecl = C.getUnownedJobDecl();
if (executorJobDecl && param->getInterfaceType()->isEqual(executorJobDecl->getDeclaredInterfaceType())) {
assert(moveOnlyEnqueueRequirement == nullptr);
moveOnlyEnqueueRequirement = funcDecl;
} else if (legacyJobDecl && param->getInterfaceType()->isEqual(legacyJobDecl->getDeclaredInterfaceType())) {
assert(legacyMoveOnlyEnqueueRequirement == nullptr);
legacyMoveOnlyEnqueueRequirement = funcDecl;
} else if (unownedJobDecl && param->getInterfaceType()->isEqual(unownedJobDecl->getDeclaredInterfaceType())) {
assert(unownedEnqueueRequirement == nullptr);
unownedEnqueueRequirement = funcDecl;
}
}
// if we found all potential requirements, we're done here and break out of the loop
if (unownedEnqueueRequirement &&
moveOnlyEnqueueRequirement &&
legacyMoveOnlyEnqueueRequirement)
break; // we're done looking for the requirements
}
auto conformance = module->lookupConformance(nominalTy, proto);
auto concreteConformance = conformance.getConcrete();
assert(unownedEnqueueRequirement && "could not find the enqueue(UnownedJob) requirement, which should be always there");
// try to find at least a single implementations of enqueue(_:)
ValueDecl *unownedEnqueueWitnessDecl = concreteConformance->getWitnessDecl(unownedEnqueueRequirement);
ValueDecl *moveOnlyEnqueueWitnessDecl = nullptr;
ValueDecl *legacyMoveOnlyEnqueueWitnessDecl = nullptr;
if (moveOnlyEnqueueRequirement) {
moveOnlyEnqueueWitnessDecl = concreteConformance->getWitnessDecl(
moveOnlyEnqueueRequirement);
}
if (legacyMoveOnlyEnqueueRequirement) {
legacyMoveOnlyEnqueueWitnessDecl = concreteConformance->getWitnessDecl(
legacyMoveOnlyEnqueueRequirement);
}
// --- Diagnose warnings and errors
// true iff the nominal type's availability allows the legacy requirement
// to be omitted in favor of moveOnlyEnqueueRequirement
bool canRemoveOldDecls;
if (!moveOnlyEnqueueRequirement) {
// The move only enqueue does not exist in this lib version, we must keep relying on the UnownedJob version
canRemoveOldDecls = false;
} else if (C.LangOpts.DisableAvailabilityChecking) {
// Assume we have all APIs available, and thus can use the ExecutorJob
canRemoveOldDecls = true;
} else {
// Check if the availability of nominal is high enough to be using the ExecutorJob version
AvailabilityContext requirementInfo
= AvailabilityInference::availableRange(moveOnlyEnqueueRequirement, C);
AvailabilityContext declInfo =
TypeChecker::overApproximateAvailabilityAtLocation(nominal->getLoc(), dyn_cast<DeclContext>(nominal));
canRemoveOldDecls = declInfo.isContainedIn(requirementInfo);
}
auto concurrencyModule = C.getLoadedModule(C.Id_Concurrency);
auto isStdlibDefaultImplDecl = [executorDecl, concurrencyModule](ValueDecl *witness) -> bool {
if (!witness)
return false;
if (auto declContext = witness->getDeclContext()) {
if (auto *extension = dyn_cast<ExtensionDecl>(declContext)) {
auto extensionModule = extension->getParentModule();
if (extensionModule != concurrencyModule) {
return false;
}
if (auto extendedNominal = extension->getExtendedNominal()) {
return extendedNominal->getDeclaredInterfaceType()->isEqual(
executorDecl->getDeclaredInterfaceType());
}
}
}
return false;
};
// If both old and new enqueue are implemented, but the old one cannot be removed,
// emit a warning that the new enqueue is unused.
if (!canRemoveOldDecls && unownedEnqueueWitnessDecl && moveOnlyEnqueueWitnessDecl) {
if (!isStdlibDefaultImplDecl(moveOnlyEnqueueWitnessDecl) &&
!isStdlibDefaultImplDecl(unownedEnqueueWitnessDecl)) {
diags.diagnose(moveOnlyEnqueueWitnessDecl->getLoc(),
diag::executor_enqueue_unused_implementation);
if (auto decl = unownedEnqueueWitnessDecl) {
decl->diagnose(diag::decl_declared_here, decl);
}
}
}
// We specifically do allow the old UnownedJob implementation to be present.
// In order to ease migration and compatibility for libraries which remain compatible with old Swift versions,
// and would be getting this warning in situations they cannot address it.
// Old Job based impl is present, warn about it suggesting the new protocol requirement.
if (legacyMoveOnlyEnqueueWitnessDecl) {
if (!isStdlibDefaultImplDecl(legacyMoveOnlyEnqueueWitnessDecl)) {
diags.diagnose(legacyMoveOnlyEnqueueWitnessDecl->getLoc(),
diag::executor_enqueue_deprecated_owned_job_implementation,
nominalTy);
}
}
bool unownedEnqueueWitnessIsDefaultImpl = isStdlibDefaultImplDecl(unownedEnqueueWitnessDecl);
bool moveOnlyEnqueueWitnessIsDefaultImpl = isStdlibDefaultImplDecl(moveOnlyEnqueueWitnessDecl);
bool legacyMoveOnlyEnqueueWitnessDeclIsDefaultImpl = isStdlibDefaultImplDecl(legacyMoveOnlyEnqueueWitnessDecl);
auto missingWitness = !unownedEnqueueWitnessDecl &&
!moveOnlyEnqueueWitnessDecl &&
!legacyMoveOnlyEnqueueWitnessDecl;
auto allWitnessesAreDefaultImpls = unownedEnqueueWitnessIsDefaultImpl &&
moveOnlyEnqueueWitnessIsDefaultImpl &&
legacyMoveOnlyEnqueueWitnessDeclIsDefaultImpl;
if ((missingWitness) ||
(!missingWitness && allWitnessesAreDefaultImpls)) {
// Neither old nor new implementation have been found, but we provide default impls for them
// that are mutually recursive, so we must error and suggest implementing the right requirement.
//
// If we're running against an SDK that does not have the ExecutorJob enqueue function,
// try to diagnose using the next-best one available.
auto missingRequirement = C.getExecutorDecl()->getExecutorOwnedEnqueueFunction();
if (!missingRequirement)
missingRequirement = C.getExecutorDecl()->getExecutorLegacyOwnedEnqueueFunction();
if (!missingRequirement)
missingRequirement = C.getExecutorDecl()->getExecutorLegacyUnownedEnqueueFunction();
if (missingRequirement) {
nominal->diagnose(diag::type_does_not_conform, nominalTy, proto->getDeclaredInterfaceType());
missingRequirement->diagnose(diag::no_witnesses,
getProtocolRequirementKind(missingRequirement),
missingRequirement,
missingRequirement->getParameters()->get(0)->getInterfaceType(),
/*AddFixIt=*/true);
return;
}
}
}
bool swift::shouldIgnoreDeprecationOfConcurrencyDecl(const Decl *decl,
DeclContext *declContext) {
auto &ctx = decl->getASTContext();
auto concurrencyModule = ctx.getLoadedModule(ctx.Id_Concurrency);
// Only suppress these diagnostics in the implementation of _Concurrency.
if (declContext->getParentModule() != concurrencyModule)
return false;
// Only suppress deprecation diagnostics for decls defined in _Concurrency.
if (decl->getDeclContext()->getParentModule() != concurrencyModule)
return false;
auto *legacyJobDecl = ctx.getJobDecl();
auto *unownedJobDecl = ctx.getUnownedJobDecl();
if (decl == legacyJobDecl)
return true;
if (auto *funcDecl = dyn_cast<FuncDecl>(decl)) {
auto enqueueDeclName =
DeclName(ctx, DeclBaseName(ctx.Id_enqueue), {Identifier()});
if (funcDecl->getName() == enqueueDeclName &&
funcDecl->getParameters()->size() == 1) {
auto paramTy = funcDecl->getParameters()->front()->getInterfaceType();
if (paramTy->isEqual(legacyJobDecl->getDeclaredInterfaceType()) ||
paramTy->isEqual(unownedJobDecl->getDeclaredInterfaceType()))
return true;
}
}
return false;
}
/// Determine whether this is the main actor type.
static bool isMainActor(Type type) {
if (auto nominal = type->getAnyNominal())
return nominal->isMainActor();
return false;
}
/// If this DeclContext is an actor, or an extension on an actor, return the
/// NominalTypeDecl, otherwise return null.
static NominalTypeDecl *getSelfActorDecl(const DeclContext *dc) {
auto nominal = dc->getSelfNominalTypeDecl();
return nominal && nominal->isActor() ? nominal : nullptr;
}
ReferencedActor ReferencedActor::forGlobalActor(VarDecl *actor,
bool isPotentiallyIsolated,
Type globalActor) {
Kind kind = isMainActor(globalActor) ? MainActor : GlobalActor;
return ReferencedActor(actor, isPotentiallyIsolated, kind, globalActor);
}
static ActorIsolation getActorIsolationForReference(
ValueDecl *decl, const DeclContext *fromDC);
bool ReferencedActor::isKnownToBeLocal() const {
switch (kind) {
case GlobalActor:
case AsyncLet:
case MainActor:
case NonIsolatedAutoclosure:
case NonIsolatedContext:
case NonIsolatedParameter:
case SendableFunction:
case SendableClosure:
if (isPotentiallyIsolated)
return true;
return actor && actor->isKnownToBeLocal();
case Isolated:
return true;
}
}
const AbstractFunctionDecl *
swift::isActorInitOrDeInitContext(const DeclContext *dc) {
while (true) {
// Stop looking if we hit an isolation inference boundary.
if (auto *closure = dyn_cast<AbstractClosureExpr>(dc)) {
if (isIsolationInferenceBoundaryClosure(closure,
false /*is for actor isolation*/))
return nullptr;
// Otherwise, look through our closure at the closure's parent decl
// context.
dc = dc->getParent();
continue;
}
if (auto func = dyn_cast<AbstractFunctionDecl>(dc)) {
// If this is an initializer or deinitializer of an actor, we're done.
if ((isa<ConstructorDecl>(func) || isa<DestructorDecl>(func)) &&
getSelfActorDecl(dc->getParent()))
return func;
// Non-Sendable local functions are considered part of the enclosing
// context.
if (func->getDeclContext()->isLocalContext()) {
if (func->isSendable())
return nullptr;
dc = dc->getParent();
continue;
}
}
return nullptr;
}
}
static bool isStoredProperty(ValueDecl const *member) {
if (auto *var = dyn_cast<VarDecl>(member))
if (var->hasStorage() && var->isInstanceMember())
return true;
return false;
}
static bool isNonInheritedStorage(ValueDecl const *member,
DeclContext const *useDC) {
auto *nominal = useDC->getParent()->getSelfNominalTypeDecl();
if (!nominal)
return false;
return isStoredProperty(member) && member->getDeclContext() == nominal;
}
/// Based on the former escaping-use restriction, which was replaced by
/// flow-isolation. We need this to support backwards compatability in the
/// type-checker for programs prior to Swift 6.
/// \param fn either a constructor or destructor of an actor.
static bool wasLegacyEscapingUseRestriction(AbstractFunctionDecl *fn) {
assert(fn->getDeclContext()->getSelfClassDecl()->isAnyActor());
assert(isa<ConstructorDecl>(fn) || isa<DestructorDecl>(fn));
// according to today's isolation, determine whether it use to have the
// escaping-use restriction
switch (getActorIsolation(fn).getKind()) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::GlobalActor:
// convenience inits did not have the restriction.
if (auto *ctor = dyn_cast<ConstructorDecl>(fn))
if (ctor->isConvenienceInit())
return false;
break; // goto basic case
case ActorIsolation::ActorInstance:
// none of these had the restriction affect them.
assert(fn->hasAsync());
return false;
case ActorIsolation::Erased:
llvm_unreachable("function decl cannot have erased isolation");
case ActorIsolation::Unspecified:
// this is basically just objc-marked inits.
break;
};
return !(fn->hasAsync()); // basic case: not async = had restriction.
}
/// Note that the given actor member is isolated.
static void noteIsolatedActorMember(ValueDecl const *decl,
std::optional<VarRefUseEnv> useKind) {
// detect if it is a distributed actor, to provide better isolation notes
auto nominal = decl->getDeclContext()->getSelfNominalTypeDecl();
bool isDistributedActor = false;
if (nominal) isDistributedActor = nominal->isDistributedActor();
// FIXME: Make this diagnostic more sensitive to the isolation context of
// the declaration.
if (isDistributedActor) {
if (auto varDecl = dyn_cast<VarDecl>(decl)) {
if (varDecl->isDistributed()) {
// This is an attempt to access a `distributed var` synchronously, so offer a more detailed error
decl->diagnose(diag::distributed_actor_synchronous_access_distributed_computed_property,
decl,
nominal->getName());
} else {
// Distributed actor properties are never accessible externally.
decl->diagnose(diag::distributed_actor_isolated_property,
decl,
nominal->getName());
}
} else {
// it's a function or subscript
decl->diagnose(diag::note_distributed_actor_isolated_method, decl);
}
} else if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
func->diagnose(diag::actor_isolated_sync_func, decl);
// was it an attempt to mutate an actor instance's isolated state?
} else if (useKind) {
if (*useKind == VarRefUseEnv::Read)
decl->diagnose(diag::kind_declared_here, decl->getDescriptiveKind());
else
decl->diagnose(diag::actor_mutable_state, decl->getDescriptiveKind());
} else {
decl->diagnose(diag::kind_declared_here, decl->getDescriptiveKind());
}
}
/// An ad-hoc check specific to member isolation checking. assumed to be
/// queried when a self-member is being accessed in a context which is not
/// isolated to self. The "special permission" is part of a backwards
/// compatability with actor inits and deinits that maintains the
/// permissive nature of the escaping-use restriction, which was only
/// staged in as a warning. See implementation for more details.
///
/// \returns true if this access in the given context should be allowed
/// in Sema, with the side-effect of emitting a warning as needed.
/// If false is returned, then the "special permission" was not granted.
static bool memberAccessHasSpecialPermissionInSwift5(
DeclContext const *refCxt, ReferencedActor &baseActor,
ValueDecl const *member, SourceLoc memberLoc,
std::optional<VarRefUseEnv> useKind) {
// no need for this in Swift 6+
if (refCxt->getASTContext().isSwiftVersionAtLeast(6))
return false;
// must be an access to an instance member.
if (!member->isInstanceMember())
return false;
// In the history of actor initializers prior to Swift 6, self-isolated
// members could be referenced from any init or deinit, even a synchronous
// one, with no diagnostics at all.
//
// When the escaping-use restriction came into place for the release of
// 5.5, it was implemented as a warning and only applied to initializers,
// which stated that it would become an error in Swift 6.
//
// Once 5.6 was released, we also added restrictions in the deinits of
// actors, at least for accessing members other than stored properties.
//
// Later on, for 5.7 we introduced flow-isolation as part of SE-327 for
// both inits and deinits. This meant that stored property accesses now
// are only sometimes going to be problematic. This change also brought
// official changes in isolation for the inits and deinits to handle the
// the non-stored-property members. Since those isolation changes are
// currently in place, the purpose of the code below is to override the
// isolation checking, so that the now-mismatched isolation on member
// access is still permitted, but with a warning stating that it will
// be rejected in Swift 6.
//
// In the checking below, we let stored-property accesses go ignored,
// so that flow-isolation can warn about them only if needed. This helps
// prevent needless warnings on property accesses that will actually be OK
// with flow-isolation in the future.
if (auto oldFn = isActorInitOrDeInitContext(refCxt)) {
auto oldFnMut = const_cast<AbstractFunctionDecl*>(oldFn);
// If function did not have the escaping-use restriction, then it gets
// no special permissions here.
if (!wasLegacyEscapingUseRestriction(oldFnMut))
return false;
// At this point, the special permission will be granted. But, we
// need to warn now about this permission being taken away in Swift 6
// for specific kinds of non-stored-property member accesses:
// If the context in which we consider the access matches between the
// old (escaping-use restriction) and new (flow-isolation) contexts,
// and it is a stored or init accessor property, then permit it here
// without any warning.
// Later, flow-isolation pass will check and emit a warning if needed.
if (refCxt == oldFn) {
if (isStoredProperty(member))
return true;
if (auto *var = dyn_cast<VarDecl>(member)) {
// Init accessor properties are permitted to access only stored
// properties.
if (var->hasInitAccessor())
return true;
}
}
// Otherwise, it's definitely going to be illegal, so warn and permit.
auto &diags = refCxt->getASTContext().Diags;
auto useKindInt = static_cast<unsigned>(
useKind.value_or(VarRefUseEnv::Read));
diags.diagnose(
memberLoc, diag::actor_isolated_non_self_reference,
member,
useKindInt,
baseActor.kind + 1,
baseActor.globalActor,
getActorIsolation(const_cast<ValueDecl *>(member)))
.warnUntilSwiftVersion(6);
noteIsolatedActorMember(member, useKind);
return true;
}
return false;
}
/// To support flow-isolation, some member accesses in inits / deinits
/// must be permitted, despite the isolation of 'self' not being
/// correct in Sema.
///
/// \param refCxt the context in which the member reference happens.
/// \param baseActor the actor referenced in the base of the member access.
/// \param member the declaration corresponding to the accessed member.
/// \param memberLoc the source location of the reference to the member.
///
/// \returns true iff the member access is permitted in Sema because it will
/// be verified later by flow-isolation.
static bool checkedByFlowIsolation(DeclContext const *refCxt,
ReferencedActor &baseActor,
ValueDecl const *member, SourceLoc memberLoc,
std::optional<VarRefUseEnv> useKind) {
// base of member reference must be `self`
if (!baseActor.isSelf())
return false;
// Must be directly in an init/deinit that uses flow-isolation,
// or a defer within such a functions.
//
// NOTE: once flow-isolation can analyze calls to arbitrary local
// functions, we should be using isActorInitOrDeInitContext instead
// of this ugly loop.
AbstractFunctionDecl const* fnDecl = nullptr;
while (true) {
fnDecl = dyn_cast_or_null<AbstractFunctionDecl>(refCxt->getAsDecl());
if (!fnDecl)
break;
// go up one level if this context is a defer.
if (auto *d = dyn_cast<FuncDecl>(fnDecl)) {
if (d->isDeferBody()) {
refCxt = refCxt->getParent();
continue;
}
}
break;
}
if (memberAccessHasSpecialPermissionInSwift5(refCxt, baseActor, member,
memberLoc, useKind))
return true; // then permit it now.
if (!usesFlowSensitiveIsolation(fnDecl))
return false;
// Stored properties are definitely OK.
if (isNonInheritedStorage(member, fnDecl))
return true;
return false;
}
/// Get the actor isolation of the innermost relevant context.
static ActorIsolation getInnermostIsolatedContext(
const DeclContext *dc,
llvm::function_ref<ActorIsolation(AbstractClosureExpr *)>
getClosureActorIsolation) {
// Retrieve the actor isolation of the context.
auto mutableDC = const_cast<DeclContext *>(dc);
switch (auto isolation =
getActorIsolationOfContext(mutableDC, getClosureActorIsolation)) {
case ActorIsolation::ActorInstance:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
return isolation;
case ActorIsolation::Erased:
llvm_unreachable("closure cannot originally have dynamic isolation");
case ActorIsolation::GlobalActor:
return ActorIsolation::forGlobalActor(
dc->mapTypeIntoContext(isolation.getGlobalActor()))
.withPreconcurrency(isolation.preconcurrency());
}
}
/// Determine whether this declaration is always accessed asynchronously.
bool swift::isAsyncDecl(ConcreteDeclRef declRef) {
auto decl = declRef.getDecl();
// An async function is asynchronously accessed.
if (auto func = dyn_cast<AbstractFunctionDecl>(decl))
return func->hasAsync();
// A computed property or subscript that has an 'async' getter
// is asynchronously accessed.
if (auto storageDecl = dyn_cast<AbstractStorageDecl>(decl)) {
if (auto effectfulGetter = storageDecl->getEffectfulGetAccessor())
return effectfulGetter->hasAsync();
}
return false;
}
AbstractFunctionDecl *swift::enclosingUnsafeInheritsExecutor(
const DeclContext *dc) {
for (; dc; dc = dc->getParent()) {
if (auto func = dyn_cast<AbstractFunctionDecl>(dc)) {
if (func->getAttrs().hasAttribute<UnsafeInheritExecutorAttr>()) {
return const_cast<AbstractFunctionDecl *>(func);
}
return nullptr;
}
if (isa<AbstractClosureExpr>(dc))
return nullptr;
if (dc->isTypeContext())
return nullptr;
}
return nullptr;
}
/// Adjust the location used for diagnostics about #isolation to account for
/// the fact that they show up in macro expansions.
///
/// Returns a pair containing the updated location and whether it's part of
/// a default argument.
static std::pair<SourceLoc, bool> adjustPoundIsolationDiagLoc(
CurrentContextIsolationExpr *isolationExpr,
ModuleDecl *module
) {
// Not part of a macro expansion.
SourceLoc diagLoc = isolationExpr->getLoc();
auto sourceFile = module->getSourceFileContainingLocation(diagLoc);
if (!sourceFile)
return { diagLoc, false };
auto macroExpansionRange = sourceFile->getMacroInsertionRange();
if (macroExpansionRange.Start.isInvalid())
return { diagLoc, false };
diagLoc = macroExpansionRange.Start;
// If this is from a default argument, note that and go one more
// level "out" to the place where the default argument was
// introduced.
auto expansionSourceFile = module->getSourceFileContainingLocation(diagLoc);
if (!expansionSourceFile ||
expansionSourceFile->Kind != SourceFileKind::DefaultArgument)
return { diagLoc, false };
return {
expansionSourceFile->getNodeInEnclosingSourceFile().getStartLoc(),
true
};
}
void swift::replaceUnsafeInheritExecutorWithDefaultedIsolationParam(
AbstractFunctionDecl *func, InFlightDiagnostic &diag) {
auto attr = func->getAttrs().getAttribute<UnsafeInheritExecutorAttr>();
assert(attr && "Caller didn't validate the presence of the attribute");
// Look for the place where we should insert the new 'isolation' parameter.
// We insert toward the back, but skip over any parameters that have function
// type.
unsigned insertionPos = func->getParameters()->size();
while (insertionPos > 0) {
Type paramType = func->getParameters()->get(insertionPos - 1)->getInterfaceType();
if (paramType->lookThroughSingleOptionalType()->is<AnyFunctionType>()) {
--insertionPos;
continue;
}
break;
}
// Determine the text to insert. We put the commas before and after, then
// slice them away depending on whether we have parameters before or after.
StringRef newParameterText = ", isolation: isolated (any Actor)? = #isolation, ";
if (insertionPos == 0)
newParameterText = newParameterText.drop_front(2);
if (insertionPos == func->getParameters()->size())
newParameterText = newParameterText.drop_back(2);
// Determine where to insert the new parameter.
SourceLoc insertionLoc;
if (insertionPos < func->getParameters()->size()) {
insertionLoc = func->getParameters()->get(insertionPos)->getStartLoc();
} else {
insertionLoc = func->getParameters()->getRParenLoc();
}
diag.fixItRemove(attr->getRangeWithAt());
diag.fixItInsert(insertionLoc, newParameterText);
}
/// Whether this declaration context is in the _Concurrency module.
static bool inConcurrencyModule(const DeclContext *dc) {
return dc->getParentModule()->getName().str().equals("_Concurrency");
}
void swift::introduceUnsafeInheritExecutorReplacements(
const DeclContext *dc, SourceLoc loc, SmallVectorImpl<ValueDecl *> &decls) {
if (decls.empty())
return;
auto isReplaceable = [&](ValueDecl *decl) {
return isa<FuncDecl>(decl) && inConcurrencyModule(decl->getDeclContext()) &&
decl->getDeclContext()->isModuleScopeContext() &&
cast<FuncDecl>(decl)->hasAsync();
};
// Make sure at least some of the entries are functions in the _Concurrency
// module.
ModuleDecl *concurrencyModule = nullptr;
DeclBaseName baseName;
for (auto decl: decls) {
if (isReplaceable(decl)) {
concurrencyModule = decl->getDeclContext()->getParentModule();
baseName = decl->getName().getBaseName();
break;
}
}
if (!concurrencyModule)
return;
// Ignore anything with a special name.
if (baseName.isSpecial())
return;
// Look for entities with the _unsafeInheritExecutor_ prefix on the name.
ASTContext &ctx = decls.front()->getASTContext();
Identifier newIdentifier = ctx.getIdentifier(
("_unsafeInheritExecutor_" + baseName.getIdentifier().str()).str());
NameLookupOptions lookupOptions = defaultUnqualifiedLookupOptions;
LookupResult lookup = TypeChecker::lookupUnqualified(
const_cast<DeclContext *>(dc), DeclNameRef(newIdentifier), loc,
lookupOptions);
if (!lookup)
return;
// Drop all of the _Concurrency entries in favor of the ones found by this
// lookup.
decls.erase(std::remove_if(decls.begin(), decls.end(), [&](ValueDecl *decl) {
return isReplaceable(decl);
}),
decls.end());
for (const auto &lookupResult: lookup) {
if (auto decl = lookupResult.getValueDecl())
decls.push_back(decl);
}
}
void swift::introduceUnsafeInheritExecutorReplacements(
const DeclContext *dc, Type base, SourceLoc loc, LookupResult &lookup) {
if (lookup.empty())
return;
auto baseNominal = base->getAnyNominal();
if (!baseNominal || !inConcurrencyModule(baseNominal))
return;
auto isReplaceable = [&](ValueDecl *decl) {
return isa<FuncDecl>(decl) && inConcurrencyModule(decl->getDeclContext()) &&
cast<FuncDecl>(decl)->hasAsync();
};
// Make sure at least some of the entries are functions in the _Concurrency
// module.
ModuleDecl *concurrencyModule = nullptr;
DeclBaseName baseName;
for (auto &result: lookup) {
auto decl = result.getValueDecl();
if (isReplaceable(decl)) {
concurrencyModule = decl->getDeclContext()->getParentModule();
baseName = decl->getBaseName();
break;
}
}
if (!concurrencyModule)
return;
// Ignore anything with a special name.
if (baseName.isSpecial())
return;
// Look for entities with the _unsafeInheritExecutor_ prefix on the name.
ASTContext &ctx = base->getASTContext();
Identifier newIdentifier = ctx.getIdentifier(
("_unsafeInheritExecutor_" + baseName.getIdentifier().str()).str());
LookupResult replacementLookup = TypeChecker::lookupMember(
const_cast<DeclContext *>(dc), base, DeclNameRef(newIdentifier), loc,
defaultMemberLookupOptions);
if (replacementLookup.innerResults().empty())
return;
// Drop all of the _Concurrency entries in favor of the ones found by this
// lookup.
lookup.filter([&](const LookupResultEntry &entry, bool) {
return !isReplaceable(entry.getValueDecl());
});
for (const auto &entry: replacementLookup.innerResults()) {
lookup.add(entry, /*isOuter=*/false);
}
}
/// Check if it is safe for the \c globalActor qualifier to be removed from
/// \c ty, when the function value of that type is isolated to that actor.
///
/// In general this is safe in a narrow but common case: a global actor
/// qualifier can be dropped from a function type while in a DeclContext
/// isolated to that same actor, as long as the value is not Sendable.
///
/// \param dc the innermost context in which the cast to remove the global actor
/// is happening.
/// \param globalActor global actor that was dropped from \c ty.
/// \param ty a function type where \c globalActor was removed from it.
/// \return true if it is safe to drop the global-actor qualifier.
static bool safeToDropGlobalActor(
DeclContext *dc, Type globalActor, Type ty, ApplyExpr *call) {
auto funcTy = ty->getAs<AnyFunctionType>();
if (!funcTy)
return false;
auto otherIsolation = funcTy->getIsolation();
// can't add a different global actor
if (otherIsolation.isGlobalActor()) {
assert(otherIsolation.getGlobalActorType()->getCanonicalType()
!= globalActor->getCanonicalType()
&& "not even dropping the actor?");
return false;
}
// Converting to an isolation-erased function type is fine.
if (otherIsolation.isErased())
return true;
// We currently allow unconditional dropping of global actors from
// async function types, despite this confusing Sendable checking
// in light of SE-338.
if (funcTy->isAsync())
return true;
// If the argument is passed over an isolation boundary, it's not
// safe to erase actor isolation, because the callee can call the
// function synchronously from outside the isolation domain.
if (call && call->getIsolationCrossing())
return false;
// fundamentally cannot be sendable if we want to drop isolation info
if (funcTy->isSendable())
return false;
// finally, must be in a context with matching isolation.
auto dcIsolation = getActorIsolationOfContext(dc);
if (dcIsolation.isGlobalActor())
if (dcIsolation.getGlobalActor()->getCanonicalType()
== globalActor->getCanonicalType())
return true;
return false;
}
static FuncDecl *findAnnotatableFunction(DeclContext *dc) {
auto fn = dyn_cast<FuncDecl>(dc);
if (!fn) return nullptr;
if (fn->isDeferBody())
return findAnnotatableFunction(fn->getDeclContext());
return fn;
}
static bool shouldCheckSendable(Expr *expr) {
if (auto *declRef = dyn_cast<DeclRefExpr>(expr->findOriginalValue())) {
auto isolation = getActorIsolation(declRef->getDecl());
return isolation != ActorIsolation::NonisolatedUnsafe;
}
return true;
}
bool swift::diagnoseApplyArgSendability(ApplyExpr *apply, const DeclContext *declContext) {
auto isolationCrossing = apply->getIsolationCrossing();
if (!isolationCrossing.has_value())
return false;
auto fnExprType = apply->getFn()->getType();
if (!fnExprType)
return false;
// Check the 'self' argument.
if (auto *selfApply = dyn_cast<SelfApplyExpr>(apply->getFn())) {
auto *base = selfApply->getBase();
if (shouldCheckSendable(base) &&
diagnoseNonSendableTypes(
base->getType(),
declContext, /*inDerivedConformance*/Type(),
base->getStartLoc(),
diag::non_sendable_call_argument,
isolationCrossing.value().exitsIsolation(),
isolationCrossing.value().getDiagnoseIsolation()))
return true;
}
auto fnType = fnExprType->getAs<FunctionType>();
if (!fnType)
return false;
auto params = fnType->getParams();
for (unsigned paramIdx : indices(params)) {
const auto ¶m = params[paramIdx];
// Dig out the location of the argument.
SourceLoc argLoc = apply->getLoc();
Type argType;
bool checkSendable = true;
if (auto argList = apply->getArgs()) {
auto arg = argList->get(paramIdx);
if (arg.getStartLoc().isValid())
argLoc = arg.getStartLoc();
// Determine the type of the argument, ignoring any implicit
// conversions that could have stripped sendability.
if (Expr *argExpr = arg.getExpr()) {
checkSendable = shouldCheckSendable(argExpr);
argType = argExpr->findOriginalType();
// If this is a default argument expression, don't check Sendability
// if the argument is evaluated in the callee's isolation domain.
if (auto *defaultExpr = dyn_cast<DefaultArgumentExpr>(argExpr)) {
auto argIsolation = defaultExpr->getRequiredIsolation();
auto calleeIsolation = isolationCrossing->getCalleeIsolation();
if (argIsolation == calleeIsolation) {
continue;
}
}
}
}
if (checkSendable &&
diagnoseNonSendableTypes(
argType ? argType : param.getParameterType(),
declContext, /*inDerivedConformance*/Type(),
argLoc, diag::non_sendable_call_argument,
isolationCrossing.value().exitsIsolation(),
isolationCrossing.value().getDiagnoseIsolation()))
return true;
}
return false;
}
namespace {
/// Check for adherence to the actor isolation rules, emitting errors
/// when actor-isolated declarations are used in an unsafe manner.
class ActorIsolationChecker : public ASTWalker {
ASTContext &ctx;
SmallVector<const DeclContext *, 4> contextStack;
SmallVector<llvm::PointerUnion<ApplyExpr *, LookupExpr *>, 4> applyStack;
SmallVector<std::pair<OpaqueValueExpr *, Expr *>, 4> opaqueValues;
SmallVector<const PatternBindingDecl *, 2> patternBindingStack;
llvm::function_ref<Type(Expr *)> getType;
llvm::function_ref<ActorIsolation(AbstractClosureExpr *)>
getClosureActorIsolation;
SourceLoc requiredIsolationLoc;
/// Used under the mode to compute required actor isolation for
/// an expression or function.
llvm::SmallDenseMap<const DeclContext *, ActorIsolation> requiredIsolation;
using ActorRefKindPair = std::pair<ReferencedActor::Kind, ActorIsolation>;
using IsolationPair = std::pair<ActorIsolation, ActorIsolation>;
using DiagnosticList = std::vector<IsolationError>;
llvm::DenseMap<ActorRefKindPair, DiagnosticList> refErrors;
llvm::DenseMap<IsolationPair, DiagnosticList> applyErrors;
/// Keeps track of the capture context of variables that have been
/// explicitly captured in closures.
llvm::SmallDenseMap<VarDecl *, TinyPtrVector<const DeclContext *>>
captureContexts;
using MutableVarSource
= llvm::PointerUnion<DeclRefExpr *, InOutExpr *, LookupExpr *>;
using MutableVarParent
= llvm::PointerUnion<InOutExpr *, LoadExpr *, AssignExpr *>;
ApplyExpr *getImmediateApply() const {
if (applyStack.empty())
return nullptr;
return applyStack.back().dyn_cast<ApplyExpr *>();
}
/// Note when the enclosing context could be put on a global actor.
// FIXME: This should handle closures too.
static bool missingGlobalActorOnContext(DeclContext *dc, Type globalActor,
DiagnosticBehavior behavior) {
// If we are in a synchronous function on the global actor,
// suggest annotating with the global actor itself.
if (auto fn = findAnnotatableFunction(dc)) {
// Suppress this for accessors because you can't change the
// actor isolation of an individual accessor. Arguably we could
// add this to the entire storage declaration, though.
// Suppress this for async functions out of caution; but don't
// suppress it if we looked through a defer.
if (!isa<AccessorDecl>(fn) &&
(!fn->isAsyncContext() || fn != dc)) {
switch (getActorIsolation(fn)) {
case ActorIsolation::ActorInstance:
case ActorIsolation::GlobalActor:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
return false;
case ActorIsolation::Erased:
llvm_unreachable("function cannot have erased isolation");
case ActorIsolation::Unspecified:
if (behavior != DiagnosticBehavior::Note) {
fn->diagnose(diag::invalid_isolated_calls_in_body,
globalActor->getWithoutParens().getString(), fn)
.limitBehaviorUntilSwiftVersion(behavior, 6);
}
// Overrides cannot be isolated to a global actor; the isolation
// must match the overridden decl.
if (fn->getOverriddenDecl())
return false;
fn->diagnose(diag::add_globalactor_to_function,
globalActor->getWithoutParens().getString(),
fn, globalActor)
.fixItInsert(fn->getAttributeInsertionLoc(false),
diag::insert_globalactor_attr, globalActor);
return true;
}
}
}
return false;
}
public:
bool diagnoseIsolationErrors() {
bool diagnosedError = false;
for (auto list : refErrors) {
ActorRefKindPair key = list.getFirst();
DiagnosticList errors = list.getSecond();
ActorIsolation isolation = key.second;
auto behavior = DiagnosticBehavior::Warning;
// Upgrade behavior if @preconcurrency not detected
if (llvm::any_of(errors, [&](IsolationError error) {
return !error.preconcurrency;
})) {
behavior = DiagnosticBehavior::Error;
}
// Add Fix-it for missing @SomeActor annotation
if (isolation.isGlobalActor()) {
if (missingGlobalActorOnContext(
const_cast<DeclContext *>(getDeclContext()),
isolation.getGlobalActor(), behavior) &&
errors.size() > 1) {
behavior = DiagnosticBehavior::Note;
}
}
for (IsolationError error : errors) {
// Diagnose actor_isolated_non_self_reference as note
// if there are multiple of these diagnostics
ctx.Diags.diagnose(error.loc, error.diag)
.limitBehaviorUntilSwiftVersion(behavior, 6);
}
}
for (auto list : applyErrors) {
IsolationPair key = list.getFirst();
DiagnosticList errors = list.getSecond();
ActorIsolation isolation = key.first;
auto behavior = DiagnosticBehavior::Warning;
// Upgrade behavior if @preconcurrency not detected
if (llvm::any_of(errors, [&](IsolationError error) {
return !error.preconcurrency;
})) {
behavior = DiagnosticBehavior::Error;
}
// Add Fix-it for missing @SomeActor annotation
if (isolation.isGlobalActor()) {
if (missingGlobalActorOnContext(
const_cast<DeclContext *>(getDeclContext()),
isolation.getGlobalActor(), behavior) &&
errors.size() > 1) {
behavior = DiagnosticBehavior::Note;
}
}
for (IsolationError error : errors) {
// Diagnose actor_isolated_call as note if
// if there are multiple actor-isolated function calls
// from outside the actor
ctx.Diags.diagnose(error.loc, error.diag)
.limitBehaviorUntilSwiftVersion(behavior, 6);
}
}
return diagnosedError;
}
private:
const PatternBindingDecl *getTopPatternBindingDecl() const {
return patternBindingStack.empty() ? nullptr : patternBindingStack.back();
}
/// Mapping from mutable variable reference exprs, or inout expressions,
/// to the parent expression, when that parent is either a load or
/// an inout expr.
llvm::SmallDenseMap<MutableVarSource, MutableVarParent, 4>
mutableLocalVarParent;
static bool isPropOrSubscript(ValueDecl const* decl) {
return isa<VarDecl>(decl) || isa<SubscriptDecl>(decl);
}
/// In the given expression \c use that refers to the decl, this
/// function finds the kind of environment tracked by
/// \c mutableLocalVarParent that corresponds to that \c use.
///
/// Note that an InoutExpr is not considered a use of the decl!
///
/// @returns None if the context expression is either an InOutExpr,
/// not tracked, or if the decl is not a property or subscript
std::optional<VarRefUseEnv> kindOfUsage(ValueDecl const *decl,
Expr *use) const {
// we need a use for lookup.
if (!use)
return std::nullopt;
// must be a property or subscript
if (!isPropOrSubscript(decl))
return std::nullopt;
if (auto lookup = dyn_cast<DeclRefExpr>(use))
return usageEnv(lookup);
else if (auto lookup = dyn_cast<LookupExpr>(use))
return usageEnv(lookup);
return std::nullopt;
}
/// @returns the kind of environment in which this expression appears, as
/// tracked by \c mutableLocalVarParent
VarRefUseEnv usageEnv(MutableVarSource src) const {
auto result = mutableLocalVarParent.find(src);
if (result != mutableLocalVarParent.end()) {
MutableVarParent parent = result->second;
assert(!parent.isNull());
if (parent.is<LoadExpr*>())
return VarRefUseEnv::Read;
else if (parent.is<AssignExpr*>())
return VarRefUseEnv::Mutating;
else if (auto inout = parent.dyn_cast<InOutExpr*>())
return inout->isImplicit() ? VarRefUseEnv::Mutating
: VarRefUseEnv::Inout;
else
llvm_unreachable("non-exhaustive case match");
}
return VarRefUseEnv::Read; // assume if it's not tracked, it's only read.
}
const DeclContext *getDeclContext() const {
return contextStack.back();
}
ModuleDecl *getParentModule() const {
return getDeclContext()->getParentModule();
}
/// Determine whether code in the given use context might execute
/// concurrently with code in the definition context.
bool mayExecuteConcurrentlyWith(
const DeclContext *useContext, const DeclContext *defContext);
/// If the subexpression is a reference to a mutable local variable from a
/// different context, record its parent. We'll query this as part of
/// capture semantics in concurrent functions.
///
/// \returns true if we recorded anything, false otherwise.
bool recordMutableVarParent(MutableVarParent parent, Expr *subExpr) {
subExpr = subExpr->getValueProvidingExpr();
if (auto declRef = dyn_cast<DeclRefExpr>(subExpr)) {
auto var = dyn_cast_or_null<VarDecl>(declRef->getDecl());
if (!var)
return false;
// Only mutable variables matter.
if (!var->supportsMutation())
return false;
// Only mutable variables outside of the current context. This is an
// optimization, because the parent map won't be queried in this case,
// and it is the most common case for variables to be referenced in
// their own context.
if (var->getDeclContext() == getDeclContext())
return false;
assert(mutableLocalVarParent[declRef].isNull());
mutableLocalVarParent[declRef] = parent;
return true;
}
// For a member reference, try to record a parent for the base expression.
if (auto memberRef = dyn_cast<MemberRefExpr>(subExpr)) {
// Record the parent of this LookupExpr too.
mutableLocalVarParent[memberRef] = parent;
return recordMutableVarParent(parent, memberRef->getBase());
}
// For a subscript, try to record a parent for the base expression.
if (auto subscript = dyn_cast<SubscriptExpr>(subExpr)) {
// Record the parent of this LookupExpr too.
mutableLocalVarParent[subscript] = parent;
return recordMutableVarParent(parent, subscript->getBase());
}
// Look through postfix '!'.
if (auto force = dyn_cast<ForceValueExpr>(subExpr)) {
return recordMutableVarParent(parent, force->getSubExpr());
}
// Look through postfix '?'.
if (auto bindOpt = dyn_cast<BindOptionalExpr>(subExpr)) {
return recordMutableVarParent(parent, bindOpt->getSubExpr());
}
if (auto optEval = dyn_cast<OptionalEvaluationExpr>(subExpr)) {
return recordMutableVarParent(parent, optEval->getSubExpr());
}
// & expressions can be embedded for references to mutable variables
// or subscribes inside a struct/enum.
if (auto inout = dyn_cast<InOutExpr>(subExpr)) {
// Record the parent of the inout so we don't look at it again later.
mutableLocalVarParent[inout] = parent;
return recordMutableVarParent(parent, inout->getSubExpr());
}
// Look through an expression that opens an existential
if (auto openExist = dyn_cast<OpenExistentialExpr>(subExpr)) {
return recordMutableVarParent(parent, openExist->getSubExpr());
}
return false;
}
/// Some function conversions synthesized by the constraint solver may not
/// be correct AND the solver doesn't know, so we must emit a diagnostic.
void checkFunctionConversion(Expr *funcConv, Type fromType, Type toType) {
if (auto fromFnType = fromType->getAs<FunctionType>()) {
if (auto fromActor = fromFnType->getGlobalActor()) {
if (auto toFnType = toType->getAs<FunctionType>()) {
// ignore some kinds of casts, as they're diagnosed elsewhere.
if (toFnType->hasGlobalActor() || toFnType->isAsync())
return;
auto dc = const_cast<DeclContext*>(getDeclContext());
if (!safeToDropGlobalActor(dc, fromActor, toType,
getImmediateApply())) {
// otherwise, it's not a safe cast.
dc->getASTContext()
.Diags
.diagnose(funcConv->getLoc(),
diag::converting_func_loses_global_actor, fromType,
toType, fromActor)
.warnUntilSwiftVersion(6);
}
}
}
}
}
bool refineRequiredIsolation(ActorIsolation refinedIsolation) {
if (requiredIsolationLoc.isInvalid())
return false;
auto infersIsolationFromContext =
[](const DeclContext *dc) -> bool {
// Isolation for declarations is based solely on explicit
// annotations; only infer isolation for initializer expressions
// and closures.
if (dc->getAsDecl())
return false;
if (auto *closure = dyn_cast<AbstractClosureExpr>(dc)) {
// We cannot infer a more specific actor isolation for a Sendable
// closure. It is an error to cast away actor isolation from a
// function type, but this is okay for non-Sendable closures
// because they cannot leave the isolation domain they're created
// in anyway.
if (closure->isSendable())
return false;
if (closure->getActorIsolation().isActorIsolated())
return false;
}
return true;
};
// For the call to require the given actor isolation, every DeclContext
// in the current context stack must require the same isolation. If
// along the way to the innermost context, we find a DeclContext that
// has a different isolation (e.g. it's a local function that does not
// receive isolation from its decl context), then the expression cannot
// require a different isolation.
for (auto *dc : contextStack) {
if (!infersIsolationFromContext(dc)) {
requiredIsolation.clear();
return false;
}
// To refine the required isolation, the existing requirement
// must either be 'nonisolated' or exactly the same as the
// new refinement.
auto isolation = requiredIsolation.find(dc);
if (isolation == requiredIsolation.end() ||
isolation->second == ActorIsolation::Nonisolated) {
requiredIsolation[dc] = refinedIsolation;
} else if (isolation->second != refinedIsolation) {
dc->getASTContext().Diags.diagnose(
requiredIsolationLoc,
diag::conflicting_default_argument_isolation,
isolation->second, refinedIsolation);
requiredIsolation.clear();
return true;
}
}
return true;
}
void checkDefaultArgument(DefaultArgumentExpr *expr) {
getCurrentContextIsolation(expr);
// Check the context isolation against the required isolation for
// evaluating the default argument synchronously. If the default
// argument must be evaluated asynchronously, record that in the
// expression node.
auto requiredIsolation = expr->getRequiredIsolation();
auto contextIsolation = getInnermostIsolatedContext(
getDeclContext(), getClosureActorIsolation);
if (requiredIsolation == contextIsolation)
return;
switch (requiredIsolation) {
// Nonisolated is okay from any caller isolation because
// default arguments cannot have any async calls.
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
return;
case ActorIsolation::Erased:
case ActorIsolation::GlobalActor:
case ActorIsolation::ActorInstance:
break;
}
expr->setImplicitlyAsync();
}
/// Check closure captures for Sendable violations.
void checkLocalCaptures(AnyFunctionRef localFunc) {
SmallVector<CapturedValue, 2> captures;
localFunc.getCaptureInfo().getLocalCaptures(captures);
for (const auto &capture : captures) {
if (capture.isDynamicSelfMetadata())
continue;
if (capture.isOpaqueValue())
continue;
auto *closure = localFunc.getAbstractClosureExpr();
auto *explicitClosure = dyn_cast_or_null<ClosureExpr>(closure);
bool preconcurrency = false;
if (explicitClosure) {
preconcurrency = explicitClosure->isIsolatedByPreconcurrency();
}
// Diagnose a `self` capture inside an escaping `sending`
// `@Sendable` closure in a deinit, which almost certainly
// means `self` would escape deinit at runtime.
auto *dc = getDeclContext();
if (explicitClosure && isa<DestructorDecl>(dc) &&
!explicitClosure->getType()->isNoEscape() &&
(explicitClosure->isPassedToSendingParameter() ||
explicitClosure->isSendable())) {
auto var = dyn_cast_or_null<VarDecl>(capture.getDecl());
if (var && var->isSelfParameter()) {
ctx.Diags.diagnose(explicitClosure->getLoc(),
diag::self_capture_deinit_task)
.limitBehaviorWithPreconcurrency(DiagnosticBehavior::Warning,
preconcurrency);
}
}
// If the closure won't execute concurrently with the context in
// which the declaration occurred, it's okay.
auto decl = capture.getDecl();
auto isolation = getActorIsolation(decl);
// 'nonisolated' local variables are always okay to capture in
// 'Sendable' closures because they can be accessed from anywhere.
// Note that only 'nonisolated(unsafe)' can be applied to local
// variables.
if (isolation.isNonisolated())
continue;
auto *context = localFunc.getAsDeclContext();
auto fnType = localFunc.getType()->getAs<AnyFunctionType>();
if (!mayExecuteConcurrentlyWith(context, decl->getDeclContext()))
continue;
Type type = getDeclContext()
->mapTypeIntoContext(decl->getInterfaceType())
->getReferenceStorageReferent();
if (type->hasError())
continue;
SendableCheckContext sendableContext(getDeclContext(),
preconcurrency);
if (closure && closure->isImplicit()) {
auto *patternBindingDecl = getTopPatternBindingDecl();
if (patternBindingDecl && patternBindingDecl->isAsyncLet()) {
// Defer diagnosing checking of non-Sendable types that are passed
// into async let to SIL level region based isolation if we have
// region based isolation enabled.
//
// We purposely do not do this for SendingArgsAndResults since that
// just triggers the actual ability to represent
// 'sending'. RegionBasedIsolation is what determines if we get the
// differing semantics.
if (!ctx.LangOpts.hasFeature(Feature::RegionBasedIsolation)) {
diagnoseNonSendableTypes(
type, getDeclContext(),
/*inDerivedConformance*/Type(), capture.getLoc(),
diag::implicit_async_let_non_sendable_capture,
decl->getName());
}
} else {
// Fallback to a generic implicit capture missing sendable
// conformance diagnostic.
diagnoseNonSendableTypes(type, sendableContext,
/*inDerivedConformance*/Type(),
capture.getLoc(),
diag::implicit_non_sendable_capture,
decl->getName());
}
} else if (fnType->isSendable()) {
diagnoseNonSendableTypes(type, sendableContext,
/*inDerivedConformance*/Type(),
capture.getLoc(),
diag::non_sendable_capture,
decl->getName(),
/*closure=*/closure != nullptr);
} else {
diagnoseNonSendableTypes(type, sendableContext,
/*inDerivedConformance*/Type(),
capture.getLoc(),
diag::non_sendable_isolated_capture,
decl->getName(),
/*closure=*/closure != nullptr);
}
}
}
public:
ActorIsolationChecker(
const DeclContext *dc,
llvm::function_ref<Type(Expr *)> getType = __Expr_getType,
llvm::function_ref<ActorIsolation(AbstractClosureExpr *)>
getClosureActorIsolation = __AbstractClosureExpr_getActorIsolation)
: ctx(dc->getASTContext()), getType(getType),
getClosureActorIsolation(getClosureActorIsolation) {
contextStack.push_back(dc);
}
ActorIsolation computeRequiredIsolation(Expr *expr) {
auto &ctx = getDeclContext()->getASTContext();
if (ctx.LangOpts.hasFeature(Feature::IsolatedDefaultValues))
requiredIsolationLoc = expr->getLoc();
expr->walk(*this);
requiredIsolationLoc = SourceLoc();
return requiredIsolation[getDeclContext()];
}
/// Searches the applyStack from back to front for the inner-most CallExpr
/// and marks that CallExpr as implicitly async.
///
/// NOTE: Crashes if no CallExpr was found.
///
/// For example, for global actor function `curryAdd`, if we have:
/// ((curryAdd 1) 2)
/// then we want to mark the inner-most CallExpr, `(curryAdd 1)`.
///
/// The same goes for calls to member functions, such as calc.add(1, 2),
/// aka ((add calc) 1 2), looks like this:
///
/// (call_expr
/// (dot_syntax_call_expr
/// (declref_expr add)
/// (declref_expr calc))
/// (tuple_expr
/// ...))
///
/// and we reach up to mark the CallExpr.
void markNearestCallAsImplicitly(std::optional<ActorIsolation> setAsync,
bool setThrows = false,
bool setDistributedThunk = false) {
assert(applyStack.size() > 0 && "not contained within an Apply?");
const auto End = applyStack.rend();
for (auto I = applyStack.rbegin(); I != End; ++I)
if (auto call = dyn_cast<CallExpr>(I->dyn_cast<ApplyExpr *>())) {
if (setAsync) {
call->setImplicitlyAsync(*setAsync);
}
if (setThrows) {
call->setImplicitlyThrows(true);
}else {
call->setImplicitlyThrows(false);
}
if (setDistributedThunk) {
call->setShouldApplyDistributedThunk(true);
}
return;
}
llvm_unreachable("expected a CallExpr in applyStack!");
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *pattern) override {
// Walking into patterns leads to nothing good because then we
// end up visiting the AccessorDecls of a top-level
// PatternBindingDecl twice.
return Action::SkipNode(pattern);
}
PreWalkAction walkToDeclPre(Decl *decl) override {
// Don't walk into local types because nothing in them can
// change the outcome of our analysis, and we don't want to
// assume things there have been type checked yet.
if (isa<TypeDecl>(decl)) {
return Action::SkipChildren();
}
if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
if (func->getDeclContext()->isLocalContext()) {
checkLocalCaptures(func);
}
contextStack.push_back(func);
}
if (auto *PBD = dyn_cast<PatternBindingDecl>(decl)) {
patternBindingStack.push_back(PBD);
}
return Action::Continue();
}
PostWalkAction walkToDeclPost(Decl *decl) override {
if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
assert(contextStack.back() == func);
contextStack.pop_back();
}
if (auto *PBD = dyn_cast<PatternBindingDecl>(decl)) {
assert(patternBindingStack.back() == PBD);
patternBindingStack.pop_back();
}
return Action::Continue();
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
// Skip expressions that didn't make it to solution application
// because the constraint system diagnosed an error.
if (!expr->getType())
return Action::SkipNode(expr);
if (auto *openExistential = dyn_cast<OpenExistentialExpr>(expr)) {
opaqueValues.push_back({
openExistential->getOpaqueValue(),
openExistential->getExistentialValue()});
return Action::Continue(expr);
}
if (auto *closure = dyn_cast<AbstractClosureExpr>(expr)) {
closure->setActorIsolation(determineClosureIsolation(closure));
checkLocalCaptures(closure);
contextStack.push_back(closure);
return Action::Continue(expr);
}
if (auto inout = dyn_cast<InOutExpr>(expr)) {
if (!applyStack.empty())
diagnoseInOutArg(applyStack.back(), inout, false);
if (mutableLocalVarParent.count(inout) == 0)
recordMutableVarParent(inout, inout->getSubExpr());
}
if (auto assign = dyn_cast<AssignExpr>(expr)) {
// mark vars in the destination expr as being part of the Assign.
if (auto destExpr = assign->getDest())
recordMutableVarParent(assign, destExpr);
return Action::Continue(expr);
}
if (auto load = dyn_cast<LoadExpr>(expr))
recordMutableVarParent(load, load->getSubExpr());
if (auto lookup = dyn_cast<LookupExpr>(expr)) {
applyStack.push_back(lookup);
checkReference(lookup->getBase(), lookup->getMember(), lookup->getLoc(),
/*partialApply*/ std::nullopt, lookup);
return Action::Continue(expr);
}
if (auto declRef = dyn_cast<DeclRefExpr>(expr)) {
auto valueRef = declRef->getDeclRef();
auto value = valueRef.getDecl();
auto loc = declRef->getLoc();
// FIXME: Should this be subsumed in reference checking?
if (value->isLocalCapture())
checkLocalCapture(valueRef, loc, declRef);
else
checkReference(nullptr, valueRef, loc, std::nullopt, declRef);
return Action::Continue(expr);
}
if (auto apply = dyn_cast<ApplyExpr>(expr)) {
// If this is a call to a partial apply thunk, decompose it to check it
// like based on the original written syntax, e.g., "self.method".
if (auto partialApply = decomposePartialApplyThunk(
apply, Parent.getAsExpr())) {
if (auto memberRef = findReference(partialApply->fn)) {
// NOTE: partially-applied thunks are never annotated as
// implicitly async, regardless of whether they are escaping.
checkReference(
partialApply->base, memberRef->first, memberRef->second,
partialApply);
partialApply->base->walk(*this);
return Action::SkipNode(expr);
}
}
applyStack.push_back(apply); // record this encounter
if (isa<SelfApplyExpr>(apply)) {
// Self applications are checked as part of the outer call.
// However, we look for inout issues here.
if (applyStack.size() >= 2) {
auto outerCall = applyStack[applyStack.size() - 2];
if (isAsyncCall(outerCall)) {
// This call is a partial application within an async call.
// If the partial application take a value inout, it is bad.
if (InOutExpr *inoutArg = dyn_cast<InOutExpr>(
apply->getArgs()->getExpr(0)->getSemanticsProvidingExpr()))
diagnoseInOutArg(outerCall, inoutArg, true);
}
}
} else {
// Check the call itself.
(void)checkApply(apply);
}
}
if (auto keyPath = dyn_cast<KeyPathExpr>(expr))
checkKeyPathExpr(keyPath);
// The children of #selector expressions are not evaluated, so we do not
// need to do isolation checking there. This is convenient because such
// expressions tend to violate restrictions on the use of instance
// methods.
if (isa<ObjCSelectorExpr>(expr))
return Action::SkipNode(expr);
// Track the capture contexts for variables.
if (auto captureList = dyn_cast<CaptureListExpr>(expr)) {
auto *closure = captureList->getClosureBody();
for (const auto &entry : captureList->getCaptureList()) {
captureContexts[entry.getVar()].push_back(closure);
}
}
// The constraint solver may not have chosen legal casts.
if (auto funcConv = dyn_cast<FunctionConversionExpr>(expr)) {
checkFunctionConversion(funcConv,
funcConv->getSubExpr()->getType(),
funcConv->getType());
}
if (auto *isolationErasure = dyn_cast<ActorIsolationErasureExpr>(expr)) {
checkFunctionConversion(isolationErasure,
isolationErasure->getSubExpr()->getType(),
isolationErasure->getType());
}
if (auto *defaultArg = dyn_cast<DefaultArgumentExpr>(expr)) {
checkDefaultArgument(defaultArg);
}
return Action::Continue(expr);
}
PostWalkResult<Expr *> walkToExprPost(Expr *expr) override {
if (auto *openExistential = dyn_cast<OpenExistentialExpr>(expr)) {
assert(opaqueValues.back().first == openExistential->getOpaqueValue());
opaqueValues.pop_back();
return Action::Continue(expr);
}
if (auto *closure = dyn_cast<AbstractClosureExpr>(expr)) {
assert(contextStack.back() == closure);
contextStack.pop_back();
}
if (auto *apply = dyn_cast<ApplyExpr>(expr)) {
assert(applyStack.back().get<ApplyExpr *>() == apply);
applyStack.pop_back();
}
// Clear out the mutable local variable parent map on the way out.
if (auto *declRefExpr = dyn_cast<DeclRefExpr>(expr)) {
mutableLocalVarParent.erase(declRefExpr);
} else if (auto *lookupExpr = dyn_cast<LookupExpr>(expr)) {
mutableLocalVarParent.erase(lookupExpr);
assert(applyStack.back().dyn_cast<LookupExpr *>() == lookupExpr);
applyStack.pop_back();
} else if (auto *inoutExpr = dyn_cast<InOutExpr>(expr)) {
mutableLocalVarParent.erase(inoutExpr);
}
// Remove the tracked capture contexts.
if (auto captureList = dyn_cast<CaptureListExpr>(expr)) {
for (const auto &entry : captureList->getCaptureList()) {
auto &contexts = captureContexts[entry.getVar()];
assert(contexts.back() == captureList->getClosureBody());
contexts.pop_back();
if (contexts.empty())
captureContexts.erase(entry.getVar());
}
}
if (auto isolationExpr = dyn_cast<CurrentContextIsolationExpr>(expr))
recordCurrentContextIsolation(isolationExpr);
return Action::Continue(expr);
}
private:
/// Find the directly-referenced parameter or capture of a parameter for
/// for the given expression.
VarDecl *getReferencedParamOrCapture(Expr *expr) {
return ::getReferencedParamOrCapture(
expr, [&](OpaqueValueExpr *opaqueValue) -> Expr * {
for (const auto &known : opaqueValues) {
if (known.first == opaqueValue) {
return known.second;
}
}
return nullptr;
},
[this]() -> VarDecl * {
auto isolation = getActorIsolationOfContext(
const_cast<DeclContext *>(getDeclContext()),
getClosureActorIsolation);
if (isolation == ActorIsolation::ActorInstance) {
VarDecl *var = isolation.getActorInstance();
if (!var) {
auto dc = const_cast<DeclContext *>(getDeclContext());
auto paramIdx = isolation.getActorInstanceParameter();
if (paramIdx == 0) {
var = cast<AbstractFunctionDecl>(dc)->getImplicitSelfDecl();
} else {
var = const_cast<ParamDecl *>(getParameterAt(dc, paramIdx - 1));
}
}
return var;
}
return nullptr;
});
}
/// Find the isolated actor instance to which the given expression refers.
ReferencedActor getIsolatedActor(Expr *expr) {
// Check whether this expression is an isolated parameter or a reference
// to a capture thereof.
auto var = getReferencedParamOrCapture(expr);
bool isPotentiallyIsolated = isPotentiallyIsolatedActor(var);
// helps aid in giving more informative diagnostics for autoclosure args.
auto specificNonIsoClosureKind =
[](DeclContext const* dc) -> ReferencedActor::Kind {
if (auto autoClos = dyn_cast<AutoClosureExpr>(dc))
if (autoClos->getThunkKind() == AutoClosureExpr::Kind::None)
return ReferencedActor::NonIsolatedAutoclosure;
return ReferencedActor::NonIsolatedContext;
};
// Walk the scopes between the variable reference and the variable
// declaration to determine whether it is still isolated.
auto dc = const_cast<DeclContext *>(getDeclContext());
for (; dc; dc = dc->getParent()) {
// If we hit the context in which the parameter is declared, we're done.
if (var && dc == var->getDeclContext()) {
if (isPotentiallyIsolated) {
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::Isolated);
}
}
// If we've hit a module or type boundary, we're done.
if (dc->isModuleScopeContext() || dc->isTypeContext())
break;
if (auto closure = dyn_cast<AbstractClosureExpr>(dc)) {
auto isolation = getClosureActorIsolation(closure);
switch (isolation) {
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
if (isSendableClosure(closure, /*forActorIsolation=*/true)) {
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::SendableClosure);
}
return ReferencedActor(var, isPotentiallyIsolated, specificNonIsoClosureKind(dc));
case ActorIsolation::ActorInstance:
// If the closure is isolated to the same variable, we're all set.
if (isPotentiallyIsolated &&
(var == isolation.getActorInstance() ||
(var->isSelfParamCapture() &&
(isolation.getActorInstance()->isSelfParameter() ||
isolation.getActorInstance()->isSelfParamCapture())))) {
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::Isolated);
}
return ReferencedActor(var, isPotentiallyIsolated, specificNonIsoClosureKind(dc));
case ActorIsolation::GlobalActor:
return ReferencedActor::forGlobalActor(
var, isPotentiallyIsolated, isolation.getGlobalActor());
case ActorIsolation::Erased:
llvm_unreachable("closure cannot have erased isolation");
}
}
// Check for an 'async let' autoclosure.
if (auto autoclosure = dyn_cast<AutoClosureExpr>(dc)) {
switch (autoclosure->getThunkKind()) {
case AutoClosureExpr::Kind::AsyncLet:
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::AsyncLet);
case AutoClosureExpr::Kind::DoubleCurryThunk:
case AutoClosureExpr::Kind::SingleCurryThunk:
case AutoClosureExpr::Kind::None:
break;
}
}
// Look through defers.
// FIXME: should this be covered automatically by the logic below?
if (auto func = dyn_cast<FuncDecl>(dc))
if (func->isDeferBody())
continue;
if (auto func = dyn_cast<AbstractFunctionDecl>(dc)) {
// @Sendable functions are nonisolated.
if (func->isSendable())
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::SendableFunction);
}
// Check isolation of the context itself. We do this separately
// from the closure check because closures capture specific variables
// while general isolation is declaration-based.
switch (auto isolation =
getActorIsolationOfContext(dc, getClosureActorIsolation)) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
// Local functions can capture an isolated parameter.
// FIXME: This really should be modeled by getActorIsolationOfContext.
if (isa<FuncDecl>(dc) && cast<FuncDecl>(dc)->isLocalCapture()) {
// FIXME: Local functions could presumably capture an isolated
// parameter that isn't 'self'.
if (isPotentiallyIsolated &&
(var->isSelfParameter() || var->isSelfParamCapture()))
continue;
}
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::NonIsolatedContext);
case ActorIsolation::Erased:
llvm_unreachable("context cannot have erased isolation");
case ActorIsolation::GlobalActor:
return ReferencedActor::forGlobalActor(
var, isPotentiallyIsolated, isolation.getGlobalActor());
case ActorIsolation::ActorInstance:
break;
}
}
if (isPotentiallyIsolated)
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::NonIsolatedContext);
return ReferencedActor(var, isPotentiallyIsolated, ReferencedActor::NonIsolatedParameter);
}
/// Note that the given actor member is isolated.
/// @param context is allowed to be null if no context is appropriate.
void noteIsolatedActorMember(ValueDecl const* decl, Expr *context) {
::noteIsolatedActorMember(decl, kindOfUsage(decl, context));
}
// Retrieve the nearest enclosing actor context.
static NominalTypeDecl *getNearestEnclosingActorContext(
const DeclContext *dc) {
while (!dc->isModuleScopeContext()) {
if (dc->isTypeContext()) {
// FIXME: Protocol extensions need specific handling here.
if (auto nominal = dc->getSelfNominalTypeDecl()) {
if (nominal->isActor())
return nominal;
}
}
dc = dc->getParent();
}
return nullptr;
}
/// Diagnose a reference to an unsafe entity.
///
/// \returns true if we diagnosed the entity, \c false otherwise.
bool diagnoseReferenceToUnsafeGlobal(ValueDecl *value, SourceLoc loc) {
auto &ctx = value->getASTContext();
switch (ctx.LangOpts.StrictConcurrencyLevel) {
case StrictConcurrency::Minimal:
case StrictConcurrency::Targeted:
// Never diagnose.
return false;
case StrictConcurrency::Complete:
break;
}
// Only diagnose direct references to mutable global state.
auto var = dyn_cast<VarDecl>(value);
if (!var || var->isLet())
return false;
if (!var->getDeclContext()->isModuleScopeContext() &&
!(var->getDeclContext()->isTypeContext() && !var->isInstanceMember()))
return false;
if (!var->hasStorage())
return false;
// If it's actor-isolated, it's already been dealt with.
const auto isolation = getActorIsolation(value);
if (isolation.isActorIsolated())
return false;
if (auto attr = value->getAttrs().getAttribute<NonisolatedAttr>();
attr && attr->isUnsafe()) {
return false;
}
// If global variable checking is enabled and the global variable is
// from the same module as the reference, we'll already have diagnosed
// the global variable itself.
if (ctx.LangOpts.hasFeature(Feature::GlobalConcurrency) &&
var->getDeclContext()->getParentModule() ==
getDeclContext()->getParentModule())
return false;
const auto import = var->findImport(getDeclContext());
const bool isPreconcurrencyImport =
import && import->options.contains(ImportFlags::Preconcurrency);
const auto isPreconcurrencyUnspecifiedIsolation =
isPreconcurrencyImport && isolation.isUnspecified();
// If the global variable is preconcurrency without an explicit
// isolation, ignore the warning. Otherwise, limit the behavior
// to a warning until Swift 6.
DiagnosticBehavior limit;
if (isPreconcurrencyUnspecifiedIsolation) {
limit = DiagnosticBehavior::Ignore;
} else {
limit = DiagnosticBehavior::Warning;
}
ctx.Diags.diagnose(loc, diag::shared_mutable_state_access, value)
.limitBehaviorUntilSwiftVersion(limit, 6)
// Preconcurrency global variables are warnings even in Swift 6
.limitBehaviorIf(isPreconcurrencyImport, limit);
value->diagnose(diag::kind_declared_here, value->getDescriptiveKind());
if (const auto sourceFile = getDeclContext()->getParentSourceFile();
sourceFile && isPreconcurrencyImport) {
sourceFile->setImportUsedPreconcurrency(*import);
}
return true;
}
/// Diagnose an inout argument passed into an async call
///
/// \returns true if we diagnosed the entity, \c false otherwise.
bool diagnoseInOutArg(
llvm::PointerUnion<ApplyExpr *, LookupExpr *> call,
const InOutExpr *arg,
bool isPartialApply) {
// check that the call is actually async
if (!isAsyncCall(call))
return false;
bool result = false;
bool downgradeToWarning = false;
auto diagnoseIsolatedInoutState = [&](
ConcreteDeclRef declRef, SourceLoc argLoc) {
auto decl = declRef.getDecl();
auto isolation = getActorIsolationForReference(decl, getDeclContext());
if (!isolation.isActorIsolated())
return;
if (isPartialApply) {
auto *apply = call.get<ApplyExpr *>();
// The partially applied InoutArg is a property of actor. This
// can really only happen when the property is a struct with a
// mutating async method.
if (auto partialApply = dyn_cast<ApplyExpr>(apply->getFn())) {
if (auto declRef = dyn_cast<DeclRefExpr>(partialApply->getFn())) {
ValueDecl *fnDecl = declRef->getDecl();
ctx.Diags.diagnose(apply->getLoc(),
diag::actor_isolated_mutating_func,
fnDecl->getName(), decl)
.warnUntilSwiftVersionIf(downgradeToWarning, 6);
result = true;
return;
}
}
}
bool isImplicitlyAsync;
if (auto *apply = call.dyn_cast<ApplyExpr *>()) {
isImplicitlyAsync = apply->isImplicitlyAsync().has_value();
} else {
auto *lookup = call.get<LookupExpr *>();
isImplicitlyAsync = lookup->isImplicitlyAsync().has_value();
}
ctx.Diags.diagnose(argLoc, diag::actor_isolated_inout_state,
decl, isImplicitlyAsync);
decl->diagnose(diag::kind_declared_here, decl->getDescriptiveKind());
result = true;
return;
};
auto findIsolatedState = [&](Expr *expr) -> Expr * {
// This code used to not walk into InOutExpr, which allowed
// some invalid code to slip by in compilers <=5.9.
if (isa<InOutExpr>(expr))
downgradeToWarning = true;
if (LookupExpr *lookup = dyn_cast<LookupExpr>(expr)) {
if (isa<DeclRefExpr>(lookup->getBase())) {
diagnoseIsolatedInoutState(lookup->getMember().getDecl(),
expr->getLoc());
return nullptr; // Diagnosed. Don't keep walking
}
}
if (DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(expr)) {
diagnoseIsolatedInoutState(declRef->getDecl(), expr->getLoc());
return nullptr; // Diagnosed. Don't keep walking
}
return expr;
};
arg->getSubExpr()->forEachChildExpr(findIsolatedState);
return result;
}
enum class AsyncMarkingResult {
FoundAsync, // successfully marked an implicitly-async operation
NotFound, // fail: no valid implicitly-async operation was found
SyncContext, // fail: a valid implicitly-async op, but in sync context
NotDistributed, // fail: non-distributed declaration in distributed actor
};
/// Determine whether we can access the given declaration that is
/// isolated to a distributed actor from a location that is potentially not
/// local to this process.
///
/// \returns the (setThrows, isDistributedThunk) bits to implicitly
/// mark the access/call with on success, or emits an error and returns
/// \c std::nullopt.
std::optional<std::pair<bool, bool>>
checkDistributedAccess(SourceLoc declLoc, ValueDecl *decl, Expr *context) {
// If the actor itself is, we're not doing any distributed access.
if (getIsolatedActor(context).isKnownToBeLocal()) {
return std::make_pair(
/*setThrows=*/false,
/*isDistributedThunk=*/false);
}
// If there is no declaration, it can't possibly be distributed.
if (!decl) {
ctx.Diags.diagnose(declLoc, diag::distributed_actor_isolated_method);
return std::nullopt;
}
// Check that we have a distributed function or computed property.
if (auto afd = dyn_cast<AbstractFunctionDecl>(decl)) {
if (!afd->isDistributed()) {
ctx.Diags.diagnose(declLoc, diag::distributed_actor_isolated_method)
.fixItInsert(decl->getAttributeInsertionLoc(true),
"distributed ");
noteIsolatedActorMember(decl, context);
return std::nullopt;
}
return std::make_pair(
/*setThrows=*/!afd->hasThrows(),
/*isDistributedThunk=*/true);
}
if (auto *var = dyn_cast<VarDecl>(decl)) {
if (var->isDistributed()) {
bool explicitlyThrowing = false;
if (auto getter = var->getAccessor(swift::AccessorKind::Get)) {
explicitlyThrowing = getter->hasThrows();
}
return std::make_pair(
/*setThrows*/ !explicitlyThrowing,
/*isDistributedThunk=*/true);
}
// In compiler versions <=5.10, the compiler did not diagnose cases
// where a non-isolated distributed actor value was passed to a VarDecl
// with a function type type that has an isolated distributed actor
// parameter, e.g. `(isolated DA) -> Void`. Stage in the error as a
// warning until Swift 6.
if (var->getTypeInContext()->getAs<FunctionType>()) {
ctx.Diags.diagnose(declLoc,
diag::distributed_actor_isolated_non_self_reference,
decl)
.warnUntilSwiftVersion(6);
noteIsolatedActorMember(decl, context);
return std::nullopt;
}
}
// FIXME: Subscript?
// This is either non-distributed variable, subscript, or something else.
ctx.Diags.diagnose(declLoc,
diag::distributed_actor_isolated_non_self_reference,
decl);
noteIsolatedActorMember(decl, context);
return std::nullopt;
}
/// Attempts to identify and mark a valid cross-actor use of a synchronous
/// actor-isolated member (e.g., sync function application, property access)
AsyncMarkingResult tryMarkImplicitlyAsync(SourceLoc declLoc,
ConcreteDeclRef concDeclRef,
Expr* context,
ActorIsolation target,
bool isDistributed) {
ValueDecl *decl = concDeclRef.getDecl();
AsyncMarkingResult result = AsyncMarkingResult::NotFound;
// is it an access to a property?
if (isPropOrSubscript(decl)) {
// Cannot reference properties or subscripts of distributed actors.
if (isDistributed) {
bool setThrows = false;
bool usesDistributedThunk = false;
if (auto access = checkDistributedAccess(declLoc, decl, context)) {
std::tie(setThrows, usesDistributedThunk) = *access;
} else {
return AsyncMarkingResult::NotDistributed;
}
// distributed computed property access, mark it throws + async
if (auto lookupExpr = dyn_cast_or_null<LookupExpr>(context)) {
if (auto memberRef = dyn_cast<MemberRefExpr>(lookupExpr)) {
memberRef->setImplicitlyThrows(true);
memberRef->setAccessViaDistributedThunk();
} else {
llvm_unreachable("expected distributed prop to be a MemberRef");
}
} else {
llvm_unreachable("expected distributed prop to have LookupExpr");
}
}
if (auto declRef = dyn_cast_or_null<DeclRefExpr>(context)) {
if (usageEnv(declRef) == VarRefUseEnv::Read) {
if (!getDeclContext()->isAsyncContext())
return AsyncMarkingResult::SyncContext;
declRef->setImplicitlyAsync(target);
result = AsyncMarkingResult::FoundAsync;
}
} else if (auto lookupExpr = dyn_cast_or_null<LookupExpr>(context)) {
if (usageEnv(lookupExpr) == VarRefUseEnv::Read) {
if (!getDeclContext()->isAsyncContext())
return AsyncMarkingResult::SyncContext;
lookupExpr->setImplicitlyAsync(target);
result = AsyncMarkingResult::FoundAsync;
}
}
}
return result;
}
/// Check actor isolation for a particular application.
bool checkApply(ApplyExpr *apply) {
auto fnExprType = getType(apply->getFn());
if (!fnExprType)
return false;
auto fnType = fnExprType->getAs<FunctionType>();
if (!fnType)
return false;
// The isolation of the context we're in.
std::optional<ActorIsolation> contextIsolation;
auto getContextIsolation = [&]() -> ActorIsolation {
if (contextIsolation)
return *contextIsolation;
auto declContext = const_cast<DeclContext *>(getDeclContext());
contextIsolation =
getInnermostIsolatedContext(declContext, getClosureActorIsolation);
return *contextIsolation;
};
// Default the call options to allow promotion to async, if it will be
// warranted.
ActorReferenceResult::Options callOptions;
if (!fnType->getExtInfo().isAsync())
callOptions |= ActorReferenceResult::Flags::AsyncPromotion;
// Determine from the callee whether actor isolation is unsatisfied.
std::optional<ActorIsolation> unsatisfiedIsolation;
bool mayExitToNonisolated = true;
Expr *argForIsolatedParam = nullptr;
auto calleeDecl = apply->getCalledValue(/*skipFunctionConversions=*/true);
auto fnTypeIsolation = fnType->getIsolation();
if (fnTypeIsolation.isGlobalActor()) {
// If the function type is global-actor-qualified, determine whether
// we are within that global actor already.
Type globalActor = fnTypeIsolation.getGlobalActorType();
if (!(getContextIsolation().isGlobalActor() &&
getContextIsolation().getGlobalActor()->isEqual(globalActor)))
unsatisfiedIsolation = ActorIsolation::forGlobalActor(globalActor);
mayExitToNonisolated = false;
} else if (fnTypeIsolation.isErased()) {
unsatisfiedIsolation = ActorIsolation::forErased();
mayExitToNonisolated = false;
} else if (auto *selfApplyFn = dyn_cast<SelfApplyExpr>(
apply->getFn()->getValueProvidingExpr())) {
// If we're calling a member function, check whether the function
// itself is isolated.
auto memberFn = selfApplyFn->getFn()->getValueProvidingExpr();
if (auto memberRef = findReference(memberFn)) {
auto isolatedActor = getIsolatedActor(selfApplyFn->getBase());
auto result = ActorReferenceResult::forReference(
memberRef->first, selfApplyFn->getLoc(), getDeclContext(),
kindOfUsage(memberRef->first.getDecl(), selfApplyFn),
isolatedActor, std::nullopt, std::nullopt,
getClosureActorIsolation);
switch (result) {
case ActorReferenceResult::SameConcurrencyDomain:
break;
case ActorReferenceResult::ExitsActorToNonisolated:
unsatisfiedIsolation =
ActorIsolation::forNonisolated(/*unsafe=*/false);
break;
case ActorReferenceResult::EntersActor:
unsatisfiedIsolation = result.isolation;
break;
}
callOptions = result.options;
mayExitToNonisolated = false;
calleeDecl = memberRef->first.getDecl();
argForIsolatedParam = selfApplyFn->getBase();
}
} else if (calleeDecl &&
calleeDecl->getAttrs()
.hasAttribute<UnsafeInheritExecutorAttr>()) {
return false;
}
// Check for isolated parameters.
for (unsigned paramIdx : range(fnType->getNumParams())) {
// We only care about isolated parameters.
if (!fnType->getParams()[paramIdx].isIsolated())
continue;
auto *args = apply->getArgs();
if (paramIdx >= args->size())
continue;
auto *arg = args->getExpr(paramIdx);
// FIXME: CurrentContextIsolationExpr does not have its actor set
// at this point.
if (auto isolation = getCurrentContextIsolation(arg))
arg = isolation;
argForIsolatedParam = arg;
unsatisfiedIsolation = std::nullopt;
// Assume that a callee with an isolated parameter does not
// cross an isolation boundary. We'll set this again below if
// the given isolated argument doesn't match the isolation of the
// caller.
mayExitToNonisolated = false;
// If the argument is an isolated parameter from the enclosing context,
// or #isolation, then the call does not cross an isolation boundary.
if (getIsolatedActor(arg) || isa<CurrentContextIsolationExpr>(arg))
continue;
auto calleeIsolation = ActorIsolation::forActorInstanceParameter(
const_cast<Expr *>(arg->findOriginalValue()), paramIdx);
if (getContextIsolation() != calleeIsolation) {
if (calleeIsolation.isNonisolated()) {
mayExitToNonisolated = true;
} else {
unsatisfiedIsolation = calleeIsolation;
}
}
if (!fnType->getExtInfo().isAsync())
callOptions |= ActorReferenceResult::Flags::AsyncPromotion;
break;
}
// If we're calling an async function that's nonisolated, and we're in
// an isolated context, then we're exiting the actor context.
if (mayExitToNonisolated && fnType->isAsync() &&
getContextIsolation().isActorIsolated())
unsatisfiedIsolation = ActorIsolation::forNonisolated(/*unsafe=*/false);
// If there was no unsatisfied actor isolation, we're done.
if (!unsatisfiedIsolation)
return false;
bool onlyArgsCrossIsolation = callOptions.contains(
ActorReferenceResult::Flags::OnlyArgsCrossIsolation);
if (!onlyArgsCrossIsolation &&
refineRequiredIsolation(*unsatisfiedIsolation))
return false;
// At this point, we know a jump is made to the callee that yields
// an isolation requirement unsatisfied by the calling context, so
// set the unsatisfiedIsolationJump fields of the ApplyExpr appropriately
apply->setIsolationCrossing(getContextIsolation(), *unsatisfiedIsolation);
bool requiresAsync =
callOptions.contains(ActorReferenceResult::Flags::AsyncPromotion);
// If we need to mark the call as implicitly asynchronous, make sure
// we're in an asynchronous context.
if (requiresAsync && !getDeclContext()->isAsyncContext()) {
if (ctx.LangOpts.hasFeature(Feature::GroupActorErrors)) {
IsolationError mismatch([calleeDecl, apply, unsatisfiedIsolation, getContextIsolation]() {
if (calleeDecl) {
auto preconcurrency = getContextIsolation().preconcurrency() ||
getActorIsolation(calleeDecl).preconcurrency();
return IsolationError(
apply->getLoc(),
preconcurrency,
Diagnostic(diag::actor_isolated_call_decl,
*unsatisfiedIsolation,
calleeDecl,
getContextIsolation()));
} else {
return IsolationError(
apply->getLoc(),
getContextIsolation().preconcurrency(),
Diagnostic(diag::actor_isolated_call,
*unsatisfiedIsolation,
getContextIsolation()));
}
}());
auto iter = applyErrors.find(std::make_pair(*unsatisfiedIsolation, getContextIsolation()));
if (iter != applyErrors.end()){
iter->second.push_back((mismatch));
} else {
DiagnosticList list;
list.push_back((mismatch));
auto keyPair = std::make_pair(*unsatisfiedIsolation, getContextIsolation());
applyErrors.insert(std::make_pair(keyPair, list));
}
} else {
if (calleeDecl) {
auto preconcurrency = getContextIsolation().preconcurrency() ||
getActorIsolation(calleeDecl).preconcurrency();
ctx.Diags.diagnose(
apply->getLoc(), diag::actor_isolated_call_decl,
*unsatisfiedIsolation,
calleeDecl,
getContextIsolation())
.warnUntilSwiftVersionIf(preconcurrency, 6);
calleeDecl->diagnose(diag::actor_isolated_sync_func, calleeDecl);
} else {
ctx.Diags.diagnose(
apply->getLoc(), diag::actor_isolated_call, *unsatisfiedIsolation,
getContextIsolation())
.warnUntilSwiftVersionIf(getContextIsolation().preconcurrency(), 6);
}
if (unsatisfiedIsolation->isGlobalActor()) {
missingGlobalActorOnContext(
const_cast<DeclContext *>(getDeclContext()),
unsatisfiedIsolation->getGlobalActor(), DiagnosticBehavior::Note);
}
}
return true;
}
// If the actor we're hopping to is distributed, we might also need
// to mark the call as throwing and/or using the distributed thunk.
// FIXME: ActorReferenceResult has this information, too.
bool setThrows = false;
bool usesDistributedThunk = false;
if (unsatisfiedIsolation->isDistributedActor() &&
!(calleeDecl && isa<ConstructorDecl>(calleeDecl))) {
auto distributedAccess = checkDistributedAccess(
apply->getFn()->getLoc(), calleeDecl, argForIsolatedParam);
if (!distributedAccess)
return true;
std::tie(setThrows, usesDistributedThunk) = *distributedAccess;
}
// Mark as implicitly async/throws/distributed thunk as needed.
if (requiresAsync || setThrows || usesDistributedThunk) {
markNearestCallAsImplicitly(
unsatisfiedIsolation, setThrows, usesDistributedThunk);
}
// Check if language features ask us to defer sendable diagnostics if so,
// don't check for sendability of arguments here.
if (!ctx.LangOpts.hasFeature(Feature::RegionBasedIsolation)) {
diagnoseApplyArgSendability(apply, getDeclContext());
}
// Check for sendability of the result type if we do not have a
// sending result.
if ((!ctx.LangOpts.hasFeature(Feature::RegionBasedIsolation) ||
!fnType->hasSendingResult())) {
assert(ctx.LangOpts.hasFeature(Feature::SendingArgsAndResults) &&
"SendingArgsAndResults should be enabled if RegionIsolation is "
"enabled");
// See if we are a autoclosure that has a direct callee that has the
// same non-transferred type value returned. If so, do not emit an
// error... we are going to emit an error on the call expr and do not
// want to emit the error twice.
auto willDoubleError = [&]() -> bool {
auto *autoclosure = dyn_cast<AutoClosureExpr>(apply->getFn());
if (!autoclosure)
return false;
auto *await =
dyn_cast<AwaitExpr>(autoclosure->getSingleExpressionBody());
if (!await)
return false;
auto *subCallExpr = dyn_cast<CallExpr>(await->getSubExpr());
if (!subCallExpr)
return false;
return subCallExpr->getType().getPointer() ==
fnType->getResult().getPointer();
};
if (!willDoubleError() &&
diagnoseNonSendableTypes(fnType->getResult(), getDeclContext(),
/*inDerivedConformance*/ Type(),
apply->getLoc(),
diag::non_sendable_call_result_type,
apply->isImplicitlyAsync().has_value(),
*unsatisfiedIsolation)) {
return true;
}
}
return false;
}
Expr *getCurrentContextIsolation(Expr *expr) {
// Look through caller-side default arguments for #isolation.
auto *defaultArg = dyn_cast<DefaultArgumentExpr>(expr);
if (defaultArg && defaultArg->isCallerSide()) {
expr = defaultArg->getCallerSideDefaultExpr();
}
if (auto *macro = dyn_cast<MacroExpansionExpr>(expr)) {
expr = macro->getRewritten();
}
if (auto *isolation = dyn_cast<CurrentContextIsolationExpr>(expr)) {
recordCurrentContextIsolation(isolation);
return isolation->getActor();
}
return nullptr;
}
/// Check whether there are _unsafeInheritExecutor_ workarounds in the
/// given _Concurrency module.
static bool hasUnsafeInheritExecutorWorkarounds(
DeclContext *dc, SourceLoc loc
) {
ASTContext &ctx = dc->getASTContext();
Identifier name =
ctx.getIdentifier("_unsafeInheritExecutor_withUnsafeContinuation");
NameLookupOptions lookupOptions = defaultUnqualifiedLookupOptions;
LookupResult lookup = TypeChecker::lookupUnqualified(
dc, DeclNameRef(name), loc, lookupOptions);
return !lookup.empty();
}
void recordCurrentContextIsolation(
CurrentContextIsolationExpr *isolationExpr) {
// If an actor has already been assigned, we're done.
if (isolationExpr->getActor())
return;
// #isolation does not work within an `@_unsafeInheritExecutor` function.
if (auto func = enclosingUnsafeInheritsExecutor(getDeclContext())) {
// This expression is always written as a macro #isolation in source,
// so find the enclosing macro expansion expression's location.
SourceLoc diagLoc;
bool inDefaultArgument;
std::tie(diagLoc, inDefaultArgument) = adjustPoundIsolationDiagLoc(
isolationExpr, getDeclContext()->getParentModule());
bool inConcurrencyModule = ::inConcurrencyModule(getDeclContext());
auto diag = ctx.Diags.diagnose(diagLoc,
diag::isolation_in_inherits_executor,
inDefaultArgument);
diag.limitBehaviorIf(inConcurrencyModule, DiagnosticBehavior::Warning);
if (!inConcurrencyModule &&
!hasUnsafeInheritExecutorWorkarounds(func, func->getLoc())) {
diag.limitBehavior(DiagnosticBehavior::Warning);
}
replaceUnsafeInheritExecutorWithDefaultedIsolationParam(func, diag);
}
auto loc = isolationExpr->getLoc();
auto isolation = getActorIsolationOfContext(
const_cast<DeclContext *>(getDeclContext()),
getClosureActorIsolation);
auto *dc = const_cast<DeclContext *>(getDeclContext());
// Note that macro expansions are never implicit. They have
// valid source locations in their macro expansion buffer, they
// do not cause implicit 'self' capture diagnostics, etc.
Expr *actorExpr = nullptr;
Type optionalAnyActorType = isolationExpr->getType();
switch (isolation) {
case ActorIsolation::ActorInstance: {
if (auto *instance = isolation.getActorInstanceExpr()) {
actorExpr = instance;
break;
}
const VarDecl *var = isolation.getActorInstance();
if (!var) {
auto dc = getDeclContext();
auto paramIdx = isolation.getActorInstanceParameter();
if (paramIdx == 0) {
var = cast<AbstractFunctionDecl>(dc)->getImplicitSelfDecl();
} else {
var = getParameterAt(dc, paramIdx - 1);
}
}
actorExpr = new (ctx) DeclRefExpr(
const_cast<VarDecl *>(var), DeclNameLoc(loc),
/*implicit=*/false);
// For a distributed actor, we need to retrieve the local
// actor.
if (isolation.isDistributedActor()) {
actorExpr = UnresolvedDotExpr::createImplicit(
ctx, actorExpr, ctx.Id_asLocalActor);
}
break;
}
case ActorIsolation::GlobalActor: {
// Form a <global actor type>.shared reference.
Type globalActorType = getDeclContext()->mapTypeIntoContext(
isolation.getGlobalActor());
auto typeExpr = TypeExpr::createForDecl(
DeclNameLoc(loc), globalActorType->getAnyNominal(), dc);
actorExpr = new (ctx) UnresolvedDotExpr(
typeExpr, loc, DeclNameRef(ctx.Id_shared), DeclNameLoc(loc),
/*implicit=*/false);
break;
}
case ActorIsolation::Erased:
llvm_unreachable("context cannot have erased isolation");
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
actorExpr = new (ctx) NilLiteralExpr(loc, /*implicit=*/false);
break;
}
// Convert the actor argument to the appropriate type.
(void)TypeChecker::typeCheckExpression(
actorExpr, dc,
constraints::ContextualTypeInfo(
optionalAnyActorType, CTP_CallArgument));
isolationExpr->setActor(actorExpr);
}
/// Find the innermost context in which this declaration was explicitly
/// captured.
const DeclContext *findCapturedDeclContext(ValueDecl *value) {
assert(value->isLocalCapture());
auto var = dyn_cast<VarDecl>(value);
if (!var)
return value->getDeclContext();
auto knownContexts = captureContexts.find(var);
if (knownContexts == captureContexts.end())
return value->getDeclContext();
return knownContexts->second.back();
}
/// Check a reference to a local capture.
bool checkLocalCapture(
ConcreteDeclRef valueRef, SourceLoc loc, DeclRefExpr *declRefExpr) {
auto value = valueRef.getDecl();
auto *dc = getDeclContext();
// Check whether we are in a context that will not execute concurrently
// with the context of 'self'. If not, it's safe.
if (!mayExecuteConcurrentlyWith(dc, findCapturedDeclContext(value)))
return false;
bool preconcurrency = false;
if (auto *closure = dyn_cast<ClosureExpr>(dc)) {
preconcurrency = closure->isIsolatedByPreconcurrency();
}
SendableCheckContext sendableBehavior(dc, preconcurrency);
auto limit = sendableBehavior.defaultDiagnosticBehavior();
// Check whether this is a local variable, in which case we can
// determine whether it was safe to access concurrently.
if (auto var = dyn_cast<VarDecl>(value)) {
// Ignore interpolation variables.
if (var->getBaseName() == ctx.Id_dollarInterpolation)
return false;
auto parent = mutableLocalVarParent[declRefExpr];
// If the variable is immutable, it's fine so long as it involves
// Sendable types.
//
// When flow-sensitive concurrent captures are enabled, we also
// allow reads, depending on a SIL diagnostic pass to identify the
// remaining race conditions.
if (!var->supportsMutation() ||
(ctx.LangOpts.hasFeature(
Feature::FlowSensitiveConcurrencyCaptures) &&
parent.dyn_cast<LoadExpr *>())) {
return false;
}
if (auto param = dyn_cast<ParamDecl>(value)) {
if (param->isInOut()) {
ctx.Diags
.diagnose(loc, diag::concurrent_access_of_inout_param,
param->getName())
.limitBehaviorWithPreconcurrency(limit, preconcurrency);
return true;
}
}
if (auto attr = var->getAttrs().getAttribute<NonisolatedAttr>();
attr && attr->isUnsafe()) {
return false;
}
// Otherwise, we have concurrent access. Complain.
ctx.Diags.diagnose(
loc, diag::concurrent_access_of_local_capture,
parent.dyn_cast<LoadExpr *>(),
var)
.limitBehaviorWithPreconcurrency(limit, preconcurrency);
return true;
}
if (auto func = dyn_cast<FuncDecl>(value)) {
if (func->isSendable())
return false;
func->diagnose(diag::local_function_executed_concurrently, func)
.fixItInsert(func->getAttributeInsertionLoc(false), "@Sendable ")
.limitBehaviorWithPreconcurrency(limit, preconcurrency);
// Add the @Sendable attribute implicitly, so we don't diagnose
// again.
const_cast<FuncDecl *>(func)->getAttrs().add(
new (ctx) SendableAttr(true));
return true;
}
// Concurrent access to some other local.
ctx.Diags.diagnose(loc, diag::concurrent_access_local, value)
.limitBehaviorWithPreconcurrency(limit, preconcurrency);
value->diagnose(
diag::kind_declared_here, value->getDescriptiveKind());
return true;
}
///
/// \return true iff a diagnostic was emitted
bool checkKeyPathExpr(KeyPathExpr *keyPath) {
bool diagnosed = false;
// check the components of the keypath.
for (const auto &component : keyPath->getComponents()) {
// The decl referred to by the path component cannot be within an actor.
if (component.hasDeclRef()) {
auto declRef = component.getDeclRef();
auto decl = declRef.getDecl();
auto isolation = getActorIsolationForReference(
decl, getDeclContext());
switch (isolation) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
break;
case ActorIsolation::Erased:
llvm_unreachable("component cannot have erased isolation");
case ActorIsolation::GlobalActor: {
auto result = ActorReferenceResult::forReference(
declRef, component.getLoc(), getDeclContext(),
kindOfUsage(decl, keyPath));
if (result == ActorReferenceResult::SameConcurrencyDomain)
break;
// An isolated key-path component requires being formed in the same
// isolation domain. Record the required isolation here if we're
// computing the isolation of a stored property initializer.
if (refineRequiredIsolation(isolation))
break;
LLVM_FALLTHROUGH;
}
case ActorIsolation::ActorInstance: {
ActorReferenceResult::Options options = std::nullopt;
if (isAccessibleAcrossActors(decl, isolation, getDeclContext(),
options)) {
break;
}
bool downgrade = isolation.isGlobalActor() ||
options.contains(
ActorReferenceResult::Flags::Preconcurrency);
ctx.Diags.diagnose(
component.getLoc(), diag::actor_isolated_keypath_component,
isolation, decl)
.warnUntilSwiftVersionIf(downgrade, 6);
diagnosed = !downgrade;
break;
}
}
}
// With `InferSendableFromCaptures` feature enabled the solver is
// responsible for inferring `& Sendable` for sendable key paths.
if (!ctx.LangOpts.hasFeature(Feature::InferSendableFromCaptures)) {
// Captured values in a path component must conform to Sendable.
// These captured values appear in Subscript, such as \Type.dict[k]
// where k is a captured dictionary key.
if (auto *args = component.getSubscriptArgs()) {
for (auto arg : *args) {
auto type = getType(arg.getExpr());
if (type && shouldDiagnoseExistingDataRaces(getDeclContext()) &&
diagnoseNonSendableTypes(type, getDeclContext(),
/*inDerivedConformance*/Type(),
component.getLoc(),
diag::non_sendable_keypath_capture))
diagnosed = true;
}
}
}
}
return diagnosed;
}
/// Check a reference to the given declaration.
///
/// \param base For a reference to a member, the base expression. May be
/// nullptr for non-member referenced.
///
/// \returns true if the reference is invalid, in which case a diagnostic
/// has already been emitted.
bool checkReference(
Expr *base, ConcreteDeclRef declRef, SourceLoc loc,
std::optional<PartialApplyThunkInfo> partialApply = std::nullopt,
Expr *context = nullptr) {
if (!declRef)
return false;
auto decl = declRef.getDecl();
// If this declaration is a callee from the enclosing application,
// it's already been checked via the call.
if (auto *apply = getImmediateApply()) {
auto immediateCallee =
apply->getCalledValue(/*skipFunctionConversions=*/true);
if (decl == immediateCallee)
return false;
}
std::optional<ReferencedActor> isolatedActor;
if (base)
isolatedActor.emplace(getIsolatedActor(base));
auto result = ActorReferenceResult::forReference(
declRef, loc, getDeclContext(), kindOfUsage(decl, context),
isolatedActor, std::nullopt, std::nullopt, getClosureActorIsolation);
switch (result) {
case ActorReferenceResult::SameConcurrencyDomain:
return diagnoseReferenceToUnsafeGlobal(decl, loc);
case ActorReferenceResult::ExitsActorToNonisolated:
if (diagnoseReferenceToUnsafeGlobal(decl, loc))
return true;
return diagnoseNonSendableTypesInReference(
base, declRef, getDeclContext(), loc,
SendableCheckReason::ExitingActor,
result.isolation,
// Function reference sendability can only cross isolation
// boundaries when they're passed as an argument or called,
// and their Sendability depends only on captures; do not
// check the parameter or result types here.
FunctionCheckOptions());
case ActorReferenceResult::EntersActor:
// Handle all of the checking below.
break;
}
// A partial application of a global-actor-isolated member is always
// okay, because the global actor is part of the resulting function
// type.
if (partialApply && result.isolation.isGlobalActor())
return false;
// A call to a global-actor-isolated function, or a function with an
// isolated parameter, is diagnosed elsewhere.
if (!partialApply &&
(result.isolation.isGlobalActor() ||
(result.isolation == ActorIsolation::ActorInstance &&
result.isolation.getActorInstanceParameter() > 0)) &&
isa<AbstractFunctionDecl>(decl))
return false;
// An escaping partial application of something that is part of
// the actor's isolated state is never permitted.
if (partialApply && partialApply->isEscaping && !isAsyncDecl(declRef)) {
ctx.Diags.diagnose(loc, diag::actor_isolated_partial_apply, decl);
return true;
}
// If we do not need any async/throws/distributed checks, just perform
// Sendable checking and we're done.
if (!result.options) {
return diagnoseNonSendableTypesInReference(
base, declRef, getDeclContext(), loc,
SendableCheckReason::CrossActor);
}
// Some combination of implicit async/throws/distributed is required.
bool isDistributed = result.options.contains(
ActorReferenceResult::Flags::Distributed);
// Determine the actor hop.
auto implicitAsyncResult = tryMarkImplicitlyAsync(
loc, declRef, context, result.isolation, isDistributed);
switch (implicitAsyncResult) {
case AsyncMarkingResult::FoundAsync:
return diagnoseNonSendableTypesInReference(
base, declRef, getDeclContext(), loc,
SendableCheckReason::SynchronousAsAsync);
case AsyncMarkingResult::NotDistributed:
// Failed, but diagnostics have already been emitted.
return true;
case AsyncMarkingResult::SyncContext:
case AsyncMarkingResult::NotFound:
// If we found an implicitly async reference in a sync
// context and we're computing the required isolation for
// an expression, the calling context requires the isolation
// of the reference.
if (refineRequiredIsolation(result.isolation)) {
return false;
}
// Complain about access outside of the isolation domain.
auto useKind = static_cast<unsigned>(
kindOfUsage(decl, context).value_or(VarRefUseEnv::Read));
ReferencedActor::Kind refKind;
Type refGlobalActor;
if (isolatedActor) {
refKind = isolatedActor->kind;
refGlobalActor = isolatedActor->globalActor;
} else {
auto contextIsolation = getInnermostIsolatedContext(
getDeclContext(), getClosureActorIsolation);
switch (contextIsolation) {
case ActorIsolation::ActorInstance:
refKind = ReferencedActor::Isolated;
break;
case ActorIsolation::Erased:
llvm_unreachable("context cannot have erased isolation");
case ActorIsolation::GlobalActor:
refGlobalActor = contextIsolation.getGlobalActor();
refKind = isMainActor(refGlobalActor)
? ReferencedActor::MainActor
: ReferencedActor::GlobalActor;
break;
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
refKind = ReferencedActor::NonIsolatedContext;
break;
}
}
// Does the reference originate from a @preconcurrency context?
bool preconcurrencyContext =
result.options.contains(ActorReferenceResult::Flags::Preconcurrency);
Type derivedConformanceType;
DeclName requirementName;
if (loc.isInvalid()) {
auto *decl = getDeclContext()->getAsDecl();
if (decl && decl->isImplicit()) {
auto *parentDC = decl->getDeclContext();
loc = parentDC->getAsDecl()->getLoc();
if (auto *implements = decl->getAttrs().getAttribute<ImplementsAttr>()) {
derivedConformanceType =
implements->getProtocol(parentDC)->getDeclaredInterfaceType();
requirementName = implements->getMemberName();
}
}
}
if (ctx.LangOpts.hasFeature(Feature::GroupActorErrors)) {
IsolationError mismatch = IsolationError(loc,
preconcurrencyContext,
Diagnostic(diag::actor_isolated_non_self_reference,
decl, useKind, refKind + 1, refGlobalActor,
result.isolation));
auto iter = refErrors.find(std::make_pair(refKind,result.isolation));
if (iter != refErrors.end()) {
iter->second.push_back(mismatch);
} else {
DiagnosticList list;
list.push_back(mismatch);
auto keyPair = std::make_pair(refKind,result.isolation);
refErrors.insert(std::make_pair(keyPair, list));
}
} else {
ctx.Diags.diagnose(
loc, diag::actor_isolated_non_self_reference,
decl, useKind,
refKind + 1, refGlobalActor,
result.isolation)
.warnUntilSwiftVersionIf(preconcurrencyContext, 6);
if (derivedConformanceType) {
auto *decl = dyn_cast<ValueDecl>(getDeclContext()->getAsDecl());
ctx.Diags.diagnose(loc, diag::in_derived_witness,
decl->getDescriptiveKind(),
requirementName,
derivedConformanceType);
}
noteIsolatedActorMember(decl, context);
if (result.isolation.isGlobalActor()) {
missingGlobalActorOnContext(
const_cast<DeclContext *>(getDeclContext()),
result.isolation.getGlobalActor(), DiagnosticBehavior::Note);
}
}
return true;
}
}
// Attempt to resolve the global actor type of a closure.
Type resolveGlobalActorType(ClosureExpr *closure) {
// Check whether the closure's type has a global actor already.
if (Type closureType = getType(closure)) {
if (auto closureFnType = closureType->getAs<FunctionType>()) {
if (Type globalActor = closureFnType->getGlobalActor())
return globalActor;
}
}
// Look for an explicit attribute.
return getExplicitGlobalActor(closure);
}
public:
/// Determine the isolation of a particular closure.
///
/// This function assumes that enclosing closures have already had their
/// isolation checked.
ActorIsolation determineClosureIsolation(
AbstractClosureExpr *closure) {
bool preconcurrency = false;
if (auto explicitClosure = dyn_cast<ClosureExpr>(closure)) {
preconcurrency = explicitClosure->isIsolatedByPreconcurrency();
// If the closure specifies a global actor, use it.
if (Type globalActor = resolveGlobalActorType(explicitClosure))
return ActorIsolation::forGlobalActor(globalActor)
.withPreconcurrency(preconcurrency);
if (auto *attr =
explicitClosure->getAttrs().getAttribute<NonisolatedAttr>();
attr && ctx.LangOpts.hasFeature(Feature::ClosureIsolation)) {
return ActorIsolation::forNonisolated(attr->isUnsafe())
.withPreconcurrency(preconcurrency);
}
}
// If a closure has an isolated parameter, it is isolated to that
// parameter.
for (auto param : *closure->getParameters()) {
if (param->isIsolated())
return ActorIsolation::forActorInstanceCapture(param)
.withPreconcurrency(preconcurrency);
}
// If we have a closure that acts as an isolation inference boundary, then
// we return that it is non-isolated.
//
// NOTE: Since we already checked for global actor isolated things, we
// know that all Sendable closures must be nonisolated. That is why it is
// safe to rely on this path to handle Sendable closures.
if (isIsolationInferenceBoundaryClosure(
closure, true /*is for closure isolation*/))
return ActorIsolation::forNonisolated(/*unsafe=*/false)
.withPreconcurrency(preconcurrency);
// A non-Sendable closure gets its isolation from its context.
auto parentIsolation = getActorIsolationOfContext(
closure->getParent(), getClosureActorIsolation);
preconcurrency |= parentIsolation.preconcurrency();
// We must have parent isolation determined to get here.
switch (parentIsolation) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
return ActorIsolation::forNonisolated(parentIsolation ==
ActorIsolation::NonisolatedUnsafe)
.withPreconcurrency(preconcurrency);
case ActorIsolation::Erased:
llvm_unreachable("context cannot have erased isolation");
case ActorIsolation::GlobalActor: {
Type globalActor = closure->mapTypeIntoContext(
parentIsolation.getGlobalActor()->mapTypeOutOfContext());
return ActorIsolation::forGlobalActor(globalActor)
.withPreconcurrency(preconcurrency);
}
case ActorIsolation::ActorInstance: {
if (auto param = closure->getCaptureInfo().getIsolatedParamCapture())
return ActorIsolation::forActorInstanceCapture(param)
.withPreconcurrency(preconcurrency);
return ActorIsolation::forNonisolated(/*unsafe=*/false)
.withPreconcurrency(preconcurrency);
}
}
}
};
}
bool ActorIsolationChecker::mayExecuteConcurrentlyWith(
const DeclContext *useContext, const DeclContext *defContext) {
// Fast path for when the use and definition contexts are the same.
if (useContext == defContext)
return false;
bool isolatedStateMayEscape = false;
auto useIsolation = getActorIsolationOfContext(
const_cast<DeclContext *>(useContext), getClosureActorIsolation);
if (useIsolation.isActorIsolated()) {
auto defIsolation = getActorIsolationOfContext(
const_cast<DeclContext *>(defContext), getClosureActorIsolation);
// If both contexts are isolated to the same actor, then they will not
// execute concurrently.
if (useIsolation == defIsolation)
return false;
auto &ctx = useContext->getASTContext();
bool regionIsolationEnabled =
ctx.LangOpts.hasFeature(Feature::RegionBasedIsolation);
// Globally-isolated closures may never be executed concurrently.
if (ctx.LangOpts.hasFeature(Feature::GlobalActorIsolatedTypesUsability) &&
regionIsolationEnabled && useIsolation.isGlobalActor())
return false;
// If the local function is not Sendable, its isolation differs
// from that of the context, and both contexts are actor isolated,
// then capturing non-Sendable values allows the closure to stash
// those values into actor isolated state. The original context
// may also stash those values into isolated state, enabling concurrent
// access later on.
isolatedStateMayEscape =
(!regionIsolationEnabled &&
useIsolation.isActorIsolated() && defIsolation.isActorIsolated());
}
// Walk the context chain from the use to the definition.
while (useContext != defContext) {
// If we find a concurrent closure... it can be run concurrently.
if (auto closure = dyn_cast<AbstractClosureExpr>(useContext)) {
if (isSendableClosure(closure, /*forActorIsolation=*/false))
return true;
if (isolatedStateMayEscape)
return true;
}
if (auto func = dyn_cast<FuncDecl>(useContext)) {
if (func->isLocalCapture()) {
// If the function is @Sendable... it can be run concurrently.
if (func->isSendable())
return true;
if (isolatedStateMayEscape)
return true;
}
}
// If we hit a module-scope or type context context, it's not
// concurrent.
useContext = useContext->getParent();
if (useContext->isModuleScopeContext() || useContext->isTypeContext())
return false;
}
// We hit the same context, so it won't execute concurrently.
return false;
}
void swift::checkTopLevelActorIsolation(TopLevelCodeDecl *decl) {
ActorIsolationChecker checker(decl);
if (auto *body = decl->getBody())
body->walk(checker);
}
void swift::checkFunctionActorIsolation(AbstractFunctionDecl *decl) {
// Disable this check for @LLDBDebuggerFunction functions.
if (decl->getAttrs().hasAttribute<LLDBDebuggerFunctionAttr>())
return;
auto &ctx = decl->getASTContext();
ActorIsolationChecker checker(decl);
if (auto body = decl->getBody()) {
body->walk(checker);
if(ctx.LangOpts.hasFeature(Feature::GroupActorErrors)){ checker.diagnoseIsolationErrors(); }
}
if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
if (auto superInit = ctor->getSuperInitCall())
superInit->walk(checker);
}
if (decl->getAttrs().hasAttribute<DistributedActorAttr>()) {
if (auto func = dyn_cast<FuncDecl>(decl)) {
checkDistributedFunction(func);
}
}
}
void swift::checkEnumElementActorIsolation(
EnumElementDecl *element, Expr *expr) {
ActorIsolationChecker checker(element);
expr->walk(checker);
}
void swift::checkPropertyWrapperActorIsolation(
VarDecl *wrappedVar, Expr *expr) {
ActorIsolationChecker checker(wrappedVar->getDeclContext());
expr->walk(checker);
}
ActorIsolation swift::determineClosureActorIsolation(
AbstractClosureExpr *closure, llvm::function_ref<Type(Expr *)> getType,
llvm::function_ref<ActorIsolation(AbstractClosureExpr *)>
getClosureActorIsolation) {
ActorIsolationChecker checker(closure->getParent(), getType,
getClosureActorIsolation);
return checker.determineClosureIsolation(closure);
}
/// Determine whethere there is an explicit isolation attribute
/// of any kind.
static bool hasExplicitIsolationAttribute(const Decl *decl) {
if (auto nonisolatedAttr =
decl->getAttrs().getAttribute<NonisolatedAttr>()) {
if (!nonisolatedAttr->isImplicit())
return true;
}
if (auto globalActorAttr = decl->getGlobalActorAttr()) {
if (!globalActorAttr->first->isImplicit())
return true;
}
return false;
}
/// Determine actor isolation solely from attributes.
///
/// \returns the actor isolation determined from attributes alone (with no
/// inference rules). Returns \c None if there were no attributes on this
/// declaration.
static std::optional<ActorIsolation>
getIsolationFromAttributes(const Decl *decl, bool shouldDiagnose = true,
bool onlyExplicit = false) {
// Look up attributes on the declaration that can affect its actor isolation.
// If any of them are present, use that attribute.
auto nonisolatedAttr = decl->getAttrs().getAttribute<NonisolatedAttr>();
auto globalActorAttr = decl->getGlobalActorAttr();
// Remove implicit attributes if we only care about explicit ones.
if (onlyExplicit) {
if (nonisolatedAttr && nonisolatedAttr->isImplicit())
nonisolatedAttr = nullptr;
if (globalActorAttr && globalActorAttr->first->isImplicit())
globalActorAttr = std::nullopt;
}
unsigned numIsolationAttrs =
(nonisolatedAttr ? 1 : 0) + (globalActorAttr ? 1 : 0);
if (numIsolationAttrs == 0)
return std::nullopt;
// Only one such attribute is valid, but we only actually care of one of
// them is a global actor.
if (numIsolationAttrs > 1 && globalActorAttr && shouldDiagnose) {
decl->diagnose(diag::actor_isolation_multiple_attr, decl,
nonisolatedAttr->getAttrName(),
globalActorAttr->second->getName().str())
.highlight(nonisolatedAttr->getRangeWithAt())
.highlight(globalActorAttr->first->getRangeWithAt());
}
// If the declaration is explicitly marked 'nonisolated', report it as
// independent.
if (nonisolatedAttr) {
return ActorIsolation::forNonisolated(nonisolatedAttr->isUnsafe());
}
// If the declaration is marked with a global actor, report it as being
// part of that global actor.
if (globalActorAttr) {
ASTContext &ctx = decl->getASTContext();
auto dc = decl->getInnermostDeclContext();
Type globalActorType = evaluateOrDefault(
ctx.evaluator,
CustomAttrTypeRequest{
globalActorAttr->first, dc, CustomAttrTypeKind::GlobalActor},
Type());
if (!globalActorType || globalActorType->hasError())
return ActorIsolation::forUnspecified();
// Handle @<global attribute type>(unsafe).
auto *attr = globalActorAttr->first;
bool isUnsafe = attr->isArgUnsafe();
if (attr->hasArgs()) {
if (isUnsafe) {
SourceFile *file = decl->getDeclContext()->getParentSourceFile();
bool inSwiftinterface =
file && file->Kind == SourceFileKind::Interface;
ctx.Diags.diagnose(
attr->getLocation(),
diag::unsafe_global_actor)
.fixItRemove(attr->getArgs()->getSourceRange())
.fixItInsert(attr->getLocation(), "@preconcurrency ")
.warnUntilSwiftVersion(6)
.limitBehaviorIf(inSwiftinterface, DiagnosticBehavior::Ignore);
} else {
ctx.Diags.diagnose(
attr->getLocation(),
diag::global_actor_arg, globalActorType)
.fixItRemove(attr->getArgs()->getSourceRange());
}
}
return ActorIsolation::forGlobalActor(
globalActorType->mapTypeOutOfContext())
.withPreconcurrency(decl->preconcurrency() || isUnsafe);
}
llvm_unreachable("Forgot about an attribute?");
}
/// Infer isolation from witnessed protocol requirements.
static std::optional<ActorIsolation>
getIsolationFromWitnessedRequirements(ValueDecl *value) {
// Associated types cannot have isolation, so there's no such inference for
// type witnesses.
if (isa<TypeDecl>(value))
return std::nullopt;
auto dc = value->getDeclContext();
auto idc = dyn_cast_or_null<IterableDeclContext>(dc->getAsDecl());
if (!idc)
return std::nullopt;
if (dc->getSelfProtocolDecl())
return std::nullopt;
// Walk through each of the conformances in this context, collecting any
// requirements that have actor isolation.
auto conformances = idc->getLocalConformances( // note this
ConformanceLookupKind::NonStructural);
using IsolatedRequirement =
std::tuple<ProtocolConformance *, ActorIsolation, ValueDecl *>;
SmallVector<IsolatedRequirement, 2> isolatedRequirements;
for (auto conformance : conformances) {
auto protocol = conformance->getProtocol();
for (auto found : protocol->lookupDirect(value->getName())) {
if (!isa<ProtocolDecl>(found->getDeclContext()))
continue;
auto requirement = dyn_cast<ValueDecl>(found);
if (!requirement || isa<TypeDecl>(requirement))
continue;
auto requirementIsolation = getActorIsolation(requirement);
switch (requirementIsolation) {
case ActorIsolation::ActorInstance:
case ActorIsolation::Unspecified:
continue;
case ActorIsolation::Erased:
llvm_unreachable("requirement cannot have erased isolation");
case ActorIsolation::GlobalActor:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
break;
}
auto witness = conformance->getWitnessDecl(requirement);
if (witness != value)
continue;
isolatedRequirements.push_back(
IsolatedRequirement{conformance, requirementIsolation, requirement});
}
}
// Filter out duplicate actors.
SmallPtrSet<CanType, 2> globalActorTypes;
bool sawActorIndependent = false;
isolatedRequirements.erase(
std::remove_if(isolatedRequirements.begin(), isolatedRequirements.end(),
[&](IsolatedRequirement &isolated) {
auto isolation = std::get<1>(isolated);
switch (isolation) {
case ActorIsolation::ActorInstance:
llvm_unreachable("protocol requirements cannot be actor instances");
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
// We only need one nonisolated.
if (sawActorIndependent)
return true;
sawActorIndependent = true;
return false;
case ActorIsolation::Erased:
llvm_unreachable("requirements cannot have erased isolation");
case ActorIsolation::Unspecified:
return true;
case ActorIsolation::GlobalActor: {
// Substitute into the global actor type.
auto conformance = std::get<0>(isolated);
auto requirementSubs = SubstitutionMap::getProtocolSubstitutions(
conformance->getProtocol(), dc->getSelfTypeInContext(),
ProtocolConformanceRef(conformance));
Type globalActor = isolation.getGlobalActor().subst(requirementSubs);
if (!globalActorTypes.insert(globalActor->getCanonicalType()).second)
return true;
// Update the global actor type, now that we've done this substitution.
std::get<1>(isolated) = ActorIsolation::forGlobalActor(globalActor)
.withPreconcurrency(isolation.preconcurrency());
return false;
}
}
}),
isolatedRequirements.end());
if (isolatedRequirements.size() != 1)
return std::nullopt;
return std::get<1>(isolatedRequirements.front());
}
/// Compute the isolation of a nominal type from the conformances that
/// are directly specified on the type.
static std::optional<ActorIsolation>
getIsolationFromConformances(NominalTypeDecl *nominal) {
auto &ctx = nominal->getASTContext();
if (isa<ProtocolDecl>(nominal))
return std::nullopt;
std::optional<ActorIsolation> foundIsolation;
for (auto conformance :
nominal->getLocalConformances(ConformanceLookupKind::NonStructural)) {
// Don't include inherited conformances. If a conformance is inherited
// from a superclass, the isolation of the subclass should be inferred
// from the superclass, which is done directly in ActorIsolationRequest.
// If the superclass has opted out of global actor inference, such as
// by conforming to the protocol in an extension, then the subclass should
// not infer isolation from the protocol.
//
// Gate this change behind an upcoming feature flag; isolation inference
// changes can break source in language modes < 6.
if (conformance->getKind() == ProtocolConformanceKind::Inherited &&
ctx.LangOpts.hasFeature(Feature::GlobalActorIsolatedTypesUsability)) {
continue;
}
auto *proto = conformance->getProtocol();
switch (auto protoIsolation = getActorIsolation(proto)) {
case ActorIsolation::ActorInstance:
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
break;
case ActorIsolation::Erased:
llvm_unreachable("protocol cannot have erased isolation");
case ActorIsolation::GlobalActor:
if (!foundIsolation) {
foundIsolation = protoIsolation;
continue;
}
if (*foundIsolation != protoIsolation)
return std::nullopt;
break;
}
}
return foundIsolation;
}
/// Compute the isolation of a protocol
static std::optional<ActorIsolation>
getIsolationFromInheritedProtocols(ProtocolDecl *protocol) {
std::optional<ActorIsolation> foundIsolation;
bool conflict = false;
auto inferIsolation = [&](ValueDecl *decl) {
switch (auto protoIsolation = getActorIsolation(decl)) {
case ActorIsolation::ActorInstance:
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
return;
case ActorIsolation::Erased:
llvm_unreachable("protocol cannot have erased isolation");
case ActorIsolation::GlobalActor:
if (!foundIsolation) {
foundIsolation = protoIsolation;
return;
}
if (*foundIsolation != protoIsolation)
conflict = true;
return;
}
};
for (auto inherited : protocol->getInheritedProtocols()) {
inferIsolation(inherited);
}
if (auto *superclass = protocol->getSuperclassDecl()) {
inferIsolation(superclass);
}
if (conflict)
return std::nullopt;
return foundIsolation;
}
/// Compute the isolation of a nominal type from the property wrappers on
/// any stored properties.
static std::optional<ActorIsolation>
getIsolationFromWrappers(NominalTypeDecl *nominal) {
if (!isa<StructDecl>(nominal) && !isa<ClassDecl>(nominal))
return std::nullopt;
if (!nominal->getParentSourceFile())
return std::nullopt;
ASTContext &ctx = nominal->getASTContext();
if (ctx.LangOpts.hasFeature(Feature::DisableOutwardActorInference)) {
// In Swift 6, we no longer infer isolation of a nominal type
// based on the property wrappers used in its stored properties
return std::nullopt;
}
std::optional<ActorIsolation> foundIsolation;
for (auto member : nominal->getMembers()) {
auto var = dyn_cast<VarDecl>(member);
if (!var || !var->isInstanceMember())
continue;
auto info = var->getAttachedPropertyWrapperTypeInfo(0);
if (!info)
continue;
auto isolation = getActorIsolation(info.valueVar);
// Inconsistent wrappedValue/projectedValue isolation disables inference.
if (info.projectedValueVar &&
getActorIsolation(info.projectedValueVar) != isolation)
continue;
switch (isolation) {
case ActorIsolation::ActorInstance:
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
break;
case ActorIsolation::Erased:
llvm_unreachable("variable cannot have erased isolation");
case ActorIsolation::GlobalActor:
if (!foundIsolation) {
foundIsolation = isolation;
continue;
}
if (*foundIsolation != isolation)
return std::nullopt;
break;
}
}
return foundIsolation;
}
namespace {
/// Describes how actor isolation is propagated to a member, if at all.
enum class MemberIsolationPropagation {
GlobalActor,
AnyIsolation
};
}
/// Determine how the given member can receive its isolation from its type
/// context.
static std::optional<MemberIsolationPropagation>
getMemberIsolationPropagation(const ValueDecl *value) {
if (!value->getDeclContext()->isTypeContext())
return std::nullopt;
switch (value->getKind()) {
case DeclKind::Import:
case DeclKind::Extension:
case DeclKind::TopLevelCode:
case DeclKind::InfixOperator:
case DeclKind::PrefixOperator:
case DeclKind::PostfixOperator:
case DeclKind::IfConfig:
case DeclKind::PoundDiagnostic:
case DeclKind::PrecedenceGroup:
case DeclKind::Missing:
case DeclKind::MissingMember:
case DeclKind::Class:
case DeclKind::Enum:
case DeclKind::Protocol:
case DeclKind::Struct:
case DeclKind::TypeAlias:
case DeclKind::GenericTypeParam:
case DeclKind::AssociatedType:
case DeclKind::OpaqueType:
case DeclKind::Param:
case DeclKind::Module:
case DeclKind::Destructor:
case DeclKind::EnumCase:
case DeclKind::EnumElement:
case DeclKind::Macro:
case DeclKind::MacroExpansion:
return std::nullopt;
case DeclKind::PatternBinding:
return MemberIsolationPropagation::GlobalActor;
case DeclKind::Constructor:
return MemberIsolationPropagation::AnyIsolation;
case DeclKind::Func:
case DeclKind::Accessor:
case DeclKind::Subscript:
case DeclKind::Var:
return value->isInstanceMember() ? MemberIsolationPropagation::AnyIsolation
: MemberIsolationPropagation::GlobalActor;
case DeclKind::BuiltinTuple:
llvm_unreachable("BuiltinTupleDecl should not show up here");
}
}
/// Given a property, determine the isolation when it part of a wrapped
/// property.
static ActorIsolation getActorIsolationFromWrappedProperty(VarDecl *var) {
// If this is a variable with a property wrapper, infer from the property
// wrapper's wrappedValue.
if (auto wrapperInfo = var->getAttachedPropertyWrapperTypeInfo(0)) {
if (auto wrappedValue = wrapperInfo.valueVar) {
if (auto isolation = getActorIsolation(wrappedValue))
return isolation;
}
}
// If this is the backing storage for a property wrapper, infer from the
// type of the outermost property wrapper.
if (auto originalVar = var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Backing)) {
if (auto backingType =
originalVar->getPropertyWrapperBackingPropertyType()) {
if (auto backingNominal = backingType->getAnyNominal()) {
if (!isa<ClassDecl>(backingNominal) ||
!cast<ClassDecl>(backingNominal)->isActor()) {
if (auto isolation = getActorIsolation(backingNominal))
return isolation;
}
}
}
}
// If this is the projected property for a property wrapper, infer from
// the property wrapper's projectedValue.
if (auto originalVar = var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection)) {
if (auto wrapperInfo =
originalVar->getAttachedPropertyWrapperTypeInfo(0)) {
if (auto projectedValue = wrapperInfo.projectedValueVar) {
if (auto isolation = getActorIsolation(projectedValue))
return isolation;
}
}
}
return ActorIsolation::forUnspecified();
}
static std::optional<ActorIsolation>
getActorIsolationForMainFuncDecl(FuncDecl *fnDecl) {
// Ensure that the base type that this function is declared in has @main
// attribute
NominalTypeDecl *declContext =
dyn_cast<NominalTypeDecl>(fnDecl->getDeclContext());
if (ExtensionDecl *exDecl =
dyn_cast<ExtensionDecl>(fnDecl->getDeclContext())) {
declContext = exDecl->getExtendedNominal();
}
// We're not even in a nominal decl type, this can't be the main function decl
if (!declContext)
return {};
const bool isMainDeclContext =
declContext->getAttrs().hasAttribute<MainTypeAttr>(
/*allow invalid*/ true);
ASTContext &ctx = fnDecl->getASTContext();
const bool isMainMain = fnDecl->isMainTypeMainMethod();
const bool isMainInternalMain =
fnDecl->getBaseIdentifier() == ctx.getIdentifier("$main") &&
!fnDecl->isInstanceMember() &&
fnDecl->getResultInterfaceType()->isVoid() &&
fnDecl->getParameters()->size() == 0;
const bool isMainFunction =
isMainDeclContext && (isMainMain || isMainInternalMain);
const bool hasMainActor = !ctx.getMainActorType().isNull();
return isMainFunction && hasMainActor
? ActorIsolation::forGlobalActor(
ctx.getMainActorType()->mapTypeOutOfContext())
: std::optional<ActorIsolation>();
}
/// Check rules related to global actor attributes on a class declaration.
///
/// \returns true if an error occurred.
static bool checkClassGlobalActorIsolation(
ClassDecl *classDecl, ActorIsolation isolation) {
assert(isolation.isGlobalActor());
// A class can only be annotated with a global actor if it has no
// superclass, the superclass is annotated with the same global actor, or
// the superclass is NSObject. A subclass of a global-actor-annotated class
// must be isolated to the same global actor.
auto superclassDecl = classDecl->getSuperclassDecl();
if (!superclassDecl)
return false;
if (superclassDecl->isNSObject())
return false;
// Ignore actors outright. They'll be diagnosed later.
if (classDecl->isActor() || superclassDecl->isActor())
return false;
// Check the superclass's isolation.
bool downgradeToWarning = false;
auto superIsolation = getActorIsolation(superclassDecl);
switch (superIsolation) {
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe: {
return false;
}
case ActorIsolation::Erased:
llvm_unreachable("class cannot have erased isolation");
case ActorIsolation::ActorInstance:
// This is an error that will be diagnosed later. Ignore it here.
return false;
case ActorIsolation::GlobalActor: {
// If the global actors match, we're fine.
Type superclassGlobalActor = superIsolation.getGlobalActor();
auto module = classDecl->getParentModule();
SubstitutionMap subsMap = classDecl->getDeclaredInterfaceType()
->getSuperclassForDecl(superclassDecl)
->getContextSubstitutionMap(module, superclassDecl);
Type superclassGlobalActorInSub = superclassGlobalActor.subst(subsMap);
if (isolation.getGlobalActor()->isEqual(superclassGlobalActorInSub))
return false;
break;
}
}
// Complain about the mismatch.
classDecl->diagnose(diag::actor_isolation_superclass_mismatch, isolation,
classDecl, superIsolation, superclassDecl)
.warnUntilSwiftVersionIf(downgradeToWarning, 6);
return true;
}
namespace {
/// Describes the result of checking override isolation.
enum class OverrideIsolationResult {
/// The override is permitted.
Allowed,
/// The override is permitted, but requires a Sendable check.
Sendable,
/// The override is not permitted.
Disallowed,
};
}
/// Return the isolation of the declaration overridden by this declaration,
/// in the context of the
static ActorIsolation getOverriddenIsolationFor(ValueDecl *value) {
auto overridden = value->getOverriddenDecl();
assert(overridden && "Doesn't have an overridden declaration");
auto isolation = getActorIsolation(overridden);
if (!isolation.requiresSubstitution())
return isolation;
SubstitutionMap subs;
if (Type selfType = value->getDeclContext()->getSelfInterfaceType()) {
subs = selfType->getMemberSubstitutionMap(
value->getModuleContext(), overridden);
}
return isolation.subst(subs);
}
ConcreteDeclRef swift::getDeclRefInContext(ValueDecl *value) {
auto declContext = value->getInnermostDeclContext();
if (auto genericEnv = declContext->getGenericEnvironmentOfContext()) {
return ConcreteDeclRef(
value, genericEnv->getForwardingSubstitutionMap());
}
return ConcreteDeclRef(value);
}
static bool isNSObjectInit(ValueDecl *overridden) {
auto *classDecl = dyn_cast_or_null<ClassDecl>(
overridden->getDeclContext()->getSelfNominalTypeDecl());
if (!classDecl || !classDecl->isNSObject()) {
return false;
}
return isa<ConstructorDecl>(overridden);
}
/// Generally speaking, the isolation of the decl that overrides
/// must match the overridden decl. But there are a number of exceptions,
/// e.g., the decl that overrides can be nonisolated.
/// \param isolation the isolation of the overriding declaration.
static OverrideIsolationResult validOverrideIsolation(
ValueDecl *value, ActorIsolation isolation,
ValueDecl *overridden, ActorIsolation overriddenIsolation) {
ConcreteDeclRef valueRef = getDeclRefInContext(value);
auto declContext = value->getInnermostDeclContext();
auto &ctx = declContext->getASTContext();
auto refResult = ActorReferenceResult::forReference(
valueRef, SourceLoc(), declContext, std::nullopt, std::nullopt, isolation,
overriddenIsolation);
switch (refResult) {
case ActorReferenceResult::SameConcurrencyDomain:
return OverrideIsolationResult::Allowed;
case ActorReferenceResult::ExitsActorToNonisolated:
return OverrideIsolationResult::Sendable;
case ActorReferenceResult::EntersActor:
// It's okay to enter the actor when the overridden declaration is
// asynchronous (because it will do the switch) or is accessible from
// anywhere.
if (isAsyncDecl(overridden) ||
isAccessibleAcrossActors(
overridden, refResult.isolation, declContext)) {
return OverrideIsolationResult::Sendable;
}
// If the overridden declaration is from Objective-C with no actor
// annotation, don't allow overriding isolation in complete concurrency
// checking. Calls from outside the actor, via the nonisolated superclass
// method that is dynamically dispatched, will crash at runtime due to
// the dynamic isolation check in the @objc thunk.
//
// There's a narrow carve out for `NSObject.init()` because overriding
// this init of `@MainActor`-isolated type is difficult-to-impossible,
// especially if you need to call an initializer from an intermediate
// superclass that is also `@MainActor`-isolated. This won't admit a
// runtime data-race safety hole, because dynamic isolation checks will
// be inserted in the @objc thunks under `DynamicActorIsolation`, and
// direct calls will enforce `@MainActor` as usual.
if (isNSObjectInit(overridden) ||
(ctx.LangOpts.StrictConcurrencyLevel != StrictConcurrency::Complete &&
overridden->hasClangNode() && !overriddenIsolation)) {
return OverrideIsolationResult::Allowed;
}
return OverrideIsolationResult::Disallowed;
}
}
/// Retrieve the index of the first isolated parameter of the given
/// declaration, if there is one.
static std::optional<unsigned> getIsolatedParamIndex(ValueDecl *value) {
auto params = getParameterList(value);
if (!params)
return std::nullopt;
for (unsigned paramIdx : range(params->size())) {
auto param = params->get(paramIdx);
if (param->isIsolated())
return paramIdx;
}
return std::nullopt;
}
/// Verifies rules about `isolated` parameters for the given decl. There is more
/// checking about these in TypeChecker::checkParameterList.
///
/// This function is focused on rules that apply when it's a declaration with
/// an isolated parameter, rather than some generic parameter list in a
/// DeclContext.
///
/// This function assumes the value already contains an isolated parameter.
static void checkDeclWithIsolatedParameter(ValueDecl *value) {
// assume there is an isolated parameter.
assert(getIsolatedParamIndex(value));
// Suggest removing global-actor attributes written on it, as its ignored.
if (auto attr = value->getGlobalActorAttr()) {
if (!attr->first->isImplicit()) {
value->diagnose(diag::isolated_parameter_combined_global_actor_attr,
value->getDescriptiveKind())
.fixItRemove(attr->first->getRangeWithAt())
.warnUntilSwiftVersion(6);
}
}
// Suggest removing `nonisolated` as it is also ignored
if (auto attr = value->getAttrs().getAttribute<NonisolatedAttr>()) {
if (!attr->isImplicit()) {
value->diagnose(diag::isolated_parameter_combined_nonisolated,
value->getDescriptiveKind())
.fixItRemove(attr->getRangeWithAt())
.warnUntilSwiftVersion(6);
}
}
}
ActorIsolation ActorIsolationRequest::evaluate(
Evaluator &evaluator, ValueDecl *value) const {
auto &ctx = value->getASTContext();
// If this declaration has actor-isolated "self", it's isolated to that
// actor.
if (evaluateOrDefault(evaluator, HasIsolatedSelfRequest{value}, false)) {
auto actor = value->getDeclContext()->getSelfNominalTypeDecl();
assert(actor && "could not find the actor that 'self' is isolated to");
return ActorIsolation::forActorInstanceSelf(value);
}
// If this declaration has an isolated parameter, it's isolated to that
// parameter.
if (auto paramIdx = getIsolatedParamIndex(value)) {
checkDeclWithIsolatedParameter(value);
ParamDecl *param = getParameterList(value)->get(*paramIdx);
Type paramType = param->getDeclContext()->mapTypeIntoContext(
param->getInterfaceType());
Type actorType;
if (auto wrapped = paramType->getOptionalObjectType()) {
actorType = wrapped;
} else {
actorType = paramType;
}
if (auto actor = actorType->getAnyActor())
return ActorIsolation::forActorInstanceParameter(param, *paramIdx);
}
// Diagnose global state that is not either immutable plus Sendable or
// isolated to a global actor.
auto checkGlobalIsolation = [var = dyn_cast<VarDecl>(value)](
ActorIsolation isolation) {
// Diagnose only declarations in the same module.
//
// TODO: This should be factored out from ActorIsolationRequest into
// either ActorIsolationChecker or DeclChecker.
if (var && var->getLoc(/*SerializedOK*/false) &&
var->getASTContext().LangOpts.hasFeature(Feature::GlobalConcurrency) &&
!isolation.isGlobalActor() &&
(isolation != ActorIsolation::NonisolatedUnsafe)) {
auto *classDecl = var->getDeclContext()->getSelfClassDecl();
const bool isActorType = classDecl && classDecl->isAnyActor();
if (var->isGlobalStorage() && !isActorType) {
auto *diagVar = var;
if (auto *originalVar = var->getOriginalWrappedProperty()) {
diagVar = originalVar;
}
bool diagnosed = false;
if (var->isLet()) {
auto type = var->getInterfaceType();
diagnosed = diagnoseIfAnyNonSendableTypes(
type, SendableCheckContext(var->getDeclContext()),
/*inDerivedConformance=*/Type(), /*typeLoc=*/SourceLoc(),
/*diagnoseLoc=*/var->getLoc(),
diag::shared_immutable_state_decl, diagVar);
} else {
diagVar->diagnose(diag::shared_mutable_state_decl, diagVar)
.warnUntilSwiftVersion(6);
diagnosed = true;
}
// If we diagnosed this global, tack on notes to suggest potential
// courses of action.
if (diagnosed) {
if (!var->isLet()) {
auto diag = diagVar->diagnose(diag::shared_state_make_immutable,
diagVar);
SourceLoc fixItLoc = getFixItLocForVarToLet(diagVar);
if (fixItLoc.isValid()) {
diag.fixItReplace(fixItLoc, "let");
}
}
diagVar->diagnose(diag::shared_state_main_actor_node,
diagVar)
.fixItInsert(diagVar->getAttributeInsertionLoc(false),
"@MainActor ");
diagVar->diagnose(diag::shared_state_nonisolated_unsafe,
diagVar)
.fixItInsert(diagVar->getAttributeInsertionLoc(true),
"nonisolated(unsafe) ");
}
}
}
return isolation;
};
auto isolationFromAttr = getIsolationFromAttributes(value);
if (isolationFromAttr && isolationFromAttr->preconcurrency() &&
!value->getAttrs().hasAttribute<PreconcurrencyAttr>()) {
auto preconcurrency =
new (ctx) PreconcurrencyAttr(/*isImplicit*/true);
value->getAttrs().add(preconcurrency);
}
if (FuncDecl *fd = dyn_cast<FuncDecl>(value)) {
// Main.main() and Main.$main are implicitly MainActor-protected.
// Any other isolation is an error.
std::optional<ActorIsolation> mainIsolation =
getActorIsolationForMainFuncDecl(fd);
if (mainIsolation) {
if (isolationFromAttr && isolationFromAttr->isGlobalActor()) {
if (!areTypesEqual(isolationFromAttr->getGlobalActor(),
mainIsolation->getGlobalActor())) {
fd->getASTContext().Diags.diagnose(
fd->getLoc(), diag::main_function_must_be_mainActor);
}
}
return *mainIsolation;
}
}
// If this declaration has one of the actor isolation attributes, report
// that.
if (isolationFromAttr) {
// Classes with global actors have additional rules regarding inheritance.
if (isolationFromAttr->isGlobalActor()) {
if (auto classDecl = dyn_cast<ClassDecl>(value))
checkClassGlobalActorIsolation(classDecl, *isolationFromAttr);
}
return checkGlobalIsolation(*isolationFromAttr);
}
// Determine the default isolation for this declaration, which may still be
// overridden by other inference rules.
ActorIsolation defaultIsolation = ActorIsolation::forUnspecified();
if (auto func = dyn_cast<AbstractFunctionDecl>(value)) {
// A @Sendable function is assumed to be actor-independent.
if (func->isSendable()) {
defaultIsolation = ActorIsolation::forNonisolated(/*unsafe=*/false);
}
}
// When no other isolation applies, an actor's non-async init is independent
if (auto nominal = value->getDeclContext()->getSelfNominalTypeDecl())
if (nominal->isAnyActor())
if (auto ctor = dyn_cast<ConstructorDecl>(value))
if (!ctor->hasAsync())
defaultIsolation = ActorIsolation::forNonisolated(/*unsafe=*/false);
// Look for and remember the overridden declaration's isolation.
std::optional<ActorIsolation> overriddenIso;
ValueDecl *overriddenValue = value->getOverriddenDecl();
if (overriddenValue) {
// use the overridden decl's iso as the default isolation for this decl.
defaultIsolation = getOverriddenIsolationFor(value);
overriddenIso = defaultIsolation;
}
// Function used when returning an inferred isolation.
auto inferredIsolation = [&](ActorIsolation inferred,
bool onlyGlobal = false) {
// Invoke the body within checkGlobalIsolation to check the result.
return checkGlobalIsolation([&] {
// check if the inferred isolation is valid in the context of
// its overridden isolation.
if (overriddenValue) {
// if the inferred isolation is not valid, then carry-over the
// overridden declaration's isolation as this decl's inferred isolation.
switch (validOverrideIsolation(value, inferred, overriddenValue,
*overriddenIso)) {
case OverrideIsolationResult::Allowed:
case OverrideIsolationResult::Sendable:
break;
case OverrideIsolationResult::Disallowed:
if (overriddenValue->hasClangNode() &&
overriddenIso->isUnspecified()) {
inferred = overriddenIso->withPreconcurrency(true);
} else {
inferred = *overriddenIso;
}
break;
}
}
// Add an implicit attribute to capture the actor isolation that was
// inferred, so that (e.g.) it will be printed and serialized.
switch (inferred) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
// Stored properties cannot be non-isolated, so don't infer it.
if (auto var = dyn_cast<VarDecl>(value)) {
if (!var->isStatic() && var->hasStorage())
return ActorIsolation::forUnspecified().withPreconcurrency(
inferred.preconcurrency());
}
if (onlyGlobal) {
return ActorIsolation::forUnspecified().withPreconcurrency(
inferred.preconcurrency());
}
value->getAttrs().add(new (ctx) NonisolatedAttr(
inferred == ActorIsolation::NonisolatedUnsafe, /*implicit=*/true));
break;
case ActorIsolation::Erased:
llvm_unreachable("cannot infer erased isolation");
case ActorIsolation::GlobalActor: {
auto typeExpr =
TypeExpr::createImplicit(inferred.getGlobalActor(), ctx);
auto attr =
CustomAttr::create(ctx, SourceLoc(), typeExpr, /*implicit=*/true);
value->getAttrs().add(attr);
if (inferred.preconcurrency() &&
!value->getAttrs().hasAttribute<PreconcurrencyAttr>()) {
auto preconcurrency =
new (ctx) PreconcurrencyAttr(/*isImplicit*/true);
value->getAttrs().add(preconcurrency);
}
break;
}
case ActorIsolation::ActorInstance:
case ActorIsolation::Unspecified:
if (onlyGlobal)
return ActorIsolation::forUnspecified().withPreconcurrency(
inferred.preconcurrency());
// Nothing to do.
break;
}
return inferred;
}());
};
// If this is a local function, inherit the actor isolation from its
// context if it global or was captured.
if (auto func = dyn_cast<FuncDecl>(value)) {
if (func->isLocalCapture() && !func->isSendable()) {
switch (auto enclosingIsolation =
getActorIsolationOfContext(func->getDeclContext())) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
// Do nothing.
break;
case ActorIsolation::Erased:
llvm_unreachable("context cannot have erased isolation");
case ActorIsolation::ActorInstance:
if (auto param = func->getCaptureInfo().getIsolatedParamCapture())
return inferredIsolation(enclosingIsolation);
break;
case ActorIsolation::GlobalActor:
return inferredIsolation(enclosingIsolation);
}
}
}
// If this is an accessor, use the actor isolation of its storage
// declaration.
if (auto accessor = dyn_cast<AccessorDecl>(value)) {
return getActorIsolation(accessor->getStorage());
}
if (auto var = dyn_cast<VarDecl>(value)) {
auto &ctx = var->getASTContext();
if (!ctx.LangOpts.isConcurrencyModelTaskToThread() &&
var->isTopLevelGlobal() &&
(ctx.LangOpts.StrictConcurrencyLevel >=
StrictConcurrency::Complete ||
var->getDeclContext()->isAsyncContext())) {
if (Type mainActor = var->getASTContext().getMainActorType())
return inferredIsolation(
ActorIsolation::forGlobalActor(mainActor))
.withPreconcurrency(var->preconcurrency());
}
if (auto isolation = getActorIsolationFromWrappedProperty(var))
return inferredIsolation(isolation);
}
// If this is a dynamic replacement for another function, use the
// actor isolation of the function it replaces.
if (auto replacedDecl = value->getDynamicallyReplacedDecl()) {
if (auto isolation = getActorIsolation(replacedDecl))
return inferredIsolation(isolation);
}
if (shouldInferAttributeInContext(value->getDeclContext())) {
// If the declaration witnesses a protocol requirement that is isolated,
// use that.
if (auto witnessedIsolation = getIsolationFromWitnessedRequirements(value)) {
if (auto inferred = inferredIsolation(*witnessedIsolation))
return inferred;
}
// If the declaration is a class with a superclass that has specified
// isolation, use that.
if (auto classDecl = dyn_cast<ClassDecl>(value)) {
if (auto superclassDecl = classDecl->getSuperclassDecl()) {
auto superclassIsolation = getActorIsolation(superclassDecl);
if (!superclassIsolation.isUnspecified()) {
if (superclassIsolation.requiresSubstitution()) {
Type superclassType = classDecl->getSuperclass();
if (!superclassType)
return ActorIsolation::forUnspecified();
SubstitutionMap subs = superclassType->getMemberSubstitutionMap(
classDecl->getModuleContext(), classDecl);
superclassIsolation = superclassIsolation.subst(subs);
}
if (auto inferred = inferredIsolation(superclassIsolation))
return inferred;
}
}
}
if (auto nominal = dyn_cast<NominalTypeDecl>(value)) {
// If the declaration is a nominal type and any of the protocols to which
// it directly conforms is isolated to a global actor, use that.
if (auto conformanceIsolation = getIsolationFromConformances(nominal))
if (auto inferred = inferredIsolation(*conformanceIsolation))
return inferred;
// For a protocol, inherit isolation from the directly-inherited
// protocols.
if (ctx.LangOpts.hasFeature(Feature::GlobalActorIsolatedTypesUsability)) {
if (auto proto = dyn_cast<ProtocolDecl>(nominal)) {
if (auto protoIsolation = getIsolationFromInheritedProtocols(proto)) {
if (auto inferred = inferredIsolation(*protoIsolation))
return inferred;
}
}
}
// Before Swift 6: If the declaration is a nominal type and any property
// wrappers on its stored properties require isolation, use that.
if (auto wrapperIsolation = getIsolationFromWrappers(nominal)) {
if (auto inferred = inferredIsolation(*wrapperIsolation))
return inferred;
}
}
}
// Infer isolation for a member.
if (auto memberPropagation = getMemberIsolationPropagation(value)) {
// If were only allowed to propagate global actors, do so.
bool onlyGlobal =
*memberPropagation == MemberIsolationPropagation::GlobalActor;
// If the declaration is in an extension that has one of the isolation
// attributes, use that.
if (auto ext = dyn_cast<ExtensionDecl>(value->getDeclContext())) {
if (auto isolationFromAttr = getIsolationFromAttributes(ext)) {
return inferredIsolation(*isolationFromAttr, onlyGlobal);
}
}
// If the declaration is in a nominal type (or extension thereof) that
// has isolation, use that.
if (auto selfTypeDecl = value->getDeclContext()->getSelfNominalTypeDecl()) {
if (auto selfTypeIsolation = getActorIsolation(selfTypeDecl))
return inferredIsolation(selfTypeIsolation, onlyGlobal);
}
}
// @IBAction implies @MainActor(unsafe).
if (value->getAttrs().hasAttribute<IBActionAttr>()) {
ASTContext &ctx = value->getASTContext();
if (Type mainActor = ctx.getMainActorType()) {
return inferredIsolation(
ActorIsolation::forGlobalActor(mainActor)
.withPreconcurrency(true));
}
}
// Default isolation for this member.
return checkGlobalIsolation(defaultIsolation);
}
bool HasIsolatedSelfRequest::evaluate(
Evaluator &evaluator, ValueDecl *value) const {
// Only ever applies to members of actors.
auto dc = value->getDeclContext();
auto selfTypeDecl = dc->getSelfNominalTypeDecl();
if (!selfTypeDecl || !selfTypeDecl->isAnyActor())
return false;
// For accessors, consider the storage declaration.
if (auto accessor = dyn_cast<AccessorDecl>(value)) {
// distributed thunks are nonisolated, although the attached to storage
// will be 'distributed var' and therefore isolated to the distributed
// actor. Therefore, if we're a thunk, don't look at the storage for
// deciding about isolation of this function.
if (accessor->isDistributedThunk()) {
return false;
}
value = accessor->getStorage();
}
// If there is an isolated parameter, then "self" is not isolated.
if (getIsolatedParamIndex(value))
return false;
// Check whether this member can be isolated to an actor at all.
auto memberIsolation = getMemberIsolationPropagation(value);
if (!memberIsolation)
return false;
switch (*memberIsolation) {
case MemberIsolationPropagation::GlobalActor:
return false;
case MemberIsolationPropagation::AnyIsolation:
break;
}
// Check whether the default isolation was overridden by any attributes on
// this declaration.
if (getIsolationFromAttributes(value))
return false;
// ... or its extension context.
if (auto ext = dyn_cast<ExtensionDecl>(dc)) {
if (getIsolationFromAttributes(ext))
return false;
}
// If this is a variable, check for a property wrapper that alters its
// isolation.
if (auto var = dyn_cast<VarDecl>(value)) {
switch (auto isolation = getActorIsolationFromWrappedProperty(var)) {
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
break;
case ActorIsolation::GlobalActor:
return false;
case ActorIsolation::Erased:
llvm_unreachable("property cannot have erased isolation");
case ActorIsolation::ActorInstance:
if (isolation.getActor() != selfTypeDecl)
return false;
break;
}
}
if (auto ctor = dyn_cast<ConstructorDecl>(value)) {
// When no other isolation applies to an actor's constructor,
// then it is isolated only if it is async.
if (!ctor->hasAsync())
return false;
}
return true;
}
ActorIsolation
DefaultInitializerIsolation::evaluate(Evaluator &evaluator,
VarDecl *var) const {
if (var->isInvalid())
return ActorIsolation::forUnspecified();
Initializer *dc = nullptr;
Expr *initExpr = nullptr;
ActorIsolation enclosingIsolation;
if (auto *pbd = var->getParentPatternBinding()) {
if (!var->isParentInitialized())
return ActorIsolation::forUnspecified();
auto i = pbd->getPatternEntryIndexForVarDecl(var);
dc = cast<Initializer>(pbd->getInitContext(i));
initExpr = pbd->getCheckedAndContextualizedInit(i);
enclosingIsolation = getActorIsolation(var);
} else if (auto *param = dyn_cast<ParamDecl>(var)) {
// If this parameter corresponds to a stored property for a
// memberwise initializer, the default argument is the default
// initializer expression.
if (auto *property = param->getStoredProperty()) {
// FIXME: Force computation of property wrapper initializers.
if (auto *wrapped = property->getOriginalWrappedProperty())
(void)property->getPropertyWrapperInitializerInfo();
return property->getInitializerIsolation();
}
if (!param->hasDefaultExpr())
return ActorIsolation::forUnspecified();
dc = param->getDefaultArgumentInitContext();
initExpr = param->getTypeCheckedDefaultExpr();
enclosingIsolation =
getActorIsolationOfContext(param->getDeclContext());
}
if (!dc || !initExpr)
return ActorIsolation::forUnspecified();
// If the default argument has isolation, it must match the
// isolation of the decl context.
ActorIsolationChecker checker(dc);
auto requiredIsolation = checker.computeRequiredIsolation(initExpr);
if (requiredIsolation.isActorIsolated()) {
if (enclosingIsolation != requiredIsolation) {
var->diagnose(
diag::isolated_default_argument_context,
requiredIsolation, enclosingIsolation)
.warnUntilSwiftVersionIf(!isa<ParamDecl>(var), 6);
return ActorIsolation::forUnspecified();
}
}
return requiredIsolation;
}
void swift::checkOverrideActorIsolation(ValueDecl *value) {
if (isa<TypeDecl>(value))
return;
auto overridden = value->getOverriddenDecl();
if (!overridden)
return;
// Determine the actor isolation of the overriding function.
auto isolation = getActorIsolation(value);
// Determine the actor isolation of the overridden function.
auto overriddenIsolation = getOverriddenIsolationFor(value);
switch (validOverrideIsolation(
value, isolation, overridden, overriddenIsolation)) {
case OverrideIsolationResult::Allowed:
return;
case OverrideIsolationResult::Sendable:
// Check that the results of the overriding method are sendable
diagnoseNonSendableTypesInReference(
/*base=*/nullptr,
getDeclRefInContext(value), value->getInnermostDeclContext(),
value->getLoc(), SendableCheckReason::Override,
getActorIsolation(value), FunctionCheckKind::Results);
// Check that the parameters of the overridden method are sendable
diagnoseNonSendableTypesInReference(
/*base=*/nullptr,
getDeclRefInContext(overridden), overridden->getInnermostDeclContext(),
overridden->getLoc(), SendableCheckReason::Override,
getActorIsolation(value), FunctionCheckKind::Params,
value->getLoc());
return;
case OverrideIsolationResult::Disallowed:
// Diagnose below.
break;
}
// Isolation mismatch. Diagnose it.
DiagnosticBehavior behavior = DiagnosticBehavior::Unspecified;
if (overridden->hasClangNode() && !overriddenIsolation) {
behavior = SendableCheckContext(value->getInnermostDeclContext())
.defaultDiagnosticBehavior();
}
value->diagnose(
diag::actor_isolation_override_mismatch, isolation,
value, overriddenIsolation)
.limitBehaviorUntilSwiftVersion(behavior, 6);
overridden->diagnose(diag::overridden_here);
}
bool swift::contextRequiresStrictConcurrencyChecking(
const DeclContext *dc,
llvm::function_ref<Type(const AbstractClosureExpr *)> getType,
llvm::function_ref<bool(const ClosureExpr *)> isolatedByPreconcurrency) {
auto concurrencyLevel = dc->getASTContext().LangOpts.StrictConcurrencyLevel;
switch (concurrencyLevel) {
case StrictConcurrency::Complete:
return true;
case StrictConcurrency::Targeted:
case StrictConcurrency::Minimal:
// Check below to see if the context has adopted concurrency features.
break;
}
while (!dc->isModuleScopeContext()) {
if (auto closure = dyn_cast<AbstractClosureExpr>(dc)) {
// A closure with an explicit global actor, async, or Sendable
// uses concurrency features.
if (auto explicitClosure = dyn_cast<ClosureExpr>(closure)) {
if (getExplicitGlobalActor(const_cast<ClosureExpr *>(explicitClosure)))
return true;
// Don't take any more cues if this only got its type information by
// being provided to a `@preconcurrency` operation.
//
// FIXME: contextRequiresStrictConcurrencyChecking is called from
// within the constraint system, but closures are only set to be isolated
// by preconcurrency in solution application because it's dependent on
// overload resolution. The constraint system either needs to check its
// own state on the current path, or not make type inference decisions based
// on concurrency checking level.
if (isolatedByPreconcurrency(explicitClosure)) {
// If we're in minimal checking, preconcurrency always suppresses
// diagnostics. Targeted checking will still produce diagnostics if
// the outer context has adopted explicit concurrency features.
if (concurrencyLevel == StrictConcurrency::Minimal)
return false;
dc = dc->getParent();
continue;
}
if (auto type = getType(closure)) {
if (auto fnType = type->getAs<AnyFunctionType>())
if (fnType->isAsync() || fnType->isSendable())
return true;
}
}
// Async and @Sendable closures use concurrency features.
if (closure->isBodyAsync() || closure->isSendable())
return true;
} else if (auto decl = dc->getAsDecl()) {
// If any isolation attributes are present, we're using concurrency
// features.
if (hasExplicitIsolationAttribute(decl))
return true;
// Extensions of explicitly isolated types are using concurrency
// features.
if (auto *extension = dyn_cast<ExtensionDecl>(decl)) {
auto *nominal = extension->getExtendedNominal();
if (nominal && hasExplicitIsolationAttribute(nominal) &&
!getActorIsolation(nominal).preconcurrency())
return true;
}
if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
// Async and concurrent functions use concurrency features.
if (func->hasAsync() || func->isSendable())
return true;
// If we're in an accessor declaration, also check the storage
// declaration.
if (auto accessor = dyn_cast<AccessorDecl>(decl)) {
if (hasExplicitIsolationAttribute(accessor->getStorage()))
return true;
}
}
}
// If we're in an actor, we're using concurrency features.
if (auto nominal = dc->getSelfNominalTypeDecl()) {
if (nominal->isActor())
return true;
}
// Keep looking.
dc = dc->getParent();
}
return false;
}
/// Check the instance storage of the given nominal type to verify whether
/// it is comprised only of Sendable instance storage.
static bool checkSendableInstanceStorage(
NominalTypeDecl *nominal, DeclContext *dc, SendableCheck check) {
// Raw storage is assumed not to be sendable.
if (auto sd = dyn_cast<StructDecl>(nominal)) {
if (auto rawLayout = sd->getAttrs().getAttribute<RawLayoutAttr>()) {
auto behavior = SendableCheckContext(
dc, check).defaultDiagnosticBehavior();
if (!isImplicitSendableCheck(check)
&& SendableCheckContext(dc, check)
.defaultDiagnosticBehavior() != DiagnosticBehavior::Ignore) {
sd->diagnose(diag::sendable_raw_storage, sd->getName())
.limitBehaviorUntilSwiftVersion(behavior, 6);
}
return true;
}
}
// Stored properties of structs and classes must have
// Sendable-conforming types.
class Visitor: public StorageVisitor {
public:
bool invalid = false;
NominalTypeDecl *nominal;
DeclContext *dc;
SendableCheck check;
const LangOptions &langOpts;
Visitor(NominalTypeDecl *nominal, DeclContext *dc, SendableCheck check)
: StorageVisitor(), nominal(nominal), dc(dc), check(check),
langOpts(nominal->getASTContext().LangOpts) { }
/// Handle a stored property.
bool operator()(VarDecl *property, Type propertyType) override {
ActorIsolation isolation = getActorIsolation(property);
// 'nonisolated' properties are always okay in 'Sendable' types because
// they can be accessed from anywhere. Note that 'nonisolated' without
// '(unsafe)' can only be applied to immutable, 'Sendable' properties.
if (isolation.isNonisolated())
return false;
// Classes with mutable properties are Sendable if property is
// actor-isolated
if (isa<ClassDecl>(nominal)) {
if (property->supportsMutation() && isolation.isUnspecified()) {
auto behavior =
SendableCheckContext(dc, check).defaultDiagnosticBehavior();
if (behavior != DiagnosticBehavior::Ignore) {
property
->diagnose(diag::concurrent_value_class_mutable_property,
property->getName(), nominal)
.limitBehaviorUntilSwiftVersion(behavior, 6);
}
invalid = invalid || (behavior == DiagnosticBehavior::Unspecified);
return true;
}
if (!(isolation.isNonisolated() || isolation.isUnspecified())) {
return false; // skip sendable check on actor-isolated properties
}
}
// Check that the property type is Sendable.
SendableCheckContext context(dc, check);
diagnoseNonSendableTypes(
propertyType, context,
/*inDerivedConformance*/Type(), property->getLoc(),
[&](Type type, DiagnosticBehavior behavior) {
auto preconcurrency =
context.preconcurrencyBehavior(type->getAnyNominal());
if (isImplicitSendableCheck(check)) {
// If this is for an externally-visible conformance, fail.
if (check == SendableCheck::ImplicitForExternallyVisible) {
invalid = true;
return true;
}
// If we are to ignore this diagnostic, just continue.
if (behavior == DiagnosticBehavior::Ignore ||
preconcurrency == DiagnosticBehavior::Ignore)
return true;
invalid = true;
return true;
}
property->diagnose(diag::non_concurrent_type_member,
propertyType, false, property->getName(),
nominal)
.limitBehaviorUntilSwiftVersion(behavior, 6)
.limitBehaviorIf(preconcurrency);
return false;
});
if (invalid) {
// For implicit checks, bail out early if anything failed.
if (isImplicitSendableCheck(check))
return true;
}
return false;
}
/// Handle an enum associated value.
bool operator()(EnumElementDecl *element, Type elementType) override {
SendableCheckContext context (dc, check);
diagnoseNonSendableTypes(
elementType, context,
/*inDerivedConformance*/Type(), element->getLoc(),
[&](Type type, DiagnosticBehavior behavior) {
auto preconcurrency =
context.preconcurrencyBehavior(type->getAnyNominal());
if (isImplicitSendableCheck(check)) {
// If this is for an externally-visible conformance, fail.
if (check == SendableCheck::ImplicitForExternallyVisible) {
invalid = true;
return true;
}
// If we are to ignore this diagnostic, just continue.
if (behavior == DiagnosticBehavior::Ignore ||
preconcurrency == DiagnosticBehavior::Ignore)
return true;
invalid = true;
return true;
}
element->diagnose(diag::non_concurrent_type_member, type,
true, element->getName(), nominal)
.limitBehaviorUntilSwiftVersion(behavior, 6)
.limitBehaviorIf(preconcurrency);
return false;
});
if (invalid) {
// For implicit checks, bail out early if anything failed.
if (isImplicitSendableCheck(check))
return true;
}
return false;
}
} visitor(nominal, dc, check);
return visitor.visit(nominal, dc) || visitor.invalid;
}
bool swift::checkSendableConformance(
ProtocolConformance *conformance, SendableCheck check) {
auto conformanceDC = conformance->getDeclContext();
auto nominal = conformance->getType()->getAnyNominal();
if (!nominal)
return false;
// If this is an always-unavailable conformance, there's nothing to check.
// We always use the root conformance for this check, because inherited
// conformances need to walk back to the original declaration for the
// superclass conformance to find an unavailable attribute.
if (auto ext = dyn_cast<ExtensionDecl>(
conformance->getRootConformance()->getDeclContext())) {
if (AvailableAttr::isUnavailable(ext))
return false;
}
bool isUnchecked = false;
if (auto *normal = conformance->getRootNormalConformance())
isUnchecked = normal->isUnchecked();
if (isUnchecked) {
// Warn if inferred or inherited '@unchecked Sendable' is not restated.
// Beyond that, '@unchecked Sendable' requires no further checking.
if (!isa<InheritedProtocolConformance>(conformance))
return false;
auto statesUnchecked =
[](InheritedTypes inheritedTypes, DeclContext *dc) -> bool {
for (auto i : inheritedTypes.getIndices()) {
auto inheritedType =
TypeResolution::forInterface(
dc,
TypeResolverContext::Inherited,
/*unboundTyOpener*/ nullptr,
/*placeholderHandler*/ nullptr,
/*packElementOpener*/ nullptr)
.resolveType(inheritedTypes.getTypeRepr(i));
if (!inheritedType || inheritedType->hasError())
continue;
if (inheritedType->getKnownProtocol() != KnownProtocolKind::Sendable)
continue;
if (inheritedTypes.getEntry(i).isUnchecked())
return true;
}
return false;
};
if (statesUnchecked(nominal->getInherited(), nominal))
return false;
for (auto *extension : nominal->getExtensions()) {
if (statesUnchecked(extension->getInherited(), extension))
return false;
}
nominal->diagnose(diag::restate_unchecked_sendable,
nominal->getName());
return false;
}
auto classDecl = dyn_cast<ClassDecl>(nominal);
if (classDecl) {
// Actors implicitly conform to Sendable and protect their state.
if (classDecl->isActor())
return false;
}
// Global-actor-isolated types can be Sendable. We do not check the
// instance data because it's all isolated to the global actor.
switch (getActorIsolation(nominal)) {
case ActorIsolation::Unspecified:
case ActorIsolation::ActorInstance:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
break;
case ActorIsolation::Erased:
llvm_unreachable("type cannot have erased isolation");
case ActorIsolation::GlobalActor:
return false;
}
// Sendable can only be used in the same source file.
auto conformanceDecl = conformanceDC->getAsDecl();
SendableCheckContext checkContext(conformanceDC, check);
DiagnosticBehavior behavior = checkContext.defaultDiagnosticBehavior();
if (conformance->getSourceKind() == ConformanceEntryKind::Implied &&
conformance->getProtocol()->isSpecificProtocol(
KnownProtocolKind::Sendable)) {
if (auto optBehavior = checkContext.preconcurrencyBehavior(
nominal, /*ignoreExplicitConformance=*/true))
behavior = *optBehavior;
}
if (conformanceDC->getOutermostParentSourceFile() &&
conformanceDC->getOutermostParentSourceFile() !=
nominal->getOutermostParentSourceFile()) {
conformanceDecl->diagnose(diag::concurrent_value_outside_source_file,
nominal)
.limitBehaviorUntilSwiftVersion(behavior, 6);
if (behavior == DiagnosticBehavior::Unspecified)
return true;
}
if (classDecl && classDecl->getParentSourceFile()) {
bool isInherited = isa<InheritedProtocolConformance>(conformance);
// An non-final class cannot conform to `Sendable`.
if (!classDecl->isSemanticallyFinal()) {
classDecl->diagnose(diag::concurrent_value_nonfinal_class,
classDecl->getName())
.limitBehaviorUntilSwiftVersion(behavior, 6);
if (behavior == DiagnosticBehavior::Unspecified)
return true;
}
if (!isInherited) {
// A 'Sendable' class cannot inherit from another class, although
// we allow `NSObject` for Objective-C interoperability.
if (auto superclassDecl = classDecl->getSuperclassDecl()) {
if (!superclassDecl->isNSObject()) {
classDecl
->diagnose(diag::concurrent_value_inherit,
nominal->getASTContext().LangOpts.EnableObjCInterop,
classDecl->getName())
.limitBehaviorUntilSwiftVersion(behavior, 6);
if (behavior == DiagnosticBehavior::Unspecified)
return true;
}
}
}
}
// In -swift-version 5 mode, a conditional conformance to a protocol can imply
// a Sendable conformance. The implied conformance is unconditional, so check
// the storage for sendability as if the conformance was declared on the nominal,
// and not some (possibly constrained) extension.
if (conformance->getSourceKind() == ConformanceEntryKind::Implied)
conformanceDC = nominal;
return checkSendableInstanceStorage(nominal, conformanceDC, check);
}
/// Add "unavailable" attributes to the given extension.
static void addUnavailableAttrs(ExtensionDecl *ext, NominalTypeDecl *nominal) {
ASTContext &ctx = nominal->getASTContext();
llvm::VersionTuple noVersion;
// Add platform-version-specific @available attributes. Search from nominal
// type declaration through its enclosing declarations to find the first one
// with platform-specific attributes.
for (Decl *enclosing = nominal;
enclosing;
enclosing = enclosing->getDeclContext()
? enclosing->getDeclContext()->getAsDecl()
: nullptr) {
bool anyPlatformSpecificAttrs = false;
for (auto available: enclosing->getAttrs().getAttributes<AvailableAttr>()) {
if (available->Platform == PlatformKind::none)
continue;
auto attr = new (ctx) AvailableAttr(
SourceLoc(), SourceRange(),
available->Platform,
available->Message,
"", nullptr,
available->Introduced.value_or(noVersion), SourceRange(),
available->Deprecated.value_or(noVersion), SourceRange(),
available->Obsoleted.value_or(noVersion), SourceRange(),
PlatformAgnosticAvailabilityKind::Unavailable,
/*implicit=*/true,
available->IsSPI);
ext->getAttrs().add(attr);
anyPlatformSpecificAttrs = true;
}
// If we found any platform-specific availability attributes, we're done.
if (anyPlatformSpecificAttrs)
break;
}
// Add the blanket "unavailable".
auto attr = new (ctx) AvailableAttr(SourceLoc(), SourceRange(),
PlatformKind::none, "", "", nullptr,
noVersion, SourceRange(),
noVersion, SourceRange(),
noVersion, SourceRange(),
PlatformAgnosticAvailabilityKind::Unavailable,
false,
false);
ext->getAttrs().add(attr);
}
ProtocolConformance *swift::deriveImplicitSendableConformance(
Evaluator &evaluator, NominalTypeDecl *nominal) {
// Protocols never get implicit Sendable conformances.
if (isa<ProtocolDecl>(nominal))
return nullptr;
// Actor types are always Sendable; they don't get it via this path.
auto classDecl = dyn_cast<ClassDecl>(nominal);
if (classDecl && classDecl->isActor())
return nullptr;
// Check whether we can infer conformance at all.
if (auto *file = dyn_cast<FileUnit>(nominal->getModuleScopeContext())) {
switch (file->getKind()) {
case FileUnitKind::Source:
// Check what kind of source file we have.
if (auto sourceFile = nominal->getParentSourceFile()) {
switch (sourceFile->Kind) {
case SourceFileKind::Interface:
// Interfaces have explicitly called-out Sendable conformances.
return nullptr;
case SourceFileKind::DefaultArgument:
case SourceFileKind::Library:
case SourceFileKind::MacroExpansion:
case SourceFileKind::Main:
case SourceFileKind::SIL:
break;
}
}
break;
case FileUnitKind::Builtin:
case FileUnitKind::SerializedAST:
case FileUnitKind::Synthesized:
// Explicitly-handled modules don't infer Sendable conformances.
return nullptr;
case FileUnitKind::ClangModule:
case FileUnitKind::DWARFModule:
// Infer conformances for imported modules.
break;
}
} else {
return nullptr;
}
ASTContext &ctx = nominal->getASTContext();
auto proto = ctx.getProtocol(KnownProtocolKind::Sendable);
if (!proto)
return nullptr;
// Local function to form the implicit conformance.
auto formConformance = [&](const DeclAttribute *attrMakingUnavailable)
-> NormalProtocolConformance * {
DeclContext *conformanceDC = nominal;
if (attrMakingUnavailable) {
// Conformance availability is currently tied to the declaring extension.
// FIXME: This is a hack--we should give conformances real availability.
auto inherits = ctx.AllocateCopy(llvm::ArrayRef(
InheritedEntry(TypeLoc::withoutLoc(proto->getDeclaredInterfaceType()),
/*isUnchecked*/ true, /*isRetroactive=*/false,
/*isPreconcurrency=*/false)));
// If you change the use of AtLoc in the ExtensionDecl, make sure you
// update isNonSendableExtension() in ASTPrinter.
auto extension = ExtensionDecl::create(ctx, attrMakingUnavailable->AtLoc,
nullptr, inherits,
nominal->getModuleScopeContext(),
nullptr);
extension->setImplicit();
addUnavailableAttrs(extension, nominal);
ctx.evaluator.cacheOutput(ExtendedTypeRequest{extension},
nominal->getDeclaredType());
ctx.evaluator.cacheOutput(ExtendedNominalRequest{extension},
std::move(nominal));
nominal->addExtension(extension);
// Make it accessible to getTopLevelDecls()
if (auto file = dyn_cast<FileUnit>(nominal->getModuleScopeContext()))
file->getOrCreateSynthesizedFile().addTopLevelDecl(extension);
conformanceDC = extension;
}
auto conformance = ctx.getNormalConformance(
nominal->getDeclaredInterfaceType(), proto, nominal->getLoc(),
conformanceDC, ProtocolConformanceState::Complete,
/*isUnchecked=*/attrMakingUnavailable != nullptr,
/*isPreconcurrency=*/false);
conformance->setSourceKindAndImplyingConformance(
ConformanceEntryKind::Synthesized, nullptr);
nominal->registerProtocolConformance(conformance, /*synthesized=*/true);
return conformance;
};
// If this is a class, check the superclass. If it's already Sendable,
// form an inherited conformance.
if (classDecl) {
if (Type superclass = classDecl->getSuperclass()) {
auto classModule = classDecl->getParentModule();
auto inheritedConformance = classModule->checkConformance(
classDecl->mapTypeIntoContext(superclass),
proto, /*allowMissing=*/false);
if (inheritedConformance.hasUnavailableConformance())
inheritedConformance = ProtocolConformanceRef::forInvalid();
if (inheritedConformance) {
inheritedConformance = inheritedConformance
.mapConformanceOutOfContext();
if (inheritedConformance.isConcrete()) {
return ctx.getInheritedConformance(
nominal->getDeclaredInterfaceType(),
inheritedConformance.getConcrete());
}
}
// Classes that add global actor isolation to non-Sendable
// superclasses cannot be 'Sendable'.
auto superclassDecl = classDecl->getSuperclassDecl();
if (nominal->getGlobalActorAttr() && !superclassDecl->isNSObject()) {
return nullptr;
}
}
}
// A non-protocol type with a global actor is implicitly Sendable.
if (getActorIsolation(nominal).isGlobalActor()) {
// Form the implicit conformance to Sendable.
return formConformance(nullptr);
}
if (auto attr = nominal->getAttrs().getEffectiveSendableAttr()) {
assert(!isa<SendableAttr>(attr) &&
"Conformance should have been added by SynthesizedProtocolAttr!");
return formConformance(cast<NonSendableAttr>(attr));
}
// Only structs and enums can get implicit Sendable conformances by
// considering their instance data.
if (!isa<StructDecl>(nominal) && !isa<EnumDecl>(nominal))
return nullptr;
SendableCheck check;
// Okay to infer Sendable conformance for non-public types or when
// specifically requested.
if (nominal->getASTContext().LangOpts.EnableInferPublicSendable ||
!nominal->getFormalAccessScope(
/*useDC=*/nullptr, /*treatUsableFromInlineAsPublic=*/true)
.isPublic()) {
check = SendableCheck::Implicit;
} else if (nominal->hasClangNode() ||
nominal->getAttrs().hasAttribute<FixedLayoutAttr>() ||
nominal->getAttrs().hasAttribute<FrozenAttr>()) {
// @_frozen public types can also infer Sendable, but be more careful here.
check = SendableCheck::ImplicitForExternallyVisible;
} else {
// No inference.
return nullptr;
}
// Check the instance storage for Sendable conformance.
if (checkSendableInstanceStorage(nominal, nominal, check))
return nullptr;
return formConformance(nullptr);
}
/// Apply @Sendable and/or @MainActor to the given parameter type.
static Type applyUnsafeConcurrencyToParameterType(
Type type, bool sendable, bool mainActor) {
if (Type objectType = type->getOptionalObjectType()) {
return OptionalType::get(
applyUnsafeConcurrencyToParameterType(objectType, sendable, mainActor));
}
auto fnType = type->getAs<FunctionType>();
if (!fnType)
return type;
auto isolation = fnType->getIsolation();
if (mainActor)
isolation = FunctionTypeIsolation::forGlobalActor(
type->getASTContext().getMainActorType());
return fnType->withExtInfo(fnType->getExtInfo()
.withSendable(sendable)
.withIsolation(isolation));
}
/// Determine whether the given name is that of a DispatchQueue operation that
/// takes a closure to be executed on the queue.
std::optional<DispatchQueueOperation>
swift::isDispatchQueueOperationName(StringRef name) {
return llvm::StringSwitch<std::optional<DispatchQueueOperation>>(name)
.Case("sync", DispatchQueueOperation::Normal)
.Case("async", DispatchQueueOperation::Sendable)
.Case("asyncAndWait", DispatchQueueOperation::Normal)
.Case("asyncUnsafe", DispatchQueueOperation::Normal)
.Case("asyncAfter", DispatchQueueOperation::Sendable)
.Case("concurrentPerform", DispatchQueueOperation::Sendable)
.Default(std::nullopt);
}
/// Determine whether this function is implicitly known to have its
/// parameters of function type be @_unsafeSendable.
///
/// This hard-codes knowledge of a number of functions that will
/// eventually have @_unsafeSendable and, eventually, @Sendable,
/// on their parameters of function type.
static bool hasKnownUnsafeSendableFunctionParams(AbstractFunctionDecl *func) {
auto nominal = func->getDeclContext()->getSelfNominalTypeDecl();
if (!nominal)
return false;
// DispatchQueue operations.
auto nominalName = nominal->getName().str();
if (nominalName == "DispatchQueue") {
auto name = func->getBaseName().userFacingName();
auto operation = isDispatchQueueOperationName(name);
if (!operation)
return false;
switch (*operation) {
case DispatchQueueOperation::Normal:
return false;
case DispatchQueueOperation::Sendable:
return true;
}
}
return false;
}
Type swift::adjustVarTypeForConcurrency(
Type type, VarDecl *var, DeclContext *dc,
llvm::function_ref<Type(const AbstractClosureExpr *)> getType,
llvm::function_ref<bool(const ClosureExpr *)> isolatedByPreconcurrency) {
if (!var->preconcurrency())
return type;
if (contextRequiresStrictConcurrencyChecking(
dc, getType, isolatedByPreconcurrency))
return type;
bool isLValue = false;
if (auto *lvalueType = type->getAs<LValueType>()) {
type = lvalueType->getObjectType();
isLValue = true;
}
type = type->stripConcurrency(/*recurse=*/false, /*dropGlobalActor=*/true);
if (isLValue)
type = LValueType::get(type);
return type;
}
/// Adjust a function type for @_unsafeSendable, @_unsafeMainActor, and
/// @preconcurrency.
static AnyFunctionType *applyUnsafeConcurrencyToFunctionType(
AnyFunctionType *fnType, ValueDecl *decl,
bool inConcurrencyContext, unsigned numApplies, bool isMainDispatchQueue) {
// Functions/subscripts/enum elements have function types to adjust.
auto func = dyn_cast_or_null<AbstractFunctionDecl>(decl);
auto subscript = dyn_cast_or_null<SubscriptDecl>(decl);
if (!func && !subscript)
return fnType;
AnyFunctionType *outerFnType = nullptr;
if ((subscript && numApplies > 1) || (func && func->hasImplicitSelfDecl())) {
outerFnType = fnType;
fnType = outerFnType->getResult()->castTo<AnyFunctionType>();
if (numApplies > 0)
--numApplies;
}
SmallVector<AnyFunctionType::Param, 4> newTypeParams;
auto typeParams = fnType->getParams();
auto paramDecls = func ? func->getParameters() : subscript->getIndices();
assert(typeParams.size() == paramDecls->size());
bool knownUnsafeParams = func && hasKnownUnsafeSendableFunctionParams(func);
bool stripConcurrency =
decl->preconcurrency() && !inConcurrencyContext;
for (unsigned index : indices(typeParams)) {
auto param = typeParams[index];
// Determine whether the resulting parameter should be @Sendable or
// @MainActor. @Sendable occurs only in concurrency contents, while
// @MainActor occurs in concurrency contexts or those where we have an
// application.
bool addSendable = knownUnsafeParams && inConcurrencyContext;
bool addMainActor = isMainDispatchQueue &&
(inConcurrencyContext || numApplies >= 1);
Type newParamType = param.getPlainType();
if (addSendable || addMainActor) {
newParamType = applyUnsafeConcurrencyToParameterType(
param.getPlainType(), addSendable, addMainActor);
} else if (stripConcurrency && numApplies == 0) {
newParamType = param.getPlainType()->stripConcurrency(
/*recurse=*/false, /*dropGlobalActor=*/numApplies == 0);
}
if (!newParamType || newParamType->isEqual(param.getPlainType())) {
// If any prior parameter has changed, record this one.
if (!newTypeParams.empty())
newTypeParams.push_back(param);
continue;
}
// If this is the first parameter to have changed, copy all of the others
// over.
if (newTypeParams.empty()) {
newTypeParams.append(typeParams.begin(), typeParams.begin() + index);
}
// Transform the parameter type.
newTypeParams.push_back(param.withType(newParamType));
}
// Compute the new result type.
Type newResultType = fnType->getResult();
if (stripConcurrency) {
newResultType = newResultType->stripConcurrency(
/*recurse=*/false, /*dropGlobalActor=*/true);
if (!newResultType->isEqual(fnType->getResult()) && newTypeParams.empty()) {
newTypeParams.append(typeParams.begin(), typeParams.end());
}
}
// If we didn't change any parameters, we're done.
if (newTypeParams.empty() && newResultType->isEqual(fnType->getResult())) {
return outerFnType ? outerFnType : fnType;
}
// Rebuild the (inner) function type.
fnType = FunctionType::get(
newTypeParams, newResultType, fnType->getExtInfo());
if (!outerFnType)
return fnType;
// Rebuild the outer function type.
if (auto genericFnType = dyn_cast<GenericFunctionType>(outerFnType)) {
return GenericFunctionType::get(
genericFnType->getGenericSignature(), outerFnType->getParams(),
Type(fnType), outerFnType->getExtInfo());
}
return FunctionType::get(
outerFnType->getParams(), Type(fnType), outerFnType->getExtInfo());
}
AnyFunctionType *swift::adjustFunctionTypeForConcurrency(
AnyFunctionType *fnType, ValueDecl *decl, DeclContext *dc,
unsigned numApplies, bool isMainDispatchQueue,
llvm::function_ref<Type(const AbstractClosureExpr *)> getType,
llvm::function_ref<bool(const ClosureExpr *)> isolatedByPreconcurrency,
llvm::function_ref<Type(Type)> openType) {
// Apply unsafe concurrency features to the given function type.
bool strictChecking = contextRequiresStrictConcurrencyChecking(
dc, getType, isolatedByPreconcurrency);
fnType = applyUnsafeConcurrencyToFunctionType(
fnType, decl, strictChecking, numApplies, isMainDispatchQueue);
Type globalActorType;
if (decl) {
switch (auto isolation = getActorIsolation(decl)) {
case ActorIsolation::ActorInstance:
// The function type may or may not have parameter isolation.
return fnType;
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
assert(fnType->getIsolation().isNonIsolated());
return fnType;
case ActorIsolation::Erased:
llvm_unreachable("declaration cannot have erased isolation");
case ActorIsolation::GlobalActor:
// For preconcurrency, only treat as global-actor-qualified
// within code that has adopted Swift Concurrency features.
if (!strictChecking && isolation.preconcurrency())
return fnType;
globalActorType = openType(isolation.getGlobalActor());
break;
}
}
auto isolation = FunctionTypeIsolation::forGlobalActor(globalActorType);
// If there's no implicit "self" declaration, apply the isolation to
// the outermost function type.
bool hasImplicitSelfDecl = decl && (isa<EnumElementDecl>(decl) ||
(isa<AbstractFunctionDecl>(decl) &&
cast<AbstractFunctionDecl>(decl)->hasImplicitSelfDecl()));
if (!hasImplicitSelfDecl) {
return fnType->withExtInfo(fnType->getExtInfo().withIsolation(isolation));
}
// Dig out the inner function type.
auto innerFnType = fnType->getResult()->getAs<AnyFunctionType>();
if (!innerFnType)
return fnType;
// Update the inner function type with the isolation.
innerFnType = innerFnType->withExtInfo(
innerFnType->getExtInfo().withIsolation(isolation));
// Rebuild the outer function type around it.
if (auto genericFnType = dyn_cast<GenericFunctionType>(fnType)) {
return GenericFunctionType::get(
genericFnType->getGenericSignature(), fnType->getParams(),
Type(innerFnType), fnType->getExtInfo());
}
return FunctionType::get(
fnType->getParams(), Type(innerFnType), fnType->getExtInfo());
}
bool swift::completionContextUsesConcurrencyFeatures(const DeclContext *dc) {
return contextRequiresStrictConcurrencyChecking(
dc, [](const AbstractClosureExpr *) {
return Type();
},
[](const ClosureExpr *closure) {
return closure->isIsolatedByPreconcurrency();
});
}
/// Find the directly-referenced parameter or capture of a parameter for
/// for the given expression.
VarDecl *swift::getReferencedParamOrCapture(
Expr *expr,
llvm::function_ref<Expr *(OpaqueValueExpr *)> getExistentialValue,
llvm::function_ref<VarDecl *()> getCurrentIsolatedVar) {
// Look through identity expressions and implicit conversions.
Expr *prior;
do {
prior = expr;
expr = expr->getSemanticsProvidingExpr();
if (auto conversion = dyn_cast<ImplicitConversionExpr>(expr))
expr = conversion->getSubExpr();
// Map opaque values.
if (auto opaqueValue = dyn_cast<OpaqueValueExpr>(expr)) {
if (auto *value = getExistentialValue(opaqueValue))
expr = value;
}
} while (prior != expr);
// 'super' references always act on a 'self' variable.
if (auto super = dyn_cast<SuperRefExpr>(expr))
return super->getSelf();
// Declaration references to a variable.
if (auto declRef = dyn_cast<DeclRefExpr>(expr))
return dyn_cast<VarDecl>(declRef->getDecl());
// The current context isolation expression (#isolation) always
// corresponds to the isolation of the given code.
if (isa<CurrentContextIsolationExpr>(expr))
return getCurrentIsolatedVar();
return nullptr;
}
bool swift::isPotentiallyIsolatedActor(
VarDecl *var, llvm::function_ref<bool(ParamDecl *)> isIsolated) {
if (!var)
return false;
if (var->getName().str().equals("__secretlyKnownToBeLocal")) {
// FIXME(distributed): we did a dynamic check and know that this actor is
// local, but we can't express that to the type system; the real
// implementation will have to mark 'self' as "known to be local" after
// an is-local check.
return true;
}
if (auto param = dyn_cast<ParamDecl>(var))
return isIsolated(param);
// If this is a captured 'self', check whether the original 'self' is
// isolated.
if (var->isSelfParamCapture())
return var->isSelfParamCaptureIsolated();
return false;
}
/// Determine the actor isolation used when we are referencing the given
/// declaration.
static ActorIsolation getActorIsolationForReference(ValueDecl *decl,
const DeclContext *fromDC) {
auto declIsolation = getActorIsolation(decl);
// If the isolation is preconcurrency global actor, adjust it based on
// context itself. For contexts that require strict checking, treat it as
// global actor isolation. Otherwise, treat it as unspecified isolation.
if (declIsolation == ActorIsolation::GlobalActor &&
declIsolation.preconcurrency()) {
if (!contextRequiresStrictConcurrencyChecking(
fromDC,
[](const AbstractClosureExpr *closure) {
return closure->getType();
},
[](const ClosureExpr *closure) {
return closure->isIsolatedByPreconcurrency();
})) {
declIsolation = ActorIsolation::forUnspecified();
}
}
// A constructor that is not explicitly 'nonisolated' is treated as
// isolated from the perspective of the referencer.
//
// FIXME: The current state is that even `nonisolated` initializers are
// externally treated as being on the actor, even though this model isn't
// consistent. We'll fix it later.
if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
// If the constructor is part of an actor, references to it are treated
// as needing to enter the actor.
if (auto nominal = ctor->getDeclContext()->getSelfNominalTypeDecl()) {
if (nominal->isAnyActor())
return ActorIsolation::forActorInstanceSelf(decl);
}
// Fall through to treat initializers like any other declaration.
}
// A 'nonisolated let' within an actor is treated as isolated if
// the access is outside the module or if the property type is not
// 'Sendable'.
//
// FIXME: getActorIsolation(decl) should treat these as isolated.
// FIXME: Expand this out to local variables?
if (auto var = dyn_cast<VarDecl>(decl)) {
auto *fromModule = fromDC->getParentModule();
ActorReferenceResult::Options options = std::nullopt;
if (varIsSafeAcrossActors(fromModule, var, declIsolation, options) &&
var->getTypeInContext()->isSendableType())
return ActorIsolation::forNonisolated(/*unsafe*/false);
if (var->isLet() && isStoredProperty(var) &&
declIsolation.isNonisolated()) {
if (auto nominal = var->getDeclContext()->getSelfNominalTypeDecl()) {
if (nominal->isAnyActor())
return ActorIsolation::forActorInstanceSelf(decl);
auto nominalIsolation = getActorIsolation(nominal);
if (nominalIsolation.isGlobalActor())
return getActorIsolationForReference(nominal, fromDC);
}
}
}
return declIsolation;
}
/// Determine whether this declaration always throws.
bool swift::isThrowsDecl(ConcreteDeclRef declRef) {
auto decl = declRef.getDecl();
// An async function is asynchronously accessed.
if (auto func = dyn_cast<AbstractFunctionDecl>(decl))
return func->hasThrows();
// A computed property or subscript that has an 'async' getter
// is asynchronously accessed.
if (auto storageDecl = dyn_cast<AbstractStorageDecl>(decl)) {
if (auto effectfulGetter = storageDecl->getEffectfulGetAccessor())
return effectfulGetter->hasThrows();
}
return false;
}
/// Determine whether a reference to this value isn't actually a value.
static bool isNonValueReference(const ValueDecl *value) {
switch (value->getKind()) {
case DeclKind::AssociatedType:
case DeclKind::Class:
case DeclKind::Enum:
case DeclKind::Extension:
case DeclKind::GenericTypeParam:
case DeclKind::OpaqueType:
case DeclKind::Protocol:
case DeclKind::Struct:
case DeclKind::TypeAlias:
case DeclKind::EnumCase:
case DeclKind::IfConfig:
case DeclKind::Import:
case DeclKind::InfixOperator:
case DeclKind::Missing:
case DeclKind::MissingMember:
case DeclKind::Module:
case DeclKind::PatternBinding:
case DeclKind::PostfixOperator:
case DeclKind::PoundDiagnostic:
case DeclKind::PrecedenceGroup:
case DeclKind::PrefixOperator:
case DeclKind::TopLevelCode:
case DeclKind::Destructor:
case DeclKind::MacroExpansion:
return true;
case DeclKind::EnumElement:
case DeclKind::Constructor:
case DeclKind::Param:
case DeclKind::Var:
case DeclKind::Accessor:
case DeclKind::Func:
case DeclKind::Subscript:
case DeclKind::Macro:
return false;
case DeclKind::BuiltinTuple:
llvm_unreachable("BuiltinTupleDecl should not show up here");
}
}
bool swift::isAccessibleAcrossActors(
ValueDecl *value, const ActorIsolation &isolation,
const DeclContext *fromDC, ActorReferenceResult::Options &options,
std::optional<ReferencedActor> actorInstance) {
// Initializers and enum elements are accessible across actors unless they
// are global-actor qualified.
if (isa<ConstructorDecl>(value) || isa<EnumElementDecl>(value)) {
switch (isolation) {
case ActorIsolation::ActorInstance:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::Unspecified:
return true;
case ActorIsolation::Erased:
llvm_unreachable("declaration cannot have erased isolation");
case ActorIsolation::GlobalActor:
return false;
}
}
// 'let' declarations are immutable, so some of them can be accessed across
// actors.
if (auto var = dyn_cast<VarDecl>(value)) {
return varIsSafeAcrossActors(
fromDC->getParentModule(), var, isolation, options);
}
return false;
}
bool swift::isAccessibleAcrossActors(
ValueDecl *value, const ActorIsolation &isolation,
const DeclContext *fromDC, std::optional<ReferencedActor> actorInstance) {
ActorReferenceResult::Options options = std::nullopt;
return isAccessibleAcrossActors(
value, isolation, fromDC, options, actorInstance);
}
ActorReferenceResult ActorReferenceResult::forSameConcurrencyDomain(
ActorIsolation isolation, Options options) {
return ActorReferenceResult{SameConcurrencyDomain, options, isolation};
}
ActorReferenceResult ActorReferenceResult::forEntersActor(
ActorIsolation isolation, Options options) {
return ActorReferenceResult{EntersActor, options, isolation};
}
ActorReferenceResult ActorReferenceResult::forExitsActorToNonisolated(
ActorIsolation isolation, Options options) {
return ActorReferenceResult{ExitsActorToNonisolated, options, isolation};
}
// Determine if two actor isolation contexts are considered to be equivalent.
static bool equivalentIsolationContexts(
const ActorIsolation &lhs, const ActorIsolation &rhs) {
if (lhs == rhs)
return true;
if (lhs == ActorIsolation::ActorInstance &&
rhs == ActorIsolation::ActorInstance &&
lhs.isDistributedActor() == rhs.isDistributedActor())
return true;
return false;
}
ActorReferenceResult ActorReferenceResult::forReference(
ConcreteDeclRef declRef, SourceLoc declRefLoc, const DeclContext *fromDC,
std::optional<VarRefUseEnv> useKind,
std::optional<ReferencedActor> actorInstance,
std::optional<ActorIsolation> knownDeclIsolation,
std::optional<ActorIsolation> knownContextIsolation,
llvm::function_ref<ActorIsolation(AbstractClosureExpr *)>
getClosureActorIsolation) {
// If not provided, compute the isolation of the declaration, adjusted
// for references.
ActorIsolation declIsolation = ActorIsolation::forUnspecified();
if (knownDeclIsolation) {
declIsolation = *knownDeclIsolation;
} else {
declIsolation = getActorIsolationForReference(declRef.getDecl(), fromDC);
if (declIsolation.requiresSubstitution())
declIsolation = declIsolation.subst(declRef.getSubstitutions());
}
// Determine what adjustments we need to perform for cross-actor
// references.
Options options = std::nullopt;
// FIXME: Actor constructors are modeled as isolated to the actor
// so that Sendable checking is applied to their arguments, but the
// call itself does not hop to another executor.
if (auto ctor = dyn_cast<ConstructorDecl>(declRef.getDecl())) {
if (auto nominal = ctor->getDeclContext()->getSelfNominalTypeDecl()) {
if (nominal->isAnyActor())
options |= Flags::OnlyArgsCrossIsolation;
}
}
// If the entity we are referencing is not a value, we're in the same
// concurrency domain.
if (isNonValueReference(declRef.getDecl()))
return forSameConcurrencyDomain(declIsolation, options);
// Compute the isolation of the context, if not provided.
ActorIsolation contextIsolation = ActorIsolation::forUnspecified();
if (knownContextIsolation) {
contextIsolation = *knownContextIsolation;
} else {
contextIsolation =
getInnermostIsolatedContext(fromDC, getClosureActorIsolation);
}
// When the declaration is not actor-isolated, it can always be accessed
// directly.
if (!declIsolation.isActorIsolated()) {
// If the declaration is asynchronous and we are in an actor-isolated
// context (of any kind), then we exit the actor to the nonisolated context.
if (isAsyncDecl(declRef) && contextIsolation.isActorIsolated() &&
!declRef.getDecl()->getAttrs()
.hasAttribute<UnsafeInheritExecutorAttr>())
return forExitsActorToNonisolated(contextIsolation, options);
// Otherwise, we stay in the same concurrency domain, whether on an actor
// or in a task.
return forSameConcurrencyDomain(declIsolation, options);
}
// The declaration we are accessing is actor-isolated. First, check whether
// we are on the same actor already.
if (actorInstance && declIsolation == ActorIsolation::ActorInstance &&
declIsolation.getActorInstanceParameter() == 0) {
// If this instance is isolated, we're in the same concurrency domain.
if (actorInstance->isIsolated())
return forSameConcurrencyDomain(declIsolation, options);
} else if (equivalentIsolationContexts(declIsolation, contextIsolation)) {
// The context isolation matches, so we are in the same concurrency
// domain.
return forSameConcurrencyDomain(declIsolation, options);
}
// Initializing an actor isolated stored property with a value effectively
// passes that value from the init context into the actor isolated context.
// It's only okay for the value to cross isolation boundaries if the property
// type is Sendable. Note that if the init is a nonisolated actor init,
// Sendable checking is already performed on arguments at the call-site.
if ((declIsolation.isActorIsolated() && contextIsolation.isGlobalActor()) ||
declIsolation.isGlobalActor()) {
auto *init = dyn_cast<ConstructorDecl>(fromDC);
auto *decl = declRef.getDecl();
if (init && init->isDesignatedInit() && isStoredProperty(decl) &&
(!actorInstance || actorInstance->isSelf())) {
auto type =
fromDC->mapTypeIntoContext(declRef.getDecl()->getInterfaceType());
if (!type->isSendableType()) {
// Treat the decl isolation as 'preconcurrency' to downgrade violations
// to warnings, because violating Sendable here is accepted by the
// Swift 5.9 compiler.
options |= Flags::Preconcurrency;
return forEntersActor(declIsolation, options);
}
}
}
// If there is an instance and it is checked by flow isolation, treat it
// as being in the same concurrency domain.
if (actorInstance &&
checkedByFlowIsolation(
fromDC, *actorInstance, declRef.getDecl(), declRefLoc, useKind))
return forSameConcurrencyDomain(declIsolation, options);
// If we are delegating to another initializer, treat them as being in the
// same concurrency domain.
// FIXME: This has a lot of overlap with both the stored-property checks
// below and the flow-isolation checks above.
if (actorInstance && actorInstance->isSelf() &&
isa<ConstructorDecl>(declRef.getDecl()) &&
isa<ConstructorDecl>(fromDC))
return forSameConcurrencyDomain(declIsolation, options);
// If there is an instance that corresponds to 'self',
// we are in a constructor or destructor, and we have a stored property of
// global-actor-qualified type, then we have problems if the stored property
// type is non-Sendable. Note that if we get here, the type must be Sendable.
if (actorInstance && actorInstance->isSelf() &&
isNonInheritedStorage(declRef.getDecl(), fromDC) &&
declIsolation.isGlobalActor() &&
(isa<ConstructorDecl>(fromDC) || isa<DestructorDecl>(fromDC)))
return forSameConcurrencyDomain(declIsolation, options);
// At this point, we are accessing the target from outside the actor.
// First, check whether it is something that can be accessed directly,
// without any kind of promotion.
if (isAccessibleAcrossActors(
declRef.getDecl(), declIsolation, fromDC, options, actorInstance))
return forEntersActor(declIsolation, options);
// This is a cross-actor reference.
// Note if the reference originates from a @preconcurrency-isolated context.
if (contextIsolation.preconcurrency() || declIsolation.preconcurrency())
options |= Flags::Preconcurrency;
// If the declaration isn't asynchronous, promote to async.
if (!isAsyncDecl(declRef))
options |= Flags::AsyncPromotion;
// If the declaration is isolated to a distributed actor and we are not
// guaranteed to be on the same node, make adjustments distributed
// access.
if (declIsolation.isDistributedActor()) {
bool needsDistributed;
if (actorInstance)
needsDistributed = !actorInstance->isKnownToBeLocal();
else
needsDistributed = !contextIsolation.isDistributedActor();
if (needsDistributed) {
options |= Flags::Distributed;
if (!isThrowsDecl(declRef))
options |= Flags::ThrowsPromotion;
}
}
return forEntersActor(declIsolation, options);
}
bool swift::diagnoseNonSendableFromDeinit(
SourceLoc refLoc, VarDecl *var, DeclContext *dc) {
return diagnoseIfAnyNonSendableTypes(var->getTypeInContext(),
SendableCheckContext(dc),
Type(),
SourceLoc(),
refLoc,
diag::non_sendable_from_deinit,
var->getDescriptiveKind(), var->getName());
}
|