diff --git a/H/YapGFlagInfo.h b/H/YapGFlagInfo.h index 2b998c1a5..64d3c279a 100644 --- a/H/YapGFlagInfo.h +++ b/H/YapGFlagInfo.h @@ -73,20 +73,20 @@ opportunity. Initial value is 10,000. May be changed. A value of 0 /**< read-only boolean, a machine running an Google's Android version of the Linux Operating System */ - YAP_FLAG(ANDROID_FLAG, "android", false, booleanFlag, IN_ANDROID, NULL), + YAP_FLAG(ANDROID_FLAG, "android", false, ro, IN_ANDROID, NULL), #if __APPLE__ /**< read-only boolean, a machine running an Apple Operating System */ - YAP_FLAG(APPLE_FLAG, "apple", false, booleanFlag, "true", NULL), + YAP_FLAG(APPLE_FLAG, "apple", false, ro, "true", NULL), #else - YAP_FLAG(APPLE_FLAG, "apple", false, booleanFlag, "false", NULL), + YAP_FLAG(APPLE_FLAG, "apple", false, ro, "false", NULL), #endif /**< read-only atom, it describes the ISA used in this version of YAP. Available from YAP_ARCH. */ - YAP_FLAG(ARCH_FLAG, "arch", false, isatom, YAP_ARCH, NULL), + YAP_FLAG(ARCH_FLAG, "arch", false, ro, YAP_ARCH, NULL), YAP_FLAG(ARGV_FLAG, "argv", false, argv, "@boot", NULL), /**< diff --git a/H/YapText.h b/H/YapText.h index 1fef851a2..7f76514f3 100644 --- a/H/YapText.h +++ b/H/YapText.h @@ -833,7 +833,7 @@ static inline Term Yap_CharsToTBQ(const char *s, Term mod, static inline Atom Yap_ListOfAtomsToAtom(Term t0 USES_REGS) { seq_tv_t inp, out; inp.val.t = t0; - inp.type = YAP_STRING_ATOMS; + inp.type = YAP_STRING_ATOMS|YAP_STRING_CODES; out.type = YAP_STRING_ATOM; out.val.uc = NULL; out.enc = ENC_ISO_UTF8; @@ -845,7 +845,7 @@ static inline Atom Yap_ListOfAtomsToAtom(Term t0 USES_REGS) { static inline Term Yap_ListOfAtomsToNumber(Term t0 USES_REGS) { seq_tv_t inp, out; inp.val.t = t0; - inp.type = YAP_STRING_ATOMS; + inp.type = YAP_STRING_ATOMS|YAP_STRING_CODES; out.type = YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_TERM; out.val.uc = NULL; @@ -858,7 +858,7 @@ static inline Term Yap_ListOfAtomsToNumber(Term t0 USES_REGS) { static inline Term Yap_ListOfAtomsToString(Term t0 USES_REGS) { seq_tv_t inp, out; inp.val.t = t0; - inp.type = YAP_STRING_ATOMS; + inp.type = YAP_STRING_ATOMS|YAP_STRING_CODES; out.type = YAP_STRING_STRING; out.val.uc = NULL; out.enc = ENC_ISO_UTF8; @@ -870,7 +870,7 @@ static inline Term Yap_ListOfAtomsToString(Term t0 USES_REGS) { static inline Atom Yap_ListOfCodesToAtom(Term t0 USES_REGS) { seq_tv_t inp, out; inp.val.t = t0; - inp.type = YAP_STRING_CODES; + inp.type = YAP_STRING_CODES|YAP_STRING_ATOMS; out.type = YAP_STRING_ATOM; out.val.uc = NULL; out.enc = ENC_ISO_UTF8; @@ -882,7 +882,7 @@ static inline Atom Yap_ListOfCodesToAtom(Term t0 USES_REGS) { static inline Term Yap_ListOfCodesToNumber(Term t0 USES_REGS) { seq_tv_t inp, out; inp.val.t = t0; - inp.type = YAP_STRING_CODES; + inp.type = YAP_STRING_CODES|YAP_STRING_ATOMS; out.type = YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG; out.enc = ENC_ISO_UTF8; out.val.uc = NULL; @@ -895,7 +895,7 @@ static inline Term Yap_ListOfCodesToString(Term t0 USES_REGS) { seq_tv_t inp, out; inp.val.t = t0; - inp.type = YAP_STRING_CODES; + inp.type = YAP_STRING_CODES|YAP_STRING_ATOMS; out.val.uc = NULL; out.type = YAP_STRING_STRING; out.enc = ENC_ISO_UTF8; diff --git a/docs/CMakeLists.txt b/docs/CMakeLists.txt index 526e72e00..455106db6 100644 --- a/docs/CMakeLists.txt +++ b/docs/CMakeLists.txt @@ -31,14 +31,18 @@ SET( EXT string(APPEND CMAKE_HTML_EXTRA ${i} " ") endforeach(i ${CMAKE_HTML_EXTRA_}) -set(DOCS_EXCLUDE_ + +set(DOC_DIRS_EXCLUDE_ ${CMAKE_SOURCE_DIR}/build ${CMAKE_SOURCE_DIR}/Debug ${CMAKE_SOURCE_DIR}/packages/jpl -${CMAKE_SOURCE_DIR}/packages/swig - ${CMAKE_SOURCE_DIR}/packages/Problog/problog_examples/output - ${CMAKE_SOURCE_DIR}/packages/Problog/problog_examples/queries +${CMAKE_SOURCE_DIR}/packages/swi +${CMAKE_SOURCE_DIR}/packages/Problog/problog_examples ${CMAKE_SOURCE_DIR}/packages/myddas/sqlite3/src +${CMAKE_SOURCE_DIR}/packages/gecode/6.0.1 +${CMAKE_SOURCE_DIR}/packages/gecode/6.0.0 +${CMAKE_SOURCE_DIR}/packages/gecode/5.1.0 +${CMAKE_SOURCE_DIR}/packages/gecode/5.0.0 ${CMAKE_SOURCE_DIR}/packages/gecode/4.4.0 ${CMAKE_SOURCE_DIR}/packages/gecode/4.2.1 ${CMAKE_SOURCE_DIR}/packages/gecode/4.2.0 @@ -48,22 +52,30 @@ ${CMAKE_SOURCE_DIR}/packages/gecode/3.7.2 ${CMAKE_SOURCE_DIR}/packages/gecode/3.7.1 ${CMAKE_SOURCE_DIR}/packages/gecode/3.7.0 ${CMAKE_SOURCE_DIR}/packages/gecode/3.6.0 -${CMAKE_SOURCE_DIR}/packages/problog ${CMAKE_SOURCE_DIR}/packages/gecode/dev -${CMAKE_SOURCE_DIR}/C/traced_absmi_insts.h -${CMAKE_SOURCE_DIR}/H/globals.h ${CMAKE_SOURCE_DIR}/packages/cplint ${CMAKE_SOURCE_DIR}/packages/CLPBN/examples ${CMAKE_SOURCE_DIR}/packages/CLPBN/horus +${CMAKE_SOURCE_DIR}/packages/cuda ${CMAKE_SOURCE_DIR}/packages/prosqlite ${CMAKE_SOURCE_DIR}/packages/pyswip ${CMAKE_SOURCE_DIR}/packages/python/yap_kernel ${CMAKE_SOURCE_DIR}/packages/python/swig ${CMAKE_SOURCE_DIR}/packages/yap-lbfgs/liblbfgs-1.10 +${CMAKE_SOURCE_DIR}/packages/swi-minisat2 ${CMAKE_SOURCE_DIR}/library/dialect/swi/os +) + + +set(DOCS_EXCLUDE_ +${CMAKE_SOURCE_DIR}/C/traced_absmi_insts.h +${CMAKE_SOURCE_DIR}/H/globals.h +${CMAKE_SOURCE_DIR}/OPTYap/locks_alpha_funcs.h +${CMAKE_SOURCE_DIR}/OPTYap/locks_mips_funcs.h +${CMAKE_SOURCE_DIR}/OPTYap/locks_sparc.h ${CMAKE_SOURCE_DIR}/*/bprolog/* ${CMAKE_SOURCE_DIR}/*/prism/* - ${CMAKE_SOURCE_DIR}/*/gecodde/[345]* + ${CMAKE_SOURCE_DIR}/*/gecode/[345]* ${CMAKE_SOURCE_DIR}/packages/gecode/gecode3_yap.cc ${CMAKE_SOURCE_DIR}/packages/gecode/gecode4_yap.cc ${CMAKE_SOURCE_DIR}/packages/gecode/gecode5_yap.cc @@ -73,15 +85,21 @@ ${CMAKE_SOURCE_DIR}/*/bprolog/* ${CMAKE_SOURCE_DIR}/packages/gecode/gecode3_yap_hand_written.yap ${CMAKE_SOURCE_DIR}/packages/gecode/gecode4_yap_hand_written.yap ${CMAKE_SOURCE_DIR}/packages/gecode/gecode5_yap_hand_written.yap - */CMakeFiles/* *~ */#* + */CMakeFiles/* ) + foreach(i ${DOCS_EXCLUDE_}) string(APPEND DOCS_EXCLUDE ${i} " ") endforeach(i ${DOCS_EXCLUDE_}) +foreach(i ${DOCS_DIR_EXCLUDE_}) + string(APPEND DOCS_DIR_EXCLUDE ${i} " ") +endforeach(i ${DOCS_DIR_EXCLUDE_}) + + # add a target to generate API documentation with Doxygen @@ -92,6 +110,7 @@ endforeach(i ${DOCS_EXCLUDE_}) SET(DOC_INPUT_FILES_ ${CMAKE_SOURCE_DIR}/docs/md ${CMAKE_SOURCE_DIR}/pl + ${CMAKE_SOURCE_DIR}/packages/ProbLog ${CMAKE_SOURCE_DIR}/CXX ${CMAKE_SOURCE_DIR}/OPTYap ${CMAKE_SOURCE_DIR}/C @@ -100,7 +119,8 @@ endforeach(i ${DOCS_EXCLUDE_}) ${CMAKE_SOURCE_DIR}/os ${CMAKE_SOURCE_DIR}/library ${CMAKE_SOURCE_DIR}/swi/library - ${CMAKE_SOURCE_DIR}/packages + #${CMAKE_SOURCE_DIR}/packages + ${CMAKE_SOURCE_DIR}/BEAM ) foreach(i ${DOC_INPUT_FILES_}) diff --git a/docs/Doxyfile.in b/docs/Doxyfile.in index 07622a5d7..7b7691590 100644 --- a/docs/Doxyfile.in +++ b/docs/Doxyfile.in @@ -296,10 +296,7 @@ OPTIMIZE_OUTPUT_FOR_PROLOG = YES # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. -EXTENSION_MAPPING = md \ - pl=Prolog \ - yap=Prolog \ - ypp=Prolog +EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable @@ -798,7 +795,7 @@ WARN_LOGFILE = # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. -INPUT = @DOC_INPUT_FILES@ +INPUT = @CMAKE_SOURCE_DIR@ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses @@ -884,7 +881,7 @@ RECURSIVE = YES # Note that relative paths are relative to the directory from which doxygen is # run. -EXCLUDE = +EXCLUDE = @DOCS_DIR_EXCLUDE@ # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded @@ -1090,7 +1087,7 @@ VERBATIM_HEADERS = YES # classes, structs, unions or interfaces. # The default value is: YES. -ALPHABETICAL_INDEX = NO +ALPHABETICAL_INDEX = YES # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in # which the alphabetical index list will be split. diff --git a/docs/md/builtins.md b/docs/md/core.md similarity index 88% rename from docs/md/builtins.md rename to docs/md/core.md index 10dd33d6b..e5f25b9ef 100644 --- a/docs/md/builtins.md +++ b/docs/md/core.md @@ -1,10 +1,14 @@ + @defgroup builtins Core Built-ins -@{ + +[TOC] -@brief This chapter describes the core built-in predicates that control the execution of +This chapter describes the core built-in predicates that control the execution of Prolog programs, provide fundamental functionality such as termm manipulation or arithmetic, and support interaction with external -resources, +resources. + +@{ Many of the predicates described here have been standardised by the International Standard Organization. The corresponding standartised subset of Prolog also known as ISO-Prolog. @@ -20,6 +24,8 @@ notation will be used: + an argument with no preceding symbol can be used in both ways. -[TOC] + + @} + diff --git a/docs/md/packages.md b/docs/md/packages.md index 4d4d869ca..7bf6e0091 100644 --- a/docs/md/packages.md +++ b/docs/md/packages.md @@ -1,6 +1,8 @@ YAP packages {#packages} ============ +[TOC] + + @ref real + @subpage BDDs @@ -11,7 +13,7 @@ YAP packages {#packages} + @ref PFL - + @subpage ProbLog1 + + @subpage problog + @ref python diff --git a/docs/md/yap.md b/docs/md/yap.md index 85a0ed893..364594002 100644 --- a/docs/md/yap.md +++ b/docs/md/yap.md @@ -21,7 +21,7 @@ The manual is organised as follows: + @ref run -+ @ref builtins ++ @subpage builtins + @ref extensions diff --git a/mkdocs/mkdocs.yml b/mkdocs/mkdocs.yml index 7be6ab53e..6abc6cb26 100644 --- a/mkdocs/mkdocs.yml +++ b/mkdocs/mkdocs.yml @@ -5,10 +5,7 @@ markdown_extensions: - toc: permalink: True - sane_lists - use_directory_urls: false plugins: - search - awesome-pages: filename: .index - disable_auto_arrange_index: false - collapse_single_pages: true \ No newline at end of file diff --git a/os/charsio.c b/os/charsio.c index f531d312e..f199a9544 100644 --- a/os/charsio.c +++ b/os/charsio.c @@ -586,7 +586,7 @@ static Int put_code(USES_REGS1) { /* '$put'(Stream,N) */ return (FALSE); if (GLOBAL_Stream[sno].status & Binary_Stream_f) { UNLOCK(GLOBAL_Stream[sno].streamlock); - Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "put/2"); + Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "put/2"); return (FALSE); } @@ -626,7 +626,7 @@ static Int put_char_1(USES_REGS1) { /* '$put'(,N) */ LOCK(GLOBAL_Stream[sno].streamlock); if (GLOBAL_Stream[sno].status & Binary_Stream_f) { UNLOCK(GLOBAL_Stream[sno].streamlock); - Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "put/2"); + Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "put/2"); return (FALSE); } GLOBAL_Stream[sno].stream_wputc(sno, ch); @@ -664,7 +664,7 @@ static Int put_char(USES_REGS1) { /* '$put'(Stream,N) */ return (FALSE); if (GLOBAL_Stream[sno].status & Binary_Stream_f) { UNLOCK(GLOBAL_Stream[sno].streamlock); - Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "put/2"); + Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "put/2"); return (FALSE); } GLOBAL_Stream[sno].stream_wputc(sno, (int)IntegerOfTerm(Deref(ARG2))); @@ -698,7 +698,7 @@ static Int tab_1(USES_REGS1) { /* nl */ LOCK(GLOBAL_Stream[sno].streamlock); if (GLOBAL_Stream[sno].status & Binary_Stream_f) { UNLOCK(GLOBAL_Stream[sno].streamlock); - Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "user_output"); + Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "user_output"); return (FALSE); } @@ -738,7 +738,7 @@ static Int tab(USES_REGS1) { /* nl(Stream) */ if (GLOBAL_Stream[sno].status & Binary_Stream_f) { UNLOCK(GLOBAL_Stream[sno].streamlock); - Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "nl/0"); + Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "nl/0"); return (FALSE); } diff --git a/packages/ProbLog/problog.md b/packages/ProbLog/problog.md new file mode 100644 index 000000000..ede92c3d6 --- /dev/null +++ b/packages/ProbLog/problog.md @@ -0,0 +1,66 @@ +The Problog-I Language and Learning System {#problog} +===================================== + +[TOC] + +This document is intended as a user guide for the users of ProbLog-I. +ProbLog is a probabilistic Prolog, a probabilistic logic programming +language, which is integrated in YAP-Prolog. Most of the work in ProbLog is now based on(Prolog-II), but we still maintain ProbLog-I in order to experiment with close integration of probabilistic nd logical systems. + +@section InstallingProbLog Installing ProbLog + + +You will need the CUDD binary decision daagram generator. CUDD is available in Fedora Linux, MacPorts and other Linux distributions. If it is not available in your system, please fetch it from: + +- [git@github.com:vscosta/cudd.git] + +To compile CUDD you will need to run: + +- `./configure --enable-dynamic=true` +- `make` +- `make -j install` + +@section RunningProbLog Running ProbLog + +To run ProbLog, go your ProbLog folder (eg. $\sim$/problog), and start +YAP (eg. $\sim$/yap/yap). This will start YAP with ProbLog +functionality. + +To use ProbLog, the ProbLog module has to be loaded at the top of your +Prolog programs. This is done with the following statement: + +> *:- use_module('../path/to/problog').* + +where '../path/to/problog' represents the path to the problog.yap module +(ie. without the extension) from the current folder from where YAP was +started. + + + +Similarly, to use the ProbLog learning module, use: + +> *:- use_module('../path/to/problog_learning').* + +@section EncodingProbs Encoding Probabilistic Facts + +A probabilistic fact is encoded in ProbLog by preceding a predicate with +a probability value. For example: + +> *0.5::heads(_).* + +encodes the fact that there's 50% chance of getting heads when tossing +an unbiassed coin. + +@subsection EncodingPars Encoding Parameter Learning Facts + +Instead of probabilities every fact has a t( ) prefix. The t stands for +tunable and indicate that ProbLog should learn the probability. The +number between the parentheses indicates the ground truth probability. +It is ignored by the learning algorithm and if you do not know the +ground truth, you can write t(_). The ground truth is used after +learning to estimate the distance of the learned model parameters to the +ground truth model parameters. For example: + +> t(0.5)::heads(1). + + diff --git a/packages/ProbLog/problog.tex b/packages/ProbLog/problog.tex deleted file mode 100644 index 7bdfdc3fe..000000000 --- a/packages/ProbLog/problog.tex +++ /dev/null @@ -1,518 +0,0 @@ -\documentclass[a4paper,12pt]{article} - -\usepackage{indentfirst} -\usepackage{hyperref} - -\author{} -\title{ProbLog User Manual} -\begin{document} - -\maketitle - -\newpage - -\tableofcontents - -\newpage - -\section{Introduction} - -This document is intended as a user guide for the users of ProbLog. ProbLog is a probabilistic Prolog, a probabilistic logic programming language, which is integrated in YAP-Prolog. - -\section{Installing ProbLog} - -\subsection{Requirements} - -For installing and running ProbLog, the following are required: -\begin{itemize} - \item a reasonable up-to-date computer, running Linux or Mac OS - \item YAP Prolog 5.1.3 (for Mac OS the more recent version 5.1.4 is needed) or YAP-6 -\end{itemize} - -\subsection{Download} -To install ProbLog, it is first necessary to download the ProbLog source files as well as SimpleCUDD. YAP Prolog also needs to be downloaded if it is not already installed on the machine. -\paragraph{} -For downloading ProbLog, go to: -\begin{itemize} - \item http://dtai.cs.kuleuven.be/problog/download.html -\end{itemize} -\paragraph{} -For downloading SimpleCUDD, go to: -\begin{itemize} - \item http://www.cs.kuleuven.be/$\sim$theo/tools/SimpleCUDD.tar.gz -\end{itemize} - -\subsection{Compiling YAP Prolog} - -ProbLog heavily depends on YAP Prolog. If YAP Prolog is already installed on your machine, proceed to the next section. - -Download and unpack YAP Prolog to $\sim$/yap, and install YAP in your home directory by typing: - -\begin{quotation} -cd $\sim$/yap - -./configure --prefix="$\sim$/yap" --exec-prefix="$\sim$/yap" - -make - -make install -\end{quotation} - -Some useful extra packages to install before configuring yap: -\begin{quotation} -sudo apt-get install libreadline6-dev - -sudo apt-get install libgmp3-dev - -sudo apt-get install g++ -\end{quotation} - -Afterwards, you can run YAP by calling $\sim$/yap/yap. Note: This will configure YAP with standard settings - which work fine in combination with ProbLog. In case you want to install YAP somewhere else or use different settings, please consult the YAP documentation. - -\subsection{Compiling ProbLog} - -Download the latest version of ProbLog and SimpleCUDD, as described in a previous section. Unpack ProbLog - for instance - to $\sim$/problog. Unpack SimpleCUDD in a subfolder - for instance - to $\sim$/problog/simlpecudd. Afterwards compile ProbLog by typing: - -\begin{quotation} -cd $\sim$/problog - -make -\end{quotation} - -This will compile CUDD and SimpleCUDD which are used by ProbLog for BDD operations. - -\section{Running ProbLog} - -To run ProbLog, go your ProbLog folder (eg. $\sim$/problog), and start YAP (eg. $\sim$/yap/yap). This will start YAP with ProbLog functionality. - -\section{Loading the ProbLog modules} - -To use ProbLog, the ProbLog module has to be loaded at the top of your Prolog programs. This is done with the following statement: -\begin{quotation} -\textit{:- use\_module('../path/to/problog').} -\end{quotation} -where '../path/to/problog' represents the path to the problog.yap module (ie. without the extension) from the current folder from where YAP was started. - -\paragraph{} -Similarly, to use the ProbLog learning module, use: -\begin{quotation} -\textit{:- use\_module('../path/to/problog\_learning').} -\end{quotation} - -\section{Encoding Probabilistic Facts} -A probabilistic fact is encoded in ProbLog by preceding a predicate with a probability value. For example: -\begin{quotation} -\textit{0.5::heads(\_).} -\end{quotation} -encodes the fact that there's 50\% chance of getting heads when tossing an unbiassed coin. - -\subsection{Encoding Parameter Learning Facts} - -Instead of probabilities every fact has a t( ) prefix. The t stands for tunable and indicate that ProbLog should learn the probability. The number between the parentheses indicates the ground truth probability. It is ignored by the learning algorithm and if you do not know the ground truth, you can write t(\_). The ground truth is used after learning to estimate the distance of the learned model parameters to the ground truth model parameters. For example: -\begin{quotation} -t(0.5)::heads(1). -\end{quotation} - -\section{ProbLog Predicates} - -This chapter describes the predicates defined by ProbLog for evaluating the probability of queries. - -In the description of the arguments of functors the following notation will be used: - -\begin{itemize} -\item a preceding plus sign will denote an argument as an "input argument" - it cannot be a free variable at the time of the call -\item a preceding minus sign will denote an "output argument" -\item an argument with no preceding symbol can be used in both ways -\end{itemize} - -\subsection{problog\_max} -\textit{problog\_max(+G, -Prob, -FactsUsed)} -\paragraph{} -This predicate returns the most likely explanation of proving the goal G and the facts used in achieving this explanation. - -\subsection{problog\_exact} -\textit{problog\_exact(+G, -Prob, -Status)} -\paragraph{} -This predicate returns the exact total probability of achieving the goal G and the status of the query. - -\subsection{problog\_kbest} -\textit{problog\_kbest(+G, +K, -Prob, -Status)} -\paragraph{} -This predicate returns the sum of the probabilities of the best K proofs of achieving the goal G and the status of the query. - -\subsection{problog\_montecarlo} -\textit{problog\_montecarlo(+G, +Interval\_width, -Prob)} -\paragraph{} -This predicate approximates the probability of achieving the goal G by using a Monte Carlo approach, with 95\% confidence in the given interval width. - -\subsection{problog\_delta} -\textit{problog\_delta(+G , +Interval\_width, -Bound\_low, -Bound\_up, -Status)} -\paragraph{} -This predicate returns the lower and upper bound of the probability of achieving the goal G by using an iterative -deepening approach with the given interval width. - -\subsection{problog\_threshold} -\textit{problog\_threshold(+G , +Prob, -Bound\_low, -Bound\_up, -Status)} -\paragraph{} -This predicate returns the lower and upper bound of the probability of achieving the goal G obtained by cutting the sld tree at the given probability for each branch. - -\subsection{problog\_low} -\textit{problog\_low(+G, +Prob, -Bound\_low, -Status)} -\paragraph{} -This predicate returns the lower bound of the probability of achieving the goal G obtained by cutting the sld tree at the given probability for each branch. - -\section{ProbLog Parameter Learning Predicates} - -\subsection{Training Example Predicate} -\textit{example(+N, +Q, +Prob)} -\paragraph{} -This predicate specifies an example. Every example has as input a unique identifier (N), a query (Q) and a probability (Prob) associated with it. - -Instead of queries, you can also give proofs as training example. They are encoded as the conjunction of the probabilistic facts used in the proof. - -\subsection{Test Example Predicate} -\textit{test\_example(+N, +Q, +Prob)} -\paragraph{} -This predicate specifies a test example. Every test example has as input a unique identifier (N), a query (Q) and a probability (Prob) associated with it. - -Test examples are ignored during learning but are used afterwards to check the performance of the model. The ID namespace is shared between the test examples and the training examples and you may only reuse an ID if the queries are identical. - -\subsection{Learning Predicates} -\textit{:- do\_learning(+N).} -\paragraph{} -Starts the learning algorithm with N iterations. -\paragraph{} -\textit{:- do\_learning(+N, +Epsilon).} -\paragraph{} -Starts the learning algorithm. The learning will stop after N iterations or if the difference of the Mean Squared Error (MSE) between two iterations gets smaller than Epsilon - depending on what happens first. - -\subsection{Learning Output} - -The output is created in the output subfolder of the current folder where YAP was started. There you will find the file log.dat which contains MSE on training and test set for every iteration, the timings, and some metrics on the gradient in CSV format. The files factprobs\_N.pl contain the fact probabilities after the Nth iteration and the files predictions\_N.pl contain the estimated probabilities for each training and test example - per default these file are generated every 5th iteration only. - -\section{Miscelaneous} - -Both the learning and the inference module have various parameters, or flags, that can be adjusted by the user. -The following predicates are defined by ProbLog to access and set these flags. - -\subsection{problog\_flags} -\textit{problog\_flags} -\paragraph{} -This predicate lists all the flags name, value, domain and description. - - -\subsection{problog\_flag} -\textit{problog\_flag(+Name, -Value)} -\paragraph{} -This predicate gives the value of the flag with the specified name. The supported flags are: -\paragraph{} -\texttt{use\_db\_trie} - -Flag telling whether to use the builtin trie to trie transformation. -The possible values for this flag are true or false. -\paragraph{} -\texttt{db\_trie\_opt\_lvl} - -Sets the optimization level for the trie to trie transformation -The possible values for this flag are any integer -\paragraph{} -\texttt{compare\_opt\_lvl} - -Flag telling whether to use comparison mode for the optimization level. -The possible values for this flag are true or false. -\paragraph{} -\texttt{db\_min\_prefix} - -Sets the minimum size of the prefix for dbtrie to optimize. -The possible values for this flag are any integer -\paragraph{} -\texttt{use\_naive\_trie} - -Flag telling whether to use the naive algorithm to generate bdd scripts. -The possible values for this flag are true or false. -\paragraph{} -\texttt{use\_old\_trie} - -Flag telling whether to use the old not nested trie to trie transformation. -The possible values for this flag are true or false. -\paragraph{} -\texttt{use\_dec\_trie} - -Flag telling whether to use the decomposition method. -The possible values for this flag are true or false. -\paragraph{} -\texttt{subset\_check} - -Flag telling whether to perform subset check in nested tries. -The possible values for this flag are true or false. -\paragraph{} -\texttt{deref\_terms} - -Flag telling whether to dereference BDD terms after their last use. -The possible values for this flag are true or false. -\paragraph{} -\texttt{trie\_preprocess} - -Flag telling whether to perform a preprocess step to nested tries. -The possible values for this flag are true or false. -\paragraph{} -\texttt{refine\_anclst} - -Flag telling whether to refine the ancestor list with their children. -The possible values for this flag are true or false. -\paragraph{} -\texttt{anclst\_represent} - -Flag that sets the representation of the ancestor list. -The possible values for this flag are list or integer -\paragraph{} -\texttt{max\_depth} - -Sets the maximum proof depth. -The possible values for this flag are any integer. -\paragraph{} -\texttt{retain\_tables} - -Flag telling whether to retain tables after the query. -The possible values for this flag are true or false. -\paragraph{} -\texttt{mc\_batchsize} - -Flag related to Monte Carlo Sampling that sets the number of samples before update. -The possible values for this flag are any integer greater than zero. -\paragraph{} -\texttt{min\_mc\_samples} - -Flag related to Monte Carlo Sampling that sets the minimum number of samples before convergence. -The possible values for this flag are any integer greater than or equal to zero. -\paragraph{} -\texttt{max\_mc\_samples} - -Flag related to Monte Carlo Sampling that sets the maximum number of samples waiting to converge. -The possible values for this flag are any integer greater than or equal to zero. -\paragraph{} -\texttt{randomizer} - -Flag related to Monte Carlo Sampling telling whether the random numbers are repeatable or not. -The possible values for this flag are repeatable or nonrepeatable. -\paragraph{} -\texttt{search\_method} - -Flag related to DNF Monte Carlo Sampling that sets the search method for picking the proof. -The possible values for this flag are linear or binary. -\paragraph{} -\texttt{represent\_world} - -Flag related to Monte Carlo Sampling that sets the structure that represents sampled world. -The possible values for this flag are list, record, array or hash\_table -\paragraph{} -\texttt{first\_threshold} - -Flag related to inference that sets the starting threshold of iterative deepening. -The possible values for this flag are a number in the interval (0,1). -\paragraph{} -\texttt{last\_threshold} - -Flag related to inference that sets the stopping threshold of iterative deepening. -The possible values for this flag are a number in the interval (0,1). -\paragraph{} -\texttt{id\_stepsize} - -Flag related to inference that sets the threshold shrinking factor of iterative deepening. -The possible values for this flag are a number in the interval [0,1]. -\paragraph{} -\texttt{prunecheck} - -Flag related to inference telling whether to stop derivations including all facts of known proofs. -The possible values for this flag are on or off. -\paragraph{} -\texttt{maxsteps} - -Flag related to inference that sets the max. number of prob. steps per derivation. -The possible values for this flag are any integer greater than zero. -\paragraph{} -\texttt{mc\_logfile} - -Flag related to MCMC that sets the logfile for montecarlo. -The possible values for this flag are any valid filename. -\paragraph{} -\texttt{bdd\_time} - -Flag related to BDD that sets the BDD computation timeout in seconds. -The possible values for this flag are any integer greater than zero. -\paragraph{} -\texttt{bdd\_par\_file} - -Flag related to BDD that sets the file for BDD variable parameters. -The possible values for this flag are any valid filename. -\paragraph{} -\texttt{bdd\_result} - -Flag related to BDD that sets the file to store result calculated from BDD. -The possible values for this flag are any valid filename. -\paragraph{} -\texttt{bdd\_file} - -Flag related to BDD that sets the file for the BDD script. -The possible values for this flag are any valid filename. -\paragraph{} -\texttt{save\_bdd} - -Flag related to BDD telling whether to save BDD files for (last) lower bound. -The possible values for this flag are true or false. -\paragraph{} -\texttt{dynamic\_reorder} - -Flag related to BDD telling whether to use dynamic re-ordering for BDD. -The possible values for this flag are true or false. -\paragraph{} -\texttt{bdd\_static\_order} - -Flag related to BDD telling whether to use static order. -The possible values for this flag are true or false. -\paragraph{} -\texttt{static\_order\_file} - -Flag related to BDD that sets the file for BDD static order. -The possible values for this flag are any valid filename. -\paragraph{} -\texttt{verbose} - -Flag telling whether to output intermediate information. -The possible values for this flag are true or false. -\paragraph{} -\texttt{show\_proofs} - -Flag telling whether to output proofs. -The possible values for this flag are true or false. -\paragraph{} -\texttt{triedump} - -Flag telling whether to generate the file: trie\_file containing the trie structure. -The possible values for this flag are true or false. -\paragraph{} -\texttt{dir} - -Flag telling the location of the output files directory. -The possible values for this flag are any valid directory name. - -\subsection{set\_problog\_flag} -\textit{set\_problog\_flag(+Name, +Value)} -\paragraph{} -This predicate sets the value of the given flag. The supported flags are the ones listed in above. - -\subsection{learning\_flags} -\textit{learning\_flags} -\paragraph{} -This predicate lists all the learning flags name, value, domain and description. - -\subsection{learning\_flag} -\textit{learning\_flag(+Name, -Value)} -\paragraph{} -This predicate gives the value of the learning flag with the specified name. The supported flags are: -\paragraph{} -\texttt{output\_directory} - -Flag setting the directory where to store results. -The possible values for this flag are any valid path name. -\paragraph{} -\texttt{query\_directory} - -Flag setting the directory where to store BDD files. -The possible values for this flag are any valid path name. -\paragraph{} -\texttt{verbosity\_level} - -Flag telling how much output shall be given. -The possible values for this flag are an integer between 0 and 5 (0=nothing, 5=all). -\paragraph{} -\texttt{reuse\_initialized\_bdds} - -Flag telling whether to reuse BDDs from previous runs. -The possible values for this flag are true or false. -\paragraph{} -\texttt{rebuild\_bdds} - -Flag telling whether to rebuild BDDs every nth iteration. -The possible values for this flag are any integer greater or equal to zero (0=never). -\paragraph{} -\texttt{check\_duplicate\_bdds} - -Flag telling whether to store intermediate results in hash table. -The possible values for this flag are true or false. -\paragraph{} -\texttt{init\_method} - -Flag setting the ProbLog predicate to search proofs. -The possible values for this flag are of the form: (+Query,-P,+BDDFile,+ProbFile,+Call). For example: A,B,C,D,problog\_kbest\_save(A,100,B,E,C,D) -\paragraph{} -\texttt{probability\_initializer} - -Flag setting the ProbLog predicate to initialize probabilities. -The possible values for this flag are of the form: (+FactID,-P,+Call). For example: A,B,random\_probability(A,B) -\paragraph{} -\texttt{log\_frequency} - -Flag telling whether to log results every nth iteration. -The possible values for this flag are any integer greater than zero. -\paragraph{} -\texttt{alpha} - -Flag setting the weight of negative examples. -The possible values for this flag are number or "auto" (auto=n\_p/n\_n). -\paragraph{} -\texttt{slope} - -Flag setting the slope of the sigmoid function. -The possible values for this flag are any real number greater than zero. -\paragraph{} -\texttt{learning\_rate} - -Flag setting the default Learning rate (if line\_search=false) -The possible values for this flag are any number greater than zero or "examples`` -\paragraph{} -\texttt{line\_search} - -Flag telling whether to use line search to estimate the learning rate. -The possible values for this flag are true or false. -\paragraph{} -\texttt{line\_search\_tau} - -Flag setting the Tau value for line search. -The possible values for this flag are a number in the interval (0,1). -\paragraph{} -\texttt{line\_search\_tolerance} - -Flag setting the tolerance value for line search. -The possible values for this flag are any number greater than zero. -\paragraph{} -\texttt{line\_search\_interval} - -Flag setting the interval for line search. -The possible values for this flag are of the form a,b where a and b are numbers and define an interval with $0<=a get_fact_list(FactIDs, Facts); Facts = FactIDs). @@ -2919,6 +2539,12 @@ problog_kbest_save(Goal, K, Prob, Status, BDDFile, ParamFile) :- % ; % true). + +/** + * @pred problog_kbest(+G, +K, -Prob, -Status) + * + * This predicate returns the sum of the probabilities of the best K proofs of achieving the goal G and the status of the query. +*/ problog_kbest(Goal, K, Prob, Status) :- problog_flag(first_threshold,InitT), init_problog_kbest(InitT), @@ -3060,13 +2686,14 @@ to_external_format_with_reverse([LogP-FactIDs|Intern],Acc,Extern) :- Facts = FactIDs), to_external_format_with_reverse(Intern,[Prob-Facts|Acc],Extern). -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% exact probability -% problog_exact(+Goal,-Prob,-Status) -% -% using all proofs = using all proofs with probability > 0 -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +/** + * @pred problog_exact(+G, -Prob, -Status) + * +This predicate returns the exact total probability of achieving the goal G and the status of the query. + + using all proofs = using all proofs with probability > 0 +*/ problog_exact(Goal,Prob,Status) :- problog_control(on, exact), problog_low(Goal,0,Prob,Status), @@ -3132,13 +2759,17 @@ problog_exact_nested(Goal, Prob, Status):- delete_ptree(Trie_Completed_Proofs), problog_restore_state(State). -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% probability by sampling: -% running another N samples until 95percentCI-width PyList_GET_SIZE(pyl)) - pyErrorAndReturn( false, false); - for (i=0; i < sz; i++) { - if (!PL_get_list(plist, targ, plist)) { - pyErrorAndReturn( false, false); - } - PyObject *t = term_to_python(targ, true, NULL); - PyList_SET_ITEM(pyl, i, t); - } - if (PL_is_variable(tlen)) { - PL_unify_int64(tlen, sz); -} else { -python_assign(tlen, PyLong_FromUnsignedLong(sz), NULL); -} - pyErrorAndReturn( true, false); -} - -install_t install_pl2pl(void) { - PL_register_foreign("array_to_python_list", 4, array_to_python_list, 0); - PL_register_foreign("array_to_python_tuple", 4, array_to_python_tuple, 0); - PL_register_foreign("array_to_python_view", 5, array_to_python_view, 0); - PL_register_foreign("prolog_list_to_python_list", 3, prolog_list_to_python_list, 0); -} diff --git a/packages/packages/python/pl2py.c b/packages/packages/python/pl2py.c deleted file mode 100644 index 377592d82..000000000 --- a/packages/packages/python/pl2py.c +++ /dev/null @@ -1,214 +0,0 @@ - - -#include "py4yap.h" - -extern PyObject *py_Local, *py_Global; - -PyObject *YE(term_t t, int line, const char *file, const char *code) { - YAPPy_ThrowError__(file, code, line, SYSTEM_ERROR_INTERNAL,t,""); -} - -void YEM(const char *exp, int line, const char *file, const char *code) { - fprintf(stderr, "**** Warning,%s@%s:%d: failed while executing %s\n", code, - file, line, exp); -} - -static PyObject *s_to_python(const char *s, bool eval, PyObject *p0) { - PyObject *o; - if (eval) { - o = PythonLookup(s, p0); - /* if (!o) - return o; - */ - } else { - o = PythonLookupSpecial(s); - } - if (o) { - Py_INCREF(o); - return CHECKNULL(YAP_MkStringTerm(s), o); - } else { - PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL); - return pobj; - } -} - -/** - * obtain the object matching a certain string. - * - * @param t handle to Prolog term - * @param t whether should try to evaluate evaluables. - * - * @return a Python object descriptor or NULL if failed - */ -X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0) { - char *buf = malloc(strlen(s) + 1), *child; - PyObject *p1; - while ((child = strchr(s, '.')) != NULL) { - size_t len = child - s; - strncpy(buf, s, len); - buf[len] = '\0'; - p1 = s_to_python(buf, eval, p0); - Py_DecRef(p0); - Py_IncRef(p1) - s = child + 1; - p0 = p1; - } - p1 = s_to_python(s, eval, p0); - Py_DecRef(p0); - return p1; -} - -/** - * term_to_python translates and evaluates from Prolog to Python - * - * @param t handle to Prolog term - * @param t whether should try to evaluate evaluables. - * - * @return a Python object descriptor or NULL if failed - */ -PyObject *term_to_python(term_t t, bool eval, PyObject *o) { - // o≈ - PyObject *o;\ - YAP_Term yt = YAP_GetFromSlot(t); - // Yap_DebugPlWriteln(yt); - switch (PL_term_type(t)) { - case PL_VARIABLE: { - if (t == 0) { - YAPPy_ThrowErrorYA(SYSTEM_ERROR_INTERNAL,t,""); -t } - PyObject *out = PyTuple_New(1); - PyTuple_SET_ITEM(out, 0, PyLong_FromLong(t)); - Py_IncRef(out); - rc = term_to_nametuple("v", 1, out); - Py_IncRef(rc); - }; - case PL_ATOM: { - YAP_Atom at = YAP_AtomOfTerm(yt); - const char *s; - - s = YAP_AtomName(at); - if (eval) { - o = PythonLookup(s, o); - /* if (!o) - return o; - */ - } else { - o = PythonLookupSpecial(s); - } - if (o) { - Py_INCREF(o); - return CHECKNULL(t, o); - } - } - case PL_STRING: { - const char *s = NULL; - if (YAP_IsAtomTerm(yt)) { - s = YAP_AtomName(YAP_AtomOfTerm(yt)); - } else if (YAP_IsStringTerm(yt)) { - s = YAP_StringOfTerm(yt); - } else { - return CHECKNULL(t, NULL); - } -#if PY_MAJOR_VERSION < 3 - if (proper_ascii_string(s)) { - PyObject *o = PyString_FromStringAndSize(s, strlen(s)); - Py_IncRef(o) - return CHECKNULL(t, o); - } else -#endif - { - // char *p = malloc(strlen(s)+1); - //strcpy(p, s); - PyObject *pobj = PyUnicode_FromString(s); - Py_IncRef(pobj); - return CHECKNULL(t, pobj); - } - } break; - case PL_INTEGER: { - int64_t j; - if (!PL_get_int64_ex(t, &j)) - return CHECKNULL(t, NULL); -#if PY_MAJOR_VERSION < 3 - PyObject *o = PyInt_FromLong(j); - return CHECKNULL(t, o); -#else - PyObject *o = PyLong_FromLong(j); - return CHECKNULL(t, o); -#endif - } - - case PL_FLOAT: { - PyObject *out; - double fl; - if (!PL_get_float(t, &fl)) - return CHECKNULL(t, NULL); - out = PyFloat_FromDouble(fl); - return CHECKNULL(t, out); - } - default: { - term_t tail = PL_new_term_ref(), arg; - size_t len, i; - if (PL_skip_list(t, tail, &len) && PL_get_nil(tail)) { - PyObject *out, *a; - - arg = tail; - out = PyList_New(len); - if (!out) { - PL_reset_term_refs(tail); - return CHECKNULL(t, Py_None); - } - - for (i = 0; i < len; i++) { - if (!PL_get_list(t, arg, t)) { - YAPPy_ThrowErrorYA(SYSTEM_ERROR_INTERNAL,t,""); - } - a = term_to_python(arg, eval, o); - if (a) { - if (PyList_SetItem(out, i, a) < 0) { - YAPPy_ThrowErrorYA(SYSTEM_ERROR_INTERNAL,t,""); - } - } - } - PL_reset_term_refs(tail); - return CHECKNULL(t, out); - } else { - functor_t fun; - PyObject *rc; - - if (!PL_get_functor(t, &fun)) { - PL_reset_term_refs(tail); - return CHECKNULL(t, Py_None); - } - if (eval) - rc = compound_to_pyeval(t, o); - else - rc = compound_to_pytree(t, o); - PL_reset_term_refs(tail); - return rc; - } - } - } - return CHECKNULL(t, Py_None); -} - -PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o) { - if (t == 0) - return NULL; - term_t yt = YAP_InitSlot(t); - o = term_to_python(yt, eval, o); - PL_reset_term_refs(yt); - return o; -} - -PyObject *deref_term_to_python(term_t t) { - // Yap_DebugPlWrite(YAP_GetFromSlot(t)); fprintf(stderr, " here I - // am\n"); - YAP_Term yt = YAP_GetFromSlot(t); - if (YAP_IsVarTerm(yt)) { - char s[32]; - char *o = YAP_WriteBuffer(yt, s, 31, 0); - PyObject *p = PyUnicode_FromString(o); - return p; - } - return term_to_python(t, false, NULL); -} diff --git a/packages/packages/python/py2pl.c b/packages/packages/python/py2pl.c deleted file mode 100644 index 2b4ace5c4..000000000 --- a/packages/packages/python/py2pl.c +++ /dev/null @@ -1,319 +0,0 @@ - -#include "py4yap.h" - -static foreign_t repr_term(PyObject *pVal, term_t t) { - term_t to = PL_new_term_ref(), t1 = PL_new_term_ref(); - PL_put_pointer(t1, pVal); - PL_cons_functor(to, FUNCTOR_pointer1, t1); - Py_INCREF(pVal); - return PL_unify(t, to); -} - -foreign_t assign_to_symbol(term_t t, PyObject *e); - -foreign_t assign_to_symbol(term_t t, PyObject *e) { - char *s = NULL; - if (!PL_get_atom_chars(t, &s)) { - return false; - } - PyObject *dic; - if (!lookupPySymbol(s, NULL, &dic)) - dic = py_Main; - return PyObject_SetAttrString(dic, s, e) == 0; -} - -foreign_t python_to_term(PyObject *pVal, term_t t) { - bool rc = true; - term_t to = PL_new_term_ref(); - // fputs(" <<*** ",stderr); PyObject_Print(pVal,stderr,0); - // fputs("<<***\n",stderr); - if (pVal == Py_None) { - // fputs("<<*** ",stderr);Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs(" - // >>***\n",stderr); - rc = PL_unify_atom(t, ATOM_none); - // fputs("<<*** ",stderr);Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs(" - // >>***\n",stderr); - } else if (PyBool_Check(pVal)) { - rc = rc && PL_unify_bool(t, PyObject_IsTrue(pVal)); - } else if (PyLong_Check(pVal)) { - rc = rc && PL_unify_int64(t, PyLong_AsLong(pVal)); -#if PY_MAJOR_VERSION < 3 - } else if (PyInt_Check(pVal)) { - rc = rc && PL_unify_int64(t, PyInt_AsLong(pVal)); -#endif - } else if (PyFloat_Check(pVal)) { - rc = rc && PL_unify_float(t, PyFloat_AsDouble(pVal)); - } else if (PyComplex_Check(pVal)) { - term_t t1 = PL_new_term_ref(), t2 = PL_new_term_ref(); - if (!PL_put_float(t1, PyComplex_RealAsDouble(pVal)) || - !PL_put_float(t2, PyComplex_ImagAsDouble(pVal)) || - !PL_cons_functor(to, FUNCTOR_complex2, t1, t2)) { - rc = false; - } else { - rc = rc && PL_unify(t, to); - } - } else if (PyUnicode_Check(pVal)) { - atom_t tmp_atom; - -#if PY_MAJOR_VERSION < 3 - size_t sz = PyUnicode_GetSize(pVal) + 1; - wchar_t *ptr = malloc(sizeof(wchar_t) * sz); - sz = PyUnicode_AsWideChar((PyUnicodeObject *)pVal, ptr, sz - 1); - tmp_atom = PL_new_atom_wchars(sz, ptr); - free(ptr); -#else - const char *s = PyUnicode_AsUTF8(pVal); - tmp_atom = PL_new_atom(s); -#endif - rc = rc && PL_unify_atom(t, tmp_atom); - } else if (PyByteArray_Check(pVal)) { - atom_t tmp_atom = PL_new_atom(PyByteArray_AsString(pVal)); - rc = rc && PL_unify_atom(t, tmp_atom); -#if PY_MAJOR_VERSION < 3 - } else if (PyString_Check(pVal)) { - atom_t tmp_atom = PL_new_atom(PyString_AsString(pVal)); - rc = rc && PL_unify_atom(t, tmp_atom); -#endif - } else if (PyTuple_Check(pVal)) { - Py_ssize_t i, sz = PyTuple_Size(pVal); - functor_t f; - const char *s; - if (sz == 0) { - rc = rc && PL_unify_atom(t, ATOM_brackets); - } else { - if ((s = (Py_TYPE(pVal)->tp_name))) { - if (!strcmp(s, "H")) { - pVal = PyTuple_GetItem(pVal, 0); - if (pVal == NULL) { - pVal = Py_None; - PyErr_Clear(); - } - } - if (s[0] == '$') { - char *ns = malloc(strlen(s) + 5); - strcpy(ns, "__"); - strcat(ns, s + 1); - strcat(ns, "__"); - f = PL_new_functor(PL_new_atom(ns), sz); - } else { - f = PL_new_functor(PL_new_atom(s), sz); - } - } else { - f = PL_new_functor(ATOM_t, sz); - } - if (PL_unify_functor(t, f)) { - for (i = 0; i < sz; i++) { - if (!PL_get_arg(i + 1, t, to)) - rc = false; - PyObject *p = PyTuple_GetItem(pVal, i); - if (p == NULL) { - PyErr_Clear(); - p = Py_None; - } - rc = rc && python_to_term(p, to); - } - } else { - rc = false; - } - // fputs(" ||*** ",stderr); Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs(" - // ||***\n",stderr); - } - } else if (PyList_Check(pVal)) { - Py_ssize_t i, sz = PyList_GET_SIZE(pVal); - - if (sz == 0) { - rc = rc && PL_unify_nil(t); - } else { - for (i = 0; i < sz; i++) { - PyObject *obj; - if (!PL_unify_list(t, to, t)) { - rc = false; - break; - } - if ((obj = PyList_GetItem(pVal, i)) == NULL) { - obj = Py_None; - } - rc = rc && python_to_term(obj, to); - } - rc = rc && PL_unify_nil(t); - } - // fputs("[***] ", stderr); - // Yap_DebugPlWrite(yt); fputs("[***]\n", stderr); - } else if (PyDict_Check(pVal)) { - Py_ssize_t pos = 0; - term_t to = PL_new_term_ref(), ti = to; - int left = PyDict_Size(pVal); - PyObject *key, *value; - - if (left == 0) { - rc = rc && PL_unify_atom(t, ATOM_curly_brackets); - } else { - while (PyDict_Next(pVal, &pos, &key, &value)) { - term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint, - tnew = PL_new_term_ref(); - /* do something interesting with the values... */ - if (!python_to_term(key, tkey)) { - continue; - } - if (!python_to_term(value, tval)) { - continue; - } - /* reuse */ - tint = tkey; - if (!PL_cons_functor(tint, FUNCTOR_colon2, tkey, tval)) { - rc = false; - continue; - } - if (--left) { - if (!PL_cons_functor(tint, FUNCTOR_comma2, tint, tnew)) - PL_reset_term_refs(tkey); - rc = false; - } - if (!PL_unify(ti, tint)) { - rc = false; - } - ti = tnew; - PL_reset_term_refs(tkey); - } - rc = rc && PL_unify(t, to); - } - } else { - rc = rc && repr_term(pVal, t); - } - PL_reset_term_refs(to); - return rc; -} - -X_API YAP_Term pythonToYAP(PyObject *pVal) { - term_t t = PL_new_term_ref(); - if (pVal == NULL || !python_to_term(pVal, t)) { - PL_reset_term_refs(t); - return 0; - } - YAP_Term tt = YAP_GetFromSlot(t); - PL_reset_term_refs(t); - Py_DECREF(pVal); - return tt; -} - -PyObject *py_Local, *py_Global; - -/** - * assigns the Python RHS to a Prolog term LHS, ie LHS = RHS - * - * @param root Python environment - * @param t left hand side, in Prolog, may be - * - a Prolog variable, exports the term to Prolog, A <- RHS - * - Python variable A, A <- RHS - * - Python variable $A, A <- RHS - * - Python string "A", A <- RHS - * - Python array range - * @param e the right-hand side - * - * @return -1 on failure. - * - * Note that this is an auxiliary routine to the Prolog - *python_assign. - */ -bool python_assign(term_t t, PyObject *exp, PyObject *context) { - context = find_obj(context, t, false); - // Yap_DebugPlWriteln(yt); - switch (PL_term_type(t)) { - case PL_VARIABLE: { - if (context == NULL) // prevent a.V= N*N[N-1] - return python_to_term(exp, t); - } - - case PL_ATOM: { - char *s = NULL; - PL_get_atom_chars(t, &s); - if (!context) - context = py_Main; - return PyObject_SetAttrString(context, s, exp) == 0; - } - case PL_STRING: - case PL_INTEGER: - case PL_FLOAT: - // domain or type erro? - return false; - default: { - term_t tail = PL_new_term_ref(), arg = PL_new_term_ref(); - size_t len, i; - if (PL_skip_list(t, tail, &len) && - PL_get_nil(tail)) { // true list - - bool o = true; - if (PySequence_Check(exp) && PySequence_Length(exp) == len) - - for (i = 0; i < len; i++) { - PyObject *p; - if (!PL_get_list(t, arg, t)) { - PL_reset_term_refs(tail); - o = false; - p = Py_None; - } - if ((p = PySequence_GetItem(exp, i)) == NULL) - p = Py_None; - if (!python_assign(arg, p, context)) { - PL_reset_term_refs(tail); - o = false; - } - } - PL_reset_term_refs(tail); - return o; - } else { - functor_t fun; - - if (!PL_get_functor(t, &fun)) { - PL_reset_term_refs(tail); - return false; - } - - if (fun == FUNCTOR_sqbrackets2) { - if (!PL_get_arg(2, t, tail)) { - PL_reset_term_refs(tail); - return false; - } - - PyObject *o = term_to_python(tail, true, context); - if (!PL_get_arg(2, t, tail) && !PL_get_nil(tail)) { - PL_reset_term_refs(tail); - return false; - } - if (!PL_get_arg(1, t, t)) { - PL_reset_term_refs(tail); - return false; - } - PL_reset_term_refs(tail); - PyObject *i = term_to_python(t, true, NULL); - if (!i) { - return false; - } - if (PyList_Check(i)) { - i = PyList_GetItem(i, 0); - if (i == NULL) - i = Py_None; - long int j; - if (PyList_Check(o)) { -#if PY_MAJOR_VERSION < 3 - if (PyInt_Check(i)) - j = PyInt_AsLong(i); - else -#endif - if (PyLong_Check(i)) - j = PyLong_AsLong(i); - else - return NULL; - return PyList_SetItem(o, j, exp) == 0; - } - if (PyDict_Check(i)) { - return PyDict_SetItem(o, i, exp) == 0; - } - return PyObject_SetAttr(o, i, exp) == 0; - } - } - } - } - } - return NULL; -} diff --git a/packages/packages/python/pybips.c b/packages/packages/python/pybips.c deleted file mode 100644 index 616702440..000000000 --- a/packages/packages/python/pybips.c +++ /dev/null @@ -1,1239 +0,0 @@ -/** - * - * @section Python Built-Ins - * - * The Python engine includes a large number of Python built-ins. Some - * of them are interfaced here. - */ - -//@{ - -#include "py4yap.h" - -static PyObject *finalLookup(PyObject *i, const char *s) { - PyObject *rc; - if (i == NULL) - return NULL; - if (strcmp(s, "none") == 0) - return Py_None; - if (PyDict_Check(i)) { - if ((rc = PyDict_GetItemString(i, s))) - return rc; - } - if (PyModule_Check(i)) { - if ((rc = PyDict_GetItemString(i, s))) - return rc; - } - if (PyObject_HasAttrString(i, s)) { - return PyObject_GetAttrString(i, s); - } - return NULL; -} - -PyObject *PythonLookupSpecial(const char *s) { - if (s == NULL) - return NULL; - if (strcmp(s, "true") == 0) { - return Py_True; - } - if (strcmp(s, "false") == 0) { - return Py_False; - } - if (strcmp(s, "[]") == 0) { - return PyList_New(0); - } - if (strcmp(s, "{}") == 0) { - return PyDict_New(); - /* return __main__,s */ - } - return NULL; -} - -PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) { - PyObject *out = NULL; - if (!sp) - return NULL; - if ((out = finalLookup(pContext, sp))) { - return out; - } - if ((out = finalLookup(py_Context, sp))) { - return out; - } - PyObject *py_Builtin = PyEval_GetBuiltins(); - if ((out = finalLookup(py_Builtin, sp))) { - return out; - } - PyObject *py_Local = PyEval_GetLocals(); - if ((out = finalLookup(py_Local, sp)) && out != Py_None) { - return out; - } - PyObject *py_Global = PyEval_GetGlobals(); - if ((out = finalLookup(py_Global, sp))) { - return out; - } - if ((out = finalLookup(py_ModDict, sp))) { - return out; - } - if ((out = finalLookup(py_Main, sp))) { - return out; - } - return NULL; -} - -PyObject *PythonLookup(const char *s, PyObject *oo) { - PyObject *o; - if ((o = PythonLookupSpecial(s))) - return o; - if ((o = lookupPySymbol(s, oo, NULL)) == NULL) - return NULL; - else { - Py_INCREF(o); - return o; - } -} - -PyObject *find_obj(PyObject *ob, term_t l, bool eval) { - YAP_Term hd, yt; - - py_Context = NULL; - yt = YAP_GetFromSlot(l); - while (YAP_IsPairTerm(yt)) { - hd = YAP_HeadOfTerm(yt); - ob = yap_to_python(hd, true, ob, false); - ob = CHECKNULL(yt, ob); - if (!ob) { - return Py_None; - } - yt = YAP_TailOfTerm(yt); - } - YAP_PutInSlot(l, yt); - return ob; -} - -/** - * Python abs - * - * @param t Prolog term with a number - * - * @return a Python object with the number's absolute value - */ - -static PyObject *bip_abs(term_t t) { - PyObject *pVal, *nVal; - - AOK(PL_get_arg(1, t, t), NULL); - pVal = term_to_python(t, true, NULL); - pVal = CHECKNULL(t, pVal); - nVal = PyNumber_Absolute(pVal); - Py_DecRef(pVal); - return nVal; -} - -/** - * Python all - * - * @param t Prolog term with a previously constructed Python iterator -> * - * @return the Python boolean `True` if all elements of the iterator are `True`, - * `False` otherwise. - */ -static PyObject *bip_all(term_t t) { - PyObject *it, *item, *v; - PyObject *(*iternext)(PyObject *); - int cmp; - - AOK(PL_get_arg(1, t, t), NULL); - (v = term_to_python(t, true, NULL)); - v = CHECKNULL(t, v); - it = PyObject_GetIter(v); - if (CHECKNULL(t, it) == NULL) - return Py_None; - iternext = *Py_TYPE(it)->tp_iternext; - - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return Py_None; - } - // PyObject_Print(v, stderr, 0); - for (;;) { - item = iternext(it); - if (CHECKNULL(t, item) == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return Py_None; - } - if (cmp == 0) { - Py_DECREF(it); - return Py_False; - } - } - Py_DECREF(it); - return Py_True; -} - -/** - * Python any - * - * @param t Prolog term with a previously constructed Python iterator - * - * @return the Python boolean `True` if any element of the iterator is `True`, - * `False` if all of them are false. - */ -static PyObject *bip_any(term_t t) { - PyObject *it, *item, *v; - PyObject *(*iternext)(PyObject *); - int cmp; - - AOK(PL_get_arg(1, t, t), NULL); - v = term_to_python(t, true, NULL); - it = PyObject_GetIter(v); - if (CHECKNULL(t, it) == NULL) - return Py_None; - iternext = *Py_TYPE(it)->tp_iternext; - - for (;;) { - item = iternext(it); - if (CHECKNULL(t, item) == NULL) - break; - cmp = PyObject_IsTrue(item); - Py_DECREF(item); - if (cmp < 0) { - Py_DECREF(it); - return Py_None; - } - if (cmp == 1) { - Py_DECREF(it); - Py_RETURN_TRUE; - } - } - Py_DECREF(it); - if (PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_StopIteration)) - PyErr_Clear(); - else - return CHECKNULL(t, NULL); - } - Py_RETURN_FALSE; -} - -static PyObject *bip_bin(term_t t) { - PyObject *v; - - AOK(PL_get_arg(1, t, t), NULL); - v = term_to_python(t, true, NULL); - return PyNumber_ToBase(v, 2); -} - -static PyObject *bip_float(term_t t, bool eval) { - PyObject *pVal, *o; - - AOK(PL_get_arg(1, t, t), NULL); - pVal = term_to_python(t, eval, NULL); - if (PyLong_Check(pVal)) { - o = PyFloat_FromDouble(PyLong_AsLong(pVal)); -#if PY_MAJOR_VERSION < 3 - } else if (PyInt_Check(pVal)) { - o = PyFloat_FromDouble(PyInt_AsLong(pVal)); -#endif - } else if (PyFloat_Check(pVal)) { - return pVal; - } else - return Py_None; - Py_DECREF(pVal); - return o; -} - -static PyObject *bip_int(term_t t) { - PyObject *pVal, *o; - - AOK(PL_get_arg(1, t, t), NULL); - pVal = term_to_python(t, true, NULL); -#if PY_MAJOR_VERSION < 3 - if (PyLong_Check(pVal)) { - o = PyInt_FromLong(PyLong_AsLong(pVal)); - } else if (PyInt_Check(pVal)) { - return pVal; -#else - if (PyLong_Check(pVal)) { - return pVal; -#endif - } else if (PyFloat_Check(pVal)) { -#if PY_MAJOR_VERSION < 3 - o = PyInt_FromLong(PyFloat_AsDouble(pVal)); -#else - o = PyLong_FromDouble(PyFloat_AsDouble(pVal)); -#endif - } else - return Py_None; - Py_DECREF(pVal); - return o; -} - -static PyObject *bip_long(term_t t) { - PyObject *pVal, *o; - - AOK(PL_get_arg(1, t, t), NULL); - pVal = term_to_python(t, true, NULL); - if (PyLong_Check(pVal)) { - return pVal; -#if PY_MAJOR_VERSION < 3 - } else if (PyInt_Check(pVal)) { - o = PyLong_FromLong(PyInt_AsLong(pVal)); -#endif - } else if (PyFloat_Check(pVal)) { - o = pVal; - } else - return Py_None; - Py_DECREF(pVal); - return o; -} - -static PyObject *bip_iter(term_t t) { - PyObject *v; - - AOK(PL_get_arg(1, t, t), NULL); - v = term_to_python(t, true, NULL); - return PyObject_GetIter(v); -} - -static PyObject *bip_ord(term_t t) { - PyObject *pVal; - Py_ssize_t size; - - AOK(PL_get_arg(1, t, t), NULL); - pVal = term_to_python(t, true, NULL); - if (PyUnicode_Check(pVal)) { -#if PY_MAJOR_VERSION < 3 - size = PyUnicode_GET_SIZE(pVal); -#else - size = PyUnicode_GetLength(pVal); -#endif - if (size == 1) { -#if PY_MAJOR_VERSION < 3 - long ord = (long)*PyUnicode_AS_UNICODE(pVal); - return PyInt_FromLong(ord); -#else - Py_UCS4 ord = PyUnicode_ReadChar(pVal, 0); - return PyLong_FromLong(ord); -#endif - } - return Py_None; - } else if (PyByteArray_Check(pVal)) { - char *s = PyByteArray_AsString(pVal); - - if (s[1]) - return Py_None; -#if PY_MAJOR_VERSION < 3 - return PyInt_FromLong(s[0]); - } else if (PyString_Check(pVal)) { - char *s = PyString_AsString(pVal); - - if (s[1]) - return Py_None; - return PyInt_FromLong(s[0]); -#else - return PyLong_FromLong(s[0]); -#endif - } else - return NULL; -} - -static PyObject *bip_sum(term_t t) { - PyObject *seq; - PyObject *result = NULL; - PyObject *temp, *item, *iter; - - AOK(PL_get_arg(1, t, t), NULL); - seq = term_to_python(t, true, NULL); - iter = PyObject_GetIter(seq); - if (iter == NULL) - return NULL; - - if (result == NULL) { -#if PY_MAJOR_VERSION < 3 - result = PyInt_FromLong(0); -#else - result = PyLong_FromLong(0); -#endif - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } else { -#if PY_MAJOR_VERSION < 3 - /* reject string values for 'start' parameter */ - if (PyObject_TypeCheck(result, &PyBaseString_Type)) { - PyErr_SetString(PyExc_TypeError, - "sum() can't sum strings [use ''.join(seq) instead]"); - Py_DECREF(iter); - return NULL; - } - Py_INCREF(result); -#endif - } - -#ifndef SLOW_SUM -/* Fast addition by keeping temporary sums in C instead of new Python objects. - Assumes all inputs are the same type. If the assumption fails, default - to the more general routine. -*/ -#if PY_MAJOR_VERSION < 3 - if (PyInt_CheckExact(result)) { - long i_result = PyInt_AS_LONG(result); -#else - if (PyLong_CheckExact(result)) { - long i_result = PyLong_AS_LONG(result); -#endif - Py_DECREF(result); - result = NULL; - while (result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; -#if PY_MAJOR_VERSION < 3 - return PyInt_FromLong(i_result); -#else - return PyLong_FromLong(i_result); -#endif - } -#if PY_MAJOR_VERSION < 3 - if (PyInt_CheckExact(item)) { - long b = PyInt_AS_LONG(item); -#else - if (PyLong_CheckExact(item)) { - long b = PyLong_AS_LONG(item); -#endif - long x = i_result + b; - if ((x ^ i_result) >= 0 || (x ^ b) >= 0) { - i_result = x; - Py_DECREF(item); - continue; - } - } -/* Either overflowed or is not an int. Restore real objects and process normally - */ -#if PY_MAJOR_VERSION < 3 - result = PyInt_FromLong(i_result); -#else - result = PyLong_FromLong(i_result); -#endif - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } - } - - if (PyFloat_CheckExact(result)) { - double f_result = PyFloat_AS_DOUBLE(result); - Py_DECREF(result); - result = NULL; - while (result == NULL) { - item = PyIter_Next(iter); - if (item == NULL) { - Py_DECREF(iter); - if (PyErr_Occurred()) - return NULL; - return PyFloat_FromDouble(f_result); - } - if (PyFloat_CheckExact(item)) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += PyFloat_AS_DOUBLE(item); - PyFPE_END_PROTECT(f_result) Py_DECREF(item); - continue; - } -#if PY_MAJOR_VERSION < 3 - if (PyInt_CheckExact(item)) { - 764PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); - return 0)f_result += (double)PyInt_AS_LONG(item); - PyFPE_END_PROTECT(f_result) Py_DECREF(item); - continue; - } -#else - if (PyLong_CheckExact(item)) { - PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) - f_result += PyLong_AsDouble(item); - PyFPE_END_PROTECT(f_result) Py_DECREF(item); - continue; - } -#endif - result = PyFloat_FromDouble(f_result); - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) { - Py_DECREF(iter); - return NULL; - } - } -#endif - } - - for (;;) { - item = PyIter_Next(iter); - if (item == NULL) { - /* error, or end-of-sequence */ - if (PyErr_Occurred()) { - Py_DECREF(result); - result = NULL; - } - break; - } - /* It's tempting to use PyNumber_InPlaceAdd instead of - PyNumber_Add here, to avoid quadratic running time - when doing 'sum(list_of_lists, [])'. However, this - would produce a change in behaviour: a snippet like - - empty = [] - sum([[x] for x in range(10)], empty) - - would change the value of empty. */ - temp = PyNumber_Add(result, item); - Py_DECREF(result); - Py_DECREF(item); - result = temp; - if (result == NULL) - break; - } - Py_DECREF(iter); - return result; -} - -//@} - -static long get_int(term_t arg, bool eval) { - long low; - - if (!PL_get_long(arg, &low)) { - PyObject *low = term_to_python(arg, eval, NULL); - if (PyLong_Check(low)) { - return PyLong_AsLong(low); -#if PY_MAJOR_VERSION < 3 - } else if (PyInt_Check(low)) { - return PyInt_AsLong(low); -#endif - } else { - return 0; - } - } - return low; -} - -/* Return number of items in range/xrange (lo, hi, step). step > 0 - * required. Return a value < 0 if & only if the true value is too - * large to fit in a signed long. - */ -static long get_len_of_range(long lo, long hi, long step) { - /* ------------------------------------------------------------- - If lo >= hi, the range is empty. - Else if n values are in the range, the last one is - lo + (n-1)*step, which must be <= hi-1. Rearranging, - n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives - the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so - the RHS is non-negative and so truncation is the same as the - floor. Letting M be the largest positive long, the worst case - for the RHS numerator is hi=M, lo=-M-1, and then - hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough - precision to compute the RHS exactly. - ---------------------------------------------------------------*/ - long n = 0; - if (lo < hi) { - unsigned long uhi = (unsigned long)hi; - unsigned long ulo = (unsigned long)lo; - unsigned long diff = uhi - ulo - 1; - n = (long)(diff / (unsigned long)step + 1); - } - return n; -} - -#if PY_MAJOR_VERSION >= 3 -static PyStructSequence_Field pnull[] = { - {"A1", NULL}, {"A2", NULL}, {"A3", NULL}, {"A4", NULL}, {"A5", NULL}, - {"A6", NULL}, {"A7", NULL}, {"A8", NULL}, {"A9", NULL}, {"A9", NULL}, - {"A10", NULL}, {"A11", NULL}, {"A12", NULL}, {"A13", NULL}, {"A14", NULL}, - {"A15", NULL}, {"A16", NULL}, {"A17", NULL}, {"A18", NULL}, {"A19", NULL}, - {"A19", NULL}, {"A20", NULL}, {"A21", NULL}, {"A22", NULL}, {"A23", NULL}, - {"A24", NULL}, {"A25", NULL}, {"A26", NULL}, {"A27", NULL}, {"A28", NULL}, - {"A29", NULL}, {"A29", NULL}, {"A30", NULL}, {"A31", NULL}, {"A32", NULL}, - {NULL, NULL}}; - -static PyObject *structseq_str(PyObject *iobj) { - -/* buffer and type size were chosen well considered. */ -#define REPR_BUFFER_SIZE 512 -#define TYPE_MAXSIZE 100 - - PyStructSequence *obj = (PyStructSequence *)iobj; - PyTypeObject *typ = Py_TYPE(obj); - bool removelast = false; - Py_ssize_t len, i; - char buf[REPR_BUFFER_SIZE]; - char *endofbuf, *pbuf = buf; - /* pointer to end of writeable buffer; safes space for "...)\0" */ - endofbuf = &buf[REPR_BUFFER_SIZE - 5]; - - /* "typename(", limited to TYPE_MAXSIZE */ - len = - strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : strlen(typ->tp_name); - strncpy(pbuf, typ->tp_name, len); - pbuf += len; - *pbuf++ = '('; - - for (i = 0; i < ((PyStructSequence *)obj)->ob_base.ob_size; i++) { - PyObject *val, *repr; - char *crepr; - - val = PyStructSequence_GET_ITEM(obj, i); - repr = PyObject_Str(val); - if (repr == NULL) - return Py_None; - crepr = PyUnicode_AsUTF8(repr); - if (crepr == NULL) { - Py_DECREF(repr); - return Py_None; - } - - /* + 3: keep space for ", " */ - len = strlen(crepr) + 2; - if ((pbuf + len) <= endofbuf) { - strcpy(pbuf, crepr); - pbuf += strlen(crepr); - *pbuf++ = ','; - *pbuf++ = ' '; - removelast = 1; - Py_DECREF(repr); - } else { - strcpy(pbuf, "..."); - pbuf += 3; - removelast = 0; - Py_DECREF(repr); - break; - } - } - if (removelast) { - /* overwrite last ", " */ - pbuf -= 2; - } - *pbuf++ = ')'; - *pbuf = '\0'; - - return PyUnicode_FromString(buf); -} - -static PyObject *structseq_repr(PyObject *iobj) { - -/* buffer and type size were chosen well considered. */ -#define REPR_BUFFER_SIZE 512 -#define TYPE_MAXSIZE 100 - - PyStructSequence *obj = (PyStructSequence *)iobj; - PyTypeObject *typ = Py_TYPE(obj); - bool removelast = false; - Py_ssize_t len, i; - char buf[REPR_BUFFER_SIZE]; - char *endofbuf, *pbuf = buf; - /* pointer to end of writeable buffer; safes space for "...)\0" */ - endofbuf = &buf[REPR_BUFFER_SIZE - 5]; - - /* "typename(", limited to TYPE_MAXSIZE */ - len = - strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : strlen(typ->tp_name); - strncpy(pbuf, typ->tp_name, len); - pbuf += len; - *pbuf++ = '('; - - for (i = 0; i < ((PyStructSequence *)obj)->ob_base.ob_size; i++) { - PyObject *val, *repr; - char *crepr; - - val = PyStructSequence_GET_ITEM(obj, i); - repr = PyObject_Repr(val); - if (repr == NULL) - return NULL; - crepr = PyUnicode_AsUTF8(repr); - if (crepr == NULL) { - Py_DECREF(repr); - return NULL; - } - - /* + 3: keep space for ", " */ - len = strlen(crepr) + 2; - if ((pbuf + len) <= endofbuf) { - strcpy(pbuf, crepr); - pbuf += strlen(crepr); - *pbuf++ = ','; - *pbuf++ = ' '; - removelast = 1; - Py_DECREF(repr); - } else { - strcpy(pbuf, "..."); - pbuf += 3; - removelast = 0; - Py_DECREF(repr); - break; - } - } - if (removelast) { - /* overwrite last ", " */ - pbuf -= 2; - } - *pbuf++ = ')'; - *pbuf = '\0'; - - return PyUnicode_FromString(buf); -} -#endif - -PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *tuple) { - PyObject *o; -#if PY_MAJOR_VERSION >= 3 - PyTypeObject *typp; - PyObject *key = PyUnicode_FromString(s); - if (py_F2P && PyDict_Contains(py_F2P, key)) { - typp = (PyTypeObject *)PyDict_GetItem(py_F2P, key); - Py_INCREF(typp); - } else { - - typp = calloc(sizeof(PyTypeObject), 1); - PyStructSequence_Desc *desc = calloc(sizeof(PyStructSequence_Desc), 1); - desc->name = PyMem_Malloc(strlen(s) + 1); - strcpy(desc->name, s); - Py_DECREF(key); - desc->doc = "YAPTerm"; - desc->fields = pnull; - desc->n_in_sequence = arity; - if (PyStructSequence_InitType2(typp, desc) < 0) - return NULL; - typp->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; - // typp->tp_str = structseq_str; - typp->tp_repr = structseq_repr; - // typp = PyStructSequence_NewType(desc); - // don't do this: we cannot add a type as an atribute. - // PyModule_AddObject(py_Main, s, (PyObject *)typp); - if (py_F2P) - PyDict_SetItem(py_F2P, key, (PyObject *)typp); - Py_INCREF(typp); - } - o = PyStructSequence_New(typp); - arity_t i; - for (i = 0; i < arity; i++) { - PyObject *pArg = PyTuple_GET_ITEM(tuple, i); - Py_INCREF(pArg); - if (pArg) - PyStructSequence_SET_ITEM(o, i, pArg); - // PyObject_Print(pArg,stderr,0);fputc('\n',stderr); - } - //((PyStructSequence *)o)->ob_base.ob_size = arity; - // PyObject_Print(o,stderr,0);fputc('\n',stderr); - return o; -#else - PyObject *o1; - o1 = PyTuple_New(2); - PyTuple_SET_ITEM(o1, 0, PyUnicode_FromString(s)); - PyTuple_SET_ITEM(o1, 1, tuple); - return o1; -#endif -} - -static PyObject *bip_range(term_t t) { - long ilow = 0, ihigh = 0, istep = 1; - long bign; - Py_ssize_t i, n; - int arity; - atom_t name; - term_t arg = PL_new_term_ref(); - - PyObject *v; - - if (!PL_get_name_arity(t, &name, &arity)) - return NULL; - AOK(PL_get_arg(1, t, arg), NULL); - ilow = get_int(arg, true); - if (arity == 1) { - ihigh = ilow; - ilow = 0; - } else { - AOK(PL_get_arg(2, t, arg), NULL); - ihigh = get_int(arg, true); - if (arity == 3) { - AOK(PL_get_arg(3, t, arg), NULL); - istep = get_int(arg, true); - } - } - if (istep == 0) { - PyErr_SetString(PyExc_ValueError, "range() step argument must not be zero"); - return NULL; - } - if (istep > 0) - bign = get_len_of_range(ilow, ihigh, istep); - else - bign = get_len_of_range(ihigh, ilow, -istep); - n = (Py_ssize_t)bign; - AOK(((bign >= 0 && (long)n == bign) || "range() result has too many items"), - NULL); - v = PyList_New(n); - - if (v == NULL) - return Py_None; - for (i = 0; i < n; i++) { -#if PY_MAJOR_VERSION < 3 - PyObject *w = PyInt_FromLong(ilow); -#else - PyObject *w = PyLong_FromLong(ilow); -#endif - if (w == NULL) { - Py_DECREF(v); - return NULL; - } - PyList_SET_ITEM(v, i, w); - Py_INCREF(w); - ilow += istep; - } - return v; -} - -static bool copy_to_dictionary(PyObject *dict, term_t targ, term_t taux, - bool eval) { - PyObject *lhs, *rhs; - term_t tleft = PL_new_term_ref(), tright = PL_new_term_ref(); - - functor_t fun; - - AOK(PL_get_functor(targ, &fun), false); - while (fun == FUNCTOR_comma2) { - AOK(PL_get_arg(1, targ, tleft), false); - if (!copy_to_dictionary(dict, tleft, taux, eval)) - return false; - AOK(PL_get_arg(2, targ, targ), false); - return copy_to_dictionary(dict, tright, taux, eval); - } - // PyObject_Print(dict, stderr, 0); fprintf(stderr,"\n"); - // Py_DECREF(lhs); - // Py_DECREF(rhs); - - AOK(PL_get_arg(1, targ, tleft), false); - lhs = atom_to_python_string(tleft); - if (lhs == NULL) { - return FALSE; - } - AOK(PL_get_arg(2, targ, tright), false); - rhs = term_to_python(tright, eval, NULL); - if (rhs == NULL) { - PyErr_Print(); - return false; - } - return PyDict_SetItem(dict, lhs, rhs) >= 0; - // PyObject_Print(dict, stderr, 0); fprintf(stderr,"\n"); - // Py_DECREF(lhs); - // Py_DECREF(rhs); -} - -PyObject *compound_to_data(term_t t, PyObject *o, functor_t fun, bool exec) { - atom_t name; - int len; - - AOK(PL_get_name_arity(t, &name, &len), o); - - if (fun == FUNCTOR_pointer1) { - void *ptr; - - AOK(PL_get_arg(1, t, t), NULL); - AOK(PL_get_pointer(t, &ptr), NULL) - /* return __main__,s */ - return (PyObject *)ptr; - } - if (name == ATOM_t) { - term_t targ = PL_new_term_ref(); - PyObject *out; - int i; - - out = PyTuple_New(len); - DebugPrintf("Tuple %p\n", out); - - if (!out) - return NULL; - for (i = 0; i < len; i++) { - AOK(PL_get_arg(i + 1, t, targ), NULL); - PyErr_Clear(); - PyObject *oa = term_to_python(targ, true, o); - bool rc = PyTuple_SET_ITEM(out, i, oa) == 0; - if (rc) { - PyErr_Print(); - } - Py_INCREF(oa); - } - return out; - } else if (fun == FUNCTOR_div2) { - term_t targ = PL_new_term_ref(); - PyObject *lhs, *rhs; - - AOK(PL_get_arg(1, t, targ), NULL); - lhs = term_to_python(targ, true, NULL); - if (!PyNumber_Check(lhs)) - return NULL; - AOK(PL_get_arg(2, t, targ), NULL); - rhs = term_to_python(targ, true, NULL); - if (!PyNumber_Check(rhs)) - return NULL; -#if PY_MAJOR_VERSION < 3 - return PyNumber_Divide(lhs, rhs); -#else - return PyNumber_TrueDivide(lhs, rhs); -#endif - } - if (fun == FUNCTOR_sqbrackets2) { - term_t targ = PL_new_term_ref(), trhs = PL_new_term_ref(); - PyObject *v; - Py_ssize_t min, max; - AOK(PL_get_arg(2, t, targ), NULL); - v = term_to_python(targ, true, o); - - AOK(PL_get_arg(1, t, targ), NULL); - AOK(PL_get_list(targ, trhs, targ), NULL); - if (PL_is_functor(trhs, FUNCTOR_colon2)) { - if (!PySequence_Check(v)) - return NULL; - min = get_p_int(term_to_python(targ, true, NULL), 0); - AOK(PL_get_arg(1, trhs, targ), NULL); - if (PL_is_functor(targ, FUNCTOR_colon2)) { - return NULL; - } - max = get_p_int(term_to_python(targ, true, o), PyObject_Size(v)); - return PySequence_GetSlice(v, min, max); - } else { - PyObject *ip = term_to_python(trhs, true, o); - if (PySequence_Check(v)) { -#if PY_MAJOR_VERSION < 3 - if (PyLong_Check(ip) { - min = PyLong_AsLong(ip); - } else if (PyInt_Check(ip) { - min = PyInt_asInt(ip); - } -#else - if (PyLong_Check(ip)) { - PyObject *o = PySequence_GetItem(v, PyLong_AsLong(ip)); - if (o == NULL) - o = Py_None; - if (CHECKNULL(t, o) == NULL) - return NULL; - Py_INCREF(o); - return o; - } -#endif - } else { - o = PyObject_GetItem(v, ip); - if (o == NULL) - o = Py_None; - Py_INCREF(o); - return o; - } - } - } - if (fun == FUNCTOR_dollar1) { - char *s = NULL; - term_t targ = PL_new_term_ref(); - AOK(PL_get_arg(1, t, targ), NULL); - AOK(PL_get_atom_chars(targ, &s), NULL); - /* return __main__,s */ - PyObject *o = PyObject_GetAttrString(py_Main, s); - return o; - } - if (fun == FUNCTOR_brackets1) { - AOK(PL_get_arg(1, t, t), NULL); - return term_to_python(t, true, NULL); - } - if (fun == FUNCTOR_complex2) { - term_t targ = PL_new_term_ref(); - PyObject *lhs, *rhs; - double d1, d2; - - AOK(PL_get_arg(1, t, targ), NULL); - lhs = term_to_python(targ, true, NULL); - AOK(PyNumber_Check(lhs), NULL); - if (PyFloat_Check(lhs)) { - d1 = PyFloat_AsDouble(lhs); - } else if (PyLong_Check(lhs)) { - d1 = PyLong_AsLong(lhs); -#if PY_MAJOR_VERSION < 3 - } else if (PyInt_Check(lhs)) { - d1 = PyInt_AsLong(lhs); -#endif - } else { - return NULL; - } - AOK(PL_get_arg(2, t, targ), NULL); - rhs = term_to_python(targ, true, NULL); - AOK(PyNumber_Check(rhs), NULL); - if (PyFloat_Check(rhs)) { - d2 = PyFloat_AsDouble(rhs); - } else if (PyLong_Check(rhs)) { - d2 = PyLong_AsLong(rhs); -#if PY_MAJOR_VERSION < 3 - } else if (PyInt_Check(rhs)) { - d2 = PyInt_AsLong(rhs); -#endif - } else { - return NULL; - } - - return PyComplex_FromDoubles(d1, d2); - } - if (fun == FUNCTOR_curly1) { - term_t targ = PL_new_term_ref(), taux = PL_new_term_ref(); - PyObject *dict; - - AOK(PL_get_arg(1, t, t), NULL); - if (!(dict = PyDict_New())) - return NULL; - DebugPrintf("Dict %p\n", dict); - - while (PL_is_functor(t, FUNCTOR_comma2)) { - AOK(PL_get_arg(1, t, targ), NULL); - AOK(PL_is_functor(targ, FUNCTOR_colon2), NULL); - - AOK(copy_to_dictionary(dict, targ, taux, true), NULL); - AOK(PL_get_arg(2, t, t), NULL); - } - - if (PL_is_functor(t, FUNCTOR_colon2)) { - AOK(copy_to_dictionary(dict, t, taux, true), NULL); - } - return dict; - } - return o; -} - -PyObject *compound_to_pytree(term_t t, PyObject *context) { - PyObject *o = py_Main, *no; - functor_t fun; - atom_t name; - int arity; - - o = find_obj(context, t, false); - AOK(PL_get_name_arity(t, &name, &arity), NULL); - if (arity == 0) - return term_to_python(t, false, o); - AOK(PL_get_functor(t, &fun), NULL); - if ((no = compound_to_data(t, o, fun, false)) != o && no) { - return no; - } - if (!arity) { - char *s = NULL; - - AOK(!PL_get_atom_chars(t, &s), NULL); - // this should never happen - return term_to_python(t, false, o); - } else { - const char *s; - if (!(s = PL_atom_chars(name))) { - return NULL; - } - term_t tleft; - int i; - PyObject *out = PyTuple_New(arity); - DebugPrintf("Tuple %p\n", o); - tleft = PL_new_term_ref(); - for (i = 0; i < arity; i++) { - PyObject *pArg; - AOK(PL_get_arg(i + 1, t, tleft), NULL); - pArg = term_to_python(tleft, false, NULL); - if (pArg) { - /* pArg reference stolen here: */ - PyTuple_SET_ITEM(out, i, pArg); - Py_INCREF(pArg); - } - } - if (CHECKNULL(t, out) == NULL) { - PyErr_Print(); - return NULL; - } - PyObject *c = lookupPySymbol(s, o, NULL); - - if (c && PyCallable_Check(c)) { - PyObject *n = PyTuple_New(arity); - PyTuple_SET_ITEM(n, 0, c); - PyTuple_SET_ITEM(n, 1, out); - return n; - } - return term_to_nametuple(s, arity, out); - } -} - -PyObject *compound_to_pyeval(term_t t, PyObject *context) { - PyObject *o = NULL, *no; - atom_t name; - int arity; - functor_t fun; - - o = find_obj(context, t, true); - AOK(PL_get_name_arity(t, &name, &arity), NULL); - if (arity == 0) - return term_to_python(t, true, o); - if (!PL_get_functor(t, &fun)) - return NULL; - if ((no = compound_to_data(t, o, fun, true)) != o && no) { - return no; - } - if (fun == FUNCTOR_abs1) { - return bip_abs(t); - } else if (fun == FUNCTOR_all1) { - return bip_all(t); - } else if (fun == FUNCTOR_any1) { - return bip_any(t); - } else if (fun == FUNCTOR_bin1) { - return bip_bin(t); - } else if (fun == FUNCTOR_ord1) { - return bip_ord(t); - } else if (fun == FUNCTOR_int1) { - return bip_int(t); - } else if (fun == FUNCTOR_long1) { - return bip_long(t); - } else if (fun == FUNCTOR_float1) { - return bip_float(t, true); - } else if (fun == FUNCTOR_iter1) { - return bip_iter(t); - } else if (fun == FUNCTOR_range1 || fun == FUNCTOR_range2 || - fun == FUNCTOR_range3) { - return bip_range(t); - } else if (fun == FUNCTOR_sum1) { - return bip_sum(t); - } - if (fun == FUNCTOR_len1) { - term_t targ = PL_new_term_ref(); - PyObject *ptr; - - AOK(PL_get_arg(1, t, targ), NULL); - ptr = term_to_python(targ, true, NULL); - return PyLong_FromLong(PyObject_Length(ptr)); - } - if (fun == FUNCTOR_dir1) { - term_t targ = PL_new_term_ref(); - PyObject *ptr; - - AOK(PL_get_arg(1, t, targ), NULL); - ptr = term_to_python(targ, true, NULL); - return PyObject_Dir(ptr); - - } - - else if (fun == FUNCTOR_plus2) { - term_t targ = PL_new_term_ref(); - PyObject *lhs, *rhs; - - if (!PL_get_arg(1, t, targ)) - return NULL; - lhs = term_to_python(targ, true, NULL); - AOK(PL_get_arg(2, t, targ), NULL); - rhs = term_to_python(targ, true, NULL); - if (PySequence_Check(lhs) && PySequence_Check(rhs)) { - return PySequence_Concat(lhs, rhs); - } - if (!PyNumber_Check(lhs)) - return NULL; - if (!PyNumber_Check(rhs)) - return NULL; - return PyNumber_Add(lhs, rhs); - } else if (fun == FUNCTOR_sub2) { - term_t targ = PL_new_term_ref(); - PyObject *lhs, *rhs; - - if (!PL_get_arg(1, t, targ)) - return NULL; - lhs = term_to_python(targ, true, NULL); - if (!PyNumber_Check(lhs)) - return NULL; - if (!PL_get_arg(2, t, targ)) - return NULL; - rhs = term_to_python(targ, true, NULL); - if (!PyNumber_Check(rhs)) - return NULL; - return PyNumber_Subtract(lhs, rhs); - } else if (fun == FUNCTOR_mul2) { - term_t targ = PL_new_term_ref(); - PyObject *lhs, *rhs; - - AOK(PL_get_arg(1, t, targ), NULL); - (lhs = term_to_python(targ, true, NULL)); - CHECKNULL(targ, lhs); - AOK(PL_get_arg(2, t, targ), NULL); - (rhs = term_to_python(targ, true, NULL)); - CHECKNULL(targ, rhs); - if (PySequence_Check(lhs) && ( -#if PY_MAJOR_VERSION < 3 - PyInt_Check(rhs) || -#endif - PyLong_Check(rhs))) { - return PySequence_Repeat(lhs, get_p_int(rhs, 0)); - } - if (!PyNumber_Check(lhs) + !PyNumber_Check(rhs)) - return NULL; - return PyNumber_Multiply(lhs, rhs); - } - if (!arity) { - char *s = NULL; - PyObject *pValue; - - AOK(PL_get_atom_chars(t, &s), NULL); - pValue = PyObject_GetAttrString(o, s); - if (CHECKNULL(t, pValue) == NULL) { - PyErr_Print(); - return NULL; - } - return pValue; - } else { - char *s = PL_atom_chars(name); - o = lookupPySymbol(s, o, NULL); - if (CHECKNULL(t, o) == NULL) { - PyErr_Print(); - return NULL; - } - PyObject *pArgs = PyTuple_New(arity); - DebugPrintf("Tuple %p\n", pArgs); - int i; - term_t tleft = PL_new_term_ref(); - for (i = 0; i < arity; i++) { - PyObject *pArg; - AOK(PL_get_arg(i + 1, t, tleft), NULL); - /* ignore (_) */ - if (i == 0 && PL_is_variable(tleft)) { - pArg = Py_None; - } else { - pArg = term_to_python(tleft, true, NULL); - // PyObject_Print(pArg,fdopen(2,"w"),0); - if (pArg == NULL) { - pArg = Py_None; - } - /* pArg reference stolen here: */ - Py_INCREF(pArg); - } - - PyTuple_SetItem(pArgs, i, pArg); - } - if (!PyCallable_Check(o)) { - return term_to_nametuple(s, arity, pArgs); - } - PyObject *rc; - - // PyObject_Print(pArgs, stderr, 0); - // PyObject_Print(o, stderr, 0); - CHECK_CALL(rc, t, PyObject_CallObject(o, pArgs)); - Py_DECREF(pArgs); - Py_DECREF(o); - DebugPrintf("CallObject %p\n", rc); - - - return rc; - } -} diff --git a/packages/packages/python/pypreds.c b/packages/packages/python/pypreds.c deleted file mode 100644 index e38221148..000000000 --- a/packages/packages/python/pypreds.c +++ /dev/null @@ -1,687 +0,0 @@ - -#include "py4yap.h" - -PyObject *py_Main; - -void pyErrorHandler__(int line, const char *file, const char *code) { - // this code is called if a Python error is found. - fprintf(stderr, " Python error detected at %s %s:%d\n\n", code, file, line); - PyErr_Print(); -} -static foreign_t python_len(term_t tobj, term_t tf) { - Py_ssize_t len; - PyObject *o; - - o = term_to_python(tobj, true, NULL); - if (o == NULL) { - pyErrorAndReturn(false, false); - } - len = PyObject_Length(o); - pyErrorAndReturn(PL_unify_int64(tf, len), false); -} - -static foreign_t python_dir(term_t tobj, term_t tf) { - PyObject *dir; - PyObject *o; - - o = term_to_python(tobj, true, NULL); - if (o == NULL) { - pyErrorAndReturn(false, false); - } - dir = PyObject_Dir(o); - { - foreign_t rc = address_to_term(dir, tf); - ; - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_index(term_t tobj, term_t tindex, term_t val) { - PyObject *i; - PyObject *o; - PyObject *f; - - o = term_to_python(tobj, true, NULL); - if (o == NULL) { - pyErrorAndReturn(false, false); - } - if (!PySequence_Check(o)) { - pyErrorAndReturn(false, false); - } - i = term_to_python(tindex, true, NULL); - if (i == NULL) { - pyErrorAndReturn(false, false); - } -#if PY_MAJOR_VERSION < 3 - f = PyObject_CallMethodObjArgs(o, PyString_FromString("getitem"), i); -#else - f = PyObject_CallMethodObjArgs(o, PyUnicode_FromString("getitem"), i); -#endif - { - foreign_t rc = address_to_term(f, val); - ; - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_is(term_t tobj, term_t tf) { - PyObject *o; - - term_t lim = python_acquire_GIL(); - - o = term_to_python(tobj, true, NULL); - if (!o) { - python_release_GIL(lim); - pyErrorAndReturn(false, false); - } - foreign_t rc = python_to_term(o, tf); - if (rc) - PyErr_Clear(); - python_release_GIL(lim); - pyErrorAndReturn(rc, false); -} - - -static foreign_t python_proc(term_t tobj) { - PyObject *o; - - term_t lim = python_acquire_GIL(); - - o = term_to_python(tobj, true, NULL); - python_release_GIL(lim); - bool rc = o != NULL; - pyErrorAndReturn(rc , false); -} - - -static foreign_t python_slice(term_t parent, term_t indx, term_t tobj) { - PyObject *pF, *pI; - - PyObject *p; - - // get Scope ... - pI = term_to_python(indx, true, NULL); - // got Scope.Exp - // get Scope ... - p = term_to_python(parent, true, NULL); - // Exp - if (!pI || !p) { - { pyErrorAndReturn(false, false); } - } else if ((pF = PySequence_GetSlice(p, 0, 0)) == NULL) { - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - Py_DecRef(pI); - Py_DecRef(p); - Py_INCREF(pF); - { - foreign_t rc; - rc = address_to_term(pF, tobj); - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_apply(term_t tin, term_t targs, term_t keywds, - term_t tf) { - PyObject *pF; - PyObject *pArgs, *pKeywords; - PyObject *pValue; - int i, arity; - atom_t aname; - foreign_t out; - term_t targ = PL_new_term_ref(); - - pF = term_to_python(tin, true, NULL); - PyErr_Clear(); - if (pF == NULL) { - { pyErrorAndReturn(false, false); } - } - if (PL_is_atom(targs)) { - pArgs = NULL; - } else { - - if (!PL_get_name_arity(targs, &aname, &arity)) { - { pyErrorAndReturn(false, false); } - } - if (arity == 1 && PL_get_arg(1, targs, targ) && PL_is_variable(targ)) { - /* ignore (_) */ - pArgs = NULL; - } else { - - pArgs = PyTuple_New(arity); - DebugPrintf("Tuple %p\n", pArgs); - - if (!pArgs) { - pyErrorAndReturn(false, false); - } - for (i = 0; i < arity; i++) { - PyObject *pArg; - if (!PL_get_arg(i + 1, targs, targ)) { - pyErrorAndReturn(false, false); - } - pArg = term_to_python(targ, true, NULL); - if (pArg == NULL) { - pyErrorAndReturn(false, false); - } - /* pArg reference stolen here: */ - PyTuple_SetItem(pArgs, i, pArg); - } - } - } - if (PL_is_atom(keywds)) { - pKeywords = NULL; - } else { - pKeywords = term_to_python(keywds, true, NULL); - } - if (PyCallable_Check(pF)) { - pValue = PyEval_CallObjectWithKeywords(pF, pArgs, pKeywords); - // PyObject_Print(pF,stderr,0);fprintf(stderr, "\n"); - // PyObject_Print(pArgs,stderr,0);fprintf(stderr, " "); - // PyObject_Print(pKeywords,stderr,0);fprintf(stderr, "\n"); - if (!pValue) - PyErr_Print(); - else - Py_IncRef(pValue); - } else if (pArgs == NULL) { - pValue = pF; - - if (pF) { - Py_IncRef(pValue); - } - } else { - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - if (pArgs) - Py_DECREF(pArgs); - Py_DECREF(pF); - if (pValue == NULL) { - pyErrorAndReturn(false, false); - } - out = address_to_term(pValue, tf); - pyErrorAndReturn(out, false); -} - -static foreign_t assign_python(term_t exp, term_t name) { -term_t stackp = python_acquire_GIL(); - PyObject *e = term_to_python(exp, true, NULL); - - if (e == NULL) { - python_release_GIL(stackp); - pyErrorAndReturn(false, false); - } - bool b = python_assign(name, e, NULL); - python_release_GIL(stackp); - pyErrorAndReturn(b, false); -} - - -static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) { - PyErr_Clear(); - PyObject *pI, *pArgs, *pOut; - PyObject *env; - atom_t name; - char *s; - int i, arity; - term_t targ = PL_new_term_ref(); - - if ((env = py_Builtin) == NULL) { - // no point in even trying - { pyErrorAndReturn(false, false); } - } - if (PL_get_name_arity(caller, &name, &arity)) { - if (!(s = PL_atom_chars(name))) { - pyErrorAndReturn(false, false); - } - if ((pI = PyObject_GetAttrString(env, s)) == NULL) { - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - Py_INCREF(pI); - } else { - // Prolog should make sure this never happens. - { pyErrorAndReturn(false, false); } - } - pArgs = PyTuple_New(arity); - DebugPrintf("Tuple %p\n", pArgs); - for (i = 0; i < arity; i++) { - PyObject *pArg; - if (!PL_get_arg(i + 1, caller, targ)) { - pyErrorAndReturn(false, false); - } - /* ignore (_) */ - if (i == 0 && PL_is_variable(targ)) { - pArg = Py_None; - } else { - pArg = term_to_python(targ, true, NULL); - if (pArg == NULL) { - pyErrorAndReturn(false, false); - } - } - /* pArg reference stolen here: */ - if (PyTuple_SetItem(pArgs, i, pArg)) { - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - } - pOut = PyObject_CallObject(pI, pArgs); - Py_DECREF(pArgs); - Py_DECREF(pI); - if (pOut == NULL) { - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - { - foreign_t rc = address_to_term(pOut, out); - ; - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_access(term_t obj, term_t f, term_t out) { - PyErr_Clear(); - PyObject *o = term_to_python(obj, true, NULL), *pValue, *pArgs, *pF; - atom_t name; - char *s = NULL; - int i, arity; - term_t targ = PL_new_term_ref(); - - if (o == NULL) { - pyErrorAndReturn(false, false); - } - if (PL_is_atom(f)) { - if (!PL_get_atom_chars(f, &s)) { - pyErrorAndReturn(false, false); - } - if ((pValue = PyObject_GetAttrString(o, s)) == NULL) { - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - Py_INCREF(pValue); - { pyErrorAndReturn(python_to_term(pValue, out), false); } - } - if (!PL_get_name_arity(f, &name, &arity)) { - { pyErrorAndReturn(false, false); } - } - s = PL_atom_chars(name); - if (!s) { - pyErrorAndReturn(false, false); - } - if ((pF = PyObject_GetAttrString(o, s)) == NULL) { - DebugPrintf("Function %p\n", pArgs); - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - pArgs = PyTuple_New(arity); - DebugPrintf("Tuple %p\n", pArgs); - for (i = 0; i < arity; i++) { - PyObject *pArg; - if (!PL_get_arg(i + 1, f, targ)) { - pyErrorAndReturn(false, false); - } - /* ignore (_) */ - if (i == 0 && PL_is_variable(targ)) { - pArgs = Py_None; - } - pArg = term_to_python(targ, true, NULL); - if (pArg == NULL) { - pyErrorAndReturn(false, false); - } - /* pArg reference stolen here: */ - PyTuple_SetItem(pArgs, i, pArg); - } - pValue = PyObject_CallObject(pF, pArgs); - Py_DECREF(pArgs); - Py_DECREF(pF); - if (pValue == NULL) { - { pyErrorAndReturn(false, false); } - } - { pyErrorAndReturn(python_to_term(pValue, out), false); } -} - -static foreign_t python_field(term_t parent, term_t att, term_t tobj) { - PyObject *pF; - atom_t name; - char *s; - int arity; - - if (!PL_get_name_arity(att, &name, &arity)) { - { pyErrorAndReturn(false, false); } - } else { - PyObject *p; - - // got Scope.Exp - // get Scope ... - p = term_to_python(parent, true, NULL); - // Exp - if (!PL_get_name_arity(att, &name, &arity)) { - { pyErrorAndReturn(false, false); } - } - s = PL_atom_chars(name); - if (arity == 1 && !strcmp(s, "()")) { - if (!PL_get_arg(1, att, att)) { - pyErrorAndReturn(false, false); - } - if (!PL_get_name_arity(att, &name, &arity)) { - { pyErrorAndReturn(false, false); } - } - s = PL_atom_chars(name); - } - if (!s || !p) { - { pyErrorAndReturn(false, false); } - } else if ((pF = PyObject_GetAttrString(p, s)) == NULL) { - PyErr_Clear(); - { pyErrorAndReturn(false, false); } - } - } - { - foreign_t rc; - rc = address_to_term(pF, tobj); - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_main_module(term_t mod) { - { - foreign_t rc; - PyErr_Clear(); - rc = address_to_term(py_Main, mod); - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_function(term_t tobj) { - PyErr_Clear(); - PyObject *obj = term_to_python(tobj, true, NULL); - foreign_t rc = PyFunction_Check(obj); - - pyErrorAndReturn(rc, false); -} - -foreign_t python_builtin(term_t out) { - { - foreign_t rc; - PyErr_Clear(); - rc = address_to_term(py_Builtin, out); - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_run_file(term_t file) { - char *s; - size_t len; - char si[256]; - s = si; - PyErr_Clear(); - if (PL_get_nchars(file, &len, &s, CVT_ALL | CVT_EXCEPTION)) { -#if PY_MAJOR_VERSION < 3 - PyObject *PyFileObject = PyFile_FromString(si, "r"); - PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1); -#else - FILE *f = fopen(s, "r"); - if (f == NULL) { - pyErrorAndReturn(false, false); - } - PyRun_SimpleFileEx(f, s, 1); -#endif - { - { pyErrorAndReturn(true, false); } - } - } - { pyErrorAndReturn(false, false); } -} - -extern PyThreadState *YAP_save; - -static foreign_t python_run_command(term_t cmd) { - char *s; - bool rc = false; - size_t len; - char si[256]; - - PyErr_Clear(); - s = si; - if (PL_get_nchars(cmd, &len, &s, CVT_ALL | CVT_EXCEPTION)) { - PyRun_SimpleString(s); - rc = true; - } - pyErrorAndReturn(rc, false); -} - -static foreign_t python_run_script(term_t cmd, term_t fun) { - char si[256], sf[256]; - size_t len = 255, len1 = 255; - PyObject *pName, *pModule, *pFunc; - PyObject *pArgs = NULL, *pValue; - char *s; - - PyErr_Clear(); - s = si; - if (PL_get_nchars(cmd, &len, &s, CVT_ALL | CVT_EXCEPTION) && - (s = sf) != NULL && - PL_get_nchars(fun, &len1, &s, CVT_ALL | CVT_EXCEPTION)) { - -#if PY_MAJOR_VERSION < 3 - pName = PyString_FromString("rbm"); -#else - // asssumes UTF-8 - pName = PyUnicode_FromString("rbm"); -#endif - /* Error checking of pName left out */ - - pModule = PyImport_Import(pName); - PyErr_Clear(); - Py_DECREF(pName); - - if (pModule != NULL) { - pFunc = PyObject_GetAttrString(pModule, sf); - /* pFunc is a new reference */ - - if (pFunc && PyCallable_Check(pFunc)) { - pValue = PyObject_CallObject(pFunc, pArgs); - if (pValue != NULL) { - Py_DECREF(pValue); - } else { - Py_DECREF(pFunc); - Py_DECREF(pModule); - PyErr_Print(); - fprintf(stderr, "Call failed\n"); - { pyErrorAndReturn(false, false); } - } - } else { - pyErrorHandler(); - if (PyErr_Occurred()) - PyErr_Print(); - fprintf(stderr, "Cannot find function \"%s\"\n", sf); - } - Py_XDECREF(pFunc); - Py_DECREF(pModule); - } else { - PyErr_Print(); - { pyErrorAndReturn(false, false); } - } - { pyErrorAndReturn(true, false); } - } - { pyErrorAndReturn(false, false); } -} - -static foreign_t python_export(term_t t, term_t pl) { - foreign_t rc = false; - PyErr_Clear(); - if (PL_is_functor(t, FUNCTOR_pointer1)) { - void *ptr; - term_t targ = PL_new_term_ref(); - - if (!PL_get_arg(1, t, targ)) { - pyErrorAndReturn(false, false); - } - if (!PL_get_pointer(targ, &ptr)) { - pyErrorAndReturn(false, false); - } - Py_INCREF((PyObject *)ptr); - /* pyErrorAndReturn( __main__, false) */ - rc = python_to_term((PyObject *)ptr, pl); - } - pyErrorAndReturn(rc, false); -} - - -/** - * @pred python_import(MName, Mod) - * Import a python module to the YAP environment. - * - * @param mname module name, either an atom or a sequence of atoms, - * eg os.sys - * @param mod the pointer to the Python object - * @return success? - */ -static int python_import(term_t mname, term_t mod) { - PyObject *pName; - -term_t t0 = python_acquire_GIL(); - term_t arg = PL_new_term_ref(); - char s0[MAXPATHLEN], *s = s0; - while (true) { - size_t len; - - len = (MAXPATHLEN - 1) - (s - s0); - if (PL_is_pair(mname)) { - char *sa = NULL; - if (!PL_get_arg(1, mname, arg) || !PL_get_atom_chars(arg, &sa) || - !PL_get_arg(2, mname, mname)) { - python_release_GIL(t0); - pyErrorAndReturn(false, false); - } - PL_get_atom_chars(arg, &sa); - strcpy(s, sa); - s += strlen(s); - *s++ = '.'; - s[0] = '\0'; - } else if (!PL_get_nchars(mname, &len, &s, - CVT_ATOM | CVT_STRING| CVT_EXCEPTION | REP_UTF8)) { - python_release_GIL(t0); - pyErrorAndReturn(false, false); - } else { - break; - } - } -#if PY_MAJOR_VERSION < 3 - pName = PyString_FromString(s0); -#else - pName = PyUnicode_FromString(s0); -#endif - python_release_GIL(t0); -if (pName == NULL) { - pyErrorAndReturn(false, false); - } - - PyObject *pModule = PyImport_Import(pName); - - Py_DECREF(pName); - if (pModule == NULL) { -#if EXTRA_MESSSAGES - if (PyErr_Occurred()) - PyErr_Print(); - PyErr_Clear(); -#endif - { pyErrorAndReturn(false, false); } - } - { - foreign_t rc = address_to_term(pModule, mod); - pyErrorAndReturn(rc, false); - } -} - -static foreign_t python_to_rhs(term_t inp, term_t t) { - PyObject *pVal; - PyErr_Clear(); - pVal = term_to_python(inp, true, NULL); - if (pVal == NULL) - pyErrorAndReturn(false, false); - pyErrorAndReturn(address_to_term(pVal, t), false); -} - -// static PyThreadState *_saveP = NULL; -static bool _threaded = false; - -/* -static YAP_Int - p_python_ensure(term_t ptr) - { - PyGILState_STATE _tState = PyGILState_Ensure(); - pyErrorAndReturn( PL_unify_int64(ptr, _tState), false); - } - -static YAP_Int - p_python_release(term_t ptr) - { - - PyGILState_STATE _tState; - PL_get_int64( ptr, &_tState); - PyGILState_Release( _tState ); - pyErrorAndReturn( true, false); - } -*/ - -int _locked = 0; -PyThreadState *tstate; - -static YAP_Int p_python_threaded(void) { - - PyErr_Clear(); - // PyEval_ReleaseThread(tstate); - // _threaded = true; - // _locked = 0; - pyErrorAndReturn(true, false); -} - -static PyGILState_STATE gstate; - -term_t python_acquire_GIL(void) { - term_t curSlot = PL_new_term_ref(); - if (!_threaded) - pyErrorAndReturn(curSlot, false); - // extern int Yap_do_low_level_trace; - // Yap_do_low_level_trace = 1; - // f[rintf( stderr, "++%d\n", ++_locked); - // if (_locked > 0) { _locked++ ; } - // else - gstate = PyGILState_Ensure(); - pyErrorAndReturn(curSlot, false); -} - -bool python_release_GIL(term_t curBlock) { - PyErr_Clear(); - PL_reset_term_refs(curBlock); - if (_threaded) { - PyGILState_Release(gstate); - } - pyErrorAndReturn(true, false); -} - -//: prolog: release python - -install_t install_pypreds(void) { - PL_register_foreign("python_builtin_eval", 3, python_builtin_eval, 0); - PL_register_foreign("python_builtin", 1, python_builtin, 0); - PL_register_foreign("python_import", 2, python_import, 0); - PL_register_foreign("python_to_rhs", 2, python_to_rhs, 0); - PL_register_foreign("python_len", 2, python_len, 0); - PL_register_foreign("python_is", 2, python_is, 0); - PL_register_foreign("python_dir", 2, python_dir, 0); - PL_register_foreign("python_apply", 4, python_apply, 0); - PL_register_foreign("python_index", 3, python_index, 0); - PL_register_foreign("python_field", 3, python_field, 0); - PL_register_foreign("python_assign", 2, assign_python, 0); - PL_register_foreign("python_export", 2, python_export, 0); - PL_register_foreign("python_function", 1, python_function, 0); - PL_register_foreign("python_slice", 4, python_slice, 0); - PL_register_foreign("python_run_file", 1, python_run_file, 0); - PL_register_foreign("python_proc", 1, python_proc, 0); - PL_register_foreign("python_run_command", 1, python_run_command, 0); - PL_register_foreign("python_run_script", 2, python_run_script, 0); - PL_register_foreign("python_main_module", 1, python_main_module, 0); - PL_register_foreign("python_import", 2, python_import, 0); - PL_register_foreign("python_access", 3, python_access, 0); - PL_register_foreign("python_threaded", 0, p_python_threaded, 0); -} diff --git a/packages/packages/python/python.c b/packages/packages/python/python.c deleted file mode 100644 index 37b6504c5..000000000 --- a/packages/packages/python/python.c +++ /dev/null @@ -1,222 +0,0 @@ - - -#include "py4yap.h" -#include - -atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t, - ATOM_comma, ATOM_builtin, ATOM_A, ATOM_V, ATOM_self, ATOM_nil, ATOM_brackets, ATOM_curly_brackets; - -functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1, - FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1, - FUNCTOR_float1, FUNCTOR_int1, FUNCTOR_iter1, FUNCTOR_iter2, FUNCTOR_long1, - FUNCTOR_len1, FUNCTOR_curly1, FUNCTOR_ord1, FUNCTOR_range1, FUNCTOR_range2, - FUNCTOR_range3, FUNCTOR_sum1, FUNCTOR_pointer1, FUNCTOR_complex2, - FUNCTOR_plus2, FUNCTOR_sub2, FUNCTOR_mul2, FUNCTOR_div2, FUNCTOR_hat2, - FUNCTOR_colon2, FUNCTOR_comma2, FUNCTOR_equal2, FUNCTOR_sqbrackets2, - FUNCTOR_dot2, FUNCTOR_brackets1; - -X_API PyObject *py_Builtin; -X_API PyObject *py_Yapex; -X_API PyObject *py_Sys; -PyObject *py_Context; -PyObject *py_ModDict; - -VFS_t pystream; - -static void * -py_open( const char *name, const char *io_mode) { -#if HAVE_STRCASESTR - if (strcasestr(name,"//python/")== name) - name += strlen("//python/"); - #else - if (strstr(name,"//python/")== name) - name += strlen("//python/"); -#endif - // we assume object is already open, so there is no need to open it. - PyObject *stream = string_to_python( name, true, NULL); - if (stream == Py_None) - return NULL; - return stream; -} - -static bool -py_close(int sno) { - PyObject *s = YAP_foreign_stream(sno); - PyObject* fclose = PyObject_GetAttrString(s, "close"); - PyObject* rc= PyObject_CallObject(fclose, NULL); - bool v = (rc == Py_True); - return v; -} - -static PyObject * pyw; // buffer -static int pyw_kind; -PyObject * pyw_data; - -static int -py_put(int sno, int ch) { - PyObject *s = YAP_foreign_stream(sno); - PyUnicode_WRITE( pyw_kind, pyw_data, 0, ch ); - PyObject* fput = PyObject_GetAttrString(s, "write"); - PyObject_CallFunctionObjArgs(fput, pyw, NULL); - return ch; -} - -static int -py_get(int sno) { - PyObject *s = YAP_foreign_stream(sno); - PyObject* fget = PyObject_GetAttrString(s, "read"); - PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL); - return PyUnicode_READ_CHAR( pyr, 0) ; -} - -static int64_t py_seek(int sno, int64_t where, int how) { - PyObject *s = YAP_foreign_stream(sno); - PyObject* fseek = PyObject_GetAttrString(s, "seek"); - PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where), PyLong_FromLong(how), NULL); - return PyLong_AsLong(pyr); -} - -static void -py_flush(int sno) { - PyObject *s = YAP_foreign_stream(sno); - PyObject* flush = PyObject_GetAttrString(s, "flush"); - PyObject_CallFunction( flush, NULL); -} - - - -static bool -init_python_stream(void) -{ - pyw = PyUnicode_FromString("x"); - pyw_kind = PyUnicode_KIND(pyw); - pyw_data = PyUnicode_DATA(pyw); - - pystream.name = "python stream"; - pystream.vflags = VFS_CAN_WRITE|VFS_CAN_EXEC| VFS_CAN_SEEK|VFS_HAS_PREFIX; - pystream.prefix = "//python/"; - pystream.suffix = NULL; - pystream.open = py_open; - pystream.close = py_close; - pystream.get_char = py_get; - pystream.put_char = py_put; - pystream.flush = py_flush; - pystream.seek = py_seek; - pystream.next = GLOBAL_VFS; - GLOBAL_VFS = &pystream; - // NULL; - return true; -} - -X_API PyObject *py_F2P; - -extern X_API bool python_in_python; - -static void add_modules(void) { - py_Main = PyImport_AddModule("__main__"); - Py_INCREF(py_Main); - py_Sys = PyImport_AddModule("sys"); - Py_INCREF(py_Sys); - py_Builtin = PyImport_AddModule("__builtin__"); - Py_INCREF(py_Builtin); - py_ModDict = PyObject_GetAttrString(py_Sys, "modules"); - // py_Yapex = PyImport_ImportModule("yap4py.yapi"); - // PyObject *py_Yap = - py_Yapex = PyImport_AddModule("yap4py.yapi"); - if (py_Yapex) - Py_INCREF(py_Yapex); - //py_F2P = PyObject_GetAttrString(py_Yap, "globals"); - py_F2P = NULL; - init_python_stream(); -} - - -static void install_py_constants(void) { - FUNCTOR_dot2 = PL_new_functor(PL_new_atom("."), 2); - // FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2); - // FUNCTOR_boolop1 = PL_new_functor(PL_new_atom("@"), 1); - ATOM_A = PL_new_atom("A"); - ATOM_V = PL_new_atom("V"); - ATOM_builtin = PL_new_atom("__builtin__"); - ATOM_comma = PL_new_atom(","); - ATOM_colon = PL_new_atom(":"); - ATOM_true = PL_new_atom("true"); - ATOM_false = PL_new_atom("false"); - ATOM_dot = PL_new_atom("."); - ATOM_self = PL_new_atom("self"); - ATOM_nil = PL_new_atom("[]"); - ATOM_brackets = PL_new_atom("()"); - ATOM_curly_brackets = PL_new_atom("{}"); - FUNCTOR_abs1 = PL_new_functor(PL_new_atom("abs"), 1); - FUNCTOR_all1 = PL_new_functor(PL_new_atom("all"), 1); - FUNCTOR_any1 = PL_new_functor(PL_new_atom("any"), 1); - FUNCTOR_bin1 = PL_new_functor(PL_new_atom("bin"), 1); - FUNCTOR_ord1 = PL_new_functor(PL_new_atom("ord"), 1); - FUNCTOR_int1 = PL_new_functor(PL_new_atom("int"), 1); - FUNCTOR_long1 = PL_new_functor(PL_new_atom("long"), 1); - FUNCTOR_float1 = PL_new_functor(PL_new_atom("float"), 1); - FUNCTOR_curly1 = PL_new_functor(PL_new_atom("{}"), 1); - FUNCTOR_brackets1 = PL_new_functor(PL_new_atom("()"), 1); - FUNCTOR_dollar1 = PL_new_functor(PL_new_atom("$"), 1); - FUNCTOR_pointer1 = PL_new_functor(PL_new_atom("__obj__"), 1); - FUNCTOR_dir1 = PL_new_functor(PL_new_atom("dir"), 1); - FUNCTOR_iter1 = PL_new_functor(PL_new_atom("iter"), 1); - FUNCTOR_iter2 = PL_new_functor(PL_new_atom("iter"), 2); - FUNCTOR_len1 = PL_new_functor(PL_new_atom("len"), 1); - FUNCTOR_range1 = PL_new_functor(PL_new_atom("range"), 1); - FUNCTOR_range2 = PL_new_functor(PL_new_atom("range"), 2); - FUNCTOR_range3 = PL_new_functor(PL_new_atom("range"), 3); - FUNCTOR_sum1 = PL_new_functor(PL_new_atom("sum"), 1); - FUNCTOR_complex2 = PL_new_functor(PL_new_atom("i"), 2); - FUNCTOR_plus2 = PL_new_functor(PL_new_atom("+"), 2); - FUNCTOR_sub2 = PL_new_functor(PL_new_atom("-"), 2); - FUNCTOR_mul2 = PL_new_functor(PL_new_atom("*"), 2); - FUNCTOR_div2 = PL_new_functor(PL_new_atom("/"), 2); - FUNCTOR_hat2 = PL_new_functor(PL_new_atom("^"), 2); - FUNCTOR_colon2 = PL_new_functor(PL_new_atom(":"), 2); - FUNCTOR_comma2 = PL_new_functor(PL_new_atom(","), 2); - FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2); - FUNCTOR_sqbrackets2 = PL_new_functor(PL_new_atom("[]"), 2); - } - -foreign_t end_python(void) { - if (!python_in_python) - Py_Finalize(); - - return true; -} - -static bool libpython_initialized = 0; - -X_API bool do_init_python(void) { - // char **argv; - if (libpython_initialized) - return true; - libpython_initialized = true; - - // PyGILState_STATE gstate = PyGILState_Ensure(); - term_t t = PL_new_term_ref(); - if (!python_in_python) - Py_Initialize(); - install_py_constants(); - PL_reset_term_refs(t); - install_pl2pl(); - // PyGILState_Release(gstate); - add_modules(); - return true; - -} - -#ifndef _WIN32 - - -O_API bool init_python_dll(void); - - -O_API bool init_python_dll(void) { - do_init_python(); - install_pypreds(); - return 1; -} - -#endif diff --git a/pl/boot.yap b/pl/boot.yap index 6d2693c10..e57399718 100644 --- a/pl/boot.yap +++ b/pl/boot.yap @@ -476,7 +476,7 @@ If this hook preodicate succeeds it must instantiate the _Action_ argument to t :- ensure_loaded('../pl/pathconf.yap'). -:- ensure_loaded('../pl/android.yap'). +:- current_prolog_fkag(android,true), ensure_loaded('../pl/android.yap'). diff --git a/pl/consult.yap b/pl/consult.yap index 75c70e50b..a7b1f71f6 100644 --- a/pl/consult.yap +++ b/pl/consult.yap @@ -968,7 +968,7 @@ source_file(Mod:Pred, FileName) :- + directory (prolog_load_context/2 option) - Full name for the directory where YAP is currently consulting the + Full name for the directory where YAP is currently consulting the file. + file (prolog_load_context/2 option) diff --git a/pl/control.yap b/pl/control.yap index 1945e8591..b6307a5d8 100644 --- a/pl/control.yap +++ b/pl/control.yap @@ -88,80 +88,80 @@ */ /** @pred forall(: _Cond_,: _Action_) - * - * + * + * * For all alternative bindings of _Cond_ _Action_ can be * proven. The example verifies that all arithmetic statements in the list * _L_ are correct. It does not say which is wrong if one proves wrong. - * + * * ~~~~~{.prolog} * ?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), * Result =:= Formula). * ~~~~~ - * - * + * + * */ forall(Cond, Action) :- \+((Cond, \+(Action))). /** @pred ignore(: _Goal_) - * - * + * + * * Calls _Goal_ as once/1, but succeeds, regardless of whether * `Goal` succeeded or not. Defined as: - * + * * ~~~~~{.prolog} * ignore(Goal) :- * Goal, !. * ignore(_). * ~~~~~ - * - * + * + * */ ignore(Goal) :- (Goal->true;true). /** @pred if(? _G_,? _H_,? _I_) - * + * * Call goal _H_ once per each solution of goal _H_. If goal * _H_ has no solutions, call goal _I_. - * + * * The built-in `if/3` is similar to `->/3`, with the difference * that it will backtrack over the test. Consider the following * small data-base: - * + * * ~~~~~{.prolog} * a(1). b(a). c(x). * a(2). b(b). c(y). * ~~~~~ - * + * * Execution of an `if/3` query will proceed as follows: - * + * * ~~~~~{.prolog} * ?- if(a(X),b(Y),c(Z)). - * + * * X = 1, * Y = a ? ; - * + * * X = 1, * Y = b ? ; - * + * * X = 2, * Y = a ? ; - * + * * X = 2, * Y = b ? ; - * + * * no * ~~~~~ - * + * * The system will backtrack over the two solutions for `a/1` and the * two solutions for `b/1`, generating four solutions. - * + * * Cuts are allowed inside the first goal _G_, but they will only prune * over _G_. - * + * * If you want _G_ to be deterministic you should use if-then-else, as * it is both more efficient and more portable. - * + * */ if(X,Y,Z) :- ( @@ -175,12 +175,12 @@ if(X,Y,Z) :- ). /** @pred call( Closure,...,? Ai,...) is iso - * - * + * + * * Meta-call with extra pattern arguments, where _Closure_ is a closure * that is converted into a goal by appending the _Ai_ additional * arguments. YAP supports up to 10 extra arguments. - * + * */ call(X,A) :- '$execute'(X,A). @@ -205,10 +205,10 @@ call(X,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10) :- '$execute'(X,A1,A2,A3,A4,A5,A6,A7,A8,A call(X,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11) :- '$execute'(X,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11). /** @pred call_cleanup(: _Goal_, : _CleanUpGoal_) - * + * * This is similar to call_cleanup/1 but with an additional * _CleanUpGoal_ which gets called after _Goal_ is finished. - * + * */ call_cleanup(Goal, Cleanup) :- '$gated_call'( false , Goal,_Catcher, Cleanup) . @@ -412,14 +412,14 @@ query_to_answer(G, V, Status, Bindings) :- %% @{ /** @pred nb_getval(+ _Name_,- _Value_) - * - * + * + * * The nb_getval/2 predicate is a synonym for b_getval/2, introduced for * compatibility and symmetry. As most scenarios will use a particular * global variable either using non-backtrackable or backtrackable * assignment, using nb_getval/2 can be used to document that the * variable is used non-backtrackable. - * + * */ nb_getval(GlobalVariable, Val) :- '__NB_getval__'(GlobalVariable, Val, Error), @@ -435,18 +435,18 @@ nb_getval(GlobalVariable, Val) :- /** @pred b_getval(+ _Name_, - _Value_) - * - * + * + * * Get the value associated with the global variable _Name_ and unify * it with _Value_. Note that this unification may further * instantiate the value of the global variable. If this is undesirable * the normal precautions (double negation or copy_term/2) must be * taken. The b_getval/2 predicate generates errors if _Name_ is not * an atom or the requested variable does not exist. - * + * * Notice that for compatibility with other systems _Name_ must be already associated with a term: otherwise the system will generate an error. - * - * + * + * */ b_getval(GlobalVariable, Val) :- '__NB_getval__'(GlobalVariable, Val, Error), @@ -487,7 +487,7 @@ b_getval(GlobalVariable, Val) :- b_setval('$spy_glist',[]), '$disable_debugging'. -'$debug_restart'(state(Trace, Debug, State, SPY_GN, GList)) :- +'$debug_restore'(state(Trace, Debug, State, SPY_GN, GList)) :- b_setval('$spy_glist',GList), b_setval('$spy_gn',SPY_GN), set_prolog_flag(debug, Debug), @@ -513,14 +513,14 @@ debugging. */ break :- '$debug_state'(DState), - '$debug_start', + '$debug_stop', '$break'( true ), current_output(OutStream), current_input(InpStream), current_prolog_flag(break_level, BL ), NBL is BL+1, set_prolog_flag(break_level, NBL ), format(user_error, '% Break (level ~w)~n', [NBL]), - '$do_live', + live, !, set_value('$live','$true'), '$debug_restore'(DState), diff --git a/pl/errors.yap b/pl/errors.yap index 96942163f..abb4fb9ea 100644 --- a/pl/errors.yap +++ b/pl/errors.yap @@ -109,22 +109,16 @@ error_handler(Error, Level) :- '$process_error'('$forward'(Msg), _) :- !, throw( '$forward'(Msg) ). -'$process_error'(abort, Level) :- +'$process_error'(error(event(abort,I),C), Level) :- !, ( + current_prolog_flag(break_level, 0), Level \== top -> - throw( abort ) - ; - current_prolog_flag(break_level, 0) - -> - print_message(informational,abort(user)), - fail - ; - current_prolog_flag(break_level, I0), - I is I0-1, - current_prolog_flag(break_level, I), - throw(abort) + print_message(informational,abort(user)), + fail + ; + throw( error(event(abort,I),C) ) ). '$process_error'(error(permission_error(module,redefined,A),B), Level) :- Level \= top, !,