fsharp.opp.exp 103 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078
File "fsharp.mly", line 153, characters 21-24:
Warning: the token ASR is unused.
File "fsharp.mly", line 216, characters 21-28:
Warning: the token COMMENT is unused.
File "fsharp.mly", line 152, characters 84-94:
Warning: the token CONSTRAINT is unused.
File "fsharp.mly", line 163, characters 61-72:
Warning: the token CONSTRUCTOR is unused.
File "fsharp.mly", line 157, characters 86-97:
Warning: the token GREATER_DOT is unused.
File "fsharp.mly", line 160, characters 30-44:
Warning: the token GREATER_RBRACE is unused.
File "fsharp.mly", line 156, characters 62-70:
Warning: the token INSTANCE is unused.
File "fsharp.mly", line 138, characters 21-34:
Warning: the token INT32_DOT_DOT is unused.
File "fsharp.mly", line 160, characters 7-18:
Warning: the token LBRACE_LESS is unused.
File "fsharp.mly", line 215, characters 16-27:
Warning: the token LEX_FAILURE is unused.
File "fsharp.mly", line 216, characters 40-52:
Warning: the token LINE_COMMENT is unused.
File "fsharp.mly", line 212, characters 15-21:
Warning: the token ODUMMY is unused.
File "fsharp.mly", line 182, characters 7-13:
Warning: the token ORESET is unused.
File "fsharp.mly", line 152, characters 49-57:
Warning: the token RESERVED is unused.
File "fsharp.mly", line 216, characters 53-64:
Warning: the token STRING_TEXT is unused.
File "fsharp.mly", line 216, characters 29-39:
Warning: the token WHITESPACE is unused.
File "fsharp.mly", line 351, characters 21-28:
Warning: the token decl_do is unused.
File "fsharp.mly", line 351, characters 10-20:
Warning: the token decl_match is unused.
File "fsharp.mly", line 350, characters 53-60:
Warning: the token expr_do is unused.
File "fsharp.mly", line 384, characters 10-18:
Warning: the token expr_not is unused.
File "fsharp.mly", line 396, characters 7-19:
Warning: the token matching_bar is unused.
File "fsharp.mly", line 278, characters 10-25:
Warning: the token prec_args_error is unused.
File "fsharp.mly", line 301, characters 7-20:
Warning: the token prec_defn_sep is unused.
File "fsharp.mly", line 405, characters 10-32:
Warning: the token prec_interaction_empty is unused.
File "fsharp.mly", line 300, characters 18-35:
Warning: the token prec_semiexpr_sep is unused.
%{
(* (c) Microsoft Corporation. All rights reserved *)
(*F# open Microsoft.Research.AbstractIL F#*)
(*F# open Microsoft.Research.AbstractIL.Internal F#*)
(*F# open Microsoft.FSharp.Compiler F#*)

open Range
open Ast
open Lib

let mk_optional m xopt = 
    match xopt with 
    | None -> mksyn_lid_get m Env.lib_MFCore_path "None"
    | Some x  -> Expr_app(mksyn_lid_get m Env.lib_MFCore_path "Some",x,m)

let mk_Do (strict,expr,m) = 
    Binding (None,
             (if strict then DoBinding else StandaloneExpression),
             false,false,[],emptyXMLDoc,None,
             (if strict then Pat_const(Const_unit,m) else Pat_wild m),
             BindingExpr([],None,expr),m)

let mksyn_lazy_ty m ty = 
  Type_app((path_to_lid m Env.lazy_path @ [mksyn_id m "Lazy"]),[ty],m)

let addAttribs attrs p =  Pat_attrib(p,attrs,range_of_synpat p)

let computeOverloadQualifier attrs = 
  let attrs = 
      attrs |> chooseList (fun attr -> 
          match attr with 
          | (Attr(lid,(Expr_const(Const_string (s,_),_) | Expr_paren(Expr_const(Const_string (s,_),_),_)),_,_)) ->
              begin match frontAndBack lid with 
              | (_,{idText="OverloadID" | "OverloadIDAttribute"}) -> Some(s)
              | _ -> None
              end
          | _ -> None) in
  match attrs with 
  | [x] -> Some x
  | [] -> None
  | _ -> failwith "Multiple OverloadID attributes"

(* error recovery*)
let arbExpr() = Expr_const(Const_unit,lhs())

let mksyn_lazy_status m e = Expr_recd(None,None, [ ((path_to_lid m Env.lazy_path, mksyn_id m "status"),e) ], m)

let mksyn_lazy (e,m) = 
  Expr_typed(mksyn_lazy_status m (Expr_app(mksyn_lid_get m Env.lazystatus_path "Delayed",mksyn_delay m e,m)),
             mksyn_lazy_ty m (Type_anon m),m)

let mksyn_anon_constraint ty m = Type_anon_constraint(ty,m) 

let parse_error s = errorR(Error(s,curr_lex_range())) (* returning initiates error recovery *)
let report_parse_warning s = warning(Error(s,curr_lex_range()))
let report_parse_error_at m s = errorR(Error(s,m))

let report_parse_warning_at m s = warning(Error(s,m))

(* OCaml generated parsers seem to create corrupted terms if parse error are raised when an "error" symbol is being shifted *)
let raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m s = report_parse_error_at m s; raise Parsing.Parse_error 

let check_eof_error_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY res t = 
  match t with 
  | AT_ifdef_skip(_,m) -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "end of file in #if section begun at or after here"
  | AT_string m ->  raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "end of file in string begun at or before here"
  | AT_vstring m ->  raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "end of file in verbatim string begun at or before here"
  | AT_comment (_,m) ->  raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "end of file in comment begun at or before here"
  | AT_comment_string (_,m) -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "end of file in string embedded in comment begun at or before here"
  | AT_camlonly m -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "end of file in IF-OCAML section begun at or before here" 
  | AT_token -> res

(* note: defns moved to ast.ml *)      
let grabXML ()      = Ast.grabXML ()

let mkClassMemberLocalBindings isStatic wholem attrs vis (_,isRec,isUse,declsPreAttrs) = 
   let ignoredFreeAttrs,decls = declsPreAttrs attrs vis in 
   if nonNil ignoredFreeAttrs then warning(Error("attributes have been ignored in this construct",wholem));
   if isUse then warning(Error("'use' bindings are not permitted in implicit class constructors",wholem));
   ClassMemberDefn_let_bindings (decls,isStatic,isRec,wholem)

let mkLocalBindings wholem (_,isRec,isUse,declsPreAttrs) body = 
   let ignoredFreeAttrs,decls = declsPreAttrs [] None in 
   if nonNil ignoredFreeAttrs then warning(Error("attributes have been ignored in this construct",wholem));
   Expr_let (isRec,isUse,decls,body,wholem) 

let mkDefnBindings wholem (_,isRec,isUse,declsPreAttrs) attrs vis attrsm = 
   if isUse then warning(Error("'use' bindings are treated as 'let' bindings in modules",wholem));
   let freeAttrs,decls = declsPreAttrs attrs vis in 
   let letDecls = [ Def_let (isRec,decls,wholem) ] in 
   let attrDecls = if nonNil freeAttrs then [ Def_attributes (freeAttrs,attrsm) ] else [] in 
   attrDecls @ letDecls

let mkComprehensionBindings wholem (_,isRec,isUse,declsPreAttrs) rest = 
   let ignoredFreeAttrs,decls = declsPreAttrs [] None in 
   if nonNil ignoredFreeAttrs then warning(Error("attributes have been ignored in this construct",wholem));
   if isRec then errorR(Error("recursive bindings are not permitted in comprehensions",wholem));
   match decls with 
   | [] -> error(Error("unexpected empty declarations",wholem))
   | [Binding (vis,bindingKind,pseudo,mut,attrs,doc,memberInfo,pat,(BindingExpr(spatsL,rtyOpt,expr)),bindm)] -> 
        if nonNil(attrs) && bindingKind = StandaloneExpression then error(Error("expressions may not have attributes",bindm));
        if isSome rtyOpt then warning(Error("this type attribute is currently ignored",bindm));
        if nonNil spatsL then error(Error("functions may not be defined in comprehensions",bindm));
        if isSome memberInfo then error(InternalError("unexpected member comprehension",bindm));
        if pseudo then error(Error("inline values may not be defined in comprehensions",bindm));
        if isSome vis then warning(Error("visibility attributes are ignored on declarations in comprehensions",bindm));
        if mut then warning(Error("declarations in comprehensions may not be declared mutable",bindm));
        if nonNil attrs then warning(Error("attributes have been ignored in this construct",bindm));
        Comp_bind(isUse,None,Some pat,expr,rest)
   | _ -> error(Error("multiple binding declarations may not be used in comprehensions",wholem))

let id_of_pat m p = match p with Pat_as (Pat_wild _,id,false,_,_) -> id | _ -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "A integer for loop must use a simple identifier"

let checkForMultipleAugmentations m a1 a2 = 
        if nonNil a1 && nonNil a2 then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "at most one 'with' augmentation is permitted";
        a1 @ a2
     
%}
%start implementationFile
%start interaction
%start signatureFile
%token <bool> YIELD_BANG
%token <bool> YIELD
%token WITH
%token <Ast.lexcont> WHITESPACE
%token WHILE
%token VOID
%token VIRTUAL
%token VAL
%token UPCAST
%token TYPE
%token TRY
%token TO
%token THEN
%token STRUCT
%token <Ast.lexcont> STRING_TEXT
%token STATIC
%token <string> SPLICE_SYMBOL
%token SIG
%token SEMICOLON_SEMICOLON
%token <string * bool> RQUOTE
%token RESERVED
%token REC
%token RBRACK
%token RBRACE
%token RARROW2
%token QUOTE
%token QMARK
%token PUBLIC
%token PRIVATE
%token OWITH
%token OVERRIDE
%token OTHEN
%token ORIGHT_BLOCK_END
%token ORESET
%token <bool> OLET
%token OINTERFACE_MEMBER
%token OFUNCTION
%token OFUN
%token OF
%token OEND
%token OELSE
%token <token> ODUMMY
%token ODO_BANG
%token ODO
%token ODECLEND
%token OBLOCKEND
%token OBLOCKBEGIN
%token <string> OBINDER
%token NAMESPACE
%token MUTABLE
%token MODULE
%token METHOD
%token MEMBER
%token MATCH
%token <string * bool> LQUOTE
%token <Ast.lexcont> LINE_COMMENT
%token <string> LEX_FAILURE
%token LBRACK_LESS
%token LBRACE_LESS
%token INTERNAL
%token <int32> INT32_DOT_DOT
%token INSTANCE
%token INLINE
%token INHERIT
%token IN
%token IF
%token <string> HASH_KEYWORD
%token HASH
%token GREATER_RBRACK
%token GREATER_RBRACE
%token GREATER_DOT
%token <string> FUNKY_OPERATOR_NAME
%token FUNCTION
%token FUN
%token FOR
%token FINALLY
%token EXTERN
%token EXCEPTION
%token <Ast.lexcont> EOF
%token END
%token ELIF
%token DO_BANG
%token DOWNTO
%token DOWNCAST
%token DONE
%token DO
%token DELEGATE
%token DEFAULT
%token CONSTRUCTOR
%token CONSTRAINT
%token <Ast.lexcont> COMMENT
%token COLON_QMARK_GREATER
%token COLON_QMARK
%token COLON
%token CLASS
%token <string> BINDER
%token BEGIN
%token BAR_RBRACK
%token ASSERT
%token ASR
%token ABSTRACT
%token AS
%token RPAREN
%token WHEN
%token BAR
%token SEMICOLON
%token OBLOCKSEP
%token <Nums.u64> UNATIVEINT
%token <Nums.u8> UINT8
%token <Nums.u64> UINT64
%token <Nums.u32> UINT32
%token <Nums.u16> UINT16
%token <Bytes.bytes> STRING
%token <int64> NATIVEINT
%token <Nums.i8> INT8
%token <int64> INT64
%token <int32> INT32
%token <Nums.i16> INT16
%token <Nums.ieee64> IEEE64
%token <Nums.ieee32> IEEE32
%token <Bytes.bytes> DECIMAL
%token <Nums.unichar> CHAR
%token <Bytes.bytes> BYTEARRAY
%token <Bytes.bytes> BIGNUM
%token <Bytes.bytes> BIGINT
%token LPAREN
%token LBRACK_BAR
%token LBRACE
%token UNDERSCORE
%token TRUE
%token NULL
%token FALSE
%token RARROW
%token LBRACK
%token LAZY
%token <string> IDENT
%token NEW
%token <bool> LET
%token ELSE
%token OPEN
%token INTERFACE
%token LARROW
%token COLON_EQUALS
%token COMMA
%token DOT_DOT
%token OR
%token BAR_BAR
%token AND
%token AMP_AMP
%token AMP
%token LESS
%token <string> INFIX_COMPARE_OP
%token <string> INFIX_BAR_OP
%token <string> INFIX_AMP_OP
%token GREATER
%token EQUALS
%token DOLLAR
%token <string> INFIX_AT_HAT_OP
%token COLON_COLON
%token COLON_GREATER
%token <string> PLUS_MINUS_OP
%token MINUS
%token <string> ADJACENT_PREFIX_PLUS_MINUS_OP
%token STAR
%token <string> PERCENT_OP
%token <string> INFIX_STAR_DIV_MOD_OP
%token <string> INFIX_STAR_STAR_OP
%token QMARK_QMARK
%token <string> PREFIX_OP
%token DOT
%token HIGH_PRECEDENCE_APP
%token HIGH_PRECEDENCE_TYAPP
%nonassoc prec_args_error 
%nonassoc prec_atomexpr_lparen_error 
%right AS 
%nonassoc prec_wheretyp_prefix 
%nonassoc RPAREN 
%right WHEN 
%nonassoc prec_pat_pat_action 
%left prec_then_before 
%nonassoc prec_then_if 
%left BAR 
%right prec_semiexpr_sep SEMICOLON OBLOCKSEP 
%right prec_defn_sep 
%nonassoc prec_atompat_pathop 
%nonassoc UNATIVEINT UINT8 UINT64 UINT32 UINT16 STRING NATIVEINT INT8 INT64 INT32 INT16 IEEE64 IEEE32 DECIMAL CHAR BYTEARRAY BIGNUM BIGINT 
%nonassoc LPAREN LBRACK_BAR LBRACE 
%nonassoc UNDERSCORE TRUE NULL FALSE 
%nonassoc prec_typ_prefix 
%nonassoc prec_tuptyp_prefix 
%nonassoc prec_tuptyptail_prefix 
%nonassoc prec_toptuptyptail_prefix 
%right RARROW 
%nonassoc LBRACK LAZY IDENT 
%nonassoc prec_opt_attributes_none 
%nonassoc NEW LET 
%nonassoc expr_let 
%nonassoc decl_let 
%nonassoc expr_try expr_match expr_function expr_fun expr_do 
%nonassoc decl_match decl_do 
%nonassoc expr_if 
%nonassoc ELSE 
%nonassoc prec_atomtyp_path 
%nonassoc prec_atomtyp_get_path 
%nonassoc prec_no_more_attr_bindings 
%nonassoc OPEN 
%nonassoc prec_interfaces_prefix 
%nonassoc INTERFACE 
%right LARROW 
%right COLON_EQUALS 
%nonassoc pat_tuple expr_tuple 
%left COMMA 
%nonassoc slice_comma 
%nonassoc DOT_DOT 
%nonassoc paren_pat_colon 
%nonassoc paren_pat_attribs 
%left OR BAR_BAR 
%left AND 
%left AMP_AMP AMP 
%nonassoc pat_conj 
%nonassoc expr_not 
%left LESS INFIX_COMPARE_OP INFIX_BAR_OP INFIX_AMP_OP GREATER EQUALS DOLLAR 
%right INFIX_AT_HAT_OP 
%right COLON_COLON 
%nonassoc pat_isinst expr_isinst COLON_GREATER 
%left PLUS_MINUS_OP MINUS ADJACENT_PREFIX_PLUS_MINUS_OP 
%left STAR PERCENT_OP INFIX_STAR_DIV_MOD_OP 
%right INFIX_STAR_STAR_OP 
%left QMARK_QMARK 
%nonassoc expr_prefix_plus_minus 
%left expr_lazy expr_assert expr_app 
%left expr_args 
%right matching_bar 
%left pat_app 
%left pat_args 
%left PREFIX_OP 
%left DOT 
%left HIGH_PRECEDENCE_APP 
%left HIGH_PRECEDENCE_TYAPP 
%nonassoc prec_interaction_empty 
%type <Ast.synexpr> declExpr
%type <Ast.synpat> headBindingPattern
%type <Ast.ident> ident
%type <Ast.impl list> implementationFile
%type <Ast.interaction> interaction
%type <Ast.intf list> signatureFile
%type <Ast.tyconSpfn list> tyconSpfns
%type <Ast.typ> typ
%%

interaction:
| opt_itop_seps interactiveExprOrDefinitions
    { IDefns ($2,lhs()) }
| opt_itop_seps hashDirective interactiveTerminator
    { $2 }
| opt_itop_seps hashDirective OBLOCKSEP
    { $2 }

hashDirective:
| HASH IDENT hashDirectiveArgs
    { IHash ($2,$3,lhs()) }
| HASH_KEYWORD hashDirectiveArgs
    { IHash ($1,$2,lhs()) }

hashDirectiveArg:
| STRING
    { Bytes.unicode_bytes_as_string $1 }

hashDirectiveArgs:
| 
    { [] }
| hashDirectiveArgs hashDirectiveArg
    { $1 @ [$2] }

interactiveTerminator:
| SEMICOLON_SEMICOLON
    {}
| EOF
    {}

interactiveDefinitions:
| moduleOrNamespaceDefn interactiveDefinitions
    { $1 @ $2 }
| moduleOrNamespaceDefn itop_seps interactiveExprOrDefinitions
    { $1 @ $3 }
| interactiveTerminator
    { [] }

interactiveExprOrDefinitions:
| declExpr itop_seps interactiveExprOrDefinitions
    { Def_let(false,[mk_Do  (false,$1,rhs 1)], rhs 1) :: $3 }
| declExpr interactiveTerminator
    { [ Def_let(false,[mk_Do  (false,$1,rhs 1)], rhs 1) ] }
| interactiveDefinitions
    { $1 }

signatureFile:
| namespaceSpecs EOF
    { check_eof_error_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY $1 $2 }

implementationFile:
| namespaceImpls EOF
    { check_eof_error_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY $1 $2 }

moduleIntro:
| MODULE grab_doc opt_access path
    { $4,true,$2,$3 }

namespaceIntro:
| NAMESPACE grab_doc path
    { $3,false,$2  }

namespaceSpecs:
| moduleSpec
    { [ ($1 ([],emptyXMLDoc)) ] }
| namespaceSpecList
    { $1 }

namespaceSpecList:
| namespaceSpec namespaceSpecList
    { $1 :: $2 }
| namespaceSpec
    { [$1] }

namespaceSpec:
| opt_attributes namespaceIntro deprecated_opt_equals moduleSpec
    { let path,_,xml = $2 in ($4 (path,xml)) }

namespaceImpls:
| moduleImpl
    { [ ($1 ([],emptyXMLDoc)) ] }
| namespaceImplList
    { $1 }

namespaceImplList:
| namespaceImpl namespaceImplList
    { $1 :: $2 }
| namespaceImpl
    { [$1] }

namespaceImpl:
| opt_attributes namespaceIntro deprecated_opt_equals moduleImpl
    { let path,_,xml = $2 in ($4 (path,xml)) }

moduleSpec:
| opt_attributes opt_decl_visibility moduleIntro specifications
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
      let m = (rhs2 3 4) in
      (fun (path,_) -> 
        let path2,_,xml,vis = $3 in 
        let lid = path@path2 in 
        NamedTopModuleSpec(ModuleSpec(lid,true, $4, xml,$1,vis,m)))  }
| specifications
    { let m = (rhs 1) in 
      (fun (path,xml) -> 
        match path with 
        | [] -> AnonTopModuleSpec($1, m)  
        | _ -> AnonNamespaceFragmentSpec(path,false, $1, xml,[],m))  }

moduleImpl:
| opt_attributes opt_decl_visibility moduleIntro exprOrDefinitions
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
      let m = (rhs2 3 4) in 
      (fun (path,_) -> 
        let path2,isModule,xml,vis = $3 in 
        let lid = path@path2 in 
        NamedTopModuleImpl(ModuleImpl(lid,isModule, $4, xml,$1,vis,m))) }
| exprOrDefinitions
    { let m = (rhs 1) in 
      (fun (path,xml) -> 
        match path with 
        | [] -> AnonTopModuleImpl($1,m)  
        | _ -> AnonNamespaceFragmentImpl(path,false, $1, xml,[],m)) }

specifications:
| moduleOrNamespaceSpfn opt_top_seps specifications
    { $1 :: $3 }
| hashDirective top_sep specifications
    { Spec_hash ($1,rhs2 1 1) :: $3 }
| error opt_top_seps specifications
    { (* silent recovery *) $3 }
| 
    { [] }

exprOrDefinitions:
| declExpr top_seps exprOrDefinitions
    { Def_let(false,[mk_Do  (false,$1,rhs 1)], rhs 1) :: $3 }
| declExpr
    { [ Def_let(false,[mk_Do  (false,$1,rhs 1)], rhs 1) ] }
| moduleOrNamespaceDefns
    { $1 }

moduleOrNamespaceDefns:
| moduleOrNamespaceDefn moduleOrNamespaceDefns
    {  $1 @ $2 }
| moduleOrNamespaceDefn top_seps exprOrDefinitions
    {  $1 @ $3 }
| hashDirective top_seps exprOrDefinitions
    { Def_hash ($1,rhs2 1 1) :: $3 }
| error moduleOrNamespaceDefns
    { (* silent recovery *) $2 }
| error top_seps exprOrDefinitions
    { (* silent recovery *) $3 }
| 
    { [] }

moduleOrNamespaceDefn:
| defnBindings %prec decl_let
    { new_arg_uniq_ref := 0;
        mkDefnBindings (lhs()) $1 [] None (lhs())  }
| hardwhiteDefnBindings %prec decl_let
    { new_arg_uniq_ref := 0;
        mkDefnBindings (lhs()) $1 [] None (lhs()) }
| opt_attributes opt_decl_visibility defnBindings %prec decl_let
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        new_arg_uniq_ref := 0;
        mkDefnBindings (rhs 3) $3 $1 $2 (rhs 3)  }
