eflint_json/spec.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 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
// SPEC.rs
// by Lut99
//
// Created:
// 08 Nov 2023, 16:25:20
// Last edited:
// 20 Dec 2023, 10:21:09
// Auto updated?
// Yes
//
// Description:
//! Defines the interface of the JSON Specification for various
//! versions. The versions are gated using features.
//!
//! The interfaces are implemented as [`serde`]-structs, which can be
//! serialized to- and deserialized from specification-compliant JSON.
//
use std::collections::HashMap;
use std::fmt::{Display, Formatter, Result as FResult};
use std::ops::{Deref, DerefMut, RangeInclusive};
#[cfg(feature = "display_eflint")]
use console::Style;
use enum_debug::EnumDebug;
use serde::de::{Deserializer, Error as _, SeqAccess, Visitor};
use serde::ser::{SerializeSeq, Serializer};
use serde::{Deserialize, Serialize};
#[cfg(feature = "display_eflint")]
use crate::display_eflint::{style, DisplayEFlint, Indent};
/***** TESTS *****/
#[cfg(test)]
mod tests {
use error_trace::ErrorTrace as _;
use super::*;
#[test]
fn test_ping_request() {
// Create a ping request
let req: Request = Request::Ping(RequestPing { common: RequestCommon { version: auxillary::Version::v1_0_0(), extensions: HashMap::new() } });
// Check serialization
let sreq: String = match serde_json::to_string_pretty(&req) {
Ok(text) => text,
Err(err) => panic!("Failed to serialize Ping-request: {}", err.trace()),
};
assert_eq!(
sreq,
r#"{
"kind": "ping",
"version": "1.0.0"
}"#
);
// Check de-serializing it
let req: Request = match serde_json::from_str(&sreq) {
Ok(text) => text,
Err(err) => panic!("Failed to deserialize Ping-request: {}", err.trace()),
};
assert!(req.is_ping());
assert_eq!(req.ping().common.version, auxillary::Version::v1_0_0());
assert_eq!(req.ping().common.extensions, HashMap::new());
}
#[test]
fn test_ping_response() {
// Create a ping request
let res: ResponsePing = ResponsePing { common: ResponseCommon { success: true, errors: vec![] } };
// Check serialization
let sres: String = match serde_json::to_string_pretty(&res) {
Ok(text) => text,
Err(err) => panic!("Failed to serialize Ping-response: {}", err.trace()),
};
assert_eq!(
sres,
r#"{
"success": true
}"#
);
// Check de-serializing it
let res: ResponsePing = match serde_json::from_str(&sres) {
Ok(text) => text,
Err(err) => panic!("Failed to deserialize Ping-response: {}", err.trace()),
};
assert_eq!(res.common.success, true);
assert!(res.common.errors.is_empty());
}
#[test]
fn test_handshake_request() {
// Create a ping request
let req: Request =
Request::Handshake(RequestHandshake { common: RequestCommon { version: auxillary::Version::v1_0_0(), extensions: HashMap::new() } });
// Check serialization
let sreq: String = match serde_json::to_string_pretty(&req) {
Ok(text) => text,
Err(err) => panic!("Failed to serialize Handshake-request: {}", err.trace()),
};
assert_eq!(
sreq,
r#"{
"kind": "handshake",
"version": "1.0.0"
}"#
);
// Check de-serializing it
let req: Request = match serde_json::from_str(&sreq) {
Ok(text) => text,
Err(err) => panic!("Failed to deserialize Handshake-request: {}", err.trace()),
};
assert!(req.is_handshake());
assert_eq!(req.handshake().common.version, auxillary::Version::v1_0_0());
assert_eq!(req.handshake().common.extensions, HashMap::new());
}
#[test]
fn test_handshake_response() {
// Create a ping request
let res: ResponseHandshake = ResponseHandshake {
common: ResponseCommon { success: true, errors: vec![] },
supported_versions: vec![auxillary::Version::v0_1_0(), auxillary::Version::v1_0_0()],
supported_extensions: None,
reasoner: None,
reasoner_version: None,
shares_updates: None,
shares_triggers: None,
shares_violations: None,
};
// Check serialization
let sres: String = match serde_json::to_string_pretty(&res) {
Ok(text) => text,
Err(err) => panic!("Failed to serialize Handshake-response: {}", err.trace()),
};
assert_eq!(
sres,
r#"{
"success": true,
"supported_versions": [
"0.1.0",
"1.0.0"
]
}"#
);
// Check de-serializing it
let res: ResponseHandshake = match serde_json::from_str(&sres) {
Ok(text) => text,
Err(err) => panic!("Failed to deserialize Handshake-response: {}", err.trace()),
};
assert_eq!(res.common.success, true);
assert!(res.common.errors.is_empty());
assert_eq!(res.supported_versions, vec![auxillary::Version::v0_1_0(), auxillary::Version::v1_0_0()]);
assert_eq!(res.supported_extensions, None);
assert_eq!(res.reasoner, None);
assert_eq!(res.reasoner_version, None);
assert_eq!(res.shares_updates, None);
assert_eq!(res.shares_triggers, None);
assert_eq!(res.shares_violations, None);
}
#[test]
fn test_handshake_response_spec() {
// Create a ping request
let res: ResponseHandshake = ResponseHandshake {
common: ResponseCommon { success: true, errors: vec![] },
supported_versions: vec![auxillary::Version::v2_0_0(), auxillary::Version::v1_0_0()],
supported_extensions: Some(HashMap::from([
(
auxillary::Version::v2_0_0(),
HashMap::from([
("instances".into(), vec![auxillary::Version(1, 0, 0)]),
("sequential".into(), vec![auxillary::Version(1, 0, 0)]),
]),
),
(auxillary::Version::v1_0_0(), HashMap::from([("sequential".into(), vec![auxillary::Version(1, 0, 0)])])),
])),
reasoner: Some(appendix::Reasoner::EFLINT.into()),
reasoner_version: None,
shares_updates: Some(true),
shares_triggers: Some(true),
shares_violations: Some(false),
};
// Check serialization
let sres: String = match serde_json::to_string_pretty(&res) {
Ok(text) => text,
Err(err) => panic!("Failed to serialize Handshake-response: {}", err.trace()),
};
let opt1 = r#"{
"success": true,
"supported_versions": [
"2.0.0",
"1.0.0"
],
"supported_extensions": {
"2.0.0": {
"instances": [
"1.0.0"
],
"sequential": [
"1.0.0"
]
},
"1.0.0": {
"sequential": [
"1.0.0"
]
}
},
"reasoner": "eflint",
"shares_updates": true,
"shares_triggers": true,
"shares_violations": false
}"#;
let opt2 = r#"{
"success": true,
"supported_versions": [
"2.0.0",
"1.0.0"
],
"supported_extensions": {
"1.0.0": {
"sequential": [
"1.0.0"
]
},
"2.0.0": {
"instances": [
"1.0.0"
],
"sequential": [
"1.0.0"
]
}
},
"reasoner": "eflint",
"shares_updates": true,
"shares_triggers": true,
"shares_violations": false
}"#;
if sres != opt1 && sres != opt2 {
panic!("Serialized ResponseHandshake is incorrect:\n\nGot:\n{sres}\n\nExpected EITHER:\n{opt1}\n\nExpected OR:\n{opt2}\n\n");
}
// Check de-serializing it
let res: ResponseHandshake = match serde_json::from_str(&sres) {
Ok(text) => text,
Err(err) => panic!("Failed to deserialize Handshake-response: {}", err.trace()),
};
assert_eq!(res.common.success, true);
assert!(res.common.errors.is_empty());
assert_eq!(res.supported_versions, vec![auxillary::Version::v2_0_0(), auxillary::Version::v1_0_0()]);
assert_eq!(
res.supported_extensions,
Some(HashMap::from([
(
auxillary::Version::v2_0_0(),
HashMap::from([
("instances".into(), vec![auxillary::Version(1, 0, 0)]),
("sequential".into(), vec![auxillary::Version(1, 0, 0)])
])
),
(auxillary::Version::v1_0_0(), HashMap::from([("sequential".into(), vec![auxillary::Version(1, 0, 0)])])),
]))
);
assert_eq!(res.reasoner, Some(appendix::Reasoner::EFLINT.into()));
assert_eq!(res.reasoner_version, None);
assert_eq!(res.shares_updates, Some(true));
assert_eq!(res.shares_triggers, Some(true));
assert_eq!(res.shares_violations, Some(false));
}
#[test]
fn test_inspect_request() {
// Create a ping request
let req: Request = Request::Inspect(RequestInspect {
common: RequestCommon { version: auxillary::Version::v2_0_0(), extensions: HashMap::new() },
targets: vec![],
});
// Check serialization
let sreq: String = match serde_json::to_string_pretty(&req) {
Ok(text) => text,
Err(err) => panic!("Failed to serialize Inspect-request: {}", err.trace()),
};
assert_eq!(
sreq,
r#"{
"kind": "inspect",
"version": "2.0.0"
}"#
);
// Check de-serializing it
let req: Request = match serde_json::from_str(&sreq) {
Ok(text) => text,
Err(err) => panic!("Failed to deserialize Inspect-request: {}", err.trace()),
};
assert!(req.is_inspect());
assert_eq!(req.inspect().common.version, auxillary::Version::v2_0_0());
assert_eq!(req.inspect().common.extensions, HashMap::new());
assert_eq!(req.inspect().targets, Vec::<String>::new());
}
#[test]
fn test_inspect_response() {
// Create a ping request
let res: ResponseInspect = ResponseInspect { common: ResponseCommon { success: true, errors: vec![] }, phrases: vec![] };
// Check serialization
let sres: String = match serde_json::to_string_pretty(&res) {
Ok(text) => text,
Err(err) => panic!("Failed to serialize Inspect-response: {}", err.trace()),
};
assert_eq!(
sres,
r#"{
"success": true,
"phrases": []
}"#
);
// Check de-serializing it
let res: ResponseInspect = match serde_json::from_str(&sres) {
Ok(text) => text,
Err(err) => panic!("Failed to deserialize Inspect-response: {}", err.trace()),
};
assert_eq!(res.common.success, true);
assert!(res.common.errors.is_empty());
assert!(res.phrases.is_empty());
}
}
/***** RUST ERRORS *****/
/// Defines Rust errors, which are not part of the spec but generated by it.
pub mod errors {
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FResult};
/// Defines errors occuring when parsing [`Version`](super::auxillary::Version)s from strings.
#[derive(Debug)]
pub enum VersionParseError {
/// Failed to find the first dot in the version.
FirstDot { raw: String },
/// Failed to find the second dot in the version.
SecondDot { raw: String },
/// Failed to parse the major version number as a number.
ParseMajor { raw: String, num: String, err: std::num::ParseIntError },
/// Failed to parse the minor version number as a number.
ParseMinor { raw: String, num: String, err: std::num::ParseIntError },
/// Failed to parse the patch version number as a number.
ParsePatch { raw: String, num: String, err: std::num::ParseIntError },
}
impl Display for VersionParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
use VersionParseError::*;
match self {
FirstDot { raw } => write!(f, "Failed to find first version dot in '{raw}' (separating major- and minor version numbers)"),
SecondDot { raw } => write!(f, "Failed to find second version dot in '{raw}' (separating minor- and patch version numbers)"),
ParseMajor { raw, num, .. } => write!(f, "Failed to parse major version number '{num}' in '{raw}' as an integer"),
ParseMinor { raw, num, .. } => write!(f, "Failed to parse minor version number '{num}' in '{raw}' as an integer"),
ParsePatch { raw, num, .. } => write!(f, "Failed to parse patch version number '{num}' in '{raw}' as an integer"),
}
}
}
impl Error for VersionParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
use VersionParseError::*;
match self {
FirstDot { .. } | SecondDot { .. } => None,
ParseMajor { err, .. } | ParseMinor { err, .. } | ParsePatch { err, .. } => Some(err),
}
}
}
/// Defines errors occuring when parsing [`AtomicType`](super::auxillary::AtomicType)s from strings.
#[derive(Debug)]
pub enum AtomicTypeParseError {
/// An illegal type string was given.
Unknown { raw: String },
}
impl Display for AtomicTypeParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
use AtomicTypeParseError::*;
match self {
Unknown { raw } => write!(f, "Unknown atomic type '{raw}' (expected 'String' or 'Int')"),
}
}
}
impl Error for AtomicTypeParseError {}
/// Defines errors occurring when parsing [`NonEmptyVec`](super::auxillary::NonEmptyVec)s from strings.
#[derive(Debug)]
pub enum NonEmptyVecParseError<E> {
/// Failed to deserialize the vector itself
Vec { err: E },
/// The vector was empty
Empty,
}
impl<E: Display> Display for NonEmptyVecParseError<E> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
use NonEmptyVecParseError::*;
match self {
Vec { .. } => write!(f, "Failed to deserialize vector"),
Empty => write!(f, "Vector is empty"),
}
}
}
impl<E: 'static + Error> Error for NonEmptyVecParseError<E> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
use NonEmptyVecParseError::*;
match self {
Vec { err } => Some(err),
Empty => None,
}
}
}
/// Defines errors occuring when parsing [`ExpressionVarRef`](super::ExpressionVarRef)s from strings.
#[derive(Debug)]
pub enum ExpressionVarRefParseError {
/// Got an empty array
TooFew,
/// Got too many elements in the array
TooMany,
}
impl Display for ExpressionVarRefParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
use ExpressionVarRefParseError::*;
match self {
TooFew => write!(f, "Got less than 1 element for variable reference list"),
TooMany => write!(f, "Got more than 1 element for variable reference list"),
}
}
}
impl Error for ExpressionVarRefParseError {}
/// Defines errors occuring when parsing [`TriggerKind`](super::auxillary::TriggerKind)s from strings.
#[derive(Debug)]
pub enum TriggerKindParseError {
/// An illegal kind string was given.
Unknown { raw: String },
}
impl Display for TriggerKindParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
use TriggerKindParseError::*;
match self {
Unknown { raw } => write!(f, "Unknown trigger kind '{raw}' (expected 'act' or 'event')"),
}
}
}
impl Error for TriggerKindParseError {}
/// Defines errors occuring when parsing [`ViolationKind`](super::auxillary::ViolationKind)s from strings.
#[derive(Debug)]
pub enum ViolationKindParseError {
/// An illegal kind string was given.
Unknown { raw: String },
}
impl Display for ViolationKindParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
use ViolationKindParseError::*;
match self {
Unknown { raw } => write!(f, "Unknown violation kind '{raw}' (expected 'act', 'duty' or 'invariant')"),
}
}
}
impl Error for ViolationKindParseError {}
}
/***** AUXILLARY *****/
/// Defines practical structs that are extremely convenient and spec-compliant, but not necessary mentioned in it.
pub mod auxillary {
use std::cmp::Ordering;
use std::fmt::{Display, Formatter, Result as FResult};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use enum_debug::EnumDebug;
use serde::de::{Deserializer, Visitor};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use super::errors::{AtomicTypeParseError, NonEmptyVecParseError, TriggerKindParseError, VersionParseError, ViolationKindParseError};
#[cfg(feature = "display_eflint")]
use crate::display_eflint::DisplayEFlint;
/// Visitor for any type that uses its [`FromStr`]-implementation.
///
/// # Generics
/// - `T`: The type for which we can use this visitor.
struct FromStrVisitor<'s, T> {
/// The thing to print in [`Visitor::expecting()`].
what: &'s str,
/// Allows us to capture `T`
_ty: PhantomData<T>,
}
impl<'s, T> FromStrVisitor<'s, T> {
/// Constructor for the FromStrVisitor.
///
/// # Arguments
/// - `what`: What we're [expecting](Visitor::expecting()). Should complete: "This visitor expects to receive ...".
///
/// # Returns
/// A new instance of Self that can visit for the given type.
#[inline]
fn new(what: &'s str) -> Self { Self { what, _ty: PhantomData::default() } }
}
impl<'s, 'de, T: FromStr> Visitor<'de> for FromStrVisitor<'s, T>
where
T::Err: Display,
{
type Value = T;
#[inline]
fn expecting(&self, f: &mut Formatter<'_>) -> FResult { write!(f, "{}", self.what) }
#[inline]
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match T::from_str(v) {
Ok(res) => Ok(res),
Err(err) => Err(E::custom(err)),
}
}
}
/// Toplevel enum that parses \*any\* eFLINT JSON request or response.
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(untagged)]
pub enum Message {
// Requests
/// It's a [request](super::Request) of some kind.
Request(super::Request),
// Responses
/// It's a [handshake response](super::ResponseHandshake).
ResponseHandshake(super::ResponseHandshake),
/// It's a [phrases response](super::ResponsePhrases).
ResponsePhrases(super::ResponsePhrases),
/// It's a [inspect response](super::ResponseInspect).
ResponseInspect(super::ResponseInspect),
// NOTE: Important ordering, ping only has common fields so needs to be last to avoid it always being parsed.
/// It's a [ping response](super::ResponsePing).
ResponsePing(super::ResponsePing),
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for Message {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
match self {
Self::Request(request) => request.eflint_fmt(indent, f),
Self::ResponseHandshake(handshake) => handshake.eflint_fmt(indent, f),
Self::ResponsePhrases(phrases) => phrases.eflint_fmt(indent, f),
Self::ResponseInspect(inspect) => inspect.eflint_fmt(indent, f),
Self::ResponsePing(ping) => ping.eflint_fmt(indent, f),
}
}
}
/// Represents a specification-compliant version number.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Version(pub u32, pub u32, pub u32);
impl Version {
/// Constructor for version 0.1.0 of the specification.
///
/// # Returns
/// A new [`Version`] that represents release 0.1.0.
#[inline]
pub const fn v0_1_0() -> Self { Self(0, 1, 0) }
/// Constructor for version 1.0.0 of the specification.
///
/// # Returns
/// A new [`Version`] that represents release 1.0.0.
#[inline]
pub const fn v1_0_0() -> Self { Self(1, 0, 0) }
/// Constructor for version 2.0.0 of the specification.
///
/// # Returns
/// A new [`Version`] that represents release 2.0.0.
#[inline]
pub const fn v2_0_0() -> Self { Self(2, 0, 0) }
/// Returns the major version number in this Version.
///
/// # Returns
/// An [`u32`] representing the major version number.
#[inline]
pub fn major(&self) -> u32 { self.0 }
/// Returns the minor version number in this Version.
///
/// # Returns
/// An [`u32`] representing the minor version number.
#[inline]
pub fn minor(&self) -> u32 { self.1 }
/// Returns the patch version number in this Version.
///
/// # Returns
/// An [`u32`] representing the patch version number.
#[inline]
pub fn patch(&self) -> u32 { self.2 }
}
impl Ord for Version {
#[inline]
fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0).then_with(|| self.1.cmp(&other.1).then_with(|| self.2.cmp(&other.2))) }
}
impl PartialOrd for Version {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl<'de> Deserialize<'de> for Version {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
/// Visitor for the [`Version`].
struct VersionVisitor;
impl<'de> Visitor<'de> for VersionVisitor {
type Value = Version;
#[inline]
fn expecting(&self, f: &mut Formatter) -> FResult { write!(f, "a semantic version number") }
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
match Version::from_str(v) {
Ok(version) => Ok(version),
Err(err) => Err(E::custom(err)),
}
}
}
// Visit the string
deserializer.deserialize_str(VersionVisitor)
}
}
impl Serialize for Version {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Simply serialize as a tuple with dots
serializer.serialize_str(&format!("{}.{}.{}", self.0, self.1, self.2))
}
}
impl Display for Version {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> FResult { write!(f, "{}.{}.{}", self.0, self.1, self.2) }
}
impl FromStr for Version {
type Err = VersionParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Attempt to split into a major, minor and patch version.
let (major, minor_patch): (&str, &str) = match s.find('.') {
Some(pos) => (&s[..pos], &s[pos + 1..]),
None => return Err(VersionParseError::FirstDot { raw: s.into() }),
};
let (minor, patch): (&str, &str) = match minor_patch.find('.') {
Some(pos) => (&minor_patch[..pos], &minor_patch[pos + 1..]),
None => return Err(VersionParseError::SecondDot { raw: s.into() }),
};
// Parse the numbers individually
let major: u32 = match u32::from_str(major) {
Ok(major) => major,
Err(err) => return Err(VersionParseError::ParseMajor { raw: s.into(), num: major.into(), err }),
};
let minor: u32 = match u32::from_str(minor) {
Ok(minor) => minor,
Err(err) => return Err(VersionParseError::ParseMinor { raw: s.into(), num: minor.into(), err }),
};
let patch: u32 = match u32::from_str(patch) {
Ok(patch) => patch,
Err(err) => return Err(VersionParseError::ParsePatch { raw: s.into(), num: patch.into(), err }),
};
// Alright, done!
Ok(Self(major, minor, patch))
}
}
/// Groups particular [`Phrase`](super::Phrase)s together into phrase subclasses.
#[derive(Clone, Copy, Debug, EnumDebug, Eq, Hash, PartialEq)]
pub enum PhraseSubclass {
/// Boolean- or instance queries.
Query,
/// Postulation, triggers.
Statement,
/// Definitions of Facts, Events, Acts, etc.
Definition,
}
/// The possible types that are considered as open-ended domains for [atomic facts](super::PhraseAtomicFact).
#[derive(Clone, Copy, Debug, EnumDebug, Eq, Hash, PartialEq)]
pub enum AtomicType {
/// Open-ended string domain
String,
/// Open-ended integer domain
Integer,
}
impl AtomicType {
/// Creates a new [`AtomicType::String`] (but in such a way we can use it as a serde default).
///
/// # Returns
/// A new instance of self that is String.
#[inline]
pub fn string() -> Self { Self::String }
/// Creates a new [`AtomicType::Integer`] (but in such a way we can use it as a serde default).
///
/// # Returns
/// A new instance of self that is Integer.
#[inline]
pub fn integer() -> Self { Self::Integer }
}
impl Display for AtomicType {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
match self {
Self::String => write!(f, "String"),
Self::Integer => write!(f, "Integer"),
}
}
}
impl FromStr for AtomicType {
type Err = AtomicTypeParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"String" => Ok(Self::String),
"Int" => Ok(Self::Integer),
raw => Err(AtomicTypeParseError::Unknown { raw: raw.into() }),
}
}
}
impl<'de> Deserialize<'de> for AtomicType {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Simply deserialize using its FromStr
deserializer.deserialize_str(FromStrVisitor::new("an atomic type identifier"))
}
}
impl Serialize for AtomicType {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
AtomicType::String => serializer.serialize_str("String"),
AtomicType::Integer => serializer.serialize_str("Int"),
}
}
}
/// A newtype for a vector that deserializes non-empty only.
#[derive(Clone, Debug)]
pub struct NonEmptyVec<T>(pub Vec<T>);
impl<T> Deref for NonEmptyVec<T> {
type Target = Vec<T>;
#[inline]
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<T> DerefMut for NonEmptyVec<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for NonEmptyVec<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize the vector first
let data: Vec<T> = match Vec::deserialize(deserializer) {
Ok(data) => data,
Err(err) => return Err(<D::Error as serde::de::Error>::custom(NonEmptyVecParseError::Vec { err })),
};
// Assert it isn't empty
if !data.is_empty() { Ok(Self(data)) } else { Err(<D::Error as serde::de::Error>::custom(NonEmptyVecParseError::<D::Error>::Empty)) }
}
}
impl<T: Serialize> Serialize for NonEmptyVec<T> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}
/// Defines the possible types that can be extended.
#[derive(Clone, Copy, Debug, EnumDebug, Eq, Hash, PartialEq)]
pub enum ExtendKind {
/// An eFLINT Fact is being extended.
Fact,
/// An eFLINT Event is being extended.
Event,
/// An eFLINT Act is being extended.
Act,
/// An eFLINT Duty is being extended.
Duty,
}
/// The type of [`Expression`](super::Expression)s, which is either a boolean expression or an instance expression.
///
/// Note that strings and integers are seen as instances.
#[derive(Clone, Copy, Debug, EnumDebug, Eq, Hash, PartialEq)]
pub enum ExpressionKind {
/// Boolean expressions evaluate to true or false.
Boolean,
/// Instance expressions evaluate to zero or more instances of a particular type.
Instance,
}
/// Determines what types may be triggered.
#[derive(Clone, Copy, Debug, EnumDebug, Eq, Hash, PartialEq)]
pub enum TriggerKind {
/// An eFLINT Act was triggered.
Act,
/// An eFLINT Event was triggered.
Event,
}
impl Display for TriggerKind {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
match self {
Self::Act => write!(f, "Act"),
Self::Event => write!(f, "Event"),
}
}
}
impl FromStr for TriggerKind {
type Err = TriggerKindParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"act" => Ok(Self::Act),
"event" => Ok(Self::Event),
raw => Err(TriggerKindParseError::Unknown { raw: raw.into() }),
}
}
}
impl<'de> Deserialize<'de> for TriggerKind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Visit using the visitor
deserializer.deserialize_str(FromStrVisitor::new("a trigger kind identifier"))
}
}
impl Serialize for TriggerKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
TriggerKind::Act => serializer.serialize_str("act"),
TriggerKind::Event => serializer.serialize_str("event"),
}
}
}
/// Determines what types may be violated.
#[derive(Clone, Copy, Debug, EnumDebug, Eq, Hash, PartialEq)]
pub enum ViolationKind {
/// An eFLINT Act was violated.
Act,
/// An eFLINT Duty was violated.
Duty,
/// An eFLINT Invariant was violated.
Invariant,
}
impl Display for ViolationKind {
fn fmt(&self, f: &mut Formatter<'_>) -> FResult {
match self {
Self::Act => write!(f, "Act"),
Self::Duty => write!(f, "Duty"),
Self::Invariant => write!(f, "Invariant"),
}
}
}
impl FromStr for ViolationKind {
type Err = ViolationKindParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"act" => Ok(Self::Act),
"duty" => Ok(Self::Duty),
"invariant" => Ok(Self::Invariant),
raw => Err(ViolationKindParseError::Unknown { raw: raw.into() }),
}
}
}
impl<'de> Deserialize<'de> for ViolationKind {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Visit using the visitor
deserializer.deserialize_str(FromStrVisitor::new("a violation kind identifier"))
}
}
impl Serialize for ViolationKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
ViolationKind::Act => serializer.serialize_str("act"),
ViolationKind::Duty => serializer.serialize_str("duty"),
ViolationKind::Invariant => serializer.serialize_str("invariant"),
}
}
}
}
/***** DEFAULT FUNCTIONS *****/
/// Defines the default for the `actor`-field in [`PhraseAct`].
///
/// # Returns
/// A new String that encodes `"author"`.
#[inline]
fn default_phrase_act_actor() -> String { "author".into() }
/***** TOPLEVEL INTERACTION *****/
/// The toplevel request of the JSON specification.
///
/// This comes in three variants:
/// - [`Request::Ping`] to establish if a server is online.
/// - [`Request::Handshake`] to retrieve server metadata, such as supported versions, reasoner used, etc.
/// - [`Request::Phrases`] to send eFLINT phrases to the server and do reasoning.
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(tag = "kind")]
pub enum Request {
/// The Ping-request can be used to establish if a server is online and reachable.
#[serde(rename = "ping")]
Ping(RequestPing),
/// The Handshake-request can be used to retrieve server metadata, such as supported versions, reasoner used, etc.
#[serde(rename = "handshake")]
Handshake(RequestHandshake),
/// The Phrases-request can be used to do reasoning on the server by sending phrases.
#[serde(rename = "phrases")]
Phrases(RequestPhrases),
/// The Inspect-request can be used to query the server's state.
#[serde(rename = "inspect")]
Inspect(RequestInspect),
}
impl Request {
/// Checks if this request is a [`Request::Ping`].
///
/// # Returns
/// True if it is, or false if not.
#[inline]
pub fn is_ping(&self) -> bool { matches!(self, Self::Ping(_)) }
/// Returns this Request as if it's a [`Request::Ping`].
///
/// # Returns
/// A reference to the internal [`RequestPing`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Ping`].
#[inline]
#[track_caller]
pub fn ping(&self) -> &RequestPing {
if let Request::Ping(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Ping", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Ping`].
///
/// # Returns
/// A mutable reference to the internal [`RequestPing`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Ping`].
#[inline]
#[track_caller]
pub fn ping_mut(&mut self) -> &mut RequestPing {
if let Request::Ping(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Ping", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Ping`].
///
/// # Returns
/// The internal [`RequestPing`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Ping`].
#[inline]
#[track_caller]
pub fn into_ping(self) -> RequestPing {
if let Request::Ping(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Ping", self.variant());
}
}
/// Checks if this request is a [`Request::Handshake`].
///
/// # Returns
/// True if it is, or false if not.
#[inline]
pub fn is_handshake(&self) -> bool { matches!(self, Self::Handshake(_)) }
/// Returns this Request as if it's a [`Request::Handshake`].
///
/// # Returns
/// A reference to the internal [`RequestHandshake`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Handshake`].
#[inline]
#[track_caller]
pub fn handshake(&self) -> &RequestHandshake {
if let Request::Handshake(h) = self {
h
} else {
panic!("Cannot unwrap a {:?} as a Request::Handshake", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Handshake`].
///
/// # Returns
/// A mutable reference to the internal [`RequestHandshake`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Handshake`].
#[inline]
#[track_caller]
pub fn handshake_mut(&mut self) -> &mut RequestHandshake {
if let Request::Handshake(h) = self {
h
} else {
panic!("Cannot unwrap a {:?} as a Request::Handshake", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Handshake`].
///
/// # Returns
/// The internal [`RequestHandshake`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Handshake`].
#[inline]
#[track_caller]
pub fn into_handshake(self) -> RequestHandshake {
if let Request::Handshake(h) = self {
h
} else {
panic!("Cannot unwrap a {:?} as a Request::Handshake", self.variant());
}
}
/// Checks if this request is a [`Request::Phrases`].
///
/// # Returns
/// True if it is, or false if not.
#[inline]
pub fn is_phrases(&self) -> bool { matches!(self, Self::Phrases(_)) }
/// Returns this Request as if it's a [`Request::Phrases`].
///
/// # Returns
/// A reference to the internal [`RequestPhrases`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Phrases`].
#[inline]
#[track_caller]
pub fn phrases(&self) -> &RequestPhrases {
if let Request::Phrases(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Phrases", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Phrases`].
///
/// # Returns
/// A mutable reference to the internal [`RequestPhrases`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Phrases`].
#[inline]
#[track_caller]
pub fn phrases_mut(&mut self) -> &mut RequestPhrases {
if let Request::Phrases(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Phrases", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Phrases`].
///
/// # Returns
/// The internal [`RequestPhrases`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Phrases`].
#[inline]
#[track_caller]
pub fn into_phrases(self) -> RequestPhrases {
if let Request::Phrases(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Phrases", self.variant());
}
}
/// Checks if this request is a [`Request::Inspect`].
///
/// # Returns
/// True if it is, or false if not.
#[inline]
pub fn is_inspect(&self) -> bool { matches!(self, Self::Inspect(_)) }
/// Returns this Request as if it's a [`Request::Inspect`].
///
/// # Returns
/// A reference to the internal [`RequestInspect`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Inspect`].
#[inline]
#[track_caller]
pub fn inspect(&self) -> &RequestInspect {
if let Request::Inspect(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Inspect", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Inspect`].
///
/// # Returns
/// A mutable reference to the internal [`RequestInspect`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Inspect`].
#[inline]
#[track_caller]
pub fn inspect_mut(&mut self) -> &mut RequestInspect {
if let Request::Inspect(p) = self {
p
} else {
panic!("Cannot unwrap a {:?} as a Request::Inspect", self.variant());
}
}
/// Returns this Request as if it's a [`Request::Inspect`].
///
/// # Returns
/// The internal [`RequestInspect`] object.
///
/// # Panics
/// This function may panic if this Request is _not_ a [`Request::Inspect`].
#[inline]
#[track_caller]
pub fn into_inspect(self) -> RequestInspect {
if let Request::Inspect(i) = self {
i
} else {
panic!("Cannot unwrap a {:?} as a Request::Inspect", self.variant());
}
}
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for Request {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
// Write the contents of the request
match self {
Self::Ping(ping) => ping.eflint_fmt(indent, f),
Self::Handshake(handshake) => handshake.eflint_fmt(indent, f),
Self::Phrases(phrases) => phrases.eflint_fmt(indent, f),
Self::Inspect(inspect) => inspect.eflint_fmt(indent, f),
}
}
}
/// Determines the common fields for all requests.
///
/// Note that this does not include the `kind`-field, as that's part of the parent [`Request`].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RequestCommon {
/// The version of the specification to use for this interaction.
pub version: auxillary::Version,
/// An optional map of extensions to the version.
#[serde(default = "HashMap::new", skip_serializing_if = "HashMap::is_empty")]
pub extensions: HashMap<String, Option<auxillary::Version>>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for RequestCommon {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `indent`: The indentation to print each line with.
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
// Write the version as an attribute
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::ATTRIBUTE.apply_to(format!("#[version = {}]", self.version)))?;
} else {
writeln!(f, "{}#[version = {}]", Indent(indent), self.version)?;
}
// Write the extensions as attributes
for (ext, ver) in &self.extensions {
let ver: String = if let Some(ver) = ver { format!("{ver}") } else { "latest".into() };
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::ATTRIBUTE.apply_to(format!("#[extension({ext}, {ver})]")))?;
} else {
writeln!(f, "{}#[extension({}, {})]", Indent(indent), ext, ver)?;
}
}
// Done
Ok(())
}
}
/// Represents a Ping-request.
///
/// The Ping-request can be used to establish if a server is online and reachable.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RequestPing {
/// The common schema of all requests
#[serde(flatten)]
pub common: RequestCommon,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for RequestPing {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common } = self;
// Write header
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Request<Handshake> {"))?;
} else {
writeln!(f, "{}Request<Handshake> {{", Indent(indent))?;
}
// Write only the common part
common.eflint_fmt(indent + 4, f)?;
// Write the footer
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done
Ok(())
}
}
/// Represents a Handshake-request.
///
/// The Handshake-request can be used to retrieve server metadata, such as supported versions, reasoner used, etc.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RequestHandshake {
/// The common schema of all requests
#[serde(flatten)]
pub common: RequestCommon,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for RequestHandshake {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common } = self;
// Write header
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Request<Handshake> {"))?;
} else {
writeln!(f, "{}Request<Handshake> {{", Indent(indent))?;
}
// Write the common part only
common.eflint_fmt(indent + 4, f)?;
// Write the footer
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done
Ok(())
}
}
/// Represents a Phrases-request.
///
/// The Phrases-request can be used to perform reasoning on the server.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RequestPhrases {
/// The common schema of all requests
#[serde(flatten)]
pub common: RequestCommon,
/// A list of phrases to send to the server.
pub phrases: Vec<Phrase>,
/// Whether to ask for updates or not.
#[serde(default = "bool::default")]
pub updates: bool,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for RequestPhrases {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, phrases, updates } = self;
// Write header
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Request<Phrases> {"))?;
} else {
writeln!(f, "{}Request<Phrases> {{", Indent(indent))?;
}
// Write the common part first
common.eflint_fmt(indent + 4, f)?;
// Add an attribute for the updates
if f.alternate() {
writeln!(f, "{}{}", Indent(indent + 4), style::ATTRIBUTE.apply_to(format!("#[updates = {updates}]")))?;
} else {
writeln!(f, "{}#[updates = {}]", Indent(indent + 4), updates)?;
}
writeln!(f)?;
// Write the phrases
for phrase in phrases {
phrase.eflint_fmt(indent + 4, f)?;
}
// Write the footer
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done!
Ok(())
}
}
/// Represents an Inspect-request.
///
/// The Inspect-request can be used to get information about the reasoner state.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RequestInspect {
/// The common schema of all requests
#[serde(flatten)]
pub common: RequestCommon,
/// A list of targets that can be used to scope the inspect request.
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub targets: Vec<String>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for RequestInspect {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, targets } = self;
// Write header
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Request<Inspect> {"))?;
} else {
writeln!(f, "{}Request<Inspect> {{", Indent(indent))?;
}
// Write the common part
common.eflint_fmt(indent + 4, f)?;
writeln!(f)?;
// Write the things we're asking information for as a comma-separated list
for target in targets {
if f.alternate() {
writeln!(f, "{}{}{}", Indent(indent + 4), target, style::PUNCTUATION.apply_to(","))?;
} else {
writeln!(f, "{}{},", Indent(indent + 4), target)?;
}
}
// Write the footer
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done!
Ok(())
}
}
/// Determines the common fields for all responses.
///
/// Note that this does not include the `kind`-field, as that's part of the parent [`Request`].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ResponseCommon {
/// Whether the response was received and parsed successfully. Basically, represents whether the request was "syntactically valid" according to the specification.
pub success: bool,
/// An optional list of errors that occurred when `success` is false.
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<Error>,
}
#[cfg(feature = "display_eflint")]
impl ResponseCommon {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `indent`: The indentation to print each line with.
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { success, errors } = self;
// Write the success as a key/value pair
if f.alternate() {
writeln!(
f,
"{}success {} {}",
Indent(indent),
style::PUNCTUATION.apply_to(":"),
if *success { style::SUCCESS.apply_to("true") } else { style::FAILURE.apply_to("false") }
)?;
} else {
writeln!(f, "{}success : {}", Indent(indent), success)?;
}
// Write the errors if there are any
if !errors.is_empty() {
if f.alternate() {
writeln!(f, "{}errors {} {}", Indent(indent), style::PUNCTUATION.apply_to(":"), style::PUNCTUATION.apply_to("["))?;
} else {
writeln!(f, "{}errors : [", Indent(indent))?;
}
for err in &self.errors {
err.eflint_fmt(indent + 4, f)?;
}
writeln!(f, "{}{}", Indent(indent), style::PUNCTUATION.apply_to("]"))?;
}
// Done
Ok(())
}
}
/// Represents the reply to a [Ping-request](RequestPing).
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ResponsePing {
// The common schema of all responses
#[serde(flatten)]
pub common: ResponseCommon,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for ResponsePing {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common } = self;
// Just write the common one
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Response<Ping> {"))?;
} else {
writeln!(f, "{}Response<Ping> {{", Indent(indent))?;
}
common.eflint_fmt(indent + 4, f)?;
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done
Ok(())
}
}
/// Represents the reply to a [Handshake-request](RequestHandshake).
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ResponseHandshake {
// The common schema of all responses
#[serde(flatten)]
pub common: ResponseCommon,
/// A list of the supported versions by the server.
pub supported_versions: Vec<auxillary::Version>,
/// A list of the supported extensions by the server.
///
/// The extensions are mapped per supported version, and map to a list of supported versions of that extension.
#[serde(skip_serializing_if = "Option::is_none")]
pub supported_extensions: Option<HashMap<auxillary::Version, HashMap<String, Vec<auxillary::Version>>>>,
/// The reasoner backend used. See [`appendix::Reasoner`] for a list of reasoners that are known at the time of writing.
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoner: Option<String>,
/// The version of the reasoner backend used.
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoner_version: Option<auxillary::Version>,
/// Whether or not this server is, in general, inclined to give you updates for state changes of phrases.
#[serde(skip_serializing_if = "Option::is_none")]
pub shares_updates: Option<bool>,
/// Whether or not this server is, in general, inclined to give you updates on triggered Acts or Events.
#[serde(skip_serializing_if = "Option::is_none")]
pub shares_triggers: Option<bool>,
/// Whether or not this server is, in general, inclined to give you updates on violations.
#[serde(skip_serializing_if = "Option::is_none")]
pub shares_violations: Option<bool>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for ResponseHandshake {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, supported_versions, supported_extensions, reasoner, reasoner_version, shares_updates, shares_triggers, shares_violations } =
self;
// Write header
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Response<Handshake> {"))?;
} else {
writeln!(f, "{}Response<Handshake> {{", Indent(indent))?;
}
// Write the common one first
common.eflint_fmt(indent + 4, f)?;
// Produce some coloured (or not) punctuation first
let colon: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to(":")) } else { Box::new(":") };
let lbrace: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to("{")) } else { Box::new("{") };
let rbrace: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to("}")) } else { Box::new("}") };
let scomma: String = if f.alternate() { style::PUNCTUATION.apply_to(", ").to_string() } else { ", ".into() };
// Write the other fields; supported versions...
writeln!(
f,
"{}{} {} {}",
Indent(indent + 4),
"supported_versions ",
colon,
supported_versions.iter().map(|ver| format!("v{ver}")).collect::<Vec<String>>().join(&scomma)
)?;
// ...supported extensions...
if let Some(supported_extensions) = supported_extensions {
writeln!(f, "{}{} {} {}", Indent(indent + 4), "supported_extensions", colon, lbrace)?;
for (spec_ver, exts) in supported_extensions {
writeln!(f, "{}v{} {} {}", Indent(indent + 8), spec_ver, colon, lbrace)?;
for (ext, vers) in exts {
writeln!(
f,
"{}{} {} {}",
Indent(indent + 12),
ext,
colon,
vers.iter().map(|ver| format!("v{ver}")).collect::<Vec<String>>().join(&scomma)
)?;
}
writeln!(f, "{}{}", Indent(indent + 8), rbrace)?;
}
writeln!(f, "{}{}", Indent(indent + 4), rbrace)?;
}
// ...reasoner data...
if let Some(reasoner) = reasoner {
writeln!(f, "{}{} {} {}", Indent(indent + 4), "reasoner ", colon, reasoner)?;
}
if let Some(reasoner_version) = reasoner_version {
writeln!(f, "{}{} {} {}", Indent(indent + 4), "reasoner_version ", colon, reasoner_version)?;
}
// ...and update sharing
if let Some(shares_updates) = shares_updates {
writeln!(f, "{}{} {} {}", Indent(indent + 4), "shares_updates ", colon, shares_updates)?;
}
if let Some(shares_triggers) = shares_triggers {
writeln!(f, "{}{} {} {}", Indent(indent + 4), "shares_triggers ", colon, shares_triggers)?;
}
if let Some(shares_violations) = shares_violations {
writeln!(f, "{}{} {} {}", Indent(indent + 4), "shares_violations ", colon, shares_violations)?;
}
// Write footer
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done
Ok(())
}
}
/// Represents the reply to a [Phrases-request](RequestPhrases).
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ResponsePhrases {
// The common schema of all responses
#[serde(flatten)]
pub common: ResponseCommon,
/// The results returned by the server that mark effects of submitted phrases.
pub results: Vec<PhraseResult>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for ResponsePhrases {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, results } = self;
// Write header
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Response<Phrases> {"))?;
} else {
writeln!(f, "{}Response<Phrases> {{", Indent(indent))?;
}
// Write the common one first
common.eflint_fmt(indent + 4, f)?;
writeln!(f)?;
// Write the phrases
if !results.is_empty() {
for result in results {
result.eflint_fmt(indent + 4, f)?;
}
} else {
if f.alternate() {
writeln!(f, "{}{}", Indent(indent + 4), style::EMPTY_LIST.apply_to("<no effects>"))?;
} else {
writeln!(f, "{}<no effects>", Indent(indent + 4))?;
}
}
// Write footer
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done
Ok(())
}
}
/// Represents the reply to an [Inspect-request](RequestInspect).
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ResponseInspect {
// The common schema of all responses
#[serde(flatten)]
pub common: ResponseCommon,
/// The phrases the list the reasoner state, or the requested definitions.
pub phrases: Vec<Phrase>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for ResponseInspect {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, phrases } = self;
// Write header
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("Response<Inspect> {"))?;
} else {
writeln!(f, "{}Response<Inspect> {{", Indent(indent))?;
}
// Write the common one first
common.eflint_fmt(indent + 4, f)?;
writeln!(f)?;
// Write the phrases
for phrase in phrases {
phrase.eflint_fmt(indent, f)?;
}
// Write footer
if f.alternate() {
writeln!(f, "{}{}", Indent(indent), style::REQUEST_DECORATION.apply_to("}"))?;
} else {
writeln!(f, "{}}}", Indent(indent))?;
}
// Done
Ok(())
}
}
/***** "TYPES" *****/
/// Represents an error returned by the server.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Error {
/// A machine-usable identifier for the error that occurred.
pub id: String,
/// A human-readable message detailling what went wrong for them to wrap their organic minds around.
pub message: String,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for Error {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
if f.alternate() {
writeln!(f, "{}{} {}", Indent(indent), self.message, style::ERROR_ID.apply_to(format!("<{}>", self.id)))
} else {
writeln!(f, "{}{} <{}>", Indent(indent), self.message, self.id)
}
}
}
/// Represents an eFLINT statement, essentially.
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(tag = "kind")]
pub enum Phrase {
/// Defines a boolean query, e.g.,
/// ```eflint
/// ? has-voted(Bob, Amy)
/// ```
#[serde(rename = "bquery")]
BooleanQuery(PhraseBooleanQuery),
/// Defines an instance query, e.g.,
/// ```eflint
/// ?- has-voted(voter, Amy)
/// ```
#[serde(rename = "iquery")]
InstanceQuery(PhraseInstanceQuery),
/// Postulates a certain fact to be true, e.g.,
/// ```eflint
/// +citizen(Amy).
/// ```
#[serde(rename = "create")]
Create(PhraseCreate),
/// Postulates a certain fact to be false, e.g.,
/// ```eflint
/// -citizen(Amy).
/// ```
#[serde(rename = "terminate")]
Terminate(PhraseTerminate),
/// Removes the postulation for a certain fact, falling back to its derived value, e.g.,
/// ```eflint
/// ~citizen(Amy).
/// ```
#[serde(rename = "obfuscate")]
Obfuscate(PhraseObfuscate),
/// Triggers an Event or an Act, e.g.,
/// ```eflint
/// vote(Amy, Bob).
/// ```
#[serde(rename = "trigger")]
Trigger(PhraseTrigger),
/// Defines a Fact that has atomic construction, e.g.,
/// ```eflint
/// Fact citizen Identified by String.
/// ```
#[serde(rename = "afact")]
AtomicFact(PhraseAtomicFact),
/// Defines a Fact that has composite fields, e.g.,
/// ```eflint
/// Fact voter Identified by citizen.
/// ```
#[serde(rename = "cfact")]
CompositeFact(PhraseCompositeFact),
/// Defines a Placeholder to create type aliases, e.g.,
/// ```eflint
/// Placeholder civilian For citizen.
/// ```
#[serde(rename = "placeholder")]
Placeholder(PhrasePlaceholder),
/// Defines a Predicate that can be used to "prepare" queries, e.g.,:
/// ```eflint
/// Predicate vote-concluded When Not(Exists citizen : voter(citizen) && !has-voted(citizen)).
/// ```
/// This includes invariants, which are checked after every derivation procedure and can trigger violations when becoming false, e.g.,
/// ```eflint
/// Invariant at-most-one-winner When Not(Exists winner, winner' : winner != winner').
/// ```
#[serde(rename = "predicate")]
Predicate(PhrasePredicate),
/// Defines an Event that can be used to automatically postulate facts, e.g.,:
/// ```eflint
/// Event fire Obfuscates vote.
/// ```
#[serde(rename = "event")]
Event(PhraseEvent),
/// Defines an Act that can be used to automatically postulate facts while noting it was instantiated by a particular actor, e.g.:
/// ```eflint
/// Act murder
/// Actor citizen1
/// Related to citizen2
/// Terminates citizen2
/// ```
#[serde(rename = "act")]
Act(PhraseAct),
/// Defines a Duty that can be violated when certain conditions are (not) met, e.g.:
/// ```eflint
/// Duty must-vote
/// Holder citizen
/// Claimant administrator
/// Enforced by not-voted.
/// ```
#[serde(rename = "duty")]
Duty(PhraseDuty),
/// Defines an extension to an existing type, e.g.:
/// ```eflint
/// Extend Duty duty-to-vote
/// Conditioned by can-vote(voter).
/// ```
#[serde(rename = "extend")]
Extend(PhraseExtend),
}
impl Phrase {
/// Returns the phrase subclass for this phrase.
///
/// # Returns
/// A [`PhraseSubclass`](auxillary::PhraseSubclass) describing the class of this data.
#[inline]
pub fn subclass(&self) -> auxillary::PhraseSubclass {
match self {
Phrase::BooleanQuery(_) => auxillary::PhraseSubclass::Query,
Phrase::InstanceQuery(_) => auxillary::PhraseSubclass::Query,
Phrase::Create(_) => auxillary::PhraseSubclass::Statement,
Phrase::Terminate(_) => auxillary::PhraseSubclass::Statement,
Phrase::Obfuscate(_) => auxillary::PhraseSubclass::Statement,
Phrase::Trigger(_) => auxillary::PhraseSubclass::Statement,
Phrase::AtomicFact(_) => auxillary::PhraseSubclass::Definition,
Phrase::CompositeFact(_) => auxillary::PhraseSubclass::Definition,
Phrase::Placeholder(_) => auxillary::PhraseSubclass::Definition,
Phrase::Predicate(_) => auxillary::PhraseSubclass::Definition,
Phrase::Event(_) => auxillary::PhraseSubclass::Definition,
Phrase::Act(_) => auxillary::PhraseSubclass::Definition,
Phrase::Duty(_) => auxillary::PhraseSubclass::Definition,
Phrase::Extend(_) => auxillary::PhraseSubclass::Definition,
}
}
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for Phrase {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
// Match to pass
match self {
Self::BooleanQuery(bquery) => bquery.eflint_fmt(indent, f),
Self::InstanceQuery(iquery) => iquery.eflint_fmt(indent, f),
Self::Create(create) => create.eflint_fmt(indent, f),
Self::Terminate(term) => term.eflint_fmt(indent, f),
Self::Obfuscate(obfus) => obfus.eflint_fmt(indent, f),
Self::Trigger(trigger) => trigger.eflint_fmt(indent, f),
Self::AtomicFact(afact) => afact.eflint_fmt(indent, f),
Self::CompositeFact(cfact) => cfact.eflint_fmt(indent, f),
Self::Placeholder(pholder) => pholder.eflint_fmt(indent, f),
Self::Predicate(predicate) => predicate.eflint_fmt(indent, f),
Self::Event(event) => event.eflint_fmt(indent, f),
Self::Act(act) => act.eflint_fmt(indent, f),
Self::Duty(duty) => duty.eflint_fmt(indent, f),
Self::Extend(extend) => extend.eflint_fmt(indent, f),
}
}
}
/// Represents a boolean query within eFLINT, e.g.,
/// ```eflint
/// ? has-voted(Bob, Amy)
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseBooleanQuery {
/// The boolean expression to evaluate.
pub expression: Expression,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseBooleanQuery {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { expression } = self;
// Write the expression, then a finishing period (it's that simple!)
if f.alternate() {
write!(f, "{}{}", Indent(indent), style::KEYWORD.apply_to("?"))?;
} else {
write!(f, "{}?", Indent(indent))?;
}
expression.eflint_fmt(f)?;
if f.alternate() { writeln!(f, "{}", style::PUNCTUATION.apply_to(".")) } else { writeln!(f, ".") }
}
}
/// Represents an instance query within eFLINT, e.g.,
/// ```eflint
/// ?- has-voted(voter, Amy)
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseInstanceQuery {
/// The instance expression to evaluate.
pub expression: Expression,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseInstanceQuery {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { expression } = self;
// Write the expression, then a finishing period (it's that simple!)
if f.alternate() {
write!(f, "{}{}", Indent(indent), style::KEYWORD.apply_to("?-"))?;
} else {
write!(f, "{}?-", Indent(indent))?;
}
expression.eflint_fmt(f)?;
if f.alternate() { writeln!(f, "{}", style::PUNCTUATION.apply_to(".")) } else { writeln!(f, ".") }
}
}
/// Represents a true-postulation within eFLINT, e.g.,
/// ```eflint
/// +citizen(Amy).
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseCreate {
/// The expression that determines the instance to postulate to true. _Probably_ a constructor application, but not necessarily.
pub operand: Expression,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseCreate {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { operand } = self;
// Write the expression, then a finishing period (it's that simple!)
if f.alternate() {
write!(f, "{}{}", Indent(indent), style::KEYWORD.apply_to("+"))?;
} else {
write!(f, "{}+", Indent(indent))?;
}
operand.eflint_fmt(f)?;
if f.alternate() { writeln!(f, "{}", style::PUNCTUATION.apply_to(".")) } else { writeln!(f, ".") }
}
}
/// Represents a false-postulation within eFLINT, e.g.,
/// ```eflint
/// -citizen(Amy).
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseTerminate {
/// The expression that determines the instance to postulate to false. _Probably_ a constructor application, but not necessarily.
pub operand: Expression,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseTerminate {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { operand } = self;
// Write the expression, then a finishing period (it's that simple!)
if f.alternate() {
write!(f, "{}{}", Indent(indent), style::KEYWORD.apply_to("-"))?;
} else {
write!(f, "{}-", Indent(indent))?;
}
operand.eflint_fmt(f)?;
if f.alternate() { writeln!(f, "{}", style::PUNCTUATION.apply_to(".")) } else { writeln!(f, ".") }
}
}
/// Represents the removal of postulation within eFLINT, e.g.,
/// ```eflint
/// ~citizen(Amy).
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseObfuscate {
/// The expression that determines the instance to un-postulate. _Probably_ a constructor application, but not necessarily.
pub operand: Expression,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseObfuscate {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { operand } = self;
// Write the expression, then a finishing period (it's that simple!)
if f.alternate() {
write!(f, "{}{}", Indent(indent), style::KEYWORD.apply_to("~"))?;
} else {
write!(f, "{}~", Indent(indent))?;
}
operand.eflint_fmt(f)?;
if f.alternate() { writeln!(f, "{}", style::PUNCTUATION.apply_to(".")) } else { writeln!(f, ".") }
}
}
/// Represents the execution of an Event or Act, e.g.,
/// ```eflint
/// vote(Amy, Bob).
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseTrigger {
/// The expression that determines the instance to trigger. _Probably_ a constructor application, but not necessarily.
pub operand: Expression,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseTrigger {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { operand } = self;
// Write the expression, then a finishing period (it's that simple!)
write!(f, "{}", Indent(indent))?;
operand.eflint_fmt(f)?;
if f.alternate() { writeln!(f, "{}", style::PUNCTUATION.apply_to(".")) } else { writeln!(f, ".") }
}
}
/// Represents common fields for all type definition phrases.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TypeDefinitionCommon {
/// A set of instance expressions that generate automatic instances for some type.
#[serde(rename = "derived-from", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub derived_from: Vec<Expression>,
/// A set of boolean expressions that filter all possible types in the positive (syntax sugar for Derived from over a type's fields with `When <expr>`).
#[serde(rename = "holds-when", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub holds_when: Vec<Expression>,
/// A set of boolean expressions that limits what instances may be derived by `Derived from`-rules and `Holds when`-rules, i.e., something is only derived if all `Conditioned by`-rules are true.
#[serde(rename = "conditioned-by", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub conditioned_by: Vec<Expression>,
}
#[cfg(feature = "display_eflint")]
impl TypeDefinitionCommon {
/// Helper function to determine if this TypeDefinitionCommon is "empty" (i.e., all of its clauses are empty).
///
/// # Returns
/// True if all fields are empty lists, or false otherwise.
#[inline]
fn is_empty(&self) -> bool {
let Self { derived_from, holds_when, conditioned_by } = self;
derived_from.is_empty() && holds_when.is_empty() && conditioned_by.is_empty()
}
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `indent`: The indentation to print each line with.
/// - `add_dot`: Whether to add the end-of-phrase dot at the end of this definition or not.
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, indent: usize, add_dot: bool, f: &mut Formatter<'_>) -> FResult {
let Self { derived_from, holds_when, conditioned_by } = self;
// Write the three rules in succession
for (i, rule) in derived_from.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Derived from"))?;
} else {
write!(f, "{}Derived from ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == derived_from.len() - 1 && holds_when.is_empty() && conditioned_by.is_empty() {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
// Do the three creates- terminates- and obfuscates in rapid succession
for (i, rule) in holds_when.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Holds when"))?;
} else {
write!(f, "{}Holds when ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == holds_when.len() - 1 && conditioned_by.is_empty() {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
for (i, rule) in conditioned_by.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Conditioned by"))?;
} else {
write!(f, "{}Conditioned by ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == conditioned_by.len() - 1 {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
// Alright that's it
Ok(())
}
}
/// Represents common fields for all event-like definition phrases.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct EventDefinitionCommon {
/// A list of other Events and Acts that are triggered when this Event or Act triggers.
///
/// These are instance expressions generating the lists.
#[serde(rename = "syncs-with", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub syncs_with: Vec<Expression>,
/// A list of instance expressions generating all the facts that are postulated to true when this Event or Act triggers.
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub creates: Vec<Expression>,
/// A list of instance expressions generating all the facts that are postulated to false when this Event or Act triggers.
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub terminates: Vec<Expression>,
/// A list of instance expressions generating all the facts whos postulation is removed when this Event or Act triggers.
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub obfuscates: Vec<Expression>,
}
#[cfg(feature = "display_eflint")]
impl EventDefinitionCommon {
/// Helper function to determine if this EventDefinitionCommon is "empty" (i.e., all of its clauses are empty).
///
/// # Returns
/// True if all fields are empty lists, or false otherwise.
#[inline]
fn is_empty(&self) -> bool {
let Self { syncs_with, creates, terminates, obfuscates } = self;
syncs_with.is_empty() && creates.is_empty() && terminates.is_empty() && obfuscates.is_empty()
}
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `indent`: The indentation to print each line with.
/// - `add_dot`: Whether to add the end-of-phrase dot at the end of this definition or not.
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, indent: usize, add_dot: bool, f: &mut Formatter<'_>) -> FResult {
let Self { syncs_with, creates, terminates, obfuscates } = self;
// Write the Syncs with-statements appropriately
for (i, rule) in syncs_with.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Syncs with"))?;
} else {
write!(f, "{}Syncs with ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == syncs_with.len() - 1 && creates.is_empty() && terminates.is_empty() && obfuscates.is_empty() {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
// Do the three creates- terminates- and obfuscates in rapid succession
for (i, rule) in creates.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Creates"))?;
} else {
write!(f, "{}Creates ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == creates.len() - 1 && terminates.is_empty() && obfuscates.is_empty() {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
for (i, rule) in terminates.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Terminates"))?;
} else {
write!(f, "{}Terminates ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == terminates.len() - 1 && obfuscates.is_empty() {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
for (i, rule) in obfuscates.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Obfuscates"))?;
} else {
write!(f, "{}Obfuscates ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == obfuscates.len() - 1 {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
// Alright that's it
Ok(())
}
}
/// Represents common fields for all duty-like definition phrases.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DutyDefinitionCommon {
/// A list of boolean expressions that will trigger the Duty violated if any of them holds true _while_ the Duty itself holds true.
#[serde(rename = "violated-when", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub violated_when: Vec<Expression>,
/// A list of type identifiers that define a set of types that, when any of them becomes true, violates this Duty.
///
/// Note that this list is quite restrictive. Only types with the same fields (names, types and order!) are allowed.
///
/// To illustrate, `enforced-by` is syntax sugar for a particular `violated-when`:
/// ```eflint
/// Duty must-vote
/// Holder citizen
/// Claimant administrator
/// Enforced by not-voted.
/// ```
/// is the same as
/// ```eflint
/// Duty must-vote
/// Holder citizen
/// Claimant administrator
/// Violated when Enabled(not-voted(citizen, administrator)).
/// ```
#[serde(rename = "enforced-by", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub enforced_by: Vec<String>,
}
#[cfg(feature = "display_eflint")]
impl DutyDefinitionCommon {
/// Helper function to determine if this TypeDefinitionCommon is "empty" (i.e., all of its clauses are empty).
///
/// # Returns
/// True if all fields are empty lists, or false otherwise.
#[inline]
fn is_empty(&self) -> bool {
let Self { violated_when, enforced_by } = self;
violated_when.is_empty() && enforced_by.is_empty()
}
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `indent`: The indentation to print each line with.
/// - `add_dot`: Whether to add the end-of-phrase dot at the end of this definition or not.
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, indent: usize, add_dot: bool, f: &mut Formatter<'_>) -> FResult {
let Self { violated_when, enforced_by } = self;
// Write the Violated when-statements appropriately
for (i, rule) in violated_when.iter().enumerate() {
// Write the 'Violated when'-part
if f.alternate() {
write!(f, "{}{} ", Indent(indent), style::KEYWORD.apply_to("Violated when"))?;
} else {
write!(f, "{}Violated when ", Indent(indent))?;
}
// Write the expression
rule.eflint_fmt(f)?;
// Write the dot, if asked
if add_dot && i == violated_when.len() - 1 && enforced_by.is_empty() {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
write!(f, ".")?;
}
}
// Write the end-of-line
writeln!(f)?;
}
// Do the same for Enforced by
for (i, name) in enforced_by.iter().enumerate() {
if f.alternate() {
write!(f, "{}{} {}", Indent(indent), style::KEYWORD.apply_to("Enforced by"), name)?;
// Write the dot, if asked
if add_dot && i == enforced_by.len() - 1 {
write!(f, "{}", style::PUNCTUATION.apply_to("."))?;
}
} else {
write!(f, "{}Enforced by {}", Indent(indent), name)?;
// Write the dot, if asked
if add_dot && i == enforced_by.len() - 1 {
write!(f, ".")?;
}
}
writeln!(f)?;
}
// Alright that's it
Ok(())
}
}
/// Represents the definition of an atomic Fact, e.g.,
/// ```eflint
/// Fact citizen Identified by String.
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseAtomicFact {
/// The common fields for this definition.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// The name of the new Fact.
pub name: String,
/// The type of the new Fact, which must be one of eFLINT's builtin types. Defaults to "String" if omitted.
#[serde(rename = "type", default = "auxillary::AtomicType::string")]
pub ty: auxillary::AtomicType,
/// If non-empty, then the atomic fact has a closed domain of the given values.
#[serde(skip_serializing_if = "Option::is_none")]
pub range: Option<Domain>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseAtomicFact {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { definition, name, ty, range } = self;
// Take highlighting into account
if f.alternate() {
write!(
f,
"{}{} {} {} ",
Indent(indent),
style::DATA.apply_to("Fact"),
style::BOLD_IDENTIFIER.apply_to(name),
style::KEYWORD.apply_to("Identified by"),
)?;
} else {
write!(f, "{}Fact {} Identified by ", Indent(indent), name)?;
}
// Write the range _or_ type
if let Some(range) = range {
range.eflint_fmt(f)?;
} else {
write!(f, "{ty}")?;
}
// Write the definition fields _or_ an ending period
if !definition.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Represents the definition of a composite Fact, e.g.,
/// ```eflint
/// Fact voter Identified by citizen.
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseCompositeFact {
/// The common fields for this definition.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// The name of the new Fact.
pub name: String,
/// The fields of this Fact, given as identifiers for nested types.
#[serde(rename = "identified-by")]
pub identified_by: auxillary::NonEmptyVec<String>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseCompositeFact {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { definition, name, identified_by } = self;
// Take highlighting into account
if f.alternate() {
write!(
f,
"{}{} {} {} {}",
Indent(indent),
style::DATA.apply_to("Fact"),
style::BOLD_IDENTIFIER.apply_to(name),
style::KEYWORD.apply_to("Identified by"),
identified_by.join(&style::PUNCTUATION.apply_to(", ").to_string()),
)?;
} else {
write!(f, "{}Fact {} Identified by {}", Indent(indent), name, identified_by.join(", "))?;
}
// Write the definition fields _or_ an ending period
if !definition.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Represents a Placeholder definition for Fact for e.g.,
/// ```eflint
/// Placeholder civilian For citizen.
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhrasePlaceholder {
/// The name of the placeholder itself. Note that multiple can be submitted in one go to do it efficiently, but not all backend reasoners may support that syntax.
pub name: Vec<String>,
/// The identifier of the Fact for which phrase holds.
#[serde(rename = "for")]
pub for_fact: String,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhrasePlaceholder {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { name, for_fact } = self;
// Generate one definition for every name
for name in name {
// Take highlighting into account
if f.alternate() {
writeln!(
f,
"{}{} {} {} {}{}",
Indent(indent),
style::DATA.apply_to("Placeholder"),
style::BOLD_IDENTIFIER.apply_to(name),
style::KEYWORD.apply_to("For"),
for_fact,
style::PUNCTUATION.apply_to(".")
)?;
} else {
writeln!(f, "{}Placeholder {} For {}.", Indent(indent), name, for_fact)?;
};
}
// Done!
Ok(())
}
}
/// Represents a predicate that can be queried but not instantiated, e.g.,
/// ```eflint
/// Predicate vote-concluded When Not(Exists citizen : voter(citizen) && !has-voted(citizen)).
/// ```
/// This includes invariants, which are checked after every derivation procedure and can trigger violations when becoming false, e.g.,
/// ```eflint
/// Invariant at-most-one-winner When Not(Exists winner, winner' : winner != winner').
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhrasePredicate {
/// The name of the predicate.
pub name: String,
/// Whether this indicate an invariant or not.
// #[serde(alias = "is-invariant", default = "bool::default")]
// pub is_invariant: bool,
#[serde(rename = "is-invariant", alias = "is_invariant", default = "bool::default")]
pub is_invariant: bool,
/// The boolean expression checked by this predicate.
pub expression: Expression,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhrasePredicate {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { name, is_invariant, expression } = self;
// Write the "header" and the expression
if f.alternate() {
// The header
writeln!(
f,
"{}{} {}",
Indent(indent),
style::DATA.apply_to(if *is_invariant { "Invariant" } else { "Predicate" }),
style::BOLD_IDENTIFIER.apply_to(name),
)?;
// Expression on next line
write!(f, "{}{} ", Indent(indent + 4), style::KEYWORD.apply_to("When"))?;
expression.eflint_fmt(f)?;
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
// The header
writeln!(f, "{}{} {}", Indent(indent), if *is_invariant { "Invariant" } else { "Predicate" }, name)?;
// Expression on next line
write!(f, "{}When ", Indent(indent + 4))?;
expression.eflint_fmt(f)?;
writeln!(f, ".")?;
};
// Done!
Ok(())
}
}
/// Defines an automatic transition between Facts, e.g.,
/// ```eflint
/// Event fire Obfuscates vote.
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseEvent {
/// The common fields for this definition.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// The common fields for event-likes.
#[serde(flatten)]
pub event: EventDefinitionCommon,
/// The name of the new event type.
pub name: String,
/// Any fields for this event, basically.
#[serde(rename = "related-to", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub related_to: Vec<String>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseEvent {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { definition, event, name, related_to } = self;
// Write the "header" and its fields
if f.alternate() {
write!(f, "{}{} {}", Indent(indent), style::DATA.apply_to("Event"), style::BOLD_IDENTIFIER.apply_to(name))?;
if !related_to.is_empty() {
write!(
f,
"\n{}{} {}",
Indent(indent + 4),
style::KEYWORD.apply_to("Related to"),
related_to.join(&style::PUNCTUATION.apply_to(", ").to_string()),
)?;
}
} else {
write!(f, "{}Event {}", Indent(indent), name)?;
if !related_to.is_empty() {
write!(f, "\n{}Related to {}", Indent(indent + 4), related_to.join(", "))?;
}
};
// Write the definition fields, then the duty fields
if !definition.is_empty() || !event.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, event.is_empty(), f)?;
event.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Defines an automatic transition between Facts instantiated by a particular actor, e.g.,
/// ```eflint
/// Act murder
/// Actor citizen1
/// Related to citizen2
/// Terminates citizen2
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseAct {
/// The common fields for this definition.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// The common fields for event-likes.
#[serde(flatten)]
pub event: EventDefinitionCommon,
/// The name of the new act type.
pub name: String,
/// The actor that instantiates this event. Given as the identifier of a particular type (as in, this is a field to the parent type). Will default to `author` if ommitted.
#[serde(default = "default_phrase_act_actor")]
pub actor: String,
/// Any fields for this act other than `actor`, basically.
#[serde(rename = "related-to", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub related_to: Vec<String>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseAct {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { definition, event, name, actor, related_to } = self;
// Write the "header" and its fields
if f.alternate() {
writeln!(f, "{}{} {}", Indent(indent), style::DATA.apply_to("Act"), style::BOLD_IDENTIFIER.apply_to(name))?;
write!(f, "{}{} {}", Indent(indent + 4), style::KEYWORD.apply_to("Actor"), actor)?;
if !related_to.is_empty() {
write!(
f,
"\n{}{} {}",
Indent(indent + 4),
style::KEYWORD.apply_to("Related to"),
related_to.join(&style::PUNCTUATION.apply_to(", ").to_string())
)?;
}
} else {
writeln!(f, "{}Act {}", Indent(indent), name)?;
write!(f, "{}Actor {}", Indent(indent + 4), actor)?;
if !related_to.is_empty() {
write!(f, "\n{}Related to {}", Indent(indent + 4), related_to.join(", "))?;
}
};
// Write the definition fields, then the duty fields
if !definition.is_empty() || !event.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, event.is_empty(), f)?;
event.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Defines an obligation that two actors have, e.g.,
/// ```eflint
/// Duty must-vote
/// Holder citizen
/// Claimant administrator
/// Enforced by not-voted.
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseDuty {
/// The common fields for this definition.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// The common fields for this duty.
#[serde(flatten)]
pub duty: DutyDefinitionCommon,
/// The name of the new duty type.
pub name: String,
/// The actor that has to perform the duty. Given as the identifier of a particular type (as in, this is a field to the parent type).
pub holder: String,
/// The actor that has power to enforce the `holder` doing the duty. Given as the identifier of a particular type (as in, this is a field to the parent type).
pub claimant: String,
/// Any fields for this act other than `holder` and `claimant`, basically.
#[serde(rename = "related-to", default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub related_to: Vec<String>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseDuty {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { definition, duty, name, holder, claimant, related_to } = self;
// Write the "header" and its fields
if f.alternate() {
writeln!(f, "{}{} {}", Indent(indent), style::DATA.apply_to("Duty"), style::BOLD_IDENTIFIER.apply_to(name))?;
writeln!(f, "{}{} {}", Indent(indent + 4), style::KEYWORD.apply_to("Holder"), holder)?;
write!(f, "{}{} {}", Indent(indent + 4), style::KEYWORD.apply_to("Claimant"), claimant)?;
if !related_to.is_empty() {
write!(
f,
"\n{}{} {}",
Indent(indent + 4),
style::KEYWORD.apply_to("Related to"),
related_to.join(&style::PUNCTUATION.apply_to(", ").to_string())
)?;
}
} else {
writeln!(f, "{}Duty {}", Indent(indent), name)?;
writeln!(f, "{}Holder {}", Indent(indent + 4), holder)?;
write!(f, "{}Claimant {}", Indent(indent + 4), claimant)?;
if !related_to.is_empty() {
write!(f, "\n{}Related to {}", Indent(indent + 4), related_to.join(", "))?;
}
};
// Write the definition fields, then the duty fields
if !definition.is_empty() || !duty.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, duty.is_empty(), f)?;
duty.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Defines an extension to an existing type, e.g.,
/// ```eflint
/// Extend Duty duty-to-vote
/// Conditioned by can-vote(voter).
/// ```
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(tag = "parent-kind")]
pub enum PhraseExtend {
/// Extend a Fact, e.g.,
/// ```eflint
/// Extend Fact vote
/// Conditioned by citizen.person != candidate.person.
/// ```
#[serde(rename = "fact")]
Fact(PhraseExtendFact),
/// Extend an Event, e.g.,
/// ```eflint
/// Extend Event fire
/// Creates ash().
/// ```
#[serde(rename = "event")]
Event(PhraseExtendEvent),
/// Extend an Act, e.g.,
/// ```eflint
/// Extend Act vote
/// Terminates (Foreach administrator : duty-to-vote(citizen, administrator)).
/// ```
#[serde(rename = "act")]
Act(PhraseExtendAct),
/// Extend a Duty, e.g.,
/// ```eflint
/// Extend Duty duty-to-vote
/// Conditioned by can-vote(voter).
/// ```
#[serde(rename = "duty")]
Duty(PhraseExtendDuty),
}
impl PhraseExtend {
/// Returns the [`auxillary::ExtendKind`] that describes what this PhraseExtend extends.
///
/// # Returns
/// An equivalent [`auxillary::ExtendKind`].
#[inline]
pub fn kind(&self) -> auxillary::ExtendKind {
match self {
Self::Fact(_) => auxillary::ExtendKind::Fact,
Self::Event(_) => auxillary::ExtendKind::Event,
Self::Act(_) => auxillary::ExtendKind::Act,
Self::Duty(_) => auxillary::ExtendKind::Duty,
}
}
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseExtend {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
// Match to pass
match self {
Self::Fact(fact) => fact.eflint_fmt(indent, f),
Self::Event(event) => event.eflint_fmt(indent, f),
Self::Act(act) => act.eflint_fmt(indent, f),
Self::Duty(duty) => duty.eflint_fmt(indent, f),
}
}
}
/// Defines an extension to an existing Fact, e.g.,
/// ```eflint
/// Extend Fact vote
/// Conditioned by citizen.person != candidate.person.
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseExtendFact {
/// The name of the thing to extend.
pub name: String,
/// Defines the common definition fields that can be extended.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseExtendFact {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { name, definition } = self;
// Write the "header"
if f.alternate() {
write!(
f,
"{}{} {} {}",
Indent(indent),
style::KEYWORD.apply_to("Extend"),
style::DATA.apply_to("Fact"),
style::BOLD_IDENTIFIER.apply_to(name),
)?;
} else {
write!(f, "{}Extend Fact {}", Indent(indent), name,)?;
};
// Write the definition fields
if !definition.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Defines an extension to an existing Event, e.g.,
/// ```eflint
/// Extend Event fire
/// Creates ash().
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseExtendEvent {
/// The name of the thing to extend.
pub name: String,
/// Defines the common definition fields that can be extended.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// Defines the common event fields that can be extended.
#[serde(flatten)]
pub event: EventDefinitionCommon,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseExtendEvent {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { name, definition, event } = self;
// Write the "header"
if f.alternate() {
write!(
f,
"{}{} {} {}",
Indent(indent),
style::KEYWORD.apply_to("Extend"),
style::DATA.apply_to("Event"),
style::BOLD_IDENTIFIER.apply_to(name),
)?;
} else {
write!(f, "{}Extend Event {}", Indent(indent), name,)?;
};
// Write the definition fields, then the duty fields
if !definition.is_empty() || !event.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, event.is_empty(), f)?;
event.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Defines an extension to an existing Act, e.g.,
/// ```eflint
/// Extend Act vote
/// Terminates (Foreach administrator : duty-to-vote(citizen, administrator)).
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseExtendAct {
/// The name of the thing to extend.
pub name: String,
/// Defines the common definition fields that can be extended.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// Defines the common event fields that can be extended.
#[serde(flatten)]
pub event: EventDefinitionCommon,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseExtendAct {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { name, definition, event } = self;
// Write the "header"
if f.alternate() {
write!(
f,
"{}{} {} {}",
Indent(indent),
style::KEYWORD.apply_to("Extend"),
style::DATA.apply_to("Act"),
style::BOLD_IDENTIFIER.apply_to(name),
)?;
} else {
write!(f, "{}Extend Act {}", Indent(indent), name,)?;
};
// Write the definition fields, then the duty fields
if !definition.is_empty() || !event.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, event.is_empty(), f)?;
event.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Defines an extension to an existing Act, e.g.,
/// ```eflint
/// Extend Duty duty-to-vote
/// Conditioned by can-vote(voter).
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseExtendDuty {
/// The name of the thing to extend.
pub name: String,
/// Defines the common definition fields that can be extended.
#[serde(flatten)]
pub definition: TypeDefinitionCommon,
/// Defines the common duty fields that can be extended.
#[serde(flatten)]
pub duty: DutyDefinitionCommon,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseExtendDuty {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { name, definition, duty } = self;
// Write the "header"
if f.alternate() {
write!(
f,
"{}{} {} {}",
Indent(indent),
style::KEYWORD.apply_to("Extend"),
style::DATA.apply_to("Duty"),
style::BOLD_IDENTIFIER.apply_to(name),
)?;
} else {
write!(f, "{}Extend Duty {}", Indent(indent), name,)?;
};
// Write the definition fields, then the duty fields
if !definition.is_empty() || !duty.is_empty() {
writeln!(f)?;
definition.eflint_fmt(indent + 4, duty.is_empty(), f)?;
duty.eflint_fmt(indent + 4, true, f)?;
} else {
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to("."))?;
} else {
writeln!(f, ".")?;
}
}
// Done!
Ok(())
}
}
/// Defines the execution result of a particular [`Phrase`].
///
/// There are three variants:
/// - [Boolean queries](PhraseResult::BooleanQuery) encodes the result to a [boolean query](Phrase::BooleanQuery) (no way!);
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(untagged)]
pub enum PhraseResult {
/// Encodes the result to a boolean query, i.e., to:
/// ```eflint
/// ?citizen(Amy).
/// query successful // <-- this
/// ```
BooleanQuery(PhraseResultBooleanQuery),
/// Encodes the result to an instance query, i.e., to:
/// ```eflint
/// ?- citizen.
/// citizen(string("Bob")) // <-- these
/// citizen(string("Amy")) // <-- these
/// ```
InstanceQuery(PhraseResultInstanceQuery),
/// Encodes the result to phrases that induce state changes, i.e., to:
/// ```eflint
/// +citizen(Amy).
/// +citizen(string("Amy")) // <-- this
/// ```
StateChange(PhraseResultStateChange),
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseResult {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
// Match to delegate, wrapped in surrounding structs
match self {
Self::BooleanQuery(bquery) => bquery.eflint_fmt(indent, f),
Self::InstanceQuery(iquery) => iquery.eflint_fmt(indent, f),
Self::StateChange(schange) => schange.eflint_fmt(indent, f),
}
}
}
/// Defines the fields common to all [PhraseResult] variants.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseResultCommon {
/// Defines if the phrase's execution was a success, or whether there was an error in the backend reasoner.
pub success: bool,
/// Defines a list of errors that may have occurred in case `success` is false.
#[serde(default = "Vec::new", skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<Error>,
}
#[cfg(feature = "display_eflint")]
impl PhraseResultCommon {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `indent`: The indentation to print each line with.
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { success, errors } = self;
// Write the success as a key/value pair
if f.alternate() {
writeln!(
f,
"{}success {} {}",
Indent(indent),
style::PUNCTUATION.apply_to(":"),
if *success { style::SUCCESS.apply_to("true") } else { style::FAILURE.apply_to("false") }
)?;
} else {
writeln!(f, "{}success : {}", Indent(indent), success)?;
}
// Write the errors if there are any
if !errors.is_empty() {
if f.alternate() {
writeln!(f, "{}errors {} {}", Indent(indent), style::PUNCTUATION.apply_to(":"), style::PUNCTUATION.apply_to("["))?;
} else {
writeln!(f, "{}errors : [", Indent(indent))?;
}
for err in &self.errors {
err.eflint_fmt(indent + 4, f)?;
}
writeln!(f, "{}{}", Indent(indent), style::PUNCTUATION.apply_to("]"))?;
}
// Done
Ok(())
}
}
/// Defines the result given by the server when a [boolean query](Phrase::BooleanQuery) is processed.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseResultBooleanQuery {
/// The common fields of any [`PhraseResult`].
#[serde(flatten)]
pub common: PhraseResultCommon,
/// A boolean flag actually indicating the result of the query itself.
pub result: bool,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseResultBooleanQuery {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, result } = self;
// Write the header
writeln!(f, "{}PhraseResult<BooleanQuery> {{", Indent(indent))?;
// Write the common part
common.eflint_fmt(indent + 4, f)?;
// Write the result too, with extra emphasis
if f.alternate() {
writeln!(
f,
"{}{}",
Indent(indent + 4),
if *result { style::SUCCESS.apply_to("query succesful") } else { style::FAILURE.apply_to("query failed") }
)?;
} else {
writeln!(f, "{}{}", Indent(indent + 4), if *result { "query succesful" } else { "query failed" })?;
}
// Finally, write the footer
writeln!(f, "{}}}", Indent(indent))?;
// Done!
Ok(())
}
}
/// Defines the result given by the server when an [instance query](Phrase::InstanceQuery) is processed.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseResultInstanceQuery {
/// The common fields of any [`PhraseResult`].
#[serde(flatten)]
pub common: PhraseResultCommon,
/// The list of instances found, encoded as constructor applications.
pub result: Vec<ExpressionConstructorApp>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseResultInstanceQuery {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, result } = self;
// Write the header
writeln!(f, "{}PhraseResult<InstanceQuery> {{", Indent(indent))?;
// Write the common part
common.eflint_fmt(indent + 4, f)?;
writeln!(f)?;
// Write the list of found instances
for res in result {
// Write the constructor app
write!(f, "{}", Indent(indent + 4))?;
res.eflint_fmt(f)?;
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to(","))?;
} else {
writeln!(f, ",")?;
}
}
// Finally, write the footer
writeln!(f, "{}}}", Indent(indent))?;
// Done!
Ok(())
}
}
/// Defines state changes that are induced after executing a [Phrase].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PhraseResultStateChange {
/// The common fields of any [`PhraseResult`].
#[serde(flatten)]
pub common: PhraseResultCommon,
/// The list of changes given by the server, encoded as phrases necessary to re-create this state. If omitted, then the server does not want to share this (and is thus different than a [`Some(...)`] with an empty list).
#[serde(skip_serializing_if = "Option::is_none")]
pub changes: Option<Vec<Phrase>>,
/// Any Acts or Events that have been triggered by the phrase. If omitted, then the server does not want to share this (and is thus different than a [`Some(...)`] with an empty list).
#[serde(skip_serializing_if = "Option::is_none")]
pub triggers: Option<Vec<Trigger>>,
/// Whether or not the given phrase triggered any violations.
pub violated: bool,
/// Any Acts, Duties or Invariants that have been violated by the phrase. If omitted, then the server does not want to share this (and is thus different than a [`Some(...)`] with an empty list).
#[serde(skip_serializing_if = "Option::is_none")]
pub violations: Option<Vec<Violation>>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for PhraseResultStateChange {
#[inline]
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { common, changes, triggers, violations, violated } = self;
// Prepare some punctuation
let colon: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to(":")) } else { Box::new(":") };
// Write the header
writeln!(f, "{}PhraseResult<StateChange> {{", Indent(indent))?;
// Write the common part
common.eflint_fmt(indent + 4, f)?;
writeln!(f)?;
// Do whether a violation has occurred first
if f.alternate() {
writeln!(
f,
"{}violated {} {}",
Indent(indent + 4),
colon,
if *violated { style::FAILURE.apply_to("true") } else { style::SUCCESS.apply_to("false") }
)?;
} else {
writeln!(f, "{}violated : {}", Indent(indent + 4), violated)?;
}
// Now write the changes, then the triggers, then the violations
if let Some(changes) = changes {
for change in changes {
change.eflint_fmt(indent + 4, f)?;
}
}
if let Some(triggers) = triggers {
if !triggers.is_empty() {
writeln!(f, "{}triggers {}", Indent(indent + 4), colon)?;
for trigger in triggers {
trigger.eflint_fmt(indent + 6, f)?;
}
}
}
if let Some(violations) = violations {
if !violations.is_empty() {
writeln!(f, "{}violations {}", Indent(indent + 4), colon)?;
for violation in violations {
violation.eflint_fmt(indent + 6, f)?;
}
}
}
// Finally, write the footer
writeln!(f, "{}}}", Indent(indent))?;
// Done!
Ok(())
}
}
/// Defines how to specify a closed domain of an atomic eFLINT Fact when we declare it.
///
/// This has two variants:
/// - [Set-syntax](Domain::Set) defines a disjoint set of possible values; and
/// - [Range-syntax](Domain::Range) defines a contious range of values for, say, numbers.
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(untagged)]
pub enum Domain {
/// A set of disjoint values that the atomic Fact can only ever take:
/// ```eflint
/// Fact number Identified by 1, 2, 3.
/// ```
Set(DomainSet),
/// A continious range of values that the atomic Fact can only ever take:
/// ```eflint
/// Fact number Identified by 1..3.
/// ```
Range(DomainRange),
}
#[cfg(feature = "display_eflint")]
impl Domain {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
match self {
Self::Range(range) => range.eflint_fmt(f),
Self::Set(set) => set.eflint_fmt(f),
}
}
}
/// Defines how to give a set of values as a domain for an atomic fact.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DomainSet(pub Vec<Expression>);
impl Deref for DomainSet {
type Target = Vec<Expression>;
#[inline]
fn deref(&self) -> &Self::Target { &self.0 }
}
impl DerefMut for DomainSet {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}
impl From<Vec<Expression>> for DomainSet {
#[inline]
fn from(value: Vec<Expression>) -> Self { Self(value) }
}
impl From<DomainSet> for Vec<Expression> {
#[inline]
fn from(value: DomainSet) -> Self { value.0 }
}
#[cfg(feature = "display_eflint")]
impl DomainSet {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
let Self(set) = self;
// Write the list manually to allow the serializers to error
let mut first: bool = true;
for val in set {
// Write punctuation
if first {
first = false;
} else {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to(", "))?;
} else {
write!(f, ", ")?;
}
}
// Write the value
val.eflint_fmt(f)?;
}
// Done
Ok(())
}
}
/// Defines how to give a range of values as a domain for an atomic fact.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DomainRange {
/// The start value of the range, inclusive.
pub start: i64,
/// The end value of the range, inclusive.
pub end: i64,
}
impl From<RangeInclusive<i64>> for DomainRange {
#[inline]
fn from(value: RangeInclusive<i64>) -> Self { Self { start: *value.start(), end: *value.end() } }
}
impl From<DomainRange> for RangeInclusive<i64> {
#[inline]
fn from(value: DomainRange) -> Self { value.start..=value.end }
}
#[cfg(feature = "display_eflint")]
impl DomainRange {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
let Self { start, end } = self;
if f.alternate() { write!(f, "{}..{}", style::NUMERIC.apply_to(start), style::NUMERIC.apply_to(end)) } else { write!(f, "{start}..{end}") }
}
}
/// Defines an eFLINT expression that evaluates to a value.
///
/// There are multiple variants of this:
/// - [Primitives](Expression::Primitive): Constants/Literals;
/// - [Variable references](Expression::VarRef): References to quantified variables;
/// - [Construction applications](Expression::ConstructorApp): Instantiation of a type of some kind;
/// - [Operators](Expression::Operator): Addition, substraction, multiplication, etc.;
/// - [Iterators](Expression::Iterator): Foreach, forall, exists, etc.; and
/// - [Projections](Expression::Projection): Field accessing of some type.
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(untagged)]
pub enum Expression {
/// eFLINT primitives, i.e., literal values:
/// ```eflint
/// "Amy"
/// 42
/// 42.0
/// true
/// ```
Primitive(ExpressionPrimitive),
/// eFLINT variable references:
/// ```eflint
/// citizen
/// // As in second occurance in:
/// Foreach citizen: citizen
/// ```
VarRef(ExpressionVarRef),
/// Constructor applications, i.e., instantiating facts:
/// ```eflint
/// citizen("Amy")
/// ```
ConstructorApp(ExpressionConstructorApp),
/// Operators (addition, multiplication, Holds, Violated, etc):
/// ```eflint
/// 1 + 2
/// Holds("Amy")
/// ```
Operator(ExpressionOperator),
/// Iterators that do inherent quantification.
///
/// Note that this is different from operators like [Count](appendix::EFlintOperator::COUNT), which do not quantify themselves but rather process an already produced instance expression.
///
/// For example:
/// ```eflint
/// Foreach citizen : citizen.
/// Forall citizen : citizen.
/// Exists citizen : citizen.
/// ```
Iterator(ExpressionIterator),
/// Projection:
/// ```eflint
/// citizen.string
/// ```
Projection(ExpressionProjection),
}
impl Expression {
/// Returns the kind of this expression, whether it's a [boolean](auxillary::ExpressionKind::Boolean) or [instance](auxillary::ExpressionKind::Instance) expression.
///
/// # Returns
/// An [`auxillary::ExpressionKind`] denoting which of the two kinds it is. If [`None`] is returned, then this is not statically determinable (this is the case for Operators and Iterators).
#[inline]
pub fn kind(&self) -> Option<auxillary::ExpressionKind> {
match self {
Expression::Primitive(primitive) => Some(match primitive {
ExpressionPrimitive::Boolean(_) => auxillary::ExpressionKind::Boolean,
ExpressionPrimitive::Integer(_) | ExpressionPrimitive::Float(_) | ExpressionPrimitive::String(_) => {
auxillary::ExpressionKind::Instance
},
}),
Expression::VarRef(_) => Some(auxillary::ExpressionKind::Instance),
Expression::ConstructorApp(_) => Some(auxillary::ExpressionKind::Instance),
Expression::Operator(_) => None,
Expression::Iterator(_) => None,
Expression::Projection(_) => Some(auxillary::ExpressionKind::Instance),
}
}
}
#[cfg(feature = "display_eflint")]
impl Expression {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
match self {
Self::Primitive(primitive) => primitive.eflint_fmt(f),
Self::VarRef(var_ref) => var_ref.eflint_fmt(f),
Self::ConstructorApp(constr_app) => constr_app.eflint_fmt(f),
Self::Operator(operator) => operator.eflint_fmt(f),
Self::Iterator(iterator) => iterator.eflint_fmt(f),
Self::Projection(proj) => proj.eflint_fmt(f),
}
}
}
/// Represents a primitive eFLINT type.
///
/// This, too, has multiple variants; one for every literal type ([strings](ExpressionPrimitive::String), [integer](ExpressionPrimitive::Integer), [float](ExpressionPrimitive::Float) and [booleans](ExpressionPrimitive::Boolean)).
///
/// Note that the specification makes no difference between integers and floating-point numbers. As such, any number without fractions are parsed as integers, and numbers with are parsed as floats.
///
/// For example:
/// ```eflint
/// "Amy"
/// 42
/// 42.0
/// true
/// ```
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(untagged)]
pub enum ExpressionPrimitive {
/// String literals, e.g.:
/// ```eflint
/// "Amy"
/// ```
String(String),
/// Integer literals, e.g.:
/// ```eflint
/// 42
/// ```
Integer(i64),
/// Floating-point literals, e.g.:
/// ```eflint
/// 42.0
/// ```
Float(f64),
/// Boolean literals, e.g.:
/// ```eflint
/// true
/// ```
Boolean(bool),
}
#[cfg(feature = "display_eflint")]
impl ExpressionPrimitive {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
// Match on the type
match self {
Self::String(s) => {
if f.alternate() {
write!(f, "{}", style::STRING.apply_to(format!("\"{s}\"")))
} else {
write!(f, "\"{s}\"")
}
},
Self::Integer(i) => {
if f.alternate() {
write!(f, "{}", style::NUMERIC.apply_to(i))
} else {
write!(f, "{i}")
}
},
Self::Float(fl) => {
if f.alternate() {
write!(f, "{}", style::NUMERIC.apply_to(fl))
} else {
write!(f, "{fl}")
}
},
Self::Boolean(b) => {
if f.alternate() {
write!(f, "{}", style::NUMERIC.apply_to(b))
} else {
write!(f, "{b}")
}
},
}
}
}
/// Represents a variable reference in eFLINT.
///
/// Note that this is serialized and deserialized as a _list_ of strings with only one string, to differentiate with a [literal string](ExpressionPrimitive::String).
///
/// For example:
/// ```eflint
/// citizen
/// // As in second occurance in:
/// Foreach citizen: citizen
/// ```
#[derive(Clone, Debug)]
pub struct ExpressionVarRef(pub String);
impl<'de> Deserialize<'de> for ExpressionVarRef {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
/// Visitor for the ExpressionVarRef
struct ExpressionVarRefVisitor;
impl<'de> Visitor<'de> for ExpressionVarRefVisitor {
type Value = ExpressionVarRef;
fn expecting(&self, f: &mut Formatter) -> FResult { write!(f, "a variable reference expression (list with a single string)") }
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
if let Some(value) = seq.next_element::<String>()? {
// Assert there is no other
if seq.next_element::<String>()?.is_none() {
Ok(ExpressionVarRef(value))
} else {
Err(<A as SeqAccess<'de>>::Error::custom(errors::ExpressionVarRefParseError::TooMany))
}
} else {
Err(<A as SeqAccess<'de>>::Error::custom(errors::ExpressionVarRefParseError::TooFew))
}
}
}
// Parse as an array of strings
deserializer.deserialize_seq(ExpressionVarRefVisitor)
}
}
impl Serialize for ExpressionVarRef {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(1))?;
seq.serialize_element(&self.0)?;
seq.end()
}
}
impl Deref for ExpressionVarRef {
type Target = String;
#[inline]
fn deref(&self) -> &Self::Target { &self.0 }
}
impl DerefMut for ExpressionVarRef {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}
impl From<String> for ExpressionVarRef {
#[inline]
fn from(value: String) -> Self { Self(value) }
}
impl From<ExpressionVarRef> for String {
#[inline]
fn from(value: ExpressionVarRef) -> Self { value.0 }
}
#[cfg(feature = "display_eflint")]
impl ExpressionVarRef {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
#[inline]
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
let Self(identifier) = self;
// Write the variable identifier
write!(f, "{identifier}")?;
// Done
Ok(())
}
}
/// Defines a constructor application in eFLINT.
///
/// For example:
/// ```eflint
/// citizen("Amy")
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ExpressionConstructorApp {
/// The name of the type we're instantiating.
pub identifier: String,
/// The list of operands to instantiate, as a [`ConstructorInput`].
///
/// This because there can be multiple ways of instantiation:
/// ```eflint
/// // Array syntax
/// citizen("Amy")
/// // Map syntax
/// citizen(string="Amy")
/// ```
#[serde(default = "ConstructorInput::default")]
pub operands: ConstructorInput,
}
#[cfg(feature = "display_eflint")]
impl ExpressionConstructorApp {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
let Self { identifier, operands } = self;
// Write the type identifier
write!(f, "{identifier}")?;
// Write the brackets, with the operands in them
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to("("))?;
operands.eflint_fmt(f)?;
write!(f, "{}", style::PUNCTUATION.apply_to(")"))?;
} else {
write!(f, "(")?;
operands.eflint_fmt(f)?;
write!(f, ")")?;
}
// Done
Ok(())
}
}
/// Defines an operator application in eFLINT.
///
/// For example:
/// ```eflint
/// 1 + 2
/// Holds("Amy")
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ExpressionOperator {
/// The operator that we're applying. See [`appendix::EFlintOperator`] for a list of eFLINT operators.
pub operator: String,
/// The operands to give to the operator. It depends on the operator itself how many are necessary.
pub operands: Vec<Expression>,
}
#[cfg(feature = "display_eflint")]
impl ExpressionOperator {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
use appendix::EFlintOperator;
let Self { operator, operands } = self;
// Prepare some syntax
let op_style: Style = if f.alternate() { style::OPERATOR.clone() } else { Style::new() };
let comma: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to(",")) } else { Box::new(",") };
let lparen: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to("(")) } else { Box::new("(") };
let rparen: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to(")")) } else { Box::new(")") };
let none: Box<dyn Display> = if f.alternate() { Box::new(style::INVALID.apply_to("<NONE>")) } else { Box::new("<NONE>") };
// We can commit to (known supported) eFLINT operators because we're serializing as eFLINT
match operator.as_str() {
EFlintOperator::AND => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("&&"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::OR => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("||"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::NOT => {
write!(f, "{}{}", op_style.apply_to("Not"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::EQUALS => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("=="))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::NOT_EQUALS => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("!="))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::GREATER => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to(">"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::GREATER_OR_EQUALS => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to(">="))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::LESSER => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("<"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::LESSER_OR_EQUALS => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("<="))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::ADD => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("+"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::SUB => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("-"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::MUL => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("*"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::DIV => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("/"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::MOD => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("%"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::COUNT => {
write!(f, "{}{}", op_style.apply_to("Count"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::SUM => {
write!(f, "{}{}", op_style.apply_to("Sum"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::MAX => {
write!(f, "{}{}", op_style.apply_to("Max"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::MIN => {
write!(f, "{}{}", op_style.apply_to("Min"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::WHEN => {
write!(f, "{lparen}")?;
if let Some(lhs) = operands.get(0) {
lhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, " {} ", op_style.apply_to("When"))?;
if let Some(rhs) = operands.get(1) {
rhs.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::HOLDS => {
write!(f, "{}{}", op_style.apply_to("Holds"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::ENABLED => {
write!(f, "{}{}", op_style.apply_to("Enabled"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
EFlintOperator::VIOLATED => {
write!(f, "{}{}", op_style.apply_to("Violated"), lparen)?;
if let Some(expr) = operands.get(0) {
expr.eflint_fmt(f)?;
} else {
write!(f, "{none}")?;
}
write!(f, "{rparen}")
},
other => {
write!(f, "{}{}", op_style.apply_to(other), lparen)?;
let mut first: bool = true;
for operand in operands {
// Write any comma in the list
if first {
first = false;
} else {
write!(f, "{comma} ")?;
}
// Write the operand
operand.eflint_fmt(f)?;
}
write!(f, "{rparen}")
},
}
}
}
/// Defines an iterator expression in eFLINT.
///
/// Note that this is different from operators like [Count](appendix::EFlintOperator::COUNT), which do not quantify themselves but rather process an already produced instance expression.
///
/// For example:
/// ```eflint
/// Foreach citizen : citizen.
/// Forall citizen : citizen.
/// Exists citizen : citizen.
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ExpressionIterator {
/// The iterator operator to execute. See [appendix::EFlintIteratorOperator] for a list of known eFLINT operators.
pub iterator: String,
/// The list of variables bound by this iterator. Basically the first occurrence of `citizen` in:
/// ```eflint
/// Foreach citizen : citizen.
/// ```
pub binds: Vec<String>,
/// The expression that is repeated for every quantified combination of bound variables.
///
/// For Foreach, this is an [instance expressions](auxillary::ExpressionKind::Instance). For Exists and Forall, these are [boolean expressions](auxillary::ExpressionKind::Boolean).
pub expression: Box<Expression>,
}
#[cfg(feature = "display_eflint")]
impl ExpressionIterator {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
use appendix::EFlintIteratorOperator;
let Self { iterator, binds, expression } = self;
// Prepare some syntax
let op_style: Style = if f.alternate() { style::OPERATOR.clone() } else { Style::new() };
let comma: String = if f.alternate() { style::PUNCTUATION.apply_to(", ").to_string() } else { ", ".into() };
let colon: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to(":")) } else { Box::new(":") };
let lparen: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to("(")) } else { Box::new("(") };
let rparen: Box<dyn Display> = if f.alternate() { Box::new(style::PUNCTUATION.apply_to(")")) } else { Box::new(")") };
// Write openening parenthesis
write!(f, "{lparen}")?;
// We can commit to (known supported) eFLINT iterator operators because we're serializing as eFLINT
match iterator.as_str() {
EFlintIteratorOperator::EXISTS => {
write!(f, "{}", op_style.apply_to("Exists"))?;
},
EFlintIteratorOperator::FORALL => {
write!(f, "{}", op_style.apply_to("Forall"))?;
},
EFlintIteratorOperator::FOREACH => {
write!(f, "{}", op_style.apply_to("Foreach"))?;
},
other => {
write!(f, "{}", op_style.apply_to(other))?;
},
}
// Write the binds & the expression
write!(f, " {} {} ", binds.join(&comma), colon)?;
expression.eflint_fmt(f)?;
// Write closing parenthesis
write!(f, "{rparen}")
}
}
/// Defines a type projection in eFLINT.
///
/// For example:
/// ```eflint
/// citizen.string
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ExpressionProjection {
/// The identifier of the field to project onto the `operand`.
///
/// Basically `string` in:
/// ```eflint
/// citizen.string
/// ```
pub parameter: String,
/// The expression evaluating to the instance on which to project the `parameter`
///
/// Basically `citizen` in:
/// ```eflint
/// citizen.string
/// ```
pub operand: Box<Expression>,
}
#[cfg(feature = "display_eflint")]
impl ExpressionProjection {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
let Self { parameter, operand } = self;
// Write the operand, then the parameter
operand.eflint_fmt(f)?;
if f.alternate() {
write!(f, "{}{}", style::PUNCTUATION.apply_to("."), parameter)?;
} else {
write!(f, ".{parameter}")?;
}
// Done
Ok(())
}
}
/// Defines the input to a [constructor application](Expression::ConstructorApp).
///
/// Basically defines the arguments to a constructor application, e.g.:
/// ```eflint
/// // Array syntax
/// has-voted(Amy, Bob).
///
/// // Map syntax
/// has-voted(citizen1=Amy, citizen2=Bob).
/// ```
#[derive(Clone, Debug, Deserialize, EnumDebug, Serialize)]
#[serde(untagged)]
pub enum ConstructorInput {
/// It's given as an array of values that must match the input to the instance completely.
ArraySyntax(Vec<Expression>),
/// It's given as a map of field names to values that only needs to match the instance partially.
MapSyntax(HashMap<String, Expression>),
}
impl Default for ConstructorInput {
#[inline]
fn default() -> Self { Self::ArraySyntax(vec![]) }
}
#[cfg(feature = "display_eflint")]
impl ConstructorInput {
/// Allows this AST node to be serialized to the given formatter.
///
/// This is used in the [`DisplayEFlint`]-trait. However, this trait itself is not implemented, as this is only implemented for types returning whole lines (thereby being "standalone"), as it were.
///
/// # Arguments
/// - `f`: The [`Formatter`] to write to.
///
/// # Errors
/// This function errors if we failed to write to the given formatter.
fn eflint_fmt(&self, f: &mut Formatter<'_>) -> FResult {
// Define some (possibly coloured) punctuation
let comma: String = if f.alternate() { style::PUNCTUATION.apply_to(", ").to_string() } else { ", ".into() };
// Match on what kind of input
match self {
Self::ArraySyntax(vals) => {
// Serialize the values separately to allow them to quit
let mut first: bool = true;
for val in vals {
if first {
first = false;
} else {
write!(f, "{comma}")?;
}
val.eflint_fmt(f)?
}
// Done!
Ok(())
},
Self::MapSyntax(vals) => {
// Serialize the values separately to allow them to quit
let mut first: bool = true;
for (field, val) in vals {
// Write any preceding comma
if first {
first = false;
} else {
write!(f, "{comma}")?;
}
// Write it as a pair
if f.alternate() {
write!(f, "{}{}", style::BOLD_IDENTIFIER.apply_to(field), style::PUNCTUATION.apply_to("="))?;
} else {
write!(f, "{field}=")?;
}
val.eflint_fmt(f)?
}
// Done!
Ok(())
},
}
}
}
/// Encodes the trigger of an Event or Act that occurs when running an eFLINT spec.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Trigger {
/// The kind of thing triggered.
pub kind: auxillary::TriggerKind,
/// The identifier (=name) of the thing that triggered this thing. May be `null` to indicate no parent.
pub parent: Option<String>,
/// The identifier (=name) of the triggered thing.
pub name: String,
/// The operands given to the thing that *got* triggered (not that triggered).
pub operands: Vec<Expression>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for Trigger {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
// let Self { kind, parent, name, operands } = self;
// if f.alternate() {
// writeln!(
// f,
// "{}{} {}{} {}{}{}{}{}",
// Indent(indent),
// style::TRIGGER.apply_to("triggered"),
// style::BOLD_IDENTIFIER.apply_to(kind),
// style::PUNCTUATION.apply_to(":"),
// style::BOLD_IDENTIFIER.apply_to(&self.name),
// style::PUNCTUATION.apply_to("("),
// operands.iter().map(|expr| todo!()).collect::<Vec<String>>().join(&style::PUNCTUATION.apply_to(",").to_string()),
// style::PUNCTUATION.apply_to(")"),
// if let Some(parent) = parent { style::TRIGGER_PARENT.apply_to(format!(" <- {parent}")).to_string() } else { String::new() },
// )
// } else {
// writeln!(
// f,
// "{}triggered {}: {}({}){}",
// Indent(indent),
// kind,
// name,
// operands.iter().map(|expr| todo!()).collect::<Vec<String>>().join(", "),
// if let Some(parent) = parent { format!(" <- {parent}") } else { String::new() }
// )
// }
let Self { kind, parent, name, operands } = self;
// Serialize the `violated <type>!`-prefix
if f.alternate() {
write!(
f,
"{}{} {}{} ",
Indent(indent),
style::TRIGGER.apply_to("triggered"),
style::BOLD_IDENTIFIER.apply_to(kind),
style::PUNCTUATION.apply_to(":"),
)?;
} else {
write!(f, "{}triggered {}: ", Indent(indent), kind)?;
}
// Serialize the rest as a constructor app; so first the ID itself (but bold for prettiness)
if f.alternate() {
write!(f, "{}{}", style::BOLD_IDENTIFIER.apply_to(name), style::PUNCTUATION.apply_to("("))?;
} else {
write!(f, "{name}(")?;
}
// Serialize the operands
let mut first: bool = true;
for operand in operands {
// Write a comma if needed
if first {
first = false;
} else {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to(", "))?;
} else {
write!(f, ", ")?;
}
}
// Write the operand
operand.eflint_fmt(f)?;
}
// Write the closing parenthesis
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to(")"))?;
} else {
write!(f, ")")?;
}
// If there is a parent, write it
if let Some(parent) = parent {
if f.alternate() {
write!(f, "{}", style::TRIGGER_PARENT.apply_to(format!(" <-- {parent}")))?;
} else {
write!(f, " <-- {parent}")?;
}
}
// Done
writeln!(f)
}
}
/// Encodes a violation that occurs when running an eFLINT spec.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Violation {
/// The kind of thing violated.
pub kind: auxillary::ViolationKind,
/// The identifier (=name) of the violated thing.
pub identifier: String,
/// The operands given to the thing that violated.
pub operands: Vec<Expression>,
}
#[cfg(feature = "display_eflint")]
impl DisplayEFlint for Violation {
fn eflint_fmt(&self, indent: usize, f: &mut Formatter<'_>) -> FResult {
let Self { kind, identifier, operands } = self;
// Serialize the `violated <type>!`-prefix
if f.alternate() {
write!(
f,
"{}{} {}{}{} ",
Indent(indent),
style::VIOLATION.apply_to("violated"),
style::BOLD_IDENTIFIER.apply_to(kind),
style::VIOLATION.apply_to("!"),
style::PUNCTUATION.apply_to(":"),
)?;
} else {
write!(f, "{}violated {}!: ", Indent(indent), kind)?;
}
// Serialize the rest as a constructor app; so first the ID itself (but bold for prettiness)
if f.alternate() {
write!(f, "{}{}", style::BOLD_IDENTIFIER.apply_to(identifier), style::PUNCTUATION.apply_to("("))?;
} else {
write!(f, "{identifier}(")?;
}
// Serialize the operands
let mut first: bool = true;
for operand in operands {
// Write a comma if needed
if first {
first = false;
} else {
if f.alternate() {
write!(f, "{}", style::PUNCTUATION.apply_to(", "))?;
} else {
write!(f, ", ")?;
}
}
// Write the operand
operand.eflint_fmt(f)?;
}
// Write the closing parenthesis
if f.alternate() {
writeln!(f, "{}", style::PUNCTUATION.apply_to(")"))?;
} else {
writeln!(f, ")")?;
}
// Done
Ok(())
}
}
/***** APPENDIX *****/
pub mod appendix {
use super::auxillary::ExpressionKind;
/// Defines identifiers for reasoners.
///
/// Reasoners the specification is aware of:
/// - [eFLINT](https://gitlab.com/eflint): [`Reasoner::EFLINT`].
#[derive(Clone, Copy, Debug)]
pub struct Reasoner;
impl Reasoner {
/// Defines the eFLINT reasoner.
pub const EFLINT: &str = "eflint";
/// Returns a list of all the reasoners known.
///
/// # Returns
/// A static slice with all reasoners.
pub const fn all() -> &'static [&'static str] { &[Self::EFLINT] }
}
/// Defines identifiers for eFLINT operators, as well as the number of operands they require.
///
/// Note that iterator operators (FORALL, FOREACH, EXISTS) are defined separately in [`EFlintIteratorOperator`].
#[derive(Clone, Copy, Debug)]
pub struct EFlintOperator;
impl EFlintOperator {
/// Arithmetic addition on two numeric values.
pub const ADD: &str = "ADD";
/// Conjunction on two boolean values.
pub const AND: &str = "AND";
/// Counts the number of instances generated by a single instance value.
pub const COUNT: &str = "COUNT";
/// Arithmetic division on two numeric values.
pub const DIV: &str = "DIV";
/// Takes a single instance value and checks if that instance _can_ be derived by the current rules. Essentially is [`EFlintOperator::HOLDS`] but without considering postulation.
pub const ENABLED: &str = "ENABLED";
/// Checks if two values are equal.
pub const EQUALS: &str = "EQ";
/// Compares two numeric values to examine if the first is stricly greater than the second.
pub const GREATER: &str = "GT";
/// Compares two numeric values to examine if the first is greater than- _or_ equal to the second.
pub const GREATER_OR_EQUALS: &str = "GE";
/// Essentially inline boolean query, i.e., takes a single instance value and checks if that instance is true.
pub const HOLDS: &str = "HOLDS";
/// Compares two numeric values to examine if the first is stricly smaller than the second.
pub const LESSER: &str = "LT";
/// Compares two numeric values to examine if the first is smaller than- _or_ equal to the second.
pub const LESSER_OR_EQUALS: &str = "LE";
/// Returns the maximum value from the instances generated by a single instance value.
pub const MAX: &str = "MAX";
/// Returns the minimum value from the instances generated by a single instance value.
pub const MIN: &str = "MIN";
/// Arithmetic modulo on two numeric values.
pub const MOD: &str = "MOD";
/// Arithmetic multiplication on two numeric values.
pub const MUL: &str = "MUL";
/// Negation on one boolean value.
pub const NOT: &str = "NOT";
/// Checks if two values are _not_ equal (inverse of [`EFlintOperator::EQUALS`]).
pub const NOT_EQUALS: &str = "NE";
/// Disjunction on two boolean values.
pub const OR: &str = "OR";
/// Arithmetic subtraction on two numeric values.
pub const SUB: &str = "SUB";
/// Sums the instances generated by a single instance value together to a numeric value.
pub const SUM: &str = "SUM";
/// Takes a single instance value and checks if, if that instantiation were to be added to the knowledge base, it would trigger any violations.
pub const VIOLATED: &str = "VIOLATED";
/// Filters an instance expression with a boolean expression to keep only the ones that evaluate to true.
pub const WHEN: &str = "WHEN";
/// Returns a list of all the eFLINT operators known.
///
/// # Returns
/// A static slice with all operators.
pub const fn all() -> &'static [&'static str] {
&[
Self::AND,
Self::OR,
Self::NOT,
Self::EQUALS,
Self::NOT_EQUALS,
Self::GREATER,
Self::GREATER_OR_EQUALS,
Self::LESSER,
Self::LESSER_OR_EQUALS,
Self::ADD,
Self::SUB,
Self::MUL,
Self::DIV,
Self::MOD,
Self::COUNT,
Self::SUM,
Self::MAX,
Self::MIN,
Self::WHEN,
Self::HOLDS,
Self::ENABLED,
Self::VIOLATED,
]
}
/// Returns a list of all the logic operators in eFLINT.
///
/// # Returns
/// A static slice with all logic operators.
pub const fn logical() -> &'static [&'static str] { &[Self::AND, Self::OR, Self::NOT] }
/// Returns a list of all the comparison operators in eFLINT.
///
/// # Returns
/// A static slice with all comparison operators.
pub const fn comparison() -> &'static [&'static str] {
&[Self::EQUALS, Self::NOT_EQUALS, Self::GREATER, Self::GREATER_OR_EQUALS, Self::LESSER, Self::LESSER_OR_EQUALS]
}
/// Returns a list of all the arithmetic operators in eFLINT.
///
/// # Returns
/// A static slice with all arithmetic operators.
pub const fn arithmetic() -> &'static [&'static str] { &[Self::ADD, Self::SUB, Self::MUL, Self::DIV, Self::MOD] }
/// Returns a list of all the iterator operators in eFLINT.
///
/// # Returns
/// A static slice with all iterator operators.
pub const fn iterator() -> &'static [&'static str] { &[Self::COUNT, Self::SUM, Self::MAX, Self::MIN] }
/// Returns a list of all the miscellaneous operators in eFLINT.
///
/// # Returns
/// A static slice with all miscellaneous operators.
pub const fn miscellaneous() -> &'static [&'static str] { &[Self::WHEN, Self::HOLDS, Self::ENABLED, Self::VIOLATED] }
/// Returns the expression kind (boolean or instance) to which the given operator evaluates.
///
/// # Arguments
/// - `op`: The eFLINT operator to return the expression kind for.
///
/// # Returns
/// An [`auxillary::ExpressionKind`](ExpressionKind) what denotes which of the two kinds it is.
///
/// # Panics
/// This function panics if the given string is not one of the eFLINT operators.
#[inline]
#[track_caller]
pub fn kind(op: &str) -> ExpressionKind {
match op {
Self::AND => ExpressionKind::Boolean,
Self::OR => ExpressionKind::Boolean,
Self::NOT => ExpressionKind::Boolean,
Self::EQUALS => ExpressionKind::Boolean,
Self::NOT_EQUALS => ExpressionKind::Boolean,
Self::GREATER => ExpressionKind::Boolean,
Self::GREATER_OR_EQUALS => ExpressionKind::Boolean,
Self::LESSER => ExpressionKind::Boolean,
Self::LESSER_OR_EQUALS => ExpressionKind::Boolean,
Self::ADD => ExpressionKind::Instance,
Self::SUB => ExpressionKind::Instance,
Self::MUL => ExpressionKind::Instance,
Self::DIV => ExpressionKind::Instance,
Self::MOD => ExpressionKind::Instance,
Self::COUNT => ExpressionKind::Instance,
Self::SUM => ExpressionKind::Instance,
Self::MAX => ExpressionKind::Instance,
Self::MIN => ExpressionKind::Instance,
Self::WHEN => ExpressionKind::Instance,
Self::HOLDS => ExpressionKind::Boolean,
Self::ENABLED => ExpressionKind::Boolean,
Self::VIOLATED => ExpressionKind::Boolean,
_ => panic!("Cannot get expression kind for unknown eFLINT operator '{op}'"),
}
}
/// Returns the number of operators required by the given eFLINT operator.
///
/// # Arguments
/// - `op`: The eFLINT operator to return the number of operators for.
///
/// # Returns
/// The number of operators.
///
/// # Panics
/// This function panics if the given string is not one of the eFLINT operators.
#[inline]
#[track_caller]
pub fn n_operators(op: &str) -> usize {
match op {
Self::AND => 2,
Self::OR => 2,
Self::NOT => 1,
Self::EQUALS => 2,
Self::NOT_EQUALS => 2,
Self::GREATER => 2,
Self::GREATER_OR_EQUALS => 2,
Self::LESSER => 2,
Self::LESSER_OR_EQUALS => 2,
Self::ADD => 2,
Self::SUB => 2,
Self::MUL => 2,
Self::DIV => 2,
Self::MOD => 2,
Self::COUNT => 1,
Self::SUM => 1,
Self::MAX => 1,
Self::MIN => 1,
Self::WHEN => 2,
Self::HOLDS => 1,
Self::ENABLED => 1,
Self::VIOLATED => 1,
_ => panic!("Cannot get number of operators for unknown eFLINT operator '{op}'"),
}
}
}
/// Defines identifiers for eFLINT operators that can (only) be used in [iterator expressions](super::Expression::Iterator).
///
/// Note that these are only Foreach, Forall and Exists. Other operators -like Count and Sum- do not quantify, but rather take a Foreach to do the quantification for them.
///
/// For non-iterator operators, see [`EFlintOperator`].
#[derive(Clone, Copy, Debug)]
pub struct EFlintIteratorOperator;
impl EFlintIteratorOperator {
/// Takes an instance pattern and checks if at least one of those generated is true.
pub const EXISTS: &str = "EXISTS";
/// Takes an instance pattern and checks if all of those generated are true.
pub const FORALL: &str = "FORALL";
/// Foreach generates an instance expression based on the given instance pattern.
pub const FOREACH: &str = "FOREACH";
/// Returns a list of all the iterator operators in eFLINT.
///
/// # Returns
/// A static slice with all iterator operators.
pub const fn all() -> &'static [&'static str] { &[Self::FOREACH, Self::EXISTS, Self::FORALL] }
pub fn kind(op: &str) -> ExpressionKind {
match op {
Self::FOREACH => ExpressionKind::Instance,
Self::EXISTS => ExpressionKind::Boolean,
Self::FORALL => ExpressionKind::Boolean,
_ => panic!("Cannot get expression kind for unknown eFLINT iterator operator '{op}'"),
}
}
}
}