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
|
\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}
machine% 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
\file{likes.pl} containing clauses for the predicates
\nopredref{likes}{2}:
\begin{code}
?- [likes].
% likes compiled, 0.00 sec, 17 clauses
true.
?-
\end{code}
After this point, Unix and Windows users unite, so if you are using
Unix please continue at \secref{execquery}.
\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{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 the 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.}
\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 startup file. The basename of this file follows
conventions of the operating system. On MS-Windows, it is the file
\file{swipl.ini} and on Unix systems \file{.swiplrc}. The file is
searched using the file_search_path/2 clauses for
\const{user_profile}.\footnote{Older versions first searched in the
current working directory. This feature has been removed for security
reasons. Users can implement loading a setup file from the working
directory in their global preference file.} The table below shows the
default value for this search path. The phrase <appdata> refers to the
Windows CSIDL name for the folder. The actual name depends on the
Windows language. English versions typically use \file{Application
Data}. See also win_folder/2
\begin{center}
\begin{tabular}{|l|l|l|}
\hline
& \bf Unix & \bf Windows \\
\hline
\bf home & \chr{~} & <appdata>/SWI-Prolog \\
\hline
\end{tabular}
\end{center}
\noindent
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/dotswiplrc} 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 an initialisation goal 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
\cmdlineoption{-q} may be used to suppress all informational messages.
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{argc} 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}. Also available as
\cmdlineoption{-arch}.
\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.
Also available as \cmdlineoption{-h} and \cmdlineoption{-help}.
\cmdlineoptionitem{--version}{}
When given as the only option, it summarises the version and the
architecture identifier. Also available as \cmdlineoption{-v}.
\end{description}
\subsection{Command line options for running Prolog}
\label{sec:running-options}
\begin{description}
\cmdlineoptionitem{--home=DIR}{}
Use 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{--nodebug}{}
Disable debugging. See the current_prolog_flag/2 flag
\prologflag{generate_debug_info} for details.
\cmdlineoptionitem{--nosignals}{}
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.
\cmdlineoptionitem{--pldoc}{[=port]}
Start the PlDoc documentation system on a free network port and launch
the user's browser on \url{http://localhost:<port>}. If \arg{port} is
specified, the server is started at the given port and the browser is
\emph{not} launched.
\cmdlineoptionitem{-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{-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{.swiplrc} (Unix) or \file{swipl.ini} (Windows).
`\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. In
particular, lists will be represented in the traditional way, double
quoted text is represented by a list of character codes and the
functional notation on maps is not supported. Maps as a syntactic entity
and the predicates that act on them remain 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}
The default limit for the Prolog stacks is 128~MB on 32-bit and 256~MB on
64-bit hardware. The 128~MB limit on 32-bit systems is the highest
possible value and the command line options can thus only be used to
lower the limit. On 64-bit systems, the limit can both be reduced and
enlarged. See \secref{limits}. Below are two examples, the first
reducing the local stack limit to catch unbounded recursion quickly and
the second using a big (32~GB) global limit, which is only possible on
64-bit hardware. Note that setting the limit using the command line only
sets a \emph{soft} limit. Stack parameters can be changed (both reduced
and enlarged) at any time using the predicate set_prolog_stack/2.
\begin{code}
$ swipl -L8m
$ swipl -G32g
\end{code}
\begin{description}
\cmdlineoptionitem*{-G}{size[kmg]}
Limit for the global stack (sometimes also called \jargon{term stack} or
\jargon{heap}). This is where compound terms and large numbers live.
\cmdlineoptionitem*{-L}{size[kmg]}
Limit for the local stack (sometimes also called
\jargon{environment stack}). This is where environments and
choice points live.
\cmdlineoptionitem*{-T}{size[kmg]}
Limit for the trail stack. This is where we keep track of assignments,
so we can rollback on backtracking or exceptions.
\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. Default is a
predicate which prints 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 here:
\begin{code}
% swipl <options> -g go,halt -t 'halt(1)'
\end{code}
\cmdlineoptionitem{-t}{goal}
Use \arg{goal} as interactive top level instead of the default goal
prolog/0. \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 restarted. This flag also determines the goal
started by break/0 and abort/0. If you want to stop the user from
entering interactive mode, start the application with
`\argoption{-g}{goal}' and give `halt' as top level.
\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{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{http://turing.ubishops.ca/home/bruda/emacs-prolog/}
\item \url{http://www.logic.at/prolog/ediprolog/ediprolog.html}
\item \url{http://www.logic.at/prolog/pceprolog/pceprolog.html}
\item \url{http://www.logic.at/prolog/etrace/etrace.html}
\end{shortlist}
\section{Online Help} \label{sec:help}
SWI-Prolog provides an online help system that covers this manual. If
the XPCE graphics system is available, online help opens a graphical
window. Otherwise the documentation is shown in the Prolog console. The
help system is controlled by the predicates below. Note that this
help system only covers the core SWI-Prolog manual. The
website\footnote{\url{http://www.swi-prolog.org}} provides an integrated
manual that covers the core system as well as all standard extension
packages. It is possible to install the SWI-Prolog website locally by
cloning the website repository
\url{git://www.swi-prolog.org/home/pl/git/plweb.git} and following the
instructions in the \file{README} file.
\begin{description}
\predicate{help}{0}{}
Equivalent to \exam{help(help/1)}.
\predicate{help}{1}{+What}
Show specified part of the manual. \arg{What} is one of:
\begin{center}\begin{tabular}{lp{3.5in}}
<Name>/<Arity> & Give help on specified predicate \\
<Name> & Give help on named predicate with any arity
or C interface function with that name \\
<Section> & Display specified section. Section numbers are
dash-separated numbers: \exam{2-3} refers to
section 2.3 of the manual. Section numbers are
obtained using apropos/1.
\end{tabular}\end{center}
Examples:
\begin{center}\begin{tabular}{lp{3.5in}}
\exam{?- help(assert).} & Give help on predicate assert \\
\exam{?- help(3-4).} & Display section 3.4 of the manual \\
\exam{?- help('PL_retry').}& Give help on interface function PL_retry() \\
\end{tabular}\end{center}
See also apropos/1 and the SWI-Prolog home page at
\url{http://www.swi-prolog.org}, which provides a FAQ, an HTML version
of the manual for online browsing, and HTML and PDF versions for downloading.
\predicate{apropos}{1}{+Pattern}
Display all predicates, functions and sections that have {\em
Pattern} in their name or summary description. Lowercase letters in
\arg{Pattern} also match a corresponding uppercase letter. Example:
\begin{center}\begin{tabular}{lp{\linewidth-3in}}
\exam{?- apropos(file).} & Display predicates, functions and sections
that have `file' (or `File', etc.) in their
summary description. \\
\end{tabular}\end{center}
\predicate{explain}{1}{+ToExplain}
Give an explanation on the given `object'. The argument may be any
Prolog data object. If the argument is an atom, a term of the form
\arg{Name/Arity} or a term of the form {\em Module:Name/Arity},
explain/1 describes the predicate as well as possible references to it.
See also gxref/0.
\predicate{explain}{2}{+ToExplain, -Explanation}
Unify \arg{Explanation} with an explanation for \arg{ToExplain}.
Backtracking yields further explanations.
\end{description}
\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 the Prolog flag \prologflag{readline}
is \const{false}. To enable this feature, 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.
28.00 seconds cpu time for 183,128 inferences
4,016 atoms, 1,904 functors, 2,042 predicates, 52 modules
55,915 byte codes; 11,239 external references
Limit Allocated In use
Heap : 624,820 Bytes
Local stack : 2,048,000 8,192 404 Bytes
Global stack : 4,096,000 16,384 968 Bytes
Trail stack : 4,096,000 8,192 432 Bytes
true.
\end{code}
\section{Overview of the Debugger} \label{sec:debugoverview}
SWI-Prolog has a 6-port tracer, extending the standard 4-port tracer
\cite{Byrd:80,Clocksin:87} with two additional ports. The optional
\arg{unify} port allows the user to inspect the result after unification
of the head. The \arg{exception} port shows exceptions raised by throw/1
or one of the built-in predicates. See \secref{exception}.
The standard ports are called \const{call}, \const{exit}, \const{redo},
\const{fail} and \const{unify}. The tracer is started by the trace/0
command, when a spy point is reached and the system is in debugging mode
(see spy/1 and debug/0), or when an exception is raised that is not
caught.
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{-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 same mechanism is useful for specifying
additional parameters for running a Prolog file on Windows. 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}
\verb$#!/path/to/swipl$
\verb$#!/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. Below is a simple
script doing expression evaluation:
\begin{code}
#!/usr/bin/env swipl
:- initialization main.
eval :-
current_prolog_flag(argv, Argv),
concat_atom(Argv, ' ', SingleArg),
term_to_atom(Term, SingleArg),
Val is Term,
format('~w~n', [Val]).
main :-
catch(eval, E, (print_message(error, E), fail)),
halt.
main :-
halt(1).
\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}
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 `Key'
instantiated, it unifies the value of the Prolog flag. Flag values are
typed. Flags marked as \const{bool} can have the values \const{true} or
\const{false}. 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 tecnhnique.} As a consequence,
modifying a flag inside a thread does not affect other threads.
\begin{description}
\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{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{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{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 reasone and because the current
definition is more practical.}
\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{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}{bool}{rw}
If \const{true} (default) autoloading of library functions is enabled.
\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{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_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{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{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.
\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}
Experimental flag that 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.
\termitem{control}{}
Compile meta-arguments that contain control structures ((A,B), (A;B),
(A->B;C), etc.). If not compiled at compile time, such arguments are
compiled to a temporary clause before execution. Using this option
enhances performance of processing complex meta-goals that are known
at compile time.
\termitem{true}{}
Also compile references to normal user predicates. This harms
performance (a little), but enhances the power of poor-mens consistency
check used by make/0 and implemented by list_undefined/0.
\termitem{always}{}
Always create an intermediate clause, even for system predicates. This
prepares 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 trace points (see trace/1).
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 {\tt true}, start the tracer after an error is detected. Otherwise
just continue execution. The goal that raised the error will normally
fail. See also fileerrors/2 and the Prolog flag {\tt report_error}. May
be changed. Default is {\tt true}, except for the runtime version.
\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{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{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{listing} 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_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{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{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{-nodebug}. 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>/boot32.prc} (32-bit machines) or
\file{<home>/boot64.prc} (64-bit machines) and to find its library as
\file{<home>/library}.
\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 on 32-bit hardware. Large file support is default on
installations built using \program{configure} that support it and may be
switched off using the configure option \const{--disable-largefile}.
\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_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_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{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{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{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{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{qcompile}{atom}{rw}
This option provides the default for the \term{qcompile}{+Atom} option
of load_files/2.
\prologflagitem{readline}{bool}{r}
If true, SWI-Prolog is linked with the readline library. This is done
by default if you have this library installed on your system. It is
also true for the Win32 swipl-win.exe version of SWI-Prolog, which realises
a subset of the readline functionality.
\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{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{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_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{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{-nosignals} is active. See
\secref{sigembedded} for details.
\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{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{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 convert_time/2.
\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 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{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{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}. 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. See also the \cmdlineoption{+/-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{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_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{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{version}{integer}{r}
The version identifier is an integer with value: $$10000 \times
\arg{Major} + 100 \times \arg{Minor} + \arg{Patch}$$
Note that in releases up to 2.7.10 this Prolog flag yielded an atom holding
the three numbers separated by dots. The current representation is much
easier for implementing version-conditional statements.
\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. Currently it is simply unified
to \const{[]}.
\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{windows}{bool}{r}
\index{windows}%
If present and \const{true}, the operating system is an implementation
of Microsoft Windows (NT/2000/XP, etc.). This flag is only available on
MS-Windows based versions.
\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/3. 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.
\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}, to 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 [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 does it call 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.
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 ~/lib/prolog
% cd ~/lib/prolog
% swipl -g true -t 'make_library_index(.)'
\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}
:- make_library_index('.',
[ '*.pl',
'trace/browse.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 necessarry to load
all predicates that would normally be autoloaded explicitly. This
is discussed in \secref{runtime}. See autoload/0.
\section{Garbage Collection} \label{sec:gc}
SWI-Prolog provides garbage collection, last-call optimization and atom
garbage collection. These features are controlled using Prolog flags
(see current_prolog_flag/2).
\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 \url[online
tutorials]{http://www.swi-prolog.org/Links.html}. 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
\url[Unicode]{http://www.unicode.org/}. See also \secref{widechars}.
\subsection{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}
\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{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}%
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.
\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, there
are two cases. First, if no hash table is available for the instantiated
arguments, it assesses the clauses for all instantiated arguments and
selects the best candidate for creating a hash table. Arguments that
cannot be indexed are flagged to avoid repeated scanning. Second, if
there is a hash table for an indexed argument but it has poor
characteristics, the system scans other instantiated arguments to see
whether it can create a better hash table. The system maintains a bit
vector on each table in which it marks arguments that are less suitable
than the argument to which the table belongs.
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. Dynamic predicates maintain a counter for
the number of goals running the predicate (a predicate can `run'
multiple times due to recursion, open choice points, and
multiple threads) and destroy removed indexes if this count drops to
zero. Outdated indexes of static predicates (e.g., due to reconsult or
enlarging multifile predicates) are reclaimed by
garbage_collect_clauses/0.
\end{itemlist}
\subsection{Future directions}
\label{sec:indexfut}
\begin{itemize}
\item
The current indexing system is largely prepared for secondary indexes.
This implies that if there are many clauses that match a given key, the
system could (JIT) create a secondary index. This secondary index could
exploit another argument or, if the key denotes a functor, an argument
inside the compound term.
\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.
\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 the environment. If the
environment variable \const{LANG} ends in "UTF-8", this encoding is
assumed. Otherwise the default is \const{text} and 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}
SWI-Prolog has a number of memory areas which are only enlarged to a
certain limit. The internal data representation limits the local,
global and trail stack to 128~MB on 32-bit processors, or more
generally to $\pow{2}{\mbox{bits-per-pointer} - 5}$ bytes. Considering
that almost all modern hardware can deal with this amount of memory with
ease, the default limits are set to their maximum on 32-bit hardware.
The representation limits can easily exceed physical memory on 64-bit
hardware. The default limits on 64-bit hardware are double that of 32-bit
hardware, which allows for storing the same amount of (Prolog) data.
The limits can be changed from the command line as well as at runtime
using set_prolog_stack/2. The table below shows these areas. The first
column gives the option name to modify the size of the area. The option
character is immediately followed by a number and optionally by a
\const{k} or \const{m}. With \const{k} or no unit indicator, the value
is interpreted in Kbytes (1024~bytes); with \const{m}, the value is
interpreted in Mbytes ($1024 \times 1024$ bytes).
The PrologScript facility described in \secref{plscript} provides a
mechanism for specifying options with the load file. On Windows the
default stack sizes are controlled using the Windows \idx{registry}
on the key \verb$HKEY_CURRENT_USER\Software\SWI\Prolog$ using the
names \const{localSize}, \const{globalSize} and \const{trailSize}. The
value is a \const{DWORD} expressing the default stack size in Kbytes.
A GUI for modifying these values is provided using the XPCE package.
To use this, start the XPCE manual tools using manpce/0, after which
you find \textit{Preferences} in the \textit{File} menu.
Considering portability, applications that need to modify the default
limits are advised to do so using set_prolog_stack/2.
\begin{table}
\begin{center}
\begin{tabular}{|c|c|l|p{5cm}|}
\hline
Option & Default & Area name & Description \\
\hline
\cmdlineoption{-L} & 128M & \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). \\
\cmdlineoption{-G} & 128M & \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). \\
\cmdlineoption{-T} & 128M & \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. \\
\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 sizes of atoms and strings. read/1 and
its derivatives, however, normally limit the number of newlines in an atom
or string to 6 to improve error detection and recovery. This can be
switched off with style_check/1.
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}
|