\chapter{Overview}			\label{sec:overview}

\section{Getting started quickly}	\label{sec:quickstart}

\subsection{Starting SWI-Prolog}	\label{sec:startpl}

\subsubsection{Starting SWI-Prolog on Unix} \label{sec:startunix}

By default, SWI-Prolog is installed as `swipl'. The command line
arguments of SWI-Prolog itself and its utility programs are documented
using standard Unix \program{man} pages. SWI-Prolog is normally operated
as an interactive application simply by starting the program:

\begin{code}
$ swipl
Welcome to SWI-Prolog ...
...

1 ?-
\end{code}

\noindent
After starting Prolog, one normally loads a program into it using
\index{consult/1}\predref{consult}{1}, which may be abbreviated by putting the name of the program
file between square brackets. The following goal loads the file
\href{https://raw.githubusercontent.com/SWI-Prolog/swipl-devel/master/demo/likes.pl}{likes.pl}
containing clauses for the predicates \nopredref{likes}{2}:

\begin{code}
?- [likes].
true.

?-
\end{code}

\noindent
Alternatively, the source file may be given as command line arguments:

\begin{code}
$ swipl likes.pl
Welcome to SWI-Prolog ...
...

1 ?-
\end{code}

\noindent
After this point, Unix and Windows users unite, so if you are using
Unix please continue at \secref{consultuser}.

\subsubsection{Starting SWI-Prolog on Windows}
\label{sec:startwin}

After SWI-Prolog has been installed on a Windows system, the following
important new things are available to the user:

\begin{itemize}
    \item A folder (called \jargon{directory} in the remainder of this
	  document) called \file{swipl} containing the executables,
	  libraries, etc., of the system.  No files are installed
	  outside this directory.
    \item A program \program{swipl-win.exe}, providing a window for interaction
          with Prolog. The program \program{swipl.exe} is a version of
	  SWI-Prolog that runs in a console window.
    \item The file extension \fileext{pl} is associated with the program
          \program{swipl-win.exe}.  Opening a \fileext{pl} file will cause
	  \program{swipl-win.exe} to start, change directory to the
	  directory in which the file to open resides, and load this
	  file.
\end{itemize}

The normal way to start the \file{likes.pl} file mentioned in
\secref{startunix} is by simply double-clicking this file in the Windows
explorer.

\subsection{Adding rules from the console}	\label{sec:consultuser}

Although we strongly advice to put your program in a file, optionally
edit it and use \index{make/0}\predref{make}{0} to reload it (see \secref{viewprogram}), it is
possible to manage facts and rules from the terminal. The most
conveniant way to add a few clauses is by consulting the pseudo file
\const{user}. The input is ended using the system end-of-file character.

\begin{code}
?- [user].
|: hello :- format('Hello world~n').
|: ^D
true.

?- hello.
Hello world
true.
\end{code}

\noindent
The predicates \index{assertz/1}\predref{assertz}{1} and \index{retract/1}\predref{retract}{1} are alternatives to add and
remove rules and facts.


\subsection{Executing a query}			\label{sec:execquery}

After loading a program, one can ask Prolog queries about the program.
The query below asks Prolog what food `sam' likes. The system responds
with \mbox{\tt X = \bnfmeta{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}

\noindent
Note that the answer written by Prolog is a valid Prolog program that,
when executed, produces the same set of answers as the original
program.\footnote{The SWI-Prolog top level differs in several ways from
traditional Prolog top level. The current top level was designed in
cooperation with Ulrich Neumerkel.}


\subsection{Examining and modifying your program} \label{sec:viewprogram}

If properly configured, the predicate \index{edit/1}\predref{edit}{1} starts the built-in or
user configured editor on the argument.  The argument can be anything
that can be linked to a location: a file name, predicate name, module
name, etc.  If the argument resolves to only one location the editor
is started on this location, otherwise the user is presented a choice.

If a graphical user interface is available, the editor normally creates
a new window and the system prompts for the next command. The user may
edit the source file, save it and run \index{make/0}\predref{make}{0} to update any modified
source file. If the editor cannot be opened in a window it the same
console and leaving the editor runs \index{make/0}\predref{make}{0} to reload any source files
that have been modified.

\begin{code}
?- edit(likes).

true.
?- make.
% /home/jan/src/pl-devel/linux/likes compiled 0.00 sec, 0 clauses

?- likes(sam, X).
...
\end{code}

\noindent
The program can also be \jargon{decompiled} using \index{listing/1}\predref{listing}{1} as below.
The argument is \index{listing/1}\predref{listing}{1} is just a predicate name, a predicate
\jargon{indicator} of the form \arg{Name/Arity}, e.g., \exam{?-
listing(\index{mild/1}\predref{mild}{1}).} or a \jargon{head}, e.g., \exam{?- listing(likes(sam,
_).}, listing all \jargon{matching} clauses. The predicate \index{listing/0}\predref{listing}{0},
i.e., without arguments lists the entire program.\footnote{This lists
several \jargon{hook} predicates that are defined by default and is
typically not very informative.}

\begin{code}
?- listing(mild).
mild(dahl).
mild(tandoori).
mild(kurma).

true.
\end{code}

\noindent
\subsection{Stopping Prolog}			\label{sec:halt}

The interactive toplevel can be stopped in two ways: enter the system
end-of-file character (typically \textit{Control-D}) or by executing the
\index{halt/0}\predref{halt}{0} predicate:

\begin{code}
?- halt.
$
\end{code}

\noindent
\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
\index{consult/1}\predref{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 \index{file_search_path/2}\predref{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 \bnfmeta{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 \index{win_folder/2}\predref{win_folder}{2}

\begin{center}
\begin{tabular}{|l|l|l|}
\hline
		& \bf Unix	& \bf Windows \\
\hline
\bf home	& \chr{\Stilde}	& \bnfmeta{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 initialisation goals and
\argoption{-t}{goal} to define the \jargon{top-level goal}. The following
is a typical example for starting an application directly from the
command line.

\begin{code}
machine% swipl -s load.pl -g go -t halt
\end{code}

\noindent
It tells SWI-Prolog to load \file{load.pl}, start the application using
the \jargon{entry point} \nopredref{go}{0} and ---instead of entering
the interactive top level--- exit after completing \nopredref{go}{0}.

The command line may have multiple \argoption{-g}{goal} occurrences. The
goals are executed in order. Possible choice points of individual goals
are pruned. If a \arg{goal} fails execution stops with exit status
\const{1}. If a \arg{goal} raises an exception, the exception is printed
and the process stops with exit code \const{2}.

The \cmdlineoption{-q} may be used to suppress all informational
messages as well as the error message that is normally printed if an
initialisation goal \emph{fails}.

In MS-Windows, the same can be achieved using a short-cut with
appropriately defined command line arguments. A typically seen
alternative is to write a file \file{run.pl} with content as illustrated
below. Double-clicking \file{run.pl} will start the application.

\begin{code}
:- [load].                      % load program
:- go.                          % run it
:- halt.                        % and exit
\end{code}

\noindent
\Secref{plscript} discusses further scripting options, and
\chapref{runtime} discusses the generation of runtime executables.
Runtime executables are a means to deliver executables that do not
require the Prolog system.


\section{Command line options}			\label{sec:cmdline}

SWI-Prolog can be executed in one of the following modes:

\begin{description}
    \definition{\exam{swipl --help}}
    \nodescription
    \definition{\exam{swipl --version}}
    \nodescription
    \definition{\exam{swipl --arch}}
    \nodescription
    \definition{\exam{swipl --dump-runtime-variables}}
These options must appear as only option. They cause Prolog to print
an informational message and exit.  See \secref{info-options}.

    \definition{\exam{swipl} [\arg{option} ...]
		\arg{script-file} [\arg{arg} ...]}
These arguments are passed on Unix systems if file that starts
with \mbox{\texttt{\#!/path/to/executable} [\arg{option} ...]} is
executed. Arguments after the script file are made available in the
Prolog flag \prologflag{argv}.

    \definition{\exam{swipl} [\arg{option} ...]
		\arg{prolog-file} ...
		[[\const{--}] \arg{arg} ...]}
This is the normal way to start Prolog. The options are described in
\secref{running-options}, \secref{stacksizes} and \secref{runoptions}.
The Prolog flag \prologflag{argv} provides access to \arg{arg} ... If
the \arg{options} are followed by one or more Prolog file names (i.e.,
names with extension \fileext{pl}, \fileext{prolog} or (on Windows) the
user preferred extension registered during installation), these files
are loaded. The first file is registered in the Prolog flag
\prologflag{associated_file}. In addition, \program{pl-win[.exe]}
switches to the directory in which this primary source file is located
using \index{working_directory/2}\predref{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}

\noindent
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 \index{current_prolog_flag/2}\predref{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.  Note that the handler to unblock system calls is still
installed. This can be prevented using \exam{--sigalert=0} additionally.
See \cmdlineoption{--sigalert}.

    \cmdlineoptionitem{--nothreads}{}
Disable threading for the multi-threaded version at runtime.  See also
the flags \prologflag{threads} and \prologflag{gc_thread}.

    \cmdlineoptionitem{--pldoc}{[=port]}
Start the PlDoc documentation system on a free network port and launch
the user's browser on \verb$http://localhost:$\arg{port}. If
\arg{port} is specified, the server is started at the given port and the
browser is \emph{not} launched.

    \cmdlineoptionitem{--sigalert=NUM}{}
Use signal \arg{NUM} (1\ldots{}31) for alerting a thread. This is needed
to make \index{thread_signal/2}\predref{thread_signal}{2}, and derived Prolog signal handling act
immediately when the target thread is blocked on an interruptable
system call (e.g., \index{sleep/1}\predref{sleep}{1}, read/write to most devices).  The default is
to use \const{SIGUSR2}.  If \arg{NUM} is 0 (zero), this handler is not
installed.  See \index{prolog_alert_signal/2}\predref{prolog_alert_signal}{2} to query or modify this value at
runtime.

    \cmdlineoptionitem{--no-tty}{}
Unix only.  Switches controlling the terminal for allowing
single-character commands to the tracer and \index{get_single_char/1}\predref{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
\index{win_folder/2}\predref{win_folder}{2}).  The \file{Prolog} subdirectory is created if it
does not exist.

    \cmdlineoptionitem{-O}{}
Optimised compilation. See \index{current_prolog_flag/2}\predref{current_prolog_flag}{2} flag
\prologflag{optimise} for details.

    \cmdlineoptionitem{-l}{file}
Load \arg{file}. This flag provides compatibility with some other Prolog
systems.\footnote{YAP, SICStus} It is used in SWI-Prolog to skip the
program initialization specified using \index{initialization/2}\predref{initialization}{2} directives. See
also \secref{plscript}, and \index{initialize/0}\predref{initialize}{0}.

    \cmdlineoptionitem{-s}{file}
Use \arg{file} as a script file.  The script file is loaded after
the initialisation file specified with the \argoption{-f}{file}
option.  Unlike \argoption{-f}{file}, using \cmdlineoption{-s}
does not stop Prolog from loading the personal initialisation file.

    \cmdlineoptionitem{-f}{file}
Use \arg{file} as initialisation file instead of the default
\file{.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 \metafile{\bnfmeta{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
\index{qsave_program/[1,2]}\predref{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{\Ssemicolon}. On other systems it is \chr{\Smodule}. A value
is either a term of the form \mbox{alias(value)} or pathname. The
computed aliases are added to \index{file_search_path/2}\predref{file_search_path}{2} using \index{asserta/1}\predref{asserta}{1}, so
they precede predefined values for the alias. See \index{file_search_path/2}\predref{file_search_path}{2} for
details on using this file location mechanism.

    \cmdlineoptionitem{--traditional}{}
This flag disables the most important extensions of SWI-Prolog
version~7 (see \secref{extensions}) that introduce incompatibilities
with earlier versions.  In particular, lists are represented in the
traditional way, double quoted text is represented by a list of
character codes and the functional notation on dicts is not supported.
Dicts as a syntactic entity, and the predicates that act on them, are
still supported if this flag is present.

    \cmdlineoptionitem{--}{}
\index{command line, arguments}%
Stops scanning for more arguments, so you can pass arguments for your
application after this one.  See \index{current_prolog_flag/2}\predref{current_prolog_flag}{2} using the
flag \prologflag{argv} for obtaining the command line arguments.
\end{description}

\subsection{Controlling the stack sizes}
\label{sec:stacksizes}

As of version 7.7.14 the stacks are no longer limited individually.
Instead, only the combined size is limited. Note that 32~bit systems
still pose a 128Mb limit. See \secref{memlimit}. The combined limit is
by deault 1Gb on 64~bit machines and 512Mb on 32~bit machines.

For example, to limit the stacks to 32Gb use the command below. Note
that the stack limits apply \emph{per thread}. Individual threads may be
controlled using the \term{stack_limit}{+Bytes} option of thread_create.
Any thread can call \term{set_prolog_flag}{stack_limit, Limit} (see
\prologflag{stack_limit}) to adjust the stack limit. This limit is
inherited by threads created from this thread.

\begin{code}
$ swipl --stack_limit=32g
\end{code}

\noindent
\begin{description}
    \cmdlineoptionitem*{--stack_limit}{size[bkmg]}
Limit the combined size of the Prolog stacks to the indicated size.
The suffix specifies the value as \textit{bytes}, \textit{Kbytes},
\textit{Mbytes} or \textit{Gbytes}.

    \cmdlineoptionitem*{-table_space}{size[bkmg]}
Limit for the \arg{table space}. This is where tries holding
memoized\footnote{The letter M is used because the T was already in
use. It is a memnonic for \textbf{M}emoizing.} answers for
\jargon{tabling} are stored. The default is 1Gb on 64~bit machines and
512Mb on 32~bit machines. See the Prolog flag
\prologflag{table_space}
\end{description}


\subsection{Running goals from the command line}
\label{sec:runoptions}

\begin{description}
    \cmdlineoptionitem{-g}{goal}
\arg{Goal} is executed just before entering the top level. This option
may appear multiple times. See \secref{initgoal} for details. If no
initialization goal is present the system calls \index{version/0}\predref{version}{0} to print the
welcome message. The welcome message can be suppressed with
\cmdlineoption{--quiet}, but also with \argoption{-g}{true}. \arg{goal}
can be a complex term. In this case quotes are normally needed to
protect it from being expanded by the shell. A safe way to run a goal
non-interactively is below. If \nopredref{go}{0} succeeds
\argoption{-g}{halt} causes the process to stop with exit code 0. If it
fails, the exit code is 1; and if it raises an exception, the exit code
is 2.

\begin{code}
% swipl <options> -g go -g halt
\end{code}

\noindent
    \cmdlineoptionitem{-t}{goal}
Use \arg{goal} as interactive top level instead of the default goal
\index{prolog/0}\predref{prolog}{0}. The \arg{goal} can be a complex term. If the top-level goal
succeeds SWI-Prolog exits with status 0. If it fails the exit status is
1. If the top level raises an exception, this is printed as an uncaught
error and the top level is \emph{restarted}. This flag also determines
the goal started by \index{break/0}\predref{break}{0} and \index{abort/0}\predref{abort}{0}. If you want to prevent the user
from entering interactive mode, start the application with
`\argoption{-g}{goal} \argoption{-t}{halt}'.
\end{description}


\subsection{Compilation options}
\label{sec:compoptions}

\begin{description}
    \cmdlineoptionitem{-c}{file \ldots}
Compile files into an `intermediate code file'. See \secref{compilation}.

    \cmdlineoptionitem{-o}{output}
Used in combination with \cmdlineoption{-c} or \cmdlineoption{-b} to
determine output file for compilation.
\end{description}

\subsection{Maintenance options}
\label{sec:maintoptions}

The following options are for system maintenance. They are given
for reference only.

\begin{description}
    \cmdlineoptionitem{-b}{initfile \ldots \cmdlineoption{-c} file \ldots}
Boot compilation.  \arg{initfile \ldots} are compiled by the C-written
bootstrap compiler, \arg{file \ldots} by the normal Prolog compiler.
System maintenance only.

    \cmdlineoptionitem{-d}{token1,token2,...}
Print debug messages for DEBUG statements tagged with one of the
indicated tokens. Only has effect if the system is compiled with the
\const{-DO_DEBUG} flag. System maintenance only.
\end{description}


\section{GNU Emacs Interface}			\label{sec:gemacs}

\index{GNU-Emacs}\index{Emacs}%

Unfortunately the default Prolog mode of GNU~Emacs is not very good.
There are several alternatives though:

\begin{shortlist}
    \item \url{https://bruda.ca/emacs/prolog_mode_for_emacs}\\
          Prolog mode for Emacs and XEmacs maintained by Stefan Bruda.
    \item \url{https://www.metalevel.at/pceprolog/}\\
          Recommended configuration options for editing Prolog code with Emacs.
    \item \url{https://www.metalevel.at/ediprolog/}\\
          Interact with SWI-Prolog directly in Emacs buffers.
    \item \url{https://www.metalevel.at/etrace/}\\
          Trace Prolog code with Emacs.
\end{shortlist}


\section{Online Help}				\label{sec:online-help}

\input{lib/help.tex}
\input{lib/explain.tex}

\section{Command line history}			\label{sec:history}

SWI-Prolog offers a query substitution mechanism similar to what is seen
in Unix shells. The availability of this feature is controlled by
\index{set_prolog_flag/2}\predref{set_prolog_flag}{2}, using the \prologflag{history} Prolog flag. By
default, history is available if no interactive command line editor is
available. To enable history, remembering the last 50 commands, put the
following into your startup file (see \secref{initfile}):

\begin{code}
:- set_prolog_flag(history, 50).
\end{code}

\noindent
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 \bnfmeta{nr} \\
\verb+!str.+          & Repeat last query starting with \bnfmeta{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}

\noindent
    \caption{Reusing top-level bindings}
    \label{fig:topevelvars}
\end{figure}

Note that variables may be set by executing \predref{\Seq}{2}:

\begin{code}
6 ?- X = statistics.
X = statistics.

7 ?- $X.
% Started at Fri Aug 24 16:42:53 2018
% 0.118 seconds cpu time for 456,902 inferences
% 7,574 atoms, 4,058 functors, 2,912 predicates, 56 modules, 109,791 VM-codes
%
%                     Limit   Allocated      In use
% Local  stack:           -       20 Kb    1,888  b
% Global stack:           -       60 Kb       36 Kb
% Trail  stack:           -       30 Kb    4,112  b
%        Total:    1,024 Mb      110 Kb       42 Kb
%
% 3 garbage collections gained 178,400 bytes in 0.000 seconds.
% 2 clause garbage collections gained 134 clauses in 0.000 seconds.
% Stack shifts: 2 local, 2 global, 2 trail in 0.000 seconds
% 2 threads, 0 finished threads used 0.000 seconds
true.
\end{code}

\noindent
\section{Overview of the Debugger}		\label{sec:debugoverview}

SWI-Prolog has a traditional commandline debugger.  It also provides
programmatic access to the debugger.  This facility is used to provide
a graphical debugger as well as remote debugging in the web interface
provided by \href{https://swish.swi-prolog.org}{SWISH}.

SWI-Prolog has a 6-port tracer, extending the standard 4-port tracer
\cite{Byrd:80,Clocksin:87} with two additional ports. The standard ports
are called \const{call}, \const{exit}, \const{redo}, and \const{fail}.
The additional \arg{unify} port allows the user to inspect the result
after unification of the head. The additional \arg{exception} port shows
exceptions raised by \index{throw/1}\predref{throw}{1} or one of the built-in predicates. See
\secref{exception}.

The tracer is started by the \index{trace/0}\predref{trace}{0} command. If the system is in debug
mode (see \index{debug/0}\predref{debug}{0}) the trace is started, after reaching a \jargon{spy
point} set using \index{spy/1}\predref{spy}{1} or \jargon{break point} set using
\index{set_breakpoint/4}\predref{set_breakpoint}{4}. The debugger is also started if an
\term{error}{Formal, Extended} exception is raised that is not caught.

If the native graphics plugin (XPCE) is available, the commands \index{gtrace/0}\predref{gtrace}{0}
and \index{gspy/1}\predref{gspy}{1} activate the graphical debugger while \index{tdebug/0}\predref{tdebug}{0} and \index{tspy/1}\predref{tspy}{1}
allow debugging of arbitrary threads.

The interactive top-level goal \index{trace/0}\predref{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 \index{write_term/2}\predref{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}

\noindent
\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}

\noindent
    \caption{Example trace of the program above showing all ports.
	     The lines marked \chr{\Shat} indicate calls to
	     \jargon{transparent} predicates.  See \secref{modules}.}
    \label{fig:tracer}
\end{figure}

On {\em leashed ports} (set with the predicate \index{leash/1}\predref{leash}{1}, default are
\const{call}, \const{exit}, \const{redo} and \const{fail}) the user is
prompted for an action. All actions are single-character commands which
are executed {\bf without} waiting for a return, unless the command line
option \cmdlineoption{--no-tty} is active. Tracer options:

\begin{description}
    \traceoption{\Splus}{Spy}{
Set a spy point (see \index{spy/1}\predref{spy}{1}) on the current predicate.}
    \traceoption{\Sminus}{No spy}{
Remove the spy point (see \index{nospy/1}\predref{nospy}{1}) from the current predicate.}
    \traceoption{\Sdiv}{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 \index{member/2}\predref{member}{2}. This is equivalent
                          to setting a spy point on \index{member/2}\predref{member}{2}. \\
\end{tabular}\end{center}}
    \traceoption{\Sdot}{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 \index{listing/1}\predref{listing}{1}.}
    \traceoption{a}{Abort}{
Abort Prolog execution (see \index{abort/0}\predref{abort}{0}).}
    \traceoption{b}{Break}{
Enter a Prolog break environment (see \index{break/0}\predref{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 \index{halt/0}\predref{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 \index{portray/1}\predref{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
(\index{debug/0}\predref{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 \index{use_module/[1,2]}\predref{use_module}{[1,2]} or \index{ensure_loaded/1}\predref{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}

\noindent
When using Windows, the user may open \file{load.pl} from the Windows
explorer, which will cause \program{swipl-win.exe} to be started in the
directory holding \file{load.pl}.  Prolog loads \file{load.pl} before
entering the top level.  If Prolog is started from an interactive shell,
one may choose the type \texttt{swipl -s load.pl}.


\subsection{For running the result}	\label{sec:runcomp}

There are various options if you want to make your program ready
for real usage.  The best choice depends on whether the program
is to be used only on machines holding the SWI-Prolog development
system, the size of the program, and the operating system (Unix
vs.\ Windows).


\subsubsection{Using PrologScript}	\label{sec:plscript}

A Prolog source file can be used directly as a Unix program using the
Unix \verb$#!$ magic start. The Unix \verb$#!$ magic is allowed because
if the first letter of a Prolog file is \verb$#$, the first line is
treated as a comment.\footnote{The \texttt{\#}-sign can be the legal
start of a normal Prolog clause. In the unlikely case this is required,
leave the first line blank or add a header comment.} To create a Prolog
script, use one of the two alternatives below as first line. The first
can be used to bind a script to a specific Prolog installation, while
the latter uses the default prolog installed in \verb"$PATH".

\begin{code}
#!/path/to/swipl
#!/usr/bin/env swipl
\end{code}

\noindent
The interpretation of arguments to the executable in the
\jargon{HashBang} line differs between Unix-derived systems. For
portability, the \verb$#!$ must be followed immediately with an absolute
path to the executable and should have none or one argument. Neither the
executable path, nor the argument shall use quotes or spaces. When
started this way, the Prolog flag \prologflag{argv} contains the command
line arguments that follow the script invocation.

Starting with version 7.5.8, \index{initialization/2}\predref{initialization}{2} support the \arg{When}
options \const{program} and \const{main}, allowing for the following
definition of a Prolog script that evaluates an arithmetic expression on
the command line. Note that \index{main/0}\predref{main}{0} is defined lib the library
\pllib{main}. It calls \index{main/1}\predref{main}{1} with the command line arguments after
disabling signal handling.

\begin{code}
#!/usr/bin/env swipl

:- initialization(main, main).

main(Argv) :-
        concat_atom(Argv, ' ', SingleArg),
        term_to_atom(Term, SingleArg),
        Val is Term,
        format('~w~n', [Val]).
\end{code}

\noindent
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}

\noindent
Prolog script may be lauched for debugging or inspection purposes using
the \cmdlineoption{-l} or \cmdlineoption{-t}. For example,
\cmdlineoption{-l} merely loads the script, ignoring \const{main} and
\const{program} initialization.

\begin{code}
swipl -l eval 1+1
<banner>

?- main.
2
true.

?-
\end{code}

\noindent
We can also force the program to enter the interactive toplevel after
the application is completed using \exam{-t prolog}:

\begin{code}
swipl -t prolog eval 1+1
2
?-
\end{code}

\noindent
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}

\noindent
\begin{code}
:- initialization go.

go :-
        current_prolog_flag(argv, Arguments),
        go(Arguments).

go(Args) :-
        ...
\end{code}

\noindent
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 \index{qsave_program/[1,2]}\predref{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 \index{qsave_program/2}\predref{qsave_program}{2} does.  The command syntax is:

\begin{code}
% swipl [option ...] [-o output] -c file.pl ...
\end{code}

\noindent
The \arg{options} argument are options to \index{qsave_program/2}\predref{qsave_program}{2} written in
the format below.  The option names and their values are described with
\index{qsave_program/2}\predref{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}

\noindent
This performs exactly the same as executing

\begin{code}
% swipl
<banner>

?- [load].
?- qsave_program(myprog,
                 [ goal(main),
                   stand_alone(true)
                 ]).
?- halt.
\end{code}

\noindent
\section{Environment Control (Prolog flags)}	\label{sec:flags}

The predicates \index{current_prolog_flag/2}\predref{current_prolog_flag}{2} and \index{set_prolog_flag/2}\predref{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 \index{current_prolog_flag/2}\predref{current_prolog_flag}{2} defines an interface to installation
features: options compiled in, version, home, etc. With both arguments
unbound, it will generate all defined Prolog flags. With \arg{Key}
instantiated, it unifies \arg{Value} with the value of the Prolog flag
or fails if the \arg{Key} is not a Prolog flag.

Flags marked \textbf{rw} can be modified by the user using
\index{set_prolog_flag/2}\predref{set_prolog_flag}{2}. Flag values are typed. Flags marked as \const{bool}
can have the values \const{true} or \const{false}. The predicate
\index{create_prolog_flag/3}\predref{create_prolog_flag}{3} may be used to create flags that describe or
control behaviour of libraries and applications.  The library
\pllib{settings} provides an alternative interface for managing
notably application parameters.

Some Prolog flags are not defined in all versions, which is normally
indicated in the documentation below as \textit{``if present and
true''}. A boolean Prolog flag is true iff the Prolog flag is present
{\bf and} the \arg{Value} is the atom \const{true}. Tests for such flags
should be written as below:

\begin{code}
        (   current_prolog_flag(windows, true)
        ->  <Do MS-Windows things>
        ;   <Do normal things>
        )
\end{code}

\noindent
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 \cfuncref{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
\index{garbage_collect_atoms/0}\predref{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 \index{read/1}\predref{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 \index{read_term/2}\predref{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 reasons 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 \index{file_search_path/2}\predref{file_search_path}{2}.

    \prologflagitem{associated_file}{atom}{r}
Set if Prolog was started with a prolog file as argument.  Used by
e.g., \index{edit/0}\predref{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{backtrace}{bool}{rw}
If \const{true} (default), print a backtrace on an uncaught exception.

    \prologflagitem{backtrace_depth}{integer}{rw}
If backtraces on errors are enabled, this flag defines the maximum
number of frames that is printed (default~20).

    \prologflagitem{backtrace_goal_depth}{integer}{rw}
The frame of a backtrace is printed after making a shallow copy of the
goal.  This flag determines the depth to which the goal term is copied.
Default is `3'.

    \prologflagitem{backtrace_show_lines}{bool}{rw}
If \const{true} (default), try to reconstruct the line number at which
the exception happened.

    \prologflagitem{bounded}{bool}{r}
ISO Prolog flag. If \const{true}, integer representation is bound by
\prologflag{min_integer} and \prologflag{max_integer}. If \const{false}
integers can be arbitrarily large and the \prologflag{min_integer} and
\prologflag{max_integer} are not present. See \secref{artypes}.

    \prologflagitem{break_level}{integer}{r}
Current break-level. The initial top level (started with
\cmdlineoption{-t}) has value 0. See \index{break/0}\predref{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 \index{char_conversion/2}\predref{char_conversion}{2}.

    \prologflagitem{character_escapes}{bool}{rw}
If \const{true} (default), \index{read/1}\predref{read}{1} interprets \verb$\$ escape sequences
in quoted atoms and strings. May be changed. This flag is local to the
module in which it is changed.  See \secref{charescapes}.

    \prologflagitem{colon_sets_calling_context}{bool}{ro}
Using the construct \bnfmeta{module}:\bnfmeta{goal} sets the \jargon{calling context}
for executing \bnfmeta{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 \index{message_property/2}\predref{message_property}{2} can be used to control the
actual color scheme depending in the message type passed to
\index{print_message/2}\predref{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{\Shat}' (see \index{meta_predicate/1}\predref{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 \index{make/0}\predref{make}{0} and implemented by \index{list_undefined/0}\predref{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.,
\index{assert/2}\predref{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 \index{thread_setconcurrency/2}\predref{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 \index{qsave_program/1}\predref{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 \index{spy/1}\predref{spy}{1}) and trace points (see \index{trace/1}\predref{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 \const{true}, start the tracer after an error is detected.
Otherwise just continue execution. The goal that raised the error will
normally fail. See also the Prolog flag \prologflag{report_error}.
Default is \const{true}.

    \prologflagitem{debugger_write_options}{term}{rw}
This argument is given as option-list to \index{write_term/2}\predref{write_term}{2} for printing goals
by the debugger.  Modified by the `w', `p' and `\bnfmeta{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}

\noindent
    \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 \index{edit/1}\predref{edit}{1}. See \secref{customedit} for
details on selecting the editor used.

    \prologflagitem{emacs_inferior_process}{bool}{r}
If true, SWI-Prolog is running as an \jargon{inferior process} of
(GNU/X-)Emacs.  SWI-Prolog assumes this is the case if the environment
variable \env{EMACS} is \const{t} and \env{INFERIOR} is \const{yes}.

    \prologflagitem{encoding}{atom}{rw}
Default encoding used for opening files in \const{text} mode. The
initial value is deduced from the environment. See \secref{encoding} for
details.

    \prologflagitem{executable}{atom}{r}
Pathname of the running executable. Used by \index{qsave_program/2}\predref{qsave_program}{2} as
default emulator.

    \prologflagitem{exit_status}{integer}{r}
Set by \index{halt/1}\predref{halt}{1} to its argument, making the exit status available to
hooks registered with \index{at_halt/1}\predref{at_halt}{1}.

    \prologflagitem{file_name_case_handling}{atom}{rw}
This flag defines how Prolog handles the case of file names. The flag is
used for case normalization and to determine whether two names refer to
the same file.\bug{Note that file name case handling is typically a
properly of the filesystem, while Prolog only has a global flag to
determine its file handling.}  It has one of the following values:

    \begin{description}
    \termitem{case_sensitive}{}
The filesystem is fully case sensitive.  Prolog does not perform
any case modification or case insensitive matching.  This is the
default on Unix systems.
    \termitem{case_preserving}{}
The filesystem is case insensitive, but it preserves the case with
which the user has created a file.  This is the default on Windows
systems.
    \termitem{case_insensitive}{}
The filesystem doesn't store or match case.  In this scenario Prolog
maps all file names to lower case.
    \end{description}

    \prologflagitem{file_name_variables}{bool}{rw}
If \const{true} (default \const{false}), expand \file{\$\arg{varname}}
and \chr{\Stilde} in arguments of built-in predicates that accept a file
name (\index{open/3}\predref{open}{3}, \index{exists_file/1}\predref{exists_file}{1}, \index{access_file/2}\predref{access_file}{2}, etc.). The predicate
\index{expand_file_name/2}\predref{expand_file_name}{2} can be used to expand environment variables and
wildcard patterns. This Prolog flag is intended for backward
compatibility with older versions of SWI-Prolog.

    \prologflagitem{file_search_cache_time}{number}{rw}
Time in seconds for which search results from \index{absolute_file_name/3}\predref{absolute_file_name}{3} are
cached. Within this time limit, the system will first check that the old
search result satisfies the conditions. Default is 10 seconds, which
typically avoids most repetitive searches for (library) files during
compilation. Setting this value to 0 (zero) disables the cache.

    \prologflagitem{gc}{bool}{rw}
If true (default), the garbage collector is active.  If false, neither
garbage collection, nor stack shifts will take place, even not on
explicit request.  May be changed.

    \prologflagitem{gc_thread}{bool}{r}
If \const{true} (default if threading is enabled), atom and
clause garbage collection are executed in a seperate thread with the
\jargon{alias} \const{gc}. Otherwise the thread that detected sufficient
garbage executes the garbage collector. As running these global
collectors may take relatively long, using a seperate thread improves
real time behaviour. The \const{gc} thread can be controlled using
\index{set_prolog_gc_thread/1}\predref{set_prolog_gc_thread}{1}.

    \prologflagitem{generate_debug_info}{bool}{rw}
If \const{true} (default) generate code that can be debugged using
\index{trace/0}\predref{trace}{0}, \index{spy/1}\predref{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
\metafile{\bnfmeta{home}/boot32.prc} (32-bit machines) or
\metafile{\bnfmeta{home}/boot64.prc} (64-bit machines) and to find its library as
\metafile{\bnfmeta{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{\Sdiv}{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 \index{atom_length/2}\predref{atom_length}{2} yields a type error if the first
          argument is a number.
    \item \index{clause/[2,3]}\predref{clause}{[2,3]} raises a permission error when accessing static
          predicates.
    \item \index{abolish/[1,2]}\predref{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{message_context}{list(atom)}{rw}
Context information to add to messages of the levels \const{error} and
\const{warning}.  The list may contain the elements \const{thread} to
add the thread that generates the message to the message, \const{time}
or \term{time}{Format} to add a time stamp.  The default time format
is \verb$%T.%3f$. The default is \exam{[thread]}. See also \index{format_time/3}\predref{format_time}{3}
and \index{print_message/2}\predref{print_message}{2}.

    \prologflagitem{min_integer}{integer}{r}
Minimum integer value if integers are \emph{bounded}.  See also
the flag \prologflag{bounded} and \secref{artypes}.

    \prologflagitem{min_tagged_integer}{integer}{r}
Start of the tagged-integer value range.

    \prologflagitem{mitigate_spectre}{bool}{rw}
When \const{true} (default \const{false}), enforce mitigation against
the
\href{https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)}{Spectre}
timing-based security vulnerability. Spectre based attacks can extract
information from memory owned by the process that should remain
invisible, such as passwords or the private key of a web server. The
attacks work by causing speculative access to sensitive data, and
leaking the data via side-channels such as differences in the duration
of successive instructions. An example of a potentially vulnerable
application is \href{https://swish.swi-prolog.org}{SWISH}. SWISH
allows users to run Prolog code while the swish server must protect
the privacy of other users as well as its HTTPS private keys, cookies
and passwords.

Currently, enabling this flag reduces the resolution of \index{get_time/1}\predref{get_time}{1} and
\index{statistics/2}\predref{statistics}{2} CPU time to $20\mu{}s$.

\textbf{WARNING}: Although a coarser timer makes a successful attack
of this type harder, it does not reliably prevent such attacks in
general. Full mitigation may require compiler support to disable
speculative access to sensitive data.

    \prologflagitem{occurs_check}{atom}{rw}
This flag controls unification that creates an infinite tree (also
called \jargon{cyclic term}) and can have three values. Using
\const{false} (default), unification succeeds, creating an infinite
tree. Using \const{true}, unification behaves as \index{unify_with_occurs_check/2}\predref{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, \index{open_shared_object/2}\predref{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 \index{true/0}\predref{true}{0} that may result from \index{expand_goal/2}\predref{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
\index{dynamic/1}\predref{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{posix_shell}{atom}{rw}
Path to a POSIX compatible shell.  This default is typically
\file{/bin/sh}.  This flag is used by \index{shell/1}\predref{shell}{1} and \index{qsave_program/2}\predref{qsave_program}{2}.

    \prologflagitem{print_write_options}{term}{rw}
Specifies the options for \index{write_term/2}\predref{write_term}{2} used by \index{print/1}\predref{print}{1} and \index{print/2}\predref{print}{2}.

    \prologflagitem{tmp_dir}{atom}{rw}
Path to the temporary directory. initialised from the environment
variable \const{TMP} or \const{TEMP} in windows. If this variable is not
defined a default is used. This default is typically \file{/tmp} or
\file{c:/temp} in windows.

    \prologflagitem{prompt_alternatives_on}{atom}{rw}
\index{prompt, alternatives}%
Determines prompting for alternatives in the Prolog top level. Default is
\const{determinism}, which implies the system prompts for alternatives
if the goal succeeded while leaving choice points.  Many classical Prolog
systems behave as \const{groundness}: they prompt for alternatives if
and only if the query contains variables.

    \prologflagitem{protect_static_code}{bool}{rw}
If \const{true} (default \const{false}), \index{clause/2}\predref{clause}{2} does not operate on
static code, providing some basic protection from hackers that wish to
list the static code of your Prolog program. Once the flag is
\const{true}, it cannot be changed back to \const{false}.  Protection
is default in ISO mode (see Prolog flag \prologflag{iso}).  Note that
many parts of the development environment require \index{clause/2}\predref{clause}{2} to work on
static code, and enabling this flag should thus only be used for
production code.

    \prologflagitem{qcompile}{atom}{rw}
This option provides the default for the \term{qcompile}{+Atom} option
of \index{load_files/2}\predref{load_files}{2}.

    \prologflagitem{readline}{atom}{rw}
Specifies which form of command line editing is provided. Possible
values are below. The flag may be set from the user's init file (see
\secref{initgoal}) to one of \const{false}, \const{readline} or
\const{editline}. This causes the toplevel not to load a command line
editor (\const{false}) or load the specified one.  If loading fails
the flag is set to \const{false}.

\begin{description}
    \termitem{false}{}
No command line editing is available.

    \termitem{readline}{}
The library \pllib{readline} is loaded, providing line editing based on
the GNU readline library.

    \termitem{editline}{}
The library \pllib{editline} is loaded, providing line editing based on
the BSD libedit.  This is the default if \pllib{editline} is available
and can be loaded.

    \termitem{swipl_win}{}
SWI-Prolog uses its own console (\program{swipl-win.exe} on Windows,
the Qt based \program{swipl-win} on MacOS) which provides line editing.
\end{description}

    \prologflagitem{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 \index{resource/3}\predref{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}), \index{load_files/2}\predref{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 \index{qsave_program/[1,2]}\predref{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
\index{absolute_file_name/3}\predref{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{stack_limit}{int}{rw}
Limits the combined sizes of the Prolog stacks for the current thread.
See alse \cmdlineoption{--stack} and \secref{memlimit}.

    \prologflagitem{stream_type_check}{atom}{rw}
Defines whether and how strictly the system validates that byte I/O
should not be applied to text streams and text I/O should not be applied
to binary streams. Values are \const{false} (no checking), \const{true}
(full checking) and \const{loose}.  Using checking mode \const{loose}
(default), the system accepts byte I/O from text stream that use ISO
Latin-1 encoding and accepts writing text to binary streams.

    \prologflagitem{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 \index{thread_self/1}\predref{thread_self}{1}.

    \prologflagitem{table_space}{integer}{rw}
Space reserved for storing answer tables for \jargon{tabled predicates}
(see \index{table/1}\predref{table}{1}).\bug{Currently only counts the space occupied by the
nodes in the answer tries.} When exceeded a
\term{resource_error}{table_space} exception is raised.

    \prologflagitem{threads}{bool}{rw}
True when threads are supported.  If the system is compiled without
thread support the value is \const{false} and read-only.  Otherwise
the value is \const{true} unless the system was started with the
\cmdlineoption{--nothreads}.  Threading may be disabled only if no
threads are running.  See also the \prologflag{gc_thread} flag.

    \prologflagitem{timezone}{integer}{r}
Offset in seconds west of GMT of the current time zone. Set at
initialization time from the \const{timezone} variable associated with
the POSIX tzset() function. See also \index{format_time/3}\predref{format_time}{3}.

    \prologflagitem{toplevel_goal}{term}{rw}
Defines the goal that is executed after running the initialization goals
and entry point (see \cmdlineoption{-g}, \index{initialization/2}\predref{initialization}{2} and
\secref{plscript}. The initial value is \const{default}, starting a
normal interactive session. This value may be changed using the command
line option \cmdlineoption{-t}. The explicit value \const{prolog} is
equavalent to \const{default}. If \term{initialization}{Goal,main} is
used and the toplevel is \const{default}, the toplevel is set to
\const{halt} (see \index{halt/0}\predref{halt}{0}).

    \prologflagitem{toplevel_mode}{atom}{rw}
If \const{backtracking} (default), the toplevel backtracks after
completing a query. If \const{recursive}, the toplevel is implemented as
a recursive loop. This implies that global variables set using
\index{b_setval/2}\predref{b_setval}{2} are maintained between queries. In \jargon{recursive}
mode, answers to toplevel variables (see \secref{topvars}) are kept
in backtrackable global variables and thus \textbf{not copied}.  In
\jargon{backtracking} mode answers to toplevel variables are kept in
the recorded database (see \secref{recdb}).

The recursive mode has been added for interactive usage of CHR (see
\secref{chr}),\footnote{Suggested by Falco Nogatz} which maintains the
global constraint store in backtrackable global variables.

    \prologflagitem{toplevel_print_anon}{bool}{rw}
If \const{true}, top-level variables starting with an underscore
(\chr{_}) are printed normally.  If \const{false} they are hidden.
This may be used to hide bindings in complex queries from the top level.

    \prologflagitem{toplevel_print_factorized}{bool}{rw}
If \const{true} (default \const{false}) show the internal sharing of
subterms in the answer substitution.  The example below reveals internal
sharing of leaf nodes in \jargon{red-black trees} as implemented by the
\pllib{rbtrees} predicate \libpredref{rb_new}{1}:

\begin{code}
?- set_prolog_flag(toplevel_print_factorized, true).
?- rb_new(X).
X = t(_S1, _S1), % where
    _S1 = black('', _G387, _G388, '').
\end{code}

\noindent
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}

\noindent
    \prologflagitem{answer_write_options}{term}{rw}
This argument is given as option-list to \index{write_term/2}\predref{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{\Stilde}m & \jargon{Type in} module if not \const{user}
	   (see \index{module/1}\predref{module}{1}) \\
\chr{\Stilde}l & \jargon{Break level} if not 0
	   (see \index{break/0}\predref{break}{0}) \\
\chr{\Stilde}d & \jargon{Debugging state} if not normal execution
	   (see \index{debug/0}\predref{debug}{0}, \index{trace/0}\predref{trace}{0}) \\
\chr{\Stilde}! & \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{\Sdollar} 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}

\noindent
    \prologflagitem{traditional}{bool}{r}
Available in SWI-Prolog version~7.  If \const{true}, `traditional'
mode has been selected using \cmdlineoption{--traditional}.  Notice
that some SWI7 features, like the functional notation on dicts, do not
work in this mode.  See also \secref{extensions}.

    \prologflagitem{tty_control}{bool}{rw}
Determines whether the terminal is switched to raw mode for
\index{get_single_char/1}\predref{get_single_char}{1}, which also reads the user actions for the trace. May
be set. If this flag is \const{false} at startup, command line editing
is disabled. See also the \cmdlineoption{--no-tty} command line option.

    \prologflagitem{unix}{bool}{r}
\index{unix}%
If present and \const{true}, the operating system is some version of
Unix. Defined if the C compiler used to compile this version of
SWI-Prolog either defines \verb$__unix__$ or \const{unix}. On other
systems this flag is not available.  See also \prologflag{apple}
and \prologflag{windows}.

    \prologflagitem{unknown}{fail,warning,error}{rw}
Determines the behaviour if an undefined procedure is encountered. If
\const{fail}, the predicate fails silently. If \const{warn}, a warning
is printed, and execution continues as if the predicate was not defined,
and if \const{error} (default), an \except{existence_error} exception is
raised. This flag is local to each module and inherited from the
module's \jargon{import-module}. Using default setup, this implies that
normal modules inherit the flag from \const{user}, which in turn
inherit the value \const{error} from \const{system}.  The user may
change the flag for module \const{user} to change the default for all
application modules or for a specific module.  It is strongly advised
to keep the \const{error} default and use \index{dynamic/1}\predref{dynamic}{1} and/or \index{multifile/1}\predref{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 \index{set_prolog_flag/2}\predref{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 \index{create_prolog_flag/3}\predref{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 \index{create_prolog_flag/3}\predref{create_prolog_flag}{3} to create flags for their library.

    \prologflagitem{var_prefix}{bool}{rw}
If \const{true} (default \const{false}), variables must start with an
underscore (\chr{_}).  May be changed. This flag is local to the
module in which it is changed.  See \secref{varprefix}.

    \prologflagitem{verbose}{atom}{rw}
This flag is used by \index{print_message/2}\predref{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 \index{load_files/2}\predref{load_files}{2}.

    \prologflagitem{verbose_file_search}{bool}{rw}
If \const{true} (default \const{false}), print messages indicating the
progress of \index{absolute_file_name/[2,3]}\predref{absolute_file_name}{[2,3]} in locating files.  Intended for
debugging complicated file-search paths.  See also \index{file_search_path/2}\predref{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}$$

    \prologflagitem{version_data}{swi(Major, Minor, Patch, Extra)}{r}
Part of the dialect compatibility layer; see also the Prolog flag
\prologflag{dialect} and \secref{dialect}. \arg{Extra} provides
platform-specific version information as a list. \arg{Extra} is used for
\jargon{tagged versions} such as ``7.4.0-rc1'', in which case
\arg{Extra} contains a term \term{tag}{rc1}.

    \prologflagitem{version_git}{atom}{r}
Available if created from a git repository.  See \program{git-describe}
for details.

    \prologflagitem{windows}{bool}{r}
If present and \const{true}, the operating system is MS-Windows.

    \prologflagitem{wine_version}{atom}{r}
If present, SWI-Prolog is the MS-Windows version running under
the \href{https://www.winehq.org/}{Wine} emulator.

    \prologflagitem{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
\index{use_module/1}\predref{use_module}{1} for details.

    \prologflagitem{win_file_access_check}{atom}{rw}
Controls the behaviour or \index{access_file/2}\predref{access_file}{2} under Windows. There is no
reliable way to check access to files and directories on Windows. This
flag allows for switching between three alternative approximations.

\begin{description}
    \termitem{access}{}
Use Windows _waccess() function. This ignores ACLs (Access Control
List) and thus may indicate that access is allowed while it is not.
    \termitem{getfilesecurity}{}
Use the Windows GetFileSecurity() function.  This does not work on
all file systems, but is probably the best choice on file systems
that do support it, notably local NTFS volumes.
    \termitem{openclose}{}
Try to open the file and close it.  This works reliable for files,
but not for directories.  Currently directories are checked using
_waccess().  This is the default.
\end{description}

    \prologflagitem{windows}{bool}{r}
\index{windows}%
If present and \const{true}, the operating system is an implementation
of Microsoft Windows. This flag is only available on MS-Windows based
versions.  See also \prologflag{unix}.

    \prologflagitem{write_attributes}{atom}{rw}
Defines how \index{write/1}\predref{write}{1} and friends write attributed variables.  The option
values are described with the \const{attributes} option of
\index{write_term/3}\predref{write_term}{3}.  Default is \const{ignore}.

    \prologflagitem{write_help_with_overstrike}{bool}{r}
Internal flag used by \index{help/1}\predref{help}{1} when writing to a terminal. If
present and \const{true} it prints bold and underlined text using
\jargon{overstrike}.

    \prologflagitem{xpce}{bool}{r}
Available and set to \const{true} if the XPCE graphics system is loaded.

    \prologflagitem{xpce_version}{atom}{r}
Available and set to the version of the loaded XPCE system.

    \prologflagitem{xref}{bool}{rw}
If \const{true}, source code is being read for \emph{analysis} purposes
such as cross-referencing.  Otherwise (default) it is being read to be
compiled.  This flag is used at several places by \index{term_expansion/2}\predref{term_expansion}{2} and
\index{goal_expansion/2}\predref{goal_expansion}{2} hooks, notably if these hooks use side effects.  See
also the libraries \pllib{prolog_source} and \pllib{prolog_xref}.
\end{description}

    \predicate[ISO]{set_prolog_flag}{2}{:Key, +Value}
Define a new Prolog flag or change its value.  \arg{Key} is an atom.
If the flag is a system-defined flag that is not marked
\jargon{changeable} above, an attempt to modify the flag yields a
\except{permission_error}.  If the provided \arg{Value} does not
match the type of the flag, a \except{type_error} is raised.

Some flags (e.g., \prologflag{unknown}) are maintained on a per-module
basis. The addressed module is determined by the \arg{Key} argument.

In addition to ISO, SWI-Prolog allows for user-defined Prolog flags. The
type of the flag is determined from the initial value and cannot be
changed afterwards. Defined types are \const{boolean} (if the initial
value is one of \const{false}, \const{true}, \const{on} or \const{off}),
\const{atom} if the initial value is any other atom, \const{integer} if
the value is an integer that can be expressed as a 64-bit signed value.
Any other initial value results in an untyped flag that can represent
any valid Prolog term.

The behaviour when \arg{Key} denotes a non-existent key depends on the
Prolog flag \prologflag{user_flags}. The default is to define them
silently. New code is encouraged to use \index{create_prolog_flag/3}\predref{create_prolog_flag}{3} for
portability.

    \predicate[YAP]{create_prolog_flag}{3}{+Key, +Value, +Options}
Create a new Prolog flag.  The ISO standard does not foresee creation
of new flags, but many libraries introduce new flags.  \arg{Options}
is a list of the options below.  See also \prologflag{user_flags}.

    \begin{description}
	\termitem{access}{+Access}
	Define access rights for the flag. Values are \const{read_write}
	and \const{read_only}.  The default is \const{read_write}.

	\termitem{type}{+Atom}
	Define a type restriction.  Possible values are
	\const{boolean}, \const{atom}, \const{integer}, \const{float}
	and \const{term}.  The default is determined from the initial
	value.  Note that \const{term} restricts the term to be ground.

	\termitem{keep}{+Boolean}
	If \const{true}, do not modify the flag if it already exists.
	Otherwise (default), this predicate behaves as \index{set_prolog_flag/2}\predref{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 [\index{portray/1}\predref{portray}{1}]
Hook into \index{write_term/3}\predref{write_term}{3} to alter the way terms are printed (ISO).
    \item [\index{message_hook/3}\predref{message_hook}{3}]
Hook into \index{print_message/2}\predref{print_message}{2} to alter the way system messages are printed
(Quintus/SICStus).
    \item [\index{message_property/2}\predref{message_property}{2}]
Hook into \index{print_message/2}\predref{print_message}{2} that defines prefix, output stream, color,
etc.
    \item [\index{message_prefix_hook/2}\predref{message_prefix_hook}{2}]
Hook into \index{print_message/2}\predref{print_message}{2} to add additional prefixes to the message such
as the time and thread.
    \item [\index{library_directory/1}\predref{library_directory}{1}]
Hook into \index{absolute_file_name/3}\predref{absolute_file_name}{3} to define new library directories
(most Prolog systems).
    \item [\index{file_search_path/2}\predref{file_search_path}{2}]
Hook into \index{absolute_file_name/3}\predref{absolute_file_name}{3} to define new search paths
(Quintus/SICStus).
    \item [\index{term_expansion/2}\predref{term_expansion}{2}]
Hook into \index{load_files/2}\predref{load_files}{2} to modify read terms before they are compiled
(macro-processing) (most Prolog systems).
    \item [\index{goal_expansion/2}\predref{goal_expansion}{2}]
Same as \index{term_expansion/2}\predref{term_expansion}{2} for individual goals (SICStus).
    \item [\index{prolog_load_file/2}\predref{prolog_load_file}{2}]
Hook into \index{load_files/2}\predref{load_files}{2} to load other data formats for Prolog sources
from `non-file' resources.  The \index{load_files/2}\predref{load_files}{2} predicate is the ancestor
of \index{consult/1}\predref{consult}{1}, \index{use_module/1}\predref{use_module}{1}, etc.
    \item [\index{prolog_edit:locate/3}\qpredref{prolog_edit}{locate}{3}]
Hook into \index{edit/1}\predref{edit}{1} to locate objects (SWI).
    \item [\index{prolog_edit:edit_source/1}\qpredref{prolog_edit}{edit_source}{1}]
Hook into \index{edit/1}\predref{edit}{1} to call an internal editor (SWI).
    \item [\index{prolog_edit:edit_command/2}\qpredref{prolog_edit}{edit_command}{2}]
Hook into \index{edit/1}\predref{edit}{1} to define the external editor to use (SWI).
    \item [\index{prolog_list_goal/1}\predref{prolog_list_goal}{1}]
Hook into the tracer to list the code associated to a particular goal
(SWI).
    \item [\index{prolog_trace_interception/4}\predref{prolog_trace_interception}{4}]
Hook into the tracer to handle trace events (SWI).
    \item [\index{prolog:debug_control_hook/1}\qpredref{prolog}{debug_control_hook}{1}]
Hook in \index{spy/1}\predref{spy}{1}, \index{nospy/1}\predref{nospy}{1}, \index{nospyall/0}\predref{nospyall}{0} and \index{debugging/0}\predref{debugging}{0} to extend these
control predicates to higher-level libraries.
    \item [\index{prolog:help_hook/1}\qpredref{prolog}{help_hook}{1}]
Hook in \index{help/0}\predref{help}{0}, \index{help/1}\predref{help}{1} and \index{apropos/1}\predref{apropos}{1} to extend the help system.
    \item [\index{resource/3}\predref{resource}{3}]
Define a new resource (not really a hook, but similar) (SWI).
    \item [\index{exception/3}\predref{exception}{3}]
Old attempt to a generic hook mechanism.  Handles undefined predicates (SWI).
    \item [\index{attr_unify_hook/2}\predref{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 \index{user:exception/3}\qpredref{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 \index{library_directory/1}\predref{library_directory}{1}, \index{file_search_path/2}\predref{file_search_path}{2} and
\index{reload_library_index/0}\predref{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 \index{current_prolog_flag/2}\predref{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 \index{use_module/2}\predref{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}

\noindent
The predicate \index{make/0}\predref{make}{0} updates the autoload index. It searches for all
library directories (see \index{library_directory/1}\predref{library_directory}{1} and \index{file_search_path/2}\predref{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
\index{make_library_index/2}\predref{make_library_index}{2}. Otherwise \index{make_library_index/1}\predref{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}

\noindent
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 \index{library_directory/1}\predref{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}

\noindent
If this call appears as a directive, it is term-expanded into a clause
for \index{user:file_search_path/2}\qpredref{user}{file_search_path}{2} and a directive calling
\index{reload_library_index/0}\predref{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}

\noindent
    \predicate{reload_library_index}{0}{}
Force reloading the index after modifying the set of library directories
by changing the rules for \index{library_directory/1}\predref{library_directory}{1}, \index{file_search_path/2}\predref{file_search_path}{2},
adding or deleting \file{INDEX.pl} files. This predicate does \emph{not}
update the \file{INDEX.pl} files.  Check \index{make_library_index/[1,2]}\predref{make_library_index}{[1,2]} and
\index{make/0}\predref{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
\index{reload_library_index/0}\predref{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 \index{qsave_program/2}\predref{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 \index{autoload/0}\predref{autoload}{0}.


\section{Packs: community add-ons}		\label{sec:packs}

SWI-Prolog has a mechanism for easy incorporation of community
extensions. See the \href{http://www.swi-prolog.org/pack/list}{pack
landing page} for details and available packs.  This section documents
the built-in predicates to attach packs.  Predicates for creating,
registering and installing packs are provided by the library
\pllib{prolog_pack}.

\begin{description}
    \predicate{attach_packs}{0}{}
Attaches all packs in subdirectories of directories that are accessible
through the \jargon{file search path} (see \index{absolute_file_name/3}\predref{absolute_file_name}{3})
\const{pack}.  The default for this search path is:

\begin{code}
user:file_search_path(pack, app_data(pack)).
user:file_search_path(pack, swi(pack)).
\end{code}

\noindent
The predicate \index{attach_packs/0}\predref{attach_packs}{0} is called on startup of SWI-Prolog.

    \predicate{attach_packs}{1}{+Directory}
Attach all packs in subdirectories of \arg{Directory}.  Same as
\term{attach_packs}{Directory, []}.
    \nodescription
    \predicate{attach_packs}{2}{+Directory, +Options}
Attach all packs in subdirectories of \arg{Directory}.  Options
is one of:

    \begin{description}
	\termitem{search}{+Where}
Determines the order in which pack library directories are searched.
Default is to add new packages at the end (\const{last}).  Using
\const{first}, new packages are added at the start.

	\termitem{duplicate}{+Action}
Determines what happens if a pack with the same name is already
attached.  Default is \const{warning}, which prints a warning and
ignores the new pack.  Other options are \const{keep}, which is
like \const{warning} but operates silently and \const{replace},
which detaches the old pack and attaches the new.
    \end{description}

The predicate \index{attach_packs/2}\predref{attach_packs}{2} can be used to attach packages that
are bundled with an application.
\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 \index{current_prolog_flag/2}\predref{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
\href{http://www.swi-prolog.org/Links.html}{online tutorials}. In
addition to the differences from the ISO standard documented here,
SWI-Prolog offers several extensions, some of which also extend the
syntax. See \secref{extensions} for more information.


\subsection{ISO Syntax Support}			\label{sec:isosyntax}

This section lists various extensions w.r.t.\ the ISO Prolog syntax.

\subsubsection{Processor Character Set}		\label{sec:processorcharset}

\index{ISO Latin 1}\index{character set}%
The processor character set specifies the class of each character used
for parsing Prolog source text.  Character classification is fixed to
\href{http://www.unicode.org/}{Unicode}.  See also \secref{widechars}.

\subsubsection{Nested comments}			\label{sec:nestedcomments}

SWI-Prolog allows for nesting \exam{/* \ldots */} comments. Where the
ISO standard accepts \exam{/* \ldots /* \ldots */} as a comment,
SWI-Prolog will search for a terminating \exam{*/}. This is useful if
some code with \exam{/* \ldots */} comment statements in it should be
commented out. This modification also avoids unintended commenting in
the example below, where the closing \exam{*/} of the first comment has
been forgotten.\footnote{Recent copies of GCC give a style warning if
\exam{/*} is encountered in a comment, which suggests that this
problem has been recognised more widely.}

\begin{code}
/* comment

code

/* second comment */

code

\end{code}

\noindent
\subsubsection{Character Escape Syntax}		\label{sec:charescapes}

Within quoted atoms (using single quotes: \exam{'\bnfmeta{atom}'}) special
characters are represented using escape sequences. An escape sequence is
led in by the backslash (\chr{\Sneg}) 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}

\noindent
    \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{\Sneg}, 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{\Sneg}\bnfmeta{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}

\noindent
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}

\noindent
Note that SWI-Prolog also allows unescaped newlines to appear in quoted
material.  This is not allowed be the ISO standard, but used to be
common practice before.
    \escapeitem{e}
Escape character (\textsc{ASCII} 27). Not ISO, but widely supported.
    \escapeitem{f}
Form-feed character.
    \escapeitem{n}
Next-line character.
    \escapeitem{r}
Carriage-return only (i.e., go back to the start of the line).
    \escapeitem{s}
Space character.  Intended to allow writing \verb$0'\s$
to get the character code of the space character. Not ISO.
    \escapeitem{t}
Horizontal tab character.
    \escapeitem{v}
Vertical tab character (\textsc{ASCII} 11).
    \escapeitem{\SxXX}
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{\Sneg} 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{\Sneg}
Escapes the backslash itself.  Thus, \verb$'\\'$ is an atom
consisting of a single \chr{\Sneg}.
    \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 \index{current_prolog_flag/2}\predref{current_prolog_flag}{2}. Character escapes conflict with \index{writef/2}\predref{writef}{2} in
two ways: \verb$\40$ is interpreted as decimal 40 by \index{writef/2}\predref{writef}{2}, but as
octal 40 (decimal 32) by \verb$read$. Also, the \index{writef/2}\predref{writef}{2} sequence
\fmtseq{\l} is illegal. It is advised to use the more widely supported
\index{format/[2,3]}\predref{format}{[2,3]} predicate instead. If you insist upon using \index{writef/2}\predref{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{\bnfmeta{radix}'\bnfmeta{number}}, where \bnfmeta{radix} is a number between 2
and 36. ISO defines binary, octal and hexadecimal numbers using
\exam{0{\em [bxo]}\bnfmeta{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}

\noindent
Integers can be printed using this notation with \index{format/2}\predref{format}{2}, using the
\verb$~I$ format specifier.  For example:

\begin{code}
?- format('~I', [1000000]).
1_000_000
\end{code}

\noindent
The current syntax has been proposed by Ulrich Neumerkel on the
SWI-Prolog mailinglist.


\subsubsection{NaN and Infinity floats and their syntax}
\label{sec:floatsyntax}

SWI-Prolog supports reading and printing `special' floating point values
according to
\href{http://eclipseclp.org/Specs/core_update_float.html}{Proposal for
Prolog Standard core update wrt floating point arithmetic} by Joachim
Schimpf and available in ECLiPSe Prolog. In particular,

\begin{itemize}
    \item Infinity is printed as \verb$1.0Inf$ or \verb$-1.0Inf$.  Any
    sequence matching the regular expression \verb$[+-]?\sd+[.]\sd+Inf$
    is mapped to plus or minus infinity.

    \item \const{NaN} (Not a Number) is printed as \verb$1.xxxNaN$, where
    \textit{1.xxx} is the float after replacing the exponent by `1'.
    Such numbers are read, resulting in the same \const{NaN}. The
    \const{NaN} constant can also be produced using the function
    \funcref{nan}{0}, e.g.,

\begin{code}
?- A is nan.
A = 1.5NaN.
\end{code}

\noindent
\end{itemize}

Note that, compliant with the ISO standard, SWI-Prolog arithmetic (see
\secref{arith}) never returns one of the above values but instead raises
an \jargon{exception}, e.g.,

\begin{code}
?- A is 1/0.
ERROR: //2: Arithmetic: evaluation error: `zero_divisor'
\end{code}

\noindent
There is one exception to this rule. For compatibility the functions
\funcref{inf}{0} and \funcref{nan}{0} return \verb$1.0Inf$ and the
default system \const{NaN}. The ability to create, read and write such
values is primarily provided to exchange data with languages that can
represent the full range of IEEE doubles.

\subsubsection{Force only underscore to introduce a variable}
\label{sec:varprefix}

According to the ISO standard and most Prolog systems, identifiers that
start with an uppercase letter or an underscore are variables. In the
past, \jargon{Prolog by BIM} provided an alternative syntax, where only
the underscore (\chr{_}) introduces a variable. As of SWI-Prolog 7.3.27
SWI-Prolog supports this alternative syntax, controlled by the Prolog
flag \prologflag{var_prefix}. As the \prologflag{character_escapes}
flag, this flag is maintained per module, where the default is
\const{false}, supporting standard syntax.

Having only the underscore introduce a variable is particularly useful
if code contains identifiers for case sensitive external languages.
Examples are the RDF library where code frequently specifies property
and class names\footnote{Samer Abdallah suggested this feature based on
experience with non-Prolog users using the RDF library.} and the R
interface for specifying functions or variables that start with an
uppercase character. Lexical databases where part of the terms start with
an uppercase letter is another category were the readability of the code
improves using this option.


\subsubsection{Unicode Prolog source}		\label{sec:unicodesyntax}

The ISO standard specifies the Prolog syntax in ASCII characters. As
SWI-Prolog supports Unicode in source files we must extend the syntax.
This section describes the implication for the source files, while
writing international source files is described in \secref{intsrcfile}.

The SWI-Prolog Unicode character classification is based on version
6.0.0 of the Unicode standard. Please note that \index{char_type/2}\predref{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{\Sequal}: 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 \index{style_check/1}\predref{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 \index{style_check/1}\predref{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
\index{read_clause/3}\predref{read_clause}{3} (and \index{read_term/3}\predref{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}

\noindent
\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{\Suniv}{2},
\predref{\Sequal}{2},
\predref{\Sstructeq}{2},
\predref{\Seq}{2},
\predref{\Stlt}{2},
\predref{\Stle}{2},
\predref{\Stge}{2},
\predref{\Stgt}{2},
\predref{\Snequal}{2},
\predref{\Sstructneq}{2},
\predref{\Sne}{2},
\index{acyclic_term/1}\predref{acyclic_term}{1},
\index{bagof/3}\predref{bagof}{3},
\index{compare/3}\predref{compare}{3},
\index{copy_term/2}\predref{copy_term}{2},
\index{cyclic_term/1}\predref{cyclic_term}{1},
\index{dif/2}\predref{dif}{2},
\index{duplicate_term/2}\predref{duplicate_term}{2},
\index{findall/3}\predref{findall}{3},
\index{ground/1}\predref{ground}{1},
\index{term_hash/2}\predref{term_hash}{2},
\index{numbervars/3}\predref{numbervars}{3},
\index{numbervars/4}\predref{numbervars}{4},
\index{recorda/3}\predref{recorda}{3},
\index{recordz/3}\predref{recordz}{3},
\index{setof/3}\predref{setof}{3},
\index{subsumes_term/2}\predref{subsumes_term}{2},
\index{term_variables/2}\predref{term_variables}{2},
\index{throw/1}\predref{throw}{1},
\index{unify_with_occurs_check/2}\predref{unify_with_occurs_check}{2},
\index{unifiable/3}\predref{unifiable}{3},
\index{when/2}\predref{when}{2},
\index{write/1}\predref{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 (\index{asserta/1}\predref{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}

\noindent
\section{Just-in-time clause indexing}		\label{sec:jitindex}

\index{jitindex}\index{indexing,jiti}%
SWI-Prolog provides `just-in-time' indexing over multiple
arguments.\footnote{JIT indexing was added in version 5.11.29 (Oct.
2011).} `Just-in-time' means that clause indexes are not built by the
compiler (or \index{asserta/1}\predref{asserta}{1} for dynamic predicates), but on the first call
to such a predicate where an index might help (i.e., a call where at
least one argument is instantiated).  This section describes the rules
used by the indexing logic.  Note that this logic is not `set in stone'.
The indexing capabilities of the system will change. Although this
inevitably leads to some regressing on some particular use cases, we
strive to avoid significant slowdowns.

The list below describes the clause selection process for various
predicates and calls.  The alternatives are considered in the order
they are presented.

\begin{itemlist}
    \item [Special purpose code]
Currently two special cases are recognised by the compiler: static code
with exactly one clause and static code with two clauses, one where the
first argument is the empty list (\verb$[]$) and one where the first
argument is a non-empty list (\verb$[_|_]$).

    \item [Linear scan on first argument]
The principal clause list maintains a \jargon{key} for the first
argument. An indexing key is either a constant or a functor (name/arity
reference). Calls with an instantiated first argument and less than
10 clauses perform a linear scan for a possible matching clause using
this index key.  If the result is deterministic it is used.  Otherwise
the system looks for better indexes.\footnote{Up to 7.7.2 this result
was used also when non-deterministic.}.

    \item [Hash lookup]
If none of the above applies, the system considers the available hash
tables for which the corresponding argument is instantiated. If a table
is found with acceptable characteristics, it is used. Otherwise it
assesses the clauses for all instantiated arguments and selects the best
candidate for creating a new hash table. If there is no single argument
that provides an acceptable hash quality it will search for a
combination of arguments.\footnote{The last step was added in SWI-Prolog
7.5.8.}  Searching for index candidates is only performed on the first
254 arguments.

If a single-argument index contains multiple compound terms with the
same name and arity and at least one non-variable argument, a
\jargon{list index} is created. A subsequent query where this argument
is bound to a compound causes jiti indexing to be applied
\jargon{recursively} on the arguments of the term.  This is called
\jargon{deep indexing}.\footnote{Deep indexing was added in version
7.7.4.}  See also \secref{deep-indexing}

Clauses that have a variable at an otherwise indexable argument must be
linked into all hash buckets. Currently, predicates that have more than
10\% such clauses for a specific argument are not considered for
indexing on that argument.

Disregarding variables, the suitability of an argument for hashing is
expressed as the number of unique indexable values divided by the
standard deviation of the number of duplicate values for each value plus
one.\footnote{Earlier versions simply used the number of unique values,
but poor distribution of values makes a table less suitable.  This was
analysed by Fabien Noth and G\"unter Kniesel.}

The indexes of dynamic predicates are deleted if the number of clauses
is doubled since its creation or reduced below 1/4th. The JIT approach
will recreate a suitable index on the next call. Indexes of running
predicates cannot be deleted. They are added to a `removed index list'
associated to the predicate. Outdated indexes of predicates are
reclaimed by \index{garbage_collect_clauses/0}\predref{garbage_collect_clauses}{0}.  The clause garbage collector
is scheduled automatically, based on time and space based heuristics.
See \index{garbage_collect_clauses/0}\predref{garbage_collect_clauses}{0} for details.
\end{itemlist}

The library \pllib{prolog_jiti} provides \index{jiti_list/0}\predref{jiti_list}{0},1 to list the
characteristics of all or some of the created hash tables.

\paragraph{Dynamic predicates} are indexed using the same rules as
static predicates, except that the \jargon{special purpose} schemes are
never applied. In addition, the JITI index is discarded if the number of
clauses has doubled since the predicate was last assessed or shrinks
below one fourth. A subsequent call reassesses the statistics of the
dynamic predicate and, when applicable, creates a new index.


\subsection{Deep indexing}
\label{sec:deep-indexing}

\index{indexing,deep}%
As introduced in \secref{jitindex}, \jargon{deep indexing} creates hash
tables distinguish clauses that share a compound with the same name and
arity. Deep indexes allow for efficient lookup of arbitrary terms.
Without it is advised to \jargon{flatten} the term, i.e., turn
\term{F}{X} into two arguments for the fact, one argument denoting the
functor \arg{F} and the second the argument {X}. This works fine as long
as the arity of the each of the terms is the same. Alternatively we can
use \index{term_hash/2}\predref{term_hash}{2} or \index{term_hash/4}\predref{term_hash}{4} to add a column holding the hash of the
term. That approach can deal with arbitrary arities, but requires us to
know that the term is ground (\index{term_hash/2}\predref{term_hash}{2}) or up to which depth we get
sufficient selectivity (\index{term_hash/4}\predref{term_hash}{4}).

Deep indexing does not require this knowledge and leads to efficient
lookup regardless of the instantiation of the query and term.  The
current version does come with some limitations:

\begin{itemize}
    \item The decision which index to use is taken independently
    at each level.  Future versions may be smarter on this.
    \item Deep indexing only applies to a \emph{single argument}
    indexes (on any argument).
    \item Currently, the depth of indexing is limited to 7 levels.
\end{itemize}

\index{indexing,DCG}\index{DCG,indexing}%
Note that, when compiling DCGs (see \secref{DCG}) and the first body
term is a \jargon{literal}, it is included into the clause head. See
for example the grammar and its plain Prolog representation below.

\begin{code}
det(det(a), sg)  --> "a".
det(det(an), pl) --> "an".
det(det(the), _) --> "the".
\end{code}

\noindent
\begin{code}
?- listing(det).
det(det(a), sg, [97|A], A).
det(det(an), pl, [97, 110|A], A).
det(det(the), _, [116, 104, 101|A], A).
\end{code}

\noindent
Deep argument indexing will create indexes for the 3rd list argument,
providing speedup and making clause selection deterministic if all rules
start with a literal and all literals are unique in the first 6
elements. Note that deep index creation stops as soon as a determistic
choice can be made or there are no two clauses that have the same
name/arity combination.

\subsection{Future directions}
\label{sec:indexfut}

\begin{itemize}
    \item
The `special cases' can be extended.  This is notably attractive for
static predicates with a relatively small number of clauses where a
hash lookup is too costly.

    \item
Create an efficient decision diagram for selecting between low numbers
of static clauses.

    \item
Implement a better judgements for selecting between deep and plain
indexes.
\end{itemize}

\subsection{Indexing and portability}
\label{sec:indexport}

The base-line functionality of Prolog implementations provides indexing
on constants and functor (name/arity) on the first argument. This must
be your assumption if wide portability of your program is important.
This can typically be achieved by exploiting \index{term_hash/2}\predref{term_hash}{2} or \index{term_hash/4}\predref{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 \index{get_code/2}\predref{get_code}{2} and \index{put_code/2}\predref{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 \index{load_files/2}\predref{load_files}{2}
for loading Prolog source with an alternative encoding, \index{open/4}\predref{open}{4} when
opening files or using \index{set_stream/2}\predref{set_stream}{2} on any open stream. For Prolog
source files we also provide the \index{encoding/1}\predref{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 \index{set_stream/2}\predref{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 \index{open/4}\predref{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 \index{stream_property/2}\predref{stream_property}{2}. When opening a file for writing,
writing a BOM can be requested using the option \term{bom}{true} with
\index{open/4}\predref{open}{4}.


\section{System limits}				\label{sec:limits}

\subsection{Limits on memory areas}		\label{sec:memlimit}

The SWI-Prolog engine uses three \jargon{stacks} the \jargon{local
stack} (also called \jargon{environment stack}) stores the environment
frames used to call predicates as well as choice points. The
\jargon{global stack} (also called \jargon{heap}) contains terms,
floats, strings and large integers. Finally, the \jargon{trail stack}
records variable bindings and assignments to support
\jargon{backtracking}. The internal data representation limits these
stacks to 128~MB (each) on 32-bit processors. More generally to
$\pow{2}{\mbox{bits-per-pointer} - 5}$ bytes, which implies they are
virtually unlimited on 64-bit machines.

As of version 7.7.14, the stacks are restricted by the writeable flag
\prologflag{stack_limit} or the command line option
\cmdlineoption{--stack_limit}. This flag limits the combined size of the
three stacks per thread. The default limit is currently 512~Mbytes on
32-bit machines, which imposes no additional limit considering the
128~Mbytes hard limit on 32-bit and 1~Gbytes on 64-bit machines.

Considering portability, applications that need to modify the default
limits are advised to do so using the Prolog flag
\prologflag{stack_limit}.

\begin{table}
\begin{center}
\begin{tabular}{|c|l|p{5cm}|}
\hline
Option & Area name & Description \\
\hline
\cmdlineoption{-L} & \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} & \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} & \bf trail stack & The trail stack is used to store
                       assignments during execution.  Entries on this
                       stack remain alive until backtracking before the
                       point of creation or the garbage collector
                       determines they are no longer needed.

		       As the trail and global stacks are garbage
		       collected together, a small trail can cause
		       an excessive amount of garbage collections.
		       To avoid this, the trail is automatically
		       resized to be at least 1/6th of the size of
		       the global stack.  \\
\hline
\end{tabular}
\end{center}
    \caption{Memory areas}
    \label{tab:areas}
\end{table}


\subsubsection{The heap}			\label{sec:heap}

\index{stack,memory management}%
\index{memory,layout}%
With the heap, we refer to the memory area used by malloc()
and friends. SWI-Prolog uses the area to store atoms, functors,
predicates and their clauses, records and other dynamic data. No limits
are imposed on the addresses returned by malloc() and friends.


\subsection{Other Limits}			\label{sec:morelimits}

\begin{description}
    \item[Clauses]
The only limit on clauses is their arity (the number of arguments to
the head), which is limited to 1024.  Raising this limit is easy and
relatively cheap; removing it is harder.

    \item[Atoms and Strings]
SWI-Prolog has no limits on the length of atoms and strings. The number
of atoms is limited to 16777216 (16M) on 32-bit machines. On 64-bit
machines this is virtually unlimited. See also \secref{atomgc}.

    \item[Memory areas]
On 32-bit hardware, SWI-Prolog data is packed in a 32-bit word, which
contains both type and value information. The size of the various memory
areas is limited to 128~MB for each of the areas, except for the program
heap, which is not limited.  On 64-bit hardware there are no meaningful
limits.

    \item[Nesting of terms]
Most built-in predicates that process Prolog terms create an explicitly
managed stack and perform optimization for processing the last argument
of a term. This implies they can process deeply nested terms at constant
and low usage of the C stack, and the system raises a resource error if
no more stack can be allocated.  Currently only \index{read/1}\predref{read}{1} and \index{write/1}\predref{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}
