cranelift_isle/sema.rs
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
//! Semantic analysis.
//!
//! This module primarily contains the type environment and term environment.
//!
//! The type environment is constructed by analyzing an input AST. The type
//! environment records the types used in the input source and the types of our
//! various rules and symbols. ISLE's type system is intentionally easy to
//! check, only requires a single pass over the AST, and doesn't require any
//! unification or anything like that.
//!
//! The term environment is constructed from both the AST and type
//! environment. It is sort of a typed and reorganized AST that more directly
//! reflects ISLE semantics than the input ISLE source code (where as the AST is
//! the opposite).
use crate::ast;
use crate::error::*;
use crate::lexer::Pos;
use crate::log;
use crate::stablemapset::{StableMap, StableSet};
use std::collections::hash_map::Entry;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::fmt;
declare_id!(
/// The id of an interned symbol.
Sym
);
declare_id!(
/// The id of an interned type inside the `TypeEnv`.
TypeId
);
declare_id!(
/// The id of a variant inside an enum.
VariantId
);
declare_id!(
/// The id of a field inside a variant.
FieldId
);
declare_id!(
/// The id of an interned term inside the `TermEnv`.
TermId
);
declare_id!(
/// The id of an interned rule inside the `TermEnv`.
RuleId
);
declare_id!(
/// The id of a bound variable inside a `Bindings`.
VarId
);
/// The type environment.
///
/// Keeps track of which symbols and rules have which types.
#[derive(Debug)]
pub struct TypeEnv {
/// Arena of interned symbol names.
///
/// Referred to indirectly via `Sym` indices.
pub syms: Vec<String>,
/// Map of already-interned symbol names to their `Sym` ids.
pub sym_map: StableMap<String, Sym>,
/// Arena of type definitions.
///
/// Referred to indirectly via `TypeId`s.
pub types: Vec<Type>,
/// A map from a type name symbol to its `TypeId`.
pub type_map: StableMap<Sym, TypeId>,
/// The types of constant symbols.
pub const_types: StableMap<Sym, TypeId>,
/// Type errors that we've found so far during type checking.
pub errors: Vec<Error>,
}
/// A built-in type.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum BuiltinType {
/// The type of booleans, with values `true` and `false`.
Bool,
/// The types of fixed-width integers.
Int(IntType),
}
/// A built-in fixed-width integer type.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum IntType {
/// Unsigned, 8 bits.
U8,
/// Unsigned, 16 bits.
U16,
/// Unsigned, 32 bits.
U32,
/// Unsigned, 64 bits.
U64,
/// Unsigned, 128 bits.
U128,
/// Unsigned, enough bits to hold a pointer.
USize,
/// Signed, 8 bits.
I8,
/// Signed, 16 bits.
I16,
/// Signed, 32 bits.
I32,
/// Signed, 64 bits.
I64,
/// Signed, 128 bits.
I128,
/// Unsigned, enough bits to hold a pointer.
ISize,
}
impl IntType {
/// Get the integer type's name.
pub fn name(&self) -> &'static str {
match self {
IntType::U8 => "u8",
IntType::U16 => "u16",
IntType::U32 => "u32",
IntType::U64 => "u64",
IntType::U128 => "u128",
IntType::USize => "usize",
IntType::I8 => "i8",
IntType::I16 => "i16",
IntType::I32 => "i32",
IntType::I64 => "i64",
IntType::I128 => "i128",
IntType::ISize => "isize",
}
}
/// Is this integer type signed?
pub fn is_signed(&self) -> bool {
match self {
IntType::U8
| IntType::U16
| IntType::U32
| IntType::U64
| IntType::U128
| IntType::USize => false,
IntType::I8
| IntType::I16
| IntType::I32
| IntType::I64
| IntType::I128
| IntType::ISize => true,
}
}
}
impl fmt::Display for IntType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl BuiltinType {
/// All the built-in types.
pub const ALL: &'static [Self] = &[
Self::Bool,
Self::Int(IntType::U8),
Self::Int(IntType::U16),
Self::Int(IntType::U32),
Self::Int(IntType::U64),
Self::Int(IntType::U128),
Self::Int(IntType::USize),
Self::Int(IntType::I8),
Self::Int(IntType::I16),
Self::Int(IntType::I32),
Self::Int(IntType::I64),
Self::Int(IntType::I128),
Self::Int(IntType::ISize),
];
/// Get the built-in type's name.
pub fn name(&self) -> &'static str {
match self {
BuiltinType::Bool => "bool",
BuiltinType::Int(it) => it.name(),
}
}
const fn to_usize(&self) -> usize {
match self {
Self::Bool => 0,
Self::Int(ty) => *ty as usize + 1,
}
}
}
impl TypeId {
const fn builtin(builtin: BuiltinType) -> Self {
Self(builtin.to_usize())
}
/// TypeId for `bool`.
pub const BOOL: Self = Self::builtin(BuiltinType::Bool);
/// TypeId for `u8`.
pub const U8: Self = Self::builtin(BuiltinType::Int(IntType::U8));
/// TypeId for `u16`.
pub const U16: Self = Self::builtin(BuiltinType::Int(IntType::U16));
/// TypeId for `u32`.
pub const U32: Self = Self::builtin(BuiltinType::Int(IntType::U32));
/// TypeId for `u64`.
pub const U64: Self = Self::builtin(BuiltinType::Int(IntType::U64));
/// TypeId for `u128`.
pub const U128: Self = Self::builtin(BuiltinType::Int(IntType::U128));
/// TypeId for `usize`.
pub const USIZE: Self = Self::builtin(BuiltinType::Int(IntType::USize));
/// TypeId for `i8`.
pub const I8: Self = Self::builtin(BuiltinType::Int(IntType::I8));
/// TypeId for `i16`.
pub const I16: Self = Self::builtin(BuiltinType::Int(IntType::I16));
/// TypeId for `i32`.
pub const I32: Self = Self::builtin(BuiltinType::Int(IntType::I32));
/// TypeId for `i64`.
pub const I64: Self = Self::builtin(BuiltinType::Int(IntType::I64));
/// TypeId for `i128`.
pub const I128: Self = Self::builtin(BuiltinType::Int(IntType::I128));
/// TypeId for `isize`.
pub const ISIZE: Self = Self::builtin(BuiltinType::Int(IntType::ISize));
}
/// A type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Type {
/// Built-in types. Always in scope, not defined anywhere in source.
Builtin(BuiltinType),
/// A primitive, `Copy` type.
///
/// These are always defined externally, and we allow literals of these
/// types to pass through from ISLE source code to the emitted Rust code.
Primitive(TypeId, Sym, Pos),
/// A sum type.
///
/// Note that enums with only one variant are equivalent to a "struct".
Enum {
/// The name of this enum.
name: Sym,
/// This `enum`'s type id.
id: TypeId,
/// Is this `enum` defined in external Rust code?
///
/// If so, ISLE will not emit a definition for it. If not, then it will
/// emit a Rust definition for it.
is_extern: bool,
/// Whether this type should *not* derive `Debug`.
///
/// Incompatible with `is_extern`.
is_nodebug: bool,
/// The different variants for this enum.
variants: Vec<Variant>,
/// The ISLE source position where this `enum` is defined.
pos: Pos,
},
}
impl Type {
/// Get the name of this `Type`.
pub fn name<'a>(&self, tyenv: &'a TypeEnv) -> &'a str {
match self {
Self::Builtin(ty) => ty.name(),
Self::Primitive(_, name, _) | Self::Enum { name, .. } => &tyenv.syms[name.index()],
}
}
/// Get the position where this type was defined.
pub fn pos(&self) -> Option<Pos> {
match self {
Self::Builtin(..) => None,
Self::Primitive(_, _, pos) | Self::Enum { pos, .. } => Some(*pos),
}
}
/// Is this a primitive type?
pub fn is_prim(&self) -> bool {
matches!(self, Type::Primitive(..))
}
/// Is this a built-in integer type?
pub fn is_int(&self) -> bool {
matches!(self, Self::Builtin(BuiltinType::Int(_)))
}
}
/// A variant of an enum.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Variant {
/// The name of this variant.
pub name: Sym,
/// The full, prefixed-with-the-enum's-name name of this variant.
///
/// E.g. if the enum is `Foo` and this variant is `Bar`, then the
/// `fullname` is `Foo.Bar`.
pub fullname: Sym,
/// The id of this variant, i.e. the index of this variant within its
/// enum's `Type::Enum::variants`.
pub id: VariantId,
/// The data fields of this enum variant.
pub fields: Vec<Field>,
}
/// A field of a `Variant`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Field {
/// The name of this field.
pub name: Sym,
/// This field's id.
pub id: FieldId,
/// The type of this field.
pub ty: TypeId,
}
/// The term environment.
///
/// This is sort of a typed and reorganized AST that more directly reflects ISLE
/// semantics than the input ISLE source code (where as the AST is the
/// opposite).
#[derive(Clone, Debug)]
pub struct TermEnv {
/// Arena of interned terms defined in this ISLE program.
///
/// This is indexed by `TermId`.
pub terms: Vec<Term>,
/// A map from am interned `Term`'s name to its `TermId`.
pub term_map: StableMap<Sym, TermId>,
/// Arena of interned rules defined in this ISLE program.
///
/// This is indexed by `RuleId`.
pub rules: Vec<Rule>,
/// Map from (inner_ty, outer_ty) pairs to term IDs, giving the
/// defined implicit type-converter terms we can try to use to fit
/// types together.
pub converters: StableMap<(TypeId, TypeId), TermId>,
/// Flag for whether to expand internal extractors in the
/// translation from the AST to sema.
pub expand_internal_extractors: bool,
}
/// A term.
///
/// Maps parameter types to result types if this is a constructor term, or
/// result types to parameter types if this is an extractor term. Or both if
/// this term can be either a constructor or an extractor.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Term {
/// This term's id.
pub id: TermId,
/// The source position where this term was declared.
pub decl_pos: Pos,
/// The name of this term.
pub name: Sym,
/// The parameter types to this term.
pub arg_tys: Vec<TypeId>,
/// The result types of this term.
pub ret_ty: TypeId,
/// The kind of this term.
pub kind: TermKind,
}
/// Flags from a term's declaration with `(decl ...)`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct TermFlags {
/// Whether the term is marked as `pure`.
pub pure: bool,
/// Whether the term is marked as `multi`.
pub multi: bool,
/// Whether the term is marked as `partial`.
pub partial: bool,
}
impl TermFlags {
/// Return a new `TermFlags` suitable for a term on the LHS of a rule.
pub fn on_lhs(mut self) -> Self {
self.pure = true;
self.partial = true;
self
}
}
/// The kind of a term.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TermKind {
/// An enum variant constructor or extractor.
EnumVariant {
/// Which variant of the enum: e.g. for enum type `A` if a term is
/// `(A.A1 ...)` then the variant ID corresponds to `A1`.
variant: VariantId,
},
/// A term declared via a `(decl ...)` form.
Decl {
/// Flags from the term's declaration.
flags: TermFlags,
/// The kind of this term's constructor, if any.
constructor_kind: Option<ConstructorKind>,
/// The kind of this term's extractor, if any.
extractor_kind: Option<ExtractorKind>,
},
}
/// The kind of a constructor for a term.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConstructorKind {
/// A term with "internal" rules that work in the forward direction. Becomes
/// a compiled Rust function in the generated code.
InternalConstructor,
/// A term defined solely by an external constructor function.
ExternalConstructor {
/// The external name of the constructor function.
name: Sym,
},
}
/// The kind of an extractor for a term.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExtractorKind {
/// A term that defines an "extractor macro" in the LHS of a pattern. Its
/// arguments take patterns and are simply substituted with the given
/// patterns when used.
InternalExtractor {
/// This extractor's pattern.
template: ast::Pattern,
},
/// A term defined solely by an external extractor function.
ExternalExtractor {
/// The external name of the extractor function.
name: Sym,
/// Is the external extractor infallible?
infallible: bool,
/// The position where this external extractor was declared.
pos: Pos,
},
}
/// How many values a function can return.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReturnKind {
/// Exactly one return value.
Plain,
/// Zero or one return values.
Option,
/// Zero or more return values.
Iterator,
}
/// An external function signature.
#[derive(Clone, Debug)]
pub struct ExternalSig {
/// The name of the external function.
pub func_name: String,
/// The name of the external function, prefixed with the context trait.
pub full_name: String,
/// The types of this function signature's parameters.
pub param_tys: Vec<TypeId>,
/// The types of this function signature's results.
pub ret_tys: Vec<TypeId>,
/// How many values can this function return?
pub ret_kind: ReturnKind,
}
impl Term {
/// Get this term's type.
pub fn ty(&self) -> TypeId {
self.ret_ty
}
fn check_args_count<T>(&self, args: &[T], tyenv: &mut TypeEnv, pos: Pos, sym: &ast::Ident) {
if self.arg_tys.len() != args.len() {
tyenv.report_error(
pos,
format!(
"Incorrect argument count for term '{}': got {}, expect {}",
sym.0,
args.len(),
self.arg_tys.len()
),
);
}
}
/// Is this term an enum variant?
pub fn is_enum_variant(&self) -> bool {
matches!(self.kind, TermKind::EnumVariant { .. })
}
/// Is this term partial?
pub fn is_partial(&self) -> bool {
matches!(
self.kind,
TermKind::Decl {
flags: TermFlags { partial: true, .. },
..
}
)
}
/// Does this term have a constructor?
pub fn has_constructor(&self) -> bool {
matches!(
self.kind,
TermKind::EnumVariant { .. }
| TermKind::Decl {
constructor_kind: Some(_),
..
}
)
}
/// Does this term have an extractor?
pub fn has_extractor(&self) -> bool {
matches!(
self.kind,
TermKind::EnumVariant { .. }
| TermKind::Decl {
extractor_kind: Some(_),
..
}
)
}
/// Is this term's extractor external?
pub fn has_external_extractor(&self) -> bool {
matches!(
self.kind,
TermKind::Decl {
extractor_kind: Some(ExtractorKind::ExternalExtractor { .. }),
..
}
)
}
/// Is this term's constructor external?
pub fn has_external_constructor(&self) -> bool {
matches!(
self.kind,
TermKind::Decl {
constructor_kind: Some(ConstructorKind::ExternalConstructor { .. }),
..
}
)
}
/// Get this term's extractor's external function signature, if any.
pub fn extractor_sig(&self, tyenv: &TypeEnv) -> Option<ExternalSig> {
match &self.kind {
TermKind::Decl {
flags,
extractor_kind:
Some(ExtractorKind::ExternalExtractor {
name, infallible, ..
}),
..
} => {
let ret_kind = if flags.multi {
ReturnKind::Iterator
} else if *infallible {
ReturnKind::Plain
} else {
ReturnKind::Option
};
Some(ExternalSig {
func_name: tyenv.syms[name.index()].clone(),
full_name: format!("C::{}", tyenv.syms[name.index()]),
param_tys: vec![self.ret_ty],
ret_tys: self.arg_tys.clone(),
ret_kind,
})
}
_ => None,
}
}
/// Get this term's constructor's external function signature, if any.
pub fn constructor_sig(&self, tyenv: &TypeEnv) -> Option<ExternalSig> {
match &self.kind {
TermKind::Decl {
constructor_kind: Some(kind),
flags,
..
} => {
let (func_name, full_name) = match kind {
ConstructorKind::InternalConstructor => {
let name = format!("constructor_{}", tyenv.syms[self.name.index()]);
(name.clone(), name)
}
ConstructorKind::ExternalConstructor { name } => (
tyenv.syms[name.index()].clone(),
format!("C::{}", tyenv.syms[name.index()]),
),
};
let ret_kind = if flags.multi {
ReturnKind::Iterator
} else if flags.partial {
ReturnKind::Option
} else {
ReturnKind::Plain
};
Some(ExternalSig {
func_name,
full_name,
param_tys: self.arg_tys.clone(),
ret_tys: vec![self.ret_ty],
ret_kind,
})
}
_ => None,
}
}
}
/// A term rewrite rule.
#[derive(Clone, Debug)]
pub struct Rule {
/// This rule's id.
pub id: RuleId,
/// The left-hand side pattern that this rule matches.
pub root_term: TermId,
/// Patterns to test against the root term's arguments.
pub args: Vec<Pattern>,
/// Any subpattern "if-let" clauses.
pub iflets: Vec<IfLet>,
/// The right-hand side expression that this rule evaluates upon successful
/// match.
pub rhs: Expr,
/// Variable names used in this rule, indexed by [VarId].
pub vars: Vec<BoundVar>,
/// The priority of this rule, defaulted to 0 if it was missing in the source.
pub prio: i64,
/// The source position where this rule is defined.
pub pos: Pos,
/// The optional name for this rule.
pub name: Option<Sym>,
}
/// A name bound in a pattern or let-expression.
#[derive(Clone, Debug)]
pub struct BoundVar {
/// The identifier used for this variable within the scope of the current [Rule].
pub id: VarId,
/// The variable's name.
pub name: Sym,
/// The type of the value this variable is bound to.
pub ty: TypeId,
/// A counter used to check whether this variable is still in scope during
/// semantic analysis. Not meaningful afterward.
scope: usize,
}
/// An `if-let` clause with a subpattern match on an expr after the
/// main LHS matches.
#[derive(Clone, Debug)]
pub struct IfLet {
/// The left-hand side pattern that this `if-let` clause matches
/// against the expression below.
pub lhs: Pattern,
/// The right-hand side expression that this pattern
/// evaluates. Must be pure.
pub rhs: Expr,
}
/// A left-hand side pattern of some rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Pattern {
/// Bind a variable of the given type from the current value.
///
/// Keep matching on the value with the subpattern.
BindPattern(TypeId, VarId, Box<Pattern>),
/// Match the current value against an already bound variable with the given
/// type.
Var(TypeId, VarId),
/// Match the current value against a constant boolean.
ConstBool(TypeId, bool),
/// Match the current value against a constant integer of the given integer
/// type.
ConstInt(TypeId, i128),
/// Match the current value against a constant primitive value of the given
/// primitive type.
ConstPrim(TypeId, Sym),
/// Match the current value against the given extractor term with the given
/// arguments.
Term(TypeId, TermId, Vec<Pattern>),
/// Match anything of the given type successfully.
Wildcard(TypeId),
/// Match all of the following patterns of the given type.
And(TypeId, Vec<Pattern>),
}
/// A right-hand side expression of some rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Expr {
/// Invoke this term constructor with the given arguments.
Term(TypeId, TermId, Vec<Expr>),
/// Get the value of a variable that was bound in the left-hand side.
Var(TypeId, VarId),
/// Get a constant boolean.
ConstBool(TypeId, bool),
/// Get a constant integer.
ConstInt(TypeId, i128),
/// Get a constant primitive.
ConstPrim(TypeId, Sym),
/// Evaluate the nested expressions and bind their results to the given
/// variables, then evaluate the body expression.
Let {
/// The type of the result of this let expression.
ty: TypeId,
/// The expressions that are evaluated and bound to the given variables.
bindings: Vec<(VarId, TypeId, Box<Expr>)>,
/// The body expression that is evaluated after the bindings.
body: Box<Expr>,
},
}
/// Visitor interface for [Pattern]s. Visitors can assign an arbitrary identifier to each
/// subpattern, which is threaded through to subsequent calls into the visitor.
pub trait PatternVisitor {
/// The type of subpattern identifiers.
type PatternId: Copy;
/// Match if `a` and `b` have equal values.
fn add_match_equal(&mut self, a: Self::PatternId, b: Self::PatternId, ty: TypeId);
/// Match if `input` is the given boolean constant.
fn add_match_bool(&mut self, input: Self::PatternId, ty: TypeId, bool_val: bool);
/// Match if `input` is the given integer constant.
fn add_match_int(&mut self, input: Self::PatternId, ty: TypeId, int_val: i128);
/// Match if `input` is the given primitive constant.
fn add_match_prim(&mut self, input: Self::PatternId, ty: TypeId, val: Sym);
/// Match if `input` is the given enum variant. Returns an identifier for each field within the
/// enum variant. The length of the return list must equal the length of `arg_tys`.
fn add_match_variant(
&mut self,
input: Self::PatternId,
input_ty: TypeId,
arg_tys: &[TypeId],
variant: VariantId,
) -> Vec<Self::PatternId>;
/// Match if the given external extractor succeeds on `input`. Returns an identifier for each
/// return value from the external extractor. The length of the return list must equal the
/// length of `output_tys`.
fn add_extract(
&mut self,
input: Self::PatternId,
input_ty: TypeId,
output_tys: Vec<TypeId>,
term: TermId,
infallible: bool,
multi: bool,
) -> Vec<Self::PatternId>;
}
impl Pattern {
/// Get this pattern's type.
pub fn ty(&self) -> TypeId {
match *self {
Self::BindPattern(t, ..) => t,
Self::Var(t, ..) => t,
Self::ConstBool(t, ..) => t,
Self::ConstInt(t, ..) => t,
Self::ConstPrim(t, ..) => t,
Self::Term(t, ..) => t,
Self::Wildcard(t, ..) => t,
Self::And(t, ..) => t,
}
}
/// Recursively visit every sub-pattern.
pub fn visit<V: PatternVisitor>(
&self,
visitor: &mut V,
input: V::PatternId,
termenv: &TermEnv,
vars: &mut HashMap<VarId, V::PatternId>,
) {
match *self {
Pattern::BindPattern(_ty, var, ref subpat) => {
// Bind the appropriate variable and recurse.
assert!(!vars.contains_key(&var));
vars.insert(var, input);
subpat.visit(visitor, input, termenv, vars);
}
Pattern::Var(ty, var) => {
// Assert that the value matches the existing bound var.
let var_val = vars
.get(&var)
.copied()
.expect("Variable should already be bound");
visitor.add_match_equal(input, var_val, ty);
}
Pattern::ConstBool(ty, value) => visitor.add_match_bool(input, ty, value),
Pattern::ConstInt(ty, value) => visitor.add_match_int(input, ty, value),
Pattern::ConstPrim(ty, value) => visitor.add_match_prim(input, ty, value),
Pattern::Term(ty, term, ref args) => {
// Determine whether the term has an external extractor or not.
let termdata = &termenv.terms[term.index()];
let arg_values = match &termdata.kind {
TermKind::EnumVariant { variant } => {
visitor.add_match_variant(input, ty, &termdata.arg_tys, *variant)
}
TermKind::Decl {
extractor_kind: None,
..
} => {
panic!("Pattern invocation of undefined term body")
}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { .. }),
..
} => {
panic!("Should have been expanded away")
}
TermKind::Decl {
flags,
extractor_kind: Some(ExtractorKind::ExternalExtractor { infallible, .. }),
..
} => {
// Evaluate all `input` args.
let output_tys = args.iter().map(|arg| arg.ty()).collect();
// Invoke the extractor.
visitor.add_extract(
input,
termdata.ret_ty,
output_tys,
term,
*infallible && !flags.multi,
flags.multi,
)
}
};
for (pat, val) in args.iter().zip(arg_values) {
pat.visit(visitor, val, termenv, vars);
}
}
Pattern::And(_ty, ref children) => {
for child in children {
child.visit(visitor, input, termenv, vars);
}
}
Pattern::Wildcard(_ty) => {
// Nothing!
}
}
}
}
/// Visitor interface for [Expr]s. Visitors can return an arbitrary identifier for each
/// subexpression, which is threaded through to subsequent calls into the visitor.
pub trait ExprVisitor {
/// The type of subexpression identifiers.
type ExprId: Copy;
/// Construct a constant boolean.
fn add_const_bool(&mut self, ty: TypeId, val: bool) -> Self::ExprId;
/// Construct a constant integer.
fn add_const_int(&mut self, ty: TypeId, val: i128) -> Self::ExprId;
/// Construct a primitive constant.
fn add_const_prim(&mut self, ty: TypeId, val: Sym) -> Self::ExprId;
/// Construct an enum variant with the given `inputs` assigned to the variant's fields in order.
fn add_create_variant(
&mut self,
inputs: Vec<(Self::ExprId, TypeId)>,
ty: TypeId,
variant: VariantId,
) -> Self::ExprId;
/// Call an external constructor with the given `inputs` as arguments.
fn add_construct(
&mut self,
inputs: Vec<(Self::ExprId, TypeId)>,
ty: TypeId,
term: TermId,
pure: bool,
infallible: bool,
multi: bool,
) -> Self::ExprId;
}
impl Expr {
/// Get this expression's type.
pub fn ty(&self) -> TypeId {
match *self {
Self::Term(t, ..) => t,
Self::Var(t, ..) => t,
Self::ConstBool(t, ..) => t,
Self::ConstInt(t, ..) => t,
Self::ConstPrim(t, ..) => t,
Self::Let { ty: t, .. } => t,
}
}
/// Recursively visit every subexpression.
pub fn visit<V: ExprVisitor>(
&self,
visitor: &mut V,
termenv: &TermEnv,
vars: &HashMap<VarId, V::ExprId>,
) -> V::ExprId {
log!("Expr::visit: expr {:?}", self);
match *self {
Expr::ConstBool(ty, val) => visitor.add_const_bool(ty, val),
Expr::ConstInt(ty, val) => visitor.add_const_int(ty, val),
Expr::ConstPrim(ty, val) => visitor.add_const_prim(ty, val),
Expr::Let {
ty: _ty,
ref bindings,
ref body,
} => {
let mut vars = vars.clone();
for &(var, _var_ty, ref var_expr) in bindings {
let var_value = var_expr.visit(visitor, termenv, &vars);
vars.insert(var, var_value);
}
body.visit(visitor, termenv, &vars)
}
Expr::Var(_ty, var_id) => *vars.get(&var_id).unwrap(),
Expr::Term(ty, term, ref arg_exprs) => {
let termdata = &termenv.terms[term.index()];
let arg_values_tys = arg_exprs
.iter()
.map(|arg_expr| arg_expr.visit(visitor, termenv, vars))
.zip(termdata.arg_tys.iter().copied())
.collect();
match &termdata.kind {
TermKind::EnumVariant { variant } => {
visitor.add_create_variant(arg_values_tys, ty, *variant)
}
TermKind::Decl {
constructor_kind: Some(_),
flags,
..
} => {
visitor.add_construct(
arg_values_tys,
ty,
term,
flags.pure,
/* infallible = */ !flags.partial,
flags.multi,
)
}
TermKind::Decl {
constructor_kind: None,
..
} => panic!("Should have been caught by typechecking"),
}
}
}
}
fn visit_in_rule<V: RuleVisitor>(
&self,
visitor: &mut V,
termenv: &TermEnv,
vars: &HashMap<VarId, <V::PatternVisitor as PatternVisitor>::PatternId>,
) -> V::Expr {
let var_exprs = vars
.iter()
.map(|(&var, &val)| (var, visitor.pattern_as_expr(val)))
.collect();
visitor.add_expr(|visitor| VisitedExpr {
ty: self.ty(),
value: self.visit(visitor, termenv, &var_exprs),
})
}
}
/// Information about an expression after it has been fully visited in [RuleVisitor::add_expr].
#[derive(Clone, Copy)]
pub struct VisitedExpr<V: ExprVisitor> {
/// The type of the top-level expression.
pub ty: TypeId,
/// The identifier returned by the visitor for the top-level expression.
pub value: V::ExprId,
}
/// Visitor interface for [Rule]s. Visitors must be able to visit patterns by implementing
/// [PatternVisitor], and to visit expressions by providing a type that implements [ExprVisitor].
pub trait RuleVisitor {
/// The type of pattern visitors constructed by [RuleVisitor::add_pattern].
type PatternVisitor: PatternVisitor;
/// The type of expression visitors constructed by [RuleVisitor::add_expr].
type ExprVisitor: ExprVisitor;
/// The type returned from [RuleVisitor::add_expr], which may be exchanged for a subpattern
/// identifier using [RuleVisitor::expr_as_pattern].
type Expr;
/// Visit one of the arguments to the top-level pattern.
fn add_arg(
&mut self,
index: usize,
ty: TypeId,
) -> <Self::PatternVisitor as PatternVisitor>::PatternId;
/// Visit a pattern, used once for the rule's left-hand side and once for each if-let. You can
/// determine which part of the rule the pattern comes from based on whether the `PatternId`
/// passed to the first call to this visitor came from `add_arg` or `expr_as_pattern`.
fn add_pattern<F>(&mut self, visitor: F)
where
F: FnOnce(&mut Self::PatternVisitor);
/// Visit an expression, used once for each if-let and once for the rule's right-hand side.
fn add_expr<F>(&mut self, visitor: F) -> Self::Expr
where
F: FnOnce(&mut Self::ExprVisitor) -> VisitedExpr<Self::ExprVisitor>;
/// Given an expression from [RuleVisitor::add_expr], return an identifier that can be used with
/// a pattern visitor in [RuleVisitor::add_pattern].
fn expr_as_pattern(
&mut self,
expr: Self::Expr,
) -> <Self::PatternVisitor as PatternVisitor>::PatternId;
/// Given an identifier from the pattern visitor, return an identifier that can be used with
/// the expression visitor.
fn pattern_as_expr(
&mut self,
pattern: <Self::PatternVisitor as PatternVisitor>::PatternId,
) -> <Self::ExprVisitor as ExprVisitor>::ExprId;
}
impl Rule {
/// Recursively visit every pattern and expression in this rule. Returns the [RuleVisitor::Expr]
/// that was returned from [RuleVisitor::add_expr] when that function was called on the rule's
/// right-hand side.
pub fn visit<V: RuleVisitor>(&self, visitor: &mut V, termenv: &TermEnv) -> V::Expr {
let mut vars = HashMap::new();
// Visit the pattern, starting from the root input value.
let termdata = &termenv.terms[self.root_term.index()];
for (i, (subpat, &arg_ty)) in self.args.iter().zip(termdata.arg_tys.iter()).enumerate() {
let value = visitor.add_arg(i, arg_ty);
visitor.add_pattern(|visitor| subpat.visit(visitor, value, termenv, &mut vars));
}
// Visit the `if-let` clauses, using `V::ExprVisitor` for the sub-exprs (right-hand sides).
for iflet in self.iflets.iter() {
let subexpr = iflet.rhs.visit_in_rule(visitor, termenv, &vars);
let value = visitor.expr_as_pattern(subexpr);
visitor.add_pattern(|visitor| iflet.lhs.visit(visitor, value, termenv, &mut vars));
}
// Visit the rule's right-hand side, making use of the bound variables from the pattern.
self.rhs.visit_in_rule(visitor, termenv, &vars)
}
}
/// Given an `Option<T>`, unwrap the inner `T` value, or `continue` if it is
/// `None`.
///
/// Useful for when we encountered an error earlier in our analysis but kept
/// going to find more errors, and now we've run into some missing data that
/// would have been filled in if we didn't hit that original error, but we want
/// to keep going to find more errors.
macro_rules! unwrap_or_continue {
($e:expr) => {
match $e {
Some(x) => x,
None => continue,
}
};
}
impl Default for TypeEnv {
fn default() -> Self {
Self {
syms: BuiltinType::ALL
.iter()
.map(|bt| String::from(bt.name()))
.collect(),
sym_map: BuiltinType::ALL
.iter()
.enumerate()
.map(|(idx, bt)| (String::from(bt.name()), Sym(idx)))
.collect(),
types: BuiltinType::ALL
.iter()
.map(|bt| Type::Builtin(*bt))
.collect(),
type_map: BuiltinType::ALL
.iter()
.enumerate()
.map(|(idx, _)| (Sym(idx), TypeId(idx)))
.collect(),
const_types: StableMap::new(),
errors: vec![],
}
}
}
impl TypeEnv {
/// Construct the type environment from the AST.
pub fn from_ast(defs: &[ast::Def]) -> Result<TypeEnv, Vec<Error>> {
let mut tyenv = TypeEnv::default();
// Traverse defs, assigning type IDs to type names. We'll fill
// in types on a second pass.
for def in defs {
match def {
&ast::Def::Type(ref td) => {
let tid = TypeId(tyenv.type_map.len());
let name = tyenv.intern_mut(&td.name);
if let Some(existing) = tyenv.type_map.get(&name).copied() {
tyenv.report_error(
td.pos,
format!("Type with name '{}' defined more than once", td.name.0),
);
let pos = unwrap_or_continue!(tyenv.types.get(existing.index())).pos();
match pos {
Some(pos) => tyenv.report_error(
pos,
format!("Type with name '{}' already defined here", td.name.0),
),
None => tyenv.report_error(
td.pos,
format!("Type with name '{}' is a built-in type", td.name.0),
),
}
continue;
}
tyenv.type_map.insert(name, tid);
}
_ => {}
}
}
// Now lower AST nodes to type definitions, raising errors
// where typenames of fields are undefined or field names are
// duplicated.
for def in defs {
match def {
&ast::Def::Type(ref td) => {
let tid = tyenv.types.len();
if let Some(ty) = tyenv.type_from_ast(TypeId(tid), td) {
tyenv.types.push(ty);
}
}
_ => {}
}
}
// Now collect types for extern constants.
for def in defs {
if let &ast::Def::Extern(ast::Extern::Const {
ref name,
ref ty,
pos,
}) = def
{
let ty = match tyenv.get_type_by_name(ty) {
Some(ty) => ty,
None => {
tyenv.report_error(pos, "Unknown type for constant");
continue;
}
};
let name = tyenv.intern_mut(name);
tyenv.const_types.insert(name, ty);
}
}
tyenv.return_errors()?;
Ok(tyenv)
}
fn return_errors(&mut self) -> Result<(), Vec<Error>> {
if self.errors.is_empty() {
Ok(())
} else {
Err(std::mem::take(&mut self.errors))
}
}
fn type_from_ast(&mut self, tid: TypeId, ty: &ast::Type) -> Option<Type> {
let name = self.intern(&ty.name).unwrap();
match &ty.ty {
&ast::TypeValue::Primitive(ref id, ..) => {
if ty.is_nodebug {
self.report_error(ty.pos, "primitive types cannot be marked `nodebug`");
return None;
}
if ty.is_extern {
self.report_error(ty.pos, "primitive types cannot be marked `extern`");
return None;
}
Some(Type::Primitive(tid, self.intern_mut(id), ty.pos))
}
&ast::TypeValue::Enum(ref ty_variants, ..) => {
if ty.is_extern && ty.is_nodebug {
self.report_error(ty.pos, "external types cannot be marked `nodebug`");
return None;
}
let mut variants = vec![];
for variant in ty_variants {
let combined_ident =
ast::Ident(format!("{}.{}", ty.name.0, variant.name.0), variant.name.1);
let fullname = self.intern_mut(&combined_ident);
let name = self.intern_mut(&variant.name);
let id = VariantId(variants.len());
if variants.iter().any(|v: &Variant| v.name == name) {
self.report_error(
variant.pos,
format!("Duplicate variant name in type: '{}'", variant.name.0),
);
return None;
}
let mut fields = vec![];
for field in &variant.fields {
let field_name = self.intern_mut(&field.name);
if fields.iter().any(|f: &Field| f.name == field_name) {
self.report_error(
field.pos,
format!(
"Duplicate field name '{}' in variant '{}' of type",
field.name.0, variant.name.0
),
);
return None;
}
let field_tid = match self.get_type_by_name(&field.ty) {
Some(tid) => tid,
None => {
self.report_error(
field.ty.1,
format!(
"Unknown type '{}' for field '{}' in variant '{}'",
field.ty.0, field.name.0, variant.name.0
),
);
return None;
}
};
fields.push(Field {
name: field_name,
id: FieldId(fields.len()),
ty: field_tid,
});
}
variants.push(Variant {
name,
fullname,
id,
fields,
});
}
Some(Type::Enum {
name,
id: tid,
is_extern: ty.is_extern,
is_nodebug: ty.is_nodebug,
variants,
pos: ty.pos,
})
}
}
}
fn error(&self, pos: Pos, msg: impl Into<String>) -> Error {
Error::TypeError {
msg: msg.into(),
span: Span::new_single(pos),
}
}
fn report_error(&mut self, pos: Pos, msg: impl Into<String>) {
let err = self.error(pos, msg);
self.errors.push(err);
}
fn intern_mut(&mut self, ident: &ast::Ident) -> Sym {
if let Some(s) = self.sym_map.get(&ident.0).copied() {
s
} else {
let s = Sym(self.syms.len());
self.syms.push(ident.0.clone());
self.sym_map.insert(ident.0.clone(), s);
s
}
}
fn intern(&self, ident: &ast::Ident) -> Option<Sym> {
self.sym_map.get(&ident.0).copied()
}
/// Lookup type by name.
pub fn get_type_by_name(&self, sym: &ast::Ident) -> Option<TypeId> {
self.intern(sym)
.and_then(|sym| self.type_map.get(&sym))
.copied()
}
}
#[derive(Clone, Debug, Default)]
struct Bindings {
/// All bindings accumulated so far within the current rule, including let-
/// bindings which have gone out of scope.
seen: Vec<BoundVar>,
/// Counter for unique scope IDs within this set of bindings.
next_scope: usize,
/// Stack of the scope IDs for bindings which are currently in scope.
in_scope: Vec<usize>,
}
impl Bindings {
fn enter_scope(&mut self) {
self.in_scope.push(self.next_scope);
self.next_scope += 1;
}
fn exit_scope(&mut self) {
self.in_scope.pop();
}
fn add_var(&mut self, name: Sym, ty: TypeId) -> VarId {
let id = VarId(self.seen.len());
let var = BoundVar {
id,
name,
ty,
scope: *self
.in_scope
.last()
.expect("enter_scope should be called before add_var"),
};
log!("binding var {:?}", var);
self.seen.push(var);
id
}
fn lookup(&self, name: Sym) -> Option<&BoundVar> {
self.seen
.iter()
.rev()
.find(|binding| binding.name == name && self.in_scope.contains(&binding.scope))
}
}
impl TermEnv {
/// Construct the term environment from the AST and the type environment.
pub fn from_ast(
tyenv: &mut TypeEnv,
defs: &[ast::Def],
expand_internal_extractors: bool,
) -> Result<TermEnv, Vec<Error>> {
let mut env = TermEnv {
terms: vec![],
term_map: StableMap::new(),
rules: vec![],
converters: StableMap::new(),
expand_internal_extractors,
};
env.collect_pragmas(defs);
env.collect_term_sigs(tyenv, defs);
env.collect_enum_variant_terms(tyenv);
tyenv.return_errors()?;
env.collect_constructors(tyenv, defs);
env.collect_extractor_templates(tyenv, defs);
tyenv.return_errors()?;
env.collect_converters(tyenv, defs);
tyenv.return_errors()?;
env.collect_externs(tyenv, defs);
tyenv.return_errors()?;
env.collect_rules(tyenv, defs);
env.check_for_undefined_decls(tyenv, defs);
env.check_for_expr_terms_without_constructors(tyenv, defs);
tyenv.return_errors()?;
Ok(env)
}
fn collect_pragmas(&mut self, _: &[ast::Def]) {
// currently, no pragmas are defined, but the infrastructure is useful to keep around
return;
}
fn collect_term_sigs(&mut self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
for def in defs {
match def {
&ast::Def::Decl(ref decl) => {
let name = tyenv.intern_mut(&decl.term);
if let Some(tid) = self.term_map.get(&name) {
tyenv.report_error(
decl.pos,
format!("Duplicate decl for '{}'", decl.term.0),
);
tyenv.report_error(
self.terms[tid.index()].decl_pos,
format!("Duplicate decl for '{}'", decl.term.0),
);
}
if decl.multi && decl.partial {
tyenv.report_error(
decl.pos,
format!("Term '{}' can't be both multi and partial", decl.term.0),
);
}
let arg_tys = decl
.arg_tys
.iter()
.map(|id| {
tyenv.get_type_by_name(id).ok_or_else(|| {
tyenv.report_error(id.1, format!("Unknown arg type: '{}'", id.0));
})
})
.collect::<Result<Vec<_>, _>>();
let arg_tys = match arg_tys {
Ok(a) => a,
Err(_) => {
continue;
}
};
let ret_ty = match tyenv.get_type_by_name(&decl.ret_ty) {
Some(t) => t,
None => {
tyenv.report_error(
decl.ret_ty.1,
format!("Unknown return type: '{}'", decl.ret_ty.0),
);
continue;
}
};
let tid = TermId(self.terms.len());
self.term_map.insert(name, tid);
let flags = TermFlags {
pure: decl.pure,
multi: decl.multi,
partial: decl.partial,
};
self.terms.push(Term {
id: tid,
decl_pos: decl.pos,
name,
arg_tys,
ret_ty,
kind: TermKind::Decl {
flags,
constructor_kind: None,
extractor_kind: None,
},
});
}
_ => {}
}
}
}
fn collect_enum_variant_terms(&mut self, tyenv: &mut TypeEnv) {
'types: for i in 0..tyenv.types.len() {
let ty = &tyenv.types[i];
match ty {
&Type::Enum {
pos,
id,
ref variants,
..
} => {
for variant in variants {
if self.term_map.contains_key(&variant.fullname) {
let variant_name = tyenv.syms[variant.fullname.index()].clone();
tyenv.report_error(
pos,
format!("Duplicate enum variant constructor: '{variant_name}'",),
);
continue 'types;
}
let tid = TermId(self.terms.len());
let arg_tys = variant.fields.iter().map(|fld| fld.ty).collect::<Vec<_>>();
let ret_ty = id;
self.terms.push(Term {
id: tid,
decl_pos: pos,
name: variant.fullname,
arg_tys,
ret_ty,
kind: TermKind::EnumVariant {
variant: variant.id,
},
});
self.term_map.insert(variant.fullname, tid);
}
}
_ => {}
}
}
}
fn collect_constructors(&mut self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
for def in defs {
log!("collect_constructors from def: {:?}", def);
match def {
&ast::Def::Rule(ref rule) => {
let pos = rule.pos;
let term = match rule.pattern.root_term() {
Some(t) => t,
None => {
tyenv.report_error(
pos,
"Rule does not have a term at the LHS root".to_string(),
);
continue;
}
};
let term = match self.get_term_by_name(tyenv, &term) {
Some(tid) => tid,
None => {
tyenv
.report_error(pos, "Rule LHS root term is not defined".to_string());
continue;
}
};
let termdata = &mut self.terms[term.index()];
match &mut termdata.kind {
TermKind::Decl {
constructor_kind, ..
} => {
match constructor_kind {
None => {
*constructor_kind = Some(ConstructorKind::InternalConstructor);
}
Some(ConstructorKind::InternalConstructor) => {
// OK, no error; multiple rules can apply to
// one internal constructor term.
}
Some(ConstructorKind::ExternalConstructor { .. }) => {
tyenv.report_error(
pos,
"Rule LHS root term is incorrect kind; cannot \
be external constructor"
.to_string(),
);
continue;
}
}
}
TermKind::EnumVariant { .. } => {
tyenv.report_error(
pos,
"Rule LHS root term is incorrect kind; cannot be enum variant"
.to_string(),
);
continue;
}
}
}
_ => {}
}
}
}
fn collect_extractor_templates(&mut self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
let mut extractor_call_graph = BTreeMap::new();
for def in defs {
if let &ast::Def::Extractor(ref ext) = def {
let term = match self.get_term_by_name(tyenv, &ext.term) {
Some(x) => x,
None => {
tyenv.report_error(
ext.pos,
"Extractor macro body definition on a non-existent term".to_string(),
);
return;
}
};
let template = ext.template.make_macro_template(&ext.args[..]);
log!("extractor def: {:?} becomes template {:?}", def, template);
let mut callees = BTreeSet::new();
template.terms(&mut |pos, t| {
if let Some(term) = self.get_term_by_name(tyenv, t) {
callees.insert(term);
} else {
tyenv.report_error(
pos,
format!(
"`{}` extractor definition references unknown term `{}`",
ext.term.0, t.0
),
);
}
});
extractor_call_graph.insert(term, callees);
let termdata = &mut self.terms[term.index()];
match &mut termdata.kind {
TermKind::EnumVariant { .. } => {
tyenv.report_error(
ext.pos,
"Extractor macro body defined on term of incorrect kind; cannot be an \
enum variant",
);
continue;
}
TermKind::Decl {
flags,
extractor_kind,
..
} => match extractor_kind {
None => {
if flags.multi {
tyenv.report_error(
ext.pos,
"A term declared with `multi` cannot have an internal extractor.".to_string());
continue;
}
*extractor_kind = Some(ExtractorKind::InternalExtractor { template });
}
Some(ext_kind) => {
tyenv.report_error(
ext.pos,
"Duplicate extractor definition".to_string(),
);
let pos = match ext_kind {
ExtractorKind::InternalExtractor { template } => template.pos(),
ExtractorKind::ExternalExtractor { pos, .. } => *pos,
};
tyenv.report_error(
pos,
"Extractor was already defined here".to_string(),
);
continue;
}
},
}
}
}
// Check for cycles in the extractor call graph.
let mut stack = vec![];
'outer: for root in extractor_call_graph.keys().copied() {
stack.clear();
stack.push((root, vec![root], StableSet::new()));
while let Some((caller, path, mut seen)) = stack.pop() {
let is_new = seen.insert(caller);
if is_new {
if let Some(callees) = extractor_call_graph.get(&caller) {
stack.extend(callees.iter().map(|callee| {
let mut path = path.clone();
path.push(*callee);
(*callee, path, seen.clone())
}));
}
} else {
let pos = match &self.terms[caller.index()].kind {
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { template }),
..
} => template.pos(),
_ => {
// There must have already been errors recorded.
assert!(!tyenv.errors.is_empty());
continue 'outer;
}
};
let path: Vec<_> = path
.iter()
.map(|sym| tyenv.syms[sym.index()].as_str())
.collect();
let msg = format!(
"`{}` extractor definition is recursive: {}",
tyenv.syms[root.index()],
path.join(" -> ")
);
tyenv.report_error(pos, msg);
continue 'outer;
}
}
}
}
fn collect_converters(&mut self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
for def in defs {
match def {
&ast::Def::Converter(ast::Converter {
ref term,
ref inner_ty,
ref outer_ty,
pos,
}) => {
let inner_ty_id = match tyenv.get_type_by_name(inner_ty) {
Some(ty) => ty,
None => {
tyenv.report_error(
inner_ty.1,
format!("Unknown inner type for converter: '{}'", inner_ty.0),
);
continue;
}
};
let outer_ty_id = match tyenv.get_type_by_name(outer_ty) {
Some(ty) => ty,
None => {
tyenv.report_error(
outer_ty.1,
format!("Unknown outer type for converter: '{}'", outer_ty.0),
);
continue;
}
};
let term_id = match self.get_term_by_name(tyenv, term) {
Some(term_id) => term_id,
None => {
tyenv.report_error(
term.1,
format!("Unknown term for converter: '{}'", term.0),
);
continue;
}
};
match self.converters.entry((inner_ty_id, outer_ty_id)) {
Entry::Vacant(v) => {
v.insert(term_id);
}
Entry::Occupied(_) => {
tyenv.report_error(
pos,
format!(
"Converter already exists for this type pair: '{}', '{}'",
inner_ty.0, outer_ty.0
),
);
continue;
}
}
}
_ => {}
}
}
}
fn collect_externs(&mut self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
for def in defs {
match def {
&ast::Def::Extern(ast::Extern::Constructor {
ref term,
ref func,
pos,
}) => {
let func_sym = tyenv.intern_mut(func);
let term_id = match self.get_term_by_name(tyenv, term) {
Some(term) => term,
None => {
tyenv.report_error(
pos,
format!("Constructor declared on undefined term '{}'", term.0),
);
continue;
}
};
let termdata = &mut self.terms[term_id.index()];
match &mut termdata.kind {
TermKind::Decl {
constructor_kind, ..
} => match constructor_kind {
None => {
*constructor_kind =
Some(ConstructorKind::ExternalConstructor { name: func_sym });
}
Some(ConstructorKind::InternalConstructor) => {
tyenv.report_error(
pos,
format!(
"External constructor declared on term that already has rules: {}",
term.0,
),
);
}
Some(ConstructorKind::ExternalConstructor { .. }) => {
tyenv.report_error(
pos,
"Duplicate external constructor definition".to_string(),
);
}
},
TermKind::EnumVariant { .. } => {
tyenv.report_error(
pos,
format!(
"External constructor cannot be defined on enum variant: {}",
term.0,
),
);
}
}
}
&ast::Def::Extern(ast::Extern::Extractor {
ref term,
ref func,
pos,
infallible,
}) => {
let func_sym = tyenv.intern_mut(func);
let term_id = match self.get_term_by_name(tyenv, term) {
Some(term) => term,
None => {
tyenv.report_error(
pos,
format!("Extractor declared on undefined term '{}'", term.0),
);
continue;
}
};
let termdata = &mut self.terms[term_id.index()];
match &mut termdata.kind {
TermKind::Decl { extractor_kind, .. } => match extractor_kind {
None => {
*extractor_kind = Some(ExtractorKind::ExternalExtractor {
name: func_sym,
infallible,
pos,
});
}
Some(ExtractorKind::ExternalExtractor { pos: pos2, .. }) => {
tyenv.report_error(
pos,
"Duplicate external extractor definition".to_string(),
);
tyenv.report_error(
*pos2,
"External extractor already defined".to_string(),
);
continue;
}
Some(ExtractorKind::InternalExtractor { template }) => {
tyenv.report_error(
pos,
"Cannot define external extractor for term that already has an \
internal extractor macro body defined"
.to_string(),
);
tyenv.report_error(
template.pos(),
"Internal extractor macro body already defined".to_string(),
);
continue;
}
},
TermKind::EnumVariant { .. } => {
tyenv.report_error(
pos,
format!("Cannot define extractor for enum variant '{}'", term.0),
);
continue;
}
}
}
_ => {}
}
}
}
fn collect_rules(&mut self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
for def in defs {
match def {
&ast::Def::Rule(ref rule) => {
let pos = rule.pos;
let mut bindings = Bindings::default();
bindings.enter_scope();
let (sym, args) = if let ast::Pattern::Term { sym, args, .. } = &rule.pattern {
(sym, args)
} else {
tyenv.report_error(
pos,
"Rule does not have a term at the root of its left-hand side"
.to_string(),
);
continue;
};
let root_term = if let Some(term) = self.get_term_by_name(tyenv, sym) {
term
} else {
tyenv.report_error(
pos,
"Cannot define a rule for an unknown term".to_string(),
);
continue;
};
let termdata = &self.terms[root_term.index()];
let flags = match &termdata.kind {
TermKind::Decl { flags, .. } => *flags,
_ => {
tyenv.report_error(
pos,
"Cannot define a rule on a left-hand-side that is an enum variant"
.to_string(),
);
continue;
}
};
termdata.check_args_count(args, tyenv, pos, sym);
let args = self.translate_args(args, termdata, tyenv, &mut bindings);
let iflets = rule
.iflets
.iter()
.filter_map(|iflet| {
self.translate_iflet(tyenv, iflet, &mut bindings, flags)
})
.collect();
let rhs = unwrap_or_continue!(self.translate_expr(
tyenv,
&rule.expr,
Some(termdata.ret_ty),
&mut bindings,
flags,
));
bindings.exit_scope();
let prio = if let Some(prio) = rule.prio {
if flags.multi {
tyenv.report_error(
pos,
"Cannot set rule priorities in multi-terms".to_string(),
);
}
prio
} else {
0
};
let rid = RuleId(self.rules.len());
self.rules.push(Rule {
id: rid,
root_term,
args,
iflets,
rhs,
vars: bindings.seen,
prio,
pos,
name: rule.name.as_ref().map(|i| tyenv.intern_mut(i)),
});
}
_ => {}
}
}
}
fn check_for_undefined_decls(&self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
for def in defs {
if let ast::Def::Decl(decl) = def {
let term = self.get_term_by_name(tyenv, &decl.term).unwrap();
let term = &self.terms[term.index()];
if !term.has_constructor() && !term.has_extractor() {
tyenv.report_error(
decl.pos,
format!(
"no rules, extractor, or external definition for declaration '{}'",
decl.term.0
),
);
}
}
}
}
fn check_for_expr_terms_without_constructors(&self, tyenv: &mut TypeEnv, defs: &[ast::Def]) {
for def in defs {
if let ast::Def::Rule(rule) = def {
rule.expr.terms(&mut |pos, ident| {
let term = match self.get_term_by_name(tyenv, ident) {
None => {
debug_assert!(!tyenv.errors.is_empty());
return;
}
Some(t) => t,
};
let term = &self.terms[term.index()];
if !term.has_constructor() {
tyenv.report_error(
pos,
format!(
"term `{}` cannot be used in an expression because \
it does not have a constructor",
ident.0
),
)
}
});
}
}
}
fn maybe_implicit_convert_pattern(
&self,
tyenv: &mut TypeEnv,
pattern: &ast::Pattern,
inner_ty: TypeId,
outer_ty: TypeId,
) -> Option<ast::Pattern> {
if let Some(converter_term) = self.converters.get(&(inner_ty, outer_ty)) {
if self.terms[converter_term.index()].has_extractor() {
// This is a little awkward: we have to
// convert back to an Ident, to be
// re-resolved. The pos doesn't matter
// as it shouldn't result in a lookup
// failure.
let converter_term_ident = ast::Ident(
tyenv.syms[self.terms[converter_term.index()].name.index()].clone(),
pattern.pos(),
);
let expanded_pattern = ast::Pattern::Term {
sym: converter_term_ident,
pos: pattern.pos(),
args: vec![pattern.clone()],
};
return Some(expanded_pattern);
}
}
None
}
fn translate_pattern(
&self,
tyenv: &mut TypeEnv,
pat: &ast::Pattern,
expected_ty: TypeId,
bindings: &mut Bindings,
) -> Option<Pattern> {
log!("translate_pattern: {:?}", pat);
log!("translate_pattern: bindings = {:?}", bindings);
match pat {
// TODO: flag on primitive type decl indicating it's an integer type?
&ast::Pattern::ConstInt { val, pos } => {
let ty = &tyenv.types[expected_ty.index()];
if !ty.is_int() && !ty.is_prim() {
tyenv.report_error(
pos,
format!(
"expected non-integer type {}, but found integer literal '{}'",
ty.name(tyenv),
val,
),
);
}
Some(Pattern::ConstInt(expected_ty, val))
}
&ast::Pattern::ConstBool { val, pos } => {
if expected_ty != TypeId::BOOL {
tyenv.report_error(
pos,
format!(
"Boolean literal '{val}' has type {} but we need {} in context",
BuiltinType::Bool.name(),
tyenv.types[expected_ty.index()].name(tyenv)
),
)
}
Some(Pattern::ConstBool(TypeId::BOOL, val))
}
&ast::Pattern::ConstPrim { ref val, pos } => {
let val = tyenv.intern_mut(val);
let const_ty = match tyenv.const_types.get(&val) {
Some(ty) => *ty,
None => {
tyenv.report_error(pos, "Unknown constant");
return None;
}
};
if expected_ty != const_ty {
tyenv.report_error(pos, "Type mismatch for constant");
}
Some(Pattern::ConstPrim(const_ty, val))
}
&ast::Pattern::Wildcard { .. } => Some(Pattern::Wildcard(expected_ty)),
&ast::Pattern::And { ref subpats, .. } => {
// If any of the subpatterns fails to type-check, we'll report
// an error at that point. Here, just skip it and keep looking
// for more errors.
let children = subpats
.iter()
.filter_map(|subpat| {
self.translate_pattern(tyenv, subpat, expected_ty, bindings)
})
.collect();
Some(Pattern::And(expected_ty, children))
}
&ast::Pattern::BindPattern {
ref var,
ref subpat,
pos,
} => {
let subpat = self.translate_pattern(tyenv, subpat, expected_ty, bindings)?;
// The sub-pattern's type should be `expected_ty`. If it isn't,
// we've already reported a type error about it, but continue
// using the type we actually found in hopes that we'll
// generate fewer follow-on error messages.
let ty = subpat.ty();
let name = tyenv.intern_mut(var);
if bindings.lookup(name).is_some() {
tyenv.report_error(
pos,
format!("Re-bound variable name in LHS pattern: '{}'", var.0),
);
// Try to keep going.
}
let id = bindings.add_var(name, ty);
Some(Pattern::BindPattern(ty, id, Box::new(subpat)))
}
&ast::Pattern::Var { ref var, pos } => {
// Look up the variable; if it has already been bound,
// then this becomes a `Var` node (which matches the
// existing bound value), otherwise it becomes a
// `BindPattern` with a wildcard subpattern to capture
// at this location.
let name = tyenv.intern_mut(var);
match bindings.lookup(name) {
None => {
let id = bindings.add_var(name, expected_ty);
Some(Pattern::BindPattern(
expected_ty,
id,
Box::new(Pattern::Wildcard(expected_ty)),
))
}
Some(bv) => {
if expected_ty != bv.ty {
tyenv.report_error(
pos,
format!(
"Mismatched types: pattern expects type '{}' but already-bound var '{}' has type '{}'",
tyenv.types[expected_ty.index()].name(tyenv),
var.0,
tyenv.types[bv.ty.index()].name(tyenv),
),
);
// Try to keep going for more errors.
}
Some(Pattern::Var(bv.ty, bv.id))
}
}
}
&ast::Pattern::Term {
ref sym,
ref args,
pos,
} => {
// Look up the term.
let tid = match self.get_term_by_name(tyenv, sym) {
Some(t) => t,
None => {
tyenv.report_error(pos, format!("Unknown term in pattern: '{}'", sym.0));
return None;
}
};
let termdata = &self.terms[tid.index()];
// Get the return type and arg types. Verify the
// expected type of this pattern, if any, against the
// return type of the term. Insert an implicit
// converter if needed.
let ret_ty = termdata.ret_ty;
if expected_ty != ret_ty {
// Can we do an implicit type conversion? Look
// up the converter term, if any. If one has
// been registered, and the term has an
// extractor, then build an expanded AST node
// right here and recurse on it.
if let Some(expanded_pattern) =
self.maybe_implicit_convert_pattern(tyenv, pat, ret_ty, expected_ty)
{
return self.translate_pattern(
tyenv,
&expanded_pattern,
expected_ty,
bindings,
);
}
tyenv.report_error(
pos,
format!(
"Mismatched types: pattern expects type '{}' but term has return type '{}'",
tyenv.types[expected_ty.index()].name(tyenv),
tyenv.types[ret_ty.index()].name(tyenv),
),
);
// Try to keep going for more errors.
}
termdata.check_args_count(args, tyenv, pos, sym);
// TODO: check that multi-extractors are only used in terms declared `multi`
match &termdata.kind {
TermKind::EnumVariant { .. } => {}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::ExternalExtractor { .. }),
..
} => {}
TermKind::Decl {
extractor_kind: Some(ExtractorKind::InternalExtractor { ref template }),
..
} => {
if self.expand_internal_extractors {
// Expand the extractor macro! We create a map
// from macro args to AST pattern trees and
// then evaluate the template with these
// substitutions.
log!("internal extractor macro args = {:?}", args);
let pat = template.subst_macro_args(&args)?;
return self.translate_pattern(tyenv, &pat, expected_ty, bindings);
}
}
TermKind::Decl {
extractor_kind: None,
..
} => {
tyenv.report_error(
pos,
format!(
"Cannot use term '{}' that does not have a defined extractor in a \
left-hand side pattern",
sym.0
),
);
}
}
let subpats = self.translate_args(args, termdata, tyenv, bindings);
Some(Pattern::Term(ret_ty, tid, subpats))
}
&ast::Pattern::MacroArg { .. } => unreachable!(),
}
}
fn translate_args(
&self,
args: &Vec<ast::Pattern>,
termdata: &Term,
tyenv: &mut TypeEnv,
bindings: &mut Bindings,
) -> Vec<Pattern> {
args.iter()
.zip(termdata.arg_tys.iter())
.filter_map(|(arg, &arg_ty)| self.translate_pattern(tyenv, arg, arg_ty, bindings))
.collect()
}
fn maybe_implicit_convert_expr(
&self,
tyenv: &mut TypeEnv,
expr: &ast::Expr,
inner_ty: TypeId,
outer_ty: TypeId,
) -> Option<ast::Expr> {
// Is there a converter for this type mismatch?
if let Some(converter_term) = self.converters.get(&(inner_ty, outer_ty)) {
if self.terms[converter_term.index()].has_constructor() {
let converter_ident = ast::Ident(
tyenv.syms[self.terms[converter_term.index()].name.index()].clone(),
expr.pos(),
);
return Some(ast::Expr::Term {
sym: converter_ident,
pos: expr.pos(),
args: vec![expr.clone()],
});
}
}
None
}
fn translate_expr(
&self,
tyenv: &mut TypeEnv,
expr: &ast::Expr,
ty: Option<TypeId>,
bindings: &mut Bindings,
root_flags: TermFlags,
) -> Option<Expr> {
log!("translate_expr: {:?}", expr);
match expr {
&ast::Expr::Term {
ref sym,
ref args,
pos,
} => {
// Look up the term.
let name = tyenv.intern_mut(&sym);
let tid = match self.term_map.get(&name) {
Some(&t) => t,
None => {
// Maybe this was actually a variable binding and the user has placed
// parens around it by mistake? (See #4775.)
if bindings.lookup(name).is_some() {
tyenv.report_error(
pos,
format!(
"Unknown term in expression: '{}'. Variable binding under this name exists; try removing the parens?", sym.0));
} else {
tyenv.report_error(
pos,
format!("Unknown term in expression: '{}'", sym.0),
);
}
return None;
}
};
let termdata = &self.terms[tid.index()];
// Get the return type and arg types. Verify the
// expected type of this pattern, if any, against the
// return type of the term, and determine whether we
// are doing an implicit conversion. Report an error
// if types don't match and no conversion is possible.
let ret_ty = termdata.ret_ty;
let ty = if ty.is_some() && ret_ty != ty.unwrap() {
// Is there a converter for this type mismatch?
if let Some(expanded_expr) =
self.maybe_implicit_convert_expr(tyenv, expr, ret_ty, ty.unwrap())
{
return self.translate_expr(
tyenv,
&expanded_expr,
ty,
bindings,
root_flags,
);
}
tyenv.report_error(
pos,
format!("Mismatched types: expression expects type '{}' but term has return type '{}'",
tyenv.types[ty.unwrap().index()].name(tyenv),
tyenv.types[ret_ty.index()].name(tyenv)));
// Keep going, to discover more errors.
ret_ty
} else {
ret_ty
};
if let TermKind::Decl { flags, .. } = &termdata.kind {
// On the left-hand side of a rule or in a pure term, only pure terms may be
// used.
let pure_required = root_flags.pure;
if pure_required && !flags.pure {
tyenv.report_error(
pos,
format!(
"Used non-pure constructor '{}' in pure expression context",
sym.0
),
);
}
// Multi-terms may only be used inside other multi-terms.
if !root_flags.multi && flags.multi {
tyenv.report_error(
pos,
format!(
"Used multi-constructor '{}' but this rule is not in a multi-term",
sym.0
),
);
}
// Partial terms may always be used on the left-hand side of a rule. On the
// right-hand side they may only be used inside other partial terms.
let partial_allowed = root_flags.partial;
if !partial_allowed && flags.partial {
tyenv.report_error(
pos,
format!(
"Rule can't use partial constructor '{}' on RHS; \
try moving it to if-let{}",
sym.0,
if root_flags.multi {
""
} else {
" or make this rule's term partial too"
}
),
);
}
}
termdata.check_args_count(args, tyenv, pos, sym);
// Resolve subexpressions.
let subexprs = args
.iter()
.zip(termdata.arg_tys.iter())
.filter_map(|(arg, &arg_ty)| {
self.translate_expr(tyenv, arg, Some(arg_ty), bindings, root_flags)
})
.collect();
Some(Expr::Term(ty, tid, subexprs))
}
&ast::Expr::Var { ref name, pos } => {
let sym = tyenv.intern_mut(name);
// Look through bindings, innermost (most recent) first.
let bv = match bindings.lookup(sym) {
None => {
tyenv.report_error(pos, format!("Unknown variable '{}'", name.0));
return None;
}
Some(bv) => bv,
};
// Verify type. Maybe do an implicit conversion.
if ty.is_some() && bv.ty != ty.unwrap() {
// Is there a converter for this type mismatch?
if let Some(expanded_expr) =
self.maybe_implicit_convert_expr(tyenv, expr, bv.ty, ty.unwrap())
{
return self.translate_expr(
tyenv,
&expanded_expr,
ty,
bindings,
root_flags,
);
}
tyenv.report_error(
pos,
format!(
"Variable '{}' has type {} but we need {} in context",
name.0,
tyenv.types[bv.ty.index()].name(tyenv),
tyenv.types[ty.unwrap().index()].name(tyenv)
),
);
}
Some(Expr::Var(bv.ty, bv.id))
}
&ast::Expr::ConstBool { val, pos } => {
match ty {
Some(ty) if ty != TypeId::BOOL => tyenv.report_error(
pos,
format!(
"Boolean literal '{val}' has type {} but we need {} in context",
BuiltinType::Bool.name(),
tyenv.types[ty.index()].name(tyenv)
),
),
Some(..) | None => {}
};
Some(Expr::ConstBool(TypeId::BOOL, val))
}
&ast::Expr::ConstInt { val, pos } => {
let Some(ty) = ty else {
tyenv.report_error(
pos,
"integer literal in a context that needs an explicit type".to_string(),
);
return None;
};
let typ = &tyenv.types[ty.index()];
if !typ.is_int() && !typ.is_prim() {
tyenv.report_error(
pos,
format!(
"expected non-integer type {}, but found integer literal '{}'",
tyenv.types[ty.index()].name(tyenv),
val,
),
);
}
Some(Expr::ConstInt(ty, val))
}
&ast::Expr::ConstPrim { ref val, pos } => {
let val = tyenv.intern_mut(val);
let const_ty = match tyenv.const_types.get(&val) {
Some(ty) => *ty,
None => {
tyenv.report_error(pos, "Unknown constant");
return None;
}
};
if ty.is_some() && const_ty != ty.unwrap() {
tyenv.report_error(
pos,
format!(
"Constant '{}' has wrong type: expected {}, but is actually {}",
tyenv.syms[val.index()],
tyenv.types[ty.unwrap().index()].name(tyenv),
tyenv.types[const_ty.index()].name(tyenv)
),
);
return None;
}
Some(Expr::ConstPrim(const_ty, val))
}
&ast::Expr::Let {
ref defs,
ref body,
pos,
} => {
bindings.enter_scope();
// For each new binding...
let mut let_defs = vec![];
for def in defs {
// Check that the given variable name does not already exist.
let name = tyenv.intern_mut(&def.var);
// Look up the type.
let tid = match tyenv.get_type_by_name(&def.ty) {
Some(tid) => tid,
None => {
tyenv.report_error(
pos,
format!("Unknown type {} for variable '{}'", def.ty.0, def.var.0),
);
continue;
}
};
// Evaluate the variable's value.
let val = Box::new(unwrap_or_continue!(self.translate_expr(
tyenv,
&def.val,
Some(tid),
bindings,
root_flags,
)));
// Bind the var with the given type.
let id = bindings.add_var(name, tid);
let_defs.push((id, tid, val));
}
// Evaluate the body, expecting the type of the overall let-expr.
let body = Box::new(self.translate_expr(tyenv, body, ty, bindings, root_flags)?);
let body_ty = body.ty();
// Pop the bindings.
bindings.exit_scope();
Some(Expr::Let {
ty: body_ty,
bindings: let_defs,
body,
})
}
}
}
fn translate_iflet(
&self,
tyenv: &mut TypeEnv,
iflet: &ast::IfLet,
bindings: &mut Bindings,
root_flags: TermFlags,
) -> Option<IfLet> {
// Translate the expr first. The `if-let` and `if` forms are part of the left-hand side of
// the rule.
let rhs = self.translate_expr(tyenv, &iflet.expr, None, bindings, root_flags.on_lhs())?;
let lhs = self.translate_pattern(tyenv, &iflet.pattern, rhs.ty(), bindings)?;
Some(IfLet { lhs, rhs })
}
/// Lookup term by name.
pub fn get_term_by_name(&self, tyenv: &TypeEnv, sym: &ast::Ident) -> Option<TermId> {
tyenv
.intern(sym)
.and_then(|sym| self.term_map.get(&sym))
.copied()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::ast::Ident;
use crate::lexer::Lexer;
use crate::parser::parse;
#[test]
fn build_type_env() {
let text = r"
(type UImm8 (primitive UImm8))
(type A extern (enum (B (f1 u32) (f2 u32)) (C (f1 u32))))
";
let ast = parse(Lexer::new(0, text).unwrap()).expect("should parse");
let tyenv = TypeEnv::from_ast(&ast).expect("should not have type-definition errors");
let sym_a = tyenv
.intern(&Ident("A".to_string(), Default::default()))
.unwrap();
let sym_b = tyenv
.intern(&Ident("B".to_string(), Default::default()))
.unwrap();
let sym_c = tyenv
.intern(&Ident("C".to_string(), Default::default()))
.unwrap();
let sym_a_b = tyenv
.intern(&Ident("A.B".to_string(), Default::default()))
.unwrap();
let sym_a_c = tyenv
.intern(&Ident("A.C".to_string(), Default::default()))
.unwrap();
let sym_uimm8 = tyenv
.intern(&Ident("UImm8".to_string(), Default::default()))
.unwrap();
let sym_f1 = tyenv
.intern(&Ident("f1".to_string(), Default::default()))
.unwrap();
let sym_f2 = tyenv
.intern(&Ident("f2".to_string(), Default::default()))
.unwrap();
assert_eq!(tyenv.type_map.get(&sym_uimm8).unwrap(), &TypeId(13));
assert_eq!(tyenv.type_map.get(&sym_a).unwrap(), &TypeId(14));
let expected_types = vec![
Type::Primitive(
TypeId(13),
sym_uimm8,
Pos {
file: 0,
offset: 19,
},
),
Type::Enum {
name: sym_a,
id: TypeId(14),
is_extern: true,
is_nodebug: false,
variants: vec![
Variant {
name: sym_b,
fullname: sym_a_b,
id: VariantId(0),
fields: vec![
Field {
name: sym_f1,
id: FieldId(0),
ty: TypeId::U32,
},
Field {
name: sym_f2,
id: FieldId(1),
ty: TypeId::U32,
},
],
},
Variant {
name: sym_c,
fullname: sym_a_c,
id: VariantId(1),
fields: vec![Field {
name: sym_f1,
id: FieldId(0),
ty: TypeId::U32,
}],
},
],
pos: Pos {
file: 0,
offset: 62,
},
},
];
assert_eq!(
tyenv.types.len(),
expected_types.len() + BuiltinType::ALL.len()
);
for (i, (actual, expected)) in tyenv
.types
.iter()
.skip(BuiltinType::ALL.len())
.zip(&expected_types)
.enumerate()
{
assert_eq!(expected, actual, "`{i}`th type is not equal!");
}
}
}