| opt_attributes opt_decl_visibility hardwhiteDefnBindings %prec decl_let
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        new_arg_uniq_ref := 0;
        mkDefnBindings (rhs 3) $3 $1 $2 (rhs 3)  }
| opt_attributes opt_decl_visibility doBinding %prec decl_let
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let letm = rhs 3 in 
        mkDefnBindings letm $3 $1 $2 (rhs 3) }
| opt_attributes opt_decl_visibility TYPE tyconDefn tyconDefnList
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let      (TyconDefn(ComponentInfo(cas   ,kind     ,a,cs,b,c,d,d2,d3),e,f,g)) = $4 in
        let tc = (TyconDefn(ComponentInfo($1@cas,TMK_Tycon,a,cs,b,c,d,d2,d3),e,f,g)) in
        [ Def_tycon(tc :: $5,rhs2 3 5) ] }
| opt_attributes opt_decl_visibility TYPE componentInfo tyconDefnAugmentation
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        if $1 <> [] then warning(Error("Attributes on augmentations are ignored, they must be placed on the original declaration",rhs 1));
        [ Def_partial_tycon($4,$5,rhs2 3 5) ] }
| opt_attributes opt_decl_visibility exconDefn
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let (ExconDefn(ExconCore(cas,a,b,c,d,d2),e,f)) = $3 in 
        let ec = (ExconDefn(ExconCore($1@cas,a,b,c,d,d2),e,f)) in 
        [ Def_exn(ec, rhs2 3 3) ] }
| opt_attributes opt_decl_visibility moduleIntro opt_signature EQUALS namedModuleAbbrevBlock
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let (path,isModule,xml,vis),mty,eqn = $3,$4,$6 in 
        if not isModule          then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "namespaces must be declared at the head of a file";
        if isSome mty            then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "a module abbreviation may not be given a constraint";
        if List.length path <> 1 then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "a module abbreviation must be a simple name, not a path";
        if List.length $1 <> 0   then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 1) "ignorning attributes on module abbreviation";
        if isSome vis            then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 1) "ignorning accessibility attribute on module abbreviation. Module abbreviations are always private";
        [ Def_module_abbrev(List.hd path,eqn,rhs2 3 6) ] }
| opt_attributes opt_decl_visibility moduleIntro opt_signature EQUALS namedModuleDefnBlock
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let attribs,(path,isModule,xml,vis),mty,def = $1,$3,$4,$6 in 
        if not isModule          then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "namespaces must be declared at the head of a file";
        if List.length path <> 1 then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "a module definition must be a simple name, not a path";
        let info = ComponentInfo(attribs,TMK_Module,[],[],path,xml,false,vis,rhs 3) in
        [ Def_module(info,def,mty,rhs2 3 6) ] }
| openDecl
    { [Def_open($1,rhs 1)] }

namedModuleAbbrevBlock:
| OBLOCKBEGIN path OBLOCKEND
    { $2 }
| path
    { $1 }

namedModuleDefnBlock:
| OBLOCKBEGIN wrappedNamedModuleDefn OBLOCKEND
    { $2 }
| OBLOCKBEGIN moduleOrNamespaceDefns OBLOCKEND
    { $2 }
| OBLOCKBEGIN moduleOrNamespaceDefns recover
    { report_parse_error_at (rhs 1) "unclosed block in #light syntax";   
         $2 }
| OBLOCKBEGIN error OBLOCKEND
    { [] }
| wrappedNamedModuleDefn
    { $1 }

wrappedNamedModuleDefn:
| structOrBegin exprOrDefinitions END
    { $2 }
| structOrBegin exprOrDefinitions recover
    { report_parse_error_at (rhs 1) "unmatched 'begin' or 'struct'";  
         $2 }
| structOrBegin error END
    { [] }

opt_signature:
| 
    { None }
| COLON moduleSpecBlock
    { deprecated "Signature types must be given in a .fsi or .mli file" (lhs());
         Some(Sign_explicit($2)) }
| COLON path
    { deprecated "Signature types must be given in a .fsi or .mli file" (lhs());
         Some(Sign_named($2)) }

tyconDefnAugmentation:
| WITH classDefnBlock decl_end
    { $2 }

moduleOrNamespaceSpfn:
| valSpfn
    { $1 }
| opt_attributes opt_decl_visibility moduleIntro colonOrEquals namedModuleAbbrevBlock
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let path,isModule,xml,vis = $3 in 
        if not isModule          then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "namespaces must be declared at the head of a file";
        if List.length path <> 1 then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "a module abbreviation must be a simple name, not a path";
        if List.length $1 <> 0   then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 1) "ignorning attributes on module abbreviation";
        if isSome(vis)           then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 1) "ignorning visibility attribute on module abbreviation. Module abbreviations are always private";
        Spec_module_abbrev(List.hd path,$5,rhs2 3 5) }
| opt_attributes opt_decl_visibility moduleIntro colonOrEquals moduleSpecBlock
    { let path,isModule,xml,vis = $3 in 
        if not isModule          then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "namespaces must be declared at the head of a file";
        if List.length path <> 1 then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "a module definition must be a simple name, not a path";
        let info = ComponentInfo($1,TMK_Module,[],[],path,xml,false,vis,rhs 3) in
        if isSome($2) then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        Spec_module(info,$5,rhs2 3 5) }
| opt_attributes opt_decl_visibility tyconSpfns
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let (TyconSpfn(ComponentInfo(cas,k,a,cs,b,c,d,d2,d3),e,f,g)),rest = 
           match $3 with
           | [] -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) "unexpected empty type definition list"
           | h::t -> h,t in 
        let tc = (TyconSpfn(ComponentInfo($1@cas,k,a,cs,b,c,d,d2,d3),e,f,g))in 
        Spec_tycon (tc::rest,rhs 3) }
| opt_attributes opt_decl_visibility exconSpfn
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let (ExconSpfn(ExconCore(cas,a,b,c,d,d2),e,f)) = $3 in 
        let ec = (ExconSpfn(ExconCore($1@cas,a,b,c,d,d2),e,f)) in 
        Spec_exn(ec, rhs 3) }
| OPEN path
    { Spec_open ($2, rhs2 1 2) }

valSpfn:
| opt_attributes opt_decl_visibility VAL opt_attributes opt_inline opt_mutable opt_access nameop grab_doc opt_explicitValTyparDecls COLON topTypeWithTypeConstraints opt_literalValue
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        (let attr1,attr2,inlineFlag,mutableFlag,vis2,id,doc,explicitValTyparDecls,(ty,arity),konst = ($1),($4),($5),($6),($7),($8),($9),($10),($12),($13) in 
        if attr2 <> [] then warning(Error("This syntactic location for attributes is deprecated. Attributes should be placed before 'val'",rhs 4));
        let m = rhs2 3 12 in 
        let valSpfn = ValSpfn((attr1@attr2),id,explicitValTyparDecls,ty,arity,inlineFlag,mutableFlag,doc, vis2,konst,m) in 
        Spec_val(valSpfn,m))
      }

opt_literalValue:
| 
    { None }
| EQUALS declExpr
    { Some($2) }

moduleSpecBlock:
| OBLOCKBEGIN specifications OBLOCKEND
    { $2 }
| OBLOCKBEGIN sigOrBegin specifications END OBLOCKEND
    { $3 }
| sigOrBegin specifications END
    { $2 }

opt_attributes:
| attributes
    { $1 }
|  %prec prec_opt_attributes_none
    { [] }

attributes:
| attributeList
    { $1 }
| attributeList attributes
    { $1 @ $2 }

