Go to the first, previous, next, last section, table of contents.

How to Run Prolog

SICStus Prolog offers the user an interactive programming environment with tools for incrementally building programs, debugging programs by following their executions, and modifying parts of programs without having to start again from scratch.

The text of a Prolog program is normally created in a file or a number of files using one of the standard text editors. The Prolog interpreter can then be instructed to read in programs from these files; this is called consulting the file. Alternatively, the Prolog compiler can be used for compiling the file.

Getting Started

SICStus Prolog is normally started from one of the UNIX shells. However, it is often convenient to run SICStus Prolog under GNU Emacs instead. A GNU Emacs mode for SICStus Prolog is described later (see section Emacs Interface). From a UNIX shell, SICStus Prolog is started by typing:

% sicstus [-f] [-i] [-B] [-l prolog-file] \
  [-P[T] [num] [-F [num]]] [-a argument...]

where the flags have the following meaning:

-f
Fast start. Don't read the `~/.sicstusrc' or `~/.sicstus.ini' file on startup and on reinitialise/0. If the flag is omitted, SICStus Prolog will consult this file on startup and on reinitialise/0, if it exists.
-i
Forced interactive. Prompt for user input, even if the standard input does not appear to be a terminal.
-B
Start by bootstrapping (i.e. not from a saved state).
-l prolog-file
Ensure the file prolog-file is loaded on startup and on reinitialise/0.
-P [num]
-PT [num]
The uninstrumented (-P) or trace (-PT) version of Muse is started. As an option, num specifies the initial number of workers used (defaults to 1). See section The Muse Model. Only available if Muse has been installed.
-F num
Only useful for the Sequent Symmetry version of Muse. Its purpose is to preallocate shared memory for num workers. If the `-F' argument is not used, num is assumed to be equal to the default number of workers. `-F' implies `-B'.
-a argument...
where the arguments can be retrieved from Prolog by prolog_flag(argv, Args), which will unify Args with argument... represented as a list of atoms.

To start SICStus Prolog from a saved state file, issue the shell command:

% file argument...

Notice that the flags are not available in this variant--all the command line arguments are treated as Prolog arguments. The above command is equivalent to:

% sicstus -r file [-a argument...]

The Development System responds with a message of identification and the prompt `| ?- ' as soon as it is ready to accept input, thus:

SICStus 3 #0: Wed Mar 15 12:29:29 MET 1995
| ?-

At this point the top-level is expecting input of a directive, i.e. a query or command. See section Directives: Queries and Commands. You cannot type in clauses immediately (see section Inserting Clauses at the Terminal). While typing in a directive, the prompt (on following lines) becomes ` '. That is, the `| ?- ' appears only for the first line of the directive, and subsequent lines are indented.

The following environment variables can be set before starting SICStus Prolog. Some of these override the default sizes of certain areas. The sizes are given in cells:

SP_PATH
If SICStus Prolog was started by sicstus -B ..., the value returned by the predicate user:library_directory/1 is derived from this environment variable if set, and otherwise from the absolute path name of the Development System, as far as it can be determined. The path to the Runtime Library for a Runtime System is also derived from SP_PATH. Finally, commands for building foreign resources, Development Systems and Runtime Systems are placed in `$SP_PATH/bin'.
SP_CTYPE
Selects the appropriate character set standard: The supported values are euc (for EUC) and iso_8859_1 (for ISO 8859/1). The latter is the default.
TMPDIR
If set, indicates the pathname where temporary files should be created. Defaults to `/usr/tmp'.
GLOBALSTKSIZE
Governs the initial size of the global stack.
LOCALSTKSIZE
Governs the initial size of the local stack.
CHOICESTKSIZE
Governs the initial size of the choicepoint stack.
TRAILSTKSIZE
Governs the initial size of the trail stack.

Send bug reports to <sicstus-bug@sics.se>. Bugs tend actually to be fixed if they can be isolated, so it is in your interest to report them in such a way that they can be easily reproduced.

The mailing list <sicstus-users@sics.se> is a mailing list for communication among users and implementors. To [un]subscribe, write to <sicstus-users-request@sics.se>.

Reading in Programs

A program is made up of a sequence of clauses, possibly interspersed with directives to the interpreter. The clauses of a predicate do not have to be immediately consecutive, but remember that their relative order may be important (see section Procedural Semantics).

