1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
|
//===- Parser.cpp ---------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Tools/PDLL/Parser/Parser.h"
#include "Lexer.h"
#include "mlir/Support/IndentedOstream.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/TableGen/Argument.h"
#include "mlir/TableGen/Attribute.h"
#include "mlir/TableGen/Constraint.h"
#include "mlir/TableGen/Format.h"
#include "mlir/TableGen/Operator.h"
#include "mlir/Tools/PDLL/AST/Context.h"
#include "mlir/Tools/PDLL/AST/Diagnostic.h"
#include "mlir/Tools/PDLL/AST/Nodes.h"
#include "mlir/Tools/PDLL/AST/Types.h"
#include "mlir/Tools/PDLL/ODS/Constraint.h"
#include "mlir/Tools/PDLL/ODS/Context.h"
#include "mlir/Tools/PDLL/ODS/Operation.h"
#include "mlir/Tools/PDLL/Parser/CodeComplete.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Parser.h"
#include <string>
#include <optional>
using namespace mlir;
using namespace mlir::pdll;
//===----------------------------------------------------------------------===//
// Parser
//===----------------------------------------------------------------------===//
namespace {
class Parser {
public:
Parser(ast::Context &ctx, llvm::SourceMgr &sourceMgr,
bool enableDocumentation, CodeCompleteContext *codeCompleteContext)
: ctx(ctx), lexer(sourceMgr, ctx.getDiagEngine(), codeCompleteContext),
curToken(lexer.lexToken()), enableDocumentation(enableDocumentation),
typeTy(ast::TypeType::get(ctx)), valueTy(ast::ValueType::get(ctx)),
typeRangeTy(ast::TypeRangeType::get(ctx)),
valueRangeTy(ast::ValueRangeType::get(ctx)),
attrTy(ast::AttributeType::get(ctx)),
codeCompleteContext(codeCompleteContext) {}
/// Try to parse a new module. Returns nullptr in the case of failure.
FailureOr<ast::Module *> parseModule();
private:
/// The current context of the parser. It allows for the parser to know a bit
/// about the construct it is nested within during parsing. This is used
/// specifically to provide additional verification during parsing, e.g. to
/// prevent using rewrites within a match context, matcher constraints within
/// a rewrite section, etc.
enum class ParserContext {
/// The parser is in the global context.
Global,
/// The parser is currently within a Constraint, which disallows all types
/// of rewrites (e.g. `erase`, `replace`, calls to Rewrites, etc.).
Constraint,
/// The parser is currently within the matcher portion of a Pattern, which
/// is allows a terminal operation rewrite statement but no other rewrite
/// transformations.
PatternMatch,
/// The parser is currently within a Rewrite, which disallows calls to
/// constraints, requires operation expressions to have names, etc.
Rewrite,
};
/// The current specification context of an operations result type. This
/// indicates how the result types of an operation may be inferred.
enum class OpResultTypeContext {
/// The result types of the operation are not known to be inferred.
Explicit,
/// The result types of the operation are inferred from the root input of a
/// `replace` statement.
Replacement,
/// The result types of the operation are inferred by using the
/// `InferTypeOpInterface` interface provided by the operation.
Interface,
};
//===--------------------------------------------------------------------===//
// Parsing
//===--------------------------------------------------------------------===//
/// Push a new decl scope onto the lexer.
ast::DeclScope *pushDeclScope() {
ast::DeclScope *newScope =
new (scopeAllocator.Allocate()) ast::DeclScope(curDeclScope);
return (curDeclScope = newScope);
}
void pushDeclScope(ast::DeclScope *scope) { curDeclScope = scope; }
/// Pop the last decl scope from the lexer.
void popDeclScope() { curDeclScope = curDeclScope->getParentScope(); }
/// Parse the body of an AST module.
LogicalResult parseModuleBody(SmallVectorImpl<ast::Decl *> &decls);
/// Try to convert the given expression to `type`. Returns failure and emits
/// an error if a conversion is not viable. On failure, `noteAttachFn` is
/// invoked to attach notes to the emitted error diagnostic. On success,
/// `expr` is updated to the expression used to convert to `type`.
LogicalResult convertExpressionTo(
ast::Expr *&expr, ast::Type type,
function_ref<void(ast::Diagnostic &diag)> noteAttachFn = {});
LogicalResult
convertOpExpressionTo(ast::Expr *&expr, ast::OperationType exprType,
ast::Type type,
function_ref<ast::InFlightDiagnostic()> emitErrorFn);
LogicalResult convertTupleExpressionTo(
ast::Expr *&expr, ast::TupleType exprType, ast::Type type,
function_ref<ast::InFlightDiagnostic()> emitErrorFn,
function_ref<void(ast::Diagnostic &diag)> noteAttachFn);
/// Given an operation expression, convert it to a Value or ValueRange
/// typed expression.
ast::Expr *convertOpToValue(const ast::Expr *opExpr);
/// Lookup ODS information for the given operation, returns nullptr if no
/// information is found.
const ods::Operation *lookupODSOperation(std::optional<StringRef> opName) {
return opName ? ctx.getODSContext().lookupOperation(*opName) : nullptr;
}
/// Process the given documentation string, or return an empty string if
/// documentation isn't enabled.
StringRef processDoc(StringRef doc) {
return enableDocumentation ? doc : StringRef();
}
/// Process the given documentation string and format it, or return an empty
/// string if documentation isn't enabled.
std::string processAndFormatDoc(const Twine &doc) {
if (!enableDocumentation)
return "";
std::string docStr;
{
llvm::raw_string_ostream docOS(docStr);
std::string tmpDocStr = doc.str();
raw_indented_ostream(docOS).printReindented(
StringRef(tmpDocStr).rtrim(" \t"));
}
return docStr;
}
//===--------------------------------------------------------------------===//
// Directives
LogicalResult parseDirective(SmallVectorImpl<ast::Decl *> &decls);
LogicalResult parseInclude(SmallVectorImpl<ast::Decl *> &decls);
LogicalResult parseTdInclude(StringRef filename, SMRange fileLoc,
SmallVectorImpl<ast::Decl *> &decls);
/// Process the records of a parsed tablegen include file.
void processTdIncludeRecords(llvm::RecordKeeper &tdRecords,
SmallVectorImpl<ast::Decl *> &decls);
/// Create a user defined native constraint for a constraint imported from
/// ODS.
template <typename ConstraintT>
ast::Decl *
createODSNativePDLLConstraintDecl(StringRef name, StringRef codeBlock,
SMRange loc, ast::Type type,
StringRef nativeType, StringRef docString);
template <typename ConstraintT>
ast::Decl *
createODSNativePDLLConstraintDecl(const tblgen::Constraint &constraint,
SMRange loc, ast::Type type,
StringRef nativeType);
//===--------------------------------------------------------------------===//
// Decls
/// This structure contains the set of pattern metadata that may be parsed.
struct ParsedPatternMetadata {
std::optional<uint16_t> benefit;
bool hasBoundedRecursion = false;
};
FailureOr<ast::Decl *> parseTopLevelDecl();
FailureOr<ast::NamedAttributeDecl *>
parseNamedAttributeDecl(std::optional<StringRef> parentOpName);
/// Parse an argument variable as part of the signature of a
/// UserConstraintDecl or UserRewriteDecl.
FailureOr<ast::VariableDecl *> parseArgumentDecl();
/// Parse a result variable as part of the signature of a UserConstraintDecl
/// or UserRewriteDecl.
FailureOr<ast::VariableDecl *> parseResultDecl(unsigned resultNum);
/// Parse a UserConstraintDecl. `isInline` signals if the constraint is being
/// defined in a non-global context.
FailureOr<ast::UserConstraintDecl *>
parseUserConstraintDecl(bool isInline = false);
/// Parse an inline UserConstraintDecl. An inline decl is one defined in a
/// non-global context, such as within a Pattern/Constraint/etc.
FailureOr<ast::UserConstraintDecl *> parseInlineUserConstraintDecl();
/// Parse a PDLL (i.e. non-native) UserRewriteDecl whose body is defined using
/// PDLL constructs.
FailureOr<ast::UserConstraintDecl *> parseUserPDLLConstraintDecl(
const ast::Name &name, bool isInline,
ArrayRef<ast::VariableDecl *> arguments, ast::DeclScope *argumentScope,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType);
/// Parse a parseUserRewriteDecl. `isInline` signals if the rewrite is being
/// defined in a non-global context.
FailureOr<ast::UserRewriteDecl *> parseUserRewriteDecl(bool isInline = false);
/// Parse an inline UserRewriteDecl. An inline decl is one defined in a
/// non-global context, such as within a Pattern/Rewrite/etc.
FailureOr<ast::UserRewriteDecl *> parseInlineUserRewriteDecl();
/// Parse a PDLL (i.e. non-native) UserRewriteDecl whose body is defined using
/// PDLL constructs.
FailureOr<ast::UserRewriteDecl *> parseUserPDLLRewriteDecl(
const ast::Name &name, bool isInline,
ArrayRef<ast::VariableDecl *> arguments, ast::DeclScope *argumentScope,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType);
/// Parse either a UserConstraintDecl or UserRewriteDecl. These decls have
/// effectively the same syntax, and only differ on slight semantics (given
/// the different parsing contexts).
template <typename T, typename ParseUserPDLLDeclFnT>
FailureOr<T *> parseUserConstraintOrRewriteDecl(
ParseUserPDLLDeclFnT &&parseUserPDLLFn, ParserContext declContext,
StringRef anonymousNamePrefix, bool isInline);
/// Parse a native (i.e. non-PDLL) UserConstraintDecl or UserRewriteDecl.
/// These decls have effectively the same syntax.
template <typename T>
FailureOr<T *> parseUserNativeConstraintOrRewriteDecl(
const ast::Name &name, bool isInline,
ArrayRef<ast::VariableDecl *> arguments,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType);
/// Parse the functional signature (i.e. the arguments and results) of a
/// UserConstraintDecl or UserRewriteDecl.
LogicalResult parseUserConstraintOrRewriteSignature(
SmallVectorImpl<ast::VariableDecl *> &arguments,
SmallVectorImpl<ast::VariableDecl *> &results,
ast::DeclScope *&argumentScope, ast::Type &resultType);
/// Validate the return (which if present is specified by bodyIt) of a
/// UserConstraintDecl or UserRewriteDecl.
LogicalResult validateUserConstraintOrRewriteReturn(
StringRef declType, ast::CompoundStmt *body,
ArrayRef<ast::Stmt *>::iterator bodyIt,
ArrayRef<ast::Stmt *>::iterator bodyE,
ArrayRef<ast::VariableDecl *> results, ast::Type &resultType);
FailureOr<ast::CompoundStmt *>
parseLambdaBody(function_ref<LogicalResult(ast::Stmt *&)> processStatementFn,
bool expectTerminalSemicolon = true);
FailureOr<ast::CompoundStmt *> parsePatternLambdaBody();
FailureOr<ast::Decl *> parsePatternDecl();
LogicalResult parsePatternDeclMetadata(ParsedPatternMetadata &metadata);
/// Check to see if a decl has already been defined with the given name, if
/// one has emit and error and return failure. Returns success otherwise.
LogicalResult checkDefineNamedDecl(const ast::Name &name);
/// Try to define a variable decl with the given components, returns the
/// variable on success.
FailureOr<ast::VariableDecl *>
defineVariableDecl(StringRef name, SMRange nameLoc, ast::Type type,
ast::Expr *initExpr,
ArrayRef<ast::ConstraintRef> constraints);
FailureOr<ast::VariableDecl *>
defineVariableDecl(StringRef name, SMRange nameLoc, ast::Type type,
ArrayRef<ast::ConstraintRef> constraints);
/// Parse the constraint reference list for a variable decl.
LogicalResult parseVariableDeclConstraintList(
SmallVectorImpl<ast::ConstraintRef> &constraints);
/// Parse the expression used within a type constraint, e.g. Attr<type-expr>.
FailureOr<ast::Expr *> parseTypeConstraintExpr();
/// Try to parse a single reference to a constraint. `typeConstraint` is the
/// location of a previously parsed type constraint for the entity that will
/// be constrained by the parsed constraint. `existingConstraints` are any
/// existing constraints that have already been parsed for the same entity
/// that will be constrained by this constraint. `allowInlineTypeConstraints`
/// allows the use of inline Type constraints, e.g. `Value<valueType: Type>`.
FailureOr<ast::ConstraintRef>
parseConstraint(std::optional<SMRange> &typeConstraint,
ArrayRef<ast::ConstraintRef> existingConstraints,
bool allowInlineTypeConstraints);
/// Try to parse the constraint for a UserConstraintDecl/UserRewriteDecl
/// argument or result variable. The constraints for these variables do not
/// allow inline type constraints, and only permit a single constraint.
FailureOr<ast::ConstraintRef> parseArgOrResultConstraint();
//===--------------------------------------------------------------------===//
// Exprs
FailureOr<ast::Expr *> parseExpr();
/// Identifier expressions.
FailureOr<ast::Expr *> parseAttributeExpr();
FailureOr<ast::Expr *> parseCallExpr(ast::Expr *parentExpr);
FailureOr<ast::Expr *> parseDeclRefExpr(StringRef name, SMRange loc);
FailureOr<ast::Expr *> parseIdentifierExpr();
FailureOr<ast::Expr *> parseInlineConstraintLambdaExpr();
FailureOr<ast::Expr *> parseInlineRewriteLambdaExpr();
FailureOr<ast::Expr *> parseMemberAccessExpr(ast::Expr *parentExpr);
FailureOr<ast::OpNameDecl *> parseOperationName(bool allowEmptyName = false);
FailureOr<ast::OpNameDecl *> parseWrappedOperationName(bool allowEmptyName);
FailureOr<ast::Expr *>
parseOperationExpr(OpResultTypeContext inputResultTypeContext =
OpResultTypeContext::Explicit);
FailureOr<ast::Expr *> parseTupleExpr();
FailureOr<ast::Expr *> parseTypeExpr();
FailureOr<ast::Expr *> parseUnderscoreExpr();
//===--------------------------------------------------------------------===//
// Stmts
FailureOr<ast::Stmt *> parseStmt(bool expectTerminalSemicolon = true);
FailureOr<ast::CompoundStmt *> parseCompoundStmt();
FailureOr<ast::EraseStmt *> parseEraseStmt();
FailureOr<ast::LetStmt *> parseLetStmt();
FailureOr<ast::ReplaceStmt *> parseReplaceStmt();
FailureOr<ast::ReturnStmt *> parseReturnStmt();
FailureOr<ast::RewriteStmt *> parseRewriteStmt();
//===--------------------------------------------------------------------===//
// Creation+Analysis
//===--------------------------------------------------------------------===//
//===--------------------------------------------------------------------===//
// Decls
/// Try to extract a callable from the given AST node. Returns nullptr on
/// failure.
ast::CallableDecl *tryExtractCallableDecl(ast::Node *node);
/// Try to create a pattern decl with the given components, returning the
/// Pattern on success.
FailureOr<ast::PatternDecl *>
createPatternDecl(SMRange loc, const ast::Name *name,
const ParsedPatternMetadata &metadata,
ast::CompoundStmt *body);
/// Build the result type for a UserConstraintDecl/UserRewriteDecl given a set
/// of results, defined as part of the signature.
ast::Type
createUserConstraintRewriteResultType(ArrayRef<ast::VariableDecl *> results);
/// Create a PDLL (i.e. non-native) UserConstraintDecl or UserRewriteDecl.
template <typename T>
FailureOr<T *> createUserPDLLConstraintOrRewriteDecl(
const ast::Name &name, ArrayRef<ast::VariableDecl *> arguments,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType,
ast::CompoundStmt *body);
/// Try to create a variable decl with the given components, returning the
/// Variable on success.
FailureOr<ast::VariableDecl *>
createVariableDecl(StringRef name, SMRange loc, ast::Expr *initializer,
ArrayRef<ast::ConstraintRef> constraints);
/// Create a variable for an argument or result defined as part of the
/// signature of a UserConstraintDecl/UserRewriteDecl.
FailureOr<ast::VariableDecl *>
createArgOrResultVariableDecl(StringRef name, SMRange loc,
const ast::ConstraintRef &constraint);
/// Validate the constraints used to constraint a variable decl.
/// `inferredType` is the type of the variable inferred by the constraints
/// within the list, and is updated to the most refined type as determined by
/// the constraints. Returns success if the constraint list is valid, failure
/// otherwise.
LogicalResult
validateVariableConstraints(ArrayRef<ast::ConstraintRef> constraints,
ast::Type &inferredType);
/// Validate a single reference to a constraint. `inferredType` contains the
/// currently inferred variabled type and is refined within the type defined
/// by the constraint. Returns success if the constraint is valid, failure
/// otherwise.
LogicalResult validateVariableConstraint(const ast::ConstraintRef &ref,
ast::Type &inferredType);
LogicalResult validateTypeConstraintExpr(const ast::Expr *typeExpr);
LogicalResult validateTypeRangeConstraintExpr(const ast::Expr *typeExpr);
//===--------------------------------------------------------------------===//
// Exprs
FailureOr<ast::CallExpr *>
createCallExpr(SMRange loc, ast::Expr *parentExpr,
MutableArrayRef<ast::Expr *> arguments);
FailureOr<ast::DeclRefExpr *> createDeclRefExpr(SMRange loc, ast::Decl *decl);
FailureOr<ast::DeclRefExpr *>
createInlineVariableExpr(ast::Type type, StringRef name, SMRange loc,
ArrayRef<ast::ConstraintRef> constraints);
FailureOr<ast::MemberAccessExpr *>
createMemberAccessExpr(ast::Expr *parentExpr, StringRef name, SMRange loc);
/// Validate the member access `name` into the given parent expression. On
/// success, this also returns the type of the member accessed.
FailureOr<ast::Type> validateMemberAccess(ast::Expr *parentExpr,
StringRef name, SMRange loc);
FailureOr<ast::OperationExpr *>
createOperationExpr(SMRange loc, const ast::OpNameDecl *name,
OpResultTypeContext resultTypeContext,
SmallVectorImpl<ast::Expr *> &operands,
MutableArrayRef<ast::NamedAttributeDecl *> attributes,
SmallVectorImpl<ast::Expr *> &results);
LogicalResult
validateOperationOperands(SMRange loc, std::optional<StringRef> name,
const ods::Operation *odsOp,
SmallVectorImpl<ast::Expr *> &operands);
LogicalResult validateOperationResults(SMRange loc,
std::optional<StringRef> name,
const ods::Operation *odsOp,
SmallVectorImpl<ast::Expr *> &results);
void checkOperationResultTypeInferrence(SMRange loc, StringRef name,
const ods::Operation *odsOp);
LogicalResult validateOperationOperandsOrResults(
StringRef groupName, SMRange loc, std::optional<SMRange> odsOpLoc,
std::optional<StringRef> name, SmallVectorImpl<ast::Expr *> &values,
ArrayRef<ods::OperandOrResult> odsValues, ast::Type singleTy,
ast::RangeType rangeTy);
FailureOr<ast::TupleExpr *> createTupleExpr(SMRange loc,
ArrayRef<ast::Expr *> elements,
ArrayRef<StringRef> elementNames);
//===--------------------------------------------------------------------===//
// Stmts
FailureOr<ast::EraseStmt *> createEraseStmt(SMRange loc, ast::Expr *rootOp);
FailureOr<ast::ReplaceStmt *>
createReplaceStmt(SMRange loc, ast::Expr *rootOp,
MutableArrayRef<ast::Expr *> replValues);
FailureOr<ast::RewriteStmt *>
createRewriteStmt(SMRange loc, ast::Expr *rootOp,
ast::CompoundStmt *rewriteBody);
//===--------------------------------------------------------------------===//
// Code Completion
//===--------------------------------------------------------------------===//
/// The set of various code completion methods. Every completion method
/// returns `failure` to stop the parsing process after providing completion
/// results.
LogicalResult codeCompleteMemberAccess(ast::Expr *parentExpr);
LogicalResult codeCompleteAttributeName(std::optional<StringRef> opName);
LogicalResult codeCompleteConstraintName(ast::Type inferredType,
bool allowInlineTypeConstraints);
LogicalResult codeCompleteDialectName();
LogicalResult codeCompleteOperationName(StringRef dialectName);
LogicalResult codeCompletePatternMetadata();
LogicalResult codeCompleteIncludeFilename(StringRef curPath);
void codeCompleteCallSignature(ast::Node *parent, unsigned currentNumArgs);
void codeCompleteOperationOperandsSignature(std::optional<StringRef> opName,
unsigned currentNumOperands);
void codeCompleteOperationResultsSignature(std::optional<StringRef> opName,
unsigned currentNumResults);
//===--------------------------------------------------------------------===//
// Lexer Utilities
//===--------------------------------------------------------------------===//
/// If the current token has the specified kind, consume it and return true.
/// If not, return false.
bool consumeIf(Token::Kind kind) {
if (curToken.isNot(kind))
return false;
consumeToken(kind);
return true;
}
/// Advance the current lexer onto the next token.
void consumeToken() {
assert(curToken.isNot(Token::eof, Token::error) &&
"shouldn't advance past EOF or errors");
curToken = lexer.lexToken();
}
/// Advance the current lexer onto the next token, asserting what the expected
/// current token is. This is preferred to the above method because it leads
/// to more self-documenting code with better checking.
void consumeToken(Token::Kind kind) {
assert(curToken.is(kind) && "consumed an unexpected token");
consumeToken();
}
/// Reset the lexer to the location at the given position.
void resetToken(SMRange tokLoc) {
lexer.resetPointer(tokLoc.Start.getPointer());
curToken = lexer.lexToken();
}
/// Consume the specified token if present and return success. On failure,
/// output a diagnostic and return failure.
LogicalResult parseToken(Token::Kind kind, const Twine &msg) {
if (curToken.getKind() != kind)
return emitError(curToken.getLoc(), msg);
consumeToken();
return success();
}
LogicalResult emitError(SMRange loc, const Twine &msg) {
lexer.emitError(loc, msg);
return failure();
}
LogicalResult emitError(const Twine &msg) {
return emitError(curToken.getLoc(), msg);
}
LogicalResult emitErrorAndNote(SMRange loc, const Twine &msg, SMRange noteLoc,
const Twine ¬e) {
lexer.emitErrorAndNote(loc, msg, noteLoc, note);
return failure();
}
//===--------------------------------------------------------------------===//
// Fields
//===--------------------------------------------------------------------===//
/// The owning AST context.
ast::Context &ctx;
/// The lexer of this parser.
Lexer lexer;
/// The current token within the lexer.
Token curToken;
/// A flag indicating if the parser should add documentation to AST nodes when
/// viable.
bool enableDocumentation;
/// The most recently defined decl scope.
ast::DeclScope *curDeclScope = nullptr;
llvm::SpecificBumpPtrAllocator<ast::DeclScope> scopeAllocator;
/// The current context of the parser.
ParserContext parserContext = ParserContext::Global;
/// Cached types to simplify verification and expression creation.
ast::Type typeTy, valueTy;
ast::RangeType typeRangeTy, valueRangeTy;
ast::Type attrTy;
/// A counter used when naming anonymous constraints and rewrites.
unsigned anonymousDeclNameCounter = 0;
/// The optional code completion context.
CodeCompleteContext *codeCompleteContext;
};
} // namespace
FailureOr<ast::Module *> Parser::parseModule() {
SMLoc moduleLoc = curToken.getStartLoc();
pushDeclScope();
// Parse the top-level decls of the module.
SmallVector<ast::Decl *> decls;
if (failed(parseModuleBody(decls)))
return popDeclScope(), failure();
popDeclScope();
return ast::Module::create(ctx, moduleLoc, decls);
}
LogicalResult Parser::parseModuleBody(SmallVectorImpl<ast::Decl *> &decls) {
while (curToken.isNot(Token::eof)) {
if (curToken.is(Token::directive)) {
if (failed(parseDirective(decls)))
return failure();
continue;
}
FailureOr<ast::Decl *> decl = parseTopLevelDecl();
if (failed(decl))
return failure();
decls.push_back(*decl);
}
return success();
}
ast::Expr *Parser::convertOpToValue(const ast::Expr *opExpr) {
return ast::AllResultsMemberAccessExpr::create(ctx, opExpr->getLoc(), opExpr,
valueRangeTy);
}
LogicalResult Parser::convertExpressionTo(
ast::Expr *&expr, ast::Type type,
function_ref<void(ast::Diagnostic &diag)> noteAttachFn) {
ast::Type exprType = expr->getType();
if (exprType == type)
return success();
auto emitConvertError = [&]() -> ast::InFlightDiagnostic {
ast::InFlightDiagnostic diag = ctx.getDiagEngine().emitError(
expr->getLoc(), llvm::formatv("unable to convert expression of type "
"`{0}` to the expected type of "
"`{1}`",
exprType, type));
if (noteAttachFn)
noteAttachFn(*diag);
return diag;
};
if (auto exprOpType = exprType.dyn_cast<ast::OperationType>())
return convertOpExpressionTo(expr, exprOpType, type, emitConvertError);
// FIXME: Decide how to allow/support converting a single result to multiple,
// and multiple to a single result. For now, we just allow Single->Range,
// but this isn't something really supported in the PDL dialect. We should
// figure out some way to support both.
if ((exprType == valueTy || exprType == valueRangeTy) &&
(type == valueTy || type == valueRangeTy))
return success();
if ((exprType == typeTy || exprType == typeRangeTy) &&
(type == typeTy || type == typeRangeTy))
return success();
// Handle tuple types.
if (auto exprTupleType = exprType.dyn_cast<ast::TupleType>())
return convertTupleExpressionTo(expr, exprTupleType, type, emitConvertError,
noteAttachFn);
return emitConvertError();
}
LogicalResult Parser::convertOpExpressionTo(
ast::Expr *&expr, ast::OperationType exprType, ast::Type type,
function_ref<ast::InFlightDiagnostic()> emitErrorFn) {
// Two operation types are compatible if they have the same name, or if the
// expected type is more general.
if (auto opType = type.dyn_cast<ast::OperationType>()) {
if (opType.getName())
return emitErrorFn();
return success();
}
// An operation can always convert to a ValueRange.
if (type == valueRangeTy) {
expr = ast::AllResultsMemberAccessExpr::create(ctx, expr->getLoc(), expr,
valueRangeTy);
return success();
}
// Allow conversion to a single value by constraining the result range.
if (type == valueTy) {
// If the operation is registered, we can verify if it can ever have a
// single result.
if (const ods::Operation *odsOp = exprType.getODSOperation()) {
if (odsOp->getResults().empty()) {
return emitErrorFn()->attachNote(
llvm::formatv("see the definition of `{0}`, which was defined "
"with zero results",
odsOp->getName()),
odsOp->getLoc());
}
unsigned numSingleResults = llvm::count_if(
odsOp->getResults(), [](const ods::OperandOrResult &result) {
return result.getVariableLengthKind() ==
ods::VariableLengthKind::Single;
});
if (numSingleResults > 1) {
return emitErrorFn()->attachNote(
llvm::formatv("see the definition of `{0}`, which was defined "
"with at least {1} results",
odsOp->getName(), numSingleResults),
odsOp->getLoc());
}
}
expr = ast::AllResultsMemberAccessExpr::create(ctx, expr->getLoc(), expr,
valueTy);
return success();
}
return emitErrorFn();
}
LogicalResult Parser::convertTupleExpressionTo(
ast::Expr *&expr, ast::TupleType exprType, ast::Type type,
function_ref<ast::InFlightDiagnostic()> emitErrorFn,
function_ref<void(ast::Diagnostic &diag)> noteAttachFn) {
// Handle conversions between tuples.
if (auto tupleType = type.dyn_cast<ast::TupleType>()) {
if (tupleType.size() != exprType.size())
return emitErrorFn();
// Build a new tuple expression using each of the elements of the current
// tuple.
SmallVector<ast::Expr *> newExprs;
for (unsigned i = 0, e = exprType.size(); i < e; ++i) {
newExprs.push_back(ast::MemberAccessExpr::create(
ctx, expr->getLoc(), expr, llvm::to_string(i),
exprType.getElementTypes()[i]));
auto diagFn = [&](ast::Diagnostic &diag) {
diag.attachNote(llvm::formatv("when converting element #{0} of `{1}`",
i, exprType));
if (noteAttachFn)
noteAttachFn(diag);
};
if (failed(convertExpressionTo(newExprs.back(),
tupleType.getElementTypes()[i], diagFn)))
return failure();
}
expr = ast::TupleExpr::create(ctx, expr->getLoc(), newExprs,
tupleType.getElementNames());
return success();
}
// Handle conversion to a range.
auto convertToRange = [&](ArrayRef<ast::Type> allowedElementTypes,
ast::RangeType resultTy) -> LogicalResult {
// TODO: We currently only allow range conversion within a rewrite context.
if (parserContext != ParserContext::Rewrite) {
return emitErrorFn()->attachNote("Tuple to Range conversion is currently "
"only allowed within a rewrite context");
}
// All of the tuple elements must be allowed types.
for (ast::Type elementType : exprType.getElementTypes())
if (!llvm::is_contained(allowedElementTypes, elementType))
return emitErrorFn();
// Build a new tuple expression using each of the elements of the current
// tuple.
SmallVector<ast::Expr *> newExprs;
for (unsigned i = 0, e = exprType.size(); i < e; ++i) {
newExprs.push_back(ast::MemberAccessExpr::create(
ctx, expr->getLoc(), expr, llvm::to_string(i),
exprType.getElementTypes()[i]));
}
expr = ast::RangeExpr::create(ctx, expr->getLoc(), newExprs, resultTy);
return success();
};
if (type == valueRangeTy)
return convertToRange({valueTy, valueRangeTy}, valueRangeTy);
if (type == typeRangeTy)
return convertToRange({typeTy, typeRangeTy}, typeRangeTy);
return emitErrorFn();
}
//===----------------------------------------------------------------------===//
// Directives
LogicalResult Parser::parseDirective(SmallVectorImpl<ast::Decl *> &decls) {
StringRef directive = curToken.getSpelling();
if (directive == "#include")
return parseInclude(decls);
return emitError("unknown directive `" + directive + "`");
}
LogicalResult Parser::parseInclude(SmallVectorImpl<ast::Decl *> &decls) {
SMRange loc = curToken.getLoc();
consumeToken(Token::directive);
// Handle code completion of the include file path.
if (curToken.is(Token::code_complete_string))
return codeCompleteIncludeFilename(curToken.getStringValue());
// Parse the file being included.
if (!curToken.isString())
return emitError(loc,
"expected string file name after `include` directive");
SMRange fileLoc = curToken.getLoc();
std::string filenameStr = curToken.getStringValue();
StringRef filename = filenameStr;
consumeToken();
// Check the type of include. If ending with `.pdll`, this is another pdl file
// to be parsed along with the current module.
if (filename.endswith(".pdll")) {
if (failed(lexer.pushInclude(filename, fileLoc)))
return emitError(fileLoc,
"unable to open include file `" + filename + "`");
// If we added the include successfully, parse it into the current module.
// Make sure to update to the next token after we finish parsing the nested
// file.
curToken = lexer.lexToken();
LogicalResult result = parseModuleBody(decls);
curToken = lexer.lexToken();
return result;
}
// Otherwise, this must be a `.td` include.
if (filename.endswith(".td"))
return parseTdInclude(filename, fileLoc, decls);
return emitError(fileLoc,
"expected include filename to end with `.pdll` or `.td`");
}
LogicalResult Parser::parseTdInclude(StringRef filename, llvm::SMRange fileLoc,
SmallVectorImpl<ast::Decl *> &decls) {
llvm::SourceMgr &parserSrcMgr = lexer.getSourceMgr();
// Use the source manager to open the file, but don't yet add it.
std::string includedFile;
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> includeBuffer =
parserSrcMgr.OpenIncludeFile(filename.str(), includedFile);
if (!includeBuffer)
return emitError(fileLoc, "unable to open include file `" + filename + "`");
// Setup the source manager for parsing the tablegen file.
llvm::SourceMgr tdSrcMgr;
tdSrcMgr.AddNewSourceBuffer(std::move(*includeBuffer), SMLoc());
tdSrcMgr.setIncludeDirs(parserSrcMgr.getIncludeDirs());
// This class provides a context argument for the llvm::SourceMgr diagnostic
// handler.
struct DiagHandlerContext {
Parser &parser;
StringRef filename;
llvm::SMRange loc;
} handlerContext{*this, filename, fileLoc};
// Set the diagnostic handler for the tablegen source manager.
tdSrcMgr.setDiagHandler(
[](const llvm::SMDiagnostic &diag, void *rawHandlerContext) {
auto *ctx = reinterpret_cast<DiagHandlerContext *>(rawHandlerContext);
(void)ctx->parser.emitError(
ctx->loc,
llvm::formatv("error while processing include file `{0}`: {1}",
ctx->filename, diag.getMessage()));
},
&handlerContext);
// Parse the tablegen file.
llvm::RecordKeeper tdRecords;
if (llvm::TableGenParseFile(tdSrcMgr, tdRecords))
return failure();
// Process the parsed records.
processTdIncludeRecords(tdRecords, decls);
// After we are done processing, move all of the tablegen source buffers to
// the main parser source mgr. This allows for directly using source locations
// from the .td files without needing to remap them.
parserSrcMgr.takeSourceBuffersFrom(tdSrcMgr, fileLoc.End);
return success();
}
void Parser::processTdIncludeRecords(llvm::RecordKeeper &tdRecords,
SmallVectorImpl<ast::Decl *> &decls) {
// Return the length kind of the given value.
auto getLengthKind = [](const auto &value) {
if (value.isOptional())
return ods::VariableLengthKind::Optional;
return value.isVariadic() ? ods::VariableLengthKind::Variadic
: ods::VariableLengthKind::Single;
};
// Insert a type constraint into the ODS context.
ods::Context &odsContext = ctx.getODSContext();
auto addTypeConstraint = [&](const tblgen::NamedTypeConstraint &cst)
-> const ods::TypeConstraint & {
return odsContext.insertTypeConstraint(
cst.constraint.getUniqueDefName(),
processDoc(cst.constraint.getSummary()),
cst.constraint.getCPPClassName());
};
auto convertLocToRange = [&](llvm::SMLoc loc) -> llvm::SMRange {
return {loc, llvm::SMLoc::getFromPointer(loc.getPointer() + 1)};
};
// Process the parsed tablegen records to build ODS information.
/// Operations.
for (llvm::Record *def : tdRecords.getAllDerivedDefinitions("Op")) {
tblgen::Operator op(def);
// Check to see if this operation is known to support type inferrence.
bool supportsResultTypeInferrence =
op.getTrait("::mlir::InferTypeOpInterface::Trait");
auto [odsOp, inserted] = odsContext.insertOperation(
op.getOperationName(), processDoc(op.getSummary()),
processAndFormatDoc(op.getDescription()), op.getQualCppClassName(),
supportsResultTypeInferrence, op.getLoc().front());
// Ignore operations that have already been added.
if (!inserted)
continue;
for (const tblgen::NamedAttribute &attr : op.getAttributes()) {
odsOp->appendAttribute(attr.name, attr.attr.isOptional(),
odsContext.insertAttributeConstraint(
attr.attr.getUniqueDefName(),
processDoc(attr.attr.getSummary()),
attr.attr.getStorageType()));
}
for (const tblgen::NamedTypeConstraint &operand : op.getOperands()) {
odsOp->appendOperand(operand.name, getLengthKind(operand),
addTypeConstraint(operand));
}
for (const tblgen::NamedTypeConstraint &result : op.getResults()) {
odsOp->appendResult(result.name, getLengthKind(result),
addTypeConstraint(result));
}
}
auto shouldBeSkipped = [this](llvm::Record *def) {
return def->isAnonymous() || curDeclScope->lookup(def->getName()) ||
def->isSubClassOf("DeclareInterfaceMethods");
};
/// Attr constraints.
for (llvm::Record *def : tdRecords.getAllDerivedDefinitions("Attr")) {
if (shouldBeSkipped(def))
continue;
tblgen::Attribute constraint(def);
decls.push_back(createODSNativePDLLConstraintDecl<ast::AttrConstraintDecl>(
constraint, convertLocToRange(def->getLoc().front()), attrTy,
constraint.getStorageType()));
}
/// Type constraints.
for (llvm::Record *def : tdRecords.getAllDerivedDefinitions("Type")) {
if (shouldBeSkipped(def))
continue;
tblgen::TypeConstraint constraint(def);
decls.push_back(createODSNativePDLLConstraintDecl<ast::TypeConstraintDecl>(
constraint, convertLocToRange(def->getLoc().front()), typeTy,
constraint.getCPPClassName()));
}
/// OpInterfaces.
ast::Type opTy = ast::OperationType::get(ctx);
for (llvm::Record *def : tdRecords.getAllDerivedDefinitions("OpInterface")) {
if (shouldBeSkipped(def))
continue;
SMRange loc = convertLocToRange(def->getLoc().front());
std::string cppClassName =
llvm::formatv("{0}::{1}", def->getValueAsString("cppNamespace"),
def->getValueAsString("cppInterfaceName"))
.str();
std::string codeBlock =
llvm::formatv("return ::mlir::success(llvm::isa<{0}>(self));",
cppClassName)
.str();
std::string desc =
processAndFormatDoc(def->getValueAsString("description"));
decls.push_back(createODSNativePDLLConstraintDecl<ast::OpConstraintDecl>(
def->getName(), codeBlock, loc, opTy, cppClassName, desc));
}
}
template <typename ConstraintT>
ast::Decl *Parser::createODSNativePDLLConstraintDecl(
StringRef name, StringRef codeBlock, SMRange loc, ast::Type type,
StringRef nativeType, StringRef docString) {
// Build the single input parameter.
ast::DeclScope *argScope = pushDeclScope();
auto *paramVar = ast::VariableDecl::create(
ctx, ast::Name::create(ctx, "self", loc), type,
/*initExpr=*/nullptr, ast::ConstraintRef(ConstraintT::create(ctx, loc)));
argScope->add(paramVar);
popDeclScope();
// Build the native constraint.
auto *constraintDecl = ast::UserConstraintDecl::createNative(
ctx, ast::Name::create(ctx, name, loc), paramVar,
/*results=*/std::nullopt, codeBlock, ast::TupleType::get(ctx),
nativeType);
constraintDecl->setDocComment(ctx, docString);
curDeclScope->add(constraintDecl);
return constraintDecl;
}
template <typename ConstraintT>
ast::Decl *
Parser::createODSNativePDLLConstraintDecl(const tblgen::Constraint &constraint,
SMRange loc, ast::Type type,
StringRef nativeType) {
// Format the condition template.
tblgen::FmtContext fmtContext;
fmtContext.withSelf("self");
std::string codeBlock = tblgen::tgfmt(
"return ::mlir::success(" + constraint.getConditionTemplate() + ");",
&fmtContext);
// If documentation was enabled, build the doc string for the generated
// constraint. It would be nice to do this lazily, but TableGen information is
// destroyed after we finish parsing the file.
std::string docString;
if (enableDocumentation) {
StringRef desc = constraint.getDescription();
docString = processAndFormatDoc(
constraint.getSummary() +
(desc.empty() ? "" : ("\n\n" + constraint.getDescription())));
}
return createODSNativePDLLConstraintDecl<ConstraintT>(
constraint.getUniqueDefName(), codeBlock, loc, type, nativeType,
docString);
}
//===----------------------------------------------------------------------===//
// Decls
FailureOr<ast::Decl *> Parser::parseTopLevelDecl() {
FailureOr<ast::Decl *> decl;
switch (curToken.getKind()) {
case Token::kw_Constraint:
decl = parseUserConstraintDecl();
break;
case Token::kw_Pattern:
decl = parsePatternDecl();
break;
case Token::kw_Rewrite:
decl = parseUserRewriteDecl();
break;
default:
return emitError("expected top-level declaration, such as a `Pattern`");
}
if (failed(decl))
return failure();
// If the decl has a name, add it to the current scope.
if (const ast::Name *name = (*decl)->getName()) {
if (failed(checkDefineNamedDecl(*name)))
return failure();
curDeclScope->add(*decl);
}
return decl;
}
FailureOr<ast::NamedAttributeDecl *>
Parser::parseNamedAttributeDecl(std::optional<StringRef> parentOpName) {
// Check for name code completion.
if (curToken.is(Token::code_complete))
return codeCompleteAttributeName(parentOpName);
std::string attrNameStr;
if (curToken.isString())
attrNameStr = curToken.getStringValue();
else if (curToken.is(Token::identifier) || curToken.isKeyword())
attrNameStr = curToken.getSpelling().str();
else
return emitError("expected identifier or string attribute name");
const auto &name = ast::Name::create(ctx, attrNameStr, curToken.getLoc());
consumeToken();
// Check for a value of the attribute.
ast::Expr *attrValue = nullptr;
if (consumeIf(Token::equal)) {
FailureOr<ast::Expr *> attrExpr = parseExpr();
if (failed(attrExpr))
return failure();
attrValue = *attrExpr;
} else {
// If there isn't a concrete value, create an expression representing a
// UnitAttr.
attrValue = ast::AttributeExpr::create(ctx, name.getLoc(), "unit");
}
return ast::NamedAttributeDecl::create(ctx, name, attrValue);
}
FailureOr<ast::CompoundStmt *> Parser::parseLambdaBody(
function_ref<LogicalResult(ast::Stmt *&)> processStatementFn,
bool expectTerminalSemicolon) {
consumeToken(Token::equal_arrow);
// Parse the single statement of the lambda body.
SMLoc bodyStartLoc = curToken.getStartLoc();
pushDeclScope();
FailureOr<ast::Stmt *> singleStatement = parseStmt(expectTerminalSemicolon);
bool failedToParse =
failed(singleStatement) || failed(processStatementFn(*singleStatement));
popDeclScope();
if (failedToParse)
return failure();
SMRange bodyLoc(bodyStartLoc, curToken.getStartLoc());
return ast::CompoundStmt::create(ctx, bodyLoc, *singleStatement);
}
FailureOr<ast::VariableDecl *> Parser::parseArgumentDecl() {
// Ensure that the argument is named.
if (curToken.isNot(Token::identifier) && !curToken.isDependentKeyword())
return emitError("expected identifier argument name");
// Parse the argument similarly to a normal variable.
StringRef name = curToken.getSpelling();
SMRange nameLoc = curToken.getLoc();
consumeToken();
if (failed(
parseToken(Token::colon, "expected `:` before argument constraint")))
return failure();
FailureOr<ast::ConstraintRef> cst = parseArgOrResultConstraint();
if (failed(cst))
return failure();
return createArgOrResultVariableDecl(name, nameLoc, *cst);
}
FailureOr<ast::VariableDecl *> Parser::parseResultDecl(unsigned resultNum) {
// Check to see if this result is named.
if (curToken.is(Token::identifier) || curToken.isDependentKeyword()) {
// Check to see if this name actually refers to a Constraint.
if (!curDeclScope->lookup<ast::ConstraintDecl>(curToken.getSpelling())) {
// If it wasn't a constraint, parse the result similarly to a variable. If
// there is already an existing decl, we will emit an error when defining
// this variable later.
StringRef name = curToken.getSpelling();
SMRange nameLoc = curToken.getLoc();
consumeToken();
if (failed(parseToken(Token::colon,
"expected `:` before result constraint")))
return failure();
FailureOr<ast::ConstraintRef> cst = parseArgOrResultConstraint();
if (failed(cst))
return failure();
return createArgOrResultVariableDecl(name, nameLoc, *cst);
}
}
// If it isn't named, we parse the constraint directly and create an unnamed
// result variable.
FailureOr<ast::ConstraintRef> cst = parseArgOrResultConstraint();
if (failed(cst))
return failure();
return createArgOrResultVariableDecl("", cst->referenceLoc, *cst);
}
FailureOr<ast::UserConstraintDecl *>
Parser::parseUserConstraintDecl(bool isInline) {
// Constraints and rewrites have very similar formats, dispatch to a shared
// interface for parsing.
return parseUserConstraintOrRewriteDecl<ast::UserConstraintDecl>(
[&](auto &&...args) {
return this->parseUserPDLLConstraintDecl(args...);
},
ParserContext::Constraint, "constraint", isInline);
}
FailureOr<ast::UserConstraintDecl *> Parser::parseInlineUserConstraintDecl() {
FailureOr<ast::UserConstraintDecl *> decl =
parseUserConstraintDecl(/*isInline=*/true);
if (failed(decl) || failed(checkDefineNamedDecl((*decl)->getName())))
return failure();
curDeclScope->add(*decl);
return decl;
}
FailureOr<ast::UserConstraintDecl *> Parser::parseUserPDLLConstraintDecl(
const ast::Name &name, bool isInline,
ArrayRef<ast::VariableDecl *> arguments, ast::DeclScope *argumentScope,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType) {
// Push the argument scope back onto the list, so that the body can
// reference arguments.
pushDeclScope(argumentScope);
// Parse the body of the constraint. The body is either defined as a compound
// block, i.e. `{ ... }`, or a lambda body, i.e. `=> <expr>`.
ast::CompoundStmt *body;
if (curToken.is(Token::equal_arrow)) {
FailureOr<ast::CompoundStmt *> bodyResult = parseLambdaBody(
[&](ast::Stmt *&stmt) -> LogicalResult {
ast::Expr *stmtExpr = dyn_cast<ast::Expr>(stmt);
if (!stmtExpr) {
return emitError(stmt->getLoc(),
"expected `Constraint` lambda body to contain a "
"single expression");
}
stmt = ast::ReturnStmt::create(ctx, stmt->getLoc(), stmtExpr);
return success();
},
/*expectTerminalSemicolon=*/!isInline);
if (failed(bodyResult))
return failure();
body = *bodyResult;
} else {
FailureOr<ast::CompoundStmt *> bodyResult = parseCompoundStmt();
if (failed(bodyResult))
return failure();
body = *bodyResult;
// Verify the structure of the body.
auto bodyIt = body->begin(), bodyE = body->end();
for (; bodyIt != bodyE; ++bodyIt)
if (isa<ast::ReturnStmt>(*bodyIt))
break;
if (failed(validateUserConstraintOrRewriteReturn(
"Constraint", body, bodyIt, bodyE, results, resultType)))
return failure();
}
popDeclScope();
return createUserPDLLConstraintOrRewriteDecl<ast::UserConstraintDecl>(
name, arguments, results, resultType, body);
}
FailureOr<ast::UserRewriteDecl *> Parser::parseUserRewriteDecl(bool isInline) {
// Constraints and rewrites have very similar formats, dispatch to a shared
// interface for parsing.
return parseUserConstraintOrRewriteDecl<ast::UserRewriteDecl>(
[&](auto &&...args) { return this->parseUserPDLLRewriteDecl(args...); },
ParserContext::Rewrite, "rewrite", isInline);
}
FailureOr<ast::UserRewriteDecl *> Parser::parseInlineUserRewriteDecl() {
FailureOr<ast::UserRewriteDecl *> decl =
parseUserRewriteDecl(/*isInline=*/true);
if (failed(decl) || failed(checkDefineNamedDecl((*decl)->getName())))
return failure();
curDeclScope->add(*decl);
return decl;
}
FailureOr<ast::UserRewriteDecl *> Parser::parseUserPDLLRewriteDecl(
const ast::Name &name, bool isInline,
ArrayRef<ast::VariableDecl *> arguments, ast::DeclScope *argumentScope,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType) {
// Push the argument scope back onto the list, so that the body can
// reference arguments.
curDeclScope = argumentScope;
ast::CompoundStmt *body;
if (curToken.is(Token::equal_arrow)) {
FailureOr<ast::CompoundStmt *> bodyResult = parseLambdaBody(
[&](ast::Stmt *&statement) -> LogicalResult {
if (isa<ast::OpRewriteStmt>(statement))
return success();
ast::Expr *statementExpr = dyn_cast<ast::Expr>(statement);
if (!statementExpr) {
return emitError(
statement->getLoc(),
"expected `Rewrite` lambda body to contain a single expression "
"or an operation rewrite statement; such as `erase`, "
"`replace`, or `rewrite`");
}
statement =
ast::ReturnStmt::create(ctx, statement->getLoc(), statementExpr);
return success();
},
/*expectTerminalSemicolon=*/!isInline);
if (failed(bodyResult))
return failure();
body = *bodyResult;
} else {
FailureOr<ast::CompoundStmt *> bodyResult = parseCompoundStmt();
if (failed(bodyResult))
return failure();
body = *bodyResult;
}
popDeclScope();
// Verify the structure of the body.
auto bodyIt = body->begin(), bodyE = body->end();
for (; bodyIt != bodyE; ++bodyIt)
if (isa<ast::ReturnStmt>(*bodyIt))
break;
if (failed(validateUserConstraintOrRewriteReturn("Rewrite", body, bodyIt,
bodyE, results, resultType)))
return failure();
return createUserPDLLConstraintOrRewriteDecl<ast::UserRewriteDecl>(
name, arguments, results, resultType, body);
}
template <typename T, typename ParseUserPDLLDeclFnT>
FailureOr<T *> Parser::parseUserConstraintOrRewriteDecl(
ParseUserPDLLDeclFnT &&parseUserPDLLFn, ParserContext declContext,
StringRef anonymousNamePrefix, bool isInline) {
SMRange loc = curToken.getLoc();
consumeToken();
llvm::SaveAndRestore saveCtx(parserContext, declContext);
// Parse the name of the decl.
const ast::Name *name = nullptr;
if (curToken.isNot(Token::identifier)) {
// Only inline decls can be un-named. Inline decls are similar to "lambdas"
// in C++, so being unnamed is fine.
if (!isInline)
return emitError("expected identifier name");
// Create a unique anonymous name to use, as the name for this decl is not
// important.
std::string anonName =
llvm::formatv("<anonymous_{0}_{1}>", anonymousNamePrefix,
anonymousDeclNameCounter++)
.str();
name = &ast::Name::create(ctx, anonName, loc);
} else {
// If a name was provided, we can use it directly.
name = &ast::Name::create(ctx, curToken.getSpelling(), curToken.getLoc());
consumeToken(Token::identifier);
}
// Parse the functional signature of the decl.
SmallVector<ast::VariableDecl *> arguments, results;
ast::DeclScope *argumentScope;
ast::Type resultType;
if (failed(parseUserConstraintOrRewriteSignature(arguments, results,
argumentScope, resultType)))
return failure();
// Check to see which type of constraint this is. If the constraint contains a
// compound body, this is a PDLL decl.
if (curToken.isAny(Token::l_brace, Token::equal_arrow))
return parseUserPDLLFn(*name, isInline, arguments, argumentScope, results,
resultType);
// Otherwise, this is a native decl.
return parseUserNativeConstraintOrRewriteDecl<T>(*name, isInline, arguments,
results, resultType);
}
template <typename T>
FailureOr<T *> Parser::parseUserNativeConstraintOrRewriteDecl(
const ast::Name &name, bool isInline,
ArrayRef<ast::VariableDecl *> arguments,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType) {
// If followed by a string, the native code body has also been specified.
std::string codeStrStorage;
std::optional<StringRef> optCodeStr;
if (curToken.isString()) {
codeStrStorage = curToken.getStringValue();
optCodeStr = codeStrStorage;
consumeToken();
} else if (isInline) {
return emitError(name.getLoc(),
"external declarations must be declared in global scope");
} else if (curToken.is(Token::error)) {
return failure();
}
if (failed(parseToken(Token::semicolon,
"expected `;` after native declaration")))
return failure();
// TODO: PDL should be able to support constraint results in certain
// situations, we should revise this.
if (std::is_same<ast::UserConstraintDecl, T>::value && !results.empty()) {
return emitError(
"native Constraints currently do not support returning results");
}
return T::createNative(ctx, name, arguments, results, optCodeStr, resultType);
}
LogicalResult Parser::parseUserConstraintOrRewriteSignature(
SmallVectorImpl<ast::VariableDecl *> &arguments,
SmallVectorImpl<ast::VariableDecl *> &results,
ast::DeclScope *&argumentScope, ast::Type &resultType) {
// Parse the argument list of the decl.
if (failed(parseToken(Token::l_paren, "expected `(` to start argument list")))
return failure();
argumentScope = pushDeclScope();
if (curToken.isNot(Token::r_paren)) {
do {
FailureOr<ast::VariableDecl *> argument = parseArgumentDecl();
if (failed(argument))
return failure();
arguments.emplace_back(*argument);
} while (consumeIf(Token::comma));
}
popDeclScope();
if (failed(parseToken(Token::r_paren, "expected `)` to end argument list")))
return failure();
// Parse the results of the decl.
pushDeclScope();
if (consumeIf(Token::arrow)) {
auto parseResultFn = [&]() -> LogicalResult {
FailureOr<ast::VariableDecl *> result = parseResultDecl(results.size());
if (failed(result))
return failure();
results.emplace_back(*result);
return success();
};
// Check for a list of results.
if (consumeIf(Token::l_paren)) {
do {
if (failed(parseResultFn()))
return failure();
} while (consumeIf(Token::comma));
if (failed(parseToken(Token::r_paren, "expected `)` to end result list")))
return failure();
// Otherwise, there is only one result.
} else if (failed(parseResultFn())) {
return failure();
}
}
popDeclScope();
// Compute the result type of the decl.
resultType = createUserConstraintRewriteResultType(results);
// Verify that results are only named if there are more than one.
if (results.size() == 1 && !results.front()->getName().getName().empty()) {
return emitError(
results.front()->getLoc(),
"cannot create a single-element tuple with an element label");
}
return success();
}
LogicalResult Parser::validateUserConstraintOrRewriteReturn(
StringRef declType, ast::CompoundStmt *body,
ArrayRef<ast::Stmt *>::iterator bodyIt,
ArrayRef<ast::Stmt *>::iterator bodyE,
ArrayRef<ast::VariableDecl *> results, ast::Type &resultType) {
// Handle if a `return` was provided.
if (bodyIt != bodyE) {
// Emit an error if we have trailing statements after the return.
if (std::next(bodyIt) != bodyE) {
return emitError(
(*std::next(bodyIt))->getLoc(),
llvm::formatv("`return` terminated the `{0}` body, but found "
"trailing statements afterwards",
declType));
}
// Otherwise if a return wasn't provided, check that no results are
// expected.
} else if (!results.empty()) {
return emitError(
{body->getLoc().End, body->getLoc().End},
llvm::formatv("missing return in a `{0}` expected to return `{1}`",
declType, resultType));
}
return success();
}
FailureOr<ast::CompoundStmt *> Parser::parsePatternLambdaBody() {
return parseLambdaBody([&](ast::Stmt *&statement) -> LogicalResult {
if (isa<ast::OpRewriteStmt>(statement))
return success();
return emitError(
statement->getLoc(),
"expected Pattern lambda body to contain a single operation "
"rewrite statement, such as `erase`, `replace`, or `rewrite`");
});
}
FailureOr<ast::Decl *> Parser::parsePatternDecl() {
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_Pattern);
llvm::SaveAndRestore saveCtx(parserContext, ParserContext::PatternMatch);
// Check for an optional identifier for the pattern name.
const ast::Name *name = nullptr;
if (curToken.is(Token::identifier)) {
name = &ast::Name::create(ctx, curToken.getSpelling(), curToken.getLoc());
consumeToken(Token::identifier);
}
// Parse any pattern metadata.
ParsedPatternMetadata metadata;
if (consumeIf(Token::kw_with) && failed(parsePatternDeclMetadata(metadata)))
return failure();
// Parse the pattern body.
ast::CompoundStmt *body;
// Handle a lambda body.
if (curToken.is(Token::equal_arrow)) {
FailureOr<ast::CompoundStmt *> bodyResult = parsePatternLambdaBody();
if (failed(bodyResult))
return failure();
body = *bodyResult;
} else {
if (curToken.isNot(Token::l_brace))
return emitError("expected `{` or `=>` to start pattern body");
FailureOr<ast::CompoundStmt *> bodyResult = parseCompoundStmt();
if (failed(bodyResult))
return failure();
body = *bodyResult;
// Verify the body of the pattern.
auto bodyIt = body->begin(), bodyE = body->end();
for (; bodyIt != bodyE; ++bodyIt) {
if (isa<ast::ReturnStmt>(*bodyIt)) {
return emitError((*bodyIt)->getLoc(),
"`return` statements are only permitted within a "
"`Constraint` or `Rewrite` body");
}
// Break when we've found the rewrite statement.
if (isa<ast::OpRewriteStmt>(*bodyIt))
break;
}
if (bodyIt == bodyE) {
return emitError(loc,
"expected Pattern body to terminate with an operation "
"rewrite statement, such as `erase`");
}
if (std::next(bodyIt) != bodyE) {
return emitError((*std::next(bodyIt))->getLoc(),
"Pattern body was terminated by an operation "
"rewrite statement, but found trailing statements");
}
}
return createPatternDecl(loc, name, metadata, body);
}
LogicalResult
Parser::parsePatternDeclMetadata(ParsedPatternMetadata &metadata) {
std::optional<SMRange> benefitLoc;
std::optional<SMRange> hasBoundedRecursionLoc;
do {
// Handle metadata code completion.
if (curToken.is(Token::code_complete))
return codeCompletePatternMetadata();
if (curToken.isNot(Token::identifier))
return emitError("expected pattern metadata identifier");
StringRef metadataStr = curToken.getSpelling();
SMRange metadataLoc = curToken.getLoc();
consumeToken(Token::identifier);
// Parse the benefit metadata: benefit(<integer-value>)
if (metadataStr == "benefit") {
if (benefitLoc) {
return emitErrorAndNote(metadataLoc,
"pattern benefit has already been specified",
*benefitLoc, "see previous definition here");
}
if (failed(parseToken(Token::l_paren,
"expected `(` before pattern benefit")))
return failure();
uint16_t benefitValue = 0;
if (curToken.isNot(Token::integer))
return emitError("expected integral pattern benefit");
if (curToken.getSpelling().getAsInteger(/*Radix=*/10, benefitValue))
return emitError(
"expected pattern benefit to fit within a 16-bit integer");
consumeToken(Token::integer);
metadata.benefit = benefitValue;
benefitLoc = metadataLoc;
if (failed(
parseToken(Token::r_paren, "expected `)` after pattern benefit")))
return failure();
continue;
}
// Parse the bounded recursion metadata: recursion
if (metadataStr == "recursion") {
if (hasBoundedRecursionLoc) {
return emitErrorAndNote(
metadataLoc,
"pattern recursion metadata has already been specified",
*hasBoundedRecursionLoc, "see previous definition here");
}
metadata.hasBoundedRecursion = true;
hasBoundedRecursionLoc = metadataLoc;
continue;
}
return emitError(metadataLoc, "unknown pattern metadata");
} while (consumeIf(Token::comma));
return success();
}
FailureOr<ast::Expr *> Parser::parseTypeConstraintExpr() {
consumeToken(Token::less);
FailureOr<ast::Expr *> typeExpr = parseExpr();
if (failed(typeExpr) ||
failed(parseToken(Token::greater,
"expected `>` after variable type constraint")))
return failure();
return typeExpr;
}
LogicalResult Parser::checkDefineNamedDecl(const ast::Name &name) {
assert(curDeclScope && "defining decl outside of a decl scope");
if (ast::Decl *lastDecl = curDeclScope->lookup(name.getName())) {
return emitErrorAndNote(
name.getLoc(), "`" + name.getName() + "` has already been defined",
lastDecl->getName()->getLoc(), "see previous definition here");
}
return success();
}
FailureOr<ast::VariableDecl *>
Parser::defineVariableDecl(StringRef name, SMRange nameLoc, ast::Type type,
ast::Expr *initExpr,
ArrayRef<ast::ConstraintRef> constraints) {
assert(curDeclScope && "defining variable outside of decl scope");
const ast::Name &nameDecl = ast::Name::create(ctx, name, nameLoc);
// If the name of the variable indicates a special variable, we don't add it
// to the scope. This variable is local to the definition point.
if (name.empty() || name == "_") {
return ast::VariableDecl::create(ctx, nameDecl, type, initExpr,
constraints);
}
if (failed(checkDefineNamedDecl(nameDecl)))
return failure();
auto *varDecl =
ast::VariableDecl::create(ctx, nameDecl, type, initExpr, constraints);
curDeclScope->add(varDecl);
return varDecl;
}
FailureOr<ast::VariableDecl *>
Parser::defineVariableDecl(StringRef name, SMRange nameLoc, ast::Type type,
ArrayRef<ast::ConstraintRef> constraints) {
return defineVariableDecl(name, nameLoc, type, /*initExpr=*/nullptr,
constraints);
}
LogicalResult Parser::parseVariableDeclConstraintList(
SmallVectorImpl<ast::ConstraintRef> &constraints) {
std::optional<SMRange> typeConstraint;
auto parseSingleConstraint = [&] {
FailureOr<ast::ConstraintRef> constraint = parseConstraint(
typeConstraint, constraints, /*allowInlineTypeConstraints=*/true);
if (failed(constraint))
return failure();
constraints.push_back(*constraint);
return success();
};
// Check to see if this is a single constraint, or a list.
if (!consumeIf(Token::l_square))
return parseSingleConstraint();
do {
if (failed(parseSingleConstraint()))
return failure();
} while (consumeIf(Token::comma));
return parseToken(Token::r_square, "expected `]` after constraint list");
}
FailureOr<ast::ConstraintRef>
Parser::parseConstraint(std::optional<SMRange> &typeConstraint,
ArrayRef<ast::ConstraintRef> existingConstraints,
bool allowInlineTypeConstraints) {
auto parseTypeConstraint = [&](ast::Expr *&typeExpr) -> LogicalResult {
if (!allowInlineTypeConstraints) {
return emitError(
curToken.getLoc(),
"inline `Attr`, `Value`, and `ValueRange` type constraints are not "
"permitted on arguments or results");
}
if (typeConstraint)
return emitErrorAndNote(
curToken.getLoc(),
"the type of this variable has already been constrained",
*typeConstraint, "see previous constraint location here");
FailureOr<ast::Expr *> constraintExpr = parseTypeConstraintExpr();
if (failed(constraintExpr))
return failure();
typeExpr = *constraintExpr;
typeConstraint = typeExpr->getLoc();
return success();
};
SMRange loc = curToken.getLoc();
switch (curToken.getKind()) {
case Token::kw_Attr: {
consumeToken(Token::kw_Attr);
// Check for a type constraint.
ast::Expr *typeExpr = nullptr;
if (curToken.is(Token::less) && failed(parseTypeConstraint(typeExpr)))
return failure();
return ast::ConstraintRef(
ast::AttrConstraintDecl::create(ctx, loc, typeExpr), loc);
}
case Token::kw_Op: {
consumeToken(Token::kw_Op);
// Parse an optional operation name. If the name isn't provided, this refers
// to "any" operation.
FailureOr<ast::OpNameDecl *> opName =
parseWrappedOperationName(/*allowEmptyName=*/true);
if (failed(opName))
return failure();
return ast::ConstraintRef(ast::OpConstraintDecl::create(ctx, loc, *opName),
loc);
}
case Token::kw_Type:
consumeToken(Token::kw_Type);
return ast::ConstraintRef(ast::TypeConstraintDecl::create(ctx, loc), loc);
case Token::kw_TypeRange:
consumeToken(Token::kw_TypeRange);
return ast::ConstraintRef(ast::TypeRangeConstraintDecl::create(ctx, loc),
loc);
case Token::kw_Value: {
consumeToken(Token::kw_Value);
// Check for a type constraint.
ast::Expr *typeExpr = nullptr;
if (curToken.is(Token::less) && failed(parseTypeConstraint(typeExpr)))
return failure();
return ast::ConstraintRef(
ast::ValueConstraintDecl::create(ctx, loc, typeExpr), loc);
}
case Token::kw_ValueRange: {
consumeToken(Token::kw_ValueRange);
// Check for a type constraint.
ast::Expr *typeExpr = nullptr;
if (curToken.is(Token::less) && failed(parseTypeConstraint(typeExpr)))
return failure();
return ast::ConstraintRef(
ast::ValueRangeConstraintDecl::create(ctx, loc, typeExpr), loc);
}
case Token::kw_Constraint: {
// Handle an inline constraint.
FailureOr<ast::UserConstraintDecl *> decl = parseInlineUserConstraintDecl();
if (failed(decl))
return failure();
return ast::ConstraintRef(*decl, loc);
}
case Token::identifier: {
StringRef constraintName = curToken.getSpelling();
consumeToken(Token::identifier);
// Lookup the referenced constraint.
ast::Decl *cstDecl = curDeclScope->lookup<ast::Decl>(constraintName);
if (!cstDecl) {
return emitError(loc, "unknown reference to constraint `" +
constraintName + "`");
}
// Handle a reference to a proper constraint.
if (auto *cst = dyn_cast<ast::ConstraintDecl>(cstDecl))
return ast::ConstraintRef(cst, loc);
return emitErrorAndNote(
loc, "invalid reference to non-constraint", cstDecl->getLoc(),
"see the definition of `" + constraintName + "` here");
}
// Handle single entity constraint code completion.
case Token::code_complete: {
// Try to infer the current type for use by code completion.
ast::Type inferredType;
if (failed(validateVariableConstraints(existingConstraints, inferredType)))
return failure();
return codeCompleteConstraintName(inferredType, allowInlineTypeConstraints);
}
default:
break;
}
return emitError(loc, "expected identifier constraint");
}
FailureOr<ast::ConstraintRef> Parser::parseArgOrResultConstraint() {
std::optional<SMRange> typeConstraint;
return parseConstraint(typeConstraint, /*existingConstraints=*/std::nullopt,
/*allowInlineTypeConstraints=*/false);
}
//===----------------------------------------------------------------------===//
// Exprs
FailureOr<ast::Expr *> Parser::parseExpr() {
if (curToken.is(Token::underscore))
return parseUnderscoreExpr();
// Parse the LHS expression.
FailureOr<ast::Expr *> lhsExpr;
switch (curToken.getKind()) {
case Token::kw_attr:
lhsExpr = parseAttributeExpr();
break;
case Token::kw_Constraint:
lhsExpr = parseInlineConstraintLambdaExpr();
break;
case Token::identifier:
lhsExpr = parseIdentifierExpr();
break;
case Token::kw_op:
lhsExpr = parseOperationExpr();
break;
case Token::kw_Rewrite:
lhsExpr = parseInlineRewriteLambdaExpr();
break;
case Token::kw_type:
lhsExpr = parseTypeExpr();
break;
case Token::l_paren:
lhsExpr = parseTupleExpr();
break;
default:
return emitError("expected expression");
}
if (failed(lhsExpr))
return failure();
// Check for an operator expression.
while (true) {
switch (curToken.getKind()) {
case Token::dot:
lhsExpr = parseMemberAccessExpr(*lhsExpr);
break;
case Token::l_paren:
lhsExpr = parseCallExpr(*lhsExpr);
break;
default:
return lhsExpr;
}
if (failed(lhsExpr))
return failure();
}
}
FailureOr<ast::Expr *> Parser::parseAttributeExpr() {
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_attr);
// If we aren't followed by a `<`, the `attr` keyword is treated as a normal
// identifier.
if (!consumeIf(Token::less)) {
resetToken(loc);
return parseIdentifierExpr();
}
if (!curToken.isString())
return emitError("expected string literal containing MLIR attribute");
std::string attrExpr = curToken.getStringValue();
consumeToken();
loc.End = curToken.getEndLoc();
if (failed(
parseToken(Token::greater, "expected `>` after attribute literal")))
return failure();
return ast::AttributeExpr::create(ctx, loc, attrExpr);
}
FailureOr<ast::Expr *> Parser::parseCallExpr(ast::Expr *parentExpr) {
consumeToken(Token::l_paren);
// Parse the arguments of the call.
SmallVector<ast::Expr *> arguments;
if (curToken.isNot(Token::r_paren)) {
do {
// Handle code completion for the call arguments.
if (curToken.is(Token::code_complete)) {
codeCompleteCallSignature(parentExpr, arguments.size());
return failure();
}
FailureOr<ast::Expr *> argument = parseExpr();
if (failed(argument))
return failure();
arguments.push_back(*argument);
} while (consumeIf(Token::comma));
}
SMRange loc(parentExpr->getLoc().Start, curToken.getEndLoc());
if (failed(parseToken(Token::r_paren, "expected `)` after argument list")))
return failure();
return createCallExpr(loc, parentExpr, arguments);
}
FailureOr<ast::Expr *> Parser::parseDeclRefExpr(StringRef name, SMRange loc) {
ast::Decl *decl = curDeclScope->lookup(name);
if (!decl)
return emitError(loc, "undefined reference to `" + name + "`");
return createDeclRefExpr(loc, decl);
}
FailureOr<ast::Expr *> Parser::parseIdentifierExpr() {
StringRef name = curToken.getSpelling();
SMRange nameLoc = curToken.getLoc();
consumeToken();
// Check to see if this is a decl ref expression that defines a variable
// inline.
if (consumeIf(Token::colon)) {
SmallVector<ast::ConstraintRef> constraints;
if (failed(parseVariableDeclConstraintList(constraints)))
return failure();
ast::Type type;
if (failed(validateVariableConstraints(constraints, type)))
return failure();
return createInlineVariableExpr(type, name, nameLoc, constraints);
}
return parseDeclRefExpr(name, nameLoc);
}
FailureOr<ast::Expr *> Parser::parseInlineConstraintLambdaExpr() {
FailureOr<ast::UserConstraintDecl *> decl = parseInlineUserConstraintDecl();
if (failed(decl))
return failure();
return ast::DeclRefExpr::create(ctx, (*decl)->getLoc(), *decl,
ast::ConstraintType::get(ctx));
}
FailureOr<ast::Expr *> Parser::parseInlineRewriteLambdaExpr() {
FailureOr<ast::UserRewriteDecl *> decl = parseInlineUserRewriteDecl();
if (failed(decl))
return failure();
return ast::DeclRefExpr::create(ctx, (*decl)->getLoc(), *decl,
ast::RewriteType::get(ctx));
}
FailureOr<ast::Expr *> Parser::parseMemberAccessExpr(ast::Expr *parentExpr) {
SMRange dotLoc = curToken.getLoc();
consumeToken(Token::dot);
// Check for code completion of the member name.
if (curToken.is(Token::code_complete))
return codeCompleteMemberAccess(parentExpr);
// Parse the member name.
Token memberNameTok = curToken;
if (memberNameTok.isNot(Token::identifier, Token::integer) &&
!memberNameTok.isKeyword())
return emitError(dotLoc, "expected identifier or numeric member name");
StringRef memberName = memberNameTok.getSpelling();
SMRange loc(parentExpr->getLoc().Start, curToken.getEndLoc());
consumeToken();
return createMemberAccessExpr(parentExpr, memberName, loc);
}
FailureOr<ast::OpNameDecl *> Parser::parseOperationName(bool allowEmptyName) {
SMRange loc = curToken.getLoc();
// Check for code completion for the dialect name.
if (curToken.is(Token::code_complete))
return codeCompleteDialectName();
// Handle the case of an no operation name.
if (curToken.isNot(Token::identifier) && !curToken.isKeyword()) {
if (allowEmptyName)
return ast::OpNameDecl::create(ctx, SMRange());
return emitError("expected dialect namespace");
}
StringRef name = curToken.getSpelling();
consumeToken();
// Otherwise, this is a literal operation name.
if (failed(parseToken(Token::dot, "expected `.` after dialect namespace")))
return failure();
// Check for code completion for the operation name.
if (curToken.is(Token::code_complete))
return codeCompleteOperationName(name);
if (curToken.isNot(Token::identifier) && !curToken.isKeyword())
return emitError("expected operation name after dialect namespace");
name = StringRef(name.data(), name.size() + 1);
do {
name = StringRef(name.data(), name.size() + curToken.getSpelling().size());
loc.End = curToken.getEndLoc();
consumeToken();
} while (curToken.isAny(Token::identifier, Token::dot) ||
curToken.isKeyword());
return ast::OpNameDecl::create(ctx, ast::Name::create(ctx, name, loc));
}
FailureOr<ast::OpNameDecl *>
Parser::parseWrappedOperationName(bool allowEmptyName) {
if (!consumeIf(Token::less))
return ast::OpNameDecl::create(ctx, SMRange());
FailureOr<ast::OpNameDecl *> opNameDecl = parseOperationName(allowEmptyName);
if (failed(opNameDecl))
return failure();
if (failed(parseToken(Token::greater, "expected `>` after operation name")))
return failure();
return opNameDecl;
}
FailureOr<ast::Expr *>
Parser::parseOperationExpr(OpResultTypeContext inputResultTypeContext) {
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_op);
// If it isn't followed by a `<`, the `op` keyword is treated as a normal
// identifier.
if (curToken.isNot(Token::less)) {
resetToken(loc);
return parseIdentifierExpr();
}
// Parse the operation name. The name may be elided, in which case the
// operation refers to "any" operation(i.e. a difference between `MyOp` and
// `Operation*`). Operation names within a rewrite context must be named.
bool allowEmptyName = parserContext != ParserContext::Rewrite;
FailureOr<ast::OpNameDecl *> opNameDecl =
parseWrappedOperationName(allowEmptyName);
if (failed(opNameDecl))
return failure();
std::optional<StringRef> opName = (*opNameDecl)->getName();
// Functor used to create an implicit range variable, used for implicit "all"
// operand or results variables.
auto createImplicitRangeVar = [&](ast::ConstraintDecl *cst, ast::Type type) {
FailureOr<ast::VariableDecl *> rangeVar =
defineVariableDecl("_", loc, type, ast::ConstraintRef(cst, loc));
assert(succeeded(rangeVar) && "expected range variable to be valid");
return ast::DeclRefExpr::create(ctx, loc, *rangeVar, type);
};
// Check for the optional list of operands.
SmallVector<ast::Expr *> operands;
if (!consumeIf(Token::l_paren)) {
// If the operand list isn't specified and we are in a match context, define
// an inplace unconstrained operand range corresponding to all of the
// operands of the operation. This avoids treating zero operands the same
// way as "unconstrained operands".
if (parserContext != ParserContext::Rewrite) {
operands.push_back(createImplicitRangeVar(
ast::ValueRangeConstraintDecl::create(ctx, loc), valueRangeTy));
}
} else if (!consumeIf(Token::r_paren)) {
// If the operand list was specified and non-empty, parse the operands.
do {
// Check for operand signature code completion.
if (curToken.is(Token::code_complete)) {
codeCompleteOperationOperandsSignature(opName, operands.size());
return failure();
}
FailureOr<ast::Expr *> operand = parseExpr();
if (failed(operand))
return failure();
operands.push_back(*operand);
} while (consumeIf(Token::comma));
if (failed(parseToken(Token::r_paren,
"expected `)` after operation operand list")))
return failure();
}
// Check for the optional list of attributes.
SmallVector<ast::NamedAttributeDecl *> attributes;
if (consumeIf(Token::l_brace)) {
do {
FailureOr<ast::NamedAttributeDecl *> decl =
parseNamedAttributeDecl(opName);
if (failed(decl))
return failure();
attributes.emplace_back(*decl);
} while (consumeIf(Token::comma));
if (failed(parseToken(Token::r_brace,
"expected `}` after operation attribute list")))
return failure();
}
// Handle the result types of the operation.
SmallVector<ast::Expr *> resultTypes;
OpResultTypeContext resultTypeContext = inputResultTypeContext;
// Check for an explicit list of result types.
if (consumeIf(Token::arrow)) {
if (failed(parseToken(Token::l_paren,
"expected `(` before operation result type list")))
return failure();
// If result types are provided, initially assume that the operation does
// not rely on type inferrence. We don't assert that it isn't, because we
// may be inferring the value of some type/type range variables, but given
// that these variables may be defined in calls we can't always discern when
// this is the case.
resultTypeContext = OpResultTypeContext::Explicit;
// Handle the case of an empty result list.
if (!consumeIf(Token::r_paren)) {
do {
// Check for result signature code completion.
if (curToken.is(Token::code_complete)) {
codeCompleteOperationResultsSignature(opName, resultTypes.size());
return failure();
}
FailureOr<ast::Expr *> resultTypeExpr = parseExpr();
if (failed(resultTypeExpr))
return failure();
resultTypes.push_back(*resultTypeExpr);
} while (consumeIf(Token::comma));
if (failed(parseToken(Token::r_paren,
"expected `)` after operation result type list")))
return failure();
}
} else if (parserContext != ParserContext::Rewrite) {
// If the result list isn't specified and we are in a match context, define
// an inplace unconstrained result range corresponding to all of the results
// of the operation. This avoids treating zero results the same way as
// "unconstrained results".
resultTypes.push_back(createImplicitRangeVar(
ast::TypeRangeConstraintDecl::create(ctx, loc), typeRangeTy));
} else if (resultTypeContext == OpResultTypeContext::Explicit) {
// If the result list isn't specified and we are in a rewrite, try to infer
// them at runtime instead.
resultTypeContext = OpResultTypeContext::Interface;
}
return createOperationExpr(loc, *opNameDecl, resultTypeContext, operands,
attributes, resultTypes);
}
FailureOr<ast::Expr *> Parser::parseTupleExpr() {
SMRange loc = curToken.getLoc();
consumeToken(Token::l_paren);
DenseMap<StringRef, SMRange> usedNames;
SmallVector<StringRef> elementNames;
SmallVector<ast::Expr *> elements;
if (curToken.isNot(Token::r_paren)) {
do {
// Check for the optional element name assignment before the value.
StringRef elementName;
if (curToken.is(Token::identifier) || curToken.isDependentKeyword()) {
Token elementNameTok = curToken;
consumeToken();
// The element name is only present if followed by an `=`.
if (consumeIf(Token::equal)) {
elementName = elementNameTok.getSpelling();
// Check to see if this name is already used.
auto elementNameIt =
usedNames.try_emplace(elementName, elementNameTok.getLoc());
if (!elementNameIt.second) {
return emitErrorAndNote(
elementNameTok.getLoc(),
llvm::formatv("duplicate tuple element label `{0}`",
elementName),
elementNameIt.first->getSecond(),
"see previous label use here");
}
} else {
// Otherwise, we treat this as part of an expression so reset the
// lexer.
resetToken(elementNameTok.getLoc());
}
}
elementNames.push_back(elementName);
// Parse the tuple element value.
FailureOr<ast::Expr *> element = parseExpr();
if (failed(element))
return failure();
elements.push_back(*element);
} while (consumeIf(Token::comma));
}
loc.End = curToken.getEndLoc();
if (failed(
parseToken(Token::r_paren, "expected `)` after tuple element list")))
return failure();
return createTupleExpr(loc, elements, elementNames);
}
FailureOr<ast::Expr *> Parser::parseTypeExpr() {
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_type);
// If we aren't followed by a `<`, the `type` keyword is treated as a normal
// identifier.
if (!consumeIf(Token::less)) {
resetToken(loc);
return parseIdentifierExpr();
}
if (!curToken.isString())
return emitError("expected string literal containing MLIR type");
std::string attrExpr = curToken.getStringValue();
consumeToken();
loc.End = curToken.getEndLoc();
if (failed(parseToken(Token::greater, "expected `>` after type literal")))
return failure();
return ast::TypeExpr::create(ctx, loc, attrExpr);
}
FailureOr<ast::Expr *> Parser::parseUnderscoreExpr() {
StringRef name = curToken.getSpelling();
SMRange nameLoc = curToken.getLoc();
consumeToken(Token::underscore);
// Underscore expressions require a constraint list.
if (failed(parseToken(Token::colon, "expected `:` after `_` variable")))
return failure();
// Parse the constraints for the expression.
SmallVector<ast::ConstraintRef> constraints;
if (failed(parseVariableDeclConstraintList(constraints)))
return failure();
ast::Type type;
if (failed(validateVariableConstraints(constraints, type)))
return failure();
return createInlineVariableExpr(type, name, nameLoc, constraints);
}
//===----------------------------------------------------------------------===//
// Stmts
FailureOr<ast::Stmt *> Parser::parseStmt(bool expectTerminalSemicolon) {
FailureOr<ast::Stmt *> stmt;
switch (curToken.getKind()) {
case Token::kw_erase:
stmt = parseEraseStmt();
break;
case Token::kw_let:
stmt = parseLetStmt();
break;
case Token::kw_replace:
stmt = parseReplaceStmt();
break;
case Token::kw_return:
stmt = parseReturnStmt();
break;
case Token::kw_rewrite:
stmt = parseRewriteStmt();
break;
default:
stmt = parseExpr();
break;
}
if (failed(stmt) ||
(expectTerminalSemicolon &&
failed(parseToken(Token::semicolon, "expected `;` after statement"))))
return failure();
return stmt;
}
FailureOr<ast::CompoundStmt *> Parser::parseCompoundStmt() {
SMLoc startLoc = curToken.getStartLoc();
consumeToken(Token::l_brace);
// Push a new block scope and parse any nested statements.
pushDeclScope();
SmallVector<ast::Stmt *> statements;
while (curToken.isNot(Token::r_brace)) {
FailureOr<ast::Stmt *> statement = parseStmt();
if (failed(statement))
return popDeclScope(), failure();
statements.push_back(*statement);
}
popDeclScope();
// Consume the end brace.
SMRange location(startLoc, curToken.getEndLoc());
consumeToken(Token::r_brace);
return ast::CompoundStmt::create(ctx, location, statements);
}
FailureOr<ast::EraseStmt *> Parser::parseEraseStmt() {
if (parserContext == ParserContext::Constraint)
return emitError("`erase` cannot be used within a Constraint");
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_erase);
// Parse the root operation expression.
FailureOr<ast::Expr *> rootOp = parseExpr();
if (failed(rootOp))
return failure();
return createEraseStmt(loc, *rootOp);
}
FailureOr<ast::LetStmt *> Parser::parseLetStmt() {
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_let);
// Parse the name of the new variable.
SMRange varLoc = curToken.getLoc();
if (curToken.isNot(Token::identifier) && !curToken.isDependentKeyword()) {
// `_` is a reserved variable name.
if (curToken.is(Token::underscore)) {
return emitError(varLoc,
"`_` may only be used to define \"inline\" variables");
}
return emitError(varLoc,
"expected identifier after `let` to name a new variable");
}
StringRef varName = curToken.getSpelling();
consumeToken();
// Parse the optional set of constraints.
SmallVector<ast::ConstraintRef> constraints;
if (consumeIf(Token::colon) &&
failed(parseVariableDeclConstraintList(constraints)))
return failure();
// Parse the optional initializer expression.
ast::Expr *initializer = nullptr;
if (consumeIf(Token::equal)) {
FailureOr<ast::Expr *> initOrFailure = parseExpr();
if (failed(initOrFailure))
return failure();
initializer = *initOrFailure;
// Check that the constraints are compatible with having an initializer,
// e.g. type constraints cannot be used with initializers.
for (ast::ConstraintRef constraint : constraints) {
LogicalResult result =
TypeSwitch<const ast::Node *, LogicalResult>(constraint.constraint)
.Case<ast::AttrConstraintDecl, ast::ValueConstraintDecl,
ast::ValueRangeConstraintDecl>([&](const auto *cst) {
if (auto *typeConstraintExpr = cst->getTypeExpr()) {
return this->emitError(
constraint.referenceLoc,
"type constraints are not permitted on variables with "
"initializers");
}
return success();
})
.Default(success());
if (failed(result))
return failure();
}
}
FailureOr<ast::VariableDecl *> varDecl =
createVariableDecl(varName, varLoc, initializer, constraints);
if (failed(varDecl))
return failure();
return ast::LetStmt::create(ctx, loc, *varDecl);
}
FailureOr<ast::ReplaceStmt *> Parser::parseReplaceStmt() {
if (parserContext == ParserContext::Constraint)
return emitError("`replace` cannot be used within a Constraint");
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_replace);
// Parse the root operation expression.
FailureOr<ast::Expr *> rootOp = parseExpr();
if (failed(rootOp))
return failure();
if (failed(
parseToken(Token::kw_with, "expected `with` after root operation")))
return failure();
// The replacement portion of this statement is within a rewrite context.
llvm::SaveAndRestore saveCtx(parserContext, ParserContext::Rewrite);
// Parse the replacement values.
SmallVector<ast::Expr *> replValues;
if (consumeIf(Token::l_paren)) {
if (consumeIf(Token::r_paren)) {
return emitError(
loc, "expected at least one replacement value, consider using "
"`erase` if no replacement values are desired");
}
do {
FailureOr<ast::Expr *> replExpr = parseExpr();
if (failed(replExpr))
return failure();
replValues.emplace_back(*replExpr);
} while (consumeIf(Token::comma));
if (failed(parseToken(Token::r_paren,
"expected `)` after replacement values")))
return failure();
} else {
// Handle replacement with an operation uniquely, as the replacement
// operation supports type inferrence from the root operation.
FailureOr<ast::Expr *> replExpr;
if (curToken.is(Token::kw_op))
replExpr = parseOperationExpr(OpResultTypeContext::Replacement);
else
replExpr = parseExpr();
if (failed(replExpr))
return failure();
replValues.emplace_back(*replExpr);
}
return createReplaceStmt(loc, *rootOp, replValues);
}
FailureOr<ast::ReturnStmt *> Parser::parseReturnStmt() {
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_return);
// Parse the result value.
FailureOr<ast::Expr *> resultExpr = parseExpr();
if (failed(resultExpr))
return failure();
return ast::ReturnStmt::create(ctx, loc, *resultExpr);
}
FailureOr<ast::RewriteStmt *> Parser::parseRewriteStmt() {
if (parserContext == ParserContext::Constraint)
return emitError("`rewrite` cannot be used within a Constraint");
SMRange loc = curToken.getLoc();
consumeToken(Token::kw_rewrite);
// Parse the root operation.
FailureOr<ast::Expr *> rootOp = parseExpr();
if (failed(rootOp))
return failure();
if (failed(parseToken(Token::kw_with, "expected `with` before rewrite body")))
return failure();
if (curToken.isNot(Token::l_brace))
return emitError("expected `{` to start rewrite body");
// The rewrite body of this statement is within a rewrite context.
llvm::SaveAndRestore saveCtx(parserContext, ParserContext::Rewrite);
FailureOr<ast::CompoundStmt *> rewriteBody = parseCompoundStmt();
if (failed(rewriteBody))
return failure();
// Verify the rewrite body.
for (const ast::Stmt *stmt : (*rewriteBody)->getChildren()) {
if (isa<ast::ReturnStmt>(stmt)) {
return emitError(stmt->getLoc(),
"`return` statements are only permitted within a "
"`Constraint` or `Rewrite` body");
}
}
return createRewriteStmt(loc, *rootOp, *rewriteBody);
}
//===----------------------------------------------------------------------===//
// Creation+Analysis
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Decls
ast::CallableDecl *Parser::tryExtractCallableDecl(ast::Node *node) {
// Unwrap reference expressions.
if (auto *init = dyn_cast<ast::DeclRefExpr>(node))
node = init->getDecl();
return dyn_cast<ast::CallableDecl>(node);
}
FailureOr<ast::PatternDecl *>
Parser::createPatternDecl(SMRange loc, const ast::Name *name,
const ParsedPatternMetadata &metadata,
ast::CompoundStmt *body) {
return ast::PatternDecl::create(ctx, loc, name, metadata.benefit,
metadata.hasBoundedRecursion, body);
}
ast::Type Parser::createUserConstraintRewriteResultType(
ArrayRef<ast::VariableDecl *> results) {
// Single result decls use the type of the single result.
if (results.size() == 1)
return results[0]->getType();
// Multiple results use a tuple type, with the types and names grabbed from
// the result variable decls.
auto resultTypes = llvm::map_range(
results, [&](const auto *result) { return result->getType(); });
auto resultNames = llvm::map_range(
results, [&](const auto *result) { return result->getName().getName(); });
return ast::TupleType::get(ctx, llvm::to_vector(resultTypes),
llvm::to_vector(resultNames));
}
template <typename T>
FailureOr<T *> Parser::createUserPDLLConstraintOrRewriteDecl(
const ast::Name &name, ArrayRef<ast::VariableDecl *> arguments,
ArrayRef<ast::VariableDecl *> results, ast::Type resultType,
ast::CompoundStmt *body) {
if (!body->getChildren().empty()) {
if (auto *retStmt = dyn_cast<ast::ReturnStmt>(body->getChildren().back())) {
ast::Expr *resultExpr = retStmt->getResultExpr();
// Process the result of the decl. If no explicit signature results
// were provided, check for return type inference. Otherwise, check that
// the return expression can be converted to the expected type.
if (results.empty())
resultType = resultExpr->getType();
else if (failed(convertExpressionTo(resultExpr, resultType)))
return failure();
else
retStmt->setResultExpr(resultExpr);
}
}
return T::createPDLL(ctx, name, arguments, results, body, resultType);
}
FailureOr<ast::VariableDecl *>
Parser::createVariableDecl(StringRef name, SMRange loc, ast::Expr *initializer,
ArrayRef<ast::ConstraintRef> constraints) {
// The type of the variable, which is expected to be inferred by either a
// constraint or an initializer expression.
ast::Type type;
if (failed(validateVariableConstraints(constraints, type)))
return failure();
if (initializer) {
// Update the variable type based on the initializer, or try to convert the
// initializer to the existing type.
if (!type)
type = initializer->getType();
else if (ast::Type mergedType = type.refineWith(initializer->getType()))
type = mergedType;
else if (failed(convertExpressionTo(initializer, type)))
return failure();
// Otherwise, if there is no initializer check that the type has already
// been resolved from the constraint list.
} else if (!type) {
return emitErrorAndNote(
loc, "unable to infer type for variable `" + name + "`", loc,
"the type of a variable must be inferable from the constraint "
"list or the initializer");
}
// Constraint types cannot be used when defining variables.
if (type.isa<ast::ConstraintType, ast::RewriteType>()) {
return emitError(
loc, llvm::formatv("unable to define variable of `{0}` type", type));
}
// Try to define a variable with the given name.
FailureOr<ast::VariableDecl *> varDecl =
defineVariableDecl(name, loc, type, initializer, constraints);
if (failed(varDecl))
return failure();
return *varDecl;
}
FailureOr<ast::VariableDecl *>
Parser::createArgOrResultVariableDecl(StringRef name, SMRange loc,
const ast::ConstraintRef &constraint) {
ast::Type argType;
if (failed(validateVariableConstraint(constraint, argType)))
return failure();
return defineVariableDecl(name, loc, argType, constraint);
}
LogicalResult
Parser::validateVariableConstraints(ArrayRef<ast::ConstraintRef> constraints,
ast::Type &inferredType) {
for (const ast::ConstraintRef &ref : constraints)
if (failed(validateVariableConstraint(ref, inferredType)))
return failure();
return success();
}
LogicalResult Parser::validateVariableConstraint(const ast::ConstraintRef &ref,
ast::Type &inferredType) {
ast::Type constraintType;
if (const auto *cst = dyn_cast<ast::AttrConstraintDecl>(ref.constraint)) {
if (const ast::Expr *typeExpr = cst->getTypeExpr()) {
if (failed(validateTypeConstraintExpr(typeExpr)))
return failure();
}
constraintType = ast::AttributeType::get(ctx);
} else if (const auto *cst =
dyn_cast<ast::OpConstraintDecl>(ref.constraint)) {
constraintType = ast::OperationType::get(
ctx, cst->getName(), lookupODSOperation(cst->getName()));
} else if (isa<ast::TypeConstraintDecl>(ref.constraint)) {
constraintType = typeTy;
} else if (isa<ast::TypeRangeConstraintDecl>(ref.constraint)) {
constraintType = typeRangeTy;
} else if (const auto *cst =
dyn_cast<ast::ValueConstraintDecl>(ref.constraint)) {
if (const ast::Expr *typeExpr = cst->getTypeExpr()) {
if (failed(validateTypeConstraintExpr(typeExpr)))
return failure();
}
constraintType = valueTy;
} else if (const auto *cst =
dyn_cast<ast::ValueRangeConstraintDecl>(ref.constraint)) {
if (const ast::Expr *typeExpr = cst->getTypeExpr()) {
if (failed(validateTypeRangeConstraintExpr(typeExpr)))
return failure();
}
constraintType = valueRangeTy;
} else if (const auto *cst =
dyn_cast<ast::UserConstraintDecl>(ref.constraint)) {
ArrayRef<ast::VariableDecl *> inputs = cst->getInputs();
if (inputs.size() != 1) {
return emitErrorAndNote(ref.referenceLoc,
"`Constraint`s applied via a variable constraint "
"list must take a single input, but got " +
Twine(inputs.size()),
cst->getLoc(),
"see definition of constraint here");
}
constraintType = inputs.front()->getType();
} else {
llvm_unreachable("unknown constraint type");
}
// Check that the constraint type is compatible with the current inferred
// type.
if (!inferredType) {
inferredType = constraintType;
} else if (ast::Type mergedTy = inferredType.refineWith(constraintType)) {
inferredType = mergedTy;
} else {
return emitError(ref.referenceLoc,
llvm::formatv("constraint type `{0}` is incompatible "
"with the previously inferred type `{1}`",
constraintType, inferredType));
}
return success();
}
LogicalResult Parser::validateTypeConstraintExpr(const ast::Expr *typeExpr) {
ast::Type typeExprType = typeExpr->getType();
if (typeExprType != typeTy) {
return emitError(typeExpr->getLoc(),
"expected expression of `Type` in type constraint");
}
return success();
}
LogicalResult
Parser::validateTypeRangeConstraintExpr(const ast::Expr *typeExpr) {
ast::Type typeExprType = typeExpr->getType();
if (typeExprType != typeRangeTy) {
return emitError(typeExpr->getLoc(),
"expected expression of `TypeRange` in type constraint");
}
return success();
}
//===----------------------------------------------------------------------===//
// Exprs
FailureOr<ast::CallExpr *>
Parser::createCallExpr(SMRange loc, ast::Expr *parentExpr,
MutableArrayRef<ast::Expr *> arguments) {
ast::Type parentType = parentExpr->getType();
ast::CallableDecl *callableDecl = tryExtractCallableDecl(parentExpr);
if (!callableDecl) {
return emitError(loc,
llvm::formatv("expected a reference to a callable "
"`Constraint` or `Rewrite`, but got: `{0}`",
parentType));
}
if (parserContext == ParserContext::Rewrite) {
if (isa<ast::UserConstraintDecl>(callableDecl))
return emitError(
loc, "unable to invoke `Constraint` within a rewrite section");
} else if (isa<ast::UserRewriteDecl>(callableDecl)) {
return emitError(loc, "unable to invoke `Rewrite` within a match section");
}
// Verify the arguments of the call.
/// Handle size mismatch.
ArrayRef<ast::VariableDecl *> callArgs = callableDecl->getInputs();
if (callArgs.size() != arguments.size()) {
return emitErrorAndNote(
loc,
llvm::formatv("invalid number of arguments for {0} call; expected "
"{1}, but got {2}",
callableDecl->getCallableType(), callArgs.size(),
arguments.size()),
callableDecl->getLoc(),
llvm::formatv("see the definition of {0} here",
callableDecl->getName()->getName()));
}
/// Handle argument type mismatch.
auto attachDiagFn = [&](ast::Diagnostic &diag) {
diag.attachNote(llvm::formatv("see the definition of `{0}` here",
callableDecl->getName()->getName()),
callableDecl->getLoc());
};
for (auto it : llvm::zip(callArgs, arguments)) {
if (failed(convertExpressionTo(std::get<1>(it), std::get<0>(it)->getType(),
attachDiagFn)))
return failure();
}
return ast::CallExpr::create(ctx, loc, parentExpr, arguments,
callableDecl->getResultType());
}
FailureOr<ast::DeclRefExpr *> Parser::createDeclRefExpr(SMRange loc,
ast::Decl *decl) {
// Check the type of decl being referenced.
ast::Type declType;
if (isa<ast::ConstraintDecl>(decl))
declType = ast::ConstraintType::get(ctx);
else if (isa<ast::UserRewriteDecl>(decl))
declType = ast::RewriteType::get(ctx);
else if (auto *varDecl = dyn_cast<ast::VariableDecl>(decl))
declType = varDecl->getType();
else
return emitError(loc, "invalid reference to `" +
decl->getName()->getName() + "`");
return ast::DeclRefExpr::create(ctx, loc, decl, declType);
}
FailureOr<ast::DeclRefExpr *>
Parser::createInlineVariableExpr(ast::Type type, StringRef name, SMRange loc,
ArrayRef<ast::ConstraintRef> constraints) {
FailureOr<ast::VariableDecl *> decl =
defineVariableDecl(name, loc, type, constraints);
if (failed(decl))
return failure();
return ast::DeclRefExpr::create(ctx, loc, *decl, type);
}
FailureOr<ast::MemberAccessExpr *>
Parser::createMemberAccessExpr(ast::Expr *parentExpr, StringRef name,
SMRange loc) {
// Validate the member name for the given parent expression.
FailureOr<ast::Type> memberType = validateMemberAccess(parentExpr, name, loc);
if (failed(memberType))
return failure();
return ast::MemberAccessExpr::create(ctx, loc, parentExpr, name, *memberType);
}
FailureOr<ast::Type> Parser::validateMemberAccess(ast::Expr *parentExpr,
StringRef name, SMRange loc) {
ast::Type parentType = parentExpr->getType();
if (ast::OperationType opType = parentType.dyn_cast<ast::OperationType>()) {
if (name == ast::AllResultsMemberAccessExpr::getMemberName())
return valueRangeTy;
// Verify member access based on the operation type.
if (const ods::Operation *odsOp = opType.getODSOperation()) {
auto results = odsOp->getResults();
// Handle indexed results.
unsigned index = 0;
if (llvm::isDigit(name[0]) && !name.getAsInteger(/*Radix=*/10, index) &&
index < results.size()) {
return results[index].isVariadic() ? valueRangeTy : valueTy;
}
// Handle named results.
const auto *it = llvm::find_if(results, [&](const auto &result) {
return result.getName() == name;
});
if (it != results.end())
return it->isVariadic() ? valueRangeTy : valueTy;
} else if (llvm::isDigit(name[0])) {
// Allow unchecked numeric indexing of the results of unregistered
// operations. It returns a single value.
return valueTy;
}
} else if (auto tupleType = parentType.dyn_cast<ast::TupleType>()) {
// Handle indexed results.
unsigned index = 0;
if (llvm::isDigit(name[0]) && !name.getAsInteger(/*Radix=*/10, index) &&
index < tupleType.size()) {
return tupleType.getElementTypes()[index];
}
// Handle named results.
auto elementNames = tupleType.getElementNames();
const auto *it = llvm::find(elementNames, name);
if (it != elementNames.end())
return tupleType.getElementTypes()[it - elementNames.begin()];
}
return emitError(
loc,
llvm::formatv("invalid member access `{0}` on expression of type `{1}`",
name, parentType));
}
FailureOr<ast::OperationExpr *> Parser::createOperationExpr(
SMRange loc, const ast::OpNameDecl *name,
OpResultTypeContext resultTypeContext,
SmallVectorImpl<ast::Expr *> &operands,
MutableArrayRef<ast::NamedAttributeDecl *> attributes,
SmallVectorImpl<ast::Expr *> &results) {
std::optional<StringRef> opNameRef = name->getName();
const ods::Operation *odsOp = lookupODSOperation(opNameRef);
// Verify the inputs operands.
if (failed(validateOperationOperands(loc, opNameRef, odsOp, operands)))
return failure();
// Verify the attribute list.
for (ast::NamedAttributeDecl *attr : attributes) {
// Check for an attribute type, or a type awaiting resolution.
ast::Type attrType = attr->getValue()->getType();
if (!attrType.isa<ast::AttributeType>()) {
return emitError(
attr->getValue()->getLoc(),
llvm::formatv("expected `Attr` expression, but got `{0}`", attrType));
}
}
assert(
(resultTypeContext == OpResultTypeContext::Explicit || results.empty()) &&
"unexpected inferrence when results were explicitly specified");
// If we aren't relying on type inferrence, or explicit results were provided,
// validate them.
if (resultTypeContext == OpResultTypeContext::Explicit) {
if (failed(validateOperationResults(loc, opNameRef, odsOp, results)))
return failure();
// Validate the use of interface based type inferrence for this operation.
} else if (resultTypeContext == OpResultTypeContext::Interface) {
assert(opNameRef &&
"expected valid operation name when inferring operation results");
checkOperationResultTypeInferrence(loc, *opNameRef, odsOp);
}
return ast::OperationExpr::create(ctx, loc, odsOp, name, operands, results,
attributes);
}
LogicalResult
Parser::validateOperationOperands(SMRange loc, std::optional<StringRef> name,
const ods::Operation *odsOp,
SmallVectorImpl<ast::Expr *> &operands) {
return validateOperationOperandsOrResults(
"operand", loc, odsOp ? odsOp->getLoc() : std::optional<SMRange>(), name,
operands, odsOp ? odsOp->getOperands() : std::nullopt, valueTy,
valueRangeTy);
}
LogicalResult
Parser::validateOperationResults(SMRange loc, std::optional<StringRef> name,
const ods::Operation *odsOp,
SmallVectorImpl<ast::Expr *> &results) {
return validateOperationOperandsOrResults(
"result", loc, odsOp ? odsOp->getLoc() : std::optional<SMRange>(), name,
results, odsOp ? odsOp->getResults() : std::nullopt, typeTy, typeRangeTy);
}
void Parser::checkOperationResultTypeInferrence(SMRange loc, StringRef opName,
const ods::Operation *odsOp) {
// If the operation might not have inferrence support, emit a warning to the
// user. We don't emit an error because the interface might be added to the
// operation at runtime. It's rare, but it could still happen. We emit a
// warning here instead.
// Handle inferrence warnings for unknown operations.
if (!odsOp) {
ctx.getDiagEngine().emitWarning(
loc, llvm::formatv(
"operation result types are marked to be inferred, but "
"`{0}` is unknown. Ensure that `{0}` supports zero "
"results or implements `InferTypeOpInterface`. Include "
"the ODS definition of this operation to remove this warning.",
opName));
return;
}
// Handle inferrence warnings for known operations that expected at least one
// result, but don't have inference support. An elided results list can mean
// "zero-results", and we don't want to warn when that is the expected
// behavior.
bool requiresInferrence =
llvm::any_of(odsOp->getResults(), [](const ods::OperandOrResult &result) {
return !result.isVariableLength();
});
if (requiresInferrence && !odsOp->hasResultTypeInferrence()) {
ast::InFlightDiagnostic diag = ctx.getDiagEngine().emitWarning(
loc,
llvm::formatv("operation result types are marked to be inferred, but "
"`{0}` does not provide an implementation of "
"`InferTypeOpInterface`. Ensure that `{0}` attaches "
"`InferTypeOpInterface` at runtime, or add support to "
"the ODS definition to remove this warning.",
opName));
diag->attachNote(llvm::formatv("see the definition of `{0}` here", opName),
odsOp->getLoc());
return;
}
}
LogicalResult Parser::validateOperationOperandsOrResults(
StringRef groupName, SMRange loc, std::optional<SMRange> odsOpLoc,
std::optional<StringRef> name, SmallVectorImpl<ast::Expr *> &values,
ArrayRef<ods::OperandOrResult> odsValues, ast::Type singleTy,
ast::RangeType rangeTy) {
// All operation types accept a single range parameter.
if (values.size() == 1) {
if (failed(convertExpressionTo(values[0], rangeTy)))
return failure();
return success();
}
/// If the operation has ODS information, we can more accurately verify the
/// values.
if (odsOpLoc) {
auto emitSizeMismatchError = [&] {
return emitErrorAndNote(
loc,
llvm::formatv("invalid number of {0} groups for `{1}`; expected "
"{2}, but got {3}",
groupName, *name, odsValues.size(), values.size()),
*odsOpLoc, llvm::formatv("see the definition of `{0}` here", *name));
};
// Handle the case where no values were provided.
if (values.empty()) {
// If we don't expect any on the ODS side, we are done.
if (odsValues.empty())
return success();
// If we do, check if we actually need to provide values (i.e. if any of
// the values are actually required).
unsigned numVariadic = 0;
for (const auto &odsValue : odsValues) {
if (!odsValue.isVariableLength())
return emitSizeMismatchError();
++numVariadic;
}
// If we are in a non-rewrite context, we don't need to do anything more.
// Zero-values is a valid constraint on the operation.
if (parserContext != ParserContext::Rewrite)
return success();
// Otherwise, when in a rewrite we may need to provide values to match the
// ODS signature of the operation to create.
// If we only have one variadic value, just use an empty list.
if (numVariadic == 1)
return success();
// Otherwise, create dummy values for each of the entries so that we
// adhere to the ODS signature.
for (unsigned i = 0, e = odsValues.size(); i < e; ++i) {
values.push_back(ast::RangeExpr::create(
ctx, loc, /*elements=*/std::nullopt, rangeTy));
}
return success();
}
// Verify that the number of values provided matches the number of value
// groups ODS expects.
if (odsValues.size() != values.size())
return emitSizeMismatchError();
auto diagFn = [&](ast::Diagnostic &diag) {
diag.attachNote(llvm::formatv("see the definition of `{0}` here", *name),
*odsOpLoc);
};
for (unsigned i = 0, e = values.size(); i < e; ++i) {
ast::Type expectedType = odsValues[i].isVariadic() ? rangeTy : singleTy;
if (failed(convertExpressionTo(values[i], expectedType, diagFn)))
return failure();
}
return success();
}
// Otherwise, accept the value groups as they have been defined and just
// ensure they are one of the expected types.
for (ast::Expr *&valueExpr : values) {
ast::Type valueExprType = valueExpr->getType();
// Check if this is one of the expected types.
if (valueExprType == rangeTy || valueExprType == singleTy)
continue;
// If the operand is an Operation, allow converting to a Value or
// ValueRange. This situations arises quite often with nested operation
// expressions: `op<my_dialect.foo>(op<my_dialect.bar>)`
if (singleTy == valueTy) {
if (valueExprType.isa<ast::OperationType>()) {
valueExpr = convertOpToValue(valueExpr);
continue;
}
}
// Otherwise, try to convert the expression to a range.
if (succeeded(convertExpressionTo(valueExpr, rangeTy)))
continue;
return emitError(
valueExpr->getLoc(),
llvm::formatv(
"expected `{0}` or `{1}` convertible expression, but got `{2}`",
singleTy, rangeTy, valueExprType));
}
return success();
}
FailureOr<ast::TupleExpr *>
Parser::createTupleExpr(SMRange loc, ArrayRef<ast::Expr *> elements,
ArrayRef<StringRef> elementNames) {
for (const ast::Expr *element : elements) {
ast::Type eleTy = element->getType();
if (eleTy.isa<ast::ConstraintType, ast::RewriteType, ast::TupleType>()) {
return emitError(
element->getLoc(),
llvm::formatv("unable to build a tuple with `{0}` element", eleTy));
}
}
return ast::TupleExpr::create(ctx, loc, elements, elementNames);
}
//===----------------------------------------------------------------------===//
// Stmts
FailureOr<ast::EraseStmt *> Parser::createEraseStmt(SMRange loc,
ast::Expr *rootOp) {
// Check that root is an Operation.
ast::Type rootType = rootOp->getType();
if (!rootType.isa<ast::OperationType>())
return emitError(rootOp->getLoc(), "expected `Op` expression");
return ast::EraseStmt::create(ctx, loc, rootOp);
}
FailureOr<ast::ReplaceStmt *>
Parser::createReplaceStmt(SMRange loc, ast::Expr *rootOp,
MutableArrayRef<ast::Expr *> replValues) {
// Check that root is an Operation.
ast::Type rootType = rootOp->getType();
if (!rootType.isa<ast::OperationType>()) {
return emitError(
rootOp->getLoc(),
llvm::formatv("expected `Op` expression, but got `{0}`", rootType));
}
// If there are multiple replacement values, we implicitly convert any Op
// expressions to the value form.
bool shouldConvertOpToValues = replValues.size() > 1;
for (ast::Expr *&replExpr : replValues) {
ast::Type replType = replExpr->getType();
// Check that replExpr is an Operation, Value, or ValueRange.
if (replType.isa<ast::OperationType>()) {
if (shouldConvertOpToValues)
replExpr = convertOpToValue(replExpr);
continue;
}
if (replType != valueTy && replType != valueRangeTy) {
return emitError(replExpr->getLoc(),
llvm::formatv("expected `Op`, `Value` or `ValueRange` "
"expression, but got `{0}`",
replType));
}
}
return ast::ReplaceStmt::create(ctx, loc, rootOp, replValues);
}
FailureOr<ast::RewriteStmt *>
Parser::createRewriteStmt(SMRange loc, ast::Expr *rootOp,
ast::CompoundStmt *rewriteBody) {
// Check that root is an Operation.
ast::Type rootType = rootOp->getType();
if (!rootType.isa<ast::OperationType>()) {
return emitError(
rootOp->getLoc(),
llvm::formatv("expected `Op` expression, but got `{0}`", rootType));
}
return ast::RewriteStmt::create(ctx, loc, rootOp, rewriteBody);
}
//===----------------------------------------------------------------------===//
// Code Completion
//===----------------------------------------------------------------------===//
LogicalResult Parser::codeCompleteMemberAccess(ast::Expr *parentExpr) {
ast::Type parentType = parentExpr->getType();
if (ast::OperationType opType = parentType.dyn_cast<ast::OperationType>())
codeCompleteContext->codeCompleteOperationMemberAccess(opType);
else if (ast::TupleType tupleType = parentType.dyn_cast<ast::TupleType>())
codeCompleteContext->codeCompleteTupleMemberAccess(tupleType);
return failure();
}
LogicalResult
Parser::codeCompleteAttributeName(std::optional<StringRef> opName) {
if (opName)
codeCompleteContext->codeCompleteOperationAttributeName(*opName);
return failure();
}
LogicalResult
Parser::codeCompleteConstraintName(ast::Type inferredType,
bool allowInlineTypeConstraints) {
codeCompleteContext->codeCompleteConstraintName(
inferredType, allowInlineTypeConstraints, curDeclScope);
return failure();
}
LogicalResult Parser::codeCompleteDialectName() {
codeCompleteContext->codeCompleteDialectName();
return failure();
}
LogicalResult Parser::codeCompleteOperationName(StringRef dialectName) {
codeCompleteContext->codeCompleteOperationName(dialectName);
return failure();
}
LogicalResult Parser::codeCompletePatternMetadata() {
codeCompleteContext->codeCompletePatternMetadata();
return failure();
}
LogicalResult Parser::codeCompleteIncludeFilename(StringRef curPath) {
codeCompleteContext->codeCompleteIncludeFilename(curPath);
return failure();
}
void Parser::codeCompleteCallSignature(ast::Node *parent,
unsigned currentNumArgs) {
ast::CallableDecl *callableDecl = tryExtractCallableDecl(parent);
if (!callableDecl)
return;
codeCompleteContext->codeCompleteCallSignature(callableDecl, currentNumArgs);
}
void Parser::codeCompleteOperationOperandsSignature(
std::optional<StringRef> opName, unsigned currentNumOperands) {
codeCompleteContext->codeCompleteOperationOperandsSignature(
opName, currentNumOperands);
}
void Parser::codeCompleteOperationResultsSignature(
std::optional<StringRef> opName, unsigned currentNumResults) {
codeCompleteContext->codeCompleteOperationResultsSignature(opName,
currentNumResults);
}
//===----------------------------------------------------------------------===//
// Parser
//===----------------------------------------------------------------------===//
FailureOr<ast::Module *>
mlir::pdll::parsePDLLAST(ast::Context &ctx, llvm::SourceMgr &sourceMgr,
bool enableDocumentation,
CodeCompleteContext *codeCompleteContext) {
Parser parser(ctx, sourceMgr, enableDocumentation, codeCompleteContext);
return parser.parseModule();
}
|