attributeList:
| LBRACK_LESS attributeListElements opt_seps GREATER_RBRACK opt_OBLOCKSEP
    {  matchPair 1 4; $2 }

attributeListElements:
| attribute
    { [$1] }
| attributeListElements seps attribute
    { $1 @ [$3] }

attribute:
| path opt_HIGH_PRECEDENCE_APP opt_argExprAfterType
    { let arg = match $3 with None -> mksyn_unit (lhs()) | Some e -> e in 
       Attr($1,arg,None,lhs()) }
| attributeTarget COLON path opt_HIGH_PRECEDENCE_APP opt_argExprAfterType
    { let arg = match $5 with None -> mksyn_unit (lhs()) | Some e -> e in 
       Attr($3,arg,Some $1,lhs()) }

attributeTarget:
| MODULE
    { ident("module",lhs()) }
| TYPE
    { ident("type",lhs()) }
| ident
    { $1 }
| YIELD
    { if $1 then report_parse_error_at (rhs 1) "syntax error";
                         ident("return",lhs()) }

grab_doc:
| 
    { grabXML() }

tyconSpfns:
| TYPE tyconSpfn_list
    { $2 }

tyconSpfn_list:
| tyconSpfn AND tyconSpfn_list
    { $1 :: $3 }
| tyconSpfn
    { [$1] }

tyconSpfn:
| componentInfo EQUALS tyconSpfnRhsBlock
    { $3 $1 }
| componentInfo opt_classSpfn
    { TyconSpfn($1,TyconSpfnRepr_simple (TyconCore_repr_hidden (lhs()),lhs()),$2,lhs()) }

tyconSpfnRhsBlock:
| OBLOCKBEGIN tyconSpfnRhs opt_OBLOCKSEP classSpfnMembers opt_classSpfn OBLOCKEND opt_classSpfn
    { let m = lhs() in 
       (fun nameInfo -> 
           $2 nameInfo (checkForMultipleAugmentations m ($4 @ $5) $7)) }
| tyconSpfnRhs opt_classSpfn
    { let m = lhs() in 
       (fun nameInfo -> 
           $1 nameInfo $2) }

tyconSpfnRhs:
| tyconDefnOrSpfnSimpleRepr
    { let m = lhs() in 
       (fun nameInfo augmentation -> 
           TyconSpfn(nameInfo,TyconSpfnRepr_simple ($1,m),augmentation,m)) }
| tyconClassSpfn
    { let m = lhs() in 
       (fun nameInfo augmentation -> 
           TyconSpfn(nameInfo,TyconSpfnRepr_class (fst $1,snd $1,m),augmentation,m)) }
| DELEGATE OF topType
    { let m = lhs() in 
       let ty,arity = $3 in
       let invoke = ClassMemberSpfn_binding(ValSpfn([],mksyn_id m "Invoke",inferredTyparDecls,ty,arity,false,false,emptyXMLDoc,None,None,m),abstractFlags None MemberKindMember,m) in 
       (fun nameInfo augmentation -> 
           if nonNil augmentation then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "augmentations are not permitted on delegate type definitions";
           TyconSpfn(nameInfo,TyconSpfnRepr_class (TyconDelegate (ty,arity),[invoke],m),[],m)) }

tyconClassSpfn:
| classSpfnBlockKindUnspecified
    { (TyconUnspecified, $1) }
| classOrInterfaceOrStruct classSpfnBlock END
    { ($1,$2) }
| classOrInterfaceOrStruct classSpfnBlock recover
    { report_parse_error_at (rhs 1) "unmatched 'class', 'interface' or 'struct'";
       ($1,$2) }
| classOrInterfaceOrStruct error END
    { (* silent recovery *) ($1,[]) }

classSpfnBlockKindUnspecified:
| OBLOCKBEGIN classSpfnMembers OBLOCKEND
    { $2 }

classSpfnBlock:
| OBLOCKBEGIN classSpfnMembers OBLOCKEND
    { $2 }
| classSpfnMembers
    { $1 }

classSpfnMembers:
| classMemberSpfn opt_seps classSpfnMembers
    { $1 :: $3 }
| 
    { []  }

memberFlags:
| STATIC MEMBER
    { (fun q k -> staticFlags q k) }
| MEMBER
    { (fun q k -> nonVirtualFlags q k) }
| METHOD
    { raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 1) "use 'member x.MyMethod(arg) = ...' to declare a new method" }
| VIRTUAL
    { raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 1) "use 'abstract' to declare a new virtual method slot, and 'default' or 'override' to specify the default implemenation for that slot" }
| OVERRIDE
    { (fun q k -> overrideFlags q k) }
| DEFAULT
    { (fun q k -> overrideFlags q k) }

memberSpecFlags:
| memberFlags
    { $1 }
| ABSTRACT
    { (fun q k -> abstractFlags q k) }
| ABSTRACT MEMBER
    { (fun q k -> abstractFlags q k) }

classMemberSpfnGetSet:
| 
    { (fun arity -> (match arity with TopValSynData([],_) -> MemberKindPropertyGet | _ -> MemberKindMember)) }
| WITH classMemberSpfnGetSetElements
    { (fun arity -> $2) }
| OWITH classMemberSpfnGetSetElements OEND
    { (fun arity -> $2) }
| OWITH classMemberSpfnGetSetElements error
    {  report_parse_error_at (rhs 1) "unmatched 'with' or badly formatted 'with' block";
       (fun arity -> $2) }

classMemberSpfnGetSetElements:
| identop
    { (let (id:ident) = $1 in 
       if id.idText = "get" then MemberKindPropertyGet 
       else if id.idText = "set" then MemberKindPropertySet 
       else raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 1) "'get', 'set' or 'get,set' required") }
| identop COMMA identop
    { let (id:ident) = $1 in 
      if not ((id.idText = "get" && $3.idText = "set") or 
              (id.idText = "set" && $3.idText = "get")) then 
         raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs2 1 3) "'get', 'set' or 'get,set' required";
      MemberKindPropertyGetSet }

classMemberSpfn:
| opt_attributes opt_decl_visibility memberSpecFlags opt_inline grab_doc opt_access nameop opt_explicitValTyparDecls COLON topTypeWithTypeConstraints classMemberSpfnGetSet opt_literalValue
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       let inlineFlag,doc,vis2,id,explicitValTyparDecls,(ty,arity),optLiteralValue = $4,$5,$6,$7,$8,$10,$12 in
       let m = rhs2 3 11 in 
       let valSpfn = ValSpfn($1,id,explicitValTyparDecls,ty,arity, inlineFlag,false,doc, vis2,optLiteralValue,m) in 
       ClassMemberSpfn_binding(valSpfn, $3 (computeOverloadQualifier $1) ($11 arity),m) }
| opt_attributes opt_decl_visibility interfaceMember appType
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       ClassMemberSpfn_interface ($4,rhs2 3 4) }
| opt_attributes opt_decl_visibility INHERIT appType
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       ClassMemberSpfn_inherit ($4,rhs2 3 4) }
| opt_attributes opt_decl_visibility VAL fieldDecl
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       ClassMemberSpfn_field($4 $1 false,rhs2 3 4) }
| opt_attributes opt_decl_visibility STATIC VAL fieldDecl
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       ClassMemberSpfn_field($5 $1 true,rhs2 3 5) }
| opt_attributes opt_decl_visibility STATIC TYPE tyconSpfn
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       ClassMemberSpfn_tycon($5,rhs2 3 5) }
| opt_attributes opt_decl_visibility NEW grab_doc COLON topTypeWithTypeConstraints
    { let vis = $2 in 
       let doc = $4 in
       let ty,arity = $6 in
       let m = rhs2 3 6 in
       let inlineFlag = false in
       let valSpfn = ValSpfn($1,mksyn_id (rhs 3) "new",noInferredTypars,ty,arity,inlineFlag,false, doc, vis,None,m) in
       ClassMemberSpfn_binding(valSpfn, ctorMemFlags  (computeOverloadQualifier $1),m) }

componentInfo:
| opt_attributes grab_doc tyconNameAndTyparDecls opt_typeConstraints
    { startName(rhs 2); 
       let a,b,c,tpcs1,vis = $3 in 
       let tpcs2 = $4 in 
       ComponentInfo($1,TMK_Tycon,a,(tpcs1 @ tpcs2),b,$2,c,vis,rhs2 3 3)  }

tyconDefnList:
| AND tyconDefn tyconDefnList
    { $2 :: $3 }
| 
    { [] }

tyconDefn:
| componentInfo EQUALS tyconDefnRhsBlock
    { let tcDefRepr,members = $3 in
       TyconDefn($1,tcDefRepr,members,lhs()) (* <-- mark changed *) }
| componentInfo opt_HIGH_PRECEDENCE_APP simplePatterns opt_as EQUALS tyconDefnRhsBlock
    { let spats, az,(tcDefRepr,members) = $3,$4,$6 in
       let memberCtorPattern = ClassMemberDefn_implicit_ctor (spats,az,rhs 1) in
       let tcDefRepr = 
         match tcDefRepr with
         | TyconDefnRepr_class (k,cspec,m) -> TyconDefnRepr_class (k,memberCtorPattern::cspec,m)
         | _ -> report_parse_error_at (rhs 1) "Only class types may take value arguments"; tcDefRepr
       in
       TyconDefn($1,tcDefRepr,members,lhs()) (* <-- mark changed *) }

tyconDefnRhsBlock:
| OBLOCKBEGIN tyconDefnRhs opt_OBLOCKSEP classDefnMembers opt_classDefn OBLOCKEND opt_classDefn
    { let m = lhs() in 
       $2 (checkForMultipleAugmentations m ($4 @ $5) $7) }
| tyconDefnRhs opt_classDefn
    { let m = lhs() in 
       $1 $2 }

tyconDefnRhs:
| tyconDefnOrSpfnSimpleRepr
    { let m = lhs() in (fun augmentation -> TyconDefnRepr_simple ($1,m),augmentation) }
| tyconClassDefn
    { let m = lhs() in (fun augmentation -> TyconDefnRepr_class (fst $1,snd $1,m),augmentation) }
| DELEGATE OF topType
    { let m = lhs() in 
       let ty,arity = $3 in
       (fun augmentation -> 
           let valSpfn = ValSpfn([],mksyn_id m "Invoke",inferredTyparDecls,ty,arity,false,false,emptyXMLDoc,None,None,m) in 
           let invoke = ClassMemberDefn_slotsig(valSpfn,abstractFlags None MemberKindMember,m) in 
           if nonNil augmentation then raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY m "augmentations are not permitted on delegate type definitions";
           TyconDefnRepr_class (TyconDelegate (ty,arity),[invoke],m),[]) }

tyconClassDefn:
| classDefnBlockKindUnspecified
    { (TyconUnspecified, $1) }
| classOrInterfaceOrStruct classDefnBlock END
    { ($1,$2) }
| classOrInterfaceOrStruct classDefnBlock recover
    { report_parse_error_at (rhs 1) "unmatched 'class', 'interface' or 'struct'";
       ($1,$2) }
| classOrInterfaceOrStruct error END
    { (* silent recovery *) ($1,[]) }

classDefnBlockKindUnspecified:
| OBLOCKBEGIN classDefnMembers OBLOCKEND
    { $2 }

classDefnBlock:
| OBLOCKBEGIN classDefnMembers OBLOCKEND
    { $2 }
| classDefnMembers
    { $1 }

classDefnMembers:
| classDefnMember opt_seps classDefnMembers
    { $1 @  $3 }
| error classDefnMembers
    { $2 }
| 
    { [] }

classDefnMemberGetSet:
| WITH classDefnMemberGetSetElements
    { $2  }
| OWITH classDefnMemberGetSetElements OEND
    { $2  }
| OWITH classDefnMemberGetSetElements error
    { report_parse_error_at (rhs 1) "unmatched 'with' or badly formatted 'with' block";
       $2  }

classDefnMemberGetSetElements:
| classDefnMemberGetSetElement
    { [$1]  }
| classDefnMemberGetSetElement AND classDefnMemberGetSetElement
    { [$1;$3] }

classDefnMemberGetSetElement:
| opt_inline bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS typedSeqExprBlock
    { ($1,$2,$3,$5,rhs 5) }

memberCore:
| opt_inline bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS typedSeqExprBlock
    {  let wholem = rhs2 2 5 in 
        let bindm = rhs 2 in 
        let rhsm = rhs 5 in 
        let mpat = rhs 2 in 
        let optReturnType = $3 in 
        let bindingBuilder = $2 in 
        (fun vis memflags attrs -> 
             [ ClassMemberDefn_member_binding (bindingBuilder vis $1 false bindm wholem optReturnType $5 rhsm [] attrs (Some (memflags (computeOverloadQualifier attrs) MemberKindMember)),bindm) ]) }