To input a program from a file file, just type the filename inside list brackets (followed by . and RET), thus:

| ?- [file].

This instructs the interpreter to read in (consult) the program. Note that it may be necessary to surround the whole file specification file with single quotes to make it a legal Prolog atom; e.g.

| ?- ['myfile.pl'].

| ?- ['/usr/prolog/somefile'].

The specified file is then read in. Clauses in the file are stored so that they can later be interpreted, while any directives are obeyed as they are encountered. When the end of the file is found, the interpreter displays on the terminal the time spent for read-in. This indicates the completion of the directive.

Predicates that expect the name of a Prolog source file as an argument use
absolute_file_name/2 (see section Stream IO) to look up the file. This predicate will first search for a file with the suffix `.pl' added to the name given as an argument. If this fails it will look for a file with no extra suffix added. There is also support for libraries.

In general, this directive can be any list of filenames, such as:

| ?- [myprog,extras,tests].

In this case all three files would be consulted.

The clauses for all the predicates in the consulted files will replace any existing clauses for those predicates, i.e. any such previously existing clauses in the database will be deleted.

Note that consult/1 in SICStus Prolog behaves like reconsult/1 in DEC-10 Prolog.

Inserting Clauses at the Terminal

Clauses may also be typed in directly at the terminal, although this is only recommended if the clauses will not be needed permanently, and are few in number. To enter clauses at the terminal, you must give the special directive:

| ?- [user].
|

and the new prompt `| ' shows that the interpreter is now in a state where it expects input of clauses or directives. To return to interpreter top level, type ^D. The interpreter responds thus:

{user consulted, 20 msec 200 bytes}

Directives: Queries and Commands

Directives are either queries or commands. Both are ways of directing the system to execute some goal or goals.

In the following, suppose that list membership has been defined by loading the following clauses from a file:

member(X, [X|_]).
member(X, [_|L]) :- member(X, L).

(Notice the use of anonymous variables written `_'.)

Queries

The full syntax of a query is `?-' followed by a sequence of goals. The interpreter top level expects queries. This is signaled by the initial prompt `| ?- '. Thus a query at top level looks like:

| ?- member(b, [a,b,c]).

Remember that Prolog terms must terminate with a full stop (., possibly followed by layout text), and that therefore Prolog will not execute anything until you have typed the full stop (and then RET) at the end of the query.

If the goal(s) specified in a query can be satisfied, and if there are no variables as in this example, then the system answers

yes

and execution of the query terminates.

If variables are included in the query, then the final value of each variable is displayed (except for variables whose names begin with _). Thus the query

| ?- member(X, [a,b,c]).

would be answered by

X = a

At this point the interpreter is waiting for input of either just a RET or else a ; followed by RET. Simply typing RET terminates the query; the interpreter responds with `yes'. However, typing ; causes the system to backtrack (see section Procedural Semantics) looking for alternative solutions. If no further solutions can be found it outputs `no'.

The outcome of some queries is shown below, where a number preceded by _ is a system-generated name for a variable.

| ?- member(X, [tom,dick,harry]).

X = tom ;
X = dick ;
X = harry ;

no
| ?- member(X, [a,b,f(Y,c)]), member(X, [f(b,Z),d]).

X = f(b,c),
Y = b,
Z = c

yes
| ?- member(X, [f(_),g]).

X = f(_A)

yes
| ?-

Commands are like queries except that

  1. Variable bindings are not displayed if and when the command succeeds.
  2. You are not given the chance to backtrack through other solutions.

Commands

Commands start with the symbol `:-'. Any required output must be programmed explicitly; e.g. the command:

:- member(3, [1,2,3]), write(ok).

directs the system to check whether 3 belongs to the list [1,2,3]. Execution of a command terminates when all the goals in the command have been successfully executed. Other alternative solutions are not sought. If no solution can be found, the system prints:

{Warning: Goal - goal failed}

as a warning.

The principal use for commands (as opposed to queries) is to allow files to contain directives which call various predicates, but for which you do not want to have the answers printed out. In such cases you only want to call the predicates for their effect, i.e. you don't want terminal interaction in the middle of consulting the file. A useful example would be the use of a directive in a file which consults a whole list of other files, e.g.

:- [ bits, bobs, main, tests, data, junk ].

If a command like this were contained in the file `myprog' then typing the following at top-level would be a quick way of reading in your entire program:

| ?- [myprog].

When simply interacting with the top-level of the Prolog interpreter this distinction between queries and commands is not normally very important. At top-level you should just type queries normally. In a file, queries are in fact treated as commands, i.e. if you wish to execute some goals then the directive in the file must be preceded by `:-' or `?-', otherwise it would be treated as a clause.

Syntax Errors

Syntax errors are detected during reading. Each clause, directive or in general any term read in by the built-in predicate read/1 that fails to comply with syntax requirements is displayed on the terminal as soon as it is read, along with its position in the input stream and a mark indicating the point in the string of symbols where the parser has failed to continue analysis, e.g.:

| member(X, X$L).

** in lines 11-12 **
** , or ) expected in arguments **
member ( X , X
** here **
$ L ) .

