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
|
//===--- TypeCheckStorage.cpp - Checking Properties and Subscripts -------===//
//
// 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 semantic analysis for properties, subscripts as well
// as their accessors.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "TypeChecker.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckDecl.h"
#include "TypeCheckMacros.h"
#include "TypeCheckType.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
using namespace swift;
/// Set each bound variable in the pattern to have an error type.
void swift::setBoundVarsTypeError(Pattern *pattern, ASTContext &ctx) {
pattern->forEachVariable([&](VarDecl *var) {
// Don't change the type of a variable that we've been able to
// compute a type for.
if (var->hasInterfaceType())
return;
var->setInvalid();
});
}
/// Build a default initializer for the given type.
Expr *TypeChecker::buildDefaultInitializer(Type type) {
auto &Context = type->getASTContext();
// Default-initialize optional types and weak values to 'nil'.
if (type->getReferenceStorageReferent()->getOptionalObjectType())
return new (Context) NilLiteralExpr(SourceLoc(), /*Implicit=*/true);
// Build tuple literals for tuple types.
if (auto tupleType = type->getAs<TupleType>()) {
SmallVector<Expr *, 2> inits;
for (const auto &elt : tupleType->getElements()) {
auto eltInit = TypeChecker::buildDefaultInitializer(elt.getType());
if (!eltInit)
return nullptr;
inits.push_back(eltInit);
}
return TupleExpr::createImplicit(Context, inits, { });
}
// We don't default-initialize anything else.
return nullptr;
}
/// Does the context allow pattern bindings that don't bind any variables?
static bool contextAllowsPatternBindingWithoutVariables(DeclContext *dc) {
// Property decls in type context must bind variables.
if (dc->isTypeContext())
return false;
// Global variable decls must bind variables, except in scripts.
if (dc->isModuleScopeContext()) {
if (dc->getParentSourceFile()
&& dc->getParentSourceFile()->isScriptMode())
return true;
return false;
}
return true;
}
static bool hasStoredProperties(NominalTypeDecl *decl,
IterableDeclContext *implDecl) {
bool isForeignReferenceTy =
isa<ClassDecl>(decl) && cast<ClassDecl>(decl)->isForeignReferenceType();
return (isa<StructDecl>(decl) ||
(isa<ClassDecl>(decl) &&
(!decl->hasClangNode() || isForeignReferenceTy
|| (decl != implDecl))));
}
namespace {
enum class LoweredPropertiesReason {
Stored,
Memberwise
};
}
static void computeLoweredProperties(NominalTypeDecl *decl,
IterableDeclContext *implDecl,
LoweredPropertiesReason reason) {
// Expand synthesized member macros.
auto &ctx = decl->getASTContext();
(void)evaluateOrDefault(ctx.evaluator,
ExpandSynthesizedMemberMacroRequest{decl},
false);
// Just walk over the members of the type, forcing backing storage
// for lazy properties and property wrappers to be synthesized.
for (auto *member : implDecl->getMembers()) {
// Expand peer macros.
(void)evaluateOrDefault(
ctx.evaluator,
ExpandPeerMacroRequest{member},
{});
auto *var = dyn_cast<VarDecl>(member);
if (!var || var->isStatic())
continue;
if (reason == LoweredPropertiesReason::Stored) {
if (var->getAttrs().hasAttribute<LazyAttr>())
(void) var->getLazyStorageProperty();
if (var->hasAttachedPropertyWrapper()) {
(void) var->getPropertyWrapperAuxiliaryVariables();
(void) var->getPropertyWrapperInitializerInfo();
}
}
}
if (reason != LoweredPropertiesReason::Stored)
return;
// If this is an actor, check conformance to the Actor protocol to
// ensure that the actor storage will get created (if needed).
if (auto classDecl = dyn_cast<ClassDecl>(decl)) {
// If this is an actor class, check conformance to the Actor protocol to
// ensure that the actor storage will get created (if needed).
if (classDecl->isActor()) {
ASTContext &ctx = decl->getASTContext();
auto evaluateConformance = [&](KnownProtocolKind Kind) {
if (auto actorProto = ctx.getProtocol(Kind)) {
SmallVector<ProtocolConformance *, 1> conformances;
classDecl->lookupConformance(actorProto, conformances);
for (auto conformance : conformances) {
// FIXME: This is too much. Instead, we should force the witnesses.
// that we actually need.
auto *normal = conformance->getRootNormalConformance();
evaluateOrDefault(ctx.evaluator,
ResolveTypeWitnessesRequest{normal},
evaluator::SideEffect());
normal->resolveValueWitnesses();
}
}
};
evaluateConformance(KnownProtocolKind::Actor);
// If this is a distributed actor, synthesize its special stored properties.
if (classDecl->isDistributedActor()) {
evaluateConformance(KnownProtocolKind::DistributedActor);
}
}
}
}
static void computeLoweredStoredProperties(NominalTypeDecl *decl,
IterableDeclContext *implDecl) {
computeLoweredProperties(decl, implDecl, LoweredPropertiesReason::Stored);
}
/// Enumerate both the stored properties and missing members,
/// in a deterministic order.
static void enumerateStoredPropertiesAndMissing(
NominalTypeDecl *decl,
IterableDeclContext *implDecl,
llvm::function_ref<void(VarDecl *)> _addStoredProperty,
llvm::function_ref<void(MissingMemberDecl *)> addMissing) {
// Add a variable as a stored properties.
llvm::SmallSet<VarDecl *, 8> knownStoredProperties;
auto addStoredProperty = [&](VarDecl *var) {
if (!var->isStatic() && var->hasStorage()) {
if (knownStoredProperties.insert(var).second)
_addStoredProperty(var);
}
};
// If we have a distributed actor, find the id and actorSystem
// properties. We always want them first, and in a specific
// order.
if (decl->isDistributedActor()) {
VarDecl *distributedActorId = nullptr;
VarDecl *distributedActorSystem = nullptr;
ASTContext &ctx = decl->getASTContext();
for (auto *member : implDecl->getMembers()) {
if (auto *var = dyn_cast<VarDecl>(member)) {
if (!var->isStatic() && var->hasStorage()) {
if (var->getName() == ctx.Id_id) {
distributedActorId = var;
} else if (var->getName() == ctx.Id_actorSystem) {
distributedActorSystem = var;
}
}
if (distributedActorId && distributedActorSystem)
break;
}
}
if (distributedActorId)
addStoredProperty(distributedActorId);
if (distributedActorSystem)
addStoredProperty(distributedActorSystem);
}
for (auto *member : implDecl->getMembers()) {
if (auto *var = dyn_cast<VarDecl>(member)) {
addStoredProperty(var);
}
member->visitAuxiliaryDecls([&](Decl *auxDecl) {
if (auto auxVar = dyn_cast<VarDecl>(auxDecl))
addStoredProperty(auxVar);
});
if (auto missing = dyn_cast<MissingMemberDecl>(member))
if (missing->getNumberOfFieldOffsetVectorEntries() > 0)
addMissing(missing);
}
}
static bool isInSourceFile(IterableDeclContext *idc) {
const DeclContext *dc = idc->getAsGenericContext();
return isa<SourceFile>(dc->getModuleScopeContext());
}
ArrayRef<VarDecl *>
StoredPropertiesRequest::evaluate(Evaluator &evaluator,
NominalTypeDecl *decl) const {
// If this is an imported class with an @_objcImplementation extension, get
// members from the extension instead.
IterableDeclContext *implDecl = decl->getImplementationContext();
if (!hasStoredProperties(decl, implDecl))
return ArrayRef<VarDecl *>();
SmallVector<VarDecl *, 4> results;
// Unless we're in a source file we don't have to do anything
// special to lower lazy properties and property wrappers.
if (isInSourceFile(implDecl))
computeLoweredStoredProperties(decl, implDecl);
enumerateStoredPropertiesAndMissing(decl, implDecl,
[&](VarDecl *var) {
results.push_back(var);
},
[](MissingMemberDecl *missing) { });
return decl->getASTContext().AllocateCopy(results);
}
ArrayRef<Decl *>
StoredPropertiesAndMissingMembersRequest::evaluate(Evaluator &evaluator,
NominalTypeDecl *decl) const {
// If this is an imported class with an @_objcImplementation extension, get
// members from the extension instead.
IterableDeclContext *implDecl = decl->getImplementationContext();
if (!hasStoredProperties(decl, implDecl))
return ArrayRef<Decl *>();
SmallVector<Decl *, 4> results;
// Unless we're in a source file we don't have to do anything
// special to lower lazy properties and property wrappers.
if (isInSourceFile(implDecl))
computeLoweredStoredProperties(decl, implDecl);
enumerateStoredPropertiesAndMissing(decl, implDecl,
[&](VarDecl *var) {
results.push_back(var);
},
[&](MissingMemberDecl *missing) {
results.push_back(missing);
});
return decl->getASTContext().AllocateCopy(results);
}
bool HasInitAccessorRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *decl) const {
auto *var = dyn_cast<VarDecl>(decl);
if (!var)
return false;
if (var->getAccessor(AccessorKind::Init))
return true;
// Look to see whether it is possible that there is an init accessor.
bool hasInitAccessor = false;
namelookup::forEachPotentialAttachedMacro(
var, MacroRole::Accessor,
[&](MacroDecl *macro, const MacroRoleAttr *attr) {
if (accessorMacroIntroducesInitAccessor(macro, attr))
hasInitAccessor = true;
});
// There is no chance for an init accessor, so we're done.
if (!hasInitAccessor)
return false;
// We might get an init accessor by expanding accessor macros; do so now.
(void)evaluateOrDefault(
var->getASTContext().evaluator, ExpandAccessorMacros{var}, { });
return var->getAccessor(AccessorKind::Init);
}
ArrayRef<VarDecl *>
InitAccessorPropertiesRequest::evaluate(Evaluator &evaluator,
NominalTypeDecl *decl) const {
SmallVector<VarDecl *, 4> results;
for (auto var : decl->getMemberwiseInitProperties()) {
if (var->hasInitAccessor())
results.push_back(var);
}
return decl->getASTContext().AllocateCopy(results);
}
ArrayRef<VarDecl *>
MemberwiseInitPropertiesRequest::evaluate(Evaluator &evaluator,
NominalTypeDecl *decl) const {
IterableDeclContext *implDecl = decl->getImplementationContext();
if (!hasStoredProperties(decl, implDecl))
return ArrayRef<VarDecl *>();
// Make sure we expand what we need to to get all of the properties.
computeLoweredProperties(decl, implDecl, LoweredPropertiesReason::Memberwise);
SmallVector<VarDecl *, 4> results;
SmallPtrSet<VarDecl *, 4> subsumedViaInitAccessor;
auto maybeAddProperty = [&](VarDecl *var) {
// We only care about properties that are memberwise initialized.
if (!var->isMemberwiseInitialized(/*preferDeclaredProperties=*/true))
return;
// Add this property.
results.push_back(var);
// If this property has an init accessor, it subsumes all of the stored properties
// that the accessor initializes. Mark those stored properties as being subsumed; we'll
// get back to them later.
if (auto initAccessor = var->getAccessor(AccessorKind::Init)) {
for (auto subsumed : initAccessor->getInitializedProperties()) {
subsumedViaInitAccessor.insert(subsumed);
}
}
};
for (auto *member : decl->getCurrentMembers()) {
if (auto *var = dyn_cast<VarDecl>(member))
maybeAddProperty(var);
member->visitAuxiliaryDecls([&](Decl *auxDecl) {
if (auto auxVar = dyn_cast<VarDecl>(auxDecl))
maybeAddProperty(auxVar);
});
}
// If any properties were subsumed via init accessors, drop them from the list.
if (!subsumedViaInitAccessor.empty()) {
results.erase(std::remove_if(results.begin(), results.end(), [&](VarDecl *var) {
return subsumedViaInitAccessor.contains(var);
}),
results.end());
}
return decl->getASTContext().AllocateCopy(results);
}
/// Validate the \c entryNumber'th entry in \c binding.
const PatternBindingEntry *PatternBindingEntryRequest::evaluate(
Evaluator &eval, PatternBindingDecl *binding, unsigned entryNumber) const {
const auto &pbe = binding->getPatternList()[entryNumber];
auto &Context = binding->getASTContext();
// Resolve the pattern.
auto *pattern = TypeChecker::resolvePattern(binding->getPattern(entryNumber),
binding->getDeclContext(),
/*isStmtCondition*/ true);
if (!pattern) {
binding->setInvalid();
binding->getPattern(entryNumber)->setType(ErrorType::get(Context));
return &pbe;
}
binding->setPattern(entryNumber, pattern);
// Validate 'static'/'class' on properties in nominal type decls.
auto StaticSpelling = binding->getStaticSpelling();
if (StaticSpelling != StaticSpellingKind::None &&
isa<ExtensionDecl>(binding->getDeclContext())) {
if (auto *NTD = binding->getDeclContext()->getSelfNominalTypeDecl()) {
if (!isa<ClassDecl>(NTD)) {
if (StaticSpelling == StaticSpellingKind::KeywordClass) {
binding->diagnose(diag::class_var_not_in_class, false)
.fixItReplace(binding->getStaticLoc(), "static");
NTD->diagnose(diag::extended_type_declared_here);
}
}
}
}
// Reject "class" methods on actors.
if (StaticSpelling == StaticSpellingKind::KeywordClass &&
binding->getDeclContext()->getSelfClassDecl() &&
binding->getDeclContext()->getSelfClassDecl()->isActor()) {
binding->diagnose(diag::class_var_not_in_class, false)
.fixItReplace(binding->getStaticLoc(), "static");
}
// Check the pattern.
auto contextualPattern =
ContextualPattern::forPatternBindingDecl(binding, entryNumber);
Type patternType = TypeChecker::typeCheckPattern(contextualPattern);
if (patternType->hasError()) {
swift::setBoundVarsTypeError(pattern, Context);
binding->setInvalid();
pattern->setType(ErrorType::get(Context));
return &pbe;
}
llvm::SmallVector<VarDecl *, 2> vars;
binding->getPattern(entryNumber)->collectVariables(vars);
bool isReq = false;
bool shouldRequireStatic = false;
if (auto *d = binding->getDeclContext()->getAsDecl()) {
isReq = isa<ProtocolDecl>(d);
shouldRequireStatic = isa<NominalTypeDecl>(d);
}
for (auto *sv: vars) {
bool hasConst = sv->getAttrs().getAttribute<CompileTimeConstAttr>();
if (!hasConst)
continue;
bool hasStatic = StaticSpelling != StaticSpellingKind::None;
// only static _const let/var is supported
if (shouldRequireStatic && !hasStatic) {
binding->diagnose(diag::require_static_for_const);
continue;
}
if (isReq) {
continue;
}
auto varSourceFile = binding->getDeclContext()->getParentSourceFile();
auto isVarInInterfaceFile =
varSourceFile && varSourceFile->Kind == SourceFileKind::Interface;
// Don't diagnose too strictly for textual interfaces.
if (isVarInInterfaceFile) {
continue;
}
// var is only allowed in a protocol.
if (!sv->isLet()) {
binding->diagnose(diag::require_let_for_const);
}
// Diagnose when an init isn't given and it's not a compile-time constant
if (auto *init = binding->getInit(entryNumber)) {
if (!init->isSemanticallyConstExpr()) {
binding->diagnose(diag::require_const_initializer_for_const);
}
} else {
binding->diagnose(diag::require_const_initializer_for_const);
}
}
auto isInitAccessorProperty = [](Pattern *pattern) {
auto *var = pattern->getSingleVar();
return var && var->getAccessor(AccessorKind::Init);
};
// If we have a type but no initializer, check whether the type is
// default-initializable. If so, do it.
if (!pbe.isInitialized() &&
binding->isDefaultInitializable(entryNumber) &&
(pattern->hasStorage() || isInitAccessorProperty(pattern))) {
if (auto defaultInit = TypeChecker::buildDefaultInitializer(patternType)) {
// If we got a default initializer, install it and re-type-check it
// to make sure it is properly coerced to the pattern type.
binding->setInit(entryNumber, defaultInit);
}
}
// If the pattern contains some form of unresolved type, we'll need to
// check the initializer.
if (patternType->hasUnresolvedType() ||
patternType->hasPlaceholder() ||
patternType->hasUnboundGenericType()) {
if (TypeChecker::typeCheckPatternBinding(binding, entryNumber,
patternType)) {
binding->setInvalid();
return &pbe;
}
// Local variable packs are not allowed.
if (binding->getDeclContext()->isLocalContext() &&
binding->getInit(entryNumber)->getType()->is<PackExpansionType>()) {
binding->diagnose(diag::expansion_not_allowed,
binding->getInit(entryNumber)->getType());
}
// A pattern binding at top level is not allowed to pick up another decl's
// opaque result type as its type by type inference.
if (!binding->getDeclContext()->isLocalContext() &&
binding->getInit(entryNumber)->getType()->hasOpaqueArchetype()) {
// TODO: Check whether the type is the pattern binding's own opaque type.
binding->diagnose(diag::inferred_opaque_type,
binding->getInit(entryNumber)->getType());
}
} else {
// Coerce the pattern to the computed type.
if (auto newPattern = TypeChecker::coercePatternToType(
contextualPattern, patternType,
TypeResolverContext::PatternBindingDecl)) {
pattern = newPattern;
} else {
binding->setInvalid();
pattern->setType(ErrorType::get(Context));
return &pbe;
}
}
// If the pattern binding appears in a type or library file context, then
// it must bind at least one variable.
if (!contextAllowsPatternBindingWithoutVariables(binding->getDeclContext())) {
if (vars.empty()) {
// Selector for error message.
enum : unsigned {
Property,
GlobalVariable,
};
Context.Diags.diagnose(binding->getPattern(entryNumber)->getLoc(),
diag::pattern_binds_no_variables,
binding->getDeclContext()->isTypeContext()
? Property
: GlobalVariable);
}
}
// If the pattern binding appears as a compound stored `let` property with an
// initializer inside of a struct type, diagnose it as unsupported.
// This hasn't ever been implemented properly.
if (!Context.LangOpts.hasFeature(Feature::StructLetDestructuring)
&& !binding->isStatic()
&& binding->isInitialized(entryNumber)
&& isa<StructDecl>(binding->getDeclContext())
&& !pattern->getSingleVar()
&& !vars.empty()
&& vars[0]->isLet()) {
Context.Diags.diagnose(binding->getPattern(entryNumber)->getLoc(),
diag::destructuring_let_struct_stored_property_unsupported);
}
return &pbe;
}
static void checkAndContextualizePatternBindingInit(PatternBindingDecl *binding,
unsigned i) {
// Force the entry to be checked.
(void)binding->getCheckedPatternBindingEntry(i);
if (binding->isInvalid())
return;
if (!binding->isInitialized(i))
return;
if (!binding->isInitializerChecked(i))
TypeChecker::typeCheckPatternBinding(binding, i);
if (binding->isInvalid())
return;
// If we entered an initializer context, contextualize any auto-closures we
// might have created. Note that we don't contextualize the initializer for a
// property with a wrapper, because the initializer will have been subsumed by
// the backing storage property.
if (binding->getDeclContext()->isLocalContext())
return;
if (auto *var = binding->getSingleVar()) {
if (var->hasAttachedPropertyWrapper())
return;
}
if (auto *initContext = binding->getInitContext(i)) {
auto *init = binding->getInit(i);
TypeChecker::contextualizeInitializer(initContext, init);
TypeChecker::checkInitializerEffects(initContext, init);
}
}
Expr *PatternBindingCheckedAndContextualizedInitRequest::evaluate(
Evaluator &eval, PatternBindingDecl *binding, unsigned i) const {
checkAndContextualizePatternBindingInit(binding, i);
return binding->getInit(i);
}
bool
IsGetterMutatingRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *storage) const {
auto storageDC = storage->getDeclContext();
bool result = (!storage->isStatic() && storageDC->isTypeContext() &&
storageDC->hasValueSemantics());
// 'lazy' overrides the normal accessor-based rules and heavily
// restricts what accessors can be used. The getter is considered
// mutating if this is instance storage on a value type.
if (storage->getAttrs().hasAttribute<LazyAttr>()) {
return result;
}
// If we have an attached property wrapper, the getter's mutating-ness
// depends on the composition of the wrappers.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (auto mut = var->getPropertyWrapperMutability()) {
return mut->Getter == PropertyWrapperMutability::Mutating
&& result;
}
}
auto checkMutability = [&](AccessorKind kind) -> bool {
auto *accessor = storage->getParsedAccessor(kind);
if (!accessor)
return false;
return accessor->isMutating();
};
// Protocol requirements are always written as '{ get }' or '{ get set }';
// the @_borrowed attribute determines if getReadImpl() becomes Get or Read.
if (isa<ProtocolDecl>(storageDC))
return checkMutability(AccessorKind::Get);
switch (storage->getReadImpl()) {
case ReadImplKind::Stored:
case ReadImplKind::Inherited:
return false;
case ReadImplKind::Get:
return checkMutability(AccessorKind::Get);
case ReadImplKind::Address:
return checkMutability(AccessorKind::Address);
case ReadImplKind::Read:
return checkMutability(AccessorKind::Read);
}
llvm_unreachable("bad impl kind");
}
bool
IsSetterMutatingRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *storage) const {
// By default, the setter is mutating if we have an instance member of a
// value type, but this can be overridden below.
auto storageDC = storage->getDeclContext();
bool result = (!storage->isStatic() && storageDC->isTypeContext() &&
storageDC->hasValueSemantics());
// If we have an attached property wrapper, the setter is mutating
// or not based on the composition of the wrappers.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (auto mut = var->getPropertyWrapperMutability()) {
bool isMutating = mut->Setter == PropertyWrapperMutability::Mutating;
if (auto *didSet = var->getParsedAccessor(AccessorKind::DidSet)) {
// If there's a didSet, we call the getter for the 'oldValue', and so
// should consider the getter's mutatingness as well
isMutating |= (mut->Getter == PropertyWrapperMutability::Mutating);
isMutating |= didSet->getAttrs().hasAttribute<MutatingAttr>();
}
if (auto *willSet = var->getParsedAccessor(AccessorKind::WillSet))
isMutating |= willSet->getAttrs().hasAttribute<MutatingAttr>();
return isMutating && result;
}
}
auto impl = storage->getImplInfo();
switch (impl.getWriteImpl()) {
case WriteImplKind::Immutable:
case WriteImplKind::Stored:
// Instance member setters are mutating; static property setters and
// top-level setters are not.
// It's important that we use this logic for "immutable" storage
// in order to handle initialization of let-properties.
return result;
case WriteImplKind::StoredWithObservers:
case WriteImplKind::InheritedWithObservers:
case WriteImplKind::Set: {
auto *setter = storage->getParsedAccessor(AccessorKind::Set);
if (setter)
result = setter->isMutating();
// As a special extra check, if the user also gave us a modify
// coroutine, check that it has the same mutatingness as the setter.
// TODO: arguably this should require the spelling to match even when
// it's the implied value.
auto modifyAccessor = storage->getParsedAccessor(AccessorKind::Modify);
if (impl.getReadWriteImpl() == ReadWriteImplKind::Modify &&
modifyAccessor != nullptr) {
auto modifyResult = modifyAccessor->isMutating();
if ((result || storage->isGetterMutating()) != modifyResult) {
modifyAccessor->diagnose(
diag::modify_mutatingness_differs_from_setter,
modifyResult ? SelfAccessKind::Mutating
: SelfAccessKind::NonMutating,
modifyResult ? SelfAccessKind::NonMutating
: SelfAccessKind::Mutating);
if (setter)
setter->diagnose(diag::previous_accessor, "setter", 0);
modifyAccessor->setInvalid();
}
}
return result;
}
case WriteImplKind::MutableAddress:
return storage->getParsedAccessor(AccessorKind::MutableAddress)
->isMutating();
case WriteImplKind::Modify:
return storage->getParsedAccessor(AccessorKind::Modify)
->isMutating();
}
llvm_unreachable("bad storage kind");
}
OpaqueReadOwnership
OpaqueReadOwnershipRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *storage) const {
enum class DiagKind {
BorrowedAttr,
NoncopyableType
};
auto usesBorrowed = [&](DiagKind kind) -> OpaqueReadOwnership {
// Check for effects on the getter.
if (auto *getter = storage->getEffectfulGetAccessor()) {
switch (kind) {
case DiagKind::NoncopyableType:
getter->diagnose(diag::noncopyable_effectful_getter,
getter->getDescriptiveKind());
break;
case DiagKind::BorrowedAttr:
getter->diagnose(diag::borrowed_with_effect,
getter->getDescriptiveKind());
break;
}
}
return OpaqueReadOwnership::Borrowed;
};
if (storage->getAttrs().hasAttribute<BorrowedAttr>())
return usesBorrowed(DiagKind::BorrowedAttr);
if (storage->getInnermostDeclContext()->mapTypeIntoContext(
storage->getValueInterfaceType())->isNoncopyable())
return usesBorrowed(DiagKind::NoncopyableType);
return OpaqueReadOwnership::Owned;
}
/// Insert the specified decl into the DeclContext's member list. If the hint
/// decl is specified, the new decl is inserted next to the hint.
static void addMemberToContextIfNeeded(Decl *D, DeclContext *DC,
Decl *Hint = nullptr) {
if (auto *ntd = dyn_cast<NominalTypeDecl>(DC)) {
ntd->addMember(D, Hint);
} else if (auto *ed = dyn_cast<ExtensionDecl>(DC)) {
ed->addMember(D, Hint);
} else {
assert((DC->isLocalContext() || isa<FileUnit>(DC)) &&
"Unknown declcontext");
}
}
/// Build a parameter list which can forward the formal index parameters of a
/// declaration.
///
/// \param prefix optional arguments to be prefixed onto the index
/// forwarding pattern.
static ParameterList *
buildIndexForwardingParamList(AbstractStorageDecl *storage,
ArrayRef<ParamDecl*> prefix,
ASTContext &context) {
auto subscript = dyn_cast<SubscriptDecl>(storage);
// Fast path: if this isn't a subscript, just use whatever we have.
if (!subscript)
return ParameterList::create(context, prefix);
// Clone the parameter list over for a new decl, so we get new ParamDecls.
auto indices = subscript->getIndices()->clone(context,
ParameterList::Implicit);
// Give all of the parameters meaningless names so that we can forward
// them properly. If it's declared anonymously, SILGen will think
// it's unused.
// TODO: use some special DeclBaseName for this?
for (auto param : indices->getArray()) {
if (!param->hasName())
param->setName(context.getIdentifier("anonymous"));
assert(param->hasName());
}
if (prefix.empty())
return indices;
// Otherwise, we need to build up a new parameter list.
SmallVector<ParamDecl*, 4> elements;
// Start with the fields we were given, if there are any.
elements.append(prefix.begin(), prefix.end());
elements.append(indices->begin(), indices->end());
return ParameterList::create(context, elements);
}
static bool doesAccessorHaveBody(AccessorDecl *accessor) {
// Protocol requirements don't have bodies.
//
// FIXME: Revisit this if we ever get 'real' default implementations.
if (isa<ProtocolDecl>(accessor->getDeclContext()))
return false;
auto *storage = accessor->getStorage();
// NSManaged getters and setters don't have bodies.
if (storage->getAttrs().hasAttribute<NSManagedAttr>(/*AllowInvalid=*/true))
if (accessor->isGetterOrSetter())
return false;
return true;
}
/// Build an argument list referencing the subscript parameters for this
/// subscript accessor.
static ArgumentList *buildSubscriptArgumentList(ASTContext &ctx,
AccessorDecl *accessor) {
// Pull out the body parameters, which we should have cloned
// previously to be forwardable. Drop the initial buffer/value
// parameter in accessors that have one.
auto params = accessor->getParameters()->getArray();
auto accessorKind = accessor->getAccessorKind();
// Ignore the value parameter of a setter.
if (accessorKind == AccessorKind::Set) {
params = params.slice(1);
}
// Okay, everything else should be forwarded, build the argument list.
return buildForwardingArgumentList(params, ctx);
}
namespace {
enum class TargetImpl {
/// We're doing an ordinary storage reference.
Ordinary,
/// We're referencing the physical storage created for the storage.
Storage,
/// We're referencing this specific implementation of the storage, not
/// an override of it.
Implementation,
/// We're referencing the superclass's implementation of the storage.
Super,
/// We're referencing the backing property for a property with a wrapper
/// through the 'value' property.
Wrapper,
/// We're referencing the backing property for a property with a wrapper
/// through the 'projectedValue' property.
WrapperStorage,
};
} // end anonymous namespace
namespace {
/// Describes the information needed to perform property wrapper access via
/// the enclosing self.
struct EnclosingSelfPropertyWrapperAccess {
/// The (generic) subscript that will be used to perform the access.
SubscriptDecl *subscript;
/// The property being accessed.
VarDecl *accessedProperty;
};
}
/// Determine whether the given property should be accessed via the enclosing-self access pattern.
static std::optional<EnclosingSelfPropertyWrapperAccess>
getEnclosingSelfPropertyWrapperAccess(VarDecl *property, bool forProjected) {
// The enclosing-self pattern only applies to instance properties of
// classes.
if (!property->isInstanceMember())
return std::nullopt;
auto classDecl = property->getDeclContext()->getSelfClassDecl();
if (!classDecl)
return std::nullopt;
// The pattern currently only works with the outermost property wrapper.
Type outermostWrapperType = property->getPropertyWrapperBackingPropertyType();
if (!outermostWrapperType)
return std::nullopt;
NominalTypeDecl *wrapperTypeDecl = outermostWrapperType->getAnyNominal();
if (!wrapperTypeDecl)
return std::nullopt;
// Look for a generic subscript that fits the general form we need.
auto wrapperInfo = wrapperTypeDecl->getPropertyWrapperTypeInfo();
auto subscript = forProjected
? wrapperInfo.enclosingInstanceProjectedSubscript
: wrapperInfo.enclosingInstanceWrappedSubscript;
if (!subscript)
return std::nullopt;
EnclosingSelfPropertyWrapperAccess result;
result.subscript = subscript;
if (forProjected) {
result.accessedProperty =
property->getPropertyWrapperAuxiliaryVariables().projectionVar;
} else {
result.accessedProperty = property;
}
return result;
}
static std::optional<PropertyWrapperLValueness>
getPropertyWrapperLValueness(VarDecl *var) {
auto &ctx = var->getASTContext();
return evaluateOrDefault(ctx.evaluator, PropertyWrapperLValuenessRequest{var},
std::nullopt);
}
/// Build a reference to the storage of a declaration. Returns nullptr if there
/// was an error. This should only occur if an invalid declaration was type
/// checked; another diagnostic should have been emitted already.
///
/// The resulting reference is used in synthesized property accessors and is of
/// one of the following forms:
/// 1. Without property wrappers:
/// - Stored: \c self.member
/// 2. With property wrappers:
/// - Wrapped: \c self._member.wrappedValue
/// - Composition: \c self._member.wrappedValue.wrappedValue….wrappedValue
/// - Projected: \c self._member.projectedValue
/// - Enclosed instance: \c Wrapper[_enclosedInstance: self, …]
static Expr *buildStorageReference(AccessorDecl *accessor,
AbstractStorageDecl *storage,
TargetImpl target,
bool isUsedForGetAccess,
bool isUsedForSetAccess,
ASTContext &ctx) {
// Whether the last component of the expression should be an l-value
bool isLValue = isUsedForSetAccess;
// Local function to "finish" the expression, creating a member reference
// to the given sequence of underlying variables.
std::optional<EnclosingSelfPropertyWrapperAccess> enclosingSelfAccess;
// Contains the underlying wrappedValue declaration in a property wrapper
// along with whether or not the reference to this field needs to be an lvalue
llvm::SmallVector<std::pair<VarDecl *, bool>, 1> underlyingVars;
auto finish = [&](Expr *result) -> Expr * {
for (auto underlyingVarPair : underlyingVars) {
auto underlyingVar = underlyingVarPair.first;
auto isWrapperRefLValue = underlyingVarPair.second;
auto subs = result->getType()
->getWithoutSpecifierType()
->getContextSubstitutionMap(
accessor->getParentModule(),
underlyingVar->getDeclContext());
ConcreteDeclRef memberRef(underlyingVar, subs);
auto *memberRefExpr = new (ctx) MemberRefExpr(
result, SourceLoc(), memberRef, DeclNameLoc(), /*Implicit=*/true);
auto type = underlyingVar->getValueInterfaceType().subst(subs);
if (isWrapperRefLValue)
type = LValueType::get(type);
memberRefExpr->setType(type);
result = memberRefExpr;
}
return result;
};
VarDecl *selfDecl = accessor->getImplicitSelfDecl();
AccessSemantics semantics;
SelfAccessorKind selfAccessKind;
Type selfTypeForAccess = (selfDecl ? selfDecl->getTypeInContext() : Type());
bool isMemberLValue = isLValue;
auto *genericEnv = accessor->getGenericEnvironment();
SubstitutionMap subs;
if (genericEnv)
subs = genericEnv->getForwardingSubstitutionMap();
switch (target) {
case TargetImpl::Ordinary:
semantics = AccessSemantics::Ordinary;
selfAccessKind = SelfAccessorKind::Peer;
break;
case TargetImpl::Storage:
semantics = AccessSemantics::DirectToStorage;
selfAccessKind = SelfAccessorKind::Peer;
break;
case TargetImpl::Implementation:
semantics = AccessSemantics::DirectToImplementation;
selfAccessKind = SelfAccessorKind::Peer;
break;
case TargetImpl::Super:
// If this really is an override, use a super-access.
if (auto override = storage->getOverriddenDecl()) {
semantics = AccessSemantics::Ordinary;
selfAccessKind = SelfAccessorKind::Super;
auto isMetatype = false;
if (auto *metaTy = selfTypeForAccess->getAs<MetatypeType>()) {
isMetatype = true;
selfTypeForAccess = metaTy->getInstanceType();
}
// Adjust the self type of the access to refer to the relevant superclass.
auto *baseClass = override->getDeclContext()->getSelfClassDecl();
selfTypeForAccess = selfTypeForAccess->getSuperclassForDecl(baseClass);
// Error recovery path. We get an ErrorType here if getSuperclassForDecl()
// fails (because, for instance, a generic parameter of a generic nominal
// type cannot be resolved).
if (!selfTypeForAccess->is<ErrorType>()) {
subs =
selfTypeForAccess->getContextSubstitutionMap(
accessor->getParentModule(),
baseClass);
}
storage = override;
if (isMetatype)
selfTypeForAccess = MetatypeType::get(selfTypeForAccess);
// Otherwise do a self-reference, which is dynamically bogus but
// should be statically valid. This should only happen in invalid cases.
} else {
semantics = AccessSemantics::Ordinary;
selfAccessKind = SelfAccessorKind::Peer;
}
break;
case TargetImpl::Wrapper: {
auto var = cast<VarDecl>(accessor->getStorage());
auto *backing = var->getPropertyWrapperBackingProperty();
// Error recovery.
if (!backing || backing->isInvalid())
return nullptr;
storage = backing;
// If the outermost property wrapper uses the enclosing self pattern,
// record that.
unsigned lastWrapperIdx = var->getAttachedPropertyWrappers().size();
unsigned firstWrapperIdx = 0;
enclosingSelfAccess =
getEnclosingSelfPropertyWrapperAccess(var, /*forProjected=*/false);
if (enclosingSelfAccess)
firstWrapperIdx = 1;
// Perform accesses to the wrappedValues along the composition chain.
if (firstWrapperIdx < lastWrapperIdx) {
auto lvalueness = *getPropertyWrapperLValueness(var);
// Figure out if the outermost wrapper instance should be an l-value
bool isLValueForGet = lvalueness.isLValueForGetAccess[firstWrapperIdx];
bool isLValueForSet = lvalueness.isLValueForSetAccess[firstWrapperIdx];
isMemberLValue = (isLValueForGet && isUsedForGetAccess) ||
(isLValueForSet && isUsedForSetAccess);
for (unsigned i : range(firstWrapperIdx, lastWrapperIdx)) {
auto wrapperInfo = var->getAttachedPropertyWrapperTypeInfo(i);
auto wrappedValue = wrapperInfo.valueVar;
// Figure out if the wrappedValue accesses should be l-values
bool isWrapperRefLValue = isLValue;
if (i < lastWrapperIdx - 1) {
bool isLValueForGet = lvalueness.isLValueForGetAccess[i+1];
bool isLValueForSet = lvalueness.isLValueForSetAccess[i+1];
isWrapperRefLValue = (isLValueForGet && isUsedForGetAccess) ||
(isLValueForSet && isUsedForSetAccess);
}
// Check for availability of wrappedValue.
if (accessor->getAccessorKind() == AccessorKind::Get ||
accessor->getAccessorKind() == AccessorKind::Read) {
if (wrappedValue->getAttrs().getUnavailable(ctx)) {
ExportContext where = ExportContext::forDeclSignature(var);
diagnoseExplicitUnavailability(
wrappedValue,
var->getAttachedPropertyWrappers()[i]->getRangeWithAt(),
where, nullptr);
}
}
underlyingVars.push_back({ wrappedValue, isWrapperRefLValue });
}
}
semantics = AccessSemantics::DirectToStorage;
selfAccessKind = SelfAccessorKind::Peer;
break;
}
case TargetImpl::WrapperStorage: {
auto var =
cast<VarDecl>(accessor->getStorage())->getOriginalWrappedProperty();
auto *backing = var->getPropertyWrapperBackingProperty();
// Error recovery.
if (!backing || backing->isInvalid())
return nullptr;
storage = backing;
enclosingSelfAccess =
getEnclosingSelfPropertyWrapperAccess(var, /*forProjected=*/true);
if (!enclosingSelfAccess) {
auto projectionVar = cast<VarDecl>(accessor->getStorage());
if (auto lvalueness = getPropertyWrapperLValueness(projectionVar)) {
isMemberLValue =
(lvalueness->isLValueForGetAccess[0] && isUsedForGetAccess) ||
(lvalueness->isLValueForSetAccess[0] && isUsedForSetAccess);
}
underlyingVars.push_back(
{ var->getAttachedPropertyWrapperTypeInfo(0).projectedValueVar,
isLValue });
}
semantics = AccessSemantics::DirectToStorage;
selfAccessKind = SelfAccessorKind::Peer;
break;
}
}
// If the base is not 'self', default get access to nonmutating and set access to mutating.
bool getterMutatesBase = selfDecl && storage->isGetterMutating();
bool setterMutatesBase = !selfDecl || storage->isSetterMutating();
// If we're not accessing via a property wrapper, we don't need to adjust
// the mutability.
if (target == TargetImpl::Wrapper || target == TargetImpl::WrapperStorage) {
auto var = cast<VarDecl>(accessor->getStorage());
auto mutability = var->getPropertyWrapperMutability();
// Only adjust mutability if it's possible to mutate the base.
if (mutability && !var->isStatic() &&
!(selfDecl && selfTypeForAccess->hasReferenceSemantics())) {
getterMutatesBase = (mutability->Getter == PropertyWrapperMutability::Mutating);
setterMutatesBase = (mutability->Setter == PropertyWrapperMutability::Mutating);
}
}
// If the accessor is mutating, then the base should be referred as an l-value
bool isBaseLValue = (getterMutatesBase && isUsedForGetAccess) ||
(setterMutatesBase && isUsedForSetAccess);
if (!selfDecl) {
assert(target != TargetImpl::Super);
auto *storageDRE = new (ctx) DeclRefExpr(storage, DeclNameLoc(),
/*IsImplicit=*/true, semantics);
auto type = storage->getValueInterfaceType().subst(subs);
if (isBaseLValue)
type = LValueType::get(type);
storageDRE->setType(type);
return finish(storageDRE);
}
// Build self
Expr *selfDRE = buildSelfReference(selfDecl, selfAccessKind, isBaseLValue,
/*convertTy*/ selfTypeForAccess);
// Build self.member or equivalent
Expr *lookupExpr;
ConcreteDeclRef memberRef(storage, subs);
auto type = storage->getValueInterfaceType().subst(subs);
if (isMemberLValue)
type = LValueType::get(type);
// When we are performing access via a property wrapper's static subscript
// that accepts the enclosing self along with key paths, form that subscript
// operation now.
if (enclosingSelfAccess) {
Type storageType = storage->getValueInterfaceType().subst(subs);
// Metatype instance for the wrapper type itself.
TypeExpr *wrapperMetatype = TypeExpr::createImplicit(storageType, ctx);
// Key path referring to the property being accessed.
Expr *propertyKeyPath = new (ctx) KeyPathDotExpr(SourceLoc());
propertyKeyPath = UnresolvedDotExpr::createImplicit(ctx, propertyKeyPath,
enclosingSelfAccess->accessedProperty->getName());
propertyKeyPath = KeyPathExpr::createImplicit(
ctx, /*backslashLoc*/ SourceLoc(), /*parsedRoot*/ nullptr,
propertyKeyPath, /*hasLeadingDot*/ true);
// Key path referring to the backing storage property.
Expr *storageKeyPath = new (ctx) KeyPathDotExpr(SourceLoc());
storageKeyPath = UnresolvedDotExpr::createImplicit(ctx, storageKeyPath,
storage->getName());
storageKeyPath = KeyPathExpr::createImplicit(
ctx, /*backslashLoc*/ SourceLoc(), /*parsedRoot*/ nullptr,
storageKeyPath, /*hasLeadingDot*/ true);
Expr *args[3] = {selfDRE, propertyKeyPath, storageKeyPath};
auto *subscriptDecl = enclosingSelfAccess->subscript;
auto argList =
ArgumentList::forImplicitCallTo(subscriptDecl->getIndices(), args, ctx);
lookupExpr = SubscriptExpr::create(ctx, wrapperMetatype, argList,
subscriptDecl, /*Implicit=*/true);
// FIXME: Since we're not resolving overloads or anything, we should be
// building fully type-checked AST above; we already have all the
// information that we need.
if (!TypeChecker::typeCheckExpression(lookupExpr, accessor))
return nullptr;
// Make sure we produce an lvalue only when desired.
if (isMemberLValue != lookupExpr->getType()->is<LValueType>()) {
if (isMemberLValue) {
// Strip off an extraneous load.
if (auto load = dyn_cast<LoadExpr>(lookupExpr))
lookupExpr = load->getSubExpr();
} else {
lookupExpr = new (ctx) LoadExpr(
lookupExpr, lookupExpr->getType()->getRValueType());
}
}
} else if (isa<SubscriptDecl>(storage)) {
auto *argList = buildSubscriptArgumentList(ctx, accessor);
lookupExpr = SubscriptExpr::create(ctx, selfDRE, argList, memberRef,
/*IsImplicit=*/true, semantics);
if (selfAccessKind == SelfAccessorKind::Super)
cast<LookupExpr>(lookupExpr)->setIsSuper(true);
lookupExpr->setType(type);
} else {
lookupExpr = new (ctx) MemberRefExpr(selfDRE, SourceLoc(), memberRef,
DeclNameLoc(), /*IsImplicit=*/true,
semantics);
if (selfAccessKind == SelfAccessorKind::Super)
cast<LookupExpr>(lookupExpr)->setIsSuper(true);
lookupExpr->setType(type);
}
// Build self.member.wrappedValue if applicable
return finish(lookupExpr);
}
/// Load the value of VD. If VD is an @override of another value, we call the
/// superclass getter. Otherwise, we do a direct load of the value.
static Expr *
createPropertyLoadOrCallSuperclassGetter(AccessorDecl *accessor,
AbstractStorageDecl *storage,
TargetImpl target,
ASTContext &ctx) {
return buildStorageReference(accessor, storage, target,
/*isUsedForGetAccess=*/true,
/*isUsedForSetAccess=*/false,
ctx);
}
static ProtocolConformanceRef checkConformanceToNSCopying(VarDecl *var,
Type type) {
auto dc = var->getDeclContext();
auto &ctx = dc->getASTContext();
auto proto = ctx.getNSCopyingDecl();
if (proto) {
if (auto result = dc->getParentModule()->checkConformance(type, proto))
return result;
}
ctx.Diags.diagnose(var->getLoc(), diag::nscopying_doesnt_conform);
return ProtocolConformanceRef::forInvalid();
}
static std::pair<Type, bool> getUnderlyingTypeOfVariable(VarDecl *var) {
Type type = var->getTypeInContext()->getReferenceStorageReferent();
if (Type objectType = type->getOptionalObjectType()) {
return {objectType, true};
} else {
return {type, false};
}
}
ProtocolConformanceRef TypeChecker::checkConformanceToNSCopying(VarDecl *var) {
Type type = getUnderlyingTypeOfVariable(var).first;
return ::checkConformanceToNSCopying(var, type);
}
/// Synthesize the code to store 'Val' to 'VD', given that VD has an @NSCopying
/// attribute on it. We know that VD is a stored property in a class, so we
/// just need to generate something like "self.property = val.copy(zone: nil)"
/// here. This does some type checking to validate that the call will succeed.
static Expr *synthesizeCopyWithZoneCall(Expr *Val, VarDecl *VD,
ASTContext &Ctx) {
// We support @NSCopying on class types (which conform to NSCopying),
// protocols which conform, and option types thereof.
auto underlyingTypeAndIsOptional = getUnderlyingTypeOfVariable(VD);
auto underlyingType = underlyingTypeAndIsOptional.first;
auto isOptional = underlyingTypeAndIsOptional.second;
// The element type must conform to NSCopying. If not, emit an error and just
// recovery by synthesizing without the copy call.
auto conformance = checkConformanceToNSCopying(VD, underlyingType);
if (!conformance)
return Val;
//- (id)copyWithZone:(NSZone *)zone;
DeclName copyWithZoneName(Ctx, Ctx.getIdentifier("copy"), { Ctx.Id_with });
FuncDecl *copyMethod = nullptr;
for (auto member : conformance.getRequirement()->getMembers()) {
if (auto func = dyn_cast<FuncDecl>(member)) {
if (func->getName() == copyWithZoneName) {
copyMethod = func;
break;
}
}
}
assert(copyMethod != nullptr);
// If we have an optional type, we have to "?" the incoming value to only
// evaluate the subexpression if the incoming value is non-null.
if (isOptional) {
Val = new (Ctx) BindOptionalExpr(Val, SourceLoc(), 0);
Val->setType(underlyingType);
}
SubstitutionMap subs =
SubstitutionMap::get(copyMethod->getGenericSignature(), {underlyingType},
ArrayRef<ProtocolConformanceRef>(conformance));
ConcreteDeclRef copyMethodRef(copyMethod, subs);
auto copyMethodType = copyMethod->getInterfaceType()
->castTo<GenericFunctionType>()
->substGenericArgs(subs);
auto DRE = new (Ctx) DeclRefExpr(copyMethodRef, DeclNameLoc(),
/*IsImplicit=*/true);
DRE->setType(copyMethodType);
// Drop the self type
copyMethodType = copyMethodType->getResult()->castTo<FunctionType>();
auto DSCE = DotSyntaxCallExpr::create(Ctx, DRE, SourceLoc(),
Argument::unlabeled(Val));
DSCE->setImplicit();
DSCE->setType(copyMethodType);
DSCE->setThrows(nullptr);
Expr *Nil = new (Ctx) NilLiteralExpr(SourceLoc(), /*implicit*/true);
Nil->setType(copyMethodType->getParams()[0].getParameterType());
auto *argList =
ArgumentList::forImplicitCallTo(copyMethod->getParameters(), {Nil}, Ctx);
auto *Call = CallExpr::createImplicit(Ctx, DSCE, argList);
Call->setType(copyMethodType->getResult());
Call->setThrows(nullptr);
// If we're working with non-optional types, we're forcing the cast.
if (!isOptional) {
auto *const Cast =
ForcedCheckedCastExpr::createImplicit(Ctx, Call, underlyingType);
Cast->setCastKind(CheckedCastKind::ValueCast);
return Cast;
}
// We're working with optional types, so perform a conditional checked
// downcast.
auto *const Cast =
ConditionalCheckedCastExpr::createImplicit(Ctx, Call, underlyingType);
Cast->setCastKind(CheckedCastKind::ValueCast);
// Use OptionalEvaluationExpr to evaluate the "?".
auto *Result = new (Ctx) OptionalEvaluationExpr(Cast);
Result->setType(OptionalType::get(underlyingType));
return Result;
}
/// In a synthesized accessor body, store 'value' to the appropriate element.
///
/// If the property is an override, we call the superclass setter.
/// Otherwise, we do a direct store of the value.
static
void createPropertyStoreOrCallSuperclassSetter(AccessorDecl *accessor,
Expr *value,
AbstractStorageDecl *storage,
TargetImpl target,
SmallVectorImpl<ASTNode> &body,
ASTContext &ctx) {
// If the storage is an @NSCopying property, then we store the
// result of a copyWithZone call on the value, not the value itself.
if (auto property = dyn_cast<VarDecl>(storage)) {
if (property->getAttrs().hasAttribute<NSCopyingAttr>())
value = synthesizeCopyWithZoneCall(value, property, ctx);
}
// Error recovery.
if (value->getType()->hasError())
return;
Expr *dest = buildStorageReference(accessor, storage, target,
/*isUsedForGetAccess=*/false,
/*isUsedForSetAccess=*/true,
ctx);
// Error recovery.
if (dest == nullptr)
return;
// A lazy property setter will store a value of type T into underlying storage
// of type T?.
auto destType = dest->getType()->getWithoutSpecifierType();
// Error recovery.
if (destType->hasError())
return;
if (!destType->isEqual(value->getType())) {
assert(destType->getOptionalObjectType());
assert(destType->getOptionalObjectType()->isEqual(value->getType()));
value = new (ctx) InjectIntoOptionalExpr(value, destType);
}
auto *assign = new (ctx) AssignExpr(dest, SourceLoc(), value,
/*IsImplicit=*/true);
assign->setType(ctx.TheEmptyTupleType);
body.push_back(assign);
}
LLVM_ATTRIBUTE_UNUSED
static bool isSynthesizedComputedProperty(AbstractStorageDecl *storage) {
return (storage->getAttrs().hasAttribute<LazyAttr>() ||
storage->getAttrs().hasAttribute<NSManagedAttr>() ||
(isa<VarDecl>(storage) &&
cast<VarDecl>(storage)->hasAttachedPropertyWrapper()));
}
/// Synthesize the body of a trivial getter. For a non-member vardecl or one
/// which is not an override of a base class property, it performs a direct
/// storage load. For an override of a base member property, it chains up to
/// super.
static std::pair<BraceStmt *, bool>
synthesizeTrivialGetterBody(AccessorDecl *getter, TargetImpl target,
ASTContext &ctx) {
auto storage = getter->getStorage();
assert(!isSynthesizedComputedProperty(storage) ||
target == TargetImpl::Wrapper ||
target == TargetImpl::WrapperStorage);
SourceLoc loc = storage->getLoc();
Expr *result =
createPropertyLoadOrCallSuperclassGetter(getter, storage, target, ctx);
SmallVector<ASTNode, 2> body;
if (result != nullptr) {
body.push_back(ReturnStmt::createImplicit(ctx, result));
}
return { BraceStmt::create(ctx, loc, body, loc, true),
/*isTypeChecked=*/true };
}
/// Synthesize the body of a getter which just directly accesses the
/// underlying storage.
static std::pair<BraceStmt *, bool>
synthesizeTrivialGetterBody(AccessorDecl *getter, ASTContext &ctx) {
assert(getter->getStorage()->getImplInfo().hasStorage());
return synthesizeTrivialGetterBody(getter, TargetImpl::Storage, ctx);
}
/// Synthesize the body of a getter which just delegates to its superclass
/// implementation.
static std::pair<BraceStmt *, bool>
synthesizeInheritedGetterBody(AccessorDecl *getter, ASTContext &ctx) {
// This should call the superclass getter.
return synthesizeTrivialGetterBody(getter, TargetImpl::Super, ctx);
}
/// Synthesize the body of a getter which just delegates to an addressor.
static std::pair<BraceStmt *, bool>
synthesizeAddressedGetterBody(AccessorDecl *getter, ASTContext &ctx) {
assert(getter->getStorage()->getParsedAccessor(AccessorKind::Address));
// This should call the addressor.
return synthesizeTrivialGetterBody(getter, TargetImpl::Implementation, ctx);
}
/// Synthesize the body of a getter which just delegates to a read
/// coroutine accessor.
static std::pair<BraceStmt *, bool>
synthesizeReadCoroutineGetterBody(AccessorDecl *getter, ASTContext &ctx) {
assert(getter->getStorage()->getParsedAccessor(AccessorKind::Read));
// This should call the read coroutine.
return synthesizeTrivialGetterBody(getter, TargetImpl::Implementation, ctx);
}
namespace {
/// This ASTWalker explores an expression tree looking for expressions (which
/// are DeclContext's) and changes their parent DeclContext to NewDC.
/// TODO: We ought to consider merging this with
/// ContextualizeClosuresAndMacros, or better yet removing it in favor of
/// avoiding the recontextualization for lazy vars.
class RecontextualizeClosures : public ASTWalker {
DeclContext *NewDC;
public:
RecontextualizeClosures(DeclContext *NewDC) : NewDC(NewDC) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
// If we find a closure, update its declcontext and do *not* walk into it.
if (auto CE = dyn_cast<AbstractClosureExpr>(E)) {
CE->setParent(NewDC);
return Action::SkipNode(E);
}
return Action::Continue(E);
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *P) override {
if (auto *EP = dyn_cast<ExprPattern>(P))
EP->setDeclContext(NewDC);
if (auto *EP = dyn_cast<EnumElementPattern>(P))
EP->setDeclContext(NewDC);
return Action::Continue(P);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
// The ASTWalker doesn't walk the case body variables, contextualize them
// ourselves.
if (auto *CS = dyn_cast<CaseStmt>(S)) {
for (auto *CaseVar : CS->getCaseBodyVariablesOrEmptyArray())
CaseVar->setDeclContext(NewDC);
}
return Action::Continue(S);
}
PreWalkAction walkToDeclPre(Decl *D) override {
D->setDeclContext(NewDC);
// Auxiliary decls need to have their contexts adjusted too.
if (auto *VD = dyn_cast<VarDecl>(D)) {
VD->visitAuxiliaryDecls([&](VarDecl *D) {
D->setDeclContext(NewDC);
});
}
// Skip walking the children of any Decls that are also DeclContexts,
// they will already have the right parent.
return Action::SkipNodeIf(isa<DeclContext>(D));
}
};
} // end anonymous namespace
/// Synthesize the getter for a lazy property with the specified storage
/// vardecl.
static std::pair<BraceStmt *, bool>
synthesizeLazyGetterBody(AccessorDecl *Get, VarDecl *VD, VarDecl *Storage,
ASTContext &Ctx) {
// The getter checks the optional, storing the initial value in if nil. The
// specific pattern we generate is:
// get {
// if let tmp1 = storage {
// return tmp1
// }
// let tmp2 : Ty = <<initializer expression>>
// storage = tmp2
// return tmp2
// }
SmallVector<ASTNode, 6> Body;
// Load the existing storage and store it into the 'tmp1' temporary.
auto *Tmp1VD = new (Ctx) VarDecl(/*IsStatic*/false, VarDecl::Introducer::Let,
SourceLoc(), Ctx.getIdentifier("tmp1"), Get);
Tmp1VD->setInterfaceType(VD->getValueInterfaceType());
Tmp1VD->setImplicit();
auto *Named = NamedPattern::createImplicit(Ctx, Tmp1VD, Tmp1VD->getTypeInContext());
auto *Let =
BindingPattern::createImplicit(Ctx, VarDecl::Introducer::Let, Named);
Let->setType(Named->getType());
auto *Some = OptionalSomePattern::createImplicit(Ctx, Let);
Some->setType(OptionalType::get(Let->getType()));
auto *StoredValueExpr =
createPropertyLoadOrCallSuperclassGetter(Get, Storage,
TargetImpl::Storage, Ctx);
SmallVector<StmtConditionElement, 1> Cond;
Cond.emplace_back(ConditionalPatternBindingInfo::create(
Ctx, SourceLoc(), Some, StoredValueExpr));
// Build the early return inside the if.
auto *Tmp1DRE = new (Ctx) DeclRefExpr(Tmp1VD, DeclNameLoc(), /*Implicit*/true,
AccessSemantics::Ordinary);
Tmp1DRE->setType(Tmp1VD->getTypeInContext());
auto *Return = ReturnStmt::createImplicit(Ctx, Tmp1DRE);
auto *ReturnBranch = BraceStmt::createImplicit(Ctx, {Return});
// Build the "if" around the early return.
Body.push_back(new (Ctx) IfStmt(LabeledStmtInfo(), SourceLoc(),
Ctx.AllocateCopy(Cond), ReturnBranch,
/*elseloc*/ SourceLoc(),
/*else*/ nullptr, /*implicit*/ true));
auto *Tmp2VD = new (Ctx) VarDecl(/*IsStatic*/false, VarDecl::Introducer::Let,
SourceLoc(), Ctx.getIdentifier("tmp2"),
Get);
Tmp2VD->setInterfaceType(VD->getValueInterfaceType());
Tmp2VD->setImplicit();
// Take the initializer from the PatternBindingDecl for VD.
// TODO: This doesn't work with complicated patterns like:
// lazy var (a,b) = foo()
auto PBD = VD->getParentPatternBinding();
unsigned entryIndex = PBD->getPatternEntryIndexForVarDecl(VD);
Expr *InitValue;
if (PBD->getInit(entryIndex)) {
assert(PBD->isInitializerSubsumed(entryIndex));
InitValue = PBD->getCheckedAndContextualizedInit(entryIndex);
} else {
InitValue = new (Ctx) ErrorExpr(SourceRange(), Tmp2VD->getTypeInContext());
}
// Recontextualize any closure declcontexts nested in the initializer to
// realize that they are in the getter function.
if (Get->hasImplicitSelfDecl())
Get->getImplicitSelfDecl()->setDeclContext(Get);
InitValue->walk(RecontextualizeClosures(Get));
// Wrap the initializer in a LazyInitializerExpr to avoid walking it twice.
auto initType = InitValue->getType();
InitValue = new (Ctx) LazyInitializerExpr(InitValue);
InitValue->setType(initType);
Pattern *Tmp2PBDPattern =
NamedPattern::createImplicit(Ctx, Tmp2VD, Tmp2VD->getTypeInContext());
Tmp2PBDPattern =
TypedPattern::createImplicit(Ctx, Tmp2PBDPattern, Tmp2VD->getTypeInContext());
auto *Tmp2PBD = PatternBindingDecl::createImplicit(
Ctx, StaticSpellingKind::None, Tmp2PBDPattern, InitValue, Get,
/*VarLoc*/ InitValue->getStartLoc());
Body.push_back(Tmp2PBD);
Body.push_back(Tmp2VD);
// Assign tmp2 into storage.
auto Tmp2DRE = new (Ctx) DeclRefExpr(Tmp2VD, DeclNameLoc(), /*Implicit*/true,
AccessSemantics::DirectToStorage);
Tmp2DRE->setType(Tmp2VD->getTypeInContext());
createPropertyStoreOrCallSuperclassSetter(Get, Tmp2DRE, Storage,
TargetImpl::Storage, Body, Ctx);
// Return tmp2.
Tmp2DRE = new (Ctx) DeclRefExpr(Tmp2VD, DeclNameLoc(), /*Implicit*/true,
AccessSemantics::DirectToStorage);
Tmp2DRE->setType(Tmp2VD->getTypeInContext());
Body.push_back(ReturnStmt::createImplicit(Ctx, Tmp2DRE));
auto Range = InitValue->getSourceRange();
return { BraceStmt::create(Ctx, Range.Start, Body, Range.End,
/*implicit*/true),
/*isTypeChecked=*/true };
}
/// Synthesize the body of a getter for a property wrapper, which
/// delegates to the wrapper's "value" property.
static std::pair<BraceStmt *, bool>
synthesizePropertyWrapperGetterBody(AccessorDecl *getter, ASTContext &ctx) {
return synthesizeTrivialGetterBody(getter, TargetImpl::Wrapper, ctx);
}
static std::pair<BraceStmt *, bool>
synthesizeInvalidAccessor(AccessorDecl *accessor, ASTContext &ctx) {
auto loc = accessor->getLoc();
return { BraceStmt::create(ctx, loc, ArrayRef<ASTNode>(), loc, true), true };
}
static std::pair<BraceStmt *, bool>
synthesizeGetterBody(AccessorDecl *getter, ASTContext &ctx) {
auto storage = getter->getStorage();
// Synthesize the getter for a lazy property or property wrapper.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (var->getAttrs().hasAttribute<LazyAttr>()) {
auto *storage = var->getLazyStorageProperty();
return synthesizeLazyGetterBody(getter, var, storage, ctx);
}
if (var->hasAttachedPropertyWrapper()) {
return synthesizePropertyWrapperGetterBody(getter, ctx);
}
if (var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection)) {
return synthesizeTrivialGetterBody(getter, TargetImpl::WrapperStorage,
ctx);
}
}
if (getter->hasForcedStaticDispatch()) {
return synthesizeTrivialGetterBody(getter, TargetImpl::Ordinary, ctx);
}
switch (getter->getStorage()->getReadImpl()) {
case ReadImplKind::Stored:
return synthesizeTrivialGetterBody(getter, ctx);
case ReadImplKind::Get:
return synthesizeInvalidAccessor(getter, ctx);
case ReadImplKind::Inherited:
return synthesizeInheritedGetterBody(getter, ctx);
case ReadImplKind::Address:
return synthesizeAddressedGetterBody(getter, ctx);
case ReadImplKind::Read:
return synthesizeReadCoroutineGetterBody(getter, ctx);
}
llvm_unreachable("bad ReadImplKind");
}
/// Synthesize the body of a setter which just stores to the given storage
/// declaration (which doesn't have to be the storage for the setter).
static std::pair<BraceStmt *, bool>
synthesizeTrivialSetterBodyWithStorage(AccessorDecl *setter,
TargetImpl target,
AbstractStorageDecl *storageToUse,
ASTContext &ctx) {
SourceLoc loc = setter->getStorage()->getLoc();
VarDecl *valueParamDecl = setter->getParameters()->get(0);
auto *valueDRE =
new (ctx) DeclRefExpr(valueParamDecl, DeclNameLoc(), /*IsImplicit=*/true);
valueDRE->setType(valueParamDecl->getTypeInContext());
SmallVector<ASTNode, 1> setterBody;
createPropertyStoreOrCallSuperclassSetter(setter, valueDRE, storageToUse,
target, setterBody, ctx);
return { BraceStmt::create(ctx, loc, setterBody, loc, true),
/*isTypeChecked=*/true };
}
static std::pair<BraceStmt *, bool>
synthesizeTrivialSetterBody(AccessorDecl *setter, ASTContext &ctx) {
auto storage = setter->getStorage();
assert(!isSynthesizedComputedProperty(storage));
return synthesizeTrivialSetterBodyWithStorage(setter, TargetImpl::Storage,
storage, ctx);
}
/// Synthesize the body of a setter for a property wrapper, which
/// delegates to the wrapper's "value" property.
static std::pair<BraceStmt *, bool>
synthesizePropertyWrapperSetterBody(AccessorDecl *setter, ASTContext &ctx) {
return synthesizeTrivialSetterBodyWithStorage(setter, TargetImpl::Wrapper,
setter->getStorage(), ctx);
}
/// Synthesize the body of a setter which just delegates to a mutable
/// addressor.
static std::pair<BraceStmt *, bool>
synthesizeMutableAddressSetterBody(AccessorDecl *setter, ASTContext &ctx) {
// This should call the mutable addressor.
return synthesizeTrivialSetterBodyWithStorage(setter,
TargetImpl::Implementation,
setter->getStorage(), ctx);
}
/// Synthesize the body of a setter which just delegates to a modify
/// coroutine accessor.
static std::pair<BraceStmt *, bool>
synthesizeModifyCoroutineSetterBody(AccessorDecl *setter, ASTContext &ctx) {
// This should call the modify coroutine.
return synthesizeTrivialSetterBodyWithStorage(setter,
TargetImpl::Implementation,
setter->getStorage(), ctx);
}
static Expr *maybeWrapInOutExpr(Expr *expr, ASTContext &ctx) {
if (auto lvalueType = expr->getType()->getAs<LValueType>()) {
auto type = lvalueType->getObjectType();
return new (ctx) InOutExpr(SourceLoc(), expr, type, true);
}
return expr;
}
/// Given a VarDecl with a willSet: and/or didSet: specifier, synthesize the
/// setter which calls them.
static std::pair<BraceStmt *, bool>
synthesizeObservedSetterBody(AccessorDecl *Set, TargetImpl target,
ASTContext &Ctx, bool isLazy = false) {
auto VD = cast<VarDecl>(Set->getStorage());
SourceLoc Loc = VD->getLoc();
// Start by finding the decls for 'self' and 'value'.
auto *SelfDecl = Set->getImplicitSelfDecl();
VarDecl *ValueDecl = Set->getParameters()->get(0);
bool IsSelfLValue = VD->isSetterMutating();
SubstitutionMap subs;
if (auto *genericEnv = Set->getGenericEnvironment())
subs = genericEnv->getForwardingSubstitutionMap();
// The setter loads the oldValue, invokes willSet with the incoming value,
// does a direct store, then invokes didSet with the oldValue.
SmallVector<ASTNode, 6> SetterBody;
auto callObserver = [&](AccessorDecl *observer, VarDecl *arg) {
ConcreteDeclRef ref(observer, subs);
auto type = observer->getInterfaceType().subst(subs);
Expr *Callee = new (Ctx) DeclRefExpr(ref, DeclNameLoc(), /*imp*/true);
Callee->setType(type);
DeclRefExpr *ValueDRE = nullptr;
if (arg) {
ValueDRE = new (Ctx) DeclRefExpr(arg, DeclNameLoc(), /*imp*/ true);
ValueDRE->setType(arg->getTypeInContext());
}
if (SelfDecl) {
auto SelfArg = buildSelfArgument(SelfDecl, SelfAccessorKind::Peer,
/*isMutable*/ IsSelfLValue);
auto *DSCE = DotSyntaxCallExpr::create(Ctx, Callee, SourceLoc(), SelfArg);
if (auto funcType = type->getAs<FunctionType>())
type = funcType->getResult();
DSCE->setType(type);
DSCE->setThrows(nullptr);
Callee = DSCE;
}
CallExpr *Call = nullptr;
if (arg) {
auto *argList = ArgumentList::forImplicitUnlabeled(Ctx, {ValueDRE});
Call = CallExpr::createImplicit(Ctx, Callee, argList);
} else {
Call = CallExpr::createImplicitEmpty(Ctx, Callee);
}
if (auto funcType = type->getAs<FunctionType>())
type = funcType->getResult();
Call->setType(type);
Call->setThrows(nullptr);
SetterBody.push_back(Call);
};
// If there is a didSet, it will take the old value. Load it into a temporary
// 'let' so we have it for later.
VarDecl *OldValue = nullptr;
if (auto didSet = VD->getParsedAccessor(AccessorKind::DidSet)) {
// Only do the load if the didSet body references the implicit oldValue
// parameter or it's provided explicitly in the parameter list.
if (!didSet->isSimpleDidSet()) {
Expr *OldValueExpr =
buildStorageReference(Set, VD, isLazy ? TargetImpl::Ordinary : target,
/*isUsedForGetAccess=*/true,
/*isUsedForSetAccess=*/true, Ctx);
// Error recovery.
if (OldValueExpr == nullptr) {
OldValueExpr = new (Ctx) ErrorExpr(SourceRange(), VD->getTypeInContext());
} else {
OldValueExpr = new (Ctx) LoadExpr(OldValueExpr, VD->getTypeInContext());
}
OldValue = new (Ctx) VarDecl(/*IsStatic*/ false, VarDecl::Introducer::Let,
SourceLoc(), Ctx.getIdentifier("tmp"), Set);
OldValue->setImplicit();
OldValue->setInterfaceType(VD->getValueInterfaceType());
auto *tmpPattern =
NamedPattern::createImplicit(Ctx, OldValue, OldValue->getTypeInContext());
auto *tmpPBD = PatternBindingDecl::createImplicit(
Ctx, StaticSpellingKind::None, tmpPattern, OldValueExpr, Set);
SetterBody.push_back(tmpPBD);
SetterBody.push_back(OldValue);
}
}
if (auto willSet = VD->getParsedAccessor(AccessorKind::WillSet))
callObserver(willSet, ValueDecl);
// Create an assignment into the storage or call to superclass setter.
auto *ValueDRE = new (Ctx) DeclRefExpr(ValueDecl, DeclNameLoc(), true);
ValueDRE->setType(ValueDecl->getTypeInContext());
createPropertyStoreOrCallSuperclassSetter(
Set, ValueDRE, isLazy ? VD->getLazyStorageProperty() : VD, target,
SetterBody, Ctx);
if (auto didSet = VD->getParsedAccessor(AccessorKind::DidSet))
callObserver(didSet, OldValue);
return { BraceStmt::create(Ctx, Loc, SetterBody, Loc, true),
/*isTypeChecked=*/true };
}
static std::pair<BraceStmt *, bool>
synthesizeStoredWithObserversSetterBody(AccessorDecl *setter, ASTContext &ctx) {
return synthesizeObservedSetterBody(setter, TargetImpl::Storage, ctx);
}
static std::pair<BraceStmt *, bool>
synthesizeInheritedWithObserversSetterBody(AccessorDecl *setter,
ASTContext &ctx) {
return synthesizeObservedSetterBody(setter, TargetImpl::Super, ctx);
}
static std::pair<BraceStmt *, bool>
synthesizeSetterBody(AccessorDecl *setter, ASTContext &ctx) {
auto storage = setter->getStorage();
// Synthesize the setter for a lazy property or property wrapper.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (var->getAttrs().hasAttribute<LazyAttr>()) {
// Lazy property setters write to the underlying storage.
if (var->hasObservers()) {
return synthesizeObservedSetterBody(setter, TargetImpl::Storage, ctx,
/*isLazy=*/true);
}
auto *storage = var->getLazyStorageProperty();
return synthesizeTrivialSetterBodyWithStorage(setter, TargetImpl::Storage,
storage, ctx);
}
if (var->hasAttachedPropertyWrapper()) {
if (var->hasObservers()) {
return synthesizeObservedSetterBody(setter, TargetImpl::Wrapper, ctx);
}
return synthesizePropertyWrapperSetterBody(setter, ctx);
}
// Synthesize a setter for the storage wrapper property of a property
// with an attached wrapper.
if (auto original = var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection)) {
auto backingVar = original->getPropertyWrapperBackingProperty();
return synthesizeTrivialSetterBodyWithStorage(setter,
TargetImpl::WrapperStorage,
backingVar, ctx);
}
}
switch (storage->getWriteImpl()) {
case WriteImplKind::Immutable:
llvm_unreachable("synthesizing setter from immutable storage");
case WriteImplKind::Stored:
return synthesizeTrivialSetterBody(setter, ctx);
case WriteImplKind::StoredWithObservers:
return synthesizeStoredWithObserversSetterBody(setter, ctx);
case WriteImplKind::InheritedWithObservers:
return synthesizeInheritedWithObserversSetterBody(setter, ctx);
case WriteImplKind::Set:
return synthesizeInvalidAccessor(setter, ctx);
case WriteImplKind::MutableAddress:
return synthesizeMutableAddressSetterBody(setter, ctx);
case WriteImplKind::Modify:
return synthesizeModifyCoroutineSetterBody(setter, ctx);
}
llvm_unreachable("bad WriteImplKind");
}
static std::pair<BraceStmt *, bool>
synthesizeModifyCoroutineBodyWithSimpleDidSet(AccessorDecl *accessor,
ASTContext &ctx) {
auto storage = accessor->getStorage();
SourceLoc loc = storage->getLoc();
auto isOverride = storage->getOverriddenDecl();
auto target = isOverride ? TargetImpl::Super : TargetImpl::Storage;
SmallVector<ASTNode, 1> body;
Expr *ref = buildStorageReference(accessor, storage, target,
/*isUsedForGetAccess=*/true,
/*isUsedForSetAccess=*/true,
ctx);
ref = maybeWrapInOutExpr(ref, ctx);
YieldStmt *yield = YieldStmt::create(ctx, loc, loc, ref, loc, true);
body.push_back(yield);
auto Set = storage->getAccessor(AccessorKind::Set);
auto DidSet = storage->getAccessor(AccessorKind::DidSet);
auto *SelfDecl = accessor->getImplicitSelfDecl();
SubstitutionMap subs;
if (auto *genericEnv = Set->getGenericEnvironment())
subs = genericEnv->getForwardingSubstitutionMap();
auto callDidSet = [&]() {
ConcreteDeclRef ref(DidSet, subs);
auto type = DidSet->getInterfaceType().subst(subs);
Expr *Callee = new (ctx) DeclRefExpr(ref, DeclNameLoc(), /*imp*/ true);
Callee->setType(type);
if (SelfDecl) {
auto SelfArg =
buildSelfArgument(SelfDecl, SelfAccessorKind::Peer,
/*isMutable*/ storage->isSetterMutating());
auto *DSCE = DotSyntaxCallExpr::create(ctx, Callee, SourceLoc(), SelfArg);
if (auto funcType = type->getAs<FunctionType>())
type = funcType->getResult();
DSCE->setType(type);
DSCE->setThrows(nullptr);
Callee = DSCE;
}
auto *Call = CallExpr::createImplicitEmpty(ctx, Callee);
if (auto funcType = type->getAs<FunctionType>())
type = funcType->getResult();
Call->setType(type);
Call->setThrows(nullptr);
body.push_back(Call);
};
callDidSet();
return {BraceStmt::create(ctx, loc, body, loc, true),
/*isTypeChecked=*/true};
}
static std::pair<BraceStmt *, bool>
synthesizeCoroutineAccessorBody(AccessorDecl *accessor, ASTContext &ctx) {
assert(accessor->isCoroutine());
auto storage = accessor->getStorage();
auto storageReadWriteImpl = storage->getReadWriteImpl();
auto target = (accessor->hasForcedStaticDispatch()
? TargetImpl::Ordinary
: TargetImpl::Implementation);
// If this is a variable with an attached property wrapper, then
// the accessors need to yield the wrappedValue or projectedValue.
if (accessor->getAccessorKind() == AccessorKind::Read ||
storageReadWriteImpl == ReadWriteImplKind::Modify) {
if (auto var = dyn_cast<VarDecl>(storage)) {
if (var->hasAttachedPropertyWrapper()) {
target = TargetImpl::Wrapper;
}
if (var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection)) {
target = TargetImpl::WrapperStorage;
}
}
}
SourceLoc loc = storage->getLoc();
SmallVector<ASTNode, 1> body;
bool isModify = accessor->getAccessorKind() == AccessorKind::Modify;
// Special-case for a modify coroutine of a simple stored property with
// observers. We can yield a borrowed copy of the underlying storage
// in this case. However, if the accessor was synthesized on-demand,
// we do the more general thing, because on-demand accessors might be
// serialized, which prevents them from being able to directly reference
// didSet/willSet accessors, which are private.
if (isModify &&
!accessor->hasForcedStaticDispatch() &&
(storageReadWriteImpl == ReadWriteImplKind::StoredWithDidSet ||
storageReadWriteImpl == ReadWriteImplKind::InheritedWithDidSet) &&
storage->getParsedAccessor(AccessorKind::DidSet)->isSimpleDidSet()) {
return synthesizeModifyCoroutineBodyWithSimpleDidSet(accessor, ctx);
}
// Build a reference to the storage.
Expr *ref = buildStorageReference(accessor, storage, target,
/*isUsedForGetAccess=*/true,
/*isUsedForSetAccess=*/isModify,
ctx);
if (ref != nullptr) {
// Wrap it with an `&` marker if this is a modify.
ref = maybeWrapInOutExpr(ref, ctx);
// Yield it.
YieldStmt *yield = YieldStmt::create(ctx, loc, loc, ref, loc, true);
body.push_back(yield);
}
return { BraceStmt::create(ctx, loc, body, loc, true),
/*isTypeChecked=*/true };
}
/// Synthesize the body of a read coroutine.
static std::pair<BraceStmt *, bool>
synthesizeReadCoroutineBody(AccessorDecl *read, ASTContext &ctx) {
assert(read->getStorage()->getReadImpl() != ReadImplKind::Read);
return synthesizeCoroutineAccessorBody(read, ctx);
}
/// Synthesize the body of a modify coroutine.
static std::pair<BraceStmt *, bool>
synthesizeModifyCoroutineBody(AccessorDecl *modify, ASTContext &ctx) {
#ifndef NDEBUG
auto storage = modify->getStorage();
auto impl = storage->getReadWriteImpl();
auto hasWrapper = isa<VarDecl>(storage) &&
cast<VarDecl>(storage)->hasAttachedPropertyWrapper();
assert((hasWrapper || impl != ReadWriteImplKind::Modify) &&
impl != ReadWriteImplKind::Immutable);
#endif
return synthesizeCoroutineAccessorBody(modify, ctx);
}
static std::pair<BraceStmt *, bool>
synthesizeAccessorBody(AbstractFunctionDecl *fn, void *) {
auto *accessor = cast<AccessorDecl>(fn);
auto &ctx = accessor->getASTContext();
if (ctx.Stats)
++ctx.Stats->getFrontendCounters().NumAccessorBodiesSynthesized;
switch (accessor->getAccessorKind()) {
case AccessorKind::Get:
case AccessorKind::DistributedGet:
return synthesizeGetterBody(accessor, ctx);
case AccessorKind::Set:
return synthesizeSetterBody(accessor, ctx);
case AccessorKind::Read:
return synthesizeReadCoroutineBody(accessor, ctx);
case AccessorKind::Modify:
return synthesizeModifyCoroutineBody(accessor, ctx);
case AccessorKind::WillSet:
case AccessorKind::DidSet:
case AccessorKind::Address:
case AccessorKind::MutableAddress:
break;
case AccessorKind::Init:
llvm_unreachable("init accessor not yet implemented");
}
llvm_unreachable("bad synthesized function kind");
}
static void finishImplicitAccessor(AccessorDecl *accessor,
ASTContext &ctx) {
accessor->setImplicit();
if (ctx.Stats)
++ctx.Stats->getFrontendCounters().NumAccessorsSynthesized;
if (doesAccessorHaveBody(accessor))
accessor->setBodySynthesizer(&synthesizeAccessorBody);
}
static AccessorDecl *createGetterPrototype(AbstractStorageDecl *storage,
ASTContext &ctx) {
SourceLoc loc = storage->getLoc();
ParamDecl *selfDecl = nullptr;
if (storage->getDeclContext()->isTypeContext()) {
if (storage->getAttrs().hasAttribute<LazyAttr>()) {
// For lazy properties, steal the 'self' from the initializer context.
auto *varDecl = cast<VarDecl>(storage);
auto *bindingDecl = varDecl->getParentPatternBinding();
const auto i = bindingDecl->getPatternEntryIndexForVarDecl(varDecl);
selfDecl = bindingDecl->getInitContext(i)->getImplicitSelfDecl();
}
}
// Add an index-forwarding clause.
auto *getterParams = buildIndexForwardingParamList(storage, {}, ctx);
SourceLoc staticLoc;
if (storage->isStatic())
staticLoc = storage->getLoc();
auto getter = AccessorDecl::create(
ctx, loc, /*AccessorKeywordLoc*/ loc, AccessorKind::Get, storage,
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), /*ThrownType=*/TypeLoc(),
getterParams, Type(), storage->getDeclContext());
getter->setSynthesized();
// If we're stealing the 'self' from a lazy initializer, set it now.
// Note that we don't re-parent the 'self' declaration to be part of
// the getter until we synthesize the body of the getter later.
if (selfDecl)
*getter->getImplicitSelfDeclStorage() = selfDecl;
if (storage->isGetterMutating())
getter->setSelfAccessKind(SelfAccessKind::Mutating);
else
getter->setSelfAccessKind(SelfAccessKind::NonMutating);
if (!storage->requiresOpaqueAccessor(AccessorKind::Get))
getter->setForcedStaticDispatch(true);
finishImplicitAccessor(getter, ctx);
return getter;
}
static void addPropertyWrapperAccessorAvailability(VarDecl *var, AccessorKind accessorKind,
SmallVectorImpl<const Decl *> &asAvailableAs) {
AccessorDecl *synthesizedFrom = nullptr;
if (var->hasAttachedPropertyWrapper()) {
AbstractStorageDecl *wrappedValueImpl;
if (auto access = getEnclosingSelfPropertyWrapperAccess(var, /*forProjected=*/false)) {
wrappedValueImpl = access->subscript;
} else {
wrappedValueImpl = var->getAttachedPropertyWrapperTypeInfo(0).valueVar;
}
// The property wrapper info may not actually link back to a wrapper
// implementation, if there was a semantic error checking the wrapper.
if (wrappedValueImpl) {
synthesizedFrom = wrappedValueImpl->getOpaqueAccessor(accessorKind);
}
} else if (auto wrapperSynthesizedKind
= var->getPropertyWrapperSynthesizedPropertyKind()) {
switch (*wrapperSynthesizedKind) {
case PropertyWrapperSynthesizedPropertyKind::Backing:
break;
case PropertyWrapperSynthesizedPropertyKind::Projection: {
if (auto origVar = var->getOriginalWrappedProperty(wrapperSynthesizedKind)) {
AbstractStorageDecl *projectedValueImpl;
if (auto access = getEnclosingSelfPropertyWrapperAccess(origVar, /*forProjected=*/true)) {
projectedValueImpl = access->subscript;
} else {
projectedValueImpl = origVar->getAttachedPropertyWrapperTypeInfo(0).projectedValueVar;
}
// The property wrapper info may not actually link back to a wrapper
// implementation, if there was a semantic error checking the wrapper.
if (projectedValueImpl) {
synthesizedFrom = projectedValueImpl->getOpaqueAccessor(accessorKind);
}
}
break;
}
}
}
// Infer availability from the accessor used for synthesis, and intersect it
// with the availability of the enclosing scope.
if (synthesizedFrom) {
asAvailableAs.push_back(synthesizedFrom);
if (auto *enclosingDecl = var->getInnermostDeclWithAvailability())
asAvailableAs.push_back(enclosingDecl);
}
}
static AccessorDecl *createSetterPrototype(AbstractStorageDecl *storage,
ASTContext &ctx,
AccessorDecl *getter = nullptr) {
assert(storage->supportsMutation());
SourceLoc loc = storage->getLoc();
bool isMutating = storage->isSetterMutating();
// Add a "(value : T, indices...)" argument list.
auto *param = new (ctx) ParamDecl(SourceLoc(), SourceLoc(),
Identifier(), loc,
ctx.getIdentifier("value"),
storage->getDeclContext());
param->setSpecifier(ParamSpecifier::Default);
param->setImplicit();
auto *params = buildIndexForwardingParamList(storage, param, ctx);
auto setter = AccessorDecl::create(
ctx, loc, /*AccessorKeywordLoc*/ SourceLoc(), AccessorKind::Set, storage,
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), /*ThrownType=*/TypeLoc(),
params, Type(), storage->getDeclContext());
setter->setSynthesized();
if (isMutating)
setter->setSelfAccessKind(SelfAccessKind::Mutating);
else
setter->setSelfAccessKind(SelfAccessKind::NonMutating);
// All mutable storage requires a setter.
assert(storage->requiresOpaqueAccessor(AccessorKind::Set));
// Copy availability from the accessor we'll synthesize the setter from.
SmallVector<const Decl *, 2> asAvailableAs;
// That could be a property wrapper...
if (auto var = dyn_cast<VarDecl>(storage)) {
addPropertyWrapperAccessorAvailability(var, AccessorKind::Set, asAvailableAs);
}
// ...or another accessor.
switch (storage->getWriteImpl()) {
case WriteImplKind::Immutable:
llvm_unreachable("synthesizing setter from immutable storage");
case WriteImplKind::Stored:
case WriteImplKind::StoredWithObservers:
case WriteImplKind::InheritedWithObservers:
case WriteImplKind::Set:
// Setter's availability shouldn't be externally influenced in these
// cases.
break;
case WriteImplKind::MutableAddress:
if (auto addr = storage->getOpaqueAccessor(AccessorKind::MutableAddress)) {
asAvailableAs.push_back(addr);
}
break;
case WriteImplKind::Modify:
if (auto mod = storage->getOpaqueAccessor(AccessorKind::Modify)) {
asAvailableAs.push_back(mod);
}
break;
}
if (!asAvailableAs.empty()) {
AvailabilityInference::applyInferredAvailableAttrs(
setter, asAvailableAs, ctx);
}
finishImplicitAccessor(setter, ctx);
return setter;
}
static AccessorDecl *
createCoroutineAccessorPrototype(AbstractStorageDecl *storage,
AccessorKind kind,
ASTContext &ctx) {
assert(kind == AccessorKind::Read || kind == AccessorKind::Modify);
SourceLoc loc = storage->getLoc();
bool isMutating = storage->isGetterMutating();
if (kind == AccessorKind::Modify)
isMutating |= storage->isSetterMutating();
auto dc = storage->getDeclContext();
// The forwarding index parameters.
auto *params = buildIndexForwardingParamList(storage, {}, ctx);
// Coroutine accessors always return ().
const Type retTy = TupleType::getEmpty(ctx);
auto *accessor = AccessorDecl::create(
ctx, loc, /*AccessorKeywordLoc=*/SourceLoc(), kind, storage,
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), /*ThrownType=*/TypeLoc(),
params, retTy, dc);
accessor->setSynthesized();
if (isMutating)
accessor->setSelfAccessKind(SelfAccessKind::Mutating);
else
accessor->setSelfAccessKind(SelfAccessKind::NonMutating);
// If the storage does not provide this accessor as an opaque accessor,
// we can't add a dynamically-dispatched method entry for the accessor,
// so force it to be statically dispatched. ("final" would be inappropriate
// because the property can still be overridden.)
if (!storage->requiresOpaqueAccessor(kind))
accessor->setForcedStaticDispatch(true);
// Make sure the coroutine is available enough to access
// the storage (and its getters/setters if it has them).
SmallVector<const Decl *, 2> asAvailableAs;
asAvailableAs.push_back(storage);
if (FuncDecl *getter = storage->getParsedAccessor(AccessorKind::Get)) {
asAvailableAs.push_back(getter);
}
if (kind == AccessorKind::Modify) {
if (FuncDecl *setter = storage->getParsedAccessor(AccessorKind::Set)) {
asAvailableAs.push_back(setter);
}
}
if (auto var = dyn_cast<VarDecl>(storage)) {
addPropertyWrapperAccessorAvailability(var, kind, asAvailableAs);
}
AvailabilityInference::applyInferredAvailableAttrs(accessor,
asAvailableAs, ctx);
// A modify coroutine should have the same SPI visibility as the setter.
if (kind == AccessorKind::Modify) {
if (FuncDecl *setter = storage->getParsedAccessor(AccessorKind::Set))
applyInferredSPIAccessControlAttr(accessor, setter, ctx);
}
finishImplicitAccessor(accessor, ctx);
return accessor;
}
static AccessorDecl *
createReadCoroutinePrototype(AbstractStorageDecl *storage,
ASTContext &ctx) {
return createCoroutineAccessorPrototype(storage, AccessorKind::Read, ctx);
}
static AccessorDecl *
createModifyCoroutinePrototype(AbstractStorageDecl *storage,
ASTContext &ctx) {
return createCoroutineAccessorPrototype(storage, AccessorKind::Modify, ctx);
}
AccessorDecl *
SynthesizeAccessorRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *storage,
AccessorKind kind) const {
auto &ctx = storage->getASTContext();
switch (kind) {
case AccessorKind::Get:
case AccessorKind::DistributedGet:
return createGetterPrototype(storage, ctx);
case AccessorKind::Set:
return createSetterPrototype(storage, ctx);
case AccessorKind::Read:
return createReadCoroutinePrototype(storage, ctx);
case AccessorKind::Modify:
return createModifyCoroutinePrototype(storage, ctx);
#define OPAQUE_ACCESSOR(ID, KEYWORD)
#define ACCESSOR(ID) \
case AccessorKind::ID:
#include "swift/AST/AccessorKinds.def"
llvm_unreachable("not an opaque accessor");
}
llvm_unreachable("Unhandled AccessorKind in switch");
}
bool
RequiresOpaqueAccessorsRequest::evaluate(Evaluator &evaluator,
VarDecl *var) const {
// Nameless vars from interface files should not have any accessors.
// TODO: Replace this check with a broader check that all storage decls
// from interface files have all their accessors up front.
if (var->getBaseName().empty())
return false;
// Computed properties always require opaque accessors.
if (!var->getImplInfo().isSimpleStored())
return true;
// The backing storage for a lazy property does require opaque accessors.
if (var->isLazyStorageProperty())
return false;
auto *dc = var->getDeclContext();
// Local stored variables don't require opaque accessors.
if (dc->isLocalContext()) {
return false;
} else if (dc->isModuleScopeContext()) {
// Fixed-layout global variables don't require opaque accessors.
if (!var->isResilient() && !var->shouldUseNativeDynamicDispatch())
return false;
// Stored properties imported from Clang don't require opaque accessors.
} else if (auto *structDecl = dyn_cast<StructDecl>(dc)) {
if (structDecl->hasClangNode())
return false;
} else if (isa<ClassDecl>(dc) &&
cast<ClassDecl>(dc)->isForeignReferenceType()) {
return false;
}
// Stored properties in SIL mode don't get accessors.
// But we might need to create opaque accessors for them.
if (auto sourceFile = dc->getParentSourceFile()) {
if (sourceFile->Kind == SourceFileKind::SIL) {
if (!var->getParsedAccessor(AccessorKind::Get))
return false;
}
}
// Everything else requires opaque accessors.
return true;
}
bool
RequiresOpaqueModifyCoroutineRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *storage) const {
// Only for mutable storage.
if (!storage->supportsMutation())
return false;
auto *dc = storage->getDeclContext();
// Local properties don't have an opaque modify coroutine.
if (dc->isLocalContext())
return false;
// Fixed-layout global properties don't have an opaque modify coroutine.
if (dc->isModuleScopeContext() && !storage->isResilient())
return false;
// Imported storage declarations don't have an opaque modify coroutine.
if (storage->hasClangNode())
return false;
// Dynamic storage does not have an opaque modify coroutine.
if (dc->getSelfClassDecl())
if (storage->shouldUseObjCDispatch())
return false;
// Requirements of ObjC protocols don't have an opaque modify coroutine.
if (auto protoDecl = dyn_cast<ProtocolDecl>(dc))
if (protoDecl->isObjC())
return false;
return true;
}
/// Mark the accessor as transparent if we can.
///
/// If the storage is inside a fixed-layout nominal type, we can mark the
/// accessor as transparent, since in this case we just want it for abstraction
/// purposes (i.e., to make access to the variable uniform and to be able to
/// put the getter in a vtable).
///
/// If the storage is for a global stored property or a stored property of a
/// resilient type, we are synthesizing accessors to present a resilient
/// interface to the storage and they should not be transparent.
bool
IsAccessorTransparentRequest::evaluate(Evaluator &evaluator,
AccessorDecl *accessor) const {
auto *storage = accessor->getStorage();
if (storage->isTransparent())
return true;
if (accessor->getAttrs().hasAttribute<TransparentAttr>())
return true;
if (!accessor->isImplicit())
return false;
if (!doesAccessorHaveBody(accessor))
return false;
auto *DC = accessor->getDeclContext();
auto *nominalDecl = DC->getSelfNominalTypeDecl();
// Global variable accessors are not @_transparent.
if (!nominalDecl)
return false;
// Accessors for resilient properties are not @_transparent.
if (storage->isResilient())
return false;
// Accessors for classes with @objc ancestry are not @_transparent,
// since they use a field offset variable which is not exported.
if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
if (classDecl->checkAncestry(AncestryFlags::ObjC))
return false;
// Accessors synthesized on-demand are never transparent.
if (accessor->hasForcedStaticDispatch())
return false;
if (accessor->getAccessorKind() == AccessorKind::Get ||
accessor->getAccessorKind() == AccessorKind::Set) {
// Getters and setters for lazy properties are not @_transparent.
if (storage->getAttrs().hasAttribute<LazyAttr>())
return false;
}
// Accessors for a property with a wrapper are not @_transparent if
// the backing variable has more-restrictive access than the original
// property. The same goes for its storage wrapper.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (auto backingVar = var->getPropertyWrapperBackingProperty()) {
if (backingVar->getFormalAccess() < var->getFormalAccess())
return false;
}
if (auto original = var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection)) {
auto backingVar = original->getPropertyWrapperBackingProperty();
if (backingVar->getFormalAccess() < var->getFormalAccess())
return false;
}
}
switch (accessor->getAccessorKind()) {
case AccessorKind::Get:
break;
case AccessorKind::DistributedGet:
return false;
case AccessorKind::Set:
switch (storage->getWriteImpl()) {
case WriteImplKind::Set:
// Setters for property wrapper are OK, unless there are observers.
// FIXME: This should be folded into the WriteImplKind below.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (var->hasAttachedPropertyWrapper()) {
if (var->hasObservers())
return false;
break;
} else if (var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection)) {
break;
}
}
if (auto subscript = dyn_cast<SubscriptDecl>(storage)) {
break;
}
// Anything else should not have a synthesized setter.
LLVM_FALLTHROUGH;
case WriteImplKind::Immutable:
if (accessor->getASTContext().LangOpts.AllowModuleWithCompilerErrors)
return false;
llvm_unreachable("should not be synthesizing accessor in this case");
case WriteImplKind::StoredWithObservers:
case WriteImplKind::InheritedWithObservers:
// Setters for observed properties are not @_transparent (because the
// observers are private) and cannot be referenced from a transparent
// method).
return false;
case WriteImplKind::Stored:
case WriteImplKind::MutableAddress:
case WriteImplKind::Modify:
break;
}
break;
case AccessorKind::Read:
case AccessorKind::Modify:
case AccessorKind::Init:
break;
case AccessorKind::WillSet:
case AccessorKind::DidSet:
case AccessorKind::Address:
case AccessorKind::MutableAddress:
llvm_unreachable("bad synthesized function kind");
}
switch (storage->getReadWriteImpl()) {
case ReadWriteImplKind::StoredWithDidSet:
case ReadWriteImplKind::InheritedWithDidSet:
if (storage->getAccessor(AccessorKind::DidSet)->isSimpleDidSet())
return false;
break;
default:
break;
}
return true;
}
VarDecl *
LazyStoragePropertyRequest::evaluate(Evaluator &evaluator,
VarDecl *VD) const {
assert(isa<SourceFile>(VD->getDeclContext()->getModuleScopeContext()));
assert(VD->getAttrs().hasAttribute<LazyAttr>());
auto &Context = VD->getASTContext();
// Create the storage property as an optional of VD's type.
SmallString<64> NameBuf;
NameBuf += "$__lazy_storage_$_";
NameBuf += VD->getName().str();
auto StorageName = Context.getIdentifier(NameBuf);
auto StorageInterfaceTy = OptionalType::get(VD->getInterfaceType());
auto StorageTy = OptionalType::get(VD->getTypeInContext());
auto *Storage = new (Context) VarDecl(/*IsStatic*/false, VarDecl::Introducer::Var,
VD->getLoc(), StorageName,
VD->getDeclContext());
Storage->setInterfaceType(StorageInterfaceTy);
Storage->setLazyStorageProperty(true);
Storage->setUserAccessible(false);
// The storage is implicit and private.
Storage->setImplicit();
Storage->overwriteAccess(AccessLevel::Private);
Storage->overwriteSetterAccess(AccessLevel::Private);
addMemberToContextIfNeeded(Storage, VD->getDeclContext(), VD);
// Create the pattern binding decl for the storage decl. This will get
// default initialized to nil.
Pattern *PBDPattern =
NamedPattern::createImplicit(Context, Storage, StorageTy);
PBDPattern = TypedPattern::createImplicit(Context, PBDPattern, StorageTy);
auto *InitExpr = new (Context) NilLiteralExpr(SourceLoc(), /*Implicit=*/true);
InitExpr->setType(Storage->getTypeInContext());
auto *PBD = PatternBindingDecl::createImplicit(
Context, StaticSpellingKind::None, PBDPattern, InitExpr,
VD->getDeclContext(), /*VarLoc*/ VD->getLoc());
PBD->setInitializerChecked(0);
addMemberToContextIfNeeded(PBD, VD->getDeclContext(), Storage);
// Make sure the original init is marked as subsumed.
auto *originalPBD = VD->getParentPatternBinding();
auto originalIndex = originalPBD->getPatternEntryIndexForVarDecl(VD);
originalPBD->setInitializerSubsumed(originalIndex);
return Storage;
}
/// Synthesize a computed property representing the wrapped value for a
/// parameter with an attached property wrapper.
static VarDecl *synthesizeLocalWrappedValueVar(VarDecl *var) {
if (!var->hasAttachedPropertyWrapper() || !isa<ParamDecl>(var))
return nullptr;
auto dc = var->getDeclContext();
auto &ctx = var->getASTContext();
SmallString<64> nameBuf;
if (var->getName().hasDollarPrefix()) {
nameBuf = var->getName().str().drop_front();
} else {
nameBuf = var->getName().str();
}
Identifier name = ctx.getIdentifier(nameBuf);
VarDecl *localVar = new (ctx) VarDecl(/*IsStatic=*/false,
VarDecl::Introducer::Var,
var->getLoc(), name, dc);
localVar->setImplicit();
localVar->getAttrs() = var->getAttrs();
localVar->overwriteAccess(var->getFormalAccess());
if (var->hasImplicitPropertyWrapper()) {
// FIXME: This can have a setter, but we need a resolved wrapper type
// to figure it out.
localVar->setImplInfo(StorageImplInfo::getImmutableComputed());
} else {
auto mutability = *var->getPropertyWrapperMutability();
if (mutability.Getter == PropertyWrapperMutability::Mutating) {
ctx.Diags.diagnose(var->getLoc(), diag::property_wrapper_param_mutating);
return nullptr;
}
if (mutability.Setter == PropertyWrapperMutability::Nonmutating) {
localVar->setImplInfo(StorageImplInfo::getMutableComputed());
} else {
localVar->setImplInfo(StorageImplInfo::getImmutableComputed());
}
}
return localVar;
}
/// Synthesize a computed property `$foo` for a property with an attached
/// wrapper that has a `projectedValue` property.
static VarDecl *synthesizePropertyWrapperProjectionVar(
ASTContext &ctx, VarDecl *var, VarDecl *wrapperVar) {
// If the original property has a @_projectedValueProperty attribute, use
// that to find the storage wrapper property.
if (auto attr = var->getAttrs().getAttribute<ProjectedValuePropertyAttr>()){
SmallVector<ValueDecl *, 2> declsFound;
DeclNameRef projectionName(attr->ProjectionPropertyName);
auto dc = var->getDeclContext();
if (dc->isTypeContext()) {
dc->lookupQualified(dc->getSelfNominalTypeDecl(), projectionName,
var->getLoc(), NL_QualifiedDefault, declsFound);
} else if (dc->isModuleScopeContext()) {
dc->lookupQualified(dc->getParentModule(), projectionName,
var->getLoc(), NL_QualifiedDefault, declsFound);
} else {
llvm_unreachable("Property wrappers don't work in local contexts");
}
if (declsFound.size() == 1 && isa<VarDecl>(declsFound.front())) {
auto property = cast<VarDecl>(declsFound.front());
property->setOriginalWrappedProperty(var);
return property;
}
ctx.Diags.diagnose(attr->getLocation(),
diag::property_wrapper_projection_value_missing,
projectionName);
attr->setInvalid();
}
// Compute the name of the storage type.
SmallString<64> nameBuf;
if (var->getName().hasDollarPrefix()) {
nameBuf = var->getName().str();
} else {
nameBuf = "$";
nameBuf += var->getName().str();
}
Identifier name = ctx.getIdentifier(nameBuf);
// Form the property.
auto dc = var->getDeclContext();
VarDecl *property = new (ctx) VarDecl(/*IsStatic=*/var->isStatic(),
VarDecl::Introducer::Var,
var->getLoc(),
name, dc);
property->setImplicit();
property->setOriginalWrappedProperty(var);
addMemberToContextIfNeeded(property, dc, var);
// Determine the access level for the property.
property->overwriteAccess(var->getFormalAccess());
// Determine setter access.
property->overwriteSetterAccess(var->getSetterFormalAccess());
// Add the accessors we need.
if (var->hasImplicitPropertyWrapper()) {
// FIXME: This can have a setter, but we need a resolved type first
// to figure it out.
property->setImplInfo(StorageImplInfo::getImmutableComputed());
} else {
bool hasSetter = wrapperVar->isSettable(nullptr) &&
wrapperVar->isSetterAccessibleFrom(var->getInnermostDeclContext());
if (hasSetter)
property->setImplInfo(StorageImplInfo::getMutableComputed());
else
property->setImplInfo(StorageImplInfo::getImmutableComputed());
}
if (!isa<ParamDecl>(var))
var->getAttrs().add(
new (ctx) ProjectedValuePropertyAttr(name, SourceLoc(), SourceRange(),
/*Implicit=*/true));
return property;
}
static void typeCheckSynthesizedWrapperInitializer(VarDecl *wrappedVar,
Expr *&initializer,
bool contextualize) {
auto *dc = wrappedVar->getInnermostDeclContext();
auto &ctx = wrappedVar->getASTContext();
auto *initContext = new (ctx) PropertyWrapperInitializer(
dc, wrappedVar, PropertyWrapperInitializer::Kind::WrappedValue);
// Type-check the initialization.
using namespace constraints;
auto target = SyntacticElementTarget::forPropertyWrapperInitializer(
wrappedVar, initContext, initializer);
auto result = TypeChecker::typeCheckExpression(target);
if (!result)
return;
initializer = result->getAsExpr();
// Contextualize the initializer which is a local variable with defaultInit or
// gets an independent initializer. The rest of initializer contextualizing
// will be done in visitPatternBindingDecl.
if (!contextualize)
return;
TypeChecker::contextualizeInitializer(initContext, initializer);
checkPropertyWrapperActorIsolation(wrappedVar, initializer);
TypeChecker::checkInitializerEffects(initContext, initializer);
}
static PropertyWrapperMutability::Value
getGetterMutatingness(VarDecl *var) {
return var->isGetterMutating()
? PropertyWrapperMutability::Mutating
: PropertyWrapperMutability::Nonmutating;
}
static PropertyWrapperMutability::Value
getSetterMutatingness(VarDecl *var, DeclContext *dc) {
if (!var->isSettable(nullptr) ||
!var->isSetterAccessibleFrom(dc))
return PropertyWrapperMutability::DoesntExist;
return var->isSetterMutating()
? PropertyWrapperMutability::Mutating
: PropertyWrapperMutability::Nonmutating;
}
std::optional<PropertyWrapperMutability>
PropertyWrapperMutabilityRequest::evaluate(Evaluator &, VarDecl *var) const {
VarDecl *originalVar = var;
unsigned numWrappers = originalVar->getAttachedPropertyWrappers().size();
bool isProjectedValue = false;
if (numWrappers < 1) {
originalVar = var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection);
if (!originalVar)
return std::nullopt;
numWrappers = originalVar->getAttachedPropertyWrappers().size();
isProjectedValue = true;
}
// Make sure we don't ignore .swiftinterface files, because those will
// have the accessors printed
auto varSourceFile = var->getDeclContext()->getParentSourceFile();
auto isVarNotInInterfaceFile =
varSourceFile && varSourceFile->Kind != SourceFileKind::Interface;
if (var->getParsedAccessor(AccessorKind::Get) && isVarNotInInterfaceFile)
return std::nullopt;
if (var->getParsedAccessor(AccessorKind::Set) && isVarNotInInterfaceFile)
return std::nullopt;
// Figure out which member we're looking through.
auto varMember = isProjectedValue
? &PropertyWrapperTypeInfo::projectedValueVar
: &PropertyWrapperTypeInfo::valueVar;
// Start with the traits from the outermost wrapper.
auto firstWrapper = originalVar->getAttachedPropertyWrapperTypeInfo(0);
if (firstWrapper.*varMember == nullptr)
return std::nullopt;
PropertyWrapperMutability result;
result.Getter = getGetterMutatingness(firstWrapper.*varMember);
result.Setter = getSetterMutatingness(firstWrapper.*varMember,
var->getInnermostDeclContext());
auto getCustomAttrTypeLoc = [](const CustomAttr *CA) -> TypeLoc {
return { CA->getTypeRepr(), CA->getType() };
};
// Compose the traits of the following wrappers.
for (unsigned i = 1; i < numWrappers && !isProjectedValue; ++i) {
assert(var == originalVar);
auto wrapper = var->getAttachedPropertyWrapperTypeInfo(i);
if (!wrapper.valueVar)
return std::nullopt;
PropertyWrapperMutability nextResult;
nextResult.Getter =
result.composeWith(getGetterMutatingness(wrapper.valueVar));
// A property must have a getter, so we can't compose a wrapper that
// exposes a mutating getter wrapped inside a get-only wrapper.
if (nextResult.Getter == PropertyWrapperMutability::DoesntExist) {
auto &ctx = var->getASTContext();
ctx.Diags.diagnose(var->getAttachedPropertyWrappers()[i]->getLocation(),
diag::property_wrapper_mutating_get_composed_to_get_only,
getCustomAttrTypeLoc(var->getAttachedPropertyWrappers()[i]),
getCustomAttrTypeLoc(var->getAttachedPropertyWrappers()[i-1]));
return std::nullopt;
}
nextResult.Setter =
result.composeWith(getSetterMutatingness(wrapper.valueVar,
var->getInnermostDeclContext()));
result = nextResult;
}
assert(result.Getter != PropertyWrapperMutability::DoesntExist
&& "getter must exist");
return result;
}
std::optional<PropertyWrapperLValueness>
PropertyWrapperLValuenessRequest::evaluate(Evaluator &, VarDecl *var) const {
VarDecl *VD = var;
unsigned numWrappers = var->getAttachedPropertyWrappers().size();
bool isProjectedValue = false;
if (numWrappers < 1) {
VD = var->getOriginalWrappedProperty(
PropertyWrapperSynthesizedPropertyKind::Projection);
numWrappers = 1; // Can't compose projected values
isProjectedValue = true;
}
if (!VD)
return std::nullopt;
auto varMember = isProjectedValue
? &PropertyWrapperTypeInfo::projectedValueVar
: &PropertyWrapperTypeInfo::valueVar;
auto accessorMutability = [&](unsigned wrapperIndex) -> PropertyWrapperMutability {
PropertyWrapperMutability mutability;
auto wrapperInfo = VD->getAttachedPropertyWrapperTypeInfo(wrapperIndex);
mutability.Getter = getGetterMutatingness(wrapperInfo.*varMember);
mutability.Setter = getSetterMutatingness(wrapperInfo.*varMember,
var->getInnermostDeclContext());
return mutability;
};
// Calling the getter (or setter) on the nth property wrapper in the chain
// is done as follows:
// 1. call the getter on the (n-1)th property wrapper instance to get the
// nth property wrapper instance
// 2. call the getter (or setter) on the nth property wrapper instance
// 3. if (2) is a mutating access, call the setter on the (n-1)th property
// wrapper instance to write back the mutated value
// Below, we determine which of these property wrapper instances need to be
// accessed mutating-ly, and therefore should be l-values.
unsigned innermostWrapperIdx = numWrappers - 1;
auto lastAccess = accessorMutability(innermostWrapperIdx);
PropertyWrapperLValueness lvalueness(numWrappers);
lvalueness.isLValueForGetAccess[innermostWrapperIdx] =
lastAccess.Getter == PropertyWrapperMutability::Mutating;
lvalueness.isLValueForSetAccess[innermostWrapperIdx] =
lastAccess.Setter == PropertyWrapperMutability::Mutating;
auto lastAccessForGet = lastAccess.Getter;
auto lastAccessForSet = lastAccess.Setter;
for (int i = innermostWrapperIdx - 1; i >= 0; --i) {
auto access = accessorMutability(i);
lastAccessForGet = access.composeWith(lastAccessForGet);
lastAccessForSet = access.composeWith(lastAccessForSet);
lvalueness.isLValueForGetAccess[i] =
lastAccessForGet == PropertyWrapperMutability::Mutating;
lvalueness.isLValueForSetAccess[i] =
lastAccessForSet == PropertyWrapperMutability::Mutating;
}
return lvalueness;
}
PropertyWrapperAuxiliaryVariables
PropertyWrapperAuxiliaryVariablesRequest::evaluate(Evaluator &evaluator,
VarDecl *var) const {
if (!var->hasAttachedPropertyWrapper())
return PropertyWrapperAuxiliaryVariables();
auto wrapperInfo = var->getAttachedPropertyWrapperTypeInfo(0);
// Compute the name of the storage type.
ASTContext &ctx = var->getASTContext();
SmallString<64> nameBuf;
nameBuf = "_";
if (var->getName().hasDollarPrefix())
nameBuf += var->getName().str().drop_front();
else
nameBuf += var->getName().str();
Identifier name = ctx.getIdentifier(nameBuf);
auto dc = var->getDeclContext();
VarDecl *backingVar = nullptr;
VarDecl *projectionVar = nullptr;
VarDecl *wrappedValueVar = nullptr;
// Create the backing storage property.
if (var->hasExternalPropertyWrapper()) {
auto *param = cast<ParamDecl>(var);
backingVar = ParamDecl::cloneWithoutType(ctx, param);
backingVar->setName(name);
} else {
auto introducer = isa<ParamDecl>(var) ? VarDecl::Introducer::Let : VarDecl::Introducer::Var;
backingVar = new (ctx) VarDecl(/*IsStatic=*/var->isStatic(),
introducer,
var->getLoc(),
name, dc);
backingVar->setImplicit();
backingVar->setOriginalWrappedProperty(var);
// The backing storage is 'private'.
backingVar->overwriteAccess(AccessLevel::Private);
backingVar->overwriteSetterAccess(AccessLevel::Private);
addMemberToContextIfNeeded(backingVar, dc, var);
}
if (wrapperInfo.projectedValueVar || var->getName().hasDollarPrefix()) {
projectionVar = synthesizePropertyWrapperProjectionVar(
ctx, var, wrapperInfo.projectedValueVar);
}
if ((wrappedValueVar = synthesizeLocalWrappedValueVar(var))) {
// Record the backing storage for the local wrapped value var, which
// is needed for synthesizing its accessors.
evaluator.cacheOutput(PropertyWrapperAuxiliaryVariablesRequest{wrappedValueVar},
PropertyWrapperAuxiliaryVariables(backingVar, projectionVar));
}
return PropertyWrapperAuxiliaryVariables(backingVar, projectionVar, wrappedValueVar);
}
PropertyWrapperInitializerInfo
PropertyWrapperInitializerInfoRequest::evaluate(Evaluator &evaluator,
VarDecl *var) const {
if (!var->hasAttachedPropertyWrapper() ||
(var->isImplicit() && !isa<ParamDecl>(var)))
return PropertyWrapperInitializerInfo();
auto wrapperInfo = var->getAttachedPropertyWrapperTypeInfo(0);
if (!wrapperInfo)
return PropertyWrapperInitializerInfo();
ASTContext &ctx = var->getASTContext();
auto dc = var->getDeclContext();
// Determine the type of the storage.
auto wrapperType = var->getPropertyWrapperBackingPropertyType();
if (!wrapperType || wrapperType->hasError())
return PropertyWrapperInitializerInfo();
Type storageType = dc->mapTypeIntoContext(wrapperType);
Expr *initializer = nullptr;
PropertyWrapperValuePlaceholderExpr *wrappedValue = nullptr;
auto createPBD = [&](VarDecl *singleVar) -> PatternBindingDecl * {
Pattern *pattern =
NamedPattern::createImplicit(ctx, singleVar, singleVar->getTypeInContext());
pattern = TypedPattern::createImplicit(ctx, pattern, singleVar->getTypeInContext());
PatternBindingDecl *pbd = PatternBindingDecl::createImplicit(
ctx, var->getCorrectStaticSpelling(), pattern, /*init*/nullptr,
dc, SourceLoc());
addMemberToContextIfNeeded(pbd, dc, var);
pbd->setStatic(var->isStatic());
return pbd;
};
// Take the initializer from the original property.
if (!isa<ParamDecl>(var)) {
auto parentPBD = var->getParentPatternBinding();
unsigned patternNumber = parentPBD->getPatternEntryIndexForVarDecl(var);
auto *backingVar = var->getPropertyWrapperBackingProperty();
auto *pbd = createPBD(backingVar);
// Force the default initializer to come into existence, if there is one,
// and the wrapper doesn't provide its own.
if (!parentPBD->isInitialized(patternNumber)
&& parentPBD->isDefaultInitializable(patternNumber)
&& !wrapperInfo.defaultInit) {
auto ty = parentPBD->getPattern(patternNumber)->getType();
if (auto defaultInit = TypeChecker::buildDefaultInitializer(ty)) {
typeCheckSynthesizedWrapperInitializer(var, defaultInit,
/*contextualize=*/false);
parentPBD->setInit(0, defaultInit);
parentPBD->setInitializerChecked(0);
}
}
if ((initializer = parentPBD->getInit(patternNumber))) {
assert(parentPBD->isInitializerChecked(0) &&
"Initializer should to be type-checked");
pbd->setInit(0, initializer);
pbd->setInitializerChecked(0);
wrappedValue = findWrappedValuePlaceholder(initializer);
} else {
if (!parentPBD->isInitialized(patternNumber) && wrapperInfo.defaultInit) {
// FIXME: Record this expression somewhere so that DI can perform the
// initialization itself.
Expr *defaultInit = nullptr;
// Only contextualize local wrapped property, the rest of wrapped
// property will be contextualized in visitPatternBindingDecl.
typeCheckSynthesizedWrapperInitializer(var, defaultInit, dc->isLocalContext());
pbd->setInit(0, defaultInit);
pbd->setInitializerChecked(0);
// If a static, global, or local wrapped property has a default
// initializer, this is the only initializer that will be used.
if (var->isStatic() || !dc->isTypeContext()) {
initializer = defaultInit;
}
} else if (var->hasObservers() && !dc->isTypeContext()) {
var->diagnose(diag::observingprop_requires_initializer);
}
if (var->getOpaqueResultTypeDecl()) {
var->diagnose(diag::opaque_type_var_no_underlying_type);
}
}
} else if (!var->hasExternalPropertyWrapper()) {
auto *param = cast<ParamDecl>(var);
auto *backingVar = var->getPropertyWrapperBackingProperty();
auto *pbd = createPBD(backingVar);
auto *paramRef = new (ctx) DeclRefExpr(var, DeclNameLoc(), /*implicit=*/true);
initializer = buildPropertyWrapperInitCall(
var, storageType, paramRef, PropertyWrapperInitKind::WrappedValue);
TypeChecker::typeCheckExpression(initializer, dc);
// Check initializer effects.
auto *initContext = new (ctx) PropertyWrapperInitializer(
dc, param, PropertyWrapperInitializer::Kind::ProjectedValue);
TypeChecker::checkInitializerEffects(initContext, initializer);
pbd->setInit(0, initializer);
pbd->setInitializerChecked(0);
}
// If there is a projection property (projectedValue) in the wrapper,
// synthesize a computed property for '$foo'.
Expr *projectedValueInit = nullptr;
if (auto *projection = var->getPropertyWrapperProjectionVar()) {
createPBD(projection);
if (var->hasExternalPropertyWrapper()) {
// Projected-value initialization is currently only supported for parameters.
auto *param = dyn_cast<ParamDecl>(var);
auto *placeholder = PropertyWrapperValuePlaceholderExpr::create(
ctx, var->getSourceRange(), projection->getTypeInContext(), /*projectedValue=*/nullptr);
projectedValueInit = buildPropertyWrapperInitCall(
var, storageType, placeholder, PropertyWrapperInitKind::ProjectedValue);
TypeChecker::typeCheckExpression(projectedValueInit, dc);
// Check initializer effects.
auto *initContext = new (ctx) PropertyWrapperInitializer(
dc, param, PropertyWrapperInitializer::Kind::ProjectedValue);
(void)projection->getInitializerIsolation();
TypeChecker::checkInitializerEffects(initContext, projectedValueInit);
}
}
// Form the initialization of the backing property from a value of the
// original property's type.
Expr *wrappedValueInit = nullptr;
if (wrappedValue) {
wrappedValueInit = initializer;
} else if (!initializer &&
var->allAttachedPropertyWrappersHaveWrappedValueInit() &&
!var->getName().hasDollarPrefix()) {
wrappedValueInit = PropertyWrapperValuePlaceholderExpr::create(
ctx, var->getSourceRange(), var->getTypeInContext(), /*wrappedValue=*/nullptr);
typeCheckSynthesizedWrapperInitializer(var, wrappedValueInit,
/*contextualize=*/true);
}
return PropertyWrapperInitializerInfo(wrappedValueInit, projectedValueInit);
}
/// Given a storage declaration in a protocol, set it up with the right
/// StorageImpl and add the right set of opaque accessors.
static void finishProtocolStorageImplInfo(AbstractStorageDecl *storage,
StorageImplInfo &info) {
if (auto *var = dyn_cast<VarDecl>(storage)) {
SourceLoc typeLoc;
if (auto *repr = var->getTypeReprOrParentPatternTypeRepr())
typeLoc = repr->getEndLoc();
if (info.hasStorage()) {
// Protocols cannot have stored properties.
if (var->isLet()) {
var->diagnose(diag::protocol_property_must_be_computed_var)
.fixItReplace(var->getParentPatternBinding()->getLoc(), "var")
.fixItInsertAfter(typeLoc, " { get }");
} else {
auto diag = var->diagnose(diag::protocol_property_must_be_computed);
auto braces = var->getBracesRange();
if (braces.isValid())
diag.fixItReplace(braces, "{ get <#set#> }");
else
diag.fixItInsertAfter(typeLoc, " { get <#set#> }");
}
}
}
auto protocol = cast<ProtocolDecl>(storage->getDeclContext());
if (protocol->isObjC()) {
info = StorageImplInfo::getComputed(info.supportsMutation());
} else {
info = StorageImplInfo::getOpaque(info.supportsMutation(),
storage->getOpaqueReadOwnership());
}
}
static void finishLazyVariableImplInfo(VarDecl *var,
StorageImplInfo &info) {
auto *attr = var->getAttrs().getAttribute<LazyAttr>();
// It cannot currently be used on let's since we don't have a mutability model
// that supports it.
if (var->isLet())
diagnoseAttrWithRemovalFixIt(var, attr, diag::lazy_not_on_let);
// lazy must have an initializer.
if (!var->getParentInitializer())
diagnoseAttrWithRemovalFixIt(var, attr, diag::lazy_requires_initializer);
bool invalid = false;
if (isa<ProtocolDecl>(var->getDeclContext())) {
diagnoseAttrWithRemovalFixIt(var, attr, diag::lazy_not_in_protocol);
invalid = true;
}
// Lazy properties must be written as stored properties in the source.
if (info.getReadImpl() != ReadImplKind::Stored &&
(info.getWriteImpl() != WriteImplKind::Stored &&
info.getWriteImpl() != WriteImplKind::StoredWithObservers)) {
diagnoseAttrWithRemovalFixIt(var, attr, diag::lazy_not_on_computed);
invalid = true;
}
// The pattern binding must only bind a single variable.
if (!var->getParentPatternBinding()->getSingleVar())
diagnoseAttrWithRemovalFixIt(var, attr, diag::lazy_requires_single_var);
if (!invalid)
info = StorageImplInfo::getMutableComputed();
}
static void finishPropertyWrapperImplInfo(VarDecl *var,
StorageImplInfo &info) {
auto parentSF = var->getDeclContext()->getParentSourceFile();
if (!parentSF)
return;
// Properties with wrappers must not declare a getter or setter.
if (!info.hasStorage() && parentSF->Kind != SourceFileKind::Interface) {
auto &ctx = parentSF->getASTContext();
for (auto attr : var->getAttrs().getAttributes<CustomAttr>())
ctx.Diags.diagnose(attr->getLocation(), diag::property_wrapper_computed);
return;
}
bool wrapperSetterIsUsable = false;
if (var->getParsedAccessor(AccessorKind::Set)) {
wrapperSetterIsUsable = true;
} else if (parentSF && parentSF->Kind != SourceFileKind::Interface
&& !var->isLet()) {
if (auto comp = var->getPropertyWrapperMutability()) {
wrapperSetterIsUsable =
comp->Setter != PropertyWrapperMutability::DoesntExist;
} else {
wrapperSetterIsUsable = true;
}
}
if (!wrapperSetterIsUsable) {
info = StorageImplInfo::getImmutableComputed();
return;
}
if (var->hasObservers() || var->getDeclContext()->isLocalContext()) {
info = StorageImplInfo::getMutableComputed();
} else {
info = StorageImplInfo(ReadImplKind::Get, WriteImplKind::Set,
ReadWriteImplKind::Modify);
}
}
static void finishNSManagedImplInfo(VarDecl *var,
StorageImplInfo &info) {
auto *attr = var->getAttrs().getAttribute<NSManagedAttr>();
if (var->isLet())
diagnoseAttrWithRemovalFixIt(var, attr, diag::attr_NSManaged_let_property);
SourceFile *parentFile = var->getDeclContext()->getParentSourceFile();
auto diagnoseNotStored = [&](unsigned kind) {
// Skip diagnosing @NSManaged declarations in module interfaces. They are
// properties that are stored, but have specially synthesized observers
// and we should allow them to have getters and setters in a module
// interface.
if (parentFile && parentFile->Kind == SourceFileKind::Interface)
return;
diagnoseAttrWithRemovalFixIt(var, attr, diag::attr_NSManaged_not_stored, kind);
};
// @NSManaged properties must be written as stored.
if (info.isSimpleStored()) {
// @NSManaged properties end up being computed; complain if there is
// an initializer.
if (var->getParentExecutableInitializer()) {
auto &Diags = var->getASTContext().Diags;
Diags.diagnose(attr->getLocation(), diag::attr_NSManaged_initial_value)
.highlight(var->getParentExecutableInitializer()->getSourceRange());
}
// Otherwise, ok.
info = StorageImplInfo::getMutableComputed();
} else if (info.getReadImpl() == ReadImplKind::Address ||
info.getWriteImpl() == WriteImplKind::MutableAddress) {
diagnoseNotStored(/*addressed*/ 2);
} else if (info.getWriteImpl() == WriteImplKind::StoredWithObservers ||
info.getWriteImpl() == WriteImplKind::InheritedWithObservers) {
diagnoseNotStored(/*observing*/ 1);
} else {
diagnoseNotStored(/*computed*/ 0);
}
}
static void finishStorageImplInfo(AbstractStorageDecl *storage,
StorageImplInfo &info) {
auto dc = storage->getDeclContext();
if (auto var = dyn_cast<VarDecl>(storage)) {
if (!info.hasStorage() && !var->hasInitAccessor()) {
if (auto *init = var->getParentExecutableInitializer()) {
auto &Diags = var->getASTContext().Diags;
Diags.diagnose(init->getLoc(), diag::getset_init)
.highlight(init->getSourceRange());
}
}
if (var->getAttrs().hasAttribute<LazyAttr>()) {
finishLazyVariableImplInfo(var, info);
} else if (var->getAttrs().hasAttribute<NSManagedAttr>()) {
finishNSManagedImplInfo(var, info);
} else if (var->hasAttachedPropertyWrapper()) {
finishPropertyWrapperImplInfo(var, info);
}
}
if (isa<ProtocolDecl>(dc))
finishProtocolStorageImplInfo(storage, info);
// If we have a stored property in an unsupported context, diagnose
// and change it to computed to avoid confusing SILGen.
// Note: Stored properties in protocols are diagnosed in
// finishProtocolStorageImplInfo().
if (info.hasStorage() && !storage->isStatic()) {
if (isa<EnumDecl>(dc)) {
storage->diagnose(diag::enum_stored_property);
info = StorageImplInfo::getMutableComputed();
} else if (auto ext = dyn_cast<ExtensionDecl>(dc)) {
// Extensions can dynamically replace a stored property.
if (storage->getAttrs().getAttribute<DynamicReplacementAttr>())
return;
// @_objcImplementation extensions on a non-category can declare stored
// properties; StoredPropertiesRequest knows to look for them there.
if (ext->isObjCImplementation() &&
ext->getCategoryNameForObjCImplementation() == Identifier())
return;
storage->diagnose(diag::extension_stored_property);
info = (info.supportsMutation()
? StorageImplInfo::getMutableComputed()
: StorageImplInfo::getImmutableComputed());
}
}
}
/// Gets the storage info of the provided storage decl if it has the
/// @_hasStorage attribute and it's not in SIL mode.
///
/// In this case, we say the decl is:
///
/// Read:
/// - Stored, always
/// Write:
/// - Stored, if the decl is a 'var'.
/// - StoredWithObservers, if the decl has a setter
/// - This indicates that the original decl had a 'didSet' and/or 'willSet'
/// - InheritedWithObservers, if the decl has a setter and is an override.
/// - Immutable, if the decl is a 'let' or it does not have a setter.
/// ReadWrite:
/// - Stored, if the decl has no accessors listed.
/// - Immutable, if the decl is a 'let' or it does not have a setter.
/// - MaterializeToTemporary, if the decl has a setter.
static StorageImplInfo classifyWithHasStorageAttr(VarDecl *var) {
WriteImplKind writeImpl;
ReadWriteImplKind readWriteImpl;
if (var->getParsedAccessor(AccessorKind::Get) &&
var->getParsedAccessor(AccessorKind::Set)) {
// If we see `@_hasStorage var x: T { get set }`, then our property has
// willSet/didSet observers.
writeImpl = var->getAttrs().hasAttribute<OverrideAttr>() ?
WriteImplKind::InheritedWithObservers :
WriteImplKind::StoredWithObservers;
readWriteImpl = ReadWriteImplKind::MaterializeToTemporary;
} else if (var->isLet()) {
writeImpl = WriteImplKind::Immutable;
readWriteImpl = ReadWriteImplKind::Immutable;
} else {
// Default to stored writes.
writeImpl = WriteImplKind::Stored;
readWriteImpl = ReadWriteImplKind::Stored;
}
// Always force Stored reads if @_hasStorage is present.
return StorageImplInfo(ReadImplKind::Stored, writeImpl, readWriteImpl);
}
bool HasStorageRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *storage) const {
// Parameters are always stored.
if (isa<ParamDecl>(storage))
return true;
// Only variables can be stored.
auto *var = dyn_cast<VarDecl>(storage);
if (!var)
return false;
// @_hasStorage implies that it... has storage.
if (var->getAttrs().hasAttribute<HasStorageAttr>())
return true;
// Protocol requirements never have storage.
if (isa<ProtocolDecl>(storage->getDeclContext()))
return false;
// lazy declarations do not have storage.
if (storage->getAttrs().hasAttribute<LazyAttr>())
return false;
// @NSManaged attributes don't have storage
if (storage->getAttrs().hasAttribute<NSManagedAttr>())
return false;
// Any accessors that read or write imply that there is no storage.
if (storage->getParsedAccessor(AccessorKind::Get) ||
storage->getParsedAccessor(AccessorKind::Read) ||
storage->getParsedAccessor(AccessorKind::Address) ||
storage->getParsedAccessor(AccessorKind::Set) ||
storage->getParsedAccessor(AccessorKind::Modify) ||
storage->getParsedAccessor(AccessorKind::MutableAddress) ||
storage->getParsedAccessor(AccessorKind::Init))
return false;
// willSet or didSet in an overriding property imply that there is no storage.
if ((storage->getParsedAccessor(AccessorKind::WillSet) ||
storage->getParsedAccessor(AccessorKind::DidSet)) &&
storage->getAttrs().hasAttribute<OverrideAttr>())
return false;
// The presence of a property wrapper implies that there is no storage.
if (var->hasAttachedPropertyWrapper())
return false;
// Look for any accessor macros that might make this property computed.
bool hasStorage = true;
namelookup::forEachPotentialAttachedMacro(
var, MacroRole::Accessor,
[&](MacroDecl *macro, const MacroRoleAttr *attr) {
// Will this macro introduce observers?
bool foundObserver = accessorMacroOnlyIntroducesObservers(macro, attr);
// If it's not (just) introducing observers, it's making the property
// computed.
if (!foundObserver)
hasStorage = false;
// If it will introduce observers, and there is an "override",
// the property doesn't have storage.
if (foundObserver && storage->getAttrs().hasAttribute<OverrideAttr>())
hasStorage = false;
});
return hasStorage;
}
std::optional<bool> HasStorageRequest::getCachedResult() const {
AbstractStorageDecl *decl = std::get<0>(getStorage());
if (decl->LazySemanticInfo.HasStorageComputed)
return static_cast<bool>(decl->LazySemanticInfo.HasStorage);
return std::nullopt;
}
void HasStorageRequest::cacheResult(bool hasStorage) const {
AbstractStorageDecl *decl = std::get<0>(getStorage());
decl->LazySemanticInfo.HasStorageComputed = true;
decl->LazySemanticInfo.HasStorage = hasStorage;
// Add an attribute for printing, but only to VarDecls.
if (isa<ParamDecl>(decl))
return;
if (auto varDecl = dyn_cast<VarDecl>(decl)) {
if (hasStorage && !varDecl->getAttrs().hasAttribute<HasStorageAttr>())
varDecl->getAttrs().add(new (varDecl->getASTContext())
HasStorageAttr(/*isImplicit=*/true));
}
}
StorageImplInfo
StorageImplInfoRequest::evaluate(Evaluator &evaluator,
AbstractStorageDecl *storage) const {
if (auto *param = dyn_cast<ParamDecl>(storage)) {
return StorageImplInfo::getSimpleStored(
param->isImmutableInFunctionBody()
? StorageIsNotMutable
: StorageIsMutable);
}
if (auto *var = dyn_cast<VarDecl>(storage)) {
// Allow the @_hasStorage attribute to override all the accessors we parsed
// when making the final classification.
if (var->getParsedAttrs().hasAttribute<HasStorageAttr>()) {
// The SIL rules for @_hasStorage are slightly different from the non-SIL
// rules. In SIL mode, @_hasStorage marks that the type is simply stored,
// and the only thing that determines mutability is the existence of the
// setter.
//
// FIXME: SIL should not be special cased here. The behavior should be
// consistent between SIL and non-SIL.
// The strategy here should be to keep track of all opaque accessors
// along with enough information to access the storage trivially
// if allowed. This could be a representational change to
// StorageImplInfo such that it keeps a bitset of listed accessors
// and dynamically determines the access strategy from that.
auto *SF = storage->getDeclContext()->getParentSourceFile();
if (SF && SF->Kind == SourceFileKind::SIL)
return StorageImplInfo::getSimpleStored(
var->getParsedAccessor(AccessorKind::Set)
? StorageIsMutable
: StorageIsNotMutable);
return classifyWithHasStorageAttr(var);
}
}
// Handle protocol requirements specially.
if (isa<ProtocolDecl>(storage->getDeclContext())) {
ReadImplKind readImpl = ReadImplKind::Stored;
// By default, treat the requirement as not having a setter.
WriteImplKind writeImpl = WriteImplKind::Immutable;
ReadWriteImplKind readWriteImpl = ReadWriteImplKind::Immutable;
if (storage->getParsedAccessor(AccessorKind::Set)) {
readImpl = ReadImplKind::Get;
writeImpl = WriteImplKind::Set;
readWriteImpl = ReadWriteImplKind::MaterializeToTemporary;
} else if (storage->getParsedAccessor(AccessorKind::Get)) {
readImpl = ReadImplKind::Get;
}
StorageImplInfo info(readImpl, writeImpl, readWriteImpl);
finishStorageImplInfo(storage, info);
return info;
}
// Expand any attached accessor macros.
(void)evaluateOrDefault(evaluator, ExpandAccessorMacros{storage}, { });
bool hasWillSet = storage->getParsedAccessor(AccessorKind::WillSet);
bool hasDidSet = storage->getParsedAccessor(AccessorKind::DidSet);
if ((hasWillSet || hasDidSet) && !isa<SubscriptDecl>(storage)) {
// Observers conflict with non-observers.
AccessorDecl *firstNonObserver = nullptr;
for (auto accessor : storage->getAllAccessors()) {
if (!accessor->isImplicit() && !accessor->isObservingAccessor()) {
firstNonObserver = accessor;
break;
}
}
if (firstNonObserver) {
if (auto willSet = storage->getParsedAccessor(AccessorKind::WillSet)) {
willSet->diagnose(
diag::observing_accessor_conflicts_with_accessor, 0,
getAccessorNameForDiagnostic(
firstNonObserver->getAccessorKind(), /*article=*/ true));
willSet->setInvalid();
hasWillSet = false;
}
if (auto didSet = storage->getParsedAccessor(AccessorKind::DidSet)) {
didSet->diagnose(
diag::observing_accessor_conflicts_with_accessor, 1,
getAccessorNameForDiagnostic(
firstNonObserver->getAccessorKind(), /*article=*/ true));
didSet->setInvalid();
hasDidSet = false;
}
}
}
bool hasSetter = storage->getParsedAccessor(AccessorKind::Set);
bool hasModify = storage->getParsedAccessor(AccessorKind::Modify);
bool hasMutableAddress = storage->getParsedAccessor(AccessorKind::MutableAddress);
bool hasInit = storage->getParsedAccessor(AccessorKind::Init);
auto *DC = storage->getDeclContext();
// 'get', 'read', and a non-mutable addressor are all exclusive.
ReadImplKind readImpl;
if (storage->getParsedAccessor(AccessorKind::Get)) {
readImpl = ReadImplKind::Get;
} else if (storage->getParsedAccessor(AccessorKind::Read)) {
readImpl = ReadImplKind::Read;
} else if (storage->getParsedAccessor(AccessorKind::Address)) {
readImpl = ReadImplKind::Address;
// If there's a writing accessor of any sort, there must also be a
// reading accessor.
} else if (hasInit || hasSetter || hasModify || hasMutableAddress) {
readImpl = ReadImplKind::Get;
// Subscripts always have to have some sort of accessor; they can't be
// purely stored.
} else if (isa<SubscriptDecl>(storage)) {
readImpl = ReadImplKind::Get;
// Check if we have observers.
} else if (hasWillSet || hasDidSet) {
if (storage->getAttrs().hasAttribute<OverrideAttr>() &&
storage->getDeclContext()->isTypeContext()) {
readImpl = ReadImplKind::Inherited;
} else {
readImpl = ReadImplKind::Stored;
}
// Extensions and enums can't have stored properties. If there are braces,
// assume this is an incomplete computed property. This avoids an
// "extensions|enums must not contain stored properties" error later on.
} else if ((isa<ExtensionDecl>(DC) || isa<EnumDecl>(DC)) &&
storage->getBracesRange().isValid()) {
readImpl = ReadImplKind::Get;
// Otherwise, it's stored.
} else {
readImpl = ReadImplKind::Stored;
}
// Prefer using 'set' and 'modify' over a mutable addressor.
WriteImplKind writeImpl;
ReadWriteImplKind readWriteImpl;
if (hasSetter) {
writeImpl = WriteImplKind::Set;
if (hasModify) {
readWriteImpl = ReadWriteImplKind::Modify;
} else {
readWriteImpl = ReadWriteImplKind::MaterializeToTemporary;
}
} else if (hasModify) {
writeImpl = WriteImplKind::Modify;
readWriteImpl = ReadWriteImplKind::Modify;
} else if (hasMutableAddress) {
writeImpl = WriteImplKind::MutableAddress;
readWriteImpl = ReadWriteImplKind::MutableAddress;
// Check if we have observers.
} else if (readImpl == ReadImplKind::Inherited) {
writeImpl = WriteImplKind::InheritedWithObservers;
if (hasWillSet)
readWriteImpl = ReadWriteImplKind::MaterializeToTemporary;
else
readWriteImpl = ReadWriteImplKind::InheritedWithDidSet;
// Otherwise, it's stored.
} else if (readImpl == ReadImplKind::Stored &&
!cast<VarDecl>(storage)->isLet()) {
if (hasWillSet || hasDidSet) {
writeImpl = WriteImplKind::StoredWithObservers;
if (hasWillSet)
readWriteImpl = ReadWriteImplKind::MaterializeToTemporary;
else
readWriteImpl = ReadWriteImplKind::StoredWithDidSet;
} else {
writeImpl = WriteImplKind::Stored;
readWriteImpl = ReadWriteImplKind::Stored;
}
// Otherwise, it's immutable.
} else {
writeImpl = WriteImplKind::Immutable;
readWriteImpl = ReadWriteImplKind::Immutable;
}
StorageImplInfo info(readImpl, writeImpl, readWriteImpl);
finishStorageImplInfo(storage, info);
assert(info.hasStorage() == storage->hasStorage() ||
storage->getASTContext().Diags.hadAnyError());
return info;
}
bool SimpleDidSetRequest::evaluate(Evaluator &evaluator,
AccessorDecl *decl) const {
class OldValueFinder : public ASTWalker {
const ParamDecl *OldValueParam;
bool foundOldValueRef = false;
public:
OldValueFinder(const ParamDecl *param) : OldValueParam(param) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
virtual PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (!E)
return Action::Continue(E);
if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
if (auto decl = DRE->getDecl()) {
if (decl == OldValueParam) {
foundOldValueRef = true;
return Action::Stop();
}
}
}
return Action::Continue(E);
}
bool didFindOldValueRef() { return foundOldValueRef; }
};
// If this is not a didSet accessor, bail out.
if (decl->getAccessorKind() != AccessorKind::DidSet) {
return false;
}
// Always assume non-simple 'didSet' in code completion mode.
if (decl->getASTContext().SourceMgr.hasIDEInspectionTargetBuffer())
return false;
// didSet must have a single parameter.
if (decl->getParameters()->size() != 1) {
return false;
}
auto param = decl->getParameters()->get(0);
// If this parameter is not implicit, then it means it has been explicitly
// provided by the user (i.e. 'didSet(oldValue)'). This means we cannot
// consider this a "simple" didSet because we have to fetch the oldValue
// regardless of whether it's referenced in the body or not.
if (!param->isImplicit()) {
return false;
}
// If we find a reference to the implicit 'oldValue' parameter, then it is
// not a "simple" didSet because we need to fetch it.
auto walker = OldValueFinder(param);
if (auto *body = decl->getTypecheckedBody())
body->walk(walker);
auto hasOldValueRef = walker.didFindOldValueRef();
if (!hasOldValueRef) {
// If the body does not refer to implicit 'oldValue', it means we can
// consider this as a "simple" didSet. Let's also erase the implicit
// oldValue as it is never used.
auto &ctx = decl->getASTContext();
decl->setParameters(ParameterList::createEmpty(ctx));
return true;
}
return false;
}
|