| opt_inline bindingPattern opt_topReturnTypeWithTypeConstraints classDefnMemberGetSet
    { let wholem = rhs2 2 4 in 
       let bindm = rhs 2 in 
       let propertyNameBindingBuilder = $2 in 
       let optPropertyType = $3 in 
       let mutableFlag = false in
       (fun vis memflags attrs -> 
             $4 |> List.map (fun (optInline,bindingBuilder,optReturnType,expr,exprm) ->
                   let optInline = $1 || optInline in 
                   let overloadQualifier =  (computeOverloadQualifier attrs) in 
                   
                   let binding = bindingBuilder vis optInline mutableFlag bindm wholem optReturnType expr exprm [] attrs (Some (memflags overloadQualifier MemberKindMember)) in
                   let (Binding (vis,_,pseudo,_,attrs,doc,memberInfo,pv,_,bindm)) = binding in 
                   let memkind = 
                         let getset = 
                               let rec go p = 
                                   match p with 
                                   | Pat_lid ([id],_,_,_,_) ->  id.idText
                                   | Pat_as (_,nm,_,_,_) ->  nm.idText
                                   | Pat_typed (p,_,_) ->  go p
                                   | Pat_attrib (p,_,_) ->  go p
                                  | _ -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY bindm "invalid declaration syntax"  in
                               go pv in 
                         if getset = "get" then MemberKindPropertyGet 
                         else if getset = "set" then MemberKindPropertySet 
                         else raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY bindm "get and/or set required" in


                   (* REVIEW: It's hard not to ignore the optPropertyType type annotation for 'set' properties. To apply it, *)
                   (* we should apply it to the last argument, but at this point we've already pushed the patterns that *)
                   (* make up the arguments onto the RHS. So we just always give a warning. *)

                   begin match optPropertyType with 
                   | Some _ -> warning(Error("type annotations on property getters and setters should be given after the 'get()' or 'set(v)', e.g. 'with get() : string = ...'",bindm))
                   | None -> ()
                   end;
                   
                   let optReturnType = 
                       match (memkind, optReturnType) with 
                       | MemberKindPropertySet,_ -> optReturnType
                       | _, None -> optPropertyType
                       | _ -> optReturnType in 

                   (* REDO with the correct member kind *)
                   let binding = bindingBuilder vis pseudo mutableFlag bindm wholem optReturnType expr exprm [] attrs (Some (memflags overloadQualifier memkind)) in 
                   let (Binding (vis,_,pseudo,_,attrs,doc,memberInfo,pv,rhs_after_pats,bindm)) = binding in 
                
                   let arity = 
                       match memberInfo with 
                       | None -> 
                           raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY bindm "unexpected empty memberInfo" 
                       | Some (_,x,_) -> x in  
                   let meminfo = Some (memflags overloadQualifier memkind, arity,None) in 

                   (* Create the binding from the first lambda pattern in order to extract out the pattern of the *)
                   (* 'this' variable and hack it into the pattern for the get/set binding, replacing the get/set part *)
                   (* A little gross. *)
                   let pv',doc' = 
                       let binding2 = propertyNameBindingBuilder vis optInline mutableFlag bindm bindm optReturnType expr exprm [] attrs (Some (memflags overloadQualifier MemberKindMember)) in
                       let (Binding (_,_,_,_,_,doc2,_,pv2,_,_)) = binding2 in 
                   
                       let lid2 = 
                           match pv2 with 
                           | Pat_lid (lid,None,[],_,m) ->  lid
                           | p -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY bindm "invalid declaration syntax"  in
                   
                       let rec go p = 
                           match p with 
                           | Pat_lid ([id],tyargs,args,vis,m) ->  Pat_lid (lid2,tyargs,args,vis,m)
                           | Pat_as (p2,nm,_,vis,m) ->  Pat_lid (lid2,None,[],vis,m)
                           | Pat_typed (p,ty,m) ->  Pat_typed(go p,ty,m)
                           | Pat_attrib (p,attribs,m) ->  Pat_attrib(go p,attribs,m)
                           | Pat_wild(m) ->  Pat_wild(m)
                           | _ -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY bindm "invalid declaration syntax"  in
                       go pv,xmlDocMerge doc2 doc in

               ClassMemberDefn_member_binding (Binding (vis,NormalBinding,pseudo,mutableFlag,attrs,doc',meminfo,pv',rhs_after_pats,bindm),bindm)))
       }

abstractMemberFlags:
| ABSTRACT
    {}
| ABSTRACT MEMBER
    {}

classDefnMember:
| opt_attributes opt_decl_visibility defnBindings
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       [mkClassMemberLocalBindings false (rhs2 3 3) $1 $2 $3] }
| opt_attributes opt_decl_visibility hardwhiteDefnBindings
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       [mkClassMemberLocalBindings false (rhs2 3 3) $1 $2 $3] }
| opt_attributes opt_decl_visibility doBinding
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        let wholem = rhs 3 in 
        [ mkClassMemberLocalBindings false (rhs 3 ) $1 $2 $3 ] }
| opt_attributes opt_decl_visibility STATIC defnBindings
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       [mkClassMemberLocalBindings true (rhs2 3 3) $1 $2 $4] }
| opt_attributes opt_decl_visibility STATIC hardwhiteDefnBindings
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       [mkClassMemberLocalBindings true (rhs2 3 3) $1 $2 $4] }
| opt_attributes opt_decl_visibility STATIC doBinding
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       [mkClassMemberLocalBindings true (rhs2 3 3) $1 $2 $4] }
| opt_attributes opt_decl_visibility memberFlags memberCore opt_ODECLEND
    { if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
       $4 $2 $3 $1 }
| opt_attributes opt_decl_visibility interfaceMember appType opt_interfaceImplDefn
    {  if $1 <> [] then warning(Error("attributes ignored on interface implementation",rhs 1));
        if isSome $2 then errorR(Error("interfaces always have the same visibility as the enclosing type",rhs 3));
        [ ClassMemberDefn_interface ($4, $5,rhs2 3 5) ] }
| opt_attributes opt_decl_visibility abstractMemberFlags opt_inline grab_doc nameop opt_explicitValTyparDecls COLON topTypeWithTypeConstraints classMemberSpfnGetSet opt_ODECLEND
    { let ty,arity = $9 in
       let inlineFlag,doc,id,explicitValTyparDecls = $4,$5,$6,$7 in
       let m = rhs2 3 10 in
       if isSome $2 then errorR(Error("abstract slots always have the same visibility as the enclosing type",m));
       let valSpfn = ValSpfn($1,id,explicitValTyparDecls,ty,arity, inlineFlag,false,doc, None,None,m) in
       [ ClassMemberDefn_slotsig(valSpfn,abstractFlags (computeOverloadQualifier $1) ($10 arity), m) ] }
| opt_attributes opt_decl_visibility inheritsDefn
    {  if $1 <> [] then warning(Error("attributes ignored on 'inherits' declaration",rhs 1));
        if isSome $2 then errorR(Error("visibility declarations are not permitted on an 'inherits' declaration",rhs 1));
        [ $3 ] }
| opt_attributes opt_decl_visibility VAL fieldDecl
    {  if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        [ ClassMemberDefn_field($4 $1 false,rhs2 3 4) ] }
| opt_attributes opt_decl_visibility STATIC VAL fieldDecl
    {  if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        [ ClassMemberDefn_field($5 $1 true,rhs2 3 5) ] }
| opt_attributes opt_decl_visibility NEW atomicPattern opt_as grab_doc EQUALS typedSeqExprBlock opt_ODECLEND
    {  let m = rhs2 3 8 in 
        let expr = $8 in
        let info = Some (ctorMemFlags (computeOverloadQualifier $1), TopValSynData([SynArgInfo.argdata_of_pat $4],SynArgInfo.unnamedRetVal), $5) in 
        let vis = $2 in 
        [ ClassMemberDefn_member_binding(Binding (None,NormalBinding,false,false,$1,$6,info, Pat_lid ([mksyn_id (rhs 3) "new"],Some noInferredTypars,[$4],vis,rhs 3),BindingExpr([],None,expr),m),m) ] }
| opt_attributes opt_decl_visibility STATIC TYPE tyconDefn
    {  if isSome $2 then errorR(Error("visibility declarations should come immediately prior to the identifier naming a construct",rhs 2));
        [ ClassMemberDefn_tycon($5,None,rhs2 3 5) ] }

atomicPatternLongIdent:
| pathop
    { (None,$1) }
| access pathop
    { (Some($1), $2) }

opt_access:
| 
    { None }
| access
    { Some($1) }

access:
| PRIVATE
    { accessPrivate }
| PUBLIC
    { (accessPublic) }
| INTERNAL
    { accessInternal }

opt_decl_visibility:
| access
    { Some($1) }
| 
    { None }

opt_interfaceImplDefn:
| WITH objectImplementationBlock decl_end
    { Some($2) }
| 
    { None }

opt_classDefn:
| WITH classDefnBlock decl_end
    { $2 }
| 
    { [] }

opt_classSpfn:
| WITH classSpfnBlock decl_end
    { $2 }
| 
    { [] }

inheritsDefn:
| INHERIT appType opt_as
    {  ClassMemberDefn_inherit($2,$3,lhs()) }
| INHERIT appType opt_HIGH_PRECEDENCE_APP argExprAfterType opt_as
    {  ClassMemberDefn_implicit_inherit($2,$4,$5,lhs()) }

opt_as:
| asSpec
    { Some($1) }
| 
    { None }

asSpec:
| AS ident
    { startName(rhs 2); $2 }

objectImplementationBlock:
| OBLOCKBEGIN objectImplementationMembers OBLOCKEND
    { $2 }
| objectImplementationMembers
    { $1 }

objectImplementationMembers:
| objectImplementationMember opt_seps objectImplementationMembers
    { $1 @  $3 }
| objectImplementationMember opt_seps
    { $1 }

objectImplementationMember:
| opt_attributes memberOrOverride memberCore opt_ODECLEND
    { $3 None overrideFlags $1 }
| opt_attributes memberOrOverride error
    { [] }

memberOrOverride:
| MEMBER
    {}
| OVERRIDE
    {}

tyconDefnOrSpfnSimpleRepr:
| typ
    { TyconCore_abbrev ($1, lhs()) }
| unionRepr
    { if List.exists (function Choice1 _ -> true | _ -> false) $1 then 
           TyconCore_enum (chooseList (function Choice1 data -> Some(data) | Choice2(UnionConstr(_,_,_,_,_,m)) -> errorR(Error("All enum fields must be given values",m)); None) $1,lhs())
       else 
           TyconCore_funion (chooseList (function Choice2 data -> Some(data) | Choice1 _ -> failwith "huh?") $1,lhs()) }
| braceFieldDeclList
    { TyconCore_recd ($1,lhs()) }
| LPAREN inlineAssemblyTyconRepr RPAREN
    {  libraryOnly (lhs());
        matchPair 1 3;  
        $2 }

braceFieldDeclList:
| LBRACE recdFieldDeclList RBRACE
    { matchPair 1 3;   $2 }
| LBRACE recdFieldDeclList recover
    { $2 }
| LBRACE error RBRACE
    { matchPair 1 3;   [] }

inlineAssemblyTyconRepr:
| HASH STRING opt_HASH
    { libraryOnly (lhs());
       let lhsm = lhs() in 
       TyconCore_asm (parse_il_typ $2 (rhs 2),lhsm) }

classOrInterfaceOrStruct:
| CLASS
    { TyconClass }
| INTERFACE
    { TyconInterface }
| STRUCT
    { TyconStruct }

interfaceMember:
| INTERFACE
    { }
| OINTERFACE_MEMBER
    { }

tyconNameAndTyparDecls:
| opt_access path
    { startName(rhs 2); [], $2,false,[],$1 }
| opt_access prefixTyparDecls path
    {startName(rhs 3);  $2, $3,false,[],$1 }
| opt_access path postfixTyparDecls
    { startName(rhs 2); 
        let tps,tpcs = $3 in 
        tps, $2,true,tpcs,$1 }

prefixTyparDecls:
| typar
    { [ TyparDecl([],$1) ] }
| LPAREN prefixTyparDeclList RPAREN
    {  matchPair 1 3; List.rev $2 }

prefixTyparDeclList:
| prefixTyparDeclList COMMA typarDecl
    { $3 :: $1 }
| typarDecl
    { [$1] }

typarDecl:
| opt_attributes typar
    { TyparDecl($1,$2) }

postfixTyparDecls:
| opt_HIGH_PRECEDENCE_TYAPP LESS prefixTyparDeclList opt_typeConstraints GREATER
    { List.rev $3, $4 }

explicitValTyparDeclsCore:
| prefixTyparDeclList COMMA DOT_DOT
    { deprecated "this declaration form is deprecated. Either specify all relevant type parameters or none" (lhs());
        (List.rev $1,true) }
| DOT_DOT
    { deprecated "this declaration form is deprecated. Either specify all relevant type parameters or none" (lhs());
        ([],true) }
| prefixTyparDeclList
    { (List.rev $1,false) }
| 
    { ([],false) }

explicitValTyparDecls:
| opt_HIGH_PRECEDENCE_TYAPP LESS explicitValTyparDeclsCore opt_typeConstraints GREATER
    { let tps,flex = $3 in 
         ValTyparDecls(tps,flex,$4) }

opt_explicitValTyparDecls:
| explicitValTyparDecls
    { $1 }
| 
    { ValTyparDecls([],true,[]) }

opt_explicitValTyparDecls2:
| explicitValTyparDecls
    { Some $1 }
| 
    { None }

opt_typeConstraints:
| 
    { [] }
| WHEN typeConstraints
    { List.rev $2 }

typeConstraints:
| typeConstraints AND typeConstraint
    { $3 :: $1 }
| typeConstraint
    { [$1] }

typeConstraint:
| DEFAULT typar COLON typ
    { libraryOnly (lhs()); WhereTyparDefaultsToType($2,$4,lhs()) }
| typar COLON_GREATER typ
    { WhereTyparSubtypeOfType($1,$3,lhs()) }
| typar COLON STRUCT
    { WhereTyparIsValueType($1,lhs()) }
| typar COLON IDENT STRUCT
    { if $3 <> "not" then report_parse_error_at (rhs 3) ("unexpected identifier: '"^ $3 ^"'");  
        WhereTyparIsReferenceType($1,lhs()) }
| typar COLON NULL
    { WhereTyparSupportsNull($1,lhs()) }
| typar COLON LPAREN classMemberSpfn RPAREN
    { WhereTyparSupportsMember([ $1 ],$4,lhs()) }
| LPAREN typar OR typar RPAREN COLON LPAREN classMemberSpfn RPAREN
    { WhereTyparSupportsMember([ $2 ; $4 ],$8,lhs()) }
| typar COLON DELEGATE typeArgs
    { WhereTyparIsDelegate($1,$4,lhs()) }
| typar COLON IDENT typeArgs
    { match $3 with 
        | "enum" -> WhereTyparIsEnum($1,$4,lhs())
        | nm -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 3) ("unexpected identifier: '"^ nm ^"'") }

unionRepr:
| BAR attrUnionCaseDecls
    { $2 }
| firstUnionCaseDeclOfMany BAR attrUnionCaseDecls
    { $1 :: $3 }
| firstUnionCaseDecl
    { [$1] }

attrUnionCaseDecls:
| attrUnionCaseDecl BAR attrUnionCaseDecls
    { $1 :: $3 }
| attrUnionCaseDecl
    { [ $1 ] }

attrUnionCaseDecl:
| opt_attributes opt_access grab_doc unionCaseName opt_OBLOCKSEP
    { startName(rhs 1); Choice2 (UnionConstr ( $1, $4,ConstrFields [],$3,$2,rhs 4)) }
| opt_attributes opt_access grab_doc unionCaseName OF unionCaseRepr opt_OBLOCKSEP
    { startName(rhs 1); Choice2 (UnionConstr ( $1, $4,ConstrFields $6,$3,$2,rhs2 4 6)) }
| opt_attributes opt_access grab_doc unionCaseName COLON topType opt_OBLOCKSEP
    { libraryOnly(lhs());
        startName(rhs 1); Choice2 (UnionConstr ( $1, $4,ConstrFullType $6,$3,$2,rhs2 4 6)) }
| opt_attributes opt_access grab_doc unionCaseName EQUALS constant opt_OBLOCKSEP
    { if isSome $2 then errorR(Error("visibility declarations are not permitted on enumeration fields",rhs 2));
        startName(rhs 1); 
        Choice1 (EnumConstr ( $1, $4,$6,$3,rhs2 4 6)) }

unionCaseName:
| nameop
    { $1 }
| LPAREN COLON_COLON RPAREN
    {  matchPair 1 3; ident(opname_Cons,rhs 2) }
| LPAREN LBRACK RBRACK RPAREN
    {  matchPair 1 4; ident(opname_Nil,rhs2 2 3) }

firstUnionCaseDeclOfMany:
| ident opt_OBLOCKSEP
    { startName(rhs 1); Choice2 (UnionConstr ( [], $1,ConstrFields [],emptyXMLDoc,None,lhs())) }
| ident EQUALS constant opt_OBLOCKSEP
    { startName(rhs 1); Choice1 (EnumConstr ([],$1,$3,emptyXMLDoc,lhs())) }
| firstUnionCaseDecl opt_OBLOCKSEP
    { $1 }