if $ has not been declared as an infix operator.

Note that any comments in the faulty line are not displayed with the error message. If you are in doubt about which clause was wrong you can use the listing/1 predicate to list all the clauses which were successfully read-in, e.g.

| ?- listing(member/2).

Note: The built in predicates read/(1-2) normaly raise an exception on syntax errors (see section Error and Exception Handling). The behavior is controlled by the flag syntax_errors (see prolog_flag/3).

Undefined Predicates

There is a difference between predicates that have no definition and predicates that have no clauses. The latter case is meaningful e.g. for dynamic predicates (see section Declarations) that clauses are being added to or removed from. There are good reasons for treating calls to undefined predicates as errors, as such calls easily arise from typing errors.

The system can optionally catch calls to predicates that have no definition. First the user defined predicate user:unknown_predicate_handler/3 (see section Error and Exception Handling) is called. If undefined or if the call fails the action is governed by the state of the unknown/2 flag which can be:

trace
which causes calls to undefined predicates to be reported and the debugger to be entered at the earliest opportunity.
error
which causes calls to such predicates to raise an exception (the default state). See section Error and Exception Handling.
fail
which causes calls to such predicates to fail.

Calls to predicates that have no clauses are not caught.

The built-in predicate unknown(?OldState, ?NewState) unifies OldState with the current state and sets the state to NewState. The built-in predicate debugging/0 prints the value of this state along with its other information. This state is also controlled by the flag unknown (see prolog_flag/3).

Program Execution And Interruption

Execution of a program is started by giving the interpreter a directive which contains a call to one of the program's predicates.

Only when execution of one directive is complete does the interpreter become ready for another directive. However, one may interrupt the normal execution of a directive by typing ^C. This ^C interruption has the effect of suspending the execution, and the following message is displayed:

Prolog interruption (h or ? for help) ?

At this point, the Development System accepts one-letter commands corresponding to certain actions. To execute an action simply type the corresponding character (lower or upper case) followed by RET. The available commands in both Development Systems are:

a
aborts the current computation.
c
continues the execution.
e
exits from SICStus Prolog, closing all files.
h
?
lists available commands.

The following commands are also available in the sequential Development System only:

b
invokes a recursive top-level.
d
enables debugging. See section Debugging.
t
enables tracing. See section Tracing.

If the standard input stream is not connected to the terminal, e.g. by redirecting standard input to a file or a UNIX pipe, the above ^C interrupt options are not available. Instead, typing ^C causes SICStus Prolog to exit, and no terminal prompts are printed.

Exiting From The Top-Level

To exit from the top-level and return to the shell, either type ^D at the top-level, or call the built-in predicate halt/0, or use the e (exit) command following a ^C interruption.

Nested Executions--Break and Abort

The Prolog system provides a way to suspend the execution of your program and to enter a new incarnation of the top level where you can issue directives to solve goals etc. This is achieved by issuing the directive (see section Program Execution And Interruption):

| ?- break.

This invokes a recursive top-level, indicated by the message:

{ Break level 1 }

You can now type queries just as if you were at top-level.

If another call of break/0 is encountered, it moves up to level 2, and so on. To close the break and resume the execution which was suspended, type ^D. The debugger state and current input and output streams will be restored, and execution will be resumed at the predicate call where it had been suspended after printing the message:

{ End break }

