summaryrefslogtreecommitdiff
path: root/tests/preprocessor/define-function-like.slang.expected
blob: 1e4b4dcc9c4b64c4aaf40e935f237c145f125bd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
result code = -1
standard error = {
tests/preprocessor/define-function-like.slang(16): error 30015: undefined identifier 'x'.
#define M (x) - (x)
           ^
tests/preprocessor/define-function-like.slang(16): error 30015: undefined identifier 'x'.
#define M (x) - (x)
                 ^
}
standard output = {
}
f='#n44'>44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025
#include "syntax-visitors.h"

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

#include "../core/secure-crt.h"
#include <assert.h>

namespace Slang
{
    // A flat representation of basic types (scalars, vectors and matrices)
    // that can be used as lookup key in caches
    struct BasicTypeKey
    {
        union
        {
            struct
            {
                unsigned char type : 4;
                unsigned char dim1 : 2;
                unsigned char dim2 : 2;
            } data;
            unsigned char aggVal;
        };
        bool fromType(Type* typeIn)
        {
            aggVal = 0;
            if (auto basicType = typeIn->AsBasicType())
            {
                data.type = (unsigned char)basicType->baseType;
                data.dim1 = data.dim2 = 0;
            }
            else if (auto vectorType = typeIn->AsVectorType())
            {
                if (auto elemCount = vectorType->elementCount.As<ConstantIntVal>())
                {
                    data.dim1 = elemCount->value - 1;
                    data.type = (unsigned char)vectorType->elementType->AsBasicType()->baseType;
                    data.dim2 = 0;
                }
                else
                    return false;
            }
            else if (auto matrixType = typeIn->AsMatrixType())
            {
                if (auto elemCount1 = dynamic_cast<ConstantIntVal*>(matrixType->getRowCount()))
                {
                    if (auto elemCount2 = dynamic_cast<ConstantIntVal*>(matrixType->getColumnCount()))
                    {
                        data.type = (unsigned char)matrixType->getElementType()->AsBasicType()->baseType;
                        data.dim1 = elemCount1->value - 1;
                        data.dim2 = elemCount2->value - 1;
                    }
                }
                else
                    return false;
            }
            else
                return false;
            return true;
        }
    };

    struct BasicTypeKeyPair
    {
        BasicTypeKey type1, type2;
        bool operator == (BasicTypeKeyPair p)
        {
            return type1.aggVal == p.type1.aggVal && type2.aggVal == p.type2.aggVal;
        }
        int GetHashCode()
        {
            return combineHash(type1.aggVal, type2.aggVal);
        }
    };

    struct OverloadCandidate
    {
        enum class Flavor
        {
            Func,
            Generic,
            UnspecializedGeneric,
        };
        Flavor flavor;

        enum class Status
        {
            GenericArgumentInferenceFailed,
            Unchecked,
            ArityChecked,
            FixityChecked,
            TypeChecked,
            DirectionChecked,
            Appicable,
        };
        Status status = Status::Unchecked;

        // Reference to the declaration being applied
        LookupResultItem item;

        // The type of the result expression if this candidate is selected
        RefPtr<Type>	resultType;

        // A system for tracking constraints introduced on generic parameters
        //            ConstraintSystem constraintSystem;

        // How much conversion cost should be considered for this overload,
        // when ranking candidates.
        ConversionCost conversionCostSum = kConversionCost_None;

        // When required, a candidate can store a pre-checked list of
        // arguments so that we don't have to repeat work across checking
        // phases. Currently this is only needed for generics.
        RefPtr<Substitutions>   subst;
    };

    struct OperatorOverloadCacheKey
    {
        IROp operatorName;
        BasicTypeKey args[2];
        bool operator == (OperatorOverloadCacheKey key)
        {
            return operatorName == key.operatorName && args[0].aggVal == key.args[0].aggVal
                && args[1].aggVal == key.args[1].aggVal;
        }
        int GetHashCode()
        {
            return ((int)(UInt64)(void*)(operatorName) << 16) ^ (args[0].aggVal << 8) ^ (args[1].aggVal);
        }
        bool fromOperatorExpr(OperatorExpr* opExpr)
        {
            // First, lets see if the argument types are ones
            // that we can encode in our space of keys.
            args[0].aggVal = 0;
            args[1].aggVal = 0;
            if (opExpr->Arguments.Count() > 2)
                return false;

            for (UInt i = 0; i < opExpr->Arguments.Count(); i++)
            {
                if (!args[i].fromType(opExpr->Arguments[i]->type.Ptr()))
                    return false;
            }

            // Next, lets see if we can find an intrinsic opcode
            // attached to an overloaded definition (filtered for
            // definitions that could conceivably apply to us).
            //
            // TODO: This should really be pased on the operator name
            // plus fixity, rather than the intrinsic opcode...
            //
            // We will need to reject postfix definitions for prefix
            // operators, and vice versa, to ensure things work.
            //
            auto prefixExpr = opExpr->As<PrefixExpr>();
            auto postfixExpr = opExpr->As<PostfixExpr>();

            if (auto overloadedBase = opExpr->FunctionExpr->As<OverloadedExpr>())
            {
                for(auto item : overloadedBase->lookupResult2 )
                {
                    // Look at a candidate definition to be called and
                    // see if it gives us a key to work with.
                    //
                    Decl* funcDecl = overloadedBase->lookupResult2.item.declRef.decl;
                    if (auto genDecl = funcDecl->As<GenericDecl>())
                        funcDecl = genDecl->inner.Ptr();

                    // Reject definitions that have the wrong fixity.
                    //
                    if(prefixExpr && !funcDecl->FindModifier<PrefixModifier>())
                        continue;
                    if(postfixExpr && !funcDecl->FindModifier<PostfixModifier>())
                        continue;

                    if (auto intrinsicOp = funcDecl->FindModifier<IntrinsicOpModifier>())
                    {
                        operatorName = intrinsicOp->op;
                        return true;
                    }
                }
            }
            return false;
        }
    };

    struct TypeCheckingCache
    {
        Dictionary<OperatorOverloadCacheKey, OverloadCandidate> resolvedOperatorOverloadCache;
        Dictionary<BasicTypeKeyPair, ConversionCost> conversionCostCache;
    };

    TypeCheckingCache* Session::getTypeCheckingCache()
    {
        if (!typeCheckingCache)
            typeCheckingCache = new TypeCheckingCache();
        return typeCheckingCache;
    }

    void Session::destroyTypeCheckingCache()
    {
        delete typeCheckingCache;
        typeCheckingCache = nullptr;
    }

    bool IsNumeric(BaseType t)
    {
        return t == BaseType::Int || t == BaseType::Float || t == BaseType::UInt;
    }

    String TranslateHLSLTypeNames(String name)
    {
        if (name == "float2" || name == "half2")
            return "vec2";
        else if (name == "float3" || name == "half3")
            return "vec3";
        else if (name == "float4" || name == "half4")
            return "vec4";
        else if (name == "half")
            return "float";
        else if (name == "int2")
            return "ivec2";
        else if (name == "int3")
            return "ivec3";
        else if (name == "int4")
            return "ivec4";
        else if (name == "uint2")
            return "uvec2";
        else if (name == "uint3")
            return "uvec3";
        else if (name == "uint4")
            return "uvec4";
        else if (name == "float3x3" || name == "half3x3")
            return "mat3";
        else if (name == "float4x4" || name == "half4x4")
            return "mat4";
        else
            return name;
    }

    enum class CheckingPhase
    {
        Header, Body
    };

