\newpage
\section{Using GNU Prolog}
%HEVEA\cutdef[1]{subsection}
\subsection{Introduction}
\label{Introduction:(Using-GNU-Prolog)}
GNU Prolog offers two ways to execute a Prolog program:

\begin{itemize}

\item interpreting it using the GNU Prolog interactive interpreter.

\item compiling it to a (machine-dependent) executable using the GNU Prolog
native-code compiler.

\end{itemize}

Running a program under the interactive interpreter allows the user to
list it and to make full use of the debugger on it \RefSP{Debugging}.
Compiling a program to native code makes it possible to obtain a stand alone
executable, with a reduced size and optimized for speed. Running a Prolog
program compiled to native-code is around 3-5 times faster than running it
under the interpreter. However, it is not possible to make full use of
the debugger on a program compiled to native-code. Nor is it possible to list
the program. In general, it is preferable to run a program under the
interpreter for debugging and then use the native-code compiler to produce an
autonomous executable. It is also possible to combine these two modes by
producing an executable that contains some parts of the program (e.g.
already debugged predicates whose execution-time speed is crucial) and
interpreting the other parts under this executable. In that case, the
executable has the same facilities as the GNU Prolog interpreter but also
integrates the native-code predicates. This way to define a new enriched
interpreter is detailed later \RefSP{Generating-a-new-interactive-interpreter}.

\subsection{The GNU Prolog interactive interpreter}
\label{The-GNU-Prolog-interactive-interpreter}

\subsubsection{Starting/exiting the interactive interpreter}
\index{interpreter|see {top-level}}
GNU Prolog offers a classical Prolog interactive interpreter also called
\emph{top-level}. It allows the user to execute queries, to consult Prolog
programs, to list them, to execute them and to debug them. The
\IdxD{top-level} can be invoked using the following command:


\OneLineTwoCols[5.5cm]{\% gprolog \textrm{[}\Param{OPTION}\textrm{]\ldots}}{(the \texttt{\%} symbol is the operating system shell prompt)}

\SPart{Options}:

\begin{CmdOptions}
\IdxKD{--init-goal}  \Param{GOAL} & execute \Param{GOAL} before entering the top-level \\
\IdxKD{--consult-file} \Param{FILE} & consult \Param{FILE} inside the top-level \\
\IdxKD{--entry-goal} \Param{GOAL} & execute \Param{GOAL} inside the top-level \\
\IdxKD{--query-goal} \Param{GOAL} & execute \Param{GOAL} as a query for the top-level \\

\IdxKD{--help} & print a help and exit \\

\IdxKD{--version} & print version number and exit \\

\IdxKD{--} & do not parse the rest of the command-line \\

\end{CmdOptions}

The main role of the \texttt{gprolog} command is to execute the top-level
itself, i.e. to execute the built-in predicate
\IdxPB{top\_level/0} \RefSP{abort/0} which will produce something like:

\begin{Code}
\begin{verbatim}
GNU Prolog 1.5.0 (64 bits)
Compiled May  3 2021, 16:36:43 with gcc
Copyright (C) 1999-2021 Daniel Diaz

| ?- 
\end{verbatim}
\end{Code}

The top-level is ready to execute your queries as explained in the next
section.

To quit the top-level type the end-of-file key sequence (\texttt{Ctl-D}) or
its term representation: \texttt{end\_of\_file.} It is also possible to use
the built-in predicate \IdxPB{halt/0} \RefSP{abort/0}.

However, before entering the top-level itself, the command-line is processed
to treat all known options (those listed above). All unrecognized arguments
are collected together to form the argument list which will be available
using
\IdxPB{argument\_value/2} \RefSP{argument-value/2} or
\IdxPB{argument\_list/1} \RefSP{argument-list/1}.
The \texttt{--} option stops the parsing of the command-line, all remainding
options are collected into the argument list.

Several options are provided to execute a goal before entering the
interaction with the user:

\begin{itemize}

\item The \texttt{--init-goal} option executes the \Param{GOAL} as soon as
it is encountered (while the command-line is processed). \Param{GOAL} is thus
executed before entering \texttt{top\_level/0}.

\item The \texttt{--consult-file} option consults the \Param{FILE} at the
entry of \texttt{top\_level/0} just after the banner is displayed. 
\texttt{--consult-file} options are handled before \texttt{--consult-file} options.

\item The \texttt{--entry-goal} option executes the \Param{GOAL} at the
entry of \texttt{top\_level/0} just after the banner is displayed.

\item The \texttt{--query-goal} option executes the \Param{GOAL} as if the
user has typed in (under the top-level).

\end{itemize}

The above order is thus the order in which each kind of goal (init, entry,
query) is executed.  If there are several goals of a same kind they are
executed in the order of appearance. Thus, all init goals are executed (in the
order of appearance) before all entry goals and all entry goals are executed
before all query goals.

Each \Param{GOAL} is passed as a shell argument (i.e. one shell string) and
should not contain a terminal dot. Example: \texttt{--init-goal
  'write(hello), nl'} under a sh-like.  To be executed, a \Param{GOAL} is
transformed into a term using
\AddPB{read\_term\_from\_atom/3}\texttt{read\_term\_from\_atom(Goal, Term,
  [end\_of\_term(eof)])}. Respecting both the syntax of shell strings and of
Prolog can be heavy. For instance, passing a backslash character
\texttt{{\bs}} can be difficult since it introduces an \Idx{escape sequence}
both in sh and inside Prolog quoted atoms. The use of back quotes can then be
useful since, by default, no escape sequence is processed inside back quotes
(this behavior can be controlled using the \IdxPF{back\_quotes} \Idx{Prolog
  flag} \RefSP{set-prolog-flag/2}).


Since the Prolog argument list is created when the whole command-line is
parsed, if a \texttt{--init-goal} option uses \texttt{argument\_value/2} or
\texttt{argument\_list/1} it will obtained the original command-line
arguments (i.e. including all recognized arguments).

Here is an example of using execution goal options:

\begin{Code}
\% gprolog --init-goal 'write(before), nl' --entry-goal 'write(inside), nl'\\
--query-goal 'append([a,b],[c,d],X)'
\end{Code}

will produce the following:

\begin{Code}
\begin{verbatim}
before
GNU Prolog 1.5.0 (64 bits)
Compiled May  3 2021, 16:36:43 with gcc
Copyright (C) 1999-2021 Daniel Diaz

inside
| ?- append([a,b],[c,d],X).

X = [a,b,c,d]

yes
| ?-
\end{verbatim}
\end{Code}

