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
|
\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 `pl', though some administrators
call it `swipl' or `swi-prolog'. 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% pl
Welcome to SWI-Prolog (Version 5.0.0)
Copyright (c) 1990-2002 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.
For help, use ?- help(Topic). or ?- apropos(Word).
1 ?-
\end{code}
After starting Prolog, one normally loads a program into it using
consult/1, which---for historical reasons---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 likes/2:
\begin{code}
?- [likes].
% likes compiled, 0.00 sec, 596 bytes.
Yes
?-
\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}
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 {\em directory} in the remainder of this
document) called \file{pl} containing the executables,
libraries, etc. of the system. No files are installed
outside this directory.
\item A program \program{plwin.exe}, providing a window for interaction
with Prolog. The program \program{plcon.exe} is a version of
SWI-Prolog that runs in a DOS-box.
\item The file-extension \fileext{pl} is associated with the program
\program{plwin.exe}. Opening a \fileext{pl} file will cause
\program{plwin.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 with 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 to prove whether `john' likes someone and
who is liked by `john'. 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 (;) if (s)he wants another solution, or {\sc return} if
(s)he is satisfied, after which Prolog will say {\bf Yes}. If Prolog
answers {\bf No}, it indicates it cannot find any more answers to the
query. Finally, Prolog can answer using an error message to indicate
the query or program contains an error.
\begin{code}
?- likes(john, X).
X = mary
\end{code}
\section{The user's initialisation file} \label{sec:initfile}
\index{startup file}%
\index{user profile file}%
\index{profile file}%
After the necessary system initialisation the system consults (see
consult/1) the user's startup file. The base-name of this file follows
conventions of the operating system. On MS-Windows, it is the file
\file{pl.ini} and on Unix systems \file{.plrc}. The file is searched
using the file_search_path/2 clauses for \const{user_profile}. The table
below shows the default value for this search-path.
\begin{center}
\begin{tabular}{|l|l|l|}
\hline
& \bf Unix & \bf Windows \\
\hline
\bf local & \file{.} & \file{.} \\
\bf home & \file{~} & \file{%HOME%} or
\file{%HOMEDRIVE%\%HOMEPATH%} \\
global & & SWI-Home directory or
\file{%WINDIR%} or \file{%SYSTEMROOT%} \\
\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.
\section{Initialisation files and goals} \label{sec:initgoal}
Using commandline 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{toplevel goal}. The following
is a typical example for starting an application directly from the
commandline.
\begin{code}
machine% pl -f 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} go/0 and ---instead of entering the interactive
toplevel--- exit after completing go/0. The \cmdlineoption{-q} may be
used to supress all informational messages.
In MS-Windows, the same can be achieved using a short-cut with
appropriately defined commandline 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 mean to deliver executables that do not
require the Prolog system.
\section{Command line options} \label{sec:cmdline}
The full set of command line options is given below:
\begin{description}
\cmdlineoptionitem{-help}{}
When given as the only option, it summarises the most important options.
\cmdlineoptionitem{-v}{}
When given as the only option, it summarises the version and the
architecture identifier.
\cmdlineoptionitem{-arch}{}
When given as the only option, it prints the architecture identifier
(see current_prolog_flag(arch, Arch)) and exits. See also
\cmdlineoption{-dump-runtime-variables}.
\cmdlineoptionitem{-dump-runtime-variables}{}
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{plld} (see \secref{plld}). Below is
a typical example of using this feature.
\begin{code}
eval `pl -dump-runtime-variables`
cc -I$PLBASE/include -L$PLBASE/runtime/$PLARCH ...
\end{code}
\cmdlineoptionitem{-q}{}
\index{verbose}\index{quiet}%
Set the prolog-flag \const{verbose} to \const{silent}, supressing
informational and banner messages.
\cmdlineoptionitem*{-L}{size[km]}
Give local stack limit (2 Mbytes default). Note that there is no space
between the size option and its argument. By default, the argument is
interpreted in Kbytes. Postfixing the argument with \const{m} causes
the argument to be interpreted in Mbytes. The following example
specifies 32 Mbytes local stack.
\begin{code}
% pl -L32m
\end{code}
A maximum is useful to stop buggy programs from claiming all memory
resources. \cmdlineoption{-L0} sets the limit to the highest possible
value. See \secref{limits}.
\cmdlineoptionitem*{-G}{size[km]}
Give global stack limit (4 Mbytes default). See \cmdlineoption{-L} for
more details.
\cmdlineoptionitem*{-T}{size[km]}
Give trail stack limit (4 Mbytes default). This limit is relatively high
because trail-stack overflows are not often caused by program bugs. See
\cmdlineoption{-L} for more details.
\cmdlineoptionitem*{-A}{size[km]}
Give argument stack limit (1 Mbytes default). The argument stack limits
the maximum nesting of terms that can be compiled and executed.
SWI-Prolog does `last-argument optimisation' to avoid many deeply nested
structure using this stack. Enlarging this limit is only necessary in
extreme cases. See \cmdlineoption{-L} for more details.
\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.
\cmdlineoptionitem{-O}{}
Optimised compilation. See current_prolog_flag/2.
\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 \cmdlineoptionitem{-s}
does not stop Prolog from loaded the personal initialisation file.
\cmdlineoptionitem{-f}{file}
Use \arg{file} as initialisation file instead of the default
\file{.plrc} (Unix) or \file{pl.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}
Selects 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{-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
thus be suppressed by giving \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 Unix shell.
\cmdlineoptionitem{-t}{goal}
Use \arg{goal} as interactive toplevel instead of the default goal
prolog/0. \arg{goal} can be a complex term. If the toplevel goal
succeeds SWI-Prolog exits with status 0. If it fails the exit status is 1.
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 toplevel.
\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. This flag is sometimes required for smooth interaction
with other applications.
\cmdlineoptionitem{-x}{bootfile}
Boot from \arg{bootfile} instead of the system's default boot file. A
bootfile 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, \arg{path1 ...} is a \chr{:} separated list of values for
the alias. 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{{\tt --}}{}
\index{commandline, 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 \const{argv} for obtaining the commandline arguments.
\end{description}
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}{level}
Set debug level to \arg{level}. 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}
The default Prolog mode for GNU-Emacs can be activated by adding
the following rules to your Emacs initialisation file:
\begin{code}
(setq auto-mode-alist
(append
'(("\\.pl" . prolog-mode))
auto-mode-alist))
(setq prolog-program-name "pl")
(setq prolog-consult-string "[user].\n")
;If you want this. Indentation is either poor or I don't use
;it as intended.
;(setq prolog-indent-width 8)
\end{code}
Unfortunately the default Prolog mode of GNU-Emacs is not very good. An
alternative \file{prolog.el} file for GNU-Emacs 20 is available from
\url{http://www.freesoft.cz/~pdm/software/emacs/prolog-mode/} and for
GNU-Emacs 19 from
\url{http://w1.858.telia.com/~u85810764/Prolog-mode/index.html}
\section{Online Help} \label{sec:help}
Online help provides a fast lookup and browsing facility to this
manual. The online manual can show predicate definitions as well as
entire sections of the manual.
The online help is displayed from the file \pllib{'MANUAL'}. The file
\pllib{helpidx} provides an index into this file. \pllib{'MANUAL'} is
created from the \LaTeX{} sources with a modified version of
\program{dvitty}, using overstrike for printing bold text and
underlining for rendering italic text. XPCE is shipped with
\pllib{swi_help}, presenting the information from the online help in a
hypertext window. The prolog-flag \const{write_help_with_overstrike}
controls whether or not help/1 writes its output using overstrike to
realise bold and underlined output or not. If this prolog-flag is not set it
is initialised by the help library to \const{true} if the \const{TERM}
variable equals \const{xterm} and \const{false} otherwise. If this
default does not satisfy you, add the following line to your personal
startup file (see \secref{initfile}):
\begin{code}
:- set_prolog_flag(write_help_with_overstrike, true).
\end{code}
\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.psy.uva.nl/projects/SWI-Prolog/}, which provides
a FAQ, an HTML version of 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{3.5in}}
\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 will try to explain the predicate
as well as possible references to it.
\predicate{explain}{2}{+ToExplain, -Explanation}
Unify \arg{Explanation} with an explanation for \arg{ToExplain}.
Backtracking yields further explanations.
\end{description}
\section{Query Substitutions} \label{sec:history}
SWI-Prolog offers a query substitution mechanism similar to that of Unix
csh (csh(1)), called `history'. The availability of this feature is
controlled by set_prolog_flag/2, using the \const{history} prolog-flag. By
default, history is available if the prolog-flag \const{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. It also allows to correct
queries and syntax errors. SWI-Prolog does not offer the Unix csh
capabilities to include arguments. This is omitted as it is unclear how
the first, second, etc.\ argument should be defined.%
\footnote{One could choose words, defining words as a sequence of
alpha-numeric characters and the word separators as
anything else, but one could also choose Prolog
arguments}
The available history commands are shown in \tabref{history}.
\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+!?str.+ & Repeat last query holding <str> \\
\verb+^old^new.+ & Substitute <old> into <new> in
last query \\
\verb+!nr^old^new.+ & Substitute in query numbered <nr> \\
\verb+!str^old^new.+ & Substitute in query starting with <str> \\
\verb+!?str^old^new.+ & Substitute in query holding <str> \\
\verb+h.+ & Show history list \\
\verb+!h.+ & Show this list \\
\hline
\end{tabular}
\end{center}
\caption{History commands}
\label{tab:history}
\end{table}
\subsection{Limitations of the History System} \label{sec:histlimits}
History expansion is executed after \jargon{raw-reading}. This is the
first stage of read_term/2 and friends, reading the term into a string
while deleting comment and canonising blank. This makes it hard to use
it for correcting syntax errors. Command-line editing as provided using
the GNU-readline library is more suitable for this. History expansion is
first of all useful for executing or combining commands from long ago.
\section{Reuse of toplevel bindings} \label{sec:topvars}
Bindings resulting from the successful execution of a toplevel goal
are asserted in a database. These values may be reused in further
toplevel queries as \$Var. Only the latest binding is available.
Example:
\begin{figure}
\begin{code}
1 ?- maplist(plus(1), "hello", X).
X = [105,102,109,109,112]
Yes
2 ?- format('~s~n', [$X]).
ifmmp
Yes
3 ?-
\end{code}
\caption{Reusing toplevel bindings}
\label{fig:topevelvars}
\end{figure}
Note that variables may be set by executing \predref{=}{2}:
\begin{code}
6 ?- X = statistics.
X = statistics
Yes
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
Yes
8 ?-
\end{code}
\section{Overview of the Debugger} \label{sec:debugoverview}
SWI-Prolog has a 6-port tracer, extending the standard 4-port tracer
\cite{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.
The interactive toplevel 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
\const{debugger_print_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}
1 ?- visible(+all), leash(-exit).
Yes
2 ?- trace, min([3, 2], X).
Call: ( 3) min([3, 2], G235) ? creep
Unify: ( 3) min([3, 2], G235)
Call: ( 4) min([2], G244) ? creep
Unify: ( 4) min([2], 2)
Exit: ( 4) min([2], 2)
Call: ( 4) min(3, 2, G235) ? creep
Unify: ( 4) min(3, 2, G235)
Call: ( 5) 3 < 2 ? creep
Fail: ( 5) 3 < 2 ? creep
Redo: ( 4) min(3, 2, G235) ? creep
Exit: ( 4) min(3, 2, 2)
Exit: ( 3) min([3, 2], 2)
Yes
[trace] 3 ?-
\end{code}
\caption{Example trace}
\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 return, space).}
\traceoption{d}{Display}{
Set the \term{max_depth}{Depth} option of
\const{debugger_print_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 \const{debugger_print_options} to
\texttt{[quoted(true), portray(true), max_depth(10)]}. 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 \const{debugger_print_options} to
\exam{[quoted(true)]}, bypassing portray/1, etc.}
\end{description}
The ideal 4 port model 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, tail recursion optimisation is
switched off.%
\footnote{This implies the system can run out of local 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
consult/1, or the list abbreviation. 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}
% pl
<banner>
1 ?- [load].
<compilation messages>
Yes
2 ?- go.
<program interaction>
\end{code}
When using Windows, the user may open \file{load.pl} from the Windows
explorer, which will cause \program{plwin.exe} to be started in the
directory holding \file{load.pl}. Prolog loads \file{load.pl} before
entering the toplevel.
\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}
New in version 4.0.5 is the possibility to use a Prolog source file
directly as a Unix script-file. the same mechanism is useful to
specify additional parameters for running a Prolog file on Windows.
If the first letter of a Prolog file is \verb$#$, the first line is
treated as 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, make the first line start like this:
\begin{quote}
\verb$#!/path/to/pl$ <options> \verb$-s$
\end{quote}
Prolog recognises this starting sequence and causes the interpreter
to receive the following argument-list:
\begin{quote}
\verb$/path/to/pl$ <options> \verb$-s$ <script> \verb$--$ <ScriptArguments>
\end{quote}
Instead of \cmdlineoption{-s}, the user may use \cmdlineoption{-f} to
stop Prolog from looking for a personal initialisation file.
Here is a simple script doing expression evaluation:
\begin{code}
#!/usr/bin/pl -q -t main -f
eval :-
current_prolog_flag(argv, Argv),
append(_, [--|Args], Argv),
concat_atom(Args, ' ', 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: Arithmetic: `foo/0' is not a function
%
\end{code}
\paragraph{The Windows version} supports the \verb$#!$ construct too,
but here it serves a rather different role. The Windows shell already
allows the user to start Prolog source-files directly through the
Windows file-type association. Windows however makes it rather
complicated to provide additional parameters, such as the required
stack-size for an individual Prolog file. The \verb$#!$ line provides
for this, providing a more flexible approach then changing the global
defaults. The following starts Prolog with unlimited stack-size on
the given source-file:
\begin{code}
#!/usr/bin/pl -L0 -T0 -G0 -s
....
\end{code}
Note the use of \verb$/usr/bin/pl$, which specifies the interpreter.
This argument is ignored in the Windows version, but required to ensure
best cross-platform compatibility.
\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=pl
exec $PL -f none -g "load_files(['$base/load'],[silent(true)])" \
-t go -- $*
\end{code}
\begin{code}
go :-
current_prolog_flag(argv, Arguments),
append(_SytemArgs, [--|Args], Arguments), !,
go(Args).
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 using the linker plld(1). A saved state is
a file containing machine-independent 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 commandline 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}
% pl [option ...] [-o output] -c file ...
\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
main/0 and for which the source is loaded through \file{load.pl}, use
the command
\begin{code}
% pl --goal=main --stand_alone=true -o myprog -c load.pl
\end{code}
This performs exactly the same as executing
\begin{code}
% pl
<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{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 the `Key'
instantiated it unify the value of the prolog-flag. Features come in
three types: boolean prolog-flags, prolog-flags with an atom value and
prolog-flags with an integer value. A boolean prolog-flag is true iff
the prolog-flag is present {\bf and} the \arg{Value} is the atom
\const{true}. Currently defined keys:
\begin{description}
\prologflagitem{arch}{atom}{r}
Identifier for the hardware and operating system SWI-Prolog is running
on. Used to determine the startup file as well as to select foreign
files for the right architecture. See also \secref{shlib}.
\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{home}{atom}{r}
SWI-Prolog's notion of the home-directory. SWI-Prolog uses it's home
directory to find its startup file as \file{<home>/startup/startup.<arch>}
and to find its library as \file{<home>/library}.
\prologflagitem{executable}{atom}{r}
Path-name of the running executable. Used by qsave_program/2 as default
emulator.
\prologflagitem{argv}{list}{r}
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.
\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{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{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{dynamic_stacks}{bool}{r}
If \const{true}, the system uses some form of `sparse-memory management'
to realise the stacks. If false, malloc()/realloc() are used for the
stacks. In earlier days this had consequenses for foreign code. As of
version 2.5, this is no longer the case.
Systems using `sparse-memory management' are a bit faster as there is no
stack-shifter, and checking the stack-boundary is often realised by the
hardware using a `guard-page'. Also, memory is actually returned to the
system after a garbage collection or call to trim_stacks/0 (called by
prolog/0 after finishing a user-query).
\prologflagitem{c_libs}{atom}{r}
Libraries passed to the C-linker when SWI-Prolog was linked. May be used
to determine the libraries needed to create statically linked extensions
for SWI-Prolog. See \secref{plld}.
\prologflagitem{c_cc}{atom}{r}
Name of the C-compiler used to compile SWI-Prolog. Normally either gcc
or cc. See \secref{plld}.
\prologflagitem{c_ldflags}{atom}{r}
Special linker flags passed to link SWI-Prolog. See \secref{plld}.
\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 plwin.exe version of SWI-Prolog, which realises
a subset of the readline functionality.
\prologflagitem{saved_program}{bool}{r}
If true, Prolog is started from a state saved with qsave_program/[1,2].
\prologflagitem{runtime}{bool}{r}
If true, SWI-Prolog is compiled with -DO_RUNTIME, disabling various
useful development features (currently the tracer and profiler).
\prologflagitem{max_integer}{integer}{r}
Maximum integer value. Most arithmetic operations will automatically
convert to floats if integer values above this are returned.
\prologflagitem{min_integer}{integer}{r}
Minimum integer value.
\prologflagitem{max_tagged_integer}{integer}{r}
Maximum integer value represented as a `tagged' value. Tagged integers
require 4-bytes storage and are used for indexing. Larger integers are
represented as `indirect data' and require 16-bytes on the stacks (though
a copy requires only 4 additional bytes).
\prologflagitem{min_tagged_integer}{integer}{r}
Start of the tagged-integer value range.
\prologflagitem{float_format}{atom}{rw}
C {\tt printf()} format specification used by write/1 and friends to
determine how floating point numbers are printed. The default is {\tt
\%g}. The specified value is passed to printf() without further
checking. For example, if you want more digits printed, {\tt \%.12g}
will print all floats using 12 digits instead of the default 6. See also
format/[1,2], write/1, print/1 and portray/1.
\prologflagitem{toplevel_print_options}{term}{rw}
This argument is given as option-list to write_term/2 for printing results
of queries. Default is \exam{[quoted(true), portray(true), max_depth(10)]}.
\prologflagitem{debugger_print_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 \exam{[quoted(true), portray(true),
max_depth(10)]}.
\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{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{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{double_quotes}{codes,chars,atom,string}{rw}
This flag determines how double-quotes strings are read by Prolog and is
---like character_escapes--- maintained for each module. If
\const{codes} (default), a list of character-codes is returned, if
\const{chars} a list of one-character atoms, if \const{atom} double
quotes are the same as single-quotes and finally, \const{string} reads
the text into a Prolog string (see \secref{strings}). See also
atom_chars/2 and atom_codes/2.
\prologflagitem{allow_variable_name_as_functor}{bool}{rw}
If true (default is false), \exam{Functor(arg)} is read as if it was
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{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 commandline editor. The default is to set this prolog-flag to 0
if a commandline editor is provided (see prolog-flag \const{readline}) and
15 otherwise.
\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{agc_margin}{integer}{rw}
If this amount of atoms has been created since the last atom-garbage
collection, 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().
\prologflagitem{iso}{bool}{rw}
Include some weird ISO compatibility that is incompatible to normal
SWI-Prolog behaviour. Currently it has the following effect:
\begin{itemize}
\item is/2 and evaluation under flag/3 do not automatically convert
floats to integers if the float represents an integer.
\item The \functor{/}{2} (float division) {\em always} return 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 an instantiation 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.
\end{itemize}
\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}
commandline option.
Currently optimise 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{char_conversion}{bool}{rw}
Determines whether character-conversion takes place while reading terms.
See also char_conversion/2.
\prologflagitem{autoload}{bool}{rw}
If \const{true} (default) autoloading of library functions is enabled.
See \secref{autoload}.
\prologflagitem{verbose_autoload}{bool}{rw}
If \const{true} the normal consult message will be printed if a library
is autoloaded. By default this message is suppressed. Intended to be
used for debugging purposes.
\prologflagitem{verbose_file_search}{bool}{rw}
If \const{true} (default \const{false}), print messages indicating the
progress of absolute_file_name/[2,3] in locating files. Intended for
debugging complicated file-search paths. See also file_search_path/2.
\prologflagitem{trace_gc}{bool}{rw}
If true (false is the default), garbage collections and stack-shifts
will be reported on the terminal. May be changed.
\prologflagitem{max_arity}{unbounded}{r}
ISO prolog-flag describing there is no maximum arity to compound terms.
\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{bounded}{true}{r}
ISO prolog-flag describing integer representation is bound by
{\tt min_integer} and {\tt min_integer}.
\prologflagitem{tty_control}{bool}{r}
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{unknown}{fail,warning,error}{rw}
Determines the behaviour if an undefined procedure is encountered. If
\const{fail}, the predicates 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.
\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, tail-recursion 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{tail_recursion_optimisation}{bool}{rw}
Determines whether or not tail-recursion optimisation is enabled.
Normally the value of this flag is equal to the \const{debug} flag. As
programs may run out of stack if tail-recursion optimisation is omitted,
it is sometimes necessary to enable it during debugging.
\prologflagitem{abort_with_exception}{bool}{rw}
Determines how abort/0 is realised. See the description of abort/0
for details.
\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{report_error}{bool}{rw}
If {\tt true}, print error messages, otherwise suppress them. May be
changed. See also the {\tt debug_on_error} prolog-flag. Default is {\tt
true}, except for the runtime version.
\prologflagitem{verbose}{Atom}{rw}
This flags is used by print_message/2. If its value is \const{silent},
messages of type \const{informational} and \const{banner} are supressed.
The \cmdlineoption{-q} switches the value from the initial
\const{normal} to \const{silent}.
\prologflagitem{file_name_variables}{bool}{rw}
If \const{true} (default \const{false}), expand \file{\$\arg{varname}}
and \file{~} in arguments of builtin-predicates that accept a file name
(open/3, exists_file/1, access_file/2, etc.). The predicate
expand_file_name/2 should be used to expand environment variables
and wildcard patterns. This prolog-flag is intended for backward
compatibility with older versions of SWI-Prolog.
\prologflagitem{unix}{bool}{r}
\index{unix}%
If {\tt 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}.
\prologflagitem{windows}{bool}{r}
\index{windows}%
If {\tt true}, the operating system is an implementation of Microsoft
Windows (3.1, 95, NT, etc.).
\end{description}
\prologflagitem{hwnd}{integer}{r}
In \program{plwin.exe}, this refers to the MS-Windows window-handle of
the console window.
\predicate{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.
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.
\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 [library_directory/1]
Hook into absolute_file_name/3 to define new library directories.
(most Prolog system).
\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/1 to modify read terms before they are compiled
(macro-processing) (most Prolog system).
\item [goal_expansion/2]
Same as term_expansion/2 for individual goals (SICStus).
\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 some 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]
Defines a new resource (not really a hook, but similar) (SWI).
\item [exception/3]
Old attempt to a generic hook mechanism. Handles undefined predicates (SWI).
\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. If
this fails the \jargon{auto loader} is activated. On first activation an
index to all library files in all library directories is loaded in core
(see library_directory/1). If the undefined predicate can be located in
the one of the libraries that library file is automatically loaded and
the call to the (previously undefined) predicate is resumed. By default
this mechanism loads the file silently. The current_prolog_flag/2
\const{verbose_autoload} is provided to get verbose loading. The
prolog-flag \const{autoload} can be used to enable/disable the entire
auto load system.
The auto-loader only works if the unknown flag (see unknown/2) is set to
\const{trace} (default). A more appropriate interaction with this flag
should be considered.
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 will be imported
to 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 a completely indexed library directory.
\begin{code}
% mkdir ~/lib/prolog
% cd !$
% pl -g true -t 'make_library_index(.)'
\end{code}
If there are more than one library files 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{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}
\end{description}
\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{Syntax Notes} \label{sec:syntax}
SWI-Prolog uses standard `Edinburgh' syntax. A description of this
syntax can be found in the Prolog books referenced in the introduction.
Below are some non-standard or non-common constructs that are accepted
by SWI-Prolog:
\begin{itemlist}
\item [\exam{0'<char>}]
This construct is not accepted by all Prolog systems that claim to have
Edinburgh compatible syntax. It describes the ASCII value of <char>.
To test whether \chr{C} is a lower case character one can use
\exam{between(0'a, 0'z, C)}.
\item [\exam{/* \ldots /* \ldots */ \ldots */}]
The \exam{/* \ldots */} comment statement can be nested. This is useful
if some code with \exam{/* \ldots */} comment statements in it should be
commented out.
\end{itemlist}
\subsection{ISO Syntax Support} \label{sec:isosyntax}
SWI-Prolog offers ISO compatible extensions to the Edinburgh syntax.
\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 lead in by the backslash (\chr{\}) character. The list of
escape sequences is compatible with the ISO standard, but contains one
extension and the interpretation of numerically specified characters is
slightly more flexible to improve compatibility.
\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. For compatibility with Quintus Prolog.
Not supported by ISO. Example:
\begin{code}
format('This is a long line that would look better if it was \c
split across multiple physical lines in the input')
\end{code}
\escapeitem{\bnfmeta{{\sc RETURN}}}
No output. Skips input till the next non-layout character or to the
end of the next line. Same intention as \fmtseq{\c} but ISO compatible.
\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{t}
Horizontal tab-character.
\escapeitem{v}
Vertical tab-character (ASCII 11).
\escapeitem{x23}
Hexadecimal specification of a character. \verb$23$ is just an example.
The `x' may be followed by a maximum of 2 hexadecimal digits. The
closing \verb$\$ is optional. The code \verb$\xa\3$ emits the character
10 (hexadecimal `a') followed by `3'. The code \verb$\x201$ emits
32 (hexadecimal `20') followed by `1'. According to ISO, the closing
\verb$\$ is obligatory and the number of digits is unlimited. The
SWI-Prolog definition allows for ISO compatible specification, but
is compatible with other implementations.
\escapeitem{40}
Octal character specification. The rules and remarks for hexadecimal
specifications apply to octal specifications too, but the maximum
allowed number of octal digits is 3.
\escapeitem{<character>}
Any character immediately preceded by a \chr{\} and not covered by the
above escape sequences is copied verbatim. Thus, \verb$'\\'$ is an atom
consisting of a single \chr{\} and \verb$'\''$ and \verb$''''$ both
describe the atom with a single~\verb$'$.
\end{description}
Character escaping is only available if the
\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
character escapes handling by read has already interpreted as 32 (40
octal). Also, \fmtseq{\l} is translated to a single `l'. It is advised
to use the more widely supported format/[2,3] predicate instead. If you
insist upon using writef/2, either switch \const{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.
\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 default sizes for these areas should suffice for most
applications, but big applications may require larger ones. They are
modified by command line options. 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 local-, global- and trail-stack are limited to 128 Mbytes on 32 bit
processors, or more generally to $\pow{2}{\mbox{bits-per-long} - 5}$
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.
\begin{table}
\begin{center}
\begin{tabular}{|c|c|l|p{5cm}|}
\hline
Option & Default & Area name & Description \\
\hline
\cmdlineoption{-L} & 2M & \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 of with
the !/0 predicate or no choice points have
been created since the invocation and the last
subclause is started (tail recursion optimisation). \\
\cmdlineoption{-G} & 4M & \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} & 4M & \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 nor needed any longer. \\
\cmdlineoption{-A} & 1M & \bf argument stack & The argument stack is used to
store one of the intermediate code interpreter's
registers. The amount of space needed on this
stack is determined entirely by the depth in
which terms are nested in the clauses that
constitute the program. Overflow is most likely
when using long strings in a clause. \\
\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 \funcref{malloc}{}
and friends. SWI-Prolog uses the area to store atoms, functors,
predicates and their clauses, records and other dynamic data. As of
SWI-Prolog 2.8.5, no limits are imposed on the addresses returned by
\funcref{malloc}{} and friends.
On some machines, the runtime stacks described above are allocated using
`sparse allocation'. Virtual space up to the limit is claimed at startup
and committed and released while the area grows and shrinks. On Win32
platform this is realised using \funcref{VirtualAlloc}{} and friends.
On Unix systems this is realised using \funcref{mmap}{}.
\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 5 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[Address space]
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.
\item[Integers]
Integers are 32-bit (64 on 64-bit machines) to the user, but integers up
to the value of the \const{max_tagged_integer} prolog-flag are
represented more efficiently.
\item[Floats]
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 (see style_check/1).
|