1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <guido.tack@monash.edu>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <minizinc/ast.hh>
#include <minizinc/astexception.hh>
#include <minizinc/astiterator.hh>
#include <minizinc/aststring.hh>
#include <minizinc/copy.hh>
#include <minizinc/eval_par.hh>
#include <minizinc/flat_exp.hh>
#include <minizinc/flatten.hh>
#include <minizinc/flatten_internal.hh>
#include <minizinc/gc.hh>
#include <minizinc/hash.hh>
#include <minizinc/iter.hh>
#include <minizinc/optimize.hh>
#include <minizinc/output.hh>
#include <minizinc/statistics.hh>
#include <minizinc/type.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/utils.hh>
#include <minizinc/values.hh>
#include <algorithm>
#include <cassert>
#include <map>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace MiniZinc {
// Create domain constraints. Return true if successful.
bool create_explicit_domain_constraints(EnvI& envi, VarDecl* vd, Expression* domain) {
std::vector<KeepAlive> calls;
{
GCLock lock;
Location iloc = Location().introduce();
if (vd->type().isOpt()) {
calls.emplace_back(Call::a(iloc, "var_dom", {vd->id(), domain}));
} else if (vd->type().isIntSet()) {
assert(Expression::type(domain).isint() || Expression::type(domain).isIntSet());
IntSetVal* isv = eval_intset(envi, domain);
calls.emplace_back(
Call::a(iloc, envi.constants.ids.set_.subset, {vd->id(), new SetLit(iloc, isv)}));
} else if (Expression::type(domain).isbool()) {
calls.emplace_back(Call::a(iloc, envi.constants.ids.bool_.eq, {vd->id(), domain}));
} else if (Expression::type(domain).isBoolSet()) {
IntSetVal* bsv = eval_boolset(envi, domain);
assert(bsv->size() == 1);
if (bsv->min() != bsv->max()) {
return true; // Both values are still possible, no change
}
calls.emplace_back(Call::a(iloc, envi.constants.ids.bool_.eq,
{vd->id(), envi.constants.boollit(bsv->min() > 0)}));
} else if (Expression::type(domain).isfloat() || Expression::type(domain).isFloatSet()) {
FloatSetVal* fsv = eval_floatset(envi, domain);
if (fsv->size() == 1) { // Range based
if (fsv->min() == fsv->max()) {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.float_.eq, {vd->id(), FloatLit::a(fsv->min())}));
} else {
FloatSetVal* cfsv;
if (vd->ti()->domain() != nullptr) {
cfsv = eval_floatset(envi, vd->ti()->domain());
} else {
cfsv = FloatSetVal::a(-FloatVal::infinity(), FloatVal::infinity());
}
if (cfsv->min() < fsv->min()) {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.float_.le, {FloatLit::a(fsv->min()), vd->id()}));
}
if (cfsv->max() > fsv->max()) {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.float_.le, {vd->id(), FloatLit::a(fsv->max())}));
}
}
} else {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.set_.in, {vd->id(), new SetLit(iloc, fsv)}));
}
} else if (Expression::type(domain).isint() || Expression::type(domain).isIntSet()) {
IntSetVal* isv = eval_intset(envi, domain);
if (isv->size() == 1) { // Range based
if (isv->min() == isv->max()) {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.int_.eq, {vd->id(), IntLit::a(isv->min())}));
} else {
IntSetVal* cisv;
if (vd->ti()->domain() != nullptr) {
cisv = eval_intset(envi, vd->ti()->domain());
} else {
cisv = IntSetVal::a(-IntVal::infinity(), IntVal::infinity());
}
if (cisv->min() < isv->min()) {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.int_.le, {IntLit::a(isv->min()), vd->id()}));
}
if (cisv->max() > isv->max()) {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.int_.le, {vd->id(), IntLit::a(isv->max())}));
}
}
} else {
calls.emplace_back(
Call::a(iloc, envi.constants.ids.set_.in, {vd->id(), new SetLit(iloc, isv)}));
}
} else {
return false;
}
}
int counter = 0;
for (const auto& ka : calls) {
auto* c = Expression::cast<Call>(ka());
CallStackItem csi(envi, IntLit::a(counter++));
Expression::ann(c).add(envi.constants.ann.domain_change_constraint);
Expression::type(c, Type::varbool());
c->decl(envi.model->matchFn(envi, c, true));
flat_exp(envi, Ctx(), c, envi.constants.varTrue, envi.constants.varTrue);
}
return true;
}
void set_computed_domain(EnvI& envi, VarDecl* vd, Expression* domain, bool is_computed) {
if (envi.hasReverseMapper(vd->id())) {
if (!create_explicit_domain_constraints(envi, vd, domain)) {
std::ostringstream ss;
ss << "Unable to create domain constraint for reverse mapped variable: " << *vd->id() << " = "
<< *domain << std::endl;
throw EvalError(envi, Expression::loc(domain), ss.str());
}
vd->ti()->domain(domain);
return;
}
if (envi.fopts.recordDomainChanges &&
!Expression::ann(vd).contains(envi.constants.ann.is_defined_var) && !vd->introduced() &&
!(vd->type().dim() > 0)) {
if (create_explicit_domain_constraints(envi, vd, domain)) {
return;
}
std::cerr << "Warning: domain change not handled by -g mode: " << *vd->id() << " = " << *domain
<< std::endl;
}
vd->ti()->domain(domain);
vd->ti()->setComputedDomain(is_computed);
}
// Create assignment constraints. Return true if successful.
bool create_explicit_assignment_constraints(EnvI& envi, VarDecl* vd, Expression* val) {
assert(vd->type().dim() == 0);
KeepAlive ka;
Location iloc = Location().introduce();
{
GCLock lock;
Call* call;
if (vd->type().isIntSet()) {
assert(Expression::type(val).isIntSet());
call = Call::a(iloc, envi.constants.ids.set_.eq, {vd->id(), val});
} else {
assert(vd->type().st() == Type::ST_PLAIN);
if (vd->type().bt() == Type::BT_BOOL) {
call = Call::a(iloc, envi.constants.ids.bool_.eq, {vd->id(), val});
} else if (vd->type().bt() == Type::BT_INT) {
call = Call::a(iloc, envi.constants.ids.int_.eq, {vd->id(), val});
} else if (vd->type().bt() == Type::BT_FLOAT) {
call = Call::a(iloc, envi.constants.ids.float_.eq, {vd->id(), val});
} else {
return false;
}
}
CallStackItem csi(envi, IntLit::a(0));
Expression::ann(call).add(envi.constants.ann.domain_change_constraint);
Expression::type(call, Type::varbool());
call->decl(envi.model->matchFn(envi, call, true));
ka = call;
}
flat_exp(envi, Ctx(), ka(), envi.constants.varTrue, envi.constants.varTrue);
return true;
}
/// Output operator for contexts
template <class Char, class Traits>
std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& os, Ctx& ctx) {
switch (ctx.b) {
case C_ROOT:
os << "R";
break;
case C_POS:
os << "+";
break;
case C_NEG:
os << "-";
break;
case C_MIX:
os << "M";
break;
default:
assert(false);
break;
}
switch (ctx.i) {
case C_ROOT:
os << "R";
break;
case C_POS:
os << "+";
break;
case C_NEG:
os << "-";
break;
case C_MIX:
os << "M";
break;
default:
assert(false);
break;
}
if (ctx.neg) {
os << "!";
}
return os;
}
BCtx operator+(const BCtx& c) {
switch (c) {
case C_ROOT:
case C_POS:
return C_POS;
case C_NEG:
return C_NEG;
case C_MIX:
return C_MIX;
default:
assert(false);
return C_ROOT;
}
}
BCtx operator-(const BCtx& c) {
switch (c) {
case C_ROOT:
case C_POS:
return C_NEG;
case C_NEG:
return C_POS;
case C_MIX:
return C_MIX;
default:
assert(false);
return C_ROOT;
}
}
/// Check if \a c is non-positive
bool nonpos(const BCtx& c) { return c == C_NEG || c == C_MIX; }
/// Check if \a c is non-negative
bool nonneg(const BCtx& c) { return c == C_ROOT || c == C_POS; }
void dump_ee_b(const std::vector<EE>& ee) {
for (const auto& i : ee) {
std::cerr << *i.b() << "\n";
}
}
void dump_ee_r(const std::vector<EE>& ee) {
for (const auto& i : ee) {
std::cerr << *i.r() << "\n";
}
}
std::tuple<BCtx, bool> EnvI::annToCtx(VarDecl* vd) const {
if (Expression::ann(vd).contains(constants.ctx.root)) {
return std::make_tuple(C_ROOT, true);
}
if (Expression::ann(vd).contains(constants.ctx.mix)) {
return std::make_tuple(C_MIX, true);
}
if (Expression::ann(vd).contains(constants.ctx.pos)) {
return std::make_tuple(C_POS, true);
}
if (Expression::ann(vd).contains(constants.ctx.neg)) {
return std::make_tuple(C_NEG, true);
}
return std::make_tuple(C_MIX, false);
}
Id* EnvI::ctxToAnn(BCtx c) const {
switch (c) {
case C_ROOT:
return constants.ctx.root;
case C_POS:
return constants.ctx.pos;
case C_NEG:
return constants.ctx.neg;
case C_MIX:
return constants.ctx.mix;
default:
assert(false);
return nullptr;
}
}
void EnvI::addCtxAnn(VarDecl* vd, const BCtx& c) const {
if (vd != nullptr) {
BCtx nc;
bool annotated;
std::tie(nc, annotated) = annToCtx(vd);
// If previously annotated
if (annotated) {
// Early exit
if (nc == c || nc == C_ROOT || (nc == C_MIX && c != C_ROOT)) {
return;
}
// Remove old annotation
Id* old_ann = ctxToAnn(nc);
Expression::ann(vd).remove(old_ann);
// Determine new context
if (c == C_ROOT) {
nc = C_ROOT;
} else {
nc = C_MIX;
}
} else {
nc = c;
}
Id* ctx_id = ctxToAnn(nc);
Expression::addAnnotation(vd, ctx_id);
}
}
void make_defined_var(EnvI& env, VarDecl* vd, Call* c) {
if (!Expression::ann(vd).contains(env.constants.ann.is_defined_var)) {
std::vector<Expression*> args(1);
args[0] = vd->id();
Call* dv = Call::a(Location().introduce(), env.constants.ann.defines_var, args);
Expression::type(dv, Type::ann());
Expression::addAnnotation(vd, env.constants.ann.is_defined_var);
Expression::addAnnotation(c, dv);
}
}
bool is_defines_var_ann(EnvI& env, Expression* e) {
return Expression::isa<Call>(e) &&
Expression::cast<Call>(e)->id() == env.constants.ann.defines_var;
}
/// Check if \a e is NULL or true
bool istrue(EnvI& env, Expression* e) {
if (e == nullptr) {
return true;
}
if (Expression::type(e) == Type::parbool()) {
if (Expression::type(e).cv()) {
Ctx ctx;
ctx.b = C_MIX;
KeepAlive r = flat_cv_exp(env, ctx, e);
return eval_bool(env, r());
}
GCLock lock;
return eval_bool(env, e);
}
return false;
}
/// Check if \a e is non-NULL and false
bool isfalse(EnvI& env, Expression* e) {
if (e == nullptr) {
return false;
}
if (Expression::type(e) == Type::parbool()) {
if (Expression::type(e).cv()) {
Ctx ctx;
ctx.b = C_MIX;
KeepAlive r = flat_cv_exp(env, ctx, e);
return !eval_bool(env, r());
}
GCLock lock;
return !eval_bool(env, e);
}
return false;
}
/// Use bounds from ovd for vd if they are better.
/// Returns true if ovd's bounds are better.
bool update_bounds(EnvI& envi, VarDecl* ovd, VarDecl* vd) {
bool tighter = false;
bool fixed = false;
if ((ovd->ti()->domain() != nullptr) || (ovd->e() != nullptr)) {
IntVal intval;
FloatVal doubleval;
bool boolval;
if (vd->type().isint()) {
IntBounds oldbounds = compute_int_bounds(envi, ovd->id());
IntBounds bounds(0, 0, false);
if ((vd->ti()->domain() != nullptr) || (vd->e() != nullptr)) {
bounds = compute_int_bounds(envi, vd->id());
}
if (((vd->ti()->domain() != nullptr) || (vd->e() != nullptr)) && bounds.valid &&
bounds.l.isFinite() && bounds.u.isFinite()) {
if (oldbounds.valid && oldbounds.l.isFinite() && oldbounds.u.isFinite()) {
fixed = oldbounds.u == oldbounds.l || bounds.u == bounds.l;
if (fixed) {
tighter = true;
intval = oldbounds.u == oldbounds.l ? oldbounds.u : bounds.l;
ovd->ti()->domain(new SetLit(Expression::loc(ovd), IntSetVal::a(intval, intval)));
} else {
IntSetVal* olddom =
ovd->ti()->domain() != nullptr ? eval_intset(envi, ovd->ti()->domain()) : nullptr;
IntSetVal* newdom =
vd->ti()->domain() != nullptr ? eval_intset(envi, vd->ti()->domain()) : nullptr;
if (olddom != nullptr) {
if (newdom == nullptr) {
tighter = true;
} else {
IntSetRanges oisr(olddom);
IntSetRanges nisr(newdom);
IntSetRanges nisr_card(newdom);
Ranges::Inter<IntVal, IntSetRanges, IntSetRanges> inter(oisr, nisr);
if (Ranges::cardinality(inter) < Ranges::cardinality(nisr_card)) {
IntSetRanges oisr_inter(olddom);
IntSetRanges nisr_inter(newdom);
Ranges::Inter<IntVal, IntSetRanges, IntSetRanges> inter_card(oisr_inter,
nisr_inter);
tighter = true;
ovd->ti()->domain(new SetLit(Expression::loc(ovd), IntSetVal::ai(inter_card)));
}
}
}
}
}
} else {
if (oldbounds.valid && oldbounds.l.isFinite() && oldbounds.u.isFinite()) {
tighter = true;
fixed = oldbounds.u == oldbounds.l;
if (fixed) {
intval = oldbounds.u;
ovd->ti()->domain(new SetLit(Expression::loc(ovd), IntSetVal::a(intval, intval)));
}
}
}
} else if (vd->type().isfloat()) {
FloatBounds oldbounds = compute_float_bounds(envi, ovd->id());
FloatBounds bounds(0.0, 0.0, false);
if ((vd->ti()->domain() != nullptr) || (vd->e() != nullptr)) {
bounds = compute_float_bounds(envi, vd->id());
}
if (((vd->ti()->domain() != nullptr) || (vd->e() != nullptr)) && bounds.valid) {
if (oldbounds.valid) {
fixed = oldbounds.u == oldbounds.l || bounds.u == bounds.l;
if (fixed) {
doubleval = oldbounds.u == oldbounds.l ? oldbounds.u : bounds.l;
}
tighter = fixed || (oldbounds.u - oldbounds.l < bounds.u - bounds.l);
}
} else {
if (oldbounds.valid) {
tighter = true;
fixed = oldbounds.u == oldbounds.l;
if (fixed) {
doubleval = oldbounds.u;
}
}
}
} else if (vd->type().isbool()) {
if (ovd->ti()->domain() != nullptr) {
fixed = tighter = true;
boolval = eval_bool(envi, ovd->ti()->domain());
} else {
fixed = tighter = ((ovd->e() != nullptr) && Expression::isa<BoolLit>(ovd->e()));
if (fixed) {
boolval = Expression::cast<BoolLit>(ovd->e())->v();
}
}
}
if (tighter) {
vd->ti()->domain(ovd->ti()->domain());
if (vd->e() == nullptr && fixed) {
if (vd->ti()->type().isvarint()) {
Expression::type(vd, Type::parint());
vd->ti(new TypeInst(Expression::loc(vd), Type::parint()));
vd->e(IntLit::a(intval));
} else if (vd->ti()->type().isvarfloat()) {
Expression::type(vd, Type::parfloat());
vd->ti(new TypeInst(Expression::loc(vd), Type::parfloat()));
vd->e(FloatLit::a(doubleval));
} else if (vd->ti()->type().isvarbool()) {
Expression::type(vd, Type::parbool());
vd->ti(new TypeInst(Expression::loc(vd), Type::parbool()));
vd->ti()->domain(envi.constants.boollit(boolval));
vd->e(new BoolLit(Expression::loc(vd), boolval));
}
}
}
}
return tighter;
}
std::string get_path(EnvI& env) {
std::string path;
std::stringstream ss;
if (env.dumpPath(ss)) {
path = ss.str();
}
return path;
}
inline Location get_loc(EnvI& env, Expression* e1, Expression* e2) {
if (e1 != nullptr) {
return Expression::loc(e1).introduce();
}
if (e2 != nullptr) {
return Expression::loc(e2).introduce();
}
return Location().introduce();
}
inline Id* get_id(EnvI& env, Id* origId) {
return origId != nullptr ? origId : new Id(Location().introduce(), env.genId(), nullptr);
}
StringLit* get_longest_mzn_path_annotation(EnvI& env, const Expression* e) {
StringLit* sl = nullptr;
if (const auto* vd = Expression::dynamicCast<const VarDecl>(e)) {
VarPathStore::ReversePathMap& reversePathMap = env.varPathStore.getReversePathMap();
auto it = reversePathMap.find(vd->id()->decl());
if (it != reversePathMap.end()) {
sl = new StringLit(Location(), it->second);
}
} else {
for (ExpressionSetIter it = Expression::ann(e).begin(); it != Expression::ann(e).end(); ++it) {
if (Call* ca = Expression::dynamicCast<Call>(*it)) {
if (ca->id() == env.constants.ann.mzn_path) {
auto* sl1 = Expression::cast<StringLit>(ca->arg(0));
if (sl != nullptr) {
if (sl1->v().size() > sl->v().size()) {
sl = sl1;
}
} else {
sl = sl1;
}
}
}
}
}
return sl;
}
void add_path_annotation(EnvI& env, Expression* e) {
if (!(Expression::type(e).isAnn() || Expression::isa<Id>(e)) && Expression::type(e).dim() == 0) {
GCLock lock;
Annotation& ann = Expression::ann(e);
if (ann.containsCall(env.constants.ann.mzn_path)) {
return;
}
VarPathStore::ReversePathMap& reversePathMap = env.varPathStore.getReversePathMap();
std::vector<Expression*> path_args(1);
std::string p;
auto it = reversePathMap.find(e);
if (it == reversePathMap.end()) {
p = get_path(env);
} else {
p = it->second;
}
if (!p.empty()) {
path_args[0] = new StringLit(Location(), p);
Call* path_call = Call::a(Expression::loc(e), env.constants.ann.mzn_path, path_args);
Expression::type(path_call, Type::ann());
Expression::addAnnotation(e, path_call);
}
}
}
void flatten_vardecl_annotations(EnvI& env, VarDecl* origVd, VarDeclI* vdi, VarDecl* toAnnotate) {
for (ExpressionSetIter it = Expression::ann(origVd).begin(); it != Expression::ann(origVd).end();
++it) {
// Check if we need to add the annotated expression as an argument
Call* addAnnotatedExpression = nullptr;
if (Id* ident = Expression::dynamicCast<Id>(*it)) {
if (ident->decl() != nullptr) {
addAnnotatedExpression =
Expression::ann(ident->decl()).getCall(env.constants.ann.mzn_add_annotated_expression);
}
} else if (Call* call = Expression::dynamicCast<Call>(*it)) {
if (call->decl() != nullptr) {
addAnnotatedExpression =
call->decl()->ann().getCall(env.constants.ann.mzn_add_annotated_expression);
}
}
KeepAlive ann;
if (addAnnotatedExpression != nullptr) {
GCLock lock;
Call* c;
if (Expression::isa<Id>(*it)) {
c = Call::a(Location().introduce(), Expression::cast<Id>(*it)->v(), {toAnnotate->id()});
} else {
unsigned int annotatedExpressionIdx =
static_cast<unsigned int>(eval_int(env, addAnnotatedExpression->arg(0)).toInt());
Call* orig_call = Expression::cast<Call>(*it);
std::vector<Expression*> args(orig_call->argCount() + 1);
for (unsigned int i = 0, j = 0; i < orig_call->argCount(); i++) {
if (j == annotatedExpressionIdx) {
args[j++] = toAnnotate->id();
}
args[j++] = orig_call->arg(i);
}
if (annotatedExpressionIdx == orig_call->argCount()) {
args[orig_call->argCount()] = toAnnotate->id();
}
c = Call::a(Location().introduce(), Expression::cast<Call>(*it)->id(), args);
}
c->decl(env.model->matchFn(env, c, false));
Expression::type(c, Type::ann());
ann = c;
} else {
ann = *it;
}
EE ee_ann = flat_exp(env, Ctx(), ann(), nullptr, env.constants.varTrue);
if (vdi != nullptr) {
Expression::addAnnotation(toAnnotate, ee_ann.r());
CollectOccurrencesE ce(env, env.varOccurrences, vdi);
top_down(ce, ee_ann.r());
}
}
}
VarDecl* new_vardecl(EnvI& env, const Ctx& ctx, TypeInst* ti, Id* origId, VarDecl* origVd,
Expression* rhs) {
VarDecl* vd = nullptr;
// Is this vardecl already in the FlatZinc (for unification)
bool hasBeenAdded = false;
// Don't use paths for arrays or annotations
if (ti->type().dim() == 0 && !ti->type().isAnn()) {
std::string path = get_path(env);
if (!path.empty()) {
VarPathStore::ReversePathMap& reversePathMap = env.varPathStore.getReversePathMap();
VarPathStore::PathMap& pathMap = env.varPathStore.getPathMap();
auto it = pathMap.find(path);
if (it != pathMap.end()) {
auto* ovd = Expression::cast<VarDecl>((it->second.decl)());
unsigned int ovd_pass = it->second.passNumber;
if (ovd != nullptr) {
// If ovd was introduced during the same pass, we can unify
if (env.multiPassInfo.currentPassNumber == ovd_pass) {
vd = ovd;
if (origId != nullptr) {
origId->decl(vd);
}
hasBeenAdded = true;
} else {
vd = new VarDecl(get_loc(env, origVd, rhs), ti, get_id(env, origId));
hasBeenAdded = false;
update_bounds(env, ovd, vd);
}
// Check whether ovd was unified in a previous pass
if (ovd->id() != ovd->id()->decl()->id()) {
// We may not have seen the pointed to decl just yet
auto path2It = reversePathMap.find(ovd->id()->decl());
if (path2It != reversePathMap.end()) {
std::string path2 = path2It->second;
VarPathStore::PathVar vd_tup{vd, env.multiPassInfo.currentPassNumber};
pathMap[path] = vd_tup;
pathMap[path2] = vd_tup;
reversePathMap.insert(vd, path);
}
}
}
} else {
// Create new VarDecl and add it to the maps
vd = new VarDecl(get_loc(env, origVd, rhs), ti, get_id(env, origId));
hasBeenAdded = false;
VarPathStore::PathVar vd_tup{vd, env.multiPassInfo.currentPassNumber};
pathMap[path] = vd_tup;
reversePathMap.insert(vd, path);
}
}
}
if (vd == nullptr) {
vd = new VarDecl(get_loc(env, origVd, rhs), ti, get_id(env, origId));
hasBeenAdded = false;
}
// If vd has an e() use bind to turn rhs into a constraint
if (vd->e() != nullptr) {
if (rhs != nullptr) {
bind(env, ctx, vd, rhs);
}
} else {
vd->e(rhs);
if ((rhs != nullptr) && hasBeenAdded) {
// This variable is being reused, so it won't be added to the model below.
// Therefore, we need to register that we changed the RHS, in order
// for the reference counts to be accurate.
env.voAddExp(vd);
}
}
if ((origVd != nullptr) && (origVd->id()->idn() != -1 || origVd->toplevel())) {
vd->introduced(origVd->introduced());
} else {
vd->introduced(true);
}
vd->flat(vd);
VarDeclI* vdi;
if (hasBeenAdded) {
vdi = (*env.flat())[env.varOccurrences.find(vd)]->cast<VarDeclI>();
} else {
vdi = VarDeclI::a(Location().introduce(), vd);
env.flatAddItem(vdi);
}
// Copy annotations from origVd
if (origVd != nullptr) {
flatten_vardecl_annotations(env, origVd, vdi, vd);
}
return vd;
}
#define MZN_FILL_REIFY_MAP(T, ID) \
_reifyMap.insert(std::pair<ASTString, ASTString>(constants.ids.T.ID, constants.ids.T##reif.ID));
MultiPassInfo::MultiPassInfo() : currentPassNumber(0), finalPassNumber(1) {}
VarPathStore::VarPathStore() : maxPathDepth(0) {}
void OutputSectionStore::add(EnvI& env, ASTString section, Expression* e, bool json) {
if (json) {
auto ret = _idx.emplace(section, _sections.size());
if (ret.second) {
_sections.emplace_back(section, e, true);
} else {
std::stringstream ss;
ss << "JSON output section '" << section << "' already used. Ignoring.";
env.addWarning(Expression::loc(e), ss.str());
}
return;
}
_blank = false;
auto ret = _idx.emplace(section, _sections.size());
if (ret.second) {
_sections.emplace_back(section, e, false);
} else {
GCLock lock;
auto idx = ret.first->second;
auto* orig = _sections[idx].e;
auto* bo = new BinOp(Location().introduce(), orig, BOT_PLUSPLUS, e);
Expression::type(bo, Type::parstring(1));
_sections[idx].e = bo;
}
}
TupleType::TupleType(const std::vector<Type>& fields) {
_size = static_cast<unsigned int>(fields.size());
for (size_t i = 0; i < _size; ++i) {
_fields[i] = fields[i];
}
}
TupleType* TupleType::a(const std::vector<Type>& fields) {
TupleType* tt = static_cast<TupleType*>(::malloc(
sizeof(TupleType) + sizeof(Type) * (std::max(0, static_cast<int>(fields.size()) - 1))));
tt = new (tt) TupleType(fields);
return tt;
}
bool TupleType::matchesBT(const EnvI& env, const TupleType& other) const {
if (other.size() != size()) {
return false;
}
for (unsigned int i = 0; i < other.size(); ++i) {
const Type& ty = operator[](i);
if (ty.bt() != Type::BT_BOT || other[i].bt() != Type::BT_BOT) {
continue;
}
if (other[i].bt() != Type::BT_TOP && ty.bt() != other[i].bt()) {
return false;
}
if (ty.bt() == Type::BT_TUPLE &&
!env.getTupleType(ty)->matchesBT(env, *env.getTupleType(other[i]))) {
return false;
}
if (ty.bt() == Type::BT_RECORD &&
!env.getRecordType(ty)->matchesBT(env, *env.getRecordType(other[i]))) {
return false;
}
}
return true;
}
bool StructType::containsArray(const EnvI& env) const {
for (unsigned int i = 0; i < size(); ++i) {
const Type& ti = operator[](i);
if (ti.dim() != 0) {
return true;
}
if (ti.structBT() && env.getStructType(ti)->containsArray(env)) {
return true;
}
}
return false;
}
RecordType::RecordType(const std::vector<std::pair<ASTString, Type>>& fields) {
_size = static_cast<unsigned int>(fields.size());
size_t str_size = 0;
for (size_t i = 0; i < _size; ++i) {
_fields[i] = {str_size, fields[i].second};
str_size += fields[i].first.size();
}
_fieldNames.reserve(str_size);
for (size_t i = 0; i < _size; ++i) {
_fieldNames.append(std::string(fields[i].first.c_str()));
}
}
RecordType::RecordType(const RecordType& orig) {
_size = orig._size;
_fieldNames = orig._fieldNames;
for (size_t i = 0; i < _size; ++i) {
_fields[i] = orig._fields[i];
}
}
RecordType* RecordType::a(const std::vector<std::pair<ASTString, Type>>& fields) {
RecordType* tt = static_cast<RecordType*>(::malloc(
sizeof(RecordType) + sizeof(FieldTup) * (std::max(0, static_cast<int>(fields.size()) - 1))));
tt = new (tt) RecordType(fields);
return tt;
}
RecordType* RecordType::a(const RecordType* orig, const std::vector<Type>& types) {
RecordType* tt = static_cast<RecordType*>(::malloc(
sizeof(RecordType) + sizeof(FieldTup) * (std::max(0, static_cast<int>(orig->size()) - 1))));
tt = new (tt) RecordType(*orig);
assert(orig->size() == types.size());
for (size_t i = 0; i < types.size(); i++) {
tt->_fields[i].second = types[i];
}
return tt;
}
bool RecordType::matchesBT(const EnvI& env, const RecordType& other) const {
if (other.size() != size()) {
return false;
}
for (unsigned int i = 0; i < other.size(); ++i) {
if (fieldName(i) != other.fieldName(i)) {
return false;
}
const Type& ty = operator[](i);
if (ty.bt() != Type::BT_BOT || other[i].bt() != Type::BT_BOT) {
continue;
}
if (other[i].bt() != Type::BT_TOP && ty.bt() != other[i].bt()) {
return false;
}
if (ty.bt() == Type::BT_TUPLE &&
!env.getTupleType(ty)->matchesBT(env, *env.getTupleType(other[i]))) {
return false;
}
if (ty.bt() == Type::BT_RECORD &&
!env.getRecordType(ty)->matchesBT(env, *env.getRecordType(other[i]))) {
return false;
}
}
return true;
}
EnvI::EnvI(Model* model0, std::ostream& outstream0, std::ostream& errstream0)
: model(model0),
originalModel(nullptr),
output(new Model),
constants(Constants::constants()),
outstream(outstream0),
errstream(errstream0),
ignorePartial(false),
ignoreUnknownIds(false),
maxCallStack(0),
inRedundantConstraint(0),
inSymmetryBreakingConstraint(0),
inMaybePartial(0),
inTraceExp(false),
inReverseMapVar(false),
warnImplicitEnum2Int(true),
counters({0, 0, 0, 0}),
_flat(new Model),
_failed(false),
_ids(0),
_collectVardecls(false) {
MZN_FILL_REIFY_MAP(int_, lin_eq);
MZN_FILL_REIFY_MAP(int_, lin_le);
MZN_FILL_REIFY_MAP(int_, lin_ne);
MZN_FILL_REIFY_MAP(int_, plus);
MZN_FILL_REIFY_MAP(int_, minus);
MZN_FILL_REIFY_MAP(int_, times);
MZN_FILL_REIFY_MAP(int_, div);
MZN_FILL_REIFY_MAP(int_, mod);
MZN_FILL_REIFY_MAP(int_, lt);
MZN_FILL_REIFY_MAP(int_, le);
MZN_FILL_REIFY_MAP(int_, gt);
MZN_FILL_REIFY_MAP(int_, ge);
MZN_FILL_REIFY_MAP(int_, eq);
MZN_FILL_REIFY_MAP(int_, ne);
MZN_FILL_REIFY_MAP(float_, lin_eq);
MZN_FILL_REIFY_MAP(float_, lin_le);
MZN_FILL_REIFY_MAP(float_, lin_lt);
MZN_FILL_REIFY_MAP(float_, lin_ne);
MZN_FILL_REIFY_MAP(float_, plus);
MZN_FILL_REIFY_MAP(float_, minus);
MZN_FILL_REIFY_MAP(float_, times);
MZN_FILL_REIFY_MAP(float_, div);
MZN_FILL_REIFY_MAP(float_, mod);
MZN_FILL_REIFY_MAP(float_, lt);
MZN_FILL_REIFY_MAP(float_, le);
MZN_FILL_REIFY_MAP(float_, gt);
MZN_FILL_REIFY_MAP(float_, ge);
MZN_FILL_REIFY_MAP(float_, eq);
MZN_FILL_REIFY_MAP(float_, ne);
_reifyMap.insert(std::pair<ASTString, ASTString>(constants.ids.forall, constants.ids.forallReif));
_reifyMap.insert(
std::pair<ASTString, ASTString>(constants.ids.bool_.eq, constants.ids.bool_reif.eq));
_reifyMap.insert(
std::pair<ASTString, ASTString>(constants.ids.bool_.clause, constants.ids.bool_reif.clause));
_reifyMap.insert(
std::pair<ASTString, ASTString>(constants.ids.clause, constants.ids.bool_reif.clause));
_reifyMap.insert({constants.ids.bool_.not_, constants.ids.bool_.not_});
}
EnvI::~EnvI() {
for (auto* _tupleType : _tupleTypes) {
TupleType::free(_tupleType);
}
delete _flat;
delete output;
delete model;
delete originalModel;
}
long long int EnvI::genId() { return _ids++; }
void EnvI::cseMapInsert(Expression* e, const EE& ee) {
GCLock lock;
if (Expression::type(e).isPar() && !Expression::isa<ArrayLit>(e)) {
return;
}
Call* c = Expression::dynamicCast<Call>(e);
if ((c != nullptr) && c->decl() != nullptr) {
if (c->decl()->ann().contains(constants.ann.no_cse)) {
return;
}
if (c->decl()->ann().contains(constants.ann.promise_commutative)) {
e = Call::commutativeNormalized(*this, c);
}
}
_cseMap.insert(e, WW(ee.r(), ee.b()));
if ((c != nullptr) && c->id() == constants.ids.bool_.not_ && Expression::isa<Id>(c->arg(0)) &&
Expression::isa<Id>(ee.r()) && ee.b() == constants.literalTrue) {
Call* neg_c = Call::a(Location().introduce(), c->id(), {ee.r()});
Expression::type(neg_c, Expression::type(e));
neg_c->decl(c->decl());
_cseMap.insert(neg_c, WW(c->arg(0), ee.b()));
}
}
EnvI::CSEMap::iterator EnvI::cseMapFind(Expression* e) {
GCLock lock;
Call* c = Expression::dynamicCast<Call>(e);
if ((c != nullptr) && c->decl() != nullptr) {
if (c->decl()->ann().contains(constants.ann.promise_commutative)) {
e = Call::commutativeNormalized(*this, c);
}
}
auto it = _cseMap.find(e);
if (it != _cseMap.end()) {
if (it->second.r != nullptr) {
VarDecl* it_vd = Expression::isa<Id>(it->second.r)
? Expression::cast<Id>(it->second.r)->decl()
: Expression::dynamicCast<VarDecl>(it->second.r);
if (it_vd != nullptr) {
int idx = varOccurrences.find(it_vd);
if (idx == -1 || (*_flat)[idx]->removed()) {
_cseMap.remove(e);
return _cseMap.end();
}
}
} else {
_cseMap.remove(e);
return _cseMap.end();
}
}
return it;
}
void EnvI::cseMapRemove(Expression* e) { _cseMap.remove(e); }
EnvI::CSEMap::iterator EnvI::cseMapEnd() { return _cseMap.end(); }
void EnvI::dump() {
struct EED {
static std::string k(Expression* e) {
std::ostringstream oss;
oss << *e;
return oss.str();
}
static std::string d(const WW& ee) {
std::ostringstream oss;
oss << *ee.r << " " << ee.b;
return oss.str();
}
};
_cseMap.dump<EED>();
}
void EnvI::flatAddItem(Item* i) {
assert(_flat);
if (_failed) {
return;
}
_flat->addItem(i);
Expression* toAnnotate = nullptr;
Expression* toAdd = nullptr;
switch (i->iid()) {
case Item::II_VD: {
auto* vd = i->cast<VarDeclI>();
add_path_annotation(*this, vd->e());
toAnnotate = vd->e()->e();
varOccurrences.addIndex(vd, _flat->size() - 1);
toAdd = vd->e();
break;
}
case Item::II_CON: {
auto* ci = i->cast<ConstraintI>();
if (Expression::isa<BoolLit>(ci->e()) && !Expression::cast<BoolLit>(ci->e())->v()) {
fail();
} else {
toAnnotate = ci->e();
add_path_annotation(*this, ci->e());
toAdd = ci->e();
}
break;
}
case Item::II_SOL: {
auto* si = i->cast<SolveI>();
CollectOccurrencesE ce(*this, varOccurrences, si);
top_down(ce, si->e());
for (ExpressionSetIter it = si->ann().begin(); it != si->ann().end(); ++it) {
top_down(ce, *it);
}
break;
}
case Item::II_OUT: {
auto* si = i->cast<OutputI>();
toAdd = si->e();
break;
}
default:
break;
}
if ((toAnnotate != nullptr) && Expression::isa<Call>(toAnnotate)) {
annotateFromCallStack(toAnnotate);
}
if (toAdd != nullptr) {
CollectOccurrencesE ce(*this, varOccurrences, i);
top_down(ce, toAdd);
}
}
void EnvI::annotateFromCallStack(Expression* e) {
int prev = !idStack.empty() ? idStack.back() : 0;
bool allCalls = true;
for (int i = static_cast<int>(callStack.size()) - 1; i >= prev; i--) {
Expression* ee = callStack[i].e;
if (Expression::type(ee).isAnn()) {
// If we are inside an annotation call, don't annotate it again with
// anything from outside the call
break;
}
if (Expression::isa<Call>(ee) && Expression::cast<Call>(ee)->decl() != nullptr &&
Expression::cast<Call>(ee)->decl()->capturedAnnotationsVar() != nullptr) {
// capturing annotations means they are not propagated
break;
}
allCalls = allCalls && (i == callStack.size() - 1 || Expression::isa<Call>(ee) ||
Expression::isa<BinOp>(ee));
for (ExpressionSetIter it = Expression::ann(ee).begin(); it != Expression::ann(ee).end();
++it) {
EE ee_ann = flat_exp(*this, Ctx(), *it, nullptr, constants.varTrue);
if (allCalls || !is_defines_var_ann(*this, ee_ann.r())) {
Expression::addAnnotation(e, ee_ann.r());
}
}
}
}
ArrayLit* EnvI::createAnnotationArray(const BCtx& ctx) {
std::vector<Expression*> annotations;
int prev = !idStack.empty() ? idStack.back() : 0;
bool allCalls = true;
for (int i = static_cast<int>(callStack.size()) - 1; i >= prev; i--) {
Expression* ee = callStack[i].e;
if (Expression::type(ee).isAnn()) {
// If we are inside an annotation call, don't annotate it again with
// anything from outside the call
break;
}
if (i != static_cast<int>(callStack.size()) - 1 && Expression::isa<Call>(ee) &&
Expression::cast<Call>(ee)->decl() != nullptr &&
Expression::cast<Call>(ee)->decl()->capturedAnnotationsVar() != nullptr &&
!callStack[i].replaced) {
// capturing annotations means they are not propagated
break;
}
allCalls = allCalls && (i == callStack.size() - 1 || Expression::isa<Call>(ee) ||
Expression::isa<BinOp>(ee));
for (ExpressionSetIter it = Expression::ann(ee).begin(); it != Expression::ann(ee).end();
++it) {
EE ee_ann = flat_exp(*this, Ctx(), *it, nullptr, constants.varTrue);
if (allCalls || !is_defines_var_ann(*this, ee_ann.r())) {
annotations.push_back(ee_ann.r());
}
}
}
if (ctx != C_MIX) {
Expression* ctx_ann;
if (ctx == C_ROOT) {
ctx_ann = constants.ctx.root;
} else if (ctx == C_POS) {
ctx_ann = constants.ctx.pos;
} else {
ctx_ann = constants.ctx.neg;
}
annotations.push_back(ctx_ann);
}
auto* al = new ArrayLit(Location(), annotations);
Expression::type(al, Type::ann(1));
return al;
}
void EnvI::copyPathMapsAndState(EnvI& env) {
multiPassInfo.finalPassNumber = env.multiPassInfo.finalPassNumber;
multiPassInfo.currentPassNumber = env.multiPassInfo.currentPassNumber;
varPathStore.pathMap = env.varPathStore.getPathMap();
varPathStore.reversePathMap = env.varPathStore.getReversePathMap();
varPathStore.filenameSet = env.varPathStore.filenameSet;
varPathStore.maxPathDepth = env.varPathStore.maxPathDepth;
}
void EnvI::flatRemoveExpr(Expression* e, Item* i) {
std::vector<VarDecl*> toRemove;
CollectDecls cd(*this, varOccurrences, toRemove, i);
top_down(cd, e);
Model& flat = (*_flat);
while (!toRemove.empty()) {
VarDecl* cur = toRemove.back();
toRemove.pop_back();
assert(varOccurrences.occurrences(cur) == 0 && CollectDecls::varIsFree(cur));
auto cur_idx = varOccurrences.idx.find(cur->id());
if (cur_idx.first) {
auto* vdi = flat[*cur_idx.second]->cast<VarDeclI>();
if (!is_output(vdi->e()) && !vdi->removed()) {
CollectDecls cd(*this, varOccurrences, toRemove, vdi);
top_down(cd, vdi->e()->e());
vdi->remove();
}
}
}
}
void EnvI::flatRemoveItem(ConstraintI* ci) {
flatRemoveExpr(ci->e(), ci);
ci->e(constants.literalTrue);
ci->remove();
}
void EnvI::flatRemoveItem(VarDeclI* vdi) {
flatRemoveExpr(vdi->e(), vdi);
vdi->remove();
}
void EnvI::fail(const std::string& msg, const Location& loc) {
if (!_failed) {
addWarning(loc, std::string("model inconsistency detected") +
(msg.empty() ? std::string() : (": " + msg)));
_failed = true;
for (auto& i : *_flat) {
i->remove();
}
auto* failedConstraint = new ConstraintI(Location().introduce(), constants.literalFalse);
_flat->addItem(failedConstraint);
_flat->addItem(SolveI::sat(Location().introduce()));
for (auto& i : *output) {
i->remove();
}
output->addItem(
new OutputI(Location().introduce(), new ArrayLit(Location(), std::vector<Expression*>())));
throw ModelInconsistent(*this, Location().introduce(), msg);
}
}
bool EnvI::failed() const { return _failed; }
unsigned int EnvI::registerEnum(VarDeclI* vdi) {
auto it = _enumMap.find(vdi);
unsigned int ret;
if (it == _enumMap.end()) {
ret = static_cast<unsigned int>(_enumVarDecls.size());
_enumVarDecls.push_back(vdi);
_enumMap.insert(std::make_pair(vdi, ret));
} else {
ret = it->second;
}
return ret + 1;
}
VarDeclI* EnvI::getEnum(unsigned int i) const {
assert(i > 0 && i <= _enumVarDecls.size());
return _enumVarDecls[i - 1];
}
unsigned int EnvI::registerArrayEnum(const std::vector<unsigned int>& arrayEnum) {
std::ostringstream oss;
bool allZero = true;
for (unsigned int i : arrayEnum) {
assert(i <= _enumVarDecls.size() || i <= _tupleTypes.size() || i <= _recordTypes.size());
oss << i << ".";
allZero = allZero && (i == 0);
}
if (allZero) {
return 0;
}
auto it = _arrayEnumMap.find(oss.str());
unsigned int ret;
if (it == _arrayEnumMap.end()) {
ret = static_cast<unsigned int>(_arrayEnumDecls.size());
_arrayEnumDecls.push_back(arrayEnum);
_arrayEnumMap.insert(std::make_pair(oss.str(), ret));
} else {
ret = it->second;
}
return ret + 1;
}
const std::vector<unsigned int>& EnvI::getArrayEnum(unsigned int i) const {
assert(i > 0 && i <= _arrayEnumDecls.size());
return _arrayEnumDecls[i - 1];
}
unsigned int EnvI::registerTupleType(const std::vector<Type>& fields) {
assert(!fields.empty());
auto* tt = TupleType::a(fields);
auto it = _tupleTypeMap.find(tt);
unsigned int ret;
if (it == _tupleTypeMap.end()) {
ret = static_cast<unsigned int>(_tupleTypes.size());
_tupleTypes.push_back(tt);
_tupleTypeMap.emplace(std::make_pair(tt, ret));
} else {
TupleType::free(tt);
ret = it->second;
}
return ret + 1;
}
unsigned int EnvI::registerTupleType(TypeInst* ti) {
auto* dom = Expression::cast<ArrayLit>(ti->domain());
bool isArrayOfArray = getTransparentType(dom) != Expression::type(dom);
std::vector<Type> fields(isArrayOfArray ? 2 : dom->size());
bool cv = false;
bool var = true;
for (unsigned int i = 0; i < dom->size(); i++) {
auto* tii = Expression::cast<TypeInst>((*dom)[i]);
// Register tuple field type when required
if (tii->type().bt() == Type::BT_TUPLE && tii->type().typeId() == 0) {
registerTupleType(tii);
} else if (tii->type().bt() == Type::BT_RECORD && tii->type().typeId() == 0) {
registerRecordType(tii);
}
fields[i] = tii->type();
cv = cv || fields[i].isvar() || fields[i].cv();
var = var && fields[i].isvar();
}
if (isArrayOfArray) {
// Add marker for array of array
fields[1] = Type();
}
// the TI_VAR ti is not processed by this function. This cononicalisation should have been done
// during typechecking.
assert(ti->type().ti() == Type::TI_PAR || var);
unsigned int ret = registerTupleType(fields);
Type t = ti->type();
t.typeId(0); // Reset any current TypeId
t.cv(cv);
t.ti(var ? Type::TI_VAR : Type::TI_PAR);
// Register an array type when required
if (!ti->ranges().empty()) {
assert(t.dim() != 0);
std::vector<unsigned int> typeIds(ti->ranges().size() + 1);
for (unsigned int i = 0; i < ti->ranges().size(); i++) {
typeIds[i] = ti->ranges()[i]->type().typeId();
}
typeIds[ti->ranges().size()] = ret;
ret = registerArrayEnum(typeIds);
} else {
assert(t.dim() == 0);
}
t.typeId(ret);
Expression::type(ti, t);
Expression::type(ti->domain(), t.elemType(*this));
return ret;
}
unsigned int EnvI::registerTupleType(ArrayLit* tup) {
assert(tup->isTuple() && tup->dims() == 1);
Type ty = tup->type();
bool isArrayOfArray = ty.typeId() != 0 && getTupleType(ty.typeId())->size() != tup->size();
ty.bt(Type::BT_TUPLE);
ty.typeId(0); // Reset any current TypeId
std::vector<Type> fields(isArrayOfArray ? 2 : tup->size());
bool cv = false;
bool var = true;
for (unsigned int i = 0; i < tup->size(); i++) {
fields[i] = Expression::type((*tup)[i]);
cv = cv || fields[i].isvar() || fields[i].cv();
var = var && fields[i].isvar();
assert(!fields[i].structBT() || fields[i].typeId() != 0);
}
if (isArrayOfArray) {
fields[1] = Type();
}
unsigned int typeId = registerTupleType(fields);
assert(ty.dim() == 0); // Tuple literals do not have array dimensions (otherwise, we should
// register arrayEnumTypes)
ty.cv(cv);
ty.ti(var ? Type::TI_VAR : Type::TI_PAR);
ty.typeId(typeId);
Expression::type(tup, ty);
return typeId;
}
Type EnvI::commonTuple(Type tuple1, Type tuple2, bool ignoreTuple1Dim) {
if (tuple1 == tuple2) {
return tuple1;
}
if (tuple1.isunknown() || tuple2.isunknown()) {
return Type();
}
// Allow to ignore the dimensions of (in progress) LHS when arrayEnumIds not yet in use
int oldDim = tuple1.dim();
if (ignoreTuple1Dim) {
unsigned int typeId = tuple1.typeId();
tuple1.typeId(0);
tuple1.dim(0);
tuple1.typeId(typeId);
}
if (tuple1.dim() != tuple2.dim()) {
return Type();
}
TupleType* tt1 = getTupleType(tuple1);
TupleType* tt2 = getTupleType(tuple2);
if (tt1->size() != tt2->size()) {
return Type();
}
std::vector<Type> common(tt1->size());
for (unsigned int i = 0; i < tt1->size(); i++) {
common[i] = Type::commonType(*this, (*tt1)[i], (*tt2)[i]);
if (common[i].isunknown()) {
return Type();
}
}
unsigned int typeId = registerTupleType(common);
if (ignoreTuple1Dim) {
tuple1.typeId(0);
tuple1.dim(oldDim);
} else if (tuple1.dim() != 0) {
const std::vector<unsigned int>& arrayEnumIds1 = getArrayEnum(tuple1.typeId());
const std::vector<unsigned int>& arrayEnumIds2 = getArrayEnum(tuple2.typeId());
std::vector<unsigned int> typeIds(tuple1.dim() + 1);
for (int i = 0; i < tuple1.dim(); i++) {
if (arrayEnumIds1[i] == arrayEnumIds2[i]) {
typeIds[i] = arrayEnumIds1[i];
} else {
typeIds[i] = 0;
}
}
typeIds[tuple1.dim()] = typeId;
typeId = registerArrayEnum(typeIds);
}
tuple1.typeId(typeId);
tuple1.cv(tuple1.cv() || tuple2.cv());
assert(tuple1.bt() != Type::BT_TUPLE || tuple1.typeId() != 0);
return tuple1;
}
Type EnvI::commonRecord(Type record1, Type record2, bool ignoreRecord1Dim) {
if (record1 == record2) {
return record1;
}
if (record1.isunknown() || record2.isunknown()) {
return Type();
}
// Allow to ignore the dimensions of (in progress) LHS when arrayEnumIds not yet in use
int oldDim = record1.dim();
if (ignoreRecord1Dim) {
unsigned int typeId = record1.typeId();
record1.typeId(0);
record1.dim(0);
record1.typeId(typeId);
}
if (record1.dim() != record2.dim()) {
return Type();
}
RecordType* rt1 = getRecordType(record1);
RecordType* rt2 = getRecordType(record2);
if (rt1->size() != rt2->size()) {
return Type();
}
std::vector<std::pair<ASTString, Type>> common(rt1->size());
for (unsigned int i = 0; i < rt1->size(); i++) {
ASTString name(rt1->fieldName(i));
if (name != rt2->fieldName(i)) {
return Type();
}
Type ct = Type::commonType(*this, (*rt1)[i], (*rt2)[i]);
if (ct.isunknown()) {
return Type();
}
common[i] = {name, ct};
}
unsigned int typeId = registerRecordType(common);
if (ignoreRecord1Dim) {
record1.typeId(0);
record1.dim(oldDim);
} else if (record1.dim() != 0) {
const std::vector<unsigned int>& arrayEnumIds1 = getArrayEnum(record1.typeId());
const std::vector<unsigned int>& arrayEnumIds2 = getArrayEnum(record2.typeId());
std::vector<unsigned int> typeIds(record1.dim() + 1);
for (int i = 0; i < record1.dim(); i++) {
if (arrayEnumIds1[i] == arrayEnumIds2[i]) {
typeIds[i] = arrayEnumIds1[i];
} else {
typeIds[i] = 0;
}
}
typeIds[record1.dim()] = typeId;
typeId = registerArrayEnum(typeIds);
}
record1.typeId(typeId);
record1.cv(record1.cv() || record2.cv());
return record1;
}
Type EnvI::mergeRecord(Type record1, Type record2, Location loc) {
RecordType* fields1 = getRecordType(record1);
RecordType* fields2 = getRecordType(record2);
RecordFieldSort cmp;
std::vector<std::pair<ASTString, Type>> all_fields;
const unsigned int total_size = fields1->size() + fields2->size();
all_fields.reserve(total_size);
unsigned int l = 0;
unsigned int r = 0;
for (unsigned int i = 0; i < total_size; i++) {
if (l >= fields1->size()) {
// must choose rhs
all_fields.emplace_back(fields2->fieldName(r), (*fields2)[r]);
++r;
} else if (r >= fields2->size()) {
// must choose lhs
all_fields.emplace_back(fields1->fieldName(l), (*fields1)[l]);
++l;
} else {
ASTString lhsN(fields1->fieldName(l));
ASTString rhsN(fields2->fieldName(r));
if (cmp(lhsN, rhsN)) {
// lhsN < rhsN
all_fields.emplace_back(lhsN, (*fields1)[l]);
++l;
} else {
all_fields.emplace_back(rhsN, (*fields2)[r]);
++r;
}
}
if (i > 0 && all_fields[i].first == all_fields[i - 1].first) {
std::ostringstream ss;
ss << "cannot merge of record types `" << record1.toString(*this) << "' and `"
<< record2.toString(*this) << "'. Both record types contain a field with the name `"
<< all_fields[i].first << "'";
throw TypeError(*this, loc, ss.str());
}
}
assert(r + l == all_fields.size());
unsigned int typeId = registerRecordType(all_fields);
bool is_var = record1.ti() == record2.ti() && record1.ti() == Type::TI_VAR;
bool is_cv = record1.cv() || record2.cv();
Type ret = Type::record(0, 0); // Delay TypeId until TI and CV is set
ret.ti(is_var ? Type::TI_VAR : Type::TI_PAR);
ret.cv(is_cv);
ret.typeId(typeId);
return ret;
}
Type EnvI::concatTuple(Type tuple1, Type tuple2) {
TupleType* fields1 = getTupleType(tuple1);
TupleType* fields2 = getTupleType(tuple2);
std::vector<Type> all_fields(fields1->size() + fields2->size());
for (unsigned int i = 0; i < fields1->size(); i++) {
all_fields[i] = (*fields1)[i];
}
for (unsigned int i = 0; i < fields2->size(); i++) {
all_fields[fields1->size() + i] = (*fields2)[i];
}
unsigned int typeId = registerTupleType(all_fields);
bool is_var = tuple1.ti() == tuple2.ti() && tuple1.ti() == Type::TI_VAR;
bool is_cv = tuple1.cv() || tuple2.cv();
Type ret = Type::tuple(0, 0); // Delay TypeId until TI and CV is set
ret.ti(is_var ? Type::TI_VAR : Type::TI_PAR);
ret.cv(is_cv);
ret.typeId(typeId);
return ret;
}
Type EnvI::getTransparentType(Type t) const {
if (t.istuple()) {
auto* tt = getTupleType(t);
if (tt->size() == 2 && (*tt)[1].isunknown()) {
return (*tt)[0];
}
}
return t;
}
Type EnvI::getTransparentType(const Expression* e) const {
return getTransparentType(Expression::type(e));
}
std::string EnvI::enumToString(unsigned int enumId, int i) {
Id* ti_id = getEnum(enumId)->e()->id();
ASTString enumName(create_enum_to_string_name(ti_id, "_toString_"));
auto* call = Call::a(Location().introduce(), enumName,
{IntLit::a(i), constants.boollit(true), constants.boollit(false)});
auto* fi = model->matchFn(*this, call, false, true);
assert(fi);
call->decl(fi);
Expression::type(call, Type::parstring());
return eval_string(*this, call);
}
bool EnvI::isSubtype(const Type& t10, const Type& t2, bool strictEnums) const {
Type t1 = t10;
if (t1.istuple() && t2.dim() != 0) {
auto* tupleType = getTupleType(t1);
if (tupleType->size() == 2 && (*tupleType)[1].isunknown()) {
t1 = (*tupleType)[0];
}
}
if (!t1.isSubtypeOf(*this, t2, strictEnums)) {
return false;
}
if (strictEnums && t1.bt() == Type::BT_INT && t1.dim() == 0 && t2.dim() != 0 &&
t2.typeId() != 0) {
// set assigned to an array
const std::vector<unsigned int>& t2enumIds = getArrayEnum(t2.typeId());
if (t2enumIds[t2enumIds.size() - 1] != 0 && t1.typeId() != t2enumIds[t2enumIds.size() - 1]) {
return false;
}
}
if (strictEnums && t1.bt() == Type::BT_INT && t1.dim() != 0 && t1.typeId() != t2.typeId()) {
if (t1.typeId() == 0) {
return t1.isbot();
}
if (t2.typeId() != 0) {
const std::vector<unsigned int>& t1enumIds = getArrayEnum(t1.typeId());
const std::vector<unsigned int>& t2enumIds = getArrayEnum(t2.typeId());
assert(t1enumIds.size() == t2enumIds.size());
for (unsigned int i = 0; i < t1enumIds.size() - 1; i++) {
if (t2enumIds[i] != 0 && t1enumIds[i] != t2enumIds[i]) {
return false;
}
}
if (!t1.isbot() && t2enumIds[t1enumIds.size() - 1] != 0 &&
t1enumIds[t1enumIds.size() - 1] != t2enumIds[t2enumIds.size() - 1]) {
return false;
}
}
}
return true;
}
#define register_rt(rt) \
do { \
auto it = _recordTypeMap.find(rt); \
unsigned int ret; \
if (it == _recordTypeMap.end()) { \
ret = static_cast<unsigned int>(_recordTypes.size()); \
_recordTypes.push_back(rt); \
_recordTypeMap.emplace(std::make_pair(rt, ret)); \
} else { \
RecordType::free(rt); \
ret = it->second; \
} \
return ret + 1; \
} while (0);
unsigned int EnvI::registerRecordType(const std::vector<std::pair<ASTString, Type>>& fields) {
assert(!fields.empty());
assert(std::is_sorted(fields.begin(), fields.end(), RecordFieldSort{}));
auto* rt = RecordType::a(fields);
register_rt(rt);
}
unsigned int EnvI::registerRecordType(const RecordType* orig, const std::vector<Type>& field_type) {
RecordType* rt = RecordType::a(orig, field_type);
register_rt(rt);
}
unsigned int EnvI::registerRecordType(ArrayLit* rec) {
assert(rec->isTuple() && rec->dims() == 1 && rec->type().isrecord());
Type ty = rec->type();
ty.bt(Type::BT_RECORD);
ty.typeId(0); // Reset any current TypeId
std::vector<VarDecl*> fields(rec->size());
bool cv = false;
bool var = true;
for (unsigned int i = 0; i < rec->size(); i++) {
fields[i] = Expression::cast<VarDecl>((*rec)[i]);
cv = cv || fields[i]->type().isvar() || fields[i]->type().cv();
var = var && fields[i]->type().isvar();
assert(!fields[i]->type().structBT() || fields[i]->type().typeId() != 0);
}
// Sort fields (and literal content)
std::sort(fields.begin(), fields.end(), RecordFieldSort{});
for (unsigned int i = 0; i < rec->size(); i++) {
rec->set(i, fields[i]->e());
}
std::vector<std::pair<ASTString, Type>> field_pairs(fields.size());
for (unsigned int i = 0; i < fields.size(); i++) {
field_pairs[i] = {fields[i]->id()->str(), fields[i]->type()};
if (i > 0 && field_pairs[i - 1].first == field_pairs[i].first) {
std::ostringstream oss;
oss << "record contains multiple fields with the name `" << field_pairs[i].first.c_str()
<< "'.";
throw TypeError(*this, Expression::loc(rec), oss.str());
}
}
unsigned int typeId = registerRecordType(field_pairs);
assert(ty.dim() == 0); // Tuple literals do not have array dimensions (otherwise, we should
// register arrayEnumTypes)
ty.cv(cv);
ty.ti(var ? Type::TI_VAR : Type::TI_PAR);
ty.typeId(typeId);
Expression::type(rec, ty);
return typeId;
}
unsigned int EnvI::registerRecordType(TypeInst* ti) {
auto* dom = Expression::cast<ArrayLit>(ti->domain());
// Register new Record
bool cv = false;
bool var = true;
unsigned int ret;
if (ti->type().typeId() == 0) {
std::vector<std::pair<ASTString, Type>> field_pairs(dom->size());
std::vector<VarDecl*> fields(dom->size());
for (unsigned int i = 0; i < dom->size(); i++) {
fields[i] = Expression::cast<VarDecl>((*dom)[i]);
// Register tuple field type when required
if (fields[i]->type().bt() == Type::BT_TUPLE && fields[i]->type().typeId() == 0) {
registerTupleType(fields[i]->ti());
Expression::type(fields[i], fields[i]->ti()->type());
} else if (fields[i]->type().bt() == Type::BT_RECORD && fields[i]->type().typeId() == 0) {
registerRecordType(fields[i]->ti());
Expression::type(fields[i], fields[i]->ti()->type());
}
cv = cv || fields[i]->type().isvar() || fields[i]->type().cv();
var = var && fields[i]->type().isvar();
}
// Sort fields (and literal content)
std::sort(fields.begin(), fields.end(), RecordFieldSort{});
for (unsigned int i = 0; i < dom->size(); i++) {
dom->set(i, fields[i]->ti());
}
for (unsigned int i = 0; i < fields.size(); i++) {
field_pairs[i] = {fields[i]->id()->str(), fields[i]->type()};
if (i > 0 && field_pairs[i - 1].first == field_pairs[i].first) {
std::ostringstream oss;
oss << "record type contains multiple fields with the name `"
<< field_pairs[i].first.c_str() << "'.";
throw TypeError(*this, Expression::loc(ti), oss.str());
}
}
ret = registerRecordType(field_pairs);
} else { // Update already registered Record (dom contains TypeInst, no need to sort)
std::vector<Type> types(dom->size());
RecordType* orig = getRecordType(ti->type());
for (unsigned int i = 0; i < types.size(); i++) {
types[i] = Expression::type((*dom)[i]);
cv = cv || Expression::type((*dom)[i]).isvar() || Expression::type((*dom)[i]).cv();
var = var && Expression::type((*dom)[i]).isvar();
}
ret = registerRecordType(orig, types);
}
// the TI_VAR ti is not processed by this function. This cononicalisation should have been done
// during typechecking.
assert(ti->type().ti() == Type::TI_PAR || var);
Type t = ti->type();
t.typeId(0); // Reset any current TypeId
t.cv(cv);
t.ti(var ? Type::TI_VAR : Type::TI_PAR);
// Register an array type when required
if (!ti->ranges().empty()) {
assert(t.dim() != 0);
std::vector<unsigned int> typeIds(ti->ranges().size() + 1);
for (unsigned int i = 0; i < ti->ranges().size(); i++) {
typeIds[i] = ti->ranges()[i]->type().typeId();
}
typeIds[ti->ranges().size()] = ret;
ret = registerArrayEnum(typeIds);
} else {
assert(t.dim() == 0);
}
t.typeId(ret);
Expression::type(ti, t);
Expression::type(ti->domain(), t.elemType(*this));
return ret;
}
void EnvI::collectVarDecls(bool b) { _collectVardecls = b; }
void EnvI::voAddExp(VarDecl* vd) {
if ((vd->e() != nullptr) && Expression::isa<Call>(vd->e()) &&
!Expression::type(vd->e()).isAnn()) {
int prev = !idStack.empty() ? idStack.back() : 0;
for (int i = static_cast<int>(callStack.size()) - 1; i >= prev; i--) {
Expression* ee = callStack[i].e;
for (ExpressionSetIter it = Expression::ann(ee).begin(); it != Expression::ann(ee).end();
++it) {
Expression* ann = *it;
if (ann != constants.ann.add_to_output && ann != constants.ann.output &&
ann != constants.ann.rhs_from_assignment) {
bool needAnnotation = true;
if (Call* ann_c = Expression::dynamicCast<Call>(ann)) {
if (ann_c->id() == constants.ann.defines_var) {
// only add defines_var annotation if vd is the defined variable
if (Id* defined_var = Expression::dynamicCast<Id>(ann_c->arg(0))) {
if (defined_var->decl() != vd->id()->decl()) {
needAnnotation = false;
}
}
}
}
if (needAnnotation) {
EE ee_ann = flat_exp(*this, Ctx(), *it, nullptr, constants.varTrue);
Expression::addAnnotation(vd->e(), ee_ann.r());
}
}
}
}
}
int idx = varOccurrences.find(vd);
CollectOccurrencesE ce(*this, varOccurrences, (*_flat)[idx]);
top_down(ce, vd->e());
if (_collectVardecls) {
modifiedVarDecls.push_back(idx);
}
}
Model* EnvI::flat() { return _flat; }
void EnvI::swap() {
Model* tmp = model;
model = _flat;
_flat = tmp;
}
ASTString EnvI::reifyId(const ASTString& id) {
auto it = _reifyMap.find(id);
if (it == _reifyMap.end()) {
std::ostringstream ss;
ss << id << "_reif";
return ASTString(ss.str());
}
return it->second;
}
#undef MZN_FILL_REIFY_MAP
ASTString EnvI::halfReifyId(const ASTString& id) {
std::ostringstream ss;
ss << id << "_imp";
return ASTString(ss.str());
}
int EnvI::addWarning(const std::string& msg) { return addWarning(Location(), msg, false); }
int EnvI::addWarning(const Location& loc, const std::string& msg, bool dumpStack) {
if (fopts.supressWarnings) {
return -1;
}
if (warnings.size() >= 20) {
if (warnings.size() == 20) {
warnings.emplace_back(new Warning("Further warnings have been suppressed."));
}
return -1;
}
if (dumpStack) {
warnings.emplace_back(new Warning(*this, loc, msg));
} else {
warnings.emplace_back(new Warning(loc, msg));
}
return static_cast<int>(warnings.size()) - 1;
}
Call* EnvI::surroundingCall() const {
if (callStack.size() >= 2) {
return Expression::dynamicCast<Call>(callStack[callStack.size() - 2].e);
}
return nullptr;
}
void EnvI::cleanupExceptOutput() {
cmap.clear();
_cseMap.clear();
delete _flat;
delete model;
delete originalModel;
_flat = nullptr;
model = nullptr;
}
bool EnvI::outputSectionEnabled(ASTString section) const {
return fopts.notSections.count(section.c_str()) == 0 &&
(fopts.onlySections.empty() || fopts.onlySections.count(section.c_str()) > 0);
}
std::string EnvI::show(Expression* e) {
auto* call = Call::a(Location().introduce(), constants.ids.show, {e});
call->decl(model->matchFn(*this, call, false));
Expression::type(call, Type::parstring());
return eval_string(*this, call);
}
std::string EnvI::show(const IntVal& iv, unsigned int enumId) {
if (enumId == 0 || !iv.isFinite()) {
std::stringstream ss;
ss << iv;
return ss.str();
}
return enumToString(enumId, static_cast<int>(iv.toInt()));
}
std::string EnvI::show(IntSetVal* isv, unsigned int enumId) {
auto* sl = new SetLit(Location().introduce(), isv);
Type t = sl->type();
t.typeId(enumId);
Expression::type(sl, t);
return show(sl);
}
CallStackItem::CallStackItem(EnvI& env0, Expression* e, const Ctx& ctx)
: _env(env0), _csiType(CSI_NONE) {
assert(Expression::type(e).bt() != Type::BT_UNKNOWN);
env0.checkCancel();
if (Expression::isa<VarDecl>(e)) {
_env.idStack.push_back(static_cast<int>(_env.callStack.size()));
_csiType = CSI_VD;
} else if (Expression::isa<Call>(e)) {
if (Expression::cast<Call>(e)->id() == _env.constants.ids.redundant_constraint) {
_env.inRedundantConstraint++;
_csiType = CSI_REDUNDANT;
} else if (Expression::cast<Call>(e)->id() == _env.constants.ids.symmetry_breaking_constraint) {
_env.inSymmetryBreakingConstraint++;
_csiType = CSI_SYMMETRY;
}
}
if (Expression::ann(e).contains(_env.constants.ann.maybe_partial)) {
_env.inMaybePartial++;
_maybePartial = true;
} else {
_maybePartial = false;
}
_env.callStack.emplace_back(e, false, ctx);
_env.maxCallStack = std::max(_env.maxCallStack, static_cast<unsigned int>(_env.callStack.size()));
}
CallStackItem::CallStackItem(EnvI& env0, Id* ident, IntVal i)
: _env(env0), _csiType(CSI_NONE), _maybePartial(false) {
_env.callStack.emplace_back(ident, true, Ctx());
_env.maxCallStack = std::max(_env.maxCallStack, static_cast<unsigned int>(_env.callStack.size()));
}
void CallStackItem::replace() { _env.callStack.back().replaced = true; }
CallStackItem::~CallStackItem() {
switch (_csiType) {
case CSI_NONE:
break;
case CSI_VD:
_env.idStack.pop_back();
break;
case CSI_REDUNDANT:
_env.inRedundantConstraint--;
break;
case CSI_SYMMETRY:
_env.inSymmetryBreakingConstraint--;
break;
}
if (_maybePartial) {
_env.inMaybePartial--;
}
assert(!_env.callStack.empty());
_env.callStack.pop_back();
}
FlatteningError::FlatteningError(EnvI& env, const Location& loc, const std::string& msg)
: LocationException(env, loc, msg) {}
Env::Env(Model* m, std::ostream& outstream, std::ostream& errstream)
: _e(new EnvI(m, outstream, errstream)) {}
Env::~Env() { delete _e; }
Model* Env::model() { return _e->model; }
void Env::model(Model* m) { _e->model = m; }
Model* Env::flat() { return _e->flat(); }
void Env::swap() { _e->swap(); }
Model* Env::output() { return _e->output; }
std::ostream& Env::evalOutput(std::ostream& os, std::ostream& log) {
return _e->evalOutput(os, log);
}
EnvI& Env::envi() { return *_e; }
const EnvI& Env::envi() const { return *_e; }
bool EnvI::dumpPath(std::ostream& os, bool force) {
force = force ? force : fopts.collectMznPaths;
if (callStack.size() > varPathStore.maxPathDepth) {
if (!force && multiPassInfo.currentPassNumber >= multiPassInfo.finalPassNumber - 1) {
return false;
}
varPathStore.maxPathDepth = static_cast<int>(callStack.size());
}
auto lastError = static_cast<unsigned int>(callStack.size());
std::string major_sep = ";";
std::string minor_sep = "|";
for (unsigned int i = 0; i < lastError; i++) {
Expression* e = callStack[i].e;
bool isCompIter = callStack[i].tag;
Location loc = Expression::loc(e);
auto findFilename = varPathStore.filenameSet.find(loc.filename());
if (findFilename == varPathStore.filenameSet.end()) {
if (!force && multiPassInfo.currentPassNumber >= multiPassInfo.finalPassNumber - 1) {
return false;
}
varPathStore.filenameSet.insert(loc.filename());
}
// If this call is not a dummy StringLit with empty Location (so that deferred compilation
// doesn't drop the paths)
if (Expression::eid(e) != Expression::E_STRINGLIT || (loc.firstLine() != 0U) ||
(loc.firstColumn() != 0U) || (loc.lastLine() != 0U) || (loc.lastColumn() != 0U)) {
os << loc.filename() << minor_sep << loc.firstLine() << minor_sep << loc.firstColumn()
<< minor_sep << loc.lastLine() << minor_sep << loc.lastColumn() << minor_sep;
switch (Expression::eid(e)) {
case Expression::E_INTLIT:
os << "il" << minor_sep << *e;
break;
case Expression::E_FLOATLIT:
os << "fl" << minor_sep << *e;
break;
case Expression::E_SETLIT:
os << "sl" << minor_sep << *e;
break;
case Expression::E_BOOLLIT:
os << "bl" << minor_sep << *e;
break;
case Expression::E_STRINGLIT:
os << "stl" << minor_sep << *e;
break;
case Expression::E_ID:
if (isCompIter) {
// if (e->cast<Id>()->decl()->e()->type().isPar())
os << *e << "=" << *Expression::cast<Id>(e)->decl()->e();
// else
// os << *e << "=?";
} else {
os << "id" << minor_sep << *e;
}
break;
case Expression::E_ANON:
os << "anon";
break;
case Expression::E_ARRAYLIT:
os << "al";
break;
case Expression::E_ARRAYACCESS:
os << "aa";
break;
case Expression::E_COMP: {
const Comprehension* cmp = Expression::cast<Comprehension>(e);
if (cmp->set()) {
os << "sc";
} else {
os << "ac";
}
} break;
case Expression::E_ITE:
os << "ite";
break;
case Expression::E_BINOP:
os << "bin" << minor_sep << Expression::cast<BinOp>(e)->opToString();
break;
case Expression::E_UNOP:
os << "un" << minor_sep << Expression::cast<UnOp>(e)->opToString();
break;
case Expression::E_CALL:
if (fopts.onlyToplevelPaths) {
return false;
}
os << "ca" << minor_sep << Expression::cast<Call>(e)->id();
break;
case Expression::E_VARDECL:
os << "vd";
break;
case Expression::E_LET:
os << "l";
break;
case Expression::E_TI:
os << "ti";
break;
case Expression::E_TIID:
os << "ty";
break;
default:
assert(false);
os << "unknown expression (internal error)";
break;
}
os << major_sep;
} else {
os << Expression::cast<StringLit>(e)->v() << major_sep;
}
}
return true;
}
void populate_output(Env& env, bool encapsulateJSON) {
EnvI& envi = env.envi();
Model* _flat = envi.flat();
Model* _output = envi.output;
std::vector<Expression*> outputVars;
for (VarDeclIterator it = _flat->vardecls().begin(); it != _flat->vardecls().end(); ++it) {
VarDecl* vd = it->e();
Annotation& ann = Expression::ann(vd);
ArrayLit* dims = nullptr;
bool has_output_ann = false;
if (!ann.isEmpty()) {
for (ExpressionSetIter ait = ann.begin(); ait != ann.end(); ++ait) {
if (Call* c = Expression::dynamicCast<Call>(*ait)) {
if (c->id() == envi.constants.ann.output_array) {
dims = Expression::cast<ArrayLit>(c->arg(0));
has_output_ann = true;
break;
}
} else if (Expression::isa<Id>(*ait) &&
Expression::cast<Id>(*ait)->str() == envi.constants.ann.output_var->str()) {
has_output_ann = true;
}
}
if (has_output_ann) {
std::ostringstream s;
s << vd->id()->str() << " = ";
auto* vd_output = Expression::cast<VarDecl>(copy(env.envi(), vd));
Type vd_t = vd_output->type();
vd_t.mkPar(env.envi());
Expression::type(vd_output, vd_t);
Expression::type(vd_output->ti(), vd_t);
if (dims != nullptr) {
std::vector<TypeInst*> ranges(dims->size());
s << "array" << dims->size() << "d(";
for (unsigned int i = 0; i < dims->size(); i++) {
IntSetVal* idxset = eval_intset(envi, (*dims)[i]);
ranges[i] = new TypeInst(Location().introduce(), Type(),
new SetLit(Location().introduce(), idxset));
s << *idxset << ",";
}
Type t = vd_t;
vd_t.dim(static_cast<int>(dims->size()));
Expression::type(vd_output, t);
vd_output->ti(new TypeInst(Location().introduce(), vd_t, ranges));
}
_output->addItem(VarDeclI::a(Location().introduce(), vd_output));
auto* sl = new StringLit(Location().introduce(), s.str());
outputVars.push_back(sl);
std::vector<Expression*> showArgs(1);
showArgs[0] = vd_output->id();
Call* show = Call::a(Location().introduce(), envi.constants.ids.show, showArgs);
Expression::type(show, Type::parstring());
FunctionI* fi = _flat->matchFn(envi, show, false);
assert(fi);
show->decl(fi);
outputVars.push_back(show);
std::string ends = dims != nullptr ? ")" : "";
ends += ";\n";
auto* eol = new StringLit(Location().introduce(), ends);
outputVars.push_back(eol);
}
}
}
auto* al = new ArrayLit(Location().introduce(), outputVars);
Expression::type(al, Type::parstring(1));
if (encapsulateJSON) {
auto* concat = Call::a(Location().introduce(), envi.constants.ids.concat, {al});
concat->type(Type::parstring());
concat->decl(_flat->matchFn(envi, concat, false));
auto* showJSON = Call::a(Location().introduce(), envi.constants.ids.showJSON, {concat});
showJSON->type(Type::parstring());
showJSON->decl(_flat->matchFn(envi, showJSON, false));
std::vector<Expression*> al_v(
{new StringLit(Location().introduce(), "\"output\": {\"dzn\": "), showJSON,
new StringLit(Location().introduce(), "}, \"sections\": [\"dzn\"]")});
al = new ArrayLit(Location().introduce(), al_v);
Expression::type(al, Type::parstring(1));
}
auto* newOutputItem = new OutputI(Location().introduce(), al);
_output->addItem(newOutputItem);
envi.flat()->mergeStdLib(envi, _output);
}
std::ostream& EnvI::evalOutput(std::ostream& os, std::ostream& log) {
GCLock lock;
warnings.clear();
ArrayLit* al = eval_array_lit(*this, output->outputItem()->e());
bool fLastEOL = true;
for (unsigned int i = 0; i < al->size(); i++) {
std::string s = eval_string(*this, (*al)[i]);
if (!s.empty()) {
os << s;
fLastEOL = ('\n' == s.back());
}
}
if (!fLastEOL) {
os << '\n';
}
for (auto& w : warnings) {
w->print(log, false);
}
return os;
}
const std::vector<std::unique_ptr<Warning>>& Env::warnings() { return envi().warnings; }
std::ostream& Env::dumpWarnings(std::ostream& os, bool werror, bool json, int exceptWarning) {
int curIdx = 0;
bool didPrint = false;
for (const auto& warning : warnings()) {
if (curIdx == exceptWarning) {
continue;
}
if (!json && (curIdx > 1 || (curIdx == 1 && exceptWarning != 0))) {
os << "\n";
}
curIdx++;
if (json) {
warning->json(os, werror);
} else {
didPrint = true;
warning->print(os, werror);
}
}
if (didPrint) {
os << "\n";
}
return os;
}
void Env::clearWarnings() { envi().warnings.clear(); }
unsigned int Env::maxCallStack() const { return envi().maxCallStack; }
void check_index_sets(EnvI& env, VarDecl* vd, Expression* e, bool isArg) {
struct ToCheck {
Expression* accessor;
Expression* e;
TypeInst* ti;
ToCheck(Expression* _accessor, Expression* _e, TypeInst* _ti)
: accessor(_accessor), e(_e), ti(_ti) {}
};
GCLock lock;
bool hasName = !vd->id()->str().empty();
std::vector<ToCheck> todo({{hasName ? vd->id() : nullptr, e, vd->ti()}});
CopyMap cm;
bool needNewTypeInst = false;
// Firstly just walks through checking index sets, then if we encounter an error,
// starts again recording what field accessors are needed to generate the error message.
bool hadError = false;
while (!todo.empty()) {
auto item = todo.back();
todo.pop_back();
if (Expression::type(item.e).dim() > 0) {
ASTExprVec<TypeInst> tis = item.ti->ranges();
GCLock lock;
switch (Expression::eid(item.e)) {
case Expression::E_ID: {
Id* id = Expression::cast<Id>(item.e);
ASTExprVec<TypeInst> e_tis = id->decl()->ti()->ranges();
if (tis.size() != e_tis.size()) {
continue;
}
for (unsigned int i = 0; i < e_tis.size(); i++) {
if (tis[i]->domain() == nullptr) {
if (!isArg) {
cm.insert(tis[i], e_tis[i]);
needNewTypeInst = true;
}
} else if (!Expression::isa<TIId>(tis[i]->domain())) {
IntSetVal* isv0 = eval_intset(env, tis[i]->domain());
IntSetVal* isv1 = eval_intset(env, e_tis[i]->domain());
if (!isv0->equal(isv1)) {
if (item.accessor != nullptr) {
std::ostringstream oss;
oss << "Index set mismatch. Declared index "
<< (tis.size() == 1 ? "set" : "sets");
oss << (isArg ? " of argument " : " of ") << "`" << *item.accessor << "' "
<< (tis.size() == 1 ? "is [" : "are [");
for (unsigned int j = 0; j < tis.size(); j++) {
if (tis[j]->domain() != nullptr) {
oss << env.show(tis[j]->domain());
} else {
oss << "int";
}
if (j < tis.size() - 1) {
oss << ", ";
}
}
oss << "], but is assigned to array `" << *id << "' with index "
<< (tis.size() == 1 ? "set [" : "sets [");
for (unsigned int j = 0; j < e_tis.size(); j++) {
oss << env.show(e_tis[j]->domain());
if (j < e_tis.size() - 1) {
oss << ", ";
}
}
oss << "]. You may need to coerce the index sets using the array" << tis.size()
<< "d function.";
throw EvalError(env, Expression::loc(e), oss.str());
}
hadError = true;
todo.clear();
Id* ident = hasName ? vd->id()
: new Id(Location().introduce(),
env.constants.ids.unnamedArgument, nullptr);
todo.emplace_back(ident, e, vd->ti());
}
}
}
} break;
case Expression::E_ARRAYLIT: {
auto* al = Expression::cast<ArrayLit>(item.e);
if (tis.size() != al->dims()) {
continue;
}
for (unsigned int i = 0; i < tis.size(); i++) {
if (tis[i]->domain() == nullptr) {
if (!isArg) {
cm.insert(tis[i], new TypeInst(Location().introduce(), Type::parint(),
new SetLit(Location().introduce(),
IntSetVal::a(al->min(i), al->max(i)))));
needNewTypeInst = true;
}
} else if ((i == 0 || !al->empty()) && !Expression::isa<TIId>(tis[i]->domain())) {
IntSetVal* isv = eval_intset(env, tis[i]->domain());
assert(isv->size() <= 1);
if ((isv->empty() && al->min(i) <= al->max(i)) ||
(!isv->empty() && (isv->min(0) != al->min(i) || isv->max(0) != al->max(i)))) {
if (item.accessor != nullptr) {
std::ostringstream oss;
oss << "Index set mismatch. Declared index "
<< (tis.size() == 1 ? "set" : "sets");
oss << (isArg ? " of argument " : " of ") << "`" << *item.accessor << "' "
<< (tis.size() == 1 ? "is [" : "are [");
for (unsigned int j = 0; j < tis.size(); j++) {
if (tis[j]->domain() != nullptr) {
oss << env.show(tis[j]->domain());
} else {
oss << "int";
}
if (j < tis.size() - 1) {
oss << ",";
}
}
oss << "], but is assigned to array with index "
<< (tis.size() == 1 ? "set [" : "sets [");
Type al_t = al->type();
if (al_t.typeId() == 0) {
for (unsigned int j = 0; j < al->dims(); j++) {
oss << al->min(j) << ".." << al->max(j);
if (j < al->dims() - 1) {
oss << ", ";
}
}
} else {
const auto& arrayIds = env.getArrayEnum(al_t.typeId());
for (unsigned int j = 0; j < al->dims(); j++) {
display_enum_range(oss, env, al->min(j), al->max(j), arrayIds[j]);
if (j < al->dims() - 1) {
oss << ", ";
}
}
}
oss << "]. You may need to coerce the index sets using the array" << tis.size()
<< "d function.";
throw EvalError(env, Expression::loc(e), oss.str());
}
hadError = true;
todo.clear();
Id* ident = hasName ? vd->id()
: new Id(Location().introduce(),
env.constants.ids.unnamedArgument, nullptr);
todo.emplace_back(ident, e, vd->ti());
} else {
unsigned int enumId = item.ti->type().typeId();
for (unsigned int i = 0; i < al->size(); i++) {
Expression* access = nullptr;
if (hadError) {
std::vector<int> indexes(al->dims());
int remDim = static_cast<int>(i);
for (unsigned int j = al->dims(); (j--) != 0U;) {
indexes[j] = (remDim % (al->max(j) - al->min(j) + 1)) + al->min(j);
remDim = remDim / (al->max(j) - al->min(j) + 1);
}
std::vector<Expression*> indexes_s(indexes.size());
if (enumId != 0) {
const auto& enumIds = env.getArrayEnum(enumId);
for (unsigned int j = 0; j < indexes.size(); j++) {
std::ostringstream index_oss;
if (enumIds[j] != 0) {
auto name = env.enumToString(enumIds[j], indexes[j]);
indexes_s[j] = new Id(Location().introduce(), name, nullptr);
} else {
indexes_s[j] = IntLit::a(indexes[j]);
}
}
} else {
for (unsigned int j = 0; j < indexes.size(); j++) {
indexes_s[j] = IntLit::a(indexes[j]);
}
}
access = new ArrayAccess(Location().introduce(), item.accessor, indexes_s);
}
todo.emplace_back(access, (*al)[i], item.ti);
}
}
}
}
} break;
default:
throw InternalError("not supported yet");
}
} else if (Expression::type(item.e).istuple()) {
auto* domains = Expression::dynamicCast<ArrayLit>(item.ti->domain());
if (domains != nullptr) {
auto* al = eval_array_lit(env, item.e);
for (unsigned int i = 0; i < al->size(); i++) {
auto* access =
hadError ? new FieldAccess(Location().introduce(), item.accessor, IntLit::a(i + 1))
: nullptr;
todo.emplace_back(access, (*al)[i], Expression::cast<TypeInst>((*domains)[i]));
}
}
} else if (Expression::type(item.e).isrecord()) {
auto* domains = Expression::dynamicCast<ArrayLit>(item.ti->domain());
if (domains != nullptr) {
RecordType* rt = env.getRecordType(Expression::type(item.e));
auto* al = eval_array_lit(env, item.e);
for (unsigned int i = 0; i < al->size(); i++) {
Expression* access = nullptr;
if (hadError) {
auto* field = new Id(Location().introduce(), rt->fieldName(i), nullptr);
access = new FieldAccess(Location().introduce(), item.accessor, field);
}
todo.emplace_back(access, (*al)[i], Expression::cast<TypeInst>((*domains)[i]));
}
}
}
}
if (needNewTypeInst) {
vd->ti(Expression::cast<TypeInst>(copy(env, cm, vd->ti())));
}
}
Expression* mk_domain_constraint(EnvI& env, Expression* expr, Expression* dom) {
assert(GC::locked());
Type ty = Expression::type(expr);
Type retType = ty.isPar() ? Type::parbool() : Type::varbool();
std::vector<Expression*> domargs(2, nullptr);
domargs[0] = expr;
switch (ty.bt()) {
case Type::BT_INT: {
IntSetVal* isv = eval_intset(env, dom);
if (ty.st() != Type::ST_SET && ty.dim() == 0) {
IntBounds ib = compute_int_bounds(env, expr);
if (ib.valid && !isv->empty() && isv->isSubset(IntSetVal::Range(ib.l, ib.u))) {
return nullptr;
}
}
domargs[1] = new SetLit(Expression::loc(dom), isv);
break;
}
case Type::BT_FLOAT: {
FloatSetVal* fsv = eval_floatset(env, dom);
if (ty.dim() == 0) {
FloatBounds fb = compute_float_bounds(env, expr);
if (fb.valid && !fsv->empty() && fsv->isSubset(FloatSetVal::Range(fb.l, fb.u))) {
return nullptr;
}
}
if (fsv->size() == 1) {
domargs[1] = FloatLit::a(fsv->min());
domargs.push_back(FloatLit::a(fsv->max()));
} else {
domargs[1] = new SetLit(Expression::loc(dom), fsv);
}
break;
}
case Type::BT_TUPLE: // fall through
case Type::BT_RECORD: {
ArrayLit* al = eval_array_lit(env, expr);
StructType* st = env.getStructType(ty);
auto* dom_al = Expression::cast<ArrayLit>(dom);
std::vector<std::pair<int, int>> dims;
if (ty.dim() > 0) {
dims.resize(al->dims());
for (unsigned int i = 0; i < al->dims(); i++) {
dims[i] = std::make_pair(al->min(i), al->max(i));
}
}
std::vector<Expression*> fieldwise;
for (unsigned int i = 0; i < dom_al->size(); ++i) {
auto* field_ti = Expression::cast<TypeInst>((*dom_al)[i]);
if (field_ti->domain() != nullptr) {
if (ty.dim() > 0) {
ArrayLit* slice = field_slice(env, st, al, dims, i + 1);
for (unsigned int j = 0; j < slice->size(); j++) {
auto* con = mk_domain_constraint(env, (*slice)[j], field_ti->domain());
if (con != nullptr) {
fieldwise.push_back(con);
};
}
} else {
auto* con = mk_domain_constraint(env, (*al)[i], field_ti->domain());
if (con != nullptr) {
fieldwise.push_back(con);
};
}
}
}
if (fieldwise.size() <= 1) {
return fieldwise.empty() ? nullptr : fieldwise[0];
}
auto* forall_al = new ArrayLit(Location().introduce(), fieldwise);
Type al_t = retType;
al_t.dim(1);
forall_al->type(al_t);
auto* c = Call::a(Location().introduce(), env.constants.ids.forall, {forall_al});
c->type(retType);
c->decl(env.model->matchFn(env, c, false));
return c;
}
case Type::BT_BOT: {
// Nothing to be done for empty arrays/sets
return nullptr;
}
default: {
throw EvalError(env, Expression::loc(dom),
"domain restrictions other than int and float not supported yet");
}
}
assert(domargs[1] != nullptr);
Call* c = Call::a(Location().introduce(), "var_dom", domargs);
c->type(Type::varbool());
c->decl(env.model->matchFn(env, c, false));
if (c->decl() == nullptr) {
throw InternalError("no matching declaration found for var_dom");
}
c->type(retType);
return c;
}
/// Turn \a c into domain constraints if possible.
/// Return whether \a c is still required in the model.
bool check_domain_constraints(EnvI& env, Call* c) {
if (env.fopts.recordDomainChanges) {
return true;
}
if (c->id() == env.constants.ids.int_.le) {
Expression* e0 = c->arg(0);
Expression* e1 = c->arg(1);
if (Expression::type(e0).isPar() && Expression::isa<Id>(e1)) {
// greater than
Id* id = Expression::cast<Id>(e1);
IntVal lb = eval_int(env, e0);
if (id->decl()->ti()->domain() != nullptr) {
IntSetVal* domain = eval_intset(env, id->decl()->ti()->domain());
assert(!domain->empty());
if (domain->min() >= lb) {
return false;
}
if (domain->max() < lb) {
env.fail();
return false;
}
IntSetRanges dr(domain);
Ranges::Const<IntVal> cr(lb, IntVal::infinity());
Ranges::Inter<IntVal, IntSetRanges, Ranges::Const<IntVal>> i(dr, cr);
IntSetVal* newibv = IntSetVal::ai(i);
id->decl()->ti()->domain(new SetLit(Location().introduce(), newibv));
id->decl()->ti()->setComputedDomain(false);
} else {
id->decl()->ti()->domain(
new SetLit(Location().introduce(), IntSetVal::a(lb, IntVal::infinity())));
}
return false;
}
if (Expression::type(e1).isPar() && Expression::isa<Id>(e0)) {
// less than
Id* id = Expression::cast<Id>(e0);
IntVal ub = eval_int(env, e1);
if (id->decl()->ti()->domain() != nullptr) {
IntSetVal* domain = eval_intset(env, id->decl()->ti()->domain());
if (domain->max() <= ub) {
return false;
}
if (domain->min() > ub) {
env.fail();
return false;
}
IntSetRanges dr(domain);
Ranges::Const<IntVal> cr(-IntVal::infinity(), ub);
Ranges::Inter<IntVal, IntSetRanges, Ranges::Const<IntVal>> i(dr, cr);
IntSetVal* newibv = IntSetVal::ai(i);
id->decl()->ti()->domain(new SetLit(Location().introduce(), newibv));
id->decl()->ti()->setComputedDomain(false);
} else {
id->decl()->ti()->domain(
new SetLit(Location().introduce(), IntSetVal::a(-IntVal::infinity(), ub)));
}
}
} else if (c->id() == env.constants.ids.int_.lin_le) {
auto* al_c = Expression::cast<ArrayLit>(follow_id(c->arg(0)));
if (al_c->size() == 1) {
auto* al_x = Expression::cast<ArrayLit>(follow_id(c->arg(1)));
IntVal coeff = eval_int(env, (*al_c)[0]);
IntVal y = eval_int(env, c->arg(2));
IntVal lb = -IntVal::infinity();
IntVal ub = IntVal::infinity();
IntVal r = y % coeff;
if (coeff >= 0) {
ub = y / coeff;
if (r < 0) {
--ub;
}
} else {
lb = y / coeff;
if (r < 0) {
++lb;
}
}
if (Id* id = Expression::dynamicCast<Id>((*al_x)[0])) {
if (id->decl()->ti()->domain() != nullptr) {
IntSetVal* domain = eval_intset(env, id->decl()->ti()->domain());
assert(!domain->empty());
if (domain->max() <= ub && domain->min() >= lb) {
return false;
}
if (domain->min() > ub || domain->max() < lb) {
env.fail();
return false;
}
IntSetRanges dr(domain);
Ranges::Const<IntVal> cr(lb, ub);
Ranges::Inter<IntVal, IntSetRanges, Ranges::Const<IntVal>> i(dr, cr);
IntSetVal* newibv = IntSetVal::ai(i);
id->decl()->ti()->domain(new SetLit(Location().introduce(), newibv));
id->decl()->ti()->setComputedDomain(false);
} else {
id->decl()->ti()->domain(new SetLit(Location().introduce(), IntSetVal::a(lb, ub)));
}
return false;
}
}
}
return true;
}
// Computer a new domain for the given TypeInst given an expression being assigned to it.
// Note that this function enforces tighter domains on the expression when possible.
KeepAlive compute_combined_domain(EnvI& env, TypeInst* ti, Expression* cur) {
if (Expression::type(cur).dim() > 0) {
if (ti->domain() != nullptr) {
auto* al = Expression::dynamicCast<ArrayLit>(
Expression::isa<Id>(cur) ? Expression::cast<Id>(cur)->decl()->e() : cur);
if (al != nullptr) {
std::vector<Expression*> ndom(0);
for (unsigned int i = 0; i < al->size(); i++) {
// TODO: Currently ignores setting the union of the RHS, should we compute the union and
// set?
compute_combined_domain(env, ti, (*al)[i]);
}
ti->setComputedDomain(true);
}
}
return nullptr;
}
if (Expression::type(cur).structBT()) {
auto* tl = Expression::dynamicCast<ArrayLit>(
Expression::isa<Id>(cur) ? Expression::cast<Id>(cur)->decl()->e() : cur);
if (tl != nullptr) {
auto* tis = Expression::cast<ArrayLit>(ti->domain());
std::vector<KeepAlive> dom_expr(tis->size());
bool any_changed = false;
for (unsigned int i = 0; i < tis->size(); i++) {
dom_expr[i] = compute_combined_domain(env, Expression::cast<TypeInst>((*tis)[i]), (*tl)[i]);
any_changed = any_changed || dom_expr[i]() != nullptr;
}
if (any_changed) {
GCLock lock;
std::vector<Expression*> dom(tis->size());
for (unsigned int i = 0; i < tis->size(); i++) {
auto* ti = Expression::cast<TypeInst>((*tis)[i]);
dom[i] = new TypeInst(Location().introduce(), ti->type(),
dom_expr[i]() == nullptr ? ti->domain() : dom_expr[i]());
}
return new ArrayLit(Location().introduce(), dom);
}
}
return nullptr;
}
Id* ident = Expression::dynamicCast<Id>(cur);
if (ident != nullptr &&
(ident == env.constants.absent || (ident->type().isAnn() && ident->decl() == nullptr))) {
// no need to do anything
return nullptr;
}
if (ident != nullptr && ident->decl()->ti()->domain() == nullptr) {
if (ti->domain() != nullptr) {
// RHS has no domain, so take ours
GCLock lock;
Expression* vd_dom = eval_par(env, ti->domain());
set_computed_domain(env, ident->decl(), vd_dom, ident->decl()->ti()->computedDomain());
}
return nullptr;
}
if (cur != nullptr && Expression::type(cur).bt() == Type::BT_INT) {
GCLock lock;
IntSetVal* rhsBounds = nullptr;
if (Expression::type(cur).isSet()) {
rhsBounds = compute_intset_bounds(env, cur);
} else {
IntBounds ib = compute_int_bounds(env, cur);
if (ib.valid) {
Call* call = Expression::dynamicCast<Call>(cur);
if ((call != nullptr) && call->id() == env.constants.ids.lin_exp) {
ArrayLit* al = eval_array_lit(env, call->arg(1));
if (al->size() == 1) {
IntBounds check_zeroone = compute_int_bounds(env, (*al)[0]);
if (check_zeroone.l == 0 && check_zeroone.u == 1) {
ArrayLit* coeffs = eval_array_lit(env, call->arg(0));
auto c = eval_int(env, (*coeffs)[0]);
auto d = eval_int(env, call->arg(2));
std::vector<IntVal> newdom(2);
newdom[0] = std::min(c + d, d);
newdom[1] = std::max(c + d, d);
rhsBounds = IntSetVal::a(newdom);
}
}
}
if (rhsBounds == nullptr) {
rhsBounds = IntSetVal::a(ib.l, ib.u);
}
}
}
IntSetVal* combinedDomain = rhsBounds;
IntSetVal* rhsDomain = nullptr;
if (ident != nullptr && ident->decl()->ti()->domain() != nullptr &&
!Expression::isa<TIId>(ident->decl()->ti()->domain())) {
// RHS has a domain, so intersect with its bounds
rhsDomain = eval_intset(env, ident->decl()->ti()->domain());
if (rhsBounds == nullptr) {
combinedDomain = rhsDomain;
} else {
IntSetRanges dr(rhsDomain);
IntSetRanges ibr(rhsBounds);
Ranges::Inter<IntVal, IntSetRanges, IntSetRanges> i(dr, ibr);
combinedDomain = IntSetVal::ai(i);
if (combinedDomain->card() == 0 && !Expression::type(cur).isSet()) {
env.fail();
}
}
}
if (combinedDomain != nullptr) {
IntSetVal* domain = nullptr;
if (ti->domain() != nullptr && !Expression::isa<TIId>(ti->domain())) {
// LHS has a domain so intersect with RHS domain
domain = eval_intset(env, ti->domain());
IntSetRanges dr(domain);
IntSetRanges ibr(combinedDomain);
Ranges::Inter<IntVal, IntSetRanges, IntSetRanges> i(dr, ibr);
combinedDomain = IntSetVal::ai(i);
if (combinedDomain->card() == 0 && !Expression::type(cur).isSet() &&
!Expression::type(cur).isOpt()) {
env.fail();
}
}
if (ident != nullptr && (rhsDomain == nullptr || !combinedDomain->equal(rhsDomain))) {
// If the RHS is an identifier, make its domain match
set_computed_domain(env, ident->decl(), new SetLit(Location().introduce(), combinedDomain),
false);
}
if (domain == nullptr || !domain->equal(combinedDomain)) {
return new SetLit(Location().introduce(), combinedDomain);
}
}
return nullptr;
}
if (cur != nullptr && Expression::type(cur).bt() == Type::BT_FLOAT) {
GCLock lock;
FloatSetVal* rhsBounds = nullptr;
FloatBounds fb = compute_float_bounds(env, cur);
if (fb.valid) {
rhsBounds = FloatSetVal::a(fb.l, fb.u);
}
FloatSetVal* combinedDomain = rhsBounds;
FloatSetVal* rhsDomain = nullptr;
if (ident != nullptr && ident->decl()->ti()->domain() != nullptr &&
!Expression::isa<TIId>(ident->decl()->ti()->domain())) {
// RHS has a domain, so intersect with its bounds
rhsDomain = eval_floatset(env, ident->decl()->ti()->domain());
if (rhsBounds == nullptr) {
combinedDomain = rhsDomain;
} else {
FloatSetRanges dr(rhsDomain);
FloatSetRanges ibr(rhsBounds);
Ranges::Inter<FloatVal, FloatSetRanges, FloatSetRanges> i(dr, ibr);
combinedDomain = FloatSetVal::ai(i);
if (combinedDomain->empty()) {
env.fail();
}
}
}
if (combinedDomain != nullptr) {
FloatSetVal* domain = nullptr;
if (ti->domain() != nullptr && !Expression::isa<TIId>(ti->domain())) {
// LHS has a domain so intersect with RHS domain
domain = eval_floatset(env, ti->domain());
FloatSetRanges dr(domain);
FloatSetRanges fbr(combinedDomain);
Ranges::Inter<FloatVal, FloatSetRanges, FloatSetRanges> i(dr, fbr);
combinedDomain = FloatSetVal::ai(i);
if (combinedDomain->empty()) {
env.fail();
}
}
if (ident != nullptr && (rhsDomain == nullptr || !combinedDomain->equal(rhsDomain))) {
// If the RHS is an identifier, make its domain match
set_computed_domain(env, ident->decl(), new SetLit(Location().introduce(), combinedDomain),
false);
}
if (domain == nullptr || !domain->equal(combinedDomain)) {
return new SetLit(Location().introduce(), combinedDomain);
}
}
return nullptr;
}
return nullptr;
}
KeepAlive bind(EnvI& env, Ctx ctx, VarDecl* vd, Expression* e) {
assert(e == nullptr || !Expression::isa<VarDecl>(e));
if (vd == env.constants.varIgnore) {
return e;
}
if (Id* ident = Expression::dynamicCast<Id>(e)) {
if (ident->decl() != nullptr) {
e = follow_id_to_decl(ident);
if (auto* e_vd = Expression::dynamicCast<VarDecl>(e)) {
e = e_vd->id();
if (!env.inReverseMapVar && ctx.b != C_ROOT && Expression::type(e) == Type::varbool()) {
env.addCtxAnn(e_vd, ctx.b);
if (e_vd != ident->decl()) {
env.addCtxAnn(ident->decl(), ctx.b);
}
}
}
}
}
if (ctx.neg) {
assert(Expression::type(e).isbool());
auto wrap_bool_not = [&](Expression* e) {
KeepAlive ka;
{
GCLock lock;
Call* bn = Call::a(Expression::loc(e), env.constants.ids.bool_.not_, {e});
bn->type(Expression::type(e));
bn->decl(env.model->matchFn(env, bn, false));
ka = bn;
}
return flat_exp(env, Ctx(), ka(), vd, env.constants.varTrue);
};
if (vd == env.constants.varTrue) {
if (!isfalse(env, e)) {
if (Id* id = Expression::dynamicCast<Id>(e)) {
while (id != nullptr) {
assert(id->decl() != nullptr);
if ((id->decl()->ti()->domain() != nullptr) &&
istrue(env, id->decl()->ti()->domain())) {
GCLock lock;
env.flatAddItem(new ConstraintI(Location().introduce(), env.constants.literalFalse));
} else {
GCLock lock;
std::vector<Expression*> args(2);
args[0] = id;
args[1] = env.constants.literalFalse;
Call* c = Call::a(Location().introduce(), env.constants.ids.bool_.eq, args);
c->decl(env.model->matchFn(env, c, false));
c->type(c->decl()->rtype(env, args, nullptr, false));
if (c->decl()->e() != nullptr) {
flat_exp(env, Ctx(), c, env.constants.varTrue, env.constants.varTrue);
}
set_computed_domain(env, id->decl(), env.constants.literalFalse,
id->decl()->ti()->computedDomain());
}
id =
id->decl()->e() != nullptr ? Expression::dynamicCast<Id>(id->decl()->e()) : nullptr;
}
return env.constants.literalTrue;
}
EE ee = wrap_bool_not(e);
return ee.r;
}
return env.constants.literalTrue;
}
EE ee = wrap_bool_not(e);
return ee.r;
}
if (vd == env.constants.varTrue) {
if (!istrue(env, e)) {
if (Id* id = Expression::dynamicCast<Id>(e)) {
assert(id->decl() != nullptr);
while (id != nullptr) {
if ((id->decl()->ti()->domain() != nullptr) && isfalse(env, id->decl()->ti()->domain())) {
GCLock lock;
env.flatAddItem(new ConstraintI(Location().introduce(), env.constants.literalFalse));
} else if (id->decl()->ti()->domain() == nullptr) {
GCLock lock;
std::vector<Expression*> args(2);
args[0] = id;
args[1] = env.constants.literalTrue;
Call* c = Call::a(Location().introduce(), env.constants.ids.bool_.eq, args);
c->decl(env.model->matchFn(env, c, false));
c->type(c->decl()->rtype(env, args, nullptr, false));
if (c->decl()->e() != nullptr) {
flat_exp(env, Ctx(), c, env.constants.varTrue, env.constants.varTrue);
}
set_computed_domain(env, id->decl(), env.constants.literalTrue,
id->decl()->ti()->computedDomain());
}
id = id->decl()->e() != nullptr ? Expression::dynamicCast<Id>(id->decl()->e()) : nullptr;
}
} else {
GCLock lock;
// extract domain information from added constraint if possible
if (!Expression::isa<Call>(e) || check_domain_constraints(env, Expression::cast<Call>(e))) {
env.flatAddItem(new ConstraintI(Location().introduce(), e));
}
}
}
return env.constants.literalTrue;
}
if (vd == env.constants.varFalse) {
if (!isfalse(env, e)) {
throw InternalError("not supported yet");
}
return env.constants.literalTrue;
}
if (vd == nullptr) {
if (e == nullptr) {
return nullptr;
}
switch (Expression::eid(e)) {
case Expression::E_INTLIT:
case Expression::E_FLOATLIT:
case Expression::E_BOOLLIT:
case Expression::E_STRINGLIT:
case Expression::E_ANON:
case Expression::E_ID:
case Expression::E_TIID:
case Expression::E_SETLIT:
case Expression::E_VARDECL:
case Expression::E_BINOP: // TODO: should not happen once operators are evaluated
case Expression::E_UNOP: // TODO: should not happen once operators are evaluated
return e;
case Expression::E_ARRAYACCESS:
case Expression::E_COMP:
case Expression::E_ITE:
case Expression::E_LET:
case Expression::E_TI:
throw InternalError("unevaluated expression");
case Expression::E_ARRAYLIT: {
GCLock lock;
auto* al = Expression::cast<ArrayLit>(e);
/// TODO: review if limit of 10 is a sensible choice
if (al->type().isbot() || al->type().bt() == Type::BT_ANN || al->size() <= 10) {
return e;
}
auto it = env.cseMapFind(al);
if (it != env.cseMapEnd()) {
return Expression::cast<VarDecl>(it->second.r)->id();
}
std::vector<TypeInst*> ranges(al->dims());
for (unsigned int i = 0; i < ranges.size(); i++) {
ranges[i] = new TypeInst(
Expression::loc(e), Type(),
new SetLit(Location().introduce(), IntSetVal::a(al->min(i), al->max(i))));
}
ASTExprVec<TypeInst> ranges_v(ranges);
Expression* domain = nullptr;
if (!al->empty() && Expression::type((*al)[0]).isint()) {
IntVal min = IntVal::infinity();
IntVal max = -IntVal::infinity();
for (unsigned int i = 0; i < al->size(); i++) {
IntBounds ib = compute_int_bounds(env, (*al)[i]);
if (!ib.valid) {
min = -IntVal::infinity();
max = IntVal::infinity();
break;
}
min = std::min(min, ib.l);
max = std::max(max, ib.u);
}
if (min != -IntVal::infinity() && max != IntVal::infinity()) {
domain = new SetLit(Location().introduce(), IntSetVal::a(min, max));
}
}
auto* ti = new TypeInst(Expression::loc(e), al->type(), ranges_v, domain);
if (domain != nullptr) {
ti->setComputedDomain(true);
}
VarDecl* nvd = new_vardecl(env, ctx, ti, nullptr, nullptr, al);
EE ee(nvd, nullptr);
env.cseMapInsert(al, ee);
if (al != nvd->e()) {
env.cseMapInsert(nvd->e(), ee);
}
return nvd->id();
}
case Expression::E_CALL: {
if (Expression::type(e).isAnn()) {
return e;
}
GCLock lock;
/// TODO: handle array types
auto* ti = new TypeInst(Location().introduce(), Expression::type(e));
VarDecl* nvd = new_vardecl(env, ctx, ti, nullptr, nullptr, e);
if (Expression::type(nvd->e()).bt() == Type::BT_INT &&
Expression::type(nvd->e()).dim() == 0) {
IntSetVal* ibv = nullptr;
if (Expression::type(nvd->e()).isSet()) {
ibv = compute_intset_bounds(env, nvd->e());
} else {
IntBounds ib = compute_int_bounds(env, nvd->e());
if (ib.valid) {
ibv = IntSetVal::a(ib.l, ib.u);
}
}
if (ibv != nullptr) {
Id* id = nvd->id();
while (id != nullptr) {
bool is_computed = id->decl()->ti()->computedDomain();
if (id->decl()->ti()->domain() != nullptr) {
IntSetVal* domain = eval_intset(env, id->decl()->ti()->domain());
IntSetRanges dr(domain);
IntSetRanges ibr(ibv);
Ranges::Inter<IntVal, IntSetRanges, IntSetRanges> i(dr, ibr);
IntSetVal* newibv = IntSetVal::ai(i);
if (ibv->equal(newibv)) {
is_computed = true;
} else {
ibv = newibv;
}
} else {
is_computed = true;
}
if (id->type().st() == Type::ST_PLAIN && ibv->empty()) {
env.fail();
} else {
set_computed_domain(env, id->decl(), new SetLit(Location().introduce(), ibv),
is_computed);
}
id = Expression::dynamicCast<Id>(id->decl()->e());
}
}
} else if (Expression::type(nvd->e()).isbool()) {
env.addCtxAnn(nvd, ctx.b);
} else if (Expression::type(nvd->e()).bt() == Type::BT_FLOAT &&
Expression::type(nvd->e()).dim() == 0) {
FloatBounds fb = compute_float_bounds(env, nvd->e());
FloatSetVal* ibv = LinearTraits<FloatLit>::intersectDomain(nullptr, fb.l, fb.u);
if (fb.valid) {
Id* id = nvd->id();
while (id != nullptr) {
bool is_computed = id->decl()->ti()->computedDomain();
if (id->decl()->ti()->domain() != nullptr) {
FloatSetVal* domain = eval_floatset(env, id->decl()->ti()->domain());
FloatSetVal* ndomain = LinearTraits<FloatLit>::intersectDomain(domain, fb.l, fb.u);
if ((ibv != nullptr) && ndomain == domain) {
is_computed = true;
} else {
ibv = ndomain;
}
} else {
is_computed = true;
}
if (LinearTraits<FloatLit>::domainEmpty(ibv)) {
env.fail();
} else {
set_computed_domain(env, id->decl(), new SetLit(Location().introduce(), ibv),
is_computed);
}
id = Expression::dynamicCast<Id>(id->decl()->e());
}
}
}
return nvd->id();
}
default:
assert(false);
return nullptr;
}
} else {
if (vd->e() == nullptr) {
Expression* ret = e;
if (e == nullptr || (Expression::type(e).isPar() && Expression::type(e).isbool())) {
GCLock lock;
bool isTrue = (e == nullptr || eval_bool(env, e));
// Check if redefinition of bool_eq exists, if yes call it
std::vector<Expression*> args(2);
args[0] = vd->id();
args[1] = env.constants.boollit(isTrue);
Call* c = Call::a(Location().introduce(), env.constants.ids.bool_.eq, args);
c->decl(env.model->matchFn(env, c, false));
c->type(c->decl()->rtype(env, args, nullptr, false));
bool didRewrite = false;
if (c->decl()->e() != nullptr) {
flat_exp(env, Ctx(), c, env.constants.varTrue, env.constants.varTrue);
didRewrite = true;
}
vd->e(env.constants.boollit(isTrue));
if (vd->ti()->domain() != nullptr) {
if (vd->ti()->domain() != vd->e()) {
env.fail();
return vd->id();
}
} else {
set_computed_domain(env, vd, vd->e(), true);
}
if (didRewrite) {
return vd->id();
}
} else {
check_index_sets(env, vd, e);
KeepAlive combinedDom = compute_combined_domain(env, vd->ti(), e);
if (combinedDom() != nullptr) {
set_computed_domain(env, vd, combinedDom(), vd->ti()->domain() == nullptr);
}
if (env.hasReverseMapper(vd->id()) && Expression::type(e).dim() == 0 &&
Expression::isa<Id>(e) && Expression::cast<Id>(e) != vd->id()) {
// Reverse mapped variable aliasing:
// E.g for optional variables, we can constrain the deopt values and the occurs values
// to match rather than only equating the deopts when they both occur.
GCLock lock;
auto* alias =
Call::a(Location().introduce(), env.constants.ids.mzn_alias_eq, {vd->id(), e});
auto* decl = env.model->matchFn(env, alias, false);
if (decl != nullptr) {
alias->decl(decl);
alias->type(Type::varbool());
if (ctx.b != C_ROOT) {
env.addCtxAnn(vd, ctx.b);
env.addCtxAnn(Expression::cast<Id>(e)->decl(), ctx.b);
}
flat_exp(env, Ctx(), alias, env.constants.varTrue, env.constants.varTrue);
ret = vd->id();
vd->e(e);
env.voAddExp(vd);
}
}
if (ret != vd->id()) {
vd->e(ret);
add_path_annotation(env, ret);
env.voAddExp(vd);
ret = vd->id();
}
}
return ret;
}
if (vd == e) {
return vd->id();
}
if (vd->e() != e) {
e = follow_id_to_decl(e);
if (vd == e) {
return vd->id();
}
switch (Expression::eid(e)) {
case Expression::E_BOOLLIT: {
Id* id = vd->id();
while (id != nullptr) {
if ((id->decl()->ti()->domain() != nullptr) &&
eval_bool(env, id->decl()->ti()->domain()) == Expression::cast<BoolLit>(e)->v()) {
return env.constants.literalTrue;
}
if ((id->decl()->ti()->domain() != nullptr) &&
eval_bool(env, id->decl()->ti()->domain()) != Expression::cast<BoolLit>(e)->v()) {
env.fail("domain is empty");
}
{
GCLock lock;
std::vector<Expression*> args(2);
args[0] = id;
args[1] = e;
Call* c = Call::a(Location().introduce(), env.constants.ids.bool_.eq, args);
c->decl(env.model->matchFn(env, c, false));
c->type(c->decl()->rtype(env, args, nullptr, false));
if (c->decl()->e() != nullptr) {
flat_exp(env, Ctx(), c, env.constants.varTrue, env.constants.varTrue);
}
set_computed_domain(env, id->decl(), e, id->decl()->ti()->computedDomain());
}
id =
id->decl()->e() != nullptr ? Expression::dynamicCast<Id>(id->decl()->e()) : nullptr;
}
return env.constants.literalTrue;
}
case Expression::E_INTLIT: {
Id* id = vd->id();
while (id != nullptr) {
if (id->decl()->ti()->domain() != nullptr) {
GCLock lock;
IntSetVal* dom = eval_set_lit(env, id->decl()->ti()->domain())->isv();
IntVal v = IntLit::v(Expression::cast<IntLit>(e));
if (!dom->contains(v)) {
env.fail("domain is empty");
}
if (dom->min(0) == v && dom->max(dom->size() - 1) == v) {
return e;
}
}
{
GCLock lock;
std::vector<Expression*> args(2);
args[0] = id;
args[1] = e;
Call* c = Call::a(Location().introduce(), env.constants.ids.int_.eq, args);
c->decl(env.model->matchFn(env, c, false));
c->type(c->decl()->rtype(env, args, nullptr, false));
if (c->decl()->e() != nullptr) {
flat_exp(env, Ctx(), c, env.constants.varTrue, env.constants.varTrue);
}
set_computed_domain(env, id->decl(), e, id->decl()->ti()->computedDomain());
}
id =
id->decl()->e() != nullptr ? Expression::dynamicCast<Id>(id->decl()->e()) : nullptr;
}
return e;
}
case Expression::E_FLOATLIT: {
Id* id = vd->id();
while (id != nullptr) {
if (id->decl()->ti()->domain() != nullptr) {
GCLock lock;
FloatSetVal* dom = eval_set_lit(env, id->decl()->ti()->domain())->fsv();
FloatVal v = FloatLit::v(Expression::cast<FloatLit>(e));
if (!dom->contains(v)) {
env.fail("domain is empty");
}
if (dom->min(0) == v && dom->max(dom->size() - 1) == v) {
return e;
}
}
{
GCLock lock;
std::vector<Expression*> args(2);
args[0] = id;
args[1] = e;
Call* c = Call::a(Location().introduce(), env.constants.ids.float_.eq, args);
c->decl(env.model->matchFn(env, c, false));
c->type(c->decl()->rtype(env, args, nullptr, false));
if (c->decl()->e() != nullptr) {
flat_exp(env, Ctx(), c, env.constants.varTrue, env.constants.varTrue);
}
set_computed_domain(env, id->decl(), e, id->decl()->ti()->computedDomain());
}
id =
id->decl()->e() != nullptr ? Expression::dynamicCast<Id>(id->decl()->e()) : nullptr;
}
return e;
}
case Expression::E_VARDECL: {
auto* e_vd = Expression::cast<VarDecl>(e);
if (vd->e() == e_vd->id() || e_vd->e() == vd->id()) {
return vd->id();
}
if (Expression::type(e).dim() != 0) {
throw InternalError("not supported yet");
}
create_explicit_assignment_constraints(env, vd, e_vd->id());
return vd->id();
}
case Expression::E_CALL: {
Call* c = Expression::cast<Call>(e);
GCLock lock;
Call* nc;
std::vector<Expression*> args;
if (c->id() == env.constants.ids.lin_exp) {
auto* le_c = Expression::cast<ArrayLit>(follow_id(c->arg(0)));
std::vector<Expression*> ncoeff(le_c->size());
for (auto i = static_cast<unsigned int>(ncoeff.size()); (i--) != 0U;) {
ncoeff[i] = (*le_c)[i];
}
ncoeff.push_back(IntLit::a(-1));
args.push_back(new ArrayLit(Location().introduce(), ncoeff));
Expression::type(args[0], le_c->type());
auto* le_x = Expression::cast<ArrayLit>(follow_id(c->arg(1)));
std::vector<Expression*> nx(le_x->size());
for (auto i = static_cast<unsigned int>(nx.size()); (i--) != 0U;) {
nx[i] = (*le_x)[i];
}
nx.push_back(vd->id());
args.push_back(new ArrayLit(Location().introduce(), nx));
Expression::type(args[1], le_x->type());
args.push_back(c->arg(2));
nc = Call::a(Expression::loc(c).introduce(), env.constants.ids.lin_exp, args);
nc->decl(env.model->matchFn(env, nc, false));
if (nc->decl() == nullptr) {
std::ostringstream ss;
ss << "undeclared function or predicate " << nc->id();
throw InternalError(ss.str());
}
nc->type(nc->decl()->rtype(env, args, nullptr, false));
auto* bop = new BinOp(Expression::loc(nc), nc, BOT_EQ, IntLit::a(0));
bop->type(Type::varbool());
flat_exp(env, Ctx(), bop, env.constants.varTrue, env.constants.varTrue);
return vd->id();
}
args.resize(c->argCount());
for (auto i = static_cast<unsigned int>(args.size()); (i--) != 0U;) {
args[i] = c->arg(i);
}
if (c->id() == env.constants.ids.exists) {
args.push_back(env.constants.emptyBoolArray);
}
args.push_back(vd->id());
ASTString nid = c->id();
FunctionI* nc_decl(nullptr);
if (c->id() == env.constants.ids.exists) {
nid = env.constants.ids.bool_reif.clause;
} else if (c->id() == env.constants.ids.forall) {
nid = env.constants.ids.bool_reif.array_and;
} else if (vd->type().isbool()) {
bool canHalfReify = env.fopts.enableHalfReification &&
Expression::ann(vd).contains(env.constants.ctx.pos);
nc_decl = env.model->matchReification(env, c->id(), args, canHalfReify, false);
nid = (nc_decl != nullptr) ? nc_decl->id() : env.reifyId(c->id());
}
nc = Call::a(Expression::loc(c).introduce(), nid, args);
if (nc_decl == nullptr) {
nc_decl = env.model->matchFn(env, nc, false);
}
if (nc_decl == nullptr) {
std::ostringstream ss;
ss << "undeclared function or predicate " << nc->id();
throw InternalError(ss.str());
}
nc->decl(nc_decl);
nc->type(nc->decl()->rtype(env, args, nullptr, false));
// vd already had a RHS, so don't make it a defined var
// make_defined_var(env, vd, nc);
flat_exp(env, Ctx(), nc, env.constants.varTrue, env.constants.varTrue);
return vd->id();
} break;
case Expression::E_SETLIT: {
Id* id = vd->id();
auto* sl = Expression::cast<SetLit>(e);
while (id != nullptr) {
if (auto* rhs = Expression::dynamicCast<SetLit>(id->decl()->e())) {
if (id->type().isIntSet() ? sl->isv()->equal(rhs->isv())
: sl->fsv()->equal(rhs->fsv())) {
return sl;
}
env.fail("domain is empty");
}
if (id->decl()->ti()->domain() != nullptr) {
GCLock lock;
SetLit* dom = eval_set_lit(env, id->decl()->ti()->domain());
if (id->type().isIntSet()) {
IntSetRanges slr(sl->isv());
IntSetRanges domr(dom->isv());
if (!Ranges::subset(slr, domr)) {
env.fail("domain is empty");
}
} else {
FloatSetRanges slr(sl->fsv());
FloatSetRanges domr(dom->fsv());
if (!Ranges::subset(slr, domr)) {
env.fail("domain is empty");
}
}
}
Id* next =
id->decl()->e() != nullptr ? Expression::dynamicCast<Id>(id->decl()->e()) : nullptr;
if (auto* _rhs = Expression::dynamicCast<Id>(id->decl()->e())) {
id->decl()->e(nullptr);
}
// There is already a RHS. If it's a call, make it relational.
// Otherwise, create explicit constraint
bool made_relational = false;
if (id->decl()->e() != nullptr) {
if (auto* c = Expression::dynamicCast<Call>(id->decl()->e())) {
KeepAlive ka;
// Remove call from RHS and add it as new constraint with the literal
std::vector<Expression*> args(c->argCount() + 1);
for (unsigned int i = 0; i < c->argCount(); ++i) {
args[i] = c->arg(i);
}
args[c->argCount()] = id->decl()->id();
FunctionI* decl = nullptr;
{
GCLock lock;
auto* nc = Call::a(Expression::loc(c), c->id(), args);
nc->type(Type::varbool());
decl = env.model->matchFn(env, nc, false);
ka = nc;
}
if (decl != nullptr) {
made_relational = true;
Expression::cast<Call>(ka())->decl(decl);
flat_exp(env, Ctx(), ka(), env.constants.varTrue, env.constants.varTrue);
}
}
}
if (id->decl()->e() == nullptr || made_relational) {
GCLock lock;
Type nty = vd->type();
nty.mkPar(env);
id->decl()->ti(new TypeInst(Expression::loc(vd), nty));
id->decl()->e(sl);
id->decl()->type(nty);
} else {
create_explicit_assignment_constraints(env, id->decl(), sl);
}
id = next;
}
return sl;
}
default:
throw InternalError("not supported yet");
}
} else {
return e;
}
}
}
KeepAlive conj(EnvI& env, VarDecl* b, const Ctx& ctx, const std::vector<EE>& e) {
if (!ctx.neg) {
std::vector<Expression*> nontrue;
for (const auto& i : e) {
if (istrue(env, i.b())) {
continue;
}
if (isfalse(env, i.b())) {
return bind(env, Ctx(), b, env.constants.literalFalse);
}
nontrue.push_back(i.b());
}
if (nontrue.empty()) {
return bind(env, Ctx(), b, env.constants.literalTrue);
}
if (nontrue.size() == 1) {
return bind(env, ctx, b, nontrue[0]);
}
if (b == env.constants.varTrue) {
for (auto& i : nontrue) {
bind(env, ctx, b, i);
}
return env.constants.literalTrue;
}
GC::lock();
std::vector<Expression*> args;
auto* al = new ArrayLit(Location().introduce(), nontrue);
al->type(Type::varbool(1));
args.push_back(al);
Call* ret = Call::a(Expression::loc(nontrue[0]).introduce(), env.constants.ids.forall, args);
ret->decl(env.model->matchFn(env, ret, false));
ret->type(ret->decl()->rtype(env, args, nullptr, false));
KeepAlive ka(ret);
GC::unlock();
return flat_exp(env, ctx, ret, b, env.constants.varTrue).r;
}
Ctx nctx = ctx;
nctx.neg = false;
nctx.b = -nctx.b;
// negated
std::vector<Expression*> nonfalse;
for (const auto& i : e) {
if (istrue(env, i.b())) {
continue;
}
if (isfalse(env, i.b())) {
return bind(env, Ctx(), b, env.constants.literalTrue);
}
nonfalse.push_back(i.b());
}
if (nonfalse.empty()) {
return bind(env, Ctx(), b, env.constants.literalFalse);
}
if (nonfalse.size() == 1) {
GC::lock();
UnOp* uo = new UnOp(Expression::loc(nonfalse[0]), UOT_NOT, nonfalse[0]);
uo->type(Type::varbool());
KeepAlive ka(uo);
GC::unlock();
return flat_exp(env, nctx, uo, b, env.constants.varTrue).r;
}
if (b == env.constants.varFalse) {
for (auto& i : nonfalse) {
bind(env, nctx, b, i);
}
return env.constants.literalFalse;
}
GC::lock();
std::vector<Expression*> args;
for (auto& i : nonfalse) {
UnOp* uo = new UnOp(Expression::loc(i), UOT_NOT, i);
uo->type(Type::varbool());
i = uo;
}
auto* al = new ArrayLit(Location().introduce(), nonfalse);
al->type(Type::varbool(1));
args.push_back(al);
Call* ret = Call::a(Location().introduce(), env.constants.ids.exists, args);
ret->decl(env.model->matchFn(env, ret, false));
ret->type(ret->decl()->rtype(env, args, nullptr, false));
assert(ret->decl());
KeepAlive ka(ret);
GC::unlock();
return flat_exp(env, nctx, ret, b, env.constants.varTrue).r;
}
Expression* eval_typeinst_domain(EnvI& env, const Ctx& ctx, Expression* dom) {
if (dom == nullptr) {
return nullptr;
}
if (auto* tup = Expression::dynamicCast<ArrayLit>(dom)) {
std::vector<Expression*> evaluated(tup->size());
for (unsigned int i = 0; i < tup->size(); ++i) {
auto* tupi = Expression::cast<TypeInst>((*tup)[i]);
if (tupi->domain() == nullptr) {
evaluated[i] = new TypeInst(Expression::loc(tupi), tupi->type(), tupi->ranges());
} else if (Expression::isa<ArrayLit>(tupi->domain())) {
evaluated[i] = new TypeInst(Expression::loc(tupi), tupi->type(), tupi->ranges(),
eval_typeinst_domain(env, ctx, tupi->domain()));
} else {
evaluated[i] = new TypeInst(Expression::loc(tupi), tupi->type(), tupi->ranges(),
flat_cv_exp(env, ctx, tupi->domain())());
}
}
return ArrayLit::constructTuple(Expression::loc(tup), evaluated);
}
return flat_cv_exp(env, ctx, dom)();
}
TypeInst* eval_typeinst(EnvI& env, const Ctx& ctx, VarDecl* vd) {
bool domIsTiVar = (vd->ti()->domain() != nullptr) && Expression::isa<TIId>(vd->ti()->domain());
bool hasTiVars = domIsTiVar;
for (unsigned int i = 0; i < vd->ti()->ranges().size(); i++) {
hasTiVars = hasTiVars || ((vd->ti()->ranges()[i]->domain() != nullptr) &&
Expression::isa<TIId>(vd->ti()->ranges()[i]->domain()));
}
if (hasTiVars) {
assert(vd->e());
if (Expression::type(vd->e()).dim() == 0) {
return new TypeInst(Location().introduce(), Expression::type(vd->e()));
}
ArrayLit* al = eval_array_lit(env, vd->e());
std::vector<TypeInst*> dims(al->dims());
for (unsigned int i = 0; i < dims.size(); i++) {
dims[i] =
new TypeInst(Location().introduce(), Type(),
new SetLit(Location().introduce(), IntSetVal::a(al->min(i), al->max(i))));
}
return new TypeInst(Location().introduce(), Expression::type(vd->e()), dims,
domIsTiVar ? nullptr : flat_cv_exp(env, ctx, vd->ti()->domain())());
}
std::vector<TypeInst*> dims(vd->ti()->ranges().size());
for (unsigned int i = 0; i < vd->ti()->ranges().size(); i++) {
if (vd->ti()->ranges()[i]->domain() != nullptr) {
KeepAlive range = flat_cv_exp(env, ctx, vd->ti()->ranges()[i]->domain());
IntSetVal* isv = eval_intset(env, range());
if (isv->size() > 1) {
throw EvalError(env, Expression::loc(vd->ti()->ranges()[i]->domain()),
"array index set must be contiguous range");
}
auto* sl = new SetLit(Expression::loc(vd->ti()->ranges()[i]), isv);
sl->type(Type::parsetint());
dims[i] = new TypeInst(Expression::loc(vd->ti()->ranges()[i]), Type(), sl);
} else {
dims[i] = new TypeInst(Expression::loc(vd->ti()->ranges()[i]), Type(), nullptr);
}
}
Type t = ((vd->e() != nullptr) && !Expression::type(vd->e()).isbot()) ? Expression::type(vd->e())
: vd->ti()->type();
return new TypeInst(Expression::loc(vd->ti()), t, dims,
eval_typeinst_domain(env, ctx, vd->ti()->domain()));
}
KeepAlive flat_cv_exp(EnvI& env, Ctx ctx, Expression* e) {
if (e == nullptr) {
return nullptr;
}
GCLock lock;
if (Expression::type(e).isPar() && !Expression::type(e).cv()) {
if (Expression::type(e) == Type::parbool()) {
try {
return eval_par(env, e);
} catch (ResultUndefinedError&) {
return env.constants.boollit(false);
}
}
return eval_par(env, e);
}
if (Expression::type(e).isvar()) {
EE ee = flat_exp(env, ctx, e, nullptr, ctx.partialityVar(env));
if (isfalse(env, ee.b())) {
throw ResultUndefinedError(env, Expression::loc(e), "");
}
return ee.r();
}
try {
switch (Expression::eid(e)) {
case Expression::E_INTLIT:
case Expression::E_FLOATLIT:
case Expression::E_BOOLLIT:
case Expression::E_STRINGLIT:
case Expression::E_TIID:
case Expression::E_VARDECL:
case Expression::E_TI:
case Expression::E_ANON:
assert(false);
return nullptr;
case Expression::E_ID: {
Id* id = Expression::cast<Id>(e);
return flat_cv_exp(env, ctx, id->decl()->e());
}
case Expression::E_SETLIT: {
auto* sl = Expression::cast<SetLit>(e);
if ((sl->isv() != nullptr) || (sl->fsv() != nullptr)) {
return sl;
}
std::vector<Expression*> es(sl->v().size());
GCLock lock;
for (unsigned int i = 0; i < sl->v().size(); i++) {
es[i] = flat_cv_exp(env, ctx, sl->v()[i])();
}
auto* sl_ret = new SetLit(Location().introduce(), es);
Type t = sl->type();
t.cv(false);
sl_ret->type(t);
return eval_par(env, sl_ret);
}
case Expression::E_ARRAYLIT: {
auto* al = Expression::cast<ArrayLit>(e);
std::vector<Expression*> es(al->size());
GCLock lock;
for (unsigned int i = 0; i < al->size(); i++) {
es[i] = flat_cv_exp(env, ctx, (*al)[i])();
}
if (al->isTuple()) {
CallStackItem csi(env, al);
Expression* al_ret = ArrayLit::constructTuple(Location().introduce(), es);
Expression::type(al_ret, al->type()); // still contains var, so still CV
// Add reverse mapper for tuple literal containing variables
VarDecl* vd = new_vardecl(env, Ctx(), new TypeInst(Location().introduce(), al->type()),
nullptr, nullptr, al_ret);
vd->ti()->setStructDomain(env, al->type());
env.reverseMappers.insert(vd->id(), al_ret);
return vd->id();
}
std::vector<std::pair<int, int>> dims(al->dims());
for (unsigned int i = 0; i < al->dims(); i++) {
dims[i] = std::make_pair(al->min(i), al->max(i));
}
Expression* al_ret = new ArrayLit(Location().introduce(), es, dims);
Type t = al->type();
t.cv(false);
Expression::type(al_ret, t);
return al_ret;
}
case Expression::E_ARRAYACCESS: {
auto* aa = Expression::cast<ArrayAccess>(e);
GCLock lock;
Expression* av = flat_cv_exp(env, ctx, aa->v())();
std::vector<Expression*> idx(aa->idx().size());
for (unsigned int i = 0; i < aa->idx().size(); i++) {
idx[i] = flat_cv_exp(env, ctx, aa->idx()[i])();
}
auto* aa_ret = new ArrayAccess(Location().introduce(), av, idx);
Type t = aa->type();
t.cv(false);
aa_ret->type(t);
return eval_par(env, aa_ret);
}
case Expression::E_FIELDACCESS: {
auto* fa = Expression::cast<FieldAccess>(e);
assert(Expression::type(fa->v()).structBT());
assert(Expression::isa<IntLit>(fa->field()));
IntVal i = IntLit::v(Expression::cast<IntLit>(fa->field()));
auto* al = Expression::cast<ArrayLit>(eval_array_lit(env, fa->v()));
return flat_cv_exp(env, ctx, (*al)[static_cast<unsigned int>(i.toInt()) - 1]);
}
case Expression::E_COMP: {
auto* c = Expression::cast<Comprehension>(e);
GCLock lock;
class EvalFlatCvExp : public EvalBase {
public:
Ctx ctx;
EvalFlatCvExp(Ctx& ctx0) : ctx(ctx0) {}
typedef Expression* ArrayVal;
Expression* e(EnvI& env, Expression* e) const { return flat_cv_exp(env, ctx, e)(); }
static Expression* exp(Expression* e) { return e; }
} eval(ctx);
EvaluatedComp<Expression*> a = eval_comp<EvalFlatCvExp>(env, eval, c);
Type t = Type::bot();
bool allPar = true;
bool allOcc = true;
for (auto& i : a.a) {
if (t == Type::bot()) {
t = Expression::type(i);
} else if (t.structBT()) {
if (t.bt() == Type::BT_TUPLE) {
t = env.commonTuple(t, Expression::type(i), true);
} else { // (tret.bt() == Type::BT_RECORD)
t = env.commonRecord(t, Expression::type(i), true);
}
}
if (!Expression::type(i).isPar()) {
allPar = false;
}
if (Expression::type(i).isOpt()) {
allOcc = false;
}
}
if (!allPar) {
t.mkVar(env);
}
if (!allOcc) {
t.ot(Type::OT_OPTIONAL);
}
if (c->set()) {
t.st(Type::ST_SET);
} else {
t = Type::arrType(env, c->type(), t);
}
t.cv(false);
if (c->set()) {
if (c->type().isPar() && allPar) {
auto* sl = new SetLit(Expression::loc(c).introduce(), a.a);
sl->type(t);
Expression* slr = eval_par(env, sl);
Expression::type(slr, t);
return slr;
}
throw InternalError("var set comprehensions not supported yet");
}
auto* alr = new ArrayLit(Location().introduce(), a.a, a.dims);
alr->type(t);
alr->flat(true);
return alr;
}
case Expression::E_ITE: {
ITE* ite = Expression::cast<ITE>(e);
Ctx nctx = ctx;
nctx.b = C_MIX;
for (unsigned int i = 0; i < ite->size(); i++) {
bool condition;
KeepAlive ka;
try {
ka = flat_cv_exp(env, nctx, ite->ifExpr(i));
condition = eval_bool(env, ka());
} catch (ResultUndefinedError&) {
condition = false;
}
if (condition) {
return flat_cv_exp(env, ctx, ite->thenExpr(i));
}
}
return flat_cv_exp(env, ctx, ite->elseExpr());
}
case Expression::E_BINOP: {
auto* bo = Expression::cast<BinOp>(e);
BinOp* nbo = nullptr;
Ctx nctx = ctx;
{
CallStackItem _csi(env, bo);
if (bo->op() == BOT_AND) {
GCLock lock;
nctx.b = +nctx.b;
Expression* lhs = flat_cv_exp(env, nctx, bo->lhs())();
if (!eval_bool(env, lhs)) {
return env.constants.literalFalse;
}
return eval_par(env, flat_cv_exp(env, ctx, bo->rhs())());
}
if (bo->op() == BOT_OR) {
GCLock lock;
nctx.b = +nctx.b;
Expression* lhs = flat_cv_exp(env, nctx, bo->lhs())();
if (eval_bool(env, lhs)) {
return env.constants.literalTrue;
}
return eval_par(env, flat_cv_exp(env, ctx, bo->rhs())());
}
GCLock lock;
if (Expression::type(bo).isbool()) {
nctx.b = C_MIX;
}
nbo = new BinOp(Expression::loc(bo).introduce(), flat_cv_exp(env, nctx, bo->lhs())(),
bo->op(), flat_cv_exp(env, nctx, bo->rhs())());
for (auto* ann : Expression::ann(bo)) {
Expression::addAnnotation(nbo, ann);
}
nbo->type(bo->type());
nbo->decl(bo->decl());
}
return eval_par(env, nbo);
}
case Expression::E_UNOP: {
UnOp* uo = Expression::cast<UnOp>(e);
UnOp* nuo = nullptr;
Ctx nctx = ctx;
{
CallStackItem _csi(env, uo);
if (Expression::type(uo).isbool()) {
nctx.b = -nctx.b;
}
GCLock lock;
nuo = new UnOp(Expression::loc(uo), uo->op(), flat_cv_exp(env, nctx, uo->e())());
for (auto* ann : Expression::ann(uo)) {
Expression::addAnnotation(nuo, ann);
}
nuo->type(uo->type());
}
return eval_par(env, nuo);
}
case Expression::E_CALL: {
Call* c = Expression::cast<Call>(e);
if (ctx.b == C_ROOT && (c->decl()->e() != nullptr) &&
Expression::isa<BoolLit>(c->decl()->e())) {
bool allBool = true;
for (unsigned int i = 0; i < c->argCount(); i++) {
if (Expression::type(c->arg(i)).bt() != Type::BT_BOOL) {
allBool = false;
break;
}
}
if (allBool) {
return c->decl()->e();
}
}
std::vector<Expression*> args(c->argCount());
GCLock lock;
if (env.constants.isCallByReferenceId(c->id())) {
return eval_par(env, c);
}
CallStackItem _csi(env, c);
for (unsigned int i = 0; i < c->argCount(); i++) {
Ctx c_mix;
c_mix.b = C_MIX;
c_mix.i = C_MIX;
args[i] = flat_cv_exp(env, c_mix, c->arg(i))();
}
Call* nc = Call::a(Expression::loc(c), c->id(), args);
nc->decl(c->decl());
Type nct(c->type());
for (auto* ann : Expression::ann(c)) {
Expression::addAnnotation(nc, ann);
}
if ((nc->decl()->e() != nullptr) && Expression::type(nc->decl()->e()).cv()) {
nct.cv(false);
nct.mkVar(env);
nc->type(nct);
EE ee;
if (c->decl()->ann().contains(env.constants.ann.cache_result)) {
auto it = env.cseMapFind(nc);
if (it == env.cseMapEnd()) {
ee = flat_exp(env, ctx, nc, nullptr, ctx.partialityVar(env));
env.cseMapInsert(nc, ee);
} else {
ee.r = it->second.r;
ee.b = it->second.b;
}
} else {
ee = flat_exp(env, ctx, nc, nullptr, ctx.partialityVar(env));
}
if (isfalse(env, ee.b())) {
std::ostringstream ss;
ss << "evaluation of `" << demonomorphise_identifier(nc->id()) << "` was undefined";
throw ResultUndefinedError(env, Expression::loc(e), ss.str());
}
return ee.r();
}
nc->type(nct);
return eval_par(env, nc);
}
case Expression::E_LET: {
Let* l = Expression::cast<Let>(e);
EE ee = flat_exp(env, ctx, l, nullptr, ctx.partialityVar(env));
if (isfalse(env, ee.b())) {
throw ResultUndefinedError(env, Expression::loc(e),
"evaluation of let expression was undefined");
}
return ee.r();
}
}
throw InternalError("internal error");
} catch (ResultUndefinedError&) {
if (Expression::type(e) == Type::parbool()) {
return env.constants.boollit(false);
}
throw;
}
}
class ItemTimer {
public:
using TimingMap =
std::map<std::pair<ASTString, unsigned int>, std::chrono::high_resolution_clock::duration>;
ItemTimer(const Location& loc, TimingMap* tm)
: _loc(loc), _tm(tm), _start(std::chrono::high_resolution_clock::now()) {}
~ItemTimer() {
try {
if (_tm != nullptr) {
std::chrono::high_resolution_clock::time_point end =
std::chrono::high_resolution_clock::now();
unsigned int line = _loc.firstLine();
auto it = _tm->find(std::make_pair(_loc.filename(), line));
if (it != _tm->end()) {
it->second += end - _start;
} else {
_tm->insert(std::make_pair(std::make_pair(_loc.filename(), line), end - _start));
}
}
} catch (std::exception& /*e*/) {
assert(false); // Invariant: Operations on the TimingMap will not throw an exception
}
}
private:
const Location& _loc;
TimingMap* _tm;
std::chrono::high_resolution_clock::time_point _start;
};
namespace {
class FlattenModelVisitor : public ItemVisitor {
public:
EnvI& env;
bool& hadSolveItem;
ItemTimer::TimingMap* timingMap;
FlattenModelVisitor(EnvI& env0, bool& hadSolveItem0, ItemTimer::TimingMap* timingMap0)
: env(env0), hadSolveItem(hadSolveItem0), timingMap(timingMap0) {}
bool enter(Item* i) const {
env.checkCancel();
return !(i->isa<ConstraintI>() && env.failed());
}
void vVarDeclI(VarDeclI* v) {
ItemTimer item_timer(v->loc(), timingMap);
Expression::ann(v->e()).remove(env.constants.ann.output_var);
Expression::ann(v->e()).removeCall(env.constants.ann.output_array);
if (Expression::ann(v->e()).contains(env.constants.ann.output_only)) {
return;
}
if (v->e()->type().isPar() && !v->e()->type().isOpt() && v->e()->e() != nullptr &&
!Expression::type(v->e()->e()).cv() && Expression::type(v->e()).dim() > 0 &&
v->e()->ti()->domain() == nullptr &&
(v->e()->type().bt() == Type::BT_INT || v->e()->type().bt() == Type::BT_FLOAT)) {
// Compute bounds for array literals
CallStackItem csi(env, v->e());
GCLock lock;
ArrayLit* al = eval_array_lit(env, v->e()->e());
v->e()->e(al);
for (unsigned int i = 0; i < v->e()->ti()->ranges().size(); i++) {
if (v->e()->ti()->ranges()[i]->domain() != nullptr) {
IntSetVal* isv = eval_intset(env, v->e()->ti()->ranges()[i]->domain());
if (isv->size() > 1) {
throw EvalError(env, Expression::loc(v->e()->ti()->ranges()[i]->domain()),
"array index set must be contiguous range");
}
}
}
check_index_sets(env, v->e(), v->e()->e());
if (!al->empty()) {
if (v->e()->type().bt() == Type::BT_INT && v->e()->type().st() == Type::ST_PLAIN) {
IntVal lb = IntVal::infinity();
IntVal ub = -IntVal::infinity();
for (unsigned int i = 0; i < al->size(); i++) {
IntVal vi = eval_int(env, (*al)[i]);
lb = std::min(lb, vi);
ub = std::max(ub, vi);
}
GCLock lock;
set_computed_domain(env, v->e(), new SetLit(Location().introduce(), IntSetVal::a(lb, ub)),
true);
} else if (v->e()->type().bt() == Type::BT_FLOAT && v->e()->type().st() == Type::ST_PLAIN) {
FloatVal lb = FloatVal::infinity();
FloatVal ub = -FloatVal::infinity();
for (unsigned int i = 0; i < al->size(); i++) {
FloatVal vi = eval_float(env, (*al)[i]);
lb = std::min(lb, vi);
ub = std::max(ub, vi);
}
GCLock lock;
set_computed_domain(env, v->e(),
new SetLit(Location().introduce(), FloatSetVal::a(lb, ub)), true);
}
}
} else if (v->e()->type().isvar() || v->e()->type().isAnn()) {
Ctx ctx;
if (Expression::ann(v->e()).contains(env.constants.ctx.pos) ||
Expression::ann(v->e()).contains(env.constants.ctx.promise_monotone)) {
if (v->e()->type().isint()) {
ctx.i = C_POS;
} else if (v->e()->type().isbool()) {
ctx.b = C_POS;
}
} else if (Expression::ann(v->e()).contains(env.constants.ctx.neg) ||
Expression::ann(v->e()).contains(env.constants.ctx.promise_antitone)) {
if (v->e()->type().isint()) {
ctx.i = C_NEG;
} else if (v->e()->type().isbool()) {
ctx.b = C_NEG;
}
}
(void)flatten_id(env, ctx, v->e()->id(), nullptr, env.constants.varTrue, true);
} else {
if (v->e()->e() == nullptr) {
if (!v->e()->type().isAnn()) {
throw EvalError(env, Expression::loc(v->e()), "Undefined parameter", v->e()->id()->v());
}
} else {
CallStackItem csi(env, v->e());
GCLock lock;
Location v_loc = Expression::loc(v->e()->e());
if (!Expression::type(v->e()->e()).cv()) {
v->e()->e(eval_par(env, v->e()->e()));
} else {
EE ee = flat_exp(env, Ctx(), v->e()->e(), nullptr, env.constants.varTrue);
v->e()->e(ee.r());
}
flatten_vardecl_annotations(env, v->e(), v, v->e());
check_par_declaration(env, v->e());
}
}
}
void vConstraintI(ConstraintI* ci) {
ItemTimer item_timer(ci->loc(), timingMap);
(void)flat_exp(env, Ctx(), ci->e(), env.constants.varTrue, env.constants.varTrue);
}
void vSolveI(SolveI* si) {
if (hadSolveItem) {
throw FlatteningError(env, si->loc(), "Only one solve item allowed");
}
ItemTimer item_timer(si->loc(), timingMap);
hadSolveItem = true;
GCLock lock;
SolveI* nsi = nullptr;
switch (si->st()) {
case SolveI::ST_SAT:
nsi = SolveI::sat(Location());
break;
case SolveI::ST_MIN: {
Ctx ctx;
ctx.i = C_NEG;
nsi = SolveI::min(Location().introduce(),
flat_exp(env, ctx, si->e(), nullptr, env.constants.varTrue).r());
} break;
case SolveI::ST_MAX: {
Ctx ctx;
ctx.i = C_POS;
nsi = SolveI::max(Location().introduce(),
flat_exp(env, ctx, si->e(), nullptr, env.constants.varTrue).r());
} break;
}
for (ExpressionSetIter it = si->ann().begin(); it != si->ann().end(); ++it) {
Expression* ret = flat_exp(env, Ctx(), *it, nullptr, env.constants.varTrue).r();
if (auto* c = Expression::dynamicCast<Call>(ret)) {
if (c->id() == env.constants.ids.on_restart.on_restart) {
assert(c->argCount() == 1);
auto* pred = Expression::cast<StringLit>(c->arg(0));
Call* nc = Call::a(Expression::loc(c).introduce(), pred->v(), std::vector<Expression*>());
nc->type(Type::varbool());
FunctionI* decl = env.model->matchFn(env, nc, false);
if (decl == nullptr) {
std::ostringstream ss;
ss << "Unknown predicate `" << pred->v()
<< "' found while evaluating on_restart annotation";
throw FlatteningError(env, Expression::loc(pred), ss.str());
}
nc->decl(decl);
env.flatAddItem(new ConstraintI(Expression::loc(c).introduce(), nc));
continue;
}
}
nsi->ann().add(ret);
}
env.flatAddItem(nsi);
}
void vOutputI(OutputI* oi) {
assert(oi->ann().size() <= 1);
auto section = env.constants.ids.mzn_default;
bool json = false;
auto* e = oi->e();
GCLock lock;
for (auto* ann : oi->ann()) {
auto* s = Expression::dynamicCast<Call>(flat_cv_exp(env, Ctx(), ann)());
if (s == nullptr || (s->id() != env.constants.ids.mzn_output_section)) {
env.addWarning(Expression::loc(ann), "Unrecognised output item section annotation.");
}
json = eval_bool(env, s->arg(1));
section = ASTString(eval_string(env, s->arg(0)));
}
if (json) {
auto* c = Call::a(Expression::loc(e).introduce(), env.constants.ids.showJSON, {e});
c->decl(env.model->matchFn(env, c, false));
c->type(Type::parstring());
auto* nl = new StringLit(Expression::loc(e).introduce(), "\n");
std::vector<Expression*> v({c, nl});
e = new ArrayLit(Expression::loc(e).introduce(), v);
Expression::type(e, Type::parstring(1));
} else if (Expression::type(e) == Type::parstring()) {
std::vector<Expression*> v({e});
e = new ArrayLit(Expression::loc(e).introduce(), v);
Expression::type(e, Type::parstring(1));
} else if (Expression::type(e) == Type::ann()) {
auto* result = Expression::dynamicCast<Id>(flat_cv_exp(env, Ctx(), e)());
if (!Expression::equal(result, env.constants.ann.output_only)) {
throw FlatteningError(env, Expression::loc(e),
"An annotation which is the expression of an output item must "
"evaluate to `output_only'.");
}
return;
} else if (Expression::type(e) != Type::parstring(1) && Expression::type(e) != Type::bot(1)) {
throw TypeError(env, Expression::loc(e),
"invalid type in output item, expected `" + Type::parstring(1).toString(env) +
"', actual `" + Expression::type(e).toString(env) + "'");
}
env.outputSections.add(env, section, e, json);
}
};
class SimplifyFunctionBodiesVisitor : public ItemVisitor {
public:
Model& toAdd;
EnvI& env;
SimplifyFunctionBodiesVisitor(EnvI& env0, Model& toAdd0) : env(env0), toAdd(toAdd0) {}
void vFunctionI(FunctionI* fi) { eval_static_function_body(env, fi, toAdd); }
};
} // namespace
void flatten(Env& e, FlatteningOptions opt) {
class OverflowWatch {
public:
OverflowWatch(Env& e) { OverflowHandler::setEnv(e); }
~OverflowWatch() { OverflowHandler::removeEnv(); }
};
OverflowWatch ow(e);
e.envi().setRandomSeed(opt.randomSeed);
ItemTimer::TimingMap timingMap_o;
ItemTimer::TimingMap* timingMap = opt.detailedTiming ? &timingMap_o : nullptr;
try {
EnvI& env = e.envi();
env.fopts = opt;
// Statically evaluate some function bodies
{
std::unique_ptr<Model> toAdd(new Model);
SimplifyFunctionBodiesVisitor _ffbv(env, *toAdd);
iter_items<SimplifyFunctionBodiesVisitor>(_ffbv, e.model());
for (auto* it : *toAdd) {
e.model()->addItem(it);
}
}
process_toplevel_output_vars(e.envi());
bool onlyRangeDomains = false;
if (opt.onlyRangeDomains) {
onlyRangeDomains = true; // compulsory
} else {
GCLock lock;
Call* check_only_range = Call::a(Location(), "mzn_check_only_range_domains", {});
check_only_range->type(Type::parbool());
check_only_range->decl(env.model->matchFn(e.envi(), check_only_range, false));
onlyRangeDomains = eval_bool(e.envi(), check_only_range);
}
bool halfReifyClause = true;
if (!env.fopts.enableHalfReification) {
halfReifyClause = false;
} else {
GCLock lock;
Call* check_hr_clause = Call::a(Location(), "mzn_check_half_reify_clause", {});
check_hr_clause->type(Type::parbool());
check_hr_clause->decl(env.model->matchFn(e.envi(), check_hr_clause, false));
halfReifyClause = eval_bool(e.envi(), check_hr_clause);
}
// Flatten main model
bool hadSolveItem = false;
FlattenModelVisitor _fv(env, hadSolveItem, timingMap);
iter_items<FlattenModelVisitor>(_fv, e.model());
if (!hadSolveItem) {
GCLock lock;
e.envi().flatAddItem(SolveI::sat(Location().introduce()));
}
// Create output model
if (e.flat()->solveItem()->st() == SolveI::SolveType::ST_SAT) {
// Never output _objective for SAT problems
opt.outputObjective = false;
}
if (opt.keepOutputInFzn) {
copy_output(env);
} else {
create_output(env, opt.outputMode, opt.outputObjective, opt.outputOutputItem, opt.hasChecker,
opt.encapsulateJSON);
}
// Flatten remaining redefinitions
Model& m = *e.flat();
int startItem = 0;
int endItem = static_cast<int>(m.size()) - 1;
FunctionI* int_lin_eq;
{
std::vector<Type> int_lin_eq_t(3);
int_lin_eq_t[0] = Type::parint(1);
int_lin_eq_t[1] = Type::varint(1);
int_lin_eq_t[2] = Type::parint(0);
GCLock lock;
FunctionI* fi = env.model->matchFn(env, env.constants.ids.int_.lin_eq, int_lin_eq_t, false);
int_lin_eq = ((fi != nullptr) && (fi->e() != nullptr)) ? fi : nullptr;
}
FunctionI* float_lin_eq;
{
std::vector<Type> float_lin_eq_t(3);
float_lin_eq_t[0] = Type::parfloat(1);
float_lin_eq_t[1] = Type::varfloat(1);
float_lin_eq_t[2] = Type::parfloat(0);
GCLock lock;
FunctionI* fi =
env.model->matchFn(env, env.constants.ids.float_.lin_eq, float_lin_eq_t, false);
float_lin_eq = ((fi != nullptr) && (fi->e() != nullptr)) ? fi : nullptr;
}
FunctionI* array_bool_and;
FunctionI* array_bool_and_imp;
FunctionI* array_bool_clause;
FunctionI* array_bool_clause_reif;
FunctionI* bool_xor;
{
std::vector<Type> argtypes(2);
argtypes[0] = Type::varbool(1);
argtypes[1] = Type::varbool(0);
GCLock lock;
FunctionI* fi =
env.model->matchFn(env, env.constants.ids.bool_reif.array_and, argtypes, false);
array_bool_and = ((fi != nullptr) && (fi->e() != nullptr)) ? fi : nullptr;
fi = env.model->matchFn(env, env.constants.ids.array_bool_and_imp, argtypes, false);
array_bool_and_imp = ((fi != nullptr) && (fi->e() != nullptr)) ? fi : nullptr;
argtypes[1] = Type::varbool(1);
fi = env.model->matchFn(env, env.constants.ids.bool_.clause, argtypes, false);
array_bool_clause = ((fi != nullptr) && (fi->e() != nullptr)) ? fi : nullptr;
argtypes.push_back(Type::varbool());
fi = env.model->matchFn(env, env.constants.ids.bool_reif.clause, argtypes, false);
array_bool_clause_reif = ((fi != nullptr) && (fi->e() != nullptr)) ? fi : nullptr;
argtypes[0] = Type::varbool();
argtypes[1] = Type::varbool();
argtypes[2] = Type::varbool();
fi = env.model->matchFn(env, env.constants.ids.bool_.ne, argtypes, false);
bool_xor = ((fi != nullptr) && (fi->e() != nullptr)) ? fi : nullptr;
}
std::vector<int> processLast;
env.collectVarDecls(true);
while (startItem <= endItem || !env.modifiedVarDecls.empty() || !processLast.empty()) {
if (env.failed()) {
return;
}
std::vector<int> agenda;
for (int i = startItem; i <= endItem; i++) {
agenda.push_back(i);
}
for (int modifiedVarDecl : env.modifiedVarDecls) {
agenda.push_back(modifiedVarDecl);
}
env.modifiedVarDecls.clear();
bool doLastProcessing = false;
if (agenda.empty()) {
for (auto i : processLast) {
agenda.push_back(i);
}
processLast.clear();
doLastProcessing = true;
}
for (int i : agenda) {
env.checkCancel();
if (auto* vdi = m[i]->dynamicCast<VarDeclI>()) {
if (vdi->removed()) {
continue;
}
/// Look at constraints
if (!is_output(vdi->e())) {
if (0 < env.varOccurrences.occurrences(vdi->e())) {
const auto it = env.varOccurrences.itemMap.find(vdi->e()->id());
if (it.first) {
bool hasRedundantOccurrenciesOnly = true;
for (const auto& c : *it.second) {
if (auto* constrI = c->dynamicCast<ConstraintI>()) {
if (auto* call = Expression::dynamicCast<Call>(constrI->e())) {
if (call->id() == env.constants.ids.mzn_reverse_map_var) {
continue; // all good
}
}
}
hasRedundantOccurrenciesOnly = false;
break;
}
if (hasRedundantOccurrenciesOnly) {
env.flatRemoveItem(vdi);
env.varOccurrences.removeAllOccurrences(vdi->e());
for (const auto& c : *it.second) {
c->remove();
}
continue;
}
}
} else { // 0 occurrencies
if ((vdi->e()->e() != nullptr) && (vdi->e()->ti()->domain() != nullptr)) {
if (vdi->e()->type().isvar() && vdi->e()->type().isbool() &&
!vdi->e()->type().isOpt() &&
Expression::equal(vdi->e()->ti()->domain(), env.constants.literalTrue)) {
GCLock lock;
auto* ci = new ConstraintI(vdi->loc(), vdi->e()->e());
if (vdi->e()->introduced()) {
env.flatAddItem(ci);
env.flatRemoveItem(vdi);
continue;
}
vdi->e()->e(nullptr);
env.flatAddItem(ci);
} else if (vdi->e()->type().isPar() || vdi->e()->ti()->computedDomain()) {
env.flatRemoveItem(vdi);
continue;
}
} else {
env.flatRemoveItem(vdi);
continue;
}
}
}
// If no reverse mapper has been put in place, introduce it now
FunctionI* fi = env.model->matchRevMap(env, vdi->e()->type());
if (fi != nullptr && !env.hasReverseMapper(vdi->e()->id())) {
if (doLastProcessing) {
GCLock lock;
Call* revmap = Call::a(Location().introduce(), fi->id(), {vdi->e()->id()});
revmap->decl(fi);
Expression::type(revmap, Type::varbool());
// Give distinct call stack
Annotation& ann = Expression::ann(vdi->e());
Expression* tmp = revmap;
if (Expression* mznpath_ann = ann.getCall(env.constants.ann.mzn_path)) {
tmp = Expression::cast<Call>(mznpath_ann)->arg(0);
}
CallStackItem csi(env, tmp);
env.flatAddItem(new ConstraintI(Location().introduce(), revmap));
} else {
processLast.push_back(i);
}
}
if (vdi->e()->type().dim() > 0 && vdi->e()->type().isvar()) {
vdi->e()->ti()->eraseDomain();
}
if (vdi->e()->type().isint() && vdi->e()->type().isvar() &&
vdi->e()->ti()->domain() != nullptr && !vdi->e()->type().isOpt()) {
GCLock lock;
IntSetVal* dom = eval_intset(env, vdi->e()->ti()->domain());
if (dom->empty()) {
std::ostringstream oss;
oss << "Variable has empty domain: " << (*vdi->e());
env.fail(oss.str());
}
bool needRangeDomain = onlyRangeDomains;
if (!needRangeDomain) {
if (dom->min(0).isMinusInfinity() || dom->max(dom->size() - 1).isPlusInfinity()) {
needRangeDomain = true;
}
}
if (needRangeDomain) {
if (doLastProcessing) {
Expression* dom_expr = vdi->e()->ti()->domain();
if (dom->min(0).isMinusInfinity() || dom->max(dom->size() - 1).isPlusInfinity()) {
// Erase the domain to remove infinity literal
auto* nti = Expression::cast<TypeInst>(copy(env, vdi->e()->ti()));
nti->domain(nullptr);
vdi->e()->ti(nti);
// Add the ub/lb back as a constraint
Call* call = nullptr;
if (dom->min(0).isFinite()) {
// Note: cannot be combined into `mzn_set_in_internal` as CSE interferes
call = Call::a(vdi->loc(), env.constants.ids.int_.le,
{IntLit::a(dom->min(0)), vdi->e()->id()});
} else if (dom->max(dom->size() - 1).isFinite()) {
// Note: cannot be combined into `mzn_set_in_internal` as CSE interferes
call = Call::a(vdi->loc(), env.constants.ids.int_.le,
{vdi->e()->id(), IntLit::a(dom->max(dom->size() - 1))});
}
if (call != nullptr) {
call->type(Type::varbool());
call->decl(env.model->matchFn(env, call, false));
env.flatAddItem(new ConstraintI(vdi->loc(), call));
}
} else if (dom->size() > 1) {
// Simplify domains to be a single range
auto* newDom = new SetLit(Location().introduce(),
IntSetVal::a(dom->min(0), dom->max(dom->size() - 1)));
auto* nti = Expression::cast<TypeInst>(copy(env, vdi->e()->ti()));
nti->domain(newDom);
vdi->e()->ti(nti);
}
// Re-add the more complex (range) domain constraint
// note: might still be required when infinity in the domain
if (dom->size() > 1) {
Call* call = Call::a(vdi->loc(), env.constants.ids.mzn_set_in_internal,
{vdi->e()->id(), dom_expr});
call->type(Type::varbool());
call->decl(env.model->matchFn(env, call, false));
// Give distinct call stack
Annotation& ann = Expression::ann(vdi->e());
Expression* tmp = call;
if (Expression* mznpath_ann = ann.getCall(env.constants.ann.mzn_path)) {
tmp = Expression::cast<Call>(mznpath_ann)->arg(0);
}
CallStackItem csi(env, tmp);
env.flatAddItem(new ConstraintI(vdi->loc(), call));
}
} else {
processLast.push_back(i);
}
}
}
if (vdi->e()->type().isfloat() && vdi->e()->type().isvar() &&
vdi->e()->ti()->domain() != nullptr) {
GCLock lock;
Expression* dom_expr = vdi->e()->ti()->domain();
FloatSetVal* vdi_dom = eval_floatset(env, dom_expr);
if (vdi_dom->empty()) {
std::ostringstream oss;
oss << "Variable has empty domain: " << (*vdi->e());
env.fail(oss.str());
}
FloatVal vmin = vdi_dom->min();
FloatVal vmax = vdi_dom->max();
if (vmin == -FloatVal::infinity() || vmax == FloatVal::infinity()) {
// Erase the domain to remove infinity literal
vdi->e()->ti()->domain(nullptr);
// Add the ub/lb back as a constraint
Call* call = nullptr;
if (vmax != FloatVal::infinity()) {
// Note: cannot be combined into `mzn_set_in_internal` as CSE interferes
call = Call::a(vdi->loc(), env.constants.ids.float_.le,
{vdi->e()->id(), FloatLit::a(vmax)});
} else if (vmin != -FloatVal::infinity()) {
// Note: cannot be combined into `mzn_set_in_internal` as CSE interferes
call = Call::a(Location().introduce(), env.constants.ids.float_.le,
{FloatLit::a(vmin), vdi->e()->id()});
}
if (call != nullptr) {
call->type(Type::varbool());
call->decl(env.model->matchFn(env, call, false));
env.flatAddItem(new ConstraintI(vdi->loc(), call));
}
} else if (vdi_dom->size() > 1) {
// Simplify domains to be a single range
auto* range = new SetLit(Expression::loc(vdi->e()->ti()->domain()),
FloatSetVal::a({FloatSetVal::Range(vmin, vmax)}));
range->type(Type::parsetfloat());
vdi->e()->ti()->domain(range);
}
// Re-add the more complex (range) domain constraint
// note: might still be required when infinity in the domain
if (vdi_dom->size() > 1) {
Call* call = Call::a(vdi->loc(), env.constants.ids.mzn_set_in_internal,
{vdi->e()->id(), dom_expr});
call->type(Type::varbool());
call->decl(env.model->matchFn(env, call, false));
// Give distinct call stack
Annotation& ann = Expression::ann(vdi->e());
Expression* tmp = call;
if (Expression* mznpath_ann = ann.getCall(env.constants.ann.mzn_path)) {
tmp = Expression::cast<Call>(mznpath_ann)->arg(0);
}
CallStackItem csi(env, tmp);
env.flatAddItem(new ConstraintI(vdi->loc(), call));
}
}
}
}
// rewrite some constraints if there are redefinitions
for (int i : agenda) {
if (m[i]->removed()) {
continue;
}
if (auto* vdi = m[i]->dynamicCast<VarDeclI>()) {
VarDecl* vd = vdi->e();
if (vd->e() != nullptr) {
bool isTrueVar = vd->type().isbool() &&
Expression::equal(vd->ti()->domain(), env.constants.literalTrue);
if (Call* c = Expression::dynamicCast<Call>(vd->e())) {
GCLock lock;
Call* nc = nullptr;
if (c->id() == env.constants.ids.lin_exp) {
if (c->type().isfloat() && (float_lin_eq != nullptr)) {
std::vector<Expression*> args(c->argCount());
auto* le_c = Expression::cast<ArrayLit>(follow_id(c->arg(0)));
std::vector<Expression*> nc_c(le_c->size());
for (auto ii = static_cast<unsigned int>(nc_c.size()); (ii--) != 0U;) {
nc_c[ii] = (*le_c)[ii];
}
nc_c.push_back(FloatLit::a(-1));
args[0] = new ArrayLit(Location().introduce(), nc_c);
Expression::type(args[0], Type::parfloat(1));
auto* le_x = Expression::cast<ArrayLit>(follow_id(c->arg(1)));
std::vector<Expression*> nx(le_x->size());
for (auto ii = static_cast<unsigned int>(nx.size()); (ii--) != 0U;) {
nx[ii] = (*le_x)[ii];
}
nx.push_back(vd->id());
args[1] = new ArrayLit(Location().introduce(), nx);
Expression::type(args[1], Type::varfloat(1));
FloatVal d = FloatLit::v(Expression::cast<FloatLit>(c->arg(2)));
args[2] = FloatLit::a(-d);
Expression::type(args[2], Type::parfloat(0));
nc = Call::a(Expression::loc(c).introduce(), ASTString("float_lin_eq"), args);
nc->type(Type::varbool());
nc->decl(float_lin_eq);
} else if (int_lin_eq != nullptr) {
assert(c->type().isint());
std::vector<Expression*> args(c->argCount());
auto* le_c = Expression::cast<ArrayLit>(follow_id(c->arg(0)));
std::vector<Expression*> nc_c(le_c->size());
for (auto ii = static_cast<unsigned int>(nc_c.size()); (ii--) != 0U;) {
nc_c[ii] = (*le_c)[ii];
}
nc_c.push_back(IntLit::a(-1));
args[0] = new ArrayLit(Location().introduce(), nc_c);
Expression::type(args[0], Type::parint(1));
auto* le_x = Expression::cast<ArrayLit>(follow_id(c->arg(1)));
std::vector<Expression*> nx(le_x->size());
for (auto ii = static_cast<unsigned int>(nx.size()); (ii--) != 0U;) {
nx[ii] = (*le_x)[ii];
}
nx.push_back(vd->id());
args[1] = new ArrayLit(Location().introduce(), nx);
Expression::type(args[1], Type::varint(1));
IntVal d = IntLit::v(Expression::cast<IntLit>(c->arg(2)));
args[2] = IntLit::a(-d);
Expression::type(args[2], Type::parint(0));
nc = Call::a(Expression::loc(c).introduce(), ASTString("int_lin_eq"), args);
nc->type(Type::varbool());
nc->decl(int_lin_eq);
}
} else if (c->id() == env.constants.ids.exists) {
if (isTrueVar && array_bool_clause != nullptr) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = env.constants.emptyBoolArray;
nc = Call::a(Expression::loc(c).introduce(), array_bool_clause->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_clause);
} else if (halfReifyClause && Expression::ann(vd).contains(env.constants.ctx.pos)) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = new ArrayLit(Expression::loc(vd).introduce(),
std::vector<Expression*>({vd->id()}));
Expression::type(args[1], Type::varbool(1));
nc = Call::a(Expression::loc(c).introduce(),
(array_bool_clause != nullptr) ? array_bool_clause->id()
: env.constants.ids.clause,
args);
nc->type(Type::varbool());
nc->decl((array_bool_clause != nullptr) ? array_bool_clause
: env.model->matchFn(env, nc, false));
} else if (!isTrueVar && array_bool_clause_reif != nullptr) {
std::vector<Expression*> args(3);
args[0] = c->arg(0);
args[1] = env.constants.emptyBoolArray;
args[2] = vd->id();
nc = Call::a(Expression::loc(c).introduce(), array_bool_clause_reif->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_clause_reif);
}
} else if (!isTrueVar && c->id() == env.constants.ids.forall) {
if (env.fopts.enableHalfReification &&
Expression::ann(vd).contains(env.constants.ctx.pos) &&
array_bool_and_imp != nullptr) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = vd->id();
nc = Call::a(Expression::loc(c).introduce(), array_bool_and_imp->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_and_imp);
} else if (array_bool_and != nullptr) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = vd->id();
nc = Call::a(Expression::loc(c).introduce(), array_bool_and->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_and);
}
} else if (isTrueVar && c->id() == env.constants.ids.clause &&
(array_bool_clause != nullptr)) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = c->arg(1);
nc = Call::a(Expression::loc(c).introduce(), array_bool_clause->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_clause);
} else if (c->id() == env.constants.ids.clause && halfReifyClause &&
Expression::ann(vd).contains(env.constants.ctx.pos)) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
ArrayLit* old = eval_array_lit(env, c->arg(1));
std::vector<Expression*> neg(old->size() + 1);
for (unsigned int i = 0; i < old->size(); ++i) {
neg[i] = (*old)[i];
}
neg[old->size()] = vd->id();
args[1] = new ArrayLit(Expression::loc(old).introduce(), neg);
Expression::type(args[1], Type::varbool(1));
nc = Call::a(Expression::loc(c).introduce(),
(array_bool_clause != nullptr) ? array_bool_clause->id()
: env.constants.ids.clause,
args);
nc->type(Type::varbool());
nc->decl((array_bool_clause != nullptr) ? array_bool_clause : c->decl());
} else if (!isTrueVar && c->id() == env.constants.ids.clause &&
(array_bool_clause_reif != nullptr)) {
std::vector<Expression*> args(3);
args[0] = c->arg(0);
args[1] = c->arg(1);
args[2] = vd->id();
nc = Call::a(Expression::loc(c).introduce(), array_bool_clause_reif->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_clause_reif);
} else if (c->id() == env.constants.ids.bool_.not_ && c->argCount() == 1 &&
c->decl()->e() == nullptr) {
bool isFalseVar = Expression::equal(vd->ti()->domain(), env.constants.literalFalse);
if (c->arg(0) == env.constants.literalTrue) {
if (isTrueVar) {
env.fail();
} else {
env.flatRemoveExpr(c, vdi);
env.cseMapRemove(c);
vd->e(env.constants.literalFalse);
vd->ti()->domain(env.constants.literalFalse);
}
} else if (c->arg(0) == env.constants.literalFalse) {
if (isFalseVar) {
env.fail();
} else {
env.flatRemoveExpr(c, vdi);
env.cseMapRemove(c);
vd->e(env.constants.literalTrue);
vd->ti()->domain(env.constants.literalTrue);
}
} else if (Expression::isa<Id>(c->arg(0)) && (isTrueVar || isFalseVar)) {
VarDecl* arg_vd = Expression::cast<Id>(c->arg(0))->decl();
if (arg_vd->ti()->domain() == nullptr) {
if (arg_vd->e() == nullptr) {
arg_vd->e(env.constants.boollit(!isTrueVar));
}
arg_vd->ti()->domain(env.constants.boollit(!isTrueVar));
} else if (arg_vd->ti()->domain() == env.constants.boollit(isTrueVar)) {
env.fail();
} else if (arg_vd->e() == nullptr) {
assert(arg_vd->ti()->domain() == env.constants.boollit(!isTrueVar));
arg_vd->e(arg_vd->ti()->domain());
}
env.flatRemoveExpr(c, vdi);
vd->e(nullptr);
// Need to remove right hand side from CSE map, otherwise
// flattening of nc could assume c has already been flattened
// to vd
env.cseMapRemove(c);
} else {
// don't know how to handle, use bool_not/2
nc = Call::a(Expression::loc(c).introduce(), c->id(), {c->arg(0), vd->id()});
nc->type(Type::varbool());
nc->decl(env.model->matchFn(env, nc, false));
}
} else {
if (isTrueVar) {
FunctionI* decl = env.model->matchFn(env, c, false);
env.cseMapRemove(c);
if ((decl->e() != nullptr) || c->id() == env.constants.ids.forall) {
if (decl->e() != nullptr) {
add_path_annotation(env, decl->e());
}
c->decl(decl);
nc = c;
}
} else {
std::vector<Expression*> args(c->argCount());
for (auto i = static_cast<unsigned int>(args.size()); (i--) != 0U;) {
args[i] = c->arg(i);
}
args.push_back(vd->id());
FunctionI* decl = nullptr;
if (c->type().isbool() && vd->type().isbool()) {
bool canHalfReify = env.fopts.enableHalfReification &&
Expression::ann(vd).contains(env.constants.ctx.pos);
decl = env.model->matchReification(env, c->id(), args, canHalfReify, false);
if (decl == nullptr) {
std::ostringstream ss;
ss << "'" << demonomorphise_identifier(c->id())
<< "' is used in a reified context but no reified version is "
"available";
throw FlatteningError(env, Expression::loc(c), ss.str());
}
} else {
decl = env.model->matchFn(env, c->id(), args, false);
}
if ((decl != nullptr) && (decl->e() != nullptr)) {
add_path_annotation(env, decl->e());
nc = Call::a(Expression::loc(c).introduce(), decl->id(), args);
nc->type(Type::varbool());
nc->decl(decl);
}
}
}
if (nc != nullptr) {
// Note: Removal of VarDecl's referenced by c must be delayed
// until nc is flattened
std::vector<VarDecl*> toRemove;
CollectDecls cd(env, env.varOccurrences, toRemove, vdi);
top_down(cd, c);
vd->e(nullptr);
// Need to remove right hand side from CSE map, otherwise
// flattening of nc could assume c has already been flattened
// to vd
env.cseMapRemove(c);
/// TODO: check if removing variables here makes sense:
// if (!is_output(vd) && env.varOccurrences.occurrences(vd)==0) {
// removedItems.push_back(vdi);
// }
if (nc != c) {
make_defined_var(env, vd, nc);
for (ExpressionSetIter it = Expression::ann(c).begin();
it != Expression::ann(c).end(); ++it) {
EE ee_ann = flat_exp(env, Ctx(), *it, nullptr, env.constants.varTrue);
Expression::addAnnotation(nc, ee_ann.r());
}
}
StringLit* vsl = get_longest_mzn_path_annotation(env, vdi->e());
StringLit* csl = get_longest_mzn_path_annotation(env, c);
CallStackItem* vsi = nullptr;
CallStackItem* csi = nullptr;
if (vsl != nullptr) {
vsi = new CallStackItem(env, vsl);
}
if (csl != nullptr) {
csi = new CallStackItem(env, csl);
}
Location orig_loc = Expression::loc(nc);
if (csl != nullptr) {
ASTString loc = csl->v();
size_t sep = loc.find('|');
std::string filename = loc.substr(0, sep);
std::string start_line_s = loc.substr(sep + 1, loc.find('|', sep + 1) - sep - 1);
int start_line = std::stoi(start_line_s);
Location new_loc(ASTString(filename), start_line, 0, start_line, 0);
orig_loc = new_loc;
}
ItemTimer item_timer(orig_loc, timingMap);
(void)flat_exp(env, Ctx(), nc, env.constants.varTrue, env.constants.varTrue);
delete csi;
delete vsi;
// Remove VarDecls becoming unused through the removal of c
// because they are not used by nc
while (!toRemove.empty()) {
VarDecl* cur = toRemove.back();
toRemove.pop_back();
if (env.varOccurrences.occurrences(cur) == 0 && CollectDecls::varIsFree(cur)) {
auto cur_idx = env.varOccurrences.idx.find(cur->id());
if (cur_idx.first) {
auto* vdi = m[*cur_idx.second]->cast<VarDeclI>();
if (!is_output(cur) && !m[*cur_idx.second]->removed()) {
CollectDecls cd(env, env.varOccurrences, toRemove, vdi);
top_down(cd, vdi->e()->e());
vdi->remove();
}
}
}
}
}
}
}
} else if (auto* ci = m[i]->dynamicCast<ConstraintI>()) {
if (Call* c = Expression::dynamicCast<Call>(ci->e())) {
GCLock lock;
Call* nc = nullptr;
if (c->id() == env.constants.ids.exists) {
if (array_bool_clause != nullptr) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = env.constants.emptyBoolArray;
nc = Call::a(Expression::loc(c).introduce(), array_bool_clause->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_clause);
}
} else if (c->id() == env.constants.ids.forall) {
if (array_bool_and != nullptr) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = env.constants.literalTrue;
nc = Call::a(Expression::loc(c).introduce(), array_bool_and->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_and);
}
} else if (c->id() == env.constants.ids.clause) {
if (array_bool_clause != nullptr) {
std::vector<Expression*> args(2);
args[0] = c->arg(0);
args[1] = c->arg(1);
nc = Call::a(Expression::loc(c).introduce(), array_bool_clause->id(), args);
nc->type(Type::varbool());
nc->decl(array_bool_clause);
}
} else if (c->id() == env.constants.ids.bool_.ne) {
if (bool_xor != nullptr) {
std::vector<Expression*> args(3);
args[0] = c->arg(0);
args[1] = c->arg(1);
args[2] = c->argCount() == 2 ? env.constants.literalTrue : c->arg(2);
nc = Call::a(Expression::loc(c).introduce(), bool_xor->id(), args);
nc->type(Type::varbool());
nc->decl(bool_xor);
}
} else if (c->id() == env.constants.ids.bool_.not_ && c->argCount() == 1 &&
c->decl()->e() == nullptr) {
if (c->arg(0) == env.constants.literalTrue) {
env.fail();
} else if (c->arg(0) == env.constants.literalFalse) {
// nothing to do, not false = true
} else if (Expression::isa<Id>(c->arg(0))) {
VarDecl* vd = Expression::cast<Id>(c->arg(0))->decl();
if (vd->ti()->domain() == nullptr) {
vd->ti()->domain(env.constants.literalFalse);
} else if (vd->ti()->domain() == env.constants.literalTrue) {
env.fail();
}
} else {
// don't know how to handle, use bool_not/2
nc = Call::a(Expression::loc(c).introduce(), c->id(),
{c->arg(0), env.constants.literalTrue});
nc->type(Type::varbool());
nc->decl(env.model->matchFn(env, nc, false));
}
if (nc == nullptr) {
env.flatRemoveItem(ci);
}
} else {
FunctionI* decl = env.model->matchFn(env, c, false);
if ((decl != nullptr) && (decl->e() != nullptr)) {
nc = c;
nc->decl(decl);
}
}
if (nc != nullptr) {
if (nc != c) {
for (ExpressionSetIter it = Expression::ann(c).begin();
it != Expression::ann(c).end(); ++it) {
EE ee_ann = flat_exp(env, Ctx(), *it, nullptr, env.constants.varTrue);
Expression::addAnnotation(nc, ee_ann.r());
}
}
StringLit* sl = get_longest_mzn_path_annotation(env, c);
CallStackItem* csi = nullptr;
if (sl != nullptr) {
csi = new CallStackItem(env, sl);
}
ItemTimer item_timer(Expression::loc(nc), timingMap);
(void)flat_exp(env, Ctx(), nc, env.constants.varTrue, env.constants.varTrue);
env.flatRemoveItem(ci);
delete csi;
}
}
}
}
startItem = endItem + 1;
endItem = static_cast<int>(m.size()) - 1;
}
// Add redefinitions for output variables that may have been redefined since create_output
for (unsigned int i = 0; i < env.output->size(); i++) {
if (auto* vdi = (*env.output)[i]->dynamicCast<VarDeclI>()) {
if (vdi->e()->e() == nullptr) {
auto it = env.reverseMappers.find(vdi->e()->id());
if (it != env.reverseMappers.end()) {
GCLock lock;
Call* rhs = Expression::cast<Call>(copy(env, env.cmap, it->second()));
check_output_par_fn(env, rhs);
output_vardecls(env, vdi, rhs);
remove_is_output(vdi->e()->flat());
vdi->e()->e(rhs);
}
}
}
}
if (!opt.keepOutputInFzn) {
finalise_output(env);
}
for (auto& i : m) {
if (auto* ci = i->dynamicCast<ConstraintI>()) {
if (Call* c = Expression::dynamicCast<Call>(ci->e())) {
if (c->decl() == env.constants.varRedef) {
env.flatRemoveItem(ci);
}
}
}
}
cleanup_output(env);
} catch (ModelInconsistent&) { /* NOLINT(bugprone-empty-catch) */
}
if (opt.detailedTiming) {
if (opt.encapsulateJSON) {
auto& os = e.envi().outstream;
os << "{\"type\": \"profiling\", \"entries\": [";
bool first = true;
for (auto& entry : *timingMap) {
std::chrono::milliseconds time_taken =
std::chrono::duration_cast<std::chrono::milliseconds>(entry.second);
if (time_taken > std::chrono::milliseconds(0)) {
if (first) {
first = false;
} else {
os << ", ";
}
os << "{\"filename\": \"" << Printer::escapeStringLit(entry.first.first)
<< "\", \"line\": " << entry.first.second << ", \"time\": " << time_taken.count()
<< "}";
}
}
os << "]}" << std::endl;
} else {
StatisticsStream ss(e.envi().outstream, opt.encapsulateJSON);
e.envi().outstream << "% Compilation profile (file,line,milliseconds)\n";
if (opt.collectMznPaths) {
e.envi().outstream << "% (time is allocated to toplevel item)\n";
} else {
e.envi().outstream << "% (locations are approximate, use --keep-paths to allocate times to "
"toplevel items)\n";
}
for (auto& entry : *timingMap) {
std::chrono::milliseconds time_taken =
std::chrono::duration_cast<std::chrono::milliseconds>(entry.second);
if (time_taken > std::chrono::milliseconds(0)) {
std::ostringstream oss;
oss << "[\"" << entry.first.first << "\"," << entry.first.second << ","
<< time_taken.count() << "]";
ss.addRaw("profiling", oss.str());
}
}
}
}
}
void clear_internal_annotations(EnvI& env, Expression* e, bool keepDefinesVar) {
auto& ann = Expression::ann(e);
ann.remove(env.constants.ann.promise_total);
ann.remove(env.constants.ann.promise_commutative);
ann.remove(env.constants.ann.maybe_partial);
ann.remove(env.constants.ann.add_to_output);
ann.remove(env.constants.ann.output);
ann.remove(env.constants.ann.rhs_from_assignment);
ann.remove(env.constants.ann.mzn_was_undefined);
// Remove defines_var(x) annotation where x is par
std::vector<Expression*> removeAnns;
for (ExpressionSetIter anns = ann.begin(); anns != ann.end(); ++anns) {
if (Call* c = Expression::dynamicCast<Call>(*anns)) {
if (c->id() == env.constants.ann.defines_var &&
(!keepDefinesVar || Expression::type(c->arg(0)).isPar())) {
removeAnns.push_back(c);
}
}
}
for (auto& removeAnn : removeAnns) {
ann.remove(removeAnn);
}
}
std::vector<Expression*> cleanup_vardecl(EnvI& env, VarDeclI* vdi, VarDecl* vd,
bool keepDefinesVar) {
std::vector<Expression*> added_constraints;
// In FlatZinc par variables have RHSs, not domains
if (vd->type().isPar()) {
Expression::ann(vd).clear();
vd->introduced(false);
vd->ti()->eraseDomain();
}
// In FlatZinc the RHS of a VarDecl must be a literal, Id or empty
// Example:
// var 1..5: x = function(y)
// becomes:
// var 1..5: x;
// relation(x, y);
if (vd->type().isvar() && vd->type().isbool()) {
bool is_fixed = (vd->ti()->domain() != nullptr);
if (Expression::equal(vd->ti()->domain(), env.constants.literalTrue)) {
// Ex: var true: b = e()
// Store RHS
Expression* ve = vd->e();
vd->e(env.constants.literalTrue);
vd->ti()->domain(nullptr);
// Ex: var bool: b = true
// If vd had a RHS
if (ve != nullptr) {
if (Call* vcc = Expression::dynamicCast<Call>(ve)) {
// Convert functions to relations:
// exists([x]) => bool_clause([x],[])
// forall([x]) => array_bool_and([x],true)
// clause([x],[y]) => bool_clause([x],[y])
ASTString cid;
std::vector<Expression*> args;
if (vcc->id() == env.constants.ids.exists) {
cid = env.constants.ids.bool_.clause;
args.push_back(vcc->arg(0));
args.push_back(env.constants.emptyBoolArray);
} else if (vcc->id() == env.constants.ids.forall) {
cid = env.constants.ids.bool_reif.array_and;
args.push_back(vcc->arg(0));
args.push_back(env.constants.literalTrue);
} else if (vcc->id() == env.constants.ids.clause) {
cid = env.constants.ids.bool_.clause;
args.push_back(vcc->arg(0));
args.push_back(vcc->arg(1));
}
if (args.empty()) {
// Post original RHS as stand alone constraint
ve = vcc;
} else {
// Create new call, retain annotations from original RHS
Call* nc = Call::a(Expression::loc(vcc).introduce(), cid, args);
nc->type(vcc->type());
Expression::ann(nc).merge(Expression::ann(vcc));
ve = nc;
}
} else if (Id* id = Expression::dynamicCast<Id>(ve)) {
if (id->decl()->ti()->domain() != env.constants.literalTrue) {
// Inconsistent assignment: post bool_eq(y, true)
std::vector<Expression*> args(2);
args[0] = id;
args[1] = env.constants.literalTrue;
GCLock lock;
ve = Call::a(Location().introduce(), env.constants.ids.bool_.eq, args);
} else {
// Don't post this
ve = env.constants.literalTrue;
}
}
// Post new constraint
if (ve != env.constants.literalTrue) {
clear_internal_annotations(env, ve, keepDefinesVar);
added_constraints.push_back(ve);
}
}
} else {
// Ex: var false: b = e()
if (vd->e() != nullptr) {
if (Expression::eid(vd->e()) == Expression::E_CALL) {
// Convert functions to relations:
// var false: b = exists([x]) => bool_clause_reif([x], [], b)
// var false: b = forall([x]) => array_bool_and([x], b)
// var false: b = clause([x]) => bool_clause_reif([x], b)
const Call* c = Expression::cast<Call>(vd->e());
GCLock lock;
vd->e(nullptr);
ASTString cid;
FunctionI* decl(nullptr);
std::vector<Expression*> args(c->argCount());
for (unsigned int i = c->argCount(); (i--) != 0U;) {
args[i] = c->arg(i);
}
if (c->id() == env.constants.ids.exists) {
args.push_back(env.constants.emptyBoolArray);
}
if (is_fixed) {
args.push_back(env.constants.literalFalse);
} else {
args.push_back(vd->id());
}
if (c->id() == env.constants.ids.exists || c->id() == env.constants.ids.clause) {
cid = env.constants.ids.bool_reif.clause;
} else if (c->id() == env.constants.ids.forall) {
cid = env.constants.ids.bool_reif.array_and;
} else {
bool canHalfReify = env.fopts.enableHalfReification &&
Expression::ann(vd).contains(env.constants.ctx.pos);
decl = env.model->matchReification(env, c->id(), args, canHalfReify, false);
cid = (decl != nullptr) ? decl->id() : env.reifyId(c->id());
}
Call* nc = Call::a(Expression::loc(c).introduce(), cid, args);
nc->type(c->type());
if (decl == nullptr) {
decl = env.model->matchFn(env, nc, false);
}
if (decl == nullptr) {
std::ostringstream ss;
ss << "'" << demonomorphise_identifier(c->id())
<< "' is used in a reified context but no reified version is available";
throw FlatteningError(env, Expression::loc(c), ss.str());
}
nc->decl(decl);
if (!is_fixed) {
make_defined_var(env, vd, nc);
}
Expression::ann(nc).merge(Expression::ann(c));
clear_internal_annotations(env, nc, keepDefinesVar);
added_constraints.push_back(nc);
} else {
assert(Expression::eid(vd->e()) == Expression::E_ID ||
Expression::eid(vd->e()) == Expression::E_BOOLLIT);
}
}
if (Expression::equal(vd->ti()->domain(), env.constants.literalFalse)) {
vd->ti()->domain(nullptr);
vd->e(env.constants.literalFalse);
}
}
if (vdi != nullptr && is_fixed && env.varOccurrences.occurrences(vd) == 0) {
if (is_output(vd)) {
VarDecl* vd_output =
(*env.output)[env.outputFlatVarOccurrences.find(vd)]->cast<VarDeclI>()->e();
if (vd_output->e() == nullptr) {
vd_output->e(vd->e());
}
}
env.flatRemoveItem(vdi);
}
} else if (vd->type().isvar() && vd->type().dim() == 0) {
// Int or Float var
if (vd->e() != nullptr) {
if (const Call* cc = Expression::dynamicCast<Call>(vd->e())) {
// Remove RHS from vd
vd->e(nullptr);
std::vector<Expression*> args(cc->argCount());
ASTString cid;
if (cc->id() == env.constants.ids.lin_exp) {
// a = lin_exp([1],[b],5) => int_lin_eq([1,-1],[b,a],-5):: defines_var(a)
auto* le_c = Expression::cast<ArrayLit>(follow_id(cc->arg(0)));
std::vector<Expression*> nc(le_c->size());
for (auto i = static_cast<unsigned int>(nc.size()); (i--) != 0U;) {
nc[i] = (*le_c)[i];
}
if (le_c->type().bt() == Type::BT_INT) {
cid = env.constants.ids.int_.lin_eq;
nc.push_back(IntLit::a(-1));
args[0] = new ArrayLit(Location().introduce(), nc);
Expression::type(args[0], Type::parint(1));
auto* le_x = Expression::cast<ArrayLit>(follow_id(cc->arg(1)));
std::vector<Expression*> nx(le_x->size());
for (auto i = static_cast<unsigned int>(nx.size()); (i--) != 0U;) {
nx[i] = (*le_x)[i];
}
nx.push_back(vd->id());
args[1] = new ArrayLit(Location().introduce(), nx);
Expression::type(args[1], le_x->type());
IntVal d = IntLit::v(Expression::cast<IntLit>(cc->arg(2)));
args[2] = IntLit::a(-d);
} else {
// float
cid = env.constants.ids.float_.lin_eq;
nc.push_back(FloatLit::a(-1.0));
args[0] = new ArrayLit(Location().introduce(), nc);
Expression::type(args[0], Type::parfloat(1));
auto* le_x = Expression::cast<ArrayLit>(follow_id(cc->arg(1)));
std::vector<Expression*> nx(le_x->size());
for (auto i = static_cast<unsigned int>(nx.size()); (i--) != 0U;) {
nx[i] = (*le_x)[i];
}
nx.push_back(vd->id());
args[1] = new ArrayLit(Location().introduce(), nx);
Expression::type(args[1], le_x->type());
FloatVal d = FloatLit::v(Expression::cast<FloatLit>(cc->arg(2)));
args[2] = FloatLit::a(-d);
}
} else {
if (cc->id() == env.constants.ids.card) {
// card is 'set_card' in old FlatZinc
cid = env.constants.ids.set_.card;
} else {
cid = cc->id();
}
for (auto i = static_cast<unsigned int>(args.size()); (i--) != 0U;) {
args[i] = cc->arg(i);
}
args.push_back(vd->id());
}
Call* nc = Call::a(Expression::loc(cc).introduce(), cid, args);
nc->type(cc->type());
make_defined_var(env, vd, nc);
Expression::ann(nc).merge(Expression::ann(cc));
clear_internal_annotations(env, nc, keepDefinesVar);
added_constraints.push_back(nc);
} else {
// RHS must be literal or Id
assert(Expression::eid(vd->e()) == Expression::E_ID ||
Expression::eid(vd->e()) == Expression::E_INTLIT ||
Expression::eid(vd->e()) == Expression::E_FLOATLIT ||
Expression::eid(vd->e()) == Expression::E_BOOLLIT ||
Expression::eid(vd->e()) == Expression::E_SETLIT);
}
}
} else if (vd->type().dim() > 0) {
// vd is an array
// If RHS is an Id, follow id to RHS
// a = [1,2,3]; b = a;
// vd = b => vd = [1,2,3]
if (!Expression::isa<ArrayLit>(vd->e())) {
vd->e(follow_id(vd->e()));
}
// If empty array or 1 indexed, continue
if (vd->ti()->ranges().size() == 1 && vd->ti()->ranges()[0]->domain() != nullptr &&
Expression::isa<SetLit>(vd->ti()->ranges()[0]->domain())) {
IntSetVal* isv = Expression::cast<SetLit>(vd->ti()->ranges()[0]->domain())->isv();
if ((isv != nullptr) && (isv->empty() || isv->min(0) == 1)) {
return added_constraints;
}
}
// Array should be 1 indexed since ArrayLit is 1 indexed
assert(vd->e() != nullptr);
ArrayLit* al = nullptr;
Expression* e = vd->e();
while (al == nullptr) {
switch (Expression::eid(e)) {
case Expression::E_ARRAYLIT:
al = Expression::cast<ArrayLit>(e);
break;
case Expression::E_ID:
e = Expression::cast<Id>(e)->decl()->e();
break;
default:
assert(false);
}
}
al->make1d();
IntSetVal* isv = IntSetVal::a(1, al->length());
if (vd->ti()->ranges().size() == 1) {
vd->ti()->ranges()[0]->domain(new SetLit(Location().introduce(), isv));
} else {
std::vector<TypeInst*> r(1);
r[0] = new TypeInst(Expression::loc(vd->ti()->ranges()[0]), vd->ti()->ranges()[0]->type(),
new SetLit(Location().introduce(), isv));
ASTExprVec<TypeInst> ranges(r);
auto* ti =
new TypeInst(Expression::loc(vd->ti()), vd->ti()->type(), ranges, vd->ti()->domain());
vd->ti(ti);
}
}
// Remove boolean context annotations used only on compilation
for (auto* ann : env.constants.internalAnn()) {
Expression::ann(vd).remove(ann);
}
Expression::ann(vd).removeCall(env.constants.ann.mzn_check_enum_var);
return added_constraints;
}
Expression* cleanup_constraint(EnvI& env, std::unordered_set<Item*>& globals, Expression* ce,
bool keepDefinesVar) {
clear_internal_annotations(env, ce, keepDefinesVar);
if (Call* vc = Expression::dynamicCast<Call>(ce)) {
for (unsigned int i = 0; i < vc->argCount(); i++) {
// Change array indicies to be 1 indexed
if (auto* al = Expression::dynamicCast<ArrayLit>(vc->arg(i))) {
if (al->dims() > 1 || al->min(0) != 1) {
al->make1d();
}
}
}
// Convert functions to relations:
// exists([x]) => bool_clause([x],[])
// forall([x]) => array_bool_and([x],true) // TODO maybe assert false since this shouldn't
// really occur clause([x]) => bool_clause([x]) bool_xor([x],[y]) => bool_xor([x],[y],true)
if (vc->id() == env.constants.ids.exists) {
GCLock lock;
vc->id(env.constants.ids.bool_.clause);
std::vector<Expression*> args(2);
args[0] = vc->arg(0);
args[1] = env.constants.emptyBoolArray;
vc->args(args);
vc->decl(env.model->matchFn(env, vc, false));
} else if (vc->id() == env.constants.ids.forall) {
GCLock lock;
vc->id(env.constants.ids.bool_reif.array_and);
std::vector<Expression*> args(2);
args[0] = vc->arg(0);
args[1] = env.constants.literalTrue;
vc->args(args);
vc->decl(env.model->matchFn(env, vc, false));
} else if (vc->id() == env.constants.ids.clause) {
GCLock lock;
vc->id(env.constants.ids.bool_.clause);
vc->decl(env.model->matchFn(env, vc, false));
} else if (vc->id() == env.constants.ids.bool_.ne && vc->argCount() == 2) {
GCLock lock;
std::vector<Expression*> args(3);
args[0] = vc->arg(0);
args[1] = vc->arg(1);
args[2] = env.constants.literalTrue;
vc->args(args);
vc->decl(env.model->matchFn(env, vc, false));
}
// If vc->decl() is a solver builtin and has not been added to the
// FlatZinc, add it
if ((vc->decl() != nullptr) && vc->decl() != env.constants.varRedef &&
!vc->decl()->fromStdLib() &&
!vc->decl()->ann().contains(env.constants.ann.flatzinc_builtin) &&
globals.find(vc->decl()) == globals.end()) {
std::vector<VarDecl*> params(vc->decl()->paramCount());
for (unsigned int i = 0; i < params.size(); i++) {
params[i] = vc->decl()->param(i);
}
GCLock lock;
auto* vc_decl_copy = new FunctionI(vc->decl()->loc(), vc->decl()->id(), vc->decl()->ti(),
params, vc->decl()->e());
env.flatAddItem(vc_decl_copy);
globals.insert(vc->decl());
}
return ce;
}
if (Id* id = Expression::dynamicCast<Id>(ce)) {
// Ex: constraint b; => constraint bool_eq(b, true);
std::vector<Expression*> args(2);
args[0] = id;
args[1] = env.constants.literalTrue;
GCLock lock;
return Call::a(Location().introduce(), env.constants.ids.bool_.eq, args);
}
if (auto* bl = Expression::dynamicCast<BoolLit>(ce)) {
// Ex: true => delete; false => bool_eq(false, true);
if (!bl->v()) {
GCLock lock;
std::vector<Expression*> args(2);
args[0] = env.constants.literalFalse;
args[1] = env.constants.literalTrue;
Call* neq = Call::a(Location().introduce(), env.constants.ids.bool_.eq, args);
return neq;
}
return nullptr;
}
return ce;
}
void oldflatzinc(Env& e) {
Model* m = e.flat();
// Check wheter we need to keep defines_var annotations
bool keepDefinesVar = true;
{
GCLock lock;
Call* c = Call::a(Location().introduce(), "mzn_check_annotate_defines_var", {});
c->type(Type::parbool());
FunctionI* fi = e.model()->matchFn(e.envi(), c, true);
if (fi != nullptr) {
c->decl(fi);
keepDefinesVar = eval_bool(e.envi(), c);
}
}
// Check wheter we need to add domain_computed annotations
bool addDomComputed = false;
{
GCLock lock;
Call* c = Call::a(Location().introduce(), "mzn_check_annotate_computed_domains", {});
c->type(Type::parbool());
FunctionI* fi = e.model()->matchFn(e.envi(), c, true);
if (fi != nullptr) {
c->decl(fi);
addDomComputed = eval_bool(e.envi(), c);
}
}
// Mark annotations and optional variables for removal, and clear flags
for (auto& vdi : m->vardecls()) {
if (vdi.e()->type().ot() == Type::OT_OPTIONAL || vdi.e()->type().bt() == Type::BT_ANN ||
vdi.e()->type().structBT()) {
vdi.remove();
}
}
EnvI& env = e.envi();
// Predicate declarations of solver builtins
std::unordered_set<Item*> globals;
// Variables mapped to the index of the constraint that defines them
enum DFS_STATUS { DFS_UNKNOWN, DFS_SEEN, DFS_DONE };
std::unordered_map<VarDecl*, std::pair<int, DFS_STATUS>> definition_map;
std::vector<VarDecl*> definitions; // Make iteration over definition_map deterministic
// Record indices of VarDeclIs with Id RHS for sorting & unification
std::vector<unsigned int> declsWithIds;
// Important: items are being added to m while iterating over it.
// The loop therefore needs to check the size in each iteration to make
// sure it also handles the new items.
for (unsigned int i = 0; i < m->size(); i++) {
if ((*m)[i]->removed()) {
continue;
}
if (auto* vdi = (*m)[i]->dynamicCast<VarDeclI>()) {
GCLock lock;
VarDecl* vd = vdi->e();
std::vector<Expression*> added_constraints =
cleanup_vardecl(e.envi(), vdi, vd, keepDefinesVar);
// Record whether this VarDecl is equal to an Id (aliasing)
if ((vd->e() != nullptr) && Expression::isa<Id>(vd->e())) {
declsWithIds.push_back(i);
vdi->e()->payload(-static_cast<int>(i) - 1);
} else {
vdi->e()->payload(static_cast<int>(i));
}
for (auto* nc : added_constraints) {
Expression* new_ce = cleanup_constraint(e.envi(), globals, nc, keepDefinesVar);
if (new_ce != nullptr) {
e.envi().flatAddItem(new ConstraintI(Location().introduce(), new_ce));
}
}
if (Expression::ann(vd).contains(e.envi().constants.ann.is_defined_var)) {
if (definition_map.find(vd) == definition_map.end()) {
// We haven't seen this variable before
definition_map.insert({vd, {-1, DFS_UNKNOWN}});
definitions.push_back(vd);
}
}
} else if (auto* ci = (*m)[i]->dynamicCast<ConstraintI>()) {
Expression* new_ce = cleanup_constraint(e.envi(), globals, ci->e(), keepDefinesVar);
if (new_ce != nullptr) {
ci->e(new_ce);
if (keepDefinesVar) {
if (Call* defines_var = Expression::ann(new_ce).getCall(env.constants.ann.defines_var)) {
if (Id* ident = Expression::dynamicCast<Id>(defines_var->arg(0))) {
auto it = definition_map.find(ident->decl());
if (it != definition_map.end()) {
if (it->second.first == -1) {
// We've only seen the decl before, but not yet the defining constraint
it->second.first = static_cast<int>(i);
} else {
// This is the second definition, remove it
Expression::ann(new_ce).removeCall(env.constants.ann.defines_var);
}
} else {
definition_map.insert({ident->decl(), {i, DFS_UNKNOWN}});
definitions.push_back(ident->decl());
}
}
}
}
} else {
ci->remove();
}
} else if (auto* fi = (*m)[i]->dynamicCast<FunctionI>()) {
if (Let* let = Expression::dynamicCast<Let>(fi->e())) {
GCLock lock;
std::vector<Expression*> new_let;
for (unsigned int i = 0; i < let->let().size(); i++) {
Expression* let_e = let->let()[i];
if (auto* vd = Expression::dynamicCast<VarDecl>(let_e)) {
std::vector<Expression*> added_constraints =
cleanup_vardecl(e.envi(), nullptr, vd, keepDefinesVar);
new_let.push_back(vd);
for (auto* nc : added_constraints) {
new_let.push_back(nc);
}
} else {
Expression* new_ce = cleanup_constraint(e.envi(), globals, let_e, keepDefinesVar);
if (new_ce != nullptr) {
new_let.push_back(new_ce);
}
}
}
fi->e(new Let(Expression::loc(let), new_let, let->in()));
}
} else if (auto* si = (*m)[i]->dynamicCast<SolveI>()) {
if ((si->e() != nullptr) && Expression::type(si->e()).isPar()) {
// Introduce VarDecl if objective expression is par
GCLock lock;
auto* ti = new TypeInst(Location().introduce(), Expression::type(si->e()), nullptr);
auto* constantobj = new VarDecl(Location().introduce(), ti, e.envi().genId(), si->e());
si->e(constantobj->id());
e.envi().flatAddItem(VarDeclI::a(Location().introduce(), constantobj));
}
}
}
if (keepDefinesVar) {
// Detect and break cycles in defines_var annotations
std::vector<VarDecl*> definesStack;
auto checkId = [&definesStack, &definition_map, &m](VarDecl* cur, Id* ident) {
if (cur == ident->decl()) {
// Never push the variable we're currently looking at
return;
}
auto it = definition_map.find(ident->decl());
if (it != definition_map.end()) {
if (it->second.second == DFS_UNKNOWN) {
// not yet visited, push
definesStack.push_back(it->first);
} else if (it->second.second == DFS_SEEN) {
// Found a cycle through variable ident
// Break cycle by removing annotations
Expression::ann(ident->decl()).remove(Constants::constants().ann.is_defined_var);
Call* c = Expression::cast<Call>((*m)[it->second.first]->cast<ConstraintI>()->e());
Expression::ann(c).removeCall(Constants::constants().ann.defines_var);
}
}
};
for (auto* it : definitions) {
if (definition_map[it].second == DFS_UNKNOWN) {
// not yet visited
definesStack.push_back(it);
while (!definesStack.empty()) {
VarDecl* cur = definesStack.back();
if (definition_map[cur].second != DFS_UNKNOWN) {
// already visited (or already finished), now finished
definition_map[cur].second = DFS_DONE;
definesStack.pop_back();
} else {
// now visited and on stack
definition_map[cur].second = DFS_SEEN;
if (definition_map[cur].first == -1) {
// No associated call, remove annotation
Expression::ann(cur).remove(Constants::constants().ann.is_defined_var);
} else if (Call* c = Expression::dynamicCast<Call>(
(*m)[definition_map[cur].first]->cast<ConstraintI>()->e())) {
// Variable is defined by a call, push all arguments
unsigned int count_cur = 0;
for (unsigned int i = 0; i < c->argCount(); i++) {
if (Expression::type(c->arg(i)).isPar()) {
continue;
}
if (Id* ident = Expression::dynamicCast<Id>(c->arg(i))) {
if (ident->type().dim() > 0) {
if (auto* al = Expression::dynamicCast<ArrayLit>(ident->decl()->e())) {
for (auto* e : al->getVec()) {
if (auto* ident = Expression::dynamicCast<Id>(e)) {
if (cur == ident->decl()) {
count_cur++;
}
checkId(cur, ident);
}
}
}
} else if (ident->type().isvar()) {
if (cur == ident->decl()) {
count_cur++;
}
checkId(cur, ident);
}
} else if (auto* al = Expression::dynamicCast<ArrayLit>(c->arg(i))) {
for (auto* e : al->getVec()) {
if (auto* ident = Expression::dynamicCast<Id>(e)) {
if (cur == ident->decl()) {
count_cur++;
}
checkId(cur, ident);
}
}
}
}
if (count_cur != 1) {
// We've seen the defined variable 0 times or more than once,
// so this call cannot define the variable
Expression::ann(cur).remove(Constants::constants().ann.is_defined_var);
Expression::ann(c).removeCall(Constants::constants().ann.defines_var);
}
}
}
}
}
}
}
// Sort VarDecls in FlatZinc so that VarDecls are declared before use
std::vector<VarDeclI*> sortedVarDecls(declsWithIds.size());
int vdCount = 0;
for (auto declsWithId : declsWithIds) {
VarDecl* cur = (*m)[declsWithId]->cast<VarDeclI>()->e();
std::vector<int> stack;
while ((cur != nullptr) && cur->payload() < 0) {
stack.push_back(cur->payload());
if (Id* id = Expression::dynamicCast<Id>(cur->e())) {
cur = id->decl();
} else {
cur = nullptr;
}
}
for (auto i = static_cast<unsigned int>(stack.size()); (i--) != 0U;) {
auto* vdi = (*m)[-stack[i] - 1]->cast<VarDeclI>();
vdi->e()->payload(-vdi->e()->payload() - 1);
sortedVarDecls[vdCount++] = vdi;
}
}
for (unsigned int i = 0; i < declsWithIds.size(); i++) {
(*m)[declsWithIds[i]] = sortedVarDecls[i];
}
// Remove marked items
m->compact();
e.envi().output->compact();
// Add computed domain annotations
if (addDomComputed) {
for (auto& vdi : m->vardecls()) {
auto* vd = vdi.e();
if (vd->ti()->computedDomain() && vd->ti()->domain() != nullptr) {
Expression::addAnnotation(vd, e.envi().constants.ann.computed_domain);
}
}
}
for (auto& it : env.varOccurrences.itemMap) {
VarOccurrences::Items keptItems;
for (auto* iit : it) {
if (!iit->removed()) {
keptItems.insert(iit);
}
}
it = keptItems;
}
class Cmp {
public:
bool operator()(Item* i, Item* j) {
if (i == j) {
return false;
}
if (i->iid() == Item::II_FUN || j->iid() == Item::II_FUN) {
if (i->iid() == j->iid()) {
return false;
}
return i->iid() == Item::II_FUN;
}
if (i->iid() == Item::II_SOL) {
assert(j->iid() != i->iid());
return false;
}
if (j->iid() == Item::II_SOL) {
assert(j->iid() != i->iid());
return true;
}
if (i->iid() == Item::II_VD) {
if (j->iid() != i->iid()) {
return true;
}
if (i->cast<VarDeclI>()->e()->type().isPar() && j->cast<VarDeclI>()->e()->type().isvar()) {
return true;
}
if (j->cast<VarDeclI>()->e()->type().isPar() && i->cast<VarDeclI>()->e()->type().isvar()) {
return false;
}
if (i->cast<VarDeclI>()->e()->type().dim() == 0 &&
j->cast<VarDeclI>()->e()->type().dim() != 0) {
return true;
}
if (i->cast<VarDeclI>()->e()->type().dim() != 0 &&
j->cast<VarDeclI>()->e()->type().dim() == 0) {
return false;
}
if (i->cast<VarDeclI>()->e()->e() == nullptr && j->cast<VarDeclI>()->e()->e() != nullptr) {
return true;
}
if ((i->cast<VarDeclI>()->e()->e() != nullptr) &&
(j->cast<VarDeclI>()->e()->e() != nullptr) &&
!Expression::isa<Id>(i->cast<VarDeclI>()->e()->e()) &&
Expression::isa<Id>(j->cast<VarDeclI>()->e()->e())) {
return true;
}
}
return false;
}
} _cmp;
// Perform final sorting
std::stable_sort(m->begin(), m->end(), _cmp);
}
FlatModelStatistics statistics(Env& m) {
Model* flat = m.flat();
FlatModelStatistics stats;
stats.n_reif_ct = m.envi().counters.reifConstraints;
stats.n_imp_ct = m.envi().counters.impConstraints;
stats.n_imp_del = m.envi().counters.impDel;
stats.n_lin_del = m.envi().counters.linDel;
for (auto& i : *flat) {
if (!i->removed()) {
if (auto* vdi = i->dynamicCast<VarDeclI>()) {
Type t = vdi->e()->type();
if (t.isvar() && t.dim() == 0) {
if (t.isSet()) {
stats.n_set_vars++;
} else if (t.isint()) {
stats.n_int_vars++;
} else if (t.isbool()) {
stats.n_bool_vars++;
} else if (t.isfloat()) {
stats.n_float_vars++;
}
}
} else if (auto* ci = i->dynamicCast<ConstraintI>()) {
if (Call* call = Expression::dynamicCast<Call>(ci->e())) {
if (call->id().endsWith("_reif")) {
stats.n_reif_ct++;
} else if (call->id().endsWith("_imp")) {
stats.n_imp_ct++;
}
if (call->argCount() > 0) {
Type all_t;
for (unsigned int i = 0; i < call->argCount(); i++) {
Type t = Expression::type(call->arg(i));
if (t.isvar()) {
if (t.st() == Type::ST_SET ||
(t.bt() == Type::BT_FLOAT && all_t.st() != Type::ST_SET) ||
(t.bt() == Type::BT_INT && all_t.bt() != Type::BT_FLOAT &&
all_t.st() != Type::ST_SET) ||
(t.bt() == Type::BT_BOOL && all_t.bt() != Type::BT_INT &&
all_t.bt() != Type::BT_FLOAT && all_t.st() != Type::ST_SET)) {
all_t = t;
}
}
}
if (all_t.isvar()) {
if (all_t.st() == Type::ST_SET) {
stats.n_set_ct++;
} else if (all_t.bt() == Type::BT_INT) {
stats.n_int_ct++;
} else if (all_t.bt() == Type::BT_BOOL) {
stats.n_bool_ct++;
} else if (all_t.bt() == Type::BT_FLOAT) {
stats.n_float_ct++;
}
}
}
}
}
}
}
return stats;
}
ArrayLit* field_slice(EnvI& env, StructType* st, ArrayLit* al,
std::vector<std::pair<int, int>> dims, unsigned int field) {
assert(GC::locked());
assert(Expression::type(al).structBT() && Expression::type(al).dim() > 0);
Type field_ty = (*st)[field - 1];
// TODO: This could be done efficiently using slicing (if we change the memory layout for
// arrays of tuples)
std::vector<Expression*> tmp(al->size());
for (unsigned int i = 0; i < al->size(); ++i) {
tmp[i] = new FieldAccess(Expression::loc((*al)[i]).introduce(), (*al)[i], IntLit::a(field));
Expression::type(tmp[i], field_ty);
}
auto* field_slice = new ArrayLit(Expression::loc(al).introduce(), tmp, dims);
Expression::type(field_slice, Type::arrType(env, al->type(), field_ty));
return field_slice;
}
std::vector<Expression*> field_slices(EnvI& env, Expression* arrExpr) {
assert(GC::locked());
assert(Expression::type(arrExpr).structBT() && Expression::type(arrExpr).dim() > 0);
ArrayLit* al = eval_array_lit(env, arrExpr);
StructType* st = env.getStructType(al->type());
std::vector<std::pair<int, int>> dims(al->dims());
for (unsigned int i = 0; i < al->dims(); i++) {
dims[i] = std::make_pair(al->min(i), al->max(i));
}
std::vector<Expression*> field_al(st->size());
for (unsigned int i = 0; i < st->size(); ++i) {
field_al[i] = field_slice(env, st, al, dims, i + 1);
}
return field_al;
}
void cse_result_change_ctx(EnvI& env, Expression* cseRes, BCtx newCtx) {
std::vector<Expression*> stack({cseRes});
bool first = true;
while (!stack.empty()) {
Expression* back = stack.back();
stack.pop_back();
auto* ident = Expression::dynamicCast<Id>(back);
if (ident != nullptr && ident->decl() != nullptr && ident->decl()->e() != nullptr) {
if (auto* al = Expression::dynamicCast<ArrayLit>(ident->decl()->e())) {
for (unsigned int i = 0; i < al->size(); i++) {
stack.push_back((*al)[i]);
}
} else if (auto* redirect = Expression::dynamicCast<Id>(ident->decl()->e())) {
stack.push_back(redirect);
} else if (auto* c = Expression::dynamicCast<Call>(ident->decl()->e())) {
BCtx vdCtx;
bool annotated;
std::tie(vdCtx, annotated) = env.annToCtx(ident->decl());
if ((!first || vdCtx != newCtx) && vdCtx != C_ROOT && vdCtx != C_MIX) {
env.addCtxAnn(ident->decl(), (first && newCtx == C_ROOT) ? C_ROOT : C_MIX);
for (unsigned int i = 0; i < c->argCount(); i++) {
if (auto* al = Expression::dynamicCast<ArrayLit>(c->arg(i))) {
for (unsigned int i = 0; i < al->size(); i++) {
stack.push_back((*al)[i]);
}
} else if (auto* arg = Expression::dynamicCast<Id>(c->arg(i))) {
stack.push_back(redirect);
}
}
}
}
}
first = false;
}
}
} // namespace MiniZinc
|