NB: depending on the used shell it may be necessary to use other string
delimiters (e.g. use \texttt{"} under Windows \texttt{cmd.exe}).

\subsubsection{The interactive interpreter read-execute-write loop}
The GNU Prolog top-level is built on a classical read-execute-write loop that
also allows for re-executions (when the query is not deterministic) as
follows:

\begin{itemize}

\item display the prompt, i.e. '\texttt{| ?-}'.

\item read a query (i.e. a goal).

\item execute the query.

\item in case of success display the values of the variables of the query.

\item if there are remaining alternatives (i.e. the query is not
deterministic), display a \texttt{?} and ask the user who can use one of the
following commands: \texttt{RETURN} to stop the execution, \texttt{;} to
compute the next solution or \texttt{a} to compute all remaining solution.

\end{itemize}

Here is an example of execution of a query (``find the lists \texttt{X} and
\texttt{Y} such that the concatenation of \texttt{X} and \texttt{Y} is
\texttt{[a,b]}''):

\begin{CodeTwoCols}
\One{| ?- append(X,Y,[a,b,c]).}
\SkipLine
\One{X = []}
\Two{Y = [a,b,c] ? ;}{(here the user presses \texttt{;} to compute another
solution)}
\SkipLine
\One{X = [a]}
\Two{Y = [b,c] ? a}{(here the user presses \texttt{a} to compute all remaining
solutions)}
\SkipLine
\One{X = [a,b]}
\Two{Y = [c]}    {(here the user is not asked and the next solution is
computed)}
\SkipLine
\One{X = [a,b,c]}
\Two{Y = []}     {(here the user is not asked and the next solution is
computed)}
\SkipLine
\Two{no}{(no more solution)}
\end{CodeTwoCols}

In some cases the top-level can detect that the current solution is the last
one (no more alternatives remaining). In such a case it does not display the
\texttt{?} symbol (and does not ask the user). Example:

\begin{CodeTwoCols}
\One{| ?- (X=1 ; X=2).}
\SkipLine
\Two{X = 1 ? ;}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 2}  {(here the user is not prompted since there are no more
alternatives)}
\SkipLine
\One{yes}
\end{CodeTwoCols}

The user can stop the execution even if there are more alternatives by
typing \texttt{RETURN}.

\begin{CodeTwoCols}
\One{| ?- (X=1 ; X=2).}
\SkipLine
\Two{X = 1 ?} {(here the user presses \texttt{RETURN} to stop the execution)}
\SkipLine
\One{yes}
\end{CodeTwoCols}

The top-level tries to display the values of the variables of the query in a
readable manner. For instance, when a variable is bound to a query variable,
the name of this variable appears. When a variable is a singleton an
underscore symbol \texttt{\_} is displayed (\texttt{\_} is a generic name
for a singleton variable, it is also called an anonymous variable). Other
variables are bound to new brand variable names. When a query variable name
\texttt{X} appears as the value of another query variable \texttt{Y} it is
because \texttt{X} is itself not instantiated otherwise the value of
\texttt{X} is displayed. In such a case, nothing is output for \texttt{X}
itself (since it is a variable). Example:

\begin{CodeTwoCols}
\One{| ?- X=f(A,B,\_,A), A=k.}
\SkipLine
\Two{A = k} {(the value of \texttt{A} is displayed also in \texttt{f/3} for
\texttt{X})}
\Two{X = f(k,B,\_,k)} {(since \texttt{B} is a variable which is also a part
of \texttt{X}, \texttt{B} is not displayed)}
\end{CodeTwoCols}

\begin{CodeTwoCols}
\One{| ?- functor(T,f,3), arg(1,T,X), arg(3,T,X).}
\SkipLine
\Two{T = f(X,\_,X)} {(the 1$^{st}$ and 3$^{rd}$ args are equal to \texttt{X},
the 2$^{nd}$ is an anonymous variable)}
\end{CodeTwoCols}

\begin{CodeTwoCols}
\One{| ?- read\_from\_atom('k(X,Y,X).',T).}
\SkipLine
\Two{T = k(A,\_,A)} {(the 1$^{st}$ and 3$^{rd}$ args are unified, a new
variable name \texttt{A} is introduced)}
\end{CodeTwoCols}

The top-level uses variable binding predicates \RefSP{Variable-naming/numbering}. To display the value of a variable, the top-level calls
\IdxPB{write\_term/3} with the following option list:
\texttt{[\AddPO{quoted}\texttt{quoted(true)},\AddPO{numbervars}\texttt{numbervars(false)},
\AddPO{namevars}\texttt{namevars(true)}]} \RefSP{write-term/3}. A term of the
form \texttt{'\$VARNAME'(Name)} where \texttt{Name} is an atom is displayed
as a variable name while a term of the form \texttt{'\$VAR'(N)} where
\texttt{N} is an integer is displayed as a normal compound term (such a term
could be output as a variable name by \texttt{write\_term/3}). Example:

\begin{CodeTwoCols}
\One{| ?- X='\$VARNAME'('Y'), Y='\$VAR'(1).}
\SkipLine
\Two{X = Y} {(the term \texttt{'\$VARNAME'('Y')} is displayed as \texttt{Y})}
\Two{Y = '\$VAR'(1)} {(the term \texttt{'\$VAR'(1)} is displayed as is)}
\end{CodeTwoCols}

\begin{CodeTwoCols}
\One{| ?- X=Y, Y='\$VAR'(1).}
\SkipLine
\One{X = '\$VAR'(1)}
\One{Y = '\$VAR'(1)}
\end{CodeTwoCols}

In the first example, \texttt{X} is explicitly bound to
\texttt{'\$VARNAME'('Y')} by the query so the top-level displays \texttt{Y}
as the value of \texttt{X}. \texttt{Y} is unified with \texttt{'\$VAR'(1)} so
the top-level displays it as a normal compound term. It should be clear that
\texttt{X} is not bound to \texttt{Y} (whereas it is in the second
query). This behavior should be kept in mind when doing variable binding
operations.

Finally, the top-level computes the user-time \RefSP{user-time/1} taken
by a query and displays it when it is significant. Example:

\begin{CodeTwoCols}
\One{| ?- retractall(p(\_)), assertz(p(0)),}
\One{~~~~~repeat,}
\One{~~~~~~~~retract(p(X)),}
\One{~~~~~~~~Y is X + 1,}
\One{~~~~~~~~assertz(p(Y)),}
\One{~~~~~~~~X = 1000, !.}
\SkipLine
\One{X = 1000}
\One{Y = 1001}
\SkipLine
\Two{(180 ms) yes}{(the query took 180ms of user time)}
\end{CodeTwoCols}

\subsubsection{Consulting a Prolog program}
\label{Consulting-a-Prolog-program}
The top-level allows the user to consult Prolog source files. Consulted
predicates can be listed, executed and debugged (while predicates compiled
to native-code cannot). For more information about the difference between a
native-code predicate and a consulted predicate refer to the introduction of
this section \RefSP{Introduction:(Using-GNU-Prolog)} and to the part devoted
to the compiler \RefSP{Different-kinds-of-codes}.

To consult a program use the built-in predicate \IdxPB{consult/1}
\RefSP{consult/1}. The argument of this predicate is a Prolog file name or
\texttt{user} to specify the terminal. This allows the user to directly input
the predicates from the terminal. In that case the input shall be terminated
by the end-of-file key sequence (\texttt{Ctl-D}) or its term representation:
\texttt{end\_of\_file.} A shorthand for
\texttt{consult(}\Param{FILE}\texttt{)} is
\texttt{[}\Param{FILE}\texttt{]}. Example:

\begin{CodeTwoCols}
\One{| ?- [user].}
\One{{\lb}compiling user for byte code...{\rb}}
\One{even(0).}
\One{even(s(s(X))):-}
\One{~~~~~~~~even(X).}
\Two{}{(here the user presses \texttt{Ctl-D} to end the input)}
\One{{\lb}user compiled, 3 lines read - 350 bytes written, 1180 ms{\rb}}
\SkipLine
\One{| ?- even(X).}
\SkipLine
\Two{X = 0 ? ;}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = s(s(0)) ? ;}{(here the user presses \texttt{;} to compute another
solution)}
\SkipLine
\Two{X = s(s(s(s(0)))) ?}{(here the user presses \texttt{RETURN} to stop the
execution)}
\SkipLine
\One{yes}
\One{| ?- listing.}
\SkipLine
\One{even(0).}
\One{even(s(s(A))) :-}
\One{~~~~~~~~even(A).}
\end{CodeTwoCols}

