1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776
|
//===--- MiscDiagnostics.cpp - AST-Level Diagnostics ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 AST-level diagnostics.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckInvertible.h"
#include "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/SaveAndRestore.h"
#define DEBUG_TYPE "Sema"
using namespace swift;
using namespace constraints;
/// Return true if this expression is an implicit promotion from T to T?.
static Expr *isImplicitPromotionToOptional(Expr *E) {
if (E->isImplicit())
if (auto IIOE = dyn_cast<InjectIntoOptionalExpr>(
E->getSemanticsProvidingExpr()))
return IIOE->getSubExpr();
return nullptr;
}
ASTWalker::PreWalkAction BaseDiagnosticWalker::walkToDeclPre(Decl *D) {
return Action::VisitNodeIf(isa<ClosureExpr>(D->getDeclContext()) &&
shouldWalkIntoDeclInClosureContext(D));
}
bool BaseDiagnosticWalker::shouldWalkIntoDeclInClosureContext(Decl *D) {
auto *closure = dyn_cast<ClosureExpr>(D->getDeclContext());
assert(closure);
if (closure->isSeparatelyTypeChecked())
return false;
// Let's not walk into declarations contained in a multi-statement
// closure because they'd be handled via `typeCheckDecl` that runs
// syntactic diagnostics.
if (!closure->hasSingleExpressionBody()) {
// Since pattern bindings get their types through solution application,
// `typeCheckDecl` doesn't touch initializers (because they are already
// fully type-checked), so pattern bindings have to be allowed to be
// walked to diagnose syntactic issues.
return isa<PatternBindingDecl>(D);
}
return true;
}
/// Diagnose syntactic restrictions of expressions.
///
/// - Module values may only occur as part of qualification.
/// - Metatype names cannot generally be used as values: they need a "T.self"
/// qualification unless used in narrow case (e.g. T() for construction).
/// - '_' may only exist on the LHS of an assignment expression.
/// - warn_unqualified_access values must not be accessed except via qualified
/// lookup.
/// - Partial application of some decls isn't allowed due to implementation
/// limitations.
/// - "&" (aka InOutExpressions) may only exist directly in function call
/// argument lists.
/// - 'self.init' and 'super.init' cannot be wrapped in a larger expression
/// or statement.
/// - Warn about promotions to optional in specific syntactic forms.
/// - Error about collection literals that default to Any collections in
/// invalid positions.
/// - Marker protocols cannot occur as the type of an as? or is expression.
/// - KeyPath expressions cannot refer to effectful properties / subscripts
/// - SingleValueStmtExprs may only appear in certain places and has
/// restrictions on the control flow allowed.
/// - Move expressions must have a declref expr subvalue.
///
static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
bool isExprStmt) {
class DiagnoseWalker : public BaseDiagnosticWalker {
SmallPtrSet<Expr*, 4> AlreadyDiagnosedMetatypes;
SmallPtrSet<DeclRefExpr*, 4> AlreadyDiagnosedBitCasts;
bool IsExprStmt;
ASTContext &Ctx;
const DeclContext *DC;
public:
DiagnoseWalker(const DeclContext *DC, bool isExprStmt)
: IsExprStmt(isExprStmt), Ctx(DC->getASTContext()), DC(DC) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *P) override {
return Action::SkipNode(P);
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
return Action::Continue();
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
// See through implicit conversions of the expression. We want to be able
// to associate the parent of this expression with the ultimate callee.
auto Base = E;
while (auto Conv = dyn_cast<ImplicitConversionExpr>(Base))
Base = Conv->getSubExpr();
if (auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
// Verify metatype uses.
if (isa<TypeDecl>(DRE->getDecl())) {
if (isa<ModuleDecl>(DRE->getDecl()))
checkUseOfModule(DRE);
else
checkUseOfMetaTypeName(Base);
}
// Verify warn_unqualified_access uses.
checkUnqualifiedAccessUse(DRE);
// Verify that special decls are eliminated.
checkForDeclWithSpecialTypeCheckingSemantics(DRE);
// Verify that `unsafeBitCast` isn't misused.
checkForSuspiciousBitCasts(DRE, nullptr);
}
if (auto *MRE = dyn_cast<MemberRefExpr>(Base)) {
if (isa<TypeDecl>(MRE->getMember().getDecl()))
checkUseOfMetaTypeName(Base);
}
if (isa<TypeExpr>(Base))
checkUseOfMetaTypeName(Base);
if (auto *KPE = dyn_cast<KeyPathExpr>(E)) {
// raise an error if this KeyPath contains an effectful member.
checkForEffectfulKeyPath(KPE);
}
// Check function calls, looking through implicit conversions on the
// function and inspecting the arguments directly.
if (auto *Call = dyn_cast<ApplyExpr>(E)) {
// Warn about surprising implicit optional promotions.
checkOptionalPromotions(Call);
// Check the callee, looking through implicit conversions.
auto base = Call->getFn();
unsigned uncurryLevel = 0;
while (auto conv = dyn_cast<ImplicitConversionExpr>(base))
base = conv->getSubExpr();
const auto findDynamicMemberRefExpr =
[](Expr *e) -> DynamicMemberRefExpr* {
if (auto open = dyn_cast<OpenExistentialExpr>(e)) {
return dyn_cast<DynamicMemberRefExpr>(open->getSubExpr());
}
return nullptr;
};
if (auto force = dyn_cast<ForceValueExpr>(base)) {
if (auto ref = findDynamicMemberRefExpr(force->getSubExpr()))
base = ref;
} else if (auto bind = dyn_cast<BindOptionalExpr>(base)) {
if (auto ref = findDynamicMemberRefExpr(bind->getSubExpr()))
base = ref;
}
while (auto ignoredBase = dyn_cast<DotSyntaxBaseIgnoredExpr>(base))
base = ignoredBase->getRHS();
ConcreteDeclRef callee;
if (auto *calleeDRE = dyn_cast<DeclRefExpr>(base)) {
checkForSuspiciousBitCasts(calleeDRE, Call);
callee = calleeDRE->getDeclRef();
// Otherwise, try to drill down through member calls for the purposes
// of argument-matching code below.
} else if (auto selfApply = dyn_cast<SelfApplyExpr>(base)) {
++uncurryLevel;
base = selfApply->getSemanticFn();
if (auto calleeDRE = dyn_cast<DeclRefExpr>(base))
callee = calleeDRE->getDeclRef();
// Otherwise, check for a dynamic member.
} else if (auto dynamicMRE = dyn_cast<DynamicMemberRefExpr>(base)) {
++uncurryLevel;
callee = dynamicMRE->getMember();
}
if (callee) {
auto *args = Call->getArgs();
for (auto idx : indices(*args)) {
auto *arg = args->getExpr(idx);
checkMagicIdentifierMismatch(callee, uncurryLevel, idx, arg);
// InOutExprs can be wrapped in some implicit casts.
Expr *unwrapped = arg;
if (auto *IIO = dyn_cast<InjectIntoOptionalExpr>(arg))
unwrapped = IIO->getSubExpr();
if (isa<InOutToPointerExpr>(unwrapped) ||
isa<ArrayToPointerExpr>(unwrapped) ||
isa<ErasureExpr>(unwrapped)) {
auto operand =
cast<ImplicitConversionExpr>(unwrapped)->getSubExpr();
if (auto *IOE = dyn_cast<InOutExpr>(operand))
operand = IOE->getSubExpr();
// Also do some additional work based on how the function uses
// the argument.
checkConvertedPointerArgument(callee, uncurryLevel, idx,
unwrapped, operand);
}
}
}
}
// If we have an assignment expression, scout ahead for acceptable _'s.
if (auto *AE = dyn_cast<AssignExpr>(E)) {
auto destExpr = AE->getDest();
// If the user is assigning the result of a function that returns
// Void to _ then warn, because that is redundant.
if (auto DAE = dyn_cast<DiscardAssignmentExpr>(destExpr)) {
if (auto CE = dyn_cast<CallExpr>(AE->getSrc())) {
if (getAsDecl<FuncDecl>(
CE->getCalledValue(/*skipFunctionConversions=*/true)) &&
CE->getType()->isVoid()) {
Ctx.Diags
.diagnose(DAE->getLoc(),
diag::discard_expr_void_result_redundant)
.fixItRemoveChars(DAE->getStartLoc(),
AE->getSrc()->getStartLoc());
}
}
}
}
// Diagnose 'self.init' or 'super.init' nested in another expression
// or closure.
if (auto *rebindSelfExpr = dyn_cast<RebindSelfInConstructorExpr>(E)) {
if (!Parent.isNull() || !IsExprStmt || DC->getParent()->isLocalContext()) {
bool isChainToSuper;
(void)rebindSelfExpr->getCalledConstructor(isChainToSuper);
Ctx.Diags.diagnose(E->getLoc(), diag::init_delegation_nested,
isChainToSuper, !IsExprStmt);
}
}
// Diagnose single-element tuple expressions.
if (auto *tupleExpr = dyn_cast<TupleExpr>(E)) {
if (tupleExpr->getNumElements() == 1 &&
!isa<PackExpansionExpr>(tupleExpr->getElement(0))) {
Ctx.Diags.diagnose(tupleExpr->getElementNameLoc(0),
diag::tuple_single_element)
.fixItRemoveChars(tupleExpr->getElementNameLoc(0),
tupleExpr->getElement(0)->getStartLoc());
}
}
auto diagnoseDuplicateLabels = [&](SourceLoc loc,
ArrayRef<Identifier> labels) {
llvm::SmallDenseSet<Identifier> names;
names.reserve(labels.size());
for (auto name : labels) {
if (name.empty())
continue;
auto inserted = names.insert(name).second;
if (!inserted) {
Ctx.Diags.diagnose(loc, diag::tuple_duplicate_label);
return;
}
}
};
// FIXME: Duplicate labels on enum payloads should be diagnosed
// when declared, not when called.
if (auto *CE = dyn_cast_or_null<CallExpr>(E)) {
auto calledValue = CE->getCalledValue(/*skipFunctionConversions=*/true);
if (calledValue && isa<EnumElementDecl>(calledValue)) {
auto *args = CE->getArgs();
SmallVector<Identifier, 4> scratch;
diagnoseDuplicateLabels(args->getLoc(),
args->getArgumentLabels(scratch));
}
}
if (auto *tupleExpr = dyn_cast<TupleExpr>(E)) {
// Diagnose tuple expressions with duplicate element label.
diagnoseDuplicateLabels(tupleExpr->getLoc(),
tupleExpr->getElementNames());
// Diagnose attempts to form a tuple with any noncopyable elements.
if (E->getType()->isNoncopyable()
&& !Ctx.LangOpts.hasFeature(Feature::MoveOnlyTuples)) {
auto noncopyableTy = E->getType();
assert(noncopyableTy->is<TupleType>() && "will use poor wording");
Ctx.Diags.diagnose(E->getLoc(),
diag::tuple_containing_move_only_not_supported,
noncopyableTy);
}
}
// Specially diagnose some checked casts that are illegal.
if (auto cast = dyn_cast<CheckedCastExpr>(E)) {
checkCheckedCastExpr(cast);
}
// Diagnose move expression uses where the sub expression is not a declref
// expr.
if (auto *consumeExpr = dyn_cast<ConsumeExpr>(E)) {
checkConsumeExpr(consumeExpr);
}
// Diagnose copy expression uses where the sub expression is not a declref
// expr.
if (auto *copyExpr = dyn_cast<CopyExpr>(E)) {
checkCopyExpr(copyExpr);
}
// Diagnose move expression uses where the sub expression is not a declref expr
if (auto *borrowExpr = dyn_cast<BorrowExpr>(E)) {
checkBorrowExpr(borrowExpr);
}
return Action::Continue(E);
}
/// Visit each component of the keypath and emit a diagnostic if they
/// refer to a member that has effects.
void checkForEffectfulKeyPath(KeyPathExpr *keyPath) {
for (const auto &component : keyPath->getComponents()) {
if (component.hasDeclRef()) {
auto decl = component.getDeclRef().getDecl();
if (auto asd = dyn_cast<AbstractStorageDecl>(decl)) {
if (auto getter = asd->getEffectfulGetAccessor()) {
Ctx.Diags.diagnose(component.getLoc(),
diag::effectful_keypath_component,
asd->getDescriptiveKind());
Ctx.Diags.diagnose(asd->getLoc(), diag::kind_declared_here,
asd->getDescriptiveKind());
}
}
}
}
}
void checkCheckedCastExpr(CheckedCastExpr *cast) {
Type castType = cast->getCastType();
if (!castType)
return;
if (castType->isNoncopyable()) {
// can't cast anything to move-only; there should be no valid ones.
Ctx.Diags.diagnose(cast->getLoc(), diag::noncopyable_cast);
return;
}
// no support for runtime casts from move-only types.
// as of now there is no type it could be cast to except itself, so
// there's no reason for it to happen at runtime.
if (auto fromType = cast->getSubExpr()->getType()) {
if (fromType->isNoncopyable()) {
// can't cast move-only to anything.
Ctx.Diags.diagnose(cast->getLoc(), diag::noncopyable_cast);
return;
}
}
// now, look for conditional casts to marker protocols.
if (!isa<ConditionalCheckedCastExpr>(cast) && !isa<IsExpr>(cast))
return;
if(!castType->isExistentialType())
return;
auto layout = castType->getExistentialLayout();
for (auto proto : layout.getProtocols()) {
if (proto->isMarkerProtocol() && !proto->getInvertibleProtocolKind()) {
// can't conditionally cast to a marker protocol
Ctx.Diags.diagnose(cast->getLoc(), diag::marker_protocol_cast,
proto->getName());
}
}
}
void checkConsumeExpr(ConsumeExpr *consumeExpr) {
auto diags = findSyntacticErrorForConsume(DC->getParentModule(),
consumeExpr->getLoc(),
consumeExpr->getSubExpr());
for (auto &diag : diags)
diag.emit(Ctx);
// As of now, SE-366 is not correctly implemented (rdar://102780553),
// so warn about certain consume's being no-ops today that will no longer
// be a no-op in the future once we fix this.
if (auto ty = consumeExpr->getType()) {
bool shouldWarn = true;
// Look through any load.
auto *expr = consumeExpr->getSubExpr();
if (auto *load = dyn_cast<LoadExpr>(expr))
expr = load->getSubExpr();
// Don't warn if explicit ownership was provided on a parameter.
// Those seem to be checked just fine in SIL.
if (auto *declRef = dyn_cast<DeclRefExpr>(expr)) {
if (auto *decl = declRef->getDecl()) {
if (auto *paramDecl = dyn_cast<ParamDecl>(decl)) {
switch (paramDecl->getSpecifier()) {
case ParamSpecifier::InOut:
case ParamSpecifier::Borrowing:
case ParamSpecifier::Consuming:
case ParamSpecifier::ImplicitlyCopyableConsuming:
shouldWarn = false;
break;
case ParamSpecifier::Default:
case ParamSpecifier::LegacyShared:
case ParamSpecifier::LegacyOwned:
break; // warn
}
}
}
}
// Only warn about obviously concrete BitwiseCopyable types, since we
// know those won't get checked for consumption.
if (diags.empty() &&
shouldWarn &&
!ty->hasError() &&
!ty->hasTypeParameter() &&
!ty->hasUnboundGenericType() &&
!ty->hasArchetype()) {
auto bitCopy = Ctx.getProtocol(KnownProtocolKind::BitwiseCopyable);
if (DC->getParentModule()->checkConformance(ty, bitCopy)) {
Ctx.Diags.diagnose(consumeExpr->getLoc(),
diag::consume_of_bitwisecopyable_noop, ty)
.fixItRemoveChars(consumeExpr->getStartLoc(),
consumeExpr->getSubExpr()->getStartLoc());
}
}
}
}
void checkCopyExpr(CopyExpr *copyExpr) {
// Do not allow for copy_expr to be used with pure move only types. We
// /do/ allow it to be used with no implicit copy types though.
if (copyExpr->getType()->isNoncopyable()) {
Ctx.Diags.diagnose(
copyExpr->getLoc(),
diag::copy_expression_cannot_be_used_with_noncopyable_types);
}
// We only allow for copy_expr to be applied directly to lvalues. We do
// not allow currently for it to be applied to fields.
auto *subExpr = copyExpr->getSubExpr();
if (auto *li = dyn_cast<LoadExpr>(subExpr))
subExpr = li->getSubExpr();
if (!isa<DeclRefExpr>(subExpr)) {
Ctx.Diags.diagnose(copyExpr->getLoc(),
diag::copy_expression_not_passed_lvalue);
}
}
void checkBorrowExpr(BorrowExpr *borrowExpr) {
// Allow for a chain of member_ref exprs that end in a decl_ref expr.
auto *subExpr = borrowExpr->getSubExpr();
while (auto *memberRef = dyn_cast<MemberRefExpr>(subExpr))
subExpr = memberRef->getBase();
if (!isa<DeclRefExpr>(subExpr)) {
Ctx.Diags.diagnose(borrowExpr->getLoc(),
diag::borrow_expression_not_passed_lvalue);
}
}
static Expr *lookThroughArgument(Expr *arg) {
while (1) {
if (auto conv = dyn_cast<ImplicitConversionExpr>(arg))
arg = conv->getSubExpr();
else if (auto *PE = dyn_cast<ParenExpr>(arg))
arg = PE->getSubExpr();
else
break;
}
return arg;
}
void checkConvertedPointerArgument(ConcreteDeclRef callee,
unsigned uncurryLevel,
unsigned argIndex,
Expr *pointerExpr,
Expr *storage) {
if (!isPointerIdentityArgument(callee, uncurryLevel, argIndex))
return;
// Flag that the argument is non-accessing.
if (auto inout = dyn_cast<InOutToPointerExpr>(pointerExpr)) {
inout->setNonAccessing(true);
} else if (auto array = dyn_cast<ArrayToPointerExpr>(pointerExpr)) {
array->setNonAccessing(true);
}
// TODO: warn if taking the address of 'storage' will definitely
// yield a temporary address.
}
/// Is the given call argument, known to be of pointer type, just used
/// for its pointer identity?
bool isPointerIdentityArgument(ConcreteDeclRef ref, unsigned uncurryLevel,
unsigned argIndex) {
// FIXME: derive this from an attribute instead of hacking it based
// on the target name!
auto decl = ref.getDecl();
// Assume that == and != are non-accessing uses.
if (decl->isOperator()) {
auto op = decl->getBaseName();
if (op == "==" || op == "!=")
return true;
return false;
}
// NSObject.addObserver(_:forKeyPath:options:context:)
if (uncurryLevel == 1 && argIndex == 3) {
return decl->getName().isCompoundName("addObserver",
{ "", "forKeyPath",
"options", "context" });
}
// NSObject.removeObserver(_:forKeyPath:context:)
if (uncurryLevel == 1 && argIndex == 2) {
return decl->getName().isCompoundName("removeObserver",
{ "", "forKeyPath", "context" });
}
return false;
}
/// We have a collection literal with a defaulted type, e.g. of [Any]. Emit
/// an error if it was inferred to this type in an invalid context, which is
/// one in which the parent expression is not itself a collection literal.
void checkTypeDefaultedCollectionExpr(CollectionExpr *c) {
// If the parent is a non-expression, or is not itself a literal, then
// produce an error with a fixit to add the type as an explicit
// annotation.
if (c->getNumElements() == 0)
Ctx.Diags.diagnose(c->getLoc(), diag::collection_literal_empty)
.highlight(c->getSourceRange());
else {
assert(c->getType()->hasTypeRepr() &&
"a defaulted type should always be printable");
Ctx.Diags
.diagnose(c->getLoc(), diag::collection_literal_heterogeneous,
c->getType())
.highlight(c->getSourceRange())
.fixItInsertAfter(c->getEndLoc(),
" as " + c->getType()->getString());
}
}
void checkMagicIdentifierMismatch(ConcreteDeclRef callee,
unsigned uncurryLevel,
unsigned argIndex,
Expr *arg) {
// We only care about args in the arg list.
if (uncurryLevel != (callee.getDecl()->hasCurriedSelf() ? 1 : 0))
return;
// Get underlying params for both callee and caller, if declared.
auto *calleeParam = getParameterAt(callee, argIndex);
auto *callerParam = dyn_cast_or_null<ParamDecl>(
arg->getReferencedDecl(/*stopAtParenExpr=*/true).getDecl()
);
// (Otherwise, we don't need to do anything.)
if (!calleeParam || !callerParam)
return;
auto calleeDefaultArg = getMagicIdentifierDefaultArgKind(calleeParam);
auto callerDefaultArg = getMagicIdentifierDefaultArgKind(callerParam);
// If one of the parameters doesn't have a default arg, or they're both
// compatible, everything's fine.
if (!calleeDefaultArg || !callerDefaultArg ||
areMagicIdentifiersCompatible(*calleeDefaultArg, *callerDefaultArg))
return;
StringRef calleeDefaultArgString =
MagicIdentifierLiteralExpr::getKindString(*calleeDefaultArg);
StringRef callerDefaultArgString =
MagicIdentifierLiteralExpr::getKindString(*callerDefaultArg);
// Emit main warning
Ctx.Diags.diagnose(arg->getLoc(), diag::default_magic_identifier_mismatch,
callerParam->getName(), callerDefaultArgString,
calleeParam->getName(), calleeDefaultArgString);
// Add "change caller default arg" fixit
SourceLoc callerDefaultArgLoc =
callerParam->getStructuralDefaultExpr()->getLoc();
Ctx.Diags.diagnose(callerDefaultArgLoc,
diag::change_caller_default_to_match_callee,
callerParam->getName(), calleeDefaultArgString)
.fixItReplace(callerDefaultArgLoc, calleeDefaultArgString);
// Add "silence with parens" fixit
Ctx.Diags.diagnose(arg->getLoc(),
diag::silence_default_magic_identifier_mismatch)
.fixItInsert(arg->getStartLoc(), "(")
.fixItInsertAfter(arg->getEndLoc(), ")");
// Point to callee parameter
Ctx.Diags.diagnose(calleeParam, diag::decl_declared_here, calleeParam);
}
std::optional<MagicIdentifierLiteralExpr::Kind>
getMagicIdentifierDefaultArgKind(const ParamDecl *param) {
switch (param->getDefaultArgumentKind()) {
#define MAGIC_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \
case DefaultArgumentKind::NAME: \
return MagicIdentifierLiteralExpr::Kind::NAME;
#include "swift/AST/MagicIdentifierKinds.def"
case DefaultArgumentKind::None:
case DefaultArgumentKind::Normal:
case DefaultArgumentKind::Inherited:
case DefaultArgumentKind::NilLiteral:
case DefaultArgumentKind::EmptyArray:
case DefaultArgumentKind::EmptyDictionary:
case DefaultArgumentKind::StoredProperty:
case DefaultArgumentKind::ExpressionMacro:
return std::nullopt;
}
llvm_unreachable("Unhandled DefaultArgumentKind in "
"getMagicIdentifierDefaultArgKind");
}
static bool
areMagicIdentifiersCompatible(MagicIdentifierLiteralExpr::Kind a,
MagicIdentifierLiteralExpr::Kind b) {
if (a == b)
return true;
// The rest of this handles special compatibility rules between the
// `*SpelledAsFile` cases and various other File-related cases.
//
// The way we're going to do this is a bit magical. We will arrange the
// cases in MagicIdentifierLiteralExpr::Kind so that they sort in
// this order:
//
// #fileID < Swift 6 #file < #filePath < Swift 5 #file < others
//
// Before we continue, let's verify that this holds.
using Kind = MagicIdentifierLiteralExpr::Kind;
static_assert(Kind::FileID < Kind::FileIDSpelledAsFile,
"#fileID < Swift 6 #file");
static_assert(Kind::FileIDSpelledAsFile < Kind::FilePath,
"Swift 6 #file < #filePath");
static_assert(Kind::FilePath < Kind::FilePathSpelledAsFile,
"#filePath < Swift 5 #file");
static_assert(Kind::FilePathSpelledAsFile < Kind::Line,
"Swift 5 #file < #line");
static_assert(Kind::FilePathSpelledAsFile < Kind::Column,
"Swift 5 #file < #column");
static_assert(Kind::FilePathSpelledAsFile < Kind::Function,
"Swift 5 #file < #function");
static_assert(Kind::FilePathSpelledAsFile < Kind::DSOHandle,
"Swift 5 #file < #dsohandle");
// The rules are all commutative, so we will take the greater of the two
// kinds.
auto maxKind = std::max(a, b);
// Both Swift 6 #file and Swift 5 #file are greater than all of the cases
// they're compatible with. So if `maxCase` is one of those two, the other
// case must have been compatible with it!
return maxKind == Kind::FileIDSpelledAsFile ||
maxKind == Kind::FilePathSpelledAsFile;
}
void checkUseOfModule(DeclRefExpr *E) {
// Allow module values as a part of:
// - ignored base expressions;
// - expressions that failed to type check.
if (auto *ParentExpr = Parent.getAsExpr()) {
if (isa<DotSyntaxBaseIgnoredExpr>(ParentExpr) ||
isa<UnresolvedDotExpr>(ParentExpr))
return;
}
Ctx.Diags.diagnose(E->getStartLoc(), diag::value_of_module_type);
}
// Diagnose metatype values that don't appear as part of a property,
// method, or constructor reference.
void checkUseOfMetaTypeName(Expr *E) {
// If we've already checked this at a higher level, we're done.
if (!AlreadyDiagnosedMetatypes.insert(E).second)
return;
DiagnosticBehavior behavior = DiagnosticBehavior::Error;
if (auto *ParentExpr = Parent.getAsExpr()) {
if (ParentExpr->isValidParentOfTypeExpr(E))
return;
// In Swift < 6 warn about
// - plain type name passed as an argument to a subscript, dynamic
// subscript, or ObjC literal since it used to be accepted.
// - member type expressions rooted on non-identifier types, e.g.
// '[X].Y' since they used to be accepted without the '.self'.
if (!Ctx.LangOpts.isSwiftVersionAtLeast(6)) {
if (isa<SubscriptExpr>(ParentExpr) ||
isa<DynamicSubscriptExpr>(ParentExpr) ||
isa<ObjectLiteralExpr>(ParentExpr)) {
auto *argList = ParentExpr->getArgs();
assert(argList);
if (argList->isUnlabeledUnary())
behavior = DiagnosticBehavior::Warning;
} else if (auto *TE = dyn_cast<TypeExpr>(E)) {
if (auto *QualIdentTR = dyn_cast_or_null<QualifiedIdentTypeRepr>(
TE->getTypeRepr())) {
if (!isa<UnqualifiedIdentTypeRepr>(QualIdentTR->getRoot())) {
behavior = DiagnosticBehavior::Warning;
}
}
}
}
}
// Is this a protocol metatype?
Ctx.Diags
.diagnose(E->getStartLoc(), diag::value_of_metatype_type,
behavior == DiagnosticBehavior::Warning)
.limitBehavior(behavior);
// Add fix-it to insert '()', only if this is a metatype of
// non-existential type and has any initializers.
bool isExistential = false;
if (auto metaTy = E->getType()->getAs<MetatypeType>()) {
auto instanceTy = metaTy->getInstanceType();
isExistential = instanceTy->isExistentialType();
if (!isExistential &&
instanceTy->mayHaveMembers() &&
!TypeChecker::lookupMember(const_cast<DeclContext *>(DC), instanceTy,
DeclNameRef::createConstructor()).empty()) {
Ctx.Diags.diagnose(E->getEndLoc(), diag::add_parens_to_type)
.fixItInsertAfter(E->getEndLoc(), "()");
}
}
// Add fix-it to insert ".self".
auto diag = Ctx.Diags.diagnose(E->getEndLoc(), diag::add_self_to_type);
if (E->canAppendPostfixExpression()) {
diag.fixItInsertAfter(E->getEndLoc(), ".self");
} else {
diag.fixItInsert(E->getStartLoc(), "(");
diag.fixItInsertAfter(E->getEndLoc(), ").self");
}
}
void checkUnqualifiedAccessUse(const DeclRefExpr *DRE) {
const Decl *D = DRE->getDecl();
if (!D->getAttrs().hasAttribute<WarnUnqualifiedAccessAttr>())
return;
if (auto *parentExpr = Parent.getAsExpr()) {
if (auto *ignoredBase = dyn_cast<DotSyntaxBaseIgnoredExpr>(parentExpr)){
if (!ignoredBase->isImplicit())
return;
}
if (auto *calledBase = dyn_cast<DotSyntaxCallExpr>(parentExpr)) {
if (!calledBase->isImplicit())
return;
}
}
const auto *VD = cast<ValueDecl>(D);
const TypeDecl *declParent =
VD->getDeclContext()->getSelfNominalTypeDecl();
if (!declParent) {
// If the declaration has been validated but not fully type-checked,
// the attribute might be applied to something invalid.
if (!VD->getDeclContext()->isModuleScopeContext())
return;
declParent = VD->getDeclContext()->getParentModule();
}
Ctx.Diags.diagnose(DRE->getLoc(), diag::warn_unqualified_access,
VD->getBaseIdentifier(),
VD->getDescriptiveKind(),
declParent);
Ctx.Diags.diagnose(VD, diag::decl_declared_here, VD);
if (VD->getDeclContext()->isTypeContext()) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::fix_unqualified_access_member)
.fixItInsert(DRE->getStartLoc(), "self.");
}
DeclContext *topLevelSubcontext = DC->getModuleScopeContext();
auto descriptor = UnqualifiedLookupDescriptor(
DeclNameRef(VD->getBaseName()), topLevelSubcontext, SourceLoc());
auto lookup = evaluateOrDefault(Ctx.evaluator,
UnqualifiedLookupRequest{descriptor}, {});
// Group results by module. Pick an arbitrary result from each module.
llvm::SmallDenseMap<const ModuleDecl*,const ValueDecl*,4> resultsByModule;
for (auto &result : lookup) {
const ValueDecl *value = result.getValueDecl();
resultsByModule.insert(std::make_pair(value->getModuleContext(),value));
}
// Sort by module name.
using ModuleValuePair = std::pair<const ModuleDecl *, const ValueDecl *>;
SmallVector<ModuleValuePair, 4> sortedResults{
resultsByModule.begin(), resultsByModule.end()
};
llvm::array_pod_sort(sortedResults.begin(), sortedResults.end(),
[](const ModuleValuePair *lhs,
const ModuleValuePair *rhs) {
return lhs->first->getName().compare(rhs->first->getName());
});
auto topLevelDiag = diag::fix_unqualified_access_top_level;
if (sortedResults.size() > 1)
topLevelDiag = diag::fix_unqualified_access_top_level_multi;
for (const ModuleValuePair &pair : sortedResults) {
DescriptiveDeclKind k = pair.second->getDescriptiveKind();
SmallString<32> namePlusDot = pair.first->getName().str();
namePlusDot.push_back('.');
Ctx.Diags.diagnose(DRE->getLoc(), topLevelDiag,
namePlusDot, k, pair.first->getName())
.fixItInsert(DRE->getStartLoc(), namePlusDot);
}
}
void checkForDeclWithSpecialTypeCheckingSemantics(const DeclRefExpr *DRE) {
// Referencing type(of:) and other decls with special type-checking
// behavior as functions is not implemented. Maybe we could wrap up the
// special-case behavior in a closure someday...
if (TypeChecker::getDeclTypeCheckingSemantics(DRE->getDecl())
!= DeclTypeCheckingSemantics::Normal) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::unsupported_special_decl_ref,
DRE->getDecl()->getBaseIdentifier());
}
}
enum BitcastableNumberKind {
BNK_None = 0,
BNK_Int8,
BNK_Int16,
BNK_Int32,
BNK_Int64,
BNK_Int,
BNK_UInt8,
BNK_UInt16,
BNK_UInt32,
BNK_UInt64,
BNK_UInt,
BNK_Float,
BNK_Double,
};
BitcastableNumberKind getBitcastableNumberKind(Type t) const {
auto decl = t->getNominalOrBoundGenericNominal();
#define MATCH_DECL(type) \
if (decl == Ctx.get##type##Decl()) \
return BNK_##type;
MATCH_DECL(Int8)
MATCH_DECL(Int16)
MATCH_DECL(Int32)
MATCH_DECL(Int64)
MATCH_DECL(Int)
MATCH_DECL(UInt8)
MATCH_DECL(UInt16)
MATCH_DECL(UInt32)
MATCH_DECL(UInt64)
MATCH_DECL(UInt)
MATCH_DECL(Float)
MATCH_DECL(Double)
#undef MATCH_DECL
return BNK_None;
}
static constexpr unsigned BNKPair(BitcastableNumberKind a,
BitcastableNumberKind b) {
return (a << 8) | b;
}
void checkForSuspiciousBitCasts(DeclRefExpr *DRE,
Expr *Parent = nullptr) {
if (DRE->getDecl() != Ctx.getUnsafeBitCast())
return;
if (DRE->getDeclRef().getSubstitutions().empty())
return;
// Don't check the same use of unsafeBitCast twice.
if (!AlreadyDiagnosedBitCasts.insert(DRE).second)
return;
auto subMap = DRE->getDeclRef().getSubstitutions();
auto fromTy = subMap.getReplacementTypes()[0];
auto toTy = subMap.getReplacementTypes()[1];
// Warn about `unsafeBitCast` formulations that are undefined behavior
// or have better-defined alternative APIs that can be used instead.
// If we have a parent ApplyExpr that calls bitcast, extract the argument
// for fixits.
Expr *subExpr = nullptr;
CharSourceRange removeBeforeRange, removeAfterRange;
if (auto apply = dyn_cast_or_null<ApplyExpr>(Parent)) {
subExpr = apply->getArgs()->getExpr(0);
// Determine the fixit range from the start of the application to
// the first argument, `unsafeBitCast(`
removeBeforeRange = CharSourceRange(Ctx.SourceMgr, DRE->getLoc(),
subExpr->getStartLoc());
// Determine the fixit range from the end of the first argument to
// the end of the application, `, to: T.self)`
removeAfterRange = CharSourceRange(Ctx.SourceMgr,
Lexer::getLocForEndOfToken(Ctx.SourceMgr,
subExpr->getEndLoc()),
Lexer::getLocForEndOfToken(Ctx.SourceMgr,
apply->getEndLoc()));
}
// Casting to the same type or a superclass is a no-op.
if (toTy->isEqual(fromTy) ||
toTy->isExactSuperclassOf(fromTy)) {
auto d = Ctx.Diags.diagnose(DRE->getLoc(), diag::bitcasting_is_no_op,
fromTy, toTy);
if (subExpr) {
d.fixItRemoveChars(removeBeforeRange.getStart(),
removeBeforeRange.getEnd())
.fixItRemoveChars(removeAfterRange.getStart(),
removeAfterRange.getEnd());
}
return;
}
if (auto fromFnTy = fromTy->getAs<FunctionType>()) {
if (auto toFnTy = toTy->getAs<FunctionType>()) {
// Casting a nonescaping function to escaping is UB.
// `withoutActuallyEscaping` ought to be used instead.
if (fromFnTy->isNoEscape() && !toFnTy->isNoEscape()) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::bitcasting_away_noescape,
fromTy, toTy);
}
// Changing function representation (say, to try to force a
// @convention(c) function pointer to exist) is also unlikely to work.
if (fromFnTy->getRepresentation() != toFnTy->getRepresentation()) {
Ctx.Diags.diagnose(DRE->getLoc(),
diag::bitcasting_to_change_function_rep, fromTy,
toTy);
}
return;
}
}
// Unchecked casting to a subclass is better done by unsafeDowncast.
if (fromTy->isBindableToSuperclassOf(toTy)) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::bitcasting_to_downcast,
fromTy, toTy)
.fixItReplace(DRE->getNameLoc().getBaseNameLoc(),
"unsafeDowncast");
return;
}
// Casting among pointer types should use the Unsafe*Pointer APIs for
// rebinding typed memory or accessing raw memory instead.
PointerTypeKind fromPTK, toPTK;
Type fromPointee = fromTy->getAnyPointerElementType(fromPTK);
Type toPointee = toTy->getAnyPointerElementType(toPTK);
if (fromPointee && toPointee) {
// Casting to a pointer to the same type or UnsafeRawPointer can use
// normal initializers on the destination type.
if (toPointee->isEqual(fromPointee)
|| isRawPointerKind(toPTK)) {
auto d = Ctx.Diags.diagnose(DRE->getLoc(),
diag::bitcasting_to_change_pointer_kind,
fromTy, toTy,
toTy->getStructOrBoundGenericStruct()->getName());
if (subExpr) {
StringRef before, after;
switch (toPTK) {
case PTK_UnsafePointer:
// UnsafePointer(mutablePointer)
before = "UnsafePointer(";
after = ")";
break;
case PTK_UnsafeMutablePointer:
case PTK_AutoreleasingUnsafeMutablePointer:
before = "UnsafeMutablePointer(mutating: ";
after = ")";
break;
case PTK_UnsafeRawPointer:
// UnsafeRawPointer(pointer)
before = "UnsafeRawPointer(";
after = ")";
break;
case PTK_UnsafeMutableRawPointer:
// UnsafeMutableRawPointer(mutating: rawPointer)
before = fromPTK == PTK_UnsafeMutablePointer
? "UnsafeMutableRawPointer("
: "UnsafeMutableRawPointer(mutating: ";
after = ")";
break;
}
d.fixItReplaceChars(removeBeforeRange.getStart(),
removeBeforeRange.getEnd(),
before)
.fixItReplaceChars(removeAfterRange.getStart(),
removeAfterRange.getEnd(),
after);
}
return;
}
// Casting to a different typed pointer type should use
// withMemoryRebound.
if (!isRawPointerKind(fromPTK) && !isRawPointerKind(toPTK)) {
Ctx.Diags.diagnose(DRE->getLoc(),
diag::bitcasting_to_change_pointee_type,
fromTy, toTy);
return;
}
// Casting a raw pointer to a typed pointer should bind the memory
// (or assume it's already bound).
assert(isRawPointerKind(fromPTK) && !isRawPointerKind(toPTK)
&& "unhandled cast combo?!");
Ctx.Diags.diagnose(DRE->getLoc(),
diag::bitcasting_to_give_type_to_raw_pointer,
fromTy, toTy);
if (subExpr) {
SmallString<64> fixitBuf;
{
llvm::raw_svector_ostream os(fixitBuf);
os << ".assumingMemoryBound(to: ";
toPointee->print(os);
os << ".self)";
}
Ctx.Diags.diagnose(DRE->getLoc(),
diag::bitcast_assume_memory_rebound,
toPointee)
.fixItRemoveChars(removeBeforeRange.getStart(),
removeBeforeRange.getEnd())
.fixItReplaceChars(removeAfterRange.getStart(),
removeAfterRange.getEnd(),
fixitBuf);
fixitBuf.clear();
{
llvm::raw_svector_ostream os(fixitBuf);
os << ".bindMemory(to: ";
toPointee->print(os);
os << ".self, capacity: <""#capacity#"">)";
}
Ctx.Diags.diagnose(DRE->getLoc(),
diag::bitcast_bind_memory,
toPointee)
.fixItRemoveChars(removeBeforeRange.getStart(),
removeBeforeRange.getEnd())
.fixItReplaceChars(removeAfterRange.getStart(),
removeAfterRange.getEnd(),
fixitBuf);
}
return;
}
StringRef replaceBefore, replaceAfter;
std::optional<Diag<Type, Type>> diagID;
SmallString<64> replaceBeforeBuf;
// Bitcasting among numeric types should use `bitPattern:` initializers.
auto fromBNK = getBitcastableNumberKind(fromTy);
auto toBNK = getBitcastableNumberKind(toTy);
if (fromBNK && toBNK) {
switch (BNKPair(fromBNK, toBNK)) {
// Combos that can be bitPattern-ed with a constructor
case BNKPair(BNK_Int8, BNK_UInt8):
case BNKPair(BNK_UInt8, BNK_Int8):
case BNKPair(BNK_Int16, BNK_UInt16):
case BNKPair(BNK_UInt16, BNK_Int16):
case BNKPair(BNK_Int32, BNK_UInt32):
case BNKPair(BNK_UInt32, BNK_Int32):
case BNKPair(BNK_Int64, BNK_UInt64):
case BNKPair(BNK_UInt64, BNK_Int64):
case BNKPair(BNK_Int, BNK_UInt):
case BNKPair(BNK_UInt, BNK_Int):
case BNKPair(BNK_UInt32, BNK_Float):
case BNKPair(BNK_UInt64, BNK_Double):
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: ";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ")";
break;
// Combos that can be bitPattern-ed with a constructor and sign flip
case BNKPair(BNK_Int32, BNK_Float):
case BNKPair(BNK_Int64, BNK_Double):
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: ";
if (fromBNK == BNK_Int32)
os << "UInt32(bitPattern: ";
else
os << "UInt64(bitPattern: ";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = "))";
break;
// Combos that can be bitPattern-ed with a property
case BNKPair(BNK_Float, BNK_UInt32):
case BNKPair(BNK_Double, BNK_UInt64):
diagID = diag::bitcasting_for_number_bit_pattern_property;
replaceAfter = ".bitPattern";
break;
// Combos that can be bitPattern-ed with a property and sign flip
case BNKPair(BNK_Float, BNK_Int32):
case BNKPair(BNK_Double, BNK_Int64):
diagID = diag::bitcasting_for_number_bit_pattern_property;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: ";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ")";
break;
// Combos that can be bitPattern-ed with a constructor once (U)Int is
// converted to a sized type.
case BNKPair(BNK_UInt, BNK_Float):
case BNKPair(BNK_Int, BNK_UInt32):
case BNKPair(BNK_UInt, BNK_Int32):
case BNKPair(BNK_Int, BNK_UInt64):
case BNKPair(BNK_UInt, BNK_Int64):
case BNKPair(BNK_UInt, BNK_Double):
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: ";
if (fromBNK == BNK_Int)
os << "Int";
else
os << "UInt";
if (toBNK == BNK_Float
|| toBNK == BNK_Int32
|| toBNK == BNK_UInt32)
os << "32(";
else
os << "64(";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = "))";
break;
case BNKPair(BNK_Int, BNK_Float):
case BNKPair(BNK_Int, BNK_Double):
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: UInt";
if (toBNK == BNK_Float
|| toBNK == BNK_Int32
|| toBNK == BNK_UInt32)
os << "32(bitPattern: Int32(";
else
os << "64(bitPattern: Int64(";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ")))";
break;
// Combos that can be bitPattern-ed then converted from a sized type
// to (U)Int.
case BNKPair(BNK_Int32, BNK_UInt):
case BNKPair(BNK_UInt32, BNK_Int):
case BNKPair(BNK_Int64, BNK_UInt):
case BNKPair(BNK_UInt64, BNK_Int):
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(";
if (toBNK == BNK_UInt)
os << "UInt";
else
os << "Int";
if (fromBNK == BNK_Int32 || fromBNK == BNK_UInt32)
os << "32(bitPattern: ";
else
os << "64(bitPattern: ";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = "))";
break;
case BNKPair(BNK_Float, BNK_UInt):
case BNKPair(BNK_Double, BNK_UInt):
diagID = diag::bitcasting_for_number_bit_pattern_property;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ".bitPattern)";
break;
case BNKPair(BNK_Float, BNK_Int):
case BNKPair(BNK_Double, BNK_Int):
diagID = diag::bitcasting_for_number_bit_pattern_property;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: UInt(";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ".bitPattern))";
break;
// Combos that should be done with a value-preserving initializer.
case BNKPair(BNK_Int, BNK_Int32):
case BNKPair(BNK_Int, BNK_Int64):
case BNKPair(BNK_UInt, BNK_UInt32):
case BNKPair(BNK_UInt, BNK_UInt64):
case BNKPair(BNK_Int32, BNK_Int):
case BNKPair(BNK_Int64, BNK_Int):
case BNKPair(BNK_UInt32, BNK_UInt):
case BNKPair(BNK_UInt64, BNK_UInt):
diagID = diag::bitcasting_to_change_from_unsized_to_sized_int;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << '(';
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ")";
break;
default:
// Leave other combos alone.
break;
}
}
// Casting a pointer to an int or back should also use bitPattern
// initializers.
if (fromPointee && toBNK) {
switch (toBNK) {
case BNK_UInt:
case BNK_Int:
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: ";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ")";
break;
case BNK_UInt64:
case BNK_UInt32:
case BNK_Int64:
case BNK_Int32:
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << '(';
if (toBNK == BNK_UInt32 || toBNK == BNK_UInt64)
os << "UInt(bitPattern: ";
else
os << "Int(bitPattern: ";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = "))";
break;
default:
break;
}
}
if (fromBNK && toPointee) {
switch (fromBNK) {
case BNK_UInt:
case BNK_Int:
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: ";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = ")";
break;
case BNK_UInt64:
case BNK_UInt32:
case BNK_Int64:
case BNK_Int32:
diagID = diag::bitcasting_for_number_bit_pattern_init;
{
llvm::raw_svector_ostream os(replaceBeforeBuf);
toTy->print(os);
os << "(bitPattern: ";
if (fromBNK == BNK_Int32 || fromBNK == BNK_Int64)
os << "Int(";
else
os << "UInt(";
}
replaceBefore = replaceBeforeBuf;
replaceAfter = "))";
break;
default:
break;
}
}
if (diagID) {
auto d = Ctx.Diags.diagnose(DRE->getLoc(), *diagID, fromTy, toTy);
if (subExpr) {
d.fixItReplaceChars(removeBeforeRange.getStart(),
removeBeforeRange.getEnd(),
replaceBefore);
d.fixItReplaceChars(removeAfterRange.getStart(),
removeAfterRange.getEnd(),
replaceAfter);
}
}
}
/// Return true if this is a 'nil' literal. This looks
/// like this if the type is Optional<T>:
///
/// (dot_syntax_call_expr type='String?'
/// (declref_expr type='(Optional<String>.Type) -> Optional<String>'
/// decl=Swift.(file).Optional.none function_ref=unapplied)
/// (argument_list implicit
/// (argument
/// (type_expr implicit type='String?.Type' typerepr='String?'))))
///
/// Or like this if it is any other ExpressibleByNilLiteral type:
///
/// (nil_literal_expr)
///
bool isTypeCheckedOptionalNil(Expr *E) {
if (dyn_cast<NilLiteralExpr>(E)) return true;
if (auto *DSCE = dyn_cast_or_null<DotSyntaxCallExpr>(E->getSemanticsProvidingExpr())) {
if (auto *DRE = dyn_cast<DeclRefExpr>(DSCE->getSemanticFn()))
return DRE->getDecl() == Ctx.getOptionalNoneDecl();
}
return false;
}
/// Warn about surprising implicit optional promotions involving operands to
/// calls. Specifically, we warn about these expressions when the 'x'
/// operand is implicitly promoted to optional:
///
/// x ?? y
/// x == nil // also !=
///
void checkOptionalPromotions(ApplyExpr *call) {
// We only care about binary expressions.
auto *BE = dyn_cast<BinaryExpr>(call);
if (!BE) return;
// Dig out the function we're calling.
auto fnExpr = call->getSemanticFn();
if (auto dotSyntax = dyn_cast<DotSyntaxCallExpr>(fnExpr))
fnExpr = dotSyntax->getSemanticFn();
if (auto *FCE = dyn_cast<FunctionConversionExpr>(fnExpr))
fnExpr = FCE->getSubExpr();
auto DRE = dyn_cast<DeclRefExpr>(fnExpr);
if (!DRE || !DRE->getDecl()->isOperator())
return;
auto lhs = BE->getLHS();
auto rhs = BE->getRHS();
auto calleeName = DRE->getDecl()->getBaseName();
Expr *subExpr = nullptr;
if (calleeName == "??" &&
(subExpr = isImplicitPromotionToOptional(lhs))) {
Ctx.Diags
.diagnose(DRE->getLoc(), diag::use_of_qq_on_non_optional_value,
subExpr->getType())
.highlight(lhs->getSourceRange())
.fixItRemoveChars(
Lexer::getLocForEndOfToken(Ctx.SourceMgr, lhs->getEndLoc()),
Lexer::getLocForEndOfToken(Ctx.SourceMgr, rhs->getEndLoc()));
return;
}
if (calleeName == "==" || calleeName == "!=" ||
calleeName == "===" || calleeName == "!==") {
if (((subExpr = isImplicitPromotionToOptional(lhs)) &&
isTypeCheckedOptionalNil(rhs)) ||
(isTypeCheckedOptionalNil(lhs) &&
(subExpr = isImplicitPromotionToOptional(rhs)))) {
bool isTrue = calleeName == "!=" || calleeName == "!==";
bool isNilLiteral = isa<NilLiteralExpr>(lhs) || isa<NilLiteralExpr>(rhs);
Ctx.Diags.diagnose(DRE->getLoc(), diag::nonoptional_compare_to_nil,
subExpr->getType(), isNilLiteral, isTrue)
.highlight(lhs->getSourceRange())
.highlight(rhs->getSourceRange());
return;
}
}
}
};
DiagnoseWalker Walker(DC, isExprStmt);
const_cast<Expr *>(E)->walk(Walker);
// Diagnose uses of collection literals with defaulted types at the top
// level.
if (auto collection =
dyn_cast<CollectionExpr>(E->getSemanticsProvidingExpr())) {
if (collection->isTypeDefaulted()) {
Walker.checkTypeDefaultedCollectionExpr(
const_cast<CollectionExpr *>(collection));
}
}
}
DeferredDiags swift::findSyntacticErrorForConsume(
ModuleDecl *module, SourceLoc loc, Expr *subExpr) {
assert(!isa<ConsumeExpr>(subExpr) && "operates on the sub-expr of a consume");
DeferredDiags result;
const bool noncopyable =
subExpr->getType()->getCanonicalType()->isNoncopyable();
bool partial = false;
Expr *current = subExpr;
while (current) {
if (auto *dre = dyn_cast<DeclRefExpr>(current)) {
if (partial & !noncopyable)
result.emplace_back(loc, diag::consume_expression_partial_copyable);
// The chain of member_ref_exprs and load_exprs terminates at a
// declref_expr. This is legal.
break;
}
// Look through loads.
if (auto *le = dyn_cast<LoadExpr>(current)) {
current = le->getSubExpr();
continue;
}
auto *mre = dyn_cast<MemberRefExpr>(current);
if (mre) {
auto *vd = dyn_cast<VarDecl>(mre->getMember().getDecl());
if (!vd) {
result.emplace_back(loc, diag::consume_expression_non_storage);
break;
}
partial = true;
AccessStrategy strategy = vd->getAccessStrategy(
mre->getAccessSemantics(), AccessKind::Read,
module, ResilienceExpansion::Minimal);
if (strategy.getKind() != AccessStrategy::Storage) {
if (noncopyable) {
result.emplace_back(loc, diag::consume_expression_non_storage);
result.emplace_back(mre->getLoc(),
diag::note_consume_expression_non_storage_property);
break;
}
result.emplace_back(loc, diag::consume_expression_partial_copyable);
break;
}
current = mre->getBase();
continue;
}
auto *ce = dyn_cast<CallExpr>(current);
if (ce) {
if (noncopyable) {
result.emplace_back(loc, diag::consume_expression_non_storage);
result.emplace_back(ce->getLoc(),
diag::note_consume_expression_non_storage_call);
break;
}
result.emplace_back(loc, diag::consume_expression_partial_copyable);
break;
}
auto *se = dyn_cast<SubscriptExpr>(current);
if (se) {
if (noncopyable) {
result.emplace_back(loc, diag::consume_expression_non_storage);
result.emplace_back(se->getLoc(),
diag::note_consume_expression_non_storage_subscript);
break;
}
result.emplace_back(loc, diag::consume_expression_partial_copyable);
break;
}
result.emplace_back(loc, diag::consume_expression_not_passed_lvalue);
break;
}
return result;
}
/// Diagnose recursive use of properties within their own accessors
static void diagRecursivePropertyAccess(const Expr *E, const DeclContext *DC) {
auto fn = dyn_cast<AccessorDecl>(DC);
if (!fn)
return;
auto var = dyn_cast<VarDecl>(fn->getStorage());
if (!var) // Ignore subscripts
return;
class DiagnoseWalker : public ASTWalker {
ASTContext &Ctx;
VarDecl *Var;
const AccessorDecl *Accessor;
public:
explicit DiagnoseWalker(VarDecl *var, const AccessorDecl *Accessor)
: Ctx(var->getASTContext()), Var(var), Accessor(Accessor) {}
/// Return true if this is an implicit reference to self.
static bool isImplicitSelfUse(Expr *E) {
auto *DRE = dyn_cast<DeclRefExpr>(E);
return DRE && DRE->isImplicit() && isa<VarDecl>(DRE->getDecl()) &&
cast<VarDecl>(DRE->getDecl())->isSelfParameter();
}
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
Expr *subExpr;
bool isStore = false;
if (auto *AE = dyn_cast<AssignExpr>(E)) {
subExpr = AE->getDest();
// If we couldn't flatten this expression, don't explode.
if (!subExpr)
return Action::Continue(E);
isStore = true;
} else if (auto *IOE = dyn_cast<InOutExpr>(E)) {
subExpr = IOE->getSubExpr();
isStore = true;
} else {
subExpr = E;
}
if (auto *BOE = dyn_cast<BindOptionalExpr>(subExpr))
subExpr = BOE;
if (auto *DRE = dyn_cast<DeclRefExpr>(subExpr)) {
if (DRE->getDecl() == Var) {
// Handle local and top-level computed variables.
if (DRE->getAccessSemantics() == AccessSemantics::Ordinary) {
bool shouldDiagnose = false;
// Warn about any property access in the getter.
if (Accessor->isGetter())
shouldDiagnose = !isStore;
// Warn about stores in the setter, but allow loads.
if (Accessor->isSetter())
shouldDiagnose = isStore;
// But silence the warning if the base was explicitly qualified.
auto parentAsExpr = Parent.getAsExpr();
if (isa_and_nonnull<DotSyntaxBaseIgnoredExpr>(parentAsExpr))
shouldDiagnose = false;
if (shouldDiagnose) {
Ctx.Diags.diagnose(subExpr->getLoc(),
diag::recursive_accessor_reference,
Var->getName(), Accessor->isSetter());
}
}
// If this is a direct store in a "willSet", we reject this because
// it is about to get overwritten.
if (isStore &&
DRE->getAccessSemantics() == AccessSemantics::DirectToStorage &&
Accessor->getAccessorKind() == AccessorKind::WillSet) {
Ctx.Diags.diagnose(E->getLoc(), diag::store_in_willset,
Var->getName());
}
}
} else if (auto *MRE = dyn_cast<MemberRefExpr>(subExpr)) {
// Handle instance and type computed variables.
// Find MemberRefExprs that have an implicit "self" base.
if (MRE->getMember().getDecl() == Var &&
isa<DeclRefExpr>(MRE->getBase()) &&
isImplicitSelfUse(MRE->getBase())) {
if (MRE->getAccessSemantics() == AccessSemantics::Ordinary) {
bool shouldDiagnose = false;
// Warn about any property access in the getter.
if (Accessor->isGetter())
shouldDiagnose = !isStore;
// Warn about stores in the setter, but allow loads.
if (Accessor->isSetter())
shouldDiagnose = isStore;
if (shouldDiagnose) {
Ctx.Diags.diagnose(subExpr->getLoc(),
diag::recursive_accessor_reference,
Var->getName(), Accessor->isSetter());
Ctx.Diags.diagnose(subExpr->getLoc(),
diag::recursive_accessor_reference_silence)
.fixItInsert(subExpr->getStartLoc(), "self.");
}
}
// If this is a direct store in a "willSet", we reject this because
// it is about to get overwritten.
if (isStore &&
MRE->getAccessSemantics() == AccessSemantics::DirectToStorage &&
Accessor->getAccessorKind() == AccessorKind::WillSet) {
Ctx.Diags.diagnose(subExpr->getLoc(), diag::store_in_willset,
Var->getName());
}
}
}
return Action::Continue(E);
}
};
DiagnoseWalker walker(var, fn);
const_cast<Expr *>(E)->walk(walker);
}
/// The `weak self` capture of this closure if present
static VarDecl *weakSelfCapture(const AbstractClosureExpr *ACE) {
if (auto closureExpr = dyn_cast<ClosureExpr>(ACE)) {
if (auto selfDecl = closureExpr->getCapturedSelfDecl()) {
if (selfDecl->getInterfaceType()->is<WeakStorageType>()) {
return selfDecl;
}
}
}
return nullptr;
}
/// Whether or not this closure captures self weakly
static bool closureHasWeakSelfCapture(const AbstractClosureExpr *ACE) {
return weakSelfCapture(ACE) != nullptr;
}
// Returns true if this is an implicit self expr
static bool isImplicitSelf(const Expr *E) {
auto *DRE = dyn_cast<DeclRefExpr>(E);
if (!DRE || !DRE->isImplicit())
return false;
ASTContext &Ctx = DRE->getDecl()->getASTContext();
return DRE->getDecl()->getName().isSimpleName(Ctx.Id_self);
}
/// Look for any property references in closures that lack a 'self.' qualifier.
/// Within a closure, we require that the source code contain 'self.' explicitly
/// (or that the closure explicitly capture 'self' in the capture list) because
/// 'self' is captured, not the property value. This is a common source of
/// confusion, so we force an explicit self.
static void diagnoseImplicitSelfUseInClosure(const Expr *E,
const DeclContext *DC) {
class DiagnoseWalker : public BaseDiagnosticWalker {
ASTContext &Ctx;
SmallVector<AbstractClosureExpr *, 4> Closures;
/// A list of "implicit self" exprs from shorthand conditions
/// like `if let self` or `guard let self`. These conditions
/// have an RHS 'self' decl that is implicit, but this is not
/// the sort of "implicit self" decl that should trigger
/// these diagnostics.
SmallPtrSet<Expr *, 16> UnwrapStmtImplicitSelfExprs;
public:
explicit DiagnoseWalker(ASTContext &Ctx, AbstractClosureExpr *ACE)
: Ctx(Ctx), Closures() {
if (ACE)
Closures.push_back(ACE);
}
static bool
implicitWeakSelfReferenceIsValid510(const DeclRefExpr *DRE,
const AbstractClosureExpr *inClosure) {
ASTContext &Ctx = DRE->getDecl()->getASTContext();
// Check if the implicit self decl refers to a var in a conditional stmt
LabeledConditionalStmt *conditionalStmt = nullptr;
if (auto var = dyn_cast<VarDecl>(DRE->getDecl())) {
if (auto parentStmt = var->getParentPatternStmt()) {
conditionalStmt = dyn_cast<LabeledConditionalStmt>(parentStmt);
}
}
if (!conditionalStmt) {
return false;
}
// Require `LoadExpr`s when validating the self binding.
// This lets us reject invalid examples like:
//
// let `self` = self ?? .somethingElse
// guard let self = self else { return }
// method() // <- implicit self is not allowed
//
return conditionalStmt->rebindsSelf(Ctx, /*requiresCaptureListRef*/ false,
/*requireLoadExpr*/ true);
}
static bool
isEnclosingSelfReference510(VarDecl *var,
const AbstractClosureExpr *inClosure) {
if (var->isSelfParameter())
return true;
// Capture variables have a DC of the parent function.
if (inClosure && var->isSelfParamCapture() &&
var->getDeclContext() != inClosure->getParent())
return true;
return false;
}
static bool
selfDeclAllowsImplicitSelf510(DeclRefExpr *DRE, Type ty,
const AbstractClosureExpr *inClosure) {
// If this is an explicit `weak self` capture, then implicit self is
// allowed once the closure's self param is unwrapped. We need to validate
// that the unwrapped `self` decl specifically refers to an unwrapped copy
// of the closure's `self` param, and not something else like in `guard
// let self = .someOptionalVariable else { return }` or `let self =
// someUnrelatedVariable`. If self hasn't been unwrapped yet and is still
// an optional, we would have already hit an error elsewhere.
if (closureHasWeakSelfCapture(inClosure)) {
return implicitWeakSelfReferenceIsValid510(DRE, inClosure);
}
// Metatype self captures don't extend the lifetime of an object.
if (ty->is<MetatypeType>())
return true;
// If self does not have reference semantics, it is very unlikely that
// capturing it will create a reference cycle.
if (!ty->hasReferenceSemantics())
return true;
if (auto closureExpr = dyn_cast<ClosureExpr>(inClosure)) {
if (auto selfDecl = closureExpr->getCapturedSelfDecl()) {
// If this capture is using the name `self` actually referring
// to some other variable (e.g. with `[self = "hello"]`)
// then implicit self is not allowed.
if (!selfDecl->isSelfParamCapture()) {
return false;
}
}
}
if (auto var = dyn_cast<VarDecl>(DRE->getDecl())) {
if (!isEnclosingSelfReference510(var, inClosure)) {
return true;
}
}
return false;
}
/// Whether or not implicit self is allowed for self decl
static bool
selfDeclAllowsImplicitSelf(Expr *E, const AbstractClosureExpr *inClosure) {
if (!isImplicitSelf(E)) {
return true;
}
auto *DRE = cast<DeclRefExpr>(E);
// Defensive check for type. If the expression doesn't have type here, it
// should have been diagnosed somewhere else.
Type ty = DRE->getType();
assert(ty && "Implicit self parameter ref without type");
if (!ty)
return true;
// Prior to Swift 6, use the old validation logic.
auto &ctx = inClosure->getASTContext();
if (!ctx.isSwiftVersionAtLeast(6))
return selfDeclAllowsImplicitSelf510(DRE, ty, inClosure);
return selfDeclAllowsImplicitSelf(DRE->getDecl(), ty, inClosure,
/*validateParentClosures:*/ true,
/*validateSelfRebindings:*/ true);
}
/// Whether or not implicit self is allowed for this implicit self decl
static bool selfDeclAllowsImplicitSelf(const ValueDecl *selfDecl,
const Type captureType,
const AbstractClosureExpr *inClosure,
bool validateParentClosures,
bool validateSelfRebindings) {
ASTContext &ctx = inClosure->getASTContext();
auto requiresSelfQualification =
isClosureRequiringSelfQualification(inClosure);
// Metatype self captures don't extend the lifetime of an object.
if (captureType->is<MetatypeType>()) {
requiresSelfQualification = false;
}
// If self does not have reference semantics, it is very unlikely that
// capturing it will create a reference cycle.
if (!captureType->hasReferenceSemantics()) {
requiresSelfQualification = false;
}
if (auto closureExpr = dyn_cast<ClosureExpr>(inClosure)) {
auto capturedSelfDecl = closureExpr->getCapturedSelfDecl();
// If this closure doesn't capture self explicitly, but this closure
// requires self qualification, then implicit self is disallowed.
if (!capturedSelfDecl && requiresSelfQualification) {
return false;
}
// If the closure has an explicit capture using the name `self` that
// actually refers to some other variable (e.g. `[self = "hello"]`)
// then implicit self is not allowed.
if (capturedSelfDecl && !isSimpleSelfCapture(capturedSelfDecl)) {
return false;
}
}
// If the self decl comes from a conditional statement, validate
// that it is an allowed `guard let self` or `if let self` condition.
// - Even if this closure doesn't have a `weak self` capture, it could
// be a closure nested in some parent closure with a `weak self`
// capture, so we should always validate the conditional statement
// that defines self if present.
if (validateSelfRebindings) {
if (auto conditionalStmt = parentConditionalStmt(selfDecl)) {
if (!hasValidSelfRebinding(conditionalStmt, ctx)) {
return false;
}
}
}
// If this closure has a `weak self` capture, require that the
// closure unwraps self. If not, implicit self is not allowed
// in this closure or in any nested closure.
if (closureHasWeakSelfCapture(inClosure) &&
!hasValidSelfRebinding(parentConditionalStmt(selfDecl), ctx)) {
return false;
}
if (auto autoclosure = dyn_cast<AutoClosureExpr>(inClosure)) {
// Implicit self is always allowed in autoclosure thunks generated
// during type checking. An example of this is when storing an instance
// method as a closure (e.g. `let closure = someInstanceMethodOnSelf`).
auto thunkKind = autoclosure->getThunkKind();
if (thunkKind == AutoClosureExpr::Kind::SingleCurryThunk ||
thunkKind == AutoClosureExpr::Kind::DoubleCurryThunk) {
return true;
}
// Explicit self is required in escaping autoclosures
if (requiresSelfQualification) {
return false;
}
}
// Lastly, validate that there aren't any parent closures
// with invalid self bindings that should disable implicit
// self for all nested closures.
// - We have to do this for all closures, even closures that typically
// don't require self qualificationm since an invalid self capture in
// a parent closure still disallows implicit self in a nested closure.
if (validateParentClosures) {
return !implicitSelfDisallowedDueToInvalidParent(selfDecl, captureType,
inClosure);
} else {
return true;
}
}
static bool implicitSelfDisallowedDueToInvalidParent(
const ValueDecl *selfDecl, const Type captureType,
const AbstractClosureExpr *inClosure) {
return parentClosureDisallowingImplicitSelf(selfDecl, captureType,
inClosure) != nullptr;
}
static const AbstractClosureExpr *
parentClosureDisallowingImplicitSelf(const ValueDecl *selfDecl,
const Type captureType,
const AbstractClosureExpr *inClosure) {
// Find the outer decl that determines what self refers to in this
// closure.
// - If this is an escaping closure that captured self, then `selfDecl`
// refers to the self capture.
// - If this is a nonescaping closure then there is no capture,
// so selfDecl already comes from an outer context.
const ValueDecl *outerSelfDecl = selfDecl;
if (auto closureExpr = dyn_cast<ClosureExpr>(inClosure)) {
if (auto capturedSelfDecl = closureExpr->getCapturedSelfDecl()) {
// Retrieve the outer decl that the self capture refers to.
outerSelfDecl = getParentInitializerDecl(capturedSelfDecl);
}
}
if (!outerSelfDecl) {
return nullptr;
}
// Find the closest parent closure that contains the outer self decl,
// potentially also validating all intermediate closures.
auto outerClosure = inClosure;
bool validateIntermediateParents = true;
while (true) {
// We have to validate all intermediate parent closures
// to prevent cases like this from succeeding, which is
// invalid because the outer closure doesn't have an
// explicit self capture:
//
// withEscaping {
// withNonEscaping {
// x += 1 // not allowed
// }
// }
//
// On the other hand, we need to support cases like this.
// As long as the inner closure has an explicit capture,
// it is not necessary for outer closures to also have
// an explicit self capture:
//
// withEscaping {
// withEscaping { [self] in
// x += 1 // ok
// }
// }
//
// So if we reach a closure with an explicit self capture,
// we no longer need to validate each intermediate closure
// (but we still have to validate the outer closure that
// contains the outer self delf).
if (auto closureExpr = dyn_cast<ClosureExpr>(outerClosure)) {
if (closureExpr->getCapturedSelfDecl()) {
validateIntermediateParents = false;
}
}
outerClosure = parentClosure(outerClosure);
if (!outerClosure) {
// Once we reach a parent context that isn't a closure,
// the only valid self capture is the self parameter.
// This disallows cases like:
//
// let `self` = somethingElse
// withEscaping { [self] in
// method()
// }
//
auto VD = dyn_cast<VarDecl>(outerSelfDecl);
if (!VD) {
return inClosure;
}
if (!VD->isSelfParameter()) {
return inClosure;
}
return nullptr;
}
// Check if this closure contains the self decl.
// - If the self decl is defined in the closure's body, its
// decl context will be the closure itself.
// - If the self decl is defined in the closure's capture list,
// its parent capture list will reference the closure.
auto selfDeclInOuterClosureContext =
outerSelfDecl->getDeclContext() == outerClosure;
auto selfDeclInOuterClosureCaptureList = false;
if (auto selfVD = dyn_cast<VarDecl>(outerSelfDecl)) {
if (auto captureList = selfVD->getParentCaptureList()) {
selfDeclInOuterClosureCaptureList =
captureList->getClosureBody() == outerClosure;
}
}
// We can stop searching because we found the first outer closure
// that contains the outer self decl. Otherwise we continue searching
// any parent closures in the next loop iteration.
if (selfDeclInOuterClosureContext ||
selfDeclInOuterClosureCaptureList) {
// Check whether implicit self is disallowed due to this specific
// closure, or if its disallowed due to some parent of this closure,
// so we can return the specific closure that is invalid.
if (!selfDeclAllowsImplicitSelf(outerSelfDecl, captureType,
outerClosure,
/*validateParentClosures:*/ false,
/*validateSelfRebindings:*/ true)) {
return outerClosure;
}
return parentClosureDisallowingImplicitSelf(
outerSelfDecl, captureType, outerClosure);
}
// Optionally validate this intermediate closure before continuing
// to search upwards. Since we're already validating the chain of
// parent closures, we don't need to do that separate for this closure.
if (validateIntermediateParents) {
if (!selfDeclAllowsImplicitSelf(selfDecl, captureType, outerClosure,
/*validateParentClosures*/ false,
/*validateSelfRebindings*/ false)) {
return outerClosure;
}
}
}
}
static bool
hasValidSelfRebinding(const LabeledConditionalStmt *conditionalStmt,
ASTContext &ctx) {
if (!conditionalStmt) {
return false;
}
// Require that the RHS of the `let self = self` condition
// refers to a variable defined in a capture list.
// This lets us reject invalid examples like:
//
// var `self` = self ?? .somethingElse
// guard let self = self else { return }
// method() // <- implicit self is not allowed
//
return conditionalStmt->rebindsSelf(ctx, /*requiresCaptureListRef*/ true);
}
/// The `LabeledConditionalStmt` that contains the given `ValueDecl` if
/// present
static LabeledConditionalStmt *
parentConditionalStmt(const ValueDecl *selfDecl) {
if (!selfDecl) {
return nullptr;
}
if (auto var = dyn_cast<VarDecl>(selfDecl)) {
if (auto parentStmt = var->getParentPatternStmt()) {
return dyn_cast<LabeledConditionalStmt>(parentStmt);
}
}
return nullptr;
}
/// Determines whether or not this is a simple self capture by retreiving
/// the `CaptureListEntry` that contains the `selfDecl`.
/// - Unlike `selfDecl->isSelfParamCapture()`, this will return true
/// for a simple `[weak self]` capture.
static bool isSimpleSelfCapture(const VarDecl *selfDecl) {
if (!selfDecl) {
return false;
}
auto captureList = selfDecl->getParentCaptureList();
if (!captureList) {
return false;
}
for (auto capture : captureList->getCaptureList()) {
if (capture.getVar() == selfDecl) {
return capture.isSimpleSelfCapture(/*excludeWeakCaptures:*/ false);
}
}
return false;
}
// Given a `self` decl that is a closure's `self` capture,
// retrieves and returns the decl that the capture refers to.
static ValueDecl *getParentInitializerDecl(const VarDecl *selfDecl) {
if (!selfDecl) {
return nullptr;
}
auto captureList = selfDecl->getParentCaptureList();
if (!captureList) {
return nullptr;
}
for (auto capture : captureList->getCaptureList()) {
if (capture.getVar() == selfDecl && capture.PBD) {
// We've found the `CaptureListEntry` that contains the `self`
// capture, now we can retrieve and inspect its parent initializer.
auto index = capture.PBD->getPatternEntryIndexForVarDecl(selfDecl);
auto parentInitializer = capture.PBD->getInit(index);
// Look through implicit conversions like `InjectIntoOptionalExpr`
if (auto implicitConversion =
dyn_cast_or_null<ImplicitConversionExpr>(parentInitializer)) {
parentInitializer = implicitConversion->getSubExpr();
}
auto DRE = dyn_cast_or_null<DeclRefExpr>(parentInitializer);
if (!DRE) {
return nullptr;
}
return DRE->getDecl();
}
}
return nullptr;
}
/// Return true if this is a closure expression that will require explicit
/// use or capture of "self." for qualification of member references.
static bool
isClosureRequiringSelfQualification(const AbstractClosureExpr *CE,
bool ignoreWeakSelf = false) {
if (!ignoreWeakSelf && closureHasWeakSelfCapture(CE)) {
return true;
}
// If the closure's type was inferred to be noescape, then it doesn't
// need qualification.
if (AnyFunctionRef(const_cast<AbstractClosureExpr *>(CE))
.isKnownNoEscape())
return false;
if (auto autoclosure = dyn_cast<AutoClosureExpr>(CE)) {
if (autoclosure->getThunkKind() == AutoClosureExpr::Kind::AsyncLet)
return false;
}
// If the closure was used in a context where it's explicitly stated
// that it does not need "self." qualification, don't require it.
if (auto closure = dyn_cast<ClosureExpr>(CE)) {
if (closure->allowsImplicitSelfCapture())
return false;
}
return true;
}
/// The closure that is a parent of this closure, if present
static const ClosureExpr *
parentClosure(const AbstractClosureExpr *closure) {
auto parentContext = closure->getParent();
if (!parentContext) {
return nullptr;
}
return parentContext->getInnermostClosureForSelfCapture();
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
bool shouldRecordClosure(const AbstractClosureExpr *E) {
// Record all closures in Swift 6 mode.
if (Ctx.isSwiftVersionAtLeast(6))
return true;
// Only record closures requiring self qualification prior to Swift 6
// mode.
return isClosureRequiringSelfQualification(E);
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (auto *CE = dyn_cast<AbstractClosureExpr>(E)) {
if (shouldRecordClosure(CE))
Closures.push_back(CE);
}
// If we aren't in a closure, no diagnostics will be produced.
if (Closures.size() == 0)
return Action::Continue(E);
// Diagnostics should correct the innermost closure
auto *ACE = Closures[Closures.size() - 1];
assert(ACE);
auto &Diags = Ctx.Diags;
// If this is an "implicit self" expr from the RHS of a shorthand
// condition like `guard let self` or `if let self`, then this is
// always allowed and we shouldn't run any diagnostics.
if (UnwrapStmtImplicitSelfExprs.count(E)) {
return Action::Continue(E);
}
SourceLoc memberLoc = SourceLoc();
const DeclRefExpr *selfDRE = nullptr;
if (auto *MRE = dyn_cast<MemberRefExpr>(E))
if (!selfDeclAllowsImplicitSelf(MRE->getBase(), ACE)) {
selfDRE = dyn_cast_or_null<DeclRefExpr>(MRE->getBase());
auto baseName = MRE->getMember().getDecl()->getBaseName();
memberLoc = MRE->getLoc();
Diags
.diagnose(memberLoc,
diag::property_use_in_closure_without_explicit_self,
baseName.getIdentifier())
.warnUntilSwiftVersionIf(
invalidImplicitSelfShouldOnlyWarn510(MRE->getBase(), ACE), 6);
}
// Handle method calls with a specific diagnostic + fixit.
if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(E))
if (!selfDeclAllowsImplicitSelf(DSCE->getBase(), ACE) &&
isa<DeclRefExpr>(DSCE->getFn())) {
selfDRE = dyn_cast_or_null<DeclRefExpr>(DSCE->getBase());
auto MethodExpr = cast<DeclRefExpr>(DSCE->getFn());
memberLoc = DSCE->getLoc();
Diags
.diagnose(DSCE->getLoc(),
diag::method_call_in_closure_without_explicit_self,
MethodExpr->getDecl()->getBaseIdentifier())
.warnUntilSwiftVersionIf(
invalidImplicitSelfShouldOnlyWarn510(DSCE->getBase(), ACE),
6);
}
if (memberLoc.isValid()) {
const AbstractClosureExpr *parentDisallowingImplicitSelf = nullptr;
if (Ctx.isSwiftVersionAtLeast(6) && selfDRE && selfDRE->getDecl()) {
parentDisallowingImplicitSelf = parentClosureDisallowingImplicitSelf(
selfDRE->getDecl(), selfDRE->getType(), ACE);
}
emitFixIts(Diags, memberLoc, parentDisallowingImplicitSelf, ACE);
return Action::SkipNode(E);
}
if (!selfDeclAllowsImplicitSelf(E, ACE)) {
Diags.diagnose(E->getLoc(), diag::implicit_use_of_self_in_closure)
.warnUntilSwiftVersionIf(
invalidImplicitSelfShouldOnlyWarn510(E, ACE), 6);
}
return Action::Continue(E);
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
auto *ACE = dyn_cast<AbstractClosureExpr>(E);
if (!ACE) {
return Action::Continue(E);
}
if (shouldRecordClosure(ACE)) {
assert(Closures.size() > 0);
Closures.pop_back();
}
return Action::Continue(E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
/// Conditions like `if let self` or `guard let self`
/// have an RHS 'self' decl that is implicit, but this is not
/// the sort of "implicit self" decl that should trigger
/// these diagnostics. Track these DREs in a list so we can
/// avoid running diagnostics on them when we see them later.
// FIXME: avoid special casing?
auto conditionalStmt = dyn_cast<LabeledConditionalStmt>(S);
if (!conditionalStmt) {
return Action::Continue(S);
}
for (auto cond : conditionalStmt->getCond()) {
if (cond.getKind() != StmtConditionElement::CK_PatternBinding) {
continue;
}
if (auto OSP = dyn_cast<OptionalSomePattern>(cond.getPattern())) {
if (OSP->getSubPattern()->getBoundName() != Ctx.Id_self) {
continue;
}
auto E = cond.getInitializer();
// Peer through any implicit conversions like a LoadExpr
if (auto *ICE = dyn_cast<ImplicitConversionExpr>(E)) {
E = ICE->getSubExpr();
}
if (isImplicitSelf(E)) {
UnwrapStmtImplicitSelfExprs.insert(E);
}
}
}
return Action::Continue(S);
}
/// Emit any fix-its for this error.
void emitFixIts(DiagnosticEngine &Diags, SourceLoc memberLoc,
const AbstractClosureExpr *parentDisallowingImplicitSelf,
const AbstractClosureExpr *ACE) {
// These fix-its have to be diagnosed on the closure that requires,
// but is currently missing, self qualification. It's possible that
// ACE doesn't require self qualification (e.g. because it's
// non-escaping) but is nested inside a closure that does require self
// qualification. In that case we have to emit the fixit for the parent
// closure.
// - Even if this closure requires self qualification, if there's an
// invalid parent we emit the diagnostic on that parent first.
// To enable implicit self you'd have to fix the parent anyway.
// This lets us avoid bogus diagnostics on this closure when
// it's actually _just_ the parent that's invalid.
auto closureForDiagnostics = ACE;
if (parentDisallowingImplicitSelf) {
// Don't do this for escaping autoclosures, which are never allowed
// to use implicit self, even after fixing any invalid parents.
auto isEscapingAutoclosure =
isa<AutoClosureExpr>(ACE) &&
isClosureRequiringSelfQualification(ACE);
if (!isEscapingAutoclosure) {
closureForDiagnostics = parentDisallowingImplicitSelf;
}
}
// This error can be fixed by either capturing self explicitly (if in an
// explicit closure), or referencing self explicitly.
if (auto *CE = dyn_cast<const ClosureExpr>(closureForDiagnostics)) {
if (diagnoseAlmostMatchingCaptures(Diags, memberLoc, CE)) {
// Bail on the rest of the diagnostics. Offering the option to
// capture 'self' explicitly will result in an error, and using
// 'self.' explicitly will be accessing something other than the
// self param.
return;
}
emitFixItsForExplicitClosure(Diags, memberLoc, CE);
} else {
// If this wasn't an explicit closure, just offer the fix-it to
// reference self explicitly.
Diags.diagnose(memberLoc, diag::note_reference_self_explicitly)
.fixItInsert(memberLoc, "self.");
}
}
/// Diagnose any captures which might have been an attempt to capture
/// \c self strongly, but do not actually enable implicit \c self. Returns
/// whether there were any such captures to diagnose.
bool diagnoseAlmostMatchingCaptures(DiagnosticEngine &Diags,
SourceLoc memberLoc,
const ClosureExpr *closureExpr) {
// If we've already captured something with the name "self" other than
// the actual self param, offer special diagnostics.
if (auto *VD = closureExpr->getCapturedSelfDecl()) {
if (!VD->getInterfaceType()->is<WeakStorageType>()) {
Diags.diagnose(VD->getLoc(), diag::note_other_self_capture);
}
return true;
}
return false;
}
/// Emit fix-its for invalid use of implicit \c self in an explicit closure.
/// The error can be solved by capturing self explicitly,
/// or by using \c self. explicitly.
void emitFixItsForExplicitClosure(DiagnosticEngine &Diags,
SourceLoc memberLoc,
const ClosureExpr *closureExpr) {
Diags.diagnose(memberLoc, diag::note_reference_self_explicitly)
.fixItInsert(memberLoc, "self.");
auto diag = Diags.diagnose(closureExpr->getLoc(),
diag::note_capture_self_explicitly);
// There are four different potential fix-its to offer based on the
// closure signature:
// 1. There is an existing capture list which already has some
// entries. We need to insert 'self' into the capture list along
// with a separating comma.
// 2. There is an existing capture list, but it is empty (just '[]').
// We can just insert 'self'.
// 3. Arguments or types are already specified in the signature,
// but there is no existing capture list. We will need to insert
// the capture list, but 'in' will already be present.
// 4. The signature empty so far. We must insert the full capture
// list as well as 'in'.
const auto brackets = closureExpr->getBracketRange();
if (brackets.isValid()) {
emitInsertSelfIntoCaptureListFixIt(brackets, diag);
}
else {
emitInsertNewCaptureListFixIt(closureExpr, diag);
}
}
/// Emit a fix-it for inserting \c self into in existing capture list, along
/// with a trailing comma if needed. The fix-it will be attached to the
/// provided diagnostic \c diag.
void emitInsertSelfIntoCaptureListFixIt(SourceRange brackets,
InFlightDiagnostic &diag) {
// Look for any non-comment token. If there's anything before the
// closing bracket, we assume that it is a valid capture list entry and
// insert 'self,'. If it wasn't a valid entry, then we will at least not
// be introducing any new errors/warnings...
const auto locAfterBracket = brackets.Start.getAdvancedLoc(1);
const auto nextAfterBracket = Lexer::getTokenAtLocation(
Ctx.SourceMgr, locAfterBracket, CommentRetentionMode::None);
if (nextAfterBracket.getLoc() != brackets.End)
diag.fixItInsertAfter(brackets.Start, "self, ");
else
diag.fixItInsertAfter(brackets.Start, "self");
}
/// Emit a fix-it for inserting a capture list into a closure that does not
/// already have one, along with a trailing \c in if necessary. The fix-it
/// will be attached to the provided diagnostic \c diag.
void emitInsertNewCaptureListFixIt(const ClosureExpr *closureExpr,
InFlightDiagnostic &diag) {
if (closureExpr->getInLoc().isValid()) {
diag.fixItInsertAfter(closureExpr->getLoc(), " [self]");
return;
}
// If there's a (non-comment) token immediately following the
// opening brace of the closure, we may need to pad the fix-it
// with a space.
const auto nextLoc = closureExpr->getLoc().getAdvancedLoc(1);
const auto next =
Lexer::getTokenAtLocation(Ctx.SourceMgr, nextLoc,
CommentRetentionMode::None);
std::string trailing = next.getLoc() == nextLoc ? " " : "";
diag.fixItInsertAfter(closureExpr->getLoc(), " [self] in" + trailing);
}
/// Whether or not this invalid usage of implicit self should be a warning
/// in Swift 5 mode, to preserve source compatibility.
bool invalidImplicitSelfShouldOnlyWarn510(Expr *selfRef,
AbstractClosureExpr *ACE) {
auto DRE = dyn_cast_or_null<DeclRefExpr>(selfRef);
if (!DRE)
return false;
auto selfDecl = dyn_cast_or_null<VarDecl>(DRE->getDecl());
if (!selfDecl)
return false;
// If this implicit self decl is from a closure that captured self
// weakly, then we should always emit an error, since implicit self was
// only allowed starting in Swift 5.8 and later.
if (closureHasWeakSelfCapture(ACE)) {
// Implicit self was incorrectly permitted for weak self captures
// in non-escaping closures in Swift 5.7, so in that case we can
// only warn until Swift 6.
return !isClosureRequiringSelfQualification(ACE,
/*ignoreWeakSelf*/ true);
}
return !selfDecl->isSelfParameter();
}
};
auto &ctx = DC->getASTContext();
AbstractClosureExpr *ACE = nullptr;
if (DC->isLocalContext()) {
while (DC->getParent()->isLocalContext() && !ACE) {
if (auto *closure = dyn_cast<AbstractClosureExpr>(DC))
if (DiagnoseWalker::isClosureRequiringSelfQualification(closure))
ACE = const_cast<AbstractClosureExpr *>(closure);
DC = DC->getParent();
}
}
const_cast<Expr *>(E)->walk(DiagnoseWalker(ctx, ACE));
}
bool TypeChecker::getDefaultGenericArgumentsString(
SmallVectorImpl<char> &buf,
const swift::GenericTypeDecl *typeDecl,
llvm::function_ref<Type(const GenericTypeParamDecl *)> getPreferredType) {
llvm::raw_svector_ostream genericParamText{buf};
genericParamText << "<";
auto printGenericParamSummary =
[&](GenericTypeParamType *genericParamTy) {
const GenericTypeParamDecl *genericParam = genericParamTy->getDecl();
if (Type result = getPreferredType(genericParam)) {
result.print(genericParamText);
return;
}
auto genericSig = typeDecl->getGenericSignature();
auto concreteTy = genericSig->getConcreteType(genericParamTy);
if (concreteTy) {
genericParamText << concreteTy;
return;
}
auto upperBound = genericSig->getUpperBound(
genericParamTy,
/*forExistentialSelf=*/false,
/*withParameterizedProtocols=*/false);
if (upperBound->isObjCExistentialType() || upperBound->isAny()) {
genericParamText << upperBound;
return;
}
genericParamText << "<#" << genericParam->getName() << ": ";
genericParamText << upperBound << "#>";
};
llvm::interleave(typeDecl->getInnermostGenericParamTypes(),
printGenericParamSummary,
[&] { genericParamText << ", "; });
genericParamText << ">";
return true;
}
/// Diagnose an argument labeling issue, returning true if we successfully
/// diagnosed the issue.
bool swift::diagnoseArgumentLabelError(ASTContext &ctx,
const ArgumentList *argList,
ArrayRef<Identifier> newNames,
ParameterContext paramContext,
InFlightDiagnostic *existingDiag) {
std::optional<InFlightDiagnostic> diagOpt;
auto getDiag = [&]() -> InFlightDiagnostic & {
if (existingDiag)
return *existingDiag;
return *diagOpt;
};
auto &diags = ctx.Diags;
argList = argList->getOriginalArgs();
// Figure out how many extraneous, missing, and wrong labels are in
// the call.
unsigned numExtra = 0, numMissing = 0, numWrong = 0;
unsigned n = std::max(argList->size(), (unsigned)newNames.size());
llvm::SmallString<16> missingBuffer;
llvm::SmallString<16> extraBuffer;
for (unsigned i = 0; i != n; ++i) {
// oldName and newName are
// - None if i is out of bounds for the argument list
// - nullptr for an argument without a label
// - have a value if the argument has a label
std::optional<Identifier> oldName;
if (i < argList->size())
oldName = argList->getLabel(i);
std::optional<Identifier> newName;
if (i < newNames.size())
newName = newNames[i];
assert(oldName || newName && "We can't have oldName and newName out of "
"bounds, otherwise n would be smaller");
if (oldName == newName || argList->isUnlabeledTrailingClosureIndex(i))
continue;
if (!oldName.has_value() && newName.has_value()) {
++numMissing;
missingBuffer += newName->str();
missingBuffer += ':';
} else if (oldName.has_value() && !newName.has_value()) {
++numExtra;
extraBuffer += oldName->str();
extraBuffer += ':';
} else if (oldName->empty()) {
// In the cases from here onwards oldValue and newValue are not null
++numMissing;
missingBuffer += newName->str();
missingBuffer += ":";
} else if (newName->empty()) {
++numExtra;
extraBuffer += oldName->str();
extraBuffer += ':';
} else {
++numWrong;
}
}
// Emit the diagnostic.
assert(numMissing > 0 || numExtra > 0 || numWrong > 0);
llvm::SmallString<16> haveBuffer; // note: diagOpt has references to this
llvm::SmallString<16> expectedBuffer; // note: diagOpt has references to this
// If we had any wrong labels, or we have both missing and extra labels,
// emit the catch-all "wrong labels" diagnostic.
if (!existingDiag) {
bool plural = (numMissing + numExtra + numWrong) > 1;
if (numWrong > 0 || (numMissing > 0 && numExtra > 0)) {
for (unsigned i = 0, n = argList->size(); i != n; ++i) {
auto haveName = argList->getLabel(i);
if (haveName.empty())
haveBuffer += '_';
else
haveBuffer += haveName.str();
haveBuffer += ':';
}
for (auto expected : newNames) {
if (expected.empty())
expectedBuffer += '_';
else
expectedBuffer += expected.str();
expectedBuffer += ':';
}
StringRef haveStr = haveBuffer;
StringRef expectedStr = expectedBuffer;
diagOpt.emplace(diags.diagnose(argList->getLoc(),
diag::wrong_argument_labels,
plural, haveStr, expectedStr,
static_cast<unsigned>(paramContext)));
} else if (numMissing > 0) {
StringRef missingStr = missingBuffer;
diagOpt.emplace(diags.diagnose(argList->getLoc(),
diag::missing_argument_labels,
plural, missingStr,
static_cast<unsigned>(paramContext)));
} else {
assert(numExtra > 0);
StringRef extraStr = extraBuffer;
diagOpt.emplace(diags.diagnose(argList->getLoc(),
diag::extra_argument_labels,
plural, extraStr,
static_cast<unsigned>(paramContext)));
}
}
// Emit Fix-Its to correct the names.
auto &diag = getDiag();
for (unsigned i = 0, n = argList->size(); i != n; ++i) {
Identifier oldName = argList->getLabel(i);
Identifier newName;
if (i < newNames.size())
newName = newNames[i];
if (oldName == newName || argList->isUnlabeledTrailingClosureIndex(i))
continue;
if (newName.empty()) {
// If this is a labeled trailing closure, we need to replace with '_'.
if (argList->isLabeledTrailingClosureIndex(i)) {
diag.fixItReplace(argList->getLabelLoc(i), "_");
continue;
}
// Otherwise, delete the old name.
diag.fixItRemoveChars(argList->getLabelLoc(i),
argList->getExpr(i)->getStartLoc());
continue;
}
bool newNameIsReserved = !canBeArgumentLabel(newName.str());
llvm::SmallString<16> newStr;
if (newNameIsReserved)
newStr += "`";
newStr += newName.str();
if (newNameIsReserved)
newStr += "`";
// If the argument was previously unlabeled, insert the new label. Note that
// we don't do this for labeled trailing closures as they write unlabeled
// args as '_:', and therefore need replacement.
if (oldName.empty() && !argList->isLabeledTrailingClosureIndex(i)) {
// Insert the name.
newStr += ": ";
diag.fixItInsert(argList->getExpr(i)->getStartLoc(), newStr);
continue;
}
// Change the name.
diag.fixItReplace(argList->getLabelLoc(i), newStr);
}
// If the diagnostic is local, flush it before returning.
// This makes sure it's emitted before the message text buffers are destroyed.
diagOpt.reset();
return true;
}
static const Expr *lookThroughExprsToImmediateDeallocation(const Expr *E) {
// Look through various expressions that don't affect the fact that the user
// will be assigning a class instance that will be immediately deallocated.
while (true) {
E = E->getValueProvidingExpr();
// We don't currently deal with tuple destructuring.
if (isa<DestructureTupleExpr>(E))
return E;
// If we have a TupleElementExpr with a child TupleExpr, dig into that
// element.
if (auto *TEE = dyn_cast<TupleElementExpr>(E)) {
auto *subExpr = lookThroughExprsToImmediateDeallocation(TEE->getBase());
if (auto *TE = dyn_cast<TupleExpr>(subExpr)) {
auto *element = TE->getElements()[TEE->getFieldNumber()];
return lookThroughExprsToImmediateDeallocation(element);
}
return subExpr;
}
if (auto *ICE = dyn_cast<ImplicitConversionExpr>(E)) {
E = ICE->getSubExpr();
continue;
}
if (auto *CE = dyn_cast<CoerceExpr>(E)) {
E = CE->getSubExpr();
continue;
}
if (auto *OEE = dyn_cast<OpenExistentialExpr>(E)) {
E = OEE->getSubExpr();
continue;
}
// Look through optional evaluations, we still want to diagnose on
// things like initializers called through optional chaining and the
// unwrapping of failable initializers.
if (auto *OEE = dyn_cast<OptionalEvaluationExpr>(E)) {
E = OEE->getSubExpr();
continue;
}
if (auto *OBE = dyn_cast<BindOptionalExpr>(E)) {
E = OBE->getSubExpr();
continue;
}
if (auto *FOE = dyn_cast<ForceValueExpr>(E)) {
E = FOE->getSubExpr();
continue;
}
if (auto *ATE = dyn_cast<AnyTryExpr>(E)) {
E = ATE->getSubExpr();
continue;
}
if (auto *DSBIE = dyn_cast<DotSyntaxBaseIgnoredExpr>(E)) {
E = DSBIE->getRHS();
continue;
}
return E;
}
}
static void diagnoseUnownedImmediateDeallocationImpl(ASTContext &ctx,
const VarDecl *varDecl,
const Expr *initExpr,
SourceLoc diagLoc,
SourceRange diagRange) {
auto *ownershipAttr =
varDecl->getAttrs().getAttribute<ReferenceOwnershipAttr>();
if (!ownershipAttr || ownershipAttr->isInvalid())
return;
// Only diagnose for non-owning ownerships such as 'weak' and 'unowned'.
// Zero is the default/strong ownership strength.
if (ReferenceOwnership::Strong == ownershipAttr->get() ||
isLessStrongThan(ReferenceOwnership::Strong, ownershipAttr->get()))
return;
// Try to find a call to a constructor.
initExpr = lookThroughExprsToImmediateDeallocation(initExpr);
auto *CE = dyn_cast<CallExpr>(initExpr);
if (!CE)
return;
auto *CRCE = dyn_cast<ConstructorRefCallExpr>(CE->getFn());
if (!CRCE)
return;
auto *DRE = dyn_cast<DeclRefExpr>(CRCE->getFn());
if (!DRE)
return;
auto *constructorDecl = dyn_cast<ConstructorDecl>(DRE->getDecl());
if (!constructorDecl)
return;
// Make sure the constructor constructs an instance that allows ownership.
// This is to ensure we don't diagnose on constructors such as
// Optional.init(nilLiteral:).
auto selfType = constructorDecl->getDeclContext()->getSelfTypeInContext();
if (!selfType->allowsOwnership())
return;
// This must stay in sync with
// diag::unowned_assignment_immediate_deallocation.
enum {
SK_Variable = 0,
SK_Property
} storageKind = SK_Variable;
if (varDecl->getDeclContext()->isTypeContext())
storageKind = SK_Property;
// TODO: The DiagnoseLifetimeIssuesPass prints a similar warning in this
// situation. We should only print one warning.
ctx.Diags.diagnose(diagLoc, diag::unowned_assignment_immediate_deallocation,
varDecl->getName(), ownershipAttr->get(),
unsigned(storageKind))
.highlight(diagRange);
ctx.Diags.diagnose(diagLoc, diag::unowned_assignment_requires_strong)
.highlight(diagRange);
ctx.Diags.diagnose(varDecl, diag::decl_declared_here, varDecl);
}
void swift::diagnoseUnownedImmediateDeallocation(ASTContext &ctx,
const AssignExpr *assignExpr) {
auto *destExpr = assignExpr->getDest()->getValueProvidingExpr();
auto *initExpr = assignExpr->getSrc();
// Try to find a referenced VarDecl.
const VarDecl *VD = nullptr;
if (auto *DRE = dyn_cast<DeclRefExpr>(destExpr)) {
VD = dyn_cast<VarDecl>(DRE->getDecl());
} else if (auto *MRE = dyn_cast<MemberRefExpr>(destExpr)) {
VD = dyn_cast<VarDecl>(MRE->getMember().getDecl());
}
if (VD)
diagnoseUnownedImmediateDeallocationImpl(ctx, VD, initExpr,
assignExpr->getLoc(),
initExpr->getSourceRange());
}
void swift::diagnoseUnownedImmediateDeallocation(ASTContext &ctx,
const Pattern *pattern,
SourceLoc equalLoc,
const Expr *initExpr) {
pattern = pattern->getSemanticsProvidingPattern();
if (auto *TP = dyn_cast<TuplePattern>(pattern)) {
initExpr = lookThroughExprsToImmediateDeallocation(initExpr);
// If we've found a matching tuple initializer with the same number of
// elements as our pattern, diagnose each element individually.
auto TE = dyn_cast<TupleExpr>(initExpr);
if (TE && TE->getNumElements() == TP->getNumElements()) {
for (unsigned i = 0, e = TP->getNumElements(); i != e; ++i) {
const TuplePatternElt &elt = TP->getElement(i);
const Pattern *subPattern = elt.getPattern();
Expr *subInitExpr = TE->getElement(i);
diagnoseUnownedImmediateDeallocation(ctx, subPattern, equalLoc,
subInitExpr);
}
}
} else if (auto *NP = dyn_cast<NamedPattern>(pattern)) {
diagnoseUnownedImmediateDeallocationImpl(ctx, NP->getDecl(), initExpr,
equalLoc,
initExpr->getSourceRange());
}
}
namespace {
enum NoteKind_t {
FixItReplace,
FixItInsert,
};
static bool fixItOverrideDeclarationTypesImpl(
ValueDecl *decl, const ValueDecl *base,
SmallVectorImpl<std::tuple<NoteKind_t, SourceRange, std::string>> ¬es) {
// For now, just rewrite cases where the base uses a value type and the
// override uses a reference type, and the value type is bridged to the
// reference type. This is a way to migrate code that makes use of types
// that previously were not bridged to value types.
auto checkValueReferenceType =
[&](Type overrideTy, ParamDecl::Specifier overrideSpec,
Type baseTy, ParamDecl::Specifier baseSpec,
SourceRange typeRange) -> bool {
if (typeRange.isInvalid())
return false;
auto normalizeType = [](Type &ty, ParamDecl::Specifier spec) -> Type {
Type normalizedTy = ty;
if (Type unwrappedTy = normalizedTy->getOptionalObjectType())
normalizedTy = unwrappedTy;
if (spec == ParamDecl::Specifier::InOut)
ty = InOutType::get(ty);
return normalizedTy;
};
// Is the base type bridged?
Type normalizedBaseTy = normalizeType(baseTy, baseSpec);
const DeclContext *DC = decl->getDeclContext();
ASTContext &ctx = decl->getASTContext();
// ...and just knowing that it's bridged isn't good enough if we don't
// know what it's bridged /to/. Also, don't do this check for trivial
// bridging---that doesn't count.
Type bridged;
if (normalizedBaseTy->isAny()) {
bridged = ctx.getAnyObjectType();
} else {
bridged = ctx.getBridgedToObjC(DC, normalizedBaseTy);
}
if (!bridged || bridged->isEqual(normalizedBaseTy))
return false;
// ...and is it bridged to the overridden type?
Type normalizedOverrideTy = normalizeType(overrideTy, overrideSpec);
if (!bridged->isEqual(normalizedOverrideTy)) {
// If both are nominal types, check again, ignoring generic arguments.
auto *overrideNominal = normalizedOverrideTy->getAnyNominal();
if (!overrideNominal || bridged->getAnyNominal() != overrideNominal) {
return false;
}
}
Type newOverrideTy = baseTy;
// Preserve optionality if we're dealing with a simple type.
if (Type unwrappedTy = newOverrideTy->getOptionalObjectType())
newOverrideTy = unwrappedTy;
if (overrideTy->getOptionalObjectType())
newOverrideTy = OptionalType::get(newOverrideTy);
SmallString<32> baseTypeBuf;
llvm::raw_svector_ostream baseTypeStr(baseTypeBuf);
PrintOptions options;
options.SynthesizeSugarOnTypes = true;
newOverrideTy->print(baseTypeStr, options);
notes.emplace_back(FixItReplace, typeRange, baseTypeStr.str().str());
return true;
};
// Check if overriding fails because we lack @escaping attribute on the function
// type repr.
auto checkTypeMissingEscaping = [&](Type overrideTy, Type baseTy,
SourceRange typeRange) -> bool {
// Fix-it needs position to apply.
if (typeRange.isInvalid())
return false;
auto overrideFnTy = overrideTy->getAs<AnyFunctionType>();
auto baseFnTy = baseTy->getAs<AnyFunctionType>();
// Both types should be function.
if (overrideFnTy && baseFnTy &&
// The overriding function type should be no escaping.
overrideFnTy->getExtInfo().isNoEscape() &&
// The overridden function type should be escaping.
!baseFnTy->getExtInfo().isNoEscape()) {
notes.emplace_back(FixItInsert, typeRange, "@escaping ");
return true;
}
return false;
};
auto checkType = [&](Type overrideTy, ParamDecl::Specifier overrideSpec,
Type baseTy, ParamDecl::Specifier baseSpec,
SourceRange typeRange) -> bool {
return checkValueReferenceType(overrideTy, overrideSpec,
baseTy, baseSpec, typeRange) ||
checkTypeMissingEscaping(overrideTy, baseTy, typeRange);
};
if (auto *param = dyn_cast<ParamDecl>(decl)) {
SourceRange typeRange = param->getTypeSourceRangeForDiagnostics();
auto *baseParam = cast<ParamDecl>(base);
return checkType(param->getInterfaceType(), param->getSpecifier(),
baseParam->getInterfaceType(), baseParam->getSpecifier(),
typeRange);
}
if (auto *var = dyn_cast<VarDecl>(decl)) {
SourceRange typeRange = var->getTypeSourceRangeForDiagnostics();
auto *baseVar = cast<VarDecl>(base);
return checkType(var->getInterfaceType(), ParamDecl::Specifier::Default,
baseVar->getInterfaceType(), ParamDecl::Specifier::Default,
typeRange);
}
if (auto *fn = dyn_cast<AbstractFunctionDecl>(decl)) {
auto *baseFn = cast<AbstractFunctionDecl>(base);
bool fixedAny = false;
if (fn->getParameters()->size() ==
baseFn->getParameters()->size()) {
for_each(*fn->getParameters(),
*baseFn->getParameters(),
[&](ParamDecl *param, const ParamDecl *baseParam) {
fixedAny |= fixItOverrideDeclarationTypesImpl(param, baseParam, notes);
});
}
if (auto *method = dyn_cast<FuncDecl>(decl)) {
auto resultType = method->mapTypeIntoContext(
method->getResultInterfaceType());
auto *baseMethod = cast<FuncDecl>(base);
auto baseResultType = baseMethod->mapTypeIntoContext(
baseMethod->getResultInterfaceType());
fixedAny |= checkType(resultType, ParamDecl::Specifier::Default,
baseResultType, ParamDecl::Specifier::Default,
method->getResultTypeSourceRange());
}
return fixedAny;
}
if (auto *subscript = dyn_cast<SubscriptDecl>(decl)) {
auto *baseSubscript = cast<SubscriptDecl>(base);
bool fixedAny = false;
if (subscript->getIndices()->size() ==
baseSubscript->getIndices()->size()) {
for_each(*subscript->getIndices(),
*baseSubscript->getIndices(),
[&](ParamDecl *param, const ParamDecl *baseParam) {
fixedAny |= fixItOverrideDeclarationTypesImpl(param, baseParam, notes);
});
}
auto resultType =
subscript->mapTypeIntoContext(subscript->getElementInterfaceType());
auto baseResultType = baseSubscript->mapTypeIntoContext(
baseSubscript->getElementInterfaceType());
fixedAny |= checkType(resultType, ParamDecl::Specifier::Default,
baseResultType, ParamDecl::Specifier::Default,
subscript->getElementTypeSourceRange());
return fixedAny;
}
llvm_unreachable("unknown overridable member");
}
}
bool swift::computeFixitsForOverriddenDeclaration(
ValueDecl *decl, const ValueDecl *base,
llvm::function_ref<std::optional<InFlightDiagnostic>(bool)> diag) {
SmallVector<std::tuple<NoteKind_t, SourceRange, std::string>, 4> Notes;
bool hasNotes = ::fixItOverrideDeclarationTypesImpl(decl, base, Notes);
std::optional<InFlightDiagnostic> diagnostic = diag(hasNotes);
if (!diagnostic) return hasNotes;
for (const auto ¬e : Notes) {
if (std::get<0>(note) == FixItReplace) {
diagnostic->fixItReplace(std::get<1>(note), std::get<2>(note));
} else {
diagnostic->fixItInsert(std::get<1>(note).Start, std::get<2>(note));
}
}
return hasNotes;
}
//===----------------------------------------------------------------------===//
// Per func/init diagnostics
//===----------------------------------------------------------------------===//
namespace {
class VarDeclUsageChecker : public ASTWalker {
DeclContext *DC;
DiagnosticEngine &Diags;
// Keep track of some information about a variable.
enum {
RK_Defined = 1, ///< Whether it was ever defined in this scope.
RK_Read = 2, ///< Whether it was ever read.
RK_Written = 4, ///< Whether it was ever written or passed inout.
RK_CaptureList = 8 ///< Var is an entry in a capture list.
};
/// These are all of the variables that we are tracking. VarDecls get added
/// to this when the declaration is seen. We use a MapVector to keep the
/// diagnostics emission in deterministic order.
llvm::SmallMapVector<VarDecl*, unsigned, 32> VarDecls;
/// This is a mapping from an OpaqueValue to the expression that initialized
/// it.
llvm::SmallDenseMap<OpaqueValueExpr *, Expr *> OpaqueValueMap;
/// The first reference to the given property.
llvm::SmallDenseMap<VarDecl *, Expr *> AssociatedGetterRefExpr;
/// This is a mapping from VarDecls to the if/while/guard statement that they
/// occur in, when they are in a pattern in a StmtCondition.
llvm::SmallDenseMap<VarDecl*, LabeledConditionalStmt*> StmtConditionForVD;
#ifndef NDEBUG
llvm::SmallPtrSet<Expr*, 32> AllExprsSeen;
#endif
bool sawError = false;
VarDeclUsageChecker(const VarDeclUsageChecker &) = delete;
void operator=(const VarDeclUsageChecker &) = delete;
public:
VarDeclUsageChecker(DeclContext *DC,
DiagnosticEngine &Diags) : DC(DC), Diags(Diags) {}
// After we have scanned the entire region, diagnose variables that could be
// declared with a narrower usage kind.
~VarDeclUsageChecker() override;
/// Check to see if the specified VarDecl is part of a larger
/// PatternBindingDecl, where some other bound variable was mutated. In this
/// case we don't want to generate a "variable never mutated" warning, because
/// it would require splitting up the destructuring of the tuple, which is
/// more code turmoil than the warning is worth.
bool isVarDeclPartOfPBDThatHadSomeMutation(VarDecl *VD) {
auto *PBD = VD->getParentPatternBinding();
if (!PBD) return false;
bool sawMutation = false;
for (auto idx : range(PBD->getNumPatternEntries())) {
PBD->getPattern(idx)->forEachVariable([&](VarDecl *VD) {
auto it = VarDecls.find(VD);
sawMutation |= it != VarDecls.end() && (it->second & RK_Written);
});
}
return sawMutation;
}
bool shouldTrackVarDecl(VarDecl *VD) {
// If the variable is implicit, ignore it.
if (VD->isImplicit() || VD->getLoc().isInvalid())
return false;
// If the variable is computed, ignore it.
if (!VD->hasStorage())
return false;
// If the variable was invalid, ignore it and notice that the code is
// malformed.
if (VD->isInvalid()) {
sawError = true;
return false;
}
// If the variable is already unnamed, ignore it.
if (!VD->hasName() || VD->getName().str() == "_")
return false;
return true;
}
void addMark(Decl *D, unsigned Flag) {
auto *vd = dyn_cast<VarDecl>(D);
if (!vd) return;
VarDecls[vd] |= Flag;
}
void markBaseOfStorageUse(Expr *E, ConcreteDeclRef decl, unsigned flags);
void markBaseOfStorageUse(Expr *E, bool isMutating);
void markStoredOrInOutExpr(Expr *E, unsigned Flags);
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
// We generally walk into declarations, other than types and nested functions.
// FIXME: peek into capture lists of nested functions.
PreWalkAction walkToDeclPre(Decl *D) override {
if (isa<TypeDecl>(D))
return Action::SkipNode();
// The body of #if clauses are not walked into, we need custom processing
// for them.
if (auto *ICD = dyn_cast<IfConfigDecl>(D))
handleIfConfig(ICD);
// If this is a VarDecl, then add it to our list of things to track.
if (auto *vd = dyn_cast<VarDecl>(D)) {
if (shouldTrackVarDecl(vd)) {
unsigned flags = RK_Defined;
if (vd->isCaptureList())
flags |= RK_CaptureList;
if (auto childVd = vd->getCorrespondingCaseBodyVariable()) {
// Child vars are never in capture lists.
assert(flags == RK_Defined);
addMark(childVd.get(), flags);
}
addMark(vd, flags);
}
}
// Don't walk into implicit accessors, since eg. an observer's setter
// references the variable, but we don't want to consider it as a real
// "use".
if (isa<AccessorDecl>(D) && D->isImplicit())
return Action::SkipNode();
if (auto *afd = dyn_cast<AbstractFunctionDecl>(D)) {
// If this AFD is a setter, track the parameter and the getter for
// the containing property so if newValue isn't used but the getter is used
// an error can be reported.
if (auto FD = dyn_cast<AccessorDecl>(afd)) {
if (FD->getAccessorKind() == AccessorKind::Set) {
if (isa<VarDecl>(FD->getStorage())) {
auto arguments = FD->getParameters();
VarDecls[arguments->get(0)] = RK_Defined;
}
}
}
if (afd->isBodyTypeChecked())
return Action::Continue();
// Don't walk into a body that has not yet been type checked. This should
// only occur for top-level code.
VarDecls.clear();
return Action::SkipNode();
}
if (auto *TLCD = dyn_cast<TopLevelCodeDecl>(D)) {
// If this is a TopLevelCodeDecl, scan for global variables
auto *body = TLCD->getBody();
for (auto node : body->getElements()) {
if (node.is<Decl *>()) {
// Flag all variables in a PatternBindingDecl
Decl *D = node.get<Decl *>();
auto *PBD = dyn_cast<PatternBindingDecl>(D);
if (!PBD) continue;
for (auto idx : range(PBD->getNumPatternEntries())) {
PBD->getPattern(idx)->forEachVariable([&](VarDecl *VD) {
VarDecls[VD] = RK_Read|RK_Written|RK_Defined;
});
}
} else if (node.is<Stmt *>()) {
// Flag all variables in guard statements
Stmt *S = node.get<Stmt *>();
auto *GS = dyn_cast<GuardStmt>(S);
if (!GS) continue;
for (StmtConditionElement SCE : GS->getCond()) {
if (auto pattern = SCE.getPatternOrNull()) {
pattern->forEachVariable([&](VarDecl *VD) {
VarDecls[VD] = RK_Read|RK_Written|RK_Defined;
});
}
}
}
}
}
// Note that we ignore the initialization behavior of PatternBindingDecls,
// but we do want to walk into them, because we want to see any uses or
// other things going on in the initializer expressions.
return Action::Continue();
}
/// The heavy lifting happens when visiting expressions.
PreWalkResult<Expr *> walkToExprPre(Expr *E) override;
/// handle #if directives.
void handleIfConfig(IfConfigDecl *ICD);
/// Custom handling for statements.
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
// Keep track of an association between vardecls and the StmtCondition that
// they are bound in for IfStmt, GuardStmt, WhileStmt, etc.
if (auto LCS = dyn_cast<LabeledConditionalStmt>(S)) {
for (auto &cond : LCS->getCond()) {
if (auto pat = cond.getPatternOrNull()) {
pat->forEachVariable([&](VarDecl *VD) {
StmtConditionForVD[VD] = LCS;
});
}
}
}
// A fallthrough dest case's bound variable means the source case's
// var of the same name is read.
if (auto *fallthroughStmt = dyn_cast<FallthroughStmt>(S)) {
if (auto *sourceCase = fallthroughStmt->getFallthroughSource()) {
SmallVector<VarDecl *, 4> sourceVars;
auto sourcePattern = sourceCase->getCaseLabelItems()[0].getPattern();
sourcePattern->collectVariables(sourceVars);
auto destCase = fallthroughStmt->getFallthroughDest();
auto destPattern = destCase->getCaseLabelItems()[0].getPattern();
destPattern->forEachVariable([&](VarDecl *V) {
if (!V->hasName())
return;
for (auto *var : sourceVars) {
if (var->hasName() && var->getName() == V->getName()) {
VarDecls[var] |= RK_Read;
break;
}
}
});
}
}
// Make sure that we setup our case body variables.
if (auto *caseStmt = dyn_cast<CaseStmt>(S)) {
for (auto *vd : caseStmt->getCaseBodyVariablesOrEmptyArray()) {
VarDecls[vd] |= RK_Defined;
}
}
return Action::Continue(S);
}
};
/// An AST walker that determines the underlying type of an opaque return decl
/// from its associated function body.
class OpaqueUnderlyingTypeChecker : public ASTWalker {
using Candidate = std::tuple<Expr *, SubstitutionMap, /*isUnique=*/bool>;
using AvailabilityContext = IfStmt *;
ASTContext &Ctx;
AbstractFunctionDecl *Implementation;
OpaqueTypeDecl *OpaqueDecl;
BraceStmt *Body;
/// A set of all candidates with unique signatures.
SmallPtrSet<const void *, 4> UniqueSignatures;
/// Represents a current availability context. `nullptr` means that
/// there are no restrictions.
AvailabilityContext CurrentAvailability = nullptr;
/// All of the candidates together with their availability.
///
/// If a candidate is found in non-`if #available` context or
/// `if #available` has other dynamic conditions, it covers 'all'
/// versions and the context is set to `nullptr`.
SmallVector<std::pair<AvailabilityContext, Candidate>, 4> Candidates;
bool HasInvalidReturn = false;
public:
OpaqueUnderlyingTypeChecker(AbstractFunctionDecl *Implementation,
OpaqueTypeDecl *OpaqueDecl, BraceStmt *Body)
: Ctx(Implementation->getASTContext()), Implementation(Implementation),
OpaqueDecl(OpaqueDecl), Body(Body) {}
void check() {
Body->walk(*this);
// If given function has any invalid `return`s in the body
// let's not try to validate the types, since it wouldn't
// be accurate.
if (HasInvalidReturn)
return;
// If there are no candidates, then the body has no return statements, and
// we have nothing to infer the underlying type from.
if (Candidates.empty()) {
Implementation->diagnose(diag::opaque_type_no_underlying_type_candidates);
// We try to find if the last element of the `Body` multi element
// `BraceStmt` is an expression that produces a value that satisfies all
// the opaque type requirements and if that is the case, it means we can
// suggest a fix-it note to add an explicit `return`.
if (Body->getNumElements() > 1) {
auto element = Body->getLastElement();
// Let's see if the last statement would make for a valid return value.
if (auto expr = element.dyn_cast<Expr *>()) {
auto exprType = expr->getType();
// Function body might not be valid and we cannot reply on
// \c typeCheckStmt here to propagate HadError because its
// unreliable.
if (!exprType || exprType->hasError())
return;
bool conforms = llvm::all_of(
OpaqueDecl->getOpaqueInterfaceGenericSignature()
.getRequirements(),
[&exprType, this](auto requirement) {
if (requirement.getKind() == RequirementKind::Conformance) {
auto conformance = Implementation->getModuleContext()
->checkConformance(
exprType->getRValueType(),
requirement.getProtocolDecl(),
/*allowMissing=*/false);
return !conformance.isInvalid();
}
// If we encounter any requirements other than `Conformance`, we
// do not attempt to type check the expression.
return false;
});
// If all requirements are fulfilled, we offer to insert `return` to
// fix the issue.
if (conforms) {
Ctx.Diags
.diagnose(expr->getStartLoc(),
diag::opaque_type_missing_return_last_expr_note)
.fixItInsert(expr->getStartLoc(), "return ");
}
}
}
return;
}
if (Candidates.size() == 1) {
finalizeUnique(Candidates.front().second);
return;
}
// Check whether all of the underlying type candidates match up.
// TODO [OPAQUE SUPPORT]: diagnose multiple opaque types
// There is a single unique signature, which means that all returns
// matched.
if (llvm::count_if(Candidates, [](const auto &entry) {
const auto &candidate = entry.second;
return std::get<2>(candidate); // isUnique field.
}) == 1) {
finalizeUnique(Candidates.front().second);
return;
}
SmallVector<Candidate, 4> universallyUniqueCandidates;
for (const auto &entry : Candidates) {
AvailabilityContext availability = entry.first;
const auto &candidate = entry.second;
// Unique candidate without availability context.
if (!availability && std::get<2>(candidate))
universallyUniqueCandidates.push_back(candidate);
}
// TODO(diagnostics): Need a tailored diagnostic for this case.
if (universallyUniqueCandidates.empty()) {
Implementation->diagnose(diag::opaque_type_no_underlying_type_candidates);
return;
}
// If there is a single universally available unique candidate
// the underlying type would have to be determined at runtime
// based on the results of availability checks.
if (universallyUniqueCandidates.size() == 1) {
finalizeOpaque(universallyUniqueCandidates.front());
return;
}
// A list of all mismatches discovered across all candidates.
// If there are any mismatches in availability contexts, they
// are not diagnosed but propagated to the declaration.
std::optional<std::pair<unsigned, GenericTypeParamType *>> mismatch;
auto opaqueParams = OpaqueDecl->getOpaqueGenericParams();
SubstitutionMap underlyingSubs = std::get<1>(Candidates.front().second);
for (auto index : indices(opaqueParams)) {
auto *genericParam = opaqueParams[index];
Type underlyingType = Type(genericParam).subst(underlyingSubs);
bool found = false;
for (const auto &candidate : universallyUniqueCandidates) {
Type otherType = Type(genericParam).subst(std::get<1>(candidate));
if (!underlyingType->isEqual(otherType)) {
mismatch.emplace(index, genericParam);
found = true;
break;
}
}
if (found)
break;
}
assert(mismatch.has_value());
if (auto genericParam =
OpaqueDecl->getExplicitGenericParam(mismatch->first)) {
Implementation
->diagnose(
diag::opaque_type_mismatched_underlying_type_candidates_named,
genericParam->getName())
.highlight(genericParam->getLoc());
} else {
TypeRepr *opaqueRepr =
OpaqueDecl->getOpaqueReturnTypeReprs()[mismatch->first];
Implementation
->diagnose(diag::opaque_type_mismatched_underlying_type_candidates,
opaqueRepr)
.highlight(opaqueRepr->getSourceRange());
}
for (const auto &candidate : universallyUniqueCandidates) {
Ctx.Diags.diagnose(std::get<0>(candidate)->getLoc(),
diag::opaque_type_underlying_type_candidate_here,
Type(mismatch->second).subst(std::get<1>(candidate)));
}
}
bool isSelfReferencing(const Candidate &candidate) {
auto substitutions = std::get<1>(candidate);
// The underlying type can't be defined recursively
// in terms of the opaque type itself.
auto opaqueTypeInContext = Implementation->mapTypeIntoContext(
OpaqueDecl->getDeclaredInterfaceType());
for (auto genericParam : OpaqueDecl->getOpaqueGenericParams()) {
auto underlyingType = Type(genericParam).subst(substitutions);
auto isSelfReferencing = underlyingType.findIf(
[&](Type t) -> bool { return t->isEqual(opaqueTypeInContext); });
if (isSelfReferencing) {
Ctx.Diags.diagnose(std::get<0>(candidate)->getLoc(),
diag::opaque_type_self_referential_underlying_type,
underlyingType);
return true;
}
}
return false;
}
// A single unique underlying substitution.
void finalizeUnique(const Candidate &candidate) {
// If we have one successful candidate, then save it as the underlying
// substitutions of the opaque decl.
OpaqueDecl->setUniqueUnderlyingTypeSubstitutions(
std::get<1>(candidate).mapReplacementTypesOutOfContext());
}
// There is no clear winner here since there are candidates within
// limited availability contexts.
void finalizeOpaque(const Candidate &universallyAvailable) {
using AvailabilityCondition = OpaqueTypeDecl::AvailabilityCondition;
SmallVector<OpaqueTypeDecl::ConditionallyAvailableSubstitutions *, 4>
conditionalSubstitutions;
for (const auto &entry : Candidates) {
auto availabilityContext = entry.first;
const auto &candidate = entry.second;
if (!availabilityContext)
continue;
SmallVector<AvailabilityCondition, 4> conditions;
for (const auto &elt : availabilityContext->getCond()) {
auto condition = elt.getAvailability();
auto availabilityRange = condition->getAvailableRange();
// If there is no lower endpoint it means that the
// current platform is unrelated to this condition
// and we can ignore it.
if (!availabilityRange.hasLowerEndpoint())
continue;
conditions.push_back(
{availabilityRange, condition->isUnavailability()});
}
if (conditions.empty())
continue;
conditionalSubstitutions.push_back(
OpaqueTypeDecl::ConditionallyAvailableSubstitutions::get(
Ctx, conditions,
std::get<1>(candidate).mapReplacementTypesOutOfContext()));
}
// Add universally available choice as the last one.
conditionalSubstitutions.push_back(
OpaqueTypeDecl::ConditionallyAvailableSubstitutions::get(
Ctx, {{VersionRange::empty(), /*unavailable=*/false}},
std::get<1>(universallyAvailable)
.mapReplacementTypesOutOfContext()));
OpaqueDecl->setConditionallyAvailableSubstitutions(
conditionalSubstitutions);
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (auto underlyingToOpaque = dyn_cast<UnderlyingToOpaqueExpr>(E)) {
auto subMap = underlyingToOpaque->substitutions;
auto key = subMap.getCanonical().getOpaqueValue();
auto isUnique = UniqueSignatures.insert(key).second;
auto candidate =
std::make_tuple(underlyingToOpaque->getSubExpr(), subMap, isUnique);
if (isSelfReferencing(candidate)) {
HasInvalidReturn = true;
return Action::Stop();
}
if (subMap.hasDynamicSelf()) {
Ctx.Diags.diagnose(E->getLoc(),
diag::opaque_type_cannot_contain_dynamic_self);
HasInvalidReturn = true;
return Action::Stop();
}
Candidates.push_back({CurrentAvailability, candidate});
return Action::SkipNode(E);
}
return Action::Continue(E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
if (auto *If = dyn_cast<IfStmt>(S)) {
if (Parent.getAsStmt() != Body) {
// If this is not a top-level `if`, let's drop
// contextual information that has been set previously.
CurrentAvailability = nullptr;
return Action::Continue(S);
}
// If this is `if #(un)available` statement with no other dynamic
// conditions, let's check if it returns opaque type directly.
if (llvm::all_of(If->getCond(), [&](const auto &condition) {
return condition.getKind() == StmtConditionElement::CK_Availability;
})) {
// Check return statement directly with availability context set.
if (auto *Then = dyn_cast<BraceStmt>(If->getThenStmt())) {
llvm::SaveAndRestore<ParentTy> parent(Parent, Then);
for (auto element : Then->getElements()) {
auto *Return = getAsStmt<ReturnStmt>(element);
// If this is not a direct return statement, walk into it
// without setting contextual availability because we want
// to find all `return`s.
if (!(Return && Return->hasResult())) {
element.walk(*this);
continue;
}
// Note that we are about to walk into a return statement
// that is located in a `if #available` without any other
// conditions.
llvm::SaveAndRestore<AvailabilityContext> context(
CurrentAvailability, If);
Return->getResult()->walk(*this);
}
}
// Walk the else branch directly as well.
if (auto *Else = If->getElseStmt()) {
llvm::SaveAndRestore<ParentTy> parent(Parent, If);
Else->walk(*this);
}
return Action::SkipNode(S);
}
}
if (auto *RS = dyn_cast<ReturnStmt>(S)) {
if (RS->hasResult()) {
auto resultTy = RS->getResult()->getType();
// If expression associated with return statement doesn't have
// a type or type has an error, checking opaque types is going
// to produce incorrect diagnostics.
HasInvalidReturn |= resultTy.isNull() || resultTy->hasError();
}
}
return Action::Continue(S);
}
// Don't descend into nested decls.
PreWalkAction walkToDeclPre(Decl *D) override {
return Action::SkipNode();
}
};
class ReturnTypePlaceholderReplacer : public ASTWalker {
FuncDecl *Implementation;
BraceStmt *Body;
SmallVector<Type, 4> Candidates;
bool HasInvalidReturn = false;
public:
ReturnTypePlaceholderReplacer(FuncDecl *Implementation, BraceStmt *Body)
: Implementation(Implementation), Body(Body) {}
void check() {
auto *resultRepr = Implementation->getResultTypeRepr();
if (!resultRepr) {
return;
}
Implementation->getASTContext()
.Diags
.diagnose(resultRepr->getLoc(),
diag::placeholder_type_not_allowed_in_return_type)
.highlight(resultRepr->getSourceRange());
Body->walk(*this);
// If given function has any invalid returns in the body
// let's not try to validate the types, since it wouldn't
// be accurate.
if (HasInvalidReturn)
return;
auto writtenType = Implementation->getResultInterfaceType();
llvm::SmallPtrSet<TypeBase *, 8> seenTypes;
for (auto candidate : Candidates) {
if (!seenTypes.insert(candidate.getPointer()).second) {
continue;
}
TypeChecker::notePlaceholderReplacementTypes(writtenType, candidate);
}
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override { return Action::Continue(E); }
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
if (auto *RS = dyn_cast<ReturnStmt>(S)) {
if (RS->hasResult()) {
auto resultTy = RS->getResult()->getType();
HasInvalidReturn |= resultTy.isNull() || resultTy->hasError();
Candidates.push_back(resultTy);
}
}
return Action::Continue(S);
}
// Don't descend into nested decls.
PreWalkAction walkToDeclPre(Decl *D) override {
return Action::SkipNode();
}
};
} // end anonymous namespace
SourceLoc swift::getFixItLocForVarToLet(VarDecl *var) {
// Try to find the location of the 'var' so we can produce a fixit. If
// this is a simple PatternBinding, use its location.
if (auto *PBD = var->getParentPatternBinding()) {
if (PBD->getSingleVar() == var)
return PBD->getLoc();
} else if (auto *pattern = var->getParentPattern()) {
BindingPattern *foundVP = nullptr;
pattern->forEachNode([&](Pattern *P) {
if (auto *VP = dyn_cast<BindingPattern>(P))
if (VP->getSingleVar() == var)
foundVP = VP;
});
if (foundVP && foundVP->getIntroducer() != VarDecl::Introducer::Let) {
return foundVP->getLoc();
}
}
return SourceLoc();
}
// After we have scanned the entire region, diagnose variables that could be
// declared with a narrower usage kind.
VarDeclUsageChecker::~VarDeclUsageChecker() {
// If we saw an ErrorExpr somewhere in the body, then we have a malformed AST
// and we know stuff got dropped. Instead of producing these diagnostics,
// lets let the bigger issues get resolved first.
if (sawError)
return;
for (auto p : VarDecls) {
VarDecl *var;
unsigned access;
std::tie(var, access) = p;
// If the variable was not defined in this scope, we can safely ignore it.
if (!(access & RK_Defined))
continue;
if (auto *caseStmt =
dyn_cast_or_null<CaseStmt>(var->getRecursiveParentPatternStmt())) {
// Only diagnose VarDecls from the first CaseLabelItem in CaseStmts, as
// the remaining items must match it anyway.
auto caseItems = caseStmt->getCaseLabelItems();
assert(!caseItems.empty() &&
"If we have any case stmt var decls, we should have a case item");
if (!caseItems.front().getPattern()->containsVarDecl(var))
continue;
auto *childVar = var->getCorrespondingCaseBodyVariable().get();
access |= VarDecls[childVar];
}
// If the setter parameter is not used, but the property is read, report
// a warning. Otherwise, parameters should not generate usage warnings. It
// is common to name a parameter and not use it (e.g. because you are an
// override or want the named keyword, etc). Warning to rewrite it to _ is
// more annoying than it is useful.
if (auto param = dyn_cast<ParamDecl>(var)) {
auto FD = dyn_cast<AccessorDecl>(param->getDeclContext());
if (FD && FD->getAccessorKind() == AccessorKind::Set) {
auto VD = dyn_cast<VarDecl>(FD->getStorage());
if ((access & RK_Read) == 0) {
auto found = AssociatedGetterRefExpr.find(VD);
if (found != AssociatedGetterRefExpr.end()) {
auto *DRE = found->second;
Diags.diagnose(DRE->getLoc(), diag::unused_setter_parameter,
var->getName());
Diags.diagnose(DRE->getLoc(), diag::fixit_for_unused_setter_parameter,
var->getName())
.fixItReplace(DRE->getSourceRange(), var->getName().str());
}
}
}
continue;
}
// If this is a 'let' value, any stores to it are actually initializations,
// not mutations.
auto isWrittenLet = false;
if (var->isLet()) {
isWrittenLet = (access & RK_Written) != 0;
access &= ~RK_Written;
}
// If this variable has WeakStorageType, then it can be mutated in ways we
// don't know.
if (var->getInterfaceType()->is<WeakStorageType>())
access |= RK_Written;
// Diagnose variables that were never used (other than their
// initialization).
//
if ((access & (RK_Read|RK_Written)) == 0) {
// If this is a member in a capture list, just say it is unused. We could
// produce a fixit hint with a parent map, but this is a lot of effort for
// a narrow case.
if (access & RK_CaptureList) {
Diags.diagnose(var->getLoc(), diag::capture_never_used,
var->getName());
continue;
}
// If the source of the VarDecl is a trivial PatternBinding with only a
// single binding, rewrite the whole thing into an assignment.
// let x = foo()
// ->
// _ = foo()
if (auto *pbd = var->getParentPatternBinding()) {
if (pbd->getSingleVar() == var && pbd->getInit(0) != nullptr &&
!isa<TypedPattern>(pbd->getPattern(0))) {
unsigned varKind = var->isLet();
SourceRange replaceRange(
pbd->getStartLoc(),
pbd->getPattern(0)->getEndLoc());
Diags.diagnose(var->getLoc(), diag::pbd_never_used,
var->getName(), varKind)
.fixItReplace(replaceRange, "_");
continue;
}
}
// If the variable is defined in a pattern in an if/while/guard statement,
// see if we can produce a tuned fixit. When we have something like:
//
// if let x = <expr> {
//
// we prefer to rewrite it to:
//
// if <expr> != nil {
//
if (auto SC = StmtConditionForVD[var]) {
// We only handle the "if let" case right now, since it is vastly the
// most common situation that people run into.
if (SC->getCond().size() == 1) {
auto pattern = SC->getCond()[0].getPattern();
if (auto OSP = dyn_cast<OptionalSomePattern>(pattern))
if (auto LP = dyn_cast<BindingPattern>(OSP->getSubPattern()))
if (isa<NamedPattern>(LP->getSubPattern())) {
auto initExpr = SC->getCond()[0].getInitializer();
if (initExpr->getStartLoc().isValid()) {
unsigned noParens = initExpr->canAppendPostfixExpression();
// If the subexpr is an "as?" cast, we can rewrite it to
// be an "is" test.
ConditionalCheckedCastExpr *CCE = nullptr;
// initExpr can be wrapped inside parens or try expressions.
if (auto ccExpr = dyn_cast<ConditionalCheckedCastExpr>(
initExpr->getValueProvidingExpr())) {
if (!ccExpr->isImplicit()) {
CCE = ccExpr;
noParens = true;
}
}
// In cases where the value is optional, the cast expr is
// wrapped inside OptionalEvaluationExpr. Unwrap it to get
// ConditionalCheckedCastExpr.
if (auto oeExpr = dyn_cast<OptionalEvaluationExpr>(
initExpr->getValueProvidingExpr())) {
if (auto ccExpr = dyn_cast<ConditionalCheckedCastExpr>(
oeExpr->getSubExpr()->getValueProvidingExpr())) {
if (!ccExpr->isImplicit()) {
CCE = ccExpr;
noParens = true;
}
}
}
auto diagIF = Diags.diagnose(var->getLoc(),
diag::pbd_never_used_stmtcond,
var->getName());
auto introducerLoc = SC->getCond()[0].getIntroducerLoc();
diagIF.fixItReplaceChars(introducerLoc,
initExpr->getStartLoc(),
&"("[noParens]);
if (CCE) {
// If this was an "x as? T" check, rewrite it to "x is T".
diagIF.fixItReplace(SourceRange(CCE->getLoc(),
CCE->getQuestionLoc()),
"is");
} else {
diagIF.fixItInsertAfter(initExpr->getEndLoc(),
&") != nil"[noParens]);
}
continue;
}
}
}
}
// If the variable is defined in a pattern that isn't one of the usual
// conditional statements, try to detect and rewrite "simple" binding
// patterns:
// case .pattern(let x):
// ->
// case .pattern(_):
if (auto *pattern = var->getParentPattern()) {
BindingPattern *foundVP = nullptr;
pattern->forEachNode([&](Pattern *P) {
if (auto *VP = dyn_cast<BindingPattern>(P))
if (VP->getSingleVar() == var)
foundVP = VP;
});
if (foundVP) {
unsigned varKind = var->isLet();
Diags
.diagnose(var->getLoc(), diag::variable_never_used,
var->getName(), varKind)
.fixItReplace(foundVP->getSourceRange(), "_");
continue;
}
}
// Otherwise, this is something more complex, perhaps
// let (a,b) = foo()
if (isWrittenLet) {
Diags.diagnose(var->getLoc(),
diag::immutable_value_never_used_but_assigned,
var->getName());
} else {
unsigned varKind = var->isLet();
// Just rewrite the one variable with a _.
Diags.diagnose(var->getLoc(), diag::variable_never_used,
var->getName(), varKind)
.fixItReplace(var->getLoc(), "_");
}
continue;
}
// If this is a mutable 'var', and it was never written to, suggest
// upgrading to 'let'.
if (var->getIntroducer() == VarDecl::Introducer::Var
&& (access & RK_Written) == 0 &&
// Don't warn if we have something like "let (x,y) = ..." and 'y' was
// never mutated, but 'x' was.
!isVarDeclPartOfPBDThatHadSomeMutation(var)) {
SourceLoc FixItLoc = getFixItLocForVarToLet(var);
// If this is a parameter explicitly marked 'var', remove it.
if (FixItLoc.isInvalid()) {
Diags.diagnose(var->getLoc(), diag::variable_never_mutated,
var->getName(), true);
}
else {
bool suggestLet = true;
if (auto *stmt = var->getRecursiveParentPatternStmt()) {
// Don't try to suggest 'var' -> 'let' conversion
// in case of 'for' loop because it's an implicitly
// immutable context.
suggestLet = !isa<ForEachStmt>(stmt);
}
auto diag = Diags.diagnose(var->getLoc(), diag::variable_never_mutated,
var->getName(), suggestLet);
if (suggestLet)
diag.fixItReplace(FixItLoc, "let");
else
diag.fixItRemove(FixItLoc);
continue;
}
}
// If this is a variable that was only written to, emit a warning.
if ((access & RK_Read) == 0) {
Diags.diagnose(var->getLoc(), diag::variable_never_read, var->getName());
continue;
}
}
}
/// Handle a use of "x.y" or "x[0]" where 'base' is the expression for x and
/// 'decl' is the property or subscript.
///
/// TODO: Rip this out and just rely on LValueAccessKind.
void VarDeclUsageChecker::markBaseOfStorageUse(Expr *base, ConcreteDeclRef decl,
unsigned flags) {
// If the base is an rvalue, then we know that this is a non-mutating access.
// Note that we can have mutating accesses even when the base has class or
// metatype type due to protocols and protocol extensions.
if (!base->getType()->hasLValueType() &&
!base->isSemanticallyInOutExpr()) {
base->walk(*this);
return;
}
// Compute whether this access is to a mutating member.
auto *ASD = dyn_cast_or_null<AbstractStorageDecl>(decl.getDecl());
bool isMutating = false;
if (!ASD) {
// If there's no abstract storage declaration (which should hopefully
// only happen with invalid code), treat the base access as mutating if
// the subobject is being mutated and the base type is not a class
// or metatype.
if (flags & RK_Written) {
Type type = base->getType()->getRValueType()->getInOutObjectType();
if (!type->isAnyClassReferenceType() && !type->is<AnyMetatypeType>())
isMutating = true;
}
} else {
// Otherwise, consider whether the accessors are mutating.
if (flags & RK_Read)
isMutating |= ASD->isGetterMutating();
if (flags & RK_Written)
isMutating |= ASD->isSettable(nullptr) && ASD->isSetterMutating();
}
markBaseOfStorageUse(base, isMutating);
}
void VarDeclUsageChecker::markBaseOfStorageUse(Expr *base, bool isMutating) {
// CSApply sometimes wraps the base in an InOutExpr just because the
// base is an l-value; look through that so we can get more precise
// checking.
if (auto *ioe = dyn_cast<InOutExpr>(base))
base = ioe->getSubExpr();
if (!isMutating) {
base->walk(*this);
return;
}
// Otherwise this is a read and write of the base.
return markStoredOrInOutExpr(base, RK_Written|RK_Read);
}
void VarDeclUsageChecker::markStoredOrInOutExpr(Expr *E, unsigned Flags) {
// Sema leaves some subexpressions null, which seems really unfortunate. It
// should replace them with ErrorExpr.
if (E == nullptr || !E->getType() || E->getType()->hasError()) {
sawError = true;
return;
}
// Ignore parens and other easy cases.
E = E->getSemanticsProvidingExpr();
// If we found a decl that is being assigned to, then mark it.
if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
addMark(DRE->getDecl(), Flags);
return;
}
if (auto *TE = dyn_cast<TupleExpr>(E)) {
for (auto &elt : TE->getElements())
markStoredOrInOutExpr(elt, Flags);
return;
}
// If this is an assignment into a mutating subscript lvalue expr, then we
// are mutating the base expression. We also need to visit the index
// expressions as loads though.
if (auto *SE = dyn_cast<SubscriptExpr>(E)) {
// The arguments of a subscript are evaluated as rvalues.
SE->getArgs()->walk(*this);
markBaseOfStorageUse(SE->getBase(), SE->getDecl(), Flags);
return;
}
// Likewise for key path applications. An application of a WritableKeyPath
// reads and writes its base; an application of a ReferenceWritableKeyPath
// only reads its base; the other KeyPath types cannot be written at all.
if (auto *KPA = dyn_cast<KeyPathApplicationExpr>(E)) {
KPA->getKeyPath()->walk(*this);
bool isMutating =
(Flags & RK_Written) &&
KPA->getKeyPath()->getType()->isWritableKeyPath();
markBaseOfStorageUse(KPA->getBase(), isMutating);
return;
}
if (auto *ioe = dyn_cast<InOutExpr>(E))
return markStoredOrInOutExpr(ioe->getSubExpr(), RK_Written|RK_Read);
if (auto *MRE = dyn_cast<MemberRefExpr>(E)) {
markBaseOfStorageUse(MRE->getBase(), MRE->getMember(), Flags);
return;
}
if (auto *TEE = dyn_cast<TupleElementExpr>(E))
return markStoredOrInOutExpr(TEE->getBase(), Flags);
if (auto *FVE = dyn_cast<ForceValueExpr>(E))
return markStoredOrInOutExpr(FVE->getSubExpr(), Flags);
if (auto *BOE = dyn_cast<BindOptionalExpr>(E))
return markStoredOrInOutExpr(BOE->getSubExpr(), Flags);
// Bind existential expressions.
if (auto *OEE = dyn_cast<OpenExistentialExpr>(E)) {
OpaqueValueMap[OEE->getOpaqueValue()] = OEE->getExistentialValue();
return markStoredOrInOutExpr(OEE->getSubExpr(), Flags);
}
// If this is an OpaqueValueExpr that we've seen a mapping for, jump to the
// mapped value.
if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
if (auto *expr = OpaqueValueMap[OVE])
return markStoredOrInOutExpr(expr, Flags);
// If we don't know what kind of expression this is, assume it's a reference
// and mark it as a read.
E->walk(*this);
}
/// The heavy lifting happens when visiting expressions.
ASTWalker::PreWalkResult<Expr *> VarDeclUsageChecker::walkToExprPre(Expr *E) {
STATISTIC(VarDeclUsageCheckerExprVisits,
"# of times VarDeclUsageChecker::walkToExprPre is called");
++VarDeclUsageCheckerExprVisits;
// Sema leaves some subexpressions null, which seems really unfortunate. It
// should replace them with ErrorExpr.
if (E == nullptr || !E->getType() || E->getType()->hasError()) {
sawError = true;
return Action::SkipNode(E);
}
assert(AllExprsSeen.insert(E).second && "duplicate traversal");
// If this is a DeclRefExpr found in a random place, it is a load of the
// vardecl.
if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
addMark(DRE->getDecl(), RK_Read);
// If the Expression is a read of a getter, track for diagnostics
if (auto VD = dyn_cast<VarDecl>(DRE->getDecl())) {
AssociatedGetterRefExpr.insert(std::make_pair(VD, DRE));
}
}
// If the Expression is a member reference, see if it is a read of the getter
// to track for diagnostics.
if (auto *MRE = dyn_cast<MemberRefExpr>(E)) {
if (auto VD = dyn_cast<VarDecl>(MRE->getMember().getDecl())) {
AssociatedGetterRefExpr.insert(std::make_pair(VD, MRE));
markBaseOfStorageUse(MRE->getBase(), MRE->getMember(), RK_Read);
return Action::SkipNode(E);
}
}
if (auto SE = dyn_cast<SubscriptExpr>(E)) {
SE->getArgs()->walk(*this);
markBaseOfStorageUse(SE->getBase(), SE->getDecl(), RK_Read);
return Action::SkipNode(E);
}
// If this is an AssignExpr, see if we're mutating something that we know
// about.
if (auto *assign = dyn_cast<AssignExpr>(E)) {
markStoredOrInOutExpr(assign->getDest(), RK_Written);
// Don't walk into the LHS of the assignment, only the RHS.
assign->getSrc()->walk(*this);
return Action::SkipNode(E);
}
// '&x' is a read and write of 'x'.
if (auto *io = dyn_cast<InOutExpr>(E)) {
markStoredOrInOutExpr(io->getSubExpr(), RK_Read|RK_Written);
// Don't bother walking into this.
return Action::SkipNode(E);
}
// If we see an OpenExistentialExpr, remember the mapping for its OpaqueValue
// and only walk the subexpr.
if (auto *oee = dyn_cast<OpenExistentialExpr>(E)) {
OpaqueValueMap[oee->getOpaqueValue()] = oee->getExistentialValue();
oee->getSubExpr()->walk(*this);
return Action::SkipNode(E);
}
// Visit bindings.
if (auto ove = dyn_cast<OpaqueValueExpr>(E)) {
if (auto mapping = OpaqueValueMap.lookup(ove))
mapping->walk(*this);
return Action::SkipNode(E);
}
// If we saw an ErrorExpr, take note of this.
if (isa<ErrorExpr>(E))
sawError = true;
return Action::Continue(E);
}
/// handle #if directives. All of the active clauses are already walked by the
/// AST walker, but we also want to handle the inactive ones to avoid false
/// positives.
void VarDeclUsageChecker::handleIfConfig(IfConfigDecl *ICD) {
struct ConservativeDeclMarker : public ASTWalker {
VarDeclUsageChecker &VDUC;
SourceFile *SF;
ConservativeDeclMarker(VarDeclUsageChecker &VDUC)
: VDUC(VDUC), SF(VDUC.DC->getParentSourceFile()) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
// If we see a bound reference to a decl in an inactive #if block, then
// conservatively mark it read and written. This will silence "variable
// unused" and "could be marked let" warnings for it.
if (auto *DRE = dyn_cast<DeclRefExpr>(E))
VDUC.addMark(DRE->getDecl(), RK_Read | RK_Written);
else if (auto *declRef = dyn_cast<UnresolvedDeclRefExpr>(E)) {
auto name = declRef->getName();
auto loc = declRef->getLoc();
if (name.isSimpleName() && loc.isValid()) {
auto *varDecl = dyn_cast_or_null<VarDecl>(
ASTScope::lookupSingleLocalDecl(SF, name.getFullName(), loc));
if (varDecl)
VDUC.addMark(varDecl, RK_Read|RK_Written);
}
}
return Action::Continue(E);
}
};
for (auto &clause : ICD->getClauses()) {
// Active clauses are handled by the normal AST walk.
if (clause.isActive) continue;
for (auto elt : clause.Elements)
elt.walk(ConservativeDeclMarker(*this));
}
}
namespace {
class SingleValueStmtUsageChecker final : public ASTWalker {
ASTContext &Ctx;
DiagnosticEngine &Diags;
llvm::DenseSet<SingleValueStmtExpr *> ValidSingleValueStmtExprs;
public:
SingleValueStmtUsageChecker(
ASTContext &ctx, ASTNode root,
std::optional<ContextualTypePurpose> contextualPurpose)
: Ctx(ctx), Diags(ctx.Diags) {
assert(!root.is<Expr *>() || contextualPurpose &&
"Must provide contextual purpose for expr");
// If we have a contextual purpose, this is for an expression. Check if it's
// an expression in a valid position.
if (contextualPurpose) {
markAnyValidTopLevelSingleValueStmt(root.get<Expr *>(),
*contextualPurpose);
}
}
private:
/// Mark a given expression as a valid position for a SingleValueStmtExpr.
void markValidSingleValueStmt(Expr *E) {
if (!E)
return;
if (auto *SVE = SingleValueStmtExpr::tryDigOutSingleValueStmtExpr(E))
ValidSingleValueStmtExprs.insert(SVE);
}
/// Mark a valid top-level expression with a given contextual purpose.
void markAnyValidTopLevelSingleValueStmt(Expr *E, ContextualTypePurpose ctp) {
// Allowed in returns, throws, and bindings.
switch (ctp) {
case CTP_ReturnStmt:
case CTP_ThrowStmt:
case CTP_Initialization:
markValidSingleValueStmt(E);
break;
default:
break;
}
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
AssignExpr *findAssignment(Expr *E) const {
// Don't consider assignments if we have a parent expression (as otherwise
// this would be effectively allowing it in an arbitrary expression
// position).
if (Parent.getAsExpr())
return nullptr;
// Look through optional exprs, which are present for e.g x?.y = z, as
// we wrap the entire assign in the optional evaluation of the destination.
if (auto *OEE = dyn_cast<OptionalEvaluationExpr>(E)) {
E = OEE->getSubExpr();
while (auto *IIO = dyn_cast<InjectIntoOptionalExpr>(E))
E = IIO->getSubExpr();
}
return dyn_cast<AssignExpr>(E);
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (auto *SVE = dyn_cast<SingleValueStmtExpr>(E)) {
// Diagnose a SingleValueStmtExpr in a context that we do not currently
// support. If we start allowing these in arbitrary places, we'll need
// to ensure that autoclosures correctly contextualize them.
if (!ValidSingleValueStmtExprs.contains(SVE)) {
Diags.diagnose(SVE->getLoc(), diag::single_value_stmt_out_of_place,
SVE->getStmt()->getKind());
}
// Diagnose invalid SingleValueStmtExprs. This should only happen for
// expressions in positions that we didn't support before
// (e.g assignment or *explicit* return).
auto *S = SVE->getStmt();
auto mayProduceSingleValue = S->mayProduceSingleValue(Ctx);
switch (mayProduceSingleValue.getKind()) {
case IsSingleValueStmtResult::Kind::Valid:
break;
case IsSingleValueStmtResult::Kind::UnterminatedBranches: {
for (auto *branch : mayProduceSingleValue.getUnterminatedBranches()) {
if (auto *BS = dyn_cast<BraceStmt>(branch)) {
if (BS->empty()) {
Diags.diagnose(branch->getStartLoc(),
diag::single_value_stmt_branch_empty,
S->getKind());
continue;
}
}
// TODO: The wording of this diagnostic will need tweaking if either
// implicit last expressions or 'then' statements are enabled by
// default.
Diags.diagnose(branch->getEndLoc(),
diag::single_value_stmt_branch_must_end_in_result,
S->getKind());
}
break;
}
case IsSingleValueStmtResult::Kind::NonExhaustiveIf: {
Diags.diagnose(S->getStartLoc(),
diag::if_expr_must_be_syntactically_exhaustive);
break;
}
case IsSingleValueStmtResult::Kind::NonExhaustiveDoCatch: {
Diags.diagnose(S->getStartLoc(),
diag::do_catch_expr_must_be_syntactically_exhaustive);
break;
}
case IsSingleValueStmtResult::Kind::HasLabel: {
// FIXME: We should offer a fix-it to remove (currently we don't track
// the colon SourceLoc).
auto label = cast<LabeledStmt>(S)->getLabelInfo();
Diags.diagnose(label.Loc,
diag::single_value_stmt_must_be_unlabeled, S->getKind())
.highlight(label.Loc);
break;
}
case IsSingleValueStmtResult::Kind::InvalidJumps: {
// Diagnose each invalid jump.
for (auto *jump : mayProduceSingleValue.getInvalidJumps()) {
Diags.diagnose(jump->getStartLoc(),
diag::cannot_jump_in_single_value_stmt,
jump->getKind(), S->getKind())
.highlight(jump->getSourceRange());
}
break;
}
case IsSingleValueStmtResult::Kind::NoResult:
// This is fine, we will have typed the expression as Void (we verify
// as such in the ASTVerifier).
break;
case IsSingleValueStmtResult::Kind::CircularReference:
// Already diagnosed.
break;
case IsSingleValueStmtResult::Kind::UnhandledStmt:
break;
}
return Action::Continue(E);
}
// Valid as the source of an assignment.
if (auto *AE = findAssignment(E))
markValidSingleValueStmt(AE->getSrc());
// Valid as a single expression body of a closure. This is needed in
// addition to ReturnStmt checking, as we will remove the return if the
// expression is inferred to be Never.
if (auto *ACE = dyn_cast<ClosureExpr>(E)) {
if (ACE->hasSingleExpressionBody())
markValidSingleValueStmt(ACE->getSingleExpressionBody());
}
return Action::Continue(E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
// Valid in a return/throw/then.
if (auto *RS = dyn_cast<ReturnStmt>(S)) {
if (RS->hasResult())
markValidSingleValueStmt(RS->getResult());
}
if (auto *TS = dyn_cast<ThrowStmt>(S))
markValidSingleValueStmt(TS->getSubExpr());
if (auto *TS = dyn_cast<ThenStmt>(S))
markValidSingleValueStmt(TS->getResult());
return Action::Continue(S);
}
PreWalkAction walkToDeclPre(Decl *D) override {
// Valid as an initializer of a pattern binding.
if (auto *PBD = dyn_cast<PatternBindingDecl>(D)) {
for (auto idx : range(PBD->getNumPatternEntries()))
markValidSingleValueStmt(PBD->getInit(idx));
return Action::Continue();
}
// We don't want to walk into any other decl, we will visit them as part of
// typeCheckDecl.
return Action::SkipNode();
}
};
} // end anonymous namespace
void swift::diagnoseOutOfPlaceExprs(
ASTContext &ctx, ASTNode root,
std::optional<ContextualTypePurpose> contextualPurpose) {
// TODO: We ought to consider moving this into pre-checking such that we can
// still diagnose on invalid code, and don't have to traverse over implicit
// exprs. We need to first separate out SequenceExpr folding though.
SingleValueStmtUsageChecker sveChecker(ctx, root, contextualPurpose);
root.walk(sveChecker);
}
/// Apply the warnings managed by VarDeclUsageChecker to the top level
/// code declarations that haven't been checked yet.
void swift::
performTopLevelDeclDiagnostics(TopLevelCodeDecl *TLCD) {
auto &ctx = TLCD->getDeclContext()->getASTContext();
VarDeclUsageChecker checker(TLCD, ctx.Diags);
TLCD->walk(checker);
}
/// Perform diagnostics for func/init/deinit declarations.
void swift::performAbstractFuncDeclDiagnostics(AbstractFunctionDecl *AFD) {
// Don't produce these diagnostics for implicitly generated code.
if (AFD->getLoc().isInvalid() || AFD->isImplicit() || AFD->isInvalid())
return;
if (!AFD->getDeclContext()->isLocalContext()) {
// Check for unused variables, as well as variables that are could be
// declared as constants. Skip local functions though, since they will
// be checked as part of their parent function or TopLevelCodeDecl.
auto &ctx = AFD->getDeclContext()->getASTContext();
VarDeclUsageChecker checker(AFD, ctx.Diags);
AFD->walk(checker);
}
auto *body = AFD->getBody();
// If the function has an opaque return type, check the return expressions
// to determine the underlying type.
if (auto opaqueResultTy = AFD->getOpaqueResultTypeDecl()) {
OpaqueUnderlyingTypeChecker(AFD, opaqueResultTy, body).check();
} else if (auto accessor = dyn_cast<AccessorDecl>(AFD)) {
if (accessor->isGetter()) {
if (auto opaqueResultTy
= accessor->getStorage()->getOpaqueResultTypeDecl()) {
OpaqueUnderlyingTypeChecker(AFD, opaqueResultTy, body).check();
}
}
} else if (auto *FD = dyn_cast<FuncDecl>(AFD)) {
auto resultIFaceTy = FD->getResultInterfaceType();
// If the result has a placeholder, we need to try to use the contextual
// type inferred in the body to replace it.
if (resultIFaceTy && resultIFaceTy->hasPlaceholder()) {
ReturnTypePlaceholderReplacer(FD, body).check();
}
}
}
static void
diagnoseMoveOnlyPatternMatchSubject(ASTContext &C,
const DeclContext *DC,
Expr *subjectExpr) {
// For now, move-only types must use the `consume` operator to be
// pattern matched. Pattern matching is only implemented as a consuming
// operation today, but we don't want to be stuck with that as the default
// in the fullness of time when we get borrowing pattern matching later.
// Don't bother if the subject wasn't given a valid type, or is a copyable
// type.
auto subjectType = subjectExpr->getType();
if (!subjectType
|| subjectType->hasError()
|| !subjectType->isNoncopyable()) {
return;
}
}
// Perform MiscDiagnostics on Switch Statements.
static void checkSwitch(ASTContext &ctx, const SwitchStmt *stmt,
DeclContext *DC) {
diagnoseMoveOnlyPatternMatchSubject(ctx, DC, stmt->getSubjectExpr());
// We want to warn about "case .Foo, .Bar where 1 != 100:" since the where
// clause only applies to the second case, and this is surprising.
for (auto cs : stmt->getCases()) {
TypeChecker::checkExistentialTypes(ctx, cs, DC);
// The case statement can have multiple case items, each can have a where.
// If we find a "where", and there is a preceding item without a where, and
// if they are on the same source line, then warn.
auto items = cs->getCaseLabelItems();
// Don't do any work for the vastly most common case.
if (items.size() == 1) continue;
// Ignore the first item, since it can't have preceding ones.
for (unsigned i = 1, e = items.size(); i != e; ++i) {
// Must have a where clause.
auto where = items[i].getGuardExpr();
if (!where)
continue;
// Preceding item must not.
if (items[i-1].getGuardExpr())
continue;
// Must be on the same source line.
auto prevLoc = items[i-1].getStartLoc();
auto thisLoc = items[i].getStartLoc();
if (prevLoc.isInvalid() || thisLoc.isInvalid())
continue;
auto &SM = ctx.SourceMgr;
auto prevLineCol = SM.getLineAndColumnInBuffer(prevLoc);
if (SM.getLineAndColumnInBuffer(thisLoc).first != prevLineCol.first)
continue;
ctx.Diags.diagnose(items[i].getWhereLoc(), diag::where_on_one_item)
.highlight(items[i].getPattern()->getSourceRange())
.highlight(where->getSourceRange());
// Whitespace it out to the same column as the previous item.
std::string whitespace(prevLineCol.second-1, ' ');
ctx.Diags.diagnose(thisLoc, diag::add_where_newline)
.fixItInsert(thisLoc, "\n"+whitespace);
auto whereRange = SourceRange(items[i].getWhereLoc(),
where->getEndLoc());
auto charRange = Lexer::getCharSourceRangeFromSourceRange(SM, whereRange);
auto whereText = SM.extractText(charRange);
ctx.Diags.diagnose(prevLoc, diag::duplicate_where)
.fixItInsertAfter(items[i-1].getEndLoc(), " " + whereText.str())
.highlight(items[i-1].getSourceRange());
}
}
}
void swift::fixItEncloseTrailingClosure(ASTContext &ctx,
InFlightDiagnostic &diag,
const CallExpr *call,
Identifier closureLabel) {
auto *argList = call->getArgs()->getOriginalArgs();
assert(argList->size() >= 1 && "must have at least one argument");
SmallString<32> replacement;
SourceLoc lastLoc;
SourceRange closureRange;
if (argList->isUnary()) {
closureRange = argList->getExpr(0)->getSourceRange();
lastLoc = argList->getLParenLoc(); // e.g funcName() { 1 }
if (!lastLoc.isValid()) {
// Bare trailing closure: e.g. funcName { 1 }
replacement = "(";
lastLoc = call->getFn()->getEndLoc();
}
} else {
// Tuple + trailing closure: e.g. funcName(x: 1) { 1 }
auto numElements = argList->size();
closureRange = argList->getExpr(numElements - 1)->getSourceRange();
lastLoc = argList->getExpr(numElements - 2)->getEndLoc();
replacement = ", ";
}
// Add argument label of the closure.
if (!closureLabel.empty()) {
replacement += closureLabel.str();
replacement += ": ";
}
lastLoc = Lexer::getLocForEndOfToken(ctx.SourceMgr, lastLoc);
diag
.fixItReplaceChars(lastLoc, closureRange.Start, replacement)
.fixItInsertAfter(closureRange.End, ")");
}
// Perform checkStmtConditionTrailingClosure for single expression.
static void checkStmtConditionTrailingClosure(ASTContext &ctx, const Expr *E) {
if (E == nullptr || isa<ErrorExpr>(E)) return;
// Walk into expressions which might have invalid trailing closures
class DiagnoseWalker : public ASTWalker {
ASTContext &Ctx;
void diagnoseIt(const CallExpr *E) {
// FIXME(https://github.com/apple/swift/issues/57382): We ought to handle multiple trailing closures here.
auto *args = E->getArgs()->getOriginalArgs();
if (args->getNumTrailingClosures() != 1)
return;
auto closureArg = *args->getFirstTrailingClosure();
auto *closureExpr = closureArg.getExpr();
auto closureTy = closureExpr->getType();
// Ignore invalid argument type. Some diagnostics are already emitted.
if (!closureTy || closureTy->hasError())
return;
// Figure out the label of the parameter the closure is being passed to.
// This will be present in the type-checked argument list (but not the
// original), so search it for the relevant argument, looking into
// variadic expansions if necessary.
Identifier label;
for (auto arg : *E->getArgs()) {
if (arg.getExpr() == closureExpr) {
label = arg.getLabel();
break;
}
if (auto *varg = dyn_cast<VarargExpansionExpr>(arg.getExpr())) {
if (auto *array = dyn_cast<ArrayExpr>(varg->getSubExpr())) {
if (!array->getElements().empty() &&
array->getElements()[0] == closureExpr) {
label = arg.getLabel();
break;
}
}
}
}
auto diag = Ctx.Diags.diagnose(closureExpr->getStartLoc(),
diag::trailing_closure_requires_parens);
fixItEncloseTrailingClosure(Ctx, diag, E, label);
}
public:
DiagnoseWalker(ASTContext &ctx) : Ctx(ctx) { }
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<ArgumentList *>
walkToArgumentListPre(ArgumentList *args) override {
// Don't walk into an explicit argument list, as trailing closures that
// appear in child arguments are fine.
return Action::VisitNodeIf(args->isImplicit(), args);
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
switch (E->getKind()) {
case ExprKind::Paren:
case ExprKind::Tuple:
case ExprKind::Array:
case ExprKind::Dictionary:
case ExprKind::InterpolatedStringLiteral:
case ExprKind::Closure:
// If a trailing closure appears as a child of one of these types of
// expression, don't diagnose it as there is no ambiguity.
return Action::VisitNodeIf(E->isImplicit(), E);
case ExprKind::Call:
diagnoseIt(cast<CallExpr>(E));
break;
default:
break;
}
return Action::Continue(E);
}
};
DiagnoseWalker Walker(ctx);
const_cast<Expr *>(E)->walk(Walker);
}
/// Diagnose trailing closure in statement-conditions.
///
/// Conditional statements, including 'for' or `switch` doesn't allow ambiguous
/// trailing closures in these conditions part. Even if the parser can recover
/// them, we force them to disambiguate.
//
/// E.g.:
/// if let _ = arr?.map {$0+1} { ... }
/// for _ in numbers.filter {$0 > 4} { ... }
static void checkStmtConditionTrailingClosure(ASTContext &ctx, const Stmt *S) {
if (auto LCS = dyn_cast<LabeledConditionalStmt>(S)) {
for (auto elt : LCS->getCond()) {
if (elt.getKind() == StmtConditionElement::CK_PatternBinding) {
checkStmtConditionTrailingClosure(ctx, elt.getInitializer());
if (auto *exprPattern = dyn_cast<ExprPattern>(elt.getPattern())) {
checkStmtConditionTrailingClosure(ctx, exprPattern->getMatchExpr());
}
} else if (elt.getKind() == StmtConditionElement::CK_Boolean)
checkStmtConditionTrailingClosure(ctx, elt.getBoolean());
// No trailing closure for CK_Availability: e.g. `if #available() {}`.
}
} else if (auto SS = dyn_cast<SwitchStmt>(S)) {
checkStmtConditionTrailingClosure(ctx, SS->getSubjectExpr());
} else if (auto FES = dyn_cast<ForEachStmt>(S)) {
checkStmtConditionTrailingClosure(ctx, FES->getParsedSequence());
checkStmtConditionTrailingClosure(ctx, FES->getWhere());
} else if (auto DCS = dyn_cast<DoCatchStmt>(S)) {
for (auto CS : DCS->getCatches())
for (auto &LabelItem : CS->getCaseLabelItems())
checkStmtConditionTrailingClosure(ctx, LabelItem.getGuardExpr());
}
}
namespace {
class ObjCSelectorWalker : public ASTWalker {
ASTContext &Ctx;
const DeclContext *DC;
Type SelectorTy;
/// Determine whether a reference to the given method via its
/// enclosing class/protocol is ambiguous (and, therefore, needs to
/// be disambiguated with a coercion).
bool isSelectorReferenceAmbiguous(AbstractFunctionDecl *method) {
// Determine the name we would search for. If there are no
// argument names, our lookup will be based solely on the base
// name.
DeclName lookupName = method->getName();
if (lookupName.getArgumentNames().empty())
lookupName = lookupName.getBaseName();
// Look for members with the given name.
auto nominal = method->getDeclContext()->getSelfNominalTypeDecl();
auto result = TypeChecker::lookupMember(
const_cast<DeclContext *>(DC), nominal->getDeclaredInterfaceType(),
DeclNameRef(lookupName), method->getLoc(),
defaultMemberLookupOptions);
// If we didn't find multiple methods, there is no ambiguity.
if (result.size() < 2) return false;
// If we found more than two methods, it's ambiguous.
if (result.size() > 2) return true;
// Dig out the methods.
auto firstMethod = dyn_cast<FuncDecl>(result[0].getValueDecl());
auto secondMethod = dyn_cast<FuncDecl>(result[1].getValueDecl());
if (!firstMethod || !secondMethod) return true;
// If one is a static/class method and the other is not...
if (firstMethod->isStatic() == secondMethod->isStatic()) return true;
// ... overload resolution will prefer the static method. Check
// that it has the correct selector. We don't even care that it's
// the same method we're asking for, just that it has the right
// selector.
FuncDecl *staticMethod =
firstMethod->isStatic() ? firstMethod : secondMethod;
return staticMethod->getObjCSelector() != method->getObjCSelector();
}
public:
ObjCSelectorWalker(const DeclContext *dc, Type selectorTy)
: Ctx(dc->getASTContext()), DC(dc), SelectorTy(selectorTy) { }
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
auto *stringLiteral = dyn_cast<StringLiteralExpr>(expr);
bool fromStringLiteral = false;
bool hadParens = false;
if (stringLiteral) {
// Is this a string literal that has type 'Selector'.
if (!stringLiteral->getType() ||
!stringLiteral->getType()->isEqual(SelectorTy))
return Action::Continue(expr);
fromStringLiteral = true;
// FIXME: hadParens
} else {
// Is this an initialization of 'Selector'?
auto call = dyn_cast<CallExpr>(expr);
if (!call) return Action::Continue(expr);
// That produce Selectors.
if (!call->getType() || !call->getType()->isEqual(SelectorTy))
return Action::Continue(expr);
// Via a constructor.
ConstructorDecl *ctor = nullptr;
if (auto ctorRefCall = dyn_cast<ConstructorRefCallExpr>(call->getFn())) {
if (auto ctorRef = dyn_cast<DeclRefExpr>(ctorRefCall->getFn()))
ctor = dyn_cast<ConstructorDecl>(ctorRef->getDecl());
else if (auto otherCtorRef =
dyn_cast<OtherConstructorDeclRefExpr>(ctorRefCall->getFn()))
ctor = otherCtorRef->getDecl();
}
if (!ctor) return Action::Continue(expr);
// Make sure the constructor is within Selector.
auto ctorContextType = ctor->getDeclContext()
->getSelfNominalTypeDecl()
->getDeclaredType();
if (!ctorContextType || !ctorContextType->isEqual(SelectorTy))
return Action::Continue(expr);
auto argNames = ctor->getName().getArgumentNames();
if (argNames.size() != 1) return Action::Continue(expr);
// Is this the init(stringLiteral:) initializer or init(_:) initializer?
if (argNames[0] == Ctx.Id_stringLiteral)
fromStringLiteral = true;
else if (!argNames[0].empty())
return Action::Continue(expr);
auto *arg = call->getArgs()->getUnaryExpr();
if (!arg)
return Action::Continue(expr);
// Track whether we had parentheses around the string literal.
if (auto paren = dyn_cast<ParenExpr>(arg)) {
hadParens = true;
arg = paren->getSubExpr();
}
// Check whether we have a string literal.
stringLiteral = dyn_cast<StringLiteralExpr>(arg);
if (!stringLiteral) return Action::Continue(expr);
}
/// Retrieve the parent expression that coerces to Selector, if
/// there is one.
auto getParentCoercion = [&]() -> CoerceExpr * {
auto parentExpr = Parent.getAsExpr();
if (!parentExpr) return nullptr;
auto coerce = dyn_cast<CoerceExpr>(parentExpr);
if (!coerce) return nullptr;
if (coerce->getType() && coerce->getType()->isEqual(SelectorTy))
return coerce;
return nullptr;
};
// Local function that adds the constructor syntax around string
// literals implicitly treated as a Selector.
auto addSelectorConstruction = [&](InFlightDiagnostic &diag) {
if (!fromStringLiteral) return;
// Introduce the beginning part of the Selector construction.
diag.fixItInsert(stringLiteral->getLoc(), "Selector(");
if (auto coerce = getParentCoercion()) {
// If the string literal was coerced to Selector, replace the
// coercion with the ")".
SourceLoc endLoc = Lexer::getLocForEndOfToken(Ctx.SourceMgr,
expr->getEndLoc());
diag.fixItReplace(SourceRange(endLoc, coerce->getEndLoc()), ")");
} else {
// Otherwise, just insert the closing ")".
diag.fixItInsertAfter(stringLiteral->getEndLoc(), ")");
}
};
// Try to parse the string literal as an Objective-C selector, and complain
// if it isn't one.
auto selector = ObjCSelector::parse(Ctx, stringLiteral->getValue());
if (!selector) {
auto diag = Ctx.Diags.diagnose(stringLiteral->getLoc(),
diag::selector_literal_invalid);
diag.highlight(stringLiteral->getSourceRange());
addSelectorConstruction(diag);
return Action::Continue(expr);
}
// Look for methods with this selector.
SmallVector<AbstractFunctionDecl *, 8> allMethods;
DC->lookupAllObjCMethods(*selector, allMethods);
// If we didn't find any methods, complain.
if (allMethods.empty()) {
// If this was Selector(("selector-name")), suppress, the
// diagnostic.
if (!fromStringLiteral && hadParens)
return Action::Continue(expr);
{
auto diag = Ctx.Diags.diagnose(stringLiteral->getLoc(),
diag::selector_literal_undeclared,
*selector);
addSelectorConstruction(diag);
}
// If the result was from a Selector("selector-name"), add a
// separate note that suggests wrapping the selector in
// parentheses to silence the warning.
if (!fromStringLiteral) {
Ctx.Diags.diagnose(stringLiteral->getLoc(),
diag::selector_construction_suppress_warning)
.fixItInsert(stringLiteral->getStartLoc(), "(")
.fixItInsertAfter(stringLiteral->getEndLoc(), ")");
}
return Action::Continue(expr);
}
// Find the "best" method that has this selector, so we can report
// that.
AbstractFunctionDecl *bestMethod = nullptr;
for (auto method : allMethods) {
// If this is the first method, use it.
if (!bestMethod) {
bestMethod = method;
continue;
}
// If referencing the best method would produce an ambiguity and
// referencing the new method would not, we have a new "best".
if (isSelectorReferenceAmbiguous(bestMethod) &&
!isSelectorReferenceAmbiguous(method)) {
bestMethod = method;
continue;
}
// If this method is within a protocol...
if (auto proto = method->getDeclContext()->getSelfProtocolDecl()) {
// If the best so far is not from a protocol, or is from a
// protocol that inherits this protocol, we have a new best.
auto bestProto = bestMethod->getDeclContext()->getSelfProtocolDecl();
if (!bestProto || bestProto->inheritsFrom(proto))
bestMethod = method;
continue;
}
// This method is from a class.
auto classDecl = method->getDeclContext()->getSelfClassDecl();
// If the best method was from a protocol, keep it.
auto bestClassDecl = bestMethod->getDeclContext()->getSelfClassDecl();
if (!bestClassDecl) continue;
// If the best method was from a subclass of the place where
// this method was declared, we have a new best.
if (classDecl->isSuperclassOf(bestClassDecl)) {
bestMethod = method;
}
}
// If we have a best method, reference it.
if (bestMethod) {
// Form the replacement #selector expression.
SmallString<32> replacement;
{
llvm::raw_svector_ostream out(replacement);
auto nominal = bestMethod->getDeclContext()->getSelfNominalTypeDecl();
out << "#selector(";
DeclName name;
auto bestAccessor = dyn_cast<AccessorDecl>(bestMethod);
if (bestAccessor) {
switch (bestAccessor->getAccessorKind()) {
case AccessorKind::Get:
out << "getter: ";
name = bestAccessor->getStorage()->getName();
break;
case AccessorKind::DistributedGet:
out << "_distributed_getter: ";
name = bestAccessor->getStorage()->getName();
break;
case AccessorKind::Set:
case AccessorKind::WillSet:
case AccessorKind::DidSet:
out << "setter: ";
name = bestAccessor->getStorage()->getName();
break;
case AccessorKind::Address:
case AccessorKind::MutableAddress:
case AccessorKind::Read:
case AccessorKind::Modify:
case AccessorKind::Init:
llvm_unreachable("cannot be @objc");
}
} else {
name = bestMethod->getName();
}
auto typeName = nominal->getName().str();
// If we're inside a type Foo (or an extension of it) and the suggestion
// is going to be #selector(Foo.bar) (or #selector(SuperclassOfFoo.bar),
// then suggest the more natural #selector(self.bar) instead.
if (auto containingTypeContext = DC->getInnermostTypeContext()) {
auto methodNominalType = nominal->getDeclaredType();
auto outerNomType = containingTypeContext->getSelfNominalTypeDecl()
->getDeclaredType();
if (methodNominalType->isEqual(outerNomType) ||
methodNominalType->isExactSuperclassOf(outerNomType))
typeName = "self";
}
out << typeName << "." << name.getBaseName();
auto argNames = name.getArgumentNames();
// Only print the parentheses if there are some argument
// names, because "()" would indicate a call.
if (!argNames.empty()) {
out << "(";
for (auto argName : argNames) {
if (argName.empty()) out << "_";
else out << argName.str();
out << ":";
}
out << ")";
}
// If there will be an ambiguity when referring to the method,
// introduce a coercion to resolve it to the method we found.
if (!bestAccessor && isSelectorReferenceAmbiguous(bestMethod)) {
if (auto fnType =
bestMethod->getInterfaceType()->getAs<FunctionType>()) {
// For static/class members, drop the metatype argument.
if (bestMethod->isStatic())
fnType = fnType->getResult()->getAs<FunctionType>();
// Coerce to this type.
assert(fnType->hasTypeRepr() &&
"Objective-C methods should always have printable types");
out << " as ";
fnType->print(out);
}
}
out << ")";
}
// Emit the diagnostic.
SourceRange replacementRange = expr->getSourceRange();
if (auto coerce = getParentCoercion())
replacementRange.End = coerce->getEndLoc();
Ctx.Diags
.diagnose(expr->getLoc(),
fromStringLiteral
? diag::selector_literal_deprecated_suggest
: diag::selector_construction_suggest)
.fixItReplace(replacementRange, replacement);
return Action::Continue(expr);
}
// If we couldn't pick a method to use for #selector, just wrap
// the string literal in Selector(...).
if (fromStringLiteral) {
auto diag = Ctx.Diags.diagnose(stringLiteral->getLoc(),
diag::selector_literal_deprecated);
addSelectorConstruction(diag);
return Action::Continue(expr);
}
return Action::Continue(expr);
}
};
} // end anonymous namespace
static void diagDeprecatedObjCSelectors(const DeclContext *dc,
const Expr *expr) {
auto selectorTy = dc->getASTContext().getSelectorType();
if (!selectorTy) return;
const_cast<Expr *>(expr)->walk(ObjCSelectorWalker(dc, selectorTy));
}
/// Skip over syntactic patterns that aren't typed patterns.
static Pattern *skipNonTypeSyntacticPatterns(Pattern *pattern) {
if (auto *pp = dyn_cast<ParenPattern>(pattern))
return skipNonTypeSyntacticPatterns(pp->getSubPattern());
if (auto *vp = dyn_cast<BindingPattern>(pattern))
return skipNonTypeSyntacticPatterns(vp->getSubPattern());
return pattern;
}
/// Diagnose things like this, where 'i' is an Int, not an Int?
/// if let x: Int = i {
static void
checkImplicitPromotionsInCondition(const StmtConditionElement &cond,
ASTContext &ctx) {
auto *p = cond.getPatternOrNull();
if (!p) return;
if (auto *subExpr = isImplicitPromotionToOptional(cond.getInitializer())) {
// If the subexpression was actually optional, then the pattern must be
// checking for a type, which forced it to be promoted to a double optional
// type.
if (auto ooType = subExpr->getType()->getOptionalObjectType()) {
if (auto OSP = dyn_cast<OptionalSomePattern>(p)) {
// Check for 'if let' to produce a tuned diagnostic.
if (auto *TP = dyn_cast<TypedPattern>(OSP->getSubPattern())) {
ctx.Diags.diagnose(cond.getIntroducerLoc(),
diag::optional_check_promotion,
subExpr->getType())
.highlight(subExpr->getSourceRange())
.fixItReplace(TP->getTypeRepr()->getSourceRange(),
ooType->getString());
return;
}
}
ctx.Diags.diagnose(cond.getIntroducerLoc(),
diag::optional_pattern_match_promotion,
subExpr->getType(), cond.getInitializer()->getType())
.highlight(subExpr->getSourceRange());
return;
}
// Check for 'if let' to produce a tuned diagnostic.
if (isa<OptionalSomePattern>(skipNonTypeSyntacticPatterns(p))) {
ctx.Diags.diagnose(
cond.getIntroducerLoc(),
p->isImplicit()
? diag::condition_optional_element_pattern_not_valid_type
: diag::optional_element_pattern_not_valid_type,
subExpr->getType())
.highlight(subExpr->getSourceRange());
return;
}
ctx.Diags.diagnose(cond.getIntroducerLoc(),
diag::optional_check_nonoptional,
subExpr->getType())
.highlight(subExpr->getSourceRange());
}
}
/// Diagnoses a `if #available(...)` condition. Returns true if a diagnostic
/// was emitted.
static bool diagnoseAvailabilityCondition(PoundAvailableInfo *info,
DeclContext *DC) {
// Reject inlinable code using availability macros. In order to lift this
// restriction, macros would need to either be expanded when printed in
// swiftinterfaces or be parsable as macros by module clients.
auto fragileKind = DC->getFragileFunctionKind();
if (fragileKind.kind != FragileFunctionKind::None) {
for (auto queries : info->getQueries()) {
if (auto availSpec =
dyn_cast<PlatformVersionConstraintAvailabilitySpec>(queries)) {
if (availSpec->getMacroLoc().isValid()) {
DC->getASTContext().Diags.diagnose(
availSpec->getMacroLoc(),
swift::diag::availability_macro_in_inlinable,
fragileKind.getSelector());
return true;
}
}
}
}
return false;
}
/// Diagnoses whether the given clang::Decl can be referenced by a
/// `if #_hasSymbol(...)` condition. Returns true if a diagnostic was emitted.
static bool diagnoseHasSymbolConditionClangDecl(SourceLoc loc,
const clang::Decl *clangDecl,
ASTContext &ctx) {
if (isa<clang::ObjCInterfaceDecl>(clangDecl) ||
isa<clang::FunctionDecl>(clangDecl))
return false;
if (auto *method = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) {
// FIXME: Allow objc_direct methods when supported by IRGen.
ctx.Diags.diagnose(loc,
diag::has_symbol_invalid_decl_use_responds_to_selector,
/*isProperty*/ false, method->getNameAsString());
return true;
}
if (auto *property = dyn_cast<clang::ObjCPropertyDecl>(clangDecl)) {
// FIXME: Allow objc_direct properties when supported by IRGen.
ctx.Diags.diagnose(loc,
diag::has_symbol_invalid_decl_use_responds_to_selector,
/*isProperty*/ true, property->getNameAsString());
return true;
}
ctx.Diags.diagnose(loc, diag::has_symbol_invalid_decl);
return true;
}
/// Diagnoses a `if #_hasSymbol(...)` condition. Returns true if a diagnostic
/// was emitted.
static bool diagnoseHasSymbolCondition(PoundHasSymbolInfo *info,
DeclContext *DC) {
// If we have an invalid info, null expression, or expression without a type
// then type checking failed already for this condition.
if (info->isInvalid())
return false;
auto symbolExpr = info->getSymbolExpr();
if (!symbolExpr)
return false;
if (!symbolExpr->getType())
return false;
auto &ctx = DC->getASTContext();
auto decl = info->getReferencedDecl().getDecl();
if (!decl) {
// Diagnose because we weren't able to interpret the expression as one
// that uniquely identifies a single declaration.
ctx.Diags.diagnose(symbolExpr->getLoc(), diag::has_symbol_invalid_expr);
return true;
}
if (auto *clangDecl = decl->getClangDecl()) {
if (diagnoseHasSymbolConditionClangDecl(symbolExpr->getLoc(), clangDecl,
ctx))
return true;
}
if (DC->getFragileFunctionKind().kind == FragileFunctionKind::None &&
!decl->isWeakImported(DC->getParentModule())) {
// `if #_hasSymbol(someStronglyLinkedSymbol)` is functionally a no-op
// and may indicate the developer has mis-identified the declaration
// they want to check (or forgot to import the module weakly).
ctx.Diags.diagnose(symbolExpr->getLoc(), diag::has_symbol_decl_must_be_weak,
decl);
return true;
}
return false;
}
/// Perform MiscDiagnostics for the conditions belonging to a \c
/// LabeledConditionalStmt.
static void checkLabeledStmtConditions(ASTContext &ctx,
const LabeledConditionalStmt *stmt,
DeclContext *DC) {
for (auto elt : stmt->getCond()) {
// Check for implicit optional promotions in stmt-condition patterns.
checkImplicitPromotionsInCondition(elt, ctx);
switch (elt.getKind()) {
case StmtConditionElement::CK_Boolean:
break;
case StmtConditionElement::CK_PatternBinding:
diagnoseMoveOnlyPatternMatchSubject(ctx, DC, elt.getInitializer());
break;
case StmtConditionElement::CK_Availability: {
auto info = elt.getAvailability();
(void)diagnoseAvailabilityCondition(info, DC);
break;
}
case StmtConditionElement::CK_HasSymbol: {
auto info = elt.getHasSymbolInfo();
if (diagnoseHasSymbolCondition(info, DC))
info->setInvalid();
break;
}
}
}
}
static void diagnoseUnintendedOptionalBehavior(const Expr *E,
const DeclContext *DC) {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return;
class UnintendedOptionalBehaviorWalker : public ASTWalker {
ASTContext &Ctx;
SmallPtrSet<Expr *, 16> IgnoredExprs;
class OptionalToAnyCoercion {
public:
Type DestType;
CoerceExpr *ParentCoercion;
bool shouldSuppressDiagnostic() {
// If we have a parent CoerceExpr that has the same type as our
// Optional-to-Any coercion, don't emit a diagnostic.
return ParentCoercion && ParentCoercion->getType()->isEqual(DestType);
}
};
/// Returns true iff a coercion from srcType to destType is an
/// Optional-to-Any coercion.
bool isOptionalToAnyCoercion(Type srcType, Type destType) {
size_t difference = 0;
return isOptionalToAnyCoercion(srcType, destType, difference);
}
/// Returns true iff a coercion from srcType to destType is an
/// Optional-to-Any coercion. On returning true, the value of 'difference'
/// will be the difference in the levels of optionality.
bool isOptionalToAnyCoercion(Type srcType, Type destType,
size_t &difference) {
SmallVector<Type, 4> destOptionals;
auto destValueType =
destType->lookThroughAllOptionalTypes(destOptionals);
if (!destValueType->isAny())
return false;
SmallVector<Type, 4> srcOptionals;
srcType->lookThroughAllOptionalTypes(srcOptionals);
if (srcOptionals.size() > destOptionals.size()) {
difference = srcOptionals.size() - destOptionals.size();
return true;
} else {
return false;
}
}
/// Returns true iff the collection upcast coercion is an Optional-to-Any
/// coercion.
bool isOptionalToAnyCoercion(CollectionUpcastConversionExpr::ConversionPair
conversion) {
if (!conversion.OrigValue || !conversion.Conversion)
return false;
auto srcType = conversion.OrigValue->getType();
auto destType = conversion.Conversion->getType();
return isOptionalToAnyCoercion(srcType, destType);
}
/// Looks through OptionalEvaluationExprs and InjectIntoOptionalExprs to
/// find a child ErasureExpr, returning nullptr if no such child is found.
/// Any intermediate OptionalEvaluationExprs will be marked as ignored.
ErasureExpr *findErasureExprThroughOptionalInjections(Expr *E) {
while (true) {
if (auto *next = dyn_cast<OptionalEvaluationExpr>(E)) {
// We don't want to re-visit any intermediate optional evaluations.
IgnoredExprs.insert(next);
E = next->getSubExpr();
} else if (auto *next = dyn_cast<InjectIntoOptionalExpr>(E)) {
E = next->getSubExpr();
} else {
break;
}
}
return dyn_cast<ErasureExpr>(E);
}
void emitSilenceOptionalAnyWarningWithCoercion(Expr *E, Type destType) {
assert(destType->hasTypeRepr() &&
"coercion to Any should always be printable");
SmallString<16> coercionString;
coercionString += " as ";
coercionString += destType->getWithoutParens()->getString();
Ctx.Diags.diagnose(E->getLoc(), diag::silence_optional_to_any,
destType, coercionString.substr(1))
.highlight(E->getSourceRange())
.fixItInsertAfter(E->getEndLoc(), coercionString);
}
static bool hasImplicitlyUnwrappedResult(Expr *E) {
auto *decl = getDeclForImplicitlyUnwrappedExpr(E);
return decl && decl->isImplicitlyUnwrappedOptional();
}
static ValueDecl *getDeclForImplicitlyUnwrappedExpr(Expr *E) {
E = E->getValueProvidingExpr();
// Look through implicit conversions like loads, derived-to-base
// conversion, etc.
if (auto *ICE = dyn_cast<ImplicitConversionExpr>(E)) {
E = ICE->getSubExpr();
}
if (auto *subscript = dyn_cast<SubscriptExpr>(E)) {
if (subscript->hasDecl())
return subscript->getDecl().getDecl();
return nullptr;
}
if (auto *memberRef = dyn_cast<MemberRefExpr>(E))
return memberRef->getMember().getDecl();
if (auto *declRef = dyn_cast<DeclRefExpr>(E))
return declRef->getDecl();
if (auto *apply = dyn_cast<ApplyExpr>(E)) {
auto *decl = apply->getCalledValue(/*skipFunctionConversions=*/true);
if (isa_and_nonnull<AbstractFunctionDecl>(decl))
return decl;
}
return nullptr;
}
void visitErasureExpr(ErasureExpr *E, OptionalToAnyCoercion coercion) {
if (coercion.shouldSuppressDiagnostic())
return;
auto subExpr = E->getSubExpr();
// Look through any BindOptionalExprs, as the coercion may have started
// from a higher level of optionality.
while (auto *bindExpr = dyn_cast<BindOptionalExpr>(subExpr))
subExpr = bindExpr->getSubExpr();
// Do not warn on coercions from implicitly unwrapped optionals
// for Swift versions less than 5.
if (!Ctx.isSwiftVersionAtLeast(5) &&
hasImplicitlyUnwrappedResult(subExpr))
return;
// We're taking the source type from the child of any BindOptionalExprs,
// and the destination from the parent of any
// (InjectIntoOptional/OptionalEvaluation)Exprs in order to take into
// account any bindings that need to be done for nested Optional-to-Any
// coercions, e.g Int??? to Any?.
auto srcType = subExpr->getType();
auto destType = coercion.DestType;
size_t optionalityDifference = 0;
if (!isOptionalToAnyCoercion(srcType, destType, optionalityDifference))
return;
// If we're implicitly unwrapping from IUO to Any then emit a custom
// diagnostic
if (hasImplicitlyUnwrappedResult(subExpr)) {
if (auto decl = getDeclForImplicitlyUnwrappedExpr(subExpr)) {
Ctx.Diags.diagnose(subExpr->getStartLoc(), diag::iuo_to_any_coercion,
/* from */ srcType, /* to */ destType)
.highlight(subExpr->getSourceRange());
auto noteDiag = isa<FuncDecl>(decl)
? diag::iuo_to_any_coercion_note_func_result
: diag::iuo_to_any_coercion_note;
Ctx.Diags.diagnose(decl->getLoc(), noteDiag, decl);
}
} else {
Ctx.Diags.diagnose(subExpr->getStartLoc(),
diag::optional_to_any_coercion,
/* from */ srcType, /* to */ destType)
.highlight(subExpr->getSourceRange());
}
if (optionalityDifference == 1) {
Ctx.Diags.diagnose(subExpr->getLoc(), diag::default_optional_to_any)
.highlight(subExpr->getSourceRange())
.fixItInsertAfter(subExpr->getEndLoc(), " ?? <#default value#>");
}
SmallString<4> forceUnwrapString;
for (size_t i = 0; i < optionalityDifference; ++i)
forceUnwrapString += "!";
Ctx.Diags.diagnose(subExpr->getLoc(), diag::force_optional_to_any)
.highlight(subExpr->getSourceRange())
.fixItInsertAfter(subExpr->getEndLoc(), forceUnwrapString);
emitSilenceOptionalAnyWarningWithCoercion(subExpr, destType);
}
void visitCollectionUpcastExpr(CollectionUpcastConversionExpr *E,
OptionalToAnyCoercion coercion) {
// We only need to consider the valueConversion, as the Key type of a
// Dictionary cannot be implicitly coerced to Any.
auto valueConversion = E->getValueConversion();
// We're handling the coercion of the entire collection, so we don't need
// to re-visit a nested ErasureExpr for the value.
if (auto conversionExpr = valueConversion.Conversion)
if (auto *erasureExpr =
findErasureExprThroughOptionalInjections(conversionExpr))
IgnoredExprs.insert(erasureExpr);
if (coercion.shouldSuppressDiagnostic() ||
!isOptionalToAnyCoercion(valueConversion))
return;
auto subExpr = E->getSubExpr();
Ctx.Diags.diagnose(subExpr->getStartLoc(), diag::optional_to_any_coercion,
/* from */ subExpr->getType(), /* to */ E->getType())
.highlight(subExpr->getSourceRange());
emitSilenceOptionalAnyWarningWithCoercion(subExpr, E->getType());
}
void visitPossibleOptionalToAnyExpr(Expr *E,
OptionalToAnyCoercion coercion) {
if (auto *upcastExpr =
dyn_cast<CollectionUpcastConversionExpr>(E)) {
visitCollectionUpcastExpr(upcastExpr, coercion);
} else if (auto *erasureExpr = dyn_cast<ErasureExpr>(E)) {
visitErasureExpr(erasureExpr, coercion);
} else if (auto *optionalEvalExpr = dyn_cast<OptionalEvaluationExpr>(E)) {
// The ErasureExpr could be nested within optional injections and
// bindings, such as is the case for e.g Int??? to Any?. Try and find
// and visit it directly, making sure we don't re-visit it later.
auto subExpr = optionalEvalExpr->getSubExpr();
if (auto *erasureExpr =
findErasureExprThroughOptionalInjections(subExpr)) {
visitErasureExpr(erasureExpr, coercion);
IgnoredExprs.insert(erasureExpr);
}
}
}
enum class UnintendedInterpolationKind: bool {
Optional,
Function
};
void visitInterpolatedStringLiteralExpr(InterpolatedStringLiteralExpr *E) {
E->forEachSegment(Ctx,
[&](bool isInterpolation, CallExpr *segment) -> void {
if (isInterpolation) {
diagnoseIfUnintendedInterpolation(segment,
UnintendedInterpolationKind::Optional);
diagnoseIfUnintendedInterpolation(segment,
UnintendedInterpolationKind::Function);
}
});
}
void diagnoseIfUnintendedInterpolation(CallExpr *segment,
UnintendedInterpolationKind kind) {
if (interpolationWouldBeUnintended(
segment->getCalledValue(/*skipFunctionConversions=*/true), kind))
if (auto firstArg =
getFirstArgIfUnintendedInterpolation(segment->getArgs(), kind))
diagnoseUnintendedInterpolation(firstArg, kind);
}
bool interpolationWouldBeUnintended(ConcreteDeclRef appendMethod,
UnintendedInterpolationKind kind) {
ValueDecl * fnDecl = appendMethod.getDecl();
// If things aren't set up right, just hope for the best.
if (!fnDecl || fnDecl->isInvalid())
return false;
// If the decl expects an optional, that's fine.
auto uncurriedType = fnDecl->getInterfaceType()->getAs<AnyFunctionType>();
auto curriedType = uncurriedType->getResult()->getAs<AnyFunctionType>();
// I don't know why you'd use a zero-arg interpolator, but it obviously
// doesn't interpolate an optional.
if (curriedType->getNumParams() == 0)
return false;
// If the first parameter explicitly accepts the type, this method
// presumably doesn't want us to warn about optional use.
auto firstParamType =
curriedType->getParams().front().getPlainType()->getRValueType();
if (kind == UnintendedInterpolationKind::Optional) {
if (firstParamType->getOptionalObjectType())
return false;
} else {
if (firstParamType->is<AnyFunctionType>())
return false;
}
return true;
}
Expr *
getFirstArgIfUnintendedInterpolation(ArgumentList *args,
UnintendedInterpolationKind kind) {
// Just check the first argument, which is usually the value
// being interpolated.
if (args->empty())
return nullptr;
auto *firstArg = args->getExpr(0);
// Allow explicit casts.
if (isa<ExplicitCastExpr>(firstArg->getSemanticsProvidingExpr()))
return nullptr;
// If we don't have a type, assume the best.
if (!firstArg->getType() || firstArg->getType()->hasError())
return nullptr;
// Bail out if we don't have an optional.
if (kind == UnintendedInterpolationKind::Optional) {
if (!firstArg->getType()->getRValueType()->getOptionalObjectType())
return nullptr;
}
else if (kind == UnintendedInterpolationKind::Function) {
if (!firstArg->getType()->getRValueType()->is<AnyFunctionType>())
return nullptr;
}
return firstArg;
}
void diagnoseUnintendedInterpolation(Expr * arg, UnintendedInterpolationKind kind) {
Ctx.Diags
.diagnose(arg->getStartLoc(),
diag::debug_description_in_string_interpolation_segment,
(bool)kind)
.highlight(arg->getSourceRange());
// Suggest 'String(describing: <expr>)'.
auto argStart = arg->getStartLoc();
Ctx.Diags
.diagnose(
arg->getLoc(),
diag::silence_debug_description_in_interpolation_segment_call)
.highlight(arg->getSourceRange())
.fixItInsert(argStart, "String(describing: ")
.fixItInsertAfter(arg->getEndLoc(), ")");
if (kind == UnintendedInterpolationKind::Optional) {
// Suggest inserting a default value.
Ctx.Diags.diagnose(arg->getLoc(), diag::default_optional_to_any)
.highlight(arg->getSourceRange())
.fixItInsertAfter(arg->getEndLoc(), " ?? <#default value#>");
}
}
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return Action::SkipNode(E);
if (IgnoredExprs.count(E))
return Action::Continue(E);
if (auto *literal = dyn_cast<InterpolatedStringLiteralExpr>(E)) {
visitInterpolatedStringLiteralExpr(literal);
} else if (auto *coercion = dyn_cast<CoerceExpr>(E)) {
// If we come across a CoerceExpr, visit its subExpr with the coercion
// as the parent, making sure we don't re-visit the subExpr later.
auto subExpr = coercion->getSubExpr();
visitPossibleOptionalToAnyExpr(subExpr,
{ subExpr->getType(), coercion });
IgnoredExprs.insert(subExpr);
} else {
visitPossibleOptionalToAnyExpr(E, { E->getType(), nullptr });
}
return Action::Continue(E);
}
public:
UnintendedOptionalBehaviorWalker(ASTContext &ctx) : Ctx(ctx) { }
};
UnintendedOptionalBehaviorWalker Walker(DC->getASTContext());
const_cast<Expr *>(E)->walk(Walker);
}
static void diagnoseDeprecatedWritableKeyPath(const Expr *E,
const DeclContext *DC) {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return;
class DeprecatedWritableKeyPathWalker : public ASTWalker {
ASTContext &Ctx;
const DeclContext *DC;
void visitKeyPathApplicationExpr(KeyPathApplicationExpr *E) {
bool isWrite = false;
if (auto *P = Parent.getAsExpr())
if (auto *AE = dyn_cast<AssignExpr>(P))
if (AE->getDest() == E)
isWrite = true;
if (!isWrite)
return;
if (auto *keyPathExpr = dyn_cast<KeyPathExpr>(E->getKeyPath())) {
if (!keyPathExpr->getType()->isWritableKeyPath() &&
!keyPathExpr->getType()->isReferenceWritableKeyPath())
return;
assert(keyPathExpr->getComponents().size() > 0);
auto &component = keyPathExpr->getComponents().back();
if (component.getKind() == KeyPathExpr::Component::Kind::Property) {
auto *storage =
cast<AbstractStorageDecl>(component.getDeclRef().getDecl());
if (!storage->isSettable(nullptr) ||
!storage->isSetterAccessibleFrom(DC)) {
Ctx.Diags.diagnose(keyPathExpr->getLoc(),
swift::diag::expr_deprecated_writable_keypath,
storage);
}
}
}
}
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
bool shouldWalkCaptureInitializerExpressions() override { return true; }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return Action::SkipNode(E);
if (auto *KPAE = dyn_cast<KeyPathApplicationExpr>(E)) {
visitKeyPathApplicationExpr(KPAE);
return Action::Continue(E);
}
return Action::Continue(E);
}
public:
DeprecatedWritableKeyPathWalker(const DeclContext *DC)
: Ctx(DC->getASTContext()), DC(DC) {}
};
DeprecatedWritableKeyPathWalker Walker(DC);
const_cast<Expr *>(E)->walk(Walker);
}
static void maybeDiagnoseCallToKeyValueObserveMethod(const Expr *E,
const DeclContext *DC) {
class KVOObserveCallWalker : public ASTWalker {
const ASTContext &C;
public:
KVOObserveCallWalker(ASTContext &ctx) : C(ctx) {}
void maybeDiagnoseCallExpr(CallExpr *expr) {
auto fn = expr->getCalledValue(/*skipFunctionConversions=*/true);
if (!fn)
return;
SmallVector<KeyPathExpr *, 1> keyPathArgs;
auto *args = expr->getArgs();
auto isKeyPathLiteral = [&](Expr *argExpr) -> KeyPathExpr * {
if (auto *DTBE = getAsExpr<DerivedToBaseExpr>(argExpr))
argExpr = DTBE->getSubExpr();
// Sendable key path literals are represented as an existential
// protocol composition with `Sendable` protocol which has to be
// opened in certain scenarios i.e. to pass it to non-Sendable version.
if (auto *OEE = getAsExpr<OpenExistentialExpr>(argExpr))
argExpr = OEE->getExistentialValue();
return getAsExpr<KeyPathExpr>(argExpr);
};
if (fn->getModuleContext()->getName() == C.Id_Foundation &&
fn->getName().isCompoundName("observe",
{"", "options", "changeHandler"})) {
if (auto keyPathArg = isKeyPathLiteral(args->getExpr(0))) {
keyPathArgs.push_back(keyPathArg);
}
} else if (fn->getAttrs()
.hasSemanticsAttr(semantics::KEYPATH_MUST_BE_VALID_FOR_KVO)) {
for (auto *argExpr : args->getArgExprs()) {
if (auto keyPathArg = isKeyPathLiteral(argExpr)) {
keyPathArgs.push_back(keyPathArg);
}
}
}
for (auto *keyPathArg : keyPathArgs) {
auto lastComponent = keyPathArg->getComponents().back();
if (lastComponent.getKind() != KeyPathExpr::Component::Kind::Property)
continue;
auto property = lastComponent.getDeclRef().getDecl();
if (!property)
continue;
auto propertyVar = cast<VarDecl>(property);
if (propertyVar->shouldUseObjCDispatch() ||
(propertyVar->isObjC() &&
propertyVar->getParsedAccessor(AccessorKind::Set)))
continue;
C.Diags
.diagnose(expr->getLoc(),
diag::observe_keypath_property_not_objc_dynamic,
property->getName(), fn->getName())
.highlight(lastComponent.getLoc());
}
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return Action::SkipNode(E);
if (auto *CE = dyn_cast<CallExpr>(E)) {
maybeDiagnoseCallExpr(CE);
return Action::SkipNode(E);
}
return Action::Continue(E);
}
};
KVOObserveCallWalker Walker(DC->getASTContext());
const_cast<Expr *>(E)->walk(Walker);
}
static void diagnoseExplicitUseOfLazyVariableStorage(const Expr *E,
const DeclContext *DC) {
class ExplicitLazyVarStorageAccessFinder : public ASTWalker {
const ASTContext &C;
public:
ExplicitLazyVarStorageAccessFinder(ASTContext &ctx) : C(ctx) {}
void tryDiagnoseExplicitLazyStorageVariableUse(MemberRefExpr *MRE) {
if (MRE->isImplicit()) {
return;
}
auto VD = dyn_cast<VarDecl>(MRE->getMember().getDecl());
if (!VD) {
return;
}
auto sourceFileKind = VD->getDeclContext()->getParentSourceFile();
if (!sourceFileKind) {
return;
}
if (sourceFileKind->Kind != SourceFileKind::Library &&
sourceFileKind->Kind != SourceFileKind::Main) {
return;
}
if (VD->isLazyStorageProperty()) {
C.Diags.diagnose(MRE->getLoc(), diag::lazy_var_storage_access);
}
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return Action::SkipNode(E);
if (auto *MRE = dyn_cast<MemberRefExpr>(E)) {
tryDiagnoseExplicitLazyStorageVariableUse(MRE);
return Action::SkipNode(E);
}
return Action::Continue(E);
}
};
ExplicitLazyVarStorageAccessFinder Walker(DC->getASTContext());
const_cast<Expr *>(E)->walk(Walker);
}
static void diagnoseComparisonWithNaN(const Expr *E, const DeclContext *DC) {
class ComparisonWithNaNFinder : public ASTWalker {
const ASTContext &C;
const DeclContext *DC;
public:
ComparisonWithNaNFinder(const DeclContext *dc)
: C(dc->getASTContext()), DC(dc) {}
void tryDiagnoseComparisonWithNaN(BinaryExpr *BE) {
ValueDecl *comparisonDecl = nullptr;
// Dig out the function declaration.
if (auto Fn = BE->getFn()) {
if (auto DSCE = dyn_cast<DotSyntaxCallExpr>(Fn)) {
comparisonDecl =
DSCE->getCalledValue(/*skipFunctionConversions=*/true);
} else {
comparisonDecl = BE->getCalledValue(/*skipFunctionConversions=*/true);
}
}
// Bail out if it isn't a function.
if (!comparisonDecl || !isa<FuncDecl>(comparisonDecl)) {
return;
}
// We're only interested in comparison functions like == or <=.
auto comparisonDeclName = comparisonDecl->getBaseIdentifier();
if (!comparisonDeclName.isStandardComparisonOperator()) {
return;
}
auto *firstArg = BE->getLHS();
auto *secondArg = BE->getRHS();
// Make sure that both arguments are valid before doing anything else,
// this helps us to debug reports of crashes in `conformsToKnownProtocol`
// referencing arguments (rdar://78920375).
//
// Since this diagnostic should only be run on type-checked AST,
// it's unclear what caused one of the arguments to have null type.
assert(firstArg->getType() && "Expected valid type for first argument");
assert(secondArg->getType() && "Expected valid type for second argument");
// Both arguments must conform to FloatingPoint protocol.
if (!TypeChecker::conformsToKnownProtocol(firstArg->getType(),
KnownProtocolKind::FloatingPoint,
DC->getParentModule()) ||
!TypeChecker::conformsToKnownProtocol(secondArg->getType(),
KnownProtocolKind::FloatingPoint,
DC->getParentModule())) {
return;
}
// Convenience utility to extract argument decl.
auto extractArgumentDecl = [&](Expr *arg) -> ValueDecl * {
if (auto DRE = dyn_cast<DeclRefExpr>(arg)) {
return DRE->getDecl();
} else if (auto MRE = dyn_cast<MemberRefExpr>(arg)) {
return MRE->getMember().getDecl();
}
return nullptr;
};
// Dig out the declarations for the arguments.
auto *firstVal = extractArgumentDecl(firstArg);
auto *secondVal = extractArgumentDecl(secondArg);
// If we can't find declarations for both arguments, bail out,
// because one of them has to be '.nan'.
if (!firstArg && !secondArg) {
return;
}
// Convenience utility to check if this is a 'nan' variable.
auto isNanDecl = [&](ValueDecl *VD) {
return VD && isa<VarDecl>(VD) && VD->getBaseIdentifier().is("nan");
};
// Diagnose comparison with '.nan'.
//
// If the comparison is done using '<=', '<', '==', '>', '>=', then
// the result is always false. If the comparison is done using '!=',
// then the result is always true.
//
// Emit a different diagnostic which doesn't mention using '.isNaN' if
// the comparison isn't done using '==' or '!=' or if both sides are
// '.nan'.
if (isNanDecl(firstVal) && isNanDecl(secondVal)) {
C.Diags.diagnose(BE->getLoc(), diag::nan_comparison_both_nan,
comparisonDeclName.str(), comparisonDeclName.is("!="));
} else if (isNanDecl(firstVal) || isNanDecl(secondVal)) {
if (comparisonDeclName.is("==") || comparisonDeclName.is("!=")) {
auto exprStr =
C.SourceMgr
.extractText(Lexer::getCharSourceRangeFromSourceRange(
C.SourceMgr, firstArg->getSourceRange()))
.str();
auto prefix = exprStr;
if (comparisonDeclName.is("!=")) {
prefix = "!" + prefix;
}
C.Diags.diagnose(BE->getLoc(), diag::nan_comparison,
comparisonDeclName, comparisonDeclName.is("!="),
prefix, exprStr);
} else {
C.Diags.diagnose(BE->getLoc(), diag::nan_comparison_without_isnan,
comparisonDeclName, comparisonDeclName.is("!="));
}
}
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return Action::SkipNode(E);
if (auto *BE = dyn_cast<BinaryExpr>(E)) {
tryDiagnoseComparisonWithNaN(BE);
return Action::SkipNode(E);
}
return Action::Continue(E);
}
};
ComparisonWithNaNFinder Walker(DC);
const_cast<Expr *>(E)->walk(Walker);
}
static void diagUnqualifiedAccessToMethodNamedSelf(const Expr *E,
const DeclContext *DC) {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return;
class DiagnoseWalker : public ASTWalker {
ASTContext &Ctx;
const DeclContext *DC;
public:
DiagnoseWalker(const DeclContext *DC) : Ctx(DC->getASTContext()), DC(DC) {}
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (!E || isa<ErrorExpr>(E) || !E->getType())
return Action::SkipNode(E);
auto *DRE = dyn_cast<DeclRefExpr>(E);
// If this is not an explicit 'self' reference, let's keep searching.
if (!DRE || DRE->isImplicit())
return Action::Continue(E);
// If this not 'self' or it's not a function reference, it's unrelated.
if (!(DRE->getDecl()->getBaseName() == Ctx.Id_self &&
DRE->getType()->is<AnyFunctionType>()))
return Action::Continue(E);
auto typeContext = DC->getInnermostTypeContext();
// Use of 'self' in enums is not confusable.
if (!typeContext || typeContext->getSelfEnumDecl())
return Action::Continue(E);
// self(...) is not easily confusable.
if (auto *parentExpr = Parent.getAsExpr()) {
if (isa<CallExpr>(parentExpr))
return Action::Continue(E);
// Explicit call to a static method 'self' of some type is not
// confusable.
if (isa<DotSyntaxCallExpr>(parentExpr) && !parentExpr->isImplicit())
return Action::Continue(E);
}
auto baseType = typeContext->getDeclaredInterfaceType();
auto baseTypeString = baseType.getString();
Ctx.Diags.diagnose(E->getLoc(), diag::self_refers_to_method,
baseTypeString);
Ctx.Diags
.diagnose(E->getLoc(), diag::fix_unqualified_access_member_named_self,
baseTypeString)
.fixItInsert(E->getLoc(), diag::insert_type_qualification, baseType);
return Action::Continue(E);
}
};
DiagnoseWalker Walker(DC);
const_cast<Expr *>(E)->walk(Walker);
}
static void
diagnoseDictionaryLiteralDuplicateKeyEntries(const Expr *E,
const DeclContext *DC) {
class DiagnoseWalker : public ASTWalker {
ASTContext &Ctx;
private:
std::string getKeyStringValue(const LiteralExpr *keyExpr) {
if (auto *MLE = dyn_cast<MagicIdentifierLiteralExpr>(keyExpr)) {
return getMagicLiteralKeyValue(MLE);
}
std::string out;
llvm::raw_string_ostream OS(out);
keyExpr->printConstExprValue(&OS, /*additionalCheck=*/nullptr);
return out;
}
std::string getMagicLiteralKeyValue(const MagicIdentifierLiteralExpr *MLE) {
auto magicLiteralValue = MLE->getLiteralKindDescription().str();
switch (MLE->getKind()) {
case MagicIdentifierLiteralExpr::DSOHandle:
case MagicIdentifierLiteralExpr::FileID:
case MagicIdentifierLiteralExpr::FileIDSpelledAsFile:
case MagicIdentifierLiteralExpr::FilePath:
case MagicIdentifierLiteralExpr::FilePathSpelledAsFile:
case MagicIdentifierLiteralExpr::Function:
break;
// Those are literals that can evaluate to different values in a
// dictionary literal declaration context based on source position
// so we need to consider that position as part of the literal value.
case MagicIdentifierLiteralExpr::Column: {
unsigned int column;
std::tie(std::ignore, column) =
Ctx.SourceMgr.getPresumedLineAndColumnForLoc(MLE->getStartLoc());
magicLiteralValue += ":" + std::to_string(column);
break;
}
case MagicIdentifierLiteralExpr::Line: {
unsigned int line;
std::tie(line, std::ignore) =
Ctx.SourceMgr.getPresumedLineAndColumnForLoc(MLE->getStartLoc());
magicLiteralValue += ":" + std::to_string(line);
break;
}
}
return magicLiteralValue;
}
std::string getKeyStringValueForDiagnostic(const LiteralExpr *keyExpr) {
std::string out;
switch (keyExpr->getKind()) {
case ExprKind::NilLiteral:
case ExprKind::MagicIdentifierLiteral:
return out;
case ExprKind::StringLiteral: {
const auto *SL = cast<StringLiteralExpr>(keyExpr);
out = SL->getValue().str();
break;
}
default:
llvm::raw_string_ostream OS(out);
keyExpr->printConstExprValue(&OS, /*additionalCheck=*/nullptr);
break;
}
return "'" + out + "'";
}
bool shouldDiagnoseLiteral(const LiteralExpr *LE) {
switch (LE->getKind()) {
case ExprKind::IntegerLiteral:
case ExprKind::FloatLiteral:
case ExprKind::BooleanLiteral:
case ExprKind::StringLiteral:
case ExprKind::MagicIdentifierLiteral:
case ExprKind::NilLiteral:
return true;
// Skip interpolated literals because they
// can contain expressions that although equal
// maybe be evaluated to different values. e.g.
// "\(a) \(a)" where 'a' is a computed variable.
case ExprKind::InterpolatedStringLiteral:
// Also skip object literals as most of them takes paramenters that can
// contain expressions that altough equal may evaluate to different
// values e.g. #fileLiteral(resourceName: a) where 'a' is a computed
// property is valid.
case ExprKind::ObjectLiteral:
// Literal expressions produce Regex<Out> type result,
// which cannot be keys due to not conforming to hashable.
case ExprKind::RegexLiteral:
return false;
// If a new literal is added in the future, the compiler
// will warn that a case is missing from this switch.
#define LITERAL_EXPR(Id, Parent)
#define EXPR(Id, Parent) case ExprKind::Id:
#include "swift/AST/ExprNodes.def"
llvm_unreachable("Not a literal expression");
}
llvm_unreachable("Unhandled literal");
}
public:
DiagnoseWalker(const DeclContext *DC) : Ctx(DC->getASTContext()) {}
bool shouldWalkIntoSeparatelyCheckedClosure(ClosureExpr *expr) override {
return false;
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Expansion;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
const auto *DLE = dyn_cast_or_null<DictionaryExpr>(E);
if (!DLE)
return Action::Continue(E);
auto type = DLE->getType();
// For other types conforming with `ExpressibleByDictionaryLiteral`
// protocol, duplicated keys may be allowed.
if (!(type && type->isDictionary())) {
return Action::Continue(E);
}
using LiteralKey = std::pair<std::string, ExprKind>;
using Element = std::pair<const TupleExpr *, size_t>;
std::map<LiteralKey, llvm::SmallVector<Element, 4>> groupedLiteralKeys;
for (size_t i = 0; i < DLE->getElements().size(); ++i) {
const auto *elt = DLE->getElement(i);
const auto *tupleElt = cast<TupleExpr>(elt);
const auto *keyExpr =
tupleElt->getElement(0)->getSemanticsProvidingExpr();
auto *LE = dyn_cast<LiteralExpr>(keyExpr);
if (!LE)
continue;
if (!shouldDiagnoseLiteral(LE))
continue;
auto keyStringValue = getKeyStringValue(LE);
auto literalKey = std::make_pair(keyStringValue, keyExpr->getKind());
groupedLiteralKeys[literalKey].push_back({tupleElt, i});
}
// All keys are unique.
if (groupedLiteralKeys.size() == DLE->getNumElements()) {
return Action::Continue(E);
}
auto &DE = Ctx.Diags;
auto emitNoteWithFixit = [&](const Element &duplicated) {
auto note = DE.diagnose(duplicated.first->getLoc(),
diag::duplicated_key_declared_here);
auto duplicatedEltIdx = duplicated.second;
const auto commanLocs = DLE->getCommaLocs();
note.fixItRemove(duplicated.first->getSourceRange());
if (duplicatedEltIdx < commanLocs.size()) {
note.fixItRemove(commanLocs[duplicatedEltIdx]);
} else {
// For the last element remove the previous comma.
note.fixItRemove(commanLocs[duplicatedEltIdx - 1]);
}
};
for (auto &entry : groupedLiteralKeys) {
auto &keyValuePairs = entry.second;
if (keyValuePairs.size() == 1) {
continue;
}
auto elt = keyValuePairs.front();
const auto keyValue = entry.first.first;
const auto keyExpr = cast<LiteralExpr>(
elt.first->getElement(0)->getSemanticsProvidingExpr());
const auto value = getKeyStringValueForDiagnostic(keyExpr);
DE.diagnose(elt.first->getLoc(),
diag::duplicated_literal_keys_in_dictionary_literal, type,
keyExpr->getLiteralKindDescription(), value.empty(), value);
for (auto &duplicated : keyValuePairs) {
emitNoteWithFixit(duplicated);
}
}
return Action::Continue(E);
}
};
DiagnoseWalker Walker(DC);
const_cast<Expr *>(E)->walk(Walker);
}
//===----------------------------------------------------------------------===//
// High-level entry points.
//===----------------------------------------------------------------------===//
/// Emit diagnostics for syntactic restrictions on a given expression.
void swift::performSyntacticExprDiagnostics(
const Expr *E, const DeclContext *DC,
std::optional<ContextualTypePurpose> contextualPurpose, bool isExprStmt,
bool disableExprAvailabilityChecking, bool disableOutOfPlaceExprChecking) {
auto &ctx = DC->getASTContext();
TypeChecker::diagnoseSelfAssignment(E);
diagSyntacticUseRestrictions(E, DC, isExprStmt);
diagRecursivePropertyAccess(E, DC);
diagnoseImplicitSelfUseInClosure(E, DC);
diagnoseUnintendedOptionalBehavior(E, DC);
maybeDiagnoseCallToKeyValueObserveMethod(E, DC);
diagnoseExplicitUseOfLazyVariableStorage(E, DC);
diagnoseComparisonWithNaN(E, DC);
if (!ctx.isSwiftVersionAtLeast(5))
diagnoseDeprecatedWritableKeyPath(E, DC);
if (!ctx.LangOpts.DisableAvailabilityChecking && !disableExprAvailabilityChecking)
diagnoseExprAvailability(E, const_cast<DeclContext*>(DC));
if (ctx.LangOpts.EnableObjCInterop)
diagDeprecatedObjCSelectors(DC, E);
diagnoseConstantArgumentRequirement(E, DC);
diagUnqualifiedAccessToMethodNamedSelf(E, DC);
diagnoseDictionaryLiteralDuplicateKeyEntries(E, DC);
if (!disableOutOfPlaceExprChecking)
diagnoseOutOfPlaceExprs(ctx, const_cast<Expr *>(E), contextualPurpose);
}
void swift::performStmtDiagnostics(const Stmt *S, DeclContext *DC) {
auto &ctx = DC->getASTContext();
TypeChecker::checkExistentialTypes(ctx, const_cast<Stmt *>(S), DC);
if (auto switchStmt = dyn_cast<SwitchStmt>(S))
checkSwitch(ctx, switchStmt, DC);
checkStmtConditionTrailingClosure(ctx, S);
if (auto *lcs = dyn_cast<LabeledConditionalStmt>(S))
checkLabeledStmtConditions(ctx, lcs, DC);
if (!ctx.LangOpts.DisableAvailabilityChecking)
diagnoseStmtAvailability(S, const_cast<DeclContext*>(DC));
}
//===----------------------------------------------------------------------===//
// Utility functions
//===----------------------------------------------------------------------===//
void swift::fixItAccess(InFlightDiagnostic &diag, ValueDecl *VD,
AccessLevel desiredAccess, bool isForSetter,
bool shouldUseDefaultAccess) {
StringRef fixItString;
switch (desiredAccess) {
case AccessLevel::Private: fixItString = "private "; break;
case AccessLevel::FilePrivate: fixItString = "fileprivate "; break;
case AccessLevel::Internal: fixItString = "internal "; break;
case AccessLevel::Package: fixItString = "package "; break;
case AccessLevel::Public: fixItString = "public "; break;
case AccessLevel::Open: fixItString = "open "; break;
}
DeclAttributes &attrs = VD->getAttrs();
AbstractAccessControlAttr *attr;
if (isForSetter) {
attr = attrs.getAttribute<SetterAccessAttr>();
cast<AbstractStorageDecl>(VD)->overwriteSetterAccess(desiredAccess);
} else {
attr = attrs.getAttribute<AccessControlAttr>();
VD->overwriteAccess(desiredAccess);
if (auto *ASD = dyn_cast<AbstractStorageDecl>(VD)) {
if (auto *getter = ASD->getAccessor(AccessorKind::Get))
getter->overwriteAccess(desiredAccess);
if (auto *setterAttr = attrs.getAttribute<SetterAccessAttr>()) {
if (setterAttr->getAccess() > desiredAccess)
fixItAccess(diag, VD, desiredAccess, true);
} else {
ASD->overwriteSetterAccess(desiredAccess);
}
}
}
if (isForSetter && VD->getFormalAccess() == desiredAccess) {
assert(attr);
attr->setInvalid();
// Remove the setter attribute.
diag.fixItRemove(attr->Range);
} else if (attr) {
// If the formal access already matches the desired access, the problem
// must be in a parent scope. Don't emit a fix-it.
// FIXME: It's also possible for access to already be /broader/ than what's
// desired, in which case the problem is also in a parent scope. However,
// this function is sometimes called to make access narrower, so assuming
// that a broader scope is acceptable breaks some diagnostics.
if (attr->getAccess() != desiredAccess) {
if (shouldUseDefaultAccess) {
// Remove the attribute if replacement is not preferred.
diag.fixItRemove(attr->getRange());
} else {
// This uses getLocation() instead of getRange() because we don't want to
// replace the "(set)" part of a setter attribute.
diag.fixItReplace(attr->getLocation(), fixItString.drop_back());
}
attr->setInvalid();
}
} else if (auto *override = VD->getAttrs().getAttribute<OverrideAttr>()) {
// Insert the access in front of 'override', if it exists, in order to
// match the same keyword order as produced by method autocompletion.
diag.fixItInsert(override->getLocation(), fixItString);
} else if (auto var = dyn_cast<VarDecl>(VD)) {
if (auto PBD = var->getParentPatternBinding())
diag.fixItInsert(PBD->getStartLoc(), fixItString);
} else {
diag.fixItInsert(VD->getStartLoc(), fixItString);
}
}
/// Retrieve the type name to be used for determining whether we can
/// omit needless words.
static OmissionTypeName getTypeNameForOmission(Type type) {
if (!type)
return "";
ASTContext &ctx = type->getASTContext();
auto objcBoolType = ctx.getObjCBoolType();
/// Determine the options associated with the given type.
auto getOptions = [&](Type type) {
// Look for Boolean types.
OmissionTypeOptions options;
// Look for Boolean types.
if (type->isBool()) {
// Swift.Bool
options |= OmissionTypeFlags::Boolean;
} else if (objcBoolType && type->isEqual(objcBoolType)) {
// ObjectiveC.ObjCBool
options |= OmissionTypeFlags::Boolean;
}
return options;
};
do {
// Look through typealiases.
if (auto aliasTy = dyn_cast<TypeAliasType>(type.getPointer())) {
type = aliasTy->getSinglyDesugaredType();
continue;
}
// Strip off lvalue/inout types.
Type newType = type->getWithoutSpecifierType();
if (newType.getPointer() != type.getPointer()) {
type = newType;
continue;
}
// Look through reference-storage types.
newType = type->getReferenceStorageReferent();
if (newType.getPointer() != type.getPointer()) {
type = newType;
continue;
}
// Look through parentheses.
type = type->getWithoutParens();
// Look through optionals.
if (auto optObjectTy = type->getOptionalObjectType()) {
type = optObjectTy;
continue;
}
break;
} while (true);
// Nominal types.
if (auto nominal = type->getAnyNominal()) {
// If we have a collection, get the element type.
if (auto bound = type->getAs<BoundGenericType>()) {
auto args = bound->getGenericArgs();
if (!args.empty() && (bound->isArray() || bound->isSet())) {
return OmissionTypeName(nominal->getName().str(),
getOptions(bound),
getTypeNameForOmission(args[0]).Name);
}
}
// AnyObject -> "Object".
if (type->isAnyObject())
return "Object";
return OmissionTypeName(nominal->getName().str(), getOptions(type));
}
// Generic type parameters.
if (auto genericParamTy = type->getAs<GenericTypeParamType>()) {
if (auto genericParam = genericParamTy->getDecl())
return genericParam->getName().str();
return "";
}
// Dependent members.
if (auto dependentMemberTy = type->getAs<DependentMemberType>()) {
return dependentMemberTy->getName().str();
}
// Archetypes.
if (auto archetypeTy = type->getAs<ArchetypeType>()) {
return archetypeTy->getName().str();
}
// Function types.
if (auto funcTy = type->getAs<AnyFunctionType>()) {
if (funcTy->getRepresentation() == AnyFunctionType::Representation::Block)
return "Block";
return "Function";
}
return "";
}
std::optional<DeclName>
TypeChecker::omitNeedlessWords(AbstractFunctionDecl *afd) {
auto &Context = afd->getASTContext();
if (afd->isInvalid() || isa<DestructorDecl>(afd))
return std::nullopt;
const DeclName name = afd->getName();
if (!name)
return std::nullopt;
// String'ify the arguments.
StringRef baseNameStr = name.getBaseName().userFacingName();
SmallVector<StringRef, 4> argNameStrs;
for (auto arg : name.getArgumentNames()) {
if (arg.empty())
argNameStrs.push_back("");
else
argNameStrs.push_back(arg.str());
}
// String'ify the parameter types.
SmallVector<OmissionTypeName, 4> paramTypes;
// Always look at the parameters in the last parameter list.
for (auto param : *afd->getParameters()) {
paramTypes.push_back(getTypeNameForOmission(param->getInterfaceType())
.withDefaultArgument(param->isDefaultArgument()));
}
// Handle contextual type, result type, and returnsSelf.
Type contextType = afd->getDeclContext()->getDeclaredInterfaceType();
Type resultType;
bool returnsSelf = afd->hasDynamicSelfResult();
if (auto func = dyn_cast<FuncDecl>(afd)) {
resultType = func->getResultInterfaceType();
resultType = func->mapTypeIntoContext(resultType);
} else if (isa<ConstructorDecl>(afd)) {
resultType = contextType;
}
// Figure out the first parameter name.
StringRef firstParamName;
auto params = afd->getParameters();
if (params->size() != 0 && !params->get(0)->getName().empty())
firstParamName = params->get(0)->getName().str();
StringScratchSpace scratch;
if (!swift::omitNeedlessWords(
baseNameStr, argNameStrs, firstParamName,
getTypeNameForOmission(resultType),
getTypeNameForOmission(contextType), paramTypes, returnsSelf, false,
/*allPropertyNames=*/nullptr, std::nullopt, std::nullopt, scratch))
return std::nullopt;
/// Retrieve a replacement identifier.
auto getReplacementIdentifier = [&](StringRef name,
DeclBaseName old) -> DeclBaseName{
if (name.empty())
return Identifier();
if (!old.empty() && name == old.userFacingName())
return old;
return Context.getIdentifier(name);
};
auto newBaseName = getReplacementIdentifier(
baseNameStr, name.getBaseName());
SmallVector<Identifier, 4> newArgNames;
auto oldArgNames = name.getArgumentNames();
for (unsigned i = 0, n = argNameStrs.size(); i != n; ++i) {
auto argBaseName = getReplacementIdentifier(argNameStrs[i],
oldArgNames[i]);
newArgNames.push_back(argBaseName.getIdentifier());
}
return DeclName(Context, newBaseName, newArgNames);
}
std::optional<Identifier> TypeChecker::omitNeedlessWords(VarDecl *var) {
auto &Context = var->getASTContext();
if (var->isInvalid())
return std::nullopt;
if (var->getName().empty())
return std::nullopt;
auto name = var->getName().str();
// Dig out the context type.
Type contextType = var->getDeclContext()->getDeclaredInterfaceType();
if (!contextType)
return std::nullopt;
// Dig out the type of the variable.
Type type = var->getValueInterfaceType();
while (auto optObjectTy = type->getOptionalObjectType())
type = optObjectTy;
// Omit needless words.
StringScratchSpace scratch;
OmissionTypeName typeName = getTypeNameForOmission(var->getInterfaceType());
OmissionTypeName contextTypeName = getTypeNameForOmission(contextType);
if (::omitNeedlessWords(name, {}, "", typeName, contextTypeName, {},
/*returnsSelf=*/false, true,
/*allPropertyNames=*/nullptr, std::nullopt,
std::nullopt, scratch)) {
return Context.getIdentifier(name);
}
return std::nullopt;
}
bool swift::diagnoseUnhandledThrowsInAsyncContext(DeclContext *dc,
ForEachStmt *forEach) {
auto &ctx = dc->getASTContext();
if (auto thrownError = TypeChecker::canThrow(ctx, forEach)) {
if (forEach->getTryLoc().isInvalid()) {
ctx.Diags
.diagnose(forEach->getAwaitLoc(), diag::throwing_call_unhandled, "call")
.fixItInsert(forEach->getAwaitLoc(), "try");
return true;
}
}
return false;
}
void DeferredDiag::emit(swift::ASTContext &ctx) {
assert(loc && "no loc... already emitted?");
ctx.Diags.diagnose(loc, diag);
loc = SourceLoc();
}
|