firstUnionCaseDecl:
| ident OF unionCaseRepr
    { startName(rhs 1); Choice2 (UnionConstr ( [],$1,ConstrFields $3,emptyXMLDoc,None,lhs())) }

unionCaseRepr:
| braceFieldDeclList
    { warning(Error("This declaration form is deprecated. Consider using a separate record type instead",lhs())); $1 }
| appType STAR tupleTypeElements
    { List.map anon_field_of_typ ($1 :: $3) }
| appType
    { [anon_field_of_typ $1] }

recdFieldDeclList:
| recdFieldDecl seps recdFieldDeclList
    { $1 :: $3 }
| recdFieldDecl opt_seps
    { [$1] }

recdFieldDecl:
| opt_attributes fieldDecl
    { $2 $1 false }

fieldDecl:
| opt_mutable opt_access ident grab_doc COLON polyType
    { startName(rhs 3); 
       let rhsm = rhs2 3 6 in 
       (fun attrs stat -> Field(attrs, stat,Some $3,$6,$1,$4,$2,rhsm)) }

exconDefn:
| exconCore opt_classDefn
    { ExconDefn($1,$2, lhs()) }

exconSpfn:
| exconCore opt_classSpfn
    { ExconSpfn($1,$2,lhs()) }

exconCore:
| EXCEPTION opt_attributes grab_doc opt_access exconIntro exconRepr
    { ExconCore($2,$5, $6,$3,$4,lhs()) }

exconIntro:
| ident
    { startName(rhs 1); UnionConstr ( [], $1,ConstrFields [],emptyXMLDoc,None,lhs()) }
| ident OF unionCaseRepr
    { startName(rhs 1); UnionConstr ( [], $1,ConstrFields $3,emptyXMLDoc,None,lhs()) }

exconRepr:
| 
    { None }
| EQUALS path
    { Some ($2) }

openDecl:
| OPEN path
    { $2 }

defnBindings:
| LET opt_rec localBindings
    { let letm = rhs 1 in 
        let isUse,isRec,bindingsPreAttrs = $1,$2,$3 in 
        (* the first binding swallow any attributes prior to the 'let' *)
        rhs 1,isRec,isUse,(fun attrs vis -> [],bindingsPreAttrs attrs vis) }
| cPrototype
    { lhs(), false,false,$1  }

doBinding:
| DO typedSeqExprBlock
    { let letm = rhs 1 in 
        let wholem = rhs2 1 2 in 
        (* any attributes prior to the 'let' are left free, e.g. become top-level attributes *)
        (* associated with the module, 'main' function or assembly depending on their target *)
        letm,false,false,(fun attrs vis -> attrs,[mk_Do (true,$2,wholem)]) }

hardwhiteLetBindings:
| OLET opt_rec localBindings hardwhiteDefnBindingsTerminator
    { $4 (rhs 1);  (* report unterminated error *)
        let letm = rhs 1 in 
        let isUse,isRec,bindingsPreAttrs = $1,$2,$3 in 
        (* the first binding swallow any attributes prior to the 'let' *)
        letm,isRec,isUse,(fun attrs vis -> [],bindingsPreAttrs attrs vis) }

hardwhiteDoBinding:
| ODO typedSeqExprBlock hardwhiteDefnBindingsTerminator
    { $3 (rhs 1);  (* report unterminated error *)
        let letm = rhs 1 in 
        let wholem = rhs2 1 2 in 
        (* any attributes prior to the 'let' are left free, e.g. become top-level attributes *)
        (* associated with the module, 'main' function or assembly depending on their target *)
        letm,false,false,(fun attrs vis -> attrs,[mk_Do (true,$2,wholem)]) }

hardwhiteDefnBindings:
| hardwhiteLetBindings
    { $1 }
| hardwhiteDoBinding
    { $1 }

hardwhiteDefnBindingsTerminator:
| ODECLEND
    { (fun m -> ()) }
| recover
    { (fun m -> report_parse_error_at m "unmatched 'let' or 'do'") }

cPrototype:
| EXTERN cRetType opt_access ident opt_HIGH_PRECEDENCE_APP LPAREN cArgs RPAREN
    { let rty,vis,nm,args  = $2,$3,$4,$7 in 
        let nmm = rhs 4 in 
        let argsm = rhs 7 in 
        let bindm = lhs() in
        let wholem = lhs() in
        let rhsm = lhs() in 
        let rhsexpr = Expr_app(Expr_lid_get(false,[ident("failwith",rhsm)],rhsm),Expr_const(Const_string(Bytes.string_as_unicode_bytes "extern was not given a DllImport attribute",rhsm),rhsm),rhsm) in
        (fun attrs vis -> [], [mksyn_binding (grabXML(),Pat_lid ([nm],Some(noInferredTypars),[Pat_tuple(args,argsm)],vis,nmm)) vis false false bindm wholem (Some(rty)) rhsexpr rhsm [] attrs None]) }

cArgs:
| cMoreArgs
    { List.rev $1 }
| cArg
    { [$1] }
| 
    { [] }

cMoreArgs:
| cMoreArgs COMMA cArg
    { $3 :: $1 }
| cArg COMMA cArg
    { [$3; $1] }

cArg:
| opt_attributes cType
    { let m = lhs() in Pat_typed(Pat_wild m,$2,m) |> addAttribs $1 }
| opt_attributes cType ident
    { let m = lhs() in Pat_as (Pat_typed(Pat_wild m,$2,m),$3,false,None,m) |> addAttribs $1 }

cType:
| ident
    { let m = lhs() in Type_app([$1],[],m) }
| cType opt_HIGH_PRECEDENCE_APP LBRACK RBRACK
    { let m = lhs() in Type_app([ident("[]",m)],[$1],m) }
| cType STAR
    { let m = lhs() in Type_app([ident("nativeptr",m)],[$1],m) }
| cType AMP
    { let m = lhs() in Type_app([ident("byref",m)],[$1],m) }
| VOID STAR
    { let m = lhs() in Type_app([ident("nativeint",m)],[],m) }

cRetType:
| opt_attributes cType
    { ($2,TopArgSynData($1,false,None)),rhs 2 }
| opt_attributes VOID
    { let m = rhs 2 in (Type_app([ident("unit",m)],[],m),TopArgSynData($1,false,None)),m }

localBindings:
| attr_localBinding more_localBindings
    { (fun attrs vis -> 
           match $1 with 
           | Some x -> (x attrs vis None true ::  $2) 
           | None -> $2) }

more_localBindings:
| AND attr_localBinding more_localBindings
    { (match $2 with Some x -> x [] None None false :: $3 | None -> $3) }
|  %prec prec_no_more_attr_bindings
    { [] }

attr_localBinding:
| DO typedSeqExprBlock
    { let m = rhs2 1 2 in 
        Some(fun _ _ _ isFirst -> 
          if isFirst then deprecated "Consider using 'let _ = expr in expr' or simply 'expr; expr' instead" m;
          mk_Do (true,$2,m)) }
| opt_attributes localBinding
    { Some(fun attrs vis memberInfo isFirst -> 
          $2 (attrs@$1) vis memberInfo) }
| error
    { None }

localBinding:
| opt_inline opt_mutable bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS typedExprWithStaticOptimizationsBlock
    { let bindm = rhs 3 in 
        let wholem = rhs 6 in 
        let expr,opts = $6 in
        let rhsm = rhs 6 in 
        let optReturnType = $4 in 
        let bindingBuilder = $3 in 
        (fun attrs vis memberInfo -> 
            bindingBuilder vis $1 $2 bindm wholem optReturnType expr rhsm opts attrs memberInfo) }
| opt_inline opt_mutable bindingPattern opt_topReturnTypeWithTypeConstraints EQUALS error
    { let bindm = rhs 3 in 
        let wholem = rhs2 3 5 in 
        let rhsm = rhs 5 in
        let optReturnType = $4 in 
        let bindingBuilder = $3 in 
        (fun attrs vis memberInfo -> 
            bindingBuilder vis $1 $2 bindm wholem optReturnType (arbExpr()) rhsm [] attrs memberInfo)  }

typedExprWithStaticOptimizationsBlock:
| OBLOCKBEGIN typedExprWithStaticOptimizations OBLOCKEND
    { $2 }
| typedExprWithStaticOptimizations
    { $1 }

typedExprWithStaticOptimizations:
| typedSeqExpr opt_staticOptimizations
    { $1,$2 }

opt_staticOptimizations:
| opt_staticOptimizations staticOptimization
    { $2 :: $1 }
| 
    { [] }

staticOptimization:
| WHEN staticOptimizationConditions EQUALS typedSeqExpr
    { ($2,$4) }

staticOptimizationConditions:
| staticOptimizationConditions AND staticOptimizationCondition
    { $3 :: $1 }
| staticOptimizationCondition
    { [$1 ] }

staticOptimizationCondition:
| typar COLON typ
    { WhenTyparTyconEqualsTycon($1,$3,lhs()) }

constant:
| INT8
    { Const_int8 $1 }
| UINT8
    { Const_uint8 $1 }
| INT16
    { Const_int16 $1 }
| UINT16
    { Const_uint16 $1 }
| INT32
    { Const_int32 $1 }
| UINT32
    { Const_uint32 $1 }
| INT64
    { Const_int64 $1 }
| UINT64
    { Const_uint64 $1 }
| NATIVEINT
    { Const_nativeint $1 }
| UNATIVEINT
    { Const_unativeint $1 }
| IEEE32
    { Const_float32 $1 }
| IEEE64
    { Const_float $1 }
| CHAR
    { Const_char $1 }
| BIGINT
    { Const_bigint $1 }
| DECIMAL
    { Const_decimal $1 }
| BIGNUM
    { Const_bignum $1 }
| STRING
    { Const_string ($1,lhs()) }
| BYTEARRAY
    { Const_bytearray ($1,lhs()) }

bindingPattern:
| headBindingPattern grab_doc
    {  mksyn_binding ($2,$1) }

simplePattern:
| ident
    { startName(rhs 1); SPat_as ($1,false,false,rhs 1) }
| QMARK ident
    { startName(rhs 2); SPat_as ($2,false,true,rhs 2) }
| simplePattern COLON typeWithTypeConstraints
    { let lhsm = lhs() in 
        SPat_typed($1,$3,lhsm) }
| attributes simplePattern %prec paren_pat_attribs
    { let lhsm = lhs()  in
        SPat_attrib($2,$1,lhsm) }

simplePatternCommaList:
| simplePattern
    { [$1] }
| simplePattern COMMA simplePatternCommaList
    { $1 :: $3 }

simplePatterns:
| LPAREN simplePatternCommaList RPAREN
    { $2 }
| LPAREN RPAREN
    { [] }
| LPAREN simplePatternCommaList recover
    { report_parse_error_at (rhs 1) "unmatched '('"; [] }
| LPAREN error RPAREN
    { (* silent recovery *) [] }
| LPAREN recover
    {  report_parse_error_at (rhs 1) "unmatched '('"; [] }

headBindingPattern:
| headBindingPattern AS ident
    { startName(rhs 3); Pat_as ($1,$3,false,None,rhs2 1 3) }
| headBindingPattern BAR headBindingPattern
    { Pat_disj($1,$3,rhs2 1 3) }
| headBindingPattern COLON_COLON headBindingPattern
    { Pat_lid (mksyn_constr (rhs2 1 3) opname_Cons, None,[Pat_tuple ([$1;$3],rhs2 1 3)],None,lhs()) }
| tuplePatternElements %prec pat_tuple
    { Pat_tuple(List.rev $1, lhs()) }
| conjPatternElements %prec pat_conj
    { Pat_conjs(List.rev $1, lhs()) }
| constrPattern
    { $1 }

tuplePatternElements:
| tuplePatternElements COMMA headBindingPattern
    { $3 :: $1 }
| headBindingPattern COMMA headBindingPattern
    { $3 :: $1 :: [] }

conjPatternElements:
| conjPatternElements AMP headBindingPattern
    { $3 :: $1 }
| headBindingPattern AMP headBindingPattern
    { $3 :: $1 :: [] }

constrPattern:
| atomicPatternLongIdent explicitValTyparDecls
    { let vis,lid = $1 in Pat_lid (lid,Some $2,[],vis,lhs()) }
| atomicPatternLongIdent opt_explicitValTyparDecls2 atomicPatterns %prec pat_app
    { let vis,lid = $1 in Pat_lid (lid,$2,$3,vis,lhs()) }
| atomicPatternLongIdent opt_explicitValTyparDecls2 HIGH_PRECEDENCE_APP atomicPatterns
    { let vis,lid = $1 in Pat_lid (lid,$2,$4,vis,lhs()) }
| COLON_QMARK atomType %prec pat_isinst
    { Pat_isinst($2,lhs()) }
| atomicPattern
    { $1 }

atomicPatterns:
| atomicPattern atomicPatterns %prec pat_args
    { $1 :: $2 }
| atomicPattern HIGH_PRECEDENCE_APP atomicPatterns
    { report_parse_error_at (rhs 1) "Successive patterns should be separated by spaces or tupled";
        $1 :: $3 }
| atomicPattern
    { [$1] }

atomicPattern:
| quoteExpr
    { Pat_expr($1,lhs()) }
| CHAR DOT_DOT CHAR
    { Pat_range ($1,$3,rhs2 1 3) }
| LBRACE recordPatternElements RBRACE
    { $2 }
| LBRACK listPatternElements RBRACK
    { matchPair 1 3; Pat_array_or_list(false,$2,lhs()) }
| LBRACK_BAR listPatternElements BAR_RBRACK
    { matchPair 1 3; Pat_array_or_list(true,$2, lhs()) }
| UNDERSCORE
    { Pat_wild (lhs()) }
| MINUS INT32
    { Pat_const (Const_int32 (Int32.neg $2),lhs()) }
| ADJACENT_PREFIX_PLUS_MINUS_OP INT32
    { match $1 with 
        | "-" -> Pat_const (Const_int32 (Int32.neg $2),lhs()) 
        | "+" -> Pat_const (Const_int32 $2,lhs()) 
        | _ -> report_parse_error_at (rhs 1) "syntax error";
               Pat_const (Const_int32 $2,lhs()) }
| QMARK ident
    { Pat_opt_var($2,lhs()) }
| atomicPatternLongIdent %prec prec_atompat_pathop
    { let vis,lid = $1 in 
        if List.length lid > 1 or (let c= String.get (List.hd lid).idText 0 in Char.uppercase c = c)  
        then mksyn_pat_maybe_var lid vis (lhs())
        else mksyn_pat_var vis (List.hd lid) }
| constant
    { Pat_const ($1,range_of_synconst $1 (lhs())) }
| FALSE
    { Pat_const(Const_bool false,lhs()) }
| TRUE
    { Pat_const(Const_bool true,lhs()) }
| NULL
    { Pat_null(lhs()) }
| LPAREN parenPatternBody RPAREN
    {  matchPair 1 3; let m = (lhs()) in Pat_paren($2 m,m) }
| LPAREN parenPatternBody recover
    { report_parse_error_at (rhs 1) "unmatched '('"; $2 (rhs2 1 2) }
| LPAREN error RPAREN
    { (* silent recovery *) Pat_wild (lhs()) }
