summaryrefslogtreecommitdiff
path: root/tests/bugs/glsl-vk-binding-define.hlsl.expected
diff options
context:
space:
mode:
Diffstat (limited to 'tests/bugs/glsl-vk-binding-define.hlsl.expected')
0 files changed, 0 insertions, 0 deletions
'#n61'>61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777
#include "slang-parser.h"

#include <assert.h>
#include <float.h>

#include "slang-compiler.h"
#include "slang-lookup.h"
#include "slang-visitor.h"

#include "../core/slang-semantic-version.h"

namespace Slang
{
    // pre-declare
    static Name* getName(Parser* parser, String const& text);

    // Helper class useful to build a list of modifiers. 
    struct ModifierListBuilder
    {
        ModifierListBuilder()
        {
            m_next = &m_result;
        }
        void add(Modifier* modifier)
        {
            // Doesn't handle SharedModifiers
            SLANG_ASSERT(as<SharedModifiers>(modifier) == nullptr);

            // Splice at end
            *m_next = modifier;
            m_next = &modifier->next;
        }
        template <typename T>
        T* find() const
        {
            Modifier* cur = m_result;
            while (cur)
            {
                T* castCur = as<T>(cur);
                if (castCur)
                {
                    return castCur;
                }
                cur = cur->next;
            }
            return nullptr;
        }
        template <typename T>
        bool hasType() const
        {
            return find<T>() != nullptr;
        }
        Modifier* getFirst() { return m_result; };
    protected:

        Modifier* m_result = nullptr;
        Modifier** m_next;
    };

    enum Precedence : int
    {
        Invalid = -1,
        Comma,
        Assignment,
        TernaryConditional,
        LogicalOr,
        LogicalAnd,
        BitOr,
        BitXor,
        BitAnd,
        EqualityComparison,
        RelationalComparison,
        BitShift,
        Additive,
        Multiplicative,
        Prefix,
        Postfix,
    };

    // TODO: implement two pass parsing for file reference and struct type recognition

    class Parser
    {
    public:
        NamePool*       namePool;
        SourceLanguage  sourceLanguage;
        ASTBuilder*     astBuilder;

        NamePool* getNamePool() { return namePool; }
        SourceLanguage getSourceLanguage() { return sourceLanguage; }

        int anonymousCounter = 0;

        // Numbers of times we are peeking the same token at `ReadToken` without advancing in
        // recover mode.
        int sameTokenPeekedTimes = 0;

        Scope* outerScope = nullptr;
        Scope* currentScope = nullptr;

        bool hasSeenCompletionToken = false;

        TokenReader tokenReader;
        DiagnosticSink* sink;
        SourceLoc lastErrorLoc;

        int genericDepth = 0;

        // Have we seen any `import` declarations? If so, we need
        // to parse function bodies completely, even if we are in
        // "rewrite" mode.
        bool haveSeenAnyImportDecls = false;

        // Is the parser in a "recovering" state?
        // During recovery we don't emit additional errors, until we find
        // a token that we expected, when we exit recovery.
        bool isRecovering = false;

        void FillPosition(SyntaxNode * node)
        {
            node->loc = tokenReader.peekLoc();
        }
        void PushScope(ContainerDecl* containerDecl)
        {
            // TODO(JS):
            // 
            // Previously Scope was ref counted. This meant that if a scope was pushed, but not used when popped
            // it's memory would be freed.
            //
            // Here the memory is consumed and will not be freed until the astBuilder goes out of scope.

            Scope* newScope = astBuilder->create<Scope>();
            newScope->containerDecl = containerDecl;
            newScope->parent = currentScope;
            currentScope = newScope;
            containerDecl->ownedScope = newScope;
        }

        void pushScopeAndSetParent(ContainerDecl* containerDecl)
        {
            containerDecl->parentDecl = currentScope->containerDecl;
            PushScope(containerDecl);
        }

        void PopScope()
        {
            currentScope = currentScope->parent;
        }
        Parser(
            ASTBuilder* inAstBuilder,
            TokenSpan const& _tokens,
            DiagnosticSink * sink,
            Scope*           outerScope)
            : tokenReader(_tokens)
            , astBuilder(inAstBuilder)
            , sink(sink)
            , outerScope(outerScope)
        {}
        Parser(const Parser & other) = default;

        //Session* getSession() { return m_session; }

        Token ReadToken();
        Token readTokenImpl(TokenType type, bool forceSkippingToClosingToken);
        Token ReadToken(TokenType type);
        // Same as `ReadToken`, but force skip to the matching closing token on error.
        Token ReadMatchingToken(TokenType type);
        Token ReadToken(const char* string);

        bool LookAheadToken(TokenType type);
        bool LookAheadToken(const char* string);

        bool LookAheadToken(TokenType type, int offset);
        bool LookAheadToken(const char* string, int offset);

        void parseSourceFile(ModuleDecl* program);
        Decl* ParseStruct();
        ClassDecl* ParseClass();
        Stmt* ParseStatement();
        Stmt* parseBlockStatement();
        Stmt* parseLabelStatement();
        DeclStmt* parseVarDeclrStatement(Modifiers modifiers);
        IfStmt* parseIfStatement();
        ForStmt* ParseForStatement();
        WhileStmt* ParseWhileStatement();
        DoWhileStmt* ParseDoWhileStatement();
        BreakStmt* ParseBreakStatement();
        ContinueStmt* ParseContinueStatement();
        ReturnStmt* ParseReturnStatement();
        ExpressionStmt* ParseExpressionStatement();
        Expr* ParseExpression(Precedence level = Precedence::Comma);

        // Parse an expression that might be used in an initializer or argument context, so we should avoid operator-comma
        inline Expr*			ParseInitExpr() { return ParseExpression(Precedence::Assignment); }
        inline Expr*			ParseArgExpr()  { return ParseExpression(Precedence::Assignment); }

        Expr*				ParseLeafExpression();
        ParamDecl*					ParseParameter();
        Expr*				ParseType();
        TypeExp										ParseTypeExp();

        Parser & operator = (const Parser &) = delete;

        // Helper to issue diagnose message that filters out errors for the same token.
        template <typename P, typename... Args>
        void diagnose(P const& pos, DiagnosticInfo const& info, Args const&... args)
        {
            auto loc = getDiagnosticPos(pos);
            if (loc != lastErrorLoc)
            {
                sink->diagnose(pos, info, args...);
                lastErrorLoc = loc;
            }
        }
    };

    // Forward Declarations

    enum class MatchedTokenType
    {
        Parentheses,
        SquareBrackets,
        CurlyBraces,
        File,
    };

        /// Parse declarations making up the body of `parent`, up to a matching token for `matchType`
    static void parseDecls(
        Parser*             parser,
        ContainerDecl*      parent,
        MatchedTokenType    matchType);

        /// Parse a body consisting of declarations enclosed in `{}`, as the children of `parent`.
    static void parseDeclBody(
        Parser*         parser,
        ContainerDecl*  parent);

    static Decl* parseEnumDecl(Parser* parser);

    static Modifiers _parseOptSemantics(
        Parser* parser);

    static void _parseOptSemantics(
        Parser* parser,
        Decl*	decl);

    static DeclBase* ParseDecl(
        Parser*			parser,
        ContainerDecl*	containerDecl);

    static Decl* ParseSingleDecl(
        Parser*			parser,
        ContainerDecl*	containerDecl);

    static void parseModernParamList(
        Parser*         parser,
        CallableDecl*   decl);

    static TokenType peekTokenType(Parser* parser);

    static Expr* _parseGenericArg(Parser* parser);

    //

    static void Unexpected(
        Parser*     parser)
    {
        // Don't emit "unexpected token" errors if we are in recovering mode
        if (!parser->isRecovering)
        {
            parser->diagnose(parser->tokenReader.peekLoc(), Diagnostics::unexpectedToken,
                parser->tokenReader.peekTokenType());

            // Switch into recovery mode, to suppress additional errors
            parser->isRecovering = true;
        }
    }

    static void Unexpected(
        Parser*     parser,
        char const* expected)
    {
        // Don't emit "unexpected token" errors if we are in recovering mode
        if (!parser->isRecovering)
        {
            parser->sink->diagnose(parser->tokenReader.peekLoc(), Diagnostics::unexpectedTokenExpectedTokenName,
                parser->tokenReader.peekTokenType(),
                expected);

            // Switch into recovery mode, to suppress additional errors
            parser->isRecovering = true;
        }
    }

    static void Unexpected(
        Parser*     parser,
        TokenType    expected)
    {
        // Don't emit "unexpected token" errors if we are in recovering mode
        if (!parser->isRecovering)
        {
            if (parser->lastErrorLoc != parser->tokenReader.peekLoc())
            {
                parser->sink->diagnose(
                    parser->tokenReader.peekLoc(),
                    Diagnostics::unexpectedTokenExpectedTokenType,
                    parser->tokenReader.peekTokenType(),
                    expected);
                parser->lastErrorLoc = parser->tokenReader.peekLoc();
            }
            // Switch into recovery mode, to suppress additional errors
            parser->isRecovering = true;
        }
    }

    static TokenType SkipToMatchingToken(TokenReader* reader, TokenType tokenType);

    // Skip a singel balanced token, which is either a single token in
    // the common case, or a matched pair of tokens for `()`, `[]`, and `{}`
    static TokenType SkipBalancedToken(
        TokenReader* reader)
    {
        TokenType tokenType = reader->advanceToken().type;
        switch (tokenType)
        {
        default:
            break;

        case TokenType::LParent:    tokenType = SkipToMatchingToken(reader, TokenType::RParent);    break;
        case TokenType::LBrace:     tokenType = SkipToMatchingToken(reader, TokenType::RBrace);     break;
        case TokenType::LBracket:   tokenType = SkipToMatchingToken(reader, TokenType::RBracket);   break;
        }
        return tokenType;
    }

    // Skip balanced
    static TokenType SkipToMatchingToken(
        TokenReader*                reader,
        TokenType    tokenType)
    {
        for (;;)
        {
            if (reader->isAtEnd()) return TokenType::EndOfFile;
            if (reader->peekTokenType() == tokenType)
            {
                reader->advanceToken();
                return tokenType;
            }
            SkipBalancedToken(reader);
        }
    }

    // Is the given token type one that is used to "close" a
    // balanced construct.
    static bool IsClosingToken(TokenType tokenType)
    {
        switch (tokenType)
        {
        case TokenType::EndOfFile:
        case TokenType::RBracket:
        case TokenType::RParent:
        case TokenType::RBrace:
            return true;

        default:
            return false;
        }
    }


    // Expect an identifier token with the given content, and consume it.
    Token Parser::ReadToken(const char* expected)
    {
        if (tokenReader.peekTokenType() == TokenType::Identifier
                && tokenReader.peekToken().getContent() == expected)
        {
            isRecovering = false;
            return tokenReader.advanceToken();
        }

        if (!isRecovering)
        {
            Unexpected(this, expected);
            return tokenReader.peekToken();
        }
        else
        {
            // Try to find a place to recover
            for (;;)
            {
                // The token we expected?
                // Then exit recovery mode and pretend like all is well.
                if (tokenReader.peekTokenType() == TokenType::Identifier
                    && tokenReader.peekToken().getContent() == expected)
                {
                    isRecovering = false;
                    return tokenReader.advanceToken();
                }


                // Don't skip past any "closing" tokens.
                if (IsClosingToken(tokenReader.peekTokenType()))
                {
                    return tokenReader.peekToken();
                }

                // Skip balanced tokens and try again.
                SkipBalancedToken(&tokenReader);
            }
        }
    }

    Token Parser::ReadToken()
    {
        return tokenReader.advanceToken();
    }

    static bool TryRecover(
        Parser*                         parser,
        TokenType const* recoverBefore,
        int                             recoverBeforeCount,
        TokenType const* recoverAfter,
        int                             recoverAfterCount)
    {
        if (!parser->isRecovering)
            return true;

        // Determine if we are looking for common closing tokens,
        // so that we can know whether or we are allowed to skip
        // over them.

        bool lookingForEOF = false;
        bool lookingForRCurly = false;
        bool lookingForRParen = false;
        bool lookingForRSquare = false;

        for (int ii = 0; ii < recoverBeforeCount; ++ii)
        {
            switch (recoverBefore[ii])
            {
            default:
                break;

            case TokenType::EndOfFile:  lookingForEOF       = true; break;
            case TokenType::RBrace:     lookingForRCurly    = true; break;
            case TokenType::RParent:    lookingForRParen    = true; break;
            case TokenType::RBracket:   lookingForRSquare   = true; break;
            }
        }
        for (int ii = 0; ii < recoverAfterCount; ++ii)
        {
            switch (recoverAfter[ii])
            {
            default:
                break;

            case TokenType::EndOfFile:  lookingForEOF       = true; break;
            case TokenType::RBrace:     lookingForRCurly    = true; break;
            case TokenType::RParent:    lookingForRParen    = true; break;
            case TokenType::RBracket:   lookingForRSquare   = true; break;
            }
        }

        TokenReader* tokenReader = &parser->tokenReader;
        for (;;)
        {
            TokenType peek = tokenReader->peekTokenType();

            // Is the next token in our recover-before set?
            // If so, then we have recovered successfully!
            for (int ii = 0; ii < recoverBeforeCount; ++ii)
            {
                if (peek == recoverBefore[ii])
                {
                    parser->isRecovering = false;
                    return true;
                }
            }

            // If we are looking at a token in our recover-after set,
            // then consume it and recover
            for (int ii = 0; ii < recoverAfterCount; ++ii)
            {
                if (peek == recoverAfter[ii])
                {
                    tokenReader->advanceToken();
                    parser->isRecovering = false;
                    return true;
                }
            }

            // Don't try to skip past end of file
            if (peek == TokenType::EndOfFile)
                return false;

            switch (peek)
            {
            // Don't skip past simple "closing" tokens, *unless*
            // we are looking for a closing token
            case TokenType::RParent:
            case TokenType::RBracket:
                if (lookingForRParen || lookingForRSquare || lookingForRCurly || lookingForEOF)
                {
                    // We are looking for a closing token, so it is okay to skip these
                }
                else
                    return false;
                break;

            // Don't skip a `}`, to avoid spurious errors,
            // with the exception of when we are looking for EOF
            case TokenType::RBrace:
                if (lookingForRCurly || lookingForEOF)
                {
                    // We are looking for end-of-file, so it is okay to skip here
                }
                else
                {
                    return false;
                }
            }

            // Skip balanced tokens and try again.
            TokenType skipped = SkipBalancedToken(tokenReader);

            // If we happened to find a matched pair of tokens, and
            // the end of it was a token we were looking for,
            // then recover here
            for (int ii = 0; ii < recoverAfterCount; ++ii)
            {
                if (skipped == recoverAfter[ii])
                {
                    parser->isRecovering = false;
                    return true;
                }
            }
        }
    }

    static bool TryRecoverBefore(
        Parser*                     parser,
        TokenType    before0)
    {
        TokenType recoverBefore[] = { before0 };
        return TryRecover(parser, recoverBefore, 1, nullptr, 0);
    }

    // Default recovery strategy, to use inside `{}`-delimeted blocks.
    static bool TryRecover(
        Parser*                     parser)
    {
        TokenType recoverBefore[] = { TokenType::RBrace };
        TokenType recoverAfter[] = { TokenType::Semicolon };
        return TryRecover(parser, recoverBefore, 1, recoverAfter, 1);
    }

    Token Parser::readTokenImpl(TokenType expected, bool forceSkippingToClosingToken)
    {
        if (tokenReader.peekTokenType() == expected)
        {
            isRecovering = false;
            sameTokenPeekedTimes = 0;
            return tokenReader.advanceToken();
        }

        if (!isRecovering)
        {
            Unexpected(this, expected);
            if (!forceSkippingToClosingToken)
                return tokenReader.peekToken();
            switch (expected)
            {
            case TokenType::RBrace:
            case TokenType::RParent:
            case TokenType::RBracket:
                break;
            default:
                return tokenReader.peekToken();
            }
        }

        // Try to find a place to recover
        if (TryRecoverBefore(this, expected))
        {
            isRecovering = false;
            return tokenReader.advanceToken();
        }
        // This could be dangerous: if `ReadToken()` is being called
        // in a loop we may never make forward progress, so we use
        // a counter to limit the maximum amount of times we are allowed
        // to peek the same token. If the outter parsing logic is
        // correct, we will pop back to the right level. If there are
        // erroneous parsing logic, this counter is to prevent us
        // looping infinitely.
        static const int kMaxTokenPeekCount = 64;
        sameTokenPeekedTimes++;
        if (sameTokenPeekedTimes < kMaxTokenPeekCount)
            return tokenReader.peekToken();
        else
        {
            sameTokenPeekedTimes = 0;
            return tokenReader.advanceToken();
        }
    }

    Token Parser::ReadToken(TokenType expected)
    {
        return readTokenImpl(expected, false);
    }

    Token Parser::ReadMatchingToken(TokenType expected)
    {
        return readTokenImpl(expected, true);
    }

    bool Parser::LookAheadToken(const char* string, int offset)
    {
        TokenReader r = tokenReader;
        for (int ii = 0; ii < offset; ++ii)
            r.advanceToken();

        return r.peekTokenType() == TokenType::Identifier
            && r.peekToken().getContent() == string;
}

    bool Parser::LookAheadToken(TokenType type, int offset)
    {
        TokenReader r = tokenReader;
        for (int ii = 0; ii < offset; ++ii)
            r.advanceToken();

        return r.peekTokenType() == type;
    }

    bool Parser::LookAheadToken(TokenType type)
    {
        return tokenReader.peekTokenType() == type;
    }

    bool Parser::LookAheadToken(const char* string)
    {
        const auto& token = tokenReader.peekToken();
        return token.type == TokenType::Identifier && token.getContent() == string;
    }

    // Consume a token and return true it if matches, otherwise false
    bool AdvanceIf(Parser* parser, TokenType tokenType)
    {
        if (parser->LookAheadToken(tokenType))
        {
            parser->ReadToken();
            return true;
        }
        return false;
    }

    bool AdvanceIf(Parser* parser, TokenType tokenType, Token* outToken)
    {
        if (parser->LookAheadToken(tokenType))
        {
            *outToken = parser->ReadToken();
            return true;
        }
        return false;
    }

    // Consume a token and return true it if matches, otherwise false
    bool AdvanceIf(Parser* parser, char const* text)
    {
        if (parser->LookAheadToken(text))
        {
            parser->ReadToken();
            return true;
        }
        return false;
    }

        /// Information on how to parse certain pairs of matches tokens
    struct MatchedTokenInfo
    {
            /// The token type that opens the pair
        TokenType openTokenType;

            /// The token type that closes the pair
        TokenType closeTokenType;

            /// A list of token types that should lead the parser
            /// to abandon its search for a matchign closing token
            /// (terminated by `TokenType::EndOfFile`).
        TokenType const* bailAtCloseTokens;
    };
    static const TokenType kMatchedToken_BailAtEOF[] = { TokenType::EndOfFile };
    static const TokenType kMatchedToken_BailAtCurlyBraceOrEOF[] = { TokenType::RBrace, TokenType::EndOfFile };
    static const MatchedTokenInfo kMatchedTokenInfos[] =
    {
        { TokenType::LParent,   TokenType::RParent,     kMatchedToken_BailAtCurlyBraceOrEOF },
        { TokenType::LBracket,  TokenType::RBracket,    kMatchedToken_BailAtCurlyBraceOrEOF },
        { TokenType::LBrace,    TokenType::RBrace,      kMatchedToken_BailAtEOF },
        { TokenType::Unknown,   TokenType::EndOfFile,   kMatchedToken_BailAtEOF },
    };

        /// Expect to enter a matched region starting with `tokenType`
        ///
        /// Returns `true` on a match and `false` if a region is not entered.
    bool beginMatch(Parser* parser, MatchedTokenType type)
    {
        auto& info = kMatchedTokenInfos[int(type)];
        bool result = peekTokenType(parser) == info.openTokenType;
        parser->ReadToken(info.openTokenType);
        return result;
    }

    // Consume a token and return true if it matches, otherwise check
    // for end-of-file and expect that token (potentially producing
    // an error) and return true to maintain forward progress.
    // Otherwise return false.
    bool AdvanceIfMatch(Parser* parser, MatchedTokenType type, Token* outToken)
    {
        // The behavior of the seatch for a match can depend on the
        // type of matches tokens we are parsing.
        //
        auto& info = kMatchedTokenInfos[int(type)];

        // First, if the parser is already in a state where it is recovering
        // from an earlier syntax error, we want to give it a fighting chance
        // to recover here, because we know a token type we are looking for.
        //
        // Basically, if the parser can skip ahead some number of tokens to
        // find a token of the correct type to close this matched list, then
        // we would like to do so.
        //
        // Note: this behavior does not mean that any syntax error in a list
        // will automatically skip the remainder of the list. The reason is
        // that most syntax lists have a separate or terminator (e.g., a
        // comma or semicolon), and reading in a separator will also serve
        // to recover the parser. The case here is only going to come up
        // when the lookahead for a separator/terminator already failed.
        //
        if (parser->isRecovering)
        {
            TryRecoverBefore(parser, info.closeTokenType);
        }

        // If the result of our recovery effort is that we are looking
        // at the token type we wanted, we can consume it and return,
        // with the parser happily recovered.
        //
        if (AdvanceIf(parser, info.closeTokenType, outToken))
            return true;

        // Otherwise, we know that we haven't yet recovered.
        // The challenge here is that `AdvanceIfMatch()` is almost always
        // called in a loop, and we need that loop to terminate at
        // some point.
        //
        // Each of the types of matched tokens is assocaited with a
        // list of token types where we should "bail" from our search
        // for a closing token and exit a nested construct.
        // In the simplest terms, when looking for `)` or `]` we will
        // bail on a `}` or end-of-file, while when looking for a `}`
        // we will only bail on an end-of-file.
        //
        auto nextTokenType = parser->tokenReader.peekTokenType();
        for(auto bailAtTokenTypePtr = info.bailAtCloseTokens;; bailAtTokenTypePtr++)
        {
            auto bailAtTokenType = *bailAtTokenTypePtr;
            if(nextTokenType == bailAtTokenType)
            {
                // If we are going to bail out of the loop here, then
                // we make sure to try to read the token type we were
                // originally looking for, even though we know it will
                // fail.
                //
                // If we are already in recovery mode, this will do nothing.
                // If we *aren't* in recovery mode, this step is what leads
                // the parser to output an error message like "expected
                // a `)`, found a `}`" which is pretty much exactly what
                // we want.
                //
                *outToken = parser->ReadToken(info.closeTokenType);
                return true;
            }

            // The list of token types that should cause us to "bail" on
            // our search is always terminated by the EOF token type, so
            // we don't want to read past that one.
            //
            if(bailAtTokenType == TokenType::EndOfFile)
                break;
        }
        return false;
    }

    bool AdvanceIfMatch(Parser* parser, MatchedTokenType type)
    {
        Token ignored;
        return AdvanceIfMatch(parser, type, &ignored);
    }

    NodeBase* parseTypeDef(Parser* parser, void* /*userData*/)
    {
        TypeDefDecl* typeDefDecl = parser->astBuilder->create<TypeDefDecl>();

        // TODO(tfoley): parse an actual declarator
        auto type = parser->ParseTypeExp();

        auto nameToken = parser->ReadToken(TokenType::Identifier);
        typeDefDecl->loc = nameToken.loc;

        typeDefDecl->nameAndLoc = NameLoc(nameToken);
        typeDefDecl->type = type;

        return typeDefDecl;
    }

    // Add a modifier to a list of modifiers being built
    static void AddModifier(Modifier*** ioModifierLink, Modifier* modifier)
    {
        Modifier**& modifierLink = *ioModifierLink;

        // We'd like to add the modifier to the end of the list,
        // but we need to be careful, in case there is a "shared"
        // section of modifiers for multiple declarations.
        //
        // TODO: This whole approach is a mess because we are "accidentally quadratic"
        // when adding many modifiers.
        for(;;)
        {
            // At end of the chain? Done.
            if(!*modifierLink)
                break;

            // About to look at shared modifiers? Done.
            Modifier* linkMod = *modifierLink;
            if(as<SharedModifiers>(linkMod))
            {
                break;
            }

            // Otherwise: keep traversing the modifier list.
            modifierLink = &(*modifierLink)->next;
        }

        // Splice the modifier into the linked list

        // We need to deal with the case where the modifier to
        // be spliced in might actually be a modifier *list*,
        // so that we actually want to splice in at the
        // end of the new list...
        auto spliceLink = &modifier->next;
        while(*spliceLink)
            spliceLink = &(*spliceLink)->next;

        // Do the splice.
        *spliceLink = *modifierLink;

        *modifierLink = modifier;
        modifierLink = &modifier->next;
    }

    void addModifier(
        ModifiableSyntaxNode*    syntax,
        Modifier*                modifier)
    {
        auto modifierLink = &syntax->modifiers.first;
        AddModifier(&modifierLink, modifier);
    }

    // 
    // '::'? identifier ('::' identifier)* 
    static Token parseAttributeName(Parser* parser)
    {
        const SourceLoc scopedIdSourceLoc = parser->tokenReader.peekLoc();

        // Strip initial :: if there is one
        const TokenType initialTokenType = parser->tokenReader.peekTokenType();
        if (initialTokenType == TokenType::Scope)
        {
            parser->ReadToken(TokenType::Scope); 
        }
        if (parser->LookAheadToken(TokenType::CompletionRequest))
            return parser->ReadToken();

        const Token firstIdentifier = parser->ReadToken(TokenType::Identifier);
        if (initialTokenType != TokenType::Scope && parser->tokenReader.peekTokenType() != TokenType::Scope)
        {
            return firstIdentifier;
        }

        // Build up scoped string
        StringBuilder scopedIdentifierBuilder;
        if (initialTokenType == TokenType::Scope)
        {
            scopedIdentifierBuilder.append('_'); 
        }
        scopedIdentifierBuilder.append(firstIdentifier.getContent());

        while (parser->tokenReader.peekTokenType() == TokenType::Scope)
        {
            parser->ReadToken(TokenType::Scope);
            scopedIdentifierBuilder.append('_'); 
            
            const Token nextIdentifier(parser->ReadToken(TokenType::Identifier));
            scopedIdentifierBuilder.append(nextIdentifier.getContent());
        }

        // Make a 'token'
        SourceManager* sourceManager = parser->sink->getSourceManager();
        const UnownedStringSlice scopedIdentifier(sourceManager->allocateStringSlice(scopedIdentifierBuilder.getUnownedSlice()));   
        Token token(TokenType::Identifier, scopedIdentifier, scopedIdSourceLoc);

        // Get the name pool
        auto namePool = parser->getNamePool();

        // Since it's an Identifier have to set the name.
        token.setName(namePool->getName(token.getContent()));

        return token;
    }