When \IdxPB{consult/1} \RefSP{consult/1} is invoked on a Prolog file it
first runs the GNU Prolog compiler \RefSP{The-GNU-Prolog-compiler} as a child
process to generate a temporary WAM file for byte-code. If the compilation
fails a message is displayed and nothing is loaded. If the compilation
succeeds, the produced file is loaded into memory using \IdxPB{load/1}
\RefSP{load/1}. Namely, the byte-code of each predicate is loaded. When a
predicate \Param{P} is loaded if there is a previous definition
for \Param{P} it is removed (i.e. all clauses defining
\Param{P} are erased). We say that \Param{P} is
redefined. Note that only consulted predicates can be redefined. If
\Param{P} is a native-code predicate, trying to redefine it will
produce an error at load-time: the predicate redefinition will be ignored
and the following message displayed:

\OneLine{native code procedure \Param{P} cannot be redefined}

Finally, an existing predicate will not be removed if it is not re-loaded.
This means that if a predicate \Param{P} is loaded when consulting
the file \Param{F}, and if later the definition of
\Param{P} is removed from the file \Param{F}, consulting
\Param{F} again will not remove the previously loaded definition
of \Param{P} from the memory.

Consulted predicates can be debugged using the Prolog debugger. Use the
debugger predicate \IdxDB{trace/0} or \IdxDB{debug/0} \RefSP{Running-and-stopping-the-debugger} to activate the debugger.


\subsubsection{Scripting Prolog}
\label{Scripting-Prolog}
Since version 1.4.0 it is possible to use a Prolog source file as a Unix
script-file (\IdxD{shebang support}). A \IdxD{PrologScript} file should begin as follows:

\begin{Code}
\begin{verbatim}
#!/usr/bin/gprolog --consult-file
\end{verbatim}
\end{Code}

GNU Prolog will be invoked as

\begin{Code}
\begin{verbatim}
/usr/bin/gprolog --consult-file FILE
\end{verbatim}
\end{Code}

Then \texttt{FILE} will be consulted. In order to correctly deal with the
\texttt{\#!} first line, \texttt{consult/1} treats as a comment a first line
of a file which begins with \texttt{\#} (if you want to use a predicate name
starting with a \texttt{\#}, simply skip a line before its definition).


Remark: it is almost never possible to pass additionnal parameters
(e.g. \texttt{query-goal}) this way since in most systems 
the shebang implementation deliver all arguments (following
\texttt{\#!/usr/bin/gprolog}) as a single string (which cannot then correctly
be recognized by \texttt{gprolog}).

\subsubsection{Interrupting a query}
\label{Interrupting-a-query}
Under the top-level it is possible to interrupt the execution of a query by
typing the interruption key (\texttt{Ctl-C}). This can be used to abort a
query, to stop an infinite loop, to activate the debugger,\ldots When an
interruption occurs the top-level displays the following message:
\texttt{Prolog interruption (h for help)~?} The user can then type one of
the following commands:

\begin{tabular}{|c|c|l|}
\hline

Command & Name & Description \\

\hline\hline

\texttt{a} & abort & abort the current execution. Same as \IdxPB{abort/0}
\RefSP{abort/0} \\

\hline

\texttt{e} & exit & quit the current Prolog process.
Same as \IdxPB{halt/0} \RefSP{abort/0} \\

\hline

\texttt{b} & break & invoke a recursive top-level. Same as \IdxPB{break/0}
\RefSP{abort/0} \\

\hline

\texttt{c} & continue & resume the execution \\

\hline

\texttt{t} & trace & start the debugger using \IdxDB{trace/0}
\RefSP{Running-and-stopping-the-debugger} \\

\hline

\texttt{d} & debug & start the debugger using \IdxDB{debug/0}
\RefSP{Running-and-stopping-the-debugger} \\

\hline

\texttt{h} or \texttt{?} & help & display a summary of available commands \\

\hline
\end{tabular}

\subsubsection{The line editor}
\label{The-line-editor}
The line editor (\IdxKD{linedit}) allows the user to build/update the current
input line using a variety of commands. This facility is available if the
\texttt{linedit} part of GNU Prolog has been installed. \texttt{linedit} is
implicitly called by any built-in predicate reading from a terminal (e.g.
\texttt{get\_char/1}, \texttt{read/1},\ldots). This is the case when the
\Idx{top-level} reads a query.

\SPart{Bindings}: each command of \texttt{linedit} is activated using a
key. For some commands another key is also available to invoke the command
(on some terminals this other key may not work properly while the primary
key always works). Here is the list of available commands:

\begin{tabular}{|c|c|l|}
\hline

Key & Alternate key & Description \\

\hline\hline

\texttt{Ctl-B} & \texttt{$\leftarrow$} & go to the previous character \\

\hline

\texttt{Ctl-F} & \texttt{$\rightarrow$} & go to the next character \\

\hline

\texttt{Esc-B} & \texttt{Ctl-$\leftarrow$} & go to the previous word \\

\hline

\texttt{Esc-F} & \texttt{Ctl-$\rightarrow$} & go to the next word \\

\hline

\texttt{Ctl-A} & \texttt{Home} & go to the beginning of the line \\

\hline

\texttt{Ctl-E} & \texttt{End} & go to the end of the line \\

\hline

\texttt{Ctl-H} & \texttt{Backspace} & delete the previous character \\

\hline

\texttt{Ctl-D} & \texttt{Delete} & delete the current character \\

\hline

\texttt{Ctl-U} & \texttt{Ctl-Home} & delete from beginning of the line to the current character  \\

\hline

\texttt{Ctl-K} & \texttt{Ctl-End} & delete from the current character to the end of the line \\

\hline

\texttt{Esc-L} & & lower case the next word \\

\hline

\texttt{Esc-U} & & upper case the next word \\

\hline

\texttt{Esc-C} & & capitalize the next word \\

\hline

\texttt{Ctl-T} & & exchange last two characters \\

\hline

\texttt{Ctl-V} & \texttt{Insert} & switch on/off the insert/replace mode \\

\hline

\texttt{Ctl-I} & \texttt{Tab} & complete word (twice displays all possible
completions) \\

\hline
\texttt{Esc-Ctl-I} & \texttt{Esc-Tab} & insert spaces to emulate a tabulation \\

\hline

\texttt{Ctl-space} & & mark beginning of the selection \\

\hline

\texttt{Esc-W} & & copy (from the begin selection mark to the current
character) \\

\hline

\texttt{Ctl-W} & & cut (from the begin selection mark to the current
character) \\

\hline

\texttt{Ctl-Y} & & paste \\

\hline

\texttt{Ctl-P} & \texttt{$\uparrow$} & recall previous history line \\

\hline

\texttt{Ctl-N} & \texttt{$\downarrow$} & recall next history line \\

\hline

\texttt{Esc-P} & & recall previous history line beginning with the current
prefix \\

\hline

\texttt{Esc-N} & & recall next history line beginning with the current
prefix \\

\hline

\texttt{Esc-{\lt}} & \texttt{Page Up} & recall first history line \\

\hline

\texttt{Esc-{\gt}} & \texttt{Page Down} & recall last history line \\

\hline

\texttt{Ctl-C} & & generate an interrupt signal \RefSP{Interrupting-a-query} \\

\hline

\texttt{Ctl-D} & & generate an end-of-file character (at the begin of the
line) \\

\hline

\texttt{RETURN} & & validate a line \\

\hline

\texttt{Esc-?} & & display a summary of available commands \\

\hline
\end{tabular}

\SPart{History}: when a line is entered (i.e. terminated by \texttt{RETURN}),
\texttt{linedit} records it in an internal list called
history. It is later possible to recall history lines using appropriate
commands (e.g. \texttt{Ctl-P} recall the last entered line) and to modify
them as needed. It is also possible to recall a history line beginning with
a given prefix. For instance to recall the previous line beginning with
\texttt{write} simply type \texttt{write} followed by \texttt{Esc-P}.
Another \texttt{Esc-P} will recall an earlier line beginning with
\texttt{write},\ldots

\SPart{Completion}: another important feature of \texttt{linedit} is its
\IdxD{completion} facility. Indeed, \texttt{linedit} maintains a list of
known words and uses it to complete the prefix of a word. Initially this list
contains all predefined atoms and the atoms corresponding to available
predicates. This list is dynamically updated when a new atom appears in the
system (whether read at the top-level, created with a built-in predicate,
associated with a new consulted predicate,\ldots). When the completion key
(\texttt{Tab}) is pressed \texttt{linedit} acts as follows:

\begin{itemize}

\item use the current word as a prefix.

\item collect all words of the list that begin with this prefix.

\item complete the current word with the longest common part of all matching
words.

\item if more than one word matches emit a beep (a second \texttt{Tab} will
display all possibilities).

\end{itemize}

Example:

\begin{CodeTwoCols}
\Two{| ?- argu} {(here the user presses \texttt{Tab} to complete the word)}
\Two{| ?- argument\_}{(\texttt{linedit} completes \texttt{argu} with
\texttt{argument\_} and emits a beep)}
\Two{}{(the user presses again \texttt{Tab} to see all possible completions)}
\Two{argument\_counter}{(\texttt{linedit} shows 3 possible completions)}
\One{argument\_list}
\One{argument\_value}
\Two{| ?- argument\_}{(\texttt{linedit} redisplays the input line)}
\SkipLine
\Two{| ?- argument\_c}{(to select \texttt{argument\_counter} the user presses
\texttt{c} and \texttt{Tab})}
\Two{| ?- argument\_counter}{(\texttt{linedit} completes with
\texttt{argument\_counter})}
\end{CodeTwoCols}

\SPart{Balancing}: \texttt{linedit} allows the user to check that (square/curly)
brackets are well balanced. For this, when a close bracket symbol, i.e.
\texttt{)}, \texttt{]} or \texttt{{\rb}}, is typed, \texttt{linedit} determines
the associated open bracket, i.e. \texttt{(}, \texttt{[} or \texttt{{\lb}}, and
temporarily repositions the cursor on it to show the match.


\SPart{Customization}: the behavior of \texttt{linedit} can be controlled via
an environment variable called \texttt{LINEDIT}. This variable can contain
the following substrings:

\begin{tabular}{ll}

\texttt{no}          & do not activated linedit (should the only value of the variable) \\
\texttt{ansi=no}     & do not use ANSI escape sequence (unix only) \\
\texttt{out=}$N$     & use the file descriptor $N$ for the output (unix only) \\
\texttt{gui=no}      & even if compiled with the \Idx{GUI console} run in text mode (windows) \\
\texttt{gui=silent}  & if the \Idx{GUI console} is not found, silently run in text mode (windows) \\
\texttt{cp=}$N$      & use code page $N$ (windows text console) \\
\texttt{oem\_put=no} & do not use Char$\rightarrow$Oem conversion when emitting a char (windows text console) \\
\texttt{oem\_get=no} & do not use Oem$\rightarrow$Char conversion when reading a char (windows text console) \\
\end{tabular}


\subsection{Adjusting the size of Prolog data}
\label{Adjusting-the-size-of-Prolog-stacks}
GNU Prolog uses several stacks to execute a Prolog program. Each stack has a
static size and cannot be dynamically increased during the execution. For
each stack there is a default size but the user can define a new size by
setting an environment variable. When a GNU Prolog program is run it first
consults these variables and if they are not defined uses the default sizes.
The following table presents each stack of GNU Prolog with its default size
and the name of its associated environment variable:

Since version 1.4.2, the size of the atom table (the table recording all atoms) 
is managed similarly to stacks. It is then included in the following table
(even if actually it is not a stack but an hash table).
In this table, the associated name is \texttt{atoms} which is the key used in statistics 
\RefSP{statistics/2}. The environment variable name is derived from the corresponding Prolog flag 
\texttt{max\_atom}, see \RefSP{set-prolog-flag/2}.


\begin{tabular}{|c|c|c|l|}
\hline

Stack & Default   & Environment & Description \\
name  & size (Kb) & variable    & \\

\hline\hline

\texttt{local} & 16384 & \texttt{LOCALSZ} & control stack (environments
and choice-points) \\

\hline

\texttt{global} & 32768 & \texttt{GLOBALSZ} & heap (compound terms) \\

\hline

\texttt{trail} & 16384 & \texttt{TRAILSZ} & conditional bindings (bindings
to undo at backtracking) \\

\hline

\texttt{cstr} & 16384 & \texttt{CSTRSZ} & finite domain constraint stack
(FD variables and constraints) \\

\hline

\texttt{atoms} & 32768 & \texttt{MAX\_ATOM} & atom table \\

\hline
\end{tabular}

In addition, under Windows (since version 1.4.0), registry keys are consulted
(key names are the same as environment names). The keys are stored in
\texttt{HKEY\_CURRENT\_USER{\bs}Software{\bs}GnuProlog{\bs}}.

If the size of a stack is too small an overflow will occur during the
execution. In that case GNU Prolog emits the following error message before
stopping:

\OneLine{\Param{S} stack overflow (size:~\Param{N} Kb, environment variable used:~\Param{E})}

where \Param{S} is the name of the stack, \Param{N} is
the current stack size in Kb and \Param{E} the name of the
associated environment variable. When such a message occurs it is possible
to (re)define the variable \Param{E} with the new size. For
instance to allocate  Kb to the local stack under a Unix shell use:

\begin{CodeTwoCols}[6cm]
\Two{LOCALSZ=32768; export LOCALSZ}{(under \texttt{sh} or \texttt{bash})}
\Two{setenv LOCALSZ 32768}{(under \texttt{csh} or \texttt{tcsh})}
\end{CodeTwoCols}

This method allows the user to adjust the size of Prolog stacks. However, in
some cases it is preferable not to allow the user to modify these sizes. For
instance, when providing a stand alone executable whose behavior should be
independent of the environment in which it is run. In that case the program
should not consult environment variables and the programmer should be able
to define new default stack sizes. The GNU Prolog compiler offers this
facilities via several command-line options such as \IdxK{--local-size} or
\IdxK{--fixed-sizes} \RefSP{Using-the-compiler}.

Finally note that GNU Prolog stacks are virtually allocated (i.e. use virtual
memory). This means that a physical memory page is allocated only when needed
(i.e. when an attempt to read/write it occurs). Thus it is possible to define
very large stacks. At the execution, only the needed amount of space will be
physically allocated.

\subsection{The GNU Prolog compiler}
\label{The-GNU-Prolog-compiler}

\subsubsection{Different kinds of codes}
\label{Different-kinds-of-codes}
One of the main advantages of GNU Prolog is its ability to produce stand
alone executables. A Prolog program can be compiled to native code to give
rise to a machine-dependent executable using the GNU Prolog compiler. However
native-code predicates cannot be listed nor fully debugged. So there is an
alternative to native-code compilation: byte-code compilation. By default the
GNU Prolog compiler produces native-code but via a command-line option it can
produce a file ready for byte-code loading. This is exactly what
\IdxPB{consult/1} does as was explained above \RefSP{Consulting-a-Prolog-program}. GNU Prolog also manages interpreted code using a Prolog interpreter
written in Prolog. Obviously interpreted code is slower than byte-code but
does not require the invocation of the GNU Prolog compiler. This interpreter is
used each time a meta-call is needed as by \texttt{call/1} \RefSP{call/1}.
This also the case of dynamically asserted clauses. The following table
summarizes these three kinds of codes:

\begin{tabular}{|l|l|c|l|}
\hline

Type & Speed & Debug ? & For what \\

\hline\hline

interpreted-code & slow & yes & meta-call and dynamically asserted clauses
\\

\hline

byte-code & medium & yes & consulted predicates \\

\hline

native-code & fast & no & compiled predicates \\

\hline
\end{tabular}

\subsubsection{Compilation scheme}
\label{Compilation-scheme}
\SPart{Native-code compilation}: a Prolog source is compiled in several
stages to produce an object file that is linked to the GNU Prolog libraries
to produce an executable. The Prolog source is first compiled to obtain a
\Idx{WAM} \cite{Warren83} file. For a detailed study of the WAM the
interested reader can refer to
\MyUrl{http://www.isg.sfu.ca/\~{}hak/documents/wam.html}{``Warren's Abstract
  Machine: A Tutorial Reconstruction''} \cite{Ait-Kaci91}. The WAM file is
translated to a machine-independent language specifically designed for GNU
Prolog. This language is close to a (universal) assembly language and is
based on a very reduced instruction set. For this reason this language is
called \IdxD{mini-assembly} (\IdxD{MA}). The mini-assembly file is then
mapped to the assembly language of the target machine. This assembly file is
assembled to give rise to an object file which is then linked with the GNU
Prolog libraries to provide an executable.  The compiler also takes into
account Finite Domain constraint definition files. It translates them to C
and invoke the C compiler to obtain object files. The following figure
presents this compilation scheme:

\InsertImage{compil-scheme}

Obviously all intermediate stages are hidden to the user who simply invokes
the compiler on his Prolog file(s) (plus other files: C,\ldots) and
obtains an executable. However, it is also possible to stop the compiler at
any given stage. This can be useful, for instance, to see the \Idx{WAM} code
produced (perhaps when learning the WAM). Finally it is possible to give any
kind of file to the compiler which will insert it in the compilation chain
at the stage corresponding to its type. The type of a file is determined
using the suffix of its file name. The following table presents all
recognized types/suffixes:

\begin{tabular}{|l|l|l|}
\hline

Suffix of the file & Type of the file & Handled by: \\

\hline\hline

\texttt{.pl}, \texttt{.pro}, \texttt{.prolog} & Prolog source file & \texttt{pl2wam} \\

\hline

\texttt{.wam} & WAM source file & \texttt{wam2ma} \\

\hline

\texttt{.ma} & Mini-assembly source file & \texttt{ma2asm} \\

\hline

\texttt{.s} & Assembly source file & the assembler \\

\hline

\texttt{.c}, \texttt{.C}, \texttt{.CC}, \texttt{.cc}, \texttt{.cxx},
\texttt{.c++}, \texttt{.cpp} & C or C++ source file & the C compiler \\

\hline

\texttt{.fd} & Finite Domain constraint source file & \texttt{fd2c} \\

\hline

any other suffix (\texttt{.o}, \texttt{.a},\ldots) & any other type
(object, library,\ldots) & the linker (C linker) \\

\hline
\end{tabular}

\SPart{Byte-code compilation}: the same compiler can be used to compile a
source Prolog file for byte-code. In that case the Prolog to WAM compiler is
invoked using a specific option and produces a WAM for byte-code source file
(suffixed \texttt{.wbc}) that can be later loaded using \IdxPB{load/1}
\RefSP{load/1}. Note that this is exactly what \IdxPB{consult/1}
\RefSP{consult/1} does as explained above \RefSP{Consulting-a-Prolog-program}.

\subsubsection{Using the compiler}
\label{Using-the-compiler}
The GNU Prolog compiler is a command-line compiler similar in spirit to a Unix
C compiler like \texttt{gcc}. To invoke the compiler use the \IdxKD{gplc}
command as follows:

\OneLineTwoCols[5.5cm]{\% gplc \textrm{[}\Param{OPTION}\textrm{]\ldots}~\Param{FILE}\textrm{\ldots}}{(the \texttt{\%} symbol is the operating system shell prompt)}

The arguments of \texttt{gplc} are file names that are dispatched in the
compilation scheme depending on the type determined from their suffix as was
explained previously \RefSP{Compilation-scheme}. All object files are then
linked to produce an executable. Note however that GNU Prolog has no module
facility (since there is not yet an ISO reference for Prolog modules) thus a
predicate defined in a Prolog file is visible from any other predicate
defined in any other file. GNU Prolog allows the user to split a big Prolog
source into several files but does not offer any way to hide a predicate
from others.

The simplest way to obtain an executable from a Prolog source file
\texttt{prog.pl} is to use:

\OneLine{\% gplc prog.pl}

This will produce an native executable called \texttt{prog} which can be
executed as follows:

\OneLine{\% prog}

However, there are several options that can be used to control the
compilation:

\SPart{General options}:

\begin{CmdOptions}
\IdxKD{-o} \Param{FILE}, \IdxKD{--output} \Param{FILE} & use
\Param{FILE} as the name of the output file \\

\IdxKD{-W}, \IdxKD{--wam-for-native} & stop after producing WAM file(s)\\

\IdxKD{-w}, \IdxKD{--wam-for-byte-code} & stop after producing WAM for
byte-code file(s) (force \texttt{--no-call-c}) \\

\IdxKD{-M}, \IdxKD{--mini-assembly} & stop after producing mini-assembly
file(s) \\

\IdxKD{-S}, \IdxKD{--assembly} & stop after producing assembly file(s)
\\

\IdxKD{-F}, \IdxKD{--fd-to-c} & stop after producing C file(s) from FD
constraint definition file(s) \\

\IdxKD{-c}, \IdxKD{--object} & stop after producing object file(s) \\

\IdxKD{--temp-dir} \Param{PATH} & use \Param{PATH} as directory
for temporary files \\

\IdxKD{--no-del-temp} & do not delete temporary files \\

\IdxKD{--no-demangling} & do not decode predicate names (name demangling) \\

\IdxKD{-v}, \IdxKD{--verbose} & print executed commands \\

\IdxKD{-h}, \IdxKD{--help} & print a help and exit \\

\IdxKD{--version} & print version number and exit \\

\end{CmdOptions}

\SPart{Prolog to WAM compiler options}:

\begin{CmdOptions}
\IdxKD{--pl-state} \Param{FILE} & read \Param{FILE} to set the initial Prolog state \\

\IdxKD{--wam-comment} \Param{COMMENT} & emit \Param{COMMENT} as a comment in the WAM file \\

\IdxKD{--no-susp-warn} & do not show warnings for suspicious predicates \\

\IdxKD{--no-singl-warn} & do not show warnings for named singleton
variables \\

\IdxKD{--no-redef-error} & do not show errors for built-in predicate
redefinitions \\

\IdxKD{--foreign-only} & only compile \texttt{foreign/1-2} directives \\

\IdxKD{--no-call-c} & do not allow the use of \texttt{fd\_tell},
\texttt{'\$call\_c}',\ldots \\

\IdxKD{--no-inline} & do not inline predicates \\

\IdxKD{--no-reorder} & do not reorder predicate arguments \\

\IdxKD{--no-reg-opt} & do not optimize registers \\

\IdxKD{--min-reg-opt} & minimally optimize registers \\

\IdxKD{--no-opt-last-subterm} & do not optimize last subterm
compilation \\

\IdxKD{--fast-math} & use fast mathematical mode (assume integer
arithmetics) \\

\IdxKD{--keep-void-inst} & keep void WAM instructions in the output file \\

\IdxKD{--compile-msg} & print a compile message \\

\IdxKD{--statistics} & print statistics information \\

\end{CmdOptions}

\SPart{WAM to mini-assembly translator options}:

\begin{CmdOptions}
\IdxKD{--comment} & include comments in the output file \\

\end{CmdOptions}

\SPart{Mini-assembly to assembly translator options}:

\begin{CmdOptions}
\IdxK{--comment} & include comments in the output file \\
\IdxK{--pic} & produce position independent code (PIC) \\

\end{CmdOptions}

\SPart{C compiler options}:

\begin{CmdOptions}
\IdxKD{--c-compiler} \Param{FILE} & use \Param{FILE} as C compiler/linker \\

\IdxKD{-C} \Param{OPTION} & pass \Param{OPTION} to the C compiler \\

\end{CmdOptions}

\SPart{Assembler options}:

\begin{CmdOptions}
\IdxKD{-A} \Param{OPTION} & pass \Param{OPTION} to the assembler \\

\end{CmdOptions}

\SPart{Linker options}:

\begin{CmdOptions}

\IdxKD{--linker} \Param{FILE} & use \Param{FILE} as linker \\

\IdxKD{--local-size} \Param{N} & set default local stack size to
\Param{N} Kb \\

\IdxKD{--global-size} \Param{N} & set default global stack size to
\Param{N} Kb \\

\IdxKD{--trail-size} \Param{N} & set default trail stack size to
\Param{N} Kb \\

\IdxKD{--cstr-size} \Param{N} & set default constraint stack size to
\Param{N} Kb \\

\IdxKD{--max-atom} \Param{N} & set default atom table size to \Param{N} atoms \\

\IdxKD{--fixed-sizes} & do not consult environment variables at run-time
(use default sizes) \\

\IdxKD{--gui-console} & link with the \Idx{GUI console} (windows only)\\

\IdxKD{--new-top-level} & link the \Idx{top-level} main (to recognize top-level command-line options) \\

\IdxKD{--no-top-level} & do not link the \Idx{top-level} (force
\IdxK{--no-debugger}) \\

\IdxKD{--no-debugger} & do not link the Prolog/WAM debugger \\

\IdxKD{--min-pl-bips} & link only used Prolog built-in predicates \\

\IdxKD{--min-fd-bips} & link only used FD solver built-in predicates \\

\IdxKD{--min-bips} & shorthand for: \texttt{--no-top-level}
\texttt{--min-pl-bips} \texttt{--min-fd-bips} \\

\IdxKD{--min-size} & shorthand for: \texttt{--min-bips} \texttt{--strip} \\

\IdxKD{--no-fd-lib} & do not look for the FD library (maintenance only) \\

\IdxKD{-s}, \IdxKD{--strip} & strip the executable \\

\IdxKD{-L} \Param{OPTION} & Pass \Param{OPTION} to the linker \\

\end{CmdOptions}

It is possible to only give the prefix of an option if there is no ambiguity.

The name of the output file is controlled via the \texttt{-o}
\Param{FILE} option. If present the output file produced will be
named \Param{FILE}. If not specified, the output file name depends on the
last stage reached by the compiler. If the link is not done the output file
name(s) is the input file name(s) with the suffix associated with the last
stage. If the link is done, the name of the executable is the name (without
suffix) of the first file name encountered in the command-line.  Note that if
the link is not done \texttt{-o} has no sense in the presence of multiple
input file names. For this reason, several meta characters are available for substitution in \Param{FILE}:

\begin{itemize}
\item \texttt{\%f} is substitued by the whole input file name.
\item \texttt{\%F} is similar to \texttt{\%f} but the directory part is omitted.
\item \texttt{\%p} is substitued by the whole prefix file name (omitting the suffix).
\item \texttt{\%P} is similar to \texttt{\%p} but the directory part is omitted.
\item \texttt{\%s} is substitued by the file suffix (including the dot).
\item \texttt{\%d} is substitued by the directory part (empty if no directory is specified).
\item \texttt{\%c} is substitued by the value of an internal counter starting from 1 and auto-incremented.
\end{itemize}

By default the compiler runs in the native-code compilation scheme. To
generate a WAM file for byte-code use the \texttt{--wam-for-byte-code}
option. The resulting file can then be loaded using \IdxPB{load/1}
\RefSP{load/1}.

To execute the Prolog to WAM compiler in a given \emph{read environment}
(operator definitions, character conversion table,\ldots) use
\texttt{--pl-state} \Param{FILE}. The state file should be
produced by \IdxPB{write\_pl\_state\_file/1}
\RefSP{write-pl-state-file/1}.

By default the Prolog to WAM compiler inlines calls to some deterministic
built-in predicates (e.g. \texttt{arg/3} and \texttt{functor/3}). Namely a
call to such a predicate will not yield a classical predicate call but a
simple C function call (which is obviously faster). It is possible to avoid
this using \texttt{--no-inline}.

Another optimization performed by the Prolog to WAM compiler is unification
reordering. The arguments of a predicate are reordered to optimize
unification. This can be deactivated using \texttt{--no-reorder}. The
compiler also optimizes the unification/loading of nested compound terms.
More precisely, the compiler emits optimized instructions when the last
subterm of a compound term is itself a compound term (e.g. lists). This can
be deactivated using \texttt{--no-opt-last-subterm}.

By default the Prolog to WAM compiler fully optimizes the allocation of
registers to decrease both the number of instruction produced and the number
of used registers. A good allocation will generate many \emph{void
instructions} that are removed from the produced file except if
\texttt{--keep-void-inst} is specified. To prevent any optimization use
\texttt{--no-reg-opt} while \texttt{--min-reg-opt} forces the compiler to
only perform simple register optimizations.

The Prolog to WAM compiler emits an error when a control construct or a
built-in predicate is redefined. This can be avoided using
\texttt{--no-redef-error}. The compiler also emits warnings for suspicious
predicate definitions like \texttt{-/2} since this often corresponds to an
earlier syntax error (e.g. \texttt{-} instead of \texttt{\_}. This can be
deactivated by specifying \texttt{--no-susp-warn}. Finally, the compiler
warns when a singleton variable has a name (i.e. not the generic anonymous
name \texttt{\_}). This can be deactivated specifying
\texttt{--no-singl-warn}.

Internally, predicate names are encoded to fit the syntax of (assembly)
identifiers. For this GNU Prolog uses it own \Idx{name mangling} scheme. This
is explained in more detail later \RefSP{Name-mangling-scheme}. By default
the error messages from the linker (e.g. multiple definitions for a given
predicate, reference to an undefined predicate,\ldots) are filtered to
replace an internal name representation by the real predicate name
(\Idx{demangling}). Specifying the \texttt{--no-demangling} prevents
\IdxK{gplc} from filtering linker output messages (internal identifiers are
then shown).

When producing an executable it is possible to specify default stack sizes
(using \texttt{--\Param{STACK\_NAME}-size}) and to prevent it from consulting
environment variables (using \texttt{--fixed-sizes}) as was explained above
\RefSP{Adjusting-the-size-of-Prolog-stacks}. By default the produced
executable will include the top-level, the Prolog/WAM debugger
and all Prolog and FD built-in predicates. It is possible to avoid linking
the top-level \RefSP{The-GNU-Prolog-interactive-interpreter} by specifying
\texttt{--no-top-level}. In this case, at least one
\IdxDi{initialization/1} directive \RefSP{initialization/1} should be
defined. The option \texttt{--no-debugger} does not link the debugger. To
include only used built-in predicates that are actually used the options
\texttt{--no-pl-bips} and/or \texttt{--no-fd-bips} can be specified. For the
smallest executable all these options should be specified. This can be
abbreviated by using the shorthand option \texttt{--min-bips}. By default,
executables are not \emph{stripped}, i.e. their symbol table is not
removed. This table is only useful for the C debugger (e.g. when interfacing
Prolog and C). To remove the symbol table (and then to reduce the size of
the final executable) use \texttt{--strip}. Finally \texttt{--min-size} is a
shortcut for \texttt{--min-bips} and \texttt{--strip}, i.e. the produced
executable is as small as possible.

Example: compile and link two Prolog sources \texttt{prog1.pl} and
\texttt{prog2.pl}. The resulting executable will be named \texttt{prog1}
(since \texttt{-o} is not specified):

\OneLine{\% gplc prog1.pl prog2.pl}

Example: compile the Prolog file \texttt{prog.pl} to study basic WAM code.
The resulting file will be named \texttt{prog.wam}:

\OneLine{\% gplc -W --no-inline --no-reorder --keep-void-inst prog.pl}

Example: compile the Prolog file \texttt{prog.pl} and its C interface file
\texttt{utils.c} to provide an autonomous executable called
\texttt{mycommand}. The executable is not stripped to allow the use of the C
debugger:

\OneLine{\% gplc -o mycommand prog.pl utils.c}

Example: detail all steps to compile the Prolog file \texttt{prog.pl} (the
resulting executable is stripped). All intermediate files are produced
(\texttt{prog.wam}, \texttt{prog.ma}, \texttt{prog.s}, \texttt{prog.o} and
the executable \texttt{prog}):

\begin{Indentation}
\begin{verbatim}
% gplc -W prog.pl
% gplc -M --comment prog.wam
% gplc -S --comment prog.ma
% gplc -c prog.s
% gplc -o prog -s prog.o
\end{verbatim}
\end{Indentation}

\subsubsection{Running an executable}
\label{Running-an-executable}
In this section we explain what happens when running an executable produced
by the GNU Prolog native-code compiler. The default main function first starts
the Prolog engine. This function collects all linked objects (issued from the
compilation of Prolog files) and initializes them. The initialization of a
Prolog object file consists in adding to appropriate tables new atoms, new
predicates and executing its system directives. A system directive is
generated by the Prolog to WAM compiler to reflect a (user) directive
executed at compile-time such as \texttt{op/3} \RefSP{op/3}. Indeed, when the
compiler encounters such a directive it immediately executes it and also
generates a system directive to execute it at the start of the executable.
When all system directives have been executed the Prolog engine executes all
initialization directives defined with \IdxDi{initialization/1}
\RefSP{initialization/1}.  If several initialization directives appear in the
same file they are executed in the order of appearance. If several
initialization directives appear in different files the order in which they
are executed is machine-dependant. However, on most machines the order will
be the reverse order in which the associated files have been linked (this is
not true under native win32). When all initialization directives have been
executed the default main function looks for the GNU Prolog
\Idx{top-level}. If present (i.e. it has been linked) it is called otherwise
the program simply ends. Note that if the top-level is not linked and if
there is no initialization directive the program is useless since it simply
ends without doing any work. The default main function detects such a
behavior and emits a warning message.

Example: compile an empty file \texttt{prog.pl} without linking the
top-level and execute it:

\begin{Indentation}
\begin{verbatim}
% gplc --no-top-level prog.pl
% prog
Warning: no initial goal executed
   use a directive :- initialization(Goal)
   or remove the link option --no-top-level (or --min-bips or --min-size)
\end{verbatim}
\end{Indentation}

\subsubsection{Generating a new interactive interpreter}
\label{Generating-a-new-interactive-interpreter}
In this section we show how to define a new \Idx{top-level} extending the
GNU Prolog interactive interpreter with new predicate definitions. The
obtained top-level can then be considered as an enriched version of the basic
GNU Prolog top-level \RefSP{The-GNU-Prolog-interactive-interpreter}. Indeed, each
added predicate can be viewed as a predefined predicate just like any other
built-in predicate. This can be achieved by compiling these predicates and
including the top-level at link-time.

The real question is: why would we include some predicates in a new
top-level instead of simply consulting them under the GNU Prolog top-level ?
There are two reasons for this:

\begin{itemize}

\item the predicate cannot be consulted. This is the case of a predicate
calling foreign code, like a predicate interfacing with C \RefSP{Interfacing-Prolog-and-C} or a predicate defining a new FD constraint.

\item the performance of the predicate is crucial. Since it is compiled to
native-code such a predicate will be executed very quickly. Consulting will
load it as byte-code. The gain is much more noticeable if the program is run
under the debugger. The included version will not be affected by the
debugger while the consulted version will be several times slower.
Obviously, a predicate should be included in a new top-level only when it is
itself debugged since it is difficult to debug native-code.

\end{itemize}

To define a new top-level simply compile the set of desired predicates and
linking them with the GNU Prolog top-level (this is the default) using
\IdxK{gplc} \RefSP{Using-the-compiler}.

Example: let us define a new top-level called \texttt{my\_top\_level}
including all predicates defined in \texttt{prog.pl}:

\OneLine{\% gplc -o my\_top\_level prog.pl}

By the way, note that if \texttt{prog.pl} is an empty Prolog file the
previous command will simply create a new interactive interpreter similar to
the GNU Prolog top-level.

Example: as before where some predicates of \texttt{prog.pl} call C functions
defined in \texttt{utils.c}:

\OneLine{\% gplc -o my\_top\_level prog.pl utils.c}

To obtain a fully extended executable, it is desirable to accept the same set
of opions as the original top-level, see
\RefSP{The-GNU-Prolog-interactive-interpreter}, e.g. \IdxK{--init-goal}. For this it is necessary to link \IdxK{main()} function used by the original top-level. This can be achieved passing the \IdxK{--new-top-level} to \texttt{gplc}:

\OneLine{\% gplc --new-top-level -o my\_top\_level prog.pl utils.c}

In conclusion, defining a particular top-level is nothing else but a
particular case of the native-code compilation. It is simple to do and very
useful in practice.

\subsubsection{The name mangling scheme}
\label{Name-mangling-scheme}

When the GNU Prolog compiler compiles a Prolog source to an object file it
has to associate a symbol to each predicate name. However, the syntax of
symbols is restricted to identifiers: string containing only letters, digits
or underscore characters. On the other hand, predicate names (i.e. atoms) can
contain any character with quotes if necessary (e.g. \texttt{'x+y=z'} is a
valid predicate name). The compiler may thus have to encode predicate names
respecting the syntax of identifiers. In addition, Prolog allows the user to
define several predicates with the same name and different arities, for this
GNU Prolog encodes predicate indicators (predicate name followed by the
arity). Finally, to support modules in the future, the module name is also
encoded.

Since version 1.4.0, GNU Prolog adopts the following \IdxD{name mangling}
scheme. A predicate indicator of the form
[\Param{MODULE}\texttt{:}]\Param{PRED}\texttt{/}\Param{N} (where
the \Param{MODULE} can be omitted) will give rise to an identifier of the
following form:
\texttt{X}\Param{K}\texttt{\_}[\textit{E(\Param{MODULE})}\texttt{\_\_}]\textit{E(\Param{PRED})}\texttt{\_\_a}\Param{N}
where:

\begin{description}

\item \Param{K} is a digit in \texttt{0}..\texttt{5} storing coding information about \Param{MODULE} and \Param{PRED}. Possible values are:

\begin{itemize}

  \item \texttt{0}: no module present,             \Param{PRED} is not encoded
  \item \texttt{1}: no module present,             \Param{PRED} is encoded
  \item \texttt{2}: \Param{MODULE} is not encoded, \Param{PRED} is not encoded
  \item \texttt{3}: \Param{MODULE} is not encoded, \Param{PRED} is encoded
  \item \texttt{4}: \Param{MODULE} is encoded,     \Param{PRED} is not encoded
  \item \texttt{5}: \Param{MODULE} is encoded,     \Param{PRED} is encoded

\end{itemize}

\item \textit{E(\Param{STR})} is a function to encode a string \Param{STR} which returns:

\begin{itemize}

  \item \Param{STR} itself (not encoded) if \Param{STR} only contains letters, digits or \texttt{\_} but does not contain the substring \texttt{\_\_} and does not begin nor end with \texttt{\_} (i.e. regexp: \texttt{[a-zA-Z0-9]([-]?[a-zA-Z0-9])*}).

\item an hexadecimal representation of each character of the string otherwise. For example: \textit{E(}\texttt{x+y=z}\textit{)} returns \texttt{782B793D7A} since
\texttt{78} is the hexadecimal representation of the ASCII code of \texttt{x},
\texttt{2B} of the code of \texttt{+}, etc.

\end{itemize}

\end{description}

Examples: 

\begin{center}
\begin{tabular}{l|l}

Predicate indicator   & internal identifier \\
\hline
\texttt{father/2}     & \texttt{X0\_father\_\_a2} \\
\texttt{'x+y=z'/3}    & \texttt{X1\_782B793D7A\_\_a3} \\
\texttt{util:same/2}  & \texttt{X2\_util\_\_same\_\_a2} \\
\texttt{util:same\_\_1/3} & \texttt{X3\_util\_\_73616D655F5F31\_\_a3} \\

\end{tabular}
\end{center}

~\BL

So, from the \Idx{mini-assembly} stage, each predicate indicator is handled
via its name mangling identifier. The knowledge of this scheme is normally
not of interest for the user, i.e. the Prolog programmer. For this reason the
GNU Prolog compiler hides this mangling. When an error occurs on a predicate
(undefined predicate, predicate with multiple definitions,\ldots) the
compiler has to decode the symbol associated with the predicate indicator
(\IdxD{name demangling}). For this \IdxK{gplc} filters each message emitted
by the linker to locate and decode eventual predicate indicators. This
filtering can be deactivated specifying \texttt{--no-demangling} when
invoking \IdxK{gplc} \RefSP{Using-the-compiler}.

This filter is provided as an utility that can be invoked using the
\IdxKD{hexgplc} command as follows:

\OneLineTwoCols[5.5cm]{\% hexgplc \textrm{[}\Param{OPTION}\textrm{]\ldots}~\Param{FILE}\textrm{\ldots}}{(the \texttt{\%} symbol is the operating system shell prompt)}

\SPart{Options}:

\begin{CmdOptions}
\IdxKD{--decode} or \IdxKD{--demangling} & decoding mode (this is the default mode) \\

\IdxKD{--encode} or \IdxKD{--mangling} & encoding mode \\

\IdxKD{--relax} & decode also predicate names (not only predicate
indicators) \\

\IdxKD{--printf} \Param{FORMAT} & pass encoded/decoded string to C
\texttt{printf(3)} with \Param{FORMAT} \\

\IdxKD{--aux-father} & decode an auxiliary predicate as its father \\

\IdxKD{--aux-father2} & decode an auxiliary predicate as its father +
auxiliary number \\

\IdxKD{--cmd-line} & encode/decode each argument of the command-line \\

\IdxKD{-E} or \IdxKD{-M} & same as: \texttt{--cmd-line --encode --relax} \\

\IdxKD{-P} or \IdxKD{-D} & same as: \texttt{--cmd-line --decode --relax --quote} \\

\IdxKD{--help} & print a help and exit \\

\IdxKD{--version} & print version number and exit \\

\end{CmdOptions}

It is possible to give a prefix of an option if there is no ambiguity.

Without arguments \texttt{hexgplc} runs in decoding mode reading its
standard input and decoding (demangling) each symbol corresponding to a predicate
indicator. To use \texttt{hexgplc} in the encoding (mangling) mode the
\texttt{--encode} option must be specified. By default \texttt{hexgplc} only
decodes predicate indicators, this can be relaxed using \texttt{--relax} to
also take into account simple predicate names (the arity can be omitted). It
is possible to format the output of an encoded/decoded string using
\texttt{--printf \Param{FORMAT}} in that case each string
\Param{S} is passed to the C \texttt{printf(3)} function as
\texttt{printf(\Param{FORMAT},\Param{S})}.

Auxiliary predicates are generated by the Prolog to WAM compiler when
simplifying some control constructs like \texttt{';'/2} present in the body
of a clause. They are of the form
\texttt{'\$\Param{NAME}/\Param{ARITY}\_\$aux\Param{N}'} where
\texttt{\Param{NAME}/\Param{ARITY}} is the predicate indicator of the
simplified (i.e. father) predicate and \Param{N} is a sequential
number (a predicate can give rise to several auxiliary predicates). It is
possible to force \texttt{hexgplc} to decode an auxiliary predicate as its
father predicate indicator using \texttt{--aux-father} or as its father
predicate indicator followed by the sequential number using
\texttt{--aux-father2}.

If no file is specified, \texttt{hexgplc} processes its standard input
otherwise each file is treated sequentially. Specifying the
\texttt{--cmd-line} option informs \texttt{hexgplc} that each argument is not
a file name but a string that must be encoded (or decoded). This is useful to
encode/decode a particular string. For this reason the option \texttt{-E}
(encode) and \texttt{-D} (decode) are provided as
shorthand.  Then, to obtain the mangling representation of a predicate
\Param{PRED} use:

\OneLine{\% hexgplc -E \Param{PRED}}

NB: if \Param{PRED} is a complex atom it is necessary to quote it 
(the quotes must be passed to \texttt{hexgplc}). Here is an example under bash:

\begin{Indentation}
\begin{verbatim}
% hexgplc -E \'x+y=z\'/3
X1_782B793D7A__a3
\end{verbatim}
\end{Indentation}

Or even more safely (using bash quotes to prevent bash from interpreting special characters):

\begin{Indentation}
\begin{verbatim}
% hexgplc -E \''x+y=z'\'/3
X1_782B793D7A__a3
\end{verbatim}
\end{Indentation}


%HEVEA\cutend