| LPAREN recover
    {  report_parse_error_at (rhs 1) "unmatched '('"; Pat_wild (lhs())}

parenPatternBody:
| parenPattern
    { (fun m -> $1) }
| 
    { (fun m -> Pat_const(Const_unit,m)) }

parenPattern:
| parenPattern AS ident
    { startName(rhs 3); Pat_as ($1,$3,false,None,rhs2 1 3) }
| parenPattern BAR parenPattern
    { Pat_disj($1,$3,rhs2 1 3) }
| tupleParenPatternElements
    { Pat_tuple(List.rev $1,lhs()) }
| conjParenPatternElements
    { Pat_conjs(List.rev $1,rhs2 1 3) }
| parenPattern COLON typeWithTypeConstraints %prec paren_pat_colon
    { let lhsm = lhs() in 
        Pat_typed($1,$3,lhsm) }
| attributes parenPattern %prec paren_pat_attribs
    { let lhsm = lhs()  in
        Pat_attrib($2,$1,lhsm) }
| parenPattern COLON_COLON parenPattern
    { Pat_lid (mksyn_constr (rhs2 1 3) opname_Cons, None, [ Pat_tuple ([$1;$3],rhs2 1 3) ],None,lhs()) }
| parenPattern COLON_GREATER typ
    { let lhsm = lhs() in 
        Pat_typed($1, mksyn_anon_constraint $3 lhsm,lhsm) }
| constrPattern
    { $1 }

tupleParenPatternElements:
| tupleParenPatternElements COMMA parenPattern
    { $3 :: $1 }
| parenPattern COMMA parenPattern
    { $3 :: $1 :: [] }

conjParenPatternElements:
| conjParenPatternElements AMP parenPattern
    { $3 :: $1 }
| parenPattern AMP parenPattern
    { $3 :: $1 :: [] }

recordPatternElements:
| path EQUALS parenPattern moreRecordPatternElements
    { Pat_recd ((frontAndBack $1,$3) :: List.rev $4,lhs()) }

moreRecordPatternElements:
| moreRecordPatternElements seps path EQUALS parenPattern
    { (frontAndBack $3,$5)::$1 }
| 
    { [] }

listPatternElements:
| parenPattern moreListPatternElements
    { $1 :: List.rev $2 }
| 
    { [] }

moreListPatternElements:
| moreListPatternElements seps parenPattern
    { $3 :: $1 }
| 
    { [] }

typedSeqExprBlock:
| OBLOCKBEGIN typedSeqExpr OBLOCKEND
    { $2 }
| typedSeqExpr
    { $1 }

typedSeqExprBlockR:
| typedSeqExpr ORIGHT_BLOCK_END
    { $1 }
| typedSeqExpr
    { $1 }

typedSeqExpr:
| seqExpr COLON typeWithTypeConstraints
    { Expr_typed ($1,$3, lhs()) }
| seqExpr COLON_QMARK typ %prec expr_isinst
    { Expr_isinst($1,$3,lhs()) }
| seqExpr COLON_GREATER typ
    { Expr_upcast($1,$3,lhs()) }
| seqExpr COLON_QMARK_GREATER typ
    { Expr_downcast($1,$3,lhs()) }
| seqExpr
    { $1 }

seqExpr:
| declExpr seps seqExpr
    { Expr_seq(true,$1,$3,lhs()) }
| declExpr seps
    { $1 }
| declExpr %prec SEMICOLON
    { $1 }
| declExpr THEN seqExpr %prec prec_then_before
    { Expr_seq(false,$1,$3,lhs()) }
| declExpr OTHEN OBLOCKBEGIN typedSeqExpr OBLOCKEND %prec prec_then_before
    { Expr_seq(false,$1,$4,lhs()) }

recover:
| error
    { }
| EOF
    {report_parse_error_at (lhs()) "syntax error at end of file" }

declExpr:
| defnBindings IN typedSeqExpr %prec expr_let
    { mkLocalBindings (rhs2 1 3) $1 $3 }
| defnBindings IN error %prec expr_let
    { mkLocalBindings (rhs2 1 2) $1 (arbExpr()) }
| defnBindings error %prec expr_let
    { report_parse_error_at (match $1 with (m,_,_,_)  -> m) "no matching 'in' found for this 'let'";
      mkLocalBindings (rhs2 1 2) $1 (arbExpr()) }
| hardwhiteDefnBindings typedSeqExprBlock %prec expr_let
    { mkLocalBindings (rhs2 1 2) $1 $2 }
| hardwhiteDefnBindings error %prec expr_let
    { report_parse_error_at (match $1 with (m,_,_,_)  -> m) "error in the return expression for this 'let'. Possible incorrect indentation";
      mkLocalBindings (rhs2 1 2) $1 (arbExpr()) }
| hardwhiteDefnBindings OBLOCKSEP typedSeqExprBlock %prec expr_let
    { mkLocalBindings (rhs2 1 3) $1 $3 }
| hardwhiteDefnBindings OBLOCKSEP error %prec expr_let
    { report_parse_error_at (match $1 with (m,_,_,_)  -> m) "error in the return expression for this 'let'. Possible incorrect indentation";
      mkLocalBindings (rhs2 1 2) $1 (arbExpr()) }
| anonMatchingExpr %prec expr_function
    { $1 }
| anonLambdaExpr %prec expr_fun
    { $1 }
| MATCH typedSeqExpr withClausses %prec expr_match
    { Expr_match( $2,$3,false,rhs2 1 3) }
| TRY typedSeqExprBlockR withClausses %prec expr_try
    { Expr_try_catch($2, rhs 2, $3,rhs 3, lhs()) }
| TRY typedSeqExprBlockR FINALLY typedSeqExprBlock %prec expr_try
    { Expr_try_finally($2, $4,rhs 4) }
| IF declExpr ifExprCases %prec expr_if
    { $3 $2 (lhs()) }
| LAZY declExpr %prec expr_lazy
    { mksyn_lazy ($2,lhs()) }
| ASSERT declExpr %prec expr_assert
    { Expr_assert($2, lhs()) }
| ASSERT %prec expr_assert
    { let m = lhs() in mksyn_lid_get m ["Microsoft";"FSharp";"Core";"Operators"] "assert" }
| WHILE declExpr do_or_odo typedSeqExprBlock done_term
    { Expr_while($2,$4,lhs()) }
| WHILE declExpr do_or_odo typedSeqExprBlock recover
    { report_parse_error_at (rhs 4) "'done' expected after this expression" ;  arbExpr() }
| WHILE declExpr do_or_odo error done_term
    { (* silent recovery *) arbExpr() }
| WHILE declExpr recover
    { report_parse_error_at (rhs 2) "'do' expected after this expression" ; arbExpr() }
| WHILE error done_term
    { (* silent recovery *) arbExpr()  }
| FOR forLoopBinder do_or_odo typedSeqExprBlock done_term
    { let (a,b) = $2 in Expr_foreach(a,b,$4,lhs()) }
| FOR forLoopRange do_or_odo typedSeqExprBlock done_term
    { let (a,b,c,d) = $2 in Expr_for(a,b,c,d,$4,lhs()) }
| FOR forLoopRange do_or_odo typedSeqExprBlock recover
    {   report_parse_error_at (rhs 1) "unclosed 'for', e.g. no 'done' found to match this 'for'" ; arbExpr() }
| FOR forLoopRange do_or_odo error done_term
    { (* silent recovery *) arbExpr() }
| FOR error do_or_odo typedSeqExprBlock done_term
    { (* silent recovery *) arbExpr() }
| FOR parenPattern error done_term
    {  report_parse_error_at (rhs 3) "'=' expected"; arbExpr() }
| declExpr COLON_EQUALS declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 ":=" $3 }
| minusExpr LARROW declExpr
    { mksyn_assign (lhs()) $1 $3 }
| tupleExpr %prec expr_tuple
    { Expr_tuple( List.rev $1,lhs()) }
| declExpr BAR_BAR declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "||" $3 }
| declExpr INFIX_BAR_OP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr OR declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "or" $3 }
| declExpr AMP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "&" $3 }
| declExpr AMP_AMP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "&&" $3 }
| declExpr INFIX_AMP_OP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr EQUALS declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "=" $3 }
| declExpr INFIX_COMPARE_OP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr DOLLAR declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "$" $3 }
| declExpr LESS declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "<" $3 }
| declExpr GREATER declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 ">" $3 }
| declExpr INFIX_AT_HAT_OP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr PERCENT_OP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr COLON_COLON declExpr
    { Expr_app (mksyn_item (lhs()) opname_Cons,Expr_tuple ([$1;$3],lhs()),lhs()) }
| declExpr PLUS_MINUS_OP declExpr
    { mksyn_infix (rhs 2)  (lhs()) $1 $2 $3 }
| declExpr MINUS declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "-" $3 }
| declExpr ADJACENT_PREFIX_PLUS_MINUS_OP declExpr
    { warning(Deprecated("In a future release of F# expressions of the form '-expr' and '+expr' in composite expressions will be treated as arguments. Consider using either 'expr-expr' or 'expr - expr' for infix subtraction, but not 'expr -expr', and likewise for addition",lhs()));
        mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr STAR declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 "*" $3 }
| declExpr INFIX_STAR_DIV_MOD_OP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr INFIX_STAR_STAR_OP declExpr
    { mksyn_infix (rhs 2) (lhs()) $1 $2 $3 }
| declExpr QMARK_QMARK declExpr
    { warning(Error("This language construct is deprecated. Consider using 'match <expr1> with null -> <expr2> | v -> v",lhs()));
        Expr_ifnull($1,$3,lhs()) }
| minusExpr %prec expr_prefix_plus_minus
    { $1 }

withClausses:
| WITH withPatternClauses
    { $2 }
| OWITH withPatternClauses OEND
    { $2 }

withPatternClauses:
| patternClauses
    { $1 }
| BAR patternClauses
    {  (* startName(rhs 1); *) (* hack - register as name so intellisense tells us the name '|' when this trigger fires *)
       $2 }
| BAR error
    {  (* startName(rhs 1); *) (* hack - register as name so intellisense tells us the name '|' when this trigger fires *)
       (* silent recovery *)  [] }
| error
    {  (* silent recovery *)  [] }

patternAndGuard:
| parenPattern patternGuard
    { $1, $2, rhs 1 }

patternClauses:
| patternAndGuard patternResult %prec prec_pat_pat_action
    { let pat,guard,patm = $1 in [Clause(pat,guard,$2,patm)]  }
| patternAndGuard patternResult BAR patternClauses
    { startName(rhs 3); (* hack - register as name so intellisense tells us the name '|' when this trigger fires *) 
       let pat,guard,patm = $1 in Clause(pat,guard,$2,patm) :: $4 }
| patternAndGuard patternResult BAR error
    { startName(rhs 3); (* hack - register as name so intellisense tells us the name '|' when this trigger fires *) 
       let pat,guard,patm = $1 in [Clause(pat,guard,$2,patm)] (* silent recovery *) }
| patternAndGuard patternResult error
    { let pat,guard,patm = $1 in [Clause(pat,guard,$2,patm)] (* silent recovery *) }

patternGuard:
| WHEN declExpr
    { Some $2 }
| 
    { None }

patternResult:
| RARROW typedSeqExprBlockR
    { $2 }

ifExprCases:
| ifExprThen ifExprElifs
    { (fun g m -> Expr_cond(g,$1,$2,m)) }

ifExprThen:
| THEN declExpr %prec prec_then_if
    { $2 }
| OTHEN OBLOCKBEGIN typedSeqExpr OBLOCKEND %prec prec_then_if
    { $3 }

ifExprElifs:
| 
    { None }
| ELSE declExpr
    { Some $2 }
| OELSE OBLOCKBEGIN typedSeqExpr OBLOCKEND
    { Some $3 }
| ELIF declExpr ifExprCases
    { Some ($3 $2 (lhs())) }

tupleExpr:
| tupleExpr COMMA declExpr
    { nextParameter (rhspos 2); $3 :: $1 }
| declExpr COMMA declExpr
    { nextParameter (rhspos 2); $3 :: $1 :: [] }

minusExpr:
| MINUS minusExpr %prec expr_prefix_plus_minus
    { mksyn_prefix (lhs()) "~-" $2 }
| PLUS_MINUS_OP minusExpr
    { mksyn_prefix (lhs()) ("~"^($1)) $2 }
| ADJACENT_PREFIX_PLUS_MINUS_OP minusExpr %prec expr_prefix_plus_minus
    { mksyn_prefix (lhs()) ("~"^($1)) $2 }
| SPLICE_SYMBOL minusExpr
    { Expr_hole((ref None,Some (mksyn_prefix (lhs()) $1 $2)), lhs()) }
| PERCENT_OP minusExpr
    { Expr_hole((ref None,Some (mksyn_prefix (lhs()) ("~"^($1)) $2)), lhs()) }
| AMP minusExpr
    { Expr_addrof(true,$2,lhs()) }
| AMP_AMP minusExpr
    { Expr_addrof(false,$2,lhs()) }
| NEW appType opt_HIGH_PRECEDENCE_APP argExprAfterType
    { let arg = match $4 with (* None -> mksyn_unit (lhs()) | Some *) e -> e in 
        Expr_new(false,$2,arg,lhs()) }
| NEW appType opt_HIGH_PRECEDENCE_APP error
    { Expr_new(false,$2,arbExpr(),lhs()) }
| UPCAST minusExpr
    { Expr_arb_upcast($2,lhs()) }
| DOWNCAST minusExpr
    { Expr_arb_downcast($2,lhs())}
| appExpr
    { $1 }

appExpr:
| appExpr argExprNoHPA %prec expr_app
    { Expr_app ($1,$2,lhs())  }
| argExpr
    { let arg,_ = $1 in 
        arg }

argExprNoHPA:
| argExpr
    { let arg,hpa = $1 in 
        if hpa then report_parse_error_at (rhs 1) "Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized";
        arg }

argExpr:
| argExpr HIGH_PRECEDENCE_APP argExpr
    { let arg1,_ = $1 in 
        let arg2,_ = $3 in 
        Expr_app (arg1,arg2,lhs()),true  }
| argExpr HIGH_PRECEDENCE_TYAPP typeArgsActual
    { let arg1,_ = $1 in 
        Expr_tyapp (arg1,$3,lhs()),true  }
| PREFIX_OP argExpr
    { let arg2,hpa2 = $2 in 
        mksyn_prefix (lhs()) $1 arg2,hpa2 }
| argExpr DOT argExprQualification
    { let arg1,hpa1 = $1 in 
        $3 arg1 (lhs()) (rhs 2),hpa1 }
| QMARK nameop
    { Expr_lid_get (true,[$2],rhs 2),false }
| nameop
    { Expr_lid_get (false,[$1],rhs 1),false }
| LBRACK listExprElements RBRACK
    { matchPair 1 3; 
        $2 (lhs()) true,false }
| LBRACK listExprElements recover
    { report_parse_error_at (rhs 1) "unmatched '['"; 
        $2 (rhs2 1 2) true, false }