    // Parse HLSL-style `[name(arg, ...)]` style "attribute" modifiers
    static void ParseSquareBracketAttributes(Parser* parser, Modifier*** ioModifierLink)
    {
        parser->ReadToken(TokenType::LBracket);

        const bool hasDoubleBracket = AdvanceIf(parser, TokenType::LBracket);

        for(;;)
        {
            // Note: When parsing we just construct an AST node for an
            // "unchecked" attribute, and defer all detailed semantic
            // checking until later.
            //
            // An alternative would be to perform lookup of an `AttributeDecl`
            // at this point, similar to what we do for `SyntaxDecl`, but it
            // seems better to not complicate the parsing process any more.
            //

            Token nameToken = parseAttributeName(parser);

            UncheckedAttribute* modifier = parser->astBuilder->create<UncheckedAttribute>();
            modifier->keywordName = nameToken.getName();
            modifier->loc = nameToken.getLoc();
            modifier->scope = parser->currentScope;

            if (AdvanceIf(parser, TokenType::LParent))
            {
                // HLSL-style `[name(arg0, ...)]` attribute

                while (!AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
                {
                    auto arg = parser->ParseArgExpr();
                    if (arg)
                    {
                        modifier->args.add(arg);
                    }

                    if (AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
                        break;

                    parser->ReadToken(TokenType::Comma);
                }
            }
            AddModifier(ioModifierLink, modifier);


            if (AdvanceIfMatch(parser, MatchedTokenType::SquareBrackets))
                break;

            parser->ReadToken(TokenType::Comma);
            
        }

        if (hasDoubleBracket)
        {
            // Read the second ]
            parser->ReadToken(TokenType::RBracket);
        }
    }

    static TokenType peekTokenType(Parser* parser)
    {
        return parser->tokenReader.peekTokenType();
    }

        /// Peek the token `offset` tokens after the cursor
    static TokenType peekTokenType(Parser* parser, int offset)
    {
        TokenReader r = parser->tokenReader;
        for (int ii = 0; ii < offset; ++ii)
            r.advanceToken();
        return r.peekTokenType();
    }

    static Token advanceToken(Parser* parser)
    {
        return parser->ReadToken();
    }

    static Token peekToken(Parser* parser)
    {
        return parser->tokenReader.peekToken();
    }

    static SyntaxDecl* tryLookUpSyntaxDecl(
        Parser* parser,
        Name*   name)
    {
        // Let's look up the name and see what we find.

        auto lookupResult = lookUp(
            parser->astBuilder,
            nullptr, // no semantics visitor available yet
            name,
            parser->currentScope);

        // If we didn't find anything, or the result was overloaded,
        // then we aren't going to be able to extract a single decl.
        if(!lookupResult.isValid() || lookupResult.isOverloaded())
            return nullptr;

        auto decl = lookupResult.item.declRef.getDecl();
        if( auto syntaxDecl = as<SyntaxDecl>(decl) )
        {
            return syntaxDecl;
        }
        else
        {
            return nullptr;
        }
    }

    template<typename T>
    bool tryParseUsingSyntaxDecl(
        Parser*     parser,
        SyntaxDecl* syntaxDecl,
        T**  outSyntax)
    {
        if (!syntaxDecl)
            return false;

        if (!syntaxDecl->syntaxClass.isSubClassOf<T>())
            return false;

        // Consume the token that specified the keyword
        auto keywordToken = advanceToken(parser);

        NodeBase* parsedObject = syntaxDecl->parseCallback(parser, syntaxDecl->parseUserData);
        if (!parsedObject)
        {
            return false;
        }

        auto syntax = as<T>(parsedObject);
        if (syntax)
        {
            if (!syntax->loc.isValid())
            {
                syntax->loc = keywordToken.loc;
            }
        }
        else if (parsedObject)
        {
            // Something was parsed, but it didn't have the expected type!
            SLANG_DIAGNOSE_UNEXPECTED(parser->sink, keywordToken, "parser callback did not return the expected type");
        }

        *outSyntax = syntax;
        return true;
    }

    template<typename T>
    bool tryParseUsingSyntaxDecl(
        Parser*     parser,
        T**  outSyntax)
    {
        if (peekTokenType(parser) != TokenType::Identifier)
            return false;

        auto nameToken = peekToken(parser);
        auto name = nameToken.getName();

        auto syntaxDecl = tryLookUpSyntaxDecl(parser, name);

        if (!syntaxDecl)
            return false;

        return tryParseUsingSyntaxDecl(parser, syntaxDecl, outSyntax);
    }

    static Modifiers ParseModifiers(Parser* parser)
    {
        Modifiers modifiers;
        Modifier** modifierLink = &modifiers.first;
        for (;;)
        {
            SourceLoc loc = parser->tokenReader.peekLoc();

            switch (peekTokenType(parser))
            {
            default:
                // If we don't see a token type that we recognize, then
                // assume we are done with the modifier sequence.
                return modifiers;

            case TokenType::Identifier:
                {
                    // We see an identifier ahead, and it might be the name
                    // of a modifier keyword of some kind.

                    Token nameToken = peekToken(parser);

                    Modifier* parsedModifier = nullptr;
                    if (tryParseUsingSyntaxDecl<Modifier>(parser, &parsedModifier))
                    {
                        parsedModifier->keywordName = nameToken.getName();
                        if (!parsedModifier->loc.isValid())
                        {
                            parsedModifier->loc = nameToken.loc;
                        }

                        AddModifier(&modifierLink, parsedModifier);
                        continue;
                    }
                    else if (AdvanceIf(parser, "no_diff"))
                    {
                        parsedModifier = parser->astBuilder->create<NoDiffModifier>();
                        parsedModifier->keywordName = nameToken.getName();
                        parsedModifier->loc = nameToken.loc;
                        AddModifier(&modifierLink, parsedModifier);
                        continue;
                    }

                    // If there was no match for a modifier keyword, then we
                    // must be at the end of the modifier sequence
                    return modifiers;
                }
                break;

            // HLSL uses `[attributeName]` style for its modifiers, which closely
            // matches the C++ `[[attributeName]]` style.
            case TokenType::LBracket:
                ParseSquareBracketAttributes(parser, &modifierLink);
                break;
            }
        }
    }

    static Name* getName(Parser* parser, String const& text)
    {
        return parser->getNamePool()->getName(text);
    }

    static bool expect(Parser* parser, TokenType tokenType)
    {
        return parser->ReadToken(tokenType).type == tokenType;
    }

    static NameLoc expectIdentifier(Parser* parser)
    {
        if (!parser->hasSeenCompletionToken && parser->LookAheadToken(TokenType::CompletionRequest))
            parser->hasSeenCompletionToken = true;
        return NameLoc(parser->ReadToken(TokenType::Identifier));
    }

    static NodeBase* parseImportDecl(
        Parser* parser, void* /*userData*/)
    {
        parser->haveSeenAnyImportDecls = true;

        auto decl = parser->astBuilder->create<ImportDecl>();
        decl->scope = parser->currentScope;
        decl->startLoc = parser->tokenReader.peekLoc();

        if (peekTokenType(parser) == TokenType::StringLiteral)
        {
            auto nameToken = parser->ReadToken(TokenType::StringLiteral);
            auto nameString = getStringLiteralTokenValue(nameToken);
            auto moduleName = getName(parser, nameString);

            decl->moduleNameAndLoc = NameLoc(moduleName, nameToken.loc);
        }
        else
        {
            auto moduleNameAndLoc = expectIdentifier(parser);

            // We allow a dotted format for the name, as sugar
            if (peekTokenType(parser) == TokenType::Dot)
            {
                StringBuilder sb;
                sb << getText(moduleNameAndLoc.name);
                while (AdvanceIf(parser, TokenType::Dot))
                {
                    sb << "/";
                    sb << parser->ReadToken(TokenType::Identifier).getContent();
                }

                moduleNameAndLoc.name = getName(parser, sb.produceString());
            }

            decl->moduleNameAndLoc = moduleNameAndLoc;
        }
        decl->endLoc = parser->tokenReader.peekLoc();
        parser->ReadToken(TokenType::Semicolon);

        return decl;
    }

    static NameLoc ParseDeclName(
        Parser* parser)
    {
        Token nameToken;
        if (AdvanceIf(parser, "operator"))
        {
            nameToken = parser->ReadToken();
            switch (nameToken.type)
            {
            case TokenType::OpAdd: case TokenType::OpSub: case TokenType::OpMul: case TokenType::OpDiv:
            case TokenType::OpMod: case TokenType::OpNot: case TokenType::OpBitNot: case TokenType::OpLsh: case TokenType::OpRsh:
            case TokenType::OpEql: case TokenType::OpNeq: case TokenType::OpGreater: case TokenType::OpLess: case TokenType::OpGeq:
            case TokenType::OpLeq: case TokenType::OpAnd: case TokenType::OpOr: case TokenType::OpBitXor: case TokenType::OpBitAnd:
            case TokenType::OpBitOr: case TokenType::OpInc: case TokenType::OpDec:
            case TokenType::OpAddAssign:
            case TokenType::OpSubAssign:
            case TokenType::OpMulAssign:
            case TokenType::OpDivAssign:
            case TokenType::OpModAssign:
            case TokenType::OpShlAssign:
            case TokenType::OpShrAssign:
            case TokenType::OpOrAssign:
            case TokenType::OpAndAssign:
            case TokenType::OpXorAssign:

            // Note(tfoley): A bit of a hack:
            case TokenType::Comma:
            case TokenType::OpAssign:
                break;

            // Note(tfoley): Even more of a hack!
            case TokenType::QuestionMark:
                if (AdvanceIf(parser, TokenType::Colon))
                {
                    // Concat : onto ?
                    nameToken.setContent(UnownedStringSlice::fromLiteral("?:")); 
                    break;
                }
                ;       // fall-thru
            default:
                parser->sink->diagnose(nameToken.loc, Diagnostics::invalidOperator, nameToken);
                break;
            }

            return NameLoc(
                getName(parser, nameToken.getContent()),
                nameToken.loc);
        }
        else
        {
            nameToken = parser->ReadToken(TokenType::Identifier);
            return NameLoc(nameToken);
        }
    }

    // A "declarator" as used in C-style languages
    struct Declarator : RefObject
    {
        // Different cases of declarator appear as "flavors" here
        enum class Flavor
        {
            name,
            Pointer,
            Array,
        };
        Flavor flavor;
    };

    // The most common case of declarator uses a simple name
    struct NameDeclarator : Declarator
    {
        NameLoc nameAndLoc;
    };

    // A declarator that declares a pointer type
    struct PointerDeclarator : Declarator
    {
        // location of the `*` token
        SourceLoc starLoc;

        RefPtr<Declarator>				inner;
    };

    // A declarator that declares an array type
    struct ArrayDeclarator : Declarator
    {
        RefPtr<Declarator>				inner;

        // location of the `[` token
        SourceLoc openBracketLoc;

        // The expression that yields the element count, or NULL
        Expr*	elementCountExpr = nullptr;
    };

    // "Unwrapped" information about a declarator
    struct DeclaratorInfo
    {
        Expr*	    typeSpec = nullptr;
        NameLoc             nameAndLoc;
        Modifiers   semantics;
        Expr*	    initializer = nullptr;
    };

    // Add a member declaration to its container, and ensure that its
    // parent link is set up correctly.
    static void AddMember(ContainerDecl* container, Decl* member)
    {
        if (container && member)
        {
            member->parentDecl = container;
            container->members.add(member);
        }
    }

    static void AddMember(Scope* scope, Decl* member)
    {
        if (scope)
        {
            AddMember(scope->containerDecl, member);
        }
    }

    static Decl* ParseGenericParamDecl(
        Parser*             parser,
        GenericDecl* genericDecl)
    {
        // simple syntax to introduce a value parameter
        if (AdvanceIf(parser, "let"))
        {
            // default case is a type parameter
            auto paramDecl = parser->astBuilder->create<GenericValueParamDecl>();
            paramDecl->nameAndLoc = NameLoc(parser->ReadToken(TokenType::Identifier));
            if (AdvanceIf(parser, TokenType::Colon))
            {
                paramDecl->type = parser->ParseTypeExp();
            }
            if (AdvanceIf(parser, TokenType::OpAssign))
            {
                paramDecl->initExpr = parser->ParseInitExpr();
            }
            return paramDecl;
        }
        else
        {
            // default case is a type parameter
            GenericTypeParamDecl* paramDecl = parser->astBuilder->create<GenericTypeParamDecl>();
            parser->FillPosition(paramDecl);
            paramDecl->nameAndLoc = NameLoc(parser->ReadToken(TokenType::Identifier));
            if (AdvanceIf(parser, TokenType::Colon))
            {
                // The user is apply a constraint to this type parameter...

                auto paramConstraint = parser->astBuilder->create<GenericTypeConstraintDecl>();
                parser->FillPosition(paramConstraint);

                auto paramType = DeclRefType::create(
                    parser->astBuilder,
                    DeclRef<Decl>(paramDecl, nullptr));

                auto paramTypeExpr = parser->astBuilder->create<SharedTypeExpr>();
                paramTypeExpr->loc = paramDecl->loc;
                paramTypeExpr->base.type = paramType;
                paramTypeExpr->type = QualType(parser->astBuilder->getTypeType(paramType));

                paramConstraint->sub = TypeExp(paramTypeExpr);
                paramConstraint->sup = parser->ParseTypeExp();

                AddMember(genericDecl, paramConstraint);


            }
            if (AdvanceIf(parser, TokenType::OpAssign))
            {
                paramDecl->initType = parser->ParseTypeExp();
            }
            return paramDecl;
        }
    }

    template<typename TFunc>
    static void ParseGenericDeclImpl(
        Parser* parser, GenericDecl* decl, const TFunc & parseInnerFunc)
    {
        parser->ReadToken(TokenType::OpLess);
        parser->genericDepth++;
        for (;;)
        {
            const TokenType tokenType = parser->tokenReader.peekTokenType();
            if (tokenType == TokenType::OpGreater ||
                tokenType == TokenType::EndOfFile)
            {
                break;
            }

            auto currentCursor = parser->tokenReader.getCursor();

            AddMember(decl, ParseGenericParamDecl(parser, decl));

            // Make sure we make forward progress.
            if (parser->tokenReader.getCursor() == currentCursor)
                advanceToken(parser);

            if (parser->LookAheadToken(TokenType::OpGreater))
                break;

            if (!AdvanceIf(parser, TokenType::Comma))
                break;
        }
        parser->genericDepth--;
        parser->ReadToken(TokenType::OpGreater);
        decl->inner = parseInnerFunc(decl);
        decl->inner->parentDecl = decl;

        // A generic decl hijacks the name of the declaration
        // it wraps, so that lookup can find it.
        if (decl->inner)
        {
            decl->nameAndLoc = decl->inner->nameAndLoc;
            decl->loc = decl->inner->loc;
        }
    }

    template<typename ParseFunc>
    static Decl* parseOptGenericDecl(
        Parser* parser, const ParseFunc& parseInner)
    {
        // TODO: may want more advanced disambiguation than this...
        if (parser->LookAheadToken(TokenType::OpLess))
        {
            GenericDecl* genericDecl = parser->astBuilder->create<GenericDecl>();
            parser->FillPosition(genericDecl);
            parser->PushScope(genericDecl);
            ParseGenericDeclImpl(parser, genericDecl, parseInner);
            parser->PopScope();
            return genericDecl;
        }
        else
        {
            return parseInner(nullptr);
        }
    }

    static NodeBase* parseGenericDecl(Parser* parser, void*)
    {
        GenericDecl* decl = parser->astBuilder->create<GenericDecl>();
        parser->FillPosition(decl);
        parser->PushScope(decl);
        ParseGenericDeclImpl(parser, decl, [=](GenericDecl* genDecl) {return ParseSingleDecl(parser, genDecl); });
        parser->PopScope();
        return decl;
    }

    static void parseParameterList(
        Parser*         parser,
        CallableDecl*    decl)
    {
        parser->ReadToken(TokenType::LParent);

        // Allow a declaration to use the keyword `void` for a parameter list,
        // since that was required in ancient C, and continues to be supported
        // in a bunch of its derivatives even if it is a Bad Design Choice
        //
        // TODO: conditionalize this so we don't keep this around for "pure"
        // Slang code
        if( parser->LookAheadToken("void") && parser->LookAheadToken(TokenType::RParent, 1) )
        {
            parser->ReadToken("void");
            parser->ReadToken(TokenType::RParent);
            return;
        }

        while (!AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
        {
            AddMember(decl, parser->ParseParameter());
            if (AdvanceIf(parser, TokenType::RParent))
                break;
            parser->ReadToken(TokenType::Comma);
        }
    }

    // systematically replace all scopes in an expression tree
    class ReplaceScopeVisitor : public ExprVisitor<ReplaceScopeVisitor>
    {
    public:
        Scope* scope = nullptr;

        void visitDeclRefExpr(DeclRefExpr* expr)
        {
            expr->scope = scope;
        }
        void visitGenericAppExpr(GenericAppExpr * expr)
        {
            expr->functionExpr->accept(this, nullptr);
            for (auto arg : expr->arguments)
                arg->accept(this, nullptr);
        }
        void visitIndexExpr(IndexExpr * expr)
        {
            expr->baseExpression->accept(this, nullptr);
            for (auto arg : expr->indexExprs)
                arg->accept(this, nullptr);
        }
        void visitMemberExpr(MemberExpr * expr)
        {
            expr->baseExpression->accept(this, nullptr);
            expr->scope = scope;
        }
        void visitStaticMemberExpr(StaticMemberExpr * expr)
        {
            expr->baseExpression->accept(this, nullptr);
            expr->scope = scope;
        }
        void visitExpr(Expr* /*expr*/)
        {}
    };

        /// Parse an optional body statement for a declaration that can have a body.
    static Stmt* parseOptBody(Parser* parser)
    {
        if (AdvanceIf(parser, TokenType::Semicolon))
        {
            // empty body
            return nullptr;
        }
        else
        {
            return parser->parseBlockStatement();
        }
    }

        /// Complete parsing of a function using traditional (C-like) declarator syntax
    static Decl* parseTraditionalFuncDecl(
        Parser*                 parser,
        DeclaratorInfo const&   declaratorInfo)
    {
        FuncDecl* decl = parser->astBuilder->create<FuncDecl>();
        parser->FillPosition(decl);
        decl->loc = declaratorInfo.nameAndLoc.loc;
        decl->nameAndLoc = declaratorInfo.nameAndLoc;

        return parseOptGenericDecl(parser, [&](GenericDecl*)
        {
            // HACK: The return type of the function will already have been
            // parsed in a scope that didn't include the function's generic
            // parameters.
            //
            // We will use a visitor here to try and replace the scope associated
            // with any name expressiosn in the reuslt type.
            //
            // TODO: This should be fixed by not associating scopes with
            // such expressions at parse time, and instead pushing down scopes
            // as part of the state during semantic checking.
            //
            ReplaceScopeVisitor replaceScopeVisitor;
            replaceScopeVisitor.scope = parser->currentScope;
            declaratorInfo.typeSpec->accept(&replaceScopeVisitor, nullptr);

            decl->returnType = TypeExp(declaratorInfo.typeSpec);

            parser->PushScope(decl);

            parseParameterList(parser, decl);

            if (AdvanceIf(parser, "throws"))
            {
                decl->errorType = parser->ParseTypeExp();
            }

            _parseOptSemantics(parser, decl);
            decl->body = parseOptBody(parser);
            if (auto block = as<BlockStmt>(decl->body))
            {
                decl->closingSourceLoc = block->closingSourceLoc;
            }
            parser->PopScope();

            return decl;
        });
    }

    static VarDeclBase* CreateVarDeclForContext(
        ASTBuilder* astBuilder, 
        ContainerDecl*  containerDecl )
    {
        if (as<CallableDecl>(containerDecl))
        {
            // Function parameters always use their dedicated syntax class.
            //
            return astBuilder->create<ParamDecl>();
        }
        else
        {
            // Globals, locals, and member variables all use the same syntax class.
            //
            return astBuilder->create<VarDecl>();
        }
    }

    // Add modifiers to the end of the modifier list for a declaration
    static void _addModifiers(Decl* decl, Modifiers const& modifiers)
    {
        if (!modifiers.first)
            return;

        Modifier** link = &decl->modifiers.first;
        while (*link)
        {
            link = &(*link)->next;
        }
        *link = modifiers.first;
    }

    static Name* generateName(Parser* parser, String const& base)
    {
        // TODO: somehow mangle the name to avoid clashes
        return getName(parser, "SLANG_" + base);
    }

    static Name* generateName(Parser* parser)
    {
        return generateName(parser, "anonymous_" + String(parser->anonymousCounter++));
    }


    // Set up a variable declaration based on what we saw in its declarator...
    static void CompleteVarDecl(
        Parser*					parser,
        VarDeclBase*		decl,
        DeclaratorInfo const&	declaratorInfo)
    {
        parser->FillPosition(decl);

        if( !declaratorInfo.nameAndLoc.name )
        {
            // HACK(tfoley): we always give a name, even if the declarator didn't include one... :(
            decl->nameAndLoc = NameLoc(generateName(parser));
        }
        else
        {
            decl->loc = declaratorInfo.nameAndLoc.loc;
            decl->nameAndLoc = declaratorInfo.nameAndLoc;
        }
        decl->type = TypeExp(declaratorInfo.typeSpec);

        _addModifiers(decl, declaratorInfo.semantics);

        decl->initExpr = declaratorInfo.initializer;
    }

    typedef unsigned int DeclaratorParseOptions;
    enum
    {
        kDeclaratorParseOptions_None = 0,
        kDeclaratorParseOption_AllowEmpty = 1 << 0,
    };

    static RefPtr<Declarator> parseDeclarator(
        Parser*                 parser,
        DeclaratorParseOptions  options);

    static RefPtr<Declarator> parseDirectAbstractDeclarator(
        Parser*                 parser,
        DeclaratorParseOptions  options)
    {
        RefPtr<Declarator> declarator;
        switch( parser->tokenReader.peekTokenType() )
        {
        case TokenType::Identifier:
            {
                auto nameDeclarator = new NameDeclarator();
                nameDeclarator->flavor = Declarator::Flavor::name;
                nameDeclarator->nameAndLoc = ParseDeclName(parser);
                declarator = nameDeclarator;
            }
            break;

        case TokenType::LParent:
            {
                // Note(tfoley): This is a point where disambiguation is required.
                // We could be looking at an abstract declarator for a function-type
                // parameter:
                //
                //     void F( int(int) );
                //
                // Or we could be looking at the use of parenthesese in an ordinary
                // declarator:
                //
                //     void (*f)(int);
                //
                // The difference really doesn't matter right now, but we err in
                // the direction of assuming the second case.
                //
                // TODO: We should consider just not supporting this case at all,
                // since it can't come up in current Slang (no pointer or function-type
                // support), and we might be able to introduce alternative syntax
                // to get around these issues when those features come online.
                //
                parser->ReadToken(TokenType::LParent);
                declarator = parseDeclarator(parser, options);
                parser->ReadMatchingToken(TokenType::RParent);
            }
            break;

        default:
            if(options & kDeclaratorParseOption_AllowEmpty)
            {
                // an empty declarator is allowed
            }
            else
            {
                // If an empty declarator is now allowed, then we
                // will give the user an error message saying that
                // an identifier was expected.
                //
                expectIdentifier(parser);
            }
            return nullptr;
        }

        // postifx additions
        for( ;;)
        {
            switch( parser->tokenReader.peekTokenType() )
            {
            case TokenType::LBracket:
                {
                    auto arrayDeclarator = new ArrayDeclarator();
                    arrayDeclarator->openBracketLoc = parser->tokenReader.peekLoc();
                    arrayDeclarator->flavor = Declarator::Flavor::Array;
                    arrayDeclarator->inner = declarator;

                    parser->ReadToken(TokenType::LBracket);
                    if( parser->tokenReader.peekTokenType() != TokenType::RBracket )
                    {
                        arrayDeclarator->elementCountExpr = parser->ParseExpression();
                    }
                    parser->ReadToken(TokenType::RBracket);

                    declarator = arrayDeclarator;
                    continue;
                }

            case TokenType::LParent:
                break;

            default:
                break;
            }

            break;
        }

        return declarator;
    }

    // Parse a declarator (or at least as much of one as we support)
    static RefPtr<Declarator> parseDeclarator(
        Parser*                 parser,
        DeclaratorParseOptions  options)
    {
        if( parser->tokenReader.peekTokenType() == TokenType::OpMul )
        {
            auto ptrDeclarator = new PointerDeclarator();
            ptrDeclarator->starLoc = parser->tokenReader.peekLoc();
            ptrDeclarator->flavor = Declarator::Flavor::Pointer;

            parser->ReadToken(TokenType::OpMul);

            // TODO(tfoley): allow qualifiers like `const` here?

            ptrDeclarator->inner = parseDeclarator(parser, options);
            return ptrDeclarator;
        }
        else
        {
            return parseDirectAbstractDeclarator(parser, options);
        }
    }

    // A declarator plus optional semantics and initializer
    struct InitDeclarator
    {
        RefPtr<Declarator>  declarator;
        Modifiers    semantics;
        Expr*        initializer = nullptr;
    };

    // Parse a declarator plus optional semantics
    static InitDeclarator parseSemanticDeclarator(
        Parser*                 parser,
        DeclaratorParseOptions  options)
    {
        InitDeclarator result;
        result.declarator = parseDeclarator(parser, options);
        result.semantics = _parseOptSemantics(parser);
        return result;
    }

    // Parse a declarator plus optional semantics and initializer
    static InitDeclarator parseInitDeclarator(
        Parser*                 parser,
        DeclaratorParseOptions  options)
    {
        InitDeclarator result = parseSemanticDeclarator(parser, options);
        if (AdvanceIf(parser, TokenType::OpAssign))
        {
            result.initializer = parser->ParseInitExpr();
        }
        return result;
    }

    static void UnwrapDeclarator(
        ASTBuilder*         astBuilder, 
        RefPtr<Declarator>	declarator,
        DeclaratorInfo*		ioInfo)
    {
        while( declarator )
        {
            switch(declarator->flavor)
            {
            case Declarator::Flavor::name:
                {
                    auto nameDeclarator = (NameDeclarator*) declarator.Ptr();
                    ioInfo->nameAndLoc = nameDeclarator->nameAndLoc;
                    return;
                }
                break;

            case Declarator::Flavor::Pointer:
                {
                    auto ptrDeclarator = (PointerDeclarator*) declarator.Ptr();
                    auto ptrTypeExpr = astBuilder->create<PointerTypeExpr>();
                    ptrTypeExpr->loc = ptrDeclarator->starLoc;
                    ptrTypeExpr->base.exp = ioInfo->typeSpec;
                    ioInfo->typeSpec = ptrTypeExpr;

                    declarator = ptrDeclarator->inner;
                }
                break;

            case Declarator::Flavor::Array:
                {
                    // TODO(tfoley): we don't support pointers for now
                    auto arrayDeclarator = (ArrayDeclarator*) declarator.Ptr();

                    auto arrayTypeExpr = astBuilder->create<IndexExpr>();
                    arrayTypeExpr->loc = arrayDeclarator->openBracketLoc;
                    arrayTypeExpr->baseExpression = ioInfo->typeSpec;
                    if (arrayDeclarator->elementCountExpr)
                        arrayTypeExpr->indexExprs.add(arrayDeclarator->elementCountExpr);
                    ioInfo->typeSpec = arrayTypeExpr;

                    declarator = arrayDeclarator->inner;
                }
                break;

            default:
                SLANG_UNREACHABLE("all cases handled");
                break;
            }
        }
    }

    static void UnwrapDeclarator(
        ASTBuilder*             astBuilder, 
        InitDeclarator const&	initDeclarator,
        DeclaratorInfo*			ioInfo)
    {
        UnwrapDeclarator(astBuilder, initDeclarator.declarator, ioInfo);
        ioInfo->semantics = initDeclarator.semantics;
        ioInfo->initializer = initDeclarator.initializer;
    }

    // Either a single declaration, or a group of them
    struct DeclGroupBuilder
    {
        SourceLoc        startPosition;
        Decl*        decl = nullptr;
        DeclGroup*   group = nullptr;
        ASTBuilder*      astBuilder = nullptr;

        // Add a new declaration to the potential group
        void addDecl(
            Decl*    newDecl)
        {
            SLANG_ASSERT(newDecl);

            if( decl )
            {
                group = astBuilder->create<DeclGroup>();
                group->loc = startPosition;
                group->decls.add(decl);
                decl = nullptr;
            }

            if( group )
            {
                group->decls.add(newDecl);
            }
            else
            {
                decl = newDecl;
            }
        }

        DeclBase* getResult()
        {
            if(group) return group;
            return decl;
        }
    };

    // Create a type expression that will refer to the given declaration
    static Expr*
    createDeclRefType(Parser* parser, Decl* decl)
    {
        // For now we just construct an expression that
        // will look up the given declaration by name.
        //
        // TODO: do this better, e.g. by filling in the `declRef` field directly

        auto expr = parser->astBuilder->create<VarExpr>();
        expr->scope = parser->currentScope;
        expr->loc = decl->getNameLoc();
        expr->name = decl->getName();
        return expr;
    }

    // Representation for a parsed type specifier, which might
    // include a declaration (e.g., of a `struct` type)
    struct TypeSpec
    {
        // If the type-spec declared something, then put it here
        Decl*                    decl = nullptr;

        // Put the resulting expression (which should evaluate to a type) here
        Expr*    expr = nullptr;
    };

    static Expr* parseGenericApp(
        Parser*                         parser,
        Expr*    base)
    {
        GenericAppExpr* genericApp = parser->astBuilder->create<GenericAppExpr>();

        genericApp->loc = base->loc;
        genericApp->functionExpr = base;
        parser->ReadToken(TokenType::OpLess);
        parser->genericDepth++;
        // For now assume all generics have at least one argument
        genericApp->arguments.add(_parseGenericArg(parser));
        while (AdvanceIf(parser, TokenType::Comma))
        {
            genericApp->arguments.add(_parseGenericArg(parser));
        }
        parser->genericDepth--;

        if (parser->tokenReader.peekToken().type == TokenType::OpRsh)
        {
            parser->tokenReader.peekToken().type = TokenType::OpGreater;
            parser->tokenReader.peekToken().loc.setRaw(parser->tokenReader.peekToken().loc.getRaw() + 1);
        }
        else if (parser->LookAheadToken(TokenType::OpGreater))
            parser->ReadToken(TokenType::OpGreater);
        else
            parser->sink->diagnose(parser->tokenReader.peekToken(), Diagnostics::tokenTypeExpected, "'>'");
        return genericApp;
    }

    static bool isGenericName(Parser* parser, Name* name)
    {
        auto lookupResult = lookUp(
            parser->astBuilder,
            nullptr, // no semantics visitor available yet
            name,
            parser->currentScope);
        if (!lookupResult.isValid() || lookupResult.isOverloaded())
            return false;

        return lookupResult.item.declRef.is<GenericDecl>();
    }

    static Expr* tryParseGenericApp(
        Parser*                         parser,
        Expr*    base)
    {
        Name * baseName = nullptr;
        if (auto varExpr = as<VarExpr>(base))
            baseName = varExpr->name;
        // if base is a known generics, parse as generics
        if (baseName && isGenericName(parser, baseName))
            return parseGenericApp(parser, base);

        // otherwise, we speculate as generics, and fallback to comparison when parsing failed
        TokenSpan tokenSpan;
        tokenSpan.m_begin = parser->tokenReader.m_cursor;
        tokenSpan.m_end = parser->tokenReader.m_end;

        // Setup without diagnostic lexer, or SourceLocationLine output
        // as this sink is just to *try* generic application
        DiagnosticSink newSink(parser->sink->getSourceManager(), nullptr);

        Parser newParser(*parser);
        newParser.sink = &newSink;

        /* auto speculateParseRs = */parseGenericApp(&newParser, base);

        if (newSink.getErrorCount() == 0)
        {
            // disambiguate based on FOLLOW set
            switch (peekTokenType(&newParser))
            {
            case TokenType::Dot:
            case TokenType::LParent:
            case TokenType::RParent:
            case TokenType::RBracket:
            case TokenType::Colon:
            case TokenType::Comma:
            case TokenType::QuestionMark:
            case TokenType::Semicolon:
            case TokenType::OpEql:
            case TokenType::OpNeq:
            case TokenType::OpGreater:
            {
                return parseGenericApp(parser, base);
            }
            }
        }
        return base;
    }
    static Expr* parseMemberType(Parser * parser, Expr* base, SourceLoc opLoc)
    {
        // When called the :: or . have been consumed, so don't need to consume here.

        MemberExpr* memberExpr = parser->astBuilder->create<MemberExpr>();
        memberExpr->memberOperatorLoc = opLoc;
        parser->FillPosition(memberExpr);
        memberExpr->baseExpression = base;
        memberExpr->name = expectIdentifier(parser).name;
        return memberExpr;
    }
    static Expr* parseStaticMemberType(Parser* parser, Expr* base, SourceLoc opLoc)
    {
        // When called the :: or . have been consumed, so don't need to consume here.

        StaticMemberExpr* memberExpr = parser->astBuilder->create<StaticMemberExpr>();
        memberExpr->memberOperatorLoc = opLoc;
        parser->FillPosition(memberExpr);
        memberExpr->baseExpression = base;
        memberExpr->name = expectIdentifier(parser).name;
        return memberExpr;
    }

    // Parse option `[]` braces after a type expression, that indicate an array type
    static Expr* parsePostfixTypeSuffix(
        Parser* parser,
        Expr* inTypeExpr)
    {
        auto typeExpr = inTypeExpr;
        for (;;)
        {
            Token token;
            if (parser->LookAheadToken(TokenType::LBracket))
            {
                IndexExpr* arrType = parser->astBuilder->create<IndexExpr>();
                arrType->loc = typeExpr->loc;
                arrType->baseExpression = typeExpr;
                parser->ReadToken(TokenType::LBracket);
                if (!parser->LookAheadToken(TokenType::RBracket))
                {
                    arrType->indexExprs.add(parser->ParseExpression());
                }
                parser->ReadToken(TokenType::RBracket);
                typeExpr = arrType;
            }
            else if (AdvanceIf(parser, TokenType::OpMul, &token))
            {
                PointerTypeExpr* ptrType = parser->astBuilder->create<PointerTypeExpr>();
                ptrType->loc = token.loc;
                ptrType->base.exp = typeExpr;
                typeExpr = ptrType;
            }
            else
                break;
        }
        return typeExpr;
    }

    static Expr* parseTaggedUnionType(Parser* parser)
    {
        TaggedUnionTypeExpr* taggedUnionType = parser->astBuilder->create<TaggedUnionTypeExpr>();

        parser->ReadToken(TokenType::LParent);
        while(!AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
        {
            auto caseType = parser->ParseTypeExp();
            taggedUnionType->caseTypes.add(caseType);

            if(AdvanceIf(parser, TokenType::RParent))
                break;

            parser->ReadToken(TokenType::Comma);
        }

        return taggedUnionType;
    }

    static NodeBase* parseTaggedUnionType(Parser* parser, void* /*unused*/)
    {
        return parseTaggedUnionType(parser);
    }
        /// Parse an expression of the form __fwd_diff(fn) where fn is an 
        /// identifier pointing to a function.
    static Expr* parseForwardDifferentiate(Parser* parser)
    {
        ForwardDifferentiateExpr* jvpExpr = parser->astBuilder->create<ForwardDifferentiateExpr>();

        parser->ReadToken(TokenType::LParent);

        jvpExpr->baseFunction = parser->ParseExpression();

        parser->ReadToken(TokenType::RParent);

        return jvpExpr;
    }

    static NodeBase* parseForwardDifferentiate(Parser* parser, void* /* unused */)
    {
        return parseForwardDifferentiate(parser);
    }

        /// Parse an expression of the form __bwd_diff(fn) where fn is an 
        /// identifier pointing to a function.
    static Expr* parseBackwardDifferentiate(Parser* parser)
    {
        BackwardDifferentiateExpr* bwdDiffExpr = parser->astBuilder->create<BackwardDifferentiateExpr>();

        parser->ReadToken(TokenType::LParent);

        bwdDiffExpr->baseFunction = parser->ParseExpression();

        parser->ReadToken(TokenType::RParent);

        return bwdDiffExpr;
    }

    static NodeBase* parseBackwardDifferentiate(Parser* parser, void* /* unused */)
    {
        return parseBackwardDifferentiate(parser);
    }

    static Expr* parseDispatchKernel(Parser* parser)
    {
        DispatchKernelExpr* dispatchExpr = parser->astBuilder->create<DispatchKernelExpr>();

        parser->ReadToken(TokenType::LParent);

        dispatchExpr->baseFunction = parser->ParseArgExpr();
        parser->ReadToken(TokenType::Comma);
        dispatchExpr->dispatchSize = parser->ParseArgExpr();
        parser->ReadToken(TokenType::Comma);
        dispatchExpr->threadGroupSize = parser->ParseArgExpr();
        parser->ReadToken(TokenType::RParent);

        return dispatchExpr;
    }

    static NodeBase* parseDispatchKernel(Parser* parser, void* /* unused */)
    {
        return parseDispatchKernel(parser);
    }

        /// Parse a `This` type expression
    static Expr* parseThisTypeExpr(Parser* parser)
    {
        ThisTypeExpr* expr = parser->astBuilder->create<ThisTypeExpr>();
        expr->scope = parser->currentScope;
        return expr;
    }

    static NodeBase* parseThisTypeExpr(Parser* parser, void* /*userData*/)
    {
        return parseThisTypeExpr(parser);
    }

        /// Apply the given `modifiers` (if any) to the given `typeExpr`
    static Expr* _applyModifiersToTypeExpr(Parser* parser, Expr* typeExpr, Modifiers const& modifiers)
    {
        if(modifiers.first)
        {
            // Currently, we represent a type with modifiers applied to it as
            // an AST node of the `ModifiedTypeExpr` class. We will create
            // one here and make it be the home for our `typeModifiers`.
            //
            ModifiedTypeExpr* modifiedTypeExpr = parser->astBuilder->create<ModifiedTypeExpr>();
            modifiedTypeExpr->base.exp = typeExpr;
            modifiedTypeExpr->modifiers = modifiers;
            return modifiedTypeExpr;
        }
        else
        {
            // If none of the modifiers were type modifiers, we can leave
            // the existing type expression alone.
            return typeExpr;
        }
    }

        /// Apply any type modifier in `ioBaseModifiers` to the given `typeExpr`.
        ///
        /// If any type modifiers were present, `ioBaseModifiers` will be updated
        /// to only include those modifiers that were not type modifiers (if any).
        /// 
        /// If no type modifiers were present, `ioBaseModifiers` will remain unchanged.
        ///
    static Expr* _applyTypeModifiersToTypeExpr(Parser* parser, Expr* typeExpr, Modifiers& ioBaseModifiers)
    {
        // The `Modifiers` that were passed in as `ioBaseModifiers` comprise
        // a singly-linked list of `Modifier` nodes.
        //
        // It is possible that some of these modifiers represent type modifiers and,
        // if so, we want to transfer those modifiers to apply to the type given
        // by `typeExpr`. Any remaining modifiers that are not type modifiers will
        // be left in the `ioBaseModifiers` list.
        //
        // The type modifiers will be collected into their own `Modifiers` list,
        // and we will retain a poiner to the final pointer in the linked list
        // (the one that is null), so that we can append to the end.
        //
        Modifiers typeModifiers;
        Modifier** typeModifierLink = &typeModifiers.first;

        // While iterating over the base modifiers, we need to be able to remove
        // a linked-list node while inspecting it, so we will similarly keep a "link"
        // variable that points at whatever location points to the current node
        // (either the head of the list, or the `next` pointer in the previous modifier)
        //
        Modifier** baseModifierLink = &ioBaseModifiers.first;
        while(auto baseModifier = *baseModifierLink)
        {
            // We want to detect whether we have a type modifier or not.
            //
            auto typeModifier = as<TypeModifier>(baseModifier);

            // The easy case is when we *don't* have a type modifier.
            //
            if(!typeModifier)
            {
                // We want to leave the modifier where it is (in the list
                // of "base" modifiers), and advance to the next one in order.
                //
                baseModifierLink = &baseModifier->next;
            }
            else
            {
                // If we have a type modifier, we need to graft it onto
                // the list of type modifiers. This is done by writing
                // a pointer to the type modifier into the "link" for
                // the type modifier list, and updating the link to point
                // to the `next` field of the current modifier (since that
                // fill be the location any further type modifiers need
                // to be linked).
                //
                *typeModifierLink = typeModifier;
                typeModifierLink = &typeModifier->next;

                // The above logic puts `typeModifier` into the type modifer
                // list, but it doesn't remove it from the base modifier list.
                // In order to do that we must replace the pointer to `typeModifer`
                // with a pointer to whatever is next in the base list, and also
                // null out the `next` field of `typeModifier` so that it no
                // longer points to the base modifiers that come after it.
                //
                *baseModifierLink = typeModifier->next;
                typeModifier->next = nullptr;

                // Note: We do *not* need to update `baseModifierLink` before
                // the next loop iteration, because `*baseModifierLink` has
                // already been updated so that it points to the next node
                // we want to visit.
            }
        }

        // If we ended up finding any type modifiers, we want to apply them
        // to the type expression.
        //
        return _applyModifiersToTypeExpr(parser, typeExpr, typeModifiers);
    }

    static TypeSpec _applyModifiersToTypeSpec(Parser* parser, TypeSpec typeSpec, Modifiers const& inModifiers)
    {
        // It is possible that the form of the type specifier will have
        // included a declaration directly (e.g., using `struct { ... }`
        // as a type specifier to declare both a type and value(s) of that
        // type in one go).
        //
        if(auto decl = typeSpec.decl)
        {
            // In the case where there *is* a declaration, we want to apply
            // any modifiers that logically belong to the type to the type,
            // and any modifiers that logically belong to the declaration to
            // the declaration.
            //
            Modifiers modifiers = inModifiers;
            typeSpec.expr = _applyTypeModifiersToTypeExpr(parser, typeSpec.expr, modifiers);

            // Any remaining modifiers should instead be applied to the declaration.
            _addModifiers(decl, modifiers);
        }
        else
        {
            // If there are modifiers, then we apply *all* of them to the type expression.
            // This may result in modifiers being applied that do not belong on a type;
            // in that case we rely on downstream semantic checking to diagnose any error.
            //
            typeSpec.expr = _applyModifiersToTypeExpr(parser, typeSpec.expr, inModifiers);
        }

        return typeSpec;
    }

        /// Parse a type specifier, without dealing with modifiers.
    static TypeSpec _parseSimpleTypeSpec(Parser* parser)
    {
        TypeSpec typeSpec;

        // We may see a `struct` (or `enum` or `class`) tag specified here, and need to act accordingly
        //
        // TODO(tfoley): Handle the case where the user is just using `struct`
        // as a way to name an existing struct "tag" (e.g., `struct Foo foo;`)
        //
        // TODO: We should really make these keywords be registered like any other
        // syntax category, rather than be special-cased here. The main issue here
        // is that we need to allow them to be used as type specifiers, as in:
        //
        //      struct Foo { int x } foo;
        //
        // The ideal answer would be to register certain keywords as being able
        // to parse a type specifier, and look for those keywords here.
        // We should ideally add special case logic that bails out of declarator
        // parsing iff we have one of these kinds of type specifiers and the
        // closing `}` is at the end of its line, as a bit of a special case
        // to allow the common idiom.
        //
        if( parser->LookAheadToken("struct") )
        {
            auto decl = parser->ParseStruct();
            typeSpec.decl = decl;
            typeSpec.expr = createDeclRefType(parser, decl);
            return typeSpec;
        }
        else if( parser->LookAheadToken("class") )
        {
            auto decl = parser->ParseClass();
            typeSpec.decl = decl;
            typeSpec.expr = createDeclRefType(parser, decl);
            return typeSpec;
        }
        else if(parser->LookAheadToken("enum"))
        {
            auto decl = parseEnumDecl(parser);
            typeSpec.decl = decl;
            typeSpec.expr = createDeclRefType(parser, decl);
            return typeSpec;
        }
        // TODO: This case would not be needed if we had the
        // code below dispatch into `parseAtomicExpr`, which
        // already includes logic for keyword lookup.
        //
        // Leaving this case here for now to avoid breaking anything.
        //
        else if(AdvanceIf(parser, "__TaggedUnion"))
        {
            typeSpec.expr = parseTaggedUnionType(parser);
            return typeSpec;
        }
        else if(AdvanceIf(parser, "This"))
        {
            typeSpec.expr = parseThisTypeExpr(parser);
            return typeSpec;
        }

        Token typeName = parser->ReadToken(TokenType::Identifier);

        auto basicType = parser->astBuilder->create<VarExpr>();
        basicType->scope = parser->currentScope;
        basicType->loc = typeName.loc;
        basicType->name = typeName.getNameOrNull();

        Expr* typeExpr = basicType;

        bool shouldLoop = true;
        while (shouldLoop)
        {
            switch (peekTokenType(parser))
            {
            case TokenType::OpLess:
                typeExpr = parseGenericApp(parser, typeExpr);
                break;
            case TokenType::Scope:
                {
                    auto opToken = parser->ReadToken(TokenType::Scope);
                    typeExpr = parseStaticMemberType(parser, typeExpr, opToken.loc);
                    break;
                }
            case TokenType::Dot:
                {
                    auto opToken = parser->ReadToken(TokenType::Dot);
                    typeExpr = parseMemberType(parser, typeExpr, opToken.loc);
                    break;
                }
            default:
                shouldLoop = false;
            }
        }

        typeSpec.expr = typeExpr;
        return typeSpec;
    }

        /// Parse a type specifier, following the given list of modifiers.
        ///
        /// If there are any modifiers in `ioModifiers`, this function may modify it
        /// by stripping out any type modifiers and attaching them to the `TypeSpec`.
        /// Any modifiers that are not type modifiers will be left where they were.
        ///
    static TypeSpec _parseTypeSpec(Parser* parser, Modifiers& ioModifiers)
    {
        TypeSpec typeSpec = _parseSimpleTypeSpec(parser);

        // We don't know whether `ioModifiers` has any modifiers in it,
        // or which of them might be type modifiers, so we will delegate
        // figuring that out to a subroutine.
        //
        typeSpec.expr = _applyTypeModifiersToTypeExpr(parser, typeSpec.expr, ioModifiers);

        return typeSpec;
    }

        /// Parse a type specifier, including any leading modifiers.
        ///
        /// Note that all the modifiers that precede the type specifier
        /// will end up as modifiers for the type specifier even if they
        /// should *not* be allowed as modifiers on a type.
        ///
        /// This function should not be used in contexts where a type specifier
        /// is being parsed as part of a declaration, such that a subset of
        /// the modifiers might inhere to the declaration rather than the
        /// type specifier.
        ///
    static TypeSpec _parseTypeSpec(Parser* parser)
    {
        Modifiers modifiers = ParseModifiers(parser);
        TypeSpec typeSpec = _parseSimpleTypeSpec(parser);

        typeSpec = _applyModifiersToTypeSpec(parser, typeSpec, modifiers);

        return typeSpec;
    }


    static DeclBase* ParseDeclaratorDecl(
        Parser*             parser,
        ContainerDecl*      containerDecl,
        Modifiers const&    inModifiers)
    {
        SourceLoc startPosition = parser->tokenReader.peekLoc();

        Modifiers modifiers = inModifiers;
        auto typeSpec = _parseTypeSpec(parser, modifiers);

        if (typeSpec.expr == nullptr && typeSpec.decl == nullptr)
        {
            return nullptr;
        }

        // We may need to build up multiple declarations in a group,
        // but the common case will be when we have just a single
        // declaration
        DeclGroupBuilder declGroupBuilder;
        declGroupBuilder.startPosition = startPosition;
        declGroupBuilder.astBuilder = parser->astBuilder;

        // The type specifier may include a declaration. E.g.,
        // it might declare a `struct` type.
        if(typeSpec.decl)
            declGroupBuilder.addDecl(typeSpec.decl);

        if( AdvanceIf(parser, TokenType::Semicolon) )
        {
            // No actual variable is being declared here, but
            // that might not be an error.

            auto result = declGroupBuilder.getResult();
            if( !result )
            {
                parser->sink->diagnose(startPosition, Diagnostics::declarationDidntDeclareAnything);
            }
            return result;
        }

        // It is possible that we have a plain `struct`, `enum`,
        // or similar declaration that isn't being used to declare
        // any variable, and the user didn't put a trailing
        // semicolon on it:
        //
        //      struct Batman
        //      {
        //          int cape;
        //      }
        //
        // We want to allow this syntax (rather than give an
        // inscrutable error), but also support the less common
        // idiom where that declaration is used as part of
        // a variable declaration:
        //
        //      struct Robin
        //      {
        //          float tights;
        //      } boyWonder;
        //
        // As a bit of a hack (insofar as it means we aren't
        // *really* compatible with arbitrary HLSL code), we
        // will check if there are any more tokens on the
        // same line as the closing `}`, and if not, we
        // will treat it like the end of the declaration.
        //
        // Just as a safety net, only apply this logic for
        // a file that is being passed in as "true" Slang code.
        //
        if(parser->getSourceLanguage() == SourceLanguage::Slang)
        {
            if(typeSpec.decl)
            {
                if(peekToken(parser).flags & TokenFlag::AtStartOfLine)
                {
                    // The token after the `}` is at the start of its
                    // own line, which means it can't be on the same line.
                    //
                    // This means the programmer probably wants to
                    // just treat this as a declaration.
                    return declGroupBuilder.getResult();
                }
            }
        }


        InitDeclarator initDeclarator = parseInitDeclarator(parser, kDeclaratorParseOptions_None);

        DeclaratorInfo declaratorInfo;
        declaratorInfo.typeSpec = typeSpec.expr;


        // Rather than parse function declarators properly for now,
        // we'll just do a quick disambiguation here. This won't
        // matter unless we actually decide to support function-type parameters,
        // using C syntax.
        //
        if ((parser->tokenReader.peekTokenType() == TokenType::LParent ||
            parser->tokenReader.peekTokenType() == TokenType::OpLess)

            // Only parse as a function if we didn't already see mutually-exclusive
            // constructs when parsing the declarator.
            && !initDeclarator.initializer
            && !initDeclarator.semantics.first)
        {
            // Looks like a function, so parse it like one.
            UnwrapDeclarator(parser->astBuilder, initDeclarator, &declaratorInfo);
            return parseTraditionalFuncDecl(parser, declaratorInfo);
        }

        // Otherwise we are looking at a variable declaration, which could be one in a sequence...

        if( AdvanceIf(parser, TokenType::Semicolon) )
        {
            // easy case: we only had a single declaration!
            UnwrapDeclarator(parser->astBuilder, initDeclarator, &declaratorInfo);
            VarDeclBase* firstDecl = CreateVarDeclForContext(parser->astBuilder, containerDecl);
            CompleteVarDecl(parser, firstDecl, declaratorInfo);

            declGroupBuilder.addDecl(firstDecl);
            return declGroupBuilder.getResult();
        }

        // Otherwise we have multiple declarations in a sequence, and these
        // declarations need to somehow share both the type spec and modifiers.
        //
        // If there are any errors in the type specifier, we only want to hear
        // about it once, so we need to share structure rather than just
        // clone syntax.

        auto sharedTypeSpec = parser->astBuilder->create<SharedTypeExpr>();
        sharedTypeSpec->loc = typeSpec.expr->loc;
        sharedTypeSpec->base = TypeExp(typeSpec.expr);

        for(;;)
        {
            declaratorInfo.typeSpec = sharedTypeSpec;
            UnwrapDeclarator(parser->astBuilder, initDeclarator, &declaratorInfo);

            VarDeclBase* varDecl = CreateVarDeclForContext(parser->astBuilder, containerDecl);
            CompleteVarDecl(parser, varDecl, declaratorInfo);

            declGroupBuilder.addDecl(varDecl);

            // end of the sequence?
            if(AdvanceIf(parser, TokenType::Semicolon))
                return declGroupBuilder.getResult();

            // ad-hoc recovery, to avoid infinite loops
            if( parser->isRecovering )
            {
                parser->ReadToken(TokenType::Semicolon);
                return declGroupBuilder.getResult();
            }

            // Let's default to assuming that a missing `,`
            // indicates the end of a declaration,
            // where a `;` would be expected, and not
            // a continuation of this declaration, where
            // a `,` would be expected (this is tailoring
            // the diagnostic message a bit).
            //
            // TODO: a more advanced heuristic here might
            // look at whether the next token is on the
            // same line, to predict whether `,` or `;`
            // would be more likely...

            if (!AdvanceIf(parser, TokenType::Comma))
            {
                parser->ReadToken(TokenType::Semicolon);
                // We don't need to enter recovering mode if next token isn't semicolon.
                // In this case we just continue parsing the token as the next decl.
                parser->isRecovering = false;
                return declGroupBuilder.getResult();
            }

            // expect another variable declaration...
            initDeclarator = parseInitDeclarator(parser, kDeclaratorParseOptions_None);
        }
    }

    /// Parse the "register name" part of a `register` or `packoffset` semantic.
    ///
    /// The syntax matched is:
    ///
    ///     register-name-and-component-mask ::= register-name component-mask?
    ///     register-name ::= identifier
    ///     component-mask ::= '.' identifier
    ///
    static void parseHLSLRegisterNameAndOptionalComponentMask(
        Parser*             parser,
        HLSLLayoutSemantic* semantic)
    {
        semantic->registerName = parser->ReadToken(TokenType::Identifier);
        if (AdvanceIf(parser, TokenType::Dot))
        {
            semantic->componentMask = parser->ReadToken(TokenType::Identifier);
        }
    }

    /// Parse an HLSL `register` semantic.
    ///
    /// The syntax matched is:
    ///
    ///     register-semantic ::= 'register' '(' register-name-and-component-mask register-space? ')'
    ///     register-space ::= ',' identifier
    ///
    static void parseHLSLRegisterSemantic(
        Parser*                 parser,
        HLSLRegisterSemantic*   semantic)
    {
        // Read the `register` keyword
        semantic->name = parser->ReadToken(TokenType::Identifier);

        // Expect a parenthized list of additional arguments
        parser->ReadToken(TokenType::LParent);

        // First argument is a required register name and optional component mask
        parseHLSLRegisterNameAndOptionalComponentMask(parser, semantic);

        // Second argument is an optional register space
        if(AdvanceIf(parser, TokenType::Comma))
        {
            semantic->spaceName = parser->ReadToken(TokenType::Identifier);
        }

        parser->ReadToken(TokenType::RParent);
    }

    /// Parse an HLSL `packoffset` semantic.
    ///
    /// The syntax matched is:
    ///
    ///     packoffset-semantic ::= 'packoffset' '(' register-name-and-component-mask ')'
    ///
    static void parseHLSLPackOffsetSemantic(
        Parser*                 parser,
        HLSLPackOffsetSemantic* semantic)
    {
        // Read the `packoffset` keyword
        semantic->name = parser->ReadToken(TokenType::Identifier);

        // Expect a parenthized list of additional arguments
        parser->ReadToken(TokenType::LParent);

        // First and only argument is a required register name and optional component mask
        parseHLSLRegisterNameAndOptionalComponentMask(parser, semantic);

        parser->ReadToken(TokenType::RParent);

        parser->sink->diagnose(semantic, Diagnostics::packOffsetNotSupported);
    }

    static RayPayloadAccessSemantic* _parseRayPayloadAccessSemantic(Parser* parser, RayPayloadAccessSemantic* semantic)
    {
        parser->FillPosition(semantic);

        // Read the keyword that introduced the semantic
        semantic->name = parser->ReadToken(TokenType::Identifier);

        parser->ReadToken(TokenType::LParent);

        for(;;)
        {
            if(AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
                break;

            auto stageName = parser->ReadToken(TokenType::Identifier);
            semantic->stageNameTokens.add(stageName);

            if(AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
                break;

            expect(parser, TokenType::Comma);
        }

        return semantic;
    }

    template<typename T>
    static T* _parseRayPayloadAccessSemantic(Parser* parser)
    {
        T* semantic = parser->astBuilder->create<T>();
        _parseRayPayloadAccessSemantic(parser, semantic);
        return semantic;
    }

    //
    // semantic ::= identifier ( '(' args ')' )?
    //
    static Modifier* ParseSemantic(
        Parser* parser)
    {
        if (parser->LookAheadToken("register"))
        {
            HLSLRegisterSemantic* semantic = parser->astBuilder->create<HLSLRegisterSemantic>();
            parser->FillPosition(semantic);
            parseHLSLRegisterSemantic(parser, semantic);
            return semantic;
        }
        else if (parser->LookAheadToken("packoffset"))
        {
            HLSLPackOffsetSemantic* semantic = parser->astBuilder->create<HLSLPackOffsetSemantic>();
            parser->FillPosition(semantic);
            parseHLSLPackOffsetSemantic(parser, semantic);
            return semantic;
        }
        else if( parser->LookAheadToken("read") && parser->LookAheadToken(TokenType::LParent, 1) )
        {
            return _parseRayPayloadAccessSemantic<RayPayloadReadSemantic>(parser);
        }
        else if( parser->LookAheadToken("write") && parser->LookAheadToken(TokenType::LParent, 1) )
        {
            return _parseRayPayloadAccessSemantic<RayPayloadWriteSemantic>(parser);
        }
        else if (parser->LookAheadToken(TokenType::Identifier))
        {
            HLSLSimpleSemantic* semantic = parser->astBuilder->create<HLSLSimpleSemantic>();
            parser->FillPosition(semantic);
            semantic->name = parser->ReadToken(TokenType::Identifier);
            return semantic;
        }
        else if (parser->LookAheadToken(TokenType::CompletionRequest))
        {
            HLSLSimpleSemantic* semantic = parser->astBuilder->create<HLSLSimpleSemantic>();
            parser->FillPosition(semantic);
            semantic->name = parser->ReadToken();
            return semantic;
        }
        else
        {
            // expect an identifier, just to produce an error message
            parser->ReadToken(TokenType::Identifier);
            return nullptr;
        }
    }

    //
    // opt-semantics ::= (':' semantic)*
    //
    static Modifiers _parseOptSemantics(
        Parser* parser)
    {
        Modifiers modifiers;

        if (!AdvanceIf(parser, TokenType::Colon))
            return modifiers;

        Modifier** link = &modifiers.first;
        SLANG_ASSERT(!*link);

        for (;;)
        {
            Modifier* semantic = ParseSemantic(parser);
            if (semantic)
            {
                *link = semantic;
                link = &semantic->next;
            }

            // If we see another `:`, then that means there
            // is yet another semantic to be processed.
            // Otherwise we assume we are at the end of the list.
            //
            // TODO: This could produce sub-optimal diagnostics
            // when the user *meant* to apply multiple semantics
            // to a single declaration:
            //
            //     Foo foo : register(t0)   register(s0);
            //                            ^
            //         missing ':' here   |
            //
            // However, that is an uncommon occurence, and trying
            // to continue parsing semantics here even if we didn't
            // see a colon forces us to be careful about
            // avoiding an infinite loop here.
            if (!AdvanceIf(parser, TokenType::Colon))
            {
                return modifiers;
            }
        }

    }


    static void _parseOptSemantics(
        Parser* parser,
        Decl*	decl)
    {
        _addModifiers(decl, _parseOptSemantics(parser));
    }

    static Decl* ParseHLSLBufferDecl(
        Parser*	parser,
        String  bufferWrapperTypeName)
    {
        // An HLSL declaration of a constant buffer like this:
        //
        //     cbuffer Foo : register(b0) { int a; float b; };
        //
        // is treated as syntax sugar for a type declaration
        // and then a global variable declaration using that type:
        //
        //     struct $anonymous { int a; float b; };
        //     ConstantBuffer<$anonymous> Foo;
        //
        // where `$anonymous` is a fresh name, and the variable
        // declaration is made to be "transparent" so that lookup
        // will see through it to the members inside.

        auto bufferWrapperTypeNamePos = parser->tokenReader.peekLoc();

        // We are going to represent each buffer as a pair of declarations.
        // The first is a type declaration that holds all the members, while
        // the second is a variable declaration that uses the buffer type.
        StructDecl* bufferDataTypeDecl = parser->astBuilder->create<StructDecl>();
        VarDecl* bufferVarDecl = parser->astBuilder->create<VarDecl>();

        // Both declarations will have a location that points to the name
        parser->FillPosition(bufferDataTypeDecl);
        parser->FillPosition(bufferVarDecl);

        auto reflectionNameToken = parser->ReadToken(TokenType::Identifier);

        // Attach the reflection name to the block so we can use it
        auto reflectionNameModifier = parser->astBuilder->create<ParameterGroupReflectionName>();
        reflectionNameModifier->nameAndLoc = NameLoc(reflectionNameToken);
        addModifier(bufferVarDecl, reflectionNameModifier);

        // Both the buffer variable and its type need to have names generated
        bufferVarDecl->nameAndLoc.name = generateName(parser, "parameterGroup_" + String(reflectionNameToken.getContent()));
        bufferDataTypeDecl->nameAndLoc.name = generateName(parser, "ParameterGroup_" + String(reflectionNameToken.getContent()));

        addModifier(bufferDataTypeDecl, parser->astBuilder->create<ImplicitParameterGroupElementTypeModifier>());
        addModifier(bufferVarDecl, parser->astBuilder->create<ImplicitParameterGroupVariableModifier>());

        // TODO(tfoley): We end up constructing unchecked syntax here that
        // is expected to type check into the right form, but it might be
        // cleaner to have a more explicit desugaring pass where we parse
        // these constructs directly into the AST and *then* desugar them.

        // Construct a type expression to reference the buffer data type
        auto bufferDataTypeExpr = parser->astBuilder->create<VarExpr>();
        bufferDataTypeExpr->loc = bufferDataTypeDecl->loc;
        bufferDataTypeExpr->name = bufferDataTypeDecl->nameAndLoc.name;
        bufferDataTypeExpr->scope = parser->currentScope;

        // Construct a type expression to reference the type constructor
        auto bufferWrapperTypeExpr = parser->astBuilder->create<VarExpr>();
        bufferWrapperTypeExpr->loc = bufferWrapperTypeNamePos;
        bufferWrapperTypeExpr->name = getName(parser, bufferWrapperTypeName);

        // Always need to look this up in the outer scope,
        // so that it won't collide with, e.g., a local variable called `ConstantBuffer`
        bufferWrapperTypeExpr->scope = parser->outerScope;

        // Construct a type expression that represents the type for the variable,
        // which is the wrapper type applied to the data type
        auto bufferVarTypeExpr = parser->astBuilder->create<GenericAppExpr>();
        bufferVarTypeExpr->loc = bufferVarDecl->loc;
        bufferVarTypeExpr->functionExpr = bufferWrapperTypeExpr;
        bufferVarTypeExpr->arguments.add(bufferDataTypeExpr);

        bufferVarDecl->type.exp = bufferVarTypeExpr;

        // Any semantics applied to the buffer declaration are taken as applying
        // to the variable instead.
        _parseOptSemantics(parser, bufferVarDecl);

        // The declarations in the body belong to the data type.
        parseDeclBody(parser, bufferDataTypeDecl);

        // All HLSL buffer declarations are "transparent" in that their
        // members are implicitly made visible in the parent scope.
        // We achieve this by applying the transparent modifier to the variable.
        auto transparentModifier = parser->astBuilder->create<TransparentModifier>();
        transparentModifier->next = bufferVarDecl->modifiers.first;
        bufferVarDecl->modifiers.first = transparentModifier;

        // Because we are constructing two declarations, we have a thorny
        // issue that were are only supposed to return one.
        // For now we handle this by adding the type declaration to
        // the current scope manually, and then returning the variable
        // declaration.
        //
        // Note: this means that any modifiers that have already been parsed
        // will get attached to the variable declaration, not the type.
        // There might be cases where we need to shuffle things around.

        AddMember(parser->currentScope, bufferDataTypeDecl);

        return bufferVarDecl;
    }

    static NodeBase* parseHLSLCBufferDecl(
        Parser*	parser, void* /*userData*/)
    {
        return ParseHLSLBufferDecl(parser, "ConstantBuffer");
    }

    static NodeBase* parseHLSLTBufferDecl(
        Parser*	parser, void* /*userData*/)
    {
        return ParseHLSLBufferDecl(parser, "TextureBuffer");
    }

    static void parseOptionalInheritanceClause(Parser* parser, AggTypeDeclBase* decl)
    {
        if (AdvanceIf(parser, TokenType::Colon))
        {
            do
            {
                auto base = parser->ParseTypeExp();

                auto inheritanceDecl = parser->astBuilder->create<InheritanceDecl>();
                inheritanceDecl->loc = base.exp->loc;
                inheritanceDecl->nameAndLoc.name = getName(parser, "$inheritance");
                inheritanceDecl->base = base;

                AddMember(decl, inheritanceDecl);

            } while (AdvanceIf(parser, TokenType::Comma));
        }
    }

    static NodeBase* parseExtensionDecl(Parser* parser, void* /*userData*/)
    {
        ExtensionDecl* decl = parser->astBuilder->create<ExtensionDecl>();
        parser->FillPosition(decl);
        decl->targetType = parser->ParseTypeExp();
        parseOptionalInheritanceClause(parser, decl);
        parseDeclBody(parser, decl);
        return decl;
    }


    static void parseOptionalGenericConstraints(Parser* parser, ContainerDecl* decl)
    {
        if (AdvanceIf(parser, TokenType::Colon))
        {
            do
            {
                GenericTypeConstraintDecl* paramConstraint = parser->astBuilder->create<GenericTypeConstraintDecl>();
                parser->FillPosition(paramConstraint);

                // substitution needs to be filled during check
                DeclRefType* paramType = DeclRefType::create(parser->astBuilder, DeclRef<Decl>(decl, nullptr));

                SharedTypeExpr* paramTypeExpr = parser->astBuilder->create<SharedTypeExpr>();
                paramTypeExpr->loc = decl->loc;
                paramTypeExpr->base.type = paramType;
                paramTypeExpr->type = QualType(parser->astBuilder->getTypeType(paramType));

                paramConstraint->sub = TypeExp(paramTypeExpr);
                paramConstraint->sup = parser->ParseTypeExp();

                AddMember(decl, paramConstraint);
            } while (AdvanceIf(parser, TokenType::Comma));
        }
    }

    static NodeBase* parseAssocType(Parser* parser, void *)
    {
        AssocTypeDecl* assocTypeDecl = parser->astBuilder->create<AssocTypeDecl>();

        auto nameToken = parser->ReadToken(TokenType::Identifier);
        assocTypeDecl->nameAndLoc = NameLoc(nameToken);
        assocTypeDecl->loc = nameToken.loc;
        parseOptionalGenericConstraints(parser, assocTypeDecl);
        parser->ReadToken(TokenType::Semicolon);
        return assocTypeDecl;
    }

    static NodeBase* parseGlobalGenericTypeParamDecl(Parser * parser, void *)
    {
        GlobalGenericParamDecl* genParamDecl = parser->astBuilder->create<GlobalGenericParamDecl>();
        auto nameToken = parser->ReadToken(TokenType::Identifier);
        genParamDecl->nameAndLoc = NameLoc(nameToken);
        genParamDecl->loc = nameToken.loc;
        parseOptionalGenericConstraints(parser, genParamDecl);
        parser->ReadToken(TokenType::Semicolon);
        return genParamDecl;
    }

    static NodeBase* parseGlobalGenericValueParamDecl(Parser * parser, void *)
    {
        GlobalGenericValueParamDecl* genericParamDecl = parser->astBuilder->create<GlobalGenericValueParamDecl>();
        auto nameToken = parser->ReadToken(TokenType::Identifier);
        genericParamDecl->nameAndLoc = NameLoc(nameToken);
        genericParamDecl->loc = nameToken.loc;

        if(AdvanceIf(parser, TokenType::Colon))
        {
            genericParamDecl->type = parser->ParseTypeExp();
        }

        if(AdvanceIf(parser, TokenType::OpAssign))
        {
            genericParamDecl->initExpr = parser->ParseInitExpr();
        }

        parser->ReadToken(TokenType::Semicolon);
        return genericParamDecl;
    }

    static NodeBase* parseInterfaceDecl(Parser* parser, void* /*userData*/)
    {
        InterfaceDecl* decl = parser->astBuilder->create<InterfaceDecl>();
        parser->FillPosition(decl);

        AdvanceIf(parser, TokenType::CompletionRequest);

        decl->nameAndLoc = NameLoc(parser->ReadToken(TokenType::Identifier));

        parseOptionalInheritanceClause(parser, decl);

        parseDeclBody(parser, decl);

        return decl;
    }

    static NodeBase* parseNamespaceDecl(Parser* parser, void* /*userData*/)
    {
        // We start by parsing the name of the namespace that is being opened.
        //
        // TODO: We should eventually support a qualified name for
        // a namespace declaration:
        //
        //      namespace A.B { ... }
        //
        // which should expand as if the user had written nested
        // namespace declarations:
        //
        //      namespace A { namespace B { ... } }
        //
        // TODO: Support we also support the degenerate case of
        // a namesapce without a name? Should that be treated as
        // an anonymous (and implicitly imported) namespace, or
        // something else?
        //
        // TODO: Should we support a shorthand syntax for putting
        // the rest of the current scope/file into a namespace:
        //
        //      namespace A.B;
        //
        //      ...
        //
        NameLoc nameAndLoc = NameLoc(parser->ReadToken(TokenType::Identifier));

        // Once we have the name for the namespace, we face a challenge:
        // either the namespace hasn't been seen before (in which case
        // we need to create it and start filling it in), or we've seen
        // the same namespace before inside the same module, such that
        // we should be adding the declarations we parse to the existing
        // declarations (so that they share a common scope/parent).
        //
        // In each case we will find a namespace that we want to fill in,
        // but depending on the case we may or may not want to return
        // a declaration to the caller (since they will try to add
        // any non-null pointer we return to the AST).
        //
        NamespaceDecl* namespaceDecl = nullptr;

        // In order to find out what case we are in, we start by looking
        // for a namespace declaration of the same name in the parent
        // declaration.
        //
        {
            auto parentDecl = parser->currentScope->containerDecl;
            SLANG_ASSERT(parentDecl);

            // We meed to make sure that the member dictionary of
            // the parent declaration has been built/rebuilt so that
            // lookup by name will work.
            //
            // TODO: The current way we rebuild the member dictionary
            // would make for O(N^2) parsing time in a file that
            // consisted of N back-to-back `namespace`s, since each
            // would trigger a rebuild of the member dictionary that
            // would take O(N) time.
            //

            // There might be multiple members of the same name
            // (if we define a namespace `foo` after an overloaded
            // function `foo` has been defined), and direct member
            // lookup will only give us the first.
            //
            Decl* firstDecl = nullptr;
            parentDecl->getMemberDictionary().tryGetValue(nameAndLoc.name, firstDecl);
            //
            // We will search through the declarations of the name
            // and find the first that is a namespace (if any).
            //
            // Note: we do not issue diagnostics here based on
            // the potential conflicts between these declarations,
            // because we want to do as little semantic analysis
            // as possible in the parser, and we'd rather be
            // as permissive as possible right now.
            //
            for(Decl* d = firstDecl; d; d = d->nextInContainerWithSameName)
            {
                namespaceDecl = as<NamespaceDecl>(d);
                if(namespaceDecl)
                    break;
            }

            // If we didn't find a pre-existing namespace, then
            // we will go ahead and create one now.
            //
            if( !namespaceDecl )
            {
                namespaceDecl = parser->astBuilder->create<NamespaceDecl>();
                namespaceDecl->nameAndLoc = nameAndLoc;
            }
        }

        // Now that we have a namespace declaration to fill in
        // (whether a new or existing one), we can parse the
        // `{}`-enclosed body to add declarations as children
        // of the namespace.
        //
        parseDeclBody(parser, namespaceDecl);

        return namespaceDecl;
    }

    static NodeBase* parseUsingDecl(Parser* parser, void* /*userData*/)
    {
        UsingDecl* decl = parser->astBuilder->create<UsingDecl>();
        parser->FillPosition(decl);

        // A `using` declaration will need to know about the current
        // scope at the point where it appears, so that it can know
        // the scope it is attempting to extend.
        //
        decl->scope = parser->currentScope;

        // TODO: We may eventually want to support declarations
        // of the form `using <id> = <expr>;` which introduce
        // a shorthand alias for a namespace/type/whatever.
        //
        // For now we are just sticking to the most basic form.

        // As a compatibility feature for programmers used to C++,
        // we allow the `namespace` keyword to come after `using`,
        // where it has no effect.
        //
        if(parser->LookAheadToken("namespace"))
        {
            advanceToken(parser);
        }

        // The entity that is going to be used is identified
        // using an arbitrary expression (although we expect
        // that valid code will not typically use the full
        // freedom of what the expression grammar supports.
        //
        decl->arg = parser->ParseExpression();

        expect(parser, TokenType::Semicolon);

        return decl;
    }

    static NodeBase* parseConstructorDecl(Parser* parser, void* /*userData*/)
    {
        ConstructorDecl* decl = parser->astBuilder->create<ConstructorDecl>();

        // Note: we leave the source location of this decl as invalid, to
        // trigger the fallback logic that fills in the location of the
        // `__init` keyword later.

        parser->PushScope(decl);

        // TODO: we need to make sure that all initializers have
        // the same name, but that this name doesn't conflict
        // with any user-defined names.
        // Giving them a name (rather than leaving it null)
        // ensures that we can use name-based lookup to find
        // all of the initializers on a type (and has
        // the potential to unify initializer lookup with
        // ordinary member lookup).
        decl->nameAndLoc.name = getName(parser, "$init");

        parseParameterList(parser, decl);

        decl->body = parseOptBody(parser);

        if (auto block = as<BlockStmt>(decl->body))
            decl->closingSourceLoc = block->closingSourceLoc;

        parser->PopScope();
        return decl;
    }

    static AccessorDecl* parseAccessorDecl(Parser* parser)
    {
        Modifiers modifiers = ParseModifiers(parser);

        AccessorDecl* decl = nullptr;
        auto loc = peekToken(parser).loc;
        auto name = peekToken(parser).getName();
        if( AdvanceIf(parser, "get") )
        {
            decl = parser->astBuilder->create<GetterDecl>();
        }
        else if( AdvanceIf(parser, "set") )
        {
            decl = parser->astBuilder->create<SetterDecl>();
        }
        else if( AdvanceIf(parser, "ref") )
        {
            decl = parser->astBuilder->create<RefAccessorDecl>();
        }
        else
        {
            Unexpected(parser);
            return nullptr;
        }
        decl->loc = loc;
        decl->nameAndLoc.name = name;
        decl->nameAndLoc.loc = loc;

        _addModifiers(decl, modifiers);

        parser->PushScope(decl);

        // A `set` declaration should support declaring an explicit
        // name for the parameter representing the new value.
        //
        // We handle this by supporting an arbitrary parameter list
        // on any accessor, and then assume that semantic checking
        // will diagnose any cases that aren't allowed.
        //
        if(parser->tokenReader.peekTokenType() == TokenType::LParent)
        {
            parseModernParamList(parser, decl);
        }

        if( parser->tokenReader.peekTokenType() == TokenType::LBrace )
        {
            decl->body = parser->parseBlockStatement();
            if (auto block = as<BlockStmt>(decl->body))
            {
                decl->closingSourceLoc = block->closingSourceLoc;
            }
        }
        else
        {
            decl->closingSourceLoc = parser->tokenReader.peekLoc();
            parser->ReadToken(TokenType::Semicolon);
        }

        parser->PopScope();


        return decl;
    }

    static void parseStorageDeclBody(Parser* parser, ContainerDecl* decl)
    {
        if( AdvanceIf(parser, TokenType::LBrace) )
        {
            // We want to parse nested "accessor" declarations
            Token closingToken;
            while (!AdvanceIfMatch(parser, MatchedTokenType::CurlyBraces, &closingToken))
            {
                auto accessor = parseAccessorDecl(parser);
                AddMember(decl, accessor);
            }
            decl->closingSourceLoc = closingToken.loc;
        }
        else
        {
            decl->closingSourceLoc = parser->tokenReader.peekLoc();

            parser->ReadToken(TokenType::Semicolon);

            // empty body should be treated like `{ get; }`
        }
    }

    static NodeBase* parseSubscriptDecl(Parser* parser, void* /*userData*/)
    {
        SubscriptDecl* decl = parser->astBuilder->create<SubscriptDecl>();
        parser->FillPosition(decl);
        parser->PushScope(decl);

        // TODO: the use of this name here is a bit magical...
        decl->nameAndLoc.name = getName(parser, "operator[]");

        parseParameterList(parser, decl);

        if( AdvanceIf(parser, TokenType::RightArrow) )
        {
            decl->returnType = parser->ParseTypeExp();
        }
        else
        {
            decl->returnType.exp = parser->astBuilder->create<IncompleteExpr>();
        }

        parseStorageDeclBody(parser, decl);

        parser->PopScope();
        return decl;
    }

        /// Peek in the token stream and return `true` if it looks like a modern-style variable declaration is coming up.
    static bool _peekModernStyleVarDecl(Parser* parser)
    {
        // A modern-style variable declaration always starts with an identifier
        if(peekTokenType(parser) != TokenType::Identifier)
            return false;

        switch(peekTokenType(parser, 1))
        {
        default:
            return false;

        case TokenType::Colon:
        case TokenType::Comma:
        case TokenType::RParent:
        case TokenType::RBrace:
        case TokenType::RBracket:
        case TokenType::LBrace:
            return true;
        }
    }

    static NodeBase* parsePropertyDecl(Parser* parser, void* /*userData*/)
    {
        PropertyDecl* decl = parser->astBuilder->create<PropertyDecl>();
        parser->PushScope(decl);

        // We want to support property declarations with two
        // different syntaxes.
        //
        // First, we want to support a syntax that is consistent
        // with C-style ("traditional") variable declarations:
        //
        //                int myVar = 2;
        //      proprerty int myProp { ... }
        //
        // Second we want to support a syntax that is
        // consistent with `let` and `var` declarations:
        //
        //      let      myVar  : int = 2;
        //      property myProp : int { ... }
        //
        // The latter case is more constrained, and we will
        // detect with two tokens of lookahead. If the 
        // next token (after `property`) is an identifier,
        // and the token after that is a colon (`:`), then
        // we assume we are in the `let`/`var`-style case.
        //
        if(_peekModernStyleVarDecl(parser))
        {
            parser->FillPosition(decl);
            decl->nameAndLoc = expectIdentifier(parser);
            expect(parser, TokenType::Colon);
            decl->type = parser->ParseTypeExp();
        }
        else
        {
            // The traditional syntax requires a bit more
            // care to parse, since it needs to support
            // C declarator syntax.
            //
            DeclaratorInfo declaratorInfo;
            declaratorInfo.typeSpec = parser->ParseType();

            auto declarator = parseDeclarator(parser, kDeclaratorParseOptions_None);
            UnwrapDeclarator(parser->astBuilder, declarator, &declaratorInfo);

            // TODO: We might want to handle the case where the
            // resulting declarator is not valid to use for
            // declaring a property (e.g., it has function parameters).

            decl->nameAndLoc = declaratorInfo.nameAndLoc;
            decl->type = TypeExp(declaratorInfo.typeSpec);
        }

        parseStorageDeclBody(parser, decl);

        parser->PopScope();
        return decl;
    }

    static void parseModernVarDeclBaseCommon(
        Parser*             parser,
        VarDeclBase* decl)
    {
        parser->FillPosition(decl);
        decl->nameAndLoc = NameLoc(parser->ReadToken(TokenType::Identifier));

        if(AdvanceIf(parser, TokenType::Colon))
        {
            decl->type = parser->ParseTypeExp();
        }

        if(AdvanceIf(parser, TokenType::OpAssign))
        {
            decl->initExpr = parser->ParseInitExpr();
        }
    }

    static void parseModernVarDeclCommon(
        Parser*         parser,
        VarDecl* decl)
    {
        parseModernVarDeclBaseCommon(parser, decl);
        expect(parser, TokenType::Semicolon);
    }

    static NodeBase* parseLetDecl(
        Parser* parser, void* /*userData*/)
    {
        LetDecl* decl = parser->astBuilder->create<LetDecl>();
        parseModernVarDeclCommon(parser, decl);
        return decl;
    }

    static NodeBase* parseVarDecl(
        Parser* parser, void* /*userData*/)
    {
        VarDecl* decl = parser->astBuilder->create<VarDecl>();
        parseModernVarDeclCommon(parser, decl);
        return decl;
    }

        /// Parse the common structured of a traditional-style parameter declaration (excluding the trailing semicolon)
    static void _parseTraditionalParamDeclCommonBase(Parser* parser, VarDeclBase* decl, DeclaratorParseOptions options = kDeclaratorParseOptions_None)
    {
        DeclaratorInfo declaratorInfo;
        declaratorInfo.typeSpec = parser->ParseType();

        InitDeclarator initDeclarator = parseInitDeclarator(parser, options);
        UnwrapDeclarator(parser->astBuilder, initDeclarator, &declaratorInfo);

        // Assume it is a variable-like declarator
        CompleteVarDecl(parser, decl, declaratorInfo);
    }

    static ParamDecl* parseModernParamDecl(
        Parser* parser)
    {
        // TODO: For "modern" parameters, we should probably
        // not allow arbitrary keyword-based modifiers (only allowing
        // `[attribute]`s), and should require that direction modifiers
        // like `in`, `out`, and `in out`/`inout` be applied to the
        // type (after the colon).
        //
        auto modifiers = ParseModifiers(parser);

        // We want to allow both "modern"-style and traditional-style
        // parameters to appear in any modern-style parameter list,
        // in order to allow programmers the flexibility to code in
        // a way that feels natural and not run into lots of
        // errors.
        //
        if(_peekModernStyleVarDecl(parser))
        {
            ParamDecl* decl = parser->astBuilder->create<ModernParamDecl>();
            decl->modifiers = modifiers;
            parseModernVarDeclBaseCommon(parser, decl);
            return decl;
        }
        else
        {
            ParamDecl* decl = parser->astBuilder->create<ParamDecl>();
            decl->modifiers = modifiers;
            _parseTraditionalParamDeclCommonBase(parser, decl);
            return decl;
        }
    }

    static void parseModernParamList(
        Parser*                 parser,
        CallableDecl*    decl)
    {
        parser->ReadToken(TokenType::LParent);

        while (!AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
        {
            AddMember(decl, parseModernParamDecl(parser));
            if (AdvanceIf(parser, TokenType::RParent))
                break;
            parser->ReadToken(TokenType::Comma);
        }
    }

    static NodeBase* parseFuncDecl(
        Parser* parser, void* /*userData*/)
    {
        FuncDecl* decl = parser->astBuilder->create<FuncDecl>();

        parser->FillPosition(decl);
        decl->nameAndLoc = NameLoc(parser->ReadToken(TokenType::Identifier));

        return parseOptGenericDecl(parser, [&](GenericDecl*)
        {
            parser->PushScope(decl);
            parseModernParamList(parser, decl);
            if (AdvanceIf(parser, "throws"))
            {
                decl->errorType = parser->ParseTypeExp();
            }
            if(AdvanceIf(parser, TokenType::RightArrow))
            {
                decl->returnType = parser->ParseTypeExp();
            }
            decl->body = parseOptBody(parser);
            if (auto blockStmt = as<BlockStmt>(decl->body))
                decl->closingSourceLoc = blockStmt->closingSourceLoc;
            parser->PopScope();
            return decl;
        });
    }

    static NodeBase* parseTypeAliasDecl(
        Parser* parser, void* /*userData*/)
    {
        TypeAliasDecl* decl = parser->astBuilder->create<TypeAliasDecl>();

        parser->FillPosition(decl);
        decl->nameAndLoc = NameLoc(parser->ReadToken(TokenType::Identifier));

        return parseOptGenericDecl(parser, [&](GenericDecl*)
        {
            if( expect(parser, TokenType::OpAssign) )
            {
                decl->type = parser->ParseTypeExp();
            }
            expect(parser, TokenType::Semicolon);
            return decl;
        });
    }

    // This is a catch-all syntax-construction callback to handle cases where
    // a piece of syntax is fully defined by the keyword to use, along with
    // the class of AST node to construct.
    NodeBase* parseSimpleSyntax(Parser* parser, void* userData)
    {
        SyntaxClassBase syntaxClass((ReflectClassInfo*) userData);
        return (NodeBase*)syntaxClass.createInstanceImpl(parser->astBuilder);
    }

    // Parse a declaration of a keyword that can be used to define further syntax.
    static NodeBase* parseSyntaxDecl(Parser* parser, void* /*userData*/)
    {
        // Right now the basic form is:
        //
        // syntax <name:id> [: <syntaxClass:id>] [= <existingKeyword:id>];
        //
        // - `name` gives the name of the keyword to define.
        // - `syntaxClass` is the name of an AST node class that we expect
        //   this syntax to construct when parsed.
        // - `existingKeyword` is the name of an existing keyword that
        //   the new syntax should be an alias for.

        // First we parse the keyword name.
        auto nameAndLoc = expectIdentifier(parser);

        // Next we look for a clause that specified the AST node class.
        SyntaxClass<NodeBase> syntaxClass;
        if (AdvanceIf(parser, TokenType::Colon))
        {
            // User is specifying the class that should be construted
            auto classNameAndLoc = expectIdentifier(parser);

            syntaxClass = parser->astBuilder->findSyntaxClass(classNameAndLoc.name);
        }

        // If the user specified a syntax class, then we will default
        // to the `parseSimpleSyntax` callback that will just construct
        // an instance of that type to represent the keyword in the AST.
        SyntaxParseCallback parseCallback = &parseSimpleSyntax;
        void* parseUserData = (void*) syntaxClass.classInfo;

        // Next we look for an initializer that will make this keyword
        // an alias for some existing keyword.
        if (AdvanceIf(parser, TokenType::OpAssign))
        {
            auto existingKeywordNameAndLoc = expectIdentifier(parser);

            auto existingSyntax = tryLookUpSyntaxDecl(parser, existingKeywordNameAndLoc.name);
            if (!existingSyntax)
            {
                // TODO: diagnose: keyword did not name syntax
            }
            else
            {
                // The user is expecting us to parse our new syntax like
                // the existing syntax given, so we need to override
                // the callback.
                parseCallback = existingSyntax->parseCallback;
                parseUserData = existingSyntax->parseUserData;

                // If we don't already have a syntax class specified, then
                // we will crib the one from the existing syntax, to ensure
                // that we are creating a drop-in alias.
                if (!syntaxClass.classInfo)
                    syntaxClass = existingSyntax->syntaxClass;
            }
        }

        // It is an error if the user didn't give us either an existing keyword
        // to use to the define the callback, or a valid AST node class to construct.
        //
        // TODO: down the line this should be expanded so that the user can reference
        // an existing *function* to use to parse the chosen syntax.
        if (!syntaxClass.classInfo)
        {
            // TODO: diagnose: either a type or an existing keyword needs to be specified
        }

        expect(parser, TokenType::Semicolon);

        // TODO: skip creating the declaration if anything failed, just to not screw things
        // up for downstream code?

        SyntaxDecl* syntaxDecl = parser->astBuilder->create<SyntaxDecl>();
        syntaxDecl->nameAndLoc = nameAndLoc;
        syntaxDecl->loc = nameAndLoc.loc;
        syntaxDecl->syntaxClass = syntaxClass;
        syntaxDecl->parseCallback = parseCallback;
        syntaxDecl->parseUserData = parseUserData;
        return syntaxDecl;
    }

    // A parameter declaration in an attribute declaration.
    //
    // We are going to use `name: type` syntax just for simplicty, and let the type
    // be optional, because we don't actually need it in all cases.
    //
    static ParamDecl* parseAttributeParamDecl(Parser* parser)
    {
        auto nameAndLoc = expectIdentifier(parser);

        ParamDecl* paramDecl = parser->astBuilder->create<ParamDecl>();
        paramDecl->nameAndLoc = nameAndLoc;

        if(AdvanceIf(parser, TokenType::Colon))
        {
            paramDecl->type = parser->ParseTypeExp();
        }

        if(AdvanceIf(parser, TokenType::OpAssign))
        {
            paramDecl->initExpr = parser->ParseInitExpr();
        }

        return paramDecl;
    }

    // Parse declaration of a name to be used for resolving `[attribute(...)]` style modifiers.
    //
    // These are distinct from `syntax` declarations, because their names don't get added
    // to the current scope using their default name.
    //
    // Also, attribute-specific code doesn't get invokved during parsing. We always parse
    // using the default attribute-parsing logic and then all specialized behavior takes
    // place during semantic checking.
    //
    static NodeBase* parseAttributeSyntaxDecl(Parser* parser, void* /*userData*/)
    {
        // Right now the basic form is:
        //
        // attribute_syntax <name:id> : <syntaxClass:id>;
        //
        // - `name` gives the name of the attribute to define.
        // - `syntaxClass` is the name of an AST node class that we expect
        //   this attribute to create when checked.
        // - `existingKeyword` is the name of an existing keyword that
        //   the new syntax should be an alias for.

        expect(parser, TokenType::LBracket);

        // First we parse the attribute name.
        auto nameAndLoc = expectIdentifier(parser);

        AttributeDecl* attrDecl = parser->astBuilder->create<AttributeDecl>();
        if(AdvanceIf(parser, TokenType::LParent))
        {
            while(!AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
            {
                auto param = parseAttributeParamDecl(parser);

                AddMember(attrDecl, param);

                if(AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
                    break;

                expect(parser, TokenType::Comma);
            }
        }

        expect(parser, TokenType::RBracket);

        // TODO: we should allow parameters to be specified here, to cut down
        // on the amount of per-attribute-type logic that has to occur later.

        // Next we look for a clause that specified the AST node class.
        SyntaxClass<NodeBase> syntaxClass;
        if (AdvanceIf(parser, TokenType::Colon))
        {
            // User is specifying the class that should be construted
            auto classNameAndLoc = expectIdentifier(parser);
            syntaxClass = parser->astBuilder->findSyntaxClass(classNameAndLoc.name);

            assert(syntaxClass.classInfo);
        }
        else
        {
            // For now we don't support the alternative approach where
            // an existing piece of syntax is named to provide the parsing
            // support.

            // TODO: diagnose: a syntax class must be specified.
        }

        expect(parser, TokenType::Semicolon);

        // TODO: skip creating the declaration if anything failed, just to not screw things
        // up for downstream code?

        attrDecl->nameAndLoc = nameAndLoc;
        attrDecl->loc = nameAndLoc.loc;
        attrDecl->syntaxClass = syntaxClass;
        return attrDecl;
    }

    // Finish up work on a declaration that was parsed
    static void CompleteDecl(
        Parser*				/*parser*/,
        Decl*		decl,
        ContainerDecl*		containerDecl,
        Modifiers			modifiers)
    {

        // If this is a namespace and already added, we don't want to add to the parent
        // Or add any modifiers
        if (as<NamespaceDecl>(decl) && decl->parentDecl)
        {
            // Presumably we have no modifiers.
            SLANG_ASSERT(modifiers.isEmpty());
            return;
        }

        // Add any modifiers we parsed before the declaration to the list
        // of modifiers on the declaration itself.
        //
        // We need to be careful, because if `decl` is a generic declaration,
        // then we really want the modifiers to apply to the inner declaration.
        //
        Decl* declToModify = decl;
        if(auto genericDecl = as<GenericDecl>(decl))
            declToModify = genericDecl->inner;
        _addModifiers(declToModify, modifiers);

        if (containerDecl)
        {
            // Make sure the decl is properly nested inside its lexical parent
            AddMember(containerDecl, decl);
        }
    }

    static DeclBase* ParseDeclWithModifiers(
        Parser*             parser,
        ContainerDecl*      containerDecl,
        Modifiers           modifiers )
    {
        DeclBase* decl = nullptr;

        auto loc = parser->tokenReader.peekLoc();

        switch (peekTokenType(parser))
        {
        case TokenType::Identifier:
            {
                // A declaration that starts with an identifier might be:
                //
                // - A keyword-based declaration (e.g., `cbuffer ...`)
                // - The beginning of a type in a declarator-based declaration (e.g., `int ...`)

                // First we will check whether we can use the identifier token
                // as a declaration keyword and parse a declaration using
                // its associated callback:
                Decl* parsedDecl = nullptr;
                if (tryParseUsingSyntaxDecl<Decl>(parser, &parsedDecl))
                {
                    decl = parsedDecl;
                    break;
                }

                // Our final fallback case is to assume that the user is
                // probably writing a C-style declarator-based declaration.
                decl = ParseDeclaratorDecl(parser, containerDecl, modifiers);
                break;
            }
            break;

        // It is valid in HLSL/GLSL to have an "empty" declaration
        // that consists of just a semicolon. In particular, this
        // gets used a lot in GLSL to attach custom semantics to
        // shader input or output.
        //
        case TokenType::Semicolon:
            {
                advanceToken(parser);

                decl = parser->astBuilder->create<EmptyDecl>();
                decl->loc = loc;
            }
            break;

        case TokenType::LBrace:
        case TokenType::LParent:
            {
                // We shouldn't be seeing an LBrace or an LParent when expecting a decl.
                // However recovery logic may lead us here. In this case we just
                // skip the whole `{}` block and return an empty decl.
                SkipBalancedToken(&parser->tokenReader);
                decl = parser->astBuilder->create<EmptyDecl>();
                decl->loc = loc;
            }
            break;
        // If nothing else matched, we try to parse an "ordinary" declarator-based declaration
        default:
            decl = ParseDeclaratorDecl(parser, containerDecl, modifiers);
            break;
        }

        if (decl)
        {
            if( auto dd = as<Decl>(decl) )
            {
                CompleteDecl(parser, dd, containerDecl, modifiers);
            }
            else if(auto declGroup = as<DeclGroup>(decl))
            {
                // We are going to add the same modifiers to *all* of these declarations,
                // so we want to give later passes a way to detect which modifiers
                // were shared, vs. which ones are specific to a single declaration.

                auto sharedModifiers = parser->astBuilder->create<SharedModifiers>();
                sharedModifiers->next = modifiers.first;
                modifiers.first = sharedModifiers;

                for( auto subDecl : declGroup->decls )
                {
                    CompleteDecl(parser, subDecl, containerDecl, modifiers);
                }
            }
        }
        return decl;
    }

    static DeclBase* ParseDecl(
        Parser*         parser,
        ContainerDecl*  containerDecl)
    {
        Modifiers modifiers = ParseModifiers(parser);
        return ParseDeclWithModifiers(parser, containerDecl, modifiers);
    }

    static Decl* ParseSingleDecl(
        Parser*			parser,
        ContainerDecl*	containerDecl)
    {
        auto declBase = ParseDecl(parser, containerDecl);
        if(!declBase)
            return nullptr;
        if( auto decl = as<Decl>(declBase) )
        {
            return decl;
        }
        else if( auto declGroup = as<DeclGroup>(declBase) )
        {
            if( declGroup->decls.getCount() == 1 )
            {
                return declGroup->decls[0];
            }
        }

        parser->sink->diagnose(declBase->loc, Diagnostics::unimplemented, "didn't expect multiple declarations here");
        return nullptr;
    }


    static void parseDecls(
        Parser*             parser,
        ContainerDecl*      containerDecl,
        MatchedTokenType    matchType)
    {
        Token closingBraceToken;
        while (!AdvanceIfMatch(parser, matchType, &closingBraceToken))
        {
            ParseDecl(parser, containerDecl);
        }
        containerDecl->closingSourceLoc = closingBraceToken.loc;
    }

    static void parseDeclBody(
        Parser*         parser,
        ContainerDecl*  parent)
    {
        parser->PushScope(parent);

        parser->ReadToken(TokenType::LBrace);
        parseDecls(parser, parent, MatchedTokenType::CurlyBraces);

        parser->PopScope();
    }


    void Parser::parseSourceFile(ModuleDecl* program)
    {
        if (outerScope)
        {
            currentScope = outerScope;
        }

        PushScope(program);

        // A single `ModuleDecl` might span multiple source files, so it
        // is possible that we are parsing a new source file into a module
        // that has already been created and filled in for a previous
        // source file.
        //
        // If this is the first source file for the module then we expect
        // its location information to be invalid, and we will set it to
        // refer to the start of the first source file.
        //
        // This convention is reasonable for any single-source-file module,
        // and about as good as possible for multiple-file modules.
        //
        if(!program->loc.isValid())
        {
            program->loc = tokenReader.peekLoc();
        }

        parseDecls(this, program, MatchedTokenType::File);
        PopScope();

        SLANG_RELEASE_ASSERT(currentScope == outerScope);
        currentScope = nullptr;
    }

    Decl* Parser::ParseStruct()
    {
        StructDecl* rs = astBuilder->create<StructDecl>();
        ReadToken("struct");
        FillPosition(rs);

        // The `struct` keyword may optionally be followed by
        // attributes that appertain to the struct declaration
        // itself, and not to any variables declared using this
        // type specifier.
        //
        // TODO: We don't yet correctly associate attributes with
        // a variable decarlation vs. a struct type when a variable
        // is declared with a struct type specified.
        //
        if(LookAheadToken(TokenType::LBracket))
        {
            Modifier** modifierLink = &rs->modifiers.first;
            ParseSquareBracketAttributes(this, &modifierLink);
        }

        // Skip completion request token to prevent producing a type named completion request.
        AdvanceIf(this, TokenType::CompletionRequest);

        // TODO: support `struct` declaration without tag
        rs->nameAndLoc = expectIdentifier(this);
        return parseOptGenericDecl(this, [&](GenericDecl*)
        {
            // We allow for an inheritance clause on a `struct`
            // so that it can conform to interfaces.
            parseOptionalInheritanceClause(this, rs);
            parseDeclBody(this, rs);
            return rs;
        });
    }

    ClassDecl* Parser::ParseClass()
    {
        ClassDecl* rs = astBuilder->create<ClassDecl>();
        ReadToken("class");

        AdvanceIf(this, TokenType::CompletionRequest);

        FillPosition(rs);
        rs->nameAndLoc = expectIdentifier(this);

        parseOptionalInheritanceClause(this, rs);

        parseDeclBody(this, rs);
        return rs;
    }

    static EnumCaseDecl* parseEnumCaseDecl(Parser* parser)
    {
        EnumCaseDecl* decl = parser->astBuilder->create<EnumCaseDecl>();
        parser->FillPosition(decl);
        
        decl->nameAndLoc = expectIdentifier(parser);

        if(AdvanceIf(parser, TokenType::OpAssign))
        {
            decl->tagExpr = parser->ParseArgExpr();
        }

        return decl;
    }

    static Decl* parseEnumDecl(Parser* parser)
    {
        EnumDecl* decl = parser->astBuilder->create<EnumDecl>();

        parser->ReadToken("enum");

        // HACK: allow the user to write `enum class` in case
        // they are trying to share a header between C++ and Slang.
        //
        // TODO: diagnose this with a warning some day, and move
        // toward deprecating it.
        //
        AdvanceIf(parser, "class");

        AdvanceIf(parser, TokenType::CompletionRequest);

        parser->FillPosition(decl);

        decl->nameAndLoc = expectIdentifier(parser);


        return parseOptGenericDecl(parser, [&](GenericDecl*)
        {
            parseOptionalInheritanceClause(parser, decl);
            parser->ReadToken(TokenType::LBrace);
            Token closingToken;
            while (!AdvanceIfMatch(parser, MatchedTokenType::CurlyBraces, &closingToken))
            {
                EnumCaseDecl* caseDecl = parseEnumCaseDecl(parser);
                AddMember(decl, caseDecl);

                if(AdvanceIf(parser, TokenType::RBrace))
                    break;

                parser->ReadToken(TokenType::Comma);
            }
            decl->closingSourceLoc = closingToken.loc;
            return decl;
        });
    }

    static Stmt* ParseSwitchStmt(Parser* parser)
    {
        SwitchStmt* stmt = parser->astBuilder->create<SwitchStmt>();
        parser->FillPosition(stmt);
        parser->ReadToken("switch");
        parser->ReadToken(TokenType::LParent);
        stmt->condition = parser->ParseExpression();
        parser->ReadToken(TokenType::RParent);
        stmt->body = parser->parseBlockStatement();
        return stmt;
    }

    static Stmt* ParseCaseStmt(Parser* parser)
    {
        CaseStmt* stmt = parser->astBuilder->create<CaseStmt>();
        parser->FillPosition(stmt);
        parser->ReadToken("case");
        stmt->expr = parser->ParseExpression();
        parser->ReadToken(TokenType::Colon);
        return stmt;
    }

    static Stmt* ParseDefaultStmt(Parser* parser)
    {
        DefaultStmt* stmt = parser->astBuilder->create<DefaultStmt>();
        parser->FillPosition(stmt);
        parser->ReadToken("default");
        parser->ReadToken(TokenType::Colon);
        return stmt;
    }

    GpuForeachStmt* ParseGpuForeachStmt(Parser* parser)
    {
        // Hard-coding parsing of the following:
        // __GPU_FOREACH(renderer, gridDims, LAMBDA(uint3 dispatchThreadID) {
        //  kernelCall(args, ...); });

        // Setup the scope so that dispatchThreadID is in scope for kernelCall
        ScopeDecl* scopeDecl = parser->astBuilder->create<ScopeDecl>();
        GpuForeachStmt* stmt = parser->astBuilder->create<GpuForeachStmt>();
        stmt->scopeDecl = scopeDecl;

        parser->FillPosition(stmt);
        parser->ReadToken("__GPU_FOREACH");
        parser->ReadToken(TokenType::LParent);
        stmt->device = parser->ParseArgExpr();
        parser->ReadToken(TokenType::Comma);
        stmt->gridDims = parser->ParseArgExpr();

        parser->ReadToken(TokenType::Comma);
        parser->ReadToken("LAMBDA");
        parser->ReadToken(TokenType::LParent);

        auto idType = parser->ParseTypeExp();
        NameLoc varNameAndLoc = expectIdentifier(parser);
        VarDecl* varDecl = parser->astBuilder->create<VarDecl>();
        varDecl->nameAndLoc = varNameAndLoc;
        varDecl->loc = varNameAndLoc.loc;
        varDecl->type = idType;
        stmt->dispatchThreadID = varDecl;

        parser->ReadToken(TokenType::RParent);
        parser->ReadToken(TokenType::LBrace);

        parser->pushScopeAndSetParent(scopeDecl);
        AddMember(parser->currentScope, varDecl);

        stmt->kernelCall = parser->ParseExpression();

        parser->PopScope();

        parser->ReadToken(TokenType::Semicolon);
        parser->ReadToken(TokenType::RBrace);

        parser->ReadToken(TokenType::RParent);

        parser->ReadToken(TokenType::Semicolon);

        return stmt;
    }

    static bool _isType(Decl* decl)
    {
        return decl && (as<AggTypeDecl>(decl) || as<SimpleTypeDecl>(decl));
    }

    // TODO(JS):
    // This only handles StaticMemberExpr, and VarExpr lookup scenarios!
    static Decl* _tryResolveDecl(Parser* parser, Expr* expr)
    {
        if (auto staticMemberExpr = as<StaticMemberExpr>(expr))
        {
            Decl* baseTypeDecl = _tryResolveDecl(parser, staticMemberExpr->baseExpression);
            if (!baseTypeDecl)
            {
                return nullptr;
            }
            if (AggTypeDecl* aggTypeDecl = as<AggTypeDecl>(baseTypeDecl))
            {
                // TODO(JS):
                // Is it valid to always have empty substitution set here?
                DeclRef<ContainerDecl> declRef(aggTypeDecl, SubstitutionSet());

                auto lookupResult = lookUpDirectAndTransparentMembers(
                    parser->astBuilder,
                    nullptr, // no semantics visitor available yet
                    staticMemberExpr->name,
                    declRef);

                if (!lookupResult.isValid() || lookupResult.isOverloaded())
                    return nullptr;

                return lookupResult.item.declRef.getDecl();
            }

            // Didn't find it
            return nullptr;
        }

        if (auto varExpr = as<VarExpr>(expr))
        {
            // Do the lookup in the current scope
            auto lookupResult = lookUp(
                parser->astBuilder,
                nullptr, // no semantics visitor available yet
                varExpr->name,
                parser->currentScope);
            if (!lookupResult.isValid() || lookupResult.isOverloaded())
                return nullptr;

            return lookupResult.item.declRef.getDecl();
        }

        return nullptr;
    }

    static bool isTypeName(Parser* parser, Name* name)
    {
        auto lookupResult = lookUp(
            parser->astBuilder,
            nullptr, // no semantics visitor available yet
            name,
            parser->currentScope);
        if(!lookupResult.isValid() || lookupResult.isOverloaded())
            return false;

        return _isType(lookupResult.item.declRef.getDecl());
    }

    static bool peekTypeName(Parser* parser)
    {
        if(!parser->LookAheadToken(TokenType::Identifier))
            return false;

        auto name = parser->tokenReader.peekToken().getName();
        return isTypeName(parser, name);
    }

    Stmt* parseCompileTimeForStmt(
        Parser* parser)
    {
        ScopeDecl* scopeDecl = parser->astBuilder->create<ScopeDecl>();
        CompileTimeForStmt* stmt = parser->astBuilder->create<CompileTimeForStmt>();
        stmt->scopeDecl = scopeDecl;


        parser->ReadToken("for");
        parser->ReadToken(TokenType::LParent);

        NameLoc varNameAndLoc = expectIdentifier(parser);
        VarDecl* varDecl = parser->astBuilder->create<VarDecl>();
        varDecl->nameAndLoc = varNameAndLoc;
        varDecl->loc = varNameAndLoc.loc;

        stmt->varDecl = varDecl;

        parser->ReadToken("in");
        parser->ReadToken("Range");
        parser->ReadToken(TokenType::LParent);

        Expr* rangeBeginExpr = nullptr;
        Expr* rangeEndExpr = parser->ParseArgExpr();
        if (AdvanceIf(parser, TokenType::Comma))
        {
            rangeBeginExpr = rangeEndExpr;
            rangeEndExpr = parser->ParseArgExpr();
        }

        stmt->rangeBeginExpr = rangeBeginExpr;
        stmt->rangeEndExpr = rangeEndExpr;

        parser->ReadToken(TokenType::RParent);
        parser->ReadToken(TokenType::RParent);

        parser->pushScopeAndSetParent(scopeDecl);
        AddMember(parser->currentScope, varDecl);

        stmt->body = parser->ParseStatement();

        parser->PopScope();

        return stmt;
    }

    Stmt* parseCompileTimeStmt(
        Parser* parser)
    {
        parser->ReadToken(TokenType::Dollar);
        if (parser->LookAheadToken("for"))
        {
            return parseCompileTimeForStmt(parser);
        }
        else
        {
            Unexpected(parser);
            return nullptr;
        }
    }

    Stmt* Parser::ParseStatement()
    {
        auto modifiers = ParseModifiers(this);

        Stmt* statement = nullptr;
        if (LookAheadToken(TokenType::LBrace))
            statement = parseBlockStatement();
        else if (LookAheadToken("if"))
            statement = parseIfStatement();
        else if (LookAheadToken("for"))
            statement = ParseForStatement();
        else if (LookAheadToken("while"))
            statement = ParseWhileStatement();
        else if (LookAheadToken("do"))
            statement = ParseDoWhileStatement();
        else if (LookAheadToken("break"))
            statement = ParseBreakStatement();
        else if (LookAheadToken("continue"))
            statement = ParseContinueStatement();
        else if (LookAheadToken("return"))
            statement = ParseReturnStatement();
        else if (LookAheadToken("discard"))
        {
            statement = astBuilder->create<DiscardStmt>();
            FillPosition(statement);
            ReadToken("discard");
            ReadToken(TokenType::Semicolon);
        }
        else if (LookAheadToken("switch"))
            statement = ParseSwitchStmt(this);
        else if (LookAheadToken("case"))
            statement = ParseCaseStmt(this);
        else if (LookAheadToken("default"))
            statement = ParseDefaultStmt(this);
        else if (LookAheadToken("__GPU_FOREACH"))
            statement = ParseGpuForeachStmt(this);
        else if (LookAheadToken(TokenType::Dollar))
        {
            statement = parseCompileTimeStmt(this);
        }
        else if (LookAheadToken("try"))
        {
            statement = ParseExpressionStatement();
        }
        else if (LookAheadToken(TokenType::Identifier))
        {
            if (LookAheadToken(TokenType::Colon, 1))
            {
                // An identifier followed by an ":" is a label.
                return parseLabelStatement();
            }

            // We might be looking at a local declaration, or an
            // expression statement, and we need to figure out which.
            //
            // We'll solve this with backtracking for now.
            //
            // TODO: This should not require backtracking at all.

            TokenReader::ParsingCursor startPos = tokenReader.getCursor();

            // Try to parse a type (knowing that the type grammar is
            // a subset of the expression grammar, and so this should
            // always succeed).
            //
            // HACK: The type grammar that `ParseType` supports is *not*
            // a subset of the expression grammar because it includes
            // type specififers like `struct` and `enum` declarations
            // which should always be the start of a declaration.
            //
            // TODO: Before launching into this attempt to parse a type,
            // this logic should really be looking up the `SyntaxDecl`,
            // if any, assocaited with the identifier. If a piece of
            // syntax is discovered, then it should dictate the next
            // steps of parsing, and only in the case where the lookahead
            // isn't a keyword should we fall back to the approach
            // here.
            //
            bool prevHasSeenCompletionToken = hasSeenCompletionToken;
            Expr* type = ParseType();

            // We don't actually care about the type, though, so
            // don't retain it
            //
            // TODO: There is no reason to throw away the work we
            // did parsing the `type` expression. Once we disambiguate
            // what to do, we should be able to use the expression
            // we already parsed as a starting point for whatever we
            // parse next. E.g., if we have `A.b` and the lookahead is `+`
            // then we can use `A.b` as the left-hand-side expression
            // when starting to parse an infix expression.
            //
            type = nullptr;
            SLANG_UNUSED(type);

            // TODO: If we decide to intermix parsing of statement bodies
            // with semantic checking (by delaying the parsing of bodies
            // until semantic context is available), then we could look
            // at the *type* of `type` to disambiguate what to do next,
            // which might result in a nice simplification (at the cost
            // of definitely making the grammar context-dependent).

            // If the next token after we parsed a type looks like
            // we are going to declare a variable, then lets guess
            // that this is a declaration.
            //
            // TODO(tfoley): this wouldn't be robust for more
            // general kinds of declarators (notably pointer declarators),
            // so we'll need to be careful about this.
            //
            // If the line being parsed token is `Something* ...`, then the `*`
            // is already consumed by `ParseType` above and the current logic
            // will continue to parse as var declaration instead of a mul expr.
            // In this context it makes sense to disambiguate
            // in favor of a pointer over a multiply, since a multiply
            // expression can't appear at the start of a statement
            // with any side effects.
            //
            //
            if (!hasSeenCompletionToken && (LookAheadToken(TokenType::Identifier) ||
                                            LookAheadToken(TokenType::CompletionRequest)))
            {
                // Reset the cursor and try to parse a declaration now.
                // Note: the declaration will consume any modifiers
                // that had been in place on the statement.
                tokenReader.setCursor(startPos);
                statement = parseVarDeclrStatement(modifiers);
                return statement;
            }

            // Fallback: reset and parse an expression
            hasSeenCompletionToken = prevHasSeenCompletionToken;
            tokenReader.setCursor(startPos);
            statement = ParseExpressionStatement();
        }
        else if (LookAheadToken(TokenType::Semicolon))
        {
            statement = astBuilder->create<EmptyStmt>();
            FillPosition(statement);
            ReadToken(TokenType::Semicolon);
        }
        else
        {
            // Default case should always fall back to parsing an expression,
            // and then let that detect any errors
            statement = ParseExpressionStatement();
        }

        if (statement && !as<DeclStmt>(statement))
        {
            // Install any modifiers onto the statement.
            // Note: this path is bypassed in the case of a
            // declaration statement, so we don't end up
            // doubling up the modifiers.
            statement->modifiers = modifiers;
        }

        return statement;
    }

    Stmt* Parser::parseBlockStatement()
    {
        if(!beginMatch(this, MatchedTokenType::CurlyBraces))
        {
            auto emptyStmt = astBuilder->create<EmptyStmt>();
            FillPosition(emptyStmt);
            return emptyStmt;
        }

        ScopeDecl* scopeDecl = astBuilder->create<ScopeDecl>();
        BlockStmt* blockStatement = astBuilder->create<BlockStmt>();
        blockStatement->scopeDecl = scopeDecl;
        pushScopeAndSetParent(scopeDecl);

        Stmt* body = nullptr;


        if(!tokenReader.isAtEnd())
        {
            FillPosition(blockStatement);
        }

        Token closingBraceToken;
        while (!AdvanceIfMatch(this, MatchedTokenType::CurlyBraces, &closingBraceToken))
        {
            auto stmt = ParseStatement();
            if(stmt)
            {
                if (!body)
                {
                    body = stmt;
                }
                else if (auto seqStmt = as<SeqStmt>(body))
                {
                    seqStmt->stmts.add(stmt);
                }
                else
                {
                    SeqStmt* newBody = astBuilder->create<SeqStmt>();
                    newBody->loc = blockStatement->loc;
                    newBody->stmts.add(body);
                    newBody->stmts.add(stmt);

                    body = newBody;
                }
            }
            TryRecover(this);
        }
        PopScope();

        // Save the closing braces source loc
        blockStatement->closingSourceLoc = closingBraceToken.loc;

        if(!body)
        {
            body = astBuilder->create<EmptyStmt>();
            body->loc = blockStatement->loc;
        }

        blockStatement->body = body;
        return blockStatement;
    }

    Stmt* Parser::parseLabelStatement()
    {
        LabelStmt* stmt = astBuilder->create<LabelStmt>();
        FillPosition(stmt);
        stmt->label = ReadToken(TokenType::Identifier);
        ReadToken(TokenType::Colon);
        stmt->innerStmt = ParseStatement();
        return stmt;
    }

    DeclStmt* Parser::parseVarDeclrStatement(
        Modifiers modifiers)
    {
        DeclStmt*varDeclrStatement = astBuilder->create<DeclStmt>();

        FillPosition(varDeclrStatement);
        auto decl = ParseDeclWithModifiers(this, currentScope->containerDecl, modifiers);
        varDeclrStatement->decl = decl;
        return varDeclrStatement;
    }

    IfStmt* Parser::parseIfStatement()
    {
        IfStmt* ifStatement = astBuilder->create<IfStmt>();
        FillPosition(ifStatement);
        ReadToken("if");
        ReadToken(TokenType::LParent);
        ifStatement->predicate = ParseExpression();
        ReadToken(TokenType::RParent);
        ifStatement->positiveStatement = ParseStatement();
        if (LookAheadToken("else"))
        {
            ReadToken("else");
            ifStatement->negativeStatement = ParseStatement();
        }
        return ifStatement;
    }

    ForStmt* Parser::ParseForStatement()
    {
        ScopeDecl* scopeDecl = astBuilder->create<ScopeDecl>();

        // HLSL implements the bad approach to scoping a `for` loop
        // variable, and we want to respect that, but *only* when
        // parsing HLSL code.
        //

        bool brokenScoping = getSourceLanguage() == SourceLanguage::HLSL;

        // We will create a distinct syntax node class for the unscoped
        // case, just so that we can correctly handle it in downstream
        // logic.
        //
        ForStmt* stmt = nullptr;
        if (brokenScoping)
        {
            stmt = astBuilder->create<UnscopedForStmt>();
        }
        else
        {
            stmt = astBuilder->create<ForStmt>();
        }

        stmt->scopeDecl = scopeDecl;

        if(!brokenScoping)
            pushScopeAndSetParent(scopeDecl);
        FillPosition(stmt);
        ReadToken("for");
        ReadToken(TokenType::LParent);
        if (peekTypeName(this))
        {
            stmt->initialStatement = parseVarDeclrStatement(Modifiers());
        }
        else
        {
            if (!LookAheadToken(TokenType::Semicolon))
            {
                stmt->initialStatement = ParseExpressionStatement();
            }
            else
            {
                ReadToken(TokenType::Semicolon);
            }
        }
        if (!LookAheadToken(TokenType::Semicolon))
            stmt->predicateExpression = ParseExpression();
        ReadToken(TokenType::Semicolon);
        if (!LookAheadToken(TokenType::RParent))
            stmt->sideEffectExpression = ParseExpression();
        ReadToken(TokenType::RParent);
        stmt->statement = ParseStatement();

        if (!brokenScoping)
            PopScope();

        return stmt;
    }

    WhileStmt* Parser::ParseWhileStatement()
    {
        WhileStmt* whileStatement = astBuilder->create<WhileStmt>();
        FillPosition(whileStatement);
        ReadToken("while");
        ReadToken(TokenType::LParent);
        whileStatement->predicate = ParseExpression();
        ReadToken(TokenType::RParent);
        whileStatement->statement = ParseStatement();
        return whileStatement;
    }

    DoWhileStmt* Parser::ParseDoWhileStatement()
    {
        DoWhileStmt* doWhileStatement = astBuilder->create<DoWhileStmt>();
        FillPosition(doWhileStatement);
        ReadToken("do");
        doWhileStatement->statement = ParseStatement();
        ReadToken("while");
        ReadToken(TokenType::LParent);
        doWhileStatement->predicate = ParseExpression();
        ReadToken(TokenType::RParent);
        ReadToken(TokenType::Semicolon);
        return doWhileStatement;
    }

    BreakStmt* Parser::ParseBreakStatement()
    {
        BreakStmt* breakStatement = astBuilder->create<BreakStmt>();
        FillPosition(breakStatement);
        ReadToken("break");
        if (LookAheadToken(TokenType::Identifier))
        {
            breakStatement->targetLabel = ReadToken();
        }
        ReadToken(TokenType::Semicolon);
        return breakStatement;
    }

    ContinueStmt* Parser::ParseContinueStatement()
    {
        ContinueStmt* continueStatement = astBuilder->create<ContinueStmt>();
        FillPosition(continueStatement);
        ReadToken("continue");
        ReadToken(TokenType::Semicolon);
        return continueStatement;
    }

    ReturnStmt* Parser::ParseReturnStatement()
    {
        ReturnStmt* returnStatement = astBuilder->create<ReturnStmt>();
        FillPosition(returnStatement);
        ReadToken("return");
        if (!LookAheadToken(TokenType::Semicolon))
            returnStatement->expression = ParseExpression();
        ReadToken(TokenType::Semicolon);
        return returnStatement;
    }

    ExpressionStmt* Parser::ParseExpressionStatement()
    {
        ExpressionStmt* statement = astBuilder->create<ExpressionStmt>();

        FillPosition(statement);
        statement->expression = ParseExpression();

        ReadToken(TokenType::Semicolon);
        return statement;
    }

    ParamDecl* Parser::ParseParameter()
    {
        ParamDecl* parameter = astBuilder->create<ParamDecl>();
        parameter->modifiers = ParseModifiers(this);

        _parseTraditionalParamDeclCommonBase(this, parameter, kDeclaratorParseOption_AllowEmpty);

        return parameter;
    }

        /// Parse an "atomic" type expression.
        ///
        /// An atomic type expression is a type specifier followed by an optional
        /// body in the case of a `struct`, `enum`, etc.
        ///
    static Expr* _parseAtomicTypeExpr(Parser* parser)
    {
        auto typeSpec = _parseTypeSpec(parser);
        if( typeSpec.decl )
        {
            AddMember(parser->currentScope, typeSpec.decl);
        }
        return typeSpec.expr;
    }

        /// Parse a postfix type expression.
        ///
        /// A postfix type expression is an atomic type expression followed
        /// by zero or more postifx suffixes like array brackets.
        ///
    static Expr* _parsePostfixTypeExpr(Parser* parser)
    {
        auto typeExpr = _parseAtomicTypeExpr(parser);
        return parsePostfixTypeSuffix(parser, typeExpr);
    }

    static Expr* _parseInfixTypeExprSuffix(Parser* parser, Expr* leftExpr)
    {
        for(;;)
        {
            // As long as the next token is an `&`, we will try
            // to gobble up another type expression and form
            // a conjunction type expression.

            auto loc = peekToken(parser).loc;
            if(!AdvanceIf(parser, TokenType::OpBitAnd))
                break;

            auto rightExpr = _parsePostfixTypeExpr(parser);

            auto andExpr = parser->astBuilder->create<AndTypeExpr>();
            andExpr->loc = loc;
            andExpr->left = TypeExp(leftExpr);
            andExpr->right = TypeExp(rightExpr);
            leftExpr = andExpr;
        }

        return leftExpr;
    }

        /// Parse an infix type expression.
        ///
        /// Currently, the only infix type expression we support is the `&`
        /// operator for forming interface conjunctions.
        ///
    static Expr* _parseInfixTypeExpr(Parser* parser)
    {
        auto leftExpr = _parsePostfixTypeExpr(parser);
        return _parseInfixTypeExprSuffix(parser, leftExpr);
    }

    Expr* Parser::ParseType()
    {
        return _parseInfixTypeExpr(this);
    }

    TypeExp Parser::ParseTypeExp()
    {
        return TypeExp(ParseType());
    }

    enum class Associativity
    {
        Left, Right
    };



    Associativity GetAssociativityFromLevel(Precedence level)
    {
        if (level == Precedence::Assignment)
            return Associativity::Right;
        else
            return Associativity::Left;
    }




    Precedence GetOpLevel(Parser* parser, const Token& token)
    {
        switch(token.type)
        {
        case TokenType::QuestionMark:
            return Precedence::TernaryConditional;
        case TokenType::Comma:
            return Precedence::Comma;
        case TokenType::OpAssign:
        case TokenType::OpMulAssign:
        case TokenType::OpDivAssign:
        case TokenType::OpAddAssign:
        case TokenType::OpSubAssign:
        case TokenType::OpModAssign:
        case TokenType::OpShlAssign:
        case TokenType::OpShrAssign:
        case TokenType::OpOrAssign:
        case TokenType::OpAndAssign:
        case TokenType::OpXorAssign:
            return Precedence::Assignment;
        case TokenType::OpOr:
            return Precedence::LogicalOr;
        case TokenType::OpAnd:
            return Precedence::LogicalAnd;
        case TokenType::OpBitOr:
            return Precedence::BitOr;
        case TokenType::OpBitXor:
            return Precedence::BitXor;
        case TokenType::OpBitAnd:
            return Precedence::BitAnd;
        case TokenType::OpEql:
        case TokenType::OpNeq:
            return Precedence::EqualityComparison;
        case TokenType::OpGreater:
        case TokenType::OpGeq:
            // Don't allow these ops inside a generic argument
            if (parser->genericDepth > 0) return Precedence::Invalid;
            ; // fall-thru
        case TokenType::OpLeq:
        case TokenType::OpLess:
            return Precedence::RelationalComparison;
        case TokenType::OpRsh:
            // Don't allow this op inside a generic argument
            if (parser->genericDepth > 0) return Precedence::Invalid;
            ; // fall-thru
        case TokenType::OpLsh:
            return Precedence::BitShift;
        case TokenType::OpAdd:
        case TokenType::OpSub:
            return Precedence::Additive;
        case TokenType::OpMul:
        case TokenType::OpDiv:
        case TokenType::OpMod:
            return Precedence::Multiplicative;
        default:
            if (token.getContent() == "is" || token.getContent() == "as")
            {
                return Precedence::RelationalComparison;
            }
            return Precedence::Invalid;
        }
    }

    static Expr* parseOperator(Parser* parser)
    {
        Token opToken;
        switch(parser->tokenReader.peekTokenType())
        {
        case TokenType::QuestionMark:
            opToken = parser->ReadToken();
            opToken.setContent(UnownedStringSlice::fromLiteral("?:"));
            break;

        default:
            opToken = parser->ReadToken();
            break;
        }

        auto opExpr = parser->astBuilder->create<VarExpr>();
        opExpr->name = getName(parser, opToken.getContent());
        opExpr->scope = parser->currentScope;
        opExpr->loc = opToken.loc;

        return opExpr;

    }

    static Expr* createInfixExpr(
        Parser*         parser,
        Expr*    left,
        Expr*    op,
        Expr*    right)
    {
        InfixExpr* expr = parser->astBuilder->create<InfixExpr>();
        expr->loc = op->loc;
        expr->functionExpr = op;
        expr->arguments.add(left);
        expr->arguments.add(right);
        return expr;
    }

    static Expr* parseInfixExprWithPrecedence(
        Parser*                         parser,
        Expr*    inExpr,
        Precedence                      prec)
    {
        auto expr = inExpr;
        for(;;)
        {
            auto opToken = parser->tokenReader.peekToken();
            auto opPrec = GetOpLevel(parser, opToken);
            if(opPrec < prec)
                break;

            // Special case the "is" and "as" operators.
            if (opToken.type == TokenType::Identifier)
            {
                if (opToken.getContent() == "is")
                {
                    auto isExpr = parser->astBuilder->create<IsTypeExpr>();
                    isExpr->value = expr;
                    parser->ReadToken();
                    isExpr->typeExpr = parser->ParseTypeExp();
                    isExpr->loc = opToken.loc;
                    expr = isExpr;
                    continue;
                }
                else if (opToken.getContent() == "as")
                {
                    auto asExpr = parser->astBuilder->create<AsTypeExpr>();
                    asExpr->value = expr;
                    parser->ReadToken();
                    asExpr->typeExpr = parser->ParseType();
                    asExpr->loc = opToken.loc;
                    expr = asExpr;
                    continue;
                }
            }

            auto op = parseOperator(parser);

            // Special case the `?:` operator since it is the
            // one non-binary case we need to deal with.
            if(opToken.type == TokenType::QuestionMark)
            {
                SelectExpr* select = parser->astBuilder->create<SelectExpr>();
                select->loc = op->loc;
                select->functionExpr = op;

                select->arguments.add(expr);

                select->arguments.add(parser->ParseExpression(opPrec));
                parser->ReadToken(TokenType::Colon);
                select->arguments.add(parser->ParseExpression(opPrec));

                expr = select;
                continue;
            }

            auto right = parser->ParseLeafExpression();

            for(;;)
            {
                auto nextOpPrec = GetOpLevel(parser, parser->tokenReader.peekToken());

                if((GetAssociativityFromLevel(nextOpPrec) == Associativity::Right) ? (nextOpPrec < opPrec) : (nextOpPrec <= opPrec))
                    break;

                right = parseInfixExprWithPrecedence(parser, right, nextOpPrec);
            }

            if (opToken.type == TokenType::OpAssign)
            {
                AssignExpr* assignExpr = parser->astBuilder->create<AssignExpr>();
                assignExpr->loc = op->loc;
                assignExpr->left = expr;
                assignExpr->right = right;

                expr = assignExpr;
            }
            else
            {
                expr = createInfixExpr(parser, expr, op, right);
            }
        }
        return expr;
    }

    Expr* Parser::ParseExpression(Precedence level)
    {
        auto expr = ParseLeafExpression();
        return parseInfixExprWithPrecedence(this, expr, level);

#if 0

        if (level == Precedence::Prefix)
            return ParseLeafExpression();
        if (level == Precedence::TernaryConditional)
        {
            // parse select clause
            auto condition = ParseExpression(Precedence(level + 1));
            if (LookAheadToken(TokenType::QuestionMark))
            {
                SelectExpr* select = new SelectExpr();
                FillPosition(select.Ptr());

                select->Arguments.add(condition);

                select->FunctionExpr = parseOperator(this);

                select->Arguments.add(ParseExpression(level));
                ReadToken(TokenType::Colon);
                select->Arguments.add(ParseExpression(level));
                return select;
            }
            else
                return condition;
        }
        else
        {
            if (GetAssociativityFromLevel(level) == Associativity::Left)
            {
                auto left = ParseExpression(Precedence(level + 1));
                while (GetOpLevel(this, tokenReader.PeekTokenType()) == level)
                {
                    OperatorExpr* tmp = new InfixExpr();
                    tmp->FunctionExpr = parseOperator(this);

                    tmp->Arguments.add(left);
                    FillPosition(tmp.Ptr());
                    tmp->Arguments.add(ParseExpression(Precedence(level + 1)));
                    left = tmp;
                }
                return left;
            }
            else
            {
                auto left = ParseExpression(Precedence(level + 1));
                if (GetOpLevel(this, tokenReader.PeekTokenType()) == level)
                {
                    OperatorExpr* tmp = new InfixExpr();
                    tmp->Arguments.add(left);
                    FillPosition(tmp.Ptr());
                    tmp->FunctionExpr = parseOperator(this);
                    tmp->Arguments.add(ParseExpression(level));
                    left = tmp;
                }
                return left;
            }
        }
#endif
    }

    // We *might* be looking at an application of a generic to arguments,
    // but we need to disambiguate to make sure.
    static Expr* maybeParseGenericApp(
        Parser*                             parser,

        // TODO: need to support more general expressions here
        Expr*     base)
    {
        if(peekTokenType(parser) != TokenType::OpLess)
            return base;
        return tryParseGenericApp(parser, base);
    }

    static Expr* parsePrefixExpr(Parser* parser);

    // Parse OOP `this` expression syntax
    static NodeBase* parseThisExpr(Parser* parser, void* /*userData*/)
    {
        ThisExpr* expr = parser->astBuilder->create<ThisExpr>();
        expr->scope = parser->currentScope;
        return expr;
    }

    static Expr* parseBoolLitExpr(Parser* parser, bool value)
    {
        BoolLiteralExpr* expr = parser->astBuilder->create<BoolLiteralExpr>();
        expr->value = value;
        return expr;
    }

    static NodeBase* parseTrueExpr(Parser* parser, void* /*userData*/)
    {
        return parseBoolLitExpr(parser, true);
    }

    static NodeBase* parseFalseExpr(Parser* parser, void* /*userData*/)
    {
        return parseBoolLitExpr(parser, false);
    }

    static NodeBase* parseNullPtrExpr(Parser* parser, void* /*userData*/)
    {
        return parser->astBuilder->create<NullPtrLiteralExpr>();
    }

    static NodeBase* parseNoneExpr(Parser* parser, void* /*userData*/)
    {
        return parser->astBuilder->create<NoneLiteralExpr>();
    }

    static NodeBase* parseTryExpr(Parser* parser, void* /*userData*/)
    {
        auto tryExpr = parser->astBuilder->create<TryExpr>();
        tryExpr->tryClauseType = TryClauseType::Standard;
        tryExpr->base = parser->ParseLeafExpression();
        tryExpr->scope = parser->currentScope;
        return tryExpr;
    }

    static NodeBase* parseTreatAsDifferentiableExpr(Parser* parser, void* /*userData*/)
    {
        auto noDiffExpr = parser->astBuilder->create<TreatAsDifferentiableExpr>();
        noDiffExpr->innerExpr = parser->ParseLeafExpression();
        noDiffExpr->scope = parser->currentScope;
        return noDiffExpr;
    }

    static bool _isFinite(double value)
    {
        // Lets type pun double to uint64_t, so we can detect special double values
        union
        {
            double d;
            uint64_t i;
        } u = { value };
        // Detects nan and +-inf
        const uint64_t i = u.i;
        int e = int(i >> 52) & 0x7ff;
        return (e != 0x7ff);
    }

    enum class FloatFixKind
    {
        None,               ///< No modification was made
        Unrepresentable,    ///< Unrepresentable
        Zeroed,             ///< Too close to 0
        Truncated,          ///< Truncated to a non zero value
    };

    static FloatFixKind _fixFloatLiteralValue(BaseType type, IRFloatingPointValue value, IRFloatingPointValue& outValue)
    {
        IRFloatingPointValue epsilon = 1e-10f;

        // Check the value is finite for checking narrowing to literal type losing information
        if (_isFinite(value))
        {
            switch (type)
            {
                case BaseType::Float:
                {
                    // Fix out of range
                    if (value > FLT_MAX)
                    {
                        if (Math::AreNearlyEqual(value, FLT_MAX, epsilon))
                        {
                            outValue = FLT_MAX;
                            return FloatFixKind::Truncated;
                        }
                        else
                        {
                            outValue = float(INFINITY);
                            return FloatFixKind::Unrepresentable;
                        }
                    }
                    else if (value < -FLT_MAX)
                    {
                        if (Math::AreNearlyEqual(-value, FLT_MAX, epsilon))
                        {
                            outValue = -FLT_MAX;
                            return FloatFixKind::Truncated;
                        }
                        else
                        {
                            outValue = -float(INFINITY);
                            return FloatFixKind::Unrepresentable;
                        }
                    }
                    else if (value && float(value) == 0.0f)
                    {
                        outValue = 0.0f;
                        return FloatFixKind::Zeroed;
                    }
                    break;
                }
                case BaseType::Double:
                {
                    // All representable
                    break;
                }
                case BaseType::Half:
                {
                    // Fix out of range
                    if (value > SLANG_HALF_MAX)
                    {
                        if (Math::AreNearlyEqual(value, FLT_MAX, epsilon))
                        {
                            outValue = SLANG_HALF_MAX;
                            return FloatFixKind::Truncated;
                        }
                        else
                        {
                            outValue = float(INFINITY);
                            return FloatFixKind::Unrepresentable;
                        }
                    }
                    else if (value < -SLANG_HALF_MAX)
                    {
                        if (Math::AreNearlyEqual(-value, FLT_MAX, epsilon))
                        {
                            outValue = -SLANG_HALF_MAX;
                            return FloatFixKind::Truncated;
                        }
                        else
                        {
                            outValue = -float(INFINITY);
                            return FloatFixKind::Unrepresentable;
                        }
                    }
                    else if (value && Math::Abs(value) < SLANG_HALF_SUB_NORMAL_MIN)
                    {
                        outValue = 0.0f;
                        return FloatFixKind::Zeroed;
                    }
                    break;
                }
                default: break;
            }
        }

        outValue = value;
        return FloatFixKind::None;
    }

    static IntegerLiteralValue _fixIntegerLiteral(BaseType baseType, IntegerLiteralValue value, Token* token, DiagnosticSink* sink)
    {
        // TODO(JS):
        // It is worth noting here that because of the way that the lexer works, that literals
        // are always handled as if they are positive (a preceding - is taken as a negate on a
        // positive value).
        // The code here is designed to work with positive and negative values, as this behavior
        // might change in the future, and is arguably more 'correct'.

        const BaseTypeInfo& info = BaseTypeInfo::getInfo(baseType);
        SLANG_ASSERT(info.flags & BaseTypeInfo::Flag::Integer);
        SLANG_COMPILE_TIME_ASSERT(sizeof(value) == sizeof(uint64_t));

        // If the type is 64 bits, do nothing, we'll assume all is good
        if (baseType != BaseType::Void && info.sizeInBytes != sizeof(value))
        {
            const IntegerLiteralValue signBit = IntegerLiteralValue(1) << (8 * info.sizeInBytes - 1);
            // Same as (~IntegerLiteralValue(0)) << (8 * info.sizeInBytes);, without the need for variable shift
            const IntegerLiteralValue mask = -(signBit + signBit);

            IntegerLiteralValue truncatedValue = value;
            // If it's signed, and top bit is set, sign extend it negative
            if (info.flags & BaseTypeInfo::Flag::Signed)
            {
                // Sign extend
                truncatedValue = (value & signBit) ? (value | mask) : (value & ~mask);
            }
            else
            {
                // 0 top bits
                truncatedValue = value & ~mask;
            }

            const IntegerLiteralValue maskedValue = value & mask;

            // If the masked value is 0 or equal to the mask, we 'assume' no information is
            // lost
            // This allows for example -1u, to give 0xffffffff
            // It also means 0xfffffffffffffffffu will give 0xffffffff, without a warning.
            if ((!(maskedValue == 0 || maskedValue == mask)) && sink && token)
            {
                // Output a warning that number has been altered
                sink->diagnose(*token, Diagnostics::integerLiteralTruncated, token->getContent(), BaseTypeInfo::asText(baseType), truncatedValue);
            }

            value = truncatedValue;
        }

        return value;
    }

    static bool _isCast(Parser* parser, Expr* expr)
    {
        if (as<PointerTypeExpr>(expr))
        {
            return true;
        }

        // We can't just look at expr and look up if it's a type, because we allow
        // out-of-order declarations. So to a first approximation we'll try and
        // determine if it is a cast via a heuristic based on what comes next

        TokenType tokenType = peekTokenType(parser);

        // Expression
        // ==========
        //
        // Misc: ; ) [ ] , . = ? (ternary) { } ++ -- -> 
        // Binary ops: * / | & ^ % << >> 
        // Logical ops: || &&  
        // Comparisons: != == < > <= =>
        //
        // Any assign op
        // 
        // If we don't have pointers then
        // & : (Thing::Another) &v 
        // * : (Thing::Another)*ptr is a cast.
        //
        // Cast
        // ====
        //
        // Misc: (
        // Identifier, Literal
        // Unary ops: !, ~
        // 
        // Ambiguous
        // =========
        //
        // - : Can be unary and therefore a cast or a binary subtract, and therefore an expression
        // + : Can be unary and therefore could be a cast, or a binary add and therefore an expression
        //
        // Arbitrary
        // =========
        //
        // End of file, End of directive, Invalid, :, ::

        switch (tokenType)
        {
            case TokenType::FloatingPointLiteral:
            case TokenType::CharLiteral:
            case TokenType::IntegerLiteral:
            case TokenType::Identifier:
            case TokenType::OpNot:
            case TokenType::OpBitNot:
            {
                // If followed by one of these, must be a cast
                return true;
            }
            case TokenType::LParent:
            {
                // If we are followed by ( it might not be a cast - it could be a call invocation.
                // BUT we can always *assume* it is a call, because such a 'call' will be correctly
                // handled as a cast if necessary later.
                return false;
            }
            case TokenType::OpAdd:
            case TokenType::OpSub:
            case TokenType::OpMul:
            case TokenType::OpBitAnd:
            {
                // + - are ambiguous, it could be a binary + or - so -> expression, or unary -> cast
                //
                // (Some::Stuff) + 3
                // (Some::Stuff) - 3
                // Strictly I can only tell if this is an expression or a cast if I know Some::Stuff is a type or not
                // but we can't know here in general because we allow out-of-order declarations.

                // If we can determine it's a type, then it must be a cast, and we are done.
                // 
                // NOTE! This test can only determine if it's a type *iff* it has already been defined. A future out
                // of order declaration, will not be correctly found here.
                //
                // This means the semantics change depending on the order of definition (!)
                Decl* decl = _tryResolveDecl(parser, expr);
                // If we can find the decl-> we can resolve unambiguously
                if (decl)
                {
                    return _isType(decl);
                }

                // Now we use a heuristic.
                //
                // Whitespace before, whitespace after->binary
                // No whitespace before, no whitespace after->binary
                // Otherwise->unary
                //
                // Unary -> cast, binary -> expression.
                // 
                // Ie:
                // (Some::Stuff) +3  - must be a cast
                // (Some::Stuff)+ 3  - must be a cast (?) This is a bit odd.
                // (Some::Stuff) + 3 - must be an expression.
                // (Some::Stuff)+3 - must be an expression.

                // TODO(JS): This covers the (SomeScope::Identifier) case
                //
                // But perhaps there other ways of referring to types, that this now misses? With associated types/generics perhaps.
                // 
                // For now we'll assume it's not a cast if it's not a StaticMemberExpr
                // The reason for the restriction (which perhaps can be broadened), is we don't
                // want the interpretation of something in parentheses to be determined by something as common as + or - whitespace.

                if (auto staticMemberExpr = dynamicCast<StaticMemberExpr>(expr))
                {
                    // Apply the heuristic:
                    TokenReader::ParsingCursor cursor = parser->tokenReader.getCursor();
                    // Skip the + or -
                    const Token opToken = advanceToken(parser);
                    // Peek the next token to see if it was preceded by white space
                    const Token nextToken = peekToken(parser);

                    // Rewind
                    parser->tokenReader.setCursor(cursor);

                    const bool isBinary = (nextToken.flags & TokenFlag::AfterWhitespace) == (opToken.flags & TokenFlag::AfterWhitespace);

                    // If it's binary it's not a cast
                    return !isBinary;
                }
                break;
            }
            default: break;
        }

        // We'll assume it's not a cast
        return false;
    }

    static bool tryParseExpression(Parser* parser, Expr* &outExpr, TokenType tokenTypeAfter)
    {
        auto cursor = parser->tokenReader.getCursor();
        auto isRecovering = parser->isRecovering;
        auto oldSink = parser->sink;
        DiagnosticSink newSink(parser->sink->getSourceManager(), nullptr);
        parser->sink = &newSink;
        outExpr = parser->ParseExpression();
        parser->sink = oldSink;
        parser->isRecovering = isRecovering;
        if (outExpr && newSink.getErrorCount() == 0 && parser->LookAheadToken(tokenTypeAfter))
        {
            return true;
        }
        parser->tokenReader.setCursor(cursor);
        return false;
    }

    static Expr* parseAtomicExpr(Parser* parser)
    {
        switch( peekTokenType(parser) )
        {
        default:
            // TODO: should this return an error expression instead of NULL?
            parser->diagnose(parser->tokenReader.peekLoc(), Diagnostics::syntaxError);
            return parser->astBuilder->create<IncompleteExpr>();

        // Either:
        // - parenthesized expression `(exp)`
        // - cast `(type) exp`
        //
        // Proper disambiguation requires mixing up parsing
        // and semantic checking (which we should do eventually)
        // but for now we will follow some heuristics.
        case TokenType::LParent:
            {
                Token openParen = parser->ReadToken(TokenType::LParent);
                Expr* typeExpr = nullptr;
                if (peekTypeName(parser) && parser->LookAheadToken(TokenType::RParent))
                {
                    TypeCastExpr* tcexpr = parser->astBuilder->create<ExplicitCastExpr>();
                    parser->FillPosition(tcexpr);
                    tcexpr->functionExpr = typeExpr;
                    parser->ReadToken(TokenType::RParent);

                    auto arg = parsePrefixExpr(parser);
                    tcexpr->arguments.add(arg);

                    return tcexpr;
                }
                else
                {
                    // The above branch catches the case where we have a cast like (Thing), but with
                    // the scoping operator it will not handle (SomeScope::Thing). In that case this
                    // branch will be taken. This is okay in so far as SomeScope::Thing will parse
                    // as an expression.
                    
                    Expr* base = nullptr;
                    if (!tryParseExpression(parser, base, TokenType::RParent))
                    {
                        base = parser->ParseType();
                    }

                    parser->ReadToken(TokenType::RParent);

                    // We now try and determine by what base is, if this is actually a cast or an expression in parentheses
                    if (_isCast(parser, base))
                    {
                        // Parse as a cast

                        TypeCastExpr* tcexpr = parser->astBuilder->create<ExplicitCastExpr>();
                        tcexpr->loc = openParen.loc;

                        tcexpr->functionExpr = base;

                        auto arg = parsePrefixExpr(parser);
                        tcexpr->arguments.add(arg);

                        return tcexpr;
                    }
                    else
                    {
                        // Pass as an expression in parentheses

                        ParenExpr* parenExpr = parser->astBuilder->create<ParenExpr>();
                        parenExpr->loc = openParen.loc;
                        parenExpr->base = base;
                        return parenExpr;
                    }
                }
            }

        // An initializer list `{ expr, ... }`
        case TokenType::LBrace:
            {
                InitializerListExpr* initExpr = parser->astBuilder->create<InitializerListExpr>();
                parser->FillPosition(initExpr);

                // Initializer list
                parser->ReadToken(TokenType::LBrace);

                List<Expr*> exprs;

                for(;;)
                {
                    if(AdvanceIfMatch(parser, MatchedTokenType::CurlyBraces))
                        break;

                    auto expr = parser->ParseArgExpr();
                    if( expr )
                    {
                        initExpr->args.add(expr);
                    }

                    if(AdvanceIfMatch(parser, MatchedTokenType::CurlyBraces))
                        break;

                    parser->ReadToken(TokenType::Comma);
                }

                return initExpr;
            }

        case TokenType::IntegerLiteral:
            {
                IntegerLiteralExpr* constExpr = parser->astBuilder->create<IntegerLiteralExpr>();
                parser->FillPosition(constExpr);

                auto token = parser->tokenReader.advanceToken();
                constExpr->token = token;

                UnownedStringSlice suffix;
                IntegerLiteralValue value = getIntegerLiteralValue(token, &suffix);

                // Look at any suffix on the value
                char const* suffixCursor = suffix.begin();
                const char*const suffixEnd = suffix.end();

                // If no suffix is defined go with the default
                BaseType suffixBaseType = BaseType::Int;

                if( suffixCursor < suffixEnd )
                {
                    // Mark as void, taken as an error
                    suffixBaseType = BaseType::Void;

                    int lCount = 0;
                    int uCount = 0;
                    int zCount = 0;
                    int unknownCount = 0;
                    while(suffixCursor < suffixEnd)
                    {
                        switch( *suffixCursor++ )
                        {
                        case 'l': case 'L':
                            lCount++;
                            break;

                        case 'u': case 'U':
                            uCount++;
                            break;

                        case 'z': case 'Z':
                            zCount++;
                            break;

                        default:
                            unknownCount++;
                            break;
                        }
                    }

                    if(unknownCount)
                    {
                        parser->sink->diagnose(token, Diagnostics::invalidIntegerLiteralSuffix, suffix);
                        suffixBaseType = BaseType::Int;
                    }
                    // `u` or `ul` suffix -> `uint`
                    else if(uCount == 1 && (lCount <= 1) && zCount == 0)
                    {
                        suffixBaseType = BaseType::UInt;
                    }
                    // `l` suffix on integer -> `int` (== `long`)
                    else if(lCount == 1 && !uCount && zCount == 0)
                    {
                        suffixBaseType = BaseType::Int; 
                    }
                    // `ull` suffix -> `uint64_t`
                    else if(uCount == 1 && lCount == 2 && zCount == 0)
                    {
                        suffixBaseType = BaseType::UInt64;
                    }
                    // `ll` suffix -> `int64_t`
                    else if(uCount == 0 && lCount == 2 && zCount == 0)
                    {
                        suffixBaseType = BaseType::Int64;
                    }
                    else if (uCount == 0 && zCount == 1)
                    {
                        suffixBaseType = BaseType::IntPtr;
                    }
                    else if (uCount == 1 && zCount == 1)
                    {
                        suffixBaseType = BaseType::UIntPtr;
                    }
                    // TODO: do we need suffixes for smaller integer types?
                    else
                    {
                        parser->sink->diagnose(token, Diagnostics::invalidIntegerLiteralSuffix, suffix);
                        suffixBaseType = BaseType::Int;
                    }
                }

                value = _fixIntegerLiteral(suffixBaseType, value, &token, parser->sink);

                ASTBuilder* astBuilder = parser->astBuilder;
                Type* suffixType = (suffixBaseType == BaseType::Void) ? astBuilder->getErrorType() : astBuilder->getBuiltinType(suffixBaseType);

                constExpr->value = value;
                constExpr->type = QualType(suffixType);

                return constExpr;
            }


        case TokenType::FloatingPointLiteral:
            {
                FloatingPointLiteralExpr* constExpr = parser->astBuilder->create<FloatingPointLiteralExpr>();
                parser->FillPosition(constExpr);

                auto token = parser->tokenReader.advanceToken();
                constExpr->token = token;

                UnownedStringSlice suffix;
                FloatingPointLiteralValue value = getFloatingPointLiteralValue(token, &suffix);

                // Look at any suffix on the value
                char const* suffixCursor = suffix.begin();
                const char*const suffixEnd = suffix.end();

                // Default is Float
                BaseType suffixBaseType = BaseType::Float;
                if( suffixCursor < suffixEnd )
                {
                    int fCount = 0;
                    int lCount = 0;
                    int hCount = 0;
                    int unknownCount = 0;
                    while(suffixCursor < suffixEnd)
                    {
                        switch( *suffixCursor++ )
                        {
                        case 'f': case 'F':
                            fCount++;
                            break;

                        case 'l': case 'L':
                            lCount++;
                            break;

                        case 'h': case 'H':
                            hCount++;
                            break;

                        default:
                            unknownCount++;
                            break;
                        }
                    }

                    if (unknownCount)
                    {
                        parser->sink->diagnose(token, Diagnostics::invalidFloatingPointLiteralSuffix, suffix);
                        suffixBaseType = BaseType::Float;
                    }
                    // `f` suffix -> `float`
                    if(fCount == 1 && !lCount && !hCount)
                    {
                        suffixBaseType = BaseType::Float;
                    }
                    // `l` or `lf` suffix on floating-point literal -> `double`
                    else if(lCount == 1 && (fCount <= 1))
                    {
                        suffixBaseType = BaseType::Double;
                    }
                    // `h` or `hf` suffix on floating-point literal -> `half`
                    else if(hCount == 1 && (fCount <= 1))
                    {
                        suffixBaseType = BaseType::Half;
                    }
                    // TODO: are there other suffixes we need to handle?
                    else
                    {
                        parser->sink->diagnose(token, Diagnostics::invalidFloatingPointLiteralSuffix, suffix);
                        suffixBaseType = BaseType::Float;
                    }
                }

                // TODO(JS):
                // It is worth noting here that because of the way that the lexer works, that literals
                // are always handled as if they are positive (a preceding - is taken as a negate on a
                // positive value).
                // The code here is designed to work with positive and negative values, as this behavior
                // might change in the future, and is arguably more 'correct'.

                FloatingPointLiteralValue fixedValue = value;
                auto fixType = _fixFloatLiteralValue(suffixBaseType, value, fixedValue);

                switch (fixType)
                {
                    case FloatFixKind::Truncated: 
                    case FloatFixKind::None:
                    {
                        // No warning.
                        // The truncation allowed must be very small. When Truncated the value *is* changed though.
                        break;
                    }
                    case FloatFixKind::Zeroed:
                    {
                        parser->sink->diagnose(token, Diagnostics::floatLiteralTooSmall, BaseTypeInfo::asText(suffixBaseType), token.getContent(), fixedValue);
                        break;
                    }
                    case FloatFixKind::Unrepresentable:
                    {
                        parser->sink->diagnose(token, Diagnostics::floatLiteralUnrepresentable, BaseTypeInfo::asText(suffixBaseType), token.getContent(), fixedValue);
                        break;
                    }
                }

                ASTBuilder* astBuilder = parser->astBuilder;

                Type* suffixType = (suffixBaseType == BaseType::Void) ? astBuilder->getErrorType() : astBuilder->getBuiltinType(suffixBaseType);

                constExpr->value = fixedValue;
                constExpr->type = QualType(suffixType);

                return constExpr;
            }

        case TokenType::StringLiteral:
            {
                StringLiteralExpr* constExpr = parser->astBuilder->create<StringLiteralExpr>();
                auto token = parser->tokenReader.advanceToken();
                constExpr->token = token;
                parser->FillPosition(constExpr);

                if (!parser->LookAheadToken(TokenType::StringLiteral))
                {
                    // Easy/common case: a single string
                    constExpr->value = getStringLiteralTokenValue(token);
                }
                else
                {
                    StringBuilder sb;
                    sb << getStringLiteralTokenValue(token);
                    while (parser->LookAheadToken(TokenType::StringLiteral))
                    {
                        token = parser->tokenReader.advanceToken();
                        sb << getStringLiteralTokenValue(token);
                    }
                    constExpr->value = sb.produceString();
                }

                return constExpr;
            }
        case TokenType::CompletionRequest:
            {
                VarExpr* varExpr = parser->astBuilder->create<VarExpr>();
                varExpr->scope = parser->currentScope;
                parser->FillPosition(varExpr);
                auto nameAndLoc = NameLoc(peekToken(parser));
                varExpr->name = nameAndLoc.name;
                parser->hasSeenCompletionToken = true;
                // Don't consume the token, instead we skip directly.
                parser->ReadToken(TokenType::Identifier);
                return varExpr;
            }
        case TokenType::Identifier:
            {
                // We will perform name lookup here so that we can find syntax
                // keywords registered for use as expressions.
                Token nameToken = peekToken(parser);

                Expr* parsedExpr = nullptr;
                if (tryParseUsingSyntaxDecl<Expr>(parser, &parsedExpr))
                {
                    if (!parsedExpr->loc.isValid())
                    {
                        parsedExpr->loc = nameToken.loc;
                    }
                    return parsedExpr;
                }

                // Default behavior is just to create a name expression
                VarExpr* varExpr = parser->astBuilder->create<VarExpr>();
                varExpr->scope = parser->currentScope;
                parser->FillPosition(varExpr);

                auto nameAndLoc = NameLoc(parser->ReadToken());
                varExpr->name = nameAndLoc.name;

                if(peekTokenType(parser) == TokenType::OpLess)
                {
                    return maybeParseGenericApp(parser, varExpr);
                }

                return varExpr;
            }
        }
    }

    static Expr* parsePostfixExpr(Parser* parser)
    {
        auto expr = parseAtomicExpr(parser);
        for(;;)
        {
            switch( peekTokenType(parser) )
            {
            default:
                return expr;

            // Postfix increment/decrement
            case TokenType::OpInc:
            case TokenType::OpDec:
                {
                    OperatorExpr* postfixExpr = parser->astBuilder->create<PostfixExpr>();
                    parser->FillPosition(postfixExpr);
                    postfixExpr->functionExpr = parseOperator(parser);
                    postfixExpr->arguments.add(expr);

                    expr = postfixExpr;
                }
                break;

            // Subscript operation `a[i]`
            case TokenType::LBracket:
                {
                    IndexExpr* indexExpr = parser->astBuilder->create<IndexExpr>();
                    indexExpr->baseExpression = expr;
                    parser->FillPosition(indexExpr);
                    auto lBracket = parser->ReadToken(TokenType::LBracket);
                    indexExpr->argumentDelimeterLocs.add(lBracket.loc);
                    while (!parser->tokenReader.isAtEnd())
                    {
                        if (!parser->LookAheadToken(TokenType::RBracket))
                            indexExpr->indexExprs.add(parser->ParseArgExpr());
                        else
                        {
                            break;
                        }
                        if (!parser->LookAheadToken(TokenType::Comma))
                            break;
                        auto comma = parser->ReadToken(TokenType::Comma);
                        indexExpr->argumentDelimeterLocs.add(comma.loc);
                    }
                    auto rBracket = parser->ReadToken(TokenType::RBracket);
                    indexExpr->argumentDelimeterLocs.add(rBracket.loc);
                    expr = indexExpr;
                }
                break;

            // Call oepration `f(x)`
            case TokenType::LParent:
                {
                    InvokeExpr* invokeExpr = parser->astBuilder->create<InvokeExpr>();
                    invokeExpr->functionExpr = expr;
                    parser->FillPosition(invokeExpr);
                    auto lParen = parser->ReadToken(TokenType::LParent);
                    invokeExpr->argumentDelimeterLocs.add(lParen.loc);
                    while (!parser->tokenReader.isAtEnd())
                    {
                        if (!parser->LookAheadToken(TokenType::RParent))
                            invokeExpr->arguments.add(parser->ParseArgExpr());
                        else
                        {
                            break;
                        }
                        if (!parser->LookAheadToken(TokenType::Comma))
                            break;
                        auto comma = parser->ReadToken(TokenType::Comma);
                        invokeExpr->argumentDelimeterLocs.add(comma.loc);
                    }
                    auto rParen = parser->ReadToken(TokenType::RParent);
                    invokeExpr->argumentDelimeterLocs.add(rParen.loc);
                    expr = invokeExpr;
                }
                break;

            // Scope access `x::m`
            case TokenType::Scope:
            {
                StaticMemberExpr* staticMemberExpr = parser->astBuilder->create<StaticMemberExpr>();

                // TODO(tfoley): why would a member expression need this?
                staticMemberExpr->scope = parser->currentScope;
                staticMemberExpr->memberOperatorLoc = parser->tokenReader.peekLoc();
                staticMemberExpr->baseExpression = expr;
                parser->ReadToken(TokenType::Scope);
                parser->FillPosition(staticMemberExpr);
                staticMemberExpr->name = expectIdentifier(parser).name;

                if (peekTokenType(parser) == TokenType::OpLess)
                    expr = maybeParseGenericApp(parser, staticMemberExpr);
                else
                    expr = staticMemberExpr;

                break;
            }
            // Member access `x.m`
            case TokenType::Dot:
                {
                    MemberExpr* memberExpr = parser->astBuilder->create<MemberExpr>();

                    // TODO(tfoley): why would a member expression need this?
                    memberExpr->scope = parser->currentScope;
                    memberExpr->memberOperatorLoc = parser->tokenReader.peekLoc();
                    memberExpr->baseExpression = expr;
                    parser->ReadToken(TokenType::Dot);
                    parser->FillPosition(memberExpr);
                    memberExpr->name = expectIdentifier(parser).name;
                    
                    if (peekTokenType(parser) == TokenType::OpLess)
                        expr = maybeParseGenericApp(parser, memberExpr);
                    else
                        expr = memberExpr;
                }
                break;
            }
        }
    }

    static IRIntegerValue _foldIntegerPrefixOp(TokenType tokenType, IRIntegerValue value)
    {
        switch (tokenType)
        {
            case TokenType::OpBitNot:   return ~value;
            case TokenType::OpAdd:      return value;
            case TokenType::OpSub:      return -value;
            default:
            {
                SLANG_ASSERT(!"Unexpected op");
                return value;
            }
        }
    }

    static IRFloatingPointValue _foldFloatPrefixOp(TokenType tokenType, IRFloatingPointValue value)
    {
        switch (tokenType)
        {
            case TokenType::OpAdd:      return value;
            case TokenType::OpSub:      return -value;
            default:
            {
                SLANG_ASSERT(!"Unexpected op");
                return value;
            }
        }
    }

    static Expr* parsePrefixExpr(Parser* parser)
    {
        auto tokenType = peekTokenType(parser);
        switch( tokenType )
        {
        default:
            if (parser->LookAheadToken("new"))
            {
                NewExpr* newExpr = parser->astBuilder->create<NewExpr>();
                parser->FillPosition(newExpr);
                parser->ReadToken();
                auto subExpr = parsePostfixExpr(parser);
                if (as<VarExpr>(subExpr) || as<GenericAppExpr>(subExpr))
                {
                    newExpr->functionExpr = subExpr;
                }
                else if (auto invokeExpr = as<InvokeExpr>(subExpr))
                {
                    newExpr->functionExpr = invokeExpr->functionExpr;
                    newExpr->arguments = invokeExpr->arguments;
                    newExpr->argumentDelimeterLocs = invokeExpr->argumentDelimeterLocs;
                }
                else
                {
                    parser->diagnose(newExpr->loc, Diagnostics::syntaxError);
                    newExpr->functionExpr = parser->astBuilder->create<IncompleteExpr>();
                }
                return newExpr;
            }
            return parsePostfixExpr(parser);
        case TokenType::OpNot:
        case TokenType::OpInc:
        case TokenType::OpDec:
        case TokenType::OpMul:
        case TokenType::OpBitAnd:
        {
            PrefixExpr* prefixExpr = parser->astBuilder->create<PrefixExpr>();
            parser->FillPosition(prefixExpr);
            prefixExpr->functionExpr = parseOperator(parser);

            auto arg = parsePrefixExpr(parser);

            prefixExpr->arguments.add(arg);
            return prefixExpr;
        }
        case TokenType::OpBitNot:
        case TokenType::OpAdd:
        case TokenType::OpSub:
            {
                PrefixExpr* prefixExpr = parser->astBuilder->create<PrefixExpr>();
                parser->FillPosition(prefixExpr);
                prefixExpr->functionExpr = parseOperator(parser);

                auto arg = parsePrefixExpr(parser);

                if (auto intLit = as<IntegerLiteralExpr>(arg))
                {
                    IntegerLiteralExpr* newLiteral = parser->astBuilder->create<IntegerLiteralExpr>(*intLit);

                    IRIntegerValue value = _foldIntegerPrefixOp(tokenType, newLiteral->value);

                    // Need to get the basic type, so we can fit to underlying type
                    if (auto basicExprType = as<BasicExpressionType>(intLit->type.type))
                    {
                        value = _fixIntegerLiteral(basicExprType->baseType, value, nullptr, nullptr);
                    }

                    newLiteral->value = value;
                    return newLiteral;
                }
                else if (auto floatLit = as<FloatingPointLiteralExpr>(arg))
                {
                    FloatingPointLiteralExpr* newLiteral = parser->astBuilder->create<FloatingPointLiteralExpr>(*floatLit);
                    newLiteral->value = _foldFloatPrefixOp(tokenType, floatLit->value);
                    return newLiteral;
                }

                prefixExpr->arguments.add(arg);
                return prefixExpr;
            }
        
            break;
        }
    }

    Expr* Parser::ParseLeafExpression()
    {
        return parsePrefixExpr(this);
    }

        /// Parse an argument to an application of a generic
    static Expr* _parseGenericArg(Parser* parser)
    {
        // The grammar for generic arguments needs to be a super-set of the
        // grammar for types and for expressions, because we do not know
        // which to expect at each argument position during parsing.
        //
        // For the most part the expression grammar is more permissive than
        // the type grammar, but types support modifiers that are not
        // (currently) allowed in pure expression contexts.
        //
        // We could in theory allow modifiers to appear in expression contexts
        // and deal with the cases where this should not be allowed downstream,
        // but doing so runs a high risk of changing the meaning of existing code
        // (notably in cases where a user might have used a variable name that
        // overlaps with a language modifier keyword).
        //
        // Instead, we will simply detect the case where modifiers appear on
        // a generic argument here, as a special case.
        //
        Modifiers modifiers = ParseModifiers(parser);
        if(modifiers.first)
        {
            // If there are any modifiers, then we know that we are actually
            // in the type case.
            //
            auto typeSpec = _parseSimpleTypeSpec(parser);
            typeSpec = _applyModifiersToTypeSpec(parser, typeSpec, modifiers);

            auto typeExpr = typeSpec.expr;

            typeExpr = parsePostfixTypeSuffix(parser, typeExpr);
            typeExpr = _parseInfixTypeExprSuffix(parser, typeExpr);

            return typeExpr;
        }

        return parser->ParseArgExpr();
    }

    Expr* parseTermFromSourceFile(
        ASTBuilder*                     astBuilder,
        TokenSpan const&                tokens,
        DiagnosticSink*                 sink,
        Scope*                          outerScope,
        NamePool*                       namePool,
        SourceLanguage                  sourceLanguage)
    {
        Parser parser(astBuilder, tokens, sink, outerScope);
        parser.currentScope = outerScope;
        parser.namePool = namePool;
        parser.sourceLanguage = sourceLanguage;
        return parser.ParseExpression();
    }

    // Parse a source file into an existing translation unit
    void parseSourceFile(
        ASTBuilder*                     astBuilder,
        TranslationUnitRequest*         translationUnit,
        TokenSpan const&                tokens,
        DiagnosticSink*                 sink,
        Scope*                          outerScope)
    {
        Parser parser(astBuilder, tokens, sink, outerScope);
        parser.namePool = translationUnit->getNamePool();
        parser.sourceLanguage = translationUnit->sourceLanguage;

        return parser.parseSourceFile(translationUnit->getModuleDecl());
    }

    static void addBuiltinSyntaxImpl(
        Session*                    session,
        Scope*                      scope,
        char const*                 nameText,
        SyntaxParseCallback         callback,
        void*                       userData,
        SyntaxClass<NodeBase>      syntaxClass)
    {
        Name* name = session->getNamePool()->getName(nameText);

        ASTBuilder* globalASTBuilder = session->getGlobalASTBuilder();

        SyntaxDecl* syntaxDecl = globalASTBuilder->create<SyntaxDecl>();
        syntaxDecl->nameAndLoc = NameLoc(name);
        syntaxDecl->syntaxClass = syntaxClass;
        syntaxDecl->parseCallback = callback;
        syntaxDecl->parseUserData = userData;

        AddMember(scope, syntaxDecl);
    }

    template<typename T>
    static void addBuiltinSyntax(
        Session*            session,
        Scope*              scope,
        char const*         name,
        SyntaxParseCallback callback,
        void*               userData = nullptr)
    {
        addBuiltinSyntaxImpl(session, scope, name, callback, userData, getClass<T>());
    }

    template<typename T>
    static void addSimpleModifierSyntax(
        Session*        session,
        Scope*          scope,
        char const*     name)
    {
        auto syntaxClass = getClass<T>();
        addBuiltinSyntaxImpl(session, scope, name, &parseSimpleSyntax, (void*) syntaxClass.classInfo, getClass<T>());
    }

    static NodeBase* parseIntrinsicOpModifier(Parser* parser, void* /*userData*/)
    {
        IntrinsicOpModifier* modifier = parser->astBuilder->create<IntrinsicOpModifier>();

        // We allow a few difference forms here:
        //
        // First, we can specify the intrinsic op `enum` value directly:
        //
        //     __intrinsic_op(<integer literal>)
        //
        // Second, we can specify the operation by name:
        //
        //     __intrinsic_op(<identifier>)
        //
        // Finally, we can leave off the specification, so that the
        // op name will be derived from the function name:
        //
        //     __intrinsic_op
        //
        if (AdvanceIf(parser, TokenType::LParent))
        {
            if (AdvanceIf(parser, TokenType::OpSub))
            {
                modifier->op = IROp(-stringToInt(parser->ReadToken().getContent()));
            }
            else if (parser->LookAheadToken(TokenType::IntegerLiteral))
            {
                modifier->op = IROp(stringToInt(parser->ReadToken().getContent()));
            }
            else
            {
                modifier->opToken = parser->ReadToken(TokenType::Identifier);

                modifier->op = findIROp(modifier->opToken.getContent());

                if (modifier->op == kIROp_Invalid)
                {
                    parser->sink->diagnose(modifier->opToken, Diagnostics::unimplemented, "unknown intrinsic op");
                }
            }

            parser->ReadToken(TokenType::RParent);
        }


        return modifier;
    }

    static NodeBase* parseTargetIntrinsicModifier(Parser* parser, void* /*userData*/)
    {
        auto modifier = parser->astBuilder->create<TargetIntrinsicModifier>();

        if (AdvanceIf(parser, TokenType::LParent))
        {
            modifier->targetToken = parser->ReadToken(TokenType::Identifier);

            if( AdvanceIf(parser, TokenType::Comma) )
            {
                if( parser->LookAheadToken(TokenType::StringLiteral) )
                {
                    modifier->definitionToken = parser->ReadToken();
                }
                else
                {
                    modifier->definitionToken = parser->ReadToken(TokenType::Identifier);
                }
            }

            parser->ReadToken(TokenType::RParent);
        }

        return modifier;
    }

    static NodeBase* parseSpecializedForTargetModifier(Parser* parser, void* /*userData*/)
    {
        auto modifier = parser->astBuilder->create<SpecializedForTargetModifier>();
        if (AdvanceIf(parser, TokenType::LParent))
        {
            modifier->targetToken = parser->ReadToken(TokenType::Identifier);
            parser->ReadToken(TokenType::RParent);
        }
        return modifier;
    }

    static NodeBase* parseGLSLExtensionModifier(Parser* parser, void* /*userData*/)
    {
        auto modifier = parser->astBuilder->create<RequiredGLSLExtensionModifier>();

        parser->ReadToken(TokenType::LParent);
        modifier->extensionNameToken = parser->ReadToken(TokenType::Identifier);
        parser->ReadToken(TokenType::RParent);

        return modifier;
    }

    static NodeBase* parseGLSLVersionModifier(Parser* parser, void* /*userData*/)
    {
        auto modifier = parser->astBuilder->create<RequiredGLSLVersionModifier>();

        parser->ReadToken(TokenType::LParent);
        modifier->versionNumberToken = parser->ReadToken(TokenType::IntegerLiteral);
        parser->ReadToken(TokenType::RParent);

        return modifier;
    }


    static SlangResult parseSemanticVersion(Parser* parser, Token& outToken, SemanticVersion& outVersion)
    {
        parser->ReadToken(TokenType::LParent);
        outToken = parser->ReadToken();
        parser->ReadToken(TokenType::RParent);

        UnownedStringSlice content = outToken.getContent();
        // We allow specified as major.minor or as a string (in quotes)
        switch (outToken.type)
        {
            case TokenType::FloatingPointLiteral:
            {
                break;
            }
            case TokenType::StringLiteral:
            {
                // We need to trim quotes if needed
                SLANG_ASSERT(content.getLength() >= 2 && content[0] == '"' && content[content.getLength() - 1] == '"');
                content = UnownedStringSlice(content.begin() + 1, content.end() - 1);
                break;
            }
            default:
            {
                return SLANG_FAIL;
            }
        }
        return SemanticVersion::parse(content, outVersion);
    }

    static NodeBase* parseSPIRVVersionModifier(Parser* parser, void* /*userData*/)
    {
        Token token;
        SemanticVersion version;
        if (SLANG_SUCCEEDED(parseSemanticVersion(parser, token, version)))
        {
            auto modifier = parser->astBuilder->create<RequiredSPIRVVersionModifier>();
            modifier->version = version;
            return modifier;
        }
        parser->sink->diagnose(token, Diagnostics::invalidSPIRVVersion);
        return nullptr;
    }

    static NodeBase* parseCUDASMVersionModifier(Parser* parser, void* /*userData*/)
    {
        Token token;
        SemanticVersion version;
        if (SLANG_SUCCEEDED(parseSemanticVersion(parser, token, version)))
        {
            auto modifier = parser->astBuilder->create<RequiredCUDASMVersionModifier>();
            modifier->version = version;
            return modifier;
        }
        parser->sink->diagnose(token, Diagnostics::invalidCUDASMVersion);
        return nullptr;
    }

    static NodeBase* parseLayoutModifier(Parser* parser, void* /*userData*/)
    {
        ModifierListBuilder listBuilder;

        UncheckedAttribute* numThreadsAttrib = nullptr;

        listBuilder.add(parser->astBuilder->create<GLSLLayoutModifierGroupBegin>());
        
        parser->ReadToken(TokenType::LParent);
        while (!AdvanceIfMatch(parser, MatchedTokenType::Parentheses))
        {
            auto nameAndLoc = expectIdentifier(parser);
            const String& nameText = nameAndLoc.name->text;

            const char localSizePrefix[] = "local_size_";

            int localSizeIndex = -1;
            if (nameText.startsWith(localSizePrefix) && nameText.getLength() == SLANG_COUNT_OF(localSizePrefix) - 1 + 1)
            {
                char lastChar = nameText[SLANG_COUNT_OF(localSizePrefix) - 1];
                localSizeIndex = (lastChar >= 'x' && lastChar <= 'z') ? (lastChar - 'x') : -1;
            }

            if (localSizeIndex >= 0)
            {
                if (!numThreadsAttrib)
                {
                    numThreadsAttrib = parser->astBuilder->create<UncheckedAttribute>();
                    numThreadsAttrib->args.setCount(3);

                    // Just mark the loc and name from the first in the list
                    numThreadsAttrib->keywordName = getName(parser, "numthreads");
                    numThreadsAttrib->loc = nameAndLoc.loc;
                    numThreadsAttrib->scope = parser->currentScope;
                }

                if (AdvanceIf(parser, TokenType::OpAssign))
                {
                    auto expr = parseAtomicExpr(parser);
                    //SLANG_ASSERT(expr);
                    if (!expr)
                    {
                        return nullptr;
                    }

                    numThreadsAttrib->args[localSizeIndex] = expr;
                }
            }
            else if (nameText == "binding" ||
                nameText == "set")
            {
                GLSLBindingAttribute* attr = listBuilder.find<GLSLBindingAttribute>();
                if (!attr)
                {
                    attr = parser->astBuilder->create<GLSLBindingAttribute>();
                    listBuilder.add(attr);
                }

                parser->ReadToken(TokenType::OpAssign);

                // If the token asked for is not returned found will put in recovering state, and return token found
                Token valToken = parser->ReadToken(TokenType::IntegerLiteral);
                // If wasn't the desired IntegerLiteral return that couldn't parse
                if (valToken.type == TokenType::IntegerLiteral)
                {
                    // Work out the value
                    auto value = getIntegerLiteralValue(valToken);

                    if (nameText == "binding")
                    {
                        attr->binding = int32_t(value);
                    }
                    else
                    {
                        attr->set = int32_t(value);
                    }
                }
            }
            else
            {
                Modifier* modifier = nullptr;

#define CASE(key, type) if (nameText == #key) { modifier = parser->astBuilder->create<type>(); } else
                CASE(push_constant, PushConstantAttribute) 
                CASE(shaderRecordNV, ShaderRecordAttribute)
                CASE(constant_id,   GLSLConstantIDLayoutModifier) 
                CASE(location, GLSLLocationLayoutModifier) 
                {
                    modifier = parser->astBuilder->create<GLSLUnparsedLayoutModifier>();
                }
                SLANG_ASSERT(modifier);
#undef CASE

                modifier->keywordName = nameAndLoc.name;
                modifier->loc = nameAndLoc.loc;

                // Special handling for GLSLLayoutModifier
                if (auto glslModifier = as<GLSLLayoutModifier>(modifier))
                {
                    if (AdvanceIf(parser, TokenType::OpAssign))
                    {
                        glslModifier->valToken = parser->ReadToken(TokenType::IntegerLiteral);
                    }
                }

                listBuilder.add(modifier);
            }

            if (AdvanceIf(parser, TokenType::RParent))
                break;
            parser->ReadToken(TokenType::Comma);
        }

        if (numThreadsAttrib)
        {
            listBuilder.add(numThreadsAttrib);
        }

        listBuilder.add(parser->astBuilder->create<GLSLLayoutModifierGroupEnd>());

        return listBuilder.getFirst();
    }

    static NodeBase* parseBuiltinTypeModifier(Parser* parser, void* /*userData*/)
    {
        BuiltinTypeModifier* modifier = parser->astBuilder->create<BuiltinTypeModifier>();
        parser->ReadToken(TokenType::LParent);
        modifier->tag = BaseType(stringToInt(parser->ReadToken(TokenType::IntegerLiteral).getContent()));
        parser->ReadToken(TokenType::RParent);

        return modifier;
    }

    static NodeBase* parseBuiltinRequirementModifier(Parser* parser, void* /*userData*/)
    {
        BuiltinRequirementModifier* modifier = parser->astBuilder->create<BuiltinRequirementModifier>();
        parser->ReadToken(TokenType::LParent);
        modifier->kind = BuiltinRequirementKind(stringToInt(parser->ReadToken(TokenType::IntegerLiteral).getContent()));
        parser->ReadToken(TokenType::RParent);

        return modifier;
    }

    static NodeBase* parseMagicTypeModifier(Parser* parser, void* /*userData*/)
    {
        MagicTypeModifier* modifier = parser->astBuilder->create<MagicTypeModifier>();
        parser->ReadToken(TokenType::LParent);
        modifier->magicName = parser->ReadToken(TokenType::Identifier).getContent();
        if (AdvanceIf(parser, TokenType::Comma))
        {
            modifier->tag = uint32_t(stringToInt(parser->ReadToken(TokenType::IntegerLiteral).getContent()));
        }
        parser->ReadToken(TokenType::RParent);

        return modifier;
    }

    static NodeBase* parseIntrinsicTypeModifier(Parser* parser, void* /*userData*/)
    {
        IntrinsicTypeModifier* modifier = parser->astBuilder->create<IntrinsicTypeModifier>();
        parser->ReadToken(TokenType::LParent);
        modifier->irOp = uint32_t(stringToInt(parser->ReadToken(TokenType::IntegerLiteral).getContent()));
        while( AdvanceIf(parser, TokenType::Comma) )
        {
            auto operand = uint32_t(stringToInt(parser->ReadToken(TokenType::IntegerLiteral).getContent()));
            modifier->irOperands.add(operand);
        }
        parser->ReadToken(TokenType::RParent);

        return modifier;
    }
    static NodeBase* parseImplicitConversionModifier(Parser* parser, void* /*userData*/)
    {
        ImplicitConversionModifier* modifier = parser->astBuilder->create<ImplicitConversionModifier>();
        BuiltinConversionKind builtinKind = kBuiltinConversion_Unknown;
        ConversionCost cost = kConversionCost_Default;
        if( AdvanceIf(parser, TokenType::LParent) )
        {
            cost = ConversionCost(stringToInt(parser->ReadToken(TokenType::IntegerLiteral).getContent()));
            if (AdvanceIf(parser, TokenType::Comma))
            {
                builtinKind = BuiltinConversionKind(stringToInt(parser->ReadToken(TokenType::IntegerLiteral).getContent()));
            }
            parser->ReadToken(TokenType::RParent);
        }
        modifier->cost = cost;
        modifier->builtinConversionKind = builtinKind;
        return modifier;
    }

    static NodeBase* parseAttributeTargetModifier(Parser* parser, void* /*userData*/)
    {
        expect(parser, TokenType::LParent);
        auto syntaxClassNameAndLoc = expectIdentifier(parser);
        expect(parser, TokenType::RParent);

        auto syntaxClass = parser->astBuilder->findSyntaxClass(syntaxClassNameAndLoc.name);

        AttributeTargetModifier* modifier = parser->astBuilder->create<AttributeTargetModifier>();
        modifier->syntaxClass = syntaxClass;

        return modifier;
    }

    static SyntaxParseInfo _makeParseExpr(const char* keywordName, SyntaxParseCallback callback)
    {
        SyntaxParseInfo entry;
        entry.classInfo = &Expr::kReflectClassInfo;
        entry.keywordName = keywordName;
        entry.callback = callback;
        return entry; 
    }
    static SyntaxParseInfo _makeParseDecl(const char* keywordName, SyntaxParseCallback callback)
    {
        SyntaxParseInfo entry;
        entry.keywordName = keywordName;
        entry.callback = callback;
        entry.classInfo = &Decl::kReflectClassInfo;
        return entry;
    }
    static SyntaxParseInfo _makeParseModifier(const char* keywordName, const ReflectClassInfo& classInfo)
    {
        // If we just have class info - use simple parser
        SyntaxParseInfo entry;
        entry.keywordName = keywordName;
        entry.callback = &parseSimpleSyntax;
        entry.classInfo = &classInfo;
        return entry;
    }
    static SyntaxParseInfo _makeParseModifier(const char* keywordName, SyntaxParseCallback callback)
    {
        SyntaxParseInfo entry;
        entry.keywordName = keywordName;
        entry.callback = callback;
        entry.classInfo = &Modifier::kReflectClassInfo;
        return entry;
    }

    // Maps a keyword to the associated parsing function
    static const SyntaxParseInfo g_parseSyntaxEntries[] = 
    {
        // !!!!!!!!!!!!!!!!!!!! Decls !!!!!!!!!!!!!!!!!!

        _makeParseDecl("typedef",           parseTypeDef),
        _makeParseDecl("associatedtype",    parseAssocType),
        _makeParseDecl("type_param",        parseGlobalGenericTypeParamDecl ),
        _makeParseDecl("cbuffer",           parseHLSLCBufferDecl ),
        _makeParseDecl("tbuffer",           parseHLSLTBufferDecl ),
        _makeParseDecl("__generic",         parseGenericDecl ),
        _makeParseDecl("__extension",       parseExtensionDecl ),
        _makeParseDecl("extension",         parseExtensionDecl ),
        _makeParseDecl("__init",            parseConstructorDecl ),
        _makeParseDecl("__subscript",       parseSubscriptDecl ),
        _makeParseDecl("property",          parsePropertyDecl ),
        _makeParseDecl("interface",         parseInterfaceDecl ),
        _makeParseDecl("syntax",            parseSyntaxDecl ),
        _makeParseDecl("attribute_syntax",  parseAttributeSyntaxDecl ),
        _makeParseDecl("__import",          parseImportDecl ),
        _makeParseDecl("import",            parseImportDecl ),
        _makeParseDecl("let",               parseLetDecl ),
        _makeParseDecl("var",               parseVarDecl ),
        _makeParseDecl("func",              parseFuncDecl ),
        _makeParseDecl("typealias",         parseTypeAliasDecl ),
        _makeParseDecl("__generic_value_param", parseGlobalGenericValueParamDecl ),
        _makeParseDecl("namespace",         parseNamespaceDecl ),
        _makeParseDecl("using",             parseUsingDecl ),

        // !!!!!!!!!!!!!!!!!!!!!! Modifer !!!!!!!!!!!!!!!!!!!!!!

        // Add syntax for "simple" modifier keywords.
        // These are the ones that just appear as a single
        // keyword (no further tokens expected/allowed),
        // and which can be represented just by creating
        // a new AST node of the corresponding type.
        
        _makeParseModifier("in",            InModifier::kReflectClassInfo),
        _makeParseModifier("input",         InputModifier::kReflectClassInfo),
        _makeParseModifier("out",           OutModifier::kReflectClassInfo),
        _makeParseModifier("inout",         InOutModifier::kReflectClassInfo),
        _makeParseModifier("__ref",         RefModifier::kReflectClassInfo),
        _makeParseModifier("const",         ConstModifier::kReflectClassInfo),
        _makeParseModifier("instance",      InstanceModifier::kReflectClassInfo),
        _makeParseModifier("__builtin",     BuiltinModifier::kReflectClassInfo),

        _makeParseModifier("__global",      ActualGlobalModifier::kReflectClassInfo),

        _makeParseModifier("inline",        InlineModifier::kReflectClassInfo),
        _makeParseModifier("public",        PublicModifier::kReflectClassInfo),
        _makeParseModifier("require",       RequireModifier::kReflectClassInfo),
        _makeParseModifier("param",         ParamModifier::kReflectClassInfo),
        _makeParseModifier("extern",        ExternModifier::kReflectClassInfo),
        
        _makeParseModifier("row_major",     HLSLRowMajorLayoutModifier::kReflectClassInfo),
        _makeParseModifier("column_major",  HLSLColumnMajorLayoutModifier::kReflectClassInfo),

        _makeParseModifier("nointerpolation",   HLSLNoInterpolationModifier::kReflectClassInfo),
        _makeParseModifier("noperspective",     HLSLNoPerspectiveModifier::kReflectClassInfo),
        _makeParseModifier("linear",        HLSLLinearModifier::kReflectClassInfo),
        _makeParseModifier("sample",        HLSLSampleModifier::kReflectClassInfo),
        _makeParseModifier("centroid",      HLSLCentroidModifier::kReflectClassInfo),
        _makeParseModifier("precise",       PreciseModifier::kReflectClassInfo),
        _makeParseModifier("shared",        HLSLEffectSharedModifier::kReflectClassInfo),
        _makeParseModifier("groupshared",   HLSLGroupSharedModifier::kReflectClassInfo),
        _makeParseModifier("static",        HLSLStaticModifier::kReflectClassInfo),
        _makeParseModifier("uniform",       HLSLUniformModifier::kReflectClassInfo),
        _makeParseModifier("volatile",      HLSLVolatileModifier::kReflectClassInfo),
        _makeParseModifier("export",        HLSLExportModifier::kReflectClassInfo),

        // Modifiers for geometry shader input
        _makeParseModifier("point",         HLSLPointModifier::kReflectClassInfo),
        _makeParseModifier("line",          HLSLLineModifier::kReflectClassInfo),
        _makeParseModifier("triangle",      HLSLTriangleModifier::kReflectClassInfo),
        _makeParseModifier("lineadj",       HLSLLineAdjModifier::kReflectClassInfo),
        _makeParseModifier("triangleadj",   HLSLTriangleAdjModifier::kReflectClassInfo),

        // Modifiers for mesh shader parameters
        _makeParseModifier("vertices",      HLSLVerticesModifier::kReflectClassInfo),
        _makeParseModifier("indices",       HLSLIndicesModifier::kReflectClassInfo),
        _makeParseModifier("primitives",    HLSLPrimitivesModifier::kReflectClassInfo),

        // Modifiers for unary operator declarations
        _makeParseModifier("__prefix",      PrefixModifier::kReflectClassInfo),
        _makeParseModifier("__postfix",     PostfixModifier::kReflectClassInfo),

        // Modifier to apply to `import` that should be re-exported
        _makeParseModifier("__exported",    ExportedModifier::kReflectClassInfo),

        // Add syntax for more complex modifiers, which allow
        // or expect more tokens after the initial keyword.

        _makeParseModifier("layout",                parseLayoutModifier),

        _makeParseModifier("__intrinsic_op",        parseIntrinsicOpModifier),
        _makeParseModifier("__target_intrinsic",    parseTargetIntrinsicModifier),
        _makeParseModifier("__specialized_for_target",    parseSpecializedForTargetModifier),
        _makeParseModifier("__glsl_extension",      parseGLSLExtensionModifier),
        _makeParseModifier("__glsl_version",        parseGLSLVersionModifier),
        _makeParseModifier("__spirv_version",       parseSPIRVVersionModifier),
        _makeParseModifier("__cuda_sm_version",     parseCUDASMVersionModifier),

        _makeParseModifier("__builtin_type",        parseBuiltinTypeModifier),
        _makeParseModifier("__builtin_requirement", parseBuiltinRequirementModifier),

        _makeParseModifier("__magic_type",          parseMagicTypeModifier),
        _makeParseModifier("__intrinsic_type",      parseIntrinsicTypeModifier),
        _makeParseModifier("__implicit_conversion", parseImplicitConversionModifier),

        _makeParseModifier("__attributeTarget",     parseAttributeTargetModifier),

        // !!!!!!!!!!!!!!!!!!!!!!! Expr !!!!!!!!!!!!!!!!!!!!!!!!!!!

        _makeParseExpr("this",  parseThisExpr),
        _makeParseExpr("This",  parseThisTypeExpr),
        _makeParseExpr("true",  parseTrueExpr),
        _makeParseExpr("false", parseFalseExpr),
        _makeParseExpr("nullptr", parseNullPtrExpr),
        _makeParseExpr("none", parseNoneExpr),
        _makeParseExpr("try",     parseTryExpr),
        _makeParseExpr("no_diff", parseTreatAsDifferentiableExpr),
        _makeParseExpr("__TaggedUnion", parseTaggedUnionType),
        _makeParseExpr("__fwd_diff", parseForwardDifferentiate),
        _makeParseExpr("__bwd_diff", parseBackwardDifferentiate),
        _makeParseExpr("__dispatch_kernel", parseDispatchKernel)
    };

    ConstArrayView<SyntaxParseInfo> getSyntaxParseInfos()
    {
        return makeConstArrayView(g_parseSyntaxEntries, SLANG_COUNT_OF(g_parseSyntaxEntries));
    }

    ModuleDecl* populateBaseLanguageModule(
        ASTBuilder*     astBuilder,
        Scope*          scope)
    {
        Session* session = astBuilder->getGlobalSession();

        ModuleDecl* moduleDecl = astBuilder->create<ModuleDecl>();
        scope->containerDecl = moduleDecl;

        // Add syntax for declaration keywords
        for (const auto& info : getSyntaxParseInfos())
        {
            addBuiltinSyntaxImpl(session, scope, info.keywordName, info.callback, const_cast<ReflectClassInfo*>(info.classInfo), info.classInfo);
        }
    
        return moduleDecl;
    }

}