diff --git a/docs/CMakeLists.txt b/docs/CMakeLists.txt index 526e72e00..bfca223cf 100644 --- a/docs/CMakeLists.txt +++ b/docs/CMakeLists.txt @@ -39,6 +39,10 @@ ${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/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 @@ -52,14 +56,19 @@ ${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}/OPTYap/locks_alpha_funcs.h +${CMAKE_SOURCE_DIR}/OPTYap/locks_mips_funcs.h +${CMAKE_SOURCE_DIR}/OPTYap/locks_sparc.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 ${CMAKE_SOURCE_DIR}/*/bprolog/* ${CMAKE_SOURCE_DIR}/*/prism/* @@ -77,6 +86,7 @@ ${CMAKE_SOURCE_DIR}/*/bprolog/* ) + foreach(i ${DOCS_EXCLUDE_}) string(APPEND DOCS_EXCLUDE ${i} " ") endforeach(i ${DOCS_EXCLUDE_}) diff --git a/docs/Doxyfile.in b/docs/Doxyfile.in index 07622a5d7..078bf9580 100644 --- a/docs/Doxyfile.in +++ b/docs/Doxyfile.in @@ -1090,7 +1090,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/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/packages/packages/python/pl2pl.c b/packages/packages/python/pl2pl.c deleted file mode 100644 index 5c2c334a0..000000000 --- a/packages/packages/python/pl2pl.c +++ /dev/null @@ -1,150 +0,0 @@ - -#include "py4yap.h" - -static foreign_t array_to_python_list(term_t addr, term_t type, term_t szt, - term_t py) { - void *src; - Py_ssize_t sz, i; - int is_float; - - if (!PL_get_pointer(addr, &src) || !PL_get_bool(type, &is_float) || - !PL_get_intptr(szt, &sz)) - return false; - PyObject *list = PyList_New(sz); - if (!list) - return false; - if (is_float) { - double *v = (double *)src; - for (i = 0; i < sz; i++) { - PyObject *x = PyFloat_FromDouble(v[i]); - PyList_SET_ITEM(list, i, x); - } - } else { - YAP_Int *v = (YAP_Int *)src; - for (i = 0; i < sz; i++) { - PyObject *x = PyFloat_FromDouble(v[i]); - PyList_SET_ITEM(list, i, x); - } - } - if (PL_is_variable(py)) { - return address_to_term(list, py); - } - return assign_to_symbol(py, list); -} - -static foreign_t array_to_python_tuple(term_t addr, term_t type, term_t szt, - term_t py) { - void *src; - Py_ssize_t sz, i; - int is_float; - - if (!PL_get_pointer(addr, &src) || !PL_get_bool(type, &is_float) || - !PL_get_intptr(szt, &sz)) - return false; - PyObject *list = PyTuple_New(sz); - if (!list) - return false; - if (is_float) { - double *v = (double *)src; - - for (i = 0; i < sz; i++) { - PyObject *x; - x = PyFloat_FromDouble(v[i]); - if (PyTuple_SetItem(list, i, x)) { - PyErr_Print(); - return FALSE; - } - } - } else { - int32_t *v = (int32_t *)src; - PyObject *x; - for (i = 0; i < sz; i++) { -#if PY_MAJOR_VERSION < 3 - x = PyInt_FromLong(v[i]); -#else - x = PyLong_FromLong(v[i]); -#endif - if (PyTuple_SetItem(list, i, x)) { - PyErr_Print(); - return FALSE; - } - } - } - if (PL_is_variable(py)) { - return address_to_term(list, py); - } - return assign_to_symbol(py, list); -} - -static foreign_t array_to_python_view(term_t addr, term_t type, term_t szt, - term_t colt, term_t py) { - void *src; - Py_ssize_t sz, rows; - int is_float; - Py_ssize_t shape[2]; - - if (!PL_get_pointer(addr, &src) || !PL_get_bool(type, &is_float) || - !PL_get_intptr(szt, &sz) || !PL_get_intptr(colt, &rows)) - return false; - Py_buffer buf; - buf.buf = src; - if (is_float) { - buf.len = sz * sizeof(double); - buf.itemsize = sizeof(double); - } else { - buf.len = sz * sizeof(YAP_Int); - buf.itemsize = sizeof(YAP_Int); - } - buf.readonly = false; - buf.format = NULL; - buf.ndim = 2; - buf.shape = shape; - buf.strides = NULL; - buf.suboffsets = NULL; - PyObject *o = PyMemoryView_FromBuffer(&buf); - if (!o) { - PyErr_Print(); - return false; - } - if (PL_is_variable(py)) { - return address_to_term(o, py); - } - return assign_to_symbol(py, o); -} - -static foreign_t prolog_list_to_python_list(term_t plist, term_t pyt, term_t tlen) { - size_t sz, i; - PyErr_Clear(); - PyObject *pyl = term_to_python(pyt, true, NULL); - term_t targ = PL_new_term_ref(); - - if (PL_skip_list(plist, targ, &sz) <0 || ! PL_get_nil(targ)) { - pyErrorAndReturn( false, false); -} - if (!PyList_Check(pyl)) - { - pyErrorAndReturn( false, false); - } - if (sz > 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