    struct SemanticsVisitor
        : ExprVisitor<SemanticsVisitor, RefPtr<Expr>>
        , StmtVisitor<SemanticsVisitor>
        , DeclVisitor<SemanticsVisitor>
    {
        CheckingPhase checkingPhase = CheckingPhase::Header;
        DeclCheckState getCheckedState()
        {
            if (checkingPhase == CheckingPhase::Body)
                return DeclCheckState::Checked;
            else
                return DeclCheckState::CheckedHeader;
        }
        DiagnosticSink* sink = nullptr;
        DiagnosticSink* getSink()
        {
            return sink;
        }

//        ModuleDecl * program = nullptr;
        FuncDecl * function = nullptr;

        CompileRequest* request = nullptr;
        TranslationUnitRequest* translationUnit = nullptr;

        SourceLanguage getSourceLanguage()
        {
            return translationUnit->sourceLanguage;
        }

        // lexical outer statements
        List<Stmt*> outerStmts;

        // We need to track what has been `import`ed,
        // to avoid importing the same thing more than once
        //
        // TODO: a smarter approach might be to filter
        // out duplicate references during lookup.
        HashSet<ModuleDecl*> importedModules;

    public:
        SemanticsVisitor(
            DiagnosticSink*         sink,
            CompileRequest*         request,
            TranslationUnitRequest* translationUnit)
            : sink(sink)
            , request(request)
            , translationUnit(translationUnit)
        {
        }

        CompileRequest* getCompileRequest() { return request; }
        TranslationUnitRequest* getTranslationUnit() { return translationUnit; }
        Session* getSession()
        {
            return getCompileRequest()->mSession;
        }

    public:
        // Translate Types
        RefPtr<Type> typeResult;
        RefPtr<Expr> TranslateTypeNodeImpl(const RefPtr<Expr> & node)
        {
            if (!node) return nullptr;

            auto expr = CheckTerm(node);
            expr = ExpectATypeRepr(expr);
            return expr;
        }
        RefPtr<Type> ExtractTypeFromTypeRepr(const RefPtr<Expr>& typeRepr)
        {
            if (!typeRepr) return nullptr;
            if (auto typeType = typeRepr->type->As<TypeType>())
            {
                return typeType->type;
            }
            return getSession()->getErrorType();
        }
        RefPtr<Type> TranslateTypeNode(const RefPtr<Expr> & node)
        {
            if (!node) return nullptr;
            auto typeRepr = TranslateTypeNodeImpl(node);
            return ExtractTypeFromTypeRepr(typeRepr);
        }
        TypeExp TranslateTypeNodeForced(TypeExp const& typeExp)
        {
            auto typeRepr = TranslateTypeNodeImpl(typeExp.exp);

            TypeExp result;
            result.exp = typeRepr;
            result.type = ExtractTypeFromTypeRepr(typeRepr);
            return result;
        }
        TypeExp TranslateTypeNode(TypeExp const& typeExp)
        {
            // HACK(tfoley): It seems that in some cases we end up re-checking
            // syntax that we've already checked. We need to root-cause that
            // issue, but for now a quick fix in this case is to early
            // exist if we've already got a type associated here:
            if (typeExp.type)
            {
                return typeExp;
            }
            return TranslateTypeNodeForced(typeExp);
        }

        RefPtr<DeclRefType> getExprDeclRefType(Expr * expr)
        {
            if (auto typetype = expr->type->As<TypeType>())
                return typetype->type.As<DeclRefType>();
            else
                return expr->type->As<DeclRefType>();
        }

        /// Is `decl` usable as a static member?
        bool isDeclUsableAsStaticMember(
            Decl*   decl)
        {
            if(decl->HasModifier<HLSLStaticModifier>())
                return true;

            if(decl->As<ConstructorDecl>())
                return true;

            if(decl->As<EnumCaseDecl>())
                return true;

            if(decl->As<AggTypeDeclBase>())
                return true;

            if(decl->As<SimpleTypeDecl>())
                return true;

            return false;
        }

        /// Is `item` usable as a static member?
        bool isUsableAsStaticMember(
            LookupResultItem const& item)
        {
            // There's a bit of a gotcha here, because a lookup result
            // item might include "breadcrumbs" that indicate more steps
            // along the lookup path. As a result it isn't always
            // valid to just check whether the final decl is usable
            // as a static member, because it might not even be a
            // member of the thing we are trying to work with.
            //

            Decl* decl = item.declRef.getDecl();
            for(auto bb = item.breadcrumbs; bb; bb = bb->next)
            {
                switch(bb->kind)
                {
                // In case lookup went through a `__transparent` member,
                // we are interested in the static-ness of that transparent
                // member, and *not* the static-ness of whatever was inside
                // of it.
                //
                // TODO: This would need some work if we ever had
                // transparent *type* members.
                //
                case LookupResultItem::Breadcrumb::Kind::Member:
                    decl = bb->declRef.getDecl();
                    break;

                // TODO: Are there any other cases that need special-case
                // handling here?

                default:
                    break;
                }
            }

            // Okay, we've found the declaration we should actually
            // be checking, so lets validate that.

            return isDeclUsableAsStaticMember(decl);
        }

        RefPtr<Expr> ConstructDeclRefExpr(
            DeclRef<Decl>   declRef,
            RefPtr<Expr>    baseExpr,
            SourceLoc       loc)
        {
            // Compute the type that this declaration reference will have in context.
            //
            auto type = GetTypeForDeclRef(declRef);

            // Construct an appropriate expression based on teh structured of
            // the declaration reference.
            //
            if (baseExpr)
            {
                // If there was a base expression, we will have some kind of
                // member expression.
                //
                if (baseExpr->type->As<TypeType>())
                {
                    auto expr = new StaticMemberExpr();
                    expr->loc = loc;
                    expr->type = type;
                    expr->BaseExpression = baseExpr;
                    expr->name = declRef.GetName();
                    expr->declRef = declRef;
                    return expr;
                }
                else
                {
                    // If the base expression wasn't a type, then this
                    // is a normal member expression.
                    //
                    auto expr = new MemberExpr();
                    expr->loc = loc;
                    expr->type = type;
                    expr->BaseExpression = baseExpr;
                    expr->name = declRef.GetName();
                    expr->declRef = declRef;

                    // When referring to a member through an expression,
                    // the result is only an l-value if both the base
                    // expression and the member agree that it should be.
                    //
                    // We have already used the `QualType` from the member
                    // above (that is `type`), so we need to take the
                    // l-value status of the base expression into account now.
                    if(!baseExpr->type.IsLeftValue)
                    {
                        expr->type.IsLeftValue = false;
                    }

                    return expr;
                }
            }
            else
            {
                // If there is no base expression, then the result must
                // be an ordinary variable expression.
                //
                auto expr = new VarExpr();
                expr->loc = loc;
                expr->name = declRef.GetName();
                expr->type = type;
                expr->declRef = declRef;
                return expr;
            }
        }

        RefPtr<Expr> ConstructDerefExpr(
            RefPtr<Expr>    base,
            SourceLoc       loc)
        {
            auto ptrLikeType = base->type->As<PointerLikeType>();
            SLANG_ASSERT(ptrLikeType);

            auto derefExpr = new DerefExpr();
            derefExpr->loc = loc;
            derefExpr->base = base;
            derefExpr->type = QualType(ptrLikeType->elementType);

            // TODO(tfoley): handle l-value status here

            return derefExpr;
        }

        RefPtr<Expr> createImplicitThisMemberExpr(
            Type*       type,
            SourceLoc   loc)
        {
            RefPtr<ThisExpr> expr = new ThisExpr();
            expr->type = type;
            expr->loc = loc;
            return expr;
        }

        RefPtr<Expr> ConstructLookupResultExpr(
            LookupResultItem const& item,
            RefPtr<Expr>            baseExpr,
            SourceLoc               loc)
        {
            // If we collected any breadcrumbs, then these represent
            // additional segments of the lookup path that we need
            // to expand here.
            auto bb = baseExpr;
            for (auto breadcrumb = item.breadcrumbs; breadcrumb; breadcrumb = breadcrumb->next)
            {
                switch (breadcrumb->kind)
                {
                case LookupResultItem::Breadcrumb::Kind::Member:
                    bb = ConstructDeclRefExpr(breadcrumb->declRef, bb, loc);
                    break;

                case LookupResultItem::Breadcrumb::Kind::Deref:
                    bb = ConstructDerefExpr(bb, loc);
                    break;

                case LookupResultItem::Breadcrumb::Kind::Constraint:
                    {
                        // TODO: do we need to make something more
                        // explicit here?
                        bb = ConstructDeclRefExpr(
                            breadcrumb->declRef,
                            bb,
                            loc);
                    }
                    break;

                case LookupResultItem::Breadcrumb::Kind::This:
                    {
                        // We expect a `this` to always come
                        // at the start of a chain.
                        SLANG_ASSERT(bb == nullptr);

                        // The member was looked up via a `this` expression,
                        // so we need to create one here.
                        if (auto extensionDeclRef = breadcrumb->declRef.As<ExtensionDecl>())
                        {
                            bb = createImplicitThisMemberExpr(
                                GetTargetType(extensionDeclRef),
                                loc);
                        }
                        else
                        {
                            auto type = DeclRefType::Create(getSession(), breadcrumb->declRef);
                            bb = createImplicitThisMemberExpr(
                                type,
                                loc);
                        }
                    }
                    break;

                default:
                    SLANG_UNREACHABLE("all cases handle");
                }
            }

            return ConstructDeclRefExpr(item.declRef, bb, loc);
        }

        RefPtr<Expr> createLookupResultExpr(
            LookupResult const&     lookupResult,
            RefPtr<Expr>            baseExpr,
            SourceLoc               loc)
        {
            if (lookupResult.isOverloaded())
            {
                auto overloadedExpr = new OverloadedExpr();
                overloadedExpr->loc = loc;
                overloadedExpr->type = QualType(
                    getSession()->getOverloadedType());
                overloadedExpr->base = baseExpr;
                overloadedExpr->lookupResult2 = lookupResult;
                return overloadedExpr;
            }
            else
            {
                return ConstructLookupResultExpr(lookupResult.item, baseExpr, loc);
            }
        }

        RefPtr<Expr> ResolveOverloadedExpr(RefPtr<OverloadedExpr> overloadedExpr, LookupMask mask)
        {
            auto lookupResult = overloadedExpr->lookupResult2;
            SLANG_RELEASE_ASSERT(lookupResult.isValid() && lookupResult.isOverloaded());

            // Take the lookup result we had, and refine it based on what is expected in context.
            lookupResult = refineLookup(lookupResult, mask);

            if (!lookupResult.isValid())
            {
                // If we didn't find any symbols after filtering, then just
                // use the original and report errors that way
                return overloadedExpr;
            }

            if (lookupResult.isOverloaded())
            {
                // We had an ambiguity anyway, so report it.
                getSink()->diagnose(overloadedExpr, Diagnostics::ambiguousReference, lookupResult.items[0].declRef.GetName());

                for(auto item : lookupResult.items)
                {
                    String declString = getDeclSignatureString(item);
                    getSink()->diagnose(item.declRef, Diagnostics::overloadCandidate, declString);
                }

                // TODO(tfoley): should we construct a new ErrorExpr here?
                return CreateErrorExpr(overloadedExpr);
            }

            // otherwise, we had a single decl and it was valid, hooray!
            return ConstructLookupResultExpr(lookupResult.item, overloadedExpr->base, overloadedExpr->loc);
        }

        RefPtr<Expr> ExpectATypeRepr(RefPtr<Expr> expr)
        {
            if (auto overloadedExpr = expr.As<OverloadedExpr>())
            {
                expr = ResolveOverloadedExpr(overloadedExpr, LookupMask::type);
            }

            if (auto typeType = expr->type.type->As<TypeType>())
            {
                return expr;
            }
            else if (auto errorType = expr->type.type->As<ErrorType>())
            {
                return expr;
            }

            getSink()->diagnose(expr, Diagnostics::unimplemented, "expected a type");
            return CreateErrorExpr(expr);
        }

        RefPtr<Type> ExpectAType(RefPtr<Expr> expr)
        {
            auto typeRepr = ExpectATypeRepr(expr);
            if (auto typeType = typeRepr->type->As<TypeType>())
            {
                return typeType->type;
            }
            return getSession()->getErrorType();
        }

        RefPtr<Type> ExtractGenericArgType(RefPtr<Expr> exp)
        {
            return ExpectAType(exp);
        }

        RefPtr<IntVal> ExtractGenericArgInteger(RefPtr<Expr> exp)
        {
            return CheckIntegerConstantExpression(exp.Ptr());
        }

        RefPtr<Val> ExtractGenericArgVal(RefPtr<Expr> exp)
        {
            if (auto overloadedExpr = exp.As<OverloadedExpr>())
            {
                // assume that if it is overloaded, we want a type
                exp = ResolveOverloadedExpr(overloadedExpr, LookupMask::type);
            }

            if (auto typeType = exp->type->As<TypeType>())
            {
                return typeType->type;
            }
            else if (auto errorType = exp->type->As<ErrorType>())
            {
                return exp->type.type;
            }
            else
            {
                return ExtractGenericArgInteger(exp);
            }
        }

        // Construct a type reprsenting the instantiation of
        // the given generic declaration for the given arguments.
        // The arguments should already be checked against
        // the declaration.
        RefPtr<Type> InstantiateGenericType(
            DeclRef<GenericDecl>        genericDeclRef,
            List<RefPtr<Expr>> const&   args)
        {
            RefPtr<GenericSubstitution> subst = new GenericSubstitution();
            subst->genericDecl = genericDeclRef.getDecl();
            subst->outer = genericDeclRef.substitutions.substitutions;

            for (auto argExpr : args)
            {
                subst->args.Add(ExtractGenericArgVal(argExpr));
            }

            DeclRef<Decl> innerDeclRef;
            innerDeclRef.decl = GetInner(genericDeclRef);
            innerDeclRef.substitutions = SubstitutionSet(subst);

            return DeclRefType::Create(
                getSession(),
                innerDeclRef);
        }

        // This routine is a bottleneck for all declaration checking,
        // so that we can add some quality-of-life features for users
        // in cases where the compiler crashes
        void dispatchDecl(DeclBase* decl)
        {
            try
            {
                DeclVisitor::dispatch(decl);
            }
            // Don't emit any context message for an explicit `AbortCompilationException`
            // because it should only happen when an error is already emitted.
            catch(AbortCompilationException&) { throw; }
            catch(...)
            {
                getCompileRequest()->noteInternalErrorLoc(decl->loc);
                throw;
            }
        }
        void dispatchStmt(Stmt* stmt)
        {
            try
            {
                StmtVisitor::dispatch(stmt);
            }
            catch(AbortCompilationException&) { throw; }
            catch(...)
            {
                getCompileRequest()->noteInternalErrorLoc(stmt->loc);
                throw;
            }
        }
        void dispatchExpr(Expr* expr)
        {
            try
            {
                ExprVisitor::dispatch(expr);
            }
            catch(AbortCompilationException&) { throw; }
            catch(...)
            {
                getCompileRequest()->noteInternalErrorLoc(expr->loc);
                throw;
            }
        }

        // Make sure a declaration has been checked, so we can refer to it.
        // Note that this may lead to us recursively invoking checking,
        // so this may not be the best way to handle things.
        void EnsureDecl(RefPtr<Decl> decl, DeclCheckState state)
        {
            if (decl->IsChecked(state)) return;
            if (decl->checkState == DeclCheckState::CheckingHeader)
            {
                // We tried to reference the same declaration while checking it!
                //
                // TODO: we should ideally be tracking a "chain" of declarations
                // being checked on the stack, so that we can report the full
                // chain that leads from this declaration back to itself.
                //
                sink->diagnose(decl, Diagnostics::cyclicReference, decl);
                return;
            }

            // Hack: if we are somehow referencing a local variable declaration
            // before the line of code that defines it, then we need to diagnose
            // an error.
            //
            // TODO: The right answer is that lookup should have been performed in
            // the scope that was in place *before* the variable was declared, but
            // this is a quick fix that at least alerts the user to how we are
            // interpreting their code.
            if (auto varDecl = decl.As<Variable>())
            {
                if (auto parenScope = varDecl->ParentDecl->As<ScopeDecl>())
                {
                    // TODO: This diagnostic should be emitted on the line that is referencing
                    // the declaration. That requires `EnsureDecl` to take the requesting
                    // location as a parameter.
                    sink->diagnose(decl, Diagnostics::localVariableUsedBeforeDeclared, decl);
                    return;
                }
            }

            if (DeclCheckState::CheckingHeader > decl->checkState)
            {
                decl->SetCheckState(DeclCheckState::CheckingHeader);
            }

            // Use visitor pattern to dispatch to correct case
            dispatchDecl(decl);

            if(state > decl->checkState)
            {
                decl->SetCheckState(state);
            }
        }

        void EnusreAllDeclsRec(RefPtr<Decl> decl)
        {
            checkDecl(decl);
            if (auto containerDecl = decl.As<ContainerDecl>())
            {
                for (auto m : containerDecl->Members)
                {
                    EnusreAllDeclsRec(m);
                }
            }
        }

        // A "proper" type is one that can be used as the type of an expression.
        // Put simply, it can be a concrete type like `int`, or a generic
        // type that is applied to arguments, like `Texture2D<float4>`.
        // The type `void` is also a proper type, since we can have expressions
        // that return a `void` result (e.g., many function calls).
        //
        // A "non-proper" type is any type that can't actually have values.
        // A simple example of this in C++ is `std::vector` - you can't have
        // a value of this type.
        //
        // Part of what this function does is give errors if somebody tries
        // to use a non-proper type as the type of a variable (or anything
        // else that needs a proper type).
        //
        // The other thing it handles is the fact that HLSL lets you use
        // the name of a non-proper type, and then have the compiler fill
        // in the default values for its type arguments (e.g., a variable
        // given type `Texture2D` will actually have type `Texture2D<float4>`).
        bool CoerceToProperTypeImpl(
            TypeExp const&  typeExp,
            RefPtr<Type>*   outProperType,
            DiagnosticSink* diagSink)
        {
            Type* type = typeExp.type.Ptr();
            if(!type && typeExp.exp)
            {
                if(auto typeType = typeExp.exp->type.type.As<TypeType>())
                {
                    type = typeType->type;
                }
            }

            if (auto genericDeclRefType = type->As<GenericDeclRefType>())
            {
                // We are using a reference to a generic declaration as a concrete
                // type. This means we should substitute in any default parameter values
                // if they are available.
                //
                // TODO(tfoley): A more expressive type system would substitute in
                // "fresh" variables and then solve for their values...
                //

                auto genericDeclRef = genericDeclRefType->GetDeclRef();
                checkDecl(genericDeclRef.decl);
                List<RefPtr<Expr>> args;
                for (RefPtr<Decl> member : genericDeclRef.getDecl()->Members)
                {
                    if (auto typeParam = member.As<GenericTypeParamDecl>())
                    {
                        if (!typeParam->initType.exp)
                        {
                            if (diagSink)
                            {
                                diagSink->diagnose(typeExp.exp.Ptr(), Diagnostics::genericTypeNeedsArgs, typeExp);
                                *outProperType = getSession()->getErrorType();
                            }
                            return false;
                        }

                        // TODO: this is one place where syntax should get cloned!
                        if(outProperType)
                            args.Add(typeParam->initType.exp);
                    }
                    else if (auto valParam = member.As<GenericValueParamDecl>())
                    {
                        if (!valParam->initExpr)
                        {
                            if (diagSink)
                            {
                                diagSink->diagnose(typeExp.exp.Ptr(), Diagnostics::unimplemented, "can't fill in default for generic type parameter");
                                *outProperType = getSession()->getErrorType();
                            }
                            return false;
                        }

                        // TODO: this is one place where syntax should get cloned!
                        if(outProperType)
                            args.Add(valParam->initExpr);
                    }
                    else
                    {
                        // ignore non-parameter members
                    }
                }

                if (outProperType)
                {
                    *outProperType = InstantiateGenericType(genericDeclRef, args);
                }
                return true;
            }
            else
            {
                // default case: we expect this to already be a proper type
                if (outProperType)
                {
                    *outProperType = type;
                }
                return true;
            }
        }



        TypeExp CoerceToProperType(TypeExp const& typeExp)
        {
            TypeExp result = typeExp;
            CoerceToProperTypeImpl(typeExp, &result.type, getSink());
            return result;
        }

        TypeExp tryCoerceToProperType(TypeExp const& typeExp)
        {
            TypeExp result = typeExp;
            if(!CoerceToProperTypeImpl(typeExp, &result.type, nullptr))
                return TypeExp();
            return result;
        }

        // Check a type, and coerce it to be proper
        TypeExp CheckProperType(TypeExp typeExp)
        {
            return CoerceToProperType(TranslateTypeNode(typeExp));
        }

        // For our purposes, a "usable" type is one that can be
        // used to declare a function parameter, variable, etc.
        // These turn out to be all the proper types except
        // `void`.
        //
        // TODO(tfoley): consider just allowing `void` as a
        // simple example of a "unit" type, and get rid of
        // this check.
        TypeExp CoerceToUsableType(TypeExp const& typeExp)
        {
            TypeExp result = CoerceToProperType(typeExp);
            Type* type = result.type.Ptr();
            if (auto basicType = type->As<BasicExpressionType>())
            {
                // TODO: `void` shouldn't be a basic type, to make this easier to avoid
                if (basicType->baseType == BaseType::Void)
                {
                    // TODO(tfoley): pick the right diagnostic message
                    getSink()->diagnose(result.exp.Ptr(), Diagnostics::invalidTypeVoid);
                    result.type = getSession()->getErrorType();
                    return result;
                }
            }
            return result;
        }

        // Check a type, and coerce it to be usable
        TypeExp CheckUsableType(TypeExp typeExp)
        {
            return CoerceToUsableType(TranslateTypeNode(typeExp));
        }

        RefPtr<Expr> CheckTerm(RefPtr<Expr> term)
        {
            if (!term) return nullptr;
            return ExprVisitor::dispatch(term);
        }

        RefPtr<Expr> CreateErrorExpr(Expr* expr)
        {
            expr->type = QualType(getSession()->getErrorType());
            return expr;
        }

        bool IsErrorExpr(RefPtr<Expr> expr)
        {
            // TODO: we may want other cases here...

            if (auto errorType = expr->type->As<ErrorType>())
                return true;

            return false;
        }

        // Capture the "base" expression in case this is a member reference
        RefPtr<Expr> GetBaseExpr(RefPtr<Expr> expr)
        {
            if (auto memberExpr = expr.As<MemberExpr>())
            {
                return memberExpr->BaseExpression;
            }
            else if(auto overloadedExpr = expr.As<OverloadedExpr>())
            {
                return overloadedExpr->base;
            }
            return nullptr;
        }

    public:

        bool ValuesAreEqual(
            RefPtr<IntVal> left,
            RefPtr<IntVal> right)
        {
            if(left == right) return true;

            if(auto leftConst = left.As<ConstantIntVal>())
            {
                if(auto rightConst = right.As<ConstantIntVal>())
                {
                    return leftConst->value == rightConst->value;
                }
            }

            if(auto leftVar = left.As<GenericParamIntVal>())
            {
                if(auto rightVar = right.As<GenericParamIntVal>())
                {
                    return leftVar->declRef.Equals(rightVar->declRef);
                }
            }

            return false;
        }

        // Compute the cost of using a particular declaration to
        // perform implicit type conversion.
        ConversionCost getImplicitConversionCost(
            Decl* decl)
        {
            if(auto modifier = decl->FindModifier<ImplicitConversionModifier>())
            {
                return modifier->cost;
            }

            return kConversionCost_Explicit;
        }

        // Central engine for implementing implicit coercion logic
        bool TryCoerceImpl(
            RefPtr<Type>			toType,		// the target type for conversion
            RefPtr<Expr>*	outToExpr,	// (optional) a place to stuff the target expression
            RefPtr<Type>			fromType,	// the source type for the conversion
            RefPtr<Expr>	fromExpr,	// the source expression
            ConversionCost*					outCost)	// (optional) a place to stuff the conversion cost
        {
            // Easy case: the types are equal
            if (toType->Equals(fromType))
            {
                if (outToExpr)
                    *outToExpr = fromExpr;
                if (outCost)
                    *outCost = kConversionCost_None;
                return true;
            }

            // If either type is an error, then let things pass.
            if (toType->As<ErrorType>() || fromType->As<ErrorType>())
            {
                if (outToExpr)
                    *outToExpr = CreateImplicitCastExpr(toType, fromExpr);
                if (outCost)
                    *outCost = kConversionCost_None;
                return true;
            }

            // Coercion from an initializer list is allowed for many types
            if( auto fromInitializerListExpr = fromExpr.As<InitializerListExpr>())
            {
                auto argCount = fromInitializerListExpr->args.Count();

                // In the case where we need to build a reuslt expression,
                // we will collect the new arguments here
                List<RefPtr<Expr>> coercedArgs;

                if (auto toVecType = toType->As<VectorExpressionType>())
                {
                    auto toElementCount = toVecType->elementCount;
                    auto toElementType = toVecType->elementType;

                    UInt elementCount = 0;
                    if (auto constElementCount = toElementCount.As<ConstantIntVal>())
                    {
                        elementCount = (UInt) constElementCount->value;
                    }
                    else
                    {
                        // We don't know the element count statically,
                        // so what are we supposed to be doing?
                        elementCount = fromInitializerListExpr->args.Count();
                    }

                    // TODO: need to check that the element count
                    // for the vector type matches the argument
                    // count for the initializer list, or else
                    // fix them up to match.

                    for(auto arg : fromInitializerListExpr->args)
                    {
                        RefPtr<Expr> coercedArg;
                        ConversionCost argCost;

                        bool argResult = TryCoerceImpl(
                            toElementType,
                            outToExpr ? &coercedArg : nullptr,
                            arg->type,
                            arg,
                            outCost ? &argCost : nullptr);

                        // No point in trying further if any argument fails
                        if(!argResult)
                            return false;

                        // TODO(tfoley): what to do with cost?
                        // This only matters if/when we allow an initializer list as an argument to
                        // an overloaded call.

                        if( outToExpr )
                        {
                            coercedArgs.Add(coercedArg);
                        }
                    }
                }
                //
                // TODO(tfoley): How to handle matrices here?
                // Should they expect individual scalars, or support
                // vectors for the rows?
                //
                if(auto toDeclRefType = toType->As<DeclRefType>())
                {
                    auto toTypeDeclRef = toDeclRefType->declRef;
                    if(auto toStructDeclRef = toTypeDeclRef.As<StructDecl>())
                    {
                        // Trying to initialize a `struct` type given an initializer list.
                        // We will go through the fields in order and try to match them
                        // up with initializer arguments.


                        UInt argIndex = 0;
                        for(auto fieldDeclRef : getMembersOfType<StructField>(toStructDeclRef))
                        {
                            if(argIndex >= argCount)
                            {
                                // We've consumed all the arguments, so we should stop
                                break;
                            }

                            auto arg = fromInitializerListExpr->args[argIndex++];

                            //
                            RefPtr<Expr> coercedArg;
                            ConversionCost argCost;

                            bool argResult = TryCoerceImpl(
                                GetType(fieldDeclRef),
                                outToExpr ? &coercedArg : nullptr,
                                arg->type,
                                arg,
                                outCost ? &argCost : nullptr);

                            // No point in trying further if any argument fails
                            if(!argResult)
                                return false;

                            // TODO(tfoley): what to do with cost?
                            // This only matters if/when we allow an initializer list as an argument to
                            // an overloaded call.

                            if( outToExpr )
                            {
                                coercedArgs.Add(coercedArg);
                            }
                        }
                    }
                }
                else if(auto toArrayType = toType->As<ArrayExpressionType>())
                {
                    // TODO(tfoley): If we can compute the size of the array statically,
                    // then we want to check that there aren't too many initializers present

                    auto toElementType = toArrayType->baseType;

                    for(auto& arg : fromInitializerListExpr->args)
                    {
                        RefPtr<Expr> coercedArg;
                        ConversionCost argCost;

                        bool argResult = TryCoerceImpl(
                                toElementType,
                                outToExpr ? &coercedArg : nullptr,
                                arg->type,
                                arg,
                                outCost ? &argCost : nullptr);

                        // No point in trying further if any argument fails
                        if(!argResult)
                            return false;

                        if( outToExpr )
                        {
                            coercedArgs.Add(coercedArg);
                        }
                    }
                }
                else
                {
                    // By default, we don't allow a type to be initialized using
                    // an initializer list.
                    return false;
                }

                // For now, coercion from an initializer list has no cost
                if(outCost)
                {
                    *outCost = kConversionCost_None;
                }

                // We were able to coerce all the arguments given, and so
                // we need to construct a suitable expression to remember the result
                if(outToExpr)
                {
                    auto toInitializerListExpr = new InitializerListExpr();
                    toInitializerListExpr->loc = fromInitializerListExpr->loc;
                    toInitializerListExpr->type = QualType(toType);
                    toInitializerListExpr->args = coercedArgs;


                    *outToExpr = toInitializerListExpr;
                }

                return true;
            }

            //
            if (auto toDeclRefType = toType->As<DeclRefType>())
            {
                auto toTypeDeclRef = toDeclRefType->declRef;
                if (auto interfaceDeclRef = toTypeDeclRef.As<InterfaceDecl>())
                {
                    // Trying to convert to an interface type.
                    //
                    // We will allow this if the type conforms to the interface.
                    if (DoesTypeConformToInterface(fromType, interfaceDeclRef))
                    {
                        if (outToExpr)
                            *outToExpr = CreateImplicitCastExpr(toType, fromExpr);
                        if (outCost)
                            *outCost = kConversionCost_CastToInterface;
                        return true;
                    }
                }
                else if (auto genParamDeclRef = toTypeDeclRef.As<GenericTypeParamDecl>())
                {
                    // We need to enumerate the constraints placed on this type by its outer
                    // generic declaration, and see if any of them guarantees that we
                    // satisfy the given interface..
                    auto genericDeclRef = genParamDeclRef.GetParent().As<GenericDecl>();
                    SLANG_ASSERT(genericDeclRef);

                    for (auto constraintDeclRef : getMembersOfType<GenericTypeConstraintDecl>(genericDeclRef))
                    {
                        auto sub = GetSub(constraintDeclRef);
                        auto sup = GetSup(constraintDeclRef);

                        auto subDeclRef = sub->As<DeclRefType>();
                        if (!subDeclRef)
                            continue;
                        if (subDeclRef->declRef != genParamDeclRef)
                            continue;
                        auto supDeclRefType = sup->As<DeclRefType>();
                        if (supDeclRefType)
                        {
                            auto toInterfaceDeclRef = supDeclRefType->declRef.As<InterfaceDecl>();
                            if (DoesTypeConformToInterface(fromType, toInterfaceDeclRef))
                            {
                                if (outToExpr)
                                    *outToExpr = CreateImplicitCastExpr(toType, fromExpr);
                                if (outCost)
                                    *outCost = kConversionCost_CastToInterface;
                                return true;
                            }
                        }
                    }

                }

            }

            // Are we converting from a parameter group type to its element type?
            if(auto fromParameterGroupType = fromType->As<ParameterGroupType>())
            {
                auto fromElementType = fromParameterGroupType->getElementType();

                // If we have, e.g., `ConstantBuffer<A>` and we want to convert
                // to `B`, where conversion from `A` to `B` is possible, then
                // we will do so here.

                ConversionCost subCost = 0;
                if(CanCoerce(toType, fromElementType, &subCost))
                {
                    if(outCost)
                        *outCost = subCost + kConversionCost_ImplicitDereference;

                    if(outToExpr)
                    {
                        auto derefExpr = new DerefExpr();
                        derefExpr->base = fromExpr;
                        derefExpr->type = QualType(fromElementType);

                        return TryCoerceImpl(
                            toType,
                            outToExpr,
                            fromElementType,
                            derefExpr,
                            nullptr);
                    }
                    return true;
                }
            }


            // Look for an initializer/constructor declaration in the target type,
            // which is marked as usable for implicit conversion, and which takes
            // the source type as an argument.

            OverloadResolveContext overloadContext;

            overloadContext.disallowNestedConversions = true;
            overloadContext.argCount = 1;
            overloadContext.argTypes = &fromType;

            overloadContext.originalExpr = nullptr;
            if(fromExpr)
            {
                overloadContext.loc = fromExpr->loc;
                overloadContext.funcLoc = fromExpr->loc;
                overloadContext.args = &fromExpr;
            }

            overloadContext.baseExpr = nullptr;
            overloadContext.mode = OverloadResolveContext::Mode::JustTrying;

            AddTypeOverloadCandidates(toType, overloadContext, toType);

            if(overloadContext.bestCandidates.Count() != 0)
            {
                // There were multiple candidates that were equally good.

                // First, we will check if these candidates are even applicable.
                // If they aren't, then they can't be used for conversion.
                if(overloadContext.bestCandidates[0].status != OverloadCandidate::Status::Appicable)
                    return false;

                // If we reach this point, then we have multiple candidates which are
                // all equally applicable, which means we have an ambiguity.
                // If the user is just querying whether a conversion is possible, we
                // will tell them it is, because ambiguity should trigger an ambiguity
                // error, and not a "no conversion possible" error.

                // We will compute a nominal conversion cost as the minimum over
                // all the conversions available.
                ConversionCost cost = kConversionCost_GeneralConversion;
                for(auto candidate : overloadContext.bestCandidates)
                {
                    ConversionCost candidateCost = getImplicitConversionCost(
                        candidate.item.declRef.getDecl());

                    if(candidateCost < cost)
                        cost = candidateCost;
                }

                if(outCost)
                    *outCost = cost;

                if(outToExpr)
                {
                    // The user is asking for us to actually perform the conversion,
                    // so we need to generate an appropriate expression here.

                    // YONGH: I am confused why we are not hitting this case before
                    //throw "foo bar baz";
                    // YONGH: temporary work around, may need to create the actual
                    // invocation expr to the constructor call
                    *outToExpr = fromExpr;
                }

                return true;
            }
            else if(overloadContext.bestCandidate)
            {
                // There is a single best candidate for conversion.

                // It might not actually be usable, so let's check that first.
                if(overloadContext.bestCandidate->status != OverloadCandidate::Status::Appicable)
                    return false;

                // Okay, it is applicable, and we just need to let the user
                // know about it, and optionally construct a call.

                // We need to extract the conversion cost from the candidate we found.
                ConversionCost cost = getImplicitConversionCost(
                        overloadContext.bestCandidate->item.declRef.getDecl());;

                if(outCost)
                    *outCost = cost;

                if(outToExpr)
                {
                    // The logic here is a bit ugly, to deal with the fact that
                    // `CompleteOverloadCandidate` will, left to its own devices,
                    // construct a vanilla `InvokeExpr` to represent the call
                    // to the initializer we found, while we *want* it to
                    // create some variety of `ImplicitCastExpr`.
                    //
                    // Now, it just so happens that `CompleteOverloadCandidate`
                    // will use the "original" expression if one is available,
                    // so we'll create one and initialize it here.
                    // We fill in the location and arguments, but not the
                    // base expression (the callee), since that will come
                    // from the selected overload candidate.
                    //
                    auto castExpr = createImplicitCastExpr();
                    castExpr->loc = fromExpr->loc;
                    castExpr->Arguments.Add(fromExpr);
                    //
                    // Next we need to set our cast expression as the "original"
                    // expression and then complete the overload process.
                    //
                    overloadContext.originalExpr = castExpr;
                    *outToExpr = CompleteOverloadCandidate(overloadContext, *overloadContext.bestCandidate);
                    //
                    // However, the above isn't *quite* enough, because
                    // the process of completing the overload candidate
                    // might overwrite the argument list that was passed
                    // in to overload resolution, and in this case that
                    // "argument list" was just a pointer to `fromExpr`.
                    //
                    // That means we need to clear the argument list and
                    // reload it from `fromExpr` to make sure that we
                    // got the arguments *after* any transformations
                    // were applied.
                    // For right now this probably doesn't matter,
                    // because we don't allow nested implicit conversions,
                    // but I'd rather play it safe.
                    //
                    castExpr->Arguments.Clear();
                    castExpr->Arguments.Add(fromExpr);
                }

                return true;
            }

            return false;
        }

        // Check whether a type coercion is possible
        bool CanCoerce(
            RefPtr<Type>			toType,			// the target type for conversion
            RefPtr<Type>			fromType,		// the source type for the conversion
            ConversionCost*					outCost = 0)	// (optional) a place to stuff the conversion cost
        {
            BasicTypeKey key1, key2;
            BasicTypeKeyPair cacheKey;
            bool shouldAddToCache = false;
            ConversionCost cost;
            TypeCheckingCache* typeCheckingCache = getSession()->getTypeCheckingCache();
            if (key1.fromType(toType.Ptr()) && key2.fromType(fromType.Ptr()))
            {
                cacheKey.type1 = key1;
                cacheKey.type2 = key2;

                if (typeCheckingCache->conversionCostCache.TryGetValue(cacheKey, cost))
                {
                    if (outCost)
                        *outCost = cost;
                    return cost != kConversionCost_Impossible;
                }
                else
                    shouldAddToCache = true;
            }
            bool rs = TryCoerceImpl(
                toType,
                nullptr,
                fromType,
                nullptr,
                &cost);
            if (outCost)
                *outCost = cost;
            if (shouldAddToCache)
            {
                if (!rs)
                    cost = kConversionCost_Impossible;
                typeCheckingCache->conversionCostCache[cacheKey] = cost;
            }
            return rs;
        }

        RefPtr<TypeCastExpr> createImplicitCastExpr()
        {
            return new ImplicitCastExpr();
        }

        RefPtr<Expr> CreateImplicitCastExpr(
            RefPtr<Type>	toType,
            RefPtr<Expr>	fromExpr)
        {
            RefPtr<TypeCastExpr> castExpr = createImplicitCastExpr();

            auto typeType = new TypeType();
            typeType->setSession(getSession());
            typeType->type = toType;

            auto typeExpr = new SharedTypeExpr();
            typeExpr->type.type = typeType;
            typeExpr->base.type = toType;

            castExpr->loc = fromExpr->loc;
            castExpr->FunctionExpr = typeExpr;
            castExpr->type = QualType(toType);
            castExpr->Arguments.Add(fromExpr);
            return castExpr;
        }

        // Perform type coercion, and emit errors if it isn't possible
        RefPtr<Expr> Coerce(
            RefPtr<Type>			toType,
            RefPtr<Expr>	fromExpr)
        {
            RefPtr<Expr> expr;
            if (!TryCoerceImpl(
                toType,
                &expr,
                fromExpr->type.Ptr(),
                fromExpr.Ptr(),
                nullptr))
            {
                getSink()->diagnose(fromExpr->loc, Diagnostics::typeMismatch, toType, fromExpr->type);

                // Note(tfoley): We don't call `CreateErrorExpr` here, because that would
                // clobber the type on `fromExpr`, and an invariant here is that coercion
                // really shouldn't *change* the expression that is passed in, but should
                // introduce new AST nodes to coerce its value to a different type...
                return CreateImplicitCastExpr(
                    getSession()->getErrorType(),
                    fromExpr);
            }
            return expr;
        }

        void CheckVarDeclCommon(RefPtr<VarDeclBase> varDecl)
        {
            // Check the type, if one was given
            TypeExp type = CheckUsableType(varDecl->type);

            // TODO: Additional validation rules on types should go here,
            // but we need to deal with the fact that some cases might be
            // allowed in one context (e.g., an unsized array parameter)
            // but not in othters (e.g., an unsized array field in a struct).

            // Check the initializers, if one was given
            RefPtr<Expr> initExpr = CheckTerm(varDecl->initExpr);

            // If a type was given, ...
            if (type.Ptr())
            {
                // then coerce any initializer to the type
                if (initExpr)
                {
                    initExpr = Coerce(type.Ptr(), initExpr);
                }
            }
            else
            {
                // TODO: infer a type from the initializers

                if (!initExpr)
                {
                    getSink()->diagnose(varDecl, Diagnostics::unimplemented, "variable declaration with no type must have initializer");
                }
                else
                {
                    getSink()->diagnose(varDecl, Diagnostics::unimplemented, "type inference for variable declaration");
                }
            }

            varDecl->type = type;
            varDecl->initExpr = initExpr;
        }

        // Fill in default substitutions for the 'subtype' part of a type constraint decl
        void CheckConstraintSubType(TypeExp & typeExp)
        {
            if (auto sharedTypeExpr = typeExp.exp.As<SharedTypeExpr>())
            {
                if (auto declRefType = sharedTypeExpr->base->AsDeclRefType())
                {
                    declRefType->declRef.substitutions = createDefaultSubstitutions(getSession(), declRefType->declRef.getDecl());
                    if (auto typetype = typeExp.exp->type.type.As<TypeType>())
                        typetype->type = declRefType;
                }
            }
        }

        void CheckGenericConstraintDecl(GenericTypeConstraintDecl* decl)
        {
            // TODO: are there any other validations we can do at this point?
            //
            // There probably needs to be a kind of "occurs check" to make
            // sure that the constraint actually applies to at least one
            // of the parameters of the generic.
            if (decl->checkState == DeclCheckState::Unchecked)
            {
                decl->checkState = getCheckedState();
                CheckConstraintSubType(decl->sub);
                decl->sub = TranslateTypeNodeForced(decl->sub);
                decl->sup = TranslateTypeNodeForced(decl->sup);
            }
        }

        void checkDecl(Decl* decl)
        {
            EnsureDecl(decl, checkingPhase == CheckingPhase::Header ? DeclCheckState::CheckedHeader : DeclCheckState::Checked);
        }

        void checkGenericDeclHeader(GenericDecl* genericDecl)
        {
            if (genericDecl->IsChecked(DeclCheckState::CheckedHeader))
                return;
            // check the parameters
            for (auto m : genericDecl->Members)
            {
                if (auto typeParam = m.As<GenericTypeParamDecl>())
                {
                    typeParam->initType = CheckProperType(typeParam->initType);
                }
                else if (auto valParam = m.As<GenericValueParamDecl>())
                {
                    // TODO: some real checking here...
                    CheckVarDeclCommon(valParam);
                }
                else if (auto constraint = m.As<GenericTypeConstraintDecl>())
                {
                    CheckGenericConstraintDecl(constraint.Ptr());
                }
            }

            genericDecl->SetCheckState(DeclCheckState::CheckedHeader);
        }

        void visitGenericDecl(GenericDecl* genericDecl)
        {
            checkGenericDeclHeader(genericDecl);

            // check the nested declaration
            // TODO: this needs to be done in an appropriate environment...
            checkDecl(genericDecl->inner);
            genericDecl->SetCheckState(getCheckedState());
        }

        void visitGenericTypeConstraintDecl(GenericTypeConstraintDecl * genericConstraintDecl)
        {
            if (genericConstraintDecl->IsChecked(DeclCheckState::CheckedHeader))
                return;
            // check the type being inherited from
            auto base = genericConstraintDecl->sup;
            base = TranslateTypeNode(base);
            genericConstraintDecl->sup = base;
        }

        void visitInheritanceDecl(InheritanceDecl* inheritanceDecl)
        {
            if (inheritanceDecl->IsChecked(DeclCheckState::CheckedHeader))
                return;
            // check the type being inherited from
            auto base = inheritanceDecl->base;
            CheckConstraintSubType(base);
            base = TranslateTypeNode(base);
            inheritanceDecl->base = base;

            // For now we only allow inheritance from interfaces, so
            // we will validate that the type expression names an interface

            if(auto declRefType = base.type->As<DeclRefType>())
            {
                if(auto interfaceDeclRef = declRefType->declRef.As<InterfaceDecl>())
                {
                    return;
                }
            }

            // If type expression didn't name an interface, we'll emit an error here
            // TODO: deal with the case of an error in the type expression (don't cascade)
            getSink()->diagnose( base.exp, Diagnostics::expectedAnInterfaceGot, base.type);
        }

        RefPtr<ConstantIntVal> checkConstantIntVal(
            RefPtr<Expr>    expr)
        {
            // First type-check the expression as normal
            expr = CheckExpr(expr);

            auto intVal = CheckIntegerConstantExpression(expr.Ptr());
            if(!intVal)
                return nullptr;

            auto constIntVal = intVal.As<ConstantIntVal>();
            if(!constIntVal)
            {
                getSink()->diagnose(expr->loc, Diagnostics::expectedIntegerConstantNotLiteral);
                return nullptr;
            }
            return constIntVal;
        }

        // Check an expression, coerce it to the `String` type, and then
        // ensure that it has a literal (not just compile-time constant) value.
        bool checkLiteralStringVal(
            RefPtr<Expr>    expr,
            String*         outVal)
        {
            // TODO: This should actually perform semantic checking, etc.,
            // but for now we are just going to look for a direct string
            // literal AST node.

            if(auto stringLitExpr = expr.As<StringLiteralExpr>())
            {
                if(outVal)
                {
                    *outVal = stringLitExpr->value;
                }
                return true;
            }

            getSink()->diagnose(expr, Diagnostics::expectedAStringLiteral);

            return false;
        }

        void visitSyntaxDecl(SyntaxDecl*)
        {
            // These are only used in the stdlib, so no checking is needed
        }

        void visitAttributeDecl(AttributeDecl*)
        {
            // These are only used in the stdlib, so no checking is needed
        }

        void visitGenericTypeParamDecl(GenericTypeParamDecl*)
        {
            // These are only used in the stdlib, so no checking is needed for now
        }

        void visitGenericValueParamDecl(GenericValueParamDecl*)
        {
            // These are only used in the stdlib, so no checking is needed for now
        }

        void visitModifier(Modifier*)
        {
            // Do nothing with modifiers for now
        }

        AttributeDecl* lookUpAttributeDecl(Name* attributeName, Scope* scope)
        {
            // Look up the name and see what we find.
            //
            // TODO: This needs to have some special filtering or naming
            // rules to keep us from seeing shadowing variable declarations.
            auto lookupResult = lookUp(getSession(), this, attributeName, scope, LookupMask::Attribute);

            // 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 attributeDecl = dynamic_cast<AttributeDecl*>(decl) )
            {
                return attributeDecl;
            }
            else
            {
                return nullptr;
            }
        }

        Stage findStageByName(String const& name)
        {
            static const struct
            {
                char const* name;
                Stage       stage;
            } kStages[] =
            {
            #define PROFILE_STAGE(ID, NAME, ENUM) \
                { #NAME,    Stage::ID },

            #define PROFILE_STAGE_ALIAS(ID, NAME, VAL) \
                { #NAME,    Stage::ID },

            #include "profile-defs.h"
            };

            for(auto entry : kStages)
            {
                if(name == entry.name)
                {
                    return entry.stage;
                }
            }

            return Stage::Unknown;
        }

        bool hasIntArgs(Attribute* attr, int numArgs)
        {
            if (int(attr->args.Count()) != numArgs)
            {
                return false;
            }
            for (int i = 0; i < numArgs; ++i)
            {
                if (!attr->args[i]->As<IntegerLiteralExpr>())
                {
                    return false;
                }
            }
            return true;
        }

        bool hasStringArgs(Attribute* attr, int numArgs)
        {
            if (int(attr->args.Count()) != numArgs)
            {
                return false;
            }
            for (int i = 0; i < numArgs; ++i)
            {
                if (!attr->args[i]->As<StringLiteralExpr>())
                {
                    return false;
                }
            }
            return true;
        }

        bool validateAttribute(RefPtr<Attribute> attr)
        {
                if(auto numThreadsAttr = attr.As<NumThreadsAttribute>())
                {
                    SLANG_ASSERT(attr->args.Count() == 3);
                    auto xVal = checkConstantIntVal(attr->args[0]);
                    auto yVal = checkConstantIntVal(attr->args[1]);
                    auto zVal = checkConstantIntVal(attr->args[2]);

                    if(!xVal) return false;
                    if(!yVal) return false;
                    if(!zVal) return false;

                    numThreadsAttr->x          = (int32_t) xVal->value;
                    numThreadsAttr->y          = (int32_t) yVal->value;
                    numThreadsAttr->z          = (int32_t) zVal->value;
                }
                else if (auto bindingAttr = attr.As<GLSLBindingAttribute>())
                {
                    SLANG_ASSERT(attr->args.Count() == 2);
                    auto binding = checkConstantIntVal(attr->args[0]);
                    auto set = checkConstantIntVal(attr->args[1]);

                    bindingAttr->binding = int32_t(binding->value);
                    bindingAttr->set = int32_t(set->value);
                }
                else if (auto maxVertexCountAttr = attr.As<MaxVertexCountAttribute>())
                {
                    SLANG_ASSERT(attr->args.Count() == 1);
                    auto val = checkConstantIntVal(attr->args[0]);

                    if(!val) return false;

                    maxVertexCountAttr->value = (int32_t)val->value;
                }
                else if(auto instanceAttr = attr.As<InstanceAttribute>())
                {
                    SLANG_ASSERT(attr->args.Count() == 1);
                    auto val = checkConstantIntVal(attr->args[0]);

                    if(!val) return false;

                    instanceAttr->value = (int32_t)val->value;
                }
                else if(auto entryPointAttr = attr.As<EntryPointAttribute>())
                {
                    SLANG_ASSERT(attr->args.Count() == 1);

                    String stageName;
                    if(!checkLiteralStringVal(attr->args[0], &stageName))
                    {
                        return false;
                    }

                    auto stage = findStageByName(stageName);
                    if(stage == Stage::Unknown)
                    {
                        getSink()->diagnose(attr->args[0], Diagnostics::unknownStageName, stageName);
                    }

                    entryPointAttr->stage = stage;
                }
                else if ((attr.As<DomainAttribute>()) ||
                         (attr.As<MaxTessFactorAttribute>()) ||
                         (attr.As<OutputTopologyAttribute>()) ||
                         (attr.As<PartitioningAttribute>()) ||
                         (attr.As<PatchConstantFuncAttribute>()))
                {
                    // Let it go thru iff single string attribute
                    if (!hasStringArgs(attr, 1))
                    {
                        getSink()->diagnose(attr, Diagnostics::expectedSingleStringArg, attr->name);
                    }
                }
                else if (attr.As<OutputControlPointsAttribute>())
                {
                    // Let it go thru iff single integral attribute
                    if (!hasIntArgs(attr, 1))
                    {
                        getSink()->diagnose(attr, Diagnostics::expectedSingleIntArg, attr->name);
                    }
                }
                else if (attr.As<PushConstantAttribute>())
                {
                    // Has no args
                    SLANG_ASSERT(attr->args.Count() == 0);
                }
                else
                {
                    if(attr->args.Count() == 0)
                    {
                        // If the attribute took no arguments, then we will
                        // assume it is valid as written.
                    }
                    else
                    {
                        // We should be special-casing the checking of any attribute
                        // with a non-zero number of arguments.
                        SLANG_DIAGNOSE_UNEXPECTED(getSink(), attr, "unhandled attribute");
                        return false;
                    }
                }

                return true;
        }

        RefPtr<AttributeBase> checkAttribute(
            UncheckedAttribute*     uncheckedAttr,
            ModifiableSyntaxNode*   attrTarget)
        {
            auto attrName = uncheckedAttr->getName();
            auto attrDecl = lookUpAttributeDecl(
                attrName,
                uncheckedAttr->scope);

            if(!attrDecl)
            {
                getSink()->diagnose(uncheckedAttr, Diagnostics::unknownAttributeName, attrName);
                return uncheckedAttr;
            }

            if(!attrDecl->syntaxClass.isSubClassOf<Attribute>())
            {
                SLANG_DIAGNOSE_UNEXPECTED(getSink(), attrDecl, "attribute declaration does not reference an attribute class");
                return uncheckedAttr;
            }

            RefPtr<RefObject> attrObj = attrDecl->syntaxClass.createInstance();
            auto attr = attrObj.As<Attribute>();
            if(!attr)
            {
                SLANG_DIAGNOSE_UNEXPECTED(getSink(), attrDecl, "attribute class did not yield an attribute object");
                return uncheckedAttr;
            }

            // We are going to replace the unchecked attribute with the checked one.

            // First copy all of the state over from the original attribute.
            attr->name  = uncheckedAttr->name;
            attr->args  = uncheckedAttr->args;
            attr->loc   = uncheckedAttr->loc;

            // We will start with checking steps that can be applied independent
            // of the concrete attribute type that was selected. These only need
            // us to look at the attribute declaration itself.
            //
            // Start by doing argument/parameter matching
            UInt argCount = attr->args.Count();
            UInt paramCounter = 0;
            bool mismatch = false;
            for(auto paramDecl : attrDecl->getMembersOfType<ParamDecl>())
            {
                UInt paramIndex = paramCounter++;
                if( paramIndex < argCount )
                {
                    auto arg = attr->args[paramIndex];

                    // TODO: support checking the argument against the declared
                    // type for the parameter.

                }
                else
                {
                    // We didn't have enough arguments for the
                    // number of parameters declared.
                    if(auto defaultArg = paramDecl->initExpr)
                    {
                        // The attribute declaration provided a default,
                        // so we should use that.
                        //
                        // TODO: we need to figure out how to hook up
                        // default arguments as needed.
                    }
                    else
                    {
                        mismatch = true;
                    }
                }
            }
            UInt paramCount = paramCounter;

            if(mismatch)
            {
                getSink()->diagnose(attr, Diagnostics::attributeArgumentCountMismatch, attrName, paramCount, argCount);
                return uncheckedAttr;
            }

            // The next bit of validation that we can apply semi-generically
            // is to validate that the target for this attribute is a valid
            // one for the chosen attribute.
            //
            // The attribute declaration will have one or more `AttributeTargetModifier`s
            // that each specify a syntax class that the attribute can be applied to.
            // If any of these match `attrTarget`, then we are good.
            //
            bool validTarget = false;
            for(auto attrTargetMod : attrDecl->GetModifiersOfType<AttributeTargetModifier>())
            {
                if(attrTarget->getClass().isSubClassOf(attrTargetMod->syntaxClass))
                {
                    validTarget = true;
                    break;
                }
            }
            if(!validTarget)
            {
                getSink()->diagnose(attr, Diagnostics::attributeNotApplicable, attrName);
                return uncheckedAttr;
            }

            // Now apply type-specific validation to the attribute.
            if(!validateAttribute(attr))
            {
                return uncheckedAttr;
            }


            return attr;
        }

        RefPtr<Modifier> checkModifier(
            RefPtr<Modifier>        m,
            ModifiableSyntaxNode*   syntaxNode)
        {
            if(auto hlslUncheckedAttribute = m.As<UncheckedAttribute>())
            {
                // We have an HLSL `[name(arg,...)]` attribute, and we'd like
                // to check that it is provides all the expected arguments
                //
                // First, look up the attribute name in the current scope to find
                // the right syntax class to instantiate.
                //

                return checkAttribute(hlslUncheckedAttribute, syntaxNode);
            }
            // Default behavior is to leave things as they are,
            // and assume that modifiers are mostly already checked.
            //
            // TODO: This would be a good place to validate that
            // a modifier is actually valid for the thing it is
            // being applied to, and potentially to check that
            // it isn't in conflict with any other modifiers
            // on the same declaration.

            return m;
        }


        void checkModifiers(ModifiableSyntaxNode* syntaxNode)
        {
            // TODO(tfoley): need to make sure this only
            // performs semantic checks on a `SharedModifier` once...

            // The process of checking a modifier may produce a new modifier in its place,
            // so we will build up a new linked list of modifiers that will replace
            // the old list.
            RefPtr<Modifier> resultModifiers;
            RefPtr<Modifier>* resultModifierLink = &resultModifiers;

            RefPtr<Modifier> modifier = syntaxNode->modifiers.first;
            while(modifier)
            {
                // Because we are rewriting the list in place, we need to extract
                // the next modifier here (not at the end of the loop).
                auto next = modifier->next;

                // We also go ahead and clobber the `next` field on the modifier
                // itself, so that the default behavior of `checkModifier()` can
                // be to return a single unlinked modifier.
                modifier->next = nullptr;

                auto checkedModifier = checkModifier(modifier, syntaxNode);
                if(checkedModifier)
                {
                    // If checking gave us a modifier to add, then we
                    // had better add it.

                    // Just in case `checkModifier` ever returns multiple
                    // modifiers, lets advance to the end of the list we
                    // are building.
                    while(*resultModifierLink)
                        resultModifierLink = &(*resultModifierLink)->next;

                    // attach the new modifier at the end of the list,
                    // and now set the "link" to point to its `next` field
                    *resultModifierLink = checkedModifier;
                    resultModifierLink = &checkedModifier->next;
                }

                // Move along to the next modifier
                modifier = next;
            }

            // Whether we actually re-wrote anything or note, lets
            // install the new list of modifiers on the declaration
            syntaxNode->modifiers.first = resultModifiers;
        }

        void visitModuleDecl(ModuleDecl* programNode)
        {
            // Try to register all the builtin decls
            for (auto decl : programNode->Members)
            {
                auto inner = decl;
                if (auto genericDecl = decl.As<GenericDecl>())
                {
                    inner = genericDecl->inner;
                }

                if (auto builtinMod = inner->FindModifier<BuiltinTypeModifier>())
                {
                    registerBuiltinDecl(getSession(), decl, builtinMod);
                }
                if (auto magicMod = inner->FindModifier<MagicTypeModifier>())
                {
                    registerMagicDecl(getSession(), decl, magicMod);
                }
            }

            // We need/want to visit any `import` declarations before
            // anything else, to make sure that scoping works.
            for(auto& importDecl : programNode->getMembersOfType<ImportDecl>())
            {
                checkDecl(importDecl);
            }
            // register all extensions
            for (auto & s : programNode->getMembersOfType<ExtensionDecl>())
                registerExtension(s);
            for (auto & g : programNode->getMembersOfType<GenericDecl>())
            {
                if (auto extDecl = g->inner->As<ExtensionDecl>())
                {
                    checkGenericDeclHeader(g);
                    registerExtension(extDecl);
                }
            }
            // check types
            for (auto & s : programNode->getMembersOfType<TypeDefDecl>())
                checkDecl(s.Ptr());

            for (int pass = 0; pass < 2; pass++)
            {
                checkingPhase = pass == 0 ? CheckingPhase::Header : CheckingPhase::Body;

                for (auto & s : programNode->getMembersOfType<AggTypeDecl>())
                {
                    checkDecl(s.Ptr());
                }
                // HACK(tfoley): Visiting all generic declarations here,
                // because otherwise they won't get visited.
                for (auto & g : programNode->getMembersOfType<GenericDecl>())
                {
                    checkDecl(g.Ptr());
                }

                // before checking conformance, make sure we check all the extension bodies
                // generic extension decls are already checked by the loop above
                for (auto & s : programNode->getMembersOfType<ExtensionDecl>())
                    checkDecl(s);

                for (auto & func : programNode->getMembersOfType<FuncDecl>())
                {
                    if (!func->IsChecked(getCheckedState()))
                    {
                        VisitFunctionDeclaration(func.Ptr());
                    }
                }
                for (auto & func : programNode->getMembersOfType<FuncDecl>())
                {
                    checkDecl(func);
                }

                if (sink->GetErrorCount() != 0)
                    return;

                // Force everything to be fully checked, just in case
                // Note that we don't just call this on the program,
                // because we'd end up recursing into this very code path...
                for (auto d : programNode->Members)
                {
                    EnusreAllDeclsRec(d);
                }

                // Do any semantic checking required on modifiers?
                for (auto d : programNode->Members)
                {
                    checkModifiers(d.Ptr());
                }

                if (pass == 0)
                {
                    // now we can check all interface conformances
                    for (auto & s : programNode->getMembersOfType<AggTypeDecl>())
                        checkAggTypeConformance(s);
                    for (auto & s : programNode->getMembersOfType<ExtensionDecl>())
                        checkExtensionConformance(s);
                    for (auto & g : programNode->getMembersOfType<GenericDecl>())
                    {
                        if (auto innerAggDecl = g->inner->As<AggTypeDecl>())
                            checkAggTypeConformance(innerAggDecl);
                        else if (auto innerExtDecl = g->inner->As<ExtensionDecl>())
                            checkExtensionConformance(innerExtDecl);
                    }
                }
            }
        }

        void visitStructField(StructField* field)
        {
            if (field->IsChecked(DeclCheckState::CheckedHeader))
                return;
            // TODO: bottleneck through general-case variable checking

            field->type = CheckUsableType(field->type);
            field->SetCheckState(getCheckedState());
        }

        bool doesSignatureMatchRequirement(
            DeclRef<CallableDecl>   satisfyingMemberDeclRef,
            DeclRef<CallableDecl>   requiredMemberDeclRef,
            RefPtr<WitnessTable>    witnessTable)
        {
            // TODO: actually implement matching here. For now we'll
            // just pretend that things are satisfied in order to make progress..
            witnessTable->requirementDictionary.Add(
                requiredMemberDeclRef.getDecl(),
                RequirementWitness(satisfyingMemberDeclRef));
            return true;
        }

        bool doesGenericSignatureMatchRequirement(
            DeclRef<GenericDecl>        genDecl,
            DeclRef<GenericDecl>        requirementGenDecl,
            RefPtr<WitnessTable>        witnessTable)
        {
            if (genDecl.getDecl()->Members.Count() != requirementGenDecl.getDecl()->Members.Count())
                return false;
            for (UInt i = 0; i < genDecl.getDecl()->Members.Count(); i++)
            {
                auto genMbr = genDecl.getDecl()->Members[i];
                auto requiredGenMbr = genDecl.getDecl()->Members[i];
                if (auto genTypeMbr = genMbr.As<GenericTypeParamDecl>())
                {
                    if (auto requiredGenTypeMbr = requiredGenMbr.As<GenericTypeParamDecl>())
                    {
                    }
                    else
                        return false;
                }
                else if (auto genValMbr = genMbr.As<GenericValueParamDecl>())
                {
                    if (auto requiredGenValMbr = requiredGenMbr.As<GenericValueParamDecl>())
                    {
                        if (!genValMbr->type->Equals(requiredGenValMbr->type))
                            return false;
                    }
                    else
                        return false;
                }
                else if (auto genTypeConstraintMbr = genMbr.As<GenericTypeConstraintDecl>())
                {
                    if (auto requiredTypeConstraintMbr = requiredGenMbr.As<GenericTypeConstraintDecl>())
                    {
                        if (!genTypeConstraintMbr->sup->Equals(requiredTypeConstraintMbr->sup))
                        {
                            return false;
                        }
                    }
                    else
                        return false;
                }
            }

            // TODO: this isn't right, because we need to specialize the
            // declarations of the generics to a common set of substitutions,
            // so that their types are comparable (e.g., foo<T> and foo<U>
            // need to have substutition applies so that they are both foo<X>,
            // after which uses of the type X in their parameter lists can
            // be compared).

            return doesMemberSatisfyRequirement(
                DeclRef<Decl>(genDecl.getDecl()->inner.Ptr(), genDecl.substitutions),
                DeclRef<Decl>(requirementGenDecl.getDecl()->inner.Ptr(), requirementGenDecl.substitutions),
                witnessTable);
        }

        bool doesTypeSatisfyAssociatedTypeRequirement(
            RefPtr<Type>            satisfyingType,
            DeclRef<AssocTypeDecl>  requiredAssociatedTypeDeclRef,
            RefPtr<WitnessTable>    witnessTable)
        {
            // We need to confirm that the chosen type `satisfyingType`,
            // meets all the constraints placed on the associated type
            // requirement `requiredAssociatedTypeDeclRef`.
            //
            // We will enumerate the type constraints placed on the
            // associated type and see if they can be satisfied.
            //
            bool conformance = true;
            for (auto requiredConstraintDeclRef : getMembersOfType<TypeConstraintDecl>(requiredAssociatedTypeDeclRef))
            {
                // Grab the type we expect to conform to from the constraint.
                auto requiredSuperType = GetSup(requiredConstraintDeclRef);

                // Perform a search for a witness to the subtype relationship.
                auto witness = tryGetSubtypeWitness(satisfyingType, requiredSuperType);
                if(witness)
                {
                    // If a subtype witness was found, then the conformance
                    // appears to hold, and we can satisfy that requirement.
                    witnessTable->requirementDictionary.Add(requiredConstraintDeclRef, RequirementWitness(witness));
                }
                else
                {
                    // If a witness couldn't be found, then the conformance
                    // seems like it will fail.
                    conformance = false;
                }
            }

            // TODO: if any conformance check failed, we should probably include
            // that in an error message produced about not satisfying the requirement.

            if(conformance)
            {
                // If all the constraints were satsified, then the chosen
                // type can indeed satisfy the interface requirement.
                witnessTable->requirementDictionary.Add(
                    requiredAssociatedTypeDeclRef.getDecl(),
                    RequirementWitness(satisfyingType));
            }

            return conformance;
        }

        // Does the given `memberDecl` work as an implementation
        // to satisfy the requirement `requiredMemberDeclRef`
        // from an interface?
        //
        // If it does, then inserts a witness into `witnessTable`
        // and returns `true`, otherwise returns `false`
        bool doesMemberSatisfyRequirement(
            DeclRef<Decl>               memberDeclRef,
            DeclRef<Decl>               requiredMemberDeclRef,
            RefPtr<WitnessTable>        witnessTable)
        {
            // At a high level, we want to check that the
            // `memberDecl` and the `requiredMemberDeclRef`
            // have the same AST node class, and then also
            // check that their signatures match.
            //
            // There are a bunch of detailed decisions that
            // have to be made, though, because we might, e.g.,
            // allow a function with more general parameter
            // types to satisfy a requirement with more
            // specific parameter types.
            //
            // If we ever allow for "property" declarations,
            // then we would probably need to allow an
            // ordinary field to satisfy a property requirement.
            //
            // An associated type requirement should be allowed
            // to be satisfied by any type declaration:
            // a typedef, a `struct`, etc.
            //
            if (auto memberFuncDecl = memberDeclRef.As<FuncDecl>())
            {
                if (auto requiredFuncDeclRef = requiredMemberDeclRef.As<FuncDecl>())
                {
                    // Check signature match.
                    return doesSignatureMatchRequirement(
                        memberFuncDecl,
                        requiredFuncDeclRef,
                        witnessTable);
                }
            }
            else if (auto memberInitDecl = memberDeclRef.As<ConstructorDecl>())
            {
                if (auto requiredInitDecl = requiredMemberDeclRef.As<ConstructorDecl>())
                {
                    // Check signature match.
                    return doesSignatureMatchRequirement(
                        memberInitDecl,
                        requiredInitDecl,
                        witnessTable);
                }
            }
            else if (auto genDecl = memberDeclRef.As<GenericDecl>())
            {
                // For a generic member, we will check if it can satisfy
                // a generic requirement in the interface.
                //
                // TODO: we could also conceivably check that the generic
                // could be *specialized* to satisfy the requirement,
                // and then install a specialization of the generic into
                // the witness table. Actually doing this would seem
                // to require performing something akin to overload
                // resolution as part of requirement satisfaction.
                //
                if (auto requiredGenDeclRef = requiredMemberDeclRef.As<GenericDecl>())
                {
                    return doesGenericSignatureMatchRequirement(genDecl, requiredGenDeclRef, witnessTable);
                }
            }
            else if (auto subAggTypeDeclRef = memberDeclRef.As<AggTypeDecl>())
            {
                if(auto requiredTypeDeclRef = requiredMemberDeclRef.As<AssocTypeDecl>())
                {
                    checkDecl(subAggTypeDeclRef.getDecl());

                    auto satisfyingType = DeclRefType::Create(getSession(), subAggTypeDeclRef);
                    return doesTypeSatisfyAssociatedTypeRequirement(satisfyingType, requiredTypeDeclRef, witnessTable);
                }
            }
            else if (auto typedefDeclRef = memberDeclRef.As<TypeDefDecl>())
            {
                // this is a type-def decl in an aggregate type
                // check if the specified type satisfies the constraints defined by the associated type
                if (auto requiredTypeDeclRef = requiredMemberDeclRef.As<AssocTypeDecl>())
                {
                    checkDecl(typedefDeclRef.getDecl());

                    auto satisfyingType = getNamedType(getSession(), typedefDeclRef);
                    return doesTypeSatisfyAssociatedTypeRequirement(satisfyingType, requiredTypeDeclRef, witnessTable);
                }
            }
            // Default: just assume that thing aren't being satisfied.
            return false;
        }

        // State used while checking if a declaration (either a type declaration
        // or an extension of that type) conforms to the interfaces it claims
        // via its inheritance clauses.
        //
        struct ConformanceCheckingContext
        {
            Dictionary<DeclRef<InterfaceDecl>, RefPtr<WitnessTable>>    mapInterfaceToWitnessTable;
        };

        // Find the appropriate member of a declared type to
        // satisfy a requirement of an interface the type
        // claims to conform to.
        //
        // The type declaration `typeDecl` has declared that it
        // conforms to the interface `interfaceDeclRef`, and
        // `requiredMemberDeclRef` is a required member of
        // the interface.
        //
        // If a satisfying value is found, registers it in
        // `witnessTable` and returns `true`, otherwise
        // returns `false`.
        //
        bool findWitnessForInterfaceRequirement(
            ConformanceCheckingContext* context,
            DeclRef<AggTypeDeclBase>    typeDeclRef,
            InheritanceDecl*            inheritanceDecl,
            DeclRef<InterfaceDecl>      interfaceDeclRef,
            DeclRef<Decl>               requiredMemberDeclRef,
            RefPtr<WitnessTable>        witnessTable)
        {
            // The goal of this function is to find a suitable
            // value to satisfy the requirement.
            //
            // The 99% case is that the requirement is a named member
            // of the interface, and we need to search for a member
            // with the same name in the type declaration and
            // its (known) extensions.

            // As a first pass, lets check if we already have a
            // witness in the table for the requirement, so
            // that we can bail out early.
            //
            if(witnessTable->requirementDictionary.ContainsKey(requiredMemberDeclRef.getDecl()))
            {
                return true;
            }


            // An important exception to the above is that an
            // inheritance declaration in the interface is not going
            // to be satisfied by an inheritance declaration in the
            // conforming type, but rather by a full "witness table"
            // full of the satisfying values for each requirement
            // in the inherited-from interface.
            //
            if( auto requiredInheritanceDeclRef = requiredMemberDeclRef.As<InheritanceDecl>() )
            {
                // Recursively check that the type conforms
                // to the inherited interface.
                //
                // TODO: we *really* need a linearization step here!!!!

                RefPtr<WitnessTable> satisfyingWitnessTable = checkConformanceToType(
                    context,
                    typeDeclRef,
                    requiredInheritanceDeclRef.getDecl(),
                    getBaseType(requiredInheritanceDeclRef));

                if(!satisfyingWitnessTable)
                    return false;

                witnessTable->requirementDictionary.Add(
                    requiredInheritanceDeclRef.getDecl(),
                    RequirementWitness(satisfyingWitnessTable));
                return true;
            }

            // We will look up members with the same name,
            // since only same-name members will be able to
            // satisfy the requirement.
            //
            // TODO: this won't work right now for members that
            // don't have names, which right now includes
            // initializers/constructors.
            Name* name = requiredMemberDeclRef.GetName();

            // We are basically looking up members of the
            // given type, but we need to be a bit careful.
            // We *cannot* perfom lookup "through" inheritance
            // declarations for this or other interfaces,
            // since that would let us satisfy a requirement
            // with itself.
            //
            // There's also an interesting question of whether
            // we can/should support innterface requirements
            // being satisfied via `__transparent` members.
            // This seems like a "clever" idea rather than
            // a useful one, and IR generation would
            // need to construct real IR to trampoline over
            // to the implementation.
            //
            // The final case that can't be reduced to just
            // "a directly declared member with the same name"
            // is the case where the type inherits a member
            // that can satisfy the requirement from a base type.
            // We are ignoring implementation inheritance for
            // now, so we won't worry about this.

            // Make sure that by-name lookup is possible.
            buildMemberDictionary(typeDeclRef.getDecl());
            auto lookupResult = lookUpLocal(getSession(), this, name, typeDeclRef);

            if (!lookupResult.isValid())
            {
                getSink()->diagnose(inheritanceDecl, Diagnostics::typeDoesntImplementInterfaceRequirement, typeDeclRef, requiredMemberDeclRef);
                return false;
            }

            // Iterate over the members and look for one that matches
            // the expected signature for the requirement.
            for (auto member : lookupResult)
            {
                if (doesMemberSatisfyRequirement(member.declRef, requiredMemberDeclRef, witnessTable))
                    return true;
            }

            // No suitable member found, although there were candidates.
            //
            // TODO: Eventually we might want something akin to the current
            // overload resolution logic, where we keep track of a list
            // of "candidates" for satisfaction of the requirement,
            // and if nothing is found we print the candidates

            getSink()->diagnose(inheritanceDecl, Diagnostics::typeDoesntImplementInterfaceRequirement, typeDeclRef, requiredMemberDeclRef);
            return false;
        }

        // Check that the type declaration `typeDecl`, which
        // declares conformance to the interface `interfaceDeclRef`,
        // (via the given `inheritanceDecl`) actually provides
        // members to satisfy all the requirements in the interface.
        RefPtr<WitnessTable> checkInterfaceConformance(
            ConformanceCheckingContext* context,
            DeclRef<AggTypeDeclBase>    typeDeclRef,
            InheritanceDecl*            inheritanceDecl,
            DeclRef<InterfaceDecl>      interfaceDeclRef)
        {
            // Has somebody already checked this conformance,
            // and/or is in the middle of checking it?
            RefPtr<WitnessTable> witnessTable;
            if(context->mapInterfaceToWitnessTable.TryGetValue(interfaceDeclRef, witnessTable))
                return witnessTable;

            // We need to check the declaration of the interface
            // before we can check that we conform to it.
            checkDecl(interfaceDeclRef.getDecl());

            // We will construct the witness table, and register it
            // *before* we go about checking fine-grained requirements,
            // in order to short-circuit any potential for infinite recursion.

            // Note: we will re-use the witnes table attached to the inheritance decl,
            // if there is one. This catches cases where semantic checking might
            // have synthesized some of the conformance witnesses for us.
            //
            witnessTable = inheritanceDecl->witnessTable;
            if(!witnessTable)
            {
                witnessTable = new WitnessTable();
            }
            context->mapInterfaceToWitnessTable.Add(interfaceDeclRef, witnessTable);

            bool result = true;

            // TODO: If we ever allow for implementation inheritance,
            // then we will need to consider the case where a type
            // declares that it conforms to an interface, but one of
            // its (non-interface) base types already conforms to
            // that interface, so that all of the requirements are
            // already satisfied with inherited implementations...
            for(auto requiredMemberDeclRef : getMembers(interfaceDeclRef))
            {
                auto requirementSatisfied = findWitnessForInterfaceRequirement(
                    context,
                    typeDeclRef,
                    inheritanceDecl,
                    interfaceDeclRef,
                    requiredMemberDeclRef,
                    witnessTable);

                result = result && requirementSatisfied;
            }

            // Extensions that apply to the interface type can create new conformances
            // for the concrete types that inherit from the interface.
            //
            // These new conformances should not be able to introduce new *requirements*
            // for an implementing interface (although they currently can), but we
            // still need to go through this logic to find the appropriate value
            // that will satisfy the requirement in these cases, and also to put
            // the required entry into the witness table for the interface itself.
            //
            // TODO: This logic is a bit slippery, and we need to figure out what
            // it means in the context of separate compilation. If module A defines
            // an interface IA, module B defines a type C that conforms to IA, and then
            // module C defines an extension that makes IA conform to IC, then it is
            // unreasonable to expect the {B:IA} witness table to contain an entry
            // corresponding to {IA:IC}.
            //
            // The simple answer then would be that the {IA:IC} conformance should be
            // fixed, with a single witness table for {IA:IC}, but then what should
            // happen in B explicitly conformed to IC already?
            //
            // For now we will just walk through the extensions that are known at
            // the time we are compiling and handle those, and punt on the larger issue
            // for abit longer.
            for(auto candidateExt = interfaceDeclRef.getDecl()->candidateExtensions; candidateExt; candidateExt = candidateExt->nextCandidateExtension)
            {
                // We need to apply the extension to the interface type that our
                // concrete type is inheriting from.
                //
                // TODO: need to decide if a this-type substitution is needed here.
                // It probably it.
                RefPtr<Type> targetType = DeclRefType::Create(
                    getSession(),
                    interfaceDeclRef);
                auto extDeclRef = ApplyExtensionToType(candidateExt, targetType);
                if(!extDeclRef)
                    continue;

                // Only inheritance clauses from the extension matter right now.
                for(auto requiredInheritanceDeclRef : getMembersOfType<InheritanceDecl>(extDeclRef))
                {
                    auto requirementSatisfied = findWitnessForInterfaceRequirement(
                        context,
                        typeDeclRef,
                        inheritanceDecl,
                        interfaceDeclRef,
                        requiredInheritanceDeclRef,
                        witnessTable);

                    result = result && requirementSatisfied;
                }
            }

            // If we failed to satisfy any requirements along the way,
            // then we don't actually want to keep the witness table
            // we've been constructing, because the whole thing was a failure.
            if(!result)
            {
                return nullptr;
            }

            return witnessTable;
        }

        RefPtr<WitnessTable> checkConformanceToType(
            ConformanceCheckingContext* context,
            DeclRef<AggTypeDeclBase>    typeDeclRef,
            InheritanceDecl*            inheritanceDecl,
            Type*                       baseType)
        {
            if (auto baseDeclRefType = baseType->As<DeclRefType>())
            {
                auto baseTypeDeclRef = baseDeclRefType->declRef;
                if (auto baseInterfaceDeclRef = baseTypeDeclRef.As<InterfaceDecl>())
                {
                    // The type is stating that it conforms to an interface.
                    // We need to check that it provides all of the members
                    // required by that interface.
                    return checkInterfaceConformance(
                        context,
                        typeDeclRef,
                        inheritanceDecl,
                        baseInterfaceDeclRef);
                }
            }

            getSink()->diagnose(inheritanceDecl, Diagnostics::unimplemented, "type not supported for inheritance");
            return nullptr;
        }

        // Check that the type (or extension) declaration `declRef`,
        // which declares that it inherits from another type via
        // `inheritanceDecl` actually does what it needs to
        // for that inheritance to be valid.
        bool checkConformance(
            DeclRef<AggTypeDeclBase>    declRef,
            InheritanceDecl*            inheritanceDecl)
        {
            declRef = createDefaultSubstitutionsIfNeeded(getSession(), declRef).As<AggTypeDeclBase>();

            // Don't check conformances for abstract types that
            // are being used to express *required* conformances.
            if (auto assocTypeDeclRef = declRef.As<AssocTypeDecl>())
            {
                // An associated type declaration represents a requirement
                // in an outer interface declaration, and its members
                // (type constraints) represent additional requirements.
                return true;
            }
            else if (auto interfaceDeclRef = declRef.As<InterfaceDecl>())
            {
                // HACK: Our semantics as they stand today are that an
                // `extension` of an interface that adds a new inheritance
                // clause acts *as if* that inheritnace clause had been
                // attached to the original `interface` decl: that is,
                // it adds additional requirements.
                //
                // This is *not* a reasonable semantic to keep long-term,
                // but it is required for some of our current example
                // code to work.
                return true;
            }


            // Look at the type being inherited from, and validate
            // appropriately.
            auto baseType = inheritanceDecl->base.type;

            ConformanceCheckingContext context;
            RefPtr<WitnessTable> witnessTable = checkConformanceToType(&context, declRef, inheritanceDecl, baseType);
            if(!witnessTable)
                return false;

            inheritanceDecl->witnessTable = witnessTable;
            return true;
        }

        void checkExtensionConformance(ExtensionDecl* decl)
        {
            if (auto targetDeclRefType = decl->targetType->As<DeclRefType>())
            {
                if (auto aggTypeDeclRef = targetDeclRefType->declRef.As<AggTypeDecl>())
                {
                    for (auto inheritanceDecl : decl->getMembersOfType<InheritanceDecl>())
                    {
                        checkConformance(aggTypeDeclRef, inheritanceDecl);
                    }
                }
            }
        }

        void checkAggTypeConformance(AggTypeDecl* decl)
        {
            // After we've checked members, we need to go through
            // any inheritance clauses on the type itself, and
            // confirm that the type actually provides whatever
            // those clauses require.

            if (auto interfaceDecl = dynamic_cast<InterfaceDecl*>(decl))
            {
                // Don't check that an interface conforms to the
                // things it inherits from.
            }
            else if (auto assocTypeDecl = dynamic_cast<AssocTypeDecl*>(decl))
            {
                // Don't check that an associated type decl conforms to the
                // things it inherits from.
            }
            else
            {
                // For non-interface types we need to check conformance.
                //
                // TODO: Need to figure out what this should do for
                // `abstract` types if we ever add them. Should they
                // be required to implement all interface requirements,
                // just with `abstract` methods that replicate things?
                // (That's what C# does).
                for (auto inheritanceDecl : decl->getMembersOfType<InheritanceDecl>())
                {
                    checkConformance(makeDeclRef(decl), inheritanceDecl);
                }
            }
        }

        void visitAggTypeDecl(AggTypeDecl* decl)
        {
            if (decl->IsChecked(getCheckedState()))
                return;

            // TODO: we should check inheritance declarations
            // first, since they need to be validated before
            // we can make use of the type (e.g., you need
            // to know that `A` inherits from `B` in order
            // to check an expression like `aValue.bMethod()`
            // where `aValue` is of type `A` but `bMethod`
            // is defined in type `B`.
            //
            // TODO: We should also add a pass that takes
            // all the stated inheritance relationships,
            // expands them to include implicitic inheritance,
            // and then linearizes them. This would allow
            // later passes that need to know everything
            // a type inherits from to proceed linearly
            // through the list, rather than having to
            // recurse (and potentially see the same interface
            // more than once).

            decl->SetCheckState(DeclCheckState::CheckedHeader);

            // Now check all of the member declarations.
            for (auto member : decl->Members)
            {
                checkDecl(member);
            }
            decl->SetCheckState(getCheckedState());
        }

        // Validate that `type` is a suitable type to use
        // as the tag type for an `enum`
        void validateEnumTagType(Type* type, SourceLoc const& loc)
        {
            if(auto basicType = type->As<BasicExpressionType>())
            {
                switch(basicType->baseType)
                {
                default:
                    // By default, don't allow a type to be used
                    // as an `enum` tag type.
                    break;

                case BaseType::Int:
                case BaseType::UInt:
                case BaseType::UInt64:
                    // These are all allowed.
                    return;
                }
            }

            getSink()->diagnose(loc, Diagnostics::invalidEnumTagType, type);
        }

        void visitEnumDecl(EnumDecl* decl)
        {
            if (decl->IsChecked(getCheckedState()))
                return;

            // Look at inheritance clauses, and
            // see if one of them is making the enum
            // "inherit" from a concrete type.
            // This will become the "tag" type
            // of the enum.
            RefPtr<Type>        tagType;
            InheritanceDecl*    tagTypeInheritanceDecl = nullptr;
            for(auto inheritanceDecl : decl->getMembersOfType<InheritanceDecl>())
            {
                checkDecl(inheritanceDecl);

                // Look at the type being inherited from.
                auto superType = inheritanceDecl->base.type;

                if(auto errorType = superType->As<ErrorType>())
                {
                    // Ignore any erroneous inheritance clauses.
                    continue;
                }
                else if(auto declRefType = superType->As<DeclRefType>())
                {
                    if(auto interfaceDeclRef = declRefType->declRef.As<InterfaceDecl>())
                    {
                        // Don't consider interface bases as candidates for
                        // the tag type.
                        continue;
                    }
                }

                if(tagType)
                {
                    // We already found a tag type.
                    getSink()->diagnose(inheritanceDecl, Diagnostics::enumTypeAlreadyHasTagType);
                    getSink()->diagnose(tagTypeInheritanceDecl, Diagnostics::seePreviousTagType);
                    break;
                }
                else
                {
                    tagType = superType;
                    tagTypeInheritanceDecl = inheritanceDecl;
                }
            }

            // If a tag type has not been set, then we
            // default it to the built-in `int` type.
            //
            // TODO: In the far-flung future we may want to distinguish
            // `enum` types that have a "raw representation" like this from
            // ones that are purely abstract and don't expose their
            // type of their tag.
            if(!tagType)
            {
                tagType = getSession()->getIntType();
            }
            else
            {
                // TODO: Need to establish that the tag
                // type is suitable. (e.g., if we are going
                // to allow raw values for case tags to be
                // derived automatically, then the tag
                // type needs to be some kind of interer type...)
                //
                // For now we will just be harsh and require it
                // to be one of a few builtin types.
                validateEnumTagType(tagType, tagTypeInheritanceDecl->loc);
            }
            decl->tagType = tagType;


            // An `enum` type should automatically conform to the `__EnumType` interface.
            // The compiler needs to insert this conformance behind the scenes, and this
            // seems like the best place to do it.
            {
                // First, look up the type of the `__EnumType` interface.
                RefPtr<Type> enumTypeType = getSession()->getEnumTypeType();

                RefPtr<InheritanceDecl> enumConformanceDecl = new InheritanceDecl();
                enumConformanceDecl->ParentDecl = decl;
                enumConformanceDecl->loc = decl->loc;
                enumConformanceDecl->base.type = getSession()->getEnumTypeType();
                decl->Members.Add(enumConformanceDecl);

                // The `__EnumType` interface has one required member, the `__Tag` type.
                // We need to satisfy this requirement automatically, rather than require
                // the user to actually declare a member with this name (otherwise we wouldn't
                // let them define a tag value with the name `__Tag`).
                //
                RefPtr<WitnessTable> witnessTable = new WitnessTable();
                enumConformanceDecl->witnessTable = witnessTable;

                Name* tagAssociatedTypeName = getSession()->getNameObj("__Tag");
                Decl* tagAssociatedTypeDecl = nullptr;
                if(auto enumTypeTypeDeclRefType = enumTypeType.As<DeclRefType>())
                {
                    if(auto enumTypeTypeInterfaceDecl = enumTypeTypeDeclRefType->declRef.getDecl()->As<InterfaceDecl>())
                    {
                        for(auto memberDecl : enumTypeTypeInterfaceDecl->Members)
                        {
                            if(memberDecl->getName() == tagAssociatedTypeName)
                            {
                                tagAssociatedTypeDecl = memberDecl;
                                break;
                            }
                        }
                    }
                }
                if(!tagAssociatedTypeDecl)
                {
                    SLANG_DIAGNOSE_UNEXPECTED(getSink(), decl, "failed to find built-in declaration '__Tag'");
                }

                // Okay, add the conformance withess for `__Tag` being satisfied by `tagType`
                witnessTable->requirementDictionary.Add(tagAssociatedTypeDecl, RequirementWitness(tagType));

                // TODO: we actually also need to synthesize a witness for the conformance of `tagType`
                // to the `__BuiltinIntegerType` interface, because that is a constraint on the
                // associated type `__Tag`.

                // TODO: eventually we should consider synthesizing other requirements for
                // the min/max tag values, or the total number of tags, so that people don't
                // have to declare these as additional cases.

                enumConformanceDecl->SetCheckState(DeclCheckState::Checked);
            }


            decl->SetCheckState(DeclCheckState::CheckedHeader);

            auto enumType = DeclRefType::Create(
                getSession(),
                makeDeclRef(decl));

            // Check the enum cases in order.
            for(auto caseDecl : decl->getMembersOfType<EnumCaseDecl>())
            {
                // Each case defines a value of the enum's type.
                //
                // TODO: If we ever support enum cases with payloads,
                // then they would probably have a type that is a
                // `FunctionType` from the payload types to the
                // enum type.
                //
                caseDecl->type.type = enumType;

                checkDecl(caseDecl);
            }

            // For any enum case that didn't provide an explicit
            // tag value, derived an appropriate tag value.
            IntegerLiteralValue defaultTag = 0;
            for(auto caseDecl : decl->getMembersOfType<EnumCaseDecl>())
            {
                if(auto explicitTagValExpr = caseDecl->initExpr)
                {
                    // This tag has an initializer, so it should establish
                    // the tag value for a successor case that doesn't
                    // provide an explicit tag.

                    RefPtr<IntVal> explicitTagVal = TryConstantFoldExpr(explicitTagValExpr);
                    if(explicitTagVal)
                    {
                        if(auto constIntVal = explicitTagVal.As<ConstantIntVal>())
                        {
                            defaultTag = constIntVal->value;
                        }
                        else
                        {
                            // TODO: need to handle other possibilities here
                            getSink()->diagnose(explicitTagValExpr, Diagnostics::unexpectedEnumTagExpr);
                        }
                    }
                    else
                    {
                        // If this happens, then the explicit tag value expression
                        // doesn't seem to be a constant after all. In this case
                        // we expect the checking logic to have applied already.
                    }
                }
                else
                {
                    // This tag has no initializer, so it should use
                    // the default tag value we are tracking.
                    RefPtr<IntegerLiteralExpr> tagValExpr = new IntegerLiteralExpr();
                    tagValExpr->loc = caseDecl->loc;
                    tagValExpr->type = QualType(tagType);
                    tagValExpr->value = defaultTag;

                    caseDecl->initExpr = tagValExpr;
                }

                // Default tag for the next case will be one more than
                // for the most recent case.
                //
                // TODO: We might consider adding a `[flags]` attribute
                // that modifies this behavior to be `defaultTagForCase <<= 1`.
                //
                defaultTag++;
            }

            // Now check any other member declarations.
            for(auto memberDecl : decl->Members)
            {
                // Already checked inheritance declarations above.
                if(auto inheritanceDecl = memberDecl->As<InheritanceDecl>())
                    continue;

                // Already checked enum case declarations above.
                if(auto caseDecl = memberDecl->As<EnumCaseDecl>())
                    continue;

                // TODO: Right now we don't support other kinds of
                // member declarations on an `enum`, but that is
                // something we may want to allow in the long run.
                //
                checkDecl(memberDecl);
            }
            decl->SetCheckState(getCheckedState());
        }

        void visitEnumCaseDecl(EnumCaseDecl* decl)
        {
            if (decl->IsChecked(getCheckedState()))
                return;

            // An enum case had better appear inside an enum!
            //
            // TODO: Do we need/want to support generic cases some day?
            auto parentEnumDecl = decl->ParentDecl->As<EnumDecl>();
            SLANG_ASSERT(parentEnumDecl);

            // The tag type should have already been set by
            // the surrounding `enum` declaration.
            auto tagType = parentEnumDecl->tagType;
            SLANG_ASSERT(tagType);

            // Need to check the init expression, if present, since
            // that represents the explicit tag for this case.
            if(auto initExpr = decl->initExpr)
            {
                initExpr = CheckExpr(initExpr);
                initExpr = Coerce(tagType, initExpr);

                // We want to enforce that this is an integer constant
                // expression, but we don't actually care to retain
                // the value.
                CheckIntegerConstantExpression(initExpr);

                decl->initExpr = initExpr;
            }
            decl->SetCheckState(getCheckedState());
        }

        void visitDeclGroup(DeclGroup* declGroup)
        {
            for (auto decl : declGroup->decls)
            {
                dispatchDecl(decl);
            }
        }

        void visitTypeDefDecl(TypeDefDecl* decl)
        {
            if (decl->IsChecked(getCheckedState())) return;
            if (checkingPhase == CheckingPhase::Header)
            {
                decl->type = CheckProperType(decl->type);
            }
            decl->SetCheckState(getCheckedState());
        }

        void visitGlobalGenericParamDecl(GlobalGenericParamDecl * decl)
        {
            if (decl->IsChecked(getCheckedState())) return;
            if (checkingPhase == CheckingPhase::Header)
            {
                decl->SetCheckState(DeclCheckState::CheckedHeader);
                // global generic param only allowed in global scope
                auto program = decl->ParentDecl->As<ModuleDecl>();
                if (!program)
                    getSink()->diagnose(decl, Slang::Diagnostics::globalGenParamInGlobalScopeOnly);
                // Now check all of the member declarations.
                for (auto member : decl->Members)
                {
                    checkDecl(member);
                }
            }
            decl->SetCheckState(getCheckedState());
        }

        void visitAssocTypeDecl(AssocTypeDecl* decl)
        {
            if (decl->IsChecked(getCheckedState())) return;
            if (checkingPhase == CheckingPhase::Header)
            {
                decl->SetCheckState(DeclCheckState::CheckedHeader);

                // assoctype only allowed in an interface
                auto interfaceDecl = decl->ParentDecl->As<InterfaceDecl>();
                if (!interfaceDecl)
                    getSink()->diagnose(decl, Slang::Diagnostics::assocTypeInInterfaceOnly);

                // Now check all of the member declarations.
                for (auto member : decl->Members)
                {
                    checkDecl(member);
                }
            }
            decl->SetCheckState(getCheckedState());
        }

        void checkStmt(Stmt* stmt)
        {
            if (!stmt) return;
            dispatchStmt(stmt);
            checkModifiers(stmt);
        }

        void visitFuncDecl(FuncDecl *functionNode)
        {
            if (functionNode->IsChecked(getCheckedState()))
                return;

            if (checkingPhase == CheckingPhase::Header)
            {
                VisitFunctionDeclaration(functionNode);
            }
            // TODO: This should really only set "checked header"
            functionNode->SetCheckState(getCheckedState());

            if (checkingPhase == CheckingPhase::Body)
            {
                // TODO: should put the checking of the body onto a "work list"
                // to avoid recursion here.
                if (functionNode->Body)
                {
                    auto oldFunc = function;
                    this->function = functionNode;
                    checkStmt(functionNode->Body);
                    this->function = oldFunc;
                }
            }
        }

        void getGenericParams(
            GenericDecl*                        decl,
            List<Decl*>&                        outParams,
            List<GenericTypeConstraintDecl*>    outConstraints)
        {
            for (auto dd : decl->Members)
            {
                if (dd == decl->inner)
                    continue;

                if (auto typeParamDecl = dd.As<GenericTypeParamDecl>())
                    outParams.Add(typeParamDecl);
                else if (auto valueParamDecl = dd.As<GenericValueParamDecl>())
                    outParams.Add(valueParamDecl);
                else if (auto constraintDecl = dd.As<GenericTypeConstraintDecl>())
                    outConstraints.Add(constraintDecl);
            }
        }

        bool doGenericSignaturesMatch(
            GenericDecl*    fst,
            GenericDecl*    snd)
        {
            // First we'll extract the parameters and constraints
            // in each generic signature. We will consider parameters
            // and constraints separately so that we are independent
            // of the order in which constraints are given (that is,
            // a constraint like `<T : IFoo>` whould be considered
            // the same as `<T>` with a later `where T : IFoo`.

            List<Decl*> fstParams;
            List<GenericTypeConstraintDecl*> fstConstraints;
            getGenericParams(fst, fstParams, fstConstraints);

            List<Decl*> sndParams;
            List<GenericTypeConstraintDecl*> sndConstraints;
            getGenericParams(snd, sndParams, sndConstraints);

            // For there to be any hope of a match, the
            // two need to have the same number of parameters.
            UInt paramCount = fstParams.Count();
            if (paramCount != sndParams.Count())
                return false;

            // Now we'll walk through the parameters.
            for (UInt pp = 0; pp < paramCount; ++pp)
            {
                Decl* fstParam = fstParams[pp];
                Decl* sndParam = sndParams[pp];

                if (auto fstTypeParam = dynamic_cast<GenericTypeParamDecl*>(fstParam))
                {
                    if (auto sndTypeParam = dynamic_cast<GenericTypeParamDecl*>(sndParam))
                    {
                        // TODO: is there any validation that needs to be peformed here?
                    }
                    else
                    {
                        // Type and non-type parameters can't match.
                        return false;
                    }
                }
                else if (auto fstValueParam = dynamic_cast<GenericValueParamDecl*>(fstParam))
                {
                    if (auto sndValueParam = dynamic_cast<GenericValueParamDecl*>(sndParam))
                    {
                        // Need to check that the parameters have the same type.
                        //
                        // Note: We are assuming here that the type of a value
                        // parameter cannot be dependent on any of the type
                        // parameters in the same signature. This is a reasonable
                        // assumption for now, but could get thorny down the road.
                        if (!fstValueParam->getType()->Equals(sndValueParam->getType()))
                        {
                            // Type mismatch.
                            return false;
                        }

                        // TODO: This is not the right place to check on default
                        // values for the parameter, because they won't affect
                        // the signature, but we should make sure to do validation
                        // later on (e.g., that only one declaration can/should
                        // be allowed to provide a default).
                    }
                    else
                    {
                        // Value and non-value parameters can't match.
                        return false;
                    }
                }
            }

            // If we got this far, then it means the parameter signatures *seem*
            // to match up all right, but now we need to check that the constraints
            // placed on those parameters are also consistent.
            //
            // For now I'm going to assume/require that all declarations must
            // declare the signature in a way that matches exactly.
            UInt constraintCount = fstConstraints.Count();
            if(constraintCount != sndConstraints.Count())
                return false;

            for (UInt cc = 0; cc < constraintCount; ++cc)
            {
                //auto fstConstraint = fstConstraints[cc];
                //auto sndConstraint = sndConstraints[cc];

                // TODO: the challenge here is that the
                // constraints are going to be expressed
                // in terms of the parameters, which means
                // we need to be doing substitution here.
            }

            // HACK: okay, we'll just assume things match for now.
            return true;
        }

        // Check if two functions have the same signature for the purposes
        // of overload resolution.
        bool doFunctionSignaturesMatch(
            DeclRef<FuncDecl> fst,
            DeclRef<FuncDecl> snd)
        {

            // TODO(tfoley): This copies the parameter array, which is bad for performance.
            auto fstParams = GetParameters(fst).ToArray();
            auto sndParams = GetParameters(snd).ToArray();

            // If the functions have different numbers of parameters, then
            // their signatures trivially don't match.
            auto fstParamCount = fstParams.Count();
            auto sndParamCount = sndParams.Count();
            if (fstParamCount != sndParamCount)
                return false;

            for (UInt ii = 0; ii < fstParamCount; ++ii)
            {
                auto fstParam = fstParams[ii];
                auto sndParam = sndParams[ii];

                // If a given parameter type doesn't match, then signatures don't match
                if (!GetType(fstParam)->Equals(GetType(sndParam)))
                    return false;

                // If one parameter is `out` and the other isn't, then they don't match
                //
                // Note(tfoley): we don't consider `out` and `inout` as distinct here,
                // because there is no way for overload resolution to pick between them.
                if (fstParam.getDecl()->HasModifier<OutModifier>() != sndParam.getDecl()->HasModifier<OutModifier>())
                    return false;

                // If one parameter is `ref` and the other isn't, then they don't match.
                //
                if(fstParam.getDecl()->HasModifier<RefModifier>() != sndParam.getDecl()->HasModifier<RefModifier>())
                    return false;
            }

            // Note(tfoley): return type doesn't enter into it, because we can't take
            // calling context into account during overload resolution.

            return true;
        }

        RefPtr<GenericSubstitution> createDummySubstitutions(
            GenericDecl* genericDecl)
        {
            RefPtr<GenericSubstitution> subst = new GenericSubstitution();
            subst->genericDecl = genericDecl;
            for (auto dd : genericDecl->Members)
            {
                if (dd == genericDecl->inner)
                    continue;

                if (auto typeParam = dd.As<GenericTypeParamDecl>())
                {
                    auto type = DeclRefType::Create(getSession(),
                        makeDeclRef(typeParam.Ptr()));
                    subst->args.Add(type);
                }
                else if (auto valueParam = dd.As<GenericValueParamDecl>())
                {
                    auto val = new GenericParamIntVal(
                        makeDeclRef(valueParam.Ptr()));
                    subst->args.Add(val);
                }
                // TODO: need to handle constraints here?
            }
            return subst;
        }

        void ValidateFunctionRedeclaration(FuncDecl* funcDecl)
        {
            auto parentDecl = funcDecl->ParentDecl;
            SLANG_ASSERT(parentDecl);
            if (!parentDecl) return;

            Decl* childDecl = funcDecl;

            // If this is a generic function (that is, its parent
            // declaration is a generic), then we need to look
            // for sibling declarations of the parent.
            auto genericDecl = dynamic_cast<GenericDecl*>(parentDecl);
            if (genericDecl)
            {
                parentDecl = genericDecl->ParentDecl;
                childDecl = genericDecl;
            }

            // Look at previously-declared functions with the same name,
            // in the same container
            //
            // Note: there is an assumption here that declarations that
            // occur earlier in the program  text will be *later* in
            // the linked list of declarations with the same name.
            // We are also assuming/requiring that the check here is
            // symmetric, in that it is okay to test (A,B) or (B,A),
            // and there is no need to test both.
            //
            buildMemberDictionary(parentDecl);
            for (auto pp = childDecl->nextInContainerWithSameName; pp; pp = pp->nextInContainerWithSameName)
            {
                auto prevDecl = pp;

                // Look through generics to the declaration underneath
                auto prevGenericDecl = dynamic_cast<GenericDecl*>(prevDecl);
                if (prevGenericDecl)
                    prevDecl = prevGenericDecl->inner.Ptr();

                // We only care about previously-declared functions
                // Note(tfoley): although we should really error out if the
                // name is already in use for something else, like a variable...
                auto prevFuncDecl = dynamic_cast<FuncDecl*>(prevDecl);
                if (!prevFuncDecl)
                    continue;

                // If one declaration is a prefix/postfix operator, and the
                // other is not a matching operator, then don't consider these
                // to be redeclarations.
                //
                // Note(tfoley): Any attempt to call such an operator using
                // ordinary function-call syntax (if we decided to allow it)
                // would be ambiguous in such a case, of course.
                //
                if (funcDecl->HasModifier<PrefixModifier>() != prevDecl->HasModifier<PrefixModifier>())
                    continue;
                if (funcDecl->HasModifier<PostfixModifier>() != prevDecl->HasModifier<PostfixModifier>())
                    continue;

                // If one is generic and the other isn't, then there is no match.
                if ((genericDecl != nullptr) != (prevGenericDecl != nullptr))
                    continue;

                // We are going to be comparing the signatures of the
                // two functions, but if they are *generic* functions
                // then we will need to compare them with consistent
                // specializations in place.
                //
                // We'll go ahead and create some (unspecialized) declaration
                // references here, just to be prepared.
                DeclRef<FuncDecl> funcDeclRef(funcDecl, nullptr);
                DeclRef<FuncDecl> prevFuncDeclRef(prevFuncDecl, nullptr);

                // If we are working with generic functions, then we need to
                // consider if their generic signatures match.
                if (genericDecl)
                {
                    SLANG_ASSERT(prevGenericDecl); // already checked above
                    if (!doGenericSignaturesMatch(genericDecl, prevGenericDecl))
                        continue;

                    // Now we need specialize the declaration references
                    // consistently, so that we can compare.
                    //
                    // First we create a "dummy" set of substitutions that
                    // just reference the parameters of the first generic.
                    auto subst = createDummySubstitutions(genericDecl);
                    //
                    // Then we use those parameters to specialize the *other*
                    // generic.
                    //
                    subst->genericDecl = prevGenericDecl;
                    prevFuncDeclRef.substitutions.substitutions = subst;
                    //
                    // One way to think about it is that if we have these
                    // declarations (ignore the name differences...):
                    //
                    //     // prevFuncDecl:
                    //     void foo1<T>(T x);
                    //
                    //     // funcDecl:
                    //     void foo2<U>(U x);
                    //
                    // Then we will compare `foo2` against `foo1<U>`.
                }

                // If the parameter signatures don't match, then don't worry
                if (!doFunctionSignaturesMatch(funcDeclRef, prevFuncDeclRef))
                    continue;

                // If we get this far, then we've got two declarations in the same
                // scope, with the same name and signature, so they appear
                // to be redeclarations.
                //
                // We will track that redeclaration occured, so that we can
                // take it into account for overload resolution.
                //
                // A huge complication that we'll need to deal with is that
                // multiple declarations might introduce default values for
                // (different) parameters, and we might need to merge across
                // all of them (which could get complicated if defaults for
                // parameters can reference earlier parameters).

                // If the previous declaration wasn't already recorded
                // as being part of a redeclaration family, then make
                // it the primary declaration of a new family.
                if (!prevFuncDecl->primaryDecl)
                {
                    prevFuncDecl->primaryDecl = prevFuncDecl;
                }

                // The new declaration will belong to the family of
                // the previous one, and so it will share the same
                // primary declaration.
                funcDecl->primaryDecl = prevFuncDecl->primaryDecl;
                funcDecl->nextDecl = nullptr;

                // Next we want to chain the new declaration onto
                // the linked list of redeclarations.
                auto link = &prevFuncDecl->nextDecl;
                while (*link)
                    link = &(*link)->nextDecl;
                *link = funcDecl;

                // Now that we've added things to a group of redeclarations,
                // we can do some additional validation.

                // First, we will ensure that the return types match
                // between the declarations, so that they are truly
                // interchangeable.
                //
                // Note(tfoley): If we ever decide to add a beefier type
                // system to Slang, we might allow overloads like this,
                // so long as the desired result type can be disambiguated
                // based on context at the call type. In that case we would
                // consider result types earlier, as part of the signature
                // matching step.
                //
                auto resultType = GetResultType(funcDeclRef);
                auto prevResultType = GetResultType(prevFuncDeclRef);
                if (!resultType->Equals(prevResultType))
                {
                    // Bad redeclaration
                    getSink()->diagnose(funcDecl, Diagnostics::functionRedeclarationWithDifferentReturnType, funcDecl->getName(), resultType, prevResultType);
                    getSink()->diagnose(prevFuncDecl, Diagnostics::seePreviousDeclarationOf, funcDecl->getName());

                    // Don't bother emitting other errors at this point
                    break;
                }

                // Note(tfoley): several of the following checks should
                // really be looping over all the previous declarations
                // in the same group, and not just the one previous
                // declaration we found just now.

                // TODO: Enforce that the new declaration had better
                // not specify a default value for any parameter that
                // already had a default value in a prior declaration.

                // We are going to want to enforce that we cannot have
                // two declarations of a function both specify bodies.
                // Before we make that check, however, we need to deal
                // with the case where the two function declarations
                // might represent different target-specific versions
                // of a function.
                //
                // TODO: if the two declarations are specialized for
                // different targets, then skip the body checks below.

                // If both of the declarations have a body, then there
                // is trouble, because we wouldn't know which one to
                // use during code generation.
                if (funcDecl->Body && prevFuncDecl->Body)
                {
                    // Redefinition
                    getSink()->diagnose(funcDecl, Diagnostics::functionRedefinition, funcDecl->getName());
                    getSink()->diagnose(prevFuncDecl, Diagnostics::seePreviousDefinitionOf, funcDecl->getName());

                    // Don't bother emitting other errors
                    break;
                }

                // At this point we've processed the redeclaration and
                // put it into a group, so there is no reason to keep
                // looping and looking at prior declarations.
                return;
            }
        }

        void visitScopeDecl(ScopeDecl*)
        {
            // Nothing to do
        }

        void visitParamDecl(ParamDecl* paramDecl)
        {
            // TODO: This logic should be shared with the other cases of
            // variable declarations. The main reason I am not doing it
            // yet is that we use a `ParamDecl` with a null type as a
            // special case in attribute declarations, and that could
            // trip up the ordinary variable checks.

            auto typeExpr = paramDecl->type;
            if(typeExpr.exp)
            {
                typeExpr = CheckUsableType(typeExpr);
                paramDecl->type = typeExpr;
            }

            paramDecl->SetCheckState(DeclCheckState::CheckedHeader);

            // The "initializer" expression for a parameter represents
            // a default argument value to use if an explicit one is
            // not supplied.
            if(auto initExpr = paramDecl->initExpr)
            {
                // We must check the expression and coerce it to the
                // actual type of the parameter.
                //
                initExpr = CheckExpr(initExpr);
                initExpr = Coerce(typeExpr.type, initExpr);
                paramDecl->initExpr = initExpr;

                // TODO: a default argument expression needs to
                // conform to other constraints to be valid.
                // For example, it should not be allowed to refer
                // to other parameters of the same function (or maybe
                // only the parameters to its left...).
            }

            paramDecl->SetCheckState(DeclCheckState::Checked);
        }

        void VisitFunctionDeclaration(FuncDecl *functionNode)
        {
            if (functionNode->IsChecked(DeclCheckState::CheckedHeader)) return;
            functionNode->SetCheckState(DeclCheckState::CheckingHeader);
            auto oldFunc = this->function;
            this->function = functionNode;
            auto returnType = CheckProperType(functionNode->ReturnType);
            functionNode->ReturnType = returnType;
            HashSet<Name*> paraNames;
            for (auto & para : functionNode->GetParameters())
            {
                EnsureDecl(para, DeclCheckState::CheckedHeader);

                if (paraNames.Contains(para->getName()))
                {
                    getSink()->diagnose(para, Diagnostics::parameterAlreadyDefined, para->getName());
                }
                else
                    paraNames.Add(para->getName());
            }
            this->function = oldFunc;
            functionNode->SetCheckState(DeclCheckState::CheckedHeader);

            // One last bit of validation: check if we are redeclaring an existing function
            ValidateFunctionRedeclaration(functionNode);
        }

        void visitDeclStmt(DeclStmt* stmt)
        {
            // We directly dispatch here instead of using `EnsureDecl()` for two
            // reasons:
            //
            // 1. We expect that a local declaration won't have been referenced
            // before it is declared, so that we can just check things in-order
            //
            // 2. `EnsureDecl()` is specialized for `Decl*` instead of `DeclBase*`
            // and trying to special case `DeclGroup*` here feels silly.
            //
            dispatchDecl(stmt->decl);
        }

        void visitBlockStmt(BlockStmt* stmt)
        {
            checkStmt(stmt->body);
        }

        void visitSeqStmt(SeqStmt* stmt)
        {
            for(auto ss : stmt->stmts)
            {
                checkStmt(ss);
            }
        }

        template<typename T>
        T* FindOuterStmt()
        {
            UInt outerStmtCount = outerStmts.Count();
            for (UInt ii = outerStmtCount; ii > 0; --ii)
            {
                auto outerStmt = outerStmts[ii-1];
                auto found = dynamic_cast<T*>(outerStmt);
                if (found)
                    return found;
            }
            return nullptr;
        }

        void visitBreakStmt(BreakStmt *stmt)
        {
            auto outer = FindOuterStmt<BreakableStmt>();
            if (!outer)
            {
                getSink()->diagnose(stmt, Diagnostics::breakOutsideLoop);
            }
            stmt->parentStmt = outer;
        }
        void visitContinueStmt(ContinueStmt *stmt)
        {
            auto outer = FindOuterStmt<LoopStmt>();
            if (!outer)
            {
                getSink()->diagnose(stmt, Diagnostics::continueOutsideLoop);
            }
            stmt->parentStmt = outer;
        }

        void PushOuterStmt(Stmt* stmt)
        {
            outerStmts.Add(stmt);
        }

        void PopOuterStmt(Stmt* /*stmt*/)
        {
            outerStmts.RemoveAt(outerStmts.Count() - 1);
        }

        RefPtr<Expr> checkPredicateExpr(Expr* expr)
        {
            RefPtr<Expr> e = expr;
            e = CheckTerm(e);
            e = Coerce(getSession()->getBoolType(), e);
            return e;
        }

        void visitDoWhileStmt(DoWhileStmt *stmt)
        {
            PushOuterStmt(stmt);
            stmt->Predicate = checkPredicateExpr(stmt->Predicate);
            checkStmt(stmt->Statement);

            PopOuterStmt(stmt);
        }
        void visitForStmt(ForStmt *stmt)
        {
            PushOuterStmt(stmt);
            checkStmt(stmt->InitialStatement);
            if (stmt->PredicateExpression)
            {
                stmt->PredicateExpression = checkPredicateExpr(stmt->PredicateExpression);
            }
            if (stmt->SideEffectExpression)
            {
                stmt->SideEffectExpression = CheckExpr(stmt->SideEffectExpression);
            }
            checkStmt(stmt->Statement);

            PopOuterStmt(stmt);
        }

        RefPtr<Expr> checkExpressionAndExpectIntegerConstant(RefPtr<Expr> expr, RefPtr<IntVal>* outIntVal)
        {
            expr = CheckExpr(expr);
            auto intVal = CheckIntegerConstantExpression(expr);
            if (outIntVal)
                *outIntVal = intVal;
            return expr;
        }

        void visitCompileTimeForStmt(CompileTimeForStmt* stmt)
        {
            PushOuterStmt(stmt);

            stmt->varDecl->type.type = getSession()->getIntType();
            addModifier(stmt->varDecl, new ConstModifier());
            stmt->varDecl->SetCheckState(DeclCheckState::Checked);

            RefPtr<IntVal> rangeBeginVal;
            RefPtr<IntVal> rangeEndVal;

            if (stmt->rangeBeginExpr)
            {
                stmt->rangeBeginExpr = checkExpressionAndExpectIntegerConstant(stmt->rangeBeginExpr, &rangeBeginVal);
            }
            else
            {
                RefPtr<ConstantIntVal> rangeBeginConst = new ConstantIntVal();
                rangeBeginConst->value = 0;
                rangeBeginVal = rangeBeginConst;
            }

            stmt->rangeEndExpr = checkExpressionAndExpectIntegerConstant(stmt->rangeEndExpr, &rangeEndVal);

            stmt->rangeBeginVal = rangeBeginVal;
            stmt->rangeEndVal = rangeEndVal;

            checkStmt(stmt->body);


            PopOuterStmt(stmt);
        }

        void visitSwitchStmt(SwitchStmt* stmt)
        {
            PushOuterStmt(stmt);
            // TODO(tfoley): need to coerce condition to an integral type...
            stmt->condition = CheckExpr(stmt->condition);
            checkStmt(stmt->body);

            // TODO(tfoley): need to check that all case tags are unique

            // TODO(tfoley): check that there is at most one `default` clause

            PopOuterStmt(stmt);
        }
        void visitCaseStmt(CaseStmt* stmt)
        {
            // TODO(tfoley): Need to coerce to type being switch on,
            // and ensure that value is a compile-time constant
            auto expr = CheckExpr(stmt->expr);
            auto switchStmt = FindOuterStmt<SwitchStmt>();

            if (!switchStmt)
            {
                getSink()->diagnose(stmt, Diagnostics::caseOutsideSwitch);
            }
            else
            {
                // TODO: need to do some basic matching to ensure the type
                // for the `case` is consistent with the type for the `switch`...
            }

            stmt->expr = expr;
            stmt->parentStmt = switchStmt;
        }
        void visitDefaultStmt(DefaultStmt* stmt)
        {
            auto switchStmt = FindOuterStmt<SwitchStmt>();
            if (!switchStmt)
            {
                getSink()->diagnose(stmt, Diagnostics::defaultOutsideSwitch);
            }
            stmt->parentStmt = switchStmt;
        }
        void visitIfStmt(IfStmt *stmt)
        {
            stmt->Predicate = checkPredicateExpr(stmt->Predicate);
            checkStmt(stmt->PositiveStatement);
            checkStmt(stmt->NegativeStatement);
        }

        void visitUnparsedStmt(UnparsedStmt*)
        {
            // Nothing to do
        }

        void visitEmptyStmt(EmptyStmt*)
        {
            // Nothing to do
        }

        void visitDiscardStmt(DiscardStmt*)
        {
            // Nothing to do
        }

        void visitReturnStmt(ReturnStmt *stmt)
        {
            if (!stmt->Expression)
            {
                if (function && !function->ReturnType.Equals(getSession()->getVoidType()))
                {
                    getSink()->diagnose(stmt, Diagnostics::returnNeedsExpression);
                }
            }
            else
            {
                stmt->Expression = CheckTerm(stmt->Expression);
                if (!stmt->Expression->type->Equals(getSession()->getErrorType()))
                {
                    if (function)
                    {
                        stmt->Expression = Coerce(function->ReturnType.Ptr(), stmt->Expression);
                    }
                    else
                    {
                        // TODO(tfoley): this case currently gets triggered for member functions,
                        // which aren't being checked consistently (because of the whole symbol
                        // table idea getting in the way).

//							getSink()->diagnose(stmt, Diagnostics::unimplemented, "case for return stmt");
                    }
                }
            }
        }

        IntegerLiteralValue GetMinBound(RefPtr<IntVal> val)
        {
            if (auto constantVal = val.As<ConstantIntVal>())
                return constantVal->value;

            // TODO(tfoley): Need to track intervals so that this isn't just a lie...
            return 1;
        }

        void maybeInferArraySizeForVariable(Variable* varDecl)
        {
            // Not an array?
            auto arrayType = varDecl->type->AsArrayType();
            if (!arrayType) return;

            // Explicit element count given?
            auto elementCount = arrayType->ArrayLength;
            if (elementCount) return;

            // No initializer?
            auto initExpr = varDecl->initExpr;
            if(!initExpr) return;

            // Is the initializer an initializer list?
            if(auto initializerListExpr = initExpr.As<InitializerListExpr>())
            {
                auto argCount = initializerListExpr->args.Count();
                elementCount = new ConstantIntVal(argCount);
            }
            // Is the type of the initializer an array type?
            else if(auto arrayInitType = initExpr->type->As<ArrayExpressionType>())
            {
                elementCount = arrayInitType->ArrayLength;
            }
            else
            {
                // Nothing to do: we couldn't infer a size
                return;
            }

            // Create a new array type based on the size we found,
            // and install it into our type.
            varDecl->type.type = getArrayType(
                arrayType->baseType,
                elementCount);
        }

        void ValidateArraySizeForVariable(Variable* varDecl)
        {
            auto arrayType = varDecl->type->AsArrayType();
            if (!arrayType) return;

            auto elementCount = arrayType->ArrayLength;
            if (!elementCount)
            {
                // Note(tfoley): For now we allow arrays of unspecified size
                // everywhere, because some source languages (e.g., GLSL)
                // allow them in specific cases.
#if 0
                getSink()->diagnose(varDecl, Diagnostics::invalidArraySize);
#endif
                return;
            }

            // TODO(tfoley): How to handle the case where bound isn't known?
            if (GetMinBound(elementCount) <= 0)
            {
                getSink()->diagnose(varDecl, Diagnostics::invalidArraySize);
                return;
            }
        }

        void visitVariable(Variable* varDecl)
        {
            if (function || checkingPhase == CheckingPhase::Header)
            {
                TypeExp typeExp = CheckUsableType(varDecl->type);
#if 0
                if (typeExp.type->GetBindableResourceType() != BindableResourceType::NonBindable)
                {
                    // We don't want to allow bindable resource types as local variables (at least for now).
                    auto parentDecl = varDecl->ParentDecl;
                    if (auto parentScopeDecl = dynamic_cast<ScopeDecl*>(parentDecl))
                    {
                        getSink()->diagnose(varDecl->type, Diagnostics::invalidTypeForLocalVariable);
                    }
                }
#endif
                varDecl->type = typeExp;
                if (varDecl->type.Equals(getSession()->getVoidType()))
                {
                    getSink()->diagnose(varDecl, Diagnostics::invalidTypeVoid);
                }
            }

            if (checkingPhase == CheckingPhase::Body)
            {
                if (auto initExpr = varDecl->initExpr)
                {
                    initExpr = CheckTerm(initExpr);
                    varDecl->initExpr = initExpr;
                }

                // If this is an array variable, then we first want to give
                // it a chance to infer an array size from its initializer
                //
                // TODO(tfoley): May need to extend this to handle the
                // multi-dimensional case...
                maybeInferArraySizeForVariable(varDecl);
                //
                // Next we want to make sure that the declared (or inferred)
                // size for the array meets whatever language-specific
                // constraints we want to enforce (e.g., disallow empty
                // arrays in specific cases)
                ValidateArraySizeForVariable(varDecl);


                if (auto initExpr = varDecl->initExpr)
                {
                    // TODO(tfoley): should coercion of initializer lists be special-cased
                    // here, or handled as a general case for coercion?

                    initExpr = Coerce(varDecl->type.Ptr(), initExpr);
                    varDecl->initExpr = initExpr;
                }
            }
            varDecl->SetCheckState(getCheckedState());
        }

        void visitWhileStmt(WhileStmt *stmt)
        {
            PushOuterStmt(stmt);
            stmt->Predicate = checkPredicateExpr(stmt->Predicate);
            checkStmt(stmt->Statement);
            PopOuterStmt(stmt);
        }
        void visitExpressionStmt(ExpressionStmt *stmt)
        {
            stmt->Expression = CheckExpr(stmt->Expression);
        }

        RefPtr<Expr> visitBoolLiteralExpr(BoolLiteralExpr* expr)
        {
            expr->type = getSession()->getBoolType();
            return expr;
        }

        RefPtr<Expr> visitIntegerLiteralExpr(IntegerLiteralExpr* expr)
        {
            // The expression might already have a type, determined by its suffix.
            // It it doesn't, we will give it a default type.
            //
            // TODO: We should be careful to pick a "big enough" type
            // based on the size of the value (e.g., don't try to stuff
            // a constant in an `int` if it requires 64 or more bits).
            //
            // The long-term solution here is to give a type to a literal
            // based on the context where it is used, but that requires
            // a more sophisticated type system than we have today.
            //
            if(!expr->type.type)
            {
                expr->type = getSession()->getIntType();
            }
            return expr;
        }

        RefPtr<Expr> visitFloatingPointLiteralExpr(FloatingPointLiteralExpr* expr)
        {
            if(!expr->type.type)
            {
                expr->type = getSession()->getFloatType();
            }
            return expr;
        }

        RefPtr<Expr> visitStringLiteralExpr(StringLiteralExpr* expr)
        {
            expr->type = getSession()->getStringType();
            return expr;
        }

        IntVal* GetIntVal(IntegerLiteralExpr* expr)
        {
            // TODO(tfoley): don't keep allocating here!
            return new ConstantIntVal(expr->value);
        }

        Name* getName(String const& text)
        {
            return getCompileRequest()->getNamePool()->getName(text);
        }

        RefPtr<IntVal> TryConstantFoldExpr(
            InvokeExpr* invokeExpr)
        {
            // We need all the operands to the expression

            // Check if the callee is an operation that is amenable to constant-folding.
            //
            // For right now we will look for calls to intrinsic functions, and then inspect
            // their names (this is bad and slow).
            auto funcDeclRefExpr = invokeExpr->FunctionExpr.As<DeclRefExpr>();
            if (!funcDeclRefExpr) return nullptr;

            auto funcDeclRef = funcDeclRefExpr->declRef;
            auto intrinsicMod = funcDeclRef.getDecl()->FindModifier<IntrinsicOpModifier>();
            if (!intrinsicMod)
            {
                // We can't constant fold anything that doesn't map to a builtin
                // operation right now.
                //
                // TODO: we should really allow constant-folding for anything
                // that can be lowerd to our bytecode...
                return nullptr;
            }



            // Let's not constant-fold operations with more than a certain number of arguments, for simplicity
            static const int kMaxArgs = 8;
            if (invokeExpr->Arguments.Count() > kMaxArgs)
                return nullptr;

            // Before checking the operation name, let's look at the arguments
            RefPtr<IntVal> argVals[kMaxArgs];
            IntegerLiteralValue constArgVals[kMaxArgs];
            int argCount = 0;
            bool allConst = true;
            for (auto argExpr : invokeExpr->Arguments)
            {
                auto argVal = TryCheckIntegerConstantExpression(argExpr.Ptr());
                if (!argVal)
                    return nullptr;

                argVals[argCount] = argVal;

                if (auto constArgVal = argVal.As<ConstantIntVal>())
                {
                    constArgVals[argCount] = constArgVal->value;
                }
                else
                {
                    allConst = false;
                }
                argCount++;
            }

            if (!allConst)
            {
                // TODO(tfoley): We probably want to support a very limited number of operations
                // on "constants" that aren't actually known, to be able to handle a generic
                // that takes an integer `N` but then constructs a vector of size `N+1`.
                //
                // The hard part there is implementing the rules for value unification in the
                // presence of more complicated `IntVal` subclasses, like `SumIntVal`. You'd
                // need inference to be smart enough to know that `2 + N` and `N + 2` are the
                // same value, as are `N + M + 1 + 1` and `M + 2 + N`.
                //
                // For now we can just bail in this case.
                return nullptr;
            }

            // At this point, all the operands had simple integer values, so we are golden.
            IntegerLiteralValue resultValue = 0;
            auto opName = funcDeclRef.GetName();

            // handle binary operators
            if (opName == getName("-"))
            {
                if (argCount == 1)
                {
                    resultValue = -constArgVals[0];
                }
                else if (argCount == 2)
                {
                    resultValue = constArgVals[0] - constArgVals[1];
                }
            }

            // simple binary operators
#define CASE(OP)                                                    \
            else if(opName == getName(#OP)) do {                    \
                if(argCount != 2) return nullptr;                   \
                resultValue = constArgVals[0] OP constArgVals[1];   \
            } while(0)

            CASE(+); // TODO: this can also be unary...
            CASE(*);
#undef CASE

            // binary operators with chance of divide-by-zero
            // TODO: issue a suitable error in that case
#define CASE(OP)                                                    \
            else if(opName == getName(#OP)) do {                    \
                if(argCount != 2) return nullptr;                   \
                if(!constArgVals[1]) return nullptr;                \
                resultValue = constArgVals[0] OP constArgVals[1];   \
            } while(0)

            CASE(/);
            CASE(%);
#undef CASE

            // TODO(tfoley): more cases
            else
            {
                return nullptr;
            }

            RefPtr<IntVal> result = new ConstantIntVal(resultValue);
            return result;
        }

        RefPtr<IntVal> TryConstantFoldExpr(
            Expr* expr)
        {
            // Unwrap any "identity" expressions
            while (auto parenExpr = dynamic_cast<ParenExpr*>(expr))
            {
                expr = parenExpr->base;
            }

            // TODO(tfoley): more serious constant folding here
            if (auto intLitExpr = dynamic_cast<IntegerLiteralExpr*>(expr))
            {
                return GetIntVal(intLitExpr);
            }

            // it is possible that we are referring to a generic value param
            if (auto declRefExpr = dynamic_cast<DeclRefExpr*>(expr))
            {
                auto declRef = declRefExpr->declRef;

                if (auto genericValParamRef = declRef.As<GenericValueParamDecl>())
                {
                    // TODO(tfoley): handle the case of non-`int` value parameters...
                    return new GenericParamIntVal(genericValParamRef);
                }

                // We may also need to check for references to variables that
                // are defined in a way that can be used as a constant expression:
                if(auto varRef = declRef.As<VarDeclBase>())
                {
                    auto varDecl = varRef.getDecl();

                    switch(getSourceLanguage())
                    {
                    default:
                    case SourceLanguage::Slang:
                    case SourceLanguage::HLSL:
                        // HLSL: `static const` is used to mark compile-time constant expressions
                        if(auto staticAttr = varDecl->FindModifier<HLSLStaticModifier>())
                        {
                            if(auto constAttr = varDecl->FindModifier<ConstModifier>())
                            {
                                // HLSL `static const` can be used as a constant expression
                                if(auto initExpr = getInitExpr(varRef))
                                {
                                    return TryConstantFoldExpr(initExpr.Ptr());
                                }
                            }
                        }
                        break;

                    case SourceLanguage::GLSL:
                        // GLSL: `const` indicates compile-time constant expression
                        //
                        // TODO(tfoley): The current logic here isn't robust against
                        // GLSL "specialization constants" - we will extract the
                        // initializer for a `const` variable and use it to extract
                        // a value, when we really should be using an opaque
                        // reference to the variable.
                        if(auto constAttr = varDecl->FindModifier<ConstModifier>())
                        {
                            // We need to handle a "specialization constant" (with a `constant_id` layout modifier)
                            // differently from an ordinary compile-time constant. The latter can/should be reduced
                            // to a value, while the former should be kept as a symbolic reference

                            if(auto constantIDModifier = varDecl->FindModifier<GLSLConstantIDLayoutModifier>())
                            {
                                // Retain the specialization constant as a symbolic reference
                                //
                                // TODO(tfoley): handle the case of non-`int` value parameters...
                                //
                                // TODO(tfoley): this is cloned from the case above that handles generic value parameters
                                return new GenericParamIntVal(varRef);
                            }
                            else if(auto initExpr = getInitExpr(varRef))
                            {
                                // This is an ordinary constant, and not a specialization constant, so we
                                // can try to fold its value right now.
                                return TryConstantFoldExpr(initExpr.Ptr());
                            }
                        }
                        break;
                    }

                }
            }

            if(auto castExpr = dynamic_cast<TypeCastExpr*>(expr))
            {
                auto val = TryConstantFoldExpr(castExpr->Arguments[0].Ptr());
                if(val)
                    return val;
            }
            else if (auto invokeExpr = dynamic_cast<InvokeExpr*>(expr))
            {
                auto val = TryConstantFoldExpr(invokeExpr);
                if (val)
                    return val;
            }

            return nullptr;
        }

        // Try to check an integer constant expression, either returning the value,
        // or NULL if the expression isn't recognized as a constant.
        RefPtr<IntVal> TryCheckIntegerConstantExpression(Expr* exp)
        {
            // Check if type is acceptable for an integer constant expression
            if(auto basicType = exp->type.type->As<BasicExpressionType>())
            {
                switch(basicType->baseType)
                {
                default:
                    return nullptr;

                case BaseType::Int:
                case BaseType::UInt:
                case BaseType::UInt64:
                    break;
                }
            }
            else
            {
                return nullptr;
            }

            // Consider operations that we might be able to constant-fold...
            return TryConstantFoldExpr(exp);
        }

        // Enforce that an expression resolves to an integer constant, and get its value
        RefPtr<IntVal> CheckIntegerConstantExpression(Expr* inExpr)
        {
            // No need to issue further errors if the expression didn't even type-check.
            if(IsErrorExpr(inExpr)) return nullptr;

            // First coerce the expression to the expected type
            auto expr = Coerce(getSession()->getIntType(),inExpr);

            // No need to issue further errors if the type coercion failed.
            if(IsErrorExpr(expr)) return nullptr;

            auto result = TryCheckIntegerConstantExpression(expr.Ptr());
            if (!result)
            {
                getSink()->diagnose(expr, Diagnostics::expectedIntegerConstantNotConstant);
            }
            return result;
        }



        RefPtr<Expr> CheckSimpleSubscriptExpr(
            RefPtr<IndexExpr>   subscriptExpr,
            RefPtr<Type>              elementType)
        {
            auto baseExpr = subscriptExpr->BaseExpression;
            auto indexExpr = subscriptExpr->IndexExpression;

            if (!indexExpr->type->Equals(getSession()->getIntType()) &&
                !indexExpr->type->Equals(getSession()->getUIntType()))
            {
                getSink()->diagnose(indexExpr, Diagnostics::subscriptIndexNonInteger);
                return CreateErrorExpr(subscriptExpr.Ptr());
            }

            subscriptExpr->type = QualType(elementType);

            // TODO(tfoley): need to be more careful about this stuff
            subscriptExpr->type.IsLeftValue = baseExpr->type.IsLeftValue;

            return subscriptExpr;
        }

        // The way that we have designed out type system, pretyt much *every*
        // type is a reference to some declaration in the standard library.
        // That means that when we construct a new type on the fly, we need
        // to make sure that it is wired up to reference the appropriate
        // declaration, or else it won't compare as equal to other types
        // that *do* reference the declaration.
        //
        // This function is used to construct a `vector<T,N>` type
        // programmatically, so that it will work just like a type of
        // that form constructed by the user.
        RefPtr<VectorExpressionType> createVectorType(
            RefPtr<Type>  elementType,
            RefPtr<IntVal>          elementCount)
        {
            auto session = getSession();
            auto vectorGenericDecl = findMagicDecl(
                session, "Vector").As<GenericDecl>();
            auto vectorTypeDecl = vectorGenericDecl->inner;

            auto substitutions = new GenericSubstitution();
            substitutions->genericDecl = vectorGenericDecl.Ptr();
            substitutions->args.Add(elementType);
            substitutions->args.Add(elementCount);

            auto declRef = DeclRef<Decl>(vectorTypeDecl.Ptr(), substitutions);

            return DeclRefType::Create(
                session,
                declRef)->As<VectorExpressionType>();
        }

        RefPtr<Expr> visitIndexExpr(IndexExpr* subscriptExpr)
        {
            auto baseExpr = subscriptExpr->BaseExpression;
            baseExpr = CheckExpr(baseExpr);

            RefPtr<Expr> indexExpr = subscriptExpr->IndexExpression;
            if (indexExpr)
            {
                indexExpr = CheckExpr(indexExpr);
            }

            subscriptExpr->BaseExpression = baseExpr;
            subscriptExpr->IndexExpression = indexExpr;

            // If anything went wrong in the base expression,
            // then just move along...
            if (IsErrorExpr(baseExpr))
                return CreateErrorExpr(subscriptExpr);

            // Otherwise, we need to look at the type of the base expression,
            // to figure out how subscripting should work.
            auto baseType = baseExpr->type.Ptr();
            if (auto baseTypeType = baseType->As<TypeType>())
            {
                // We are trying to "index" into a type, so we have an expression like `float[2]`
                // which should be interpreted as resolving to an array type.

                RefPtr<IntVal> elementCount = nullptr;
                if (indexExpr)
                {
                    elementCount = CheckIntegerConstantExpression(indexExpr.Ptr());
                }

                auto elementType = CoerceToUsableType(TypeExp(baseExpr, baseTypeType->type));
                auto arrayType = getArrayType(
                    elementType,
                    elementCount);

                typeResult = arrayType;
                subscriptExpr->type = QualType(getTypeType(arrayType));
                return subscriptExpr;
            }
            else if (auto baseArrayType = baseType->As<ArrayExpressionType>())
            {
                return CheckSimpleSubscriptExpr(
                    subscriptExpr,
                    baseArrayType->baseType);
            }
            else if (auto vecType = baseType->As<VectorExpressionType>())
            {
                return CheckSimpleSubscriptExpr(
                    subscriptExpr,
                    vecType->elementType);
            }
            else if (auto matType = baseType->As<MatrixExpressionType>())
            {
                // TODO(tfoley): We shouldn't go and recompute
                // row types over and over like this... :(
                auto rowType = createVectorType(
                    matType->getElementType(),
                    matType->getColumnCount());

                return CheckSimpleSubscriptExpr(
                    subscriptExpr,
                    rowType);
            }

            // Default behavior is to look at all available `__subscript`
            // declarations on the type and try to call one of them.

            {
                LookupResult lookupResult = lookUpMember(
                    getSession(),
                    this,
                    getName("operator[]"),
                    baseType);
                if (!lookupResult.isValid())
                {
                    goto fail;
                }

                // Now that we know there is at least one subscript member,
                // we will construct a reference to it and try to call it.
                //
                // Note: the expression may be an `OverloadedExpr`, in which
                // case the attempt to call it will trigger overload
                // resolution.
                RefPtr<Expr> subscriptFuncExpr = createLookupResultExpr(
                    lookupResult, subscriptExpr->BaseExpression, subscriptExpr->loc);

                RefPtr<InvokeExpr> subscriptCallExpr = new InvokeExpr();
                subscriptCallExpr->loc = subscriptExpr->loc;
                subscriptCallExpr->FunctionExpr = subscriptFuncExpr;

                // TODO(tfoley): This path can support multiple arguments easily
                subscriptCallExpr->Arguments.Add(subscriptExpr->IndexExpression);

                return CheckInvokeExprWithCheckedOperands(subscriptCallExpr.Ptr());
            }

        fail:
            {
                getSink()->diagnose(subscriptExpr, Diagnostics::subscriptNonArray, baseType);
                return CreateErrorExpr(subscriptExpr);
            }
        }

        bool MatchArguments(FuncDecl * functionNode, List <RefPtr<Expr>> &args)
        {
            if (functionNode->GetParameters().Count() != args.Count())
                return false;
            int i = 0;
            for (auto param : functionNode->GetParameters())
            {
                if (!param->type.Equals(args[i]->type.Ptr()))
                    return false;
                i++;
            }
            return true;
        }

        // Coerce an expression to a specific  type that it is expected to have in context
        RefPtr<Expr> CoerceExprToType(
            RefPtr<Expr>	expr,
            RefPtr<Type>			type)
        {
            // TODO(tfoley): clean this up so there is only one version...
            return Coerce(type, expr);
        }

        RefPtr<Expr> visitParenExpr(ParenExpr* expr)
        {
            auto base = expr->base;
            base = CheckTerm(base);

            expr->base = base;
            expr->type = base->type;
            return expr;
        }

        //

        RefPtr<Expr> visitAssignExpr(AssignExpr* expr)
        {
            expr->left = CheckExpr(expr->left);

            auto type = expr->left->type;

            expr->right = Coerce(type, CheckTerm(expr->right));

            if (!type.IsLeftValue)
            {
                if (type->As<ErrorType>())
                {
                    // Don't report an l-value issue on an errorneous expression
                }
                else
                {
                    getSink()->diagnose(expr, Diagnostics::assignNonLValue);

                    // As a special case, check if the LHS expression is derived
                    // from a `this` parameter (implicitly or explicitly), which
                    // is immutable. We can give the user a bit more context into
                    // what is going on.
                    //
                    // We will try to handle expressions of the form:
                    //
                    //      e ::= "this"
                    //          | e . name
                    //          | e [ expr ]
                    //
                    // We will unwrap the `e.name` and `e[expr]` cases in a loop.
                    RefPtr<Expr> e = expr->left;
                    for(;;)
                    {
                        if(auto memberExpr = e.As<MemberExpr>())
                        {
                            e = memberExpr->BaseExpression;
                        }
                        else if(auto subscriptExpr = e.As<IndexExpr>())
                        {
                            e = subscriptExpr->BaseExpression;
                        }
                        else
                        {
                            break;
                        }
                    }
                    //
                    // Now we check to see if we have a `this` expression,
                    // and if it is immutable.
                    if(auto thisExpr = e.As<ThisExpr>())
                    {
                        if(!thisExpr->type.IsLeftValue)
                        {
                            getSink()->diagnose(thisExpr, Diagnostics::thisIsImmutableByDefault);
                        }
                    }

                }
            }
            expr->type = type;
            return expr;
        }

        void registerExtension(ExtensionDecl* decl)
        {
            if (decl->IsChecked(DeclCheckState::CheckedHeader))
                return;

            decl->SetCheckState(DeclCheckState::CheckingHeader);
            decl->targetType = CheckProperType(decl->targetType);
            decl->SetCheckState(DeclCheckState::CheckedHeader);

            // TODO: need to check that the target type names a declaration...

            if (auto targetDeclRefType = decl->targetType->As<DeclRefType>())
            {
                // Attach our extension to that type as a candidate...
                if (auto aggTypeDeclRef = targetDeclRefType->declRef.As<AggTypeDecl>())
                {
                    auto aggTypeDecl = aggTypeDeclRef.getDecl();
                    decl->nextCandidateExtension = aggTypeDecl->candidateExtensions;
                    aggTypeDecl->candidateExtensions = decl;
                    return;
                }
            }
            getSink()->diagnose(decl->targetType.exp, Diagnostics::unimplemented, "expected a nominal type here");
        }

        void visitExtensionDecl(ExtensionDecl* decl)
        {
            if (decl->IsChecked(getCheckedState())) return;

            if (!decl->targetType->As<DeclRefType>())
            {
                getSink()->diagnose(decl->targetType.exp, Diagnostics::unimplemented, "expected a nominal type here");
            }
            // now check the members of the extension
            for (auto m : decl->Members)
            {
                checkDecl(m);
            }
            decl->SetCheckState(getCheckedState());
        }

        // Figure out what type an initializer/constructor declaration
        // is supposed to return. In most cases this is just the type
        // declaration that its declaration is nested inside.
        RefPtr<Type> findResultTypeForConstructorDecl(ConstructorDecl* decl)
        {
            // We want to look at the parent of the declaration,
            // but if the declaration is generic, the parent will be
            // the `GenericDecl` and we need to skip past that to
            // the grandparent.
            //
            auto parent = decl->ParentDecl;
            auto genericParent = dynamic_cast<GenericDecl*>(parent);
            if (genericParent)
            {
                parent = genericParent->ParentDecl;
            }

            // Now look at the type of the parent (or grandparent).
            if (auto aggTypeDecl = dynamic_cast<AggTypeDecl*>(parent))
            {
                // We are nested in an aggregate type declaration,
                // so the result type of the initializer will just
                // be the surrounding type.
                return DeclRefType::Create(
                    getSession(),
                    makeDeclRef(aggTypeDecl));
            }
            else if (auto extDecl = dynamic_cast<ExtensionDecl*>(parent))
            {
                // We are nested inside an extension, so the result
                // type needs to be the type being extended.
                return extDecl->targetType.type;
            }
            else
            {
                getSink()->diagnose(decl, Diagnostics::initializerNotInsideType);
                return nullptr;
            }
        }

        void visitConstructorDecl(ConstructorDecl* decl)
        {
            if (decl->IsChecked(getCheckedState())) return;
            if (checkingPhase == CheckingPhase::Header)
            {
                decl->SetCheckState(DeclCheckState::CheckingHeader);

                for (auto& paramDecl : decl->GetParameters())
                {
                    paramDecl->type = CheckUsableType(paramDecl->type);
                }

                // We need to compute the result tyep for this declaration,
                // since it wasn't filled in for us.
                decl->ReturnType.type = findResultTypeForConstructorDecl(decl);
            }
            else
            {
                // TODO(tfoley): check body
            }
            decl->SetCheckState(getCheckedState());
        }


        void visitSubscriptDecl(SubscriptDecl* decl)
        {
            if (decl->IsChecked(getCheckedState())) return;
            for (auto& paramDecl : decl->GetParameters())
            {
                paramDecl->type = CheckUsableType(paramDecl->type);
            }

            decl->ReturnType = CheckUsableType(decl->ReturnType);

            // If we have a subscript declaration with no accessor declarations,
            // then we should create a single `GetterDecl` to represent
            // the implicit meaning of their declaration, so:
            //
            //      subscript(uint index) -> T;
            //
            // becomes:
            //
            //      subscript(uint index) -> T { get; }
            //

            bool anyAccessors = false;
            for(auto accessorDecl : decl->getMembersOfType<AccessorDecl>())
            {
                anyAccessors = true;
            }

            if(!anyAccessors)
            {
                RefPtr<GetterDecl> getterDecl = new GetterDecl();
                getterDecl->loc = decl->loc;

                getterDecl->ParentDecl = decl;
                decl->Members.Add(getterDecl);
            }

            for(auto mm : decl->Members)
            {
                checkDecl(mm);
            }

            decl->SetCheckState(getCheckedState());
        }

        void visitAccessorDecl(AccessorDecl* decl)
        {
            if (checkingPhase == CheckingPhase::Header)
            {
                // An acessor must appear nested inside a subscript declaration (today),
                // or a property declaration (when we add them). It will derive
                // its return type from the outer declaration, so we handle both
                // of these checks at the same place.
                auto parent = decl->ParentDecl;
                if (auto parentSubscript = dynamic_cast<SubscriptDecl*>(parent))
                {
                    decl->ReturnType = parentSubscript->ReturnType;
                }
                // TODO: when we add "property" declarations, check for them here
                else
                {
                    getSink()->diagnose(decl, Diagnostics::accessorMustBeInsideSubscriptOrProperty);
                }

            }
            else
            {
                // TODO: check the body!
            }
            decl->SetCheckState(getCheckedState());
        }


        //

        struct Constraint
        {
            Decl*		decl; // the declaration of the thing being constraints
            RefPtr<Val>	val; // the value to which we are constraining it
            bool satisfied = false; // Has this constraint been met?
        };

        // A collection of constraints that will need to be satisified (solved)
        // in order for checking to suceed.
        struct ConstraintSystem
        {
            // A source location to use in reporting any issues
            SourceLoc loc;

            // The generic declaration whose parameters we
            // are trying to solve for.
            RefPtr<GenericDecl> genericDecl;

            // Constraints we have accumulated, which constrain
            // the possible arguments for those parameters.
            List<Constraint> constraints;
        };

        RefPtr<Type> TryJoinVectorAndScalarType(
            RefPtr<VectorExpressionType> vectorType,
            RefPtr<BasicExpressionType>  scalarType)
        {
            // Join( vector<T,N>, S ) -> vetor<Join(T,S), N>
            //
            // That is, the join of a vector and a scalar type is
            // a vector type with a joined element type.
            auto joinElementType = TryJoinTypes(
                vectorType->elementType,
                scalarType);
            if(!joinElementType)
                return nullptr;

            return createVectorType(
                joinElementType,
                vectorType->elementCount);
        }

        struct TypeWitnessBreadcrumb
        {
            TypeWitnessBreadcrumb*  prev;

            RefPtr<Type>            sub;
            RefPtr<Type>            sup;
            DeclRef<Decl>           declRef;
        };

        // Crete a subtype witness based on the declared relationship
        // found in a single breadcrumb
        RefPtr<DeclaredSubtypeWitness> createSimpleSubtypeWitness(
            TypeWitnessBreadcrumb*  breadcrumb)
        {
            RefPtr<DeclaredSubtypeWitness> witness = new DeclaredSubtypeWitness();
            witness->sub = breadcrumb->sub;
            witness->sup = breadcrumb->sup;
            witness->declRef = breadcrumb->declRef;
            return witness;
        }

        RefPtr<Val> createTypeWitness(
            RefPtr<Type>            type,
            DeclRef<InterfaceDecl>  interfaceDeclRef,
            TypeWitnessBreadcrumb*  inBreadcrumbs)
        {
            if(!inBreadcrumbs)
            {
                // We need to construct a witness to the fact
                // that `type` has been proven to be *equal*
                // to `interfaceDeclRef`.
                //
                SLANG_UNEXPECTED("reflexive type witness");
                UNREACHABLE_RETURN(nullptr);
            }

            // We might have one or more steps in the breadcrumb trail, e.g.:
            //
            //      {A : B} {B : C} {C : D}
            //
            // The chain is stored as a reversed linked list, so that
            // the first entry would be the `(C : D)` relationship
            // above.
            //
            // We need to walk the list and build up a suitable witness,
            // which in the above case would look like:
            //
            //      Transitive(
            //          Transitive(
            //              Declared({A : B}),
            //              {B : C}),
            //          {C : D})
            //
            // Because of the ordering of the breadcrumb trail, along
            // with the way the `Transitive` case nests, we will be
            // building these objects outside-in, and keeping
            // track of the "hole" where the next step goes.
            //
            auto bb = inBreadcrumbs;

            // `witness` here will hold the first (outer-most) object
            // we create, which is the overall result.
            RefPtr<SubtypeWitness> witness;

            // `link` will point at the remaining "hole" in the
            // data structure, to be filled in.
            RefPtr<SubtypeWitness>* link = &witness;

            // As long as there is more than one breadcrumb, we
            // need to be creating transitie witnesses.
            while(bb->prev)
            {
                // On the first iteration when processing the list
                // above, the breadcrumb would be for `{ C : D }`,
                // and so we'd create:
                //
                //      Transitive(
                //          [...],
                //          { C : D})
                //
                // where `[...]` represents the "hole" we leave
                // open to fill in next.
                //
                RefPtr<TransitiveSubtypeWitness> transitiveWitness = new TransitiveSubtypeWitness();
                transitiveWitness->sub = bb->sub;
                transitiveWitness->sup = bb->sup;
                transitiveWitness->midToSup = bb->declRef;

                // Fill in the current hole, and then set the
                // hole to point into the node we just created.
                *link = transitiveWitness;
                link = &transitiveWitness->subToMid;

                // Move on with the list.
                bb = bb->prev;
            }

            // If we exit the loop, then there is only one breadcrumb left.
            // In our running example this would be `{ A : B }`. We create
            // a simple (declared) subtype witness for it, and plug the
            // final hole, after which there shouldn't be a hole to deal with.
            RefPtr<DeclaredSubtypeWitness> declaredWitness = createSimpleSubtypeWitness(bb);
            *link = declaredWitness;

            // We now know that our original `witness` variable has been
            // filled in, and there are no other holes.
            return witness;
        }

        bool doesTypeConformToInterfaceImpl(
            RefPtr<Type>            originalType,
            RefPtr<Type>            type,
            DeclRef<InterfaceDecl>  interfaceDeclRef,
            RefPtr<Val>*            outWitness,
            TypeWitnessBreadcrumb*  inBreadcrumbs)
        {
            // for now look up a conformance member...
            if(auto declRefType = type->As<DeclRefType>())
            {
                auto declRef = declRefType->declRef;

                // Easy case: a type conforms to itself.
                //
                // TODO: This is actually a bit more complicated, as
                // the interface needs to be "object-safe" for us to
                // really make this determination...
                if(declRef == interfaceDeclRef)
                {
                    if(outWitness)
                    {
                        *outWitness = createTypeWitness(originalType, interfaceDeclRef, inBreadcrumbs);
                    }
                    return true;
                }

                if( auto aggTypeDeclRef = declRef.As<AggTypeDecl>() )
                {
                    checkDecl(aggTypeDeclRef.getDecl());

                    for( auto inheritanceDeclRef : getMembersOfTypeWithExt<InheritanceDecl>(aggTypeDeclRef))
                    {
                        checkDecl(inheritanceDeclRef.getDecl());

                        // Here we will recursively look up conformance on the type
                        // that is being inherited from. This is dangerous because
                        // it might lead to infinite loops.
                        //
                        // TODO: A better appraoch would be to create a linearized list
                        // of all the interfaces that a given type direclty or indirectly
                        // inheirts, and store it with the type, so that we don't have
                        // to recurse in places like this (and can maybe catch infinite
                        // loops better). This would also help avoid checking multiply-inherited
                        // conformances multiple times.

                        auto inheritedType = getBaseType(inheritanceDeclRef);

                        // We need to ensure that the witness that gets created
                        // is a composite one, reflecting lookup through
                        // the inheritance declaration.
                        TypeWitnessBreadcrumb breadcrumb;
                        breadcrumb.prev = inBreadcrumbs;

                        breadcrumb.sub = type;
                        breadcrumb.sup = inheritedType;
                        breadcrumb.declRef = inheritanceDeclRef;

                        if(doesTypeConformToInterfaceImpl(originalType, inheritedType, interfaceDeclRef, outWitness, &breadcrumb))
                        {
                            return true;
                        }
                    }
                    // if an inheritance decl is not found, try to find a GenericTypeConstraintDecl
                    for (auto genConstraintDeclRef : getMembersOfType<GenericTypeConstraintDecl>(aggTypeDeclRef))
                    {
                        checkDecl(genConstraintDeclRef.getDecl());
                        auto inheritedType = GetSup(genConstraintDeclRef);
                        TypeWitnessBreadcrumb breadcrumb;
                        breadcrumb.prev = inBreadcrumbs;
                        breadcrumb.sub = type;
                        breadcrumb.sup = inheritedType;
                        breadcrumb.declRef = genConstraintDeclRef;
                        if (doesTypeConformToInterfaceImpl(originalType, inheritedType, interfaceDeclRef, outWitness, &breadcrumb))
                        {
                            return true;
                        }
                    }
                }
                else if( auto genericTypeParamDeclRef = declRef.As<GenericTypeParamDecl>() )
                {
                    // We need to enumerate the constraints placed on this type by its outer
                    // generic declaration, and see if any of them guarantees that we
                    // satisfy the given interface..
                    auto genericDeclRef = genericTypeParamDeclRef.GetParent().As<GenericDecl>();
                    SLANG_ASSERT(genericDeclRef);

                    for( auto constraintDeclRef : getMembersOfType<GenericTypeConstraintDecl>(genericDeclRef) )
                    {
                        auto sub = GetSub(constraintDeclRef);
                        auto sup = GetSup(constraintDeclRef);

                        auto subDeclRef = sub->As<DeclRefType>();
                        if(!subDeclRef)
                            continue;
                        if(subDeclRef->declRef != genericTypeParamDeclRef)
                            continue;

                        // The witness that we create needs to reflect that
                        // it found the needed conformance by lookup through
                        // a generic type constraint.

                        TypeWitnessBreadcrumb breadcrumb;
                        breadcrumb.prev = inBreadcrumbs;
                        breadcrumb.sub = sub;
                        breadcrumb.sup = sup;
                        breadcrumb.declRef = constraintDeclRef;

                        if(doesTypeConformToInterfaceImpl(originalType, sup, interfaceDeclRef, outWitness, &breadcrumb))
                        {
                            return true;
                        }
                    }
                }
            }

            // default is failure
            return false;
        }

        bool DoesTypeConformToInterface(
            RefPtr<Type>  type,
            DeclRef<InterfaceDecl>        interfaceDeclRef)
        {
            return doesTypeConformToInterfaceImpl(type, type, interfaceDeclRef, nullptr, nullptr);
        }

        RefPtr<Val> tryGetInterfaceConformanceWitness(
            RefPtr<Type>  type,
            DeclRef<InterfaceDecl>        interfaceDeclRef)
        {
            RefPtr<Val> result;
            doesTypeConformToInterfaceImpl(type, type, interfaceDeclRef, &result, nullptr);
            return result;
        }

        /// Does there exist an implicit conversion from `fromType` to `toType`?
        bool canConvertImplicitly(
            RefPtr<Type> toType,
            RefPtr<Type> fromType)
        {
            // Can we convert at all?
            ConversionCost conversionCost;
            if(!CanCoerce(toType, fromType, &conversionCost))
                return false;

            // Is the conversion cheap enough to be done implicitly?
            if(conversionCost >= kConversionCost_GeneralConversion)
                return false;

            return true;
        }

        RefPtr<Type> TryJoinTypeWithInterface(
            RefPtr<Type>            type,
            DeclRef<InterfaceDecl>      interfaceDeclRef)
        {
            // The most basic test here should be: does the type declare conformance to the trait.
            if(DoesTypeConformToInterface(type, interfaceDeclRef))
                return type;

            // Just because `type` doesn't conform to the given `interfaceDeclRef`, that
            // doesn't necessarily indicate a failure. It is possible that we have a call
            // like `sqrt(2)` so that `type` is `int` and `interfaceDeclRef` is
            // `__BuiltinFloatingPointType`. The "obvious" answer is that we should infer
            // the type `float`, but it seems like the compiler would have to synthesize
            // that answer from thin air.
            //
            // A robsut/correct solution here might be to enumerate set of types types `S`
            // such that for each type `X` in `S`:
            //
            // * `type` is implicitly convertible to `X`
            // * `X` conforms to the interface named by `interfaceDeclRef`
            //
            // If the set `S` is non-empty then we would try to pick the "best" type from `S`.
            // The "best" type would be a type `Y` such that `Y` is implicitly convertible to
            // every other type in `S`.
            //
            // We are going to implement a much simpler strategy for now, where we only apply
            // the search process if `type` is a builtin scalar type, and then we only search
            // through types `X` that are also builtin scalar types.
            //
            RefPtr<Type> bestType;
            if(auto basicType = type.As<BasicExpressionType>())
            {
                basicType->baseType;
                for(Int baseTypeFlavorIndex = 0; baseTypeFlavorIndex < Int(BaseType::CountOf); baseTypeFlavorIndex++)
                {
                    // Don't consider `type`, since we already know it doesn't work.
                    if(baseTypeFlavorIndex == Int(basicType->baseType))
                        continue;

                    // Look up the type in our session.
                    auto candidateType = type->getSession()->getBuiltinType(BaseType(baseTypeFlavorIndex));
                    if(!candidateType)
                        continue;

                    // We only want to consider types that implement the target interface.
                    if(!DoesTypeConformToInterface(candidateType, interfaceDeclRef))
                        continue;

                    // We only want to consider types where we can implicitly convert from `type`
                    if(!canConvertImplicitly(candidateType, type))
                        continue;

                    // At this point, we have a candidate type that is usable.
                    //
                    // If this is our first viable candidate, then it is our best one:
                    //
                    if(!bestType)
                    {
                        bestType = candidateType;
                    }
                    else
                    {
                        // Otherwise, we want to pick the "better" type between `candidateType`
                        // and `bestType`.
                        //
                        // We are going to be a bit loose here, and not worry about the
                        // case where conversion is allowed in both directions.
                        //
                        // TODO: make this completely robust.
                        //
                        if(canConvertImplicitly(bestType, candidateType))
                        {
                            // Our candidate can convert to the current "best" type, so
                            // it is logically a more specific type that satisfies our
                            // constraints, thereforce we should keep it.
                            //
                            bestType = candidateType;
                        }
                    }
                }
                if(bestType)
                    return bestType;
            }

            // For all other cases, we will just bail out for now.
            //
            // TODO: In the future we should build some kind of side data structure
            // to accelerate either one or both of these queries:
            //
            // * Given a type `T`, what types `U` can it convert to implicitly?
            //
            // * Given an interface `I`, what types `U` conform to it?
            //
            // The intersection of the sets returned by these two queries is
            // the set of candidates we would like to consider here.

            return nullptr;
        }

        // Try to compute the "join" between two types
        RefPtr<Type> TryJoinTypes(
            RefPtr<Type>  left,
            RefPtr<Type>  right)
        {
            // Easy case: they are the same type!
            if (left->Equals(right))
                return left;

            // We can join two basic types by picking the "better" of the two
            if (auto leftBasic = left->As<BasicExpressionType>())
            {
                if (auto rightBasic = right->As<BasicExpressionType>())
                {
                    auto leftFlavor = leftBasic->baseType;
                    auto rightFlavor = rightBasic->baseType;

                    // TODO(tfoley): Need a special-case rule here that if
                    // either operand is of type `half`, then we promote
                    // to at least `float`

                    // Return the one that had higher rank...
                    if (leftFlavor > rightFlavor)
                        return left;
                    else
                    {
                        SLANG_ASSERT(rightFlavor > leftFlavor); // equality was handles at the top of this function
                        return right;
                    }
                }

                // We can also join a vector and a scalar
                if(auto rightVector = right->As<VectorExpressionType>())
                {
                    return TryJoinVectorAndScalarType(rightVector, leftBasic);
                }
            }

            // We can join two vector types by joining their element types
            // (and also their sizes...)
            if( auto leftVector = left->As<VectorExpressionType>())
            {
                if(auto rightVector = right->As<VectorExpressionType>())
                {
                    // Check if the vector sizes match
                    if(!leftVector->elementCount->EqualsVal(rightVector->elementCount.Ptr()))
                        return nullptr;

                    // Try to join the element types
                    auto joinElementType = TryJoinTypes(
                        leftVector->elementType,
                        rightVector->elementType);
                    if(!joinElementType)
                        return nullptr;

                    return createVectorType(
                        joinElementType,
                        leftVector->elementCount);
                }

                // We can also join a vector and a scalar
                if(auto rightBasic = right->As<BasicExpressionType>())
                {
                    return TryJoinVectorAndScalarType(leftVector, rightBasic);
                }
            }

            // HACK: trying to work trait types in here...
            if(auto leftDeclRefType = left->As<DeclRefType>())
            {
                if( auto leftInterfaceRef = leftDeclRefType->declRef.As<InterfaceDecl>() )
                {
                    //
                    return TryJoinTypeWithInterface(right, leftInterfaceRef);
                }
            }
            if(auto rightDeclRefType = right->As<DeclRefType>())
            {
                if( auto rightInterfaceRef = rightDeclRefType->declRef.As<InterfaceDecl>() )
                {
                    //
                    return TryJoinTypeWithInterface(left, rightInterfaceRef);
                }
            }

            // TODO: all the cases for vectors apply to matrices too!

            // Default case is that we just fail.
            return nullptr;
        }

        // Try to solve a system of generic constraints.
        // The `system` argument provides the constraints.
        // The `varSubst` argument provides the list of constraint
        // variables that were created for the system.
        //
        // Returns a new substitution representing the values that
        // we solved for along the way.
        SubstitutionSet TrySolveConstraintSystem(
            ConstraintSystem*		system,
            DeclRef<GenericDecl>          genericDeclRef)
        {
            // For now the "solver" is going to be ridiculously simplistic.

            // The generic itself will have some constraints, and for now we add these
            // to the system of constrains we will use for solving for the type variables.
            //
            // TODO: we need to decide whether constraints are used like this to influence
            // how we solve for type/value variables, or whether constraints in the parameter
            // list just work as a validation step *after* we've solved for the types.
            //
            // That is, should we allow `<T : Int>` to be written, and cause us to "infer"
            // that `T` should be the type `Int`? That seems a little silly.
            //
            // Eventually, though, we may want to support type identity constraints, especially
            // on associated types, like `<C where C : IContainer && C.IndexType == Int>`
            // These seem more reasonable to have influence constraint solving, since it could
            // conceivably let us specialize a `X<T> : IContainer` to `X<Int>` if we find
            // that `X<T>.IndexType == T`.
            for( auto constraintDeclRef : getMembersOfType<GenericTypeConstraintDecl>(genericDeclRef) )
            {
                if(!TryUnifyTypes(*system, GetSub(constraintDeclRef), GetSup(constraintDeclRef)))
                    return SubstitutionSet();
            }
            SubstitutionSet resultSubst = genericDeclRef.substitutions;
            // We will loop over the generic parameters, and for
            // each we will try to find a way to satisfy all
            // the constraints for that parameter
            List<RefPtr<Val>> args;
            for (auto m : getMembers(genericDeclRef))
            {
                if (auto typeParam = m.As<GenericTypeParamDecl>())
                {
                    RefPtr<Type> type = nullptr;
                    for (auto& c : system->constraints)
                    {
                        if (c.decl != typeParam.getDecl())
                            continue;

                        auto cType = c.val.As<Type>();
                        SLANG_RELEASE_ASSERT(cType.Ptr());

                        if (!type)
                        {
                            type = cType;
                        }
                        else
                        {
                            auto joinType = TryJoinTypes(type, cType);
                            if (!joinType)
                            {
                                // failure!
                                return SubstitutionSet();
                            }
                            type = joinType;
                        }

                        c.satisfied = true;
                    }

                    if (!type)
                    {
                        // failure!
                        return SubstitutionSet();
                    }
                    args.Add(type);
                }
                else if (auto valParam = m.As<GenericValueParamDecl>())
                {
                    // TODO(tfoley): maybe support more than integers some day?
                    // TODO(tfoley): figure out how this needs to interact with
                    // compile-time integers that aren't just constants...
                    RefPtr<IntVal> val = nullptr;
                    for (auto& c : system->constraints)
                    {
                        if (c.decl != valParam.getDecl())
                            continue;

                        auto cVal = c.val.As<IntVal>();
                        SLANG_RELEASE_ASSERT(cVal.Ptr());

                        if (!val)
                        {
                            val = cVal;
                        }
                        else
                        {
                            if(!val->EqualsVal(cVal.Ptr()))
                            {
                                // failure!
                                return SubstitutionSet();
                            }
                        }

                        c.satisfied = true;
                    }

                    if (!val)
                    {
                        // failure!
                        return SubstitutionSet();
                    }
                    args.Add(val);
                }
                else
                {
                    // ignore anything that isn't a generic parameter
                }
            }

            // After we've solved for the explicit arguments, we need to
            // make a second pass and consider the implicit arguments,
            // based on what we've already determined to be the values
            // for the explicit arguments.

            // Before we begin, we are going to go ahead and create the
            // "solved" substitution that we will return if everything works.
            // This is because we are going to use this substitution,
            // partially filled in with the results we know so far,
            // in order to specialize any constraints on the generic.
            //
            // E.g., if the generic parameters were `<T : ISidekick>`, and
            // we've already decided that `T` is `Robin`, then we want to
            // search for a conformance `Robin : ISidekick`, which involved
            // apply the substitutions we already know...

            RefPtr<GenericSubstitution> solvedSubst = new GenericSubstitution();
            solvedSubst->genericDecl = genericDeclRef.getDecl();
            solvedSubst->outer = genericDeclRef.substitutions.substitutions;
            solvedSubst->args = args;
            resultSubst.substitutions = solvedSubst;

            for( auto constraintDecl : genericDeclRef.getDecl()->getMembersOfType<GenericTypeConstraintDecl>() )
            {
                DeclRef<GenericTypeConstraintDecl> constraintDeclRef(
                    constraintDecl,
                    solvedSubst);

                // Extract the (substituted) sub- and super-type from the constraint.
                auto sub = GetSub(constraintDeclRef);
                auto sup = GetSup(constraintDeclRef);

                // Search for a witness that shows the constraint is satisfied.
                auto subTypeWitness = tryGetSubtypeWitness(sub, sup);
                if(subTypeWitness)
                {
                    // We found a witness, so it will become an (implicit) argument.
                    solvedSubst->args.Add(subTypeWitness);
                }
                else
                {
                    // No witness was found, so the inference will now fail.
                    //
                    // TODO: Ideally we should print an error message in
                    // this case, to let the user know why things failed.
                    return SubstitutionSet();
                }

                // TODO: We may need to mark some constrains in our constraint
                // system as being solved now, as a result of the witness we found.
            }

            // Make sure we haven't constructed any spurious constraints
            // that we aren't able to satisfy:
            for (auto c : system->constraints)
            {
                if (!c.satisfied)
                {
                    return SubstitutionSet();
                }
            }

            return resultSubst;
        }


        // State related to overload resolution for a call
        // to an overloaded symbol
        struct OverloadResolveContext