| LBRACK error RBRACK
    { matchPair 1 3; 
        (* silent recovery *) 
        Expr_array_or_list(false,[ ], lhs()),false  }
| argExprAfterType
    { $1,false }

argExprQualification:
| identop
    { let idm = rhs 1 in 
        (fun e lhsm dotm -> 
              qualifyNameIfAlongside dotm idm; 
              mksyn_dot lhsm e $1) }
| recover
    { 
        (* silent recovery *) (fun e lhsm dotm -> qualifyName dotm dotm; e) }
| INT32
    { (fun e lhsm dotm -> 
            libraryOnly (lhs());
            qualifyName dotm dotm; mksyn_dotn lhsm e $1) }
| LPAREN COLON_COLON RPAREN DOT INT32
    { (fun e lhsm dotm -> 
            libraryOnly(lhs());
            Expr_constr_field_get (e,mksyn_constr lhsm opname_Cons,Int32.to_int $5,lhsm)) }
| LPAREN typedSeqExpr RPAREN
    { startParameters (rhspos 1); 
        endParameters (rhspos 3); 
        matchPair 1 3; 
        (fun e lhsm dotm -> 
            ocamlCompat "The expression form 'expr.(expr)' is for use when OCaml compatibility is enabled. In F# code you may use 'expr.[expr]'. A type annotation may be required to indicate the first expression is an array" (lhs()); 
            qualifyName dotm dotm; mksyn_dot_lparen_get lhsm e $2) }
| LBRACK typedSeqExpr RBRACK
    { matchPair 1 3; 
        (fun e lhsm dotm -> 
            qualifyName dotm dotm; mksyn_dot_lbrack_get lhsm e $2) }
| LBRACK optRange RBRACK
    { matchPair 1 3; 
        (fun e lhsm dotm -> qualifyName dotm dotm; mksyn_dot_lbrack_slice_get lhsm e $2) }
| LBRACK optRange COMMA optRange RBRACK %prec slice_comma
    { matchPair 1 5; 
        (fun e lhsm dotm -> qualifyName dotm dotm; mksyn_dot_lbrack_slice2_get lhsm e $2 $4) }

optRange:
| declExpr DOT_DOT declExpr
    { mk_optional (rhs 1) (Some $1), mk_optional (rhs 3) (Some $3) }
| declExpr DOT_DOT
    { mk_optional (rhs 1) (Some $1), mk_optional (rhs 2) None }
| DOT_DOT declExpr
    { mk_optional (rhs 1) None, mk_optional (rhs 2) (Some $2) }
| STAR
    { mk_optional (rhs 1) None, mk_optional (rhs 1) None }

argExprAfterType:
| constant
    { Expr_const ($1,range_of_synconst $1 (lhs())) }
| parenExpr
    { $1 }
| braceExpr
    { $1 }
| NULL
    { Expr_null(lhs()) }
| FALSE
    { Expr_const(Const_bool false,lhs()) }
| TRUE
    { Expr_const(Const_bool true,lhs()) }
| quoteExpr
    { $1 }
| arrayExpr
    { $1 }
| beginEndExpr
    { $1 }
| UNDERSCORE
    { Expr_hole((ref None, None),lhs()) }

beginEndExpr:
| BEGIN typedSeqExpr END
    { Expr_paren($2,rhs2 1 3) }
| BEGIN typedSeqExpr recover
    { report_parse_error_at (rhs 1) "unmatched 'begin'"; $2 }
| BEGIN error END
    { (* silent recovery *) arbExpr()  }
| BEGIN END
    { mksyn_unit (lhs()) }

quoteExpr:
| LQUOTE typedSeqExpr RQUOTE
    { matchPair 1 3; 
        if $1 <> $3 then report_parse_error_at (rhs 1) ("mismatched quotation, beginning with '"^ fst $1 ^ "'");  
        (Expr_quote(mksyn_item (lhs()) (compileOpName (fst $1)), snd $1,$2,lhs())) }
| LQUOTE typedSeqExpr recover
    { report_parse_error_at (rhs 1) ("unmatched '"^fst $1^"'");  Expr_quote(mksyn_item (lhs()) (compileOpName (fst $1)),snd $1,$2,rhs2 1 2)  }
| LQUOTE error RQUOTE
    { matchPair 1 3; (* silent recovery *) Expr_quote(mksyn_item (lhs()) (compileOpName (fst $1)),snd $1,arbExpr(),lhs())  }

arrayExpr:
| LBRACK_BAR listExprElements BAR_RBRACK
    {  matchPair 1 3; $2 (lhs()) false }
| LBRACK_BAR listExprElements recover
    { report_parse_error_at (rhs 1) "unmatched '[|'"; 
        $2 (rhs2 1 2) false }
| LBRACK_BAR error BAR_RBRACK
    {  matchPair 1 3; (* silent recovery *) Expr_array_or_list(true,[ ], lhs()) }

parenExpr:
| LPAREN parenExprBody RPAREN
    { startParameters (rhspos 1); endParameters (rhspos 3); matchPair 1 3; $2 (rhs2 1 3) }
| LPAREN parenExprBody recover
    { startParameters (rhspos 1); endParameters (rhspos 3); report_parse_error_at (rhs 1) "unmatched '('"; let lhsm = rhs2 1 2 in Expr_paren($2 lhsm,lhsm) }
| LPAREN error RPAREN
    { startParameters (rhspos 1); endParameters (rhspos 3); matchPair 1 3; (* silent recovery *) arbExpr() }
| LPAREN recover %prec prec_atomexpr_lparen_error
    {  startParameters (rhspos 1); endParameters (rhspos 2); report_parse_error_at (rhs 1) "unmatched '('"; arbExpr()  }

parenExprBody:
| 
    {  (fun m -> Expr_const(Const_unit,m)) }
| TYPE typ
    {  (fun  m -> Expr_typeof($2,m)) }
| staticallyKnownHeadTypars COLON LPAREN classMemberSpfn RPAREN LPAREN typedSeqExpr RPAREN
    {  matchPair 3 5;  
         matchPair 6 8; 
         (fun m -> Expr_trait_call($1,$4,(match $7 with Expr_tuple(l,_) -> l | e -> [e]),m)) }
| typedSeqExpr
    { (fun m -> Expr_paren($1,m)) }
| inlineAssemblyExpr
    { $1 }

staticallyKnownHeadTypars:
| staticallyKnownHeadTypar
    { [$1] }
| LPAREN staticallyKnownHeadTypar OR staticallyKnownHeadTypar RPAREN
    { [$2 ; $4 ] }

braceExpr:
| LBRACE braceExprBody RBRACE
    {  matchPair 1 3; $2 (lhs()) }
| LBRACE braceExprBody recover
    { report_parse_error_at (rhs 1) "unmatched '{'" ; $2 (lhs()) }
| LBRACE error RBRACE
    { matchPair 1 3; (* silent recovery *) arbExpr()  }

braceExprBody:
| recdExpr
    {  (fun m -> let a,b,c = $1 in Expr_recd(a,b,c,m)) }
| objExpr
    { $1 }
| monadicExprInitial
    { $1  }

listExprElements:
| monadicExprInitial
    { (fun lhsm isList -> if isList then Expr_list_of_seq($1 lhsm,lhsm) else Expr_array_of_seq($1 lhsm,lhsm) ) }
| declExpr moreListExprElements opt_seps
    { (fun lhsm isList -> let elems = ($1 :: List.rev $2) in Expr_array_or_list(not isList, elems, lhsm)) }
| 
    { (fun lhsm isList -> Expr_array_or_list(not isList,[ ], lhsm)) }

moreListExprElements:
| moreListExprElements seps declExpr
    { $3 :: $1 }
| 
    { [] }

monadicExprInitial:
| monadicExprNonEmptyInitial
    { (fun lhsm -> Expr_comprehension($1,lhsm)) }
| rangeSequenceExpr
    { $1 }

rangeSequenceExpr:
| declExpr TO declExpr %prec expr_let
    { deprecated "use 'expr .. expr' instead" (lhs()); (fun m -> mksyn_infix m m $1 ".." $3) }
| declExpr DOT_DOT declExpr
    { (fun m -> mksyn_infix m m $1 ".." $3) }
| declExpr DOT_DOT declExpr DOT_DOT declExpr
    { (fun m -> mksyn_trifix m ".. .." $1 $3 $5) }

monadicExprNonEmptyNonInitial:
| monadicExprNonEmptyInitial
    { $1 }

monadicExprNonEmptyNonInitialBlock:
| OBLOCKBEGIN monadicExprNonEmptyNonInitial OBLOCKEND
    { $2 }
| monadicExprNonEmptyNonInitial
    { $1 }

monadicExprNonEmptyNonInitialBlockR:
| monadicExprNonEmptyNonInitial ORIGHT_BLOCK_END
    { $1 }
| monadicExprNonEmptyNonInitial
    { $1 }

monadicExprNonEmptyInitial:
| monadicExprNonEmptyInitial OBLOCKSEP monadicExprNonEmptyInitial
    { Comp_sum($1,$3,rhs 1, rhs 3) }
| FOR forLoopBinder monadicSingleLineQualifiersThenArrowThenExprR %prec decl_let
    { let a,b= $2 in Comp_for(true,a,b,$3 (rhs 2)) }
| FOR forLoopBinder OBLOCKSEP monadicExprNonEmptyNonInitial %prec decl_let
    { let a,b= $2 in Comp_for(true,a,b,$4) }
| FOR forLoopBinder do_or_odo monadicExprNonEmptyNonInitialBlock done_term %prec decl_let
    { let a,b= $2 in Comp_for(false,a,b,$4) }
| FOR forLoopRange do_or_odo monadicExprNonEmptyNonInitialBlock done_term
    { report_parse_error_at (rhs2  3 6) ("Integer loops 'for x = a to b do ...' may not be used in computation expressions. Consider using 'for x in n .. m do' instead"); $4 }
| monadicWhenCondition monadicSingleLineQualifiersThenArrowThenExprR %prec decl_let
    { Comp_cond(true,$1,$2 (rhs 1),Comp_zero) }
| monadicWhenCondition OBLOCKSEP monadicExprNonEmptyNonInitial %prec decl_let
    { Comp_cond(true,$1,$3,Comp_zero) }
| monadicWhenCondition do_or_odo monadicExprNonEmptyNonInitialBlock done_term %prec decl_let
    { Comp_cond(true,$1,$3,Comp_zero) }
| IF declExpr monadicIfExprCases %prec expr_if
    { $3 $2 }
| WHILE declExpr do_or_odo monadicExprNonEmptyNonInitialBlock done_term
    { Comp_while($2,$4) }
| TRY monadicExprNonEmptyNonInitialBlockR monadicWithClauses %prec expr_try
    { Comp_try_with($2, $3) }
| TRY monadicExprNonEmptyNonInitialBlockR FINALLY typedSeqExprBlock %prec expr_try
    { Comp_try_finally($2,$4) }
| MATCH typedSeqExpr monadicWithClauses %prec expr_match
    { Comp_match( $2,$3) }
| monadicExprBindings
    { $1 }
| YIELD declExpr
    { Comp_yield(($1,not $1),$2) }
| YIELD_BANG declExpr
    { Comp_yieldm(($1,not $1), $2) }
| RARROW typedSeqExprBlockR
    { Comp_yield((true,true),$2) }
| RARROW2 typedSeqExprBlockR
    { Comp_yieldm((false,false),$2) }

monadicWithClauses:
| WITH monadicWithPatternClauses %prec expr_match
    { $2 }
| OWITH monadicWithPatternClauses OEND %prec expr_match
    { $2 }

monadicExprBindings:
| hardwhiteLetBindings OBLOCKSEP monadicExprNonEmptyNonInitial %prec decl_let
    { mkComprehensionBindings (rhs 1) $1 $3 }
| hardwhiteLetBindings monadicExprNonEmptyNonInitial %prec decl_let
    { mkComprehensionBindings (rhs 1) $1 $2 }
| hardwhiteDoBinding OBLOCKSEP monadicExpr %prec decl_let
    { mkComprehensionBindings (rhs 1) $1 $3 }
| hardwhiteDoBinding monadicExpr %prec decl_let
    { mkComprehensionBindings (rhs 1) $1 $2 }
| defnBindings IN monadicExprNonEmptyNonInitial %prec decl_let
    { mkComprehensionBindings (rhs 1) $1 $3 }
| doBinding IN monadicExprNonEmptyNonInitial %prec decl_let
    { mkComprehensionBindings (rhs 1) $1 $3 }
| BINDER headBindingPattern EQUALS typedSeqExprBlock IN opt_OBLOCKSEP monadicExprNonEmptyNonInitial %prec decl_let
    { let m = rhs 1 in
       if $1 <> "let" && $1 <> "use" then warning(Error("the use of custom binders in computation expressions is experimental and will be deleted in the next release",m));
       Comp_bind(false,Some $1,Some $2,$4,$7) }
| OBINDER headBindingPattern EQUALS typedSeqExprBlock hardwhiteDefnBindingsTerminator opt_OBLOCKSEP monadicExprNonEmptyNonInitial %prec decl_let
    { let m = rhs 1 in
       if $1 <> "let" && $1 <> "use" then warning(Error("the use of custom binders in computation expressions is experimental and will be deleted in the next release",m));
       Comp_bind(false,Some $1,Some $2,$4,$7) }
| DO_BANG typedSeqExpr IN opt_OBLOCKSEP monadicExprNonEmptyNonInitial %prec decl_let
    { Comp_bind(false,Some "let",None,$2,$5) }
| ODO_BANG typedSeqExprBlock hardwhiteDefnBindingsTerminator opt_OBLOCKSEP monadicExpr %prec decl_let
    { Comp_bind(false,Some "let",None,$2,$5) }

monadicExpr:
| monadicExprNonEmptyNonInitial
    { $1 }
| 
    { Comp_zero }
| error
    { (* silent recovery *) Comp_zero }

monadicWhenCondition:
| WHEN declExpr
    { $2 }

monadicWithPatternClauses:
| monadicPatternClauses
    { $1 }
| BAR monadicPatternClauses
    {  $2 }

monadicPatternClauses:
| patternAndGuard monadicPatternResult %prec prec_pat_pat_action
    { let pat,guard,patm = $1 in [CompClause(pat,guard,$2,patm)]  }
| patternAndGuard monadicPatternResult BAR monadicPatternClauses
    { let pat,guard,patm = $1 in CompClause(pat,guard,$2,patm) :: $4 }

monadicPatternResult:
| RARROW monadicExprNonEmptyNonInitialBlockR
    { $2 }

monadicSingleLineQualifiersThenArrowThenExprR:
| RARROW typedSeqExprBlockR
    { (fun m -> Comp_yield((true,false),$2)) }
| RARROW2 typedSeqExprBlockR
    { (fun m -> Comp_yieldm((true,false),$2)) }
| FOR forLoopBinder monadicSingleLineQualifiersThenArrowThenExprR %prec decl_let
    { let a2,b2= $2 in 
       (fun m -> 
           Comp_for(true,a2,b2,$3 m)) }
