\chapter{Overview} \label{sec:overview} \section{Getting started quickly} \label{sec:quickstart} \subsection{Starting SWI-Prolog} \label{sec:starting} \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 \begin{quote} Both the above assume \file{likes.pl} is in your \jargon{working directory}. If you use the command line version \program{swipl} the working directory is the same as the shell from which you started SWI-Prolog. If you started the GUI version (\program{swipl-win}) this depends largely on the OS. You can use \index{pwd/0}\predref{pwd}{0} and \index{cd/0}\predref{cd}{0} to find and change the working directory. The utility \index{ls/0}\predref{ls}{0} lists the contents of the working directory. \begin{code} ?- pwd. % /home/janw/src/swipl-devel/linux/ true. ?- cd('~/tmp'). true. ?- pwd. % /home/janw/tmp/ true. \end{code} \noindent The file \file{likes.pl} is also installed in a subdirectory \file{demo} insides SWI-Prolog's installation directory and may be loaded regardless of the working directory using the command below. See \index{absolute_file_name/3}\predref{absolute_file_name}{3} and \index{file_search_path/2}\predref{file_search_path}{2} for details on how SWI-Prolog specifies file locations. \begin{code} ?- [swi(demo/likes)]. true. \end{code} \noindent \end{quote} 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 convenient way to add a few clauses is by consulting the pseudo file \const{user}. The input is ended using the system end-of-file character. \begin{code} ?- [user]. |: hello :- format('Hello world~n'). |: ^D true. ?- hello. Hello world true. \end{code} \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 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 opens in 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 of \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 \jargon{init} file. This file is searched using \index{absolute_file_name/3}\predref{absolute_file_name}{3} using the path alias (see \index{file_search_path/2}\predref{file_search_path}{2}) \const{app_config}. This is a directory named \file{swi-prolog} below the OS default name for placing application configuration data: \begin{itemize} \item On Windows, the CSIDL folder \const{CSIDL_APPDATA}, typically \verb$C:\Documents and Settings\username\Application Data$. \item If the environment variable \env{XDG_DATA_HOME} is set, use this. This follows the \href{https://standards.freedesktop.org}{free desktop} standard. \item The expansion of \file{~/.config}. \end{itemize} The directory can be found using this call: \begin{code} ?- absolute_file_name(app_config(.), Dir, [file_type(directory)]). Dir = '/home/jan/.config/swi-prolog'. \end{code} \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/init.pl} with (commented) commands that are often used to customize the behaviour of Prolog, such as interfacing to the editor, color selection or history parameters. Many of the development tools provide menu entries for editing the startup file and starting a fresh startup file from the system skeleton. See also the \cmdlineoption{-s} (script) and \cmdlineoption{-F} (system-wide initialisation) in \secref{cmdline} and \secref{initgoal}. \section{Initialisation files and goals} \label{sec:initgoal} Using command line arguments (see \secref{cmdline}), SWI-Prolog can be forced to load files and execute queries for initialisation purposes or non-interactive operation. The most commonly used options are \argoption{-f}{file} or \argoption{-s}{file} to make Prolog load a file, \argoption{-g}{goal} to define initialisation goals and \argoption{-t}{goal} to define the \jargon{top-level goal}. The following is a typical example for starting an application directly from the command line. \begin{code} machine% swipl -s load.pl -g go -t halt \end{code} \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}. \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. \cmdlineoptionitem{--version}{} When given as the only option, it summarises the version and the architecture identifier. \cmdlineoptionitem{--abi-version}{} Print a key (string) that represents the binary compatibility on a number of aspects. See \secref{abi-versions}. \end{description} \subsection{Command line options for running Prolog} \label{sec:running-options} Note that \jargon{boolean options} may be written as \exam{--name} (true), \exam{--noname} or \exam{--no-name} (false). They are written as \exam{--no-name} below as the default is `true'. \begin{description} \cmdlineoptionitem{--debug-on-interrupt}{} Enable debugging on an interrupt signal (Control-C, \const{SIGINT}) immediately. Normally debugging on interrupt is enabled when entering the interactive toplevel. This flag can be used to start the debugger on an interrupt while executing goals from \cmdlineoption{-g} or \index{initialization/[1,2]}\predref{initialization}{[1,2]}. See also the Prolog flag \prologflag{debug_on_interrupt}. \cmdlineoptionitem{--home[=DIR]}{} Use \arg{DIR} as home directory. See \secref{findhome} for details. If \arg{DIR} is omitted, the found location is printed and the process exits. If the location cannot be found an error is printed and the process exits with status 1. \cmdlineoptionitem{--quiet}{} \index{verbose}\index{quiet}% Set the Prolog flag \prologflag{verbose} to \const{silent}, suppressing informational and banner messages. Also available as \cmdlineoption{-q}. \cmdlineoptionitem{--no-debug}{} Disable debugging. See the \index{current_prolog_flag/2}\predref{current_prolog_flag}{2} flag \prologflag{generate_debug_info} for details. \cmdlineoptionitem{--no-signals}{} Inhibit any signal handling by Prolog, a property that is sometimes desirable for embedded applications. This option sets the flag \prologflag{signals} to \const{false}. See \secref{sigembedded} for details. Note that the handler to unblock system calls is still installed. This can be prevented using \exam{--sigalert=0} additionally. See \cmdlineoption{--sigalert}. \cmdlineoptionitem{--no-threads}{} Disable threading for the multi-threaded version at runtime. See also the flags \prologflag{threads} and \prologflag{gc_thread}. \cmdlineoptionitem{--no-packs}{} Do \emph{not} attach extension packages (add-ons). See also \index{attach_packs/0}\predref{attach_packs}{0} and the Prolog flag \prologflag{packs}. \cmdlineoptionitem{--no-pce}{} Enable/disable the xpce GUI subsystem. The default is to make it available as autoload component if it is installed and the system can access the graphics. Using \exam{--pce} load the xpce system in user space and \exam{--no-pce} makes it unavailable in the session. \cmdlineoptionitem{--on-error}{=style} How to handle on errors. See the Prolog flag \prologflag{on_error} for details. \cmdlineoptionitem{--on-warning}{=style} How to handle on warnings. See the Prolog flag \prologflag{on_warning} for details. \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 interruptible 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{init.pl}. `\argoption{-f}{none}' stops SWI-Prolog from searching for a startup file. This option can be used as an alternative to \argoption{-s}{file} that stops Prolog from loading the personal initialisation file. See also \secref{initfile}. \cmdlineoptionitem{-F}{script} Select a startup script from the SWI-Prolog home directory. The script file is named \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 default 1Gb on 64~bit machines and 512Mb on 32~bit machines. For example, to limit the stacks to 32Gb use the command below. Note that the stack limits apply \emph{per thread}. Individual threads may be controlled using the \term{stack_limit}{+Bytes} option of thread_create. Any thread can call \term{set_prolog_flag}{stack_limit, Limit} (see \prologflag{stack_limit}) to adjust the stack limit. This limit is inherited by threads created from this thread. \begin{code} $ swipl --stack-limit=32g \end{code} \noindent \begin{description} \cmdlineoptionitem*{--stack-limit}{=size[bkmg]} Limit the combined size of the Prolog stacks to the indicated \arg{size}. The suffix specifies the value as \textit{bytes}, \textit{Kbytes}, \textit{Mbytes} or \textit{Gbytes}. \cmdlineoptionitem*{--table-space}{=size[bkmg]} Limit for the \arg{table space}. This is where tries holding memoized\footnote{The letter M is used because the T was already in use. It is a memnonic for \textbf{M}emoizing.} answers for \jargon{tabling} are stored. The default is 1Gb on 64~bit machines and 512Mb on 32~bit machines. See the Prolog flag \prologflag{table_space}. \cmdlineoptionitem*{--shared-table-space}{=size[bkmg]} Limit for the table space for \jargon{shared} tables. See \secref{tabling-shared}. \end{description} \subsection{Running goals from the command line} \label{sec:runoptions} \begin{description} \cmdlineoptionitem{-g}{goal} \arg{Goal} is executed just before entering the top level. This option may appear multiple times. See \secref{initgoal} for details. If no initialization goal is present the system calls \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 -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{UI Themes} \label{sec:theme} UI (colour) themes play a role in two parts: when writing to the \jargon{console} and for the xpce-based development tools such as PceEmacs or the graphical debugger. Coloured console output is based on \index{ansi_format/3}\predref{ansi_format}{3}. The central message infra structure based on \index{print_message/2}\predref{print_message}{2} labels message (components) with a Prolog term that specifies the role. This is mapped to concrete colours by means of the hook \index{prolog:console_color/2}\qpredref{prolog}{console_color}{2}. Theming the IDE uses xpce \jargon{class variables} that are initialised from Prolog when xpce is loaded. Themes are implemented as a Prolog file in the file search path library/theme. A theme can be loaded using (for example) the directive below in the user's initialization file (see \secref{initfile}). \begin{code} :- use_module(library(theme/dark)). \end{code} \noindent The theme file \exam{library(theme/auto)} is provided to automatically choose a reasonable theme based on the environment. The current version detects the background color on \textit{xterm} compatible terminal emulators (found on most Unix systems) and loads the \const{dark} theme if the background is `darkish'. The following notes apply to the different platforms on which SWI-Prolog is supported: \begin{description} \item[Unix/Linux] If an xterm compatible terminal emulator is used to run Prolog you may wish to load either an explicit theme or \exam{library(theme/auto)}. \item[Windows] The \program{swipl-win.exe} graphical application can be themed by loading a theme file. The theme file also sets the foreground and background colours for the console. \end{description} \subsection{Status of theme support} \label{sec:theme-status} Theme support was added in SWI-Prolog 8.1.11. Only part of the IDE tools are covered and the only additional theme (\const{dark}) is not net well balanced. The interfaces between the theme file and notably the IDE components is not very well established. Please contribute by improving the \const{dark} theme. Once that is complete and properly functioning we can start adding new themes. \section{GNU Emacs Interface} \label{sec:gemacs} \index{GNU-Emacs}\index{Emacs}% SWI-Prolog provides tight integration with GNU~Emacs through the \const{sweep} package. This package embeds SWI-Prolog as a dynamic Emacs module, allowing for Prolog queries to be executed directly from Emacs Lisp. The accompanying Emacs package \const{sweeprolog.el}, available for installation with the standard Emacs package manager \const{package.el}, builds on top of this embedding to provide a fully integrated development environment for SWI-Prolog in GNU~Emacs. GNU~Emacs ships with by default with a Prolog mode called \const{prolog.el}. Compared to \const{sweeprolog.el}, this mode suffers from some problems that arise due to the lack of a proper Prolog parser. The original \const{prolog.el} by Masanobu Umeda has been included in GNU Emacs since 1989, in 2006 Stefan Monnier added explicit support for SWI-Prolog to \const{prolog.el}. In 2011, most of the original implementation has been replaced with a new Prolog mode written by initially for the XEmacs port by Stefan Bruda. Bruda's mode was adapted to GNU~Emacs by Stefan Monnier, who has been maintaining it along with other GNU~Emacs contributor since. Users of this mode may find useful configuration suggestions at \url{https://www.metalevel.at/pceprolog/}. Other Emacs package that can be useful for working with SWI-Prolog are: \begin{shortlist} \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. \item \url{https://emacs-lsp.github.io/dap-mode/page/configuration/#swi-prolog}\\ Debug Adapter Protocol (DAP) support for SWI-Prolog in Emacs via \exam{dap-mode} and the \const{debug_adapter} pack from \url{https://github.com/eshelyaron/debug_adapter} \item \url{https://emacs-lsp.github.io/lsp-mode/page/lsp-prolog/}\\ Language Server Protocol (LSP) support for SWI-Prolog in Emacs via \exam{lsp-mode} and the \const{lsp_server} pack from \url{https://github.com/jamesnvc/lsp_server} \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} (as defined by the Prolog flag \prologflag{toplevel_var_size}). 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} \input{textdebugger.tex} \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 1 ?- [load]. true. 2 ?- go. \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 launched for debugging or inspection purposes using the \cmdlineoption{-l} or \cmdlineoption{-t}. For example, \cmdlineoption{-l} merely loads the script, ignoring \const{main} and \const{program} initialization. \begin{code} swipl -l eval 1+1 ?- 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= 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 ?- [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 \jargon{changeable} 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) -> ; ) \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 technique.} As a consequence, modifying a flag inside a thread does not affect other threads. \begin{description} \prologflagitem{abi_version}{dict}{r} The flag value is a dict with keys that describe the version of the various Application Binary Interface (ABI) components. See \secref{abi-versions} for details. \prologflagitem{access_level}{atom}{rw} This flag defines a normal `user' view (\const{user}, default) or a `system' view. In system view all system code is fully accessible as if it was normal user code. In user view, certain operations are not permitted and some details are kept invisible. We leave the exact consequences undefined, but, for example, system code can be traced using system access and system predicates can be redefined. \prologflagitem{address_bits}{integer}{r} Address size of the hosting machine. Typically 32 or 64. Except for the maximum stack limit, this has few implications to the user. See also the Prolog flag \prologflag{arch}. \prologflagitem{agc_close_streams}{boolean}{rw} When \const{true} (default \const{false}\footnote{Future versions are likely to change the default to \const{true}.}), that atom garbage collector streams that are garbage collected while being open. In addition, a warning is printed. Below is an example of such a warning. \begin{code} WARNING: AGC: closed (0x560e29014400) \end{code} \noindent Note that closing I/O streams should not be left to the (atom) garbage collector because it may take long before the atom garbage collector runs and because that atom garbage collector is \jargon{conservative}, which implies that it is not guaranteed that all garbage atoms are reclaimed. Code that uses I/O streams should use \index{setup_call_cleanup/3}\predref{setup_call_cleanup}{3} using the skeleton below, where \nopredref{process}{1} is a predicate that reads from or writes to \arg{Stream}. \begin{code} setup_call_cleanup( open(..., Stream), process(Stream), close(Stream)), ... \end{code} \noindent Note that the setting for this flag in the \const{main} thread applies. \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{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{android}{bool}{r} If present and true, it indicates we are running on the Android OS. The flag is not present in other operating systems. \prologflagitem{android_api}{integer}{r} If running on Android, it indicates the compile-time API Level defined by the C macro \verb$__ANDROID_API__$. It is not defined if running on other operating systems. The API level may or may not match the API level of the running device, since it is the API level at compile time. \prologflagitem{answer_write_options}{term}{rw} This flag is used by the interactive toplevel to print the value if \jargon{bindings} (answers). The flag value is passed to \index{write_term/2}\predref{write_term}{2} when printing an answer queries. Default is \texttt{[quoted(true), portray(true), max_depth(10), attributes(portray)]}. \prologflagitem{apple}{bool}{r} \index{MacOS}% If present and \const{true}, the operating system is MacOSX. Defined if the C compiler used to compile this version of SWI-Prolog defines \verb$__APPLE__$. Note that the \prologflag{unix} is also defined for MacOSX. \prologflag{apple_universal_binary}{bool}{r} If present and \const{true}, SWI-Prolog has been build as a \jargon{universal binary}. Universal binaries contain native executable code for multiple architectures. Currently the supported architectures are \const{x86_64} and \const{arm64}. The archirecture prefix for components is \const{fat-darwin} while the \prologflag{arch} depends on the actual CPU type. \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}. For Apple, see also \prologflag{apple_universal_binary}. \prologflagitem{argv}{list}{rw} List is a list of atoms representing the application command line arguments. Application command line arguments are those that have \emph{not} been processed by Prolog during its initialization. Note that Prolog's argument processing stops at \const{--} or the first non-option argument. See also \prologflag{os_argv}.\footnote{Prior to version 6.5.2, \prologflag{argv} was defined as \prologflag{os_argv} is now. The change was made for compatibility reasons and because the current definition is more practical.} \prologflagitem{associated_file}{atom}{r} Set if Prolog was started with a prolog file as argument. Used by e.g., \index{edit/0}\predref{edit}{0} to edit the initial file. \prologflagitem{autoload}{atom}{rw} This flag controls autoloading predicates based on \index{autoload/1}\predref{autoload}{1} and \index{autoload/2}\predref{autoload}{2} as well as predicates from \jargon{autoload libraries}. It has the following values: \begin{description} \termitem{false}{} Predicates are never auto-loaded. If predicates have been imported before using \index{autoload/[1,2]}\predref{autoload}{[1,2]}, load the referenced files immediately using \index{use_module/[1,2]}\predref{use_module}{[1,2]}. Note that most of the development utilities such as \index{listing/1}\predref{listing}{1} have to be explicitly imported before they can be used at the toplevel. \termitem{explicit}{} Do not autoload from \jargon{autoload libraries}, but do use lazy loading for predicates imported using \index{autoload/[1,2]}\predref{autoload}{[1,2]}. \termitem{user}{} As \const{false}, but to autoload library predicates into the global \const{user} module. This makes the development tools and library implicitly available to the toplevel, but not to modules. \termitem{user_or_explicit}{} Combines \const{explicit} with \const{user}, providing lazy loading of predicates imported using \index{autoload/[1,2]}\predref{autoload}{[1,2]} and implicit access to the whole library for the toplevel. \termitem{true}{} Provide full autoloading everywhere. This is the default. \end{description} \prologflagitem{back_quotes}{codes,chars,string,symbol_char}{rw} Defines the term-representation for back-quoted material. The default is \const{codes}. If \cmdlineoption{--traditional} is given, the default is \const{symbol_char}, which allows using \verb$`$ in operators composed of symbols.\footnote{Older versions had a boolean flag \const{backquoted_strings}, which toggled between \const{string} and \const{symbol_char}} See also \secref{string}. \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_libplso}{atom}{rw} Libraries needed to link extensions (shared object, DLL) to SWI-Prolog. Typically empty on ELF systems and \const{-lswipl} on COFF-based systems. See \secref{plld}. \prologflagitem{c_libs}{atom}{rw} Libraries needed to link executables that embed SWI-Prolog. Typically \const{-lswipl} if the SWI-Prolog kernel is a shared (DLL). If the SWI-Prolog kernel is in a static library, this flag also contains the dependencies. \prologflagitem{char_conversion}{bool}{rw} Determines whether character conversion takes place while reading terms. See also \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{character_escapes_unicode}{bool}{rw} If \const{true} (default), \index{write/1}\predref{write}{1} and friends write escaped characters using the \verb$\uXXXX$ or \verb$\UXXXXXXXX$ syntax rather than the ISO Prolog \verb$\x\$ syntax. SWI-Prolog reads both. \prologflagitem{cmake_build_type}{atom}{ro} Provides the \href{https://cmake.org/}{cmake} \jargon{build type} used to build this version of SWI-Prolog. \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} This flag 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. If the argument is a control structure ((A,B), (A;B), (A->B;C), etc.) it is compile to an temporary clause allocated on the environment stack when the meta-predicate is called. \termitem{control}{} Compile meta-arguments that contain control structures to an auxiliary predicate. This generally improves performance as well as the debugging experience. \termitem{always}{} Always create an intermediate clause, even for system predicates.\footnote{This may be used in the future for replacing the normal head of the generated predicate with a special reference (similar to database references as used by, e.g., \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 break points. In addition, last-call optimisation is disabled and the system is more conservative in destroying choice points to simplify debugging. Disabling these optimisations can cause the system to run out of memory on programs that behave correctly if debug mode is off. \prologflagitem{debug_on_error}{bool}{rw} If \const{true}, start the tracer after an error is detected. Otherwise just continue execution. The goal that raised the error will normally fail. See also the Prolog flag \prologflag{report_error}. Default is \const{true}. \prologflagitem{debug_on_interrupt}{bool}{rw} If \const{true}, start the debugger on Control-C.\footnote{More precisely when receiving \const{SIGINT}}. The initial value is \const{false} and the value is set to \const{true} when entering the interactive top level. See \cmdlineoption{--debug-on-interrupt} to start handling interrupts immediately. \prologflagitem{debugger_show_context}{bool}{rw} If \const{true}, show the context module while printing a stack-frame in the tracer. Normally controlled using the `C' option of the tracer. \prologflagitem{debugger_write_options}{term}{rw} This argument is given as option-list to \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{determinism_error}{atom}{rw} This flag defines the behaviour when the predicate determinism is not according to its declaration. See \index{det/1}\predref{det}{1}. Possible values are \const{error} (default), \const{warning} and \const{silent}. \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{string}. 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{executable_format}{atom}{r} Format of the SWI-Prolog executable, e.g. \const{elf} for when \file{swipl} is an ELF binary file. \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{float_max}{float}{r} The biggest representable floating point number. \prologflagitem{float_max_integer}{float}{r} The highest integer that can be represented precisely as a floating point number. \prologflagitem{float_min}{float}{r} The smallest representable floating point number above 0.0. See also \funcref{nexttoward}{2}. \prologflagitem{float_overflow}{atom}{rw} One of \const{error} (default) or \const{infinity}. The first is ISO compliant. Using \const{infinity}, floating point overflow is mapped to positive or negative \const{Inf}. See \secref{ieee-float}. \prologflagitem{float_rounding}{atom}{rw} Defines how arithmetic rounds to a float. Defined values are \const{to_nearest} (default), \const{to_positive}, \const{to_negative} or \const{to_zero}. For most scenarios the function \funcref{roundtoward}{2} provides a safer and faster alternative. \prologflagitem{float_undefined}{atom}{rw} One of \const{error} (default) or \const{nan}. The first is ISO compliant. Using \const{nan}, undefined operations such as \term{sqrt}{-2.0} is mapped to \const{NaN}. See \secref{ieee-float}. \prologflagitem{float_underflow}{atom}{rw} One of \const{error} or \const{ignore} (default). The second is ISO compliant, binding the result to 0.0. \prologflagitem{float_zero_div}{atom}{rw} One of \const{error} (default) or \const{infinity}. The first is ISO compliant. Using \const{infinity}, division by 0.0 is mapped to positive or negative \const{Inf}. See \secref{ieee-float}. \prologflagitem{gc}{bool}{rw} If true (default), the garbage collector is active. If false, neither garbage collection, nor stack shifts will take place, even not on explicit request. May be changed. \prologflagitem{gc_thread}{bool}{r} If \const{true} (default if threading is enabled), atom and clause garbage collection are executed in a separate thread with the \jargon{alias} \const{gc}. Otherwise the thread that detected sufficient garbage executes the garbage collector. As running these global collectors may take relatively long, using a separate thread improves real time behaviour. The \const{gc} thread can be controlled using \index{set_prolog_gc_thread/1}\predref{set_prolog_gc_thread}{1}, which either enables the gc thread or kills the gc thread and waits for it to die. \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{--no-debug}. This flag is scoped within a source file. Many of the libraries have \verb$:- set_prolog_flag(generate_debug_info, false)$ to hide their details from a normal trace.% \footnote{In the current implementation this only causes a flag to be set on the predicate that causes children to be hidden from the debugger. The name anticipates further changes to the compiler.} \prologflagitem{gmp_version}{integer}{r} If Prolog is linked with GMP, this flag gives the major version of the GMP library used. See also \secref{gmpforeign}. This flag is not present when linked to \href{https://bellard.org/libbf/}{LibBF}. Use non-existence of the Prolog flag \prologflag{bounded} to test for big integer and rational number support. \prologflagitem{gui}{bool}{r} Set to \const{true} if XPCE is around and can be used for graphics. \prologflagitem{heartbeat}{integer}{rw} If not zero, call \index{prolog:heartbeat/0}\qpredref{prolog}{heartbeat}{0} every $N$ inferences. $N$ is rounded to a multiple of 16. \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}/boot.prc} and to find its library as \metafile{\bnfmeta{home}/library}. Some installations may put architecture independent files in a \jargon{shared home} and also define \prologflag{shared_home}. System files can be found using \index{absolute_file_name/3}\predref{absolute_file_name}{3} as \term{swi}{file}. See \index{file_search_path/2}\predref{file_search_path}{2}. \prologflagitem{hwnd}{integer}{r} In \program{swipl-win.exe}, this refers to the MS-Windows window handle of the console window. \prologflagitem{integer_rounding_function}{down,toward_zero}{r} ISO Prolog flag describing rounding by \verb$//$ and \verb$rem$ arithmetic functions. Value depends on the C compiler used. \prologflagitem{iso}{bool}{rw} Include some weird ISO compatibility that is incompatible with normal SWI-Prolog behaviour. Currently it has the following effect: \begin{itemize} \item The \functor{\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 Within functional notation and list notation terms must have priority below 1000. That means that rules and control constructs appearing as arguments need bracketing. A term like \exam{[a :- b, c].} must now be disambiguated to mean \exam{[(a :- b), c].} or \exam{[(a :- b, c)].} \item Operators appearing as operands must be bracketed. Instead of \exam{X == -, true.} write \exam{X == (-), true.} Currently, this is not entirely enforced. \item Backslash-escaped newlines are interpreted according to the ISO standard. See \secref{charescapes}. \end{itemize} \end{itemize} \prologflagitem{large_files}{bool}{r} If present and \const{true}, SWI-Prolog has been compiled with \jargon{large file support} (LFS) and is capable of accessing files larger than 2GB. This flag is always \const{true} on 64-bit hardware and true on 32-bit hardware if the configuration detected support for LFS. Note that it may still be the case that the \jargon{file system} on which a particular file resides puts limits on the file size. \prologflagitem{last_call_optimisation}{bool}{rw} Determines whether or not last-call optimisation is enabled. Normally the value of this flag is the negation of the \prologflag{debug} flag. As programs may run out of stack if last-call optimisation is omitted, it is sometimes necessary to enable it during debugging. \prologflagitem{libswipl}{atom}{rw} Path where the SWI-Prolog shared library \file{libswipl}, the SWI-Prolog shared object that provides Prolog, resides. On some systems this can be determined reliably from the running system. On these systems the flag is \emph{read-only}. On other systems it is the configured target installation location and thus this value can be wrong if the installation has been relocated. As we do not have a cross-platform reliable way to compute this path the flag is read-write on such platforms.\footnote{When running from the build environment, this flag is adjusted to reflect the location in the build tree.} Currently, this flag is reliable on Windows and POSIX systems providing the dladdr() function. This function is provided on Linux and MacOS. \prologflagitem{malloc}{atom}{r} Set after a successful identification of the used malloc() implementation. Currently possibly values are \const{tcmalloc} and \const{ptmalloc}. See \secref{malloc} for details. \prologflagitem{max_answers_for_subgoal}{integer}{rw} Limit the number of answers in a table. The atom \const{infinite} clears the flag. By default this flag is not defined. See \secref{tabling-restraints} for details. \prologflagitem{max_answers_for_subgoal_action}{atom}{rw} The action taken when a table reaches the number of answers specified in \prologflag{max_answers_for_subgoal}. Supported values are \const{bounded_rationality}, \const{error} (default) or \const{suspend}. \prologflagitem{max_arity}{unbounded}{r} ISO Prolog flag describing there is no maximum arity to compound terms. \prologflagitem{max_char_code}{integer}{r} Highest (Unicode) code point that is supported. SWI-Prolog supports all Unicode code points from 0 (zero) upto and including the value of this flag. Currently \const{0xffff} on Windows (UCS-2) and \const{0x10ffff} on most other platforms. \prologflagitem{max_integer}{integer}{r} Maximum integer value if integers are \emph{bounded}. See also the flag \prologflag{bounded} and \secref{artypes}. \prologflagitem{max_procedure_arity}{integer}{r} Maximum arity for a predicate. An attempt to define or call such a predicate results in a \exam{representation_error(max_procedure_arity)} exception. Currently set to 1024. \prologflagitem{max_rational_size}{integer}{rw} Limit the size in bytes for rational numbers. This \jargon{tripwire} can be used to identify cases where setting the Prolog flag \prologflag{prefer_rationals} to \const{true} creates excessively big rational numbers and, if precision is not required, one should use floating point arithmetic. \prologflagitem{max_rational_size_action}{atom}{rw} Action when the \prologflag{max_rational_size} tripwire is exceeded. Possible values are \const{error} (default), which throws a tripwire resource error and \const{float}, which converts the rational number into a floating point number. Note that rational numbers may exceed the range for floating point numbers. \prologflagitem{max_table_answer_size}{integer}{rw} Limit the size of an answer substitution for tabling. The atom \const{infinite} clears the flag. By default this flag is not defined. See \secref{tabling-restraints} for details. \prologflagitem{max_table_answer_size_action}{atom}{rw} The action taken if an answer substitution larger than \prologflag{max_table_answer_size} is added to a table. Supported values are \const{error} (default), \const{bounded_rationality}, \const{suspend} and \const{fail}. \prologflagitem{max_table_subgoal_size}{integer}{rw} Limit the size of a goal term accessing a table. The atom \const{infinite} clears the flag. By default this flag is not defined. See \secref{tabling-restraints} for details. \prologflagitem{max_table_subgoal_size_action}{atom}{rw} The action taken if a tabled goal exceeds \prologflag{max_table_subgoal_size}. Supported values are \const{error} (default), \const{abstract} and \const{suspend}. \prologflagitem{max_tagged_integer}{integer}{r} Maximum integer value represented as a `tagged' value. Tagged integers require one word storage. Larger integers are represented as `indirect data' and require significantly more space. \prologflagitem{message_context}{list(atom)}{rw} Context information to add to messages of the levels \const{error} and \const{warning}. The list may contain the elements \const{thread} to add the thread that generates the message to the message, \const{time} or \term{time}{Format} to add a time stamp. The default time format is \verb$%T.%3f$. The default is \exam{[thread]}. See also \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{msys2}{bool}{r} If present, SWI-Prolog is the MS-Windows version running under a \href{https://www.msys2.org/}{MSYS2} shell. \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{on_error}{atom}{rw} Determines how to act on an error printed using \index{print_message/2}\predref{print_message}{2}, i.e., an error that is reported to the user. The possible values are \const{print} (default), \const{status} and \const{halt}. Using \const{halt} the process halts immediately with status 1. Otherwise execution continues. Using \const{status} \index{halt/0}\predref{halt}{0} exits with status 1 if one or more errors were printed by the process. In \jargon{compile} mode (see \cmdlineoption{-c}) the default is \const{status}. This flag can be set from the commandline using \cmdlineoption{--on-error}. See also \secref{compilation-messages}. \prologflagitem{on_warning}{atom}{rw} As \prologflag{on_error}, but for warnings. The default is always \const{print}. The commandline option is \cmdlineoption{--on-warning}. \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{optimise_unify}{bool}{rw} If \const{true} (default), allow the compiler to (re)move explicit unification calls (\predref{\Seq}{2}). While this behaviour can significantly improve performance, it is not yet handled properly by the source-level debugger. See \secref{indexbody}. \prologflagitem{os_argv}{list}{rw} List is a list of atoms representing the command line arguments used to invoke SWI-Prolog. Please note that {\bf all} arguments are included in the list returned. See \prologflag{argv} to get the application options. \prologflagitem{packs}{bool}{r} If \const{true}, extension packs (add-ons) are attached. Can be set to \const{false} using the \cmdlineoption{--no-packs}. \prologflagitem{path_max}{integer}{r} Maximum length of a file pathname as reported by the OS. This length does typically not directly define the number of characters in the file name. The actual limit may be shorter due to jargon{encoding} (e.g., on POSIX systems it typically defines the length limit of the (often) UTF-8 encoded name). The underlying file system may impose additional limits. \prologflagitem{pid}{int}{r} Process identifier of the running Prolog process. Existence of this flag is implementation-defined. \prologflagitem{pipe}{bool}{rw} If true, \exam{open(pipe(command), mode, Stream)}, etc.\ are supported. Can be changed to disable the use of pipes in applications testing this feature. Not recommended. \prologflagitem{portable_vmi}{bool}{rw} If \const{true} (default), generate \fileext{qlf} files and saved states that run both on 32 bit and 64-bit hardware. If \const{false}, some optimized virtual machine instructions are only used if the integer argument is within the range of a tagged integer for 32-bit machines. \prologflagitem{posix_shell}{atom}{rw} Path to a POSIX compatible shell. This default is typically \file{/bin/sh}. This flag is used by \index{shell/1}\predref{shell}{1} and \index{qsave_program/2}\predref{qsave_program}{2}. \prologflagitem{prefer_rationals}{bool}{rw} Only provided if the system is compiled with unbounded and rational arithmetic support (see \prologflag{bounded}). If \const{true}, prefer arithmetic to produce rational numbers over floats. This implies: \begin{itemize} \item Division (\funcref{\Sdiv}{2}) of two integers produces a rational number. \item Power (\funcref{\Shat}{2}) of two integers produces a rational number, \emph{also} if the second operant is a negative number. For example, \verb$2^(-2)$ evaluates to \verb$1/4$. \end{itemize} Using \const{true} can create excessively large rational numbers. The Prolog flag \prologflag{max_rational_size} can be used to detect and act on this \jargon{tripwire}. If \const{false}, rational numbers can only be created using the functions \funcref{rational}{1}, \funcref{rationalize}{1} and \funcref{rdiv}{2} or by reading them. See also \prologflag{rational_syntax}, \secref{syntax-rational-numbers} and \secref{rational}. The current default is \const{false}. We consider changing this to \const{true} in the future. Users are strongly encouraged to set this flag to \const{true} and report issues this may cause. \prologflagitem{print_write_options}{term}{rw} Specifies the options for \index{write_term/2}\predref{write_term}{2} used by \index{print/1}\predref{print}{1} and \index{print/2}\predref{print}{2}. \prologflagitem{prompt_alternatives_on}{atom}{rw} \index{prompt, alternatives}% Determines prompting for alternatives in the Prolog top level. Default is \const{determinism}, which implies the system prompts for alternatives if the goal succeeded while leaving choice points. Many classical Prolog systems behave as \const{groundness}: they prompt for alternatives if and only if the query contains variables. \prologflagitem{protect_static_code}{bool}{rw} If \const{true} (default \const{false}), \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{rational_syntax}{atom}{rw} Determines the read and write syntax for rational numbers. Possible values are \const{natural} (e.g., \exam{1/3}) or \const{compatibility} (e.g., \exam{1r3}). The \const{compatibility} syntax is always accepted. This flag is module sensitive. The default for this flag is currently \const{compatibility}, which reads and writes rational numbers as e.g., \exam{1r3}.\footnote{There is still some discussion on the separating character. See \secref{syntax-rational-numbers}.} We will consider \const{natural} as a default in the future. Users are strongly encouraged to set this flag to \const{natural} and report issues this may cause. \prologflagitem{readline}{atom}{rw} Specifies which form of command line editing is provided. Possible values are below. The flag may be set from the user's init file (see \secref{initgoal}) to one of \const{false}, \const{readline} or \const{editline}. This causes the toplevel not to load a command line editor (\const{false}) or load the specified one. If loading fails the flag is set to \const{false}. \begin{description} \termitem{false}{} No command line editing is available. \termitem{readline}{} The library \pllib{readline} is loaded, providing line editing based on the GNU readline library. \termitem{editline}{} The library \pllib{editline} is loaded, providing line editing based on the BSD libedit. This is the default if \pllib{editline} is available and can be loaded. \termitem{swipl_win}{} SWI-Prolog uses its own console (\program{swipl-win.exe} on Windows, the Qt based \program{swipl-win} on MacOS) which provides line editing. \end{description} \prologflagitem{report_error}{bool}{rw} If \const{true}, print error messages; otherwise suppress them. May be changed. See also the \prologflag{debug_on_error} Prolog flag. Default is \const{true}, except for the runtime version. \prologflagitem{resource_database}{atom}{r} Set to the absolute filename of the attached state. Typically this is the file \file{boot32.prc}, the file specified with \cmdlineoption{-x} or the running executable. See also \index{resource/3}\predref{resource}{3}. \prologflagitem{runtime}{bool}{r} If present and \const{true}, SWI-Prolog is compiled with -DO_RUNTIME, disabling various useful development features (currently the tracer and profiler). \prologflagitem{sandboxed_load}{bool}{rw} If \const{true} (default \const{false}), \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_home}{atom}{r} Indicates that part of the SWI-Prolog system files are installed in \metafile{\bnfmeta{prefix}/share/swipl} instead of in the home at the \metafile{\bnfmeta{prefix}/lib/swipl}. This flag indicates the location of this \emph{shared home} and the directory is added to the file search path \const{swi}. See \index{file_search_path/2}\predref{file_search_path}{2} and the flag \prologflag{home}. \prologflagitem{shared_object_extension}{atom}{r} Extension used by the operating system for shared objects. \fileext{so} for most Unix systems and \fileext{dll} for Windows. Used for locating files using the \const{file_type} \const{executable}. See also \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{shared_table_space}{integer}{rw} Space reserved for storing shared answer tables. See \secref{tabling-shared} and the Prolog flag \prologflag{table_space}. \prologflagitem{shift_check}{bool}{rw} When \const{true} (default \const{false}), check for suspicious delimited continuations captured by \index{shift_for_copy/1}\predref{shift_for_copy}{1}. \prologflagitem{signals}{bool}{r} Determine whether Prolog is handling signals (software interrupts). This flag is \const{false} if the hosting OS does not support signal handling or the command line option \cmdlineoption{--no-signals} is active. See \secref{sigembedded} for details. \prologflagitem{stack_limit}{int}{rw} Limits the combined sizes of the Prolog stacks for the current thread. See also \cmdlineoption{--stack-limit} and \secref{memlimit}. \prologflagitem{stream_type_check}{atom}{rw} Defines whether and how strictly the system validates that byte I/O should not be applied to text streams and text I/O should not be applied to binary streams. Values are \const{false} (no checking), \const{true} (full checking) and \const{loose}. Using checking mode \const{loose} (default), the system accepts byte I/O from text stream that use ISO Latin-1 encoding and accepts writing text to binary streams. \prologflagitem{string_stack_tripwire}{int}{rw} Maintenance for foreign language string management. Prints a warning if the string stack depth hits the tripwire value. See \secref{foreign-strings} for details. \prologflagitem{system_thread_id}{int}{r} Available in multithreaded version (see \secref{threads}) where the operating system provides system-wide integer thread identifiers. The integer is the thread identifier used by the operating system for the calling thread. On Linux systems this is the PID of the thread. \prologflagitem{table_incremental}{bool}{rw} Set the default for whether to use incremental tabling or not. Initially set to \const{false}. See \index{table/1}\predref{table}{1}. \prologflagitem{table_shared}{bool}{rw} Set the default for whether to use shared tabling or not. Initially set to \const{false}. See \index{table/1}\predref{table}{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{table_subsumptive}{bool}{rw} Set the default choice between \jargon{variant} tabling and \jargon{subsumptive} tabling. Initially set to \const{false}. See \index{table/1}\predref{table}{1}. \prologflagitem{threads}{bool}{rw} True when threads are supported. If the system is compiled without thread support the value is \const{false} and read-only. Otherwise the value is \const{true} unless the system was started with the \cmdlineoption{--no-threads}. Threading may be disabled only if no threads are running. See also the \prologflag{gc_thread} flag. \prologflagitem{timezone}{integer}{r} Offset in seconds west of GMT of the current time zone. Set at initialization time from the \const{timezone} variable associated with the POSIX tzset() function. See also \index{format_time/3}\predref{format_time}{3}. \prologflagitem{tmp_dir}{atom}{rw} Path to the temporary directory. initialised from the environment variable \const{TMP} or \const{TEMP} in windows. If this variable is not defined a default is used. This default is typically \file{/tmp} or \file{c:/temp} in windows. \prologflagitem{toplevel_goal}{term}{rw} Defines the goal that is executed after running the initialization goals and entry point (see \cmdlineoption{-g}, \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 equivalent to \const{default}. If \term{initialization}{Goal,main} is used and the toplevel is \const{default}, the toplevel is set to \const{halt} (see \index{halt/0}\predref{halt}{0}). \prologflagitem{toplevel_list_wfs_residual_program}{bool}{rw} If \const{true} (default) and the answer is \jargon{undefined} according to the Well Founded Semantics (see \secref{WFS}), list the \jargon{residual program} before the answer. Otherwise the answer terminated with \textbf{undefined}. See also \index{undefined/0}\predref{undefined}{0}. \prologflagitem{toplevel_mode}{atom}{rw} If \const{backtracking} (default), the toplevel backtracks after completing a query. If \const{recursive}, the toplevel is implemented as a recursive loop. This implies that global variables set using \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_name_variables}{bool}{rw} If \const{true} (default), give names to variables at the toplevel instead of printing them as \arg{_NNN}. The variables are named \arg{_A}, \arg{_B}, ... Variables that appear only once (singletons) are printed as \arg{_}. \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{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_residue_vars}{bool}{rw} When \const{true} (default \const{false}), print residual variables as detected by \index{call_residue_vars/2}\predref{call_residue_vars}{2} that do not appear in the bindings returned by the goal. \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. When 0 (zero), the variable recording and reuse is disabled. 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_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{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{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{vmi_builtin}{bool}{rw} Determines whether well known built-ins such as \index{true/0}\predref{true}{0} or \index{atom/1}\predref{atom}{1} are handled by their translation into virtual machine code. The default for this flag is \const{true}, unless debug mode is enabled. Setting this flag to \const{false} may improve other runtime instrumentation results. Note that optimized arithmetic (\cmdlineoption{-O}, see Prolog flag \prologflag{optimise}) is currently not translated into a normal predicate call. \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{wine_version}{atom}{r} If present, SWI-Prolog is the MS-Windows version running under the \href{https://www.winehq.org/}{Wine} emulator. \prologflagitem{write_attributes}{atom}{rw} Defines how \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/2}\predref{write_term}{2}. 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 it calls 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. A more controlled form of autoloading as well as lazy loading application modules is provided by \index{autoload/[1,2]}\predref{autoload}{[1,2]}. 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 ~/${XDG_DATA_HOME-.config}/swi-prolog/lib % cd ~/${XDG_DATA_HOME-.config}/swi-prolog/lib % swipl -g 'make_library_index(.)' -t halt \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} :- prolog_load_context(directory, Dir), make_library_index(Dir, [ '*.pl', 'trace/browse.pl', 'swi/*.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 necessary to load all predicates that would normally be autoloaded explicitly. This is discussed in \secref{runtime}. See \index{autoload_all/0}\predref{autoload_all}{0}. \section{Packs: community add-ons} \label{sec:packs} SWI-Prolog has a mechanism for easy incorporation of community extensions. See the \href{http://www.swi-prolog.org/pack/list}{pack landing page} for details and available packs. This section documents the built-in predicates to attach packs. Predicates for creating, registering and installing packs are provided by the library \pllib{prolog_pack}. \begin{description} \predicate{attach_packs}{0}{} Attaches all packs in subdirectories of directories that are accessible through the \jargon{file search path} (see \index{absolute_file_name/3}\predref{absolute_file_name}{3}) \const{pack}. The default for this search path is given below. See \index{file_search_path/2}\predref{file_search_path}{2} for the \const{app_data} search path. \begin{code} user:file_search_path(pack, app_data(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{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 by the ISO standard, but used to be common practice before. \escapeitem{e} Escape character (\textsc{ASCII} 27). Not ISO, but widely supported. \escapeitem{f} Form-feed character. \escapeitem{n} Next-line character. \escapeitem{r} Carriage-return only (i.e., go back to the start of the line). \escapeitem{s} Space character. Intended to allow writing \verb$0'\s$ to get the character code of the space character. Not ISO. \escapeitem{t} Horizontal tab character. \escapeitem{v} Vertical tab character (\textsc{ASCII} 11). \escapeitem{\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{Rational number syntax} \label{sec:syntax-rational-numbers} As of version 8.1.22, SWI-Prolog supports rational numbers as a primary citizen atomic data type if SWI-Prolog is compiled with the GMP library. This can be tested using the \prologflag{bounded} Prolog flag. An atomic type also requires a syntax. Unfortunately there are few options for adding rational numbers without breaking the ISO standard.\footnote{ECLiPSe uses \arg{numerator}_\arg{denominator}. This syntax conflicts with SWI-Prolog digit groups (see \secref{digitgroupsyntax}) and does not have a recognised link to rational numbers. The notation \exam{1/3r} and \exam{1/3R} have also been proposed. The \exam{1/3r} is compatible to Ruby, but is hard to parse due to the required look-ahead and not very natural. See also \url{https://en.wikipedia.org/wiki/Rational_data_type}.} ECLiPSe and SWI-Prolog have agreed to define the canonical syntax for rational numbers to be e.g., \exam{1r3}. In addition, ECLiPSe accepts \exam{1_3} and SWI-Prolog can be asked to accept \exam{1/3} using the module sensitive Prolog flag \prologflag{rational_syntax}, which has the values below. Note that \index{write_canonical/1}\predref{write_canonical}{1} always uses the compatible \exam{1r3} syntax. \begin{description} \termitem{natural}{} This is the default mode where we ignore the ambiguity issue and follow the most natural \bnfmeta{integer}/\bnfmeta{nonneg} alternative. Here, \bnfmeta{integer} follows the normal rules for Prolog decimal integers and \bnfmeta{nonneg} does the same, but does not allows for a sign. Note that the parser translates a rational number to its canonical form which implies there are no common divisors in the resulting numerator and denominator. Examples of ration numbers are: \begin{tabular}{ll} 1/2 & 1/2 \\ 2/4 & 1/2 \\ 1 000 000/33 000 & 1000/33 \\ -3/5 & -3/5 \\ \end{tabular} We expect very few programs to have text parsed into a rational number while a term was expected. Note that for rationals appearing in an arithmetic expression the only difference is that evaluation moves from runtime to compiletime. The utility \index{list_rationals/0}\predref{list_rationals}{0} may be used on a loaded program to check whether the program contains rational numbers inside clauses and thus may be subject to compatibility issues. If a term is intended this can be written as \verb$/(1,2)$, \verb$(1)/2$, \verb$1 / 2$ or some variation thereof. \termitem{compatibility}{} Read and write rational numbers as e.g., \exam{1r3}. In other words, this adheres to the same rules as \const{natural} above, but using the `\chr{r}' instead of `\chr{\Sdiv}'. Note that this may conflict with traditional Prolog as `\const{r}' can be defined as an infix operator. The same argument holds for \exam{0x23} and similar syntax for numbers that are part of the ISO standard. \end{description} While the syntax is controlled by the flag \prologflag{rational_syntax}, behavior on integer division and exponentiation is controlled by the flag \prologflag{prefer_rationals}. See section \secref{rational} for arithmetic on rational numbers. \subsubsection{NaN and Infinity floats and their syntax} \label{sec:floatsyntax} SWI-Prolog supports reading and printing `special' floating point values according to \href{http://eclipseclp.org/Specs/core_update_float.html}{Proposal for Prolog Standard core update wrt floating point arithmetic} by Joachim Schimpf and available in ECLiPSe Prolog. In particular, \begin{itemize} \item Infinity is printed as \verb$1.0Inf$ or \verb$-1.0Inf$. Any sequence matching the regular expression \verb$[+-]?\sd+[.]\sd+Inf$ is mapped to plus or minus infinity. \item \const{NaN} (Not a Number) is printed as \verb$1.xxxNaN$, where \textit{1.xxx} is the float after replacing the exponent by `1'. Such numbers are read, resulting in the same \const{NaN}. The \const{NaN} constant can also be produced using the function \funcref{nan}{0}, e.g., \begin{code} ?- A is nan. A = 1.5NaN. \end{code} \noindent \end{itemize} By default SWI-Prolog arithmetic (see \secref{arith}) follows the ISO standard with describes that floating point operations either produce a \jargon{normal} floating point number or raise an exception. \secref{ieee-float} describes the Prolog flags that can be used to support the IEEE special float values. The ability to create, read and write such values facilitates the exchange of data with languages that can represent the full range of IEEE doubles. \subsubsection{Force only underscore to introduce a variable} \label{sec:varprefix} According to the ISO standard and most Prolog systems, identifiers that start with an uppercase letter or an underscore are variables. In the past, \jargon{Prolog by BIM} provided an alternative syntax, where only the underscore (\chr{_}) introduces a variable. As of SWI-Prolog 7.3.27 SWI-Prolog supports this alternative syntax, controlled by the Prolog flag \prologflag{var_prefix}. As the \prologflag{character_escapes} flag, this flag is maintained per module, where the default is \const{false}, supporting standard syntax. Having only the underscore introduce a variable is particularly useful if code contains identifiers for case sensitive external languages. Examples are the RDF library where code frequently specifies property and class names\footnote{Samer Abdallah suggested this feature based on experience with non-Prolog users using the RDF library.} and the R interface for specifying functions or variables that start with an uppercase character. Lexical databases where part of the terms start with an uppercase letter is another category were the readability of the code improves using this option. \subsubsection{Unicode Prolog source} \label{sec:unicodesyntax} The ISO standard specifies the Prolog syntax in ASCII characters. As SWI-Prolog supports Unicode in source files we must extend the syntax. This section describes the implication for the source files, while writing international source files is described in \secref{intsrcfile}. The SWI-Prolog Unicode character classification is currently based on version 14.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 [Numbers] Decimal number characters (Nd) are accepted to form numbers, regardless of the Unicode block in which they appear. Currently this is supported for integers, rational numbers (see \secref{syntax-rational-numbers}) and floating point numbers. In any number, \emph{all} digits must come from the same block, i.e., if the nominator of a rational is uses Indian script, so must the demoninator. All special characters such as the sign, rational separator, floating point \chr{\Sdot}, and floating point exponent must use their usual ASCII character. \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. Quoted writing (e.g., \index{writeq/1}\predref{writeq}{1}) of an atom or string that contains one of these characters causes the atom or string to be quoted and the control or unassigned characters to be written using an escape sequence. See \secref{charescapes}. \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 deterministic choice can be made or there are no two clauses that have the same name/arity combination. \subsection{Future directions} \label{sec:indexfut} \begin{itemize} \item The `special cases' can be extended. This is notably attractive for static predicates with a relatively small number of clauses where a hash lookup is too costly. \item Create an efficient decision diagram for selecting between low numbers of static clauses. \item Implement a better judgements for selecting between deep and plain indexes. \end{itemize} \subsection{Indexing for body code} \label{sec:indexbody} The current SWI-Prolog versions only consider the head for generating clause indexing. This would make it impossible to examine a head argument and pass the argument in the body without copying the argument. Consider the two clauses below. Both have equal semantics under Prolog. The first version would loose clause indexing while the second creates a copy of the \funcref{f}{1} argument. Neither is desirable. \begin{code} p(X) :- X = f(I), integer(I), q(X). p(f(I)) :- integer(I), q(f(X)). \end{code} \noindent As of SWI-Prolog 8.3.21, unifications against head arguments that happen before anything else in the body are compiled special. Effectively, the term unified too is moved into the head (providing indexing) and places where this term is used simply use the corresponding argument. The explicit unification is removed. Decompilation (\index{clause/2}\predref{clause}{2}) reverses this process, but may not produce exactly the same term. The re-inserted unfications are ordered according to the argument position and the variable is always on the left hand of the \predref{\Seq}{2}. Thus, \begin{code} p(X,Y) :- f(_) = Y, X = g(_), q(X,Y). \end{code} \noindent Is decompiled into the following equivalent clause. \begin{code} p(X,Y) :- X = g(_), Y = f(_), q(X,Y). \end{code} \noindent Additional notes: \begin{itemize} \item This transformation is only performed on \emph{static} code. \item The unifications must \emph{immediately} follow the head in a \jargon{conjunction}. \item As sole exception, calls to \index{true/0}\predref{true}{0} are skipped. This allows \index{goal_expansion/2}\predref{goal_expansion}{2} to convert goals to \const{true} while preserving this optimization. \item If the head argument is not used the body unification is still moved into the head. The decompiler does not inverse the process in that case. Thus, \exam{p(X) :- X = a.} is fully equivalent to \exam{p(a).} \item Currently this optimziation is enabled regardless of the Prolog flag \prologflag{optimise}. As this optimization harms source-level debugging, this may not be desirable. On the other hand we do not want determinism to depend on optimization while this optimization affects determinism. \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{UTF-16}\index{Unicode}\index{UCS}\index{internationalization}% SWI-Prolog represents characters using \href{https://home.unicode.org}{Unicode}. Unicode defines \jargon{code points} in the range $0\ldots{}0x10FFFF$. These code points represent virtually any character in any language. In addition, the Unicode standard defines character classes (letter, digit, punctuation, etc.), case conversion and much more. Unicode is a super set of ISO 8859-1 (ISO Latin-1), which is a superset of US-ASCII. SWI-Prolog has two representations for atoms and string objects (see \secref{string}). 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 \ctype{wchar_t} characters. On virtually all systems except for MS-Windows, \ctype{wchar_t} is a 32-bit unsigned integer and thus capable of representing all Unicode code points. On MS-Windows \ctype{wchar_t} is a 16-bit unsigned integer and thus only capable of representing the code points $0\ldots{}0xFFFF$. As of SWI-Prolog version 8.5.14, the \ctype{wchar_t} is (on Windows) interpreted as a UTF-16 string. The UTF-16 encoding uses \jargon{surrogate pairs} to represent the code points $0x10000\ldots{}0x10FFFF$ as two \jargon{code units} in the $0xD800\ldots{}0xDFFF$. As Unicode \jargon{code points}, this range is \jargon{unassigned}. For consistency, SWI-Prolog does not accept integers in the surrogate pair range as valid code points, e.g. \begin{code} ?- char_code(X, 0xD800). ERROR: Type error: `character_code' expected, found `55296' (an integer) \end{code} \noindent The internal character representation 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 Unicode standard internally, streams and files are byte (8-bit) oriented and there are a variety of ways to represent the larger Unicode 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 Unicode space. Especially on MS-Windows the 16-bit UTF-16 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 \exam{setlocale(LC_CTYPE, NULL)} to one of \const{text}, \const{utf8} or \const{iso_latin_1}. One of the latter two is used if the encoding name is recognized, while \const{text} is used as default. Using \const{text}, the translation is left to the wide-character functions of the C library.\footnote{The Prolog native UTF-8 mode is considerably faster than the generic mbrtowc() one.} The encoding can be specified explicitly in \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. The above is the SWI-Prolog native name. This encoding may be specified using the official \href{https://www.iana.org}{IANA} name \const{ISO-8859-1}. \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 encodings, 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 Unicode, compatible with \const{ascii}. See above. The above is the SWI-Prolog native name. This encoding may be specified using the official \href{https://www.iana.org}{IANA} name \const{UTF-8}. \termitem{utf16be}{} \nodescription \termitem{utf16le}{} UTF-16 encoding. Reads input in pairs of bytes. \const{utf16be} is \jargon{Big Endian}, putting the most significant byte first and \const{utf16le} is \jargon{Little Endian}, putting the most significant byte second. UTF-16 can represent full Unicode using \jargon{surrogate pairs}. The above are the SWI-Prolog native names. These encodings may be specified using the official \href{https://www.iana.org}{IANA} names \const{UTF-16BE} and \const{UTF-16LE}. For backward compatibility we also support \const{unicode_be} and \const{unicode_le}. \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}{|l|p{5cm}|} \hline Area name & Description \\ \hline \bf local stack & The local stack is used to store the execution environments of procedure invocations. The space for an environment is reclaimed when it fails, exits without leaving choice points, the alternatives are cut off with the !/0 predicate or no choice points have been created since the invocation and the last subclause is started (last call optimisation). \\ \bf global stack & The global stack is used to store terms created during Prolog's execution. Terms on this stack will be reclaimed by backtracking to a point before the term was created or by garbage collection (provided the term is no longer referenced). \\ \bf trail stack & The trail stack is used to store assignments during execution. Entries on this stack remain alive until backtracking before the point of creation or the garbage collector determines they are no longer needed. As the trail and global stacks are garbage collected together, a small trail can cause an excessive amount of garbage collections. To avoid this, the trail is automatically resized to be at least 1/6th of the size of the global stack. \\ \hline \end{tabular} \end{center} \caption{Memory areas} \label{tab:areas} \end{table} \subsubsection{The heap} \label{sec:heap} \index{stack,memory management}% \index{memory,layout}% With the heap, we refer to the memory area used by malloc() and friends. SWI-Prolog uses the area to store atoms, functors, predicates and their clauses, records and other dynamic data. No limits are imposed on the addresses returned by malloc() and friends. \subsection{Other Limits} \label{sec:morelimits} \begin{description} \item[Clauses] The only limit on clauses is their arity (the number of arguments to the head), which is limited to 1024. Raising this limit is easy and relatively cheap; removing it is harder. \item[Atoms and Strings] SWI-Prolog has no limits on the length of atoms and strings. The number of atoms is limited to 16777216 (16M) on 32-bit machines. On 64-bit machines this is virtually unlimited. See also \secref{atomgc}. \item[Memory areas] On 32-bit hardware, SWI-Prolog data is packed in a 32-bit word, which contains both type and value information. The size of the various memory areas is limited to 128~MB for each of the areas, except for the program heap, which is not limited. On 64-bit hardware there are no meaningful limits. \item[Nesting of terms] Most built-in predicates that process Prolog terms create an explicitly managed stack and perform optimization for processing the last argument of a term. This implies they can process deeply nested terms at constant and low usage of the C stack, and the system raises a resource error if no more stack can be allocated. Currently only \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} \section{Binary compatibility} \label{sec:abi-versions} \index{compatibility,binary}% \index{ABI,compatibility}% SWI-Prolog first of all attempts to maintain \jargon{source code} compatibility between versions. Data and programs can often be represented in binary form. This touches a number of interfaces with varying degrees of compatibility. The relevant version numbers and signatures are made available by \cfuncref{PL_version_info}{}, the \cmdlineoption{--abi-version} and the Prolog flag \prologflag{abi_version}. \begin{description} \definition{Foreign extensions} Dynamically loadable foreign extensions have the usual dependencies on the architecture, ABI model of the (C) compiler, dynamic link library format, etc. They also depend on the backward compatibility of the PL_* API functions provided lib \file{libswipl}. A compatible API allows distribution of foreign extensions in binary form, notably for platforms on which compilation is complicated (e.g., Windows). This compatibility is therefore high on the priority list, but must infrequently be compromised. \cfuncref{PL_version_info}{}: \const{PL_VERSION_FLI}, \prologflag{abi_version} key: \const{foreign_interface} \definition{Binary terms} Terms may be represented in binary format using \cfuncref{PL_record_external}{} and \index{fast_write/2}\predref{fast_write}{2}. As these formats are used for storing binary terms in databases or communicate terms between Prolog processes in binary form, great care is taken to maintain compatibility. \cfuncref{PL_version_info}{}: \const{PL_VERSION_REC}, \prologflag{abi_version} key: \const{record} \definition{QLF files} QLF files (see \index{qcompile/1}\predref{qcompile}{1}) are binary representation of Prolog file or module. They represent clauses as sequences of \jargon{virtual machine} (VM) instructions. Their compatibility relies on the QLF file format and the ABI of the VM. Some care is taken to maintain compatibility. \cfuncref{PL_version_info}{}: \const{PL_VERSION_QLF}, \const{PL_VERSION_QLF_LOAD} and \const{PL_VERSION_VM}, \prologflag{abi_version} key: \const{qlf}, \const{qlf_min_load}, \const{vmi} \definition{Saved states} Saved states (see \cmdlineoption{-c} and \index{qsave_program/2}\predref{qsave_program}{2}) is a zip file that contains the entire Prolog database using the same representation as QLF files. A saved state may contain additional resources, such as foreign extensions, data files, etc. In addition to the dependency concerns of QLF files, built-in and core library predicates may call \emph{internal} foreign predicates. The interface between the public built-ins and internal foreign predicates changes frequently. Patch level releases in the \emph{stable branch} will as much as possible maintain compatibility. The relevant ABI version keys are the same as for QLF files with one addition: \cfuncref{PL_version_info}{}: \const{PL_VERSION_BUILT_IN}, \prologflag{abi_version} key: \const{built_in} \end{description}