\input texinfo @c -*- mode: texinfo; coding: utf-8; -*- @documentencoding UTF-8 @c %**start of header @setfilename yap.info @setcontentsaftertitlepage @settitle YAP Prolog User's Manual @c For double-sided printing, uncomment: @c @setchapternewpage odd @c %**end of header @set VERSION 6.3.4 @set EDITION 4.2.9 @set UPDATED Oct 2010 @c Index for C-Prolog compatible predicate @defindex cy @c Index for predicates not in C-Prolog @defindex cn @c Index for predicates sort of (almost) in C-Prolog @defindex ca @c Index for SICStus Prolog compatible predicate @defindex sy @c Index for predicates not in SICStus Prolog @defindex sn @c Index for predicates sort of (almost) in SICStus Prolog @defindex sa @alias pl_example=example @alias c_example=example @setchapternewpage odd @c @smallbook @comment %** end of header @ifnottex @format @dircategory The YAP Prolog System @direntry * YAP: (yap). YAP Prolog User's Manual. @end direntry @end format @end ifnottex @titlepage @title YAP User's Manual @subtitle Version @value{VERSION} @author Vitor Santos Costa, @author Luís Damas, @author Rogério Reis @author Rúben Azevedo @page @vskip 2pc @copyright{} 1989-2014 L. Damas, V. Santos Costa and Universidade do Porto. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions. @end titlepage @ifnottex @node Top, , , (dir) @top YAP Prolog This file documents the YAP Prolog System version @value{VERSION}, a high-performance Prolog compiler developed at LIACC, Universidade do Porto. YAP is based on David H. D. Warren's WAM (Warren Abstract Machine), with several optimizations for better performance. YAP follows the Edinburgh tradition, and is largely compatible with DEC-10 Prolog, Quintus Prolog, and especially with C-Prolog. @ifplaintext @end ifplaintext Before describing in full detail how to interface to C code, we will examine a brief example. Assume the user requires a predicate @code{my_process_id(Id)} which succeeds when @var{Id} unifies with the number of the process under which YAP is running. In this case we will create a @code{my_process.c} file containing the C-code described below. @c_example @cartouche #include "YAP/YapInterface.h" static int my_process_id(void) @{ YAP_Term pid = YAP_MkIntTerm(getpid()); YAP_Term out = YAP_ARG1; return(YAP_Unify(out,pid)); @} void init_my_predicates() @{ YAP_UserCPredicate("my_process_id",my_process_id,1); @} @end cartouche @end c_example The commands to compile the above file depend on the operating system. Under Linux (i386 and Alpha) you should use: @example gcc -c -shared -fPIC my_process.c ld -shared -o my_process.so my_process.o @end example @noindent Under WIN32 in a MINGW/CYGWIN environment, using the standard installation path you should use: @example gcc -mno-cygwin -I "c:/Yap/include" -c my_process.c gcc -mno-cygwin "c:/Yap/bin/yap.dll" --shared -o my_process.dll my_process.o @end example @noindent Under WIN32 in a pure CYGWIN environment, using the standard installation path, you should use: @example gcc -I/usr/local -c my_process.c gcc -shared -o my_process.dll my_process.o /usr/local/bin/yap.dll @end example @noindent Under Solaris2 it is sufficient to use: @example gcc -fPIC -c my_process.c @end example @noindent Under SunOS it is sufficient to use: @example gcc -c my_process.c @end example @noindent Under Digital Unix you need to create a @code{so} file. Use: @example gcc tst.c -c -fpic ld my_process.o -o my_process.so -shared -expect_unresolved '*' @end example @noindent and replace my @code{process.so} for my @code{process.o} in the remainder of the example. @noindent And could be loaded, under YAP, by executing the following Prolog goal @example load_foreign_files(['my_process'],[],init_my_predicates). @end example Note that since YAP4.3.3 you should not give the suffix for object files. YAP will deduce the correct suffix from the operating system it is running under. After loading that file the following Prolog goal @example my_process_id(N) @end example @noindent would unify N with the number of the process under which YAP is running. Having presented a full example, we will now examine in more detail the contents of the C source code file presented above. The include statement is used to make available to the C source code the macros for the handling of Prolog terms and also some YAP public definitions. The function @code{my_process_id} is the implementation, in C, of the desired predicate. Note that it returns an integer denoting the success of failure of the goal and also that it has no arguments even though the predicate being defined has one. In fact the arguments of a Prolog predicate written in C are accessed through macros, defined in the include file, with names @var{YAP_ARG1}, @var{YAP_ARG2}, ..., @var{YAP_ARG16} or with @var{YAP_A}(@var{N}) where @var{N} is the argument number (starting with 1). In the present case the function uses just one local variable of type @code{YAP_Term}, the type used for holding YAP terms, where the integer returned by the standard unix function @code{getpid()} is stored as an integer term (the conversion is done by @code{YAP_MkIntTerm(Int))}. Then it calls the pre-defined routine @code{YAP_Unify(YAP_Term, YAP_Term)} which in turn returns an integer denoting success or failure of the unification. @findex YAP_UserCPredicate The role of the procedure @code{init_my_predicates} is to make known to YAP, by calling @code{YAP_UserCPredicate}, the predicates being defined in the file. This is in fact why, in the example above, @code{init_my_predicates} was passed as the third argument to @code{load_foreign_files/3}. The rest of this appendix describes exhaustively how to interface C to YAP. @menu * Manipulating Terms:: Primitives available to the C programmer * Unifying Terms:: How to Unify Two Prolog Terms * Manipulating Strings:: From character arrays to Lists of codes and back * Memory Allocation:: Stealing Memory From YAP * Controlling Streams:: Control How YAP sees Streams * Utility Functions:: From character arrays to Lists of codes and back * Calling YAP From C:: From C to YAP to C to YAP * Module Manipulation in C:: Create and Test Modules from within C * Miscellaneous C-Functions:: Other Helpful Interface Functions * Writing C:: Writing Predicates in C * Loading Objects:: Loading Object Files * Save&Rest:: Saving and Restoring * YAP4 Notes:: Changes in Foreign Predicates Interface @end menu @node Manipulating Terms, Unifying Terms, , C-Interface @section Terms This section provides information about the primitives available to the C programmer for manipulating Prolog terms. Several C typedefs are included in the header file @code{yap/YAPInterface.h} to describe, in a portable way, the C representation of Prolog terms. The user should write is programs using this macros to ensure portability of code across different versions of YAP. The more important typedef is @var{YAP_Term} which is used to denote the type of a Prolog term. Terms, from a point of view of the C-programmer, can be classified as follows @table @i @item uninstantiated variables @item instantiated variables @item integers @item floating-point numbers @item database references @item atoms @item pairs (lists) @item compound terms @end table The primitive @table @code @item YAP_Bool YAP_IsVarTerm(YAP_Term @var{t}) @findex YAP_IsVarTerm (C-Interface function) @noindent returns true iff its argument is an uninstantiated variable. Conversely the primitive @item YAP_Bool YAP_NonVarTerm(YAP_Term @var{t}) @findex YAP_IsNonVarTerm (C-Interface function) returns true iff its argument is not a variable. @end table @noindent The user can create a new uninstantiated variable using the primitive @table @code @item YAP_Term YAP_MkVarTerm() @end table The following primitives can be used to discriminate among the different types of non-variable terms: @table @code @item YAP_Bool YAP_IsIntTerm(YAP_Term @var{t}) @findex YAP_IsIntTerm (C-Interface function) @item YAP_Bool YAP_IsFloatTerm(YAP_Term @var{t}) @findex YAP_IsFloatTerm (C-Interface function) @item YAP_Bool YAP_IsDbRefTerm(YAP_Term @var{t}) @findex YAP_IsDBRefTerm (C-Interface function) @item YAP_Bool YAP_IsAtomTerm(YAP_Term @var{t}) @findex YAP_IsAtomTerm (C-Interface function) @item YAP_Bool YAP_IsPairTerm(YAP_Term @var{t}) @findex YAP_IsPairTerm (C-Interface function) @item YAP_Bool YAP_IsApplTerm(YAP_Term @var{t}) @findex YAP_IsApplTerm (C-Interface function) @item YAP_Bool YAP_IsCompoundTerm(YAP_Term @var{t}) @findex YAP_IsCompoundTerm (C-Interface function) @end table The next primitive gives the type of a Prolog term: @table @code @item YAP_tag_t YAP_TagOfTerm(YAP_Term @var{t}) @end table The set of possible values is an enumerated type, with the following values: @table @i @item @code{YAP_TAG_ATT}: an attributed variable @item @code{YAP_TAG_UNBOUND}: an unbound variable @item @code{YAP_TAG_REF}: a reference to a term @item @code{YAP_TAG_PAIR}: a list @item @code{YAP_TAG_ATOM}: an atom @item @code{YAP_TAG_INT}: a small integer @item @code{YAP_TAG_LONG_INT}: a word sized integer @item @code{YAP_TAG_BIG_INT}: a very large integer @item @code{YAP_TAG_RATIONAL}: a rational number @item @code{YAP_TAG_FLOAT}: a floating point number @item @code{YAP_TAG_OPAQUE}: an opaque term @item @code{YAP_TAG_APPL}: a compound term @end table Next, we mention the primitives that allow one to destruct and construct terms. All the above primitives ensure that their result is @i{dereferenced}, i.e. that it is not a pointer to another term. The following primitives are provided for creating an integer term from an integer and to access the value of an integer term. @table @code @item YAP_Term YAP_MkIntTerm(YAP_Int @var{i}) @findex YAP_MkIntTerm (C-Interface function) @item YAP_Int YAP_IntOfTerm(YAP_Term @var{t}) @findex YAP_IntOfTerm (C-Interface function) @end table @noindent where @code{YAP_Int} is a typedef for the C integer type appropriate for the machine or compiler in question (normally a long integer). The size of the allowed integers is implementation dependent but is always greater or equal to 24 bits: usually 32 bits on 32 bit machines, and 64 on 64 bit machines. The two following primitives play a similar role for floating-point terms @table @code @item YAP_Term YAP_MkFloatTerm(YAP_flt @var{double}) @findex YAP_MkFloatTerm (C-Interface function) @item YAP_flt YAP_FloatOfTerm(YAP_Term @var{t}) @findex YAP_FloatOfTerm (C-Interface function) @end table @noindent where @code{flt} is a typedef for the appropriate C floating point type, nowadays a @code{double} The following primitives are provided for verifying whether a term is a big int, creating a term from a big integer and to access the value of a big int from a term. @table @code @item YAP_Bool YAP_IsBigNumTerm(YAP_Term @var{t}) @findex YAP_IsBigNumTerm (C-Interface function) @item YAP_Term YAP_MkBigNumTerm(void *@var{b}) @findex YAP_MkBigNumTerm (C-Interface function) @item void *YAP_BigNumOfTerm(YAP_Term @var{t}, void *@var{b}) @findex YAP_BigNumOfTerm (C-Interface function) @end table @noindent YAP must support bignum for the configuration you are using (check the YAP configuration and setup). For now, YAP only supports the GNU GMP library, and @code{void *} will be a cast for @code{mpz_t}. Notice that @code{YAP_BigNumOfTerm} requires the number to be already initialised. As an example, we show how to print a bignum: @example static int p_print_bignum(void) @{ mpz_t mz; if (!YAP_IsBigNumTerm(YAP_ARG1)) return FALSE; mpz_init(mz); YAP_BigNumOfTerm(YAP_ARG1, mz); gmp_printf("Shows up as %Zd\n", mz); mpz_clear(mz); return TRUE; @} @end example Currently, no primitives are supplied to users for manipulating data base references. A special typedef @code{YAP_Atom} is provided to describe Prolog @i{atoms} (symbolic constants). The two following primitives can be used to manipulate atom terms @table @code @item YAP_Term YAP_MkAtomTerm(YAP_Atom at) @findex YAP_MkAtomTerm (C-Interface function) @item YAP_Atom YAP_AtomOfTerm(YAP_Term @var{t}) @findex YAP_AtomOfTerm (C-Interface function) @end table @noindent The following primitives are available for associating atoms with their names @table @code @item YAP_Atom YAP_LookupAtom(char * @var{s}) @findex YAP_LookupAtom (C-Interface function) @item YAP_Atom YAP_FullLookupAtom(char * @var{s}) @findex YAP_FullLookupAtom (C-Interface function) @item char *YAP_AtomName(YAP_Atom @var{t}) @findex YAP_AtomName (C-Interface function) @end table The function @code{YAP_LookupAtom} looks up an atom in the standard hash table. The function @code{YAP_FullLookupAtom} will also search if the atom had been "hidden": this is useful for system maintenance from C code. The functor @code{YAP_AtomName} returns a pointer to the string for the atom. @noindent The following primitives handle constructing atoms from strings with wide characters, and vice-versa: @table @code @item YAP_Atom YAP_LookupWideAtom(wchar_t * @var{s}) @findex YAP_LookupWideAtom (C-Interface function) @item wchar_t *YAP_WideAtomName(YAP_Atom @var{t}) @findex YAP_WideAtomName (C-Interface function) @end table @noindent The following primitive tells whether an atom needs wide atoms in its representation: @table @code @item int YAP_IsWideAtom(YAP_Atom @var{t}) @findex YAP_IsIsWideAtom (C-Interface function) @end table @noindent The following primitive can be used to obtain the size of an atom in a representation-independent way: @table @code @item int YAP_AtomNameLength(YAP_Atom @var{t}) @findex YAP_AtomNameLength (C-Interface function) @end table The next routines give users some control over the atom garbage collector. They allow the user to guarantee that an atom is not to be garbage collected (this is important if the atom is hold externally to the Prolog engine, allow it to be collected, and call a hook on garbage collection: @table @code @item int YAP_AtomGetHold(YAP_Atom @var{at}) @findex YAP_AtomGetHold (C-Interface function) @item int YAP_AtomReleaseHold(YAP_Atom @var{at}) @findex YAP_AtomReleaseHold (C-Interface function) @item int YAP_AGCRegisterHook(YAP_AGC_hook @var{f}) @findex YAP_AGCHook (C-Interface function) @end table A @i{pair} is a Prolog term which consists of a tuple of two Prolog terms designated as the @i{head} and the @i{tail} of the term. Pairs are most often used to build @emph{lists}. The following primitives can be used to manipulate pairs: @table @code @item YAP_Term YAP_MkPairTerm(YAP_Term @var{Head}, YAP_Term @var{Tail}) @findex YAP_MkPairTerm (C-Interface function) @item YAP_Term YAP_MkNewPairTerm(void) @findex YAP_MkNewPairTerm (C-Interface function) @item YAP_Term YAP_HeadOfTerm(YAP_Term @var{t}) @findex YAP_HeadOfTerm (C-Interface function) @item YAP_Term YAP_TailOfTerm(YAP_Term @var{t}) @findex YAP_TailOfTerm (C-Interface function) @item YAP_Term YAP_MkListFromTerms(YAP_Term *@var{pt}, YAP_Int *@var{sz}) @findex YAP_MkListFromTerms (C-Interface function) @end table One can construct a new pair from two terms, or one can just build a pair whose head and tail are new unbound variables. Finally, one can fetch the head or the tail. The last function supports the common operation of constructing a list from an array of terms of size @var{sz} in a simple sweep. Notice that the list constructors can call the garbage collector if there is not enough space in the global stack. A @i{compound} term consists of a @i{functor} and a sequence of terms with length equal to the @i{arity} of the functor. A functor, described in C by the typedef @code{Functor}, consists of an atom and of an integer. The following primitives were designed to manipulate compound terms and functors @table @code @item YAP_Term YAP_MkApplTerm(YAP_Functor @var{f}, unsigned long int @var{n}, YAP_Term[] @var{args}) @findex YAP_MkApplTerm (C-Interface function) @item YAP_Term YAP_MkNewApplTerm(YAP_Functor @var{f}, int @var{n}) @findex YAP_MkNewApplTerm (C-Interface function) @item YAP_Term YAP_ArgOfTerm(int argno,YAP_Term @var{ts}) @findex YAP_ArgOfTerm (C-Interface function) @item YAP_Term *YAP_ArgsOfTerm(YAP_Term @var{ts}) @findex YAP_ArgsOfTerm (C-Interface function) @item YAP_Functor YAP_FunctorOfTerm(YAP_Term @var{ts}) @findex YAP_FunctorOfTerm (C-Interface function) @end table @noindent The @code{YAP_MkApplTerm} function constructs a new term, with functor @var{f} (of arity @var{n}), and using an array @var{args} of @var{n} terms with @var{n} equal to the arity of the functor. @code{YAP_MkNewApplTerm} builds up a compound term whose arguments are unbound variables. @code{YAP_ArgOfTerm} gives an argument to a compound term. @code{argno} should be greater or equal to 1 and less or equal to the arity of the functor. @code{YAP_ArgsOfTerm} returns a pointer to an array of arguments. Notice that the compound term constructors can call the garbage collector if there is not enough space in the global stack. YAP allows one to manipulate the functors of compound term. The function @code{YAP_FunctorOfTerm} allows one to obtain a variable of type @code{YAP_Functor} with the functor to a term. The following functions then allow one to construct functors, and to obtain their name and arity. @findex YAP_MkFunctor (C-Interface function) @findex YAP_NameOfFunctor (C-Interface function) @findex YAP_ArityOfFunctor (C-Interface function) @table @code @item YAP_Functor YAP_MkFunctor(YAP_Atom @var{a},unsigned long int @var{arity}) @item YAP_Atom YAP_NameOfFunctor(YAP_Functor @var{f}) @item YAP_Int YAP_ArityOfFunctor(YAP_Functor @var{f}) @end table @noindent Note that the functor is essentially a pair formed by an atom, and arity. Constructing terms in the stack may lead to overflow. The routine @table @code @item int YAP_RequiresExtraStack(size_t @var{min}) @end table verifies whether you have at least @var{min} cells free in the stack, and it returns true if it has to ensure enough memory by calling the garbage collector and or stack shifter. The routine returns false if no memory is needed, and a negative number if it cannot provide enough memory. You can set @var{min} to zero if you do not know how much room you need but you do know you do not need a big chunk at a single go. Usually, the routine would usually be called together with a long-jump to restart the code. Slots can also be used if there is small state. @node Unifying Terms, Manipulating Strings, Manipulating Terms, C-Interface @section Unification @findex YAP_Unify (C-Interface function) YAP provides a single routine to attempt the unification of two Prolog terms. The routine may succeed or fail: @table @code @item Int YAP_Unify(YAP_Term @var{a}, YAP_Term @var{b}) @end table @noindent The routine attempts to unify the terms @var{a} and @var{b} returning @code{TRUE} if the unification succeeds and @code{FALSE} otherwise. @node Manipulating Strings, Memory Allocation, Unifying Terms, C-Interface @section Strings @findex YAP_StringToBuffer (C-Interface function) The YAP C-interface now includes an utility routine to copy a string represented as a list of a character codes to a previously allocated buffer @table @code @item int YAP_StringToBuffer(YAP_Term @var{String}, char *@var{buf}, unsigned int @var{bufsize}) @end table @noindent The routine copies the list of character codes @var{String} to a previously allocated buffer @var{buf}. The string including a terminating null character must fit in @var{bufsize} characters, otherwise the routine will simply fail. The @var{StringToBuffer} routine fails and generates an exception if @var{String} is not a valid string. @findex YAP_BufferToString (C-Interface function) @findex YAP_NBufferToString (C-Interface function) @findex YAP_WideBufferToString (C-Interface function) @findex YAP_NWideBufferToString (C-Interface function) @findex YAP_BufferToAtomList (C-Interface function) @findex YAP_NBufferToAtomList (C-Interface function) @findex YAP_WideBufferToAtomList (C-Interface function) @findex YAP_NWideBufferToAtomList (C-Interface function) @findex YAP_BufferToDiffList (C-Interface function) @findex YAP_NBufferToDiffList (C-Interface function) @findex YAP_WideBufferToDiffList (C-Interface function) @findex YAP_NWideBufferToDiffList (C-Interface function) The C-interface also includes utility routines to do the reverse, that is, to copy a from a buffer to a list of character codes, to a difference list, or to a list of character atoms. The routines work either on strings of characters or strings of wide characters: @table @code @item YAP_Term YAP_BufferToString(char *@var{buf}) @item YAP_Term YAP_NBufferToString(char *@var{buf}, size_t @var{len}) @item YAP_Term YAP_WideBufferToString(wchar_t *@var{buf}) @item YAP_Term YAP_NWideBufferToString(wchar_t *@var{buf}, size_t @var{len}) @item YAP_Term YAP_BufferToAtomList(char *@var{buf}) @item YAP_Term YAP_NBufferToAtomList(char *@var{buf}, size_t @var{len}) @item YAP_Term YAP_WideBufferToAtomList(wchar_t *@var{buf}) @item YAP_Term YAP_NWideBufferToAtomList(wchar_t *@var{buf}, size_t @var{len}) @end table @noindent Users are advised to use the @var{N} version of the routines. Otherwise, the user-provided string must include a terminating null character. @findex YAP_ReadBuffer (C-Interface function) The C-interface function calls the parser on a sequence of characters stored at @var{buf} and returns the resulting term. @table @code @item YAP_Term YAP_ReadBuffer(char *@var{buf},YAP_Term *@var{error}) @end table @noindent The user-provided string must include a terminating null character. Syntax errors will cause returning @code{FALSE} and binding @var{error} to a Prolog term. @findex YAP_IntsToList (C-Interface function) @findex YAP_FloatsToList (C-Interface function) These C-interface functions are useful when converting chunks of data to Prolog: @table @code @item YAP_Term YAP_FloatsToList(double *@var{buf},size_t @var{sz}) @item YAP_Term YAP_IntsToList(YAP_Int *@var{buf},size_t @var{sz}) @end table @noindent Notice that they are unsafe, and may call the garbage collector. They return 0 on error. @findex YAP_ListToInts (C-Interface function) @findex YAP_ToListFloats (C-Interface function) These C-interface functions are useful when converting Prolog lists to arrays: @table @code @item YAP_Int YAP_IntsToList(YAP_Term t, YAP_Int *@var{buf},size_t @var{sz}) @item YAP_Int YAP_FloatsToList(YAP_Term t, double *@var{buf},size_t @var{sz}) @end table @noindent They return the number of integers scanned, up to a maximum of @t{sz}, and @t{-1} on error. @node Memory Allocation, Controlling Streams, Manipulating Strings, C-Interface @section Memory Allocation @findex YAP_AllocSpaceFromYAP (C-Interface function) The next routine can be used to ask space from the Prolog data-base: @table @code @item void *YAP_AllocSpaceFromYAP(int @var{size}) @end table @noindent The routine returns a pointer to a buffer allocated from the code area, or @code{NULL} if sufficient space was not available. @findex YAP_FreeSpaceFromYAP (C-Interface function) The space allocated with @code{YAP_AllocSpaceFromYAP} can be released back to YAP by using: @table @code @item void YAP_FreeSpaceFromYAP(void *@var{buf}) @end table @noindent The routine releases a buffer allocated from the code area. The system may crash if @code{buf} is not a valid pointer to a buffer in the code area. @node Controlling Streams, Utility Functions, Memory Allocation, C-Interface @section Controlling YAP Streams from @code{C} @findex YAP_StreamToFileNo (C-Interface function) The C-Interface also provides the C-application with a measure of control over the YAP Input/Output system. The first routine allows one to find a file number given a current stream: @table @code @item int YAP_StreamToFileNo(YAP_Term @var{stream}) @end table @noindent This function gives the file descriptor for a currently available stream. Note that null streams and in memory streams do not have corresponding open streams, so the routine will return a negative. Moreover, YAP will not be aware of any direct operations on this stream, so information on, say, current stream position, may become stale. @findex YAP_CloseAllOpenStreams (C-Interface function) A second routine that is sometimes useful is: @table @code @item void YAP_CloseAllOpenStreams(void) @end table @noindent This routine closes the YAP Input/Output system except for the first three streams, that are always associated with the three standard Unix streams. It is most useful if you are doing @code{fork()}. @findex YAP_FlushAllStreams (C-Interface function) Last, one may sometimes need to flush all streams: @table @code @item void YAP_CloseAllOpenStreams(void) @end table @noindent It is also useful before you do a @code{fork()}, or otherwise you may have trouble with unflushed output. @findex YAP_OpenStream (C-Interface function) The next routine allows a currently open file to become a stream. The routine receives as arguments a file descriptor, the true file name as a string, an atom with the user name, and a set of flags: @table @code @item void YAP_OpenStream(void *@var{FD}, char *@var{name}, YAP_Term @var{t}, int @var{flags}) @end table @noindent The available flags are @code{YAP_INPUT_STREAM}, @code{YAP_OUTPUT_STREAM}, @code{YAP_APPEND_STREAM}, @code{YAP_PIPE_STREAM}, @code{YAP_TTY_STREAM}, @code{YAP_POPEN_STREAM}, @code{YAP_BINARY_STREAM}, and @code{YAP_SEEKABLE_STREAM}. By default, the stream is supposed to be at position 0. The argument @var{name} gives the name by which YAP should know the new stream. @node Utility Functions, Calling YAP From C, Controlling Streams, C-Interface @section Utility Functions in @code{C} The C-Interface provides the C-application with a a number of utility functions that are useful. @findex YAP_Record (C-Interface function) The first provides a way to insert a term into the data-base @table @code @item void *YAP_Record(YAP_Term @var{t}) @end table @noindent This function returns a pointer to a copy of the term in the database (or to @t{NULL} if the operation fails. @findex YAP_Recorded (C-Interface function) The next functions provides a way to recover the term from the data-base: @table @code @item YAP_Term YAP_Recorded(void *@var{handle}) @end table @noindent Notice that the semantics are the same as for @code{recorded/3}: this function creates a new copy of the term in the stack, with fresh variables. The function returns @t{0L} if it cannot create a new term. @findex YAP_Erase (C-Interface function) Last, the next function allows one to recover space: @table @code @item int YAP_Erase(void *@var{handle}) @end table @noindent Notice that any accesses using @var{handle} after this operation may lead to a crash. The following functions are often required to compare terms. @findex YAP_ExactlyEqual (C-Interface function) Succeed if two terms are actually the same term, as in @code{==/2}: @table @code @item int YAP_ExactlyEqual(YAP_Term t1, YAP_Term t2) @end table @noindent The next function succeeds if two terms are variant terms, and returns 0 otherwise, as @code{=@=/2}: @table @code @item int YAP_Variant(YAP_Term t1, YAP_Term t2) @end table @noindent The next functions deal with numbering variables in terms: @table @code @item int YAP_NumberVars(YAP_Term t, YAP_Int first_number) @item YAP_Term YAP_UnNumberVars(YAP_Term t) @item int YAP_IsNumberedVariable(YAP_Term t) @end table @noindent The next one returns the length of a well-formed list @var{t}, or @code{-1} otherwise: @table @code @item Int YAP_ListLength(YAP_Term t) @end table @noindent Last, this function succeeds if two terms are unifiable: @code{=@=/2}: @table @code @item int YAP_Unifiable(YAP_Term t1, YAP_Term t2) @end table @noindent The second function computes a hash function for a term, as in @code{term_hash/4}. @table @code @item YAP_Int YAP_TermHash(YAP_Term t, YAP_Int range, YAP_Int depth, int ignore_variables)); @end table @noindent The first three arguments follow @code{term_has/4}. The last argument indicates what to do if we find a variable: if @code{0} fail, otherwise ignore the variable. @node Calling YAP From C, Module Manipulation in C, Utility Functions, C-Interface @section From @code{C} back to Prolog @findex YAP_RunGoal (C-Interface function) There are several ways to call Prolog code from C-code. By default, the @code{YAP_RunGoal()} should be used for this task. It assumes the engine has been initialised before: @table @code @item YAP_Int YAP_RunGoal(YAP_Term Goal) @end table Execute query @var{Goal} and return 1 if the query succeeds, and 0 otherwise. The predicate returns 0 if failure, otherwise it will return an @var{YAP_Term}. Quite often, one wants to run a query once. In this case you should use @var{Goal}: @table @code @item YAP_Int YAP_RunGoalOnce(YAP_Term Goal) @end table The @code{YAP_RunGoal()} function makes sure to recover stack space at the end of execution. Prolog terms are pointers: a problem users often find is that the term @var{Goal} may actually @emph{be moved around} during the execution of @code{YAP_RunGoal()}, due to garbage collection or stack shifting. If this is possible, @var{Goal} will become invalid after executing @code{YAP_RunGoal()}. In this case, it is a good idea to save @var{Goal} @emph{slots}, as shown next: @example long sl = YAP_InitSlot(scoreTerm); out = YAP_RunGoal(t); t = YAP_GetFromSlot(sl); YAP_RecoverSlots(1); if (out == 0) return FALSE; @end example @ifplaintext @copydoc real @end ifplaintext @texinfo Slots are safe houses in the stack, the garbage collector and the stack shifter know about them and make sure they have correct values. In this case, we use a slot to preserve @var{t} during the execution of @code{YAP_RunGoal}. When the execution of @var{t} is over we read the (possibly changed) value of @var{t} back from the slot @var{sl} and tell YAP that the slot @var{sl} is not needed and can be given back to the system. The slot functions are as follows: @table @code @item YAP_Int YAP_NewSlots(int @var{NumberOfSlots}) @findex YAP_NewSlots (C-Interface function) Allocate @var{NumberOfSlots} from the stack and return an handle to the last one. The other handle can be obtained by decrementing the handle. @item YAP_Int YAP_CurrentSlot(void) @findex YAP_CurrentSlot (C-Interface function) Return a handle to the system's default slot. @item YAP_Int YAP_InitSlot(YAP_Term @var{t}) @findex YAP_InitSlot (C-Interface function) Create a new slot, initialise it with @var{t}, and return a handle to this slot, that also becomes the current slot. @item YAP_Term *YAP_AddressFromSlot(YAP_Int @var{slot}) @findex YAP_AddressFromSlot (C-Interface function) Return the address of slot @var{slot}: please use with care. @item void YAP_PutInSlot(YAP_Int @var{slot}, YAP_Term @var{t}) @findex YAP_PutInSlot (C-Interface function) Set the contents of slot @var{slot} to @var{t}. @item int YAP_RecoverSlots(int @var{HowMany}) @findex YAP_RecoverSlots (C-Interface function) Recover the space for @var{HowMany} slots: these will include the current default slot. Fails if no such slots exist. @item YAP_Int YAP_ArgsToSlots(int @var{HowMany}) @findex YAP_ArgsToSlots (C-Interface function) Store the current first @var{HowMany} arguments in new slots. @item void YAP_SlotsToArgs(int @var{HowMany}, YAP_Int @var{slot}) @findex YAP_SlotsToArgs (C-Interface function) Set the first @var{HowMany} arguments to the @var{HowMany} slots starting at @var{slot}. @end table @end texinfo The following functions complement @var{YAP_RunGoal}: @table @code @item @code{int} YAP_RestartGoal(@code{void}) @findex YAP_RestartGoal (C-Interface function) Look for the next solution to the current query by forcing YAP to backtrack to the latest goal. Notice that slots allocated since the last @code{YAP_RunGoal} will become invalid. @Item @code{int} YAP_Reset(@code{void}) @findex YAP_Reset (C-Interface function) Reset execution environment (similar to the @code{abort/0} built-in). This is useful when you want to start a new query before asking all solutions to the previous query. @item @code{int} YAP_ShutdownGoal(@code{int backtrack}) @findex YAP_ShutdownGoal (C-Interface function) Clean up the current goal. If @code{backtrack} is true, stack space will be recovered and bindings will be undone. In both cases, any slots allocated since the goal was created will become invalid. @item @code{YAP_Bool} YAP_GoalHasException(@code{YAP_Term *tp}) @findex YAP_GoalHasException (C-Interface function) Check if the last goal generated an exception, and if so copy it to the space pointed to by @var{tp} @item @code{void} YAP_ClearExceptions(@code{void}) @findex YAP_ClearExceptions (C-Interface function) Reset any exceptions left over by the system. @end table The @var{YAP_RunGoal} interface is designed to be very robust, but may not be the most efficient when repeated calls to the same goal are made and when there is no interest in processing exception. The @var{YAP_EnterGoal} interface should have lower-overhead: @table @code @item @code{YAP_PredEntryPtr} YAP_FunctorToPred(@code{YAP_Functor} @var{f}, @findex YAP_FunctorToPred (C-Interface function) Return the predicate whose main functor is @var{f}. @item @code{YAP_PredEntryPtr} YAP_AtomToPred(@code{YAP_Atom} @var{at} @findex YAP_AtomToPred (C-Interface function) Return the arity 0 predicate whose name is @var{at}. @item @code{YAP_PredEntryPtr} YAP_FunctorToPredInModule(@code{YAP_Functor} @var{f}, @code{YAP_Module} @var{m}), @findex YAP_FunctorToPredInModule (C-Interface function) Return the predicate in module @var{m} whose main functor is @var{f}. @item @code{YAP_PredEntryPtr} YAP_AtomToPred(@code{YAP_Atom} @var{at}, @code{YAP_Module} @var{m}), @findex YAP_AtomToPredInModule (C-Interface function) Return the arity 0 predicate in module @var{m} whose name is @var{at}. @item @code{YAP_Bool} YAP_EnterGoal(@code{YAP_PredEntryPtr} @var{pe}, @code{YAP_Term *} @var{array}, @code{YAP_dogoalinfo *} @var{infop}) @findex YAP_EnterGoal (C-Interface function) Execute a query for predicate @var{pe}. The query is given as an array of terms @var{Array}. @var{infop} is the address of a goal handle that can be used to backtrack and to recover space. Succeeds if a solution was found. Notice that you cannot create new slots if an YAP_EnterGoal goal is open. @item @code{YAP_Bool} YAP_RetryGoal(@code{YAP_dogoalinfo *} @var{infop}) @findex YAP_RetryGoal (C-Interface function) Backtrack to a query created by @code{YAP_EnterGoal}. The query is given by the handle @var{infop}. Returns whether a new solution could be be found. @item @code{YAP_Bool} YAP_LeaveGoal(@code{YAP_Bool} @var{backtrack}, @code{YAP_dogoalinfo *} @var{infop}) @findex YAP_LeaveGoal (C-Interface function) Exit a query query created by @code{YAP_EnterGoal}. If @code{backtrack} is @code{TRUE}, variable bindings are undone and Heap space is recovered. Otherwise, only stack space is recovered, ie, @code{LeaveGoal} executes a cut. @end table Next, follows an example of how to use @code{YAP_EnterGoal}: @example void runall(YAP_Term g) @{ YAP_dogoalinfo goalInfo; YAP_Term *goalArgs = YAP_ArraysOfTerm(g); YAP_Functor *goalFunctor = YAP_FunctorOfTerm(g); YAP_PredEntryPtr goalPred = YAP_FunctorToPred(goalFunctor); result = YAP_EnterGoal( goalPred, goalArgs, &goalInfo ); while (result) result = YAP_RetryGoal( &goalInfo ); YAP_LeaveGoal(TRUE, &goalInfo); @} @end example @findex YAP_CallProlog (C-Interface function) YAP allows calling a @strong{new} Prolog interpreter from @code{C}. One way is to first construct a goal @code{G}, and then it is sufficient to perform: @table @code @item YAP_Bool YAP_CallProlog(YAP_Term @var{G}) @end table @noindent the result will be @code{FALSE}, if the goal failed, or @code{TRUE}, if the goal succeeded. In this case, the variables in @var{G} will store the values they have been unified with. Execution only proceeds until finding the first solution to the goal, but you can call @code{findall/3} or friends if you need all the solutions. Notice that during execution, garbage collection or stack shifting may have moved the terms @node Module Manipulation in C, Miscellaneous C-Functions, Calling YAP From C, C-Interface @section Module Manipulation in C YAP allows one to create a new module from C-code. To create the new code it is sufficient to call: @table @code @item YAP_Module YAP_CreateModule(YAP_Atom @var{ModuleName}) @end table @noindent Notice that the new module does not have any predicates associated and that it is not the current module. To find the current module, you can call: @table @code @item YAP_Module YAP_CurrentModule() @end table Given a module, you may want to obtain the corresponding name. This is possible by using: @table @code @item YAP_Term YAP_ModuleName(YAP_Module mod) @end table @noindent Notice that this function returns a term, and not an atom. You can @code{YAP_AtomOfTerm} to extract the corresponding Prolog atom. @node Miscellaneous C-Functions, Writing C, Module Manipulation in C, C-Interface @section Miscellaneous C Functions @table @code @item @code{void} YAP_Throw(@code{YAP_Term exception}) @item @code{void} YAP_AsyncThrow(@code{YAP_Term exception}) @findex YAP_Throw (C-Interface function) @findex YAP_AsyncThrow (C-Interface function) Throw an exception with term @var{exception}, just like if you called @code{throw/2}. The function @t{YAP_AsyncThrow} is supposed to be used from interrupt handlers. @c See also @code{at_halt/1}. @item @code{int} YAP_SetYAPFlag(@code{yap_flag_t flag, int value}) @findex YAP_SetYAPFlag (C-Interface function) This function allows setting some YAP flags from @code{C} .Currently, only two boolean flags are accepted: @code{YAPC_ENABLE_GC} and @code{YAPC_ENABLE_AGC}. The first enables/disables the standard garbage collector, the second does the same for the atom garbage collector.` @item @code{YAP_TERM} YAP_AllocExternalDataInStack(@code{size_t bytes}) @item @code{void *} YAP_ExternalDataInStackFromTerm(@code{YAP_Term t}) @item @code{YAP_Bool} YAP_IsExternalDataInStackTerm(@code{YAP_Term t}) @findex YAP_AllocExternalDataInStack (C-Interface function) The next routines allow one to store external data in the Prolog execution stack. The first routine reserves space for @var{sz} bytes and returns an opaque handle. The second routines receives the handle and returns a pointer to the data. The last routine checks if a term is an opaque handle. Data will be automatically reclaimed during backtracking. Also, this storage is opaque to the Prolog garbage compiler, so it should not be used to store Prolog terms. On the other hand, it may be useful to store arrays in a compact way, or pointers to external objects. @item @code{int} YAP_HaltRegisterHook(@code{YAP_halt_hook f, void *closure}) @findex YAP_HaltRegisterHook (C-Interface function) Register the function @var{f} to be called if YAP is halted. The function is called with two arguments: the exit code of the process (@code{0} if this cannot be determined on your operating system) and the closure argument @var{closure}. @c See also @code{at_halt/1}. @item @code{int} YAP_Argv(@code{char ***argvp}) @findex YAP_Argv (C-Interface function) Return the number of arguments to YAP and instantiate argvp to point to the list of such arguments. @end table @node Writing C, Loading Objects, Miscellaneous C-Functions, C-Interface @section Writing predicates in C We will distinguish two kinds of predicates: @table @i @item @i{deterministic} predicates which either fail or succeed but are not backtrackable, like the one in the introduction; @item @i{backtrackable} predicates which can succeed more than once. @end table The first kind of predicates should be implemented as a C function with no arguments which should return zero if the predicate fails and a non-zero value otherwise. The predicate should be declared to YAP, in the initialization routine, with a call to @table @code @item void YAP_UserCPredicate(char *@var{name}, YAP_Bool *@var{fn}(), unsigned long int @var{arity}); @findex YAP_UserCPredicate (C-Interface function) @noindent where @var{name} is a string with the name of the predicate, @var{init}, @var{cont}, @var{cut} are the C functions used to start, continue and when pruning the execution of the predicate, @var{arity} is the predicate arity, and @var{sizeof} is the size of the data to be preserved in the stack. For the second kind of predicates we need three C functions. The first one is called when the predicate is first activated; the second one is called on backtracking to provide (possibly) other solutions; the last one is called on pruning. Note also that we normally also need to preserve some information to find out the next solution. In fact the role of the two functions can be better understood from the following Prolog definition @example p :- start. p :- repeat, continue. @end example @noindent where @code{start} and @code{continue} correspond to the two C functions described above. The interface works as follows: @table @code @item void YAP_UserBackCutCPredicate(char *@var{name}, int *@var{init}(), int *@var{cont}(), int *@var{cut}(), unsigned long int @var{arity}, unsigned int @var{sizeof}) @findex YAP_UserBackCutCPredicate (C-Interface function) @noindent describes a new predicate where @var{name} is the name of the predicate, @var{init}, @var{cont}, and @var{cut} are the C functions that implement the predicate and @var{arity} is the predicate's arity. @item void YAP_UserBackCPredicate(char *@var{name}, int *@var{init}(), int *@var{cont}(), unsigned long int @var{arity}, unsigned int @var{sizeof}) @findex YAP_UserBackCPredicate (C-Interface function) @noindent describes a new predicate where @var{name} is the name of the predicate, @var{init}, and @var{cont} are the C functions that implement the predicate and @var{arity} is the predicate's arity. @item void YAP_PRESERVE_DATA(@var{ptr}, @var{type}); @findex YAP_PRESERVE_DATA (C-Interface function) @item void YAP_PRESERVED_DATA(@var{ptr}, @var{type}); @findex YAP_PRESERVED_DATA (C-Interface function) @item void YAP_PRESERVED_DATA_CUT(@var{ptr}, @var{type}); @findex YAP_PRESERVED_DATA_CUT (C-Interface function) @item void YAP_cut_succeed( void ); @findex YAP_cut_succeed (C-Interface function) @item void YAP_cut_fail( void ); @findex YAP_cut_fail (C-Interface function) @end table As an example we will consider implementing in C a predicate @code{n100(N)} which, when called with an instantiated argument should succeed if that argument is a numeral less or equal to 100, and, when called with an uninstantiated argument, should provide, by backtracking, all the positive integers less or equal to 100. To do that we first declare a structure, which can only consist of Prolog terms, containing the information to be preserved on backtracking and a pointer variable to a structure of that type. @example #include "YAPInterface.h" static int start_n100(void); static int continue_n100(void); typedef struct @{ YAP_Term next_solution; @} n100_data_type; n100_data_type *n100_data; @end example We now write the @code{C} function to handle the first call: @example static int start_n100(void) @{ YAP_Term t = YAP_ARG1; YAP_PRESERVE_DATA(n100_data,n100_data_type); if(YAP_IsVarTerm(t)) @{ n100_data->next_solution = YAP_MkIntTerm(0); return continue_n100(); @} if(!YAP_IsIntTerm(t) || YAP_IntOfTerm(t)<0 || YAP_IntOfTerm(t)>100) @{ YAP_cut_fail(); @} else @{ YAP_cut_succeed(); @} @} @end example The routine starts by getting the dereference value of the argument. The call to @code{YAP_PRESERVE_DATA} is used to initialize the memory which will hold the information to be preserved across backtracking. The first argument is the variable we shall use, and the second its type. Note that we can only use @code{YAP_PRESERVE_DATA} once, so often we will want the variable to be a structure. This data is visible to the garbage collector, so it should consist of Prolog terms, as in the example. It is also correct to store pointers to objects external to YAP stacks, as the garbage collector will ignore such references. If the argument of the predicate is a variable, the routine initializes the structure to be preserved across backtracking with the information required to provide the next solution, and exits by calling @code{continue_n100} to provide that solution. If the argument was not a variable, the routine then checks if it was an integer, and if so, if its value is positive and less than 100. In that case it exits, denoting success, with @code{YAP_cut_succeed}, or otherwise exits with @code{YAP_cut_fail} denoting failure. The reason for using for using the functions @code{YAP_cut_succeed} and @code{YAP_cut_fail} instead of just returning a non-zero value in the first case, and zero in the second case, is that otherwise, if backtracking occurred later, the routine @code{continue_n100} would be called to provide additional solutions. The code required for the second function is @example static int continue_n100(void) @{ int n; YAP_Term t; YAP_Term sol = YAP_ARG1; YAP_PRESERVED_DATA(n100_data,n100_data_type); n = YAP_IntOfTerm(n100_data->next_solution); if( n == 100) @{ t = YAP_MkIntTerm(n); YAP_Unify(sol,t); YAP_cut_succeed(); @} else @{ YAP_Unify(sol,n100_data->next_solution); n100_data->next_solution = YAP_MkIntTerm(n+1); return(TRUE); @} @} @end example Note that again the macro @code{YAP_PRESERVED_DATA} is used at the beginning of the function to access the data preserved from the previous solution. Then it checks if the last solution was found and in that case exits with @code{YAP_cut_succeed} in order to cut any further backtracking. If this is not the last solution then we save the value for the next solution in the data structure and exit normally with 1 denoting success. Note also that in any of the two cases we use the function @code{YAP_unify} to bind the argument of the call to the value saved in @code{ n100_state->next_solution}. Note also that the only correct way to signal failure in a backtrackable predicate is to use the @code{YAP_cut_fail} macro. Backtrackable predicates should be declared to YAP, in a way similar to what happened with deterministic ones, but using instead a call to @example @end example @noindent In this example, we would have something like @example void init_n100(void) @{ YAP_UserBackCutCPredicate("n100", start_n100, continue_n100, cut_n100, 1, 1); @} @end example The argument before last is the predicate's arity. Notice again the last argument to the call. function argument gives the extra space we want to use for @code{PRESERVED_DATA}. Space is given in cells, where a cell is the same size as a pointer. The garbage collector has access to this space, hence users should use it either to store terms or to store pointers to objects outside the stacks. The code for @code{cut_n100} could be: @example static int cut_n100(void) @{ YAP_PRESERVED_DATA_CUT(n100_data,n100_data_type*); fprintf("n100 cut with counter %ld\n", YAP_IntOfTerm(n100_data->next_solution)); return TRUE; @} @end example Notice that we have to use @code{YAP_PRESERVED_DATA_CUT}: this is because the Prolog engine is at a different state during cut. If no work is required at cut, we can use: @example void init_n100(void) @{ YAP_UserBackCutCPredicate("n100", start_n100, continue_n100, NULL, 1, 1); @} @end example in this case no code is executed at cut time. @node Loading Objects, Save&Rest, Writing C, C-Interface @section Loading Object Files The primitive predicate @table @code @item load_foreign_files(@var{Files},@var{Libs},@var{InitRoutine}) @end table @noindent should be used, from inside YAP, to load object files produced by the C compiler. The argument @var{ObjectFiles} should be a list of atoms specifying the object files to load, @var{Libs} is a list (possibly empty) of libraries to be passed to the unix loader (@code{ld}) and InitRoutine is the name of the C routine (to be called after the files are loaded) to perform the necessary declarations to YAP of the predicates defined in the files. YAP will search for @var{ObjectFiles} in the current directory first. If it cannot find them it will search for the files using the environment variable: @table @code @item YAPLIBDIR @findex YAPLIBDIR @noindent @end table if defined, or in the default library. YAP also supports the SWI-Prolog interface to loading foreign code: @table @code @item open_shared_object(+@var{File}, -@var{Handle}) @findex open_shared_object/2 @snindex open_shared_object/2 @cnindex open_shared_object/2 File is the name of a shared object file (called dynamic load library in MS-Windows). This file is attached to the current process and @var{Handle} is unified with a handle to the library. Equivalent to @code{open_shared_object(File, [], Handle)}. See also @code{load_foreign_library/1} and @code{load_foreign_library/2}. On errors, an exception @code{shared_object}(@var{Action}, @var{Message}) is raised. @var{Message} is the return value from dlerror(). @item open_shared_object(+@var{File}, -@var{Handle}, +@var{Options}) @findex open_shared_object/3 @snindex open_shared_object/3 @cnindex open_shared_object/3 As @code{open_shared_object/2}, but allows for additional flags to be passed. @var{Options} is a list of atoms. @code{now} implies the symbols are resolved immediately rather than lazily (default). @code{global} implies symbols of the loaded object are visible while loading other shared objects (by default they are local). Note that these flags may not be supported by your operating system. Check the documentation of @code{dlopen()} or equivalent on your operating system. Unsupported flags are silently ignored. @item close_shared_object(+@var{Handle}) @findex close_shared_object/1 @snindex close_shared_object/1 @cnindex close_shared_object/1 Detach the shared object identified by @var{Handle}. @item call_shared_object_function(+@var{Handle}, +@var{Function}) @findex call_shared_object_function/2 @snindex call_shared_object_function/2 @cnindex call_shared_object_function/2 Call the named function in the loaded shared library. The function is called without arguments and the return-value is ignored. In SWI-Prolog, normally this function installs foreign language predicates using calls to @code{PL_register_foreign()}. @end table @node Save&Rest, YAP4 Notes, Loading Objects, C-Interface @section Saving and Restoring @comment The primitive predicates @code{save} and @code{restore} will save and restore @comment object code loaded with @code{load_foreign_files/3}. However, the values of @comment any non-static data created by the C files loaded will not be saved nor @comment restored. YAP4 currently does not support @code{save} and @code{restore} for object code loaded with @code{load_foreign_files/3}. We plan to support save and restore in future releases of YAP. @node YAP4 Notes, , Save&Rest, C-Interface @section Changes to the C-Interface in YAP4 YAP4 includes several changes over the previous @code{load_foreign_files/3} interface. These changes were required to support the new binary code formats, such as ELF used in Solaris2 and Linux. @itemize @bullet @item All Names of YAP objects now start with @var{YAP_}. This is designed to avoid clashes with other code. Use @code{YAPInterface.h} to take advantage of the new interface. @code{c_interface.h} is still available if you cannot port the code to the new interface. @item Access to elements in the new interface always goes through @emph{functions}. This includes access to the argument registers, @code{YAP_ARG1} to @code{YAP_ARG16}. This change breaks code such as @code{unify(&ARG1,&t)}, which is nowadays: @example @{ YAP_Unify(ARG1, t); @} @end example @item @code{cut_fail()} and @code{cut_succeed()} are now functions. @item The use of @code{Deref} is deprecated. All functions that return Prolog terms, including the ones that access arguments, already dereference their arguments. @item Space allocated with PRESERVE_DATA is ignored by garbage collection and stack shifting. As a result, any pointers to a Prolog stack object, including some terms, may be corrupted after garbage collection or stack shifting. Prolog terms should instead be stored as arguments to the backtrackable procedure. @end itemize @node YAPLibrary, Compatibility, C-Interface, Top @section Using YAP as a Library YAP can be used as a library to be called from other programs. To do so, you must first create the YAP library: @example make library make install_library @end example This will install a file @code{libyap.a} in @var{LIBDIR} and the Prolog headers in @var{INCLUDEDIR}. The library contains all the functionality available in YAP, except the foreign function loader and for @code{YAP}'s startup routines. To actually use this library you must follow a five step process: @enumerate @item You must initialize the YAP environment. A single function, @code{YAP_FastInit} asks for a contiguous chunk in your memory space, fills it in with the data-base, and sets up YAP's stacks and execution registers. You can use a saved space from a standard system by calling @code{save_program/1}. @item You then have to prepare a query to give to YAP. A query is a Prolog term, and you just have to use the same functions that are available in the C-interface. @item You can then use @code{YAP_RunGoal(query)} to actually evaluate your query. The argument is the query term @code{query}, and the result is 1 if the query succeeded, and 0 if it failed. @item You can use the term destructor functions to check how arguments were instantiated. @item If you want extra solutions, you can use @code{YAP_RestartGoal()} to obtain the next solution. @end enumerate The next program shows how to use this system. We assume the saved program contains two facts for the procedure @t{b}: @example @cartouche #include #include "YAP/YAPInterface.h" int main(int argc, char *argv[]) @{ if (YAP_FastInit("saved_state") == YAP_BOOT_ERROR) exit(1); if (YAP_RunGoal(YAP_MkAtomTerm(YAP_LookupAtom("do")))) @{ printf("Success\n"); while (YAP_RestartGoal()) printf("Success\n"); @} printf("NO\n"); @} @end cartouche @end example The program first initializes YAP, calls the query for the first time and succeeds, and then backtracks twice. The first time backtracking succeeds, the second it fails and exits. To compile this program it should be sufficient to do: @example cc -o exem -I../YAP4.3.0 test.c -lYAP -lreadline -lm @end example You may need to adjust the libraries and library paths depending on the Operating System and your installation of YAP. Note that YAP4.3.0 provides the first version of the interface. The interface may change and improve in the future. The following C-functions are available from YAP: @itemize @bullet @item YAP_CompileClause(@code{YAP_Term} @var{Clause}) @findex YAP_CompileClause/1 Compile the Prolog term @var{Clause} and assert it as the last clause for the corresponding procedure. @item @code{int} YAP_ContinueGoal(@code{void}) @findex YAP_ContinueGoal/0 Continue execution from the point where it stopped. @item @code{void} YAP_Error(@code{int} @var{ID},@code{YAP_Term} @var{Cause},@code{char *} @var{error_description}) @findex YAP_Error/1 Generate an YAP System Error with description given by the string @var{error_description}. @var{ID} is the error ID, if known, or @code{0}. @var{Cause} is the term that caused the crash. @item @code{void} YAP_Exit(@code{int} @var{exit_code}) @findex YAP_Exit/1 Exit YAP immediately. The argument @var{exit_code} gives the error code and is supposed to be 0 after successful execution in Unix and Unix-like systems. @item @code{YAP_Term} YAP_GetValue(@code{Atom} @var{at}) @findex YAP_GetValue/1 Return the term @var{value} associated with the atom @var{at}. If no such term exists the function will return the empty list. @item YAP_FastInit(@code{char *} @var{SavedState}) @findex YAP_FastInit/1 Initialize a copy of YAP from @var{SavedState}. The copy is monolithic and currently must be loaded at the same address where it was saved. @code{YAP_FastInit} is a simpler version of @code{YAP_Init}. @item YAP_Init(@var{InitInfo}) @findex YAP_Init/1 Initialize YAP. The arguments are in a @code{C} structure of type @code{YAP_init_args}. The fields of @var{InitInfo} are @code{char *} @var{SavedState}, @code{int} @var{HeapSize}, @code{int} @var{StackSize}, @code{int} @var{TrailSize}, @code{int} @var{NumberofWorkers}, @code{int} @var{SchedulerLoop}, @code{int} @var{DelayedReleaseLoad}, @code{int} @var{argc}, @code{char **} @var{argv}, @code{int} @var{ErrorNo}, and @code{char *} @var{ErrorCause}. The function returns an integer, which indicates the current status. If the result is @code{YAP_BOOT_ERROR} booting failed. If @var{SavedState} is not NULL, try to open and restore the file @var{SavedState}. Initially YAP will search in the current directory. If the saved state does not exist in the current directory YAP will use either the default library directory or the directory given by the environment variable @code{YAPLIBDIR}. Note that currently the saved state must be loaded at the same address where it was saved. If @var{HeapSize} is different from 0 use @var{HeapSize} as the minimum size of the Heap (or code space). If @var{StackSize} is different from 0 use @var{HeapSize} as the minimum size for the Stacks. If @var{TrailSize} is different from 0 use @var{TrailSize} as the minimum size for the Trails. The @var{NumberofWorkers}, @var{NumberofWorkers}, and @var{DelayedReleaseLoad} are only of interest to the or-parallel system. The argument count @var{argc} and string of arguments @var{argv} arguments are to be passed to user programs as the arguments used to call YAP. If booting failed you may consult @code{ErrorNo} and @code{ErrorCause} for the cause of the error, or call @code{YAP_Error(ErrorNo,0L,ErrorCause)} to do default processing. @item @code{void} YAP_PutValue(@code{Atom} @var{at}, @code{YAP_Term} @var{value}) @findex YAP_PutValue/2 Associate the term @var{value} with the atom @var{at}. The term @var{value} must be a constant. This functionality is used by YAP as a simple way for controlling and communicating with the Prolog run-time. @item @code{YAP_Term} YAP_Read(@code{IOSTREAM *Stream}) @findex YAP_Read Parse a @var{Term} from the stream @var{Stream}. @item @code{YAP_Term} YAP_Write(@code{YAP_Term} @var{t}) @findex YAP_CopyTerm Copy a Term @var{t} and all associated constraints. May call the garbage collector and returns @code{0L} on error (such as no space being available). @item @code{void} YAP_Write(@code{YAP_Term} @var{t}, @code{IOSTREAM} @var{stream}, @code{int} @var{flags}) @findex YAP_Write/3 Write a Term @var{t} using the stream @var{stream} to output characters. The term is written according to a mask of the following flags in the @code{flag} argument: @code{YAP_WRITE_QUOTED}, @code{YAP_WRITE_HANDLE_VARS}, @code{YAP_WRITE_USE_PORTRAY}, and @code{YAP_WRITE_IGNORE_OPS}. @item @code{int} YAP_WriteBuffer(@code{YAP_Term} @var{t}, @code{char *} @var{buff}, @code{size_t} @var{size}, @code{int} @var{flags}) @findex YAP_WriteBuffer Write a YAP_Term @var{t} to buffer @var{buff} with size @var{size}. The term is written according to a mask of the following flags in the @code{flag} argument: @code{YAP_WRITE_QUOTED}, @code{YAP_WRITE_HANDLE_VARS}, @code{YAP_WRITE_USE_PORTRAY}, and @code{YAP_WRITE_IGNORE_OPS}. The function will fail if it does not have enough space in the buffer. @item @code{char *} YAP_WriteDynamicBuffer(@code{YAP_Term} @var{t}, @code{char *} @var{buff}, @code{size_t} @var{size}, @code{size_t} @var{*lengthp}, @code{size_t} @var{*encodingp}, @code{int} @var{flags}) @findex YAP_WriteDynamicBuffer/6 Write a YAP_Term @var{t} to buffer @var{buff} with size @var{size}. The code will allocate an extra buffer if @var{buff} is @code{NULL} or if @code{buffer} does not have enough room. The variable @code{lengthp} is assigned the size of the resulting buffer, and @code{encodingp} will receive the type of encoding (currently only @code{PL_ENC_ISO_LATIN_1} and @code{PL_ENC_WCHAR} are supported) @item @code{void} YAP_InitConsult(@code{int} @var{mode}, @code{char *} @var{filename}) @findex YAP_InitConsult/2 Enter consult mode on file @var{filename}. This mode maintains a few data-structures internally, for instance to know whether a predicate before or not. It is still possible to execute goals in consult mode. If @var{mode} is @code{TRUE} the file will be reconsulted, otherwise just consulted. In practice, this function is most useful for bootstrapping Prolog, as otherwise one may call the Prolog predicate @code{compile/1} or @code{consult/1} to do compilation. Note that it is up to the user to open the file @var{filename}. The @code{YAP_InitConsult} function only uses the file name for internal bookkeeping. @item @code{void} YAP_EndConsult(@code{void}) @findex YAP_EndConsult/0 Finish consult mode. @end itemize Some observations: @itemize @bullet @item The system will core dump if you try to load the saved state in a different address from where it was made. This may be a problem if your program uses @code{mmap}. This problem will be addressed in future versions of YAP. @item Currently, the YAP library will pollute the name space for your program. @item The initial library includes the complete YAP system. In the future we plan to split this library into several smaller libraries (e.g. if you do not want to perform Input/Output). @item You can generate your own saved states. Look at the @code{boot.yap} and @code{init.yap} files. @end itemize @node Compatibility, Operators, YAPLibrary, Top @chapter Compatibility with Other Prolog systems YAP has been designed to be as compatible as possible with other Prolog systems, and initially with C-Prolog. More recent work on YAP has included features initially proposed for the Quintus and SICStus Prolog systems. Developments since @code{YAP4.1.6} we have striven at making YAP compatible with the ISO-Prolog standard. @menu * C-Prolog:: Compatibility with the C-Prolog interpreter * SICStus Prolog:: Compatibility with the SICStus Prolog system * ISO Prolog:: Compatibility with the ISO Prolog standard @end menu @node C-Prolog, SICStus Prolog, , Compatibility @section Compatibility with the C-Prolog interpreter @menu C-Prolog Compatibility * Major Differences with C-Prolog:: Major Differences between YAP and C-Prolog * Fully C-Prolog Compatible:: YAP predicates fully compatible with C-Prolog * Not Strictly C-Prolog Compatible:: YAP predicates not strictly as C-Prolog * Not in C-Prolog:: YAP predicates not available in C-Prolog * Not in YAP:: C-Prolog predicates not available in YAP @end menu @node Major Differences with C-Prolog, Fully C-Prolog Compatible, , C-Prolog @subsection Major Differences between YAP and C-Prolog. YAP includes several extensions over the original C-Prolog system. Even so, most C-Prolog programs should run under YAP without changes. The most important difference between YAP and C-Prolog is that, being YAP a compiler, some changes should be made if predicates such as @code{assert}, @code{clause} and @code{retract} are used. First predicates which will change during execution should be declared as @code{dynamic} by using commands like: @example :- dynamic f/n. @end example @noindent where @code{f} is the predicate name and n is the arity of the predicate. Note that several such predicates can be declared in a single command: @example :- dynamic f/2, ..., g/1. @end example Primitive predicates such as @code{retract} apply only to dynamic predicates. Finally note that not all the C-Prolog primitive predicates are implemented in YAP. They can easily be detected using the @code{unknown} system predicate provided by YAP. Last, by default YAP enables character escapes in strings. You can disable the special interpretation for the escape character by using: @example :- yap_flag(character_escapes,off). @end example @noindent or by using: @example :- yap_flag(language,cprolog). @end example @node Fully C-Prolog Compatible, Not Strictly C-Prolog Compatible, Major Differences with C-Prolog, C-Prolog @subsection YAP predicates fully compatible with C-Prolog These are the Prolog built-ins that are fully compatible in both C-Prolog and YAP: @printindex cy @node Not Strictly C-Prolog Compatible, Not in C-Prolog, Fully C-Prolog Compatible, C-Prolog @subsection YAP predicates not strictly compatible with C-Prolog These are YAP built-ins that are also available in C-Prolog, but that are not fully compatible: @printindex ca @node Not in C-Prolog, Not in YAP, Not Strictly C-Prolog Compatible, C-Prolog @subsection YAP predicates not available in C-Prolog These are YAP built-ins not available in C-Prolog. @printindex cn @node Not in YAP, , Not in C-Prolog, C-Prolog @subsection YAP predicates not available in C-Prolog These are C-Prolog built-ins not available in YAP: @table @code @item 'LC' The following Prolog text uses lower case letters. @item 'NOLC' The following Prolog text uses upper case letters only. @end table @node SICStus Prolog, ISO Prolog, C-Prolog, Compatibility @section Compatibility with the Quintus and SICStus Prolog systems The Quintus Prolog system was the first Prolog compiler to use Warren's Abstract Machine. This system was very influential in the Prolog community. Quintus Prolog implemented compilation into an abstract machine code, which was then emulated. Quintus Prolog also included several new built-ins, an extensive library, and in later releases a garbage collector. The SICStus Prolog system, developed at SICS (Swedish Institute of Computer Science), is an emulator based Prolog system largely compatible with Quintus Prolog. SICStus Prolog has evolved through several versions. The current version includes several extensions, such as an object implementation, co-routining, and constraints. Recent work in YAP has been influenced by work in Quintus and SICStus Prolog. Wherever possible, we have tried to make YAP compatible with recent versions of these systems, and specifically of SICStus Prolog. You should use @example :- yap_flag(language, sicstus). @end example @noindent for maximum compatibility with SICStus Prolog. @menu SICStus Compatibility * Major Differences with SICStus:: Major Differences between YAP and SICStus Prolog * Fully SICStus Compatible:: YAP predicates fully compatible with SICStus Prolog * Not Strictly SICStus Compatible:: YAP predicates not strictly as SICStus Prolog * Not in SICStus Prolog:: YAP predicates not available in SICStus Prolog @end menu @node Major Differences with SICStus, Fully SICStus Compatible, , SICStus Prolog @subsection Major Differences between YAP and SICStus Prolog. Both YAP and SICStus Prolog obey the Edinburgh Syntax and are based on the WAM. Even so, there are quite a few important differences: @itemize @bullet @item Differently from SICStus Prolog, YAP does not have a notion of interpreted code. All code in YAP is compiled. @item YAP does not support an intermediate byte-code representation, so the @code{fcompile/1} and @code{load/1} built-ins are not available in YAP. @item YAP implements escape sequences as in the ISO standard. SICStus Prolog implements Unix-like escape sequences. @item YAP implements @code{initialization/1} as per the ISO standard. Use @code{prolog_initialization/1} for the SICStus Prolog compatible built-in. @item Prolog flags are different in SICStus Prolog and in YAP. @item The SICStus Prolog @code{on_exception/3} and @code{raise_exception} built-ins correspond to the ISO built-ins @code{catch/3} and @code{throw/1}. @item The following SICStus Prolog v3 built-ins are not (currently) implemented in YAP (note that this is only a partial list): @code{file_search_path/2}, @code{stream_interrupt/3}, @code{reinitialize/0}, @code{help/0}, @code{help/1}, @code{trimcore/0}, @code{load_files/1}, @code{load_files/2}, and @code{require/1}. The previous list is incomplete. We also cannot guarantee full compatibility for other built-ins (although we will try to address any such incompatibilities). Last, SICStus Prolog is an evolving system, so one can be expect new incompatibilities to be introduced in future releases of SICStus Prolog. @item YAP allows asserting and abolishing static code during execution through the @code{assert_static/1} and @code{abolish/1} built-ins. This is not allowed in Quintus Prolog or SICStus Prolog. @item The socket predicates, although designed to be compatible with SICStus Prolog, are built-ins, not library predicates, in YAP. @item This list is incomplete. @end itemize The following differences only exist if the @code{language} flag is set to @code{yap} (the default): @itemize @bullet @item The @code{consult/1} predicate in YAP follows C-Prolog semantics. That is, it adds clauses to the data base, even for preexisting procedures. This is different from @code{consult/1} in SICStus Prolog or SWI-Prolog. @cindex logical update semantics @item By default, the data-base in YAP follows "logical update semantics", as Quintus Prolog or SICStus Prolog do. Previous versions followed "immediate update semantics". The difference is depicted in the next example: @example :- dynamic a/1. ?- assert(a(1)). ?- retract(a(X)), X1 is X +1, assertz(a(X)). @end example With immediate semantics, new clauses or entries to the data base are visible in backtracking. In this example, the first call to @code{retract/1} will succeed. The call to @strong{assertz/1} will then succeed. On backtracking, the system will retry @code{retract/1}. Because the newly asserted goal is visible to @code{retract/1}, it can be retracted from the data base, and @code{retract(a(X))} will succeed again. The process will continue generating integers for ever. Immediate semantics were used in C-Prolog. With logical update semantics, any additions or deletions of clauses for a goal @emph{will not affect previous activations of the goal}. In the example, the call to @code{assertz/1} will not see the update performed by the @code{assertz/1}, and the query will have a single solution. Calling @code{yap_flag(update_semantics,logical)} will switch YAP to use logical update semantics. @item @code{dynamic/1} is a built-in, not a directive, in YAP. @item By default, YAP fails on undefined predicates. To follow default SICStus Prolog use: @example :- yap_flag(unknown,error). @end example @item By default, directives in YAP can be called from the top level. @end itemize @node Fully SICStus Compatible, Not Strictly SICStus Compatible, Major Differences with SICStus, SICStus Prolog @subsection YAP predicates fully compatible with SICStus Prolog These are the Prolog built-ins that are fully compatible in both SICStus Prolog and YAP: @printindex sy @node Not Strictly SICStus Compatible, Not in SICStus Prolog, Fully SICStus Compatible, SICStus Prolog @subsection YAP predicates not strictly compatible with SICStus Prolog These are YAP built-ins that are also available in SICStus Prolog, but that are not fully compatible: @printindex sa @node Not in SICStus Prolog, , Not Strictly SICStus Compatible, SICStus Prolog @subsection YAP predicates not available in SICStus Prolog These are YAP built-ins not available in SICStus Prolog. @printindex sn @node ISO Prolog, , SICStus Prolog, Compatibility @section Compatibility with the ISO Prolog standard The Prolog standard was developed by ISO/IEC JTC1/SC22/WG17, the international standardization working group for the programming language Prolog. The book "Prolog: The Standard" by Deransart, Ed-Dbali and Cervoni gives a complete description of this standard. Development in YAP from YAP4.1.6 onwards have striven at making YAP compatible with ISO Prolog. As such: @itemize @bullet @item YAP now supports all of the built-ins required by the ISO-standard, and, @item Error-handling is as required by the standard. @end itemize YAP by default is not fully ISO standard compliant. You can set the @code{language} flag to @code{iso} to obtain very good compatibility. Setting this flag changes the following: @itemize @bullet @item By default, YAP uses "immediate update semantics" for its database, and not "logical update semantics", as per the standard, (@pxref{SICStus Prolog}). This affects @code{assert/1}, @code{retract/1}, and friends. Calling @code{set_prolog_flag(update_semantics,logical)} will switch YAP to use logical update semantics. @item By default, YAP implements the @code{atom_chars/2}(@pxref{Testing Terms}), and @code{number_chars/2}, (@pxref{Testing Terms}), built-ins as per the original Quintus Prolog definition, and not as per the ISO definition. Calling @code{set_prolog_flag(to_chars_mode,iso)} will switch YAP to use the ISO definition for @code{atom_chars/2} and @code{number_chars/2}. @item By default, YAP allows executable goals in directives. In ISO mode most directives can only be called from top level (the exceptions are @code{set_prolog_flag/2} and @code{op/3}). @item Error checking for meta-calls under ISO Prolog mode is stricter than by default. @item The @code{strict_iso} flag automatically enables the ISO Prolog standard. This feature should disable all features not present in the standard. @end itemize The following incompatibilities between YAP and the ISO standard are known to still exist: @itemize @bullet @item Currently, YAP does not handle overflow errors in integer operations, and handles floating-point errors only in some architectures. Otherwise, YAP follows IEEE arithmetic. @end itemize Please inform the authors on other incompatibilities that may still exist. @node Operators, Predicate Index, Compatibility, Top @section Summary of YAP Predefined Operators The Prolog syntax caters for operators of three main kinds: @itemize @bullet @item prefix; @item infix; @item postfix. @end itemize Each operator has precedence in the range 1 to 1200, and this precedence is used to disambiguate expressions where the structure of the term denoted is not made explicit using brackets. The operator of higher precedence is the main functor. If there are two operators with the highest precedence, the ambiguity is solved analyzing the types of the operators. The possible infix types are: @var{xfx}, @var{xfy}, and @var{yfx}. With an operator of type @var{xfx} both sub-expressions must have lower precedence than the operator itself, unless they are bracketed (which assigns to them zero precedence). With an operator type @var{xfy} only the left-hand sub-expression must have lower precedence. The opposite happens for @var{yfx} type. A prefix operator can be of type @var{fx} or @var{fy}. A postfix operator can be of type @var{xf} or @var{yf}. The meaning of the notation is analogous to the above. @example a + b * c @end example @noindent means @example a + (b * c) @end example @noindent as + and * have the following types and precedences: @example :-op(500,yfx,'+'). :-op(400,yfx,'*'). @end example Now defining @example :-op(700,xfy,'++'). :-op(700,xfx,'=:='). a ++ b =:= c @end example @noindent means @example a ++ (b =:= c) @end example The following is the list of the declarations of the predefined operators: @example :-op(1200,fx,['?-', ':-']). :-op(1200,xfx,[':-','-->']). :-op(1150,fx,[block,dynamic,mode,public,multifile,meta_predicate, sequential,table,initialization]). :-op(1100,xfy,[';','|']). :-op(1050,xfy,->). :-op(1000,xfy,','). :-op(999,xfy,'.'). :-op(900,fy,['\+', not]). :-op(900,fx,[nospy, spy]). :-op(700,xfx,[@@>=,@@=<,@@<,@@>,<,=,>,=:=,=\=,\==,>=,=<,==,\=,=..,is]). :-op(500,yfx,['\/','/\','+','-']). :-op(500,fx,['+','-']). :-op(400,yfx,['<<','>>','//','*','/']). :-op(300,xfx,mod). :-op(200,xfy,['^','**']). :-op(50,xfx,same). @end example @node Predicate Index, Concept Index, Operators, Top @unnumbered Predicate Index @printindex fn @node Concept Index, , Predicate Index, Top @unnumbered Concept Index @printindex cp @contents @bye