Alternatively, the suspended execution can be aborted by calling the built-in predicate abort/0.

A suspended execution can be aborted by issuing the directive:

| ?- abort.

within a break. In this case no ^D is needed to close the break; all break levels are discarded and the system returns right back to top-level. IO streams remain open, but the debugger is switched off. abort/0 may also be called from within a program.

Saving and Restoring Program States

Once a program has been read, the interpreter will have available all the information necessary for its execution. This information is called a program state.

The state of a program may be saved on disk for future execution. To save a program into a file File, type the directive:

| ?- save(File).

This predicate may be called at any time, for example it may be useful to call it in a break in order to save an intermediate execution state. The file File becomes an executable file. See section Getting Started.

Once a program has been saved into a file File, the following directive will restore the interpreter to the saved state:

| ?- restore(File).

After execution of this directive, which may be given in the same session or at some future date, the interpreter will be in exactly the same state as existed immediately prior to the call to save/1. Thus if you saved a program as follows:

| ?- save(myprog), write('myprog restored').

then on restoring you will get the message `myprog restored' printed out.

A partial program state, containing only the user defined predicates may also be saved with the directive:

| ?- save_program(File).

The file File becomes an executable file. See section Getting Started. After restoring a partial program state, the interpreter will reinitialize itself.

Note that when a new version of the Prolog system is installed, all program files saved with the old version become obsolete.

In the Muse Development System, the above predicates may only be called when the system has been adjusted to one worker; see section The Muse Model.

The save facility is not available in Runtime Systems and the predicates defined in this chapter are undefined; see section Runtime Systems.

Note: Foreign resources, see section Calling C from Prolog, are unloaded by save/1 and save_program/1. The names and paths of the resources are however included in the saved state. After the save, and after a restore of the saved state, this information is used to reload the foreign resources again. The state of the foreign resource in terms of global C variables and allocated memory is thus not preserved. Foreign resources may define init and deinit functions to take special action upon loading and unloading, see section Init and Deinit Functions.

Emacs Interface

This section explains how to use the GNU Emacs mode for SICStus Prolog, and how to customize your GNU Emacs environment for it.

Customizing Emacs

Assuming the GNU Emacs mode for SICStus Prolog has been installed, inserting the following lines in your `~/.emacs' will make Emacs use this mode automatically when editing files with a `.pl' extension:

;; (setq load-path (cons "/usr/local/lib/sicstus3" load-path))
(autoload 'run-prolog "prolog"
                  "Start a Prolog sub-process." t)
(autoload 'prolog-mode "prolog"
                  "Major mode for editing prolog programs" t)

where we assume that the Emacs interface has been placed in the Emacs Lisp modules directory. If that is not the case, uncomment the first line above, and replace `/usr/local/lib/sicstus3' by the name of the SICStus Prolog source code directory.

Adding the following lines will make Emacs display a command menu when in Prolog mode:

(autoload 'prolog-menu-hook-function "prolog-menu" t)
(add-hook 'prolog-mode-hook 'prolog-menu-hook-function)

The Emacs mode will use the value of the environment variable EPROLOG as a shell command to invoke SICStus Prolog. This value defaults to sicstus. The Emacs mode provides the following commands:

Available Commands

M-x run-prolog
Runs an inferior Prolog process, input and output via the buffer *prolog*.
C-c K
The entire buffer is compiled.
C-c k
The current region is compiled.
C-c C-k
The predicate around point is compiled. Empty lines are treated as predicate boundaries.
C-c C
The entire buffer is consulted.
C-c c
The current region is consulted.
C-c C-c
The predicate around point is consulted. Empty lines are treated as predicate boundaries.

Mode Line

If you are working with an application split into several modules, it is recommended that your source files begin with a "mode line":

% -*- Module: ModuleName; -*-

The Emacs interface will look for the mode line and notify the SICStus Prolog module system that the predicates being incrementally reconsulted or recompiled belong to the module ModuleName. If SICStus Prolog recognizes the file as one being loaded before, it will remember what module it belongs to. If the mode line is missing, and the file has not been loaded before, the predicates will go into the type-in module. Even if the file has been loaded earlier, its filename may have a slightly different appearance to Prolog via the Emacs interface, so it is safest to always include the mode line.


Go to the first, previous, next, last section, table of contents.