| monadicWhenCondition monadicSingleLineQualifiersThenArrowThenExprR %prec decl_let
    { (fun m -> 
           Comp_cond(true,$1,$2 m,Comp_zero)) }
| FOR forLoopBinder OBLOCKSEP monadicSingleLineQualifiersThenArrowThenExprR %prec decl_let
    { let a2,b2= $2 in 
       (fun m -> 
           warning(Error("'for' binders and 'when' clauses in computation expressions should be either stacked (each on a separate line starting at the same column), or each should have a matching 'do', e.g. 'for x in <expr> do for y in <expr> -> ...'",m)); 
           Comp_for(true,a2,b2,$4 m)) }
| monadicWhenCondition OBLOCKSEP monadicSingleLineQualifiersThenArrowThenExprR %prec decl_let
    { (fun m -> 
           warning(Error("'for' binders and 'when' clauses in computation expressions should either be stacked (each on a separate line starting at the same column), or each should have a matching '->' or 'do', e.g. 'for x in <expr> do when <expr> -> ...'",m));
           Comp_cond(true,$1,$3 m,Comp_zero)) }

monadicIfExprThen:
| THEN monadicExprNonEmptyNonInitial %prec prec_then_if
    { $2 }
| OTHEN OBLOCKBEGIN monadicExprNonEmptyNonInitial OBLOCKEND %prec prec_then_if
    { $3 }

monadicIfExprElifs:
| 
    { Comp_zero }
| ELSE monadicExprNonEmptyNonInitial
    { $2 }
| OELSE OBLOCKBEGIN monadicExprNonEmptyNonInitial OBLOCKEND
    { $3 }
| ELIF declExpr monadicIfExprCases
    { $3 $2  }

monadicIfExprCases:
| monadicIfExprThen monadicIfExprElifs
    { (fun g -> Comp_cond(false,g,$1,$2)) }

forLoopBinder:
| parenPattern IN declExpr
    { ($1, $3) }
| parenPattern IN rangeSequenceExpr
    { ($1, $3 (rhs 3)) }
| parenPattern IN recover
    { ($1, arbExpr()) }

forLoopRange:
| parenPattern EQUALS declExpr direction declExpr
    { id_of_pat (rhs 1) $1,$3,$4,$5 }

inlineAssemblyExpr:
| HASH STRING opt_inlineAssemblyTypeArg opt_curriedArgExprs opt_inlineAssemblyReturnTypes opt_HASH
    { libraryOnly (lhs());
        let s,sm = $2,rhs 2 in
        (fun m -> Expr_asm (parse_il_instrs s sm,$3,List.rev $4,$5,m)) }

opt_curriedArgExprs:
| opt_curriedArgExprs argExprNoHPA %prec expr_args
    { $2 :: $1 }
| 
    { [] }

opt_argExprAfterType:
| 
    { None }
| argExprAfterType
    { Some($1) }

opt_inlineAssemblyTypeArg:
| 
    { [] }
| TYPE LPAREN typ RPAREN
    {  matchPair 2 4; [$3] }

opt_inlineAssemblyReturnTypes:
| 
    { [] }
| COLON typ
    { [$2] }
| COLON LPAREN RPAREN
    {  matchPair 2 3; [] }

recdExpr:
| 
    { (None,None, []) }
| INHERIT appType opt_HIGH_PRECEDENCE_APP opt_argExprAfterType recdExprBindings opt_seps
    { let arg = match $4 with None -> mksyn_unit (lhs()) | Some e -> e in 
       (Some($2,arg,rhs2 2 4),None, $5) }
| appExpr EQUALS declExpr recdExprBindings opt_seps
    { match $1 with 
       | Expr_lid_get(false,v,m) -> (None,None, (frontAndBack v,$3) :: List.rev $4) 
       | _ -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 2) "field bindings must have the form 'id = expr;'" }
| appExpr WITH path EQUALS declExpr recdExprBindings opt_seps
    {  (None,Some $1,(frontAndBack $3,$5):: List.rev $6) }
| appExpr OWITH path EQUALS declExpr recdExprBindings opt_seps OEND
    {  (None,Some $1,(frontAndBack $3,$5):: List.rev $6) }

recdExprBindings:
| recdExprBindings seps path EQUALS declExpr
    { (frontAndBack $3,$5) :: $1 }
| 
    { [] }

objExpr:
| objExprBaseCall opt_objExprBindings opt_OBLOCKSEP objExprInterfaces
    { (fun m -> let (a,b) = $1 in Expr_impl(a,b,$2,$4, m)) }

objExprBaseCall:
| NEW appType opt_HIGH_PRECEDENCE_APP opt_argExprAfterType opt_as
    { startName(rhs 5); 
       let argInfo = match $4 with None -> None | Some e -> Some(e,$5) in 
       ($2, argInfo) }

opt_objExprBindings:
| objExprBindings
    { $1 }
| 
    { [] }

objExprBindings:
| WITH localBindings
    { ($2 [] None) }
| OWITH localBindings OEND
    { ($2 [] None) }
| WITH objectImplementationBlock opt_decl_end
    { $2 |> 
        (chooseList (function ClassMemberDefn_member_binding(b,m) -> Some b
                          | ClassMemberDefn_implicit_inherit (_, _, _, m)
                          | ClassMemberDefn_implicit_ctor (_, _, m)
                          | ClassMemberDefn_let_bindings(_,_,_,m)                    
                          | ClassMemberDefn_slotsig(_,_,m) 
                          | ClassMemberDefn_interface(_,_,m) 
                          | ClassMemberDefn_inherit(_,_,m)
                          | ClassMemberDefn_field(_,m)
                          | ClassMemberDefn_open(_,m)
                          | ClassMemberDefn_tycon(_,_,m) -> errorR(Error("This member is not permitted in an object implementation",m)); None)) }

objExprInterfaces:
|  %prec prec_interfaces_prefix
    { [] }
| objExprInterface objExprInterfaces
    { $1 :: $2 }
| error objExprInterfaces
    { (* silent recovery *) $2 }

objExprInterface:
| interfaceMember appType opt_objExprBindings opt_decl_end opt_OBLOCKSEP
    { InterfaceImpl($2, $3, lhs()) }

direction:
| TO
    { true }
| DOWNTO
    { false }

anonLambdaExpr:
| FUN atomicPatterns RARROW typedSeqExprBlock
    { mksyn_match_lambdas false (lhs()) $2 $4 }
| FUN atomicPatterns RARROW error
    { mksyn_match_lambdas false (lhs()) $2 (arbExpr()) }
| OFUN atomicPatterns RARROW typedSeqExprBlockR OEND
    { mksyn_match_lambdas false (rhs2 1 4) $2 $4 }
| OFUN atomicPatterns RARROW error OEND
    { mksyn_match_lambdas false (rhs2 1 3) $2 (arbExpr()) }

anonMatchingExpr:
| FUNCTION opt_bar patternClauses %prec expr_function
    { mksyn_match_lambda false false (lhs()) $3 }
| OFUNCTION opt_bar patternClauses OEND %prec expr_function
    { mksyn_match_lambda false false (lhs()) $3 }
| OFUNCTION opt_bar patternClauses error OEND %prec expr_function
    { report_parse_error_at (rhs 1) "error in 'function' block"; 
        mksyn_match_lambda false false (lhs()) $3 }

typeWithTypeConstraints:
| typ %prec prec_wheretyp_prefix
    { $1 }
| typ WHEN typeConstraints
    { Type_with_global_constraints($1, List.rev $3,lhs()) }

topTypeWithTypeConstraints:
| topType
    { $1 }
| topType WHEN typeConstraints
    { let ty,arity = $1 in 
        (* nb. it doesn't matter where the constraints go in the structure of the type. *)
        Type_with_global_constraints(ty,List.rev $3,lhs()), arity }

opt_topReturnTypeWithTypeConstraints:
| 
    { None }
| COLON topTypeWithTypeConstraints
    { let ty,arity = $2 in 
       let arity = (match arity with TopValSynData([],rmdata)-> rmdata | _ -> SynArgInfo.unnamedRetVal) in
       Some ((ty,arity),rhs 2) }

topType:
| topTupleType RARROW topType
    { let dty,dmdata= $1 in 
       let rty,(TopValSynData(dmdatas,rmdata)) = $3 in 
       Type_fun(dty,rty,lhs()), (TopValSynData(dmdata::dmdatas, rmdata)) }
| topTupleType
    { let ty,rmdata = $1 in ty, (TopValSynData([],(match rmdata with [md] -> md | _ -> SynArgInfo.unnamedRetVal))) }

topTupleType:
| topAppType STAR topTupleTypeElements
    { let ty,mdata = $1 in let tys,mdatas = List.split $3 in (Type_tuple(ty ::tys, lhs())),(mdata :: mdatas) }
| topAppType
    { let ty,mdata = $1 in ty,[mdata] }

topTupleTypeElements:
| topAppType STAR topTupleTypeElements
    { $1 :: $3 }
| topAppType %prec prec_toptuptyptail_prefix
    { [$1] }

topAppType:
| attributes appType COLON appType
    { match $2 with 
       | Type_app([id],_,_) -> $4,TopArgSynData($1,false,Some id)
       | _ -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 2) "syntax error in labelled type argument"  }
| attributes QMARK ident COLON appType
    { $5,TopArgSynData($1,true,Some $3) }
| attributes appType
    { ($2,TopArgSynData($1,false,None)) }
| appType COLON appType
    { match $1 with 
       | Type_app([id],_,_) -> $3,TopArgSynData([],false,Some id)
       | _ -> raise_parse_error_at_USE_ONLY_IF_NOT_IN_ERROR_RECOVERY (rhs 2) "syntax error in labelled type argument"  }
| QMARK ident COLON appType
    { $4,TopArgSynData([],true,Some $2) }
| appType
    { $1,TopArgSynData([],false,None) }

polyType:
| typar DOT typ
    { Type_forall(TyparDecl([],$1),$3,lhs()) }
| typ
    { $1 }

typ:
| tupleType RARROW typ
    { Type_fun($1,$3,lhs()) }
| tupleType %prec prec_typ_prefix
    { $1 }

tupleType:
| appType STAR tupleTypeElements
    { Type_tuple($1 :: $3,lhs()) }
| appType %prec prec_tuptyp_prefix
    { $1 }

tupleTypeElements:
| appType STAR tupleTypeElements
    { $1 :: $3 }
| appType %prec prec_tuptyptail_prefix
    { [$1] }

appType:
| appType arrayTypeSuffix
    {  Type_arr($2,$1,lhs()) }
| appType HIGH_PRECEDENCE_APP arrayTypeSuffix
    {  Type_arr($3,$1,lhs()) }
| appType path
    { Type_app($2,[$1],lhs()) }
| appType LAZY
    { mksyn_lazy_ty (lhs()) $1 }
| LPAREN appTypePrexifArguments RPAREN path
    {  matchPair 1 3; Type_app($4,$2, lhs()) }
| atomType
    { $1 }
| typar COLON_GREATER typ
    {  let tp,typ = $1,$3 in 
         let m = lhs() in 
         Type_with_global_constraints(Type_var (tp, rhs 1), [WhereTyparSubtypeOfType(tp,typ,m)],m)  }
| UNDERSCORE COLON_GREATER typ %prec COLON_GREATER
    {  matchPair 1 3; mksyn_anon_constraint $3 (lhs()) }

arrayTypeSuffix:
| LBRACK RBRACK
    {  matchPair 1 2; 1 }
| LBRACK COMMA RBRACK
    {  matchPair 1 3; 2 }
| LBRACK COMMA COMMA RBRACK
    {  matchPair 1 4; 3 }
| LBRACK COMMA COMMA COMMA RBRACK
    {  matchPair 1 5; 4 }

appTypePrexifArguments:
| typ COMMA typ typeListElements
    { $1 :: $3 :: List.rev $4 }

typeListElements:
| typeListElements COMMA typ
    { $3 :: $1 }
| 
    { [] }

atomType:
| HASH atomType
    { mksyn_anon_constraint $2 (lhs()) }
| typar
    { Type_var ($1,lhs()) }
| UNDERSCORE
    { Type_anon (lhs()) }
| LPAREN typ RPAREN
    {  matchPair 1 3; $2 }
| LPAREN typ recover
    { report_parse_error_at (rhs 1) "unmatched '('" ; $2 }
| LPAREN error RPAREN
    { (* silent recovery *) Type_anon (lhs()) }
| path %prec prec_atomtyp_path
    { Type_app($1,[],lhs()) }
| path typeArgs %prec prec_atomtyp_path
    { Type_app($1,$2,lhs()) }
| atomType DOT path %prec prec_atomtyp_get_path
    { Type_proj_then_app($1,$3,[],lhs()) }
| atomType DOT path typeArgs %prec prec_atomtyp_get_path
    { Type_proj_then_app($1,$3,$4,lhs()) }

typeArgs:
| typeArgsActual
    { $1 }
| HIGH_PRECEDENCE_TYAPP typeArgsActual
    { $2 }

typeArgsActual:
| LESS GREATER
    { [] }
| LESS typ GREATER
    { [$2] }
| LESS typ COMMA typ typeListElements GREATER
    { $2 :: $4 :: List.rev $5 }

typar:
| QUOTE ident
    {  let id = mksyn_id (lhs()) ($2).idText in
        Typar(id ,NoStaticReq,false) }
| DOLLAR ident
    {  libraryOnly (lhs()); 
        let id = mksyn_id (lhs()) ($2).idText in
        Typar(id,CompleteStaticReq,false) }
| staticallyKnownHeadTypar
    { $1 }

staticallyKnownHeadTypar:
| INFIX_AT_HAT_OP ident
    {  if $1 <> "^" then report_parse_error_at (rhs 1) "syntax error: unexpeced type paramter specification";
       Typar($2,HeadTypeStaticReq,false) }

ident:
| IDENT
    { ident($1,rhs 1) }

path:
| ident
    { startName(rhs 1); [$1] }
| path DOT ident
    { qualifyNameIfAlongside(rhs 2) (rhs 3); (* silent recovery *) $1 @ [$3] }
| path DOT error
    { qualifyName(rhs 2) (rhs 2); (* silent recovery *) $1  }

identop:
| ident
    { $1 }
| LPAREN operatorName RPAREN
    {  matchPair 1 3; ident(compileOpName $2,rhs 2) }
| LPAREN barNames BAR RPAREN
    { ident(("|"^String.concat "|" (List.rev $2) ^ "|"),rhs2 2 4) }
| LPAREN barNames BAR UNDERSCORE BAR RPAREN
    { ident(("|"^String.concat "|" (List.rev $2) ^ "|_|" ),rhs2 2 5) }

operatorName:
| PREFIX_OP
    { $1 }
| INFIX_STAR_STAR_OP
    { $1 }
| INFIX_COMPARE_OP
    { $1 }
| INFIX_AT_HAT_OP
    { $1 }
| INFIX_BAR_OP
    { $1 }
| INFIX_AMP_OP
    { $1 }
| PLUS_MINUS_OP
    { $1 }
| INFIX_STAR_DIV_MOD_OP
    { $1 }</