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
|
//===--- TypeCheckAvailability.cpp - Availability Diagnostics -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 availability diagnostics.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckAvailability.h"
#include "MiscDiagnostics.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckObjC.h"
#include "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeDeclFinder.h"
#include "swift/AST/TypeRefinementContext.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Sema/IDETypeChecking.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
ExportContext::ExportContext(
DeclContext *DC, AvailabilityContext runningOSVersion,
FragileFunctionKind kind, bool spi, bool exported, bool implicit,
bool deprecated, std::optional<PlatformKind> unavailablePlatformKind)
: DC(DC), RunningOSVersion(runningOSVersion), FragileKind(kind) {
SPI = spi;
Exported = exported;
Implicit = implicit;
Deprecated = deprecated;
if (unavailablePlatformKind) {
Unavailable = 1;
Platform = unsigned(*unavailablePlatformKind);
} else {
Unavailable = 0;
Platform = 0;
}
Reason = unsigned(ExportabilityReason::General);
}
bool swift::isExported(const ValueDecl *VD) {
if (VD->getAttrs().hasAttribute<ImplementationOnlyAttr>())
return false;
if (VD->isObjCMemberImplementation())
return false;
// Is this part of the module's API or ABI?
AccessScope accessScope =
VD->getFormalAccessScope(nullptr,
/*treatUsableFromInlineAsPublic*/true);
if (accessScope.isPublic())
return true;
// Is this a stored property in a @frozen struct or class?
if (auto *property = dyn_cast<VarDecl>(VD))
if (property->isLayoutExposedToClients())
return true;
return false;
}
static bool hasConformancesToPublicProtocols(const ExtensionDecl *ED) {
auto protocols = ED->getLocalProtocols(ConformanceLookupKind::OnlyExplicit);
for (const ProtocolDecl *PD : protocols) {
AccessScope scope =
PD->getFormalAccessScope(/*useDC*/ nullptr,
/*treatUsableFromInlineAsPublic*/ true);
if (scope.isPublic())
return true;
}
return false;
}
bool swift::isExported(const ExtensionDecl *ED) {
// An extension can only be exported if it extends an exported type.
if (auto *NTD = ED->getExtendedNominal()) {
if (!isExported(NTD))
return false;
}
// If there are any exported members then the extension is exported.
for (const Decl *D : ED->getMembers()) {
if (isExported(D))
return true;
}
// If the extension declares a conformance to a public protocol then the
// extension is exported.
if (hasConformancesToPublicProtocols(ED))
return true;
return false;
}
bool swift::isExported(const Decl *D) {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
return isExported(VD);
}
if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) {
for (unsigned i = 0, e = PBD->getNumPatternEntries(); i < e; ++i) {
if (auto *VD = PBD->getAnchoringVarDecl(i))
return isExported(VD);
}
return false;
}
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
return isExported(ED);
}
return true;
}
template<typename Fn>
static void forEachOuterDecl(DeclContext *DC, Fn fn) {
for (; !DC->isModuleScopeContext(); DC = DC->getParent()) {
switch (DC->getContextKind()) {
case DeclContextKind::AbstractClosureExpr:
case DeclContextKind::SerializedAbstractClosure:
case DeclContextKind::TopLevelCodeDecl:
case DeclContextKind::SerializedTopLevelCodeDecl:
case DeclContextKind::Package:
case DeclContextKind::Module:
case DeclContextKind::FileUnit:
case DeclContextKind::MacroDecl:
break;
case DeclContextKind::Initializer:
if (auto *PBI = dyn_cast<PatternBindingInitializer>(DC))
fn(PBI->getBinding());
else if (auto *I = dyn_cast<PropertyWrapperInitializer>(DC))
fn(I->getWrappedVar());
break;
case DeclContextKind::SubscriptDecl:
fn(cast<SubscriptDecl>(DC));
break;
case DeclContextKind::EnumElementDecl:
fn(cast<EnumElementDecl>(DC));
break;
case DeclContextKind::AbstractFunctionDecl:
fn(cast<AbstractFunctionDecl>(DC));
if (auto *AD = dyn_cast<AccessorDecl>(DC))
fn(AD->getStorage());
break;
case DeclContextKind::GenericTypeDecl:
fn(cast<GenericTypeDecl>(DC));
break;
case DeclContextKind::ExtensionDecl:
fn(cast<ExtensionDecl>(DC));
break;
}
}
}
static void
computeExportContextBits(ASTContext &Ctx, Decl *D, bool *spi, bool *implicit,
bool *deprecated,
std::optional<PlatformKind> *unavailablePlatformKind) {
if (D->isSPI() ||
D->isAvailableAsSPI())
*spi = true;
// Defer bodies are desugared to an implicit closure expression. We need to
// dilute the meaning of "implicit" to make sure we're still checking
// availability inside of defer statements.
const auto isDeferBody = isa<FuncDecl>(D) && cast<FuncDecl>(D)->isDeferBody();
if (D->isImplicit() && !isDeferBody)
*implicit = true;
if (D->getAttrs().isDeprecated(Ctx))
*deprecated = true;
if (auto *A = D->getAttrs().getUnavailable(Ctx)) {
*unavailablePlatformKind = A->Platform;
}
if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) {
for (unsigned i = 0, e = PBD->getNumPatternEntries(); i < e; ++i) {
if (auto *VD = PBD->getAnchoringVarDecl(i))
computeExportContextBits(Ctx, VD, spi, implicit, deprecated,
unavailablePlatformKind);
}
}
}
ExportContext ExportContext::forDeclSignature(Decl *D) {
auto &Ctx = D->getASTContext();
auto *DC = D->getInnermostDeclContext();
auto fragileKind = DC->getFragileFunctionKind();
auto runningOSVersion =
(Ctx.LangOpts.DisableAvailabilityChecking
? AvailabilityContext::alwaysAvailable()
: TypeChecker::overApproximateAvailabilityAtLocation(D->getLoc(), DC));
bool spi = Ctx.LangOpts.LibraryLevel == LibraryLevel::SPI;
bool implicit = false;
bool deprecated = false;
std::optional<PlatformKind> unavailablePlatformKind;
computeExportContextBits(Ctx, D, &spi, &implicit, &deprecated,
&unavailablePlatformKind);
forEachOuterDecl(D->getDeclContext(),
[&](Decl *D) {
computeExportContextBits(Ctx, D,
&spi, &implicit, &deprecated,
&unavailablePlatformKind);
});
bool exported = ::isExported(D);
return ExportContext(DC, runningOSVersion, fragileKind,
spi, exported, implicit, deprecated,
unavailablePlatformKind);
}
ExportContext ExportContext::forFunctionBody(DeclContext *DC, SourceLoc loc) {
auto &Ctx = DC->getASTContext();
auto fragileKind = DC->getFragileFunctionKind();
auto runningOSVersion =
(Ctx.LangOpts.DisableAvailabilityChecking
? AvailabilityContext::alwaysAvailable()
: TypeChecker::overApproximateAvailabilityAtLocation(loc, DC));
bool spi = Ctx.LangOpts.LibraryLevel == LibraryLevel::SPI;
bool implicit = false;
bool deprecated = false;
std::optional<PlatformKind> unavailablePlatformKind;
forEachOuterDecl(DC,
[&](Decl *D) {
computeExportContextBits(Ctx, D,
&spi, &implicit, &deprecated,
&unavailablePlatformKind);
});
bool exported = false;
return ExportContext(DC, runningOSVersion, fragileKind,
spi, exported, implicit, deprecated,
unavailablePlatformKind);
}
ExportContext ExportContext::forConformance(DeclContext *DC,
ProtocolDecl *proto) {
assert(isa<ExtensionDecl>(DC) || isa<NominalTypeDecl>(DC));
auto where = forDeclSignature(DC->getInnermostDeclarationDeclContext());
where.Exported &= proto->getFormalAccessScope(
DC, /*usableFromInlineAsPublic*/true).isPublic();
return where;
}
ExportContext ExportContext::withReason(ExportabilityReason reason) const {
auto copy = *this;
copy.Reason = unsigned(reason);
return copy;
}
ExportContext ExportContext::withExported(bool exported) const {
auto copy = *this;
copy.Exported = isExported() && exported;
return copy;
}
std::optional<PlatformKind> ExportContext::getUnavailablePlatformKind() const {
if (Unavailable)
return PlatformKind(Platform);
return std::nullopt;
}
bool ExportContext::mustOnlyReferenceExportedDecls() const {
return Exported || FragileKind.kind != FragileFunctionKind::None;
}
std::optional<ExportabilityReason>
ExportContext::getExportabilityReason() const {
if (Exported)
return ExportabilityReason(Reason);
return std::nullopt;
}
/// Returns the first availability attribute on the declaration that is active
/// on the target platform.
static const AvailableAttr *getActiveAvailableAttribute(const Decl *D,
ASTContext &AC) {
D = abstractSyntaxDeclForAvailableAttribute(D);
for (auto Attr : D->getAttrs())
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (!AvAttr->isInvalid() && AvAttr->isActivePlatform(AC)) {
return AvAttr;
}
}
return nullptr;
}
/// Returns true if there is any availability attribute on the declaration
/// that is active on the target platform.
static bool hasActiveAvailableAttribute(Decl *D,
ASTContext &AC) {
return getActiveAvailableAttribute(D, AC);
}
static bool computeContainedByDeploymentTarget(TypeRefinementContext *TRC,
ASTContext &ctx) {
return TRC->getAvailabilityInfo()
.isContainedIn(AvailabilityContext::forDeploymentTarget(ctx));
}
/// Returns true if the reference or any of its parents is an
/// unconditional unavailable declaration for the same platform.
static bool isInsideCompatibleUnavailableDeclaration(
const Decl *D, const ExportContext &where, const AvailableAttr *attr) {
auto referencedPlatform = where.getUnavailablePlatformKind();
if (!referencedPlatform)
return false;
if (!attr->isUnconditionallyUnavailable()) {
return false;
}
// Unless in embedded Swift mode, refuse calling unavailable functions from
// unavailable code, but allow the use of types.
PlatformKind platform = attr->Platform;
if (!D->getASTContext().LangOpts.hasFeature(Feature::Embedded)) {
if (platform == PlatformKind::none && !isa<TypeDecl>(D) &&
!isa<ExtensionDecl>(D)) {
return false;
}
}
return (*referencedPlatform == platform ||
inheritsAvailabilityFromPlatform(platform, *referencedPlatform));
}
static bool shouldAllowReferenceToUnavailableInSwiftDeclaration(
const Decl *D, const ExportContext &where) {
auto *DC = where.getDeclContext();
auto *SF = DC->getParentSourceFile();
// Unavailable-in-Swift declarations shouldn't be referenced directly in
// source. However, they can be referenced in implicit declarations that are
// printed in .swiftinterfaces.
if (!SF || SF->Kind != SourceFileKind::Interface)
return false;
if (auto constructor = dyn_cast_or_null<ConstructorDecl>(DC->getAsDecl())) {
// Designated initializers inherited from an Obj-C superclass may have
// parameters that are unavailable-in-Swift.
if (constructor->isObjC())
return true;
}
return false;
}
// Utility function to help determine if noasync diagnostics are still
// appropriate even if a `DeclContext` returns `false` from `isAsyncContext()`.
static bool shouldTreatDeclContextAsAsyncForDiagnostics(const DeclContext *DC) {
if (auto *D = DC->getAsDecl())
if (auto *FD = dyn_cast<FuncDecl>(D))
if (FD->isDeferBody())
// If this is a defer body, we should delegate to its parent.
return shouldTreatDeclContextAsAsyncForDiagnostics(DC->getParent());
return DC->isAsyncContext();
}
namespace {
/// A class to walk the AST to build the type refinement context hierarchy.
class TypeRefinementContextBuilder : private ASTWalker {
ASTContext &Context;
/// Represents an entry in a stack of active type refinement contexts. The
/// stack is used to facilitate building the TRC's tree structure. A new TRC
/// is pushed onto this stack before visiting children whenever the current
/// AST node requires a new context and the TRC is then popped
/// post-visitation.
struct ContextInfo {
TypeRefinementContext *TRC;
/// The AST node. This node can be null (ParentTy()),
/// indicating that custom logic elsewhere will handle removing
/// the context when needed.
ParentTy ScopeNode;
bool ContainedByDeploymentTarget;
};
std::vector<ContextInfo> ContextStack;
/// Represents an entry in a stack of pending decl body type refinement
/// contexts. TRCs in this stack should be pushed onto \p ContextStack when
/// \p BodyStmt is encountered.
struct DeclBodyContextInfo {
Decl *Decl;
llvm::DenseMap<ASTNode, TypeRefinementContext *> BodyTRCs;
};
std::vector<DeclBodyContextInfo> DeclBodyContextStack;
TypeRefinementContext *getCurrentTRC() {
return ContextStack.back().TRC;
}
bool isCurrentTRCContainedByDeploymentTarget() {
return ContextStack.back().ContainedByDeploymentTarget;
}
void pushContext(TypeRefinementContext *TRC, ParentTy PopAfterNode) {
ContextInfo Info;
Info.TRC = TRC;
Info.ScopeNode = PopAfterNode;
if (!ContextStack.empty() && isCurrentTRCContainedByDeploymentTarget()) {
assert(computeContainedByDeploymentTarget(TRC, Context) &&
"incorrectly skipping computeContainedByDeploymentTarget()");
Info.ContainedByDeploymentTarget = true;
} else {
Info.ContainedByDeploymentTarget =
computeContainedByDeploymentTarget(TRC, Context);
}
ContextStack.push_back(Info);
}
void pushDeclBodyContext(
Decl *D, llvm::SmallVector<std::pair<ASTNode, TypeRefinementContext *>, 4>
NodesAndTRCs) {
DeclBodyContextInfo Info;
Info.Decl = D;
for (auto NodeAndTRC : NodesAndTRCs) {
Info.BodyTRCs.insert(NodeAndTRC);
}
DeclBodyContextStack.push_back(Info);
}
const char *stackTraceAction() const {
return "building type refinement context for";
}
friend class swift::ExpandChildTypeRefinementContextsRequest;
public:
TypeRefinementContextBuilder(TypeRefinementContext *TRC, ASTContext &Context)
: Context(Context) {
assert(TRC);
pushContext(TRC, ParentTy());
}
void build(Decl *D) {
PrettyStackTraceDecl trace(stackTraceAction(), D);
unsigned StackHeight = ContextStack.size();
D->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
void build(Stmt *S) {
PrettyStackTraceStmt trace(Context, stackTraceAction(), S);
unsigned StackHeight = ContextStack.size();
S->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
void build(Expr *E) {
PrettyStackTraceExpr trace(Context, stackTraceAction(), E);
unsigned StackHeight = ContextStack.size();
E->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
private:
MacroWalking getMacroWalkingBehavior() const override {
// Expansion buffers will have their type refinement contexts built lazily.
return MacroWalking::Arguments;
}
PreWalkAction walkToDeclPre(Decl *D) override {
PrettyStackTraceDecl trace(stackTraceAction(), D);
// Implicit decls don't have source locations so they cannot have a TRC.
if (D->isImplicit())
return Action::Continue();
// The AST of this decl may not be ready to traverse yet if it hasn't been
// full typechecked. If that's the case, we leave a placeholder node in the
// tree to indicate that the subtree should be expanded lazily when it
// needs to be traversed.
if (buildLazyContextForDecl(D))
return Action::SkipNode();
// Adds in a TRC that covers the entire declaration.
if (auto DeclTRC = getNewContextForSignatureOfDecl(D)) {
pushContext(DeclTRC, D);
}
// Create TRCs that cover only the body of the declaration.
buildContextsForBodyOfDecl(D);
return Action::Continue();
}
PostWalkAction walkToDeclPost(Decl *D) override {
while (ContextStack.back().ScopeNode.getAsDecl() == D) {
ContextStack.pop_back();
}
while (!DeclBodyContextStack.empty() &&
DeclBodyContextStack.back().Decl == D) {
// All pending body TRCs should have been consumed.
assert(DeclBodyContextStack.back().BodyTRCs.empty());
DeclBodyContextStack.pop_back();
}
return Action::Continue();
}
bool shouldBuildLazyContextForDecl(Decl *D) {
// Skip functions that have unparsed bodies on an initial descent to avoid
// eagerly parsing bodies unnecessarily.
if (auto *afd = dyn_cast<AbstractFunctionDecl>(D)) {
if (afd->hasBody() && !afd->isBodySkipped() &&
!afd->getBody(/*canSynthesize=*/false))
return true;
}
// Pattern binding declarations may have attached property wrappers that
// get expanded from macros attached to the parent declaration. We must
// not eagerly expand the attached property wrappers to avoid request
// cycles.
if (isa<PatternBindingDecl>(D)) {
return true;
}
if (isa<ExtensionDecl>(D)) {
return true;
}
return false;
}
/// For declarations that were previously skipped prepare the AST before
/// building out TRCs.
void prepareDeclForLazyExpansion(Decl *D) {
if (auto AFD = dyn_cast<AbstractFunctionDecl>(D)) {
(void)AFD->getBody(/*canSynthesize*/ true);
}
}
/// Constructs a placeholder TRC node that should be expanded later. This is
/// useful for postponing unnecessary work (and request triggers) when
/// initally building out the TRC subtree under a declaration. Lazy nodes
/// constructed here will be expanded by
/// ExpandChildTypeRefinementContextsRequest. Returns true if a node was
/// created.
bool buildLazyContextForDecl(Decl *D) {
// Check whether the current TRC is already a lazy placeholder. If it is,
// we should try to expand it rather than creating a new placeholder.
auto currentTRC = getCurrentTRC();
if (currentTRC->getNeedsExpansion() && currentTRC->getDeclOrNull() == D)
return false;
if (!shouldBuildLazyContextForDecl(D))
return false;
// If we've made it this far then we've identified a declaration that
// requires lazy expansion later.
auto lazyTRC = TypeRefinementContext::createForDeclImplicit(
Context, D, currentTRC, currentTRC->getAvailabilityInfo(),
refinementSourceRangeForDecl(D));
lazyTRC->setNeedsExpansion(true);
return true;
}
/// Returns a new context to be introduced for the declaration, or nullptr
/// if no new context should be introduced.
TypeRefinementContext *getNewContextForSignatureOfDecl(Decl *D) {
if (!isa<ValueDecl>(D) &&
!isa<ExtensionDecl>(D) &&
!isa<MacroExpansionDecl>(D) &&
!isa<PatternBindingDecl>(D))
return nullptr;
// Only introduce for an AbstractStorageDecl if it is not local. We
// introduce for the non-local case because these may have getters and
// setters (and these may be synthesized, so they might not even exist yet).
if (isa<AbstractStorageDecl>(D) && D->getDeclContext()->isLocalContext())
return nullptr;
// Don't introduce for variable declarations that have a parent pattern
// binding; all of the relevant information is on the pattern binding.
if (auto var = dyn_cast<VarDecl>(D)) {
if (var->getParentPatternBinding())
return nullptr;
}
// Declarations with an explicit availability attribute always get a TRC.
if (hasActiveAvailableAttribute(D, Context)) {
AvailabilityContext DeclaredAvailability =
swift::AvailabilityInference::availableRange(D, Context);
return TypeRefinementContext::createForDecl(
Context, D, getCurrentTRC(),
getEffectiveAvailabilityForDeclSignature(D, DeclaredAvailability),
DeclaredAvailability, refinementSourceRangeForDecl(D));
}
// Declarations without explicit availability get a TRC if they are
// effectively less available than the surrounding context. For example, an
// internal property in a public struct can be effectively less available
// than the containing struct decl because the internal property will only
// be accessed by code running at the deployment target or later.
AvailabilityContext CurrentAvailability =
getCurrentTRC()->getAvailabilityInfo();
AvailabilityContext EffectiveAvailability =
getEffectiveAvailabilityForDeclSignature(D, CurrentAvailability);
if (CurrentAvailability.isSupersetOf(EffectiveAvailability))
return TypeRefinementContext::createForDeclImplicit(
Context, D, getCurrentTRC(), EffectiveAvailability,
refinementSourceRangeForDecl(D));
return nullptr;
}
AvailabilityContext getEffectiveAvailabilityForDeclSignature(
Decl *D, const AvailabilityContext BaseAvailability) {
AvailabilityContext EffectiveAvailability = BaseAvailability;
// As a special case, extension decls are treated as effectively as
// available as the nominal type they extend, up to the deployment target.
// This rule is a convenience for library authors who have written
// extensions without specifying availabilty on the extension itself.
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
auto ET = ED->getExtendedType();
if (ET && !hasActiveAvailableAttribute(D, Context)) {
EffectiveAvailability.intersectWith(
swift::AvailabilityInference::inferForType(ET));
// We want to require availability to be specified on extensions of
// types that would be potentially unavailable to the module containing
// the extension, so limit the effective availability to the deployment
// target.
EffectiveAvailability.unionWith(
AvailabilityContext::forDeploymentTarget(Context));
}
}
EffectiveAvailability.intersectWith(getCurrentTRC()->getAvailabilityInfo());
if (shouldConstrainSignatureToDeploymentTarget(D))
EffectiveAvailability.intersectWith(
AvailabilityContext::forDeploymentTarget(Context));
return EffectiveAvailability;
}
/// Checks whether the entire declaration, including its signature, should be
/// constrained to the deployment target. Generally public API declarations
/// are not constrained since they appear in the interface of the module and
/// may be consumed by clients with lower deployment targets, but there are
/// some exceptions.
bool shouldConstrainSignatureToDeploymentTarget(Decl *D) {
if (isCurrentTRCContainedByDeploymentTarget())
return false;
// A declaration inside of a local context always inherits the availability
// of the parent.
if (D->getDeclContext()->isLocalContext())
return false;
// As a convenience, SPI decls and explicitly unavailable decls are
// constrained to the deployment target. There's not much benefit to
// checking these declarations at a lower availability version floor since
// neither can be used by API clients.
if (D->isSPI() || D->getSemanticUnavailableAttr())
return true;
return !::isExported(D);
}
/// Returns the source range which should be refined by declaration. This
/// provides a convenient place to specify the refined range when it is
/// different than the declaration's source range.
SourceRange refinementSourceRangeForDecl(Decl *D) {
// We require a valid range in order to be able to query for the TRC
// corresponding to a given SourceLoc.
// If this assert fires, it means we have probably synthesized an implicit
// declaration without location information. The appropriate fix is
// probably to gin up a source range for the declaration when synthesizing
// it.
assert(D->getSourceRange().isValid());
if (auto *storageDecl = dyn_cast<AbstractStorageDecl>(D)) {
// Use the declaration's availability for the context when checking
// the bodies of its accessors.
SourceRange Range = storageDecl->getSourceRange();
// HACK: For synthesized trivial accessors we may have not a valid
// location for the end of the braces, so in that case we will fall back
// to using the range for the storage declaration. The right fix here is
// to update AbstractStorageDecl::addTrivialAccessors() to take brace
// locations and have callers of that method provide appropriate source
// locations.
SourceRange BracesRange = storageDecl->getBracesRange();
if (BracesRange.isValid()) {
Range.widen(BracesRange);
}
return Range;
}
return D->getSourceRangeIncludingAttrs();
}
// Creates an implicit decl TRC specifying the deployment
// target for `range` in decl `D`.
TypeRefinementContext *
createImplicitDeclContextForDeploymentTarget(Decl *D, SourceRange range){
AvailabilityContext Availability =
AvailabilityContext::forDeploymentTarget(Context);
Availability.intersectWith(getCurrentTRC()->getAvailabilityInfo());
return TypeRefinementContext::createForDeclImplicit(
Context, D, getCurrentTRC(), Availability, range);
}
void buildContextsForBodyOfDecl(Decl *D) {
// Are we already constrained by the deployment target? If not, adding
// new contexts won't change availability.
if (isCurrentTRCContainedByDeploymentTarget())
return;
// Top level code always uses the deployment target.
if (auto tlcd = dyn_cast<TopLevelCodeDecl>(D)) {
if (auto bodyStmt = tlcd->getBody()) {
pushDeclBodyContext(
tlcd, {{bodyStmt, createImplicitDeclContextForDeploymentTarget(
tlcd, tlcd->getSourceRange())}});
}
return;
}
// Function bodies use the deployment target if they are within the module's
// resilience domain.
if (auto afd = dyn_cast<AbstractFunctionDecl>(D)) {
if (!afd->isImplicit() &&
afd->getResilienceExpansion() != ResilienceExpansion::Minimal) {
if (auto body = afd->getBody(/*canSynthesize*/ false)) {
pushDeclBodyContext(
afd, {{body, createImplicitDeclContextForDeploymentTarget(
afd, afd->getBodySourceRange())}});
}
}
return;
}
// Pattern binding declarations can have children corresponding to property
// wrappers and the initial values provided in each pattern binding entry
if (auto *pbd = dyn_cast<PatternBindingDecl>(D)) {
llvm::SmallVector<std::pair<ASTNode, TypeRefinementContext *>, 4>
nodesAndTRCs;
for (unsigned index : range(pbd->getNumPatternEntries())) {
auto var = pbd->getAnchoringVarDecl(index);
if (!var)
continue;
// Var decls may have associated pattern binding decls or property
// wrappers with init expressions. Those expressions need to be
// constrained to the deployment target unless they are exposed to
// clients.
if (!var->hasInitialValue() || var->isInitExposedToClients())
continue;
auto *initExpr = pbd->getInit(index);
if (initExpr && !initExpr->isImplicit()) {
assert(initExpr->getSourceRange().isValid());
// Create a TRC for the init written in the source.
nodesAndTRCs.push_back(
{initExpr, createImplicitDeclContextForDeploymentTarget(
var, initExpr->getSourceRange())});
}
}
if (nodesAndTRCs.size() > 0)
pushDeclBodyContext(pbd, nodesAndTRCs);
// Ideally any init expression would be returned by `getInit()` above.
// However, for property wrappers it doesn't get populated until
// typechecking completes (which is too late). Instead, we find the
// the property wrapper attribute and use its source range to create a
// TRC for the initializer expression.
//
// FIXME: Since we don't have an expression here, we can't build out its
// TRC. If the Expr that will eventually be created contains a closure
// expression, then it might have AST nodes that need to be refined. For
// example, property wrapper initializers that takes block arguments
// are not handled correctly because of this (rdar://77841331).
if (auto firstVar = pbd->getAnchoringVarDecl(0)) {
if (firstVar->hasInitialValue() &&
!firstVar->isInitExposedToClients()) {
for (auto *wrapper : firstVar->getAttachedPropertyWrappers()) {
createImplicitDeclContextForDeploymentTarget(firstVar,
wrapper->getRange());
}
}
}
return;
}
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
PrettyStackTraceStmt trace(Context, stackTraceAction(), S);
if (consumeDeclBodyContextIfNecessary(S)) {
return Action::Continue(S);
}
if (auto *IS = dyn_cast<IfStmt>(S)) {
buildIfStmtRefinementContext(IS);
return Action::SkipNode(S);
}
if (auto *RS = dyn_cast<GuardStmt>(S)) {
buildGuardStmtRefinementContext(RS);
return Action::SkipNode(S);
}
if (auto *WS = dyn_cast<WhileStmt>(S)) {
buildWhileStmtRefinementContext(WS);
return Action::SkipNode(S);
}
return Action::Continue(S);
}
PostWalkResult<Stmt *> walkToStmtPost(Stmt *S) override {
// If we have multiple guard statements in the same block
// then we may have multiple refinement contexts to pop
// after walking that block.
while (!ContextStack.empty() &&
ContextStack.back().ScopeNode.getAsStmt() == S) {
ContextStack.pop_back();
}
return Action::Continue(S);
}
/// Attempts to consume a TRC from the `BodyTRCs` of the top of
/// `DeclBodyContextStack`. Returns \p true if a context was pushed.
template <typename T>
bool consumeDeclBodyContextIfNecessary(T Body) {
if (DeclBodyContextStack.empty())
return false;
auto &Info = DeclBodyContextStack.back();
auto Iter = Info.BodyTRCs.find(Body);
if (Iter == Info.BodyTRCs.end())
return false;
pushContext(Iter->getSecond(), Body);
Info.BodyTRCs.erase(Iter);
return true;
}
/// Builds the type refinement hierarchy for the IfStmt if the guard
/// introduces a new refinement context for the Then branch.
/// There is no need for the caller to explicitly traverse the children
/// of this node.
void buildIfStmtRefinementContext(IfStmt *IS) {
std::optional<AvailabilityContext> ThenRange;
std::optional<AvailabilityContext> ElseRange;
std::tie(ThenRange, ElseRange) =
buildStmtConditionRefinementContext(IS->getCond());
if (ThenRange.has_value()) {
// Create a new context for the Then branch and traverse it in that new
// context.
auto *ThenTRC =
TypeRefinementContext::createForIfStmtThen(Context, IS,
getCurrentTRC(),
ThenRange.value());
TypeRefinementContextBuilder(ThenTRC, Context).build(IS->getThenStmt());
} else {
build(IS->getThenStmt());
}
Stmt *ElseStmt = IS->getElseStmt();
if (!ElseStmt)
return;
// Refine the else branch if we're given a version range for that branch.
// For now, if present, this will only be the empty range, indicating
// that the branch is dead. We use it to suppress potential unavailability
// and deprecation diagnostics on code that definitely will not run with
// the current platform and minimum deployment target.
// If we add a more precise version range lattice (i.e., one that can
// support "<") we should create non-empty contexts for the Else branch.
if (ElseRange.has_value()) {
// Create a new context for the Then branch and traverse it in that new
// context.
auto *ElseTRC =
TypeRefinementContext::createForIfStmtElse(Context, IS,
getCurrentTRC(),
ElseRange.value());
TypeRefinementContextBuilder(ElseTRC, Context).build(ElseStmt);
} else {
build(IS->getElseStmt());
}
}
/// Builds the type refinement hierarchy for the WhileStmt if the guard
/// introduces a new refinement context for the body branch.
/// There is no need for the caller to explicitly traverse the children
/// of this node.
void buildWhileStmtRefinementContext(WhileStmt *WS) {
std::optional<AvailabilityContext> BodyRange =
buildStmtConditionRefinementContext(WS->getCond()).first;
if (BodyRange.has_value()) {
// Create a new context for the body and traverse it in the new
// context.
auto *BodyTRC = TypeRefinementContext::createForWhileStmtBody(
Context, WS, getCurrentTRC(), BodyRange.value());
TypeRefinementContextBuilder(BodyTRC, Context).build(WS->getBody());
} else {
build(WS->getBody());
}
}
/// Builds the type refinement hierarchy for the GuardStmt and pushes
/// the fallthrough context onto the context stack so that subsequent
/// AST elements in the same scope are analyzed in the context of the
/// fallthrough TRC.
void buildGuardStmtRefinementContext(GuardStmt *GS) {
// 'guard' statements fall through if all of the
// guard conditions are true, so we refine the range after the require
// until the end of the enclosing block.
// if ... {
// guard available(...) else { return } <-- Refined range starts here
// ...
// } <-- Refined range ends here
//
// This is slightly tricky because, unlike our other control constructs,
// the refined region is not lexically contained inside the construct
// introducing the refinement context.
std::optional<AvailabilityContext> FallthroughRange;
std::optional<AvailabilityContext> ElseRange;
std::tie(FallthroughRange, ElseRange) =
buildStmtConditionRefinementContext(GS->getCond());
if (Stmt *ElseBody = GS->getBody()) {
if (ElseRange.has_value()) {
auto *TrueTRC = TypeRefinementContext::createForGuardStmtElse(
Context, GS, getCurrentTRC(), ElseRange.value());
TypeRefinementContextBuilder(TrueTRC, Context).build(ElseBody);
} else {
build(ElseBody);
}
}
auto *ParentBrace = dyn_cast<BraceStmt>(Parent.getAsStmt());
assert(ParentBrace && "Expected parent of GuardStmt to be BraceStmt");
if (!FallthroughRange.has_value())
return;
// Create a new context for the fallthrough.
auto *FallthroughTRC =
TypeRefinementContext::createForGuardStmtFallthrough(Context, GS,
ParentBrace, getCurrentTRC(), FallthroughRange.value());
pushContext(FallthroughTRC, ParentBrace);
}
/// Build the type refinement context for a StmtCondition and return a pair
/// of optional version ranges, the first for the true branch and the second
/// for the false branch. A value of None for a given branch indicates that
/// the branch does not introduce a new refinement.
std::pair<std::optional<AvailabilityContext>,
std::optional<AvailabilityContext>>
buildStmtConditionRefinementContext(StmtCondition Cond) {
// Any refinement contexts introduced in the statement condition
// will end at the end of the last condition element.
StmtConditionElement LastElement = Cond.back();
// Keep track of how many nested refinement contexts we have pushed on
// the context stack so we can pop them when we're done building the
// context for the StmtCondition.
unsigned NestedCount = 0;
// Tracks the potential version range when the condition is false.
auto FalseFlow = AvailabilityContext::neverAvailable();
TypeRefinementContext *StartingTRC = getCurrentTRC();
// Tracks if we're refining for availability or unavailability.
std::optional<bool> isUnavailability = std::nullopt;
for (StmtConditionElement Element : Cond) {
TypeRefinementContext *CurrentTRC = getCurrentTRC();
AvailabilityContext CurrentInfo = CurrentTRC->getAvailabilityInfo();
AvailabilityContext CurrentExplicitInfo =
CurrentTRC->getExplicitAvailabilityInfo();
// If the element is not a condition, walk it in the current TRC.
if (Element.getKind() != StmtConditionElement::CK_Availability) {
// Assume any condition element that is not a #available() can
// potentially be false, so conservatively combine the version
// range of the current context with the accumulated false flow
// of all other conjuncts.
FalseFlow.unionWith(CurrentInfo);
Element.walk(*this);
continue;
}
// #available query: introduce a new refinement context for the statement
// condition elements following it.
auto *Query = Element.getAvailability();
if (isUnavailability == std::nullopt) {
isUnavailability = Query->isUnavailability();
} else if (isUnavailability != Query->isUnavailability()) {
// Mixing availability with unavailability in the same statement will
// cause the false flow's version range to be ambiguous. Report it.
//
// Technically we can support this by not refining ambiguous flows,
// but there are currently no legitimate cases where one would have
// to mix availability with unavailability.
Context.Diags.diagnose(Query->getLoc(),
diag::availability_cannot_be_mixed);
break;
}
// If this query expression has no queries, we will not introduce a new
// refinement context. We do not diagnose here: a diagnostic will already
// have been emitted by the parser.
// For #unavailable, empty queries are valid as wildcards are implied.
if (!Query->isUnavailability() && Query->getQueries().empty())
continue;
AvailabilitySpec *Spec = bestActiveSpecForQuery(Query);
if (!Spec) {
// We couldn't find an appropriate spec for the current platform,
// so rather than refining, emit a diagnostic and just use the current
// TRC.
Context.Diags.diagnose(
Query->getLoc(), diag::availability_query_required_for_platform,
platformString(targetPlatform(Context.LangOpts)));
continue;
}
AvailabilityContext NewConstraint = contextForSpec(Spec, false);
Query->setAvailableRange(contextForSpec(Spec, true).getOSVersion());
// When compiling zippered for macCatalyst, we need to collect both
// a macOS version (the target version) and an iOS/macCatalyst version
// (the target-variant). These versions will both be passed to a runtime
// entrypoint that will check either the macOS version or the iOS
// version depending on the kind of process this code is loaded into.
if (Context.LangOpts.TargetVariant) {
AvailabilitySpec *VariantSpec =
bestActiveSpecForQuery(Query, /*ForTargetVariant*/ true);
VersionRange VariantRange =
contextForSpec(VariantSpec, true).getOSVersion();
Query->setVariantAvailableRange(VariantRange);
}
if (Spec->getKind() == AvailabilitySpecKind::OtherPlatform) {
// The wildcard spec '*' represents the minimum deployment target, so
// there is no need to create a refinement context for this query.
// Further, we won't diagnose for useless #available() conditions
// where * matched on this platform -- presumably those conditions are
// needed for some other platform.
continue;
}
// If the explicitly-specified (via #availability) version range for the
// current TRC is completely contained in the range for the spec, then
// a version query can never be false, so the spec is useless.
// If so, report this.
if (CurrentExplicitInfo.isContainedIn(NewConstraint)) {
// Unavailability refinements are always "useless" from a symbol
// availability point of view, so only useless availability specs are
// reported.
if (isUnavailability.value()) {
continue;
}
DiagnosticEngine &Diags = Context.Diags;
if (CurrentTRC->getReason() != TypeRefinementContext::Reason::Root) {
PlatformKind BestPlatform = targetPlatform(Context.LangOpts);
auto *PlatformSpec =
dyn_cast<PlatformVersionConstraintAvailabilitySpec>(Spec);
// If possible, try to report the diagnostic in terms for the
// platform the user uttered in the '#available()'. For a platform
// that inherits availability from another platform it may be
// different from the platform specified in the target triple.
if (PlatformSpec)
BestPlatform = PlatformSpec->getPlatform();
Diags.diagnose(Query->getLoc(),
diag::availability_query_useless_enclosing_scope,
platformString(BestPlatform));
Diags.diagnose(CurrentTRC->getIntroductionLoc(),
diag::availability_query_useless_enclosing_scope_here);
}
}
if (CurrentInfo.isContainedIn(NewConstraint)) {
// No need to actually create the refinement context if we know it is
// useless.
continue;
}
// If the #available() is not useless then there is potential false flow,
// so join the false flow with the potential versions of the current
// context.
// We could be more precise here if we enriched the lattice to include
// ranges of the form [x, y).
FalseFlow.unionWith(CurrentInfo);
auto *TRC = TypeRefinementContext::createForConditionFollowingQuery(
Context, Query, LastElement, CurrentTRC, NewConstraint);
pushContext(TRC, ParentTy());
++NestedCount;
}
std::optional<AvailabilityContext> FalseRefinement = std::nullopt;
// The version range for the false branch should never have any versions
// that weren't possible when the condition started evaluating.
assert(FalseFlow.isContainedIn(StartingTRC->getAvailabilityInfo()));
// If the starting version range is not completely contained in the
// false flow version range then it must be the case that false flow range
// is strictly smaller than the starting range (because the false flow
// range *is* contained in the starting range), so we should introduce a
// new refinement for the false flow.
if (!StartingTRC->getAvailabilityInfo().isContainedIn(FalseFlow)) {
FalseRefinement = FalseFlow;
}
auto makeResult =
[isUnavailability](std::optional<AvailabilityContext> TrueRefinement,
std::optional<AvailabilityContext> FalseRefinement) {
if (isUnavailability.has_value() && isUnavailability.value()) {
// If this is an unavailability check, invert the result.
return std::make_pair(FalseRefinement, TrueRefinement);
}
return std::make_pair(TrueRefinement, FalseRefinement);
};
if (NestedCount == 0)
return makeResult(std::nullopt, FalseRefinement);
TypeRefinementContext *NestedTRC = getCurrentTRC();
while (NestedCount-- > 0)
ContextStack.pop_back();
assert(getCurrentTRC() == StartingTRC);
return makeResult(NestedTRC->getAvailabilityInfo(), FalseRefinement);
}
/// Return the best active spec for the target platform or nullptr if no
/// such spec exists.
AvailabilitySpec *bestActiveSpecForQuery(PoundAvailableInfo *available,
bool forTargetVariant = false) {
OtherPlatformAvailabilitySpec *FoundOtherSpec = nullptr;
PlatformVersionConstraintAvailabilitySpec *BestSpec = nullptr;
for (auto *Spec : available->getQueries()) {
if (auto *OtherSpec = dyn_cast<OtherPlatformAvailabilitySpec>(Spec)) {
FoundOtherSpec = OtherSpec;
continue;
}
auto *VersionSpec =
dyn_cast<PlatformVersionConstraintAvailabilitySpec>(Spec);
if (!VersionSpec)
continue;
// FIXME: This is not quite right: we want to handle AppExtensions
// properly. For example, on the OSXApplicationExtension platform
// we want to chose the OS X spec unless there is an explicit
// OSXApplicationExtension spec.
if (isPlatformActive(VersionSpec->getPlatform(), Context.LangOpts,
forTargetVariant, /* ForRuntimeQuery */ true)) {
if (!BestSpec ||
inheritsAvailabilityFromPlatform(VersionSpec->getPlatform(),
BestSpec->getPlatform())) {
BestSpec = VersionSpec;
}
}
}
if (BestSpec)
return BestSpec;
// If we have reached this point, we found no spec for our target, so
// we return the other spec ('*'), if we found it, or nullptr, if not.
if (FoundOtherSpec) {
return FoundOtherSpec;
} else if (available->isUnavailability()) {
// For #unavailable, imply the presence of a wildcard.
SourceLoc Loc = available->getRParenLoc();
return new (Context) OtherPlatformAvailabilitySpec(Loc);
} else {
return nullptr;
}
}
/// Return the availability context for the given spec.
AvailabilityContext contextForSpec(AvailabilitySpec *Spec,
bool GetRuntimeContext) {
if (isa<OtherPlatformAvailabilitySpec>(Spec)) {
return AvailabilityContext::alwaysAvailable();
}
auto *VersionSpec = cast<PlatformVersionConstraintAvailabilitySpec>(Spec);
llvm::VersionTuple Version = (GetRuntimeContext ?
VersionSpec->getRuntimeVersion() :
VersionSpec->getVersion());
return AvailabilityContext(VersionRange::allGTE(Version));
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
(void)consumeDeclBodyContextIfNecessary(E);
return Action::Continue(E);
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
if (ContextStack.back().ScopeNode.getAsExpr() == E) {
ContextStack.pop_back();
}
return Action::Continue(E);
}
};
} // end anonymous namespace
void TypeChecker::buildTypeRefinementContextHierarchy(SourceFile &SF) {
TypeRefinementContext *RootTRC = SF.getTypeRefinementContext();
ASTContext &Context = SF.getASTContext();
assert(!Context.LangOpts.DisableAvailabilityChecking);
if (!RootTRC) {
// The root type refinement context reflects the fact that all parts of
// the source file are guaranteed to be executing on at least the minimum
// platform version for inlining.
auto MinPlatformReq = AvailabilityContext::forInliningTarget(Context);
RootTRC = TypeRefinementContext::createForSourceFile(&SF, MinPlatformReq);
SF.setTypeRefinementContext(RootTRC);
}
// Build refinement contexts, if necessary, for all declarations starting
// with StartElem.
TypeRefinementContextBuilder Builder(RootTRC, Context);
for (auto item : SF.getTopLevelItems()) {
if (auto decl = item.dyn_cast<Decl *>())
Builder.build(decl);
else if (auto expr = item.dyn_cast<Expr *>())
Builder.build(expr);
else if (auto stmt = item.dyn_cast<Stmt *>())
Builder.build(stmt);
}
}
TypeRefinementContext *
TypeChecker::getOrBuildTypeRefinementContext(SourceFile *SF) {
if (SF->getASTContext().LangOpts.DisableAvailabilityChecking)
return nullptr;
TypeRefinementContext *TRC = SF->getTypeRefinementContext();
if (!TRC) {
buildTypeRefinementContextHierarchy(*SF);
TRC = SF->getTypeRefinementContext();
}
return TRC;
}
std::vector<TypeRefinementContext *>
ExpandChildTypeRefinementContextsRequest::evaluate(
Evaluator &evaluator, TypeRefinementContext *parentTRC) const {
assert(parentTRC->getNeedsExpansion());
if (auto decl = parentTRC->getDeclOrNull()) {
ASTContext &ctx = decl->getASTContext();
TypeRefinementContextBuilder builder(parentTRC, ctx);
builder.prepareDeclForLazyExpansion(decl);
builder.build(decl);
}
return parentTRC->Children;
}
AvailabilityContext
TypeChecker::overApproximateAvailabilityAtLocation(SourceLoc loc,
const DeclContext *DC,
const TypeRefinementContext **MostRefined) {
SourceFile *SF;
if (loc.isValid())
SF = DC->getParentModule()->getSourceFileContainingLocation(loc);
else
SF = DC->getParentSourceFile();
auto &Context = DC->getASTContext();
// If our source location is invalid (this may be synthesized code), climb
// the decl context hierarchy until we find a location that is valid,
// collecting availability ranges on the way up.
// We will combine the version ranges from these annotations
// with the TRC for the valid location to overapproximate the running
// OS versions at the original source location.
// Because we are climbing DeclContexts we will miss refinement contexts in
// synthesized code that are introduced by AST elements that are themselves
// not DeclContexts, such as #available(..) and property declarations.
// That is, a reference with an invalid location that is contained
// inside a #available() and with no intermediate DeclContext will not be
// refined. For now, this is fine -- but if we ever synthesize #available(),
// this will be a real problem.
// We can assume we are running on at least the minimum inlining target.
auto OverApproximateContext = AvailabilityContext::forInliningTarget(Context);
auto isInvalidLoc = [SF](SourceLoc loc) {
return SF ? loc.isInvalid() : true;
};
while (DC && isInvalidLoc(loc)) {
const Decl *D = DC->getInnermostDeclarationDeclContext();
if (!D)
break;
loc = D->getLoc();
std::optional<AvailabilityContext> Info =
AvailabilityInference::annotatedAvailableRange(D, Context);
if (Info.has_value()) {
OverApproximateContext.constrainWith(Info.value());
}
DC = D->getDeclContext();
}
if (SF && loc.isValid()) {
TypeRefinementContext *rootTRC = getOrBuildTypeRefinementContext(SF);
if (rootTRC) {
TypeRefinementContext *TRC =
rootTRC->findMostRefinedSubContext(loc, Context);
OverApproximateContext.constrainWith(TRC->getAvailabilityInfo());
if (MostRefined) {
*MostRefined = TRC;
}
}
}
return OverApproximateContext;
}
bool TypeChecker::isDeclarationUnavailable(
const Decl *D, const DeclContext *referenceDC,
llvm::function_ref<AvailabilityContext()> getAvailabilityContext) {
ASTContext &Context = referenceDC->getASTContext();
if (Context.LangOpts.DisableAvailabilityChecking) {
return false;
}
if (!referenceDC->getParentSourceFile()) {
// We only check availability if this reference is in a source file; we do
// not check in other kinds of FileUnits.
return false;
}
AvailabilityContext safeRangeUnderApprox{
AvailabilityInference::availableRange(D, Context)};
if (safeRangeUnderApprox.isAlwaysAvailable())
return false;
AvailabilityContext runningOSOverApprox = getAvailabilityContext();
// The reference is safe if an over-approximation of the running OS
// versions is fully contained within an under-approximation
// of the versions on which the declaration is available. If this
// containment cannot be guaranteed, we say the reference is
// not available.
return !runningOSOverApprox.isContainedIn(safeRangeUnderApprox);
}
std::optional<UnavailabilityReason>
TypeChecker::checkDeclarationAvailability(const Decl *D,
const ExportContext &Where) {
// Skip computing potential unavailability if the declaration is explicitly
// unavailable and the context is also unavailable.
if (const AvailableAttr *Attr = AvailableAttr::isUnavailable(D))
if (isInsideCompatibleUnavailableDeclaration(D, Where, Attr))
return std::nullopt;
if (isDeclarationUnavailable(D, Where.getDeclContext(), [&Where] {
return Where.getAvailabilityContext();
})) {
auto &Context = Where.getDeclContext()->getASTContext();
AvailabilityContext safeRangeUnderApprox{
AvailabilityInference::availableRange(D, Context)};
VersionRange version = safeRangeUnderApprox.getOSVersion();
return UnavailabilityReason::requiresVersionRange(version);
}
return std::nullopt;
}
std::optional<UnavailabilityReason>
TypeChecker::checkConformanceAvailability(const RootProtocolConformance *conf,
const ExtensionDecl *ext,
const ExportContext &where) {
return checkDeclarationAvailability(ext, where);
}
/// A class that walks the AST to find the innermost (i.e., deepest) node that
/// contains a target SourceRange and matches a particular criterion.
/// This class finds the innermost nodes of interest by walking
/// down the root until it has found the target range (in a Pre-visitor)
/// and then recording the innermost node on the way back up in the
/// Post-visitors. It does its best to not search unnecessary subtrees,
/// although this is complicated by the fact that not all nodes have
/// source range information.
class InnermostAncestorFinder : private ASTWalker {
public:
/// The type of a match predicate, which takes as input a node and its
/// parent and returns a bool indicating whether the node matches.
using MatchPredicate = std::function<bool(ASTNode, ASTWalker::ParentTy)>;
private:
const SourceRange TargetRange;
const SourceManager &SM;
const MatchPredicate Predicate;
bool FoundTarget = false;
std::optional<ASTNode> InnermostMatchingNode;
public:
InnermostAncestorFinder(SourceRange TargetRange, const SourceManager &SM,
ASTNode SearchNode, const MatchPredicate &Predicate)
: TargetRange(TargetRange), SM(SM), Predicate(Predicate) {
assert(TargetRange.isValid());
SearchNode.walk(*this);
}
/// Returns the innermost node containing the target range that matches
/// the predicate.
std::optional<ASTNode> getInnermostMatchingNode() {
return InnermostMatchingNode;
}
MacroWalking getMacroWalkingBehavior() const override {
// This is SourceRange based finder. 'SM.rangeContains()' fails anyway when
// crossing source buffers.
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
return getPreWalkActionFor(E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
return getPreWalkActionFor(S);
}
PreWalkAction walkToDeclPre(Decl *D) override {
return getPreWalkActionFor(D).Action;
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *P) override {
return getPreWalkActionFor(P);
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
return getPreWalkActionFor(T).Action;
}
/// Retrieve the pre-walk action for a given node, which determines whether
/// or not it should be walked into.
template <typename T>
PreWalkResult<T> getPreWalkActionFor(T Node) {
// When walking down the tree, we traverse until we have found a node
// inside the target range. Once we have found such a node, there is no
// need to traverse any deeper.
if (FoundTarget)
return Action::SkipNode(Node);
// If we haven't found our target yet and the node we are pre-visiting
// doesn't have a valid range, we still have to traverse it because its
// subtrees may have valid ranges.
auto Range = Node->getSourceRange();
if (Range.isInvalid())
return Action::Continue(Node);
// We have found our target if the range of the node we are visiting
// is contained in the range we are looking for.
FoundTarget = SM.rangeContains(TargetRange, Range);
if (FoundTarget)
return Action::SkipNode(Node);
// Search the subtree if the target range is inside its range.
if (!SM.rangeContains(Range, TargetRange))
return Action::SkipNode(Node);
return Action::Continue(Node);
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
return walkToNodePost(E);
}
PostWalkResult<Stmt *> walkToStmtPost(Stmt *S) override {
return walkToNodePost(S);
}
PostWalkAction walkToDeclPost(Decl *D) override {
return walkToNodePost(D).Action;
}
/// Once we have found the target node, look for the innermost ancestor
/// matching our criteria on the way back up the spine of the tree.
template <typename T>
PostWalkResult<T> walkToNodePost(T Node) {
if (!InnermostMatchingNode.has_value() && Predicate(Node, Parent)) {
assert(Node->getSourceRange().isInvalid() ||
SM.rangeContains(Node->getSourceRange(), TargetRange));
InnermostMatchingNode = Node;
return Action::Stop();
}
return Action::Continue(Node);
}
};
/// Starting from SearchRoot, finds the innermost node containing ChildRange
/// for which Predicate returns true. Returns None if no such root is found.
static std::optional<ASTNode> findInnermostAncestor(
SourceRange ChildRange, const SourceManager &SM, ASTNode SearchRoot,
const InnermostAncestorFinder::MatchPredicate &Predicate) {
InnermostAncestorFinder Finder(ChildRange, SM, SearchRoot, Predicate);
return Finder.getInnermostMatchingNode();
}
/// Given a reference range and a declaration context containing the range,
/// attempt to find a declaration containing the reference. This may not
/// be the innermost declaration containing the range.
/// Returns null if no such declaration can be found.
static const Decl *findContainingDeclaration(SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
const SourceManager &SM) {
auto ContainsReferenceRange = [&](const Decl *D) -> bool {
if (ReferenceRange.isInvalid())
return false;
// Members of an active #if are represented both inside the
// IfConfigDecl and in the enclosing context. Skip over the IfConfigDecl
// so that the member declaration is found rather the #if itself.
if (isa<IfConfigDecl>(D))
return false;
return SM.rangeContains(D->getSourceRange(), ReferenceRange);
};
if (const Decl *D = ReferenceDC->getInnermostDeclarationDeclContext()) {
// If we have an inner declaration context, see if we can narrow the search
// down to one of its members. This is important for properties, which don't
// count as DeclContexts of their own but which can still introduce
// availability.
if (auto *IDC = dyn_cast<IterableDeclContext>(D)) {
auto BestMember = llvm::find_if(IDC->getMembers(),
ContainsReferenceRange);
if (BestMember != IDC->getMembers().end())
return *BestMember;
}
return D;
}
// We couldn't find a suitable node by climbing the DeclContext hierarchy, so
// fall back to looking for a top-level declaration that contains the
// reference range. We will hit this case for top-level elements that do not
// themselves introduce DeclContexts, such as global variables. If we don't
// have a reference range, there is nothing we can do, so return null.
if (ReferenceRange.isInvalid())
return nullptr;
SourceFile *SF = ReferenceDC->getParentSourceFile();
if (!SF)
return nullptr;
auto BestTopLevelDecl = llvm::find_if(SF->getTopLevelDecls(),
ContainsReferenceRange);
if (BestTopLevelDecl != SF->getTopLevelDecls().end())
return *BestTopLevelDecl;
return nullptr;
}
/// Given a declaration that allows availability attributes in the abstract
/// syntax tree, return the declaration upon which the declaration would
/// appear in concrete syntax. This function is necessary because for semantic
/// analysis, the parser attaches attributes to declarations other
/// than those on which they, concretely, appear. For these declarations (enum
/// cases and variable declarations) a Fix-It for an added availability
/// attribute should be suggested for the appropriate concrete location.
static const Decl *
concreteSyntaxDeclForAvailableAttribute(const Decl *AbstractSyntaxDecl) {
// This function needs to be kept in sync with its counterpart,
// abstractSyntaxDeclForAvailableAttribute().
// The source range for VarDecls does not include 'var ' (and, in any
// event, multiple variables can be introduced with a single 'var'),
// so suggest adding an attribute to the PatterningBindingDecl instead.
if (auto *VD = dyn_cast<VarDecl>(AbstractSyntaxDecl)) {
return VD->getParentPatternBinding();
}
// Similarly suggest applying the Fix-It to the parent enum case rather than
// the enum element.
if (auto *EE = dyn_cast<EnumElementDecl>(AbstractSyntaxDecl)) {
return EE->getParentCase();
}
return AbstractSyntaxDecl;
}
/// Given a declaration, return a better related declaration for which
/// to suggest an @available fixit, or the original declaration
/// if no such related declaration exists.
static const Decl *relatedDeclForAvailabilityFixit(const Decl *D) {
if (auto *accessor = dyn_cast<AccessorDecl>(D)) {
// Suggest @available Fix-Its on property rather than individual
// accessors.
D = accessor->getStorage();
}
return abstractSyntaxDeclForAvailableAttribute(D);
}
/// Walk the DeclContext hierarchy starting from D to find a declaration
/// at the member level (i.e., declared in a type context) on which to provide
/// an @available() Fix-It.
static const Decl *ancestorMemberLevelDeclForAvailabilityFixit(const Decl *D) {
while (D) {
D = relatedDeclForAvailabilityFixit(D);
if (!D->isImplicit() && D->getDeclContext()->isTypeContext() &&
DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind::Available, D)) {
break;
}
D = cast_or_null<AbstractFunctionDecl>(
D->getDeclContext()->getInnermostMethodContext());
}
return D;
}
/// Returns true if the declaration is at the type level (either a nominal
/// type, an extension, or a global function) and can support an @available
/// attribute.
static bool isTypeLevelDeclForAvailabilityFixit(const Decl *D) {
if (!DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind::Available, D)) {
return false;
}
if (isa<ExtensionDecl>(D) || isa<NominalTypeDecl>(D)) {
return true;
}
bool IsModuleScopeContext = D->getDeclContext()->isModuleScopeContext();
// We consider global functions to be "type level"
if (isa<FuncDecl>(D)) {
return IsModuleScopeContext;
}
if (auto *VD = dyn_cast<VarDecl>(D)) {
if (!IsModuleScopeContext)
return false;
if (PatternBindingDecl *PBD = VD->getParentPatternBinding()) {
return PBD->getDeclContext()->isModuleScopeContext();
}
}
return false;
}
/// Walk the DeclContext hierarchy starting from D to find a declaration
/// at a member level (i.e., declared in a type context) on which to provide an
/// @available() Fix-It.
static const Decl *ancestorTypeLevelDeclForAvailabilityFixit(const Decl *D) {
assert(D);
D = relatedDeclForAvailabilityFixit(D);
while (D && !isTypeLevelDeclForAvailabilityFixit(D)) {
D = D->getDeclContext()->getInnermostDeclarationDeclContext();
}
return D;
}
/// Given the range of a reference to an unavailable symbol and the
/// declaration context containing the reference, make a best effort find up to
/// three locations for potential fixits.
///
/// \param FoundVersionCheckNode Returns a node that can be wrapped in a
/// if #available(...) { ... } version check to fix the unavailable reference,
/// or None if such a node cannot be found.
///
/// \param FoundMemberLevelDecl Returns member-level declaration (i.e., the
/// child of a type DeclContext) for which an @available attribute would
/// fix the unavailable reference.
///
/// \param FoundTypeLevelDecl returns a type-level declaration (a
/// a nominal type, an extension, or a global function) for which an
/// @available attribute would fix the unavailable reference.
static void findAvailabilityFixItNodes(
SourceRange ReferenceRange, const DeclContext *ReferenceDC,
const SourceManager &SM, std::optional<ASTNode> &FoundVersionCheckNode,
const Decl *&FoundMemberLevelDecl, const Decl *&FoundTypeLevelDecl) {
FoundVersionCheckNode = std::nullopt;
FoundMemberLevelDecl = nullptr;
FoundTypeLevelDecl = nullptr;
// Limit tree to search based on the DeclContext of the reference.
const Decl *DeclarationToSearch =
findContainingDeclaration(ReferenceRange, ReferenceDC, SM);
if (!DeclarationToSearch)
return;
// Const-cast to inject into ASTNode. This search will not modify
// the declaration.
ASTNode SearchRoot = const_cast<Decl *>(DeclarationToSearch);
// The node to wrap in if #available(...) { ... } is the innermost node in
// SearchRoot that (1) can be guarded with an if statement and (2)
// contains the ReferenceRange.
// We make no guarantee that the Fix-It, when applied, will result in
// semantically valid code -- but, at a minimum, it should parse. So,
// for example, we may suggest wrapping a variable declaration in a guard,
// which would not be valid if the variable is later used. The goal
// is discoverability of #os() (via the diagnostic and Fix-It) rather than
// magically fixing the code in all cases.
InnermostAncestorFinder::MatchPredicate IsGuardable =
[](ASTNode Node, ASTWalker::ParentTy Parent) {
if (Expr *ParentExpr = Parent.getAsExpr()) {
auto *ParentClosure = dyn_cast<ClosureExpr>(ParentExpr);
if (!ParentClosure ||
ParentClosure->isSeparatelyTypeChecked()) {
return false;
}
} else if (auto *ParentStmt = Parent.getAsStmt()) {
if (!isa<BraceStmt>(ParentStmt)) {
return false;
}
} else {
return false;
}
return true;
};
FoundVersionCheckNode =
findInnermostAncestor(ReferenceRange, SM, SearchRoot, IsGuardable);
// Try to find declarations on which @available attributes can be added.
// The heuristics for finding these declarations are biased towards deeper
// nodes in the AST to limit the scope of suggested availability regions
// and provide a better IDE experience (it can get jumpy if Fix-It locations
// are far away from the error needing the Fix-It).
if (DeclarationToSearch) {
FoundMemberLevelDecl =
ancestorMemberLevelDeclForAvailabilityFixit(DeclarationToSearch);
FoundTypeLevelDecl =
ancestorTypeLevelDeclForAvailabilityFixit(DeclarationToSearch);
}
}
/// Emit a diagnostic note and Fix-It to add an @available attribute
/// on the given declaration for the given version range.
static void fixAvailabilityForDecl(SourceRange ReferenceRange, const Decl *D,
const VersionRange &RequiredRange,
ASTContext &Context) {
assert(D);
// Don't suggest adding an @available() to a declaration where we would
// emit a diagnostic saying it is not allowed.
if (TypeChecker::diagnosticIfDeclCannotBePotentiallyUnavailable(D).has_value())
return;
if (getActiveAvailableAttribute(D, Context)) {
// For QoI, in future should emit a fixit to update the existing attribute.
return;
}
// For some declarations (variables, enum elements), the location in concrete
// syntax to suggest the Fix-It may differ from the declaration to which
// we attach availability attributes in the abstract syntax tree during
// parsing.
const Decl *ConcDecl = concreteSyntaxDeclForAvailableAttribute(D);
DescriptiveDeclKind KindForDiagnostic = ConcDecl->getDescriptiveKind();
SourceLoc InsertLoc;
// To avoid exposing the pattern binding declaration to the user, get the
// descriptive kind from one of the VarDecls. We get the Fix-It location
// from the PatternBindingDecl unless the VarDecl has attributes,
// in which case we get the start location of the VarDecl attributes.
DeclAttributes AttrsForLoc;
if (KindForDiagnostic == DescriptiveDeclKind::PatternBinding) {
KindForDiagnostic = D->getDescriptiveKind();
AttrsForLoc = D->getAttrs();
} else {
InsertLoc = ConcDecl->getAttrs().getStartLoc(/*forModifiers=*/false);
}
InsertLoc = D->getAttrs().getStartLoc(/*forModifiers=*/false);
if (InsertLoc.isInvalid()) {
InsertLoc = ConcDecl->getStartLoc();
}
if (InsertLoc.isInvalid())
return;
StringRef OriginalIndent =
Lexer::getIndentationForLine(Context.SourceMgr, InsertLoc);
PlatformKind Target = targetPlatform(Context.LangOpts);
D->diagnose(diag::availability_add_attribute, KindForDiagnostic)
.fixItInsert(InsertLoc, diag::insert_available_attr,
platformString(Target),
RequiredRange.getLowerEndpoint().getAsString(),
OriginalIndent);
}
/// In the special case of being in an existing, nontrivial type refinement
/// context that's close but not quite narrow enough to satisfy requirements
/// (i.e. requirements are contained-in the existing TRC but off by a subminor
/// version), emit a diagnostic and fixit that narrows the existing TRC
/// condition to the required range.
static bool fixAvailabilityByNarrowingNearbyVersionCheck(
SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
const VersionRange &RequiredRange,
ASTContext &Context,
InFlightDiagnostic &Err) {
const TypeRefinementContext *TRC = nullptr;
(void)TypeChecker::overApproximateAvailabilityAtLocation(ReferenceRange.Start,
ReferenceDC, &TRC);
if (!TRC)
return false;
VersionRange RunningRange = TRC->getExplicitAvailabilityInfo().getOSVersion();
if (RunningRange.hasLowerEndpoint() &&
RequiredRange.hasLowerEndpoint() &&
TRC->getReason() != TypeRefinementContext::Reason::Root &&
AvailabilityContext(RequiredRange).isContainedIn(
AvailabilityContext(RunningRange))) {
// Only fix situations that are "nearby" versions, meaning
// disagreement on a minor-or-less version (subminor-or-less version for
// macOS 10.x.y).
auto RunningVers = RunningRange.getLowerEndpoint();
auto RequiredVers = RequiredRange.getLowerEndpoint();
auto Platform = targetPlatform(Context.LangOpts);
if (RunningVers.getMajor() != RequiredVers.getMajor())
return false;
if ((Platform == PlatformKind::macOS ||
Platform == PlatformKind::macOSApplicationExtension) &&
RunningVers.getMajor() == 10 &&
!(RunningVers.getMinor().has_value() &&
RequiredVers.getMinor().has_value() &&
RunningVers.getMinor().value() ==
RequiredVers.getMinor().value()))
return false;
auto FixRange = TRC->getAvailabilityConditionVersionSourceRange(
Platform, RunningVers);
if (!FixRange.isValid())
return false;
// Have found a nontrivial type refinement context-introducer to narrow.
Err.fixItReplace(FixRange, RequiredVers.getAsString());
return true;
}
return false;
}
/// Emit a diagnostic note and Fix-It to add an if #available(...) { } guard
/// that checks for the given version range around the given node.
static void fixAvailabilityByAddingVersionCheck(
ASTNode NodeToWrap, const VersionRange &RequiredRange,
SourceRange ReferenceRange, ASTContext &Context) {
// If this is an implicit variable that wraps an expression,
// let's point to it's initializer. For example, result builder
// transform captures expressions into implicit variables.
if (auto *PB =
dyn_cast_or_null<PatternBindingDecl>(NodeToWrap.dyn_cast<Decl *>())) {
if (PB->isImplicit() && PB->getSingleVar()) {
if (auto *init = PB->getInit(0))
NodeToWrap = init;
}
}
SourceRange RangeToWrap = NodeToWrap.getSourceRange();
if (RangeToWrap.isInvalid())
return;
SourceLoc ReplaceLocStart = RangeToWrap.Start;
StringRef ExtraIndent;
StringRef OriginalIndent = Lexer::getIndentationForLine(
Context.SourceMgr, ReplaceLocStart, &ExtraIndent);
std::string IfText;
{
llvm::raw_string_ostream Out(IfText);
SourceLoc ReplaceLocEnd =
Lexer::getLocForEndOfToken(Context.SourceMgr, RangeToWrap.End);
std::string GuardedText =
Context.SourceMgr.extractText(CharSourceRange(Context.SourceMgr,
ReplaceLocStart,
ReplaceLocEnd)).str();
std::string NewLine = "\n";
std::string NewLineReplacement = (NewLine + ExtraIndent).str();
// Indent the body of the Fix-It if. Because the body may be a compound
// statement, we may have to indent multiple lines.
size_t StartAt = 0;
while ((StartAt = GuardedText.find(NewLine, StartAt)) !=
std::string::npos) {
GuardedText.replace(StartAt, NewLine.length(), NewLineReplacement);
StartAt += NewLine.length();
}
PlatformKind Target = targetPlatform(Context.LangOpts);
Out << "if #available(" << platformString(Target)
<< " " << RequiredRange.getLowerEndpoint().getAsString()
<< ", *) {\n";
Out << OriginalIndent << ExtraIndent << GuardedText << "\n";
// We emit an empty fallback case with a comment to encourage the developer
// to think explicitly about whether fallback on earlier versions is needed.
Out << OriginalIndent << "} else {\n";
Out << OriginalIndent << ExtraIndent << "// Fallback on earlier versions\n";
Out << OriginalIndent << "}";
}
Context.Diags.diagnose(
ReferenceRange.Start, diag::availability_guard_with_version_check)
.fixItReplace(RangeToWrap, IfText);
}
/// Emit suggested Fix-Its for a reference with to an unavailable symbol
/// requiting the given OS version range.
static void fixAvailability(SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
const VersionRange &RequiredRange,
ASTContext &Context) {
if (ReferenceRange.isInvalid())
return;
std::optional<ASTNode> NodeToWrapInVersionCheck;
const Decl *FoundMemberDecl = nullptr;
const Decl *FoundTypeLevelDecl = nullptr;
findAvailabilityFixItNodes(ReferenceRange, ReferenceDC, Context.SourceMgr,
NodeToWrapInVersionCheck, FoundMemberDecl,
FoundTypeLevelDecl);
// Suggest wrapping in if #available(...) { ... } if possible.
if (NodeToWrapInVersionCheck.has_value()) {
fixAvailabilityByAddingVersionCheck(NodeToWrapInVersionCheck.value(),
RequiredRange, ReferenceRange, Context);
}
// Suggest adding availability attributes.
if (FoundMemberDecl) {
fixAvailabilityForDecl(ReferenceRange, FoundMemberDecl, RequiredRange,
Context);
}
if (FoundTypeLevelDecl) {
fixAvailabilityForDecl(ReferenceRange, FoundTypeLevelDecl, RequiredRange,
Context);
}
}
void TypeChecker::diagnosePotentialUnavailability(
SourceRange ReferenceRange, Diag<StringRef, llvm::VersionTuple> Diag,
const DeclContext *ReferenceDC,
const UnavailabilityReason &Reason) {
ASTContext &Context = ReferenceDC->getASTContext();
auto RequiredRange = Reason.getRequiredOSVersionRange();
{
auto Err =
Context.Diags.diagnose(
ReferenceRange.Start, Diag,
prettyPlatformString(targetPlatform(Context.LangOpts)),
Reason.getRequiredOSVersionRange().getLowerEndpoint());
// Direct a fixit to the error if an existing guard is nearly-correct
if (fixAvailabilityByNarrowingNearbyVersionCheck(
ReferenceRange, ReferenceDC, RequiredRange, Context, Err))
return;
}
fixAvailability(ReferenceRange, ReferenceDC, RequiredRange, Context);
}
bool TypeChecker::checkAvailability(SourceRange ReferenceRange,
AvailabilityContext Availability,
Diag<StringRef, llvm::VersionTuple> Diag,
const DeclContext *ReferenceDC) {
ASTContext &ctx = ReferenceDC->getASTContext();
if (ctx.LangOpts.DisableAvailabilityChecking)
return false;
auto runningOS =
TypeChecker::overApproximateAvailabilityAtLocation(
ReferenceRange.Start, ReferenceDC);
if (!runningOS.isContainedIn(Availability)) {
diagnosePotentialUnavailability(
ReferenceRange, Diag, ReferenceDC,
UnavailabilityReason::requiresVersionRange(Availability.getOSVersion()));
return true;
}
return false;
}
void TypeChecker::checkConcurrencyAvailability(SourceRange ReferenceRange,
const DeclContext *ReferenceDC) {
checkAvailability(
ReferenceRange,
ReferenceDC->getASTContext().getBackDeployedConcurrencyAvailability(),
diag::availability_concurrency_only_version_newer,
ReferenceDC);
}
/// Returns the diagnostic to emit for the potentially unavailable decl and sets
/// \p IsError accordingly.
static Diagnostic getPotentialUnavailabilityDiagnostic(
const ValueDecl *D, const DeclContext *ReferenceDC,
const UnavailabilityReason &Reason, bool WarnBeforeDeploymentTarget,
bool &IsError) {
ASTContext &Context = ReferenceDC->getASTContext();
auto Platform = prettyPlatformString(targetPlatform(Context.LangOpts));
auto Version = Reason.getRequiredOSVersionRange().getLowerEndpoint();
if (Reason.requiresDeploymentTargetOrEarlier(Context)) {
// The required OS version is at or before the deployment target so this
// diagnostic should indicate that the decl could be unavailable to clients
// of the module containing the reference.
IsError = !WarnBeforeDeploymentTarget;
return Diagnostic(
IsError ? diag::availability_decl_only_version_newer_for_clients
: diag::availability_decl_only_version_newer_for_clients_warn,
D, Platform, Version, ReferenceDC->getParentModule());
}
IsError = true;
return Diagnostic(diag::availability_decl_only_version_newer, D, Platform,
Version);
}
bool TypeChecker::diagnosePotentialUnavailability(
const ValueDecl *D, SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
const UnavailabilityReason &Reason,
bool WarnBeforeDeploymentTarget = false) {
ASTContext &Context = ReferenceDC->getASTContext();
auto RequiredRange = Reason.getRequiredOSVersionRange();
bool IsError;
{
auto Diag = Context.Diags.diagnose(
ReferenceRange.Start,
getPotentialUnavailabilityDiagnostic(
D, ReferenceDC, Reason, WarnBeforeDeploymentTarget, IsError));
// Direct a fixit to the error if an existing guard is nearly-correct
if (fixAvailabilityByNarrowingNearbyVersionCheck(
ReferenceRange, ReferenceDC, RequiredRange, Context, Diag))
return IsError;
}
fixAvailability(ReferenceRange, ReferenceDC, RequiredRange, Context);
return IsError;
}
void TypeChecker::diagnosePotentialAccessorUnavailability(
const AccessorDecl *Accessor, SourceRange ReferenceRange,
const DeclContext *ReferenceDC, const UnavailabilityReason &Reason,
bool ForInout) {
ASTContext &Context = ReferenceDC->getASTContext();
assert(Accessor->isGetterOrSetter());
auto &diag = ForInout ? diag::availability_inout_accessor_only_version_newer
: diag::availability_decl_only_version_newer;
auto RequiredRange = Reason.getRequiredOSVersionRange();
{
auto Err =
Context.Diags.diagnose(
ReferenceRange.Start, diag, Accessor,
prettyPlatformString(targetPlatform(Context.LangOpts)),
Reason.getRequiredOSVersionRange().getLowerEndpoint());
// Direct a fixit to the error if an existing guard is nearly-correct
if (fixAvailabilityByNarrowingNearbyVersionCheck(ReferenceRange,
ReferenceDC,
RequiredRange, Context, Err))
return;
}
fixAvailability(ReferenceRange, ReferenceDC, RequiredRange, Context);
}
static DiagnosticBehavior
behaviorLimitForExplicitUnavailability(
const RootProtocolConformance *rootConf,
const DeclContext *fromDC) {
auto protoDecl = rootConf->getProtocol();
// Soften errors about unavailable `Sendable` conformances depending on the
// concurrency checking mode.
if (protoDecl->isSpecificProtocol(KnownProtocolKind::Sendable)) {
SendableCheckContext checkContext(fromDC);
if (auto nominal = rootConf->getType()->getAnyNominal())
return checkContext.diagnosticBehavior(nominal);
return checkContext.defaultDiagnosticBehavior();
}
return DiagnosticBehavior::Unspecified;
}
void TypeChecker::diagnosePotentialUnavailability(
const RootProtocolConformance *rootConf,
const ExtensionDecl *ext,
SourceLoc loc,
const DeclContext *dc,
const UnavailabilityReason &reason) {
ASTContext &ctx = dc->getASTContext();
auto requiredRange = reason.getRequiredOSVersionRange();
{
auto type = rootConf->getType();
auto proto = rootConf->getProtocol()->getDeclaredInterfaceType();
auto err = ctx.Diags.diagnose(
loc, diag::conformance_availability_only_version_newer, type, proto,
prettyPlatformString(targetPlatform(ctx.LangOpts)),
reason.getRequiredOSVersionRange().getLowerEndpoint());
err.warnUntilSwiftVersion(6);
err.limitBehavior(behaviorLimitForExplicitUnavailability(rootConf, dc));
// Direct a fixit to the error if an existing guard is nearly-correct
if (fixAvailabilityByNarrowingNearbyVersionCheck(loc, dc,
requiredRange, ctx, err))
return;
}
fixAvailability(loc, dc, requiredRange, ctx);
}
const AvailableAttr *TypeChecker::getDeprecated(const Decl *D) {
if (auto *Attr = D->getAttrs().getDeprecated(D->getASTContext()))
return Attr;
// Treat extensions methods as deprecated if their extension
// is deprecated.
DeclContext *DC = D->getDeclContext();
if (auto *ED = dyn_cast<ExtensionDecl>(DC)) {
return getDeprecated(ED);
}
return nullptr;
}
static void fixItAvailableAttrRename(InFlightDiagnostic &diag,
SourceRange referenceRange,
const ValueDecl *renamedDecl,
const AvailableAttr *attr,
const Expr *call) {
if (isa<AccessorDecl>(renamedDecl))
return;
ParsedDeclName parsed = swift::parseDeclName(attr->Rename);
if (!parsed)
return;
bool originallyWasKnownOperatorExpr = false;
if (call) {
originallyWasKnownOperatorExpr =
isa<BinaryExpr>(call) ||
isa<PrefixUnaryExpr>(call) ||
isa<PostfixUnaryExpr>(call);
}
if (parsed.isOperator() != originallyWasKnownOperatorExpr)
return;
auto &ctx = renamedDecl->getASTContext();
SourceManager &sourceMgr = ctx.SourceMgr;
if (parsed.isInstanceMember()) {
auto *CE = dyn_cast_or_null<CallExpr>(call);
if (!CE)
return;
// Replace the base of the call with the "self argument".
// We can only do a good job with the fix-it if we have the whole call
// expression.
// FIXME: Should we be validating the ContextName in some way?
unsigned selfIndex = parsed.SelfIndex.value();
const Expr *selfExpr = nullptr;
SourceLoc removeRangeStart;
SourceLoc removeRangeEnd;
auto *originalArgs = CE->getArgs()->getOriginalArgs();
size_t numElementsWithinParens = originalArgs->size();
numElementsWithinParens -= originalArgs->getNumTrailingClosures();
if (selfIndex >= numElementsWithinParens)
return;
if (parsed.IsGetter) {
if (numElementsWithinParens != 1)
return;
} else if (parsed.IsSetter) {
if (numElementsWithinParens != 2)
return;
} else {
if (parsed.ArgumentLabels.size() != originalArgs->size() - 1)
return;
}
selfExpr = originalArgs->getExpr(selfIndex);
if (selfIndex + 1 == numElementsWithinParens) {
if (selfIndex > 0) {
// Remove from the previous comma to the close-paren (half-open).
removeRangeStart = originalArgs->getExpr(selfIndex - 1)->getEndLoc();
removeRangeStart = Lexer::getLocForEndOfToken(sourceMgr,
removeRangeStart);
} else {
// Remove from after the open paren to the close paren (half-open).
removeRangeStart =
Lexer::getLocForEndOfToken(sourceMgr, originalArgs->getStartLoc());
}
// Prefer the r-paren location, so that we get the right behavior when
// there's a trailing closure, but handle some implicit cases too.
removeRangeEnd = originalArgs->getRParenLoc();
if (removeRangeEnd.isInvalid())
removeRangeEnd = originalArgs->getEndLoc();
} else {
// Remove from the label to the start of the next argument (half-open).
SourceLoc labelLoc = originalArgs->getLabelLoc(selfIndex);
if (labelLoc.isValid())
removeRangeStart = labelLoc;
else
removeRangeStart = selfExpr->getStartLoc();
SourceLoc nextLabelLoc = originalArgs->getLabelLoc(selfIndex + 1);
if (nextLabelLoc.isValid())
removeRangeEnd = nextLabelLoc;
else
removeRangeEnd = originalArgs->getExpr(selfIndex + 1)->getStartLoc();
}
// Avoid later argument label fix-its for this argument.
if (!parsed.isPropertyAccessor()) {
Identifier oldLabel = originalArgs->getLabel(selfIndex);
StringRef oldLabelStr;
if (!oldLabel.empty())
oldLabelStr = oldLabel.str();
parsed.ArgumentLabels.insert(parsed.ArgumentLabels.begin() + selfIndex,
oldLabelStr);
}
if (auto *inoutSelf = dyn_cast<InOutExpr>(selfExpr))
selfExpr = inoutSelf->getSubExpr();
CharSourceRange selfExprRange =
Lexer::getCharSourceRangeFromSourceRange(sourceMgr,
selfExpr->getSourceRange());
bool needsParens = !selfExpr->canAppendPostfixExpression();
SmallString<64> selfReplace;
if (needsParens)
selfReplace.push_back('(');
// If the base is contextual member lookup and we know the type,
// let's just prepend it, otherwise we'll end up with an incorrect fix-it.
auto base = sourceMgr.extractText(selfExprRange);
if (!base.empty() && base.front() == '.') {
auto newName = attr->Rename;
// If this is not a rename, let's not
// even try to emit a fix-it because
// it's going to be invalid.
if (newName.empty())
return;
auto parts = newName.split('.');
auto nominalName = parts.first;
assert(!nominalName.empty());
selfReplace += nominalName;
}
selfReplace += base;
if (needsParens)
selfReplace.push_back(')');
selfReplace.push_back('.');
selfReplace += parsed.BaseName;
diag.fixItReplace(CE->getFn()->getSourceRange(), selfReplace);
if (!parsed.isPropertyAccessor())
diag.fixItRemoveChars(removeRangeStart, removeRangeEnd);
// Continue on to diagnose any argument label renames.
} else if (parsed.BaseName == "init" && isa_and_nonnull<CallExpr>(call)) {
auto *CE = cast<CallExpr>(call);
// If it is a call to an initializer (rather than a first-class reference):
if (parsed.isMember()) {
// replace with a "call" to the type (instead of writing `.init`)
diag.fixItReplace(CE->getFn()->getSourceRange(), parsed.ContextName);
} else if (auto *dotCall = dyn_cast<DotSyntaxCallExpr>(CE->getFn())) {
// if it's a dot call, and the left side is a type (and not `self` or
// `super`, for example), just remove the dot and the right side, again
// in order to make it a "call" to the type
if (isa<TypeExpr>(dotCall->getBase())) {
SourceLoc removeLoc = dotCall->getDotLoc();
if (removeLoc.isInvalid())
return;
diag.fixItRemove(SourceRange(removeLoc, dotCall->getFn()->getEndLoc()));
}
} else if (!isa<ConstructorRefCallExpr>(CE->getFn())) {
return;
}
// Continue on to diagnose any constructor argument label renames.
} else if (parsed.IsSubscript) {
if (auto *CE = dyn_cast_or_null<CallExpr>(call)) {
// Renaming from CallExpr to SubscriptExpr. Remove function name and
// replace parens with square brackets.
if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(CE->getFn())) {
if (DSCE->getBase()->isImplicit()) {
// If self is implicit, self must be inserted before subscript syntax.
diag.fixItInsert(CE->getStartLoc(), "self");
}
}
diag.fixItReplace(CE->getFn()->getEndLoc(), "[");
diag.fixItReplace(CE->getEndLoc(), "]");
}
} else {
// Just replace the base name.
SmallString<64> baseReplace;
if (!parsed.ContextName.empty()) {
baseReplace += parsed.ContextName;
baseReplace += '.';
}
baseReplace += parsed.BaseName;
if (parsed.IsFunctionName && isa_and_nonnull<SubscriptExpr>(call)) {
auto *SE = cast<SubscriptExpr>(call);
// Renaming from SubscriptExpr to CallExpr. Insert function name and
// replace square brackets with parens.
diag.fixItReplace(SE->getArgs()->getStartLoc(),
("." + baseReplace.str() + "(").str());
diag.fixItReplace(SE->getEndLoc(), ")");
} else {
bool shouldEmitRenameFixit = true;
if (auto *CE = dyn_cast_or_null<CallExpr>(call)) {
SmallString<64> callContextName;
llvm::raw_svector_ostream name(callContextName);
if (auto *DCE = dyn_cast<DotSyntaxCallExpr>(CE->getDirectCallee())) {
if (auto *TE = dyn_cast<TypeExpr>(DCE->getBase())) {
TE->getTypeRepr()->print(name);
if (!parsed.ContextName.empty()) {
// If there is a context in rename function e.g.
// `Context.function()` and call context is a `DotSyntaxCallExpr`
// adjust the range so it replaces the base as well.
referenceRange =
SourceRange(TE->getStartLoc(), referenceRange.End);
}
}
}
// Function names are the same (including context if applicable), so
// renaming fix-it doesn't need do be produced.
auto calledValue = CE->getCalledValue(/*skipFunctionConversions=*/true);
if ((parsed.ContextName.empty() ||
parsed.ContextName == callContextName) &&
calledValue && calledValue->getBaseName() == parsed.BaseName) {
shouldEmitRenameFixit = false;
}
}
if (shouldEmitRenameFixit) {
if (parsed.IsFunctionName && parsed.ArgumentLabels.empty() &&
isa<VarDecl>(renamedDecl)) {
// If we're going from a var to a function with no arguments, emit an
// empty parameter list.
baseReplace += "()";
}
diag.fixItReplace(referenceRange, baseReplace);
}
}
}
if (!call || !call->getArgs())
return;
auto *originalArgs = call->getArgs()->getOriginalArgs();
if (parsed.IsGetter) {
diag.fixItRemove(originalArgs->getSourceRange());
return;
}
if (parsed.IsSetter) {
const Expr *newValueExpr = nullptr;
if (originalArgs->size() >= 1) {
size_t newValueIndex = 0;
if (parsed.isInstanceMember()) {
assert(parsed.SelfIndex.value() == 0 ||
parsed.SelfIndex.value() == 1);
newValueIndex = !parsed.SelfIndex.value();
}
newValueExpr = originalArgs->getExpr(newValueIndex);
} else {
newValueExpr = originalArgs->getExpr(0);
}
diag.fixItReplaceChars(originalArgs->getStartLoc(),
newValueExpr->getStartLoc(), " = ");
diag.fixItRemoveChars(
Lexer::getLocForEndOfToken(sourceMgr, newValueExpr->getEndLoc()),
Lexer::getLocForEndOfToken(sourceMgr, originalArgs->getEndLoc()));
return;
}
if (!parsed.IsFunctionName)
return;
SmallVector<Identifier, 4> argumentLabelIDs;
llvm::transform(parsed.ArgumentLabels, std::back_inserter(argumentLabelIDs),
[&ctx](StringRef labelStr) -> Identifier {
return labelStr.empty() ? Identifier()
: ctx.getIdentifier(labelStr);
});
// Coerce the `argumentLabelIDs` to the user supplied arguments.
// e.g:
// @available(.., renamed: "new(w:x:y:z:)")
// func old(a: Int, b: Int..., c: String="", d: Int=0){}
// old(a: 1, b: 2, 3, 4, d: 5)
// coerce
// argumentLabelIDs = {"w", "x", "y", "z"}
// to
// argumentLabelIDs = {"w", "x", "", "", "z"}
auto I = argumentLabelIDs.begin();
auto updateLabelsForArg = [&](Expr *expr) -> bool {
if (I == argumentLabelIDs.end())
return true;
if (isa<DefaultArgumentExpr>(expr)) {
// Defaulted: remove param label of it.
I = argumentLabelIDs.erase(I);
return false;
}
if (auto *varargExpr = dyn_cast<VarargExpansionExpr>(expr)) {
if (auto *arrayExpr = dyn_cast<ArrayExpr>(varargExpr->getSubExpr())) {
auto variadicArgsNum = arrayExpr->getNumElements();
if (variadicArgsNum == 0) {
// No arguments: Remove param label of it.
I = argumentLabelIDs.erase(I);
} else if (variadicArgsNum == 1) {
// One argument: Just advance.
++I;
} else {
++I;
// Two or more arguments: Insert empty labels after the first one.
--variadicArgsNum;
I = argumentLabelIDs.insert(I, variadicArgsNum, Identifier());
I += variadicArgsNum;
}
return false;
}
}
// Normal: Just advance.
++I;
return false;
};
for (auto arg : *call->getArgs()) {
if (updateLabelsForArg(arg.getExpr()))
return;
}
if (argumentLabelIDs.size() != originalArgs->size()) {
// Mismatched lengths; give up.
return;
}
// If any of the argument labels are mismatched, perform label correction.
for (auto i : indices(*originalArgs)) {
// The argument label of an unlabeled trailing closure is ignored.
if (originalArgs->isUnlabeledTrailingClosureIndex(i))
continue;
if (argumentLabelIDs[i] != originalArgs->getLabel(i)) {
auto paramContext = parsed.IsSubscript ? ParameterContext::Subscript
: ParameterContext::Call;
diagnoseArgumentLabelError(ctx, originalArgs, argumentLabelIDs,
paramContext, &diag);
return;
}
}
}
// Must be kept in sync with diag::availability_decl_unavailable_rename and
// others.
namespace {
enum class ReplacementDeclKind : unsigned {
None,
InstanceMethod,
Property,
};
} // end anonymous namespace
static std::optional<ReplacementDeclKind>
describeRename(ASTContext &ctx, const AvailableAttr *attr, const ValueDecl *D,
SmallVectorImpl<char> &nameBuf) {
ParsedDeclName parsed = swift::parseDeclName(attr->Rename);
if (!parsed)
return std::nullopt;
// Only produce special descriptions for renames to
// - instance members
// - properties (or global bindings)
// - class/static methods
// - initializers, unless the original was known to be an initializer
// Leave non-member renames alone, as well as renames from top-level types
// and bindings to member types and class/static properties.
if (!(parsed.isInstanceMember() || parsed.isPropertyAccessor() ||
(parsed.isMember() && parsed.IsFunctionName) ||
(parsed.BaseName == "init" &&
!dyn_cast_or_null<ConstructorDecl>(D)))) {
return std::nullopt;
}
llvm::raw_svector_ostream name(nameBuf);
if (!parsed.ContextName.empty())
name << parsed.ContextName << '.';
if (parsed.IsFunctionName) {
name << parsed.formDeclName(ctx, (D && isa<SubscriptDecl>(D)));
} else {
name << parsed.BaseName;
}
if (parsed.isMember() && parsed.isPropertyAccessor())
return ReplacementDeclKind::Property;
if (parsed.isInstanceMember() && parsed.IsFunctionName)
return ReplacementDeclKind::InstanceMethod;
// We don't have enough information.
return ReplacementDeclKind::None;
}
void TypeChecker::diagnoseIfDeprecated(SourceRange ReferenceRange,
const ExportContext &Where,
const ValueDecl *DeprecatedDecl,
const Expr *Call) {
const AvailableAttr *Attr = TypeChecker::getDeprecated(DeprecatedDecl);
if (!Attr)
return;
// We match the behavior of clang to not report deprecation warnings
// inside declarations that are themselves deprecated on all deployment
// targets.
if (Where.isDeprecated()) {
return;
}
auto *ReferenceDC = Where.getDeclContext();
auto &Context = ReferenceDC->getASTContext();
if (!Context.LangOpts.DisableAvailabilityChecking) {
AvailabilityContext RunningOSVersions = Where.getAvailabilityContext();
if (RunningOSVersions.isKnownUnreachable()) {
// Suppress a deprecation warning if the availability checking machinery
// thinks the reference program location will not execute on any
// deployment target for the current platform.
return;
}
}
if (shouldIgnoreDeprecationOfConcurrencyDecl(DeprecatedDecl, ReferenceDC))
return;
StringRef Platform = Attr->prettyPlatformString();
llvm::VersionTuple DeprecatedVersion;
if (Attr->Deprecated)
DeprecatedVersion = Attr->Deprecated.value();
if (Attr->Message.empty() && Attr->Rename.empty()) {
Context.Diags.diagnose(
ReferenceRange.Start, diag::availability_deprecated,
DeprecatedDecl, Attr->hasPlatform(), Platform,
Attr->Deprecated.has_value(), DeprecatedVersion,
/*message*/ StringRef())
.highlight(Attr->getRange());
return;
}
llvm::VersionTuple RemappedDeprecatedVersion;
if (AvailabilityInference::updateDeprecatedPlatformForFallback(
Attr, Context, Platform, RemappedDeprecatedVersion))
DeprecatedVersion = RemappedDeprecatedVersion;
SmallString<32> newNameBuf;
std::optional<ReplacementDeclKind> replacementDeclKind =
describeRename(Context, Attr, /*decl*/ nullptr, newNameBuf);
StringRef newName = replacementDeclKind ? newNameBuf.str() : Attr->Rename;
if (!Attr->Message.empty()) {
EncodedDiagnosticMessage EncodedMessage(Attr->Message);
Context.Diags.diagnose(
ReferenceRange.Start, diag::availability_deprecated,
DeprecatedDecl, Attr->hasPlatform(), Platform,
Attr->Deprecated.has_value(), DeprecatedVersion,
EncodedMessage.Message)
.highlight(Attr->getRange());
} else {
unsigned rawReplaceKind = static_cast<unsigned>(
replacementDeclKind.value_or(ReplacementDeclKind::None));
Context.Diags.diagnose(
ReferenceRange.Start, diag::availability_deprecated_rename,
DeprecatedDecl, Attr->hasPlatform(), Platform,
Attr->Deprecated.has_value(), DeprecatedVersion,
replacementDeclKind.has_value(), rawReplaceKind, newName)
.highlight(Attr->getRange());
}
if (!Attr->Rename.empty() && !isa<AccessorDecl>(DeprecatedDecl)) {
auto renameDiag = Context.Diags.diagnose(
ReferenceRange.Start,
diag::note_deprecated_rename,
newName);
fixItAvailableAttrRename(renameDiag, ReferenceRange, DeprecatedDecl,
Attr, Call);
}
}
bool TypeChecker::diagnoseIfDeprecated(SourceLoc loc,
const RootProtocolConformance *rootConf,
const ExtensionDecl *ext,
const ExportContext &where) {
const AvailableAttr *attr = TypeChecker::getDeprecated(ext);
if (!attr)
return false;
// We match the behavior of clang to not report deprecation warnings
// inside declarations that are themselves deprecated on all deployment
// targets.
if (where.isDeprecated()) {
return false;
}
auto *dc = where.getDeclContext();
auto &ctx = dc->getASTContext();
if (!ctx.LangOpts.DisableAvailabilityChecking) {
AvailabilityContext runningOSVersion = where.getAvailabilityContext();
if (runningOSVersion.isKnownUnreachable()) {
// Suppress a deprecation warning if the availability checking machinery
// thinks the reference program location will not execute on any
// deployment target for the current platform.
return false;
}
}
auto type = rootConf->getType();
auto proto = rootConf->getProtocol()->getDeclaredInterfaceType();
StringRef platform = attr->prettyPlatformString();
llvm::VersionTuple deprecatedVersion;
if (attr->Deprecated)
deprecatedVersion = attr->Deprecated.value();
llvm::VersionTuple remappedDeprecatedVersion;
if (AvailabilityInference::updateDeprecatedPlatformForFallback(
attr, ctx, platform, remappedDeprecatedVersion))
deprecatedVersion = remappedDeprecatedVersion;
if (attr->Message.empty()) {
ctx.Diags.diagnose(
loc, diag::conformance_availability_deprecated,
type, proto, attr->hasPlatform(), platform,
attr->Deprecated.has_value(), deprecatedVersion,
/*message*/ StringRef())
.highlight(attr->getRange());
return true;
}
EncodedDiagnosticMessage encodedMessage(attr->Message);
ctx.Diags.diagnose(
loc, diag::conformance_availability_deprecated,
type, proto, attr->hasPlatform(), platform,
attr->Deprecated.has_value(), deprecatedVersion,
encodedMessage.Message)
.highlight(attr->getRange());
return true;
}
void swift::diagnoseOverrideOfUnavailableDecl(ValueDecl *override,
const ValueDecl *base,
const AvailableAttr *attr) {
ASTContext &ctx = override->getASTContext();
auto &diags = ctx.Diags;
if (attr->Rename.empty()) {
EncodedDiagnosticMessage EncodedMessage(attr->Message);
diags.diagnose(override, diag::override_unavailable,
override->getBaseName(), EncodedMessage.Message);
diags.diagnose(base, diag::availability_marked_unavailable, base);
return;
}
ExportContext where = ExportContext::forDeclSignature(override);
diagnoseExplicitUnavailability(
base, override->getLoc(), where,
/*Flags*/ std::nullopt, [&](InFlightDiagnostic &diag) {
ParsedDeclName parsedName = parseDeclName(attr->Rename);
if (!parsedName || parsedName.isPropertyAccessor() ||
parsedName.isMember() || parsedName.isOperator()) {
return;
}
// Only initializers should be named 'init'.
if (isa<ConstructorDecl>(override) ^ (parsedName.BaseName == "init")) {
return;
}
if (!parsedName.IsFunctionName) {
diag.fixItReplace(override->getNameLoc(), parsedName.BaseName);
return;
}
DeclName newName = parsedName.formDeclName(ctx);
size_t numArgs = override->getName().getArgumentNames().size();
if (!newName || newName.getArgumentNames().size() != numArgs)
return;
fixDeclarationName(diag, override, newName);
});
}
/// Emit a diagnostic for references to declarations that have been
/// marked as unavailable, either through "unavailable" or "obsoleted:".
bool swift::diagnoseExplicitUnavailability(const ValueDecl *D, SourceRange R,
const ExportContext &Where,
const Expr *call,
DeclAvailabilityFlags Flags) {
return diagnoseExplicitUnavailability(D, R, Where, Flags,
[=](InFlightDiagnostic &diag) {
fixItAvailableAttrRename(diag, R, D, AvailableAttr::isUnavailable(D),
call);
});
}
/// Emit a diagnostic for references to declarations that have been
/// marked as unavailable, either through "unavailable" or "obsoleted:".
bool swift::diagnoseExplicitUnavailability(SourceLoc loc,
const RootProtocolConformance *rootConf,
const ExtensionDecl *ext,
const ExportContext &where,
bool warnIfConformanceUnavailablePreSwift6,
bool preconcurrency) {
auto *attr = AvailableAttr::isUnavailable(ext);
if (!attr)
return false;
// Calling unavailable code from within code with the same
// unavailability is OK -- the eventual caller can't call the
// enclosing code in the same situations it wouldn't be able to
// call this code.
if (isInsideCompatibleUnavailableDeclaration(ext, where, attr))
return false;
// Invertible protocols are never unavailable.
if (rootConf->getProtocol()->getInvertibleProtocolKind())
return false;
ASTContext &ctx = ext->getASTContext();
auto &diags = ctx.Diags;
auto type = rootConf->getType();
auto proto = rootConf->getProtocol()->getDeclaredInterfaceType();
StringRef platform;
auto behavior = DiagnosticBehavior::Unspecified;
switch (attr->getPlatformAgnosticAvailability()) {
case PlatformAgnosticAvailabilityKind::Deprecated:
llvm_unreachable("shouldn't see deprecations in explicit unavailability");
case PlatformAgnosticAvailabilityKind::NoAsync:
llvm_unreachable("shouldn't see noasync in explicit unavailability");
case PlatformAgnosticAvailabilityKind::None:
case PlatformAgnosticAvailabilityKind::Unavailable:
if (attr->Platform != PlatformKind::none) {
// This was platform-specific; indicate the platform.
platform = attr->prettyPlatformString();
break;
}
// Downgrade unavailable Sendable conformance diagnostics where
// appropriate.
behavior = behaviorLimitForExplicitUnavailability(
rootConf, where.getDeclContext());
LLVM_FALLTHROUGH;
case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific:
case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific:
// We don't want to give further detail about these.
platform = "";
break;
case PlatformAgnosticAvailabilityKind::UnavailableInSwift:
// This API is explicitly unavailable in Swift.
platform = "Swift";
break;
}
EncodedDiagnosticMessage EncodedMessage(attr->Message);
diags.diagnose(loc, diag::conformance_availability_unavailable,
type, proto,
platform.empty(), platform, EncodedMessage.Message)
.limitBehaviorWithPreconcurrency(behavior, preconcurrency)
.warnUntilSwiftVersionIf(warnIfConformanceUnavailablePreSwift6, 6);
switch (attr->getVersionAvailability(ctx)) {
case AvailableVersionComparison::Available:
case AvailableVersionComparison::PotentiallyUnavailable:
llvm_unreachable("These aren't considered unavailable");
case AvailableVersionComparison::Unavailable:
if ((attr->isLanguageVersionSpecific() ||
attr->isPackageDescriptionVersionSpecific())
&& attr->Introduced.has_value())
diags.diagnose(ext, diag::conformance_availability_introduced_in_version,
type, proto,
(attr->isLanguageVersionSpecific() ?
"Swift" : "PackageDescription"),
*attr->Introduced)
.highlight(attr->getRange());
else
diags.diagnose(ext, diag::conformance_availability_marked_unavailable,
type, proto)
.highlight(attr->getRange());
break;
case AvailableVersionComparison::Obsoleted:
// FIXME: Use of the platformString here is non-awesome for application
// extensions.
StringRef platformDisplayString;
if (attr->isLanguageVersionSpecific()) {
platformDisplayString = "Swift";
} else if (attr->isPackageDescriptionVersionSpecific()) {
platformDisplayString = "PackageDescription";
} else {
platformDisplayString = platform;
}
diags.diagnose(ext, diag::conformance_availability_obsoleted,
type, proto, platformDisplayString, *attr->Obsoleted)
.highlight(attr->getRange());
break;
}
return true;
}
/// Check if this is a subscript declaration inside String or
/// Substring that returns String, and if so return true.
bool isSubscriptReturningString(const ValueDecl *D, ASTContext &Context) {
// Is this a subscript?
if (!isa<SubscriptDecl>(D))
return false;
// Is the subscript declared in String or Substring?
auto *declContext = D->getDeclContext();
assert(declContext && "Expected decl context!");
auto *stringDecl = Context.getStringDecl();
auto *substringDecl = Context.getSubstringDecl();
auto *typeDecl = declContext->getSelfNominalTypeDecl();
if (!typeDecl)
return false;
if (typeDecl != stringDecl && typeDecl != substringDecl)
return false;
// Is the subscript index one we want to emit a special diagnostic
// for, and the return type String?
auto fnTy = D->getInterfaceType()->getAs<AnyFunctionType>();
assert(fnTy && "Expected function type for subscript decl!");
// We're only going to warn for BoundGenericStructType with a single
// type argument that is not Int!
auto params = fnTy->getParams();
if (params.size() != 1)
return false;
const auto ¶m = params.front();
if (param.hasLabel() || param.isVariadic() || param.isInOut())
return false;
auto inputTy = param.getPlainType()->getAs<BoundGenericStructType>();
if (!inputTy)
return false;
auto genericArgs = inputTy->getGenericArgs();
if (genericArgs.size() != 1)
return false;
// The subscripts taking T<Int> do not return Substring, and our
// special fixit does not help here.
auto nominalTypeParam = genericArgs[0]->getAs<NominalType>();
if (!nominalTypeParam)
return false;
if (nominalTypeParam->isInt())
return false;
auto resultTy = fnTy->getResult()->getAs<NominalType>();
if (!resultTy)
return false;
return resultTy->isString();
}
static bool diagnoseParameterizedProtocolAvailability(
SourceRange ReferenceRange, const DeclContext *ReferenceDC) {
return TypeChecker::checkAvailability(
ReferenceRange,
ReferenceDC->getASTContext().getParameterizedExistentialAvailability(),
diag::availability_parameterized_protocol_only_version_newer,
ReferenceDC);
}
static bool diagnoseIsolatedAnyAvailability(
SourceRange ReferenceRange, const DeclContext *ReferenceDC) {
return TypeChecker::checkAvailability(
ReferenceRange,
ReferenceDC->getASTContext().getIsolatedAnyAvailability(),
diag::availability_isolated_any_only_version_newer,
ReferenceDC);
}
static bool diagnoseTypedThrowsAvailability(
SourceRange ReferenceRange, const DeclContext *ReferenceDC) {
return TypeChecker::checkAvailability(
ReferenceRange,
ReferenceDC->getASTContext().getTypedThrowsAvailability(),
diag::availability_typed_throws_only_version_newer,
ReferenceDC);
}
/// Make sure the generic arguments conform to all known invertible protocols.
/// Runtimes prior to NoncopyableGenerics do not check if any of the
/// generic arguments conform to Copyable/Escapable during dynamic casts.
/// But a dynamic cast *needs* to check if the generic arguments conform,
/// to determine if the cast should be permitted at all. For example:
///
/// struct X<T> {}
/// extension X: P where T: Y {}
///
/// func f<Y: ~Copyable>(...) {
/// let x: X<Y> = ...
/// _ = x as? any P // <- cast should fail
/// }
///
/// The dynamic cast here must fail because Y does not conform to Copyable,
/// thus X<Y> doesn't conform to P!
///
/// \param boundTy The generic type with its generic arguments.
/// \returns the invertible protocol for which a conformance is missing in
/// one of the generic arguments, or none if all are present for
/// every generic argument.
static std::optional<InvertibleProtocolKind> checkGenericArgsForInvertibleReqs(
BoundGenericType *boundTy) {
for (auto arg : boundTy->getGenericArgs()) {
for (auto ip : InvertibleProtocolSet::allKnown()) {
switch (ip) {
case InvertibleProtocolKind::Copyable:
if (arg->isNoncopyable())
return ip;
break;
case InvertibleProtocolKind::Escapable:
if (!arg->isEscapable())
return ip;
}
}
}
return std::nullopt;
}
/// Older runtimes won't check for required invertible protocol conformances
/// at runtime during a cast.
///
/// \param srcType the source or initial type of the cast
/// \param refLoc source location of the cast
/// \param refDC decl context in which the cast occurs
/// \return true if diagnosed
static bool checkInverseGenericsCastingAvailability(Type srcType,
SourceRange refLoc,
const DeclContext *refDC) {
if (!srcType) return false;
auto type = srcType->getCanonicalType();
if (auto boundTy = dyn_cast<BoundGenericType>(type)) {
if (auto missing = checkGenericArgsForInvertibleReqs(boundTy)) {
std::optional<Diag<StringRef, llvm::VersionTuple>> diag;
switch (*missing) {
case InvertibleProtocolKind::Copyable:
diag =
diag::availability_copyable_generics_casting_only_version_newer;
break;
case InvertibleProtocolKind::Escapable:
diag =
diag::availability_escapable_generics_casting_only_version_newer;
break;
}
// Enforce the availability restriction.
return TypeChecker::checkAvailability(
refLoc,
refDC->getASTContext().getNoncopyableGenericsAvailability(),
*diag,
refDC);
}
}
return false;
}
static bool checkTypeMetadataAvailabilityInternal(CanType type,
SourceRange refLoc,
const DeclContext *refDC) {
return type.findIf([&](CanType type) {
if (isa<ParameterizedProtocolType>(type)) {
return diagnoseParameterizedProtocolAvailability(refLoc, refDC);
} else if (auto fnType = dyn_cast<AnyFunctionType>(type)) {
auto isolation = fnType->getIsolation();
if (isolation.isErased())
return diagnoseIsolatedAnyAvailability(refLoc, refDC);
if (fnType.getThrownError())
return diagnoseTypedThrowsAvailability(refLoc, refDC);
}
return false;
});
}
/// Check whether type metadata is available for the given type (and its
/// component types).
bool swift::checkTypeMetadataAvailability(Type type,
SourceRange refLoc,
const DeclContext *refDC) {
if (!type) return false;
return checkTypeMetadataAvailabilityInternal(type->getCanonicalType(),
refLoc, refDC);
}
/// Check whether type metadata is available for the given type, given that
/// it is the operand of a dynamic cast or existential conversion.
static bool checkTypeMetadataAvailabilityForConverted(Type refType,
SourceRange refLoc,
const DeclContext *refDC) {
if (!refType) return false;
auto type = refType->getCanonicalType();
// SILGen emits these conversions by opening the outermost level of
// existential, so we never need to emit type metadata for an
// existential in such a position. We necessarily have type metadata
// for the dynamic type of the existential, so there's nothing to check
// there.
if (type.isAnyExistentialType()) return false;
if (checkTypeMetadataAvailabilityInternal(type, refLoc, refDC))
return true;
if (checkInverseGenericsCastingAvailability(type, refLoc, refDC))
return true;
return false;
}
namespace {
class CheckConversionAvailability {
SourceRange refLoc;
const DeclContext *refDC;
public:
CheckConversionAvailability(SourceRange refLoc, const DeclContext *refDC)
: refLoc(refLoc), refDC(refDC) {}
void check(CanType srcType, CanType destType);
void checkFunction(CanAnyFunctionType srcType, CanAnyFunctionType destType);
private:
void checkTuple(CanTupleType srcType, CanTupleType destType);
};
} // end anonymous namespace
void CheckConversionAvailability::check(CanType srcType, CanType destType) {
if (srcType == destType)
return;
// We care about specific optionality structure here: converting
// `(any P<T>)?` to `Any?` doesn't require metadata for `any P<T>`,
// but converting `(any P<T>)?` to non-optional `Any` does.
if (auto destObjectType = destType.getOptionalObjectType()) {
// optional -> optional conversion
if (auto srcObjectType = srcType.getOptionalObjectType()) {
check(srcObjectType, destObjectType);
// optional injection
} else {
check(srcType, destObjectType);
}
// Conversions to existential types require type metadata for the
// source type, except that we look into existentials.
} else if (destType.isAnyExistentialType()) {
checkTypeMetadataAvailabilityForConverted(srcType, refLoc, refDC);
// Conversions between function types perform a bunch of recursive
// conversions.
} else if (auto destFnType = dyn_cast<AnyFunctionType>(destType)) {
if (auto srcFnType = dyn_cast<AnyFunctionType>(srcType)) {
checkFunction(srcFnType, destFnType);
}
// Conversions between tuple types perform a bunch of recursive
// conversions.
} else if (auto destTupleType = dyn_cast<TupleType>(destType)) {
if (auto srcTupleType = dyn_cast<TupleType>(srcType)) {
checkTuple(srcTupleType, destTupleType);
}
// Conversions of things containing pack expansions convert the
// expansion patterns. We won't print the types we get here, so
// we can ignore them.
} else if (auto destExpType = dyn_cast<PackExpansionType>(destType)) {
if (auto srcExpType = dyn_cast<PackExpansionType>(srcType)) {
check(srcExpType.getPatternType(), destExpType.getPatternType());
}
}
}
void CheckConversionAvailability::checkFunction(CanAnyFunctionType srcType,
CanAnyFunctionType destType) {
// Results are covariantly converted.
check(srcType.getResult(), destType.getResult());
// Defensively ignored invalid conversion structure.
if (srcType->getNumParams() != destType->getNumParams())
return;
// Parameters are contravariantly converted.
for (auto i : range(srcType->getNumParams())) {
const auto &srcParam = srcType.getParams()[i];
const auto &destParam = destType.getParams()[i];
// Note the reversal for contravariance.
check(destParam.getParameterType(), srcParam.getParameterType());
}
}
void CheckConversionAvailability::checkTuple(CanTupleType srcType,
CanTupleType destType) {
// Handle invalid structure appropriately.
if (srcType->getNumElements() != destType->getNumElements())
return;
for (auto i : range(srcType->getNumElements())) {
check(srcType.getElementType(i), destType.getElementType(i));
}
}
static void checkFunctionConversionAvailability(Type srcType, Type destType,
SourceRange refLoc,
const DeclContext *refDC) {
if (srcType && destType) {
auto srcFnType = cast<AnyFunctionType>(srcType->getCanonicalType());
auto destFnType = cast<AnyFunctionType>(destType->getCanonicalType());
CheckConversionAvailability(refLoc, refDC)
.checkFunction(srcFnType, destFnType);
}
}
bool swift::diagnoseExplicitUnavailability(
const ValueDecl *D,
SourceRange R,
const ExportContext &Where,
DeclAvailabilityFlags Flags,
llvm::function_ref<void(InFlightDiagnostic &)> attachRenameFixIts) {
auto *Attr = AvailableAttr::isUnavailable(D);
if (!Attr)
return false;
// Calling unavailable code from within code with the same
// unavailability is OK -- the eventual caller can't call the
// enclosing code in the same situations it wouldn't be able to
// call this code.
if (isInsideCompatibleUnavailableDeclaration(D, Where, Attr))
return false;
SourceLoc Loc = R.Start;
ASTContext &ctx = D->getASTContext();
auto &diags = ctx.Diags;
StringRef platform;
switch (Attr->getPlatformAgnosticAvailability()) {
case PlatformAgnosticAvailabilityKind::Deprecated:
llvm_unreachable("shouldn't see deprecations in explicit unavailability");
case PlatformAgnosticAvailabilityKind::NoAsync:
llvm_unreachable("shouldn't see noasync with explicit unavailability");
case PlatformAgnosticAvailabilityKind::None:
case PlatformAgnosticAvailabilityKind::Unavailable:
if (Attr->Platform != PlatformKind::none) {
// This was platform-specific; indicate the platform.
platform = Attr->prettyPlatformString();
break;
}
LLVM_FALLTHROUGH;
case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific:
case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific:
// We don't want to give further detail about these.
platform = "";
break;
case PlatformAgnosticAvailabilityKind::UnavailableInSwift:
if (shouldAllowReferenceToUnavailableInSwiftDeclaration(D, Where))
return true;
platform = "Swift";
break;
}
// TODO: Consider removing this.
// ObjC keypaths components weren't checked previously, so errors are demoted
// to warnings to avoid source breakage. In some cases unavailable or
// obsolete decls still map to valid ObjC runtime names, so behave correctly
// at runtime, even though their use would produce an error outside of a
// #keyPath expression.
auto limit = Flags.contains(DeclAvailabilityFlag::ForObjCKeyPath)
? DiagnosticBehavior::Warning
: DiagnosticBehavior::Unspecified;
if (!Attr->Rename.empty()) {
SmallString<32> newNameBuf;
std::optional<ReplacementDeclKind> replaceKind =
describeRename(ctx, Attr, D, newNameBuf);
unsigned rawReplaceKind = static_cast<unsigned>(
replaceKind.value_or(ReplacementDeclKind::None));
StringRef newName = replaceKind ? newNameBuf.str() : Attr->Rename;
EncodedDiagnosticMessage EncodedMessage(Attr->Message);
auto diag =
diags.diagnose(Loc, diag::availability_decl_unavailable_rename,
D, replaceKind.has_value(),
rawReplaceKind, newName, EncodedMessage.Message);
diag.limitBehavior(limit);
attachRenameFixIts(diag);
} else if (isSubscriptReturningString(D, ctx)) {
diags.diagnose(Loc, diag::availability_string_subscript_migration)
.highlight(R)
.fixItInsert(R.Start, "String(")
.fixItInsertAfter(R.End, ")");
// Skip the note emitted below.
return true;
} else {
auto unavailableDiagnosticPlatform = platform;
AvailabilityInference::updatePlatformStringForFallback(Attr, ctx, unavailableDiagnosticPlatform);
EncodedDiagnosticMessage EncodedMessage(Attr->Message);
diags
.diagnose(Loc, diag::availability_decl_unavailable, D, platform.empty(),
unavailableDiagnosticPlatform, EncodedMessage.Message)
.highlight(R)
.limitBehavior(limit);
}
switch (Attr->getVersionAvailability(ctx)) {
case AvailableVersionComparison::Available:
case AvailableVersionComparison::PotentiallyUnavailable:
llvm_unreachable("These aren't considered unavailable");
case AvailableVersionComparison::Unavailable:
if ((Attr->isLanguageVersionSpecific() ||
Attr->isPackageDescriptionVersionSpecific())
&& Attr->Introduced.has_value())
diags.diagnose(D, diag::availability_introduced_in_version, D,
(Attr->isLanguageVersionSpecific() ?
"Swift" : "PackageDescription"),
*Attr->Introduced)
.highlight(Attr->getRange());
else
diags.diagnose(D, diag::availability_marked_unavailable, D)
.highlight(Attr->getRange());
break;
case AvailableVersionComparison::Obsoleted:
// FIXME: Use of the platformString here is non-awesome for application
// extensions.
StringRef platformDisplayString;
if (Attr->isLanguageVersionSpecific()) {
platformDisplayString = "Swift";
} else if (Attr->isPackageDescriptionVersionSpecific()) {
platformDisplayString = "PackageDescription";
} else {
platformDisplayString = platform;
}
diags.diagnose(D, diag::availability_obsoleted, D, platformDisplayString,
*Attr->Obsoleted)
.highlight(Attr->getRange());
break;
}
return true;
}
namespace {
class ExprAvailabilityWalker : public ASTWalker {
/// Models how member references will translate to accessor usage. This is
/// used to diagnose the availability of individual accessors that may be
/// called by the expression being checked.
enum class MemberAccessContext : unsigned {
/// The starting access context for the root of any expression tree. In this
/// context, a member access will call the get accessor only.
Default,
/// The access context for expressions rooted in a LoadExpr. A LoadExpr
/// coerces l-values to r-values and thus member access inside of a LoadExpr
/// will only invoke get accessors.
Load,
/// The access context for the outermost member accessed in the expression
/// tree on the left-hand side of an assignment. Only the set accessor will
/// be invoked on this member.
Assignment,
/// The access context for expressions in which member is being read and
/// then written back to. For example, a writeback will occur inside of an
/// InOutExpr. Both the get and set accessors may be called in this context.
Writeback
};
ASTContext &Context;
MemberAccessContext AccessContext = MemberAccessContext::Default;
SmallVector<const Expr *, 16> ExprStack;
SmallVector<bool, 4> PreconcurrencyCalleeStack;
const ExportContext &Where;
public:
explicit ExprAvailabilityWalker(const ExportContext &Where)
: Context(Where.getDeclContext()->getASTContext()), Where(Where) {}
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
MacroWalking getMacroWalkingBehavior() const override {
// Expanded source should be type checked and diagnosed separately.
return MacroWalking::Arguments;
}
PreWalkAction walkToArgumentPre(const Argument &Arg) override {
// Arguments should be walked in their own member access context which
// starts out read-only by default.
walkInContext(Arg.getExpr(), MemberAccessContext::Default);
return Action::SkipChildren();
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
auto *DC = Where.getDeclContext();
ExprStack.push_back(E);
if (auto *apply = dyn_cast<ApplyExpr>(E)) {
bool preconcurrency = false;
auto *fn = apply->getFn();
if (auto *selfApply = dyn_cast<SelfApplyExpr>(fn)) {
fn = selfApply->getFn();
}
auto declRef = fn->getReferencedDecl();
if (auto *decl = declRef.getDecl()) {
preconcurrency = decl->preconcurrency();
}
PreconcurrencyCalleeStack.push_back(preconcurrency);
}
if (auto DR = dyn_cast<DeclRefExpr>(E)) {
diagnoseDeclRefAvailability(DR->getDeclRef(), DR->getSourceRange(),
getEnclosingApplyExpr(), std::nullopt);
maybeDiagStorageAccess(DR->getDecl(), DR->getSourceRange(), DC);
}
if (auto MR = dyn_cast<MemberRefExpr>(E)) {
walkMemberRef(MR);
return Action::SkipChildren(E);
}
if (auto OCDR = dyn_cast<OtherConstructorDeclRefExpr>(E))
diagnoseDeclRefAvailability(OCDR->getDeclRef(),
OCDR->getConstructorLoc().getSourceRange(),
getEnclosingApplyExpr());
if (auto DMR = dyn_cast<DynamicMemberRefExpr>(E))
diagnoseDeclRefAvailability(DMR->getMember(),
DMR->getNameLoc().getSourceRange(),
getEnclosingApplyExpr());
if (auto DS = dyn_cast<DynamicSubscriptExpr>(E))
diagnoseDeclRefAvailability(DS->getMember(), DS->getSourceRange());
if (auto S = dyn_cast<SubscriptExpr>(E)) {
if (S->hasDecl()) {
diagnoseDeclRefAvailability(S->getDecl(), S->getSourceRange(), S);
maybeDiagStorageAccess(S->getDecl().getDecl(), S->getSourceRange(), DC);
}
}
if (auto *LE = dyn_cast<LiteralExpr>(E)) {
if (auto literalType = LE->getType()) {
// Check availability of the type produced by implicit literal
// initializer.
if (auto *nominalDecl = literalType->getAnyNominal()) {
diagnoseDeclAvailability(nominalDecl, LE->getSourceRange(),
/*call=*/nullptr, Where);
}
}
diagnoseDeclRefAvailability(LE->getInitializer(), LE->getSourceRange());
}
if (auto *CE = dyn_cast<CollectionExpr>(E)) {
// Diagnose availability of implicit collection literal initializers.
diagnoseDeclRefAvailability(CE->getInitializer(), CE->getSourceRange());
}
if (auto *FCE = dyn_cast<FunctionConversionExpr>(E)) {
checkFunctionConversionAvailability(FCE->getSubExpr()->getType(),
FCE->getType(),
FCE->getLoc(),
Where.getDeclContext());
}
if (auto KP = dyn_cast<KeyPathExpr>(E)) {
maybeDiagKeyPath(KP);
}
if (auto A = dyn_cast<AssignExpr>(E)) {
walkAssignExpr(A);
return Action::SkipChildren(E);
}
if (auto IO = dyn_cast<InOutExpr>(E)) {
walkInOutExpr(IO);
return Action::SkipChildren(E);
}
if (auto T = dyn_cast<TypeExpr>(E)) {
if (!T->isImplicit()) {
diagnoseTypeAvailability(T->getTypeRepr(), T->getType(), E->getLoc(),
Where);
}
}
if (auto CE = dyn_cast<ClosureExpr>(E)) {
for (auto *param : *CE->getParameters()) {
diagnoseTypeAvailability(param->getTypeRepr(), param->getInterfaceType(),
E->getLoc(), Where);
}
diagnoseTypeAvailability(CE->hasExplicitResultType()
? CE->getExplicitResultTypeRepr()
: nullptr,
CE->getResultType(), E->getLoc(), Where);
}
if (AbstractClosureExpr *closure = dyn_cast<AbstractClosureExpr>(E)) {
if (shouldWalkIntoClosure(closure)) {
walkAbstractClosure(closure);
return Action::SkipChildren(E);
}
}
if (auto CE = dyn_cast<ExplicitCastExpr>(E)) {
if (!isa<CoerceExpr>(CE)) {
SourceLoc loc = CE->getCastTypeRepr() ? CE->getCastTypeRepr()->getLoc()
: E->getLoc();
checkTypeMetadataAvailability(CE->getCastType(), loc,
Where.getDeclContext());
checkTypeMetadataAvailabilityForConverted(CE->getSubExpr()->getType(),
loc, Where.getDeclContext());
}
diagnoseTypeAvailability(CE->getCastTypeRepr(), CE->getCastType(),
E->getLoc(), Where);
}
if (auto EE = dyn_cast<ErasureExpr>(E)) {
checkTypeMetadataAvailability(EE->getSubExpr()->getType(),
EE->getLoc(), Where.getDeclContext());
checkInverseGenericsCastingAvailability(EE->getSubExpr()->getType(),
EE->getLoc(),
Where.getDeclContext());
bool preconcurrency = false;
if (!PreconcurrencyCalleeStack.empty()) {
preconcurrency = PreconcurrencyCalleeStack.back();
}
for (ProtocolConformanceRef C : EE->getConformances()) {
diagnoseConformanceAvailability(E->getLoc(), C, Where, Type(), Type(),
/*useConformanceAvailabilityErrorsOpt=*/true,
/*preconcurrency=*/preconcurrency);
}
}
if (auto UTO = dyn_cast<UnderlyingToOpaqueExpr>(E)) {
diagnoseSubstitutionMapAvailability(
UTO->getLoc(), UTO->substitutions, Where);
}
if (auto ME = dyn_cast<MacroExpansionExpr>(E)) {
diagnoseDeclRefAvailability(
ME->getMacroRef(), ME->getMacroNameLoc().getSourceRange());
}
if (auto LE = dyn_cast<LoadExpr>(E)) {
walkLoadExpr(LE);
return Action::SkipChildren(E);
}
return Action::Continue(E);
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
assert(ExprStack.back() == E);
ExprStack.pop_back();
if (auto *apply = dyn_cast<ApplyExpr>(E)) {
PreconcurrencyCalleeStack.pop_back();
}
return Action::Continue(E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
// We end up here when checking the output of the result builder transform,
// which includes closures that are not "separately typechecked" and yet
// contain statements and declarations. We need to walk them recursively,
// since these availability for these statements is not diagnosed from
// typeCheckStmt() as usual.
diagnoseStmtAvailability(S, Where.getDeclContext(), /*walkRecursively=*/true);
return Action::SkipNode(S);
}
bool
diagnoseDeclRefAvailability(ConcreteDeclRef declRef, SourceRange R,
const Expr *call = nullptr,
DeclAvailabilityFlags flags = std::nullopt) const;
private:
bool diagnoseIncDecRemoval(const ValueDecl *D, SourceRange R,
const AvailableAttr *Attr) const;
bool diagnoseMemoryLayoutMigration(const ValueDecl *D, SourceRange R,
const AvailableAttr *Attr,
const ApplyExpr *call) const;
/// Walks up from a potential callee to the enclosing ApplyExpr.
const ApplyExpr *getEnclosingApplyExpr() const {
ArrayRef<const Expr *> parents = ExprStack;
assert(!parents.empty() && "must be called while visiting an expression");
size_t idx = parents.size() - 1;
do {
if (idx == 0)
return nullptr;
--idx;
} while (isa<DotSyntaxBaseIgnoredExpr>(parents[idx]) || // Mod.f(a)
isa<SelfApplyExpr>(parents[idx]) || // obj.f(a)
isa<IdentityExpr>(parents[idx]) || // (f)(a)
isa<ForceValueExpr>(parents[idx]) || // f!(a)
isa<BindOptionalExpr>(parents[idx]) || // f?(a)
isa<FunctionConversionExpr>(parents[idx]));
auto *call = dyn_cast<ApplyExpr>(parents[idx]);
if (!call || call->getFn() != parents[idx+1])
return nullptr;
return call;
}
/// Walk an assignment expression, checking for availability.
void walkAssignExpr(AssignExpr *E) {
// We take over recursive walking of assignment expressions in order to
// walk the destination and source expressions in different member
// access contexts.
Expr *Dest = E->getDest();
if (!Dest) {
return;
}
// Check the Dest expression in a setter context.
// We have an implicit assumption here that the first MemberRefExpr
// encountered walking (pre-order) is the Dest is the destination of the
// write. For the moment this is fine -- but future syntax might violate
// this assumption.
walkInContext(Dest, MemberAccessContext::Assignment);
// Check RHS in getter context
Expr *Source = E->getSrc();
if (!Source) {
return;
}
walkInContext(Source, MemberAccessContext::Default);
}
/// Walk a load expression, checking for availability.
void walkLoadExpr(LoadExpr *E) {
walkInContext(E->getSubExpr(), MemberAccessContext::Load);
}
/// Walk a member reference expression, checking for availability.
void walkMemberRef(MemberRefExpr *E) {
// Walk the base. If the access context is currently `Assignment`, then we
// must be diagnosing the destination of an assignment. When recursing,
// diagnose any remaining member refs in a `Writeback` context, since
// there is a writeback occurring through them as a result of the
// assignment.
//
// someVar.x.y = 1
// │ ╰─ MemberAccessContext::Assignment
// ╰─── MemberAccessContext::Writeback
//
MemberAccessContext accessContext =
(AccessContext == MemberAccessContext::Assignment)
? MemberAccessContext::Writeback
: AccessContext;
walkInContext(E->getBase(), accessContext);
ConcreteDeclRef DR = E->getMember();
// Diagnose for the member declaration itself.
if (diagnoseDeclRefAvailability(DR, E->getNameLoc().getSourceRange(),
getEnclosingApplyExpr(), std::nullopt))
return;
// Diagnose for appropriate accessors, given the access context.
auto *DC = Where.getDeclContext();
maybeDiagStorageAccess(DR.getDecl(), E->getSourceRange(), DC);
}
/// Walk a keypath expression, checking all of its components for
/// availability.
void maybeDiagKeyPath(KeyPathExpr *KP) {
auto flags = DeclAvailabilityFlags();
auto declContext = Where.getDeclContext();
if (KP->isObjC())
flags = DeclAvailabilityFlag::ForObjCKeyPath;
for (auto &component : KP->getComponents()) {
switch (component.getKind()) {
case KeyPathExpr::Component::Kind::Property:
case KeyPathExpr::Component::Kind::Subscript: {
auto decl = component.getDeclRef();
auto loc = component.getLoc();
auto range = component.getSourceRange();
if (diagnoseDeclRefAvailability(decl, loc, nullptr, flags))
break;
maybeDiagStorageAccess(decl.getDecl(), range, declContext);
break;
}
case KeyPathExpr::Component::Kind::TupleElement:
break;
case KeyPathExpr::Component::Kind::Invalid:
case KeyPathExpr::Component::Kind::UnresolvedProperty:
case KeyPathExpr::Component::Kind::UnresolvedSubscript:
case KeyPathExpr::Component::Kind::OptionalChain:
case KeyPathExpr::Component::Kind::OptionalWrap:
case KeyPathExpr::Component::Kind::OptionalForce:
case KeyPathExpr::Component::Kind::Identity:
case KeyPathExpr::Component::Kind::DictionaryKey:
case KeyPathExpr::Component::Kind::CodeCompletion:
break;
}
}
}
/// Walk an inout expression, checking for availability.
void walkInOutExpr(InOutExpr *E) {
// Typically an InOutExpr should begin a `Writeback` context. However,
// inside a LoadExpr this transition is suppressed since the entire
// expression is being coerced to an r-value.
auto accessContext = AccessContext != MemberAccessContext::Load
? MemberAccessContext::Writeback
: AccessContext;
walkInContext(E->getSubExpr(), accessContext);
}
bool shouldWalkIntoClosure(AbstractClosureExpr *closure) const {
return true;
}
/// Walk an abstract closure expression, checking for availability
void walkAbstractClosure(AbstractClosureExpr *closure) {
// Do the walk with the closure set as the decl context of the 'where'
auto where = ExportContext::forFunctionBody(closure, closure->getStartLoc());
if (where.isImplicit())
return;
ExprAvailabilityWalker walker(where);
// Manually dive into the body
closure->getBody()->walk(walker);
return;
}
/// Walk the given expression in the member access context.
void walkInContext(Expr *E, MemberAccessContext AccessContext) {
llvm::SaveAndRestore<MemberAccessContext>
C(this->AccessContext, AccessContext);
E->walk(*this);
}
/// Emit diagnostics, if necessary, for accesses to storage where
/// the accessor for the AccessContext is not available.
void maybeDiagStorageAccess(const ValueDecl *VD,
SourceRange ReferenceRange,
const DeclContext *ReferenceDC) const {
if (Context.LangOpts.DisableAvailabilityChecking)
return;
auto *D = dyn_cast<AbstractStorageDecl>(VD);
if (!D)
return;
if (!D->requiresOpaqueAccessors()) {
return;
}
// Check availability of accessor functions.
// TODO: if we're talking about an inlineable storage declaration,
// this probably needs to be refined to not assume that the accesses are
// specifically using the getter/setter.
switch (AccessContext) {
case MemberAccessContext::Default:
case MemberAccessContext::Load:
diagAccessorAvailability(D->getOpaqueAccessor(AccessorKind::Get),
ReferenceRange, ReferenceDC, std::nullopt);
break;
case MemberAccessContext::Assignment:
diagAccessorAvailability(D->getOpaqueAccessor(AccessorKind::Set),
ReferenceRange, ReferenceDC, std::nullopt);
break;
case MemberAccessContext::Writeback:
diagAccessorAvailability(D->getOpaqueAccessor(AccessorKind::Get),
ReferenceRange, ReferenceDC,
DeclAvailabilityFlag::ForInout);
diagAccessorAvailability(D->getOpaqueAccessor(AccessorKind::Set),
ReferenceRange, ReferenceDC,
DeclAvailabilityFlag::ForInout);
break;
}
}
/// Emit a diagnostic, if necessary for a potentially unavailable accessor.
void diagAccessorAvailability(AccessorDecl *D, SourceRange ReferenceRange,
const DeclContext *ReferenceDC,
DeclAvailabilityFlags Flags) const {
if (!D)
return;
Flags &= DeclAvailabilityFlag::ForInout;
Flags |= DeclAvailabilityFlag::ContinueOnPotentialUnavailability;
if (diagnoseDeclAvailability(D, ReferenceRange, /*call*/ nullptr, Where,
Flags))
return;
}
};
} // end anonymous namespace
/// Diagnose uses of unavailable declarations. Returns true if a diagnostic
/// was emitted.
bool ExprAvailabilityWalker::diagnoseDeclRefAvailability(
ConcreteDeclRef declRef, SourceRange R, const Expr *call,
DeclAvailabilityFlags Flags) const {
if (!declRef)
return false;
const ValueDecl *D = declRef.getDecl();
// Suppress availability diagnostics for uses of builtins. We don't
// synthesize availability for builtin functions anyway, so this really
// means to not check availability for the substitution maps. This is
// abstractly reasonable, since calls to generic builtins usually do not
// require metadata for generic arguments the same way that calls to
// generic functions might. More importantly, the stdlib has to get the
// availability right anyway, and diagnostics from builtin usage are not
// likely to be of significant assistance in that.
if (D->getModuleContext()->isBuiltinModule())
return false;
if (auto *attr = AvailableAttr::isUnavailable(D)) {
if (diagnoseIncDecRemoval(D, R, attr))
return true;
if (isa_and_nonnull<ApplyExpr>(call) &&
diagnoseMemoryLayoutMigration(D, R, attr, cast<ApplyExpr>(call)))
return true;
}
if (diagnoseDeclAvailability(D, R, call, Where, Flags))
return true;
if (R.isValid()) {
if (diagnoseSubstitutionMapAvailability(
R.Start, declRef.getSubstitutions(), Where,
Type(), Type(),
/*warnIfConformanceUnavailablePreSwift6*/false,
/*suppressParameterizationCheckForOptional*/false,
/*preconcurrency*/D->preconcurrency())) {
return true;
}
}
return false;
}
/// Diagnose misuses of API in asynchronous contexts.
/// Returns true if a fatal diagnostic was emitted, false otherwise.
static bool
diagnoseDeclAsyncAvailability(const ValueDecl *D, SourceRange R,
const Expr *call, const ExportContext &Where) {
// If we are not in an (effective) async context, don't check it
if (!shouldTreatDeclContextAsAsyncForDiagnostics(Where.getDeclContext()))
return false;
ASTContext &ctx = Where.getDeclContext()->getASTContext();
// Only suggest async alternatives if the DeclContext is truly async
if (Where.getDeclContext()->isAsyncContext()) {
if (const AbstractFunctionDecl *afd = dyn_cast<AbstractFunctionDecl>(D)) {
if (const AbstractFunctionDecl *asyncAlt = afd->getAsyncAlternative()) {
SourceLoc diagLoc = call ? call->getLoc() : R.Start;
ctx.Diags.diagnose(diagLoc, diag::warn_use_async_alternative);
asyncAlt->diagnose(diag::decl_declared_here, asyncAlt);
}
}
}
// @available(noasync) spelling
if (const AvailableAttr *attr = D->getAttrs().getNoAsync(ctx)) {
SourceLoc diagLoc = call ? call->getLoc() : R.Start;
auto diag = ctx.Diags.diagnose(diagLoc, diag::async_unavailable_decl,
D, attr->Message);
diag.warnUntilSwiftVersion(6);
if (!attr->Rename.empty()) {
fixItAvailableAttrRename(diag, R, D, attr, call);
}
return true;
}
const bool hasUnavailableAttr =
D->getAttrs().hasAttribute<UnavailableFromAsyncAttr>();
if (!hasUnavailableAttr)
return false;
// @_unavailableFromAsync spelling
const UnavailableFromAsyncAttr *attr =
D->getAttrs().getAttribute<UnavailableFromAsyncAttr>();
SourceLoc diagLoc = call ? call->getLoc() : R.Start;
ctx.Diags
.diagnose(diagLoc, diag::async_unavailable_decl, D, attr->Message)
.warnUntilSwiftVersion(6);
D->diagnose(diag::decl_declared_here, D);
return true;
}
/// Diagnose uses of unavailable declarations. Returns true if a diagnostic
/// was emitted.
bool swift::diagnoseDeclAvailability(const ValueDecl *D, SourceRange R,
const Expr *call,
const ExportContext &Where,
DeclAvailabilityFlags Flags) {
assert(!Where.isImplicit());
// Generic parameters are always available.
if (isa<GenericTypeParamDecl>(D))
return false;
// Keep track if this is an accessor.
auto accessor = dyn_cast<AccessorDecl>(D);
if (accessor) {
// If the property/subscript is unconditionally unavailable, don't bother
// with any of the rest of this.
if (AvailableAttr::isUnavailable(accessor->getStorage()))
return false;
}
if (R.isValid()) {
if (TypeChecker::diagnoseInlinableDeclRefAccess(R.Start, D, Where))
return true;
if (TypeChecker::diagnoseDeclRefExportability(R.Start, D, Where))
return true;
}
if (diagnoseExplicitUnavailability(D, R, Where, call, Flags))
return true;
if (diagnoseDeclAsyncAvailability(D, R, call, Where))
return true;
// Make sure not to diagnose an accessor's deprecation if we already
// complained about the property/subscript.
bool isAccessorWithDeprecatedStorage =
accessor && TypeChecker::getDeprecated(accessor->getStorage());
// Diagnose for deprecation
if (!isAccessorWithDeprecatedStorage)
TypeChecker::diagnoseIfDeprecated(R, Where, D, call);
if (Flags.contains(DeclAvailabilityFlag::AllowPotentiallyUnavailableProtocol)
&& isa<ProtocolDecl>(D))
return false;
// Diagnose (and possibly signal) for potential unavailability
auto maybeUnavail = TypeChecker::checkDeclarationAvailability(D, Where);
if (!maybeUnavail.has_value())
return false;
auto unavailReason = maybeUnavail.value();
auto *DC = Where.getDeclContext();
if (Flags.contains(
DeclAvailabilityFlag::
AllowPotentiallyUnavailableAtOrBelowDeploymentTarget) &&
unavailReason.requiresDeploymentTargetOrEarlier(DC->getASTContext()))
return false;
if (accessor) {
bool forInout = Flags.contains(DeclAvailabilityFlag::ForInout);
TypeChecker::diagnosePotentialAccessorUnavailability(
accessor, R, DC, unavailReason, forInout);
} else {
if (!TypeChecker::diagnosePotentialUnavailability(D, R, DC, unavailReason))
return false;
}
return !Flags.contains(
DeclAvailabilityFlag::ContinueOnPotentialUnavailability);
}
/// Return true if the specified type looks like an integer of floating point
/// type.
static bool isIntegerOrFloatingPointType(Type ty, ModuleDecl *M) {
return (TypeChecker::conformsToKnownProtocol(
ty, KnownProtocolKind::ExpressibleByIntegerLiteral, M) ||
TypeChecker::conformsToKnownProtocol(
ty, KnownProtocolKind::ExpressibleByFloatLiteral, M));
}
/// If this is a call to an unavailable ++ / -- operator, try to diagnose it
/// with a fixit hint and return true. If not, or if we fail, return false.
bool
ExprAvailabilityWalker::diagnoseIncDecRemoval(const ValueDecl *D, SourceRange R,
const AvailableAttr *Attr) const {
// We can only produce a fixit if we're talking about ++ or --.
bool isInc = D->getBaseName() == "++";
if (!isInc && D->getBaseName() != "--")
return false;
// We can only handle the simple cases of lvalue++ and ++lvalue. This is
// always modeled as:
// (postfix_unary_expr (declrefexpr ++), (inoutexpr (lvalue)))
// if not, bail out.
if (ExprStack.size() != 2 ||
!isa<DeclRefExpr>(ExprStack[1]) ||
!(isa<PostfixUnaryExpr>(ExprStack[0]) ||
isa<PrefixUnaryExpr>(ExprStack[0])))
return false;
auto call = cast<ApplyExpr>(ExprStack[0]);
// If the expression type is integer or floating point, then we can rewrite it
// to "lvalue += 1".
auto *DC = Where.getDeclContext();
std::string replacement;
if (isIntegerOrFloatingPointType(call->getType(), DC->getParentModule()))
replacement = isInc ? " += 1" : " -= 1";
else {
// Otherwise, it must be an index type. Rewrite to:
// "lvalue = lvalue.successor()".
auto &SM = Context.SourceMgr;
auto CSR = Lexer::getCharSourceRangeFromSourceRange(
SM, call->getArgs()->getSourceRange());
replacement = " = " + SM.extractText(CSR).str();
replacement += isInc ? ".successor()" : ".predecessor()";
}
if (!replacement.empty()) {
// If we emit a deprecation diagnostic, produce a fixit hint as well.
auto diag = Context.Diags.diagnose(
R.Start, diag::availability_decl_unavailable, D, true, "",
"it has been removed in Swift 3");
if (isa<PrefixUnaryExpr>(call)) {
// Prefix: remove the ++ or --.
diag.fixItRemove(call->getFn()->getSourceRange());
diag.fixItInsertAfter(call->getArgs()->getEndLoc(), replacement);
} else {
// Postfix: replace the ++ or --.
diag.fixItReplace(call->getFn()->getSourceRange(), replacement);
}
return true;
}
return false;
}
/// If this is a call to an unavailable sizeof family function, diagnose it
/// with a fixit hint and return true. If not, or if we fail, return false.
bool
ExprAvailabilityWalker::diagnoseMemoryLayoutMigration(const ValueDecl *D,
SourceRange R,
const AvailableAttr *Attr,
const ApplyExpr *call) const {
if (!D->getModuleContext()->isStdlibModule())
return false;
StringRef Property;
if (D->getBaseName() == "sizeof") {
Property = "size";
} else if (D->getBaseName() == "alignof") {
Property = "alignment";
} else if (D->getBaseName() == "strideof") {
Property = "stride";
}
if (Property.empty())
return false;
auto *args = call->getArgs();
auto *subject = args->getUnlabeledUnaryExpr();
if (!subject)
return false;
EncodedDiagnosticMessage EncodedMessage(Attr->Message);
auto diag =
Context.Diags.diagnose(
R.Start, diag::availability_decl_unavailable, D, true, "",
EncodedMessage.Message);
diag.highlight(R);
StringRef Prefix = "MemoryLayout<";
StringRef Suffix = ">.";
if (auto DTE = dyn_cast<DynamicTypeExpr>(subject)) {
// Replace `sizeof(type(of: x))` with `MemoryLayout<X>.size`, where `X` is
// the static type of `x`. The previous spelling misleadingly hinted that
// `sizeof(_:)` might return the size of the *dynamic* type of `x`, when
// it is not the case.
auto valueType = DTE->getBase()->getType()->getRValueType();
if (!valueType || valueType->hasError()) {
// If we don't have a suitable argument, we can't emit a fixit.
return true;
}
// Note that in rare circumstances we may be destructively replacing the
// source text. For example, we'd replace `sizeof(type(of: doSomething()))`
// with `MemoryLayout<T>.size`, if T is the return type of `doSomething()`.
diag.fixItReplace(call->getSourceRange(),
(Prefix + valueType->getString() + Suffix + Property).str());
} else {
SourceRange PrefixRange(call->getStartLoc(), args->getLParenLoc());
SourceRange SuffixRange(args->getRParenLoc());
// We must remove `.self`.
if (auto *DSE = dyn_cast<DotSelfExpr>(subject))
SuffixRange.Start = DSE->getDotLoc();
diag
.fixItReplace(PrefixRange, Prefix)
.fixItReplace(SuffixRange, (Suffix + Property).str());
}
return true;
}
/// Diagnose uses of unavailable declarations.
void swift::diagnoseExprAvailability(const Expr *E, DeclContext *DC) {
auto where = ExportContext::forFunctionBody(DC, E->getStartLoc());
if (where.isImplicit())
return;
ExprAvailabilityWalker walker(where);
const_cast<Expr*>(E)->walk(walker);
}
namespace {
class StmtAvailabilityWalker : public BaseDiagnosticWalker {
DeclContext *DC;
bool WalkRecursively;
public:
explicit StmtAvailabilityWalker(DeclContext *dc, bool walkRecursively)
: DC(dc), WalkRecursively(walkRecursively) {}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
if (!WalkRecursively && isa<BraceStmt>(S))
return Action::SkipNode(S);
return Action::Continue(S);
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (WalkRecursively)
diagnoseExprAvailability(E, DC);
return Action::SkipNode(E);
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
auto where = ExportContext::forFunctionBody(DC, T->getStartLoc());
diagnoseTypeReprAvailability(T, where);
return Action::SkipNode();
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *P) override {
if (auto *IP = dyn_cast<IsPattern>(P)) {
auto where = ExportContext::forFunctionBody(DC, P->getLoc());
diagnoseTypeAvailability(IP->getCastType(), P->getLoc(), where);
}
return Action::Continue(P);
}
};
}
void swift::diagnoseStmtAvailability(const Stmt *S, DeclContext *DC,
bool walkRecursively) {
// We'll visit the individual statements when we check them.
if (!walkRecursively && isa<BraceStmt>(S))
return;
StmtAvailabilityWalker walker(DC, walkRecursively);
const_cast<Stmt*>(S)->walk(walker);
}
namespace {
class TypeReprAvailabilityWalker : public ASTWalker {
const ExportContext &where;
DeclAvailabilityFlags flags;
bool checkDeclRefTypeRepr(DeclRefTypeRepr *declRefTR) const {
ArrayRef<AssociatedTypeDecl *> primaryAssociatedTypes;
if (auto *qualIdentTR = dyn_cast<QualifiedIdentTypeRepr>(declRefTR)) {
// If the base is unavailable, don't go on to diagnose
// the member since that will just produce a redundant
// diagnostic.
if (diagnoseTypeReprAvailability(qualIdentTR->getBase(), where, flags)) {
return true;
}
}
if (auto *typeDecl = declRefTR->getBoundDecl()) {
auto range = declRefTR->getNameLoc().getSourceRange();
if (diagnoseDeclAvailability(typeDecl, range, nullptr, where, flags))
return true;
if (auto protocol = dyn_cast<ProtocolDecl>(typeDecl)) {
primaryAssociatedTypes = protocol->getPrimaryAssociatedTypes();
}
}
bool foundAnyIssues = false;
if (declRefTR->hasGenericArgList()) {
auto genericFlags = flags;
genericFlags -= DeclAvailabilityFlag::AllowPotentiallyUnavailableProtocol;
for (auto *genericArg : declRefTR->getGenericArgs()) {
if (diagnoseTypeReprAvailability(genericArg, where, genericFlags))
foundAnyIssues = true;
// The associated type that is being specified must be available as
// well.
if (!primaryAssociatedTypes.empty()) {
auto primaryAssociatedType = primaryAssociatedTypes.front();
primaryAssociatedTypes = primaryAssociatedTypes.drop_front();
if (diagnoseDeclAvailability(
primaryAssociatedType, genericArg->getSourceRange(),
nullptr, where, genericFlags))
foundAnyIssues = true;
}
}
}
return foundAnyIssues;
}
public:
bool foundAnyIssues = false;
TypeReprAvailabilityWalker(const ExportContext &where,
DeclAvailabilityFlags flags)
: where(where), flags(flags) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
auto *declRefTR = dyn_cast<DeclRefTypeRepr>(T);
if (!declRefTR)
return Action::Continue();
if (checkDeclRefTypeRepr(declRefTR)) {
foundAnyIssues = true;
}
// We've already visited all the children above, so we don't
// need to recurse.
return Action::SkipNode();
}
};
}
bool swift::diagnoseTypeReprAvailability(const TypeRepr *T,
const ExportContext &where,
DeclAvailabilityFlags flags) {
if (!T)
return false;
TypeReprAvailabilityWalker walker(where, flags);
const_cast<TypeRepr*>(T)->walk(walker);
return walker.foundAnyIssues;
}
namespace {
class ProblematicTypeFinder : public TypeDeclFinder {
SourceLoc Loc;
const ExportContext &Where;
DeclAvailabilityFlags Flags;
public:
ProblematicTypeFinder(SourceLoc Loc, const ExportContext &Where,
DeclAvailabilityFlags Flags)
: Loc(Loc), Where(Where), Flags(Flags) {}
void visitTypeDecl(TypeDecl *decl) {
// We only need to diagnose exportability here. Availability was
// already checked on the TypeRepr.
if (Where.mustOnlyReferenceExportedDecls())
TypeChecker::diagnoseDeclRefExportability(Loc, decl, Where);
}
Action visitNominalType(NominalType *ty) override {
visitTypeDecl(ty->getDecl());
// If some generic parameters are missing, don't check conformances.
if (ty->hasUnboundGenericType())
return Action::Continue;
// When the DeclContext parameter to getContextSubstitutionMap()
// is a protocol declaration, the receiver must be a concrete
// type, so it doesn't make sense to perform this check on
// protocol types.
if (isa<ProtocolType>(ty))
return Action::Continue;
ModuleDecl *useModule = Where.getDeclContext()->getParentModule();
auto subs = ty->getContextSubstitutionMap(useModule, ty->getDecl());
(void) diagnoseSubstitutionMapAvailability(Loc, subs, Where);
return Action::Continue;
}
Action visitBoundGenericType(BoundGenericType *ty) override {
visitTypeDecl(ty->getDecl());
ModuleDecl *useModule = Where.getDeclContext()->getParentModule();
auto subs = ty->getContextSubstitutionMap(useModule, ty->getDecl());
(void)diagnoseSubstitutionMapAvailability(
Loc, subs, Where,
/*depTy=*/Type(),
/*replacementTy=*/Type(),
/*warnIfConformanceUnavailablePreSwift6=*/false,
/*suppressParameterizationCheckForOptional=*/ty->isOptional(),
/*preconcurrency*/ty->getAnyNominal()->preconcurrency());
return Action::Continue;
}
Action visitTypeAliasType(TypeAliasType *ty) override {
visitTypeDecl(ty->getDecl());
auto subs = ty->getSubstitutionMap();
(void) diagnoseSubstitutionMapAvailability(Loc, subs, Where);
return Action::Continue;
}
// We diagnose unserializable Clang function types in the
// post-visitor so that we diagnose any unexportable component
// types first.
Action walkToTypePost(Type T) override {
if (Where.mustOnlyReferenceExportedDecls()) {
if (auto fnType = T->getAs<AnyFunctionType>()) {
if (auto clangType = fnType->getClangTypeInfo().getType()) {
auto *DC = Where.getDeclContext();
auto &ctx = DC->getASTContext();
auto loader = ctx.getClangModuleLoader();
// Serialization will serialize the sugared type if it can,
// but we need the canonical type to be serializable or else
// canonicalization (e.g. in SIL) might break things.
if (!loader->isSerializable(clangType, /*check canonical*/ true)) {
ctx.Diags.diagnose(Loc, diag::unexportable_clang_function_type, T);
}
}
}
}
return TypeDeclFinder::walkToTypePost(T);
}
};
}
void swift::diagnoseTypeAvailability(Type T, SourceLoc loc,
const ExportContext &where,
DeclAvailabilityFlags flags) {
if (!T)
return;
T.walk(ProblematicTypeFinder(loc, where, flags));
}
void swift::diagnoseTypeAvailability(const TypeRepr *TR, Type T, SourceLoc loc,
const ExportContext &where,
DeclAvailabilityFlags flags) {
if (diagnoseTypeReprAvailability(TR, where, flags))
return;
diagnoseTypeAvailability(T, loc, where, flags);
}
static void diagnoseMissingConformance(
SourceLoc loc, Type type, ProtocolDecl *proto, const DeclContext *fromDC,
bool preconcurrency) {
assert(proto->isSpecificProtocol(KnownProtocolKind::Sendable));
diagnoseMissingSendableConformance(loc, type, fromDC, preconcurrency);
}
bool
swift::diagnoseConformanceAvailability(SourceLoc loc,
ProtocolConformanceRef conformance,
const ExportContext &where,
Type depTy, Type replacementTy,
bool warnIfConformanceUnavailablePreSwift6,
bool preconcurrency) {
assert(!where.isImplicit());
if (conformance.isInvalid() || conformance.isAbstract())
return false;
if (conformance.isPack()) {
bool diagnosed = false;
auto *pack = conformance.getPack();
for (auto patternConf : pack->getPatternConformances()) {
diagnosed |= diagnoseConformanceAvailability(
loc, patternConf, where, depTy, replacementTy,
warnIfConformanceUnavailablePreSwift6,
preconcurrency);
}
return diagnosed;
}
const ProtocolConformance *concreteConf = conformance.getConcrete();
const RootProtocolConformance *rootConf = concreteConf->getRootConformance();
// Conformance to Copyable and Escapable doesn't have its own availability
// independent of the type.
if (rootConf->getProtocol()->getInvertibleProtocolKind())
return false;
// Diagnose "missing" conformances where we needed a conformance but
// didn't have one.
auto *DC = where.getDeclContext();
if (auto builtinConformance = dyn_cast<BuiltinProtocolConformance>(rootConf)){
if (builtinConformance->isMissing()) {
diagnoseMissingConformance(loc, builtinConformance->getType(),
builtinConformance->getProtocol(), DC,
preconcurrency);
}
}
auto maybeEmitAssociatedTypeNote = [&]() {
if (!depTy && !replacementTy)
return;
Type selfTy = rootConf->getProtocol()->getSelfInterfaceType();
if (!depTy->isEqual(selfTy)) {
auto &ctx = DC->getASTContext();
ctx.Diags.diagnose(
loc,
diag::assoc_conformance_from_implementation_only_module,
depTy, replacementTy->getCanonicalType());
}
};
if (auto *ext = dyn_cast<ExtensionDecl>(rootConf->getDeclContext())) {
if (TypeChecker::diagnoseConformanceExportability(loc, rootConf, ext, where,
warnIfConformanceUnavailablePreSwift6)) {
maybeEmitAssociatedTypeNote();
return true;
}
if (diagnoseExplicitUnavailability(loc, rootConf, ext, where,
warnIfConformanceUnavailablePreSwift6,
preconcurrency)) {
maybeEmitAssociatedTypeNote();
return true;
}
// Diagnose (and possibly signal) for potential unavailability
auto maybeUnavail = TypeChecker::checkConformanceAvailability(
rootConf, ext, where);
if (maybeUnavail.has_value()) {
TypeChecker::diagnosePotentialUnavailability(rootConf, ext, loc, DC,
maybeUnavail.value());
maybeEmitAssociatedTypeNote();
return true;
}
// Diagnose for deprecation
if (TypeChecker::diagnoseIfDeprecated(loc, rootConf, ext, where)) {
maybeEmitAssociatedTypeNote();
// Deprecation is just a warning, so keep going with checking the
// substitution map below.
}
}
// Now, check associated conformances.
SubstitutionMap subConformanceSubs = concreteConf->getSubstitutionMap();
if (diagnoseSubstitutionMapAvailability(loc, subConformanceSubs, where,
depTy, replacementTy,
warnIfConformanceUnavailablePreSwift6,
preconcurrency))
return true;
return false;
}
bool
swift::diagnoseSubstitutionMapAvailability(SourceLoc loc,
SubstitutionMap subs,
const ExportContext &where,
Type depTy, Type replacementTy,
bool warnIfConformanceUnavailablePreSwift6,
bool suppressParameterizationCheckForOptional,
bool preconcurrency) {
bool hadAnyIssues = false;
for (ProtocolConformanceRef conformance : subs.getConformances()) {
if (diagnoseConformanceAvailability(loc, conformance, where,
depTy, replacementTy,
warnIfConformanceUnavailablePreSwift6,
preconcurrency))
hadAnyIssues = true;
}
// If we're looking at \c (any P)? (or any other depth of optional) then
// there's no availability problem.
if (suppressParameterizationCheckForOptional)
return hadAnyIssues;
for (auto replacement : subs.getReplacementTypes()) {
if (checkTypeMetadataAvailability(replacement, loc, where.getDeclContext()))
hadAnyIssues = true;
}
return hadAnyIssues;
}
/// Should we warn that \p decl needs an explicit availability annotation
/// in -require-explicit-availability mode?
static bool declNeedsExplicitAvailability(const Decl *decl) {
auto &ctx = decl->getASTContext();
// Don't require an introduced version on platforms that don't support
// versioned availability.
if (!ctx.supportsVersionedAvailability())
return false;
// Skip non-public decls.
if (auto valueDecl = dyn_cast<const ValueDecl>(decl)) {
AccessScope scope =
valueDecl->getFormalAccessScope(/*useDC*/nullptr,
/*treatUsableFromInlineAsPublic*/true);
if (!scope.isPublic())
return false;
}
// Skip functions emitted into clients, SPI or implicit.
if (decl->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>() ||
decl->isSPI() ||
decl->isImplicit())
return false;
// Skip unavailable decls.
if (AvailableAttr::isUnavailable(decl))
return false;
// Warn on decls without an introduction version.
auto safeRangeUnderApprox = AvailabilityInference::availableRange(decl, ctx);
return !safeRangeUnderApprox.getOSVersion().hasLowerEndpoint();
}
void swift::checkExplicitAvailability(Decl *decl) {
// Skip if the command line option was not set and
// accessors as we check the pattern binding decl instead.
auto &ctx = decl->getASTContext();
auto DiagLevel = ctx.LangOpts.RequireExplicitAvailability;
if (!DiagLevel || isa<AccessorDecl>(decl))
return;
// Only look at decls at module level or in extensions.
// This could be changed to force having attributes on all decls.
if (!decl->getDeclContext()->isModuleScopeContext() &&
!isa<ExtensionDecl>(decl->getDeclContext())) return;
if (auto extension = dyn_cast<ExtensionDecl>(decl)) {
// decl should be either a ValueDecl or an ExtensionDecl.
auto extended = extension->getExtendedNominal();
if (!extended || !extended->getFormalAccessScope().isPublic())
return;
// Skip extensions without public members or conformances.
auto members = extension->getMembers();
auto hasMembers = std::any_of(members.begin(), members.end(),
[](const Decl *D) -> bool {
if (auto VD = dyn_cast<ValueDecl>(D))
if (declNeedsExplicitAvailability(VD))
return true;
return false;
});
auto hasProtocols = hasConformancesToPublicProtocols(extension);
if (!hasMembers && !hasProtocols) return;
} else if (auto pbd = dyn_cast<PatternBindingDecl>(decl)) {
// Check the first var instead.
if (pbd->getNumPatternEntries() == 0)
return;
llvm::SmallVector<VarDecl *, 2> vars;
pbd->getPattern(0)->collectVariables(vars);
if (vars.empty())
return;
decl = vars.front();
}
if (declNeedsExplicitAvailability(decl)) {
auto diag = decl->diagnose(diag::public_decl_needs_availability);
diag.limitBehavior(*DiagLevel);
auto suggestPlatform = ctx.LangOpts.RequireExplicitAvailabilityTarget;
if (!suggestPlatform.empty()) {
auto InsertLoc = decl->getAttrs().getStartLoc(/*forModifiers=*/false);
if (InsertLoc.isInvalid())
InsertLoc = decl->getStartLoc();
if (InsertLoc.isInvalid())
return;
std::string AttrText;
{
llvm::raw_string_ostream Out(AttrText);
StringRef OriginalIndent = Lexer::getIndentationForLine(
ctx.SourceMgr, InsertLoc);
Out << "@available(" << suggestPlatform << ", *)\n"
<< OriginalIndent;
}
diag.fixItInsert(InsertLoc, AttrText);
}
}
}
|