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
|
\chapter{Overview} \label{sec:overview}
\section{Getting started quickly} \label{sec:quickstart}
\subsection{Starting SWI-Prolog} \label{sec:startpl}
\subsubsection{Starting SWI-Prolog on Unix} \label{sec:startunix}
By default, SWI-Prolog is installed as `swipl'. The command line
arguments of SWI-Prolog itself and its utility programs are documented
using standard Unix \program{man} pages. SWI-Prolog is normally operated
as an interactive application simply by starting the program:
\begin{code}
$ swipl
Welcome to SWI-Prolog ...
...
1 ?-
\end{code}
After starting Prolog, one normally loads a program into it using
consult/1, which may be abbreviated by putting the name of the program
file between square brackets. The following goal loads the file
\href{https://raw.githubusercontent.com/SWI-Prolog/swipl-devel/master/demo/likes.pl}{likes.pl}
containing clauses for the predicates \nopredref{likes}{2}:
\begin{code}
?- [likes].
true.
?-
\end{code}
Alternatively, the source file may be given as command line arguments:
\begin{code}
$ swipl likes.pl
Welcome to SWI-Prolog ...
...
1 ?-
\end{code}
After this point, Unix and Windows users unite, so if you are using
Unix please continue at \secref{consultuser}.
\subsubsection{Starting SWI-Prolog on Windows}
\label{sec:startwin}
After SWI-Prolog has been installed on a Windows system, the following
important new things are available to the user:
\begin{itemize}
\item A folder (called \jargon{directory} in the remainder of this
document) called \file{swipl} containing the executables,
libraries, etc., of the system. No files are installed
outside this directory.
\item A program \program{swipl-win.exe}, providing a window for interaction
with Prolog. The program \program{swipl.exe} is a version of
SWI-Prolog that runs in a console window.
\item The file extension \fileext{pl} is associated with the program
\program{swipl-win.exe}. Opening a \fileext{pl} file will cause
\program{swipl-win.exe} to start, change directory to the
directory in which the file to open resides, and load this
file.
\end{itemize}
The normal way to start the \file{likes.pl} file mentioned in
\secref{startunix} is by simply double-clicking this file in the Windows
explorer.
\subsection{Adding rules from the console} \label{sec:consultuser}
Although we strongly advice to put your program in a file, optionally
edit it and use make/0 to reload it (see \secref{viewprogram}), it is
possible to manage facts and rules from the terminal. The most
convenient way to add a few clauses is by consulting the pseudo file
\const{user}. The input is ended using the system end-of-file character.
\begin{code}
?- [user].
|: hello :- format('Hello world~n').
|: ^D
true.
?- hello.
Hello world
true.
\end{code}
The predicates assertz/1 and retract/1 are alternatives to add and
remove rules and facts.
\subsection{Executing a query} \label{sec:execquery}
After loading a program, one can ask Prolog queries about the program.
The query below asks Prolog what food `sam' likes. The system responds
with \mbox{\tt X = <value>} if it can prove the goal for a certain
\arg{X}. The user can type the semi-colon (;) or spacebar%
\footnote{On most installations, single-character commands are
executed without waiting for the {\sc return} key.}
if (s)he wants another solution. Use the \textsc{return} key if you do
not want to see more answers. Prolog completes the output with a full
stop (.) if the user uses the \textsc{return} key or Prolog
\emph{knows} there are no more answers. If Prolog cannot find (more)
answers, it writes \textbf{false.} Finally, Prolog answers using an
error message to indicate the query or program contains an error.
\begin{code}
?- likes(sam, X).
X = dahl ;
X = tandoori ;
...
X = chips.
?-
\end{code}
Note that the answer written by Prolog is a valid Prolog program that,
when executed, produces the same set of answers as the original
program.\footnote{The SWI-Prolog top level differs in several ways from
traditional Prolog top level. The current top level was designed in
cooperation with Ulrich Neumerkel.}
\subsection{Examining and modifying your program} \label{sec:viewprogram}
If properly configured, the predicate edit/1 starts the built-in or
user configured editor on the argument. The argument can be anything
that can be linked to a location: a file name, predicate name, module
name, etc. If the argument resolves to only one location the editor
is started on this location, otherwise the user is presented a choice.
If a graphical user interface is available, the editor normally creates
a new window and the system prompts for the next command. The user may
edit the source file, save it and run make/0 to update any modified
source file. If the editor cannot be opened in a window, it opens in
the same console and leaving the editor runs make/0 to reload any
source files that have been modified.
\begin{code}
?- edit(likes).
true.
?- make.
% /home/jan/src/pl-devel/linux/likes compiled 0.00 sec, 0 clauses
?- likes(sam, X).
...
\end{code}
The program can also be \jargon{decompiled} using listing/1 as below.
The argument of listing/1 is just a predicate name, a predicate
\jargon{indicator} of the form \arg{Name/Arity}, e.g., \exam{?-
listing(mild/1).} or a \jargon{head}, e.g., \exam{?- listing(likes(sam,
_)).}, listing all \jargon{matching} clauses. The predicate listing/0,
i.e., without arguments lists the entire program.\footnote{This lists
several \jargon{hook} predicates that are defined by default and is
typically not very informative.}
\begin{code}
?- listing(mild).
mild(dahl).
mild(tandoori).
mild(kurma).
true.
\end{code}
\subsection{Stopping Prolog} \label{sec:halt}
The interactive toplevel can be stopped in two ways: enter the system
end-of-file character (typically \textit{Control-D}) or by executing the
halt/0 predicate:
\begin{code}
?- halt.
$
\end{code}
\section{The user's initialisation file} \label{sec:initfile}
\index{startup file}%
\index{user profile file}%
\index{profile file}%
After the system initialisation, the system consults (see consult/1) the
user's \jargon{init} file. This file is searched using
absolute_file_name/3 using the path alias (see file_search_path/2)
\const{app_config}. This is a directory named \file{swi-prolog} below
the OS default name for placing application configuration data:
\begin{itemize}
\item On Windows, the CSIDL folder \const{CSIDL_APPDATA}, typically
\verb$C:\Documents and Settings\username\Application Data$.
\item If the environment variable \env{XDG_DATA_HOME} is set,
use this. This follows the \href{https://standards.freedesktop.org}{free
desktop} standard.
\item The expansion of \file{~/.config}.
\end{itemize}
The directory can be found using this call:
\begin{code}
?- absolute_file_name(app_config(.), Dir, [file_type(directory)]).
Dir = '/home/jan/.config/swi-prolog'.
\end{code}
After the first startup file is found it is loaded and Prolog
stops looking for further startup files. The name of the
startup file can be changed with the `\argoption{-f}{file}'
option. If \arg{File} denotes an absolute path, this file is loaded,
otherwise the file is searched for using the same conventions as for
the default startup file. Finally, if \arg{file} is
\const{none}, no file is loaded.
The installation provides a file \file{customize/init.pl} with
(commented) commands that are often used to customize the behaviour of
Prolog, such as interfacing to the editor, color selection or history
parameters. Many of the development tools provide menu entries for
editing the startup file and starting a fresh startup file from the
system skeleton.
See also the \cmdlineoption{-s} (script) and \cmdlineoption{-F}
(system-wide initialisation) in \secref{cmdline} and \secref{initgoal}.
\section{Initialisation files and goals} \label{sec:initgoal}
Using command line arguments (see \secref{cmdline}), SWI-Prolog can be
forced to load files and execute queries for initialisation purposes or
non-interactive operation. The most commonly used options are
\argoption{-f}{file} or \argoption{-s}{file} to make Prolog load a file,
\argoption{-g}{goal} to define initialisation goals and
\argoption{-t}{goal} to define the \jargon{top-level goal}. The following
is a typical example for starting an application directly from the
command line.
\begin{code}
machine% swipl -s load.pl -g go -t halt
\end{code}
It tells SWI-Prolog to load \file{load.pl}, start the application using
the \jargon{entry point} \nopredref{go}{0} and ---instead of entering
the interactive top level--- exit after completing \nopredref{go}{0}.
The command line may have multiple \argoption{-g}{goal} occurrences. The
goals are executed in order. Possible choice points of individual goals
are pruned. If a \arg{goal} fails execution stops with exit status
\const{1}. If a \arg{goal} raises an exception, the exception is printed
and the process stops with exit code \const{2}.
The \cmdlineoption{-q} may be used to suppress all informational
messages as well as the error message that is normally printed if an
initialisation goal \emph{fails}.
In MS-Windows, the same can be achieved using a short-cut with
appropriately defined command line arguments. A typically seen
alternative is to write a file \file{run.pl} with content as illustrated
below. Double-clicking \file{run.pl} will start the application.
\begin{code}
:- [load]. % load program
:- go. % run it
:- halt. % and exit
\end{code}
\Secref{plscript} discusses further scripting options, and
\chapref{runtime} discusses the generation of runtime executables.
Runtime executables are a means to deliver executables that do not
require the Prolog system.
\section{Command line options} \label{sec:cmdline}
SWI-Prolog can be executed in one of the following modes:
\begin{description}
\definition{\exam{swipl --help}}
\nodescription
\definition{\exam{swipl --version}}
\nodescription
\definition{\exam{swipl --arch}}
\nodescription
\definition{\exam{swipl --dump-runtime-variables}}
These options must appear as only option. They cause Prolog to print
an informational message and exit. See \secref{info-options}.
\definition{\exam{swipl} [\arg{option} ...]
\arg{script-file} [\arg{arg} ...]}
These arguments are passed on Unix systems if file that starts
with \mbox{\texttt{\#!/path/to/executable} [\arg{option} ...]} is
executed. Arguments after the script file are made available in the
Prolog flag \prologflag{argv}.
\definition{\exam{swipl} [\arg{option} ...]
\arg{prolog-file} ...
[[\const{--}] \arg{arg} ...]}
This is the normal way to start Prolog. The options are described in
\secref{running-options}, \secref{stacksizes} and \secref{runoptions}.
The Prolog flag \prologflag{argv} provides access to \arg{arg} ... If
the \arg{options} are followed by one or more Prolog file names (i.e.,
names with extension \fileext{pl}, \fileext{prolog} or (on Windows) the
user preferred extension registered during installation), these files
are loaded. The first file is registered in the Prolog flag
\prologflag{associated_file}. In addition, \program{pl-win[.exe]}
switches to the directory in which this primary source file is located
using working_directory/2.
\definition{\exam{swipl} -o \arg{output} -c \arg{prolog-file} ...}
The \cmdlineoption{-c} option is used to compile a set of Prolog
files into an executable. See \secref{compoptions}.
\definition{\exam{swipl} -o \arg{output} -b \arg{bootfile}
\arg{prolog-file} ...}
Bootstrap compilation. See \secref{maintoptions}.
\end{description}
\subsection{Informational command line options}
\label{sec:info-options}
\begin{description}
\cmdlineoptionitem{--arch}{}
When given as the only option, it prints the architecture identifier
(see Prolog flag \prologflag{arch}) and exits. See also
\cmdlineoption{--dump-runtime-variables}.
\cmdlineoptionitem{--dump-runtime-variables}{[=format]}
When given as the only option, it prints a sequence of variable settings
that can be used in shell scripts to deal with Prolog parameters. This
feature is also used by \program{swipl-ld} (see \secref{plld}). Below is
a typical example of using this feature.
\begin{code}
eval `swipl --dump-runtime-variables`
cc -I$PLBASE/include -L$PLBASE/lib/$PLARCH ...
\end{code}
The option can be followed by \const{=sh} to dump in POSIX shell format
(default) or \const{=cmd} to dump in MS-Windows \program{cmd.exe}
compatible format.
\cmdlineoptionitem{--help}{}
When given as the only option, it summarises the most important options.
\cmdlineoptionitem{--version}{}
When given as the only option, it summarises the version and the
architecture identifier.
\cmdlineoptionitem{--abi-version}{}
Print a key (string) that represents the binary compatibility on
a number of aspects. See \secref{abi-versions}.
\end{description}
\subsection{Command line options for running Prolog}
\label{sec:running-options}
Note that \jargon{boolean options} may be written as \exam{--name}
(true), \exam{--noname} or \exam{--no-name} (false). They are written
as \exam{--no-name} below as the default is `true'.
\begin{description}
\cmdlineoptionitem{--home=DIR}{}
Use \arg{DIR} as home directory. See \secref{findhome} for details.
\cmdlineoptionitem{--quiet}{}
\index{verbose}\index{quiet}%
Set the Prolog flag \prologflag{verbose} to \const{silent}, suppressing
informational and banner messages. Also available as \cmdlineoption{-q}.
\cmdlineoptionitem{--no-debug}{}
Disable debugging. See the current_prolog_flag/2 flag
\prologflag{generate_debug_info} for details.
\cmdlineoptionitem{--no-signals}{}
Inhibit any signal handling by Prolog, a property that is sometimes
desirable for embedded applications. This option sets the flag
\prologflag{signals} to \const{false}. See \secref{sigembedded} for
details. Note that the handler to unblock system calls is still
installed. This can be prevented using \exam{--sigalert=0} additionally.
See \cmdlineoption{--sigalert}.
\cmdlineoptionitem{--no-threads}{}
Disable threading for the multi-threaded version at runtime. See also
the flags \prologflag{threads} and \prologflag{gc_thread}.
\cmdlineoptionitem{--no-packs}{}
Do \emph{not} attach extension packages (add-ons). See also
attach_packs/0 and the Prolog flag \prologflag{packs}.
\cmdlineoptionitem{--no-pce}{}
Enable/disable the xpce GUI subsystem. The default is to make it
available as autoload component if it is installed and the system
can access the graphics. Using \exam{--pce} load the xpce system
in user space and \exam{--no-pce} makes it unavailable in the session.
\cmdlineoptionitem{--pldoc}{[=port]}
Start the PlDoc documentation system on a free network port and launch
the user's browser on \verb$http://localhost:$\arg{port}. If
\arg{port} is specified, the server is started at the given port and the
browser is \emph{not} launched.
\cmdlineoptionitem{--sigalert=NUM}{}
Use signal \arg{NUM} (1\ldots{}31) for alerting a thread. This is needed
to make thread_signal/2, and derived Prolog signal handling act
immediately when the target thread is blocked on an interruptible
system call (e.g., sleep/1, read/write to most devices). The default is
to use \const{SIGUSR2}. If \arg{NUM} is 0 (zero), this handler is not
installed. See prolog_alert_signal/2 to query or modify this value at
runtime.
\cmdlineoptionitem{--no-tty}{}
Unix only. Switches controlling the terminal for allowing
single-character commands to the tracer and get_single_char/1. By
default, manipulating the terminal is enabled unless the system detects
it is not connected to a terminal or it is running as a GNU-Emacs
inferior process. See also \prologflag{tty_control}.
\cmdlineoptionitem{--win-app}{}
This option is available only in \program{swipl-win.exe} and is used for the
start-menu item. If causes \program{plwin} to start in the folder
\verb$...\My Documents\Prolog$ or local equivalent thereof (see
win_folder/2). The \file{Prolog} subdirectory is created if it
does not exist.
\cmdlineoptionitem{-O}{}
Optimised compilation. See current_prolog_flag/2 flag
\prologflag{optimise} for details.
\cmdlineoptionitem{-l}{file}
Load \arg{file}. This flag provides compatibility with some other Prolog
systems.\footnote{YAP, SICStus} It is used in SWI-Prolog to skip the
program initialization specified using initialization/2 directives. See
also \secref{plscript}, and initialize/0.
\cmdlineoptionitem{-s}{file}
Use \arg{file} as a script file. The script file is loaded after
the initialisation file specified with the \argoption{-f}{file}
option. Unlike \argoption{-f}{file}, using \cmdlineoption{-s}
does not stop Prolog from loading the personal initialisation file.
\cmdlineoptionitem{-f}{file}
Use \arg{file} as initialisation file instead of the default
\file{init.pl}. `\argoption{-f}{none}' stops SWI-Prolog from searching
for a startup file. This option can be used as an alternative to
\argoption{-s}{file} that stops Prolog from loading the personal
initialisation file. See also \secref{initfile}.
\cmdlineoptionitem{-F}{script}
Select a startup script from the SWI-Prolog home directory. The
script file is named \file{<script>.rc}. The default
\arg{script} name is deduced from the executable, taking the leading
alphanumerical characters (letters, digits and underscore) from the
program name. \argoption{-F}{none} stops looking for a script. Intended
for simple management of slightly different versions. One could, for
example, write a script \file{iso.rc} and then select ISO compatibility
mode using \exam{pl -F iso} or make a link from \program{iso-pl} to
\program{pl}.
\cmdlineoptionitem{-x}{bootfile}
Boot from \arg{bootfile} instead of the system's default boot file. A
boot file is a file resulting from a Prolog compilation using the
\cmdlineoption{-b} or \cmdlineoption{-c} option or a program saved using
qsave_program/[1,2].
\cmdlineoptionitem{-p}{alias=path1[:path2 \ldots]}
Define a path alias for file_search_path. \arg{alias} is the name of
the alias, and arg{path1 ...} is a list of values for the alias. On Windows
the list separator is \chr{;}. On other systems it is \chr{:}. A value
is either a term of the form \mbox{alias(value)} or pathname. The
computed aliases are added to file_search_path/2 using asserta/1, so
they precede predefined values for the alias. See file_search_path/2 for
details on using this file location mechanism.
\cmdlineoptionitem{--traditional}{}
This flag disables the most important extensions of SWI-Prolog
version~7 (see \secref{extensions}) that introduce incompatibilities
with earlier versions. In particular, lists are represented in the
traditional way, double quoted text is represented by a list of
character codes and the functional notation on dicts is not supported.
Dicts as a syntactic entity, and the predicates that act on them, are
still supported if this flag is present.
\cmdlineoptionitem{--}{}
\index{command line, arguments}%
Stops scanning for more arguments, so you can pass arguments for your
application after this one. See current_prolog_flag/2 using the
flag \prologflag{argv} for obtaining the command line arguments.
\end{description}
\subsection{Controlling the stack sizes}
\label{sec:stacksizes}
As of version 7.7.14 the stacks are no longer limited individually.
Instead, only the combined size is limited. Note that 32~bit systems
still pose a 128Mb limit. See \secref{memlimit}. The combined limit is
by default 1Gb on 64~bit machines and 512Mb on 32~bit machines.
For example, to limit the stacks to 32Gb use the command below. Note
that the stack limits apply \emph{per thread}. Individual threads may be
controlled using the \term{stack_limit}{+Bytes} option of thread_create.
Any thread can call \term{set_prolog_flag}{stack_limit, Limit} (see
\prologflag{stack_limit}) to adjust the stack limit. This limit is
inherited by threads created from this thread.
\begin{code}
$ swipl --stack-limit=32g
\end{code}
\begin{description}
\cmdlineoptionitem*{--stack-limit}{=size[bkmg]}
Limit the combined size of the Prolog stacks to the indicated \arg{size}.
The suffix specifies the value as \textit{bytes}, \textit{Kbytes},
\textit{Mbytes} or \textit{Gbytes}.
\cmdlineoptionitem*{--table-space}{=size[bkmg]}
Limit for the \arg{table space}. This is where tries holding
memoized\footnote{The letter M is used because the T was already in
use. It is a memnonic for \textbf{M}emoizing.} answers for
\jargon{tabling} are stored. The default is 1Gb on 64~bit machines and
512Mb on 32~bit machines. See the Prolog flag
\prologflag{table_space}.
\cmdlineoptionitem*{--shared-table-space}{=size[bkmg]}
Limit for the table space for \jargon{shared} tables. See
\secref{tabling-shared}.
\end{description}
\subsection{Running goals from the command line}
\label{sec:runoptions}
\begin{description}
\cmdlineoptionitem{-g}{goal}
\arg{Goal} is executed just before entering the top level. This option
may appear multiple times. See \secref{initgoal} for details. If no
initialization goal is present the system calls version/0 to print the
welcome message. The welcome message can be suppressed with
\cmdlineoption{--quiet}, but also with \argoption{-g}{true}. \arg{goal}
can be a complex term. In this case quotes are normally needed to
protect it from being expanded by the shell. A safe way to run a goal
non-interactively is below. If \nopredref{go}{0} succeeds
\argoption{-g}{halt} causes the process to stop with exit code 0. If it
fails, the exit code is 1; and if it raises an exception, the exit code
is 2.
\begin{code}
% swipl <options> -g go -g halt
\end{code}
\cmdlineoptionitem{-t}{goal}
Use \arg{goal} as interactive top level instead of the default goal
prolog/0. The \arg{goal} can be a complex term. If the top-level goal
succeeds SWI-Prolog exits with status 0. If it fails the exit status is
1. If the top level raises an exception, this is printed as an uncaught
error and the top level is \emph{restarted}. This flag also determines
the goal started by break/0 and abort/0. If you want to prevent the user
from entering interactive mode, start the application with
`\argoption{-g}{goal} \argoption{-t}{halt}'.
\end{description}
\subsection{Compilation options}
\label{sec:compoptions}
\begin{description}
\cmdlineoptionitem{-c}{file \ldots}
Compile files into an `intermediate code file'. See \secref{compilation}.
\cmdlineoptionitem{-o}{output}
Used in combination with \cmdlineoption{-c} or \cmdlineoption{-b} to
determine output file for compilation.
\end{description}
\subsection{Maintenance options}
\label{sec:maintoptions}
The following options are for system maintenance. They are given
for reference only.
\begin{description}
\cmdlineoptionitem{-b}{initfile \ldots \cmdlineoption{-c} file \ldots}
Boot compilation. \arg{initfile \ldots} are compiled by the C-written
bootstrap compiler, \arg{file \ldots} by the normal Prolog compiler.
System maintenance only.
\cmdlineoptionitem{-d}{token1,token2,...}
Print debug messages for DEBUG statements tagged with one of the
indicated tokens. Only has effect if the system is compiled with the
\const{-DO_DEBUG} flag. System maintenance only.
\end{description}
\section{UI Themes} \label{sec:theme}
UI (colour) themes play a role in two parts: when writing to the
\jargon{console} and for the xpce-based development tools such as
PceEmacs or the graphical debugger. Coloured console output is based on
ansi_format/3. The central message infra structure based on
print_message/2 labels message (components) with a Prolog term that
specifies the role. This is mapped to concrete colours by means of the
hook prolog:console_color/2. Theming the IDE uses xpce \jargon{class
variables} that are initialised from Prolog when xpce is loaded.
Themes are implemented as a Prolog file in the file search path
library/theme. A theme can be loaded using (for example) the directive
below in the user's initialization file (see \secref{initfile}).
\begin{code}
:- use_module(library(theme/dark)).
\end{code}
The theme file \exam{library(theme/auto)} is provided to automatically
choose a reasonable theme based on the environment. The current version
detects the background color on \textit{xterm} compatible terminal
emulators (found on most Unix systems) and loads the \const{dark} theme
if the background is `darkish'.
The following notes apply to the different platforms on which SWI-Prolog
is supported:
\begin{description}
\item[Unix/Linux]
If an xterm compatible terminal emulator is used to run Prolog you may
wish to load either an explicit theme or \exam{library(theme/auto)}.
\item[Windows]
The \program{swipl-win.exe} graphical application can be themed by
loading a theme file. The theme file also sets the foreground and
background colours for the console.
\end{description}
\subsection{Status of theme support} \label{sec:theme-status}
Theme support was added in SWI-Prolog 8.1.11. Only part of the IDE tools
are covered and the only additional theme (\const{dark}) is not net well
balanced. The interfaces between the theme file and notably the IDE
components is not very well established. Please contribute by improving
the \const{dark} theme. Once that is complete and properly functioning
we can start adding new themes.
\section{GNU Emacs Interface} \label{sec:gemacs}
\index{GNU-Emacs}\index{Emacs}
Unfortunately the default Prolog mode of GNU~Emacs is not very good.
There are several alternatives though:
\begin{shortlist}
\item \url{https://bruda.ca/emacs/prolog_mode_for_emacs}\\
Prolog mode for Emacs and XEmacs maintained by Stefan Bruda.
\item \url{https://www.metalevel.at/pceprolog/}\\
Recommended configuration options for editing Prolog code with Emacs.
\item \url{https://www.metalevel.at/ediprolog/}\\
Interact with SWI-Prolog directly in Emacs buffers.
\item \url{https://www.metalevel.at/etrace/}\\
Trace Prolog code with Emacs.
\end{shortlist}
\section{Online Help} \label{sec:online-help}
\input{lib/help.tex}
\input{lib/explain.tex}
\section{Command line history} \label{sec:history}
SWI-Prolog offers a query substitution mechanism similar to what is seen
in Unix shells. The availability of this feature is controlled by
set_prolog_flag/2, using the \prologflag{history} Prolog flag. By
default, history is available if no interactive command line editor is
available. To enable history, remembering the last 50 commands, put the
following into your startup file (see \secref{initfile}):
\begin{code}
:- set_prolog_flag(history, 50).
\end{code}
The history system allows the user to compose new queries from those
typed before and remembered by the system. The available history
commands are shown in \tabref{history}. History expansion is not done if
these sequences appear in quoted atoms or strings.
\begin{table}
\begin{center}
\begin{tabular}{|l|l|}
\hline
\verb+!!.+ & Repeat last query \\
\verb+!nr.+ & Repeat query numbered <nr> \\
\verb+!str.+ & Repeat last query starting with <str> \\
\verb+h.+ & Show history of commands \\
\verb+!h.+ & Show this list \\
\hline
\end{tabular}
\end{center}
\caption{History commands}
\label{tab:history}
\end{table}
\section{Reuse of top-level bindings} \label{sec:topvars}
Bindings resulting from the successful execution of a top-level goal are
asserted in a database \emph{if they are not too large}. These values
may be reused in further top-level queries as \$Var. If the same
variable name is used in a subsequent query the system associates the
variable with the latest binding. Example:
\begin{figure}
\begin{code}
1 ?- maplist(plus(1), `hello`, X).
X = [105,102,109,109,112].
2 ?- format('~s~n', [$X]).
ifmmp
true.
3 ?-
\end{code}
\caption{Reusing top-level bindings}
\label{fig:topevelvars}
\end{figure}
Note that variables may be set by executing \predref{=}{2}:
\begin{code}
6 ?- X = statistics.
X = statistics.
7 ?- $X.
% Started at Fri Aug 24 16:42:53 2018
% 0.118 seconds cpu time for 456,902 inferences
% 7,574 atoms, 4,058 functors, 2,912 predicates, 56 modules, 109,791 VM-codes
%
% Limit Allocated In use
% Local stack: - 20 Kb 1,888 b
% Global stack: - 60 Kb 36 Kb
% Trail stack: - 30 Kb 4,112 b
% Total: 1,024 Mb 110 Kb 42 Kb
%
% 3 garbage collections gained 178,400 bytes in 0.000 seconds.
% 2 clause garbage collections gained 134 clauses in 0.000 seconds.
% Stack shifts: 2 local, 2 global, 2 trail in 0.000 seconds
% 2 threads, 0 finished threads used 0.000 seconds
true.
\end{code}
\section{Overview of the Debugger} \label{sec:debugoverview}
SWI-Prolog has a traditional commandline debugger. It also provides
programmatic access to the debugger. This facility is used to provide
a graphical debugger as well as remote debugging in the web interface
provided by \href{https://swish.swi-prolog.org}{SWISH}.
SWI-Prolog has a 6-port tracer, extending the standard 4-port tracer
\cite{Byrd:80,Clocksin:87} with two additional ports. The standard ports
are called \const{call}, \const{exit}, \const{redo}, and \const{fail}.
The additional \arg{unify} port allows the user to inspect the result
after unification of the head. The additional \arg{exception} port shows
exceptions raised by throw/1 or one of the built-in predicates. See
\secref{exception}.
The tracer is started by the trace/0 command. If the system is in debug
mode (see debug/0) the trace is started, after reaching a \jargon{spy
point} set using spy/1 or \jargon{break point} set using
set_breakpoint/4. The debugger is also started if an
\term{error}{Formal, Extended} exception is raised that is not caught.
If the native graphics plugin (XPCE) is available, the commands gtrace/0
and gspy/1 activate the graphical debugger while tdebug/0 and tspy/1
allow debugging of arbitrary threads.
The interactive top-level goal trace/0 means ``trace the next query''.
The tracer shows the port, displaying the port name, the current depth
of the recursion and the goal. The goal is printed using the Prolog
predicate write_term/2. The style is defined by the Prolog flag
\prologflag{debugger_write_options} and can be modified using this flag
or using the \const{w}, \const{p} and \const{d} commands of the tracer.
\begin{figure}
\begin{code}
min_numlist([H|T], Min) :-
min_numlist(T, H, Min).
min_numlist([], Min, Min).
min_numlist([H|T], Min0, Min) :-
Min1 is min(H, Min0),
min_numlist(T, Min1, Min).
\end{code}
\begin{code}
1 ?- visible(+all), leash(-exit).
true.
2 ?- trace, min_numlist([3, 2], X).
Call: (7) min_numlist([3, 2], _G0) ? creep
Unify: (7) min_numlist([3, 2], _G0)
Call: (8) min_numlist([2], 3, _G0) ? creep
Unify: (8) min_numlist([2], 3, _G0)
^ Call: (9) _G54 is min(2, 3) ? creep
^ Exit: (9) 2 is min(2, 3)
Call: (9) min_numlist([], 2, _G0) ? creep
Unify: (9) min_numlist([], 2, 2)
Exit: (9) min_numlist([], 2, 2)
Exit: (8) min_numlist([2], 3, 2)
Exit: (7) min_numlist([3, 2], 2)
X = 2.
\end{code}
\caption{Example trace of the program above showing all ports.
The lines marked \chr{^} indicate calls to
\jargon{transparent} predicates. See \secref{modules}.}
\label{fig:tracer}
\end{figure}
On {\em leashed ports} (set with the predicate leash/1, default are
\const{call}, \const{exit}, \const{redo} and \const{fail}) the user is
prompted for an action. All actions are single-character commands which
are executed {\bf without} waiting for a return, unless the command line
option \cmdlineoption{--no-tty} is active. Tracer options:
\begin{description}
\traceoption{+}{Spy}{
Set a spy point (see spy/1) on the current predicate.}
\traceoption{-}{No spy}{
Remove the spy point (see nospy/1) from the current predicate.}
\traceoption{/}{Find}{
Search for a port. After the `/', the user can enter a line
to specify the port to search for. This line consists of a set of
letters indicating the port type, followed by an optional term,
that should unify with the goal run by the port. If no term is
specified it is taken as a variable, searching for any port of the
specified type. If an atom is given, any goal whose functor has a
name equal to that atom matches. Examples:
\begin{center}\begin{tabular}{lp{3in}}
\tt /f & Search for any fail port \\
\tt /fe solve & Search for a fail or exit port of any goal with
name \const{solve} \\
\tt /c solve(a, _) & Search for a call to {solve}/2 whose first argument
is a variable or the atom \const{a} \\
\tt /a member(_, _) & Search for any port on member/2. This is equivalent
to setting a spy point on member/2. \\
\end{tabular}\end{center}}
\traceoption{.}{Repeat find}{
Repeat the last find command (see `/').}
\traceoption{A}{Alternatives}{
Show all goals that have alternatives.}
\traceoption{C}{Context}{
Toggle `Show Context'. If \const{on}, the context module of the goal is
displayed between square brackets (see \secref{modules}).
Default is \const{off}.}
\traceoption{L}{Listing}{
List the current predicate with listing/1.}
\traceoption{a}{Abort}{
Abort Prolog execution (see abort/0).}
\traceoption{b}{Break}{
Enter a Prolog break environment (see break/0).}
\traceoption{c}{Creep}{
Continue execution, stop at next port. (Also \textsc{return}, \textsc{space}).}
\traceoption{d}{Display}{
Set the \term{max_depth}{Depth} option of
\prologflag{debugger_write_options}, limiting the depth to which terms are
printed. See also the \const{w} and \const{p} options.}
\traceoption{e}{Exit}{
Terminate Prolog (see halt/0).}
\traceoption{f}{Fail}{
Force failure of the current goal.}
\traceoption{g}{Goals}{
Show the list of parent goals (the execution stack). Note that due to tail
recursion optimization a number of parent goals might not exist any more.}
\traceoption{h}{Help}{
Show available options (also `?').}
\traceoption{i}{Ignore}{
Ignore the current goal, pretending it succeeded.}
\traceoption{l}{Leap}{
Continue execution, stop at next spy point.}
\traceoption{n}{No debug}{
Continue execution in `no debug' mode.}
\traceoption{p}{Print}{
Set the Prolog flag \prologflag{debugger_write_options} to
\texttt{[quoted(true), portray(true), max_depth(10), priority(699)]}. This is the
default.}
\traceoption{r}{Retry}{
Undo all actions (except for database and I/O actions) back to the call
port of the current goal and resume execution at the call port.}
\traceoption{s}{Skip}{
Continue execution, stop at the next port of {\bf this} goal (thus skipping
all calls to children of this goal).}
\traceoption{u}{Up}{
Continue execution, stop at the next port of {\bf the parent} goal (thus
skipping this goal and all calls to children of this goal). This option
is useful to stop tracing a failure driven loop.}
\traceoption{w}{Write}{
Set the Prolog flag \prologflag{debugger_write_options} to
\texttt{[quoted(true), attributes(write), priority(699)]}, bypassing portray/1, etc.}
\end{description}
The ideal 4-port model \cite{Byrd:80} as described in many Prolog books
\cite{Clocksin:87} is not visible in many Prolog implementations because
code optimisation removes part of the choice and exit points. Backtrack
points are not shown if either the goal succeeded deterministically or
its alternatives were removed using the cut. When running in debug mode
(debug/0) choice points are only destroyed when removed by the cut. In
debug mode, last call optimisation is switched off.\footnote{This
implies the system can run out of stack in debug mode, while no problems
arise when running in non-debug mode.}
Reference information to all predicates available for manipulating the
debugger is in \secref{debugger}.
\section{Compilation} \label{sec:compilation}
\subsection{During program development} \label{sec:develcomp}
During program development, programs are normally loaded using the list
abbreviation (\texttt{?- [load].}). It is common practice to organise a
project as a collection of source files and a \jargon{load file}, a
Prolog file containing only use_module/[1,2] or ensure_loaded/1
directives, possibly with a definition of the \jargon{entry point} of
the program, the predicate that is normally used to start the program.
This file is often called \file{load.pl}. If the entry point is called
{\em go}, a typical session starts as:
\begin{code}
% swipl
<banner>
1 ?- [load].
<compilation messages>
true.
2 ?- go.
<program interaction>
\end{code}
When using Windows, the user may open \file{load.pl} from the Windows
explorer, which will cause \program{swipl-win.exe} to be started in the
directory holding \file{load.pl}. Prolog loads \file{load.pl} before
entering the top level. If Prolog is started from an interactive shell,
one may choose the type \texttt{swipl -s load.pl}.
\subsection{For running the result} \label{sec:runcomp}
There are various options if you want to make your program ready
for real usage. The best choice depends on whether the program
is to be used only on machines holding the SWI-Prolog development
system, the size of the program, and the operating system (Unix
vs.\ Windows).
\subsubsection{Using PrologScript} \label{sec:plscript}
A Prolog source file can be used directly as a Unix program using the
Unix \verb$#!$ magic start. The Unix \verb$#!$ magic is allowed because
if the first letter of a Prolog file is \verb$#$, the first line is
treated as a comment.\footnote{The \texttt{\#}-sign can be the legal
start of a normal Prolog clause. In the unlikely case this is required,
leave the first line blank or add a header comment.} To create a Prolog
script, use one of the two alternatives below as first line. The first
can be used to bind a script to a specific Prolog installation, while
the latter uses the default prolog installed in \verb"$PATH".
\begin{code}
#!/path/to/swipl
#!/usr/bin/env swipl
\end{code}
The interpretation of arguments to the executable in the
\jargon{HashBang} line differs between Unix-derived systems. For
portability, the \verb$#!$ must be followed immediately with an absolute
path to the executable and should have none or one argument. Neither the
executable path, nor the argument shall use quotes or spaces. When
started this way, the Prolog flag \prologflag{argv} contains the command
line arguments that follow the script invocation.
Starting with version 7.5.8, initialization/2 support the \arg{When}
options \const{program} and \const{main}, allowing for the following
definition of a Prolog script that evaluates an arithmetic expression on
the command line. Note that main/0 is defined lib the library
\pllib{main}. It calls main/1 with the command line arguments after
disabling signal handling.
\begin{code}
#!/usr/bin/env swipl
:- initialization(main, main).
main(Argv) :-
concat_atom(Argv, ' ', SingleArg),
term_to_atom(Term, SingleArg),
Val is Term,
format('~w~n', [Val]).
\end{code}
And here are two example runs:
\begin{code}
% ./eval 1+2
3
% ./eval foo
ERROR: is/2: Arithmetic: `foo/0' is not a function
\end{code}
Prolog script may be launched for debugging or inspection purposes using
the \cmdlineoption{-l} or \cmdlineoption{-t}. For example,
\cmdlineoption{-l} merely loads the script, ignoring \const{main} and
\const{program} initialization.
\begin{code}
swipl -l eval 1+1
<banner>
?- main.
2
true.
?-
\end{code}
We can also force the program to enter the interactive toplevel after
the application is completed using \exam{-t prolog}:
\begin{code}
swipl -t prolog eval 1+1
2
?-
\end{code}
The Windows version simply ignores the \verb$#!$ line.\footnote{Older
versions extracted command line arguments from the \jargon{HashBang}
line. As of version 5.9 all relevant setup can be achieved using
\jargon{directives}. Due to the compatibility issues around
\jargon{HashBang} line processing, we decided to remove it completely.}
\subsubsection{Creating a shell script} \label{sec:shellscript}
With the introduction of \jargon{PrologScript} (see \secref{plscript}),
using shell scripts as explained in this section has become redundant
for most applications.
Especially on Unix systems and not-too-large applications, writing
a shell script that simply loads your application and calls the
entry point is often a good choice. A skeleton for the script is
given below, followed by the Prolog code to obtain the program
arguments.
\begin{code}
#!/bin/sh
base=<absolute-path-to-source>
PL=swipl
exec $PL -q -f "$base/load" --
\end{code}
\begin{code}
:- initialization go.
go :-
current_prolog_flag(argv, Arguments),
go(Arguments).
go(Args) :-
...
\end{code}
On Windows systems, similar behaviour can be achieved by creating a
shortcut to Prolog, passing the proper options or writing a \fileext{bat}
file.
\subsubsection{Creating a saved state} \label{sec:makestate}
For larger programs, as well as for programs that are required to run on
systems that do not have the SWI-Prolog development system installed,
creating a saved state is the best solution. A saved state is created
using qsave_program/[1,2] or the \cmdlineoption{-c} command line option.
A saved state is a file containing machine-independent\footnote{The
saved state does not depend on the CPU instruction set or endianness.
Saved states for 32- and 64-bits are not compatible. Typically, saved
states only run on the same version of Prolog on which they have been
created.} intermediate code in a format dedicated for fast loading.
Optionally, the emulator may be integrated in the saved state, creating
a single file, but machine-dependent, executable. This process is
described in \chapref{runtime}.
\subsubsection{Compilation using the -c command line option}
\label{sec:cmdlinecomp}
This mechanism loads a series of Prolog source files and then creates
a saved state as qsave_program/2 does. The command syntax is:
\begin{code}
% swipl [option ...] [-o output] -c file.pl ...
\end{code}
The \arg{options} argument are options to qsave_program/2 written in
the format below. The option names and their values are described with
qsave_program/2.
\begin{quote}
\verb$--${\em option-name}\verb$=$\em{option-value}
\end{quote}
For example, to create a stand-alone executable that starts by executing
\nopredref{main}{0} and for which the source is loaded through
\file{load.pl}, use the command
\begin{code}
% swipl --goal=main --stand_alone=true -o myprog -c load.pl
\end{code}
This performs exactly the same as executing
\begin{code}
% swipl
<banner>
?- [load].
?- qsave_program(myprog,
[ goal(main),
stand_alone(true)
]).
?- halt.
\end{code}
\section{Environment Control (Prolog flags)} \label{sec:flags}
The predicates current_prolog_flag/2 and set_prolog_flag/2 allow the
user to examine and modify the execution environment. It provides
access to whether optional features are available on this version,
operating system, foreign code environment, command line arguments,
version, as well as runtime flags to control the runtime behaviour
of certain predicates to achieve compatibility with other Prolog
environments.
\begin{description}
\predicate[ISO]{current_prolog_flag}{2}{?Key, -Value}
The predicate current_prolog_flag/2 defines an interface to installation
features: options compiled in, version, home, etc. With both arguments
unbound, it will generate all defined Prolog flags. With \arg{Key}
instantiated, it unifies \arg{Value} with the value of the Prolog flag
or fails if the \arg{Key} is not a Prolog flag.
Flags marked \jargon{changeable} can be modified by the user using
set_prolog_flag/2. Flag values are typed. Flags marked as \const{bool}
can have the values \const{true} or \const{false}. The predicate
create_prolog_flag/3 may be used to create flags that describe or
control behaviour of libraries and applications. The library
\pllib{settings} provides an alternative interface for managing
notably application parameters.
Some Prolog flags are not defined in all versions, which is normally
indicated in the documentation below as \textit{``if present and
true''}. A boolean Prolog flag is true iff the Prolog flag is present
{\bf and} the \arg{Value} is the atom \const{true}. Tests for such flags
should be written as below:
\begin{code}
( current_prolog_flag(windows, true)
-> <Do MS-Windows things>
; <Do normal things>
)
\end{code}
Some Prolog flags are scoped to a source file. This implies that if they
are set using a directive inside a file, the flag value encountered when
loading of the file started is restored when loading of the file is
completed. Currently, the following flags are scoped to the source file:
\prologflag{generate_debug_info} and \prologflag{optimise}.
A new thread (see \secref{threads}) \emph{copies} all flags from the
thread that created the new thread (its \jargon{parent}).\footnote{This
is implemented using the copy-on-write technique.} As a consequence,
modifying a flag inside a thread does not affect other threads.
\begin{description}
\prologflagitem{abi_version}{dict}{r}
The flag value is a dict with keys that describe the version of
the various Application Binary Interface (ABI) components. See
\secref{abi-versions} for details.
\prologflagitem{access_level}{atom}{rw}
This flag defines a normal `user' view (\const{user}, default) or a
`system' view. In system view all system code is fully accessible as if
it was normal user code. In user view, certain operations are not
permitted and some details are kept invisible. We leave the exact
consequences undefined, but, for example, system code can be traced
using system access and system predicates can be redefined.
\prologflagitem{address_bits}{integer}{r}
Address size of the hosting machine. Typically 32 or 64. Except for
the maximum stack limit, this has few implications to the user. See
also the Prolog flag \prologflag{arch}.
\prologflagitem{agc_margin}{integer}{rw}
If this amount of atoms possible garbage atoms exist perform atom
garbage collection at the first opportunity. Initial value is 10,000.
May be changed. A value of 0 (zero) disables atom garbage collection.
See also PL_register_atom().\footnote{Given that SWI-Prolog has no
limit on the length of atoms, 10,000 atoms may still occupy a lot of
memory. Applications using extremely large atoms may wish to call
garbage_collect_atoms/0 explicitly or lower the margin.}
\prologflagitem{allow_dot_in_atom}{bool}{rw}
If \const{true} (default \const{false}), dots may be embedded into atoms
that are not quoted and start with a letter. The embedded dot
\emph{must} be followed by an identifier continuation character (i.e.,
letter, digit or underscore). The dot is allowed in identifiers in many
languages, which can make this a useful flag for defining DSLs. Note
that this conflicts with cascading functional notation. For example,
\exam{Post.meta.author} is read as \exam{.(Post, 'meta.author'} if this
flag is set to \const{true}.
\prologflagitem{allow_variable_name_as_functor}{bool}{rw}
If true (default is false), \exam{Functor(arg)} is read as if it were
written \exam{'Functor'(arg)}. Some applications use the Prolog read/1
predicate for reading an application-defined script language. In these
cases, it is often difficult to explain to non-Prolog users of the
application that constants and functions can only start with a lowercase
letter. Variables can be turned into atoms starting with an uppercase
atom by calling read_term/2 using the option \const{variable_names} and
binding the variables to their name. Using this feature, F(x) can be
turned into valid syntax for such script languages. Suggested by Robert
van Engelen. SWI-Prolog specific.
\prologflagitem{android}{bool}{r}
If present and true, it indicates we are running on the
Android OS. The flag is not present in other operating systems.
\prologflagitem{android_api}{integer}{r}
If running on Android, it indicates the compile-time API
Level defined by the C macro \verb$__ANDROID_API__$. It is not
defined if running on other operating systems. The API level may
or may not match the API level of the running device, since it is
the API level at compile time.
\prologflagitem{answer_write_options}{term}{rw}
This argument is given as option-list to write_term/2 for printing results
of queries. Default is \texttt{[quoted(true), portray(true),
max_depth(10), attributes(portray)]}.
\prologflagitem{apple}{bool}{r}
\index{MacOS}%
If present and \const{true}, the operating system is MacOSX. Defined if
the C compiler used to compile this version of SWI-Prolog defines
\verb$__APPLE__$. Note that the \prologflag{unix} is also defined
for MacOSX.
\prologflagitem{arch}{atom}{r}
Identifier for the hardware and operating system SWI-Prolog is running
on. Used to select foreign files for the right architecture. See also
\secref{shlib} and file_search_path/2.
\prologflagitem{argv}{list}{rw}
List is a list of atoms representing the application command line
arguments. Application command line arguments are those that have
\emph{not} been processed by Prolog during its initialization. Note that
Prolog's argument processing stops at \const{--} or the first non-option
argument. See also \prologflag{os_argv}.\footnote{Prior to version
6.5.2, \prologflag{argv} was defined as \prologflag{os_argv} is now.
The change was made for compatibility reasons and because the current
definition is more practical.}
\prologflagitem{associated_file}{atom}{r}
Set if Prolog was started with a prolog file as argument. Used by
e.g., edit/0 to edit the initial file.
\prologflagitem{autoload}{atom}{rw}
This flag controls autoloading predicates based on autoload/1 and
autoload/2 as well as predicates from \jargon{autoload libraries}.
It has the following values:
\begin{description}
\termitem{false}{}
Predicates are never auto-loaded. If predicates have been imported
before using autoload/1,2, load the referenced files immediately using
use_module/1,2. Note that most of the development utilities such as
listing/1 have to be explicitly imported before they can be used at the
toplevel.
\termitem{explicit}{}
Do not autoload from \jargon{autoload libraries}, but do use lazy
loading for predicates imported using autoload/1,2.
\termitem{user}{}
As \const{false}, but to autoload library predicates into the global
\const{user} module. This makes the development tools and library
implicitly available to the toplevel, but not to modules.
\termitem{user_or_explicit}{}
Combines \const{explicit} with \const{user}, providing lazy loading
of predicates imported using autoload/1,2 and implicit access to the
whole library for the toplevel.
\termitem{true}{}
Provide full autoloading everywhere. This is the default.
\end{description}
\prologflagitem{back_quotes}{codes,chars,string,symbol_char}{rw}
Defines the term-representation for back-quoted material. The default
is \const{codes}. If \cmdlineoption{--traditional} is given, the default
is \const{symbol_char}, which allows using \verb$`$ in operators
composed of symbols.\footnote{Older versions had a boolean flag
\const{backquoted_strings}, which toggled between \const{string} and
\const{symbol_char}} See also \secref{strings}.
\prologflagitem{backtrace}{bool}{rw}
If \const{true} (default), print a backtrace on an uncaught exception.
\prologflagitem{backtrace_depth}{integer}{rw}
If backtraces on errors are enabled, this flag defines the maximum
number of frames that is printed (default~20).
\prologflagitem{backtrace_goal_depth}{integer}{rw}
The frame of a backtrace is printed after making a shallow copy of the
goal. This flag determines the depth to which the goal term is copied.
Default is `3'.
\prologflagitem{backtrace_show_lines}{bool}{rw}
If \const{true} (default), try to reconstruct the line number at which
the exception happened.
\prologflagitem{bounded}{bool}{r}
ISO Prolog flag. If \const{true}, integer representation is bound by
\prologflag{min_integer} and \prologflag{max_integer}. If \const{false}
integers can be arbitrarily large and the \prologflag{min_integer} and
\prologflag{max_integer} are not present. See \secref{artypes}.
\prologflagitem{break_level}{integer}{r}
Current break-level. The initial top level (started with
\cmdlineoption{-t}) has value 0. See break/0. This flag is absent from
threads that are not running a top-level loop.
\prologflagitem{c_cc}{atom}{rw}
Name of the C compiler used to compile SWI-Prolog. Normally either gcc
or cc. See \secref{plld}.
\prologflagitem{c_cflags}{atom}{rw}
CFLAGS used to compile SWI-Prolog. See \secref{plld}.
\prologflagitem{c_ldflags}{atom}{rw}
LDFLAGS used to link SWI-Prolog. See \secref{plld}.
\prologflagitem{c_libplso}{atom}{rw}
Libraries needed to link extensions (shared object, DLL) to SWI-Prolog.
Typically empty on ELF systems and \const{-lswipl} on COFF-based
systems. See \secref{plld}.
\prologflagitem{c_libs}{atom}{rw}
Libraries needed to link executables that embed SWI-Prolog. Typically
\const{-lswipl} if the SWI-Prolog kernel is a shared (DLL). If the
SWI-Prolog kernel is in a static library, this flag also contains the
dependencies.
\prologflagitem{char_conversion}{bool}{rw}
Determines whether character conversion takes place while reading terms.
See also char_conversion/2.
\prologflagitem{character_escapes}{bool}{rw}
If \const{true} (default), read/1 interprets \verb$\$ escape sequences
in quoted atoms and strings. May be changed. This flag is local to the
module in which it is changed. See \secref{charescapes}.
\prologflagitem{colon_sets_calling_context}{bool}{ro}
Using the construct <module>:<goal> sets the \jargon{calling context}
for executing <goal>. This flag is defined by ISO/IEC 13211-2 (Prolog
modules standard). See \secref{modules}.
\prologflagitem{color_term}{bool}{rw}
This flag is managed by library \pllib{ansi_term}, which is loaded at
startup if the two conditions below are both true. Note that this
implies that setting this flag to \const{false} from the system or
personal initialization file (see \secref{initfile} disables colored
output. The predicate message_property/2 can be used to control the
actual color scheme depending in the message type passed to
print_message/2.
\begin{itemize}
\item \verb$stream_property(current_output, tty(true))$
\item \verb$\+ current_prolog_flag(color_term, false)$
\end{itemize}
\prologflagitem{compile_meta_arguments}{atom}{rw}
This flag controls compilation of arguments passed to meta-calls marked
`0' or `\chr{^}' (see meta_predicate/1). Supported values are:
\begin{description}
\termitem{false}{}
(default). Meta-arguments are passed verbatim. If the argument is a
control structure ((A,B), (A;B), (A->B;C), etc.) it is compile to an
temporary clause allocated on the environment stack when the
meta-predicate is called.
\termitem{control}{}
Compile meta-arguments that contain control structures to an auxiliary
predicate. This generally improves performance as well as the debugging
experience.
\termitem{always}{}
Always create an intermediate clause, even for system
predicates.\footnote{This may be used in the future for
replacing the normal head of the generated predicate with a special
reference (similar to database references as used by, e.g., assert/2)
that provides direct access to the executable code, thus avoiding
runtime lookup of predicates for meta-calling.}
\end{description}
\prologflagitem{compiled_at}{atom}{r}
Describes when the system has been compiled. Only available if the
C compiler used to compile SWI-Prolog provides the __DATE__ and __TIME__
macros.
\prologflagitem{console_menu}{bool}{r}
Set to \const{true} in \program{swipl-win.exe} to indicate that the console
supports menus. See also \secref{plwin}.
\prologflagitem{cpu_count}{integer}{rw}
Number of physical CPUs or cores in the system. The flag is marked
read-write both to allow pretending the system has more or less
processors. See also thread_setconcurrency/2 and the library
\pllib{thread}. This flag is not available on systems where we do not
know how to get the number of CPUs. This flag is not included in a saved
state (see qsave_program/1).
\prologflagitem{dde}{bool}{r}
Set to \const{true} if this instance of Prolog supports DDE as
described in \secref{DDE}.
\prologflagitem{debug}{bool}{rw}
Switch debugging mode on/off. If debug mode is activated the system
traps encountered spy points (see spy/1) and break points.
In addition, last-call optimisation is disabled and the system is
more conservative in destroying choice points to simplify debugging.
Disabling these optimisations can cause the system to run out of memory
on programs that behave correctly if debug mode is off.
\prologflagitem{debug_on_error}{bool}{rw}
If \const{true}, start the tracer after an error is detected.
Otherwise just continue execution. The goal that raised the error will
normally fail. See also the Prolog flag \prologflag{report_error}.
Default is \const{true}.
\prologflagitem{debugger_show_context}{bool}{rw}
If \const{true}, show the context module while printing a stack-frame in
the tracer. Normally controlled using the `C' option of the tracer.
\prologflagitem{debugger_write_options}{term}{rw}
This argument is given as option-list to write_term/2 for printing goals
by the debugger. Modified by the `w', `p' and `<N> d' commands of the
debugger. Default is \texttt{[quoted(true), portray(true),
max_depth(10), attributes(portray)]}.
\prologflagitem{dialect}{atom}{r}
Fixed to \const{swi}. The code below is a reliable and portable way to
detect SWI-Prolog.
\begin{code}
is_dialect(swi) :-
catch(current_prolog_flag(dialect, swi), _, fail).
\end{code}
\prologflagitem{double_quotes}{codes,chars,atom,string}{rw}
This flag determines how double quoted strings are read by Prolog and is
---like \prologflag{character_escapes} and \prologflag{back_quotes}---
maintained for each module. The default is \const{string}, which
produces a string as described in \secref{strings}. If
\cmdlineoption{--traditional} is given, the default is \const{codes},
which produces a list of character codes, integers that represent a
Unicode code-point. The value \const{chars} produces a list of
one-character atoms and the value \const{atom} makes double quotes the
same as single quotes, creating a atom. See also \secref{extensions}.
\prologflagitem{editor}{atom}{rw}
Determines the editor used by edit/1. See \secref{customedit} for
details on selecting the editor used.
\prologflagitem{emacs_inferior_process}{bool}{r}
If true, SWI-Prolog is running as an \jargon{inferior process} of
(GNU/X-)Emacs. SWI-Prolog assumes this is the case if the environment
variable \env{EMACS} is \const{t} and \env{INFERIOR} is \const{yes}.
\prologflagitem{encoding}{atom}{rw}
Default encoding used for opening files in \const{text} mode. The
initial value is deduced from the environment. See \secref{encoding} for
details.
\prologflagitem{executable}{atom}{r}
Pathname of the running executable. Used by qsave_program/2 as
default emulator.
\prologflagitem{exit_status}{integer}{r}
Set by halt/1 to its argument, making the exit status available to
hooks registered with at_halt/1.
\prologflagitem{file_name_case_handling}{atom}{rw}
This flag defines how Prolog handles the case of file names. The flag is
used for case normalization and to determine whether two names refer to
the same file.\bug{Note that file name case handling is typically a
properly of the filesystem, while Prolog only has a global flag to
determine its file handling.} It has one of the following values:
\begin{description}
\termitem{case_sensitive}{}
The filesystem is fully case sensitive. Prolog does not perform
any case modification or case insensitive matching. This is the
default on Unix systems.
\termitem{case_preserving}{}
The filesystem is case insensitive, but it preserves the case with
which the user has created a file. This is the default on Windows
systems.
\termitem{case_insensitive}{}
The filesystem doesn't store or match case. In this scenario Prolog
maps all file names to lower case.
\end{description}
\prologflagitem{file_name_variables}{bool}{rw}
If \const{true} (default \const{false}), expand \file{\$\arg{varname}}
and \chr{~} in arguments of built-in predicates that accept a file
name (open/3, exists_file/1, access_file/2, etc.). The predicate
expand_file_name/2 can be used to expand environment variables and
wildcard patterns. This Prolog flag is intended for backward
compatibility with older versions of SWI-Prolog.
\prologflagitem{file_search_cache_time}{number}{rw}
Time in seconds for which search results from absolute_file_name/3 are
cached. Within this time limit, the system will first check that the old
search result satisfies the conditions. Default is 10 seconds, which
typically avoids most repetitive searches for (library) files during
compilation. Setting this value to 0 (zero) disables the cache.
\prologflagitem{float_max}{float}{r}
The biggest representable floating point number.
\prologflagitem{float_max_integer}{float}{r}
The highest integer that can be represented precisely as a floating
point number.
\prologflagitem{float_min}{float}{r}
The smallest representable floating point number above 0.0. See also
\funcref{nexttoward}{2}.
\prologflagitem{float_overflow}{atom}{rw}
One of \const{error} (default) or \const{infinity}. The first is ISO
compliant. Using \const{infinity}, floating point overflow is mapped
to positive or negative \const{Inf}. See \secref{ieee-float}.
\prologflagitem{float_rounding}{atom}{rw}
Defines how arithmetic rounds to a float. Defined values are
\const{to_nearest} (default), \const{to_positive}, \const{to_negative}
or \const{to_zero}. For most scenarios the function
\funcref{roundtoward}{2} provides a safer and faster alternative.
\prologflagitem{float_undefined}{atom}{rw}
One of \const{error} (default) or \const{nan}. The first is ISO
compliant. Using \const{nan}, undefined operations such as
\term{sqrt}{-2.0} is mapped to \const{NaN}. See \secref{ieee-float}.
\prologflagitem{float_underflow}{atom}{rw}
One of \const{error} or \const{ignore} (default). The second is ISO
compliant, binding the result to 0.0.
\prologflagitem{float_zero_div}{atom}{rw}
One of \const{error} (default) or \const{infinity}. The first is ISO
compliant. Using \const{infinity}, division by 0.0 is mapped to positive
or negative \const{Inf}. See \secref{ieee-float}.
\prologflagitem{gc}{bool}{rw}
If true (default), the garbage collector is active. If false, neither
garbage collection, nor stack shifts will take place, even not on
explicit request. May be changed.
\prologflagitem{gc_thread}{bool}{r}
If \const{true} (default if threading is enabled), atom and
clause garbage collection are executed in a separate thread with the
\jargon{alias} \const{gc}. Otherwise the thread that detected sufficient
garbage executes the garbage collector. As running these global
collectors may take relatively long, using a separate thread improves
real time behaviour. The \const{gc} thread can be controlled using
set_prolog_gc_thread/1.
\prologflagitem{generate_debug_info}{bool}{rw}
If \const{true} (default) generate code that can be debugged using
trace/0, spy/1, etc. Can be set to \const{false} using the
\cmdlineoption{--no-debug}. This flag is scoped within a source file.
Many of the libraries have
\verb$:- set_prolog_flag(generate_debug_info, false)$ to hide their
details from a normal trace.%
\footnote{In the current implementation this only causes a flag
to be set on the predicate that causes children to be
hidden from the debugger. The name anticipates
further changes to the compiler.}
\prologflagitem{gmp_version}{integer}{r}
If Prolog is linked with GMP, this flag gives the major version of the
GMP library used. See also \secref{gmpforeign}.
\prologflagitem{gui}{bool}{r}
Set to \const{true} if XPCE is around and can be used for graphics.
\prologflagitem{history}{integer}{rw}
If $\arg{integer}> 0$, support Unix \program{csh(1)}-like history as
described in \secref{history}. Otherwise, only support reusing commands
through the command line editor. The default is to set this Prolog flag
to 0 if a command line editor is provided (see Prolog flag
\prologflag{readline}) and 15 otherwise.
\prologflagitem{home}{atom}{r}
SWI-Prolog's notion of the home directory. SWI-Prolog uses its home
directory to find its startup file as \file{<home>/boot.prc} and to find
its library as \file{<home>/library}. Some installations may put
architecture independent files in a \jargon{shared home} and also
define \prologflag{shared_home}. System files can be found using
absolute_file_name/3 as \term{swi}{file}. See file_search_path/2.
\prologflagitem{hwnd}{integer}{r}
In \program{swipl-win.exe}, this refers to the MS-Windows window handle of
the console window.
\prologflagitem{integer_rounding_function}{down,toward_zero}{r}
ISO Prolog flag describing rounding by \verb$//$ and \verb$rem$ arithmetic
functions. Value depends on the C compiler used.
\prologflagitem{iso}{bool}{rw}
Include some weird ISO compatibility that is incompatible with normal
SWI-Prolog behaviour. Currently it has the following effect:
\begin{itemize}
\item The \functor{/}{2} (float division) {\em always} returns a
float, even if applied to integers that can be divided.
\item In the standard order of terms (see \secref{standardorder}),
all floats are before all integers.
\item atom_length/2 yields a type error if the first
argument is a number.
\item clause/[2,3] raises a permission error when accessing static
predicates.
\item abolish/[1,2] raises a permission error when accessing static
predicates.
\item Syntax is closer to the ISO standard:
\begin{itemize}
\item Unquoted commas and bars appearing as atoms
are not allowed. Instead of
\exam{f(,,a)} now write \exam{f(',',a)}.
Unquoted commas can only be used to separate arguments in
functional notation and list notation, and as a conjunction operator.
Unquoted bars can only appear within lists to separate head
and tail, like \exam{[Head|Tail]}, and as infix operator for
alternation in grammar rules, like \exam{a --> b | c.}
\item Within functional notation and list notation terms must have priority
below 1000. That means that rules and control constructs
appearing as arguments need bracketing.
A term like \exam{[a :- b, c].} must now be disambiguated
to mean \exam{[(a :- b), c].} or \exam{[(a :- b, c)].}
\item Operators appearing as operands must be bracketed.
Instead of \exam{X == -, true.} write \exam{X == (-), true.}
Currently, this is not entirely enforced.
\item Backslash-escaped newlines are interpreted according to
the ISO standard. See \secref{charescapes}.
\end{itemize}
\end{itemize}
\prologflagitem{large_files}{bool}{r}
If present and \const{true}, SWI-Prolog has been compiled with
\jargon{large file support} (LFS) and is capable of accessing files larger
than 2GB. This flag is always \const{true} on 64-bit hardware and true
on 32-bit hardware if the configuration detected support for LFS. Note
that it may still be the case that the \jargon{file system} on which a
particular file resides puts limits on the file size.
\prologflagitem{last_call_optimisation}{bool}{rw}
Determines whether or not last-call optimisation is enabled. Normally
the value of this flag is the negation of the \prologflag{debug} flag.
As programs may run out of stack if last-call optimisation is omitted,
it is sometimes necessary to enable it during debugging.
\prologflagitem{max_answers_for_subgoal}{integer}{rw}
Limit the number of answers in a table. The atom
\const{infinite} clears the flag. By default this flag is not defined.
See \secref{tabling-restraints} for details.
\prologflagitem{max_answers_for_subgoal_action}{atom}{rw}
The action taken when a table reaches the number of
answers specified in \prologflag{max_answers_for_subgoal}. Supported values
are \const{bounded_rationality}, \const{error} (default) or
\const{suspend}.
\prologflagitem{max_arity}{unbounded}{r}
ISO Prolog flag describing there is no maximum arity to compound terms.
\prologflagitem{max_integer}{integer}{r}
Maximum integer value if integers are \emph{bounded}. See also
the flag \prologflag{bounded} and \secref{artypes}.
\prologflagitem{max_rational_size}{integer}{rw}
Limit the size in bytes for rational numbers. This \jargon{tripwire} can
be used to identify cases where setting the Prolog flag
\prologflag{prefer_rationals} to \const{true} creates excessively big
rational numbers and, if precision is not required, one should use
floating point arithmetic.
\prologflagitem{max_rational_size_action}{atom}{rw}
Action when the \prologflag{max_rational_size} tripwire is exceeded.
Possible values are \const{error} (default), which throws a tripwire
resource error and \const{float}, which converts the rational number
into a floating point number. Note that rational numbers may exceed the
range for floating point numbers.
\prologflagitem{max_table_answer_size}{integer}{rw}
Limit the size of an answer substitution for tabling. The atom
\const{infinite} clears the flag. By default this flag is not defined.
See \secref{tabling-restraints} for details.
\prologflagitem{max_table_answer_size_action}{atom}{rw}
The action taken if an answer substitution larger than
\prologflag{max_table_answer_size} is added to a table. Supported values
are \const{error} (default), \const{bounded_rationality},
\const{suspend} and \const{fail}.
\prologflagitem{max_table_subgoal_size}{integer}{rw}
Limit the size of a goal term accessing a table. The atom
\const{infinite} clears the flag. By default this flag is not defined.
See \secref{tabling-restraints} for details.
\prologflagitem{max_table_subgoal_size_action}{atom}{rw}
The action taken if a tabled goal exceeds
\prologflag{max_table_subgoal_size}. Supported values
are \const{error} (default), \const{abstract} and \const{suspend}.
\prologflagitem{max_tagged_integer}{integer}{r}
Maximum integer value represented as a `tagged' value. Tagged integers
require one word storage. Larger integers are represented as `indirect data'
and require significantly more space.
\prologflagitem{message_context}{list(atom)}{rw}
Context information to add to messages of the levels \const{error} and
\const{warning}. The list may contain the elements \const{thread} to
add the thread that generates the message to the message, \const{time}
or \term{time}{Format} to add a time stamp. The default time format
is \verb$%T.%3f$. The default is \exam{[thread]}. See also format_time/3
and print_message/2.
\prologflagitem{min_integer}{integer}{r}
Minimum integer value if integers are \emph{bounded}. See also
the flag \prologflag{bounded} and \secref{artypes}.
\prologflagitem{min_tagged_integer}{integer}{r}
Start of the tagged-integer value range.
\prologflagitem{mitigate_spectre}{bool}{rw}
When \const{true} (default \const{false}), enforce mitigation against
the
\href{https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)}{Spectre}
timing-based security vulnerability. Spectre based attacks can extract
information from memory owned by the process that should remain
invisible, such as passwords or the private key of a web server. The
attacks work by causing speculative access to sensitive data, and
leaking the data via side-channels such as differences in the duration
of successive instructions. An example of a potentially vulnerable
application is \href{https://swish.swi-prolog.org}{SWISH}. SWISH
allows users to run Prolog code while the swish server must protect
the privacy of other users as well as its HTTPS private keys, cookies
and passwords.
Currently, enabling this flag reduces the resolution of get_time/1 and
statistics/2 CPU time to $20\mu{}s$.
\textbf{WARNING}: Although a coarser timer makes a successful attack
of this type harder, it does not reliably prevent such attacks in
general. Full mitigation may require compiler support to disable
speculative access to sensitive data.
\prologflagitem{occurs_check}{atom}{rw}
This flag controls unification that creates an infinite tree (also
called \jargon{cyclic term}) and can have three values. Using
\const{false} (default), unification succeeds, creating an infinite
tree. Using \const{true}, unification behaves as unify_with_occurs_check/2,
failing silently. Using \const{error}, an attempt to create a cyclic
term results in an \except{occurs_check} exception. The latter
is intended for debugging unintentional creations of cyclic terms. Note
that this flag is a global flag modifying fundamental behaviour of
Prolog. Changing the flag from its default may cause libraries to stop
functioning properly.
\prologflagitem{open_shared_object}{bool}{r}
If true, open_shared_object/2 and friends are implemented, providing
access to shared libraries (\fileext{so} files) or dynamic link
libraries (\fileext{DLL} files).
\prologflagitem{optimise}{bool}{rw}
If \const{true}, compile in optimised mode. The initial value is
\const{true} if Prolog was started with the \cmdlineoption{-O}
command line option. The \prologflag{optimise} flag is scoped to
a source file.
Currently optimised compilation implies compilation of arithmetic,
and deletion of redundant true/0 that may result from expand_goal/2.
Later versions might imply various other optimisations such as
integrating small predicates into their callers, eliminating constant
expressions and other predictable constructs. Source code optimisation
is never applied to predicates that are declared dynamic (see
dynamic/1).
\prologflagitem{os_argv}{list}{rw}
List is a list of atoms representing the command line arguments used to
invoke SWI-Prolog. Please note that {\bf all} arguments are included
in the list returned. See \prologflag{argv} to get the application
options.
\prologflagitem{packs}{bool}{r}
If \const{true}, extension packs (add-ons) are attached. Can be set to
\const{false} using the \cmdlineoption{--no-packs}.
\prologflagitem{pid}{int}{r}
Process identifier of the running Prolog process. Existence of this
flag is implementation-defined.
\prologflagitem{pipe}{bool}{rw}
If true, \exam{open(pipe(command), mode, Stream)}, etc.\ are supported.
Can be changed to disable the use of pipes in applications testing this
feature. Not recommended.
\prologflagitem{portable_vmi}{bool}{rw}
If \const{true} (default), generate \fileext{qlf} files and saved states
that run both on 32 bit and 64-bit hardware. If \const{false}, some
optimized virtual machine instructions are only used if the integer
argument is within the range of a tagged integer for 32-bit machines.
\prologflagitem{posix_shell}{atom}{rw}
Path to a POSIX compatible shell. This default is typically
\file{/bin/sh}. This flag is used by shell/1 and qsave_program/2.
\prologflagitem{prefer_rationals}{bool}{rw}
Only provided if the system is compiled with unbounded and rational
arithmetic support (see \prologflag{bounded}). If \const{true},
prefer arithmetic to produce rational numbers over floats. This implies:
\begin{itemize}
\item Division (\funcref{/}{2}) of two integers produces a
rational number.
\item Power (\funcref{^}{2}) of two integers produces a
rational number, \emph{also} if the second operant is a
negative number. For example, \verb$2^(-2)$ evaluates to
\verb$1/4$.
\end{itemize}
Using \const{true} can create excessively large rational numbers. The
Prolog flag \prologflag{max_rational_size} can be used to detect and
act on this \jargon{tripwire}.
If \const{false}, rational numbers can only be created using the
functions \funcref{rational}{1}, \funcref{rationalize}{1} and
\funcref{rdiv}{2} or by reading them. See also
\prologflag{rational_syntax}, \secref{syntax-rational-numbers} and
\secref{rational}.
The current default is \const{false}. We consider changing this to
\const{true} in the future. Users are strongly encouraged to set
this flag to \const{true} and report issues this may cause.
\prologflagitem{print_write_options}{term}{rw}
Specifies the options for write_term/2 used by print/1 and print/2.
\prologflagitem{prompt_alternatives_on}{atom}{rw}
\index{prompt, alternatives}%
Determines prompting for alternatives in the Prolog top level. Default is
\const{determinism}, which implies the system prompts for alternatives
if the goal succeeded while leaving choice points. Many classical Prolog
systems behave as \const{groundness}: they prompt for alternatives if
and only if the query contains variables.
\prologflagitem{protect_static_code}{bool}{rw}
If \const{true} (default \const{false}), clause/2 does not operate on
static code, providing some basic protection from hackers that wish to
list the static code of your Prolog program. Once the flag is
\const{true}, it cannot be changed back to \const{false}. Protection
is default in ISO mode (see Prolog flag \prologflag{iso}). Note that
many parts of the development environment require clause/2 to work on
static code, and enabling this flag should thus only be used for
production code.
\prologflagitem{qcompile}{atom}{rw}
This option provides the default for the \term{qcompile}{+Atom} option
of load_files/2.
\prologflagitem{rational_syntax}{atom}{rw}
Determines the read and write syntax for rational numbers. Possible
values are \const{natural} (e.g., \exam{1/3}) or \const{compatibility}
(e.g., \exam{1r3}). The \const{compatibility} syntax is always accepted.
This flag is module sensitive.
The default for this flag is currently \const{compatibility}, which
reads and writes rational numbers as e.g., \exam{1r3}.\footnote{There is
still some discussion on the separating character. See
\secref{syntax-rational-numbers}.} We will consider \const{natural} as a
default in the future. Users are strongly encouraged to set this flag to
\const{natural} and report issues this may cause.
\prologflagitem{readline}{atom}{rw}
Specifies which form of command line editing is provided. Possible
values are below. The flag may be set from the user's init file (see
\secref{initgoal}) to one of \const{false}, \const{readline} or
\const{editline}. This causes the toplevel not to load a command line
editor (\const{false}) or load the specified one. If loading fails
the flag is set to \const{false}.
\begin{description}
\termitem{false}{}
No command line editing is available.
\termitem{readline}{}
The library \pllib{readline} is loaded, providing line editing based on
the GNU readline library.
\termitem{editline}{}
The library \pllib{editline} is loaded, providing line editing based on
the BSD libedit. This is the default if \pllib{editline} is available
and can be loaded.
\termitem{swipl_win}{}
SWI-Prolog uses its own console (\program{swipl-win.exe} on Windows,
the Qt based \program{swipl-win} on MacOS) which provides line editing.
\end{description}
\prologflagitem{report_error}{bool}{rw}
If \const{true}, print error messages; otherwise suppress them. May
be changed. See also the \prologflag{debug_on_error} Prolog flag.
Default is \const{true}, except for the runtime version.
\prologflagitem{resource_database}{atom}{r}
Set to the absolute filename of the attached state. Typically this is
the file \file{boot32.prc}, the file specified with \cmdlineoption{-x}
or the running executable. See also resource/3.
\prologflagitem{runtime}{bool}{r}
If present and \const{true}, SWI-Prolog is compiled with -DO_RUNTIME,
disabling various useful development features (currently the tracer and
profiler).
\prologflagitem{sandboxed_load}{bool}{rw}
If \const{true} (default \const{false}), load_files/2 calls hooks to
allow library(sandbox) to verify the safety of directives.
\prologflagitem{saved_program}{bool}{r}
If present and \const{true}, Prolog has been started from a state saved
with qsave_program/[1,2].
\prologflagitem{shared_home}{atom}{r}
Indicates that part of the SWI-Prolog system files are installed in
\file{<prefix>/share/swipl} instead of in the home at the
\file{<prefix>/lib/swipl}. This flag indicates the location of this
\emph{shared home} and the directory is added to the file search path
\const{swi}. See file_search_path/2 and the flag \prologflag{home}.
\prologflagitem{shared_object_extension}{atom}{r}
Extension used by the operating system for shared objects. \fileext{so}
for most Unix systems and \fileext{dll} for Windows. Used for locating
files using the \const{file_type} \const{executable}. See also
absolute_file_name/3.
\prologflagitem{shared_object_search_path}{atom}{r}
Name of the environment variable used by the system to search for shared
objects.
\prologflagitem{shared_table_space}{integer}{rw}
Space reserved for storing shared answer tables. See
\secref{tabling-shared} and the Prolog flag \prologflag{table_space}.
\prologflagitem{signals}{bool}{r}
Determine whether Prolog is handling signals (software interrupts). This
flag is \const{false} if the hosting OS does not support signal handling
or the command line option \cmdlineoption{--no-signals} is active. See
\secref{sigembedded} for details.
\prologflagitem{stack_limit}{int}{rw}
Limits the combined sizes of the Prolog stacks for the current thread.
See also \cmdlineoption{--stack-limit} and \secref{memlimit}.
\prologflagitem{stream_type_check}{atom}{rw}
Defines whether and how strictly the system validates that byte I/O
should not be applied to text streams and text I/O should not be applied
to binary streams. Values are \const{false} (no checking), \const{true}
(full checking) and \const{loose}. Using checking mode \const{loose}
(default), the system accepts byte I/O from text stream that use ISO
Latin-1 encoding and accepts writing text to binary streams.
\prologflagitem{string_stack_tripwire}{int}{rw}
Maintenance for foreign language string management. Prints a warning
if the string stack depth hits the tripwire value. See
\secref{foreign-strings} for details.
\prologflagitem{system_thread_id}{int}{r}
Available in multithreaded version (see \secref{threads}) where the
operating system provides system-wide integer thread identifiers. The
integer is the thread identifier used by the operating system for the
calling thread. See also thread_self/1.
\prologflagitem{table_incremental}{bool}{rw}
Set the default for whether to use incremental tabling or not.
Initially set to \const{false}. See table/1.
\prologflagitem{table_shared}{bool}{rw}
Set the default for whether to use shared tabling or not.
Initially set to \const{false}. See table/1.
\prologflagitem{table_space}{integer}{rw}
Space reserved for storing answer tables for \jargon{tabled predicates}
(see table/1).\bug{Currently only counts the space occupied by the
nodes in the answer tries.} When exceeded a
\term{resource_error}{table_space} exception is raised.
\prologflagitem{table_subsumptive}{bool}{rw}
Set the default choice between \jargon{variant} tabling and
\jargon{subsumptive} tabling. Initially set to \const{false}. See
table/1.
\prologflagitem{threads}{bool}{rw}
True when threads are supported. If the system is compiled without
thread support the value is \const{false} and read-only. Otherwise
the value is \const{true} unless the system was started with the
\cmdlineoption{--no-threads}. Threading may be disabled only if no
threads are running. See also the \prologflag{gc_thread} flag.
\prologflagitem{timezone}{integer}{r}
Offset in seconds west of GMT of the current time zone. Set at
initialization time from the \const{timezone} variable associated with
the POSIX tzset() function. See also format_time/3.
\prologflagitem{tmp_dir}{atom}{rw}
Path to the temporary directory. initialised from the environment
variable \const{TMP} or \const{TEMP} in windows. If this variable is not
defined a default is used. This default is typically \file{/tmp} or
\file{c:/temp} in windows.
\prologflagitem{toplevel_goal}{term}{rw}
Defines the goal that is executed after running the initialization goals
and entry point (see \cmdlineoption{-g}, initialization/2 and
\secref{plscript}. The initial value is \const{default}, starting a
normal interactive session. This value may be changed using the command
line option \cmdlineoption{-t}. The explicit value \const{prolog} is
equivalent to \const{default}. If \term{initialization}{Goal,main} is
used and the toplevel is \const{default}, the toplevel is set to
\const{halt} (see halt/0).
\prologflagitem{toplevel_list_wfs_residual_program}{bool}{rw}
If \const{true} (default) and the answer is \jargon{undefined} according
to the Well Founded Semantics (see \secref{WFS}), list the
\jargon{residual program} before the answer. Otherwise the answer
terminated with \textbf{undefined}. See also undefined/0.
\prologflagitem{toplevel_mode}{atom}{rw}
If \const{backtracking} (default), the toplevel backtracks after
completing a query. If \const{recursive}, the toplevel is implemented as
a recursive loop. This implies that global variables set using
b_setval/2 are maintained between queries. In \jargon{recursive}
mode, answers to toplevel variables (see \secref{topvars}) are kept
in backtrackable global variables and thus \textbf{not copied}. In
\jargon{backtracking} mode answers to toplevel variables are kept in
the recorded database (see \secref{recdb}).
The recursive mode has been added for interactive usage of CHR (see
\secref{chr}),\footnote{Suggested by Falco Nogatz} which maintains the
global constraint store in backtrackable global variables.
\prologflagitem{toplevel_print_anon}{bool}{rw}
If \const{true}, top-level variables starting with an underscore
(\chr{_}) are printed normally. If \const{false} they are hidden.
This may be used to hide bindings in complex queries from the top level.
\prologflagitem{toplevel_print_factorized}{bool}{rw}
If \const{true} (default \const{false}) show the internal sharing of
subterms in the answer substitution. The example below reveals internal
sharing of leaf nodes in \jargon{red-black trees} as implemented by the
\pllib{rbtrees} predicate \libpredref{rb_new}{1}:
\begin{code}
?- set_prolog_flag(toplevel_print_factorized, true).
?- rb_new(X).
X = t(_S1, _S1), % where
_S1 = black('', _G387, _G388, '').
\end{code}
If this flag is \const{false}, the \verb!% where! notation is still used
to indicate cycles as illustrated below. This example also shows that
the implementation reveals the internal cycle length, and \emph{not} the
minimal cycle length. Cycles of different length are indistinguishable
in Prolog (as illustrated by \verb!S == R!).
\begin{code}
?- S = s(S), R = s(s(R)), S == R.
S = s(S),
R = s(s(R)).
\end{code}
\prologflagitem{toplevel_prompt}{atom}{rw}
Define the prompt that is used by the interactive top level. The
following \verb$~$ (tilde) sequences are replaced:
\begin{center}
\begin{tabular}{ll}
\hline
\chr{~}m & \jargon{Type in} module if not \const{user}
(see module/1) \\
\chr{~}l & \jargon{Break level} if not 0
(see break/0) \\
\chr{~}d & \jargon{Debugging state} if not normal execution
(see debug/0, trace/0) \\
\chr{~}! & \jargon{History event} if history is enabled
(see flag \prologflag{history}) \\
\hline
\end{tabular}
\end{center}
\prologflagitem{toplevel_var_size}{int}{rw}
Maximum size counted in literals of a term returned as a binding for a
variable in a top-level query that is saved for re-use using the
\chr{$} variable reference. See \secref{topvars}.
\prologflagitem{trace_gc}{bool}{rw}
If \const{true} (default \const{false}), garbage collections and
stack-shifts will be reported on the terminal. May be changed. Values
are reported in bytes as $G$+$T$, where $G$ is the global stack value
and $T$ the trail stack value. `Gained' describes the number of bytes
reclaimed. `used' the number of bytes on the stack after GC and `free'
the number of bytes allocated, but not in use. Below is an example
output.
\begin{code}
% GC: gained 236,416+163,424 in 0.00 sec;
used 13,448+5,808; free 72,568+47,440
\end{code}
\prologflagitem{traditional}{bool}{r}
Available in SWI-Prolog version~7. If \const{true}, `traditional'
mode has been selected using \cmdlineoption{--traditional}. Notice
that some SWI7 features, like the functional notation on dicts, do not
work in this mode. See also \secref{extensions}.
\prologflagitem{tty_control}{bool}{rw}
Determines whether the terminal is switched to raw mode for
get_single_char/1, which also reads the user actions for the trace. May
be set. If this flag is \const{false} at startup, command line editing
is disabled. See also the \cmdlineoption{--no-tty} command line option.
\prologflagitem{unix}{bool}{r}
\index{unix}%
If present and \const{true}, the operating system is some version of
Unix. Defined if the C compiler used to compile this version of
SWI-Prolog either defines \verb$__unix__$ or \const{unix}. On other
systems this flag is not available. See also \prologflag{apple}
and \prologflag{windows}.
\prologflagitem{unknown}{fail,warning,error}{rw}
Determines the behaviour if an undefined procedure is encountered. If
\const{fail}, the predicate fails silently. If \const{warn}, a warning
is printed, and execution continues as if the predicate was not defined,
and if \const{error} (default), an \except{existence_error} exception is
raised. This flag is local to each module and inherited from the
module's \jargon{import-module}. Using default setup, this implies that
normal modules inherit the flag from \const{user}, which in turn
inherit the value \const{error} from \const{system}. The user may
change the flag for module \const{user} to change the default for all
application modules or for a specific module. It is strongly advised
to keep the \const{error} default and use dynamic/1 and/or multifile/1
to specify possible non-existence of a predicate.
\prologflagitem{unload_foreign_libraries}{bool}{rw}
If \const{true} (default \const{false}), unload all loaded foreign
libraries. Default is \const{false} because modern OSes reclaim the
resources anyway and unloading the foreign code may cause registered
hooks to point to no longer existing data or code.
\prologflagitem{user_flags}{Atom}{rw}
Define the behaviour of set_prolog_flag/2 if the flag is not known.
Values are \const{silent}, \const{warning} and \const{error}. The first
two create the flag on-the-fly, where \const{warning} prints a message.
The value \const{error} is consistent with ISO: it raises an existence
error and does not create the flag. See also create_prolog_flag/3. The
default is \const{silent}, but future versions may change that.
Developers are encouraged to use another value and ensure proper use
of create_prolog_flag/3 to create flags for their library.
\prologflagitem{var_prefix}{bool}{rw}
If \const{true} (default \const{false}), variables must start with an
underscore (\chr{_}). May be changed. This flag is local to the
module in which it is changed. See \secref{varprefix}.
\prologflagitem{verbose}{atom}{rw}
This flag is used by print_message/2. If its value is \const{silent},
messages of type \const{informational} and \const{banner} are suppressed.
The \cmdlineoption{-q} switches the value from the initial
\const{normal} to \const{silent}.
\prologflagitem{verbose_autoload}{bool}{rw}
If \const{true} the normal consult message will be printed if a library
is autoloaded. By default this message is suppressed. Intended to be
used for debugging purposes.
\prologflagitem{verbose_file_search}{bool}{rw}
If \const{true} (default \const{false}), print messages indicating the
progress of absolute_file_name/[2,3] in locating files. Intended for
debugging complicated file-search paths. See also file_search_path/2.
\prologflagitem{verbose_load}{atom}{rw}
Determines messages printed for loading (compiling) Prolog files.
Current values are \const{full} (print a message at the start and end of
each file loaded), \const{normal} (print a message at the end of each
file loaded), \const{brief} (print a message at end of loading the
toplevel file), and \const{silent} (no messages are printed, default).
The value of this flag is normally controlled by the option
\term{silent}{Bool} provided by load_files/2.
\prologflagitem{version}{integer}{r}
The version identifier is an integer with value: $$10000 \times
\arg{Major} + 100 \times \arg{Minor} + \arg{Patch}$$
\prologflagitem{version_data}{swi(Major, Minor, Patch, Extra)}{r}
Part of the dialect compatibility layer; see also the Prolog flag
\prologflag{dialect} and \secref{dialect}. \arg{Extra} provides
platform-specific version information as a list. \arg{Extra} is used for
\jargon{tagged versions} such as ``7.4.0-rc1'', in which case
\arg{Extra} contains a term \term{tag}{rc1}.
\prologflagitem{version_git}{atom}{r}
Available if created from a git repository. See \program{git-describe}
for details.
\prologflagitem{warn_override_implicit_import}{bool}{rw}
If \const{true} (default), a warning is printed if an implicitly
imported predicate is clobbered by a local definition. See
use_module/1 for details.
\prologflagitem{win_file_access_check}{atom}{rw}
Controls the behaviour or access_file/2 under Windows. There is no
reliable way to check access to files and directories on Windows. This
flag allows for switching between three alternative approximations.
\begin{description}
\termitem{access}{}
Use Windows _waccess() function. This ignores ACLs (Access Control
List) and thus may indicate that access is allowed while it is not.
\termitem{getfilesecurity}{}
Use the Windows GetFileSecurity() function. This does not work on
all file systems, but is probably the best choice on file systems
that do support it, notably local NTFS volumes.
\termitem{openclose}{}
Try to open the file and close it. This works reliable for files,
but not for directories. Currently directories are checked using
_waccess(). This is the default.
\end{description}
\prologflagitem{windows}{bool}{r}
\index{windows}%
If present and \const{true}, the operating system is an implementation
of Microsoft Windows. This flag is only available on MS-Windows based
versions. See also \prologflag{unix}.
\prologflagitem{wine_version}{atom}{r}
If present, SWI-Prolog is the MS-Windows version running under
the \href{https://www.winehq.org/}{Wine} emulator.
\prologflagitem{write_attributes}{atom}{rw}
Defines how write/1 and friends write attributed variables. The option
values are described with the \const{attributes} option of
write_term/2. Default is \const{ignore}.
\prologflagitem{write_help_with_overstrike}{bool}{r}
Internal flag used by help/1 when writing to a terminal. If
present and \const{true} it prints bold and underlined text using
\jargon{overstrike}.
\prologflagitem{xpce}{bool}{r}
Available and set to \const{true} if the XPCE graphics system is loaded.
\prologflagitem{xpce_version}{atom}{r}
Available and set to the version of the loaded XPCE system.
\prologflagitem{xref}{bool}{rw}
If \const{true}, source code is being read for \emph{analysis} purposes
such as cross-referencing. Otherwise (default) it is being read to be
compiled. This flag is used at several places by term_expansion/2 and
goal_expansion/2 hooks, notably if these hooks use side effects. See
also the libraries \pllib{prolog_source} and \pllib{prolog_xref}.
\end{description}
\predicate[ISO]{set_prolog_flag}{2}{:Key, +Value}
Define a new Prolog flag or change its value. \arg{Key} is an atom.
If the flag is a system-defined flag that is not marked
\jargon{changeable} above, an attempt to modify the flag yields a
\except{permission_error}. If the provided \arg{Value} does not
match the type of the flag, a \except{type_error} is raised.
Some flags (e.g., \prologflag{unknown}) are maintained on a per-module
basis. The addressed module is determined by the \arg{Key} argument.
In addition to ISO, SWI-Prolog allows for user-defined Prolog flags. The
type of the flag is determined from the initial value and cannot be
changed afterwards. Defined types are \const{boolean} (if the initial
value is one of \const{false}, \const{true}, \const{on} or \const{off}),
\const{atom} if the initial value is any other atom, \const{integer} if
the value is an integer that can be expressed as a 64-bit signed value.
Any other initial value results in an untyped flag that can represent
any valid Prolog term.
The behaviour when \arg{Key} denotes a non-existent key depends on the
Prolog flag \prologflag{user_flags}. The default is to define them
silently. New code is encouraged to use create_prolog_flag/3 for
portability.
\predicate[YAP]{create_prolog_flag}{3}{+Key, +Value, +Options}
Create a new Prolog flag. The ISO standard does not foresee creation
of new flags, but many libraries introduce new flags. \arg{Options}
is a list of the options below. See also \prologflag{user_flags}.
\begin{description}
\termitem{access}{+Access}
Define access rights for the flag. Values are \const{read_write}
and \const{read_only}. The default is \const{read_write}.
\termitem{type}{+Atom}
Define a type restriction. Possible values are
\const{boolean}, \const{atom}, \const{integer}, \const{float}
and \const{term}. The default is determined from the initial
value. Note that \const{term} restricts the term to be ground.
\termitem{keep}{+Boolean}
If \const{true}, do not modify the flag if it already exists.
Otherwise (default), this predicate behaves as set_prolog_flag/2
if the flag already exists.
\end{description}
\end{description}
\section{An overview of hook predicates} \label{sec:hooks}
\index{hooks}
SWI-Prolog provides a large number of hooks, mainly to control handling
messages, debugging, startup, shut-down, macro-expansion, etc. Below
is a summary of all defined hooks with an indication of their
portability.
\begin{itemlist}
\item [portray/1]
Hook into write_term/3 to alter the way terms are printed (ISO).
\item [message_hook/3]
Hook into print_message/2 to alter the way system messages are printed
(Quintus/SICStus).
\item [message_property/2]
Hook into print_message/2 that defines prefix, output stream, color,
etc.
\item [message_prefix_hook/2]
Hook into print_message/2 to add additional prefixes to the message such
as the time and thread.
\item [library_directory/1]
Hook into absolute_file_name/3 to define new library directories
(most Prolog systems).
\item [file_search_path/2]
Hook into absolute_file_name/3 to define new search paths
(Quintus/SICStus).
\item [term_expansion/2]
Hook into load_files/2 to modify read terms before they are compiled
(macro-processing) (most Prolog systems).
\item [goal_expansion/2]
Same as term_expansion/2 for individual goals (SICStus).
\item [prolog_load_file/2]
Hook into load_files/2 to load other data formats for Prolog sources
from `non-file' resources. The load_files/2 predicate is the ancestor
of consult/1, use_module/1, etc.
\item [prolog_edit:locate/3]
Hook into edit/1 to locate objects (SWI).
\item [prolog_edit:edit_source/1]
Hook into edit/1 to call an internal editor (SWI).
\item [prolog_edit:edit_command/2]
Hook into edit/1 to define the external editor to use (SWI).
\item [prolog_list_goal/1]
Hook into the tracer to list the code associated to a particular goal
(SWI).
\item [prolog_trace_interception/4]
Hook into the tracer to handle trace events (SWI).
\item [prolog:debug_control_hook/1]
Hook in spy/1, nospy/1, nospyall/0 and debugging/0 to extend these
control predicates to higher-level libraries.
\item [prolog:help_hook/1]
Hook in help/0, help/1 and apropos/1 to extend the help system.
\item [resource/3]
Define a new resource (not really a hook, but similar) (SWI).
\item [exception/3]
Old attempt to a generic hook mechanism. Handles undefined predicates (SWI).
\item [attr_unify_hook/2]
Unification hook for attributed variables. Can be defined in any
module. See \secref{attvar} for details.
\end{itemlist}
\section{Automatic loading of libraries} \label{sec:autoload}
If ---at runtime--- an undefined predicate is trapped, the system will
first try to import the predicate from the module's default module (see
\secref{importmodule}. If this fails the \jargon{auto loader} is
activated.\footnote{Actually, the hook user:exception/3 is called; only
if this hook fails it calls the autoloader.} On first activation an
index to all library files in all library directories is loaded in core
(see library_directory/1, file_search_path/2 and
reload_library_index/0). If the undefined predicate can be located in
one of the libraries, that library file is automatically loaded and the
call to the (previously undefined) predicate is restarted. By default
this mechanism loads the file silently. The current_prolog_flag/2
key \prologflag{verbose_autoload} is provided to get verbose loading. The
Prolog flag \prologflag{autoload} can be used to enable/disable the
autoload system. A more controlled form of autoloading as well as
lazy loading application modules is provided by autoload/1,2.
Autoloading only handles (library) source files that use the module
mechanism described in \chapref{modules}. The files are loaded
with use_module/2 and only the trapped undefined predicate is imported
into the module where the undefined predicate was called. Each library
directory must hold a file \file{INDEX.pl} that contains an index to all
library files in the directory. This file consists of lines of the
following format:
\begin{code}
index(Name, Arity, Module, File).
\end{code}
The predicate make/0 updates the autoload index. It searches for all
library directories (see library_directory/1 and file_search_path/2)
holding the file \file{MKINDEX.pl} or \file{INDEX.pl}. If the current
user can write or create the file \file{INDEX.pl} and it does not exist
or is older than the directory or one of its files, the index for this
directory is updated. If the file \file{MKINDEX.pl} exists, updating is
achieved by loading this file, normally containing a directive calling
make_library_index/2. Otherwise make_library_index/1 is called, creating
an index for all \file{*.pl} files containing a module.
Below is an example creating an indexed library directory.
\begin{code}
% mkdir ~/${XDG_DATA_HOME-.config}/swi-prolog/lib
% cd ~/${XDG_DATA_HOME-.config}/swi-prolog/lib
% swipl -g 'make_library_index(.)' -t halt
\end{code}
If there is more than one library file containing the desired predicate,
the following search schema is followed:
\begin{enumerate}
\item If there is a library file that defines the module in which
the undefined predicate is trapped, this file is used.
\item Otherwise library files are considered in the order they appear
in the library_directory/1 predicate and within the directory
alphabetically.
\end{enumerate}
\begin{description}
\predicate{autoload_path}{1}{+DirAlias}
Add \arg{DirAlias} to the libraries that are used by the autoloader. This
extends the search path \const{autoload} and reloads the library
index. For example:
\begin{code}
:- autoload_path(library(http)).
\end{code}
If this call appears as a directive, it is term-expanded into a clause
for user:file_search_path/2 and a directive calling
reload_library_index/0. This keeps source information and allows for
removing this directive.
\predicate{make_library_index}{1}{+Directory}
Create an index for this directory. The index is written to the file
'INDEX.pl' in the specified directory. Fails with a warning if the
directory does not exist or is write protected.
\predicate{make_library_index}{2}{+Directory, +ListOfPatterns}
Normally used in \file{MKINDEX.pl}, this predicate creates \file{INDEX.pl}
for \arg{Directory}, indexing all files that match one of the file patterns
in \arg{ListOfPatterns}.
Sometimes library packages consist of one public load file and a number
of files used by this load file, exporting predicates that should not be
used directly by the end user. Such a library can be placed in a
sub-directory of the library and the files containing public
functionality can be added to the index of the library. As an
example we give the XPCE library's \file{MKINDEX.pl}, including the
public functionality of \file{trace/browse.pl} to the autoloadable
predicates for the XPCE package.
\begin{code}
:- prolog_load_context(directory, Dir),
make_library_index(Dir,
[ '*.pl',
'trace/browse.pl',
'swi/*.pl'
]).
\end{code}
\predicate{reload_library_index}{0}{}
Force reloading the index after modifying the set of library directories
by changing the rules for library_directory/1, file_search_path/2,
adding or deleting \file{INDEX.pl} files. This predicate does \emph{not}
update the \file{INDEX.pl} files. Check make_library_index/[1,2] and
make/0 for updating the index files.
Normally, the index is reloaded automatically if a predicate cannot be
found in the index and the set of library directories has changed. Using
reload_library_index/0 is necessary if directories are removed or the
order of the library directories is changed.
\end{description}
When creating an executable using either qsave_program/2 or the
\cmdlineoption{-c} command line options, it is necessary to load
all predicates that would normally be autoloaded explicitly. This
is discussed in \secref{runtime}. See autoload_all/0.
\section{Packs: community add-ons} \label{sec:packs}
SWI-Prolog has a mechanism for easy incorporation of community
extensions. See the \href{http://www.swi-prolog.org/pack/list}{pack
landing page} for details and available packs. This section documents
the built-in predicates to attach packs. Predicates for creating,
registering and installing packs are provided by the library
\pllib{prolog_pack}.
\begin{description}
\predicate{attach_packs}{0}{}
Attaches all packs in subdirectories of directories that are accessible
through the \jargon{file search path} (see absolute_file_name/3)
\const{pack}. The default for this search path is given below. See
file_search_path/2 for the \const{app_data} search path.
\begin{code}
user:file_search_path(pack, app_data(pack)).
\end{code}
The predicate attach_packs/0 is called on startup of SWI-Prolog.
\predicate{attach_packs}{1}{+Directory}
Attach all packs in subdirectories of \arg{Directory}. Same as
\term{attach_packs}{Directory, []}.
\nodescription
\predicate{attach_packs}{2}{+Directory, +Options}
Attach all packs in subdirectories of \arg{Directory}. Options
is one of:
\begin{description}
\termitem{search}{+Where}
Determines the order in which pack library directories are searched.
Default is to add new packages at the end (\const{last}). Using
\const{first}, new packages are added at the start.
\termitem{duplicate}{+Action}
Determines what happens if a pack with the same name is already
attached. Default is \const{warning}, which prints a warning and
ignores the new pack. Other options are \const{keep}, which is
like \const{warning} but operates silently and \const{replace},
which detaches the old pack and attaches the new.
\end{description}
The predicate attach_packs/2 can be used to attach packages that
are bundled with an application.
\end{description}
\section{The SWI-Prolog syntax} \label{sec:syntax}
SWI-Prolog syntax is close to ISO-Prolog standard syntax, which is based
on the Edinburgh Prolog syntax. A formal description can be found in the
ISO standard document. For an informal introduction we refer to Prolog
text books (see \secref{intro}) and
\href{http://www.swi-prolog.org/Links.html}{online tutorials}. In
addition to the differences from the ISO standard documented here,
SWI-Prolog offers several extensions, some of which also extend the
syntax. See \secref{extensions} for more information.
\subsection{ISO Syntax Support} \label{sec:isosyntax}
This section lists various extensions w.r.t.\ the ISO Prolog syntax.
\subsubsection{Processor Character Set} \label{sec:processorcharset}
\index{ISO Latin 1}\index{character set}%
The processor character set specifies the class of each character used
for parsing Prolog source text. Character classification is fixed to
\href{http://www.unicode.org/}{Unicode}. See also \secref{widechars}.
\subsubsection{Nested comments} \label{sec:nestedcomments}
SWI-Prolog allows for nesting \exam{/* \ldots */} comments. Where the
ISO standard accepts \exam{/* \ldots /* \ldots */} as a comment,
SWI-Prolog will search for a terminating \exam{*/}. This is useful if
some code with \exam{/* \ldots */} comment statements in it should be
commented out. This modification also avoids unintended commenting in
the example below, where the closing \exam{*/} of the first comment has
been forgotten.\footnote{Recent copies of GCC give a style warning if
\exam{/*} is encountered in a comment, which suggests that this
problem has been recognised more widely.}
\begin{code}
/* comment
code
/* second comment */
code
\end{code}
\subsubsection{Character Escape Syntax} \label{sec:charescapes}
Within quoted atoms (using single quotes: \exam{'<atom>'}) special
characters are represented using escape sequences. An escape sequence is
led in by the backslash (\chr{\}) character. The list of escape
sequences is compatible with the ISO standard but contains some
extensions, and the interpretation of numerically specified characters
is slightly more flexible to improve compatibility. Undefined escape
characters raise a \const{syntax_error} exception.\footnote{Up to
SWI-Prolog~6.1.9, undefined escape characters were copied verbatim,
i.e., removing the backslash.}
\begin{description}
\escapeitem{a}
Alert character. Normally the ASCII character 7 (beep).
\escapeitem{b}
Backspace character.
\escapeitem{c}
No output. All input characters up to but not including the first
non-layout character are skipped. This allows for the specification
of pretty-looking long lines. Not supported by ISO. Example:
\begin{code}
format('This is a long line that looks better if it was \c
split across multiple physical lines in the input')
\end{code}
\escapeitem{\bnfmeta{{\sc NEWLINE}}}
When in ISO mode (see the Prolog flag \prologflag{iso}), only skip this
sequence. In native mode, white space that follows the newline is
skipped as well and a warning is printed, indicating that this construct
is deprecated and advising to use \verb$\c$. We advise using \verb$\c$
or putting the layout \emph{before} the \chr{\}, as shown below. Using
\verb$\c$ is supported by various other Prolog implementations and will
remain supported by SWI-Prolog. The style shown below is the most
compatible solution.\footnote{Future versions will interpret
\chr{\}<return> according to ISO.}
\begin{code}
format('This is a long line that looks better if it was \
split across multiple physical lines in the input')
\end{code}
instead of
\begin{code}
format('This is a long line that looks better if it was\
split across multiple physical lines in the input')
\end{code}
Note that SWI-Prolog also allows unescaped newlines to appear in quoted
material. This is not allowed by the ISO standard, but used to be
common practice before.
\escapeitem{e}
Escape character (\textsc{ASCII} 27). Not ISO, but widely supported.
\escapeitem{f}
Form-feed character.
\escapeitem{n}
Next-line character.
\escapeitem{r}
Carriage-return only (i.e., go back to the start of the line).
\escapeitem{s}
Space character. Intended to allow writing \verb$0'\s$
to get the character code of the space character. Not ISO.
\escapeitem{t}
Horizontal tab character.
\escapeitem{v}
Vertical tab character (\textsc{ASCII} 11).
\escapeitem{xXX..\}
Hexadecimal specification of a character. The closing \verb$\$ is
obligatory according to the ISO standard, but optional in SWI-Prolog to
enhance compatibility with the older Edinburgh standard. The code
\verb$\xa\3$ emits the character 10 (hexadecimal `a') followed by `3'.
Characters specified this way are interpreted as Unicode characters. See
also \verb$\u$.
\escapeitem{uXXXX}
Unicode character specification where the character is specified using
\emph{exactly} 4 hexadecimal digits. This is an extension to the ISO
standard, fixing two problems. First, where \verb$\x$ defines
a numeric character code, it doesn't specify the character set in which
the character should be interpreted. Second, it is not needed to
use the idiosyncratic closing \chr{\} ISO Prolog syntax.
\escapeitem{UXXXXXXXX}
Same as \verb$\uXXXX$, but using 8 digits to cover the whole Unicode
set.
\escapeitem{40}
Octal character specification. The rules and remarks for hexadecimal
specifications apply to octal specifications as well.
\escapeitem{\}
Escapes the backslash itself. Thus, \verb$'\\'$ is an atom
consisting of a single \chr{\}.
\escapeitem{'}
Single quote. Note that \verb$'\''$ and \verb$''''$ both describe
the atom with a single~\chr{'}, i.e., \verb$'\'' == ''''$ is true.
\escapeitem{"}
Double quote.
\escapeitem{`}
Back quote.
\end{description}
Character escaping is only available if
\exam{current_prolog_flag(character_escapes, true)} is active (default).
See current_prolog_flag/2. Character escapes conflict with writef/2 in
two ways: \verb$\40$ is interpreted as decimal 40 by writef/2, but as
octal 40 (decimal 32) by \verb$read$. Also, the writef/2 sequence
\fmtseq{\l} is illegal. It is advised to use the more widely supported
format/[2,3] predicate instead. If you insist upon using writef/2,
either switch \prologflag{character_escapes} to \const{false}, or use
double \fmtseq{\\}, as in \verb$writef('\\l')$.
\subsubsection{Syntax for non-decimal numbers} \label{sec:nondecsyntax}
SWI-Prolog implements both Edinburgh and ISO representations for
non-decimal numbers. According to Edinburgh syntax, such numbers are
written as \exam{<radix>'<number>}, where <radix> is a number between 2
and 36. ISO defines binary, octal and hexadecimal numbers using
\exam{0{\em [bxo]}<number>}. For example: \verb$A is 0b100 \/ 0xf00$ is
a valid expression. Such numbers are always unsigned.
\subsubsection{Using digit groups in large integers}
\label{sec:digitgroupsyntax}
SWI-Prolog supports splitting long integers into \jargon{digit groups}.
Digit groups can be separated with the sequence \bnfmeta{underscore},
\bnfmeta{optional white space}. If the \bnfmeta{radix} is 10 or lower,
they may also be separated with exactly one space. The following all
express the integer 1~million:
\begin{code}
1_000_000
1 000 000
1_000_/*more*/000
\end{code}
Integers can be printed using this notation with format/2, using the
\verb$~I$ format specifier. For example:
\begin{code}
?- format('~I', [1000000]).
1_000_000
\end{code}
The current syntax has been proposed by Ulrich Neumerkel on the
SWI-Prolog mailinglist.
\subsubsection{Rational number syntax}
\label{sec:syntax-rational-numbers}
As of version 8.1.22, SWI-Prolog supports rational numbers as a primary
citizen atomic data type if SWI-Prolog is compiled with the GMP library.
This can be tested using the \prologflag{bounded} Prolog flag. An atomic
type also requires a syntax. Unfortunately there are few options for
adding rational numbers without breaking the ISO
standard.\footnote{ECLiPSe uses \arg{numerator}_\arg{denominator}. This
syntax conflicts with SWI-Prolog digit groups (see
\secref{digitgroupsyntax}) and does not have a recognised link to
rational numbers. The notation \exam{1/3r} and \exam{1/3R} have also
been proposed. The \exam{1/3r} is compatible to Ruby, but is hard to
parse due to the required look-ahead and not very natural. See also
\url{https://en.wikipedia.org/wiki/Rational_data_type}.}
ECLiPSe and SWI-Prolog have agreed to define the canonical syntax for
rational numbers to be e.g., \exam{1r3}. In addition, ECLiPSe accepts
\exam{1_3} and SWI-Prolog can be asked to accept \exam{1/3} using the
module sensitive Prolog flag \prologflag{rational_syntax}, which has the
values below. Note that write_canonical/1 always uses the compatible
\exam{1r3} syntax.
\begin{description}
\termitem{natural}{}
This is the default mode where we ignore the ambiguity issue and follow
the most natural <integer>/<nonneg> alternative. Here, <integer> follows
the normal rules for Prolog decimal integers and <nonneg> does the same,
but does not allows for a sign. Note that the parser translates a
rational number to its canonical form which implies there are no common
divisors in the resulting numerator and denominator. Examples of ration
numbers are:
\begin{tabular}{ll}
1/2 & 1/2 \\
2/4 & 1/2 \\
1 000 000/33 000 & 1000/33 \\
-3/5 & -3/5 \\
\end{tabular}
We expect very few programs to have text parsed into a rational number
while a term was expected. Note that for rationals appearing in an
arithmetic expression the only difference is that evaluation moves from
runtime to compiletime. The utility list_rationals/0 may be used on a
loaded program to check whether the program contains rational numbers
inside clauses and thus may be subject to compatibility issues. If a
term is intended this can be written as \verb$/(1,2)$, \verb$(1)/2$,
\verb$1 / 2$ or some variation thereof.
\termitem{compatibility}{}
Read and write rational numbers as e.g., \exam{1r3}. In other words,
this adheres to the same rules as \const{natural} above, but using the
`\chr{r}' instead of `\chr{/}'. Note that this may conflict with
traditional Prolog as `\const{r}' can be defined as an infix operator.
The same argument holds for \exam{0x23} and similar syntax for numbers
that are part of the ISO standard.
\end{description}
While the syntax is controlled by the flag \prologflag{rational_syntax},
behavior on integer division and exponentiation is controlled by the
flag \prologflag{prefer_rationals}. See section \secref{rational} for
arithmetic on rational numbers.
\subsubsection{NaN and Infinity floats and their syntax}
\label{sec:floatsyntax}
SWI-Prolog supports reading and printing `special' floating point values
according to
\href{http://eclipseclp.org/Specs/core_update_float.html}{Proposal for
Prolog Standard core update wrt floating point arithmetic} by Joachim
Schimpf and available in ECLiPSe Prolog. In particular,
\begin{itemize}
\item Infinity is printed as \verb$1.0Inf$ or \verb$-1.0Inf$. Any
sequence matching the regular expression \verb$[+-]?\sd+[.]\sd+Inf$
is mapped to plus or minus infinity.
\item \const{NaN} (Not a Number) is printed as \verb$1.xxxNaN$, where
\textit{1.xxx} is the float after replacing the exponent by `1'.
Such numbers are read, resulting in the same \const{NaN}. The
\const{NaN} constant can also be produced using the function
\funcref{nan}{0}, e.g.,
\begin{code}
?- A is nan.
A = 1.5NaN.
\end{code}
\end{itemize}
By default SWI-Prolog arithmetic (see \secref{arith}) follows the ISO
standard with describes that floating point operations either produce a
\jargon{normal} floating point number or raise an exception.
\secref{ieee-float} describes the Prolog flags that can be used to
support the IEEE special float values. The ability to create, read and
write such values facilitates the exchange of data with languages that
can represent the full range of IEEE doubles.
\subsubsection{Force only underscore to introduce a variable}
\label{sec:varprefix}
According to the ISO standard and most Prolog systems, identifiers that
start with an uppercase letter or an underscore are variables. In the
past, \jargon{Prolog by BIM} provided an alternative syntax, where only
the underscore (\chr{_}) introduces a variable. As of SWI-Prolog 7.3.27
SWI-Prolog supports this alternative syntax, controlled by the Prolog
flag \prologflag{var_prefix}. As the \prologflag{character_escapes}
flag, this flag is maintained per module, where the default is
\const{false}, supporting standard syntax.
Having only the underscore introduce a variable is particularly useful
if code contains identifiers for case sensitive external languages.
Examples are the RDF library where code frequently specifies property
and class names\footnote{Samer Abdallah suggested this feature based on
experience with non-Prolog users using the RDF library.} and the R
interface for specifying functions or variables that start with an
uppercase character. Lexical databases where part of the terms start with
an uppercase letter is another category were the readability of the code
improves using this option.
\subsubsection{Unicode Prolog source} \label{sec:unicodesyntax}
The ISO standard specifies the Prolog syntax in ASCII characters. As
SWI-Prolog supports Unicode in source files we must extend the syntax.
This section describes the implication for the source files, while
writing international source files is described in \secref{intsrcfile}.
The SWI-Prolog Unicode character classification is based on version
6.0.0 of the Unicode standard. Please note that char_type/2 and
friends, intended to be used with all text except Prolog source code, is
based on the C library locale-based classification routines.
\begin{itemlist}
\item [Quoted atoms and strings]
Any character of any script can be used in quoted atoms and strings. The
escape sequences \verb$\uXXXX$ and \verb$\UXXXXXXXX$ (see
\secref{charescapes}) were introduced to specify Unicode code points in
ASCII files.
\item [Atoms and Variables]
We handle them in one item as they are closely related. The Unicode
standard defines a syntax for identifiers in computer languages.%
\footnote{\url{http://www.unicode.org/reports/tr31/}}
In this syntax identifiers start with \const{ID_Start} followed by a
sequence of \const{ID_Continue} codes. Such sequences are handled as a
single token in SWI-Prolog. The token is a \emph{variable} iff it starts
with an uppercase character or an underscore (\chr{_}). Otherwise it is
an atom. Note that many languages do not have the notion of
character case. In such languages variables \emph{must} be written as
\verb$_name$.
\item [White space]
All characters marked as separators (Z*) in the Unicode tables are
handled as layout characters.
\item [Control and unassigned characters]
Control and unassigned (C*) characters produce a syntax error if
encountered outside quoted atoms/strings and outside comments.
\item [Other characters]
The first 128 characters follow the ISO Prolog standard. Unicode symbol
and punctuation characters (general category S* and P*) act as glueing
symbol characters (i.e., just like \const{==}: an unquoted sequence of
symbol characters are combined into an atom).
Other characters (this is mainly \const{No}: \textit{a numeric character
of other type}) are currently handled as `solo'.
\end{itemlist}
\subsubsection{Singleton variable checking} \label{sec:singleton}
\index{singleton,variable}\index{anonymous,variable}%
A \jargon{singleton variable} is a variable that appears only one time
in a clause. It can always be replaced by \verb$_$, the
\jargon{anonymous} variable. In some cases, however, people prefer to give
the variable a name. As mistyping a variable is a common mistake, Prolog
systems generally give a warning (controlled by style_check/1) if a
variable is used only once. The system can be informed that a variable is
meant to appear once by \emph{starting} it with an underscore, e.g.,
\verb$_Name$. Please note that any variable, except plain \verb$_$,
shares with variables of the same name. The term \verb$t(_X, _X)$ is
equivalent to \verb$t(X, X)$, which is \emph{different} from
\verb$t(_, _)$.
As Unicode requires variables to start with an underscore in many
languages, this schema needs to be extended.%
\footnote{After a proposal by Richard O'Keefe.}
First we define the two classes of named variables.
\begin{itemlist}
\item [Named singleton variables]
Named singletons start with a double underscore (\verb$__$) or a single
underscore followed by an uppercase letter, e.g., \verb$__var$ or
\verb$_Var$.
\item [Normal variables]
All other variables are `normal' variables. Note this makes \verb$_var$
a normal variable.%
\footnote{Some Prolog dialects write variables this way.}
\end{itemlist}
Any normal variable appearing exactly once in the clause \emph{and}
any named singleton variables appearing more than once are reported.
Below are some examples with warnings in the right column. Singleton
messages can be suppressed using the style_check/1 directive.
\begin{center}
\begin{tabular}{|l|l|}
\hline
test(_). & \\
test(_a). & Singleton variables: [_a] \\
test(_12). & Singleton variables: [_12] \\
test(A). & Singleton variables: [A] \\
test(_A). & \\
test(__a). & \\
test(_, _). & \\
test(_a, _a). & \\
test(__a, __a). & Singleton-marked variables appearing more than once: [__a] \\
test(_A, _A). & Singleton-marked variables appearing more than once: [_A] \\
test(A, A). & \\
\hline
\end{tabular}
\end{center}
\paragraph{Semantic singletons}
Starting with version 6.5.1, SWI-Prolog has \jargon{syntactic
singletons} and \jargon{semantic singletons}. The first are checked by
read_clause/3 (and read_term/3 using the option
\term{singletons}{warning}). The latter are generated by the compiler
for variables that appear alone in a \jargon{branch}. For example, in
the code below the variable \arg{X} is not a \emph{syntactic} singleton,
but the variable \arg{X} does not communicate any bindings and replacing
\arg{X} with \arg{_} does not change the semantics.
\begin{code}
test :-
( test_1(X)
; test_2(X)
).
\end{code}
\section{Rational trees (cyclic terms)} \label{sec:cyclic}
\index{rational trees}%
\index{infinite trees}\index{cyclic terms}\index{terms,cyclic}%
SWI-Prolog supports rational trees, also known as cyclic terms.
`Supports' is so defined that most relevant built-in predicates terminate
when faced with rational trees. Almost all SWI-Prolog's built-in term
manipulation predicates process terms in a time that is linear to the
amount of memory used to represent the term on the stack. The following
set of predicates safely handles rational trees:
%
\predref{=..}{2},
\predref{==}{2},
\predref{=@=}{2},
\predref{=}{2},
\predref{@<}{2},
\predref{@=<}{2},
\predref{@>=}{2},
\predref{@>}{2},
\predref{\==}{2},
\predref{\=@=}{2},
\predref{\=}{2},
acyclic_term/1,
bagof/3,
compare/3,
copy_term/2,
cyclic_term/1,
dif/2,
duplicate_term/2,
findall/3,
ground/1,
term_hash/2,
numbervars/3,
numbervars/4,
recorda/3,
recordz/3,
setof/3,
subsumes_term/2,
term_variables/2,
throw/1,
unify_with_occurs_check/2,
unifiable/3,
when/2,
write/1 (and related predicates)
.
In addition, some built-ins recognise rational trees and raise an
appropriate exception. Arithmetic evaluation belongs to this group. The
compiler (asserta/1, etc.) also raises an exception. Future versions may
support rational trees. Predicates that could provide meaningful
processing of rational trees raise a \const{representation_error}.
Predicates for which rational trees have no meaningful interpretation
raise a \const{type_error}. For example:
\begin{code}
1 ?- A = f(A), asserta(a(A)).
ERROR: asserta/1: Cannot represent due to `cyclic_term'
2 ?- A = 1+A, B is A.
ERROR: is/2: Type error: `expression' expected, found
`@(S_1,[S_1=1+S_1])' (cyclic term)
\end{code}
\section{Just-in-time clause indexing} \label{sec:jitindex}
\index{jitindex}\index{indexing,jiti}%
SWI-Prolog provides `just-in-time' indexing over multiple
arguments.\footnote{JIT indexing was added in version 5.11.29 (Oct.
2011).} `Just-in-time' means that clause indexes are not built by the
compiler (or asserta/1 for dynamic predicates), but on the first call
to such a predicate where an index might help (i.e., a call where at
least one argument is instantiated). This section describes the rules
used by the indexing logic. Note that this logic is not `set in stone'.
The indexing capabilities of the system will change. Although this
inevitably leads to some regressing on some particular use cases, we
strive to avoid significant slowdowns.
The list below describes the clause selection process for various
predicates and calls. The alternatives are considered in the order
they are presented.
\begin{itemlist}
\item [Special purpose code]
Currently two special cases are recognised by the compiler: static code
with exactly one clause and static code with two clauses, one where the
first argument is the empty list (\verb$[]$) and one where the first
argument is a non-empty list (\verb$[_|_]$).
\item [Linear scan on first argument]
The principal clause list maintains a \jargon{key} for the first
argument. An indexing key is either a constant or a functor (name/arity
reference). Calls with an instantiated first argument and less than
10 clauses perform a linear scan for a possible matching clause using
this index key. If the result is deterministic it is used. Otherwise
the system looks for better indexes.\footnote{Up to 7.7.2 this result
was used also when non-deterministic.}.
\item [Hash lookup]
If none of the above applies, the system considers the available hash
tables for which the corresponding argument is instantiated. If a table
is found with acceptable characteristics, it is used. Otherwise it
assesses the clauses for all instantiated arguments and selects the best
candidate for creating a new hash table. If there is no single argument
that provides an acceptable hash quality it will search for a
combination of arguments.\footnote{The last step was added in SWI-Prolog
7.5.8.} Searching for index candidates is only performed on the first
254 arguments.
If a single-argument index contains multiple compound terms with the
same name and arity and at least one non-variable argument, a
\jargon{list index} is created. A subsequent query where this argument
is bound to a compound causes jiti indexing to be applied
\jargon{recursively} on the arguments of the term. This is called
\jargon{deep indexing}.\footnote{Deep indexing was added in version
7.7.4.} See also \secref{deep-indexing}
Clauses that have a variable at an otherwise indexable argument must be
linked into all hash buckets. Currently, predicates that have more than
10\% such clauses for a specific argument are not considered for
indexing on that argument.
Disregarding variables, the suitability of an argument for hashing is
expressed as the number of unique indexable values divided by the
standard deviation of the number of duplicate values for each value plus
one.\footnote{Earlier versions simply used the number of unique values,
but poor distribution of values makes a table less suitable. This was
analysed by Fabien Noth and G\"unter Kniesel.}
The indexes of dynamic predicates are deleted if the number of clauses
is doubled since its creation or reduced below 1/4th. The JIT approach
will recreate a suitable index on the next call. Indexes of running
predicates cannot be deleted. They are added to a `removed index list'
associated to the predicate. Outdated indexes of predicates are
reclaimed by garbage_collect_clauses/0. The clause garbage collector
is scheduled automatically, based on time and space based heuristics.
See garbage_collect_clauses/0 for details.
\end{itemlist}
The library \pllib{prolog_jiti} provides jiti_list/0,1 to list the
characteristics of all or some of the created hash tables.
\paragraph{Dynamic predicates} are indexed using the same rules as
static predicates, except that the \jargon{special purpose} schemes are
never applied. In addition, the JITI index is discarded if the number of
clauses has doubled since the predicate was last assessed or shrinks
below one fourth. A subsequent call reassesses the statistics of the
dynamic predicate and, when applicable, creates a new index.
\subsection{Deep indexing}
\label{sec:deep-indexing}
\index{indexing,deep}%
As introduced in \secref{jitindex}, \jargon{deep indexing} creates hash
tables distinguish clauses that share a compound with the same name and
arity. Deep indexes allow for efficient lookup of arbitrary terms.
Without it is advised to \jargon{flatten} the term, i.e., turn
\term{F}{X} into two arguments for the fact, one argument denoting the
functor \arg{F} and the second the argument {X}. This works fine as long
as the arity of the each of the terms is the same. Alternatively we can
use term_hash/2 or term_hash/4 to add a column holding the hash of the
term. That approach can deal with arbitrary arities, but requires us to
know that the term is ground (term_hash/2) or up to which depth we get
sufficient selectivity (term_hash/4).
Deep indexing does not require this knowledge and leads to efficient
lookup regardless of the instantiation of the query and term. The
current version does come with some limitations:
\begin{itemize}
\item The decision which index to use is taken independently
at each level. Future versions may be smarter on this.
\item Deep indexing only applies to a \emph{single argument}
indexes (on any argument).
\item Currently, the depth of indexing is limited to 7 levels.
\end{itemize}
\index{indexing,DCG}\index{DCG,indexing}%
Note that, when compiling DCGs (see \secref{DCG}) and the first body
term is a \jargon{literal}, it is included into the clause head. See
for example the grammar and its plain Prolog representation below.
\begin{code}
det(det(a), sg) --> "a".
det(det(an), pl) --> "an".
det(det(the), _) --> "the".
\end{code}
\begin{code}
?- listing(det).
det(det(a), sg, [97|A], A).
det(det(an), pl, [97, 110|A], A).
det(det(the), _, [116, 104, 101|A], A).
\end{code}
Deep argument indexing will create indexes for the 3rd list argument,
providing speedup and making clause selection deterministic if all rules
start with a literal and all literals are unique in the first 6
elements. Note that deep index creation stops as soon as a deterministic
choice can be made or there are no two clauses that have the same
name/arity combination.
\subsection{Future directions}
\label{sec:indexfut}
\begin{itemize}
\item
The `special cases' can be extended. This is notably attractive for
static predicates with a relatively small number of clauses where a
hash lookup is too costly.
\item
Create an efficient decision diagram for selecting between low numbers
of static clauses.
\item
Implement a better judgements for selecting between deep and plain
indexes.
\end{itemize}
\subsection{Indexing and portability}
\label{sec:indexport}
The base-line functionality of Prolog implementations provides indexing
on constants and functor (name/arity) on the first argument. This must
be your assumption if wide portability of your program is important.
This can typically be achieved by exploiting term_hash/2 or term_hash/4
and/or maintaining multiple copies of a predicate with reordered
arguments and wrappers that update all implementations (assert/retract)
and selects the appropriate implementation (query).
YAP provides full JIT indexing, including indexing arguments of compound
terms. YAP's indexing has been the inspiration for enhancing
SWI-Prolog's indexing capabilities.
\section{Wide character support} \label{sec:widechars}
\index{UTF-8}\index{Unicode}\index{UCS}\index{internationalization}%
SWI-Prolog supports \jargon{wide characters}, characters with character
codes above 255 that cannot be represented in a single \jargon{byte}.
\jargon{Universal Character Set} (UCS) is the ISO/IEC 10646 standard
that specifies a unique 31-bit unsigned integer for any character in
any language. It is a superset of 16-bit Unicode, which in turn is
a superset of ISO 8859-1 (ISO Latin-1), a superset of US-ASCII. UCS
can handle strings holding characters from multiple languages, and
character classification (uppercase, lowercase, digit, etc.) and
operations such as case conversion are unambiguously defined.
For this reason SWI-Prolog has two representations for atoms and string
objects (see \secref{strings}). If the text fits in ISO Latin-1, it is
represented as an array of 8-bit characters. Otherwise the text is
represented as an array of 32-bit numbers. This representational issue
is completely transparent to the Prolog user. Users of the foreign
language interface as described in \chapref{foreign} sometimes need to
be aware of these issues though.
Character coding comes into view when characters of strings need to be
read from or written to file or when they have to be communicated to
other software components using the foreign language interface. In this
section we only deal with I/O through streams, which includes file I/O
as well as I/O through network sockets.
\subsection{Wide character encodings on streams} \label{sec:encoding}
Although characters are uniquely coded using the UCS standard
internally, streams and files are byte (8-bit) oriented and there are a
variety of ways to represent the larger UCS codes in an 8-bit octet
stream. The most popular one, especially in the context of the web, is
UTF-8. Bytes 0~\ldots{}~127 represent simply the corresponding US-ASCII
character, while bytes 128~\ldots{}~255 are used for multi-byte
encoding of characters placed higher in the UCS space. Especially on
MS-Windows the 16-bit Unicode standard, represented by pairs of bytes, is
also popular.
Prolog I/O streams have a property called \jargon{encoding} which
specifies the used encoding that influences get_code/2 and put_code/2 as
well as all the other text I/O predicates.
The default encoding for files is derived from the Prolog flag
\prologflag{encoding}, which is initialised from
\exam{setlocale(LC_CTYPE, NULL)} to one of \const{text}, \const{utf8} or
\const{iso_latin_1}. One of the latter two is used if the encoding name
is recognized, while \const{text} is used as default. Using
\const{text}, the translation is left to the wide-character functions of
the C library.\footnote{The Prolog native UTF-8 mode is considerably
faster than the generic mbrtowc() one.} The encoding can be specified
explicitly in load_files/2 for loading Prolog source with an alternative
encoding, open/4 when opening files or using set_stream/2 on any open
stream. For Prolog source files we also provide the encoding/1 directive
that can be used to switch between encodings that are compatible with
US-ASCII (\const{ascii}, \const{iso_latin_1}, \const{utf8} and many
locales). See also \secref{intsrcfile} for writing Prolog files with
non-US-ASCII characters and \secref{unicodesyntax} for syntax issues.
For additional information and Unicode resources, please visit
\url{http://www.unicode.org/}.
SWI-Prolog currently defines and supports the following encodings:
\begin{description}
\termitem{octet}{}
Default encoding for \const{binary} streams. This causes
the stream to be read and written fully untranslated.
\termitem{ascii}{}
7-bit encoding in 8-bit bytes. Equivalent to \const{iso_latin_1},
but generates errors and warnings on encountering values above
127.
\termitem{iso_latin_1}{}
8-bit encoding supporting many Western languages. This causes
the stream to be read and written fully untranslated.
\termitem{text}{}
C library default locale encoding for text files. Files are read and
written using the C library functions mbrtowc() and wcrtomb(). This
may be the same as one of the other locales, notably it may be the
same as \const{iso_latin_1} for Western languages and \const{utf8}
in a UTF-8 context.
\termitem{utf8}{}
Multi-byte encoding of full UCS, compatible with \const{ascii}.
See above.
\termitem{unicode_be}{}
Unicode \jargon{Big Endian}. Reads input in pairs of bytes, most
significant byte first. Can only represent 16-bit characters.
\termitem{unicode_le}{}
Unicode \jargon{Little Endian}. Reads input in pairs of bytes, least
significant byte first. Can only represent 16-bit characters.
\end{description}
Note that not all encodings can represent all characters. This implies
that writing text to a stream may cause errors because the stream cannot
represent these characters. The behaviour of a stream on these errors
can be controlled using set_stream/2. Initially the terminal stream
writes the characters using Prolog escape sequences while other streams
generate an I/O exception.
\subsubsection{BOM: Byte Order Mark} \label{sec:bom}
\index{BOM}\index{Byte Order Mark}%
From \secref{encoding}, you may have got the impression that text files are
complicated. This section deals with a related topic, making life often
easier for the user, but providing another worry to the programmer.
\textbf{BOM} or \jargon{Byte Order Marker} is a technique for
identifying Unicode text files as well as the encoding they use. Such
files start with the Unicode character 0xFEFF, a non-breaking,
zero-width space character. This is a pretty unique sequence that is not
likely to be the start of a non-Unicode file and uniquely distinguishes
the various Unicode file formats. As it is a zero-width blank, it even
doesn't produce any output. This solves all problems, or \ldots
Some formats start off as US-ASCII and may contain some encoding mark to
switch to UTF-8, such as the \verb$encoding="UTF-8"$ in an XML header.
Such formats often explicitly forbid the use of a UTF-8 BOM. In
other cases there is additional information revealing the encoding, making
the use of a BOM redundant or even illegal.
The BOM is handled by SWI-Prolog open/4 predicate. By default,
text files are probed for the BOM when opened for reading. If a BOM is
found, the encoding is set accordingly and the property \term{bom}{true}
is available through stream_property/2. When opening a file for writing,
writing a BOM can be requested using the option \term{bom}{true} with
open/4.
\section{System limits} \label{sec:limits}
\subsection{Limits on memory areas} \label{sec:memlimit}
The SWI-Prolog engine uses three \jargon{stacks} the \jargon{local
stack} (also called \jargon{environment stack}) stores the environment
frames used to call predicates as well as choice points. The
\jargon{global stack} (also called \jargon{heap}) contains terms,
floats, strings and large integers. Finally, the \jargon{trail stack}
records variable bindings and assignments to support
\jargon{backtracking}. The internal data representation limits these
stacks to 128~MB (each) on 32-bit processors. More generally to
$\pow{2}{\mbox{bits-per-pointer} - 5}$ bytes, which implies they are
virtually unlimited on 64-bit machines.
As of version 7.7.14, the stacks are restricted by the writeable flag
\prologflag{stack_limit} or the command line option
\cmdlineoption{--stack-limit}. This flag limits the combined size of the
three stacks per thread. The default limit is currently 512~Mbytes on
32-bit machines, which imposes no additional limit considering the
128~Mbytes hard limit on 32-bit and 1~Gbytes on 64-bit machines.
Considering portability, applications that need to modify the default
limits are advised to do so using the Prolog flag
\prologflag{stack_limit}.
\begin{table}
\begin{center}
\begin{tabular}{|l|p{5cm}|}
\hline
Area name & Description \\
\hline
\bf local stack & The local stack is used to store
the execution environments of procedure
invocations. The space for an environment is
reclaimed when it fails, exits without leaving
choice points, the alternatives are cut off with
the !/0 predicate or no choice points have
been created since the invocation and the last
subclause is started (last call optimisation). \\
\bf global stack & The global stack is used
to store terms created during Prolog's
execution. Terms on this stack will be reclaimed
by backtracking to a point before the term
was created or by garbage collection (provided the
term is no longer referenced). \\
\bf trail stack & The trail stack is used to store
assignments during execution. Entries on this
stack remain alive until backtracking before the
point of creation or the garbage collector
determines they are no longer needed.
As the trail and global stacks are garbage
collected together, a small trail can cause
an excessive amount of garbage collections.
To avoid this, the trail is automatically
resized to be at least 1/6th of the size of
the global stack. \\
\hline
\end{tabular}
\end{center}
\caption{Memory areas}
\label{tab:areas}
\end{table}
\subsubsection{The heap} \label{sec:heap}
\index{stack,memory management}%
\index{memory,layout}%
With the heap, we refer to the memory area used by malloc()
and friends. SWI-Prolog uses the area to store atoms, functors,
predicates and their clauses, records and other dynamic data. No limits
are imposed on the addresses returned by malloc() and friends.
\subsection{Other Limits} \label{sec:morelimits}
\begin{description}
\item[Clauses]
The only limit on clauses is their arity (the number of arguments to
the head), which is limited to 1024. Raising this limit is easy and
relatively cheap; removing it is harder.
\item[Atoms and Strings]
SWI-Prolog has no limits on the length of atoms and strings. The number
of atoms is limited to 16777216 (16M) on 32-bit machines. On 64-bit
machines this is virtually unlimited. See also \secref{atomgc}.
\item[Memory areas]
On 32-bit hardware, SWI-Prolog data is packed in a 32-bit word, which
contains both type and value information. The size of the various memory
areas is limited to 128~MB for each of the areas, except for the program
heap, which is not limited. On 64-bit hardware there are no meaningful
limits.
\item[Nesting of terms]
Most built-in predicates that process Prolog terms create an explicitly
managed stack and perform optimization for processing the last argument
of a term. This implies they can process deeply nested terms at constant
and low usage of the C stack, and the system raises a resource error if
no more stack can be allocated. Currently only read/1 and write/1 (and
all variations thereof) still use the C stack and may cause the system
to crash in an uncontrolled way (i.e., not mapped to a Prolog exception
that can be caught).
\item[Integers]
On most systems SWI-Prolog is compiled with support for unbounded
integers by means of the GNU GMP library. In practice this means that
integers are bound by the global stack size. Too large integers cause a
\except{resource_error}. On systems that lack GMP, integers are 64-bit
on 32- as well as 64-bit machines.
Integers up to the value of the \prologflag{max_tagged_integer} Prolog
flag are represented more efficiently on the stack. For integers that
appear in clauses, the value (below \prologflag{max_tagged_integer} or
not) has little impact on the size of the clause.
\item[Floating point numbers]
Floating point numbers are represented as C-native double precision
floats, 64-bit IEEE on most machines.
\end{description}
\subsection{Reserved Names} \label{sec:resnames}
The boot compiler (see \cmdlineoption{-b} option) does not support the module
system. As large parts of the system are written in Prolog itself
we need some way to avoid name clashes with the user's predicates,
database keys, etc. Like Edinburgh C-Prolog \cite{CPROLOG:manual} all
predicates, database keys, etc., that should be hidden from the user
start with a dollar (\chr{\$}) sign.
\input{bit64.tex}
\section{Binary compatibility} \label{sec:abi-versions}
\index{compatibility,binary}%
\index{ABI,compatibility}%
SWI-Prolog first of all attempts to maintain \jargon{source code}
compatibility between versions. Data and programs can often be
represented in binary form. This touches a number of interfaces
with varying degrees of compatibility. The relevant version numbers
and signatures are made available by PL_version(), the
\cmdlineoption{--abi-version} and the Prolog flag
\prologflag{abi_version}.
\begin{description}
\definition{Foreign extensions}
Dynamically loadable foreign extensions have the usual dependencies on
the architecture, ABI model of the (C) compiler, dynamic link library
format, etc. They also depend on the backward compatibility of the PL_*
API functions provided lib \file{libswipl}.
A compatible API allows distribution of foreign extensions in binary
form, notably for platforms on which compilation is complicated (e.g.,
Windows). This compatibility is therefore high on the priority list, but
must infrequently be compromised.
PL_version(): \const{PL_VERSION_FLI}, \prologflag{abi_version} key:
\const{foreign_interface}
\definition{Binary terms}
Terms may be represented in binary format using PL_record_external() and
fast_write/2. As these formats are used for storing binary terms in
databases or communicate terms between Prolog processes in binary form,
great care is taken to maintain compatibility.
PL_version(): \const{PL_VERSION_REC}, \prologflag{abi_version} key:
\const{record}
\definition{QLF files}
QLF files (see qcompile/1) are binary representation of Prolog file or
module. They represent clauses as sequences of \jargon{virtual machine}
(VM) instructions. Their compatibility relies on the QLF file format and
the ABI of the VM. Some care is taken to maintain compatibility.
PL_version(): \const{PL_VERSION_QLF}, \const{PL_VERSION_QLF_LOAD} and
\const{PL_VERSION_VM}, \prologflag{abi_version} key: \const{qlf},
\const{qlf_min_load}, \const{vmi}
\definition{Saved states}
Saved states (see \cmdlineoption{-c} and qsave_program/2) is a zip file
that contains the entire Prolog database using the same representation
as QLF files. A saved state may contain additional resources, such as
foreign extensions, data files, etc. In addition to the dependency
concerns of QLF files, built-in and core library predicates may call
\emph{internal} foreign predicates. The interface between the public
built-ins and internal foreign predicates changes frequently. Patch
level releases in the \emph{stable branch} will as much as possible
maintain compatibility.
The relevant ABI version keys are the same as for QLF files with one
addition: PL_version(): \const{PL_VERSION_BUILT_IN}, \prologflag{abi_version}
key: \const{built_in}
\end{description}
|