\newpage
\section{Interfacing Prolog and C}
\label{Interfacing-Prolog-and-C}
%HEVEA\cutdef[1]{subsection}
\subsection{Calling C from Prolog}
\label{Calling-C-from-Prolog}

\subsubsection{Introduction}
This interface allows a Prolog predicate to call a C function. Here are some
features of this facility:

\begin{itemize}

\item implicit Prolog $\leftrightarrow$ C data conversions for simple types.

\item functions to handle complex types.

\item error detection depending on the type of the argument.

\item different kinds of arguments: input, output or input/output.

\item possibility to write non-deterministic code.

\end{itemize}

This interface can then be used to write both simple and complex C routines.
A simple routine uses either input or output arguments which type is simple.
In that case the user does not need any knowledge of Prolog data structures
since all Prolog $\leftrightarrow$ C data conversions are implicitly
achieved. To manipulate complex terms (lists, structures) a set of
functions is provided. Finally it is also possible to write
non-deterministic C code.

\subsubsection{\texttt{foreign/2} directive}
\label{foreign/2-directive}
The \IdxDiD{foreign/2} directive \RefSP{foreign/2} directive is provided
to declare a C function interface. The general form is
\texttt{foreign(Template, Options)} which defines an interface predicate
whose prototype is \texttt{Template} according to the options given by
\texttt{Options}. \texttt{Template} is a callable term specifying the
type/mode of each argument of the associated Prolog predicate.

\SPart{Foreign options}: \texttt{Options} is a list of foreign options. If
this list contains contradictory options, the rightmost option is the one
which applies. Possible options are:

\begin{itemize}

\item \IdxPOD[fct\_name]{fct\_name(F)}: \texttt{F} is an atom representing
the name of the C function to call. By default the name of the C function is
the same as the principal functor of \texttt{Template}. In any case, the atom
associated to the name of the function must conforms to the syntax of C
identifiers.

\item \IdxPOD[return]{return(boolean}/\texttt{none}/\texttt{jump)}:
specifies the value returned by the C function:

\begin{itemize}

\item \IdxPOD{boolean}: the type of the function is \texttt{Bool} (returns
\texttt{TRUE} on success, \texttt{FALSE} otherwise).

\item \IdxPOD{none}: the type of the function is \texttt{void} (no returned
value).

\item \IdxPOD{jump}: the type of the function is \texttt{void(*)()} (returns
the address of a Prolog code to execute).

\end{itemize}

The default value is \texttt{boolean}.

\item \IdxPOD[bip\_name]{bip\_name(Name, Arity)}: initializes the error
context with \texttt{Name} and \texttt{Arity}. If an error occurs this
information is used to indicate from which predicate the error occurred
\RefSP{General-format-and-error-context}. It is also possible to prevent the
initialization of the error context using \texttt{bip\_name(none)}. By
default \texttt{Name} and \texttt{Arity} are set to the functor and arity of
\texttt{Template}.

\item \IdxPOD[choice\_size]{choice\_size(N)}: this option specifies that the
function implements a non-deterministic code. \texttt{N} is an integer
specifying the size needed by the non-deterministic C function. This facility
is explained later \RefSP{Writing-non-deterministic-C-code}. By default a
foreign function is deterministic.

\end{itemize}

\IdxDiD[foreign/1]{foreign(Template)} is equivalent to
\texttt{foreign(Template, [])}.

\SPart{Foreign modes and types}: each argument of \texttt{Template}
specifies the foreign mode and type of the corresponding argument. This
information is used to check the type of effective arguments at run-time and
to perform Prolog $\leftrightarrow$ C data conversions. Each argument of
\texttt{Template} is formed with a mode symbol followed by a type name.
Possible foreign modes are:

\begin{itemize}

\item \texttt{+}: input argument.

\item \texttt{-}: output argument.

\item \texttt{?}: input/output argument.

\end{itemize}

Possible foreign types are:

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

Foreign type & Prolog type & C type & Description of the C type \\

\hline\hline

\texttt{integer} & integer & \texttt{int} & value of the integer \\

\hline

\texttt{positive} & positive integer & \texttt{int} & value of the integer
\\

\hline

\texttt{float} & floating point number & \texttt{double} & value of the
floating point number \\

\hline

\texttt{number} & number & \texttt{double} & value of the number \\

\hline

\texttt{atom} & atom & \texttt{int} & internal key of the atom \\

\hline

\texttt{boolean} & boolean & \texttt{int} & value of the boolean
(0=\texttt{false}, 1=\texttt{true}) \\

\hline

\texttt{char} & character & \texttt{int} & value of (the code of) the
character \\

\hline

\texttt{code} & character code & \texttt{int} & value of the character-code
\\

\hline

\texttt{byte} & byte & \texttt{int} & value of the byte \\

\hline

\texttt{in\_char} & in-character & \texttt{int} & value of the character or
\texttt{-1} for end-of-file \\

\hline

\texttt{in\_code} & in-character code & \texttt{int} & value of the
character-code or \texttt{-1} for end-of-file \\

\hline

\texttt{in\_byte} & in-byte & \texttt{int} & value of the byte or
\texttt{-1} for the end-of-file \\

\hline

\texttt{string} & atom & \texttt{char *} & C string containing the name of
the atom \\

\hline

\texttt{chars} & character list & \texttt{char *} & C string containing the
characters of the list \\

\hline

\texttt{codes} & character-code list & \texttt{char *} & C string containing
the characters of the list \\

\hline

\texttt{term} & Prolog term & \texttt{PlTerm} & generic Prolog term \\

\hline
\end{tabular}

\SPart{Simple foreign type}: a simple type is any foreign type listed in
the above tabled except \texttt{term}. A simple foreign type is an atomic
term (character and character-code lists are in fact lists of constants).
Each simple foreign type is converted to/from a C type to simplify the
writing of the C function.

\SPart{Complex foreign type}: type foreign type \texttt{term} refers to any
Prolog term (e.g. lists, structures\ldots). When such an type is
specified the argument is passed to the C function as a \texttt{PlTerm}
(GNU Prolog C type equivalent to a \texttt{long}). Several functions are
provided to manipulate \texttt{PlTerm} variables \RefSP{Manipulating-Prolog-terms}. Since the original term is passed to the function it is
possible to read its value or to unify it. So the meaning of the mode symbol
is less significant. For this reason it is possible to omit the mode symbol.
In that case \texttt{term} is equivalent to \texttt{+term}.

\subsubsection{The C function}
The C code is written in a C file which must first include the GNU Prolog
header file called \texttt{gprolog.h}. This file contains all GNU Prolog C
definitions (constants, types, prototypes,\ldots). 

The type returned by a C function depends on the value of the
\IdxPO{return} foreign option \RefSP{foreign/2-directive}. If it is
\IdxPO{boolean} then the C function is of type \texttt{Bool} and shall
return \texttt{TRUE} in case of success and \texttt{FALSE} otherwise. If the
\texttt{return} option is \IdxPO{none} the C function is of type
\texttt{void}. Finally if it is \IdxPO{jump}, the function shall return the
address of a Prolog predicate and, at the exit of the function, the control
is given to that predicate.

The type of the arguments of the C function depends on the mode and type
declaration specified in \texttt{Template} for the corresponding argument as
explained in the following sections.

\subsubsection{Input arguments}
\label{Input-arguments}
An input argument is tested at run-time to check if its type conforms to the
foreign type and then it is passed to the C function. The type of the
associated C argument is given by the above table \RefSP{foreign/2-directive}. For instance, the effective argument \texttt{Arg} associated to
\texttt{+positive} foreign declaration is submitted to the following
process:

\begin{itemize}

\item if \texttt{Arg} is a variable an \texttt{instantiation\_error} is
raised.

\item if \texttt{Arg} is neither a variable nor an integer a
\texttt{type\_error(integer, Arg)} is raised.

\item if \texttt{Arg} is an integer $<$ 0 a
\texttt{domain\_error(not\_less\_than\_zero, Arg)} is raised.

\item otherwise the value of \texttt{Arg} is passed to the C is passed to
the C function as an integer (\texttt{int}).

\end{itemize}

When \texttt{+string} is specified the string passed to the function is the
internal string of the corresponding atom and should not be modified.

When \texttt{+term} is specified the term passed to the function is the
original Prolog term. It can be read and/or unified. It is also the case
when \texttt{term} is specified without any mode symbol.

\subsubsection{Output arguments}
\label{Output-arguments}
An output argument is tested at run-time to check if its type conforms to
the foreign type and it is unified with the value set by the C function. The
type of the associated C argument is a pointer to the type given by the
above table \RefSP{foreign/2-directive}. For instance, the effective
argument \texttt{Arg} associated to \texttt{-positive} foreign declaration
is handled as follows:

\begin{itemize}

\item if \texttt{Arg} is neither a variable nor an integer a
\texttt{type\_error(integer, Arg)} is raised.

\item if \texttt{Arg} is an integer $<$ 0 a
\texttt{domain\_error(not\_less\_than\_zero, Arg)} is raised.

\item otherwise a pointer to an integer (\texttt{int} \texttt{*}) is passed
to the C function. If the function returns \texttt{TRUE} the integer stored
at this location is unified with \texttt{Arg}.

\end{itemize}

When \texttt{-term} is specified, the function must construct a term into
the its corresponding argument (which is of type \texttt{PlTerm *}). At the
exit of the function this term will be unified with the actual predicate
argument.

\subsubsection{Input/output arguments}
\label{Input/output-arguments}
Basically an input/output argument is treated as in input argument if it is
not a variable, as an output argument otherwise. The type of the associated
C argument is a pointer to a \texttt{FIOArg} (GNU Prolog C type) defined as
follows:

\begin{Indentation}
\begin{verbatim}
typedef struct
    {
     Bool is_var;
     Bool unify;
     union
        {
         long   l;
         char  *s;
         double d;
        }value;
    }FIOArg;
\end{verbatim}
\end{Indentation}

The field \texttt{is\_var} is set to \texttt{TRUE} if the argument is a
variable and \texttt{FALSE} otherwise. This value can be tested by the C
function to determine which treatment to perform. The field \texttt{unify}
controls whether the effective argument must be unified at the exit of the C
function. Initially \texttt{unify} is set to the same value as
\texttt{is\_var} (i.e. a variable argument will be unified while a
non-variable argument will not) but it can be modified by the C function.
The field \texttt{value} stores the value of the argument. It is declared as
a C \texttt{union} since there are several kinds of value types. The field
\texttt{s} is used for C strings, \texttt{d} for C doubles and \texttt{l}
otherwise (\texttt{int}, \texttt{PlTerm}). if \texttt{is\_var} is
\texttt{FALSE} then \texttt{value} contains the input value of the argument
with the same conventions as for input arguments \RefSP{Input-arguments}.
At the exit of the function, if unify is \texttt{TRUE} \texttt{value} must
contain the value to unify with the same conventions as for output arguments
\RefSP{Output-arguments}.

For instance, the effective argument \texttt{Arg} associated to
\texttt{?positive} foreign declaration is handled as follows:

\begin{itemize}

\item if \texttt{Arg} is a variable \texttt{is\_var} and \texttt{unify} are
set to \texttt{TRUE} else to \texttt{FALSE} and its value is copied in
\texttt{value.l}.

\item if \texttt{Arg} is neither a variable nor an integer a
\texttt{type\_error(integer, Arg)} is raised.

\item if \texttt{Arg} is an integer $<$ 0 a
\texttt{domain\_error(not\_less\_than\_zero, Arg)} is raised.

\item otherwise a pointer to the \texttt{FIOArg} (\texttt{FIOArg}
\texttt{*}) is passed to the C function. If the function returns
\texttt{TRUE} and if \texttt{unify} is TRUE the value stored in
\texttt{value.l} is unified with \texttt{Arg}.

\end{itemize}

\subsubsection{Writing non-deterministic C code}
\label{Writing-non-deterministic-C-code}
The interface allows the user to write non-deterministic C code. When a C
function is non-deterministic, a choice-point is created for this function.
When a failure occurs, if all more recent non-deterministic code are
finished, the function is re-invoked. It is then important to inform Prolog
when there is no more solution (i.e. no more choice) for a non-deterministic
code. So, when no more choices remains the function must remove the
choice-point. The interface increments a counter each time the function is
re-invoked. At the first call this counter is equal to 0. This information
allows the function to detect its first call. When writing non-deterministic
code, it is often useful to record data between consecutive re-invocations
of the function. The interface maintains a buffer to record such an
information. The size of this buffer is given by
\IdxPO[choice\_size]{choice\_size(N)} when using \texttt{foreign/2}
\RefSP{foreign/2-directive}. This size is the number of (consecutive)
\texttt{long}\emph{s} needed by the C function. Inside the function it is
possible to call the following functions/macros:

\begin{Indentation}
\begin{verbatim}
void Get_Choice_Counter(void)
TYPE Get_Choice_Buffer (TYPE)
void No_More_Choice    (void)
\end{verbatim}
\end{Indentation}

The function \texttt{Get\_Choice\_Counter()} returns the value of the
invocation counter (0 at the first call).

The macro \texttt{Get\_Choice\_Buffer(\Param{TYPE})} returns a
pointer to the buffer (casted to \Param{TYPE}).

The function \texttt{No\_More\_Choice()} deletes the choice point
associated to the function.

\subsubsection{Example: input and output arguments}
Let us define a predicate \texttt{first\_occurrence(A, C, P)} which unifies
\texttt{P} with the position (from 0) of the first occurrence of the
character \texttt{C} in the atom \texttt{A}. The predicate must fail if
\texttt{C} does not appear in \texttt{A}.

In the prolog file \texttt{prog.pl}:

\OneLine{:- foreign(first\_occurrence(+string, +char, -positive)).}

In the C file \texttt{utils.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include "gprolog.h"

Bool first_occurrence(char *str, int c, int *pos)

{
 char *p;

 if ((p=strchr(str,c))==NULL)         /* C does not appear in A */
     return FALSE;                    /* fail */

 *pos=p-str;                          /* set the output argument */
 return TRUE;                         /* succeed */
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{prog}:

\OneLine{\% gplc prog.pl utils.c}

Examples of use:

\begin{Indentation}
\begin{verbatim}
| ?- first_occurrence(prolog, p, X).

X = 0

| ?- first_occurrence(prolog, k, X).

no

| ?- first_occurrence(prolog, A, X).
{exception: error(instantiation_error,first_occurrence/3)}

| ?- first_occurrence(prolog, 1 ,X).
{exception: error(type_error(character,1),first_occurrence/3)}
\end{verbatim}
\end{Indentation}

\subsubsection{Example: non-deterministic code}
We here define a predicate \texttt{occurrence(A, C, P)} which unifies
\texttt{P} with the position (from 0) of one occurrence of the character
\texttt{C} in the atom \texttt{A}. The predicate will fail if \texttt{C}
does not appear in \texttt{A}. The predicate is re-executable on
backtracking. The information that must be recorded between two invocations
of the function is the next starting position in \texttt{A} to search for
\texttt{C}.

In the prolog file \texttt{prog.pl}:

\OneLine{:- foreign(occurrence(+string, +char, -positive), 
[choice\_size(1)]).}

In the C file \texttt{utils.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include "gprolog.h"

Bool occurrence(char *str, int c, int *pos)

{
 char **info_pos;
 char  *p;

 info_pos=Get_Choice_Buffer(char **); /* recover the buffer */

 if (Get_Choice_Counter()==0)         /* first invocation ? */
     *info_pos=str;

 if ((p=strchr(*info_pos,c))==NULL)   /* C does not appear */
    {
     No_More_Choice();                /* remove choice-point */
     return FALSE;                    /* fail */
    }

 *pos=p-str;                          /* set the output argument */
 *info_pos=p+1;                       /* update next starting pos */
 return TRUE;                         /* succeed */
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{prog}:

\OneLine{\% gplc prog.pl utils.c}

Examples of use:


\begin{CodeTwoCols}
\One{| ?- occurrence(prolog, o, X).}
\SkipLine
\Two{X = 2 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 4 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{no}     {(no more solution)}
\SkipLine
\One{| ?- occurrence(prolog, k, X).}
\SkipLine
\One{no}
\end{CodeTwoCols}

In the first example when the second (the last) occurrence is found
(\texttt{X=4}) the choice-point remains and the failure is detected only
when another solution is requested (by pressing \texttt{;}). It is possible
to improve this behavior by deleting the choice-point when there is no more
occurrence. To do this it is necessary to do one search ahead. The
information stored is the position of the next occurrence.

Here is the corresponding definition of the C function:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include "gprolog.h"

Bool occurrence(char *str, int c, int *pos)

{
 char **info_pos;
 char  *p;

 info_pos=Get_Choice_Buffer(char **); /* recover the buffer */

 if (Get_Choice_Counter()==0)         /* first invocation ? */
    {
     if ((p=strchr(str,c))==NULL)     /* C does not appear at all */
        {
         No_More_Choice();            /* remove choice-point */
         return FALSE;                /* fail */
        }

     *info_pos=p;
    }
                                      /* info_pos = an occurrence */
 *pos=*info_pos-str;                  /* set the output argument */

 if ((p=strchr(*info_pos+1,c))==NULL) /* no more occurrence */
     No_More_Choice();                /* remove choice-point */
  else
     *info_pos=p;                     /* else update next solution */

 return TRUE;                         /* succeed */
}
\end{verbatim}
\end{Indentation}

Examples of use:

\begin{CodeTwoCols}
\One{| ?- occurrence(prolog, l, X).}
\SkipLine
\Two{X = 3}{(here the user is not prompted since there is no more alternative)}
\SkipLine
\One{| ?- occurrence(prolog, o, X).}
\SkipLine
\Two{X = 2 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 4}{(here the user is not prompted since there is no more alternative)}
\end{CodeTwoCols}

\subsubsection{Example: input/output arguments}
We here define a predicate \texttt{char\_ascii(Char, Code}) which converts
in both directions the character \texttt{Char} and its character-code
\texttt{Code}. This predicate is then similar to \IdxPB{char\_code/2}
\RefSP{char-code/2}.

In the prolog file \texttt{prog.pl}:

\OneLine{:- foreign(char\_ascii(?char, ?code), [fct\_name('Char\_Ascii')]).}

In the C file \texttt{utils.c}:

\begin{Indentation}
\begin{verbatim}
#include "gprolog.h"

Bool Char_Ascii(FIOArg *c, FIOArg *ascii)

{
 if (!c->is_var)                      /* Char is not a variable */
    {
     ascii->unify=TRUE;               /* enforce unif. of Code */
     ascii->value.l=c->value.l;       /* set Code */
     return TRUE;                     /* succeed */
    }

 if (ascii->is_var)                   /* Code is also a variable */
     Pl_Err_Instantiation();          /* emit instantiation_error */

 c->value.l=ascii->value.l;           /* set Char */
 return TRUE;                         /* succeed */
}
\end{verbatim}
\end{Indentation}

If \texttt{Char} is instantiated it is necessary to enforce the unification
of \texttt{Code} since it could be instantiated. Recall that by default if
an input/output argument is instantiated it will not be unified at the exit
of the function \RefSP{Input/output-arguments}. If both \texttt{Char} and
\texttt{Code} are variables the function raises an
\texttt{instantiation\_error}. The way to raise Prolog errors is described
later \RefSP{Raising-Prolog-errors}.

The compilation produces an executable called \texttt{prog}:

\OneLine{\% gplc prog.pl utils.c}

Examples of use:

\begin{Indentation}
\begin{verbatim}
| ?- char_ascii(a, X).

X = 97

| ?- char_ascii(X, 65).

X = 'A'

| ?- char_ascii(a, 12).

no

| ?- char_ascii(X, X).
{exception: error(instantiation_error,char_ascii/2)}

| ?- char_ascii(1, 12).
{exception: error(type_error(character,1),char_ascii/2)}
\end{verbatim}
\end{Indentation}

\subsection{Manipulating Prolog terms}
\label{Manipulating-Prolog-terms}

\subsubsection{Introduction}
\label{Introduction:(Manipulating-Prolog-terms)}
In the following we presents a set of functions to manipulate Prolog terms.
For simple foreign terms the functions manipulate simple C types
\RefSP{foreign/2-directive}. 

Functions managing lists handle an array of 2 elements (of type
\texttt{PlTerm}) containing the terms corresponding to the head and the tail
of the list. For the empty list \texttt{NULL} is passed as the array. These
functions require to flatten a list in each sub-list. To simplify the
management of proper lists (i.e. lists terminated by \texttt{[]}) a set of
functions is provided that handle the number of elements of the list (an
integer) and an array whose elements (of type \texttt{PlTerm}) are the
elements of the list. The caller of these functions must provide the array.

Functions managing compound terms handle a functor (the principal functor of
the term), an arity \Param{N} $\geq$ 0 and an array of \Param{N} elements
(of type \texttt{PlTerm}) containing the sub-terms of the compound term.
Since a list is a special case of compound term (functor = \texttt{'.'} and
arity=2) it is possible to use any function managing compound terms to deal
with a list but the error detection is not the same. Indeed many functions
check if the Prolog argument is correct. The name of a read or unify
function checking the Prolog arguments is of the form
\texttt{\Param{Name}\_Check()}. For each of these functions there is a also
check-free version called \texttt{\Param{Name}()}. We then only present the
name of checking functions.

\subsubsection{Managing Prolog atoms}
Each atom has a unique internal key which corresponds to its index in the
GNU Prolog atom table. It is possible to obtain the information about an atom
and to create new atoms using:

\begin{Indentation}
\begin{verbatim}
char *Atom_Name           (int atom)
int   Atom_Length         (int atom)
Bool  Atom_Needs_Quote    (int atom)
Bool  Atom_Needs_Scan     (int atom)
Bool  Is_Valid_Atom       (int atom)
int   Create_Atom         (char *str)
int   Create_Allocate_Atom(char *str)
int   Find_Atom           (char *str)
int   atom_char[256]
int   atom_nil
int   atom_false
int   atom_true
int   atom_end_of_file
\end{verbatim}
\end{Indentation}

The macro \texttt{Atom\_Name(atom)} returns the internal string of
\texttt{atom} (this string should not be modified). The function
\texttt{Atom\_Lengh(atom)} returns the length (of the name) of \texttt{atom}.

The function \texttt{Atom\_Needs\_Scan(atom)} indicates if the canonical form
of \texttt{atom} needs to be quoted as done by \IdxPB{writeq/2}
\RefSP{write-term/3}. In that case \texttt{Atom\_Needs\_Scan(atom)}
indicates if this simply comes down to write quotes around the name of
\texttt{atom} or if it necessary to scan each character of the name because
there are some non-printable characters (or included quote characters). The
function \texttt{Is\_Valid\_Atom(atom)} is true only if \texttt{atom} is the
internal key of an existing atom.

The function \texttt{Create\_Atom(str)} adds a new atom whose name is the
content of \texttt{str} to the system and returns its internal key. If the
atom already exists its key is simply returned. The string \texttt{str}
passed to the function should not be modified later. The function
\texttt{Create\_Allocate\_Atom(str)} is provided when this condition cannot
be ensured. It simply makes a dynamic copy of \texttt{str}. 

The function \texttt{Find\_Atom(str)} returns the internal key of the
atom whose name is \texttt{str} or \texttt{-1} if does not exist.

All atoms corresponding to a single character already exist and their
key can be obtained via the global array \texttt{atom\_char[]}.  For
instance \texttt{atom\_char['.']} is the atom associated to
\texttt{'.'} (this atom is the functor of lists). The other variables
correspond to the internal key of frequently used atoms: \texttt{[]},
\texttt{false}, \texttt{true} and
\texttt{end\_of\_file}.

\subsubsection{Reading Prolog terms}
\label{Reading-Prolog-terms}
The name of all functions presented here are of the form
\texttt{Rd\_\Param{Name}\_Check()}. They all check the validity of the
Prolog term to read emitting appropriate errors if necessary. Each function
has a check-free version called \texttt{Rd\_\Param{Name}()}.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is a read function (used by the
interface when an input argument is provided):

\begin{Indentation}
\begin{verbatim}
int     Rd_Integer_Check  (PlTerm term)
int     Rd_Positive_Check (PlTerm term)
double  Rd_Float_Check    (PlTerm term)
double  Rd_Number_Check   (PlTerm term)
int     Rd_Atom_Check     (PlTerm term)
int     Rd_Boolean_Check  (PlTerm term)
int     Rd_Char_Check     (PlTerm term)
int     Rd_In_Char_Check  (PlTerm term)
int     Rd_Code_Check     (PlTerm term)
int     Rd_In_Code_Check  (PlTerm term)
int     Rd_Byte_Check     (PlTerm term)
int     Rd_In_Byte_Check  (PlTerm term)
char   *Rd_String_Check   (PlTerm term)
char   *Rd_Chars_Check    (PlTerm term)
char   *Rd_Codes_Check    (PlTerm term)
int     Rd_Chars_Str_Check(PlTerm term, char *str)
int     Rd_Codes_Str_Check(PlTerm term, char *str)
\end{verbatim}
\end{Indentation}

All functions returning a C string (\texttt{char *}) use a same buffer. The
function \texttt{Rd\_Chars\_Str\_Check()} is similar to
\texttt{Rd\_Chars\_Check()} but accepts as argument a string to store the
result and returns the length of that string (which is also the length of
the Prolog list). Similarly for \texttt{Rd\_Codes\_Str\_Check()}.

\SPart{Complex terms}: the following functions return the sub-arguments
(terms) of complex terms as an array of \texttt{PlTerm} except
\texttt{Rd\_Proper\_List\_Check()} which returns the size of the list read
(and initializes the array \texttt{element}). Refer to the introduction of
this section for more information about the arguments of complex functions
\RefSP{Introduction:(Manipulating-Prolog-terms)}.

\begin{Indentation}
\begin{verbatim}
int     Rd_Proper_List_Check(PlTerm term, PlTerm *arg)
PlTerm *Rd_List_Check       (PlTerm term)
PlTerm *Rd_Compound_Check   (PlTerm term, int *functor, int *arity)
PlTerm *Rd_Callable_Check   (PlTerm term, int *functor, int *arity)
\end{verbatim}
\end{Indentation}

\subsubsection{Unifying Prolog terms}
The name of all functions presented here are of the form
\texttt{Un\_\Param{Name}\_Check()}. They all check the validity of the
Prolog term to unify emitting appropriate errors if necessary. Each function
has a check-free version called \texttt{Un\_\Param{Name}()}.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is an unify function (used by the
interface when an output argument is provided):

\begin{Indentation}
\begin{verbatim}
Bool Un_Integer_Check (int n,     PlTerm term)
Bool Un_Positive_Check(int n,     PlTerm term)
Bool Un_Float_Check   (double n,  PlTerm term)
Bool Un_Number_Check  (double n,  PlTerm term)
Bool Un_Atom_Check    (int atom,  PlTerm term)
Bool Un_Boolean_Check (int b,     PlTerm term)
Bool Un_Char_Check    (int c,     PlTerm term)
Bool Un_In_Char_Check (int c,     PlTerm term)
Bool Un_Code_Check    (int c,     PlTerm term)
Bool Un_In_Code_Check (int c,     PlTerm term)
Bool Un_Byte_Check    (int b,     PlTerm term)
Bool Un_In_Byte_Check (int b,     PlTerm term)
Bool Un_String_Check  (char *str, PlTerm term)
Bool Un_Chars_Check   (char *str, PlTerm term)
Bool Un_Codes_Check   (char *str, PlTerm term)
\end{verbatim}
\end{Indentation}

The function \texttt{Un\_Number\_Check(n, term)} unifies \texttt{term} with
an integer if \texttt{n} is an integer, with a floating point number
otherwise. The function \texttt{Un\_String\_Check(str, term)} creates the
atom corresponding to \texttt{str} and then unifies term with it (same as
\texttt{Un\_Atom\_Check(Create\_Allocate\_Atom(str), term)}).

\SPart{Complex terms}: the following functions accept the sub-arguments
(terms) of complex terms as an array of \texttt{PlTerm}. Refer to the
introduction of this section for more information about the arguments of
complex functions \RefSP{Introduction:(Manipulating-Prolog-terms)}.

\begin{Indentation}
\begin{verbatim}
Bool Un_Proper_List_Check(int size, PlTerm *arg, PlTerm term)
Bool Un_List_Check       (PlTerm *arg, PlTerm term)
Bool Un_Compound_Check   (int functor, int arity, PlTerm *arg,
                          PlTerm term)
Bool Un_Callable_Check   (int functor, int arity, PlTerm *arg,
                          PlTerm term)
\end{verbatim}
\end{Indentation}

All these functions check the type of the term to unify and return the
result of the unification. Generally if an unification fails the C function
returns \texttt{FALSE} to enforce a failure. However if there are several
arguments to unify and if an unification fails then the C function returns
\texttt{FALSE} and the type of other arguments has not been checked.
Normally all error cases are tested before doing any work to be sure that
the predicate fails/succeeds only if no error condition is satisfied. So a
good method is to check if the validity of all arguments to unify and later
to do the unification (using check-free functions). Obviously if there is
only one to unify it is more efficient to use a unify function checking the
argument. For the other cases the interface provides a set of functions to
check the type of a term.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is check-for-unification function (used
by the interface when an output argument is provided):

\begin{Indentation}
\begin{verbatim}
void Check_For_Un_Integer (PlTerm term)
void Check_For_Un_Positive(PlTerm term)
void Check_For_Un_Float   (PlTerm term)
void Check_For_Un_Number  (PlTerm term)
void Check_For_Un_Atom    (PlTerm term)
void Check_For_Un_Boolean (PlTerm term)
void Check_For_Un_Char    (PlTerm term)
void Check_For_Un_In_Char (PlTerm term)
void Check_For_Un_Code    (PlTerm term)
void Check_For_Un_In_Code (PlTerm term)
void Check_For_Un_Byte    (PlTerm term)
void Check_For_Un_In_Byte (PlTerm term)
void Check_For_Un_String  (PlTerm term)
void Check_For_Un_Chars   (PlTerm term)
void Check_For_Un_Codes   (PlTerm term)
\end{verbatim}
\end{Indentation}

\SPart{Complex terms}: the following functions check the validity of
complex terms:

\begin{Indentation}
\begin{verbatim}
void Check_For_Un_List    (PlTerm term)
void Check_For_Un_Compound(PlTerm term)
void Check_For_Un_Callable(PlTerm term)
void Check_For_Un_Variable(PlTerm term)
\end{verbatim}
\end{Indentation}

The function \texttt{Check\_For\_Un\_List(term)} checks if \texttt{term} can
be unified with a list. This test is done for the entire list (not only for
the functor/arity of \texttt{term} but also recursively on the tail of the
list). The function \texttt{Check\_For\_Un\_Variable(term)} ensures that
\texttt{term} is not currently instantiated. These functions can be defined
using functions to test the type of a Prolog term \RefSP{Testing-the-type-of-Prolog-terms} and functions to raise Prolog errors \RefSP{Raising-Prolog-errors}. For instance \texttt{Check\_For\_Un\_List(term)} is defined
as follows:

\begin{Indentation}
\begin{verbatim}
void Check_For_Un_List(PlTerm term)
{
 if (!Blt_List_Or_Partial_List(term))
     Pl_Err_Type(type_list, term);
}
\end{verbatim}
\end{Indentation}

\subsubsection{Creating Prolog terms}
These functions are provided to creates Prolog terms. Each function returns
a \texttt{PlTerm} containing the created term.

\SPart{Simple foreign types}: for each simple foreign type
\RefSP{foreign/2-directive} there is a creation function:

\begin{Indentation}
\begin{verbatim}
PlTerm Mk_Integer (int n)
PlTerm Mk_Positive(int n)
PlTerm Mk_Float   (double n)
PlTerm Mk_Number  (double n)
PlTerm Mk_Atom    (int atom)
PlTerm Mk_Boolean (int b)
PlTerm Mk_Char    (int c)
PlTerm Mk_In_Char (int c)
PlTerm Mk_Code    (int c)
PlTerm Mk_In_Code (int c)
PlTerm Mk_Byte    (int b)
PlTerm Mk_In_Byte (int b)
PlTerm Mk_String  (char *str)
PlTerm Mk_Chars   (char *str)
PlTerm Mk_Codes   (char *str)
\end{verbatim}
\end{Indentation}

The function \texttt{Mk\_Number(n, term)} initializes \texttt{term} with an
integer if \texttt{n} is an integer, with a floating point number otherwise.
The function \texttt{Mk\_String(str)} first creates an atom corresponding to
\texttt{str} and then returns that Prolog atom (i.e. equivalent to
\texttt{Mk\_Atom(Create\_Allocate\_Atom(str))}).

\SPart{Complex terms}: the following functions accept the sub-arguments
(terms) of complex terms as an array of \texttt{PlTerm}. Refer to the
introduction of this section for more information about the arguments of
complex functions \RefSP{Introduction:(Manipulating-Prolog-terms)}.

\begin{Indentation}
\begin{verbatim}
PlTerm Mk_Proper_List(int size, PlTerm *arg)
PlTerm Mk_List       (PlTerm *arg)
PlTerm Mk_Compound   (int functor, int arity, PlTerm *arg)
PlTerm Mk_Callable   (int functor, int arity, PlTerm *arg)
\end{verbatim}
\end{Indentation}

\subsubsection{Testing the type of Prolog terms}
\label{Testing-the-type-of-Prolog-terms}
The following functions test the type of a Prolog term. Each function
corresponds to a type testing built-in predicate \RefSP{var/1}.

\begin{Indentation}
\begin{verbatim}
Bool Blt_Var                 (PlTerm term)
Bool Blt_Non_Var             (PlTerm term)
Bool Blt_Atom                (PlTerm term)
Bool Blt_Integer             (PlTerm term)
Bool Blt_Float               (PlTerm term)
Bool Blt_Number              (PlTerm term)
Bool Blt_Atomic              (PlTerm term)
Bool Blt_Compound            (PlTerm term)
Bool Blt_Callable            (PlTerm term)
Bool Blt_List                (PlTerm term)
Bool Blt_Partial_List        (PlTerm term)
Bool Blt_List_Or_Partial_List(PlTerm term)
Bool Blt_Fd_Var              (PlTerm term)
Bool Blt_Non_Fd_Var          (PlTerm term)
Bool Blt_Generic_Var         (PlTerm term)
Bool Blt_Non_Generic_Var     (PlTerm term)
int  Type_Of_Term            (PlTerm term)
int  List_Length             (PlTerm list)
\end{verbatim}
\end{Indentation}

The function \texttt{Type\_Of\_Term(term)} returns the type of
\texttt{term}, the following constants can be used to test this type (e.g.
in a \texttt{switch} instruction):

\begin{itemize}
\item \texttt{PLV}: Prolog variable.

\item \texttt{FDV}: finite domain variable.

\item \texttt{INT}: integer.

\item \texttt{FLT}: floating point number.

\item \texttt{ATM}: atom.

\item \texttt{LST}: list.

\item \texttt{STC}: structure
\end{itemize}

The tag \texttt{LST} means a term whose principal functor is \texttt{'.'}
and whose arity is 2 (recall that the empty list is the atom \texttt{[]}).
The tag \texttt{STC} means any other compound term.

The function \texttt{List\_Length(list)} returns the number of elements of
the \texttt{list} (\texttt{0} for the empty list). If list is not a list
this function returns \texttt{-1}.

\subsubsection{Comparing Prolog terms}
The following functions compares Prolog terms. Each function corresponds to
a comparison built-in predicate \RefSP{(==)/2}.

\begin{Indentation}
\begin{verbatim}
Bool Blt_Term_Eq (PlTerm term1, PlTerm term2)
Bool Blt_Term_Neq(PlTerm term1, PlTerm term2)
Bool Blt_Term_Lt (PlTerm term1, PlTerm term2)
Bool Blt_Term_Lte(PlTerm term1, PlTerm term2)
Bool Blt_Term_Gt (PlTerm term1, PlTerm term2)
Bool Blt_Term_Gte(PlTerm term1, PlTerm term2)
\end{verbatim}
\end{Indentation}

All these functions are based on a general comparison function returning a
negative integer if \texttt{term1} is less than \texttt{term2}, 0 if they
are equal and a positive integer otherwise:

\begin{Indentation}
\begin{verbatim}
int Term_Compare(PlTerm term1, PlTerm term2)
\end{verbatim}
\end{Indentation}

\subsubsection{Copying Prolog terms}
The following functions make a copy of a Prolog term:

\begin{Indentation}
\begin{verbatim}
void Copy_Term           (PlTerm *dst_adr, PlTerm *src_adr)
void Copy_Contiguous_Term(PlTerm *dst_adr, PlTerm *src_adr)
int  Term_Size           (PlTerm term)
\end{verbatim}
\end{Indentation}

The function \texttt{Copy\_Term(dst\_adr, src\_adr)} makes a copy of the
term located at \texttt{src\_adr} and stores it from the address given by
\texttt{dst\_adr}. The result is a contiguous term. If it can be ensured
that the source term is a contiguous term (i.e. result of a previous copy)
the function \texttt{Copy\_Contiguous\_Term()} can be used instead (it is
faster). In any case, sufficient space should be available for the copy
(i.e. from \texttt{dst\_adr}). The function \texttt{Term\_Size(term)}
returns the number of \texttt{PlTerm} needed by \texttt{term}.

\subsubsection{Comparing and evaluating arithmetic expressions}
The following functions compare arithmetic expressions. Each function
corresponds to a comparison built-in predicate \RefSP{(=:=)/2}.

\begin{Indentation}
\begin{verbatim}
Bool Blt_Eq (PlTerm expr1, PlTerm expr2)
Bool Blt_Neq(PlTerm expr1, PlTerm expr2)
Bool Blt_Lt (PlTerm expr1, PlTerm expr2)
Bool Blt_Lte(PlTerm expr1, PlTerm expr2)
Bool Blt_Gt (PlTerm expr1, PlTerm expr2)
Bool Blt_Gte(PlTerm expr1, PlTerm expr2)
\end{verbatim}
\end{Indentation}

The following function evaluates the expression \texttt{expr} and stores its
result as a Prolog number (integer or floating point number) in
\texttt{result}:

\begin{Indentation}
\begin{verbatim}
void Math_Load_Value(PlTerm expr, PlTerm *result)
\end{verbatim}
\end{Indentation}

This function can be followed by a read function \RefSP{Reading-Prolog-terms} to obtain the result.

\subsection{Raising Prolog errors}
\label{Raising-Prolog-errors}
The following functions allows a C function to raise a Prolog error. Refer
to the section concerning Prolog errors for more information about the
effect of raising an error \RefSP{Errors}.

\subsubsection{Managing the error context}
When one of the following error function is invoked it refers to the
implicit error context \RefSP{General-format-and-error-context}. This
context indicates the name and the arity of the concerned predicate. When
using a \texttt{foreign/2} declaration this context is set by default to the
name and arity of the associated Prolog predicate. This can be controlled
using the \IdxPO{bip\_name} option \RefSP{foreign/2-directive}. In any
case, the following functions can also be used to modify this context:

\begin{Indentation}
\begin{verbatim}
void Set_C_Bip_Name  (char *functor, int arity)
void Unset_C_Bip_Name(void)
\end{verbatim}
\end{Indentation}

The function \texttt{Set\_C\_Bip\_Name(functor, arity)} initializes the
context of the error with \texttt{functor} and \texttt{arity} (if
\texttt{arity}$<$0 only \texttt{functor} is significant). The function
\texttt{Unset\_C\_Bip\_Name()} removes such an initialization (the context
is then reset to the last \texttt{Functor}/\texttt{Arity} set by a call to
\IdxPB{set\_bip\_name/2} \RefSP{set-bip-name/2}. This is useful when
writing a C routine to define a context for errors occurring in this routine
and, before exiting to restore the previous context.

\subsubsection{Instantiation error}
The following function raises an instantiation error \RefSP{Instantiation-error}:

\OneLine{void Pl\_Err\_Instantiation(void)}

\subsubsection{Type error}
The following function raises a type error \RefSP{Type-error}:

\OneLine{void Pl\_Err\_Type(int atom\_type, PlTerm culprit)}

\texttt{atom\_type} is (the internal key of) the atom associated to the
expected type. For each type name \Param{T} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{type\_\Param{T}}. \texttt{culprit} is the argument which
caused the error.

\SPart{Example}: \texttt{x} is an atom while an integer was expected:
\texttt{Pl\_Err\_Type(type\_integer, x)}.

\subsubsection{Domain error}
The following function raises a domain error \RefSP{Domain-error}:

\OneLine{void Pl\_Err\_Domain(int atom\_domain, PlTerm culprit)}

\texttt{atom\_domain} is (the internal key of) the atom associated to the
expected domain. For each domain name \Param{D} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{domain\_\Param{D}}. \texttt{culprit} is the argument which
caused the error.

\SPart{Example}: \texttt{x} is $<$ 0 but should be $\geq$ 0:
\texttt{Pl\_Err\_Domain(domain\_not\_less\_than\_zero, x)}.

\subsubsection{Existence error}
The following function raises an existence error \RefSP{Existence-error}:

\OneLine{void Pl\_Err\_Existence(int atom\_object, PlTerm culprit)}

\texttt{atom\_object} is (the internal key of) the atom associated to the
type of the object. For each object name \Param{O} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{existence\_\Param{O}}. \texttt{culprit} is the argument
which caused the error.

\SPart{Example}: \texttt{x} does not refer to an existing source:
\texttt{Pl\_Err\_Existence(existence\_source\_sink, x)}.

\subsubsection{Permission error}
The following function raises a permission error \RefSP{Permission-error}:

\OneLine{void Pl\_Err\_Permission(int atom\_operation, int atom\_permission,
PlTerm culprit)}

\texttt{atom\_operation} is (the internal key of) the atom associated to the
operation which caused the error. For each operation name
\Param{O} there is a corresponding predefined atom stored in a
global variable whose name is of the form
\texttt{permission\_operation\_\Param{O}}. \texttt{atom\_permission} is
(the internal key of) the atom associated to the tried permission. For each
permission name \Param{P} there is a corresponding predefined atom
stored in a global variable whose name is of the form
\texttt{permission\_type\_\Param{P}}. \texttt{culprit} is the argument
which caused the error.

\SPart{Example}: reading from an output stream \texttt{x}:
\texttt{Pl\_Err\_Permission(permission\_operation\_input, \\
permission\_type\_stream, x)}.

\subsubsection{Representation error}
The following function raises a representation error \RefSP{Representation-error}:

\OneLine{void Pl\_Err\_Representation(int atom\_limit)}

\texttt{atom\_limit} is (the internal key of) the atom associated to the
reached limit. For each limit name \Param{L} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{representation\_\Param{L}}.

\SPart{Example}: an arity too big occurs:
\texttt{Pl\_Err\_Representation(representation\_max\_arity)}.

\subsubsection{Evaluation error}
The following function raises an evaluation error \RefSP{Evaluation-error}:

\OneLine{void Pl\_Err\_Evaluation(int atom\_error)}

\texttt{atom\_error} is (the internal key of) the atom associated to the
error. For each evaluation error name \Param{E} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{evaluation\_\Param{E}}.

\SPart{Example}: a division by zero occurs:
\texttt{Pl\_Err\_Evaluation(evluation\_zero\_divisor)}.

\subsubsection{Resource error}
The following function raises a resource error \RefSP{Resource-error}:

\OneLine{void Pl\_Err\_Resource(int atom\_resource)}

\texttt{atom\_resource} is (the internal key of) the atom associated to the
resource. For each resource error name \Param{R} there is a
corresponding predefined atom stored in a global variable whose name is of
the form \texttt{resource\_\Param{R}}.

\SPart{Example}: too many open streams:
\texttt{Pl\_Err\_Resource(resource\_too\_many\_open\_streams)}.

\subsubsection{Syntax error}
The following function raises a syntax error \RefSP{Syntax-error}:

\OneLine{void Pl\_Err\_Syntax(int atom\_error)}

\texttt{atom\_error} is (the internal key of) the atom associated to the
error. There is no predefined syntax error atoms. 

\SPart{Example}: a \texttt{/} is expected:
\texttt{Pl\_Err\_Syntax(Create\_Atom("/ expected"))}.

The following function emits a syntax error according to the value of the
\IdxPF{syntax\_error} \Idx{Prolog flag} \RefSP{set-prolog-flag/2}. This
function can then return (if the value of the flag is either
\texttt{warning} or \texttt{fail}). In that case the calling function should
fail (e.g. returning \texttt{FALSE}). This function accepts a file name (the
empty string C \texttt{""} can be passed), a line and column number and an
error message string. Using this function makes it possible to further call
the built-in predicate \IdxPB{syntax\_error\_info/4}
\RefSP{syntax-error-info/4}:

\OneLine{void Emit\_Syntax\_Error(char *file\_name, int line, int column,
char *message)}

\SPart{Example}: a \texttt{/} is expected:
\texttt{Emit\_Syntax\_Error("data", 10, 30, "/ expected")}.

\subsubsection{System error}
The following function raises a system error (4.3.11, page *):

\OneLine{void Pl\_Err\_System(int atom\_error)}

\texttt{atom\_error} is (the internal key of) the atom associated to the
error. There is no predefined system error atoms. 

\SPart{Example}: an invalid pathname is given:
\texttt{Pl\_Err\_System(Create\_Atom("invalid path name"))}.

The following function emits a system error associated to an operating
system error according to the value of the \IdxPF{os\_error}
\Idx{Prolog flag} \RefSP{set-prolog-flag/2}. This function can then return (if the value of the flag is either \texttt{warning} or \texttt{fail}).
In that case the calling function should fail (e.g. returning
\texttt{FALSE}). This function uses the value of the \texttt{errno} C
library variable:

\OneLine{void Os\_Error(void)}

\SPart{Example}: a call to the C Unix function \texttt{chdir(3)} returns
\texttt{-1}: \texttt{Os\_Error()}.

\subsection{Calling Prolog from C}

\subsubsection{Introduction}
The following functions allows a C function to call a Prolog predicate:

\begin{Indentation}
\begin{verbatim}
int    Pl_Query_Start        (int functor, int arity, PlTerm *arg,
                              Bool recoverable)
int    Pl_Query_Next_Solution(void)
void   Pl_Query_End          (int op)
PlTerm Pl_Get_Exception      (void)
void   Pl_Exec_Continuation  (int functor, int arity, PlTerm *arg)
\end{verbatim}
\end{Indentation}

The invocation of a Prolog predicate should be done as follows:

\begin{itemize}

\item open a query using \texttt{Pl\_Query\_Start()} (computes the first
solution)

\item eventually compute next solutions using
\texttt{Pl\_Query\_Next\_Solution()}

\item close the query using \texttt{Pl\_Query\_End()}

\end{itemize}

The function \texttt{Pl\_Query\_Start(functor, arity, arg, recoverable)} is
used to initialize a query (computes the first solution). The arguments
\texttt{functor}, \texttt{arity} and \texttt{arg} are similar to those of
the functions handling complex terms \RefSP{Introduction:(Manipulating-Prolog-terms)}. The argument \texttt{recoverable} shall be set to
\texttt{TRUE} if the user wants to recover, at the end of the query, the
memory space consumed by the query (in that case an additional choice-point
is created). This functions returns:

\begin{itemize}

\item \texttt{PL\_FAILURE} (a constant equal to \texttt{FALSE}, i.e. 0) if
the query fails.

\item \texttt{PL\_SUCCESS} (a constant equal to \texttt{TRUE}, i.e. 1) in
case of success. In that case the argument array \texttt{arg} can be used to
obtain the unification performed by the query.

\item \texttt{PL\_EXCEPTION} (a constant equal to 2). In that case function
\texttt{Pl\_Get\_Exception()} can be used to obtained the exceptional term
raised by \IdxPB{throw/1} \RefSP{catch/3}.

\end{itemize}

The function \texttt{Pl\_Query\_Next\_Solution()} is used to compute a new
solution. It must be only used if the result of the previous solution was
\texttt{PL\_SUCCESS}. This functions returns the same kind of values as
\texttt{Pl\_Query\_Start()} (see above).

The function \texttt{Pl\_Query\_End(op)} is used to finish a query. This
function mainly manages the remaining alternatives of the query. However,
even if the query has no alternatives this function must be used to
correctly finish the query. The value of \texttt{op} is:

\begin{itemize}

\item \texttt{PL\_RECOVER}: to recover the memory space consumed by the
query. After that the state of Prolog stacks is exactly the same as before
opening the query. To use this option the query must have been opened
specifying \texttt{TRUE} for \texttt{recoverable} (see above).

\item \texttt{PL\_CUT}: to cut remaining alternatives. The effect of this
option is similar to a cut after the query.

\item \texttt{PL\_KEEP\_FOR\_PROLOG}: to keep the alternatives for Prolog.
This is useful when the query was invoked in a foreign C function. In that
case, when the predicate corresponding to the C foreign function is invoked
a query is executed and the remaining alternatives are then available as
alternatives of that predicate.

\end{itemize}

Note that several queries can be nested since a stack of queries is
maintained. For instance, it is possible to call a query and before
terminating it to call another query. In that case the first execution of
\texttt{Pl\_Query\_End()} will finish the second query (i.e. the inner) and
the next execution of \texttt{Pl\_Query\_End()} will finish the first query.

Finally, the function \texttt{Pl\_Exec\_Continuation(functor, arity,
arg)} replaces the current calculus by the execution of the specified
predicate. The arguments \texttt{functor}, \texttt{arity} and
\texttt{arg} are similar to those of the functions handling complex
terms \RefSP{Introduction:(Manipulating-Prolog-terms)}.

\subsubsection{Example: \texttt{my\_call/1} - a \texttt{call/1} clone}

We here define a predicate \texttt{my\_call(Goal)} which acts like
\texttt{call(Goal)} except that we do not handle exceptions (if an exception
occurs the goal simply fails):

In the prolog file \texttt{prog.pl}:

\OneLine{:- foreign(my\_call(term)).}

In the C file \texttt{utils.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include "gprolog.h"

Bool my_call(PlTerm goal)

{
 PlTerm *arg;
 int     functor, arity;
 int     result;

 arg=Rd_Callable_Check(goal, &functor, &arity);
 result=Pl_Query_Start(functor, arity, arg, FALSE);
 Pl_Query_End(PL_KEEP_FOR_PROLOG);
 return (result==PL_SUCCESS);
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{prog}:

\OneLine{\% gplc prog.pl utils.c}

Examples of use:

\begin{CodeTwoCols}
\One{| ?- my\_call(write(hello)).}
\One{hello}
\SkipLine
\One{| ?- my\_call(for(X,1,3)).}
\SkipLine
\Two{X = 1 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 2 ?}{(here the user presses \texttt{;} to compute another solution)}
\SkipLine
\Two{X = 3}{(here the user is not prompted since there is no more alternative)}
\SkipLine
\One{| ?- my\_call(1).}
\One{{\lb}exception:~error(type\_error(callable,1),my\_call/1){\rb}}
\SkipLine
\One{| ?- my\_call(call(1)).}
\SkipLine
\One{no}
\end{CodeTwoCols}

When \texttt{my\_call(1)} is called an error is raised due to the use of
\texttt{Rd\_Callable\_Check()}. However the error raised by
\texttt{my\_call(call(1))} is ignored and \texttt{FALSE} (i.e. a failure) is
returned by the foreign function. 

To really simulate the behavior of \texttt{call/1} when an exception
is recovered it should be re-raised to be captured by an earlier
handler. The idea is then to execute a \texttt{throw/1} as the
continuation. This is what it is done by the following code:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include "gprolog.h"

Bool my_call(PlTerm goal)

{
 PlTerm *arg;
 int     functor, arity;
 int     result;

 arg=Rd_Callable_Check(goal, &functor, &arity);
 result=Pl_Query_Start(functor, arity, arg, FALSE);
 Pl_Query_End(PL_KEEP_FOR_PROLOG);
 if (result==PL_EXCEPTION)
    {
     PlTerm except=Pl_Get_Exception();
     Pl_Exec_Continuation(Find_Atom("throw"),1,&except);
    }
 return (result==PL_SUCCESS);
}
\end{verbatim}
\end{Indentation}

The following code propagates the error raised by \texttt{call/1}.

\begin{CodeTwoCols}
\One{| ?- my\_call(call(1)).}
\One{{\lb}exception:~error(type\_error(callable,1),my\_call/1){\rb}}
\end{CodeTwoCols}

Finally note that a simpler way to define \texttt{my\_call/1} is to use 
\texttt{Pl\_Exec\_Continuation()} as follows:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include "gprolog.h"

Bool my_call(PlTerm goal)

{
 PlTerm *args;
 int    functor,arity;

 args=Rd_Callable_Check(goal, &functor, &arity);
 Pl_Exec_Continuation(functor, arity, args);
 return TRUE;
}
\end{verbatim}
\end{Indentation}

\subsubsection{Example: recovering the list of all operators}

We here define a predicate \texttt{all\_op(List)} which unifies
\texttt{List} with the list of all currently defined operators as would be done by: \texttt{findall(X,current\_op(\_,\_,X),List)}.

In the prolog file \texttt{prog.pl}:

\OneLine{:- foreign(all\_op(term)).}

In the C file \texttt{utils.c}:

\begin{Indentation}
\begin{verbatim}
#include <string.h>
#include "gprolog.h"

Bool all_op(PlTerm list)

{
 PlTerm op[1024];
 PlTerm args[3];
 int    n=0;
 int    result;

 args[0]=Mk_Variable();
 args[1]=Mk_Variable();
 args[2]=Mk_Variable();
 result=Pl_Query_Start(Find_Atom("current_op"), 3, args, TRUE);
 while(result)
    {
     op[n++]=Mk_Atom(Rd_Atom(args[2])); /* arg #2 is the name of the op */
     result=Pl_Query_Next_Solution();
    }
 Pl_Query_End(PL_RECOVER);

 return Un_Proper_List_Check(n, op, list);
}
\end{verbatim}
\end{Indentation}

Note that we know here that there is no source for exception. In that
case the result of \texttt{Pl\_Query\_Start} and \texttt{Pl\_Query\_End} can
be considered as a boolean.

The compilation produces an executable called
\texttt{prog}:

\OneLine{\% gplc prog.pl utils.c}

Example of use:

\begin{Indentation}
\begin{verbatim}
| ?- all_op(L).

L = [:-,:-,\=,=:=,#>=,#<#,@>=,-->,mod,#>=#,**,*,+,+,',',...]

| ?- findall(X,current_op(_,_,X),L).

L = [:-,:-,\=,=:=,#>=,#<#,@>=,-->,mod,#>=#,**,*,+,+,',',...]
\end{verbatim}
\end{Indentation}


\subsection{Defining a new C \texttt{main()} function}

GNU Prolog allows the user to define his own \texttt{main()}
function. This can be useful to perform several tasks before starting
the Prolog engine. To do this simply define a classical
\texttt{main(argc, argv)} function. The following functions can then be used:

\begin{Indentation}
\begin{verbatim}
int  Start_Prolog         (int argc, char *argv[])
void Stop_Prolog          (void)
void Reset_Prolog         (void)
Bool Try_Execute_Top_Level(void)
\end{verbatim}
\end{Indentation}

The function \texttt{Start\_Prolog(argc, argv)} initializes the Prolog engine
(\texttt{argc} and \texttt{argv} are the command-line variables). 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}. The function returns the number of user
directives (i.e. \texttt{initialization/1}) executed. This function mst be
called only once.

The function \texttt{Stop\_Prolog()} stops the Prolog engine. This function
must be called only once after all Prolog treatment have been done.

The function \texttt{Reset\_Prolog()} reinitializes the Prolog engine
(i.e. reset all Prolog stacks).

The function \texttt{Try\_Execute\_Top\_Level()} executes the
\Idx{top-level} if linked \RefSP{Using-the-compiler} and returns
\texttt{TRUE}. If the top-level is not present the functions returns
\texttt{FALSE}.

Here is the definition of the default GNU Prolog \texttt{main()} function:

\begin{Indentation}
\begin{verbatim}
int main(int argc, char *argv[])

{
 int  nb_user_directive;
 Bool top_level;

 nb_user_directive=Start_Prolog(argc, argv);

 top_level=Try_Execute_Top_Level();

 Stop_Prolog();

 if (top_level)
     return 0;

 if (nb_user_directive)
     return 0;

 printf("Warning: no initial goal executed\n"
        "   use a directive :- initialization(Goal)\n"
        "   or remove the link option --no-top-level"
        " (or --min-bips or --min-size)\n");

 return 1;
}
\end{verbatim}
\end{Indentation}

\subsubsection{Example: asking for ancestors}

In this example we use the following Prolog code (in a file called 
\texttt{prog.pl}):

\begin{Indentation}
\begin{verbatim}
parent(bob,   mary).
parent(jane,  mary).
parent(mary,  peter).
parent(paul,  peter).
parent(peter, john).

anc(X, Y):-
        parent(X, Y).

anc(X, Z) :-
        parent(X, Y),
        anc(Y, Z).
\end{verbatim}
\end{Indentation}

The following \texttt{main()} function asks for the name of a person and
displays all successors of that person (this is equivalent to the Prolog
query: \texttt{anc(Result, Name)}).

\begin{Indentation}
\begin{verbatim}
int main(int argc, char *argv[])

{
 int     func;
 WamWord arg[10];
 char    str[100];
 char   *sol[100];
 int     i,nb_sol=0;
 Bool    res;

 Start_Prolog(argc,argv);

 func=Find_Atom("anc");
 for(;;)
    {
     printf("\nEnter a name (or 'end' to finish): ");
     scanf("%s",str);

     if (strcmp(str, "end")==0)
         break;

     arg[0]=Mk_Variable();
     arg[1]=Mk_String(str);
     nb_sol=0;
     res=Pl_Query_Start(func, 2, arg, TRUE);
     while(res)
        {
         sol[nb_sol++]=Rd_String(arg[0]);
         res=Pl_Query_Next_Solution();
        }
     Pl_Query_End(PL_RECOVER);

     for(i=0;i<nb_sol;i++)
         printf("  solution: %s\n", sol[i]);
     printf("%d solution(s)\n", nb_sol);
    }

 Stop_Prolog();
 return 0;     
}
\end{verbatim}
\end{Indentation}

The compilation produces an executable called \texttt{prog}:

\OneLine{\% gplc prog.pl utils.c}

Examples of use:

\begin{Indentation}
\begin{verbatim}
Enter a name (or 'end' to finish): john
  solution: peter
  solution: bob
  solution: jane
  solution: mary
  solution: paul
5 solution(s)

Enter a name (or 'end' to finish): mary
  solution: bob
  solution: jane
2 solution(s)

Enter a name (or 'end' to finish): end
\end{verbatim}
\end{Indentation}

%HEVEA\cutend
