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
|
//===--- ParseStmt.cpp - Swift Language Parser for Statements -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Statement Parsing and AST Building
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/AST/FileUnit.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Version.h"
#include "swift/Parse/IDEInspectionCallbacks.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
/// isStartOfStmt - Return true if the current token starts a statement.
///
bool Parser::isStartOfStmt(bool preferExpr) {
// This needs to be kept in sync with `Parser::parseStmt()`. If a new token
// kind is accepted here as start of statement, it should also be handled in
// `Parser::parseStmt()`.
switch (Tok.getKind()) {
default: return false;
case tok::kw_return:
case tok::kw_throw:
case tok::kw_defer:
case tok::kw_if:
case tok::kw_guard:
case tok::kw_while:
case tok::kw_do:
case tok::kw_for:
case tok::kw_break:
case tok::kw_continue:
case tok::kw_fallthrough:
case tok::kw_switch:
case tok::kw_case:
case tok::kw_default:
case tok::kw_yield:
case tok::kw_discard:
case tok::pound_assert:
case tok::pound_if:
case tok::pound_warning:
case tok::pound_error:
case tok::pound_sourceLocation:
return true;
case tok::kw_repeat:
// 'repeat' followed by anything other than a brace stmt
// is a pack expansion expression.
// FIXME: 'repeat' followed by '{' could be a pack expansion
// with a closure pattern.
return peekToken().is(tok::l_brace);
case tok::pound_line:
// #line at the start of a line is a directive, when within, it is an expr.
return Tok.isAtStartOfLine();
case tok::kw_try: {
// "try" cannot actually start any statements, but we parse it there for
// better recovery in cases like 'try return'.
// For 'if', 'switch', and 'do' we can parse as an expression.
if (peekToken().isAny(tok::kw_if, tok::kw_switch) ||
(peekToken().is(tok::kw_do) &&
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
return false;
}
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::kw_try);
return isStartOfStmt(preferExpr);
}
case tok::identifier: {
// "identifier ':' for/while/do/switch" is a label on a loop/switch.
if (!peekToken().is(tok::colon)) {
// "yield", "discard", and "then" in the right context begins a statement.
if (isContextualYieldKeyword() || isContextualDiscardKeyword() ||
isContextualThenKeyword(preferExpr)) {
return true;
}
return false;
}
// To disambiguate other cases of "identifier :", which might be part of a
// question colon expression or something else, we look ahead to the second
// token.
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::identifier);
consumeToken(tok::colon);
// We treating IDENTIFIER: { as start of statement to provide missed 'do'
// diagnostics. This case will be handled in parseStmt().
if (Tok.is(tok::l_brace)) {
return true;
}
// For better recovery, we just accept a label on any statement. We reject
// putting a label on something inappropriate in parseStmt().
return isStartOfStmt(preferExpr);
}
case tok::at_sign: {
// Might be a statement or case attribute. The only one of these we have
// right now is `@unknown default`, so hardcode a check for an attribute
// without any parens.
if (!peekToken().is(tok::identifier))
return false;
Parser::BacktrackingScope backtrack(*this);
consumeToken(tok::at_sign);
consumeToken(tok::identifier);
return isStartOfStmt(preferExpr);
}
}
}
ParserStatus Parser::parseExprOrStmt(ASTNode &Result) {
if (Tok.is(tok::semi)) {
diagnose(Tok, diag::illegal_semi_stmt)
.fixItRemove(SourceRange(Tok.getLoc()));
consumeToken();
return makeParserError();
}
if (Tok.is(tok::pound) && Tok.isAtStartOfLine() &&
peekToken().is(tok::code_complete)) {
consumeToken();
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeAfterPoundDirective();
}
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
if (isStartOfStmt(/*preferExpr*/ false)) {
ParserResult<Stmt> Res = parseStmt();
if (Res.isNonNull()) {
auto *S = Res.get();
// Special case: An 'if' or 'switch' statement followed by an 'as' must
// be an if/switch expression in a coercion.
// We could also achieve this by more eagerly attempting to parse an 'if'
// or 'switch' as an expression when in statement position, but that
// could result in less useful recovery behavior.
if ((isa<IfStmt>(S) || isa<SwitchStmt>(S) ||
((isa<DoStmt>(S) || isa<DoCatchStmt>(S)) &&
Context.LangOpts.hasFeature(Feature::DoExpressions))) &&
Tok.is(tok::kw_as)) {
auto *SVE = SingleValueStmtExpr::createWithWrappedBranches(
Context, S, CurDeclContext, /*mustBeExpr*/ true);
auto As = parseExprAs();
if (As.isParseErrorOrHasCompletion())
return As;
Result = SequenceExpr::create(Context, {SVE, As.get(), As.get()});
} else {
Result = S;
}
}
return Res;
}
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->setExprBeginning(getParserPosition());
}
if (Tok.is(tok::code_complete)) {
auto *CCE = new (Context) CodeCompletionExpr(Tok.getLoc());
Result = CCE;
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeStmtOrExpr(CCE);
}
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
ParserResult<Expr> ResultExpr = parseExpr(diag::expected_expr);
if (ResultExpr.isNonNull()) {
Result = ResultExpr.get();
} else if (!ResultExpr.hasCodeCompletion()) {
// If we've consumed any tokens at all, build an error expression
// covering the consumed range.
SourceLoc startLoc = StructureMarkers.back().Loc;
if (startLoc != Tok.getLoc()) {
Result = new (Context) ErrorExpr(SourceRange(startLoc, PreviousLoc));
}
}
return ResultExpr;
}
/// Returns whether the parser's current position is the start of a switch case,
/// given that we're in the middle of a switch already.
static bool isAtStartOfSwitchCase(Parser &parser,
bool needsToBacktrack = true) {
std::optional<Parser::BacktrackingScope> backtrack;
// Check for and consume attributes. The only valid attribute is `@unknown`
// but that's a semantic restriction.
while (parser.Tok.is(tok::at_sign)) {
if (!parser.peekToken().is(tok::identifier))
return false;
if (needsToBacktrack && !backtrack)
backtrack.emplace(parser);
parser.consumeToken(tok::at_sign);
parser.consumeToken(tok::identifier);
if (parser.Tok.is(tok::l_paren))
parser.skipSingle();
}
return parser.Tok.isAny(tok::kw_case, tok::kw_default);
}
bool Parser::isTerminatorForBraceItemListKind(BraceItemListKind Kind,
ArrayRef<ASTNode> ParsedDecls) {
switch (Kind) {
case BraceItemListKind::Brace:
case BraceItemListKind::TopLevelCode:
case BraceItemListKind::TopLevelLibrary:
case BraceItemListKind::MacroExpansion:
return false;
case BraceItemListKind::Case: {
if (Tok.is(tok::pound_if)) {
// Backtracking scopes are expensive, so avoid setting one up if possible.
Parser::BacktrackingScope Backtrack(*this);
// '#if' here could be to guard 'case:' or statements in cases.
// If the next non-directive line starts with 'case' or 'default', it is
// for 'case's.
do {
consumeToken();
// just find the end of the line
skipUntilTokenOrEndOfLine(tok::NUM_TOKENS);
} while (Tok.isAny(tok::pound_if, tok::pound_elseif, tok::pound_else));
return isAtStartOfSwitchCase(*this, /*needsToBacktrack*/false);
}
return isAtStartOfSwitchCase(*this);
}
case BraceItemListKind::ActiveConditionalBlock:
case BraceItemListKind::InactiveConditionalBlock:
return Tok.isNot(tok::pound_else) && Tok.isNot(tok::pound_endif) &&
Tok.isNot(tok::pound_elseif);
}
llvm_unreachable("Unhandled BraceItemListKind in switch.");
}
void Parser::consumeTopLevelDecl(ParserPosition BeginParserPosition,
TopLevelCodeDecl *TLCD) {
SourceLoc EndLoc = PreviousLoc;
backtrackToPosition(BeginParserPosition);
SourceLoc BeginLoc = Tok.getLoc();
State->setIDEInspectionDelayedDeclState(
SourceMgr, L->getBufferID(),
IDEInspectionDelayedDeclKind::TopLevelCodeDecl, TLCD, {BeginLoc, EndLoc},
BeginParserPosition.PreviousLoc);
// Skip the rest of the file to prevent the parser from constructing the AST
// for it. Forward references are not allowed at the top level.
while (!Tok.is(tok::eof))
consumeToken();
}
/// brace-item:
/// decl
/// expr
/// stmt
/// stmt:
/// ';'
/// stmt-assign
/// stmt-if
/// stmt-guard
/// stmt-for-c-style
/// stmt-for-each
/// stmt-switch
/// stmt-control-transfer
/// stmt-control-transfer:
/// stmt-return
/// stmt-break
/// stmt-continue
/// stmt-fallthrough
/// stmt-assign:
/// expr '=' expr
ParserStatus Parser::parseBraceItems(SmallVectorImpl<ASTNode> &Entries,
BraceItemListKind Kind,
BraceItemListKind ConditionalBlockKind,
bool &IsFollowingGuard) {
bool IsTopLevel = (Kind == BraceItemListKind::TopLevelCode) ||
(Kind == BraceItemListKind::TopLevelLibrary ||
(Kind == BraceItemListKind::MacroExpansion &&
isa<FileUnit>(CurDeclContext)));
bool isActiveConditionalBlock =
ConditionalBlockKind == BraceItemListKind::ActiveConditionalBlock;
bool isConditionalBlock = isActiveConditionalBlock ||
ConditionalBlockKind == BraceItemListKind::InactiveConditionalBlock;
ParserStatus BraceItemsStatus;
bool PreviousHadSemi = true;
while ((IsTopLevel || Tok.isNot(tok::r_brace)) &&
Tok.isNot(tok::pound_endif) &&
Tok.isNot(tok::pound_elseif) &&
Tok.isNot(tok::pound_else) &&
Tok.isNot(tok::eof) &&
!isStartOfSILDecl() &&
(isConditionalBlock ||
!isTerminatorForBraceItemListKind(Kind, Entries))) {
if (Tok.is(tok::r_brace)) {
assert(IsTopLevel);
diagnose(Tok, diag::extra_rbrace)
.fixItRemove(Tok.getLoc());
consumeToken();
continue;
}
// Eat invalid tokens instead of allowing them to produce downstream errors.
if (Tok.is(tok::unknown)) {
if (startsWithMultilineStringDelimiter(Tok)) {
// This was due to unterminated multi-line string.
IsInputIncomplete = true;
}
consumeToken();
continue;
}
bool NeedParseErrorRecovery = false;
ASTNode Result;
// If the previous statement didn't have a semicolon and this new
// statement doesn't start a line, complain.
const bool IsAtStartOfLineOrPreviousHadSemi =
PreviousHadSemi || Tok.isAtStartOfLine();
if (!IsAtStartOfLineOrPreviousHadSemi) {
SourceLoc EndOfPreviousLoc = getEndOfPreviousLoc();
diagnose(EndOfPreviousLoc, diag::statement_same_line_without_semi)
.fixItInsert(EndOfPreviousLoc, ";");
// FIXME: Add semicolon to the AST?
}
ParserPosition BeginParserPosition;
if (isIDEInspectionFirstPass())
BeginParserPosition = getParserPosition();
// Parse the decl, stmt, or expression.
PreviousHadSemi = false;
if (Tok.is(tok::pound_if) && !isStartOfSwiftDecl()) {
auto IfConfigResult = parseIfConfig(
[&](SmallVectorImpl<ASTNode> &Elements, bool IsActive) {
parseBraceItems(Elements, Kind, IsActive
? BraceItemListKind::ActiveConditionalBlock
: BraceItemListKind::InactiveConditionalBlock,
IsFollowingGuard);
});
if (IfConfigResult.hasCodeCompletion() && isIDEInspectionFirstPass()) {
consumeDecl(BeginParserPosition, IsTopLevel);
return IfConfigResult;
}
BraceItemsStatus |= IfConfigResult;
if (auto ICD = IfConfigResult.getPtrOrNull()) {
Result = ICD;
// Add the #if block itself
Entries.push_back(ICD);
for (auto &Entry : ICD->getActiveClauseElements()) {
if (Entry.is<Decl *>() && isa<IfConfigDecl>(Entry.get<Decl *>()))
// Don't hoist nested '#if'.
continue;
Entries.push_back(Entry);
if (Entry.is<Decl *>())
Entry.get<Decl *>()->setEscapedFromIfConfig(true);
}
} else {
NeedParseErrorRecovery = true;
continue;
}
} else if (Tok.is(tok::pound_line)) {
ParserStatus Status = parseLineDirective(true);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isErrorOrHasCompletion();
} else if (Tok.is(tok::pound_sourceLocation)) {
ParserStatus Status = parseLineDirective(false);
BraceItemsStatus |= Status;
NeedParseErrorRecovery = Status.isErrorOrHasCompletion();
} else if (isStartOfSwiftDecl()) {
SmallVector<Decl*, 8> TmpDecls;
ParserResult<Decl> DeclResult =
parseDecl(IsAtStartOfLineOrPreviousHadSemi,
/*IfConfigsAreDeclAttrs=*/true, [&](Decl *D) {
TmpDecls.push_back(D);
// Any function after a 'guard' statement is marked as
// possibly having local captures. This allows SILGen
// to correctly determine its capture list, since
// otherwise it would be skipped because it is not
// defined inside a local context.
if (IsFollowingGuard)
if (auto *FD = dyn_cast<FuncDecl>(D))
FD->setHasTopLevelLocalContextCaptures();
});
BraceItemsStatus |= DeclResult;
if (DeclResult.isParseErrorOrHasCompletion()) {
NeedParseErrorRecovery = true;
if (DeclResult.hasCodeCompletion() && IsTopLevel &&
isIDEInspectionFirstPass()) {
consumeDecl(BeginParserPosition, IsTopLevel);
return DeclResult;
}
}
Result = DeclResult.getPtrOrNull();
Entries.append(TmpDecls.begin(), TmpDecls.end());
} else if (IsTopLevel) {
// If this is a statement or expression at the top level of the module,
// Parse it as a child of a TopLevelCodeDecl.
auto *TLCD = new (Context) TopLevelCodeDecl(CurDeclContext);
ContextChange CC(*this, TLCD);
SourceLoc StartLoc = Tok.getLoc();
// Expressions can't begin with a closure literal at statement position.
// This prevents potential ambiguities with trailing closure syntax.
if (Tok.is(tok::l_brace)) {
diagnose(Tok, diag::statement_begins_with_closure);
}
ParserStatus Status = parseExprOrStmt(Result);
BraceItemsStatus |= Status;
if (Status.hasCodeCompletion() && isIDEInspectionFirstPass()) {
consumeTopLevelDecl(BeginParserPosition, TLCD);
auto Brace = BraceStmt::create(Context, StartLoc, {}, PreviousLoc);
TLCD->setBody(Brace);
Entries.push_back(TLCD);
return Status;
}
if (Status.isErrorOrHasCompletion())
NeedParseErrorRecovery = true;
else if (!allowTopLevelCode()) {
diagnose(StartLoc,
Result.is<Stmt*>() ? diag::illegal_top_level_stmt
: diag::illegal_top_level_expr);
}
if (!Result.isNull()) {
// NOTE: this is a 'virtual' brace statement which does not have
// explicit '{' or '}', so the start and end locations should be
// the same as those of the result node, plus any junk consumed
// afterwards
auto Brace = BraceStmt::create(Context, Result.getStartLoc(),
Result, PreviousLoc, /*Implicit=*/true);
TLCD->setBody(Brace);
Entries.push_back(TLCD);
// A top-level 'guard' statement can introduce local bindings, so we
// must mark all functions following one. This makes them behave
// as if they were in local context for the purposes of capture
// emission in SILGen.
if (auto *stmt = Result.dyn_cast<Stmt *>())
if (isa<GuardStmt>(stmt))
IsFollowingGuard = true;
}
} else {
ParserStatus ExprOrStmtStatus = parseExprOrStmt(Result);
BraceItemsStatus |= ExprOrStmtStatus;
if (ExprOrStmtStatus.isError())
NeedParseErrorRecovery = true;
if (!Result.isNull())
Entries.push_back(Result);
}
if (!NeedParseErrorRecovery && Tok.is(tok::semi)) {
PreviousHadSemi = true;
if (auto *E = Result.dyn_cast<Expr*>())
E->TrailingSemiLoc = consumeToken(tok::semi);
else if (auto *S = Result.dyn_cast<Stmt*>())
S->TrailingSemiLoc = consumeToken(tok::semi);
else if (auto *D = Result.dyn_cast<Decl*>())
D->TrailingSemiLoc = consumeToken(tok::semi);
else
assert(!Result && "Unsupported AST node");
}
if (NeedParseErrorRecovery) {
// If we had a parse error, skip to the start of the next stmt or decl.
//
// It would be ideal to stop at the start of the next expression (e.g.
// "X = 4"), but distinguishing the start of an expression from the middle
// of one is "hard".
skipUntilDeclStmtRBrace();
// If we have to recover, pretend that we had a semicolon; it's less
// noisy that way.
PreviousHadSemi = true;
}
}
return BraceItemsStatus;
}
/// Recover from a 'case' or 'default' outside of a 'switch' by consuming up to
/// the next ':' or '}'.
static ParserResult<Stmt> recoverFromInvalidCase(Parser &P) {
assert(P.Tok.is(tok::kw_case) || P.Tok.is(tok::kw_default)
&& "not case or default?!");
P.diagnose(P.Tok, diag::case_outside_of_switch, P.Tok.getText());
P.skipUntil(tok::colon, tok::r_brace);
// FIXME: Return an ErrorStmt?
return nullptr;
}
/// parseStmt
///
/// \param fromASTGen If true , this function in called from ASTGen as the
/// fallback, so do not attempt a callback to ASTGen.
ParserResult<Stmt> Parser::parseStmt(bool fromASTGen) {
AssertParserMadeProgressBeforeLeavingScopeRAII apmp(*this);
#if SWIFT_BUILD_SWIFT_SYNTAX
if (IsForASTGen && !fromASTGen)
return parseStmtFromSyntaxTree();
#endif
// If this is a label on a loop/switch statement, consume it and pass it into
// parsing logic below.
LabeledStmtInfo LabelInfo;
if (Tok.is(tok::identifier) && peekToken().is(tok::colon)) {
LabelInfo.Loc = consumeIdentifier(LabelInfo.Name,
/*diagnoseDollarPrefix=*/true);
consumeToken(tok::colon);
}
// Note that we're parsing a statement.
StructureMarkerRAII ParsingStmt(*this, Tok.getLoc(),
StructureMarkerKind::Statement);
SourceLoc tryLoc;
(void)consumeIf(tok::kw_try, tryLoc);
// Claim contextual statement keywords now that we've committed
// to parsing a statement.
if (isContextualYieldKeyword()) {
Tok.setKind(tok::kw_yield);
} else if (isContextualDiscardKeyword()) {
Tok.setKind(tok::kw_discard);
}
if (isContextualThenKeyword(/*preferExpr*/ false))
Tok.setKind(tok::kw_then);
// This needs to handle everything that `Parser::isStartOfStmt()` accepts as
// start of statement.
switch (Tok.getKind()) {
case tok::pound_line:
case tok::pound_sourceLocation:
case tok::pound_if:
case tok::pound_error:
case tok::pound_warning:
assert((LabelInfo || tryLoc.isValid()) &&
"unlabeled directives should be handled earlier");
// Bailout, and let parseBraceItems() parse them.
LLVM_FALLTHROUGH;
default:
diagnose(Tok, tryLoc.isValid() ? diag::expected_expr : diag::expected_stmt);
if (Tok.is(tok::at_sign)) {
// Recover from erroneously placed attribute.
consumeToken(tok::at_sign);
consumeIf(tok::identifier);
}
return nullptr;
case tok::kw_return:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtReturn(tryLoc);
case tok::kw_yield:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtYield(tryLoc);
case tok::kw_then:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtThen(tryLoc);
case tok::kw_throw:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
return parseStmtThrow(tryLoc);
case tok::kw_defer:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDefer();
case tok::kw_if:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtIf(LabelInfo);
case tok::kw_guard:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtGuard();
case tok::kw_while:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtWhile(LabelInfo);
case tok::kw_repeat:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtRepeat(LabelInfo);
case tok::kw_do:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDo(LabelInfo);
case tok::kw_for:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtForEach(LabelInfo);
case tok::kw_discard:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtDiscard();
case tok::kw_switch:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtSwitch(LabelInfo);
/// 'case' and 'default' are only valid at the top level of a switch.
case tok::kw_case:
case tok::kw_default:
return recoverFromInvalidCase(*this);
case tok::kw_break:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtBreak();
case tok::kw_continue:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtContinue();
case tok::kw_fallthrough: {
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return makeParserResult(
new (Context) FallthroughStmt(consumeToken(tok::kw_fallthrough)));
}
case tok::pound_assert:
if (LabelInfo) diagnose(LabelInfo.Loc, diag::invalid_label_on_stmt);
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
return parseStmtPoundAssert();
case tok::l_brace:
if (tryLoc.isValid()) diagnose(tryLoc, diag::try_on_stmt, Tok.getText());
SourceLoc colonLoc = Tok.getLoc();
diagnose(colonLoc, diag::labeled_block_needs_do)
.fixItInsert(colonLoc, "do ");
return parseStmtDo(LabelInfo, /*shouldSkipDoTokenConsume*/ true);
}
}
/// parseBraceItemList - A brace enclosed expression/statement/decl list. For
/// example { 1; 4+5; } or { 1; 2 }. Always occurs as part of some other stmt
/// or decl.
///
/// brace-item-list:
/// '{' brace-item* '}'
///
ParserResult<BraceStmt> Parser::parseBraceItemList(Diag<> ID) {
if (Tok.isNot(tok::l_brace)) {
diagnose(Tok, ID);
// Attempt to recover by looking for a left brace on the same line
if (!skipUntilTokenOrEndOfLine(tok::l_brace, tok::r_brace) ||
!Tok.is(tok::l_brace))
return nullptr;
}
SourceLoc LBLoc = consumeToken(tok::l_brace);
SmallVector<ASTNode, 16> Entries;
SourceLoc RBLoc;
ParserStatus Status = parseBraceItems(Entries, BraceItemListKind::Brace,
BraceItemListKind::Brace);
if (!parseMatchingToken(tok::r_brace, RBLoc,
diag::expected_rbrace_in_brace_stmt, LBLoc)) {
// We recovered do don't propagate any error status (but still preserve
// HasCodeCompletion).
Status.clearIsError();
}
return makeParserResult(Status,
BraceStmt::create(Context, LBLoc, Entries, RBLoc));
}
static ParserStatus parseOptionalControlTransferTarget(Parser &P,
Identifier &Target,
SourceLoc &TargetLoc,
StmtKind Kind) {
// If we have an identifier after 'break' or 'continue', which is not the
// start of another stmt or decl, we assume it is the label to break to,
// unless there is a line break. There is ambiguity with expressions (e.g.
// "break x+y") but since the expression after the them is dead, we don't feel
// bad eagerly parsing this.
if (!P.Tok.isAtStartOfLine()) {
if (P.Tok.is(tok::identifier) && !P.isStartOfStmt(/*preferExpr*/ true) &&
!P.isStartOfSwiftDecl()) {
TargetLoc = P.consumeIdentifier(Target, /*diagnoseDollarPrefix=*/false);
return makeParserSuccess();
} else if (P.Tok.is(tok::code_complete)) {
if (P.CodeCompletionCallbacks)
P.CodeCompletionCallbacks->completeStmtLabel(Kind);
TargetLoc = P.consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
}
}
return makeParserSuccess();
}
/// parseStmtBreak
///
/// stmt-break:
/// 'break' identifier?
///
ParserResult<Stmt> Parser::parseStmtBreak() {
SourceLoc Loc = consumeToken(tok::kw_break);
SourceLoc TargetLoc;
Identifier Target;
ParserStatus Status;
Status |= parseOptionalControlTransferTarget(*this, Target, TargetLoc,
StmtKind::Break);
auto *BS = new (Context) BreakStmt(Loc, Target, TargetLoc, CurDeclContext);
return makeParserResult(Status, BS);
}
/// parseStmtContinue
///
/// stmt-continue:
/// 'continue' identifier?
///
ParserResult<Stmt> Parser::parseStmtContinue() {
SourceLoc Loc = consumeToken(tok::kw_continue);
SourceLoc TargetLoc;
Identifier Target;
ParserStatus Status;
Status |= parseOptionalControlTransferTarget(*this, Target, TargetLoc,
StmtKind::Continue);
auto *CS = new (Context) ContinueStmt(Loc, Target, TargetLoc, CurDeclContext);
return makeParserResult(Status, CS);
}
/// parseStmtReturn
///
/// stmt-return:
/// 'return' expr?
///
ParserResult<Stmt> Parser::parseStmtReturn(SourceLoc tryLoc) {
SourceLoc ReturnLoc = consumeToken(tok::kw_return);
if (Tok.is(tok::code_complete)) {
auto CCE = new (Context) CodeCompletionExpr(Tok.getLoc());
auto Result =
makeParserResult(ReturnStmt::createParsed(Context, ReturnLoc, CCE));
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeReturnStmt(CCE);
}
Result.setHasCodeCompletionAndIsError();
consumeToken();
return Result;
}
auto isStartOfReturnExpr = [&]() {
if (Tok.isAny(tok::r_brace, tok::semi, tok::eof, tok::pound_if,
tok::pound_error, tok::pound_warning, tok::pound_endif,
tok::pound_else, tok::pound_elseif)) {
return false;
}
// Allowed for if/switch/do expressions.
if (Tok.isAny(tok::kw_if, tok::kw_switch) ||
(Tok.is(tok::kw_do) &&
Context.LangOpts.hasFeature(Feature::DoExpressions))) {
return true;
}
if (isStartOfStmt(/*preferExpr*/ true) || isStartOfSwiftDecl())
return false;
return true;
};
// Handle the ambiguity between consuming the expression and allowing the
// enclosing stmt-brace to get it by eagerly eating it unless the return is
// followed by a '}', ';', statement or decl start keyword sequence.
if (isStartOfReturnExpr()) {
SourceLoc ExprLoc = Tok.getLoc();
// Issue a warning when the returned expression is on a different line than
// the return keyword, but both have the same indentation.
if (SourceMgr.getLineAndColumnInBuffer(ReturnLoc).second ==
SourceMgr.getLineAndColumnInBuffer(ExprLoc).second) {
diagnose(ExprLoc, diag::unindented_code_after_return);
diagnose(ExprLoc, diag::indent_expression_to_silence);
}
ParserResult<Expr> Result = parseExpr(diag::expected_expr_return);
if (Result.isNull()) {
// Create an ErrorExpr to tell the type checker that this return
// statement had an expression argument in the source. This suppresses
// the error about missing return value in a non-void function.
Result = makeParserErrorResult(new (Context) ErrorExpr(ExprLoc));
}
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*return=*/0)
.fixItInsert(ExprLoc, "try ")
.fixItRemoveChars(tryLoc, ReturnLoc);
// Note: We can't use tryLoc here because that's outside the ReturnStmt's
// source range.
if (Result.isNonNull() && !isa<ErrorExpr>(Result.get()))
Result = makeParserResult(new (Context) TryExpr(ExprLoc, Result.get()));
}
return makeParserResult(
Result,
ReturnStmt::createParsed(Context, ReturnLoc, Result.getPtrOrNull()));
}
if (tryLoc.isValid())
diagnose(tryLoc, diag::try_on_stmt, "return");
return makeParserResult(
ReturnStmt::createParsed(Context, ReturnLoc, nullptr));
}
/// parseStmtYield
///
/// stmt-yield:
/// 'yield' expr
/// 'yield' '(' expr-list ')'
///
/// Note that a parenthesis always starts the second (list) grammar.
ParserResult<Stmt> Parser::parseStmtYield(SourceLoc tryLoc) {
SourceLoc yieldLoc = consumeToken(tok::kw_yield);
if (Tok.is(tok::code_complete)) {
auto cce = new (Context) CodeCompletionExpr(Tok.getLoc());
auto result = makeParserResult(
YieldStmt::create(Context, yieldLoc, SourceLoc(), cce, SourceLoc()));
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeYieldStmt(cce, /*index=*/std::nullopt);
}
result.setHasCodeCompletionAndIsError();
consumeToken();
return result;
}
ParserStatus status;
SourceLoc lpLoc, rpLoc;
SmallVector<Expr*, 4> yields;
if (Tok.is(tok::l_paren)) {
// If there was a 'try' on the yield, and there are multiple
// yielded values, suggest just removing the try instead of
// suggesting adding it to every yielded value.
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*yield=*/2)
.fixItRemoveChars(tryLoc, yieldLoc);
}
SmallVector<ExprListElt, 4> yieldElts;
status = parseExprList(tok::l_paren, tok::r_paren, /*isArgumentList*/ false,
lpLoc, yieldElts, rpLoc);
for (auto &elt : yieldElts) {
// We don't accept labels in a list of yields.
if (elt.LabelLoc.isValid()) {
diagnose(elt.LabelLoc, diag::unexpected_label_yield)
.fixItRemoveChars(elt.LabelLoc, elt.E->getStartLoc());
}
yields.push_back(elt.E);
}
} else {
SourceLoc beginLoc = Tok.getLoc();
// There's a single yielded value, so suggest moving 'try' before it.
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*yield=*/2)
.fixItInsert(beginLoc, "try ")
.fixItRemoveChars(tryLoc, yieldLoc);
}
auto expr = parseExpr(diag::expected_expr_yield);
if (expr.hasCodeCompletion() && expr.isNonNull()) {
status |= expr;
yields.push_back(expr.get());
} else if (expr.isParseErrorOrHasCompletion()) {
auto endLoc = (Tok.getLoc() == beginLoc ? beginLoc : PreviousLoc);
yields.push_back(
new (Context) ErrorExpr(SourceRange(beginLoc, endLoc)));
} else {
yields.push_back(expr.get());
}
}
return makeParserResult(
status, YieldStmt::create(Context, yieldLoc, lpLoc, yields, rpLoc));
}
bool Parser::isContextualThenKeyword(bool preferExpr) {
if (!Context.LangOpts.hasFeature(Feature::ThenStatements))
return false;
if (!Tok.isContextualKeyword("then"))
return false;
// If we want to prefer an expr, and aren't at the start of a newline, then
// don't parse a ThenStmt.
if (preferExpr && !Tok.isAtStartOfLine())
return false;
// 'then' immediately followed by '('/'[' is a function/subscript call. If
// immediately followed by '.', it's a member access.
if (peekToken().isAny(tok::l_paren, tok::l_square, tok::period)) {
auto tokEndLoc = Lexer::getLocForEndOfToken(SourceMgr, Tok.getLoc());
return peekToken().getLoc() != tokEndLoc;
}
// 'then' followed by '{' is a trailing closure on a function call.
if (peekToken().is(tok::l_brace))
return false;
// If we have 'then' followed by an infix or postfix operator, we know this
// must be an expression.
if (peekToken().isBinaryOperatorLike() || peekToken().isPostfixOperatorLike())
return false;
// These act like binary operators.
if (peekToken().isAny(tok::kw_is, tok::kw_as))
return false;
return true;
}
/// parseStmtThen
///
/// stmt-then:
/// 'then' expr
///
ParserResult<Stmt> Parser::parseStmtThen(SourceLoc tryLoc) {
SourceLoc thenLoc = consumeToken(tok::kw_then);
if (Tok.is(tok::code_complete)) {
auto ccLoc = consumeToken();
auto *CCE = new (Context) CodeCompletionExpr(ccLoc);
if (CodeCompletionCallbacks)
CodeCompletionCallbacks->completeThenStmt(CCE);
return makeParserCodeCompletionResult(
ThenStmt::createParsed(Context, thenLoc, CCE));
}
auto exprLoc = Tok.getLoc();
// Issue a warning when the expression is on a different line than
// the 'then' keyword, but both have the same indentation.
if (SourceMgr.getLineAndColumnInBuffer(thenLoc).second ==
SourceMgr.getLineAndColumnInBuffer(exprLoc).second) {
diagnose(exprLoc, diag::unindented_code_after_then);
diagnose(exprLoc, diag::indent_expression_to_silence);
}
ParserResult<Expr> result = parseExpr(diag::expected_expr_after_then);
bool hasCodeCompletion = result.hasCodeCompletion();
// If we couldn't parse an expr, fill it the gap with an ErrorExpr, as
// ThenStmt expects an expression node.
if (result.isNull())
result = makeParserErrorResult(new (Context) ErrorExpr(exprLoc));
if (tryLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*then=*/3)
.fixItInsert(exprLoc, "try ")
.fixItRemoveChars(tryLoc, thenLoc);
// Note: We can't use tryLoc here because that's outside the ThenStmt's
// source range.
if (!isa<ErrorExpr>(result.get()))
result = makeParserResult(new (Context) TryExpr(exprLoc, result.get()));
}
if (hasCodeCompletion)
result.setHasCodeCompletionAndIsError();
return makeParserResult(
result, ThenStmt::createParsed(Context, thenLoc, result.get()));
}
/// parseStmtThrow
///
/// stmt-throw
/// 'throw' expr
///
ParserResult<Stmt> Parser::parseStmtThrow(SourceLoc tryLoc) {
SourceLoc throwLoc = consumeToken(tok::kw_throw);
SourceLoc exprLoc;
if (Tok.isNot(tok::eof))
exprLoc = Tok.getLoc();
ParserResult<Expr> Result = parseExpr(diag::expected_expr_throw);
bool hasCodeCompletion = Result.hasCodeCompletion();
if (Result.isNull())
Result = makeParserErrorResult(new (Context) ErrorExpr(throwLoc));
if (tryLoc.isValid() && exprLoc.isValid()) {
diagnose(tryLoc, diag::try_must_come_after_stmt, /*throw=*/1)
.fixItInsert(exprLoc, "try ")
.fixItRemoveChars(tryLoc, throwLoc);
// Note: We can't use tryLoc here because that's outside the ThrowStmt's
// source range.
if (Result.isNonNull() && !isa<ErrorExpr>(Result.get()))
Result = makeParserResult(new (Context) TryExpr(exprLoc, Result.get()));
}
if (hasCodeCompletion)
Result.setHasCodeCompletionAndIsError();
return makeParserResult(Result,
new (Context) ThrowStmt(throwLoc, Result.get()));
}
/// parseStmtDiscard
///
/// stmt-discard
/// 'discard' 'self'
///
ParserResult<Stmt> Parser::parseStmtDiscard() {
SourceLoc discardLoc = consumeToken(tok::kw_discard);
SourceLoc exprLoc;
if (Tok.isNot(tok::eof))
exprLoc = Tok.getLoc();
// We parse the whole expression, because we might have something like:
// discard self.x.y
// and we want to emit good diagnostics for this later on.
ParserResult<Expr> Result = parseExpr(diag::expected_expr_discard);
bool hasCodeCompletion = Result.hasCodeCompletion();
if (Result.isNull())
Result = makeParserErrorResult(new (Context) ErrorExpr(discardLoc));
if (hasCodeCompletion)
Result.setHasCodeCompletionAndIsError();
return makeParserResult(Result,
new (Context) DiscardStmt(discardLoc, Result.get()));
}
/// parseStmtDefer
///
/// stmt-defer:
/// 'defer' brace-stmt
///
ParserResult<Stmt> Parser::parseStmtDefer() {
SourceLoc DeferLoc = consumeToken(tok::kw_defer);
// Expand out the defer into a closure and call, which we can typecheck
// and emit where needed.
//
// The AST representation for a defer statement is a bit weird. We retain the
// brace statement that the user wrote, but actually model this as if they
// wrote:
//
// func tmpClosure() { body }
// tmpClosure() // This is emitted on each path that needs to run this.
//
// As such, the body of the 'defer' is actually type checked within the
// closure's DeclContext.
auto *DS = DeferStmt::create(CurDeclContext, DeferLoc);
ParserStatus Status;
{
auto *tempDecl = DS->getTempDecl();
// Change the DeclContext for any variables declared in the defer to be within
// the defer closure.
ParseFunctionBody cc(*this, tempDecl);
llvm::SaveAndRestore<std::optional<StableHasher>> T(
CurrentTokenHash, StableHasher::defaultHasher());
ParserResult<BraceStmt> Body =
parseBraceItemList(diag::expected_lbrace_after_defer);
if (Body.isNull())
return nullptr;
Status |= Body;
// Clone the current hasher and extract a Fingerprint.
StableHasher currentHash{*CurrentTokenHash};
Fingerprint fp(std::move(currentHash));
tempDecl->setBodyParsed(Body.get(), fp);
}
return makeParserResult(Status, DS);
}
namespace {
struct GuardedPattern {
Pattern *ThePattern = nullptr;
SourceLoc WhereLoc;
Expr *Guard = nullptr;
};
/// Contexts in which a guarded pattern can appear.
enum class GuardedPatternContext {
Case,
Catch,
};
} // unnamed namespace
static void parseWhereGuard(Parser &P, GuardedPattern &result,
ParserStatus &status,
GuardedPatternContext parsingContext,
bool isExprBasic) {
if (P.Tok.is(tok::kw_where)) {
result.WhereLoc = P.consumeToken(tok::kw_where);
SourceLoc startOfGuard = P.Tok.getLoc();
auto diagKind = [=]() -> Diag<> {
switch (parsingContext) {
case GuardedPatternContext::Case:
return diag::expected_case_where_expr;
case GuardedPatternContext::Catch:
return diag::expected_catch_where_expr;
}
llvm_unreachable("bad context");
}();
ParserResult<Expr> guardResult = P.parseExprImpl(diagKind, isExprBasic);
status |= guardResult;
// Use the parsed guard expression if possible.
if (guardResult.isNonNull()) {
result.Guard = guardResult.get();
// Otherwise, fake up an ErrorExpr.
} else {
// If we didn't consume any tokens failing to parse the
// expression, don't put in the source range of the ErrorExpr.
SourceRange errorRange;
if (startOfGuard == P.Tok.getLoc()) {
errorRange = result.WhereLoc;
} else {
errorRange = SourceRange(startOfGuard, P.PreviousLoc);
}
result.Guard = new (P.Context) ErrorExpr(errorRange);
}
}
}
/// Parse a pattern-matching clause for a case or catch statement,
/// including the guard expression:
///
/// pattern 'where' expr
static void parseGuardedPattern(Parser &P, GuardedPattern &result,
ParserStatus &status,
SmallVectorImpl<VarDecl *> &boundDecls,
GuardedPatternContext parsingContext,
bool isFirstPattern) {
ParserResult<Pattern> patternResult;
bool isExprBasic = [&]() -> bool {
switch (parsingContext) {
// 'case' is terminated with a colon and so allows a trailing closure.
case GuardedPatternContext::Case:
return false;
// 'catch' is terminated with a brace and so cannot.
case GuardedPatternContext::Catch:
return true;
}
llvm_unreachable("bad pattern context");
}();
// Do some special-case code completion for the start of the pattern.
if (P.Tok.is(tok::code_complete)) {
auto CCE = new (P.Context) CodeCompletionExpr(P.Tok.getLoc());
result.ThePattern =
ExprPattern::createParsed(P.Context, CCE, P.CurDeclContext);
if (P.CodeCompletionCallbacks) {
switch (parsingContext) {
case GuardedPatternContext::Case:
P.CodeCompletionCallbacks->completeCaseStmtBeginning(CCE);
break;
case GuardedPatternContext::Catch:
P.CodeCompletionCallbacks->completePostfixExprBeginning(CCE);
break;
}
}
P.consumeToken(tok::code_complete);
status.setHasCodeCompletionAndIsError();
return;
}
// If this is a 'catch' clause and we have "catch {" or "catch where...",
// then we get an implicit "let error" pattern.
if (parsingContext == GuardedPatternContext::Catch &&
P.Tok.isAny(tok::l_brace, tok::kw_where)) {
patternResult = makeParserResult(
BindingPattern::createImplicitCatch(P.CurDeclContext, P.Tok.getLoc()));
}
// Okay, if the special code-completion didn't kick in, parse a
// matching pattern.
if (patternResult.isNull()) {
llvm::SaveAndRestore<decltype(P.InBindingPattern)> T(
P.InBindingPattern, PatternBindingState::InMatchingPattern);
patternResult = P.parseMatchingPattern(isExprBasic);
}
// If that didn't work, use a bogus pattern so that we can fill out
// the AST.
if (patternResult.isNull()) {
auto *AP = new (P.Context) AnyPattern(P.PreviousLoc);
if (P.PreviousLoc.isInvalid())
AP->setImplicit();
patternResult = makeParserErrorResult(AP);
}
// Fill in the pattern.
status |= patternResult;
result.ThePattern = patternResult.get();
if (isFirstPattern) {
// Add variable bindings from the pattern to the case scope. We have
// to do this with a full AST walk, because the freshly parsed pattern
// represents tuples and var patterns as tupleexprs and
// unresolved_pattern_expr nodes, instead of as proper pattern nodes.
patternResult.get()->forEachVariable([&](VarDecl *VD) {
boundDecls.push_back(VD);
});
// Parse the optional 'where' guard.
parseWhereGuard(P, result, status, parsingContext, isExprBasic);
} else {
// If boundDecls already contains variables, then we must match the
// same number and same names in this pattern as were declared in a
// previous pattern (and later we will make sure they have the same
// types).
SmallVector<VarDecl*, 4> repeatedDecls;
patternResult.get()->forEachVariable([&](VarDecl *VD) {
if (!VD->hasName())
return;
bool found = false;
for (auto previous : boundDecls) {
if (previous->hasName() && previous->getName() == VD->getName()) {
found = true;
break;
}
}
if (!found) {
// Diagnose a declaration that doesn't match a previous pattern.
P.diagnose(VD->getLoc(), diag::extra_var_in_multiple_pattern_list, VD->getName());
status.setIsParseError();
}
repeatedDecls.push_back(VD);
});
for (auto previous : boundDecls) {
bool found = false;
for (auto repeat : repeatedDecls) {
if (previous->hasName() && previous->getName() == repeat->getName()) {
found = true;
break;
}
}
if (!found) {
// Diagnose a previous declaration that is missing in this pattern.
P.diagnose(previous->getLoc(), diag::extra_var_in_multiple_pattern_list, previous->getName());
status.setIsParseError();
}
}
// Parse the optional 'where' guard, with this particular pattern's bound
// vars in scope.
parseWhereGuard(P, result, status, parsingContext, isExprBasic);
}
}
/// Validate availability spec list, emitting diagnostics if necessary and
/// removing specs for unrecognized platforms.
static void
validateAvailabilitySpecList(Parser &P,
SmallVectorImpl<AvailabilitySpec *> &Specs,
Parser::AvailabilitySpecSource Source) {
llvm::SmallSet<PlatformKind, 4> Platforms;
std::optional<SourceLoc> OtherPlatformSpecLoc = std::nullopt;
if (Specs.size() == 1 &&
isa<PlatformAgnosticVersionConstraintAvailabilitySpec>(Specs[0])) {
// @available(swift N) and @available(_PackageDescription N) are allowed
// only in isolation; they cannot be combined with other availability specs
// in a single list.
return;
}
SmallVector<AvailabilitySpec *, 5> RecognizedSpecs;
for (auto *Spec : Specs) {
RecognizedSpecs.push_back(Spec);
if (auto *OtherPlatSpec = dyn_cast<OtherPlatformAvailabilitySpec>(Spec)) {
OtherPlatformSpecLoc = OtherPlatSpec->getStarLoc();
continue;
}
if (auto *PlatformAgnosticSpec =
dyn_cast<PlatformAgnosticVersionConstraintAvailabilitySpec>(Spec)) {
P.diagnose(PlatformAgnosticSpec->getPlatformAgnosticNameLoc(),
diag::availability_must_occur_alone,
PlatformAgnosticSpec->isLanguageVersionSpecific()
? "swift"
: "_PackageDescription");
continue;
}
auto *VersionSpec = cast<PlatformVersionConstraintAvailabilitySpec>(Spec);
// We keep specs for unrecognized platforms around for error recovery
// during parsing but remove them once parsing is completed.
if (VersionSpec->isUnrecognizedPlatform()) {
RecognizedSpecs.pop_back();
continue;
}
bool Inserted = Platforms.insert(VersionSpec->getPlatform()).second;
if (!Inserted) {
// Rule out multiple version specs referring to the same platform.
// For example, we emit an error for
/// #available(OSX 10.10, OSX 10.11, *)
PlatformKind Platform = VersionSpec->getPlatform();
P.diagnose(VersionSpec->getPlatformLoc(),
diag::availability_query_repeated_platform,
platformString(Platform));
}
}
switch (Source) {
case Parser::AvailabilitySpecSource::Available: {
if (OtherPlatformSpecLoc == std::nullopt) {
SourceLoc InsertWildcardLoc = P.PreviousLoc;
P.diagnose(InsertWildcardLoc, diag::availability_query_wildcard_required)
.fixItInsertAfter(InsertWildcardLoc, ", *");
}
break;
}
case Parser::AvailabilitySpecSource::Unavailable: {
if (OtherPlatformSpecLoc != std::nullopt) {
SourceLoc Loc = OtherPlatformSpecLoc.value();
P.diagnose(Loc, diag::unavailability_query_wildcard_not_required)
.fixItRemove(Loc);
}
break;
}
case Parser::AvailabilitySpecSource::Macro: {
if (OtherPlatformSpecLoc != std::nullopt) {
SourceLoc Loc = OtherPlatformSpecLoc.value();
P.diagnose(Loc, diag::attr_availability_wildcard_in_macro);
}
break;
}
}
Specs = RecognizedSpecs;
}
// #available(...)
// #unavailable(...)
ParserResult<PoundAvailableInfo> Parser::parseStmtConditionPoundAvailable() {
tok MainToken;
AvailabilitySpecSource Source;
bool isUnavailability;
if (Tok.is(tok::pound_available)) {
MainToken = tok::pound_available;
Source = AvailabilitySpecSource::Available;
isUnavailability = false;
} else {
MainToken = tok::pound_unavailable;
Source = AvailabilitySpecSource::Unavailable;
isUnavailability = true;
}
SourceLoc PoundLoc;
PoundLoc = consumeToken(MainToken);
if (!Tok.isFollowingLParen()) {
diagnose(Tok, diag::avail_query_expected_condition);
return makeParserError();
}
StructureMarkerRAII ParsingAvailabilitySpecList(*this, Tok);
SourceLoc LParenLoc = consumeToken(tok::l_paren);
SmallVector<AvailabilitySpec *, 5> Specs;
ParserStatus Status = parseAvailabilitySpecList(Specs, Source);
for (auto *Spec : Specs) {
if (auto *PlatformAgnostic =
dyn_cast<PlatformAgnosticVersionConstraintAvailabilitySpec>(Spec)) {
diagnose(PlatformAgnostic->getPlatformAgnosticNameLoc(),
PlatformAgnostic->isLanguageVersionSpecific()
? diag::pound_available_swift_not_allowed
: diag::pound_available_package_description_not_allowed,
getTokenText(MainToken));
Status.setIsParseError();
}
}
SourceLoc RParenLoc;
if (parseMatchingToken(tok::r_paren, RParenLoc,
diag::avail_query_expected_rparen, LParenLoc))
Status.setIsParseError();
// Diagnose #available == false as being a wrong spelling of #unavailable.
if (!isUnavailability && Tok.isAnyOperator() && Tok.getText() == "==" &&
peekToken().is(tok::kw_false)) {
diagnose(Tok, diag::false_available_is_called_unavailable)
.highlight(SourceRange(PoundLoc, peekToken().getLoc()))
.fixItReplace(PoundLoc, getTokenText(tok::pound_unavailable))
.fixItRemove(SourceRange(Tok.getLoc(), peekToken().getLoc()));
consumeToken();
consumeToken();
Status.setIsParseError();
}
auto *result = PoundAvailableInfo::create(Context, PoundLoc, LParenLoc, Specs,
RParenLoc, isUnavailability);
return makeParserResult(Status, result);
}
ParserStatus
Parser::parseAvailabilityMacroDefinition(AvailabilityMacroDefinition &Result) {
// Prime the lexer.
if (Tok.is(tok::NUM_TOKENS))
consumeTokenWithoutFeedingReceiver();
if (!Tok.isIdentifierOrUnderscore()) {
diagnose(Tok, diag::attr_availability_missing_macro_name);
return makeParserError();
}
Result.Name = Tok.getText();
consumeToken();
if (Tok.isAny(tok::integer_literal, tok::floating_literal)) {
SourceRange VersionRange;
if (parseVersionTuple(Result.Version, VersionRange,
diag::avail_query_expected_version_number)) {
return makeParserError();
}
}
if (!consumeIf(tok::colon)) {
diagnose(Tok, diag::attr_availability_expected_colon_macro, Result.Name);
return makeParserError();
}
return parseAvailabilitySpecList(Result.Specs, AvailabilitySpecSource::Macro);
}
ParserStatus
Parser::parseAvailabilitySpecList(SmallVectorImpl<AvailabilitySpec *> &Specs,
AvailabilitySpecSource Source) {
ParserStatus Status = makeParserSuccess();
// We don't use parseList() because we want to provide more specific
// diagnostics disallowing operators in version specs.
while (1) {
// First look for a macro as we need Specs for the expansion.
bool MatchedAMacro = false;
switch (Source) {
case AvailabilitySpecSource::Available:
case AvailabilitySpecSource::Unavailable:
if (Tok.is(tok::identifier)) {
SmallVector<AvailabilitySpec *, 4> MacroSpecs;
ParserStatus MacroStatus = parseAvailabilityMacro(MacroSpecs);
if (MacroStatus.isError()) {
// There's a parsing error if the platform name matches a macro
// but something goes wrong after.
Status.setIsParseError();
MatchedAMacro = true;
} else {
MatchedAMacro = !MacroSpecs.empty();
Specs.append(MacroSpecs.begin(), MacroSpecs.end());
}
}
break;
case AvailabilitySpecSource::Macro:
break;
}
if (!MatchedAMacro) {
auto SpecResult = parseAvailabilitySpec();
if (auto *Spec = SpecResult.getPtrOrNull()) {
Specs.push_back(Spec);
} else {
if (SpecResult.hasCodeCompletion()) {
return makeParserCodeCompletionStatus();
}
Status.setIsParseError();
}
}
// We don't allow binary operators to combine specs.
if (Tok.isBinaryOperator()) {
diagnose(Tok, diag::avail_query_disallowed_operator, Tok.getText());
consumeToken();
Status.setIsParseError();
} else if (consumeIf(tok::comma)) {
// There is more to parse in this list.
// Before continuing to parse the next specification, we check that it's
// also in the shorthand syntax and provide a more specific diagnostic if
// that's not the case.
if (Tok.isIdentifierOrUnderscore() &&
!peekToken().isAny(tok::integer_literal, tok::floating_literal) &&
!Specs.empty()) {
auto Text = Tok.getText();
if (Text == "deprecated" || Text == "renamed" || Text == "introduced" ||
Text == "message" || Text == "obsoleted" || Text == "unavailable") {
auto *Previous = Specs.back();
auto &SourceManager = Context.SourceMgr;
auto PreviousSpecText =
SourceManager.extractText(L->getCharSourceRangeFromSourceRange(
SourceManager, Previous->getSourceRange()));
diagnose(Tok,
diag::avail_query_argument_and_shorthand_mix_not_allowed,
Text, PreviousSpecText);
// If this was preceded by a single platform version constraint, we
// can guess that the intention was to treat it as 'introduced' and
// suggest a fix-it to combine them.
if (Specs.size() == 1 &&
PlatformVersionConstraintAvailabilitySpec::classof(Previous) &&
Text != "introduced") {
auto *PlatformSpec =
cast<PlatformVersionConstraintAvailabilitySpec>(Previous);
auto PlatformNameEndLoc =
Lexer::getLocForEndOfToken(SourceManager,
PlatformSpec->getPlatformLoc());
diagnose(PlatformSpec->getPlatformLoc(),
diag::avail_query_meant_introduced)
.fixItInsert(PlatformNameEndLoc, ", introduced:");
}
Status.setIsParseError();
break;
}
}
// Otherwise, keep going.
} else {
break;
}
}
if (Status.isSuccess() && !Status.hasCodeCompletion())
validateAvailabilitySpecList(*this, Specs, Source);
return Status;
}
// #_hasSymbol(...)
ParserResult<PoundHasSymbolInfo> Parser::parseStmtConditionPoundHasSymbol() {
SourceLoc PoundLoc = consumeToken(tok::pound__hasSymbol);
if (!Tok.isFollowingLParen()) {
diagnose(Tok, diag::has_symbol_expected_lparen);
return makeParserError();
}
SourceLoc LParenLoc = consumeToken(tok::l_paren);
ParserStatus status = makeParserSuccess();
auto ExprResult = parseExprBasic(diag::has_symbol_expected_expr);
status |= ExprResult;
SourceLoc RParenLoc;
if (parseMatchingToken(tok::r_paren, RParenLoc,
diag::has_symbol_expected_rparen, LParenLoc))
status.setIsParseError();
auto *result = PoundHasSymbolInfo::create(
Context, PoundLoc, LParenLoc, ExprResult.getPtrOrNull(), RParenLoc);
return makeParserResult(status, result);
}
ParserStatus
Parser::parseStmtConditionElement(SmallVectorImpl<StmtConditionElement> &result,
Diag<> DefaultID, StmtKind ParentKind,
StringRef &BindingKindStr) {
ParserStatus Status;
// Diagnose !#available as being a wrong spelling of #unavailable.
if (Tok.getText() == "!" && peekToken().is(tok::pound_available)) {
SourceRange Range = SourceRange(Tok.getLoc(), peekToken().getLoc());
diagnose(Tok, diag::false_available_is_called_unavailable)
.fixItReplace(Range, getTokenText(tok::pound_unavailable));
// For better error recovery, reject but allow parsing to continue.
consumeToken();
}
// Parse a leading #available/#unavailable condition if present.
if (Tok.isAny(tok::pound_available, tok::pound_unavailable)) {
auto res = parseStmtConditionPoundAvailable();
if (res.isNull() || res.hasCodeCompletion()) {
Status |= res;
return Status;
}
BindingKindStr = StringRef();
result.push_back({res.get()});
return Status;
}
// Parse a leading #_hasSymbol condition if present.
if (Tok.is(tok::pound__hasSymbol)) {
auto res = parseStmtConditionPoundHasSymbol();
if (res.isNull() || res.hasCodeCompletion()) {
Status |= res;
return Status;
}
BindingKindStr = StringRef();
result.push_back({res.get()});
return Status;
}
// Handle code completion after the #.
if (Tok.is(tok::pound) && peekToken().is(tok::code_complete) &&
Tok.getLoc().getAdvancedLoc(1) == peekToken().getLoc()) {
auto Expr = parseExprPoundCodeCompletion(ParentKind);
Status |= Expr;
result.push_back(Expr.get());
}
// Parse the basic expression case. If we have a leading let/var/case
// keyword or an assignment, then we know this is a binding.
if (Tok.isNot(tok::kw_let, tok::kw_var, tok::kw_case) &&
(!Context.LangOpts.hasFeature(Feature::ReferenceBindings) ||
Tok.isNot(tok::kw_inout))) {
// If we lack it, then this is theoretically a boolean condition.
// However, we also need to handle migrating from Swift 2 syntax, in
// which a comma followed by an expression could actually be a pattern
// clause followed by a binding. Determine what we have by checking for a
// syntactically valid pattern followed by an '=', which can never be a
// boolean condition.
//
// However, if this is the first clause, and we see "x = y", then this is
// almost certainly a typo for '==' and definitely not a continuation of
// another clause, so parse it as an expression. This also avoids
// lookahead + backtracking on simple if conditions that are obviously
// boolean conditions.
auto isBooleanExpr = [&]() -> bool {
Parser::BacktrackingScope Backtrack(*this);
return !canParseTypedPattern() || Tok.isNot(tok::equal);
};
if (BindingKindStr.empty() || isBooleanExpr()) {
auto diagID = result.empty() ? DefaultID :
diag::expected_expr_conditional;
auto BoolExpr = parseExprBasic(diagID);
Status |= BoolExpr;
if (BoolExpr.isNull())
return Status;
result.push_back(BoolExpr.get());
BindingKindStr = StringRef();
return Status;
}
}
SourceLoc IntroducerLoc;
if (Tok.isAny(tok::kw_let, tok::kw_var, tok::kw_case) ||
(Context.LangOpts.hasFeature(Feature::ReferenceBindings) &&
Tok.isAny(tok::kw_inout))) {
BindingKindStr = Tok.getText();
IntroducerLoc = consumeToken();
} else {
// If we lack the leading let/var/case keyword, then we're here because
// the user wrote something like "if let x = foo(), y = bar() {". Fix
// this by inserting a new 'let' keyword before y.
IntroducerLoc = Tok.getLoc();
assert(!BindingKindStr.empty() &&
"Shouldn't get here without a leading binding");
diagnose(Tok.getLoc(), diag::expected_binding_keyword, BindingKindStr)
.fixItInsert(Tok.getLoc(), BindingKindStr.str()+" ");
}
// We're parsing a conditional binding.
assert(CurDeclContext->isLocalContext() &&
"conditional binding in non-local context?!");
ParserResult<Pattern> ThePattern;
if (BindingKindStr == "case") {
// In our recursive parse, remember that we're in a matching pattern.
llvm::SaveAndRestore<decltype(InBindingPattern)> T(
InBindingPattern, PatternBindingState::InMatchingPattern);
// Reset async attribute in parser context.
llvm::SaveAndRestore<bool> AsyncAttr(InPatternWithAsyncAttribute, false);
ThePattern = parseMatchingPattern(/*isExprBasic*/ true);
} else if (Tok.is(tok::kw_case)) {
// If will probably be a common typo to write "if let case" instead of
// "if case let" so detect this and produce a nice fixit.
diagnose(IntroducerLoc, diag::wrong_condition_case_location,
BindingKindStr)
.fixItRemove(IntroducerLoc)
.fixItInsertAfter(Tok.getLoc(), " " + BindingKindStr.str());
consumeToken(tok::kw_case);
auto newPatternBindingState = PatternBindingState::get(BindingKindStr)
.value_or(PatternBindingState(PatternBindingState::InVar));
BindingKindStr = "case";
// In our recursive parse, remember that we're in a var/let pattern.
llvm::SaveAndRestore<decltype(InBindingPattern)> T(InBindingPattern,
newPatternBindingState);
// Reset async attribute in parser context.
llvm::SaveAndRestore<bool> AsyncAttr(InPatternWithAsyncAttribute, false);
ThePattern = parseMatchingPattern(/*isExprBasic*/ true);
if (ThePattern.isNonNull()) {
auto *P = new (Context)
BindingPattern(IntroducerLoc, *newPatternBindingState.getIntroducer(),
ThePattern.get());
ThePattern = makeParserResult(Status, P);
}
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeOptionalBinding();
}
ThePattern = makeParserResult(new (Context) AnyPattern(Tok.getLoc()));
ThePattern.setHasCodeCompletionAndIsError();
consumeToken(tok::code_complete);
} else {
// Otherwise, this is an implicit optional binding "if let".
ThePattern = parseMatchingPatternAsBinding(
PatternBindingState::get(BindingKindStr)
.value_or(PatternBindingState(PatternBindingState::InVar)),
IntroducerLoc,
/*isExprBasic*/ true);
// The let/var pattern is part of the statement.
if (Pattern *P = ThePattern.getPtrOrNull())
P->setImplicit();
}
ThePattern = parseOptionalPatternTypeAnnotation(ThePattern);
if (ThePattern.hasCodeCompletion()) {
Status.setHasCodeCompletionAndIsError();
// Skip to '=' so that the completion can see the expected type of the
// pattern which is determined by the initializer.
skipUntilDeclStmtRBrace(tok::equal, tok::l_brace);
}
if (ThePattern.isNull()) {
// Recover by creating AnyPattern.
auto *AP = new (Context) AnyPattern(PreviousLoc);
if (PreviousLoc.isInvalid())
AP->setImplicit();
ThePattern = makeParserResult(AP);
}
// Conditional bindings can have the format:
// `let newBinding = <expr>`, or
// `let newBinding`, which is shorthand for `let newBinding = newBinding`
ParserResult<Expr> Init;
if (Tok.is(tok::equal)) {
consumeToken();
Init = parseExprBasic(diag::expected_expr_conditional_var);
} else if (!ThePattern.getPtrOrNull()->getBoundName().empty()) {
auto bindingName = DeclNameRef(ThePattern.getPtrOrNull()->getBoundName());
auto loc = DeclNameLoc(ThePattern.getPtrOrNull()->getEndLoc());
auto declRefExpr = new (Context) UnresolvedDeclRefExpr(bindingName,
DeclRefKind::Ordinary,
loc);
// We do NOT mark this declRefExpr as implicit because that'd avoid
// reporting errors if it were used in a synchronous context in
// 'diagnoseUnhandledAsyncSite'. There may be other ways to resolve the
// reporting issue that we could explore in the future.
//
// Even though implicit, the ast node has correct source location.
Init = makeParserResult(declRefExpr);
} else if (BindingKindStr != "case") {
// If the pattern is present but isn't an identifier, the user wrote
// something invalid like `let foo.bar`. Emit a special diagnostic for this,
// with a fix-it prepending "<#identifier#> = "
// - We don't emit this fix-it if the user wrote `case let` (etc),
// since the shorthand syntax isn't available for pattern matching
auto diagLoc = ThePattern.get()->getSemanticsProvidingPattern()->getStartLoc();
diagnose(diagLoc, diag::conditional_var_valid_identifiers_only)
.fixItInsert(diagLoc, "<#identifier#> = ");
// For better recovery, assume the expression pattern as the initializer,
// and synthesize an optional AnyPattern.
auto *semanticPattern = ThePattern.get()->getSemanticsProvidingPattern();
if (auto *EP = dyn_cast<ExprPattern>(semanticPattern)) {
Init = makeParserResult(EP->getSubExpr());
auto *AP = AnyPattern::createImplicit(Context);
ThePattern =
makeParserResult(OptionalSomePattern::createImplicit(Context, AP));
}
} else {
diagnose(Tok, diag::conditional_var_initializer_required);
}
if (Init.hasCodeCompletion())
Status.setHasCodeCompletionAndIsError();
if (Init.isNull()) {
// Recover by creating ErrorExpr.
Init = makeParserResult(new (Context)
ErrorExpr(ThePattern.get()->getEndLoc()));
}
result.push_back(ConditionalPatternBindingInfo::create(
Context, IntroducerLoc, ThePattern.get(), Init.get()));
return Status;
}
/// Parse the condition of an 'if' or 'while'.
///
/// condition:
/// condition-clause (',' condition-clause)*
/// condition-clause:
/// expr-basic
/// ('var' | 'let' | 'case') pattern '=' expr-basic
/// '#available' '(' availability-spec (',' availability-spec)* ')'
/// '#_hasSymbol' '(' expr ')'
///
/// The use of expr-basic here disallows trailing closures, which are
/// problematic given the curly braces around the if/while body.
///
ParserStatus Parser::parseStmtCondition(StmtCondition &Condition,
Diag<> DefaultID, StmtKind ParentKind) {
ParserStatus Status;
Condition = StmtCondition();
SmallVector<StmtConditionElement, 4> result;
// For error recovery purposes, keep track of the disposition of the last
// pattern binding we saw ('let', 'var', or 'case').
StringRef BindingKindStr;
// We have a simple comma separated list of clauses, but also need to handle
// a variety of common errors situations (including migrating from Swift 2
// syntax).
while (true) {
Status |= parseStmtConditionElement(result, DefaultID, ParentKind,
BindingKindStr);
if (Status.isErrorOrHasCompletion())
break;
// If a comma exists consume it and succeed.
if (consumeIf(tok::comma))
continue;
// If we have an "&&" token followed by a continuation of the statement
// condition, then fixit the "&&" to "," and keep going.
if (Tok.isAny(tok::oper_binary_spaced, tok::oper_binary_unspaced) &&
Tok.getText() == "&&") {
diagnose(Tok, diag::expected_comma_stmtcondition)
.fixItReplaceChars(getEndOfPreviousLoc(), Tok.getRange().getEnd(), ",");
consumeToken();
continue;
}
// Boolean conditions are separated by commas, not the 'where' keyword, as
// they were in Swift 2 and earlier.
if (Tok.is(tok::kw_where)) {
diagnose(Tok, diag::expected_comma_stmtcondition)
.fixItReplaceChars(getEndOfPreviousLoc(), Tok.getRange().getEnd(), ",");
consumeToken();
continue;
}
break;
};
Condition = Context.AllocateCopy(result);
return Status;
}
///
/// stmt-if:
/// 'if' condition stmt-brace stmt-if-else?
/// stmt-if-else:
/// 'else' stmt-brace
/// 'else' stmt-if
ParserResult<Stmt> Parser::parseStmtIf(LabeledStmtInfo LabelInfo,
bool IfWasImplicitlyInserted) {
SourceLoc IfLoc;
if (IfWasImplicitlyInserted) {
// The code was invalid due to a missing 'if' (e.g. 'else x < y {') and a
// fixit implicitly inserted it.
IfLoc = Tok.getLoc();
} else {
IfLoc = consumeToken(tok::kw_if);
}
ParserStatus Status;
StmtCondition Condition;
ParserResult<BraceStmt> NormalBody;
// A scope encloses the condition and true branch for any variables bound
// by a conditional binding. The else branch does *not* see these variables.
{
auto recoverWithCond = [&](ParserStatus Status,
StmtCondition Condition) -> ParserResult<Stmt> {
if (Condition.empty()) {
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(IfLoc));
Condition = Context.AllocateCopy(ConditionElems);
}
auto EndLoc = Condition.back().getEndLoc();
return makeParserResult(
Status,
new (Context) IfStmt(
LabelInfo, IfLoc, Condition,
BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true),
SourceLoc(), nullptr));
};
if (Tok.is(tok::l_brace)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(IfLoc, diag::missing_condition_after_if)
.highlight(SourceRange(IfLoc, LBraceLoc));
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc));
Condition = Context.AllocateCopy(ConditionElems);
} else {
Status |= parseStmtCondition(Condition, diag::expected_condition_if,
StmtKind::If);
if (Status.isErrorOrHasCompletion())
return recoverWithCond(Status, Condition);
}
if (Tok.is(tok::kw_else)) {
SourceLoc ElseLoc = Tok.getLoc();
diagnose(ElseLoc, diag::unexpected_else_after_if);
diagnose(ElseLoc, diag::suggest_removing_else)
.fixItRemove(ElseLoc);
consumeToken(tok::kw_else);
}
NormalBody = parseBraceItemList(diag::expected_lbrace_after_if);
Status |= NormalBody;
if (NormalBody.isNull())
return recoverWithCond(Status, Condition);
}
// The else branch, if any, is outside of the scope of the condition.
SourceLoc ElseLoc;
ParserResult<Stmt> ElseBody;
if (Tok.is(tok::kw_else)) {
ElseLoc = consumeToken(tok::kw_else);
bool implicitlyInsertIf = false;
if (Tok.isNot(tok::kw_if, tok::l_brace, tok::code_complete)) {
// The code looks like 'if ... { ... } else not_if_or_lbrace', so we've
// got a problem. If the last bit is 'else ... {' on one line, let's
// assume they've forgotten the 'if'.
BacktrackingScope backtrack(*this);
if (skipUntilTokenOrEndOfLine(tok::l_brace, tok::r_brace))
implicitlyInsertIf = Tok.is(tok::l_brace);
}
if (Tok.is(tok::kw_if) || implicitlyInsertIf) {
if (implicitlyInsertIf) {
diagnose(ElseLoc, diag::expected_lbrace_or_if_after_else_fixit)
.fixItInsertAfter(ElseLoc, " if");
}
ElseBody = parseStmtIf(LabeledStmtInfo(), implicitlyInsertIf);
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeAfterIfStmtElse();
}
Status.setHasCodeCompletionAndIsError();
consumeToken(tok::code_complete);
} else {
ElseBody = parseBraceItemList(diag::expected_lbrace_or_if_after_else);
}
Status |= ElseBody;
}
return makeParserResult(
Status, new (Context) IfStmt(LabelInfo,
IfLoc, Condition, NormalBody.get(),
ElseLoc, ElseBody.getPtrOrNull()));
}
/// stmt-guard:
/// 'guard' condition 'else' stmt-brace
///
ParserResult<Stmt> Parser::parseStmtGuard() {
SourceLoc GuardLoc = consumeToken(tok::kw_guard);
ParserStatus Status;
StmtCondition Condition;
ParserResult<BraceStmt> Body;
auto recoverWithCond = [&](ParserStatus Status,
StmtCondition Condition) -> ParserResult<Stmt> {
if (Condition.empty()) {
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(GuardLoc));
Condition = Context.AllocateCopy(ConditionElems);
}
auto EndLoc = Condition.back().getEndLoc();
return makeParserResult(
Status,
new (Context) GuardStmt(
GuardLoc, Condition,
BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true)));
};
if (Tok.isAny(tok::l_brace, tok::kw_else)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(GuardLoc, diag::missing_condition_after_guard)
.highlight(SourceRange(GuardLoc, LBraceLoc));
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc));
Condition = Context.AllocateCopy(ConditionElems);
} else {
Status |= parseStmtCondition(Condition, diag::expected_condition_guard,
StmtKind::Guard);
if (Status.isErrorOrHasCompletion()) {
// FIXME: better recovery
return recoverWithCond(Status, Condition);
}
}
// Parse the 'else'. If it is missing, and if the following token isn't a {
// then the parser is hopelessly lost - just give up instead of spewing.
if (!consumeIf(tok::kw_else)) {
checkForInputIncomplete();
auto diag = diagnose(Tok, diag::expected_else_after_guard);
if (Tok.is(tok::l_brace))
diag.fixItInsert(Tok.getLoc(), "else ");
else
return recoverWithCond(Status, Condition);
}
Body = parseBraceItemList(diag::expected_lbrace_after_guard);
if (Body.isNull())
return recoverWithCond(Status, Condition);
Status |= Body;
return makeParserResult(Status,
new (Context) GuardStmt(GuardLoc, Condition, Body.get()));
}
///
/// stmt-while:
/// (identifier ':')? 'while' expr-basic stmt-brace
ParserResult<Stmt> Parser::parseStmtWhile(LabeledStmtInfo LabelInfo) {
SourceLoc WhileLoc = consumeToken(tok::kw_while);
ParserStatus Status;
StmtCondition Condition;
auto recoverWithCond = [&](ParserStatus Status,
StmtCondition Condition) -> ParserResult<Stmt> {
if (Condition.empty()) {
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(WhileLoc));
Condition = Context.AllocateCopy(ConditionElems);
}
auto EndLoc = Condition.back().getEndLoc();
return makeParserResult(
Status,
new (Context) WhileStmt(
LabelInfo, WhileLoc, Condition,
BraceStmt::create(Context, EndLoc, {}, EndLoc, /*implicit=*/true)));
};
if (Tok.is(tok::l_brace)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(WhileLoc, diag::missing_condition_after_while)
.highlight(SourceRange(WhileLoc, LBraceLoc));
SmallVector<StmtConditionElement, 1> ConditionElems;
ConditionElems.emplace_back(new (Context) ErrorExpr(LBraceLoc));
Condition = Context.AllocateCopy(ConditionElems);
} else {
Status |= parseStmtCondition(Condition, diag::expected_condition_while,
StmtKind::While);
if (Status.isErrorOrHasCompletion())
return recoverWithCond(Status, Condition);
}
ParserResult<BraceStmt> Body =
parseBraceItemList(diag::expected_lbrace_after_while);
Status |= Body;
if (Body.isNull())
return recoverWithCond(Status, Condition);
return makeParserResult(
Status, new (Context) WhileStmt(LabelInfo, WhileLoc, Condition,
Body.get()));
}
///
/// stmt-repeat:
/// (identifier ':')? 'repeat' stmt-brace 'while' expr
ParserResult<Stmt> Parser::parseStmtRepeat(LabeledStmtInfo labelInfo) {
SourceLoc repeatLoc = consumeToken(tok::kw_repeat);
ParserStatus status;
ParserResult<BraceStmt> body =
parseBraceItemList(diag::expected_lbrace_after_repeat);
status |= body;
if (body.isNull())
body = makeParserResult(
body, BraceStmt::create(Context, repeatLoc, {}, PreviousLoc, true));
SourceLoc whileLoc;
if (!consumeIf(tok::kw_while, whileLoc)) {
diagnose(body.getPtrOrNull()->getEndLoc(),
diag::expected_while_after_repeat_body);
return body;
}
ParserResult<Expr> condition;
if (Tok.is(tok::l_brace)) {
diagnose(whileLoc, diag::missing_condition_after_while);
condition = makeParserErrorResult(new (Context) ErrorExpr(whileLoc));
} else {
condition = parseExpr(diag::expected_expr_repeat_while);
status |= condition;
if (condition.isNull()) {
condition = makeParserErrorResult(new (Context) ErrorExpr(whileLoc));
}
}
return makeParserResult(
status,
new (Context) RepeatWhileStmt(labelInfo, repeatLoc, condition.get(),
whileLoc, body.get()));
}
///
/// stmt-do:
/// (identifier ':')? 'do' throws-clause? stmt-brace
/// (identifier ':')? 'do' throws-clause? stmt-brace stmt-catch+
ParserResult<Stmt> Parser::parseStmtDo(LabeledStmtInfo labelInfo,
bool shouldSkipDoTokenConsume) {
SourceLoc doLoc;
if (shouldSkipDoTokenConsume) {
doLoc = Tok.getLoc();
} else {
doLoc = consumeToken(tok::kw_do);
}
ParserStatus status;
// Parse the optional 'throws' clause.
SourceLoc throwsLoc;
TypeRepr *thrownType = nullptr;
if (consumeIf(tok::kw_throws, throwsLoc)) {
// Parse the thrown error type.
SourceLoc lParenLoc;
if (consumeIf(tok::l_paren, lParenLoc)) {
ParserResult<TypeRepr> parsedThrownTy =
parseType(diag::expected_thrown_error_type);
thrownType = parsedThrownTy.getPtrOrNull();
status |= parsedThrownTy;
SourceLoc rParenLoc;
parseMatchingToken(
tok::r_paren, rParenLoc,
diag::expected_rparen_after_thrown_error_type, lParenLoc);
}
}
ParserResult<BraceStmt> body =
parseBraceItemList(diag::expected_lbrace_after_do);
status |= body;
if (body.isNull())
body = makeParserResult(
body, BraceStmt::create(Context, doLoc, {}, PreviousLoc, true));
// If the next token is 'catch', this is a 'do'/'catch' statement.
if (Tok.is(tok::kw_catch)) {
// Parse 'catch' clauses
SmallVector<CaseStmt *, 4> allClauses;
ParserStatus catchClausesStatus;
do {
ParserResult<CaseStmt> clause = parseStmtCatch();
catchClausesStatus |= clause;
if (catchClausesStatus.hasCodeCompletion() && clause.isNull()) {
status |= catchClausesStatus;
return makeParserResult<Stmt>(status, nullptr);
}
// parseStmtCatch promises to return non-null unless we are
// completing inside the catch's pattern.
allClauses.push_back(clause.get());
} while (Tok.is(tok::kw_catch) && !catchClausesStatus.hasCodeCompletion());
status |= catchClausesStatus;
// Recover from all of the clauses failing to parse by returning a
// normal do-statement.
if (allClauses.empty()) {
assert(status.isErrorOrHasCompletion());
return makeParserResult(status,
new (Context) DoStmt(labelInfo, doLoc, body.get()));
}
return makeParserResult(status,
DoCatchStmt::create(CurDeclContext, labelInfo, doLoc, throwsLoc,
thrownType, body.get(), allClauses));
}
if (throwsLoc.isValid()) {
diagnose(throwsLoc, diag::do_throws_without_catch);
}
// If we dont see a 'while' or see a 'while' that starts
// from new line. This is just the bare `do` scoping statement.
if (Tok.getKind() != tok::kw_while || Tok.isAtStartOfLine()) {
return makeParserResult(status,
new (Context) DoStmt(labelInfo, doLoc, body.get()));
}
SourceLoc whileLoc = Tok.getLoc();
// But if we do, advise the programmer that it's 'repeat' now.
diagnose(doLoc, diag::do_while_now_repeat_while);
diagnose(doLoc, diag::do_while_expected_repeat_while)
.fixItReplace(doLoc, "repeat");
diagnose(doLoc, diag::do_while_expected_separate_stmt)
.fixItInsert(whileLoc, "\n");
consumeToken(tok::kw_while);
status.setIsParseError();
ParserResult<Expr> condition;
if (Tok.is(tok::l_brace)) {
SourceLoc lbraceLoc = Tok.getLoc();
diagnose(whileLoc, diag::missing_condition_after_while);
condition = makeParserErrorResult(new (Context) ErrorExpr(lbraceLoc));
} else {
condition = parseExpr(diag::expected_expr_repeat_while);
status |= condition;
if (condition.isNull() || condition.hasCodeCompletion())
return makeParserResult<Stmt>(status, nullptr); // FIXME: better recovery
}
return makeParserResult(
status,
new (Context) RepeatWhileStmt(labelInfo, doLoc, condition.get(), whileLoc,
body.get()));
}
/// stmt-catch:
/// 'catch' pattern ('where' expr)? stmt-brace
///
/// Note that this is not a "first class" statement; it can only
/// appear following a 'do' statement.
///
/// This routine promises to return a non-null result unless there was
/// a code-completion token in the pattern.
ParserResult<CaseStmt> Parser::parseStmtCatch() {
// A catch block has its own scope for variables bound out of the pattern.
SourceLoc catchLoc = consumeToken(tok::kw_catch);
SmallVector<VarDecl*, 4> boundDecls;
ParserStatus status;
SmallVector<CaseLabelItem, 1> caseLabelItems;
{
bool isFirst = true;
while (true) {
GuardedPattern PatternResult;
parseGuardedPattern(*this, PatternResult, status, boundDecls,
GuardedPatternContext::Catch, isFirst);
caseLabelItems.emplace_back(PatternResult.ThePattern,
PatternResult.WhereLoc, PatternResult.Guard);
isFirst = false;
if (!consumeIf(tok::comma))
break;
}
}
auto bodyResult = parseBraceItemList(diag::expected_lbrace_after_catch);
status |= bodyResult;
if (bodyResult.isNull()) {
bodyResult = makeParserErrorResult(BraceStmt::create(Context, PreviousLoc,
{}, PreviousLoc,
/*implicit=*/ true));
}
return makeParserResult(
status, CaseStmt::createParsedDoCatch(Context, catchLoc, caseLabelItems,
bodyResult.get()));
}
static bool isStmtForCStyle(Parser &P) {
// If we have a leading identifier followed by a ':' or 'in', or have a
// 'case', then this is obviously a for-each loop. "for in ..." is malformed
// but it's obviously not a C-style for.
if ((P.Tok.isIdentifierOrUnderscore() &&
P.peekToken().isAny(tok::colon, tok::kw_in)) ||
P.Tok.isAny(tok::kw_case, tok::kw_in))
return false;
// Otherwise, we have to look forward if we see ';' in control part.
Parser::BacktrackingScope Backtrack(P);
// The condition of a c-style-for loop can be parenthesized.
auto HasLParen = P.consumeIf(tok::l_paren);
// Skip until we see ';', or something that ends control part.
while (true) {
if (P.Tok.isAny(tok::eof, tok::kw_in, tok::l_brace, tok::r_brace,
tok::r_paren) ||
P.isStartOfStmt(/*preferExpr*/ false))
return false;
// If we saw newline before ';', consider it is a foreach statement.
if (!HasLParen && P.Tok.isAtStartOfLine())
return false;
if (P.Tok.is(tok::semi))
return true;
P.skipSingle();
}
}
///
/// stmt-for-each:
/// (identifier ':')? 'for' pattern 'in' expr-basic \
/// ('where' expr-basic)? stmt-brace
ParserResult<Stmt> Parser::parseStmtForEach(LabeledStmtInfo LabelInfo) {
SourceLoc ForLoc = consumeToken(tok::kw_for);
ParserStatus Status;
ParserResult<Pattern> pattern;
ParserResult<Expr> Container;
// The C-style for loop which was supported in Swift2 and foreach-style-for
// loop are conflated together into a single keyword, so we have to do some
// lookahead to resolve what is going on.
bool IsCStyleFor = isStmtForCStyle(*this);
auto StartOfControl = Tok.getLoc();
SourceLoc AwaitLoc;
SourceLoc TryLoc;
if (Tok.isContextualKeyword("await")) {
AwaitLoc = consumeToken();
} else if (Tok.is(tok::kw_try)) {
TryLoc = consumeToken();
if (Tok.isContextualKeyword("await")) {
AwaitLoc = consumeToken();
}
}
if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeForEachPatternBeginning(
TryLoc.isValid(), AwaitLoc.isValid());
}
consumeToken(tok::code_complete);
// Since 'completeForeachPatternBeginning' is a keyword only completion,
// we don't need to parse the rest of 'for' statement.
return makeParserCodeCompletionStatus();
}
// Parse the pattern. This is either 'case <refutable pattern>' or just a
// normal pattern.
if (consumeIf(tok::kw_case)) {
llvm::SaveAndRestore<decltype(InBindingPattern)> T(
InBindingPattern, PatternBindingState::InMatchingPattern);
// Reset async attribute in parser context.
llvm::SaveAndRestore<bool> AsyncAttr(InPatternWithAsyncAttribute, false);
pattern = parseMatchingPattern(/*isExprBasic*/true);
pattern = parseOptionalPatternTypeAnnotation(pattern);
} else if (!IsCStyleFor || Tok.is(tok::kw_var)) {
// Change the parser state to know that the pattern we're about to parse is
// implicitly mutable. Bound variables can be changed to mutable explicitly
// if desired by using a 'var' pattern.
assert(InBindingPattern == PatternBindingState::NotInBinding &&
"for-each loops cannot exist inside other patterns");
InBindingPattern = PatternBindingState::ImplicitlyImmutable;
pattern = parseTypedPattern();
assert(InBindingPattern == PatternBindingState::ImplicitlyImmutable);
InBindingPattern = PatternBindingState::NotInBinding;
}
SourceLoc InLoc;
if (pattern.isNull()) {
// Recover by creating a "_" pattern.
pattern = makeParserErrorResult(AnyPattern::createImplicit(Context));
consumeIf(tok::kw_in, InLoc);
} else if (!IsCStyleFor) {
parseToken(tok::kw_in, InLoc, diag::expected_foreach_in);
}
if (IsCStyleFor) {
// Skip until start of body part.
if (Tok.is(tok::l_paren)) {
skipSingle();
} else {
// If not parenthesized, don't run over the line.
while (Tok.isNot(tok::eof, tok::r_brace, tok::l_brace, tok::code_complete)
&& !Tok.isAtStartOfLine())
skipSingle();
}
if (Tok.is(tok::code_complete))
return makeParserCodeCompletionStatus();
assert(StartOfControl != Tok.getLoc());
SourceRange ControlRange(StartOfControl, PreviousLoc);
Container = makeParserErrorResult(new (Context) ErrorExpr(ControlRange));
diagnose(ForLoc, diag::c_style_for_stmt_removed)
.highlight(ControlRange);
Status = makeParserError();
} else if (Tok.is(tok::l_brace)) {
SourceLoc LBraceLoc = Tok.getLoc();
diagnose(LBraceLoc, diag::expected_foreach_container);
Container = makeParserErrorResult(new (Context) ErrorExpr(LBraceLoc));
} else if (Tok.is(tok::code_complete)) {
// If there is no "in" keyword, suggest it. Otherwise, complete the
// sequence.
if (InLoc.isInvalid()) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeForEachInKeyword();
}
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
} else {
Container =
makeParserResult(new (Context) CodeCompletionExpr(Tok.getLoc()));
Container.setHasCodeCompletionAndIsError();
Status |= Container;
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeForEachSequenceBeginning(
cast<CodeCompletionExpr>(Container.get()));
}
consumeToken(tok::code_complete);
}
} else {
Container = parseExprBasic(diag::expected_foreach_container);
Status |= Container;
if (Container.isNull())
Container = makeParserErrorResult(new (Context) ErrorExpr(Tok.getLoc()));
if (Container.isParseErrorOrHasCompletion())
// Recover.
skipUntilDeclStmtRBrace(tok::l_brace, tok::kw_where);
}
// Parse the 'where' expression if present.
ParserResult<Expr> Where;
SourceLoc WhereLoc;
if (Tok.is(tok::kw_where)) {
WhereLoc = consumeToken();
Where = parseExprBasic(diag::expected_foreach_where_expr);
if (Where.isNull())
Where = makeParserErrorResult(new (Context) ErrorExpr(Tok.getLoc()));
Status |= Where;
}
// stmt-brace
ParserResult<BraceStmt> Body =
parseBraceItemList(diag::expected_foreach_lbrace);
Status |= Body;
if (Body.isNull())
Body = makeParserResult(
Body, BraceStmt::create(Context, ForLoc, {}, PreviousLoc, true));
return makeParserResult(
Status,
new (Context) ForEachStmt(LabelInfo, ForLoc, TryLoc, AwaitLoc, pattern.get(), InLoc,
Container.get(), WhereLoc, Where.getPtrOrNull(),
Body.get()));
}
///
/// stmt-switch:
/// (identifier ':')? 'switch' expr-basic '{' stmt-case+ '}'
ParserResult<Stmt> Parser::parseStmtSwitch(LabeledStmtInfo LabelInfo) {
SourceLoc SwitchLoc = consumeToken(tok::kw_switch);
ParserStatus Status;
ParserResult<Expr> SubjectExpr;
SourceLoc SubjectLoc = Tok.getLoc();
if (Tok.is(tok::l_brace)) {
diagnose(SubjectLoc, diag::expected_switch_expr);
SubjectExpr = makeParserErrorResult(new (Context) ErrorExpr(SubjectLoc));
} else {
SubjectExpr = parseExprBasic(diag::expected_switch_expr);
if (SubjectExpr.isNull()) {
SubjectExpr = makeParserErrorResult(new (Context) ErrorExpr(SubjectLoc));
}
Status |= SubjectExpr;
}
SourceLoc lBraceLoc;
SourceLoc rBraceLoc;
SmallVector<ASTNode, 8> cases;
if (Status.isErrorOrHasCompletion()) {
return makeParserResult(
Status, SwitchStmt::create(LabelInfo, SwitchLoc, SubjectExpr.get(),
lBraceLoc, cases, rBraceLoc,
/*EndLoc=*/PreviousLoc, Context));
}
if (!consumeIf(tok::l_brace, lBraceLoc)) {
diagnose(Tok, diag::expected_lbrace_after_switch);
return makeParserResult(
Status, SwitchStmt::create(LabelInfo, SwitchLoc, SubjectExpr.get(),
lBraceLoc, cases, rBraceLoc,
/*EndLoc=*/PreviousLoc, Context));
}
Status |= parseStmtCases(cases, /*IsActive=*/true);
// We cannot have additional cases after a default clause. Complain on
// the first offender.
bool hasDefault = false;
for (auto Element : cases) {
if (!Element.is<Stmt*>()) continue;
auto *CS = cast<CaseStmt>(Element.get<Stmt*>());
if (hasDefault) {
diagnose(CS->getLoc(), diag::case_after_default);
break;
}
hasDefault |= CS->isDefault();
}
if (parseMatchingToken(tok::r_brace, rBraceLoc,
diag::expected_rbrace_switch, lBraceLoc)) {
Status.setIsParseError();
}
return makeParserResult(
Status, SwitchStmt::create(LabelInfo, SwitchLoc, SubjectExpr.get(),
lBraceLoc, cases, rBraceLoc,
/*EndLoc=*/rBraceLoc, Context));
}
ParserStatus
Parser::parseStmtCases(SmallVectorImpl<ASTNode> &cases, bool IsActive) {
ParserStatus Status;
while (Tok.isNot(tok::r_brace, tok::eof,
tok::pound_endif, tok::pound_elseif, tok::pound_else)) {
if (isAtStartOfSwitchCase(*this)) {
ParserResult<CaseStmt> Case = parseStmtCase(IsActive);
Status |= Case;
if (Case.isNonNull())
cases.emplace_back(Case.get());
} else if (Tok.is(tok::pound_if)) {
// '#if' in 'case' position can enclose one or more 'case' or 'default'
// clauses.
auto IfConfigResult = parseIfConfig(
[&](SmallVectorImpl<ASTNode> &Elements, bool IsActive) {
parseStmtCases(Elements, IsActive);
});
Status |= IfConfigResult;
if (auto ICD = IfConfigResult.getPtrOrNull()) {
cases.emplace_back(ICD);
for (auto &Entry : ICD->getActiveClauseElements()) {
if (Entry.is<Decl*>() &&
(isa<IfConfigDecl>(Entry.get<Decl*>())))
// Don't hoist nested '#if'.
continue;
assert((Entry.is<Stmt*>() && isa<CaseStmt>(Entry.get<Stmt*>())) ||
(Entry.is<Decl*>() &&
isa<PoundDiagnosticDecl>(Entry.get<Decl*>())));
cases.push_back(Entry);
}
}
} else if (Tok.is(tok::pound_warning) || Tok.is(tok::pound_error)) {
auto PoundDiagnosticResult = parseDeclPoundDiagnostic();
Status |= PoundDiagnosticResult;
if (auto PDD = PoundDiagnosticResult.getPtrOrNull()) {
cases.emplace_back(PDD);
}
} else if (Tok.is(tok::code_complete)) {
if (CodeCompletionCallbacks) {
CodeCompletionCallbacks->completeCaseStmtKeyword();
}
consumeToken(tok::code_complete);
return makeParserCodeCompletionStatus();
} else {
// If there are non-case-label statements at the start of the switch body,
// raise an error and recover by discarding them.
diagnose(Tok, diag::stmt_in_switch_not_covered_by_case);
while (Tok.isNot(tok::r_brace, tok::eof, tok::pound_elseif,
tok::pound_else, tok::pound_endif) &&
!isTerminatorForBraceItemListKind(BraceItemListKind::Case, {})) {
skipSingle();
}
}
}
return Status;
}
static ParserStatus parseStmtCase(Parser &P, SourceLoc &CaseLoc,
SmallVectorImpl<CaseLabelItem> &LabelItems,
SmallVectorImpl<VarDecl *> &BoundDecls,
SourceLoc &ColonLoc) {
ParserStatus Status;
CaseLoc = P.consumeToken(tok::kw_case);
{
bool isFirst = true;
while (true) {
GuardedPattern PatternResult;
parseGuardedPattern(P, PatternResult, Status, BoundDecls,
GuardedPatternContext::Case, isFirst);
LabelItems.emplace_back(PatternResult.ThePattern, PatternResult.WhereLoc,
PatternResult.Guard);
isFirst = false;
if (!P.consumeIf(tok::comma))
break;
}
}
ColonLoc = P.Tok.getLoc();
if (!P.Tok.is(tok::colon)) {
P.diagnose(P.Tok, diag::expected_case_colon, "case");
Status.setIsParseError();
} else
P.consumeToken(tok::colon);
return Status;
}
static ParserStatus
parseStmtCaseDefault(Parser &P, SourceLoc &CaseLoc,
SmallVectorImpl<CaseLabelItem> &LabelItems,
SourceLoc &ColonLoc) {
ParserStatus Status;
CaseLoc = P.consumeToken(tok::kw_default);
// We don't allow 'where' guards on a 'default' block. For recovery
// parse one if present.
SourceLoc WhereLoc;
ParserResult<Expr> Guard;
if (P.Tok.is(tok::kw_where)) {
P.diagnose(P.Tok, diag::default_with_where);
WhereLoc = P.consumeToken(tok::kw_where);
Guard = P.parseExpr(diag::expected_case_where_expr);
Status |= Guard;
}
ColonLoc = P.Tok.getLoc();
if (!P.Tok.is(tok::colon)) {
P.diagnose(P.Tok, diag::expected_case_colon, "default");
Status.setIsParseError();
} else
P.consumeToken(tok::colon);
// Create an implicit AnyPattern to represent the default match.
auto Any = new (P.Context) AnyPattern(CaseLoc);
if (CaseLoc.isInvalid())
Any->setImplicit();
LabelItems.push_back(
CaseLabelItem::getDefault(Any, WhereLoc, Guard.getPtrOrNull()));
return Status;
}
ParserResult<CaseStmt> Parser::parseStmtCase(bool IsActive) {
ParserStatus Status;
SmallVector<CaseLabelItem, 2> CaseLabelItems;
SmallVector<VarDecl *, 4> BoundDecls;
SourceLoc UnknownAttrLoc;
while (Tok.is(tok::at_sign)) {
if (peekToken().isContextualKeyword("unknown")) {
if (!UnknownAttrLoc.isValid()) {
UnknownAttrLoc = consumeToken(tok::at_sign);
} else {
diagnose(Tok, diag::duplicate_attribute, false);
diagnose(UnknownAttrLoc, diag::previous_attribute, false);
consumeToken(tok::at_sign);
}
consumeToken(tok::identifier);
if (Tok.is(tok::l_paren)) {
diagnose(Tok, diag::unexpected_lparen_in_attribute, "unknown");
skipSingle();
}
} else {
assert(peekToken().is(tok::identifier) && "isAtStartOfSwitchCase() lied");
consumeToken(tok::at_sign);
diagnose(Tok, diag::unknown_attribute, Tok.getText());
consumeToken(tok::identifier);
if (Tok.is(tok::l_paren))
skipSingle();
}
}
SourceLoc CaseLoc;
SourceLoc ColonLoc;
if (Tok.is(tok::kw_case)) {
Status |=
::parseStmtCase(*this, CaseLoc, CaseLabelItems, BoundDecls, ColonLoc);
} else if (Tok.is(tok::kw_default)) {
Status |= parseStmtCaseDefault(*this, CaseLoc, CaseLabelItems, ColonLoc);
} else {
llvm_unreachable("isAtStartOfSwitchCase() lied.");
}
assert(!CaseLabelItems.empty() && "did not parse any labels?!");
SmallVector<ASTNode, 8> BodyItems;
SourceLoc StartOfBody = Tok.getLoc();
if (Tok.isNot(tok::r_brace) && !isAtStartOfSwitchCase(*this)) {
Status |= parseBraceItems(BodyItems, BraceItemListKind::Case);
} else if (Status.isSuccess() && !Status.hasCodeCompletion()) {
diagnose(CaseLoc, diag::case_stmt_without_body,
CaseLabelItems.back().isDefault())
.highlight(SourceRange(CaseLoc, ColonLoc))
.fixItInsertAfter(ColonLoc, " break");
}
BraceStmt *Body;
if (BodyItems.empty()) {
Body = BraceStmt::create(Context, PreviousLoc, ArrayRef<ASTNode>(),
PreviousLoc, /*implicit=*/true);
} else {
Body = BraceStmt::create(Context, StartOfBody, BodyItems,
PreviousLoc, /*implicit=*/true);
}
return makeParserResult(
Status, CaseStmt::createParsedSwitchCase(Context, CaseLoc, CaseLabelItems,
UnknownAttrLoc, ColonLoc, Body));
}
/// stmt-pound-assert:
/// '#assert' '(' expr (',' string_literal)? ')'
ParserResult<Stmt> Parser::parseStmtPoundAssert() {
SourceLoc startLoc = consumeToken(tok::pound_assert);
SourceLoc endLoc;
if (Tok.isNot(tok::l_paren)) {
diagnose(Tok, diag::pound_assert_expected_lparen);
return makeParserError();
}
SourceLoc LBLoc = consumeToken(tok::l_paren);
auto conditionExprResult = parseExpr(diag::pound_assert_expected_expression);
if (conditionExprResult.isParseErrorOrHasCompletion())
return ParserStatus(conditionExprResult);
StringRef message;
if (consumeIf(tok::comma)) {
if (Tok.isNot(tok::string_literal)) {
diagnose(Tok.getLoc(), diag::pound_assert_expected_string_literal);
return makeParserError();
}
auto messageOpt = getStringLiteralIfNotInterpolated(Tok.getLoc(),
"'#assert' message");
consumeToken();
if (!messageOpt)
return makeParserError();
message = *messageOpt;
}
if (parseMatchingToken(tok::r_paren, endLoc,
diag::pound_assert_expected_rparen, LBLoc)) {
return makeParserError();
}
if (!Context.LangOpts.hasFeature(Feature::StaticAssert)) {
diagnose(startLoc, diag::pound_assert_disabled);
return makeParserError();
}
return makeParserResult<Stmt>(new (Context) PoundAssertStmt(
SourceRange(startLoc, endLoc), conditionExprResult.get(), message));
}
|