This commit is contained in:
Vitor Santos Costa 2016-09-23 01:38:09 -05:00
commit 94cde0bf18
71 changed files with 5430 additions and 4258 deletions

22
.gitignore vendored
View File

@ -181,3 +181,25 @@ packages/myddas/DaysInHospital_Y3.csv
packages/myddas/agile.csv
*.pyc
*.cmake#
*.tex
*.c#
packages/swig/yap_wrap.cxx
packages/swig/yap_wrap.h
packages/swig/yap_wrap.cpp
packages/swig/yap.py
*.ipynb
packages/python/yap_kernel/x/__init__.py
packages/python/yap_kernel/x/__main__.py
*.gch

View File

@ -33,10 +33,6 @@
#if BP_FREE
P1REG = PCBACKUP;
#endif
if (LOCAL_Error_TYPE == THROW_EVENT) {
LOCAL_Error_TYPE = YAP_NO_ERROR;
return 1;
}
return 0;
ENDBOp();

View File

@ -1101,19 +1101,10 @@
#if defined(YAPOR) || defined(THREADS)
PP = NULL;
#endif
if (LOCAL_Error_TYPE == RESOURCE_ERROR_ATTRIBUTED_VARIABLES) {
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (!Yap_growglobal(NULL)) {
Yap_NilError(RESOURCE_ERROR_ATTRIBUTED_VARIABLES, LOCAL_ErrorMessage);
FAIL();
}
} else {
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (!Yap_gc(3, ENV, CP)) {
Yap_NilError(RESOURCE_ERROR_STACK, LOCAL_ErrorMessage);
FAIL();
}
}
#if defined(YAPOR) || defined(THREADS)
PELOCK(5,ClauseCodeToLogUpdClause(PREG)->ClPred);
PP = ClauseCodeToLogUpdClause(PREG)->ClPred;
@ -8171,7 +8162,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreProcessedError(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
setregs();
FAIL();
}
@ -8216,7 +8207,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8257,7 +8248,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8305,7 +8296,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8349,7 +8340,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8394,7 +8385,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8435,7 +8426,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8483,7 +8474,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8527,7 +8518,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8572,7 +8563,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8613,7 +8604,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8661,7 +8652,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8712,7 +8703,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8757,7 +8748,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8800,7 +8791,7 @@
d0 = p_div(MkIntegerTerm(d1),Yap_Eval(d0) PASS_REGS);
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8848,7 +8839,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8896,7 +8887,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8943,7 +8934,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -8988,7 +8979,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9033,7 +9024,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9074,7 +9065,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9122,7 +9113,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9167,7 +9158,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9211,7 +9202,7 @@
d0 = p_or(Yap_Eval(d0), MkIntegerTerm(d1) PASS_REGS);
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9252,7 +9243,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9300,7 +9291,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9349,7 +9340,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9395,7 +9386,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9436,7 +9427,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9480,7 +9471,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9529,7 +9520,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9574,7 +9565,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9621,7 +9612,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9665,7 +9656,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9708,7 +9699,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9753,7 +9744,7 @@
BEGP(pt0);
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9799,7 +9790,7 @@
setregs();
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}
@ -9844,7 +9835,7 @@
}
if (d0 == 0L) {
saveregs();
Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage);
Yap_PreprocessedError()
setregs();
FAIL();
}

View File

@ -16,7 +16,6 @@
*************************************************************************/
#ifdef SCCS
static char SccsId[] = "%W% %G%";
#endif
#define ADTDEFS_C
@ -810,6 +809,7 @@ Prop Yap_NewPredPropByFunctor(FunctorEntry *fe, Term cur_mod) {
p->cs.p_code.ExpandCode = EXPAND_OP_CODE;
p->TimeStampOfPred = 0L;
p->LastCallOfPred = LUCALL_ASSERT;
p->MetaEntryOfPred = NULL;
if (cur_mod == TermProlog)
p->ModuleOfPred = 0L;
else
@ -892,6 +892,7 @@ Prop Yap_NewThreadPred(PredEntry *ap USES_REGS) {
#if SIZEOF_INT_P == 4
p->ExtraPredFlags = 0L;
#endif
p->MetaEntryOfPred = NULL;
p->src.OwnerFile = ap->src.OwnerFile;
p->OpcodeOfPred = FAIL_OPCODE;
p->CodeOfPred = p->cs.p_code.TrueCodeOfPred = (yamop *)(&(p->OpcodeOfPred));
@ -946,6 +947,7 @@ Prop Yap_NewPredPropByAtom(AtomEntry *ae, Term cur_mod) {
p->OpcodeOfPred = UNDEF_OPCODE;
p->cs.p_code.ExpandCode = EXPAND_OP_CODE;
p->CodeOfPred = p->cs.p_code.TrueCodeOfPred = (yamop *)(&(p->OpcodeOfPred));
p->MetaEntryOfPred = NULL;
if (cur_mod == TermProlog)
p->ModuleOfPred = 0;
else

View File

@ -21,10 +21,9 @@ static char SccsId[] = "%W% %G%";
#include "Yap.h"
#include "alloc.h"
#include "YapHeap.h"
#include "Yatom.h"
#include "alloc.h"
#include "yapio.h"
#if HAVE_STRING_H
#include <string.h>
@ -78,6 +77,8 @@ void *my_malloc(size_t sz) {
p = malloc(sz);
// Yap_DebugPuts(stderr,"gof\n");
if (Yap_do_low_level_trace)
fprintf(stderr, "+ %p : %lu\n", p, sz);
if (sz > 500 && write_malloc++ > 0)
__android_log_print(ANDROID_LOG_ERROR, "YAPDroid ", "+ %d %p", write_malloc,
p);
@ -88,6 +89,8 @@ void *my_realloc(void *ptr, size_t sz) {
void *p;
p = realloc(ptr, sz);
if (Yap_do_low_level_trace)
fprintf(stderr, "+ %p -> %p : %lu\n", ptr, p, sz);
// Yap_DebugPuts(stderr,"gof\n");
if (sz > 500 && write_malloc++ > 0)
__android_log_print(ANDROID_LOG_ERROR, "YAPDroid ", "* %d %p", write_malloc,
@ -97,6 +100,8 @@ void *my_realloc(void *ptr, size_t sz) {
void my_free(void *p) {
// printf("f %p\n",p);
if (Yap_do_low_level_trace)
fprintf(stderr, "+ %p\n", p);
if (write_malloc && write_malloc++ > 0)
__android_log_print(ANDROID_LOG_ERROR, "YAPDroid ", "- %d %p", write_malloc,
p);

1102
C/amasm.c

File diff suppressed because it is too large Load Diff

View File

@ -2,8 +2,6 @@
#include "Yap.h"
#include "Yatom.h"
/**
* Scan a list of arguments and output results to a pre-processed vector.
*
@ -13,9 +11,7 @@
* @return all arguments, some of them set, some of them not.
*/
static xarg *
matchKey(Atom key, xarg *e0, int n, const param_t *def)
{
static xarg *matchKey(Atom key, xarg *e0, int n, const param_t *def) {
int i;
for (i = 0; i < n; i++) {
if (!strcmp((char *)def->name, (char *)RepAtom(key)->StrOfAE)) {
@ -31,9 +27,7 @@ matchKey(Atom key, xarg *e0, int n, const param_t *def)
* Returns the index of an argument key, or -1 if not found.
*
*/
int
Yap_ArgKey(Atom key, const param_t *def, int n)
{
int Yap_ArgKey(Atom key, const param_t *def, int n) {
int i;
for (i = 0; i < n; i++) {
if (!strcmp((char *)def->name, (char *)RepAtom(key)->StrOfAE)) {
@ -46,23 +40,15 @@ Yap_ArgKey(Atom key, const param_t *def, int n)
#define failed(e, t, a) failed__(e, t, a PASS_REGS)
static xarg *
failed__( yap_error_number e, Term t, xarg *a USES_REGS)
{
static xarg *failed__(yap_error_number e, Term t, xarg *a USES_REGS) {
free(a);
LOCAL_Error_TYPE = e;
LOCAL_Error_Term = t;
return NULL;
}
xarg *
Yap_ArgListToVector (Term listl, const param_t *def, int n)
{
xarg *Yap_ArgListToVector(Term listl, const param_t *def, int n) {
CACHE_REGS
listl = Deref(listl);
xarg *a = calloc(n, sizeof(xarg));
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (IsApplTerm(listl) && FunctorOfTerm(listl) == FunctorModule)
listl = ArgOfTerm(2, listl);
if (!IsPairTerm(listl) && listl != TermNil) {
@ -139,9 +125,7 @@ Yap_ArgListToVector (Term listl, const param_t *def, int n)
return a;
}
static xarg *
matchKey2(Atom key, xarg *e0, int n, const param2_t *def)
{
static xarg *matchKey2(Atom key, xarg *e0, int n, const param2_t *def) {
int i;
for (i = 0; i < n; i++) {
if (!strcmp((char *)def->name, (char *)RepAtom(key)->StrOfAE)) {
@ -153,13 +137,10 @@ matchKey2(Atom key, xarg *e0, int n, const param2_t *def)
return NULL;
}
/// Yap_ArgList2ToVector is much the same as before,
/// but assumes parameters also have something called a
/// scope
xarg *
Yap_ArgList2ToVector (Term listl, const param2_t *def, int n)
{
xarg *Yap_ArgList2ToVector(Term listl, const param2_t *def, int n) {
CACHE_REGS
xarg *a = calloc(n, sizeof(xarg));
if (!IsPairTerm(listl) && listl != TermNil) {

View File

@ -234,22 +234,23 @@ static Int CloseMmappedArray(StaticArrayEntry *pp, void *area USES_REGS) {
}
if (ptr == NULL) {
#if !defined(USE_SYSTEM_MALLOC)
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1,
"close_mmapped_array (array chain incoherent)", strerror(errno));
Yap_FullError(SYSTEM_ERROR_INTERNAL, ARG1,
"close_mmapped_array (array chain incoherent)",
strerror(errno));
#endif
return FALSE;
}
if (munmap(ptr->start, ptr->size) == -1) {
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1, "close_mmapped_array (munmap: %s)",
strerror(errno));
Yap_FullError(SYSTEM_ERROR_INTERNAL, ARG1,
"close_mmapped_array (munmap: %s)", strerror(errno));
return (FALSE);
}
optr->next = ptr->next;
pp->ValueOfVE.ints = NULL;
pp->ArrayEArity = 0;
if (close(ptr->fd) < 0) {
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1, "close_mmapped_array (close: %s)",
strerror(errno));
Yap_FullError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1,
"close_mmapped_array (close: %s)", strerror(errno));
return (FALSE);
}
Yap_FreeAtomSpace((char *)ptr);
@ -271,30 +272,31 @@ static void ResizeMmappedArray(StaticArrayEntry *pp, Int dim,
and last we initialize again
*/
if (munmap(ptr->start, ptr->size) == -1) {
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1, "resize_mmapped_array (munmap: %s)",
strerror(errno));
Yap_FullError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1,
"resize_mmapped_array (munmap: %s)", strerror(errno));
return;
}
total_size = (ptr->size / ptr->items) * dim;
if (ftruncate(ptr->fd, total_size) < 0) {
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1,
Yap_FullError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1,
"resize_mmapped_array (ftruncate: %s)", strerror(errno));
return;
}
if (lseek(ptr->fd, total_size - 1, SEEK_SET) < 0) {
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1, "resize_mmapped_array (lseek: %s)",
strerror(errno));
Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1,
"resize_mmapped_array (lseek: %s)", strerror(errno));
return;
}
if (write(ptr->fd, "", 1) < 0) {
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1, "resize_mmapped_array (write: %s)",
strerror(errno));
Yap_FullError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1,
"resize_mmapped_array (write: %s)", strerror(errno));
return;
}
if ((ptr->start = (void *)mmap(0, (size_t)total_size, PROT_READ | PROT_WRITE,
MAP_SHARED, ptr->fd, 0)) == (void *)-1) {
Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1, "resize_mmapped_array (mmap: %s)",
strerror(errno));
Yap_FullError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1,
"resize_mmapped_array (mmap: %s)", ___LINE__, __FUNCTION__,
-__FILE__, strerror(errno));
return;
}
ptr->size = total_size;
@ -309,25 +311,15 @@ static Term GetTermFromArray(DBTerm *ref USES_REGS) {
Term TRef;
while ((TRef = Yap_FetchTermFromDB(ref)) == 0L) {
if (LOCAL_Error_TYPE == RESOURCE_ERROR_ATTRIBUTED_VARIABLES) {
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (!Yap_growglobal(NULL)) {
Yap_Error(RESOURCE_ERROR_ATTRIBUTED_VARIABLES, TermNil,
LOCAL_ErrorMessage);
return TermNil;
}
} else {
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, Yap_gcP())) {
Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage);
return TermNil;
}
return 0;
}
}
return TRef;
} else {
P = (yamop *)FAILCODE;
return TermNil;
Yap_Error(DOMAIN_ERROR_NOT_ZERO, ARG1, "Null reference.");
return 0;
}
}
@ -355,8 +347,8 @@ static Term GetNBTerm(live_term *ar, Int indx USES_REGS) {
livet = termt;
} else {
DBTerm *ref = (DBTerm *)RepAppl(termt);
if ((livet = GetTermFromArray(ref PASS_REGS)) == TermNil) {
return TermNil;
if ((livet = GetTermFromArray(ref PASS_REGS)) == 0) {
return 0;
}
}
YapBind(&(ar[indx].tlive), livet);
@ -391,10 +383,13 @@ static Term AccessNamedArray(Atom a, Int indx USES_REGS) {
if (ArrayIsDynamic(pp)) {
Term out;
READ_LOCK(pp->ArRWLock);
if (IsVarTerm(pp->ValueOfVE) || pp->ArrayEArity <= indx || indx < 0) {
if (IsVarTerm(pp->ValueOfVE)) {
READ_UNLOCK(pp->ArRWLock);
P = (yamop *)FAILCODE;
return (MkAtomTerm(AtomFoundVar));
Yap_Error(INSTANTIATION_ERROR, ARG1, "unbound static array", indx);
}
if (pp->ArrayEArity <= indx || indx < 0) {
READ_UNLOCK(pp->ArRWLock);
Yap_Error(DOMAIN_ERROR_ARRAY_OVERFLOW, ARG1, "bad index %ld", indx);
}
out = RepAppl(pp->ValueOfVE)[indx + 1];
READ_UNLOCK(pp->ArRWLock);
@ -404,11 +399,7 @@ static Term AccessNamedArray(Atom a, Int indx USES_REGS) {
READ_LOCK(ptr->ArRWLock);
if (pp->ArrayEArity <= indx || indx < 0) {
/* Yap_Error(DOMAIN_ERROR_ARRAY_OVERFLOW, MkIntegerTerm(indx),
* "access_array");*/
READ_UNLOCK(ptr->ArRWLock);
P = (yamop *)FAILCODE;
return (MkAtomTerm(AtomFoundVar));
Yap_Error(DOMAIN_ERROR_ARRAY_OVERFLOW, ARG1, "bad index %ld", indx);
}
switch (ptr->ArrayType) {
@ -489,9 +480,9 @@ static Term AccessNamedArray(Atom a, Int indx USES_REGS) {
case array_of_nb_terms: {
/* The object is now in use */
Term out = GetNBTerm(ptr->ValueOfVE.lterms, indx PASS_REGS);
READ_UNLOCK(ptr->ArRWLock);
return out;
if (out == 0)
return TermNil;
}
case array_of_terms: {
/* The object is now in use */
@ -1655,7 +1646,6 @@ static Int array_references(USES_REGS1) {
/** @pred update_array(+ _Name_, + _Index_, ? _Value_)
Attribute value _Value_ to _Name_[ _Index_]. Type
restrictions must be respected for static arrays. This operation is
available for dynamic arrays if `MULTI_ASSIGNMENT_VARIABLES` is

View File

@ -704,13 +704,6 @@ restart_aux:
cut_fail();
}
#define CastToAtom(x) CastToAtom__(x PASS_REGS)
static Term CastToAtom__(Term t USES_REGS) {
if (IsAtomTerm(t))
return t;
return MkAtomTerm(Yap_AtomicToAtom(t PASS_REGS));
}
#define CastToNumeric(x) CastToNumeric__(x PASS_REGS)

View File

@ -1623,7 +1623,7 @@ static int run_emulator(USES_REGS1) {
return out;
}
X_API bool YAP_EnterGoal(PredEntry *pe, yhandle_t ptr, YAP_dogoalinfo *dgi) {
X_API bool YAP_EnterGoal(PredEntry *pe, CELL *ptr, YAP_dogoalinfo *dgi) {
CACHE_REGS
bool out;
@ -1634,7 +1634,7 @@ X_API bool YAP_EnterGoal(PredEntry *pe, yhandle_t ptr, YAP_dogoalinfo *dgi) {
dgi->CurSlot = LOCAL_CurSlot;
// ensure our current ENV receives current P.
Yap_PrepGoal(pe->ArityOfPE, Yap_AddressFromSlot(ptr), B PASS_REGS);
Yap_PrepGoal(pe->ArityOfPE, nullptr, B PASS_REGS);
P = pe->CodeOfPred;
// __android_log_print(ANDROID_LOG_INFO, "YAP ", "ap=%p %d %x %x args=%x,%x
// slot=%d", pe, pe->CodeOfPred->opc, FAILCODE, Deref(ARG1), Deref(ARG2),
@ -1679,7 +1679,7 @@ X_API bool YAP_RetryGoal(YAP_dogoalinfo *dgi) {
return out;
}
X_API bool YAP_LeaveGoal(int backtrack, YAP_dogoalinfo *dgi) {
X_API bool YAP_LeaveGoal(bool backtrack, YAP_dogoalinfo *dgi) {
CACHE_REGS
choiceptr myB;

View File

@ -1408,7 +1408,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
DBRef *TmpRefBase = (DBRef *)LOCAL_TrailTop;
CELL *CodeAbs; /* how much code did we find */
int vars_found = FALSE;
yap_error_number oerr = LOCAL_Error_TYPE;
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (p == NULL) {
@ -1418,6 +1418,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
#endif
DBRef out = (DBRef)CreateDBTermForVar(extra_size, dbg);
*pstat = TRUE;
LOCAL_Error_TYPE = oerr;
return out;
#ifdef COROUTINING
}
@ -1425,6 +1426,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
} else if (IsAtomOrIntTerm(Tm)) {
DBRef out = (DBRef)CreateDBTermForAtom(Tm, extra_size, dbg);
*pstat = FALSE;
LOCAL_Error_TYPE = oerr;
return out;
}
} else {
@ -1434,8 +1436,10 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
#endif
) {
*pstat = TRUE;
LOCAL_Error_TYPE = oerr;
return CreateDBRefForVar(Tm, p, InFlag, dbg);
} else if (IsAtomOrIntTerm(Tm)) {
LOCAL_Error_TYPE = oerr;
return CreateDBRefForAtom(Tm, p, InFlag, dbg);
}
}
@ -1463,6 +1467,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
LOCAL_Error_Size = (UInt)(extra_size + sizeof(ppt0));
LOCAL_Error_TYPE = RESOURCE_ERROR_AUXILIARY_STACK;
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL;
}
ntp0 = ppt0->Contents;
@ -1470,6 +1475,8 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
LOCAL_Error_Size = 0;
LOCAL_Error_TYPE = RESOURCE_ERROR_TRAIL;
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL;
}
dbg->lr = dbg->LinkAr = (link_entry *)TR;
@ -1481,6 +1488,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
&attachments, &vars_found, dbg);
if (ntp == NULL) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL;
}
} else
@ -1495,6 +1503,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
&vars_found, dbg);
if (ntp == NULL) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL;
}
} else {
@ -1535,6 +1544,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
&vars_found, dbg);
if (ntp == NULL) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL;
}
}
@ -1542,6 +1552,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
CodeAbs = (CELL *)((CELL)ntp - (CELL)ntp0);
if (LOCAL_Error_TYPE) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL; /* Error Situation */
}
NOfCells = ntp - ntp0; /* End Of Code Info */
@ -1560,11 +1571,13 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
LOCAL_Error_Size = (UInt)DBLength(CodeAbs);
LOCAL_Error_TYPE = RESOURCE_ERROR_AUXILIARY_STACK;
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL;
}
if ((InFlag & MkIfNot) &&
(dbg->found_one = check_if_wvars(p->First, NOfCells, ntp0))) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return dbg->found_one;
}
} else {
@ -1572,6 +1585,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
if ((InFlag & MkIfNot) &&
(dbg->found_one = check_if_nvars(p->First, NOfCells, ntp0, dbg))) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return dbg->found_one;
}
}
@ -1581,6 +1595,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
LOCAL_Error_Size = (UInt)DBLength(CodeAbs);
LOCAL_Error_TYPE = RESOURCE_ERROR_AUXILIARY_STACK;
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return NULL;
}
flag |= DBWithRefs;
@ -1588,6 +1603,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
#if SIZEOF_LINK_ENTRY == 2
if (Unsigned(CodeAbs) >= 0x40000) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return generate_dberror_msg(SYSTEM_ERROR_INTERNAL, 0,
"trying to store term larger than 256KB");
}
@ -1598,6 +1614,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
ppt = (DBTerm *)(ptr + extra_size);
if (ptr == NULL) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return generate_dberror_msg(RESOURCE_ERROR_HEAP, sz,
"heap crashed against stacks");
}
@ -1609,6 +1626,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
pp = AllocDBSpace(sz);
if (pp == NULL) {
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return generate_dberror_msg(RESOURCE_ERROR_HEAP, sz,
"heap crashed against stacks");
}
@ -1682,6 +1700,7 @@ static DBRef CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat,
ppt->DBRefs = NULL;
}
Yap_ReleasePreAllocCodeSpace((ADDR)pp0);
LOCAL_Error_TYPE = oerr;
return pp;
}
}

View File

@ -11,7 +11,7 @@
* File: errors.c *
* Last Rev: *
* Mods: *
* Comments: Yap'S error handlers *
* Comments: Yap's error handlers *
* *
*************************************************************************/
@ -32,7 +32,6 @@
#endif
#include "Foreign.h"
bool Yap_Warning(const char *s, ...) {
CACHE_REGS
va_list ap;
@ -62,8 +61,7 @@ bool Yap_Warning(const char *s, ...) {
} else
return false;
va_end(ap);
if (pred->OpcodeOfPred == UNDEF_OPCODE||
pred->OpcodeOfPred == FAIL_OPCODE) {
if (pred->OpcodeOfPred == UNDEF_OPCODE || pred->OpcodeOfPred == FAIL_OPCODE) {
fprintf(stderr, "warning message: %s\n", tmpbuf);
LOCAL_DoingUndefp = false;
LOCAL_within_print_message = false;
@ -75,6 +73,21 @@ bool Yap_Warning(const char *s, ...) {
rc = Yap_execute_pred(pred, ts, true PASS_REGS);
return rc;
}
void Yap_InitError(yap_error_number e, Term t, const char *msg) {
if (LOCAL_ActiveError.status) {
Yap_exit(1);
}
LOCAL_ActiveError.errorNo = e;
LOCAL_ActiveError.errorFile = NULL;
LOCAL_ActiveError.errorFunction = NULL;
LOCAL_ActiveError.errorLine = 0;
if (msg) {
LOCAL_Error_Size = strlen(msg);
strcpy(LOCAL_ActiveError.errorComment, msg);
} else {
LOCAL_Error_Size = 0;
}
}
bool Yap_PrintWarning(Term twarning) {
CACHE_REGS
@ -91,9 +104,7 @@ bool Yap_PrintWarning(Term twarning) {
}
LOCAL_DoingUndefp = true;
LOCAL_within_print_message = true;
if (pred->OpcodeOfPred == UNDEF_OPCODE ||
pred->OpcodeOfPred == FAIL_OPCODE
) {
if (pred->OpcodeOfPred == UNDEF_OPCODE || pred->OpcodeOfPred == FAIL_OPCODE) {
fprintf(stderr, "warning message:\n");
Yap_DebugPlWrite(twarning);
fprintf(stderr, "\n");
@ -112,12 +123,12 @@ bool Yap_PrintWarning(Term twarning) {
return rc;
}
bool Yap_HandleError__(const char *file, const char *function, int lineno, const char *s, ...) {
bool Yap_HandleError__(const char *file, const char *function, int lineno,
const char *s, ...) {
CACHE_REGS
yap_error_number err = LOCAL_Error_TYPE;
const char *serr;
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (LOCAL_ErrorMessage) {
serr = LOCAL_ErrorMessage;
} else {
@ -136,7 +147,8 @@ bool Yap_HandleError__(const char *file, const char *function, int lineno, const
}
if (!Yap_ExpandPreAllocCodeSpace(0, NULL, TRUE)) {
/* crash in flames */
Yap_Error__(file, function, lineno, RESOURCE_ERROR_AUXILIARY_STACK, ARG1, serr);
Yap_Error__(file, function, lineno, RESOURCE_ERROR_AUXILIARY_STACK, ARG1,
serr);
return false;
}
return true;
@ -156,7 +168,6 @@ int Yap_SWIHandleError(const char *s, ...) {
yap_error_number err = LOCAL_Error_TYPE;
char *serr;
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (LOCAL_ErrorMessage) {
serr = LOCAL_ErrorMessage;
} else {
@ -214,7 +225,6 @@ static void error_exit_yap(int value) {
fprintf(stderr, "Execution stack:\n");
for (i = 0; i < frames; ++i) {
fprintf(stderr, " %s\n", strs[i]);
}
free(strs);
#endif
@ -257,6 +267,7 @@ static char tmpbuf[YAP_BUF_SIZE];
#define END_ERROR_CLASSES() \
} \
return TermNil; \
}
#define BEGIN_ERRORS() \
@ -281,7 +292,7 @@ static char tmpbuf[YAP_BUF_SIZE];
return mkerrorct(B, ts);
#define END_ERRORS() \
} \
} return TermNil; \
}
#include "YapErrors.h"
@ -336,14 +347,22 @@ yamop *Yap_Error__(const char *file, const char *function, int lineno,
tmpbuf);
Yap_RestartYap(1);
}
LOCAL_ActiveError.errorNo = type;
LOCAL_ActiveError.errorAsText = Yap_LookupAtom(Yap_errorName( type ));
LOCAL_ActiveError.errorClass = Yap_errorClass( type);
LOCAL_ActiveError.classAsText = Yap_LookupAtom(Yap_errorClassName( LOCAL_ActiveError.errorClass ));
LOCAL_ActiveError.errorLine = lineno;
LOCAL_ActiveError.errorFunction = function;
LOCAL_ActiveError.errorFile = file;
Yap_find_prolog_culprit(PASS_REGS1);
LOCAL_PrologMode |= InErrorMode;
LOCAL_Error_TYPE = YAP_NO_ERROR;
Yap_ClearExs();
if (where == 0L) {
where = TermNil;
}
// first, obtain current location
// sprintf(LOCAL_FileNameBuf, "%s:%d in C-function %s ", file, lineno, function);
// sprintf(LOCAL_FileNameBuf, "%s:%d in C-function %s ", file, lineno,
// function);
// tf = MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf));
#if DEBUG_STRICT
if (Yap_heap_regs && !(LOCAL_PrologMode & BootMode))
@ -416,14 +435,15 @@ yamop *Yap_Error__(const char *file, const char *function, int lineno,
if (LOCAL_PrologMode & BootMode) {
/* crash in flames! */
fprintf(stderr, "%s:%d:0 YAP Fatal Error %d in function %s:\n %s exiting....\n", file, lineno, type, function, s);
fprintf(stderr,
"%s:%d:0 YAP Fatal Error %d in function %s:\n %s exiting....\n",
file, lineno, type, function, s);
error_exit_yap(1);
}
#ifdef DEBUG
// DumpActiveGoals( USES_REGS1 );
#endif /* DEBUG */
if (!IsVarTerm(where) &&
IsApplTerm(where) &&
if (!IsVarTerm(where) && IsApplTerm(where) &&
FunctorOfTerm(where) == FunctorError) {
error_t = where;
P = (yamop *)FAILCODE;
@ -501,9 +521,6 @@ yamop *Yap_Error__(const char *file, const char *function, int lineno,
ts[2] = where;
nt[0] = mkerrort(type, ts + 2);
}
}
LOCAL_PrologMode &= ~InErrorMode;
if (type != ABORT_EVENT) {
@ -540,12 +557,12 @@ yamop *Yap_Error__(const char *file, const char *function, int lineno,
MkPairTerm(MkPairTerm(MkAtomTerm(Yap_LookupAtom("c")), t3), nt[1]);
}
if ((location = Yap_pc_location(P, B, ENV)) != TermNil) {
nt[1] = MkPairTerm(MkPairTerm(MkAtomTerm(Yap_LookupAtom("p")), location),
nt[1]);
nt[1] = MkPairTerm(
MkPairTerm(MkAtomTerm(Yap_LookupAtom("p")), location), nt[1]);
}
if ((location = Yap_env_location(CP, B, ENV, 0)) != TermNil) {
nt[1] = MkPairTerm(MkPairTerm(MkAtomTerm(Yap_LookupAtom("e")), location),
nt[1]);
nt[1] = MkPairTerm(
MkPairTerm(MkAtomTerm(Yap_LookupAtom("e")), location), nt[1]);
}
}
}
@ -568,14 +585,11 @@ yamop *Yap_Error__(const char *file, const char *function, int lineno,
Yap_JumpToEnv(error_t);
P = (yamop *)FAILCODE;
LOCAL_PrologMode &= ~InErrorMode;
return P;
}
static Int
is_boolean( USES_REGS1 )
{
static Int is_boolean(USES_REGS1) {
Term t = Deref(ARG1);
// Term Context = Deref(ARG2)Yap_Error(INSTANTIATION_ERROR, t, NULL);;
if (IsVarTerm(t)) {
@ -585,9 +599,7 @@ is_boolean( USES_REGS1 )
return t == TermTrue || t == TermFalse;
}
static Int
is_atom( USES_REGS1 )
{
static Int is_atom(USES_REGS1) {
Term t = Deref(ARG1);
// Term Context = Deref(ARG2)Yap_Error(INSTANTIATION_ERROR, t, NULL);;
if (IsVarTerm(t)) {
@ -597,11 +609,7 @@ is_atom( USES_REGS1 )
return IsAtomTerm(t);
}
static Int
is_callable( USES_REGS1 )
{
static Int is_callable(USES_REGS1) {
Term G = Deref(ARG1);
// Term Context = Deref(ARG2);
while (true) {
@ -638,9 +646,7 @@ is_callable( USES_REGS1 )
return false;
}
static Int
is_predicate_indicator( USES_REGS1 )
{
static Int is_predicate_indicator(USES_REGS1) {
Term G = Deref(ARG1);
// Term Context = Deref(ARG2);
Term mod = CurrentModule;
@ -667,13 +673,85 @@ is_predicate_indicator( USES_REGS1 )
return false;
}
static Int close_error(USES_REGS1) {
LOCAL_Error_TYPE = YAP_NO_ERROR;
return true;
}
void
Yap_InitErrorPreds( void )
{
#undef BEGIN_ERROR_CLASSES
#undef ECLASS
#undef END_ERROR_CLASSES
#undef BEGIN_ERRORS
#undef E0
#undef E
#undef E2
#undef END_ERRORS
#define BEGIN_ERROR_CLASSES() typedef enum aux_class {
#define ECLASS(CL, A, B) CL##__,
#define END_ERROR_CLASSES() \
} \
aux_class_t;
#define BEGIN_ERRORS()
#define E0(X, Y)
#define E(X, Y, Z)
#define E2(X, Y, Z, W)
#define END_ERRORS()
#include <YapErrors.h>
#undef BEGIN_ERROR_CLASSES
#undef ECLASS
#undef END_ERROR_CLASSES
#undef BEGIN_ERRORS
#undef E0
#undef E
#undef E2
#undef END_ERRORS
#define BEGIN_ERROR_CLASSES() static const char *c_error_class_name[] = {
#define ECLASS(CL, A, B) A,
#define END_ERROR_CLASSES() \
NULL \
}
typedef struct c_error_info {
int class;
const char *name;
} c_error_t;
#define BEGIN_ERRORS() static struct c_error_info c_error_list[] = {
#define E0(X, Y) {Y##__, ""},
#define E(X, Y, Z) {Y##__, Z},
#define E2(X, Y, Z, W) {Y##__, Z " " W},
#define END_ERRORS() \
{ YAPC_NO_ERROR, "" } \
} \
;
#include <YapErrors.h>
yap_error_class_number Yap_errorClass(yap_error_number e) {
return c_error_list[e].class;
}
const char *Yap_errorName(yap_error_number e) { return c_error_list[e].name; }
const char *Yap_errorClassName(yap_error_class_number e) {
return c_error_class_name[e];
}
void Yap_InitErrorPreds(void) {
CACHE_REGS
Yap_InitCPred("$close_error", 0, close_error, HiddenPredFlag);
Yap_InitCPred("is_boolean", 2, is_boolean, TestPredFlag);
Yap_InitCPred("is_callable", 2, is_callable, TestPredFlag);
Yap_InitCPred("is_atom", 2, is_atom, TestPredFlag);
Yap_InitCPred("is_predicate_indicator", 2, is_predicate_indicator, TestPredFlag);
Yap_InitCPred("is_predicate_indicator", 2, is_predicate_indicator,
TestPredFlag);
}

114
C/exec.c
View File

@ -209,6 +209,66 @@ static Int save_env_b(USES_REGS1) {
return true;
}
/** Look for a predicate with same functor as t,
create a new one of it cannot find it.
*/
static PredEntry *new_pred(Term t, Term tmod, char *pname) {
Term t0 = t;
restart:
if (IsVarTerm(t)) {
Yap_Error(INSTANTIATION_ERROR, t0, pname);
return NULL;
} else if (IsAtomTerm(t)) {
return RepPredProp(PredPropByAtom(AtomOfTerm(t), tmod));
} else if (IsIntegerTerm(t) && tmod == IDB_MODULE) {
return Yap_FindLUIntKey(IntegerOfTerm(t));
} else if (IsApplTerm(t)) {
Functor fun = FunctorOfTerm(t);
if (IsExtensionFunctor(fun)) {
Yap_Error(TYPE_ERROR_CALLABLE, Yap_PredicateIndicator(t, tmod), pname);
return NULL;
}
if (fun == FunctorModule) {
Term tmod = ArgOfTerm(1, t);
if (IsVarTerm(tmod)) {
Yap_Error(INSTANTIATION_ERROR, t0, pname);
return NULL;
}
if (!IsAtomTerm(tmod)) {
Yap_Error(TYPE_ERROR_ATOM, t0, pname);
return NULL;
}
t = ArgOfTerm(2, t);
goto restart;
}
return RepPredProp(PredPropByFunc(fun, tmod));
} else
return NULL;
}
static bool CommaCall(Term t, Term mod) {
PredEntry *pen;
arity_t i;
if (IsVarTerm(t) || (pen = new_pred(t, mod, "_,_")))
return false;
for (i = 0; i < pen->ArityOfPE; i++) {
YENV[-EnvSizeInCells - i] = XREGS[i + 1];
}
YENV[E_CB] = (CELL)B;
YENV[E_CP] = (CELL)P;
YENV[E_E] = (CELL)ENV;
YENV[E_DEPTH] = DEPTH;
ASP = YENV - (EnvSizeInCells + i);
ENV = YENV;
YENV = ASP;
if ((P = pen->MetaEntryOfPred) == NULL) {
P = Yap_InitCommaContinuation(pen);
}
return P == NULL;
}
inline static bool do_execute(Term t, Term mod USES_REGS) {
Term t0 = t;
t = Yap_YapStripModule(t, &mod);
@ -220,14 +280,28 @@ inline static bool do_execute(Term t, Term mod USES_REGS) {
}
if (IsVarTerm(t) || IsVarTerm(mod)) {
return CallError(INSTANTIATION_ERROR, t0, mod PASS_REGS);
} else if (IsApplTerm(t)) {
}
if (IsApplTerm(t)) {
register Functor f = FunctorOfTerm(t);
register CELL *pt;
PredEntry *pen;
unsigned int i, arity;
f = FunctorOfTerm(t);
if (IsExtensionFunctor(f)) {
if (f == FunctorComma && false) {
Term t2 = ArgOfTerm(2, t);
if (IsVarTerm(t2))
return CallMetaCall(t, mod PASS_REGS);
if (!CommaCall(t2, mod))
return CallMetaCall(t, mod PASS_REGS);
Term t1 = ArgOfTerm(1, t);
t = t1;
pen = new_pred(t, mod, "_,_");
if (pen == NULL || (arity = pen->ArityOfPE) == 0) {
return do_execute(t, mod);
}
} else if (IsExtensionFunctor(f)) {
return CallError(TYPE_ERROR_CALLABLE, t, mod PASS_REGS);
}
arity = ArityOfFunctor(f);
@ -237,9 +311,6 @@ inline static bool do_execute(Term t, Term mod USES_REGS) {
pen = RepPredProp(PredPropByFunc(f, mod));
/* You thought we would be over by now */
/* but no meta calls require special preprocessing */
if (pen->PredFlags & MetaPredFlag) {
return CallMetaCall(t, mod PASS_REGS);
}
/* now let us do what we wanted to do from the beginning !! */
/* I cannot use the standard macro here because
otherwise I would dereference the argument and
@ -249,7 +320,7 @@ inline static bool do_execute(Term t, Term mod USES_REGS) {
#if YAPOR_SBA
Term d0 = *pt++;
if (d0 == 0)
` XREGS[i] = (CELL)(pt - 1);
XREGS[i] = (CELL)(pt - 1);
else
XREGS[i] = d0;
#else
@ -257,8 +328,9 @@ inline static bool do_execute(Term t, Term mod USES_REGS) {
XREGS[i] = *pt++;
#endif
}
return (CallPredicate(pen, B, pen->CodeOfPred PASS_REGS));
} else if (IsAtomTerm(t)) {
return CallPredicate(pen, B, pen->CodeOfPred PASS_REGS);
}
if (IsAtomTerm(t)) {
PredEntry *pe;
Atom a = AtomOfTerm(t);
@ -271,12 +343,8 @@ inline static bool do_execute(Term t, Term mod USES_REGS) {
/* call may not define new system predicates!! */
pe = RepPredProp(PredPropByAtom(a, mod));
return (CallPredicate(pe, B, pe->CodeOfPred PASS_REGS));
} else if (IsIntTerm(t)) {
return CallError(TYPE_ERROR_CALLABLE, t, mod PASS_REGS);
} else {
/* Is Pair Term */
return (CallMetaCall(t, mod PASS_REGS));
}
return CallMetaCall(t, mod PASS_REGS);
}
static Term copy_execn_to_heap(Functor f, CELL *pt, unsigned int n,
@ -1133,6 +1201,7 @@ static Int execute0(USES_REGS1) { /* '$execute0'(Goal,Mod) */
if (Yap_has_a_signal() && !LOCAL_InterruptsDisabled) {
return EnterCreepMode(t, mod PASS_REGS);
}
t = Yap_YapStripModule(t, &mod);
restart_exec:
if (IsVarTerm(t)) {
Yap_Error(INSTANTIATION_ERROR, ARG3, "call/1");
@ -1407,7 +1476,7 @@ static bool exec_absmi(bool top, yap_reset_t reset_mode USES_REGS) {
return out;
}
void Yap_PrepGoal(UInt arity, CELL *pt, choiceptr saved_b USES_REGS) {
void Yap_PrepGoal(arity_t arity, CELL *pt, choiceptr saved_b USES_REGS) {
/* create an initial pseudo environment so that when garbage
collection is going up in the environment chain it doesn't get
confused */
@ -2004,13 +2073,28 @@ static Int jump_env(USES_REGS1) {
if (IsVarTerm(t)) {
Yap_Error(INSTANTIATION_ERROR, t, "throw ball must be bound");
return false;
} else if (IsApplTerm(t) && FunctorOfTerm(t) == FunctorError) {
Term t2;
Yap_find_prolog_culprit(PASS_REGS1);
LOCAL_Error_TYPE = ERROR_EVENT;
t = ArgOfTerm(1, t);
if (IsApplTerm(t) && IsAtomTerm((t2 = ArgOfTerm(1,t)))) {
LOCAL_ActiveError.errorAsText = AtomOfTerm(t2);
LOCAL_ActiveError.classAsText = NameOfFunctor(t);
} else if (IsAtomTerm(t)) {
LOCAL_ActiveError.errorAsText = AtomOfTerm(t);
LOCAL_ActiveError.classAsText = NULL;
}
} else {
LOCAL_Error_TYPE = THROW_EVENT;
}
LOCAL_ActiveError.prologPredName = NULL;
Yap_PutException(t);
bool out = JumpToEnv(PASS_REGS1);
if (B != NULL && P == FAILCODE && B->cp_ap == NOCODE &&
LCL0 - (CELL *)B > LOCAL_CBorder) {
// we're failing up to the top layer
LOCAL_Error_TYPE = THROW_EVENT;
}
return out;
}

View File

@ -134,7 +134,7 @@
CPredicate f = PREG->y_u.pp.p->cs.f_code;
yamop *oldPREG = PREG;
saveregs();
d0 = (f)(PASS_REGS1);
d0 = f(PASS_REGS1);
setregs();
#ifdef SHADOW_S
SREG = Yap_REGS.S_;

View File

@ -49,7 +49,6 @@ p_load_foreign( USES_REGS1 )
Int returncode = FALSE;
yhandle_t CurSlot = Yap_StartSlots();
strcpy(LOCAL_ErrorSay,"Invalid arguments");
// Yap_DebugPlWrite(ARG1); printf("%s\n", " \n");
//Yap_DebugPlWrite(ARG2); printf("%s\n", " \n");
//ap_DebugPlWrite(ARG3); printf("%s\n", " \n");

View File

@ -23,7 +23,7 @@
/* original goal */
d0 = ENV_YREG[-EnvSizeInCells-1];
/* predicate we had used */
pen = RepPredProp((Prop)IntegerOfTerm(ENV_YREG[-EnvSizeInCells-2]));
pen = RepPredProp(AddressOfTerm(ENV_YREG[-EnvSizeInCells-2]));
/* current module at the time */
mod = ENV_YREG[-EnvSizeInCells-3];
/* set YREG */

146
C/stack.c
View File

@ -30,10 +30,10 @@
#include "Yap.h"
#include "clause.h"
#include "yapio.h"
#include "iopreds.h"
#include "eval.h"
#include "iopreds.h"
#include "tracer.h"
#include "yapio.h"
#ifdef YAPOR
#include "or.macros.h"
#endif /* YAPOR */
@ -507,8 +507,7 @@ static Int find_code_in_clause(PredEntry *pp, yamop *codeptr, void **startp,
if (cl == NULL)
return 0;
if (IN_BLOCK(codeptr, cl, cl->ClSize)) {
if
(startp)
if (startp)
*startp = (CODEADDR)cl;
if (endp)
*endp = (CODEADDR)cl + cl->ClSize;
@ -528,8 +527,7 @@ static Term clause_loc(void *clcode, PredEntry *pp) {
CACHE_REGS
if (pp->PredFlags & LogUpdatePredFlag) {
LogUpdClause *cl = ClauseCodeToLogUpdClause(clcode);
cl = ClauseCodeToLogUpdClause(clcode);
LogUpdClause *cl = clcode;
if (cl->ClFlags & FactMask) {
return MkIntegerTerm(cl->lusl.ClLine);
@ -537,25 +535,25 @@ static Term clause_loc(void *clcode, PredEntry *pp) {
return MkIntegerTerm(cl->lusl.ClSource->ag.line_number);
}
} else if (pp->PredFlags & DynamicPredFlag) {
DynamicClause *cl;
cl = ClauseCodeToDynamicClause(clcode);
// DynamicClause *cl;
// cl = ClauseCodeToDynamicClause(clcode);
return TermNil;
return MkIntTerm(0);
} else if (pp->PredFlags & MegaClausePredFlag) {
MegaClause *mcl = ClauseCodeToMegaClause(pp->cs.p_code.FirstClause);
return MkIntTerm(mcl->ClLine);
} else {
StaticClause *cl;
cl = ClauseCodeToStaticClause(clcode);
cl = clcode;
if (cl->ClFlags & FactMask) {
return MkIntTerm(cl->usc.ClLine);
} else if (cl->ClFlags & SrcMask) {
return MkIntTerm(cl->usc.ClSource->ag.line_number);
} else
return TermNil;
return MkIntTerm(0);
}
return TermNil;
return MkIntTerm(0);
}
static int cl_code_in_pred(PredEntry *pp, yamop *codeptr, void **startp,
@ -1007,10 +1005,9 @@ static Term all_cps(choiceptr b_ptr USES_REGS) {
bp[1] = AbsPair(HR);
}
b_ptr = b_ptr->cp_b;
if (!IsVarTerm((CELL)b_ptr) ||
(CELL*)b_ptr < HR ||
(CELL*)b_ptr > LCL0) {
//Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "choice-point chain corrupted at %p!!!\n", b_ptr);
if (!IsVarTerm((CELL)b_ptr) || (CELL *)b_ptr < HR || (CELL *)b_ptr > LCL0) {
// Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "choice-point chain
// corrupted at %p!!!\n", b_ptr);
break;
}
}
@ -1040,7 +1037,7 @@ static Int p_all_envs(USES_REGS1) {
return Yap_unify(ARG1, t);
}
Term clause_info(yamop *codeptr, PredEntry *pp) {
static Term clause_info(yamop *codeptr, PredEntry *pp) {
CACHE_REGS
Term ts[2];
void *begin;
@ -1055,24 +1052,72 @@ Term clause_info(yamop *codeptr, PredEntry *pp) {
ts[0] = MkAtomTerm(pp->src.OwnerFile);
Term t1 = Yap_MkApplTerm(FunctorModule, 2, ts);
if (find_code_in_clause(pp, codeptr, &begin, NULL) <= 0 ||
((ts[0] = clause_loc(begin, pp) == TermNil))) {
if ((find_code_in_clause(pp, codeptr, &begin, NULL)) <= 0) {
ts[0] = clause_loc(pp->cs.p_code.FirstClause, pp);
ts[1] = clause_loc(pp->cs.p_code.LastClause, pp);
if (ts[0] == ts[1] && ts[1] != TermNil) {
} else if (ts[1] == TermNil && ts[0] != TermNil)
} else if (ts[1] == TermNil && ts[0] != MkIntTerm(0))
ts[0] = Yap_MkApplTerm(FunctorMinus, 2, ts);
}
ts[1] = t1;
return Yap_MkApplTerm(FunctorModule, 2, ts);
}
bool set_clause_info(yamop *codeptr, PredEntry *pp) {
CACHE_REGS
Term ts[2];
void *begin;
if (pp->ArityOfPE == 0) {
LOCAL_ActiveError.prologPredName = (Atom)pp->FunctorOfPred;
LOCAL_ActiveError.prologPredArity = 0;
} else {
LOCAL_ActiveError.prologPredName = NameOfFunctor(pp->FunctorOfPred);
LOCAL_ActiveError.prologPredArity = pp->ArityOfPE;
}
LOCAL_ActiveError.prologPredModule =
(pp->ModuleOfPred ? pp->ModuleOfPred : TermProlog);
LOCAL_ActiveError.prologPredFile = pp->src.OwnerFile;
if (codeptr->opc == UNDEF_OPCODE) {
LOCAL_ActiveError.prologPredFirstLine = 0;
LOCAL_ActiveError.prologPredLine = 0;
LOCAL_ActiveError.prologPredLastLine = 0;
return true;
} else if (pp->cs.p_code.NOfClauses) {
if ((LOCAL_ActiveError.prologPredCl =
find_code_in_clause(pp, codeptr, &begin, NULL)) <= 0) {
LOCAL_ActiveError.prologPredLine = 0;
} else {
LOCAL_ActiveError.prologPredLine = IntegerOfTerm(clause_loc(begin, pp));
}
if (pp->PredFlags & LogUpdatePredFlag) {
LOCAL_ActiveError.prologPredFirstLine = IntegerOfTerm(
ts[0] = clause_loc(
ClauseCodeToLogUpdClause(pp->cs.p_code.FirstClause), pp));
LOCAL_ActiveError.prologPredLastLine = IntegerOfTerm(
ts[1] = clause_loc(ClauseCodeToLogUpdClause(pp->cs.p_code.LastClause),
pp));
} else {
LOCAL_ActiveError.prologPredFirstLine = IntegerOfTerm(
ts[0] = clause_loc(
ClauseCodeToStaticClause(pp->cs.p_code.FirstClause), pp));
LOCAL_ActiveError.prologPredLastLine = IntegerOfTerm(
ts[1] = clause_loc(ClauseCodeToStaticClause(pp->cs.p_code.LastClause),
pp));
}
return true;
} else {
return false;
}
}
static Term error_culprit(bool internal USES_REGS) {
PredEntry *pe;
// case number 1: Yap_Error called from built-in.
void *startp, *endp;
// case number 1: Yap_Error called from built-in.
pe = ClauseInfoForCode(P, &startp, &endp PASS_REGS);
if (internal) {
pe = EnvPreg(CP);
if (pe->PredFlags & HiddenPredFlag)
return clause_info(P, pe);
} else {
CELL *curENV = ENV;
@ -1081,7 +1126,7 @@ static Term error_culprit(bool internal USES_REGS) {
while (curCP != YESCODE) {
if (pe->ModuleOfPred)
return clause_info(P, pe);
return clause_info(curCP, pe);
curENV = (CELL *)(curENV[E_E]);
curCP = (yamop *)(curENV[E_CP]);
pe = EnvPreg(curCP);
@ -1090,6 +1135,31 @@ static Term error_culprit(bool internal USES_REGS) {
return TermNil;
}
bool Yap_find_prolog_culprit(USES_REGS1) {
PredEntry *pe;
void *startp, *endp;
// case number 1: Yap_Error called from built-in.
pe = ClauseInfoForCode(P, &startp, &endp PASS_REGS);
if (pe && (CurrentModule == 0 || !(pe->PredFlags & HiddenPredFlag))) {
return set_clause_info(P, pe);
} else {
CELL *curENV = ENV;
yamop *curCP = CP;
PredEntry *pe = EnvPreg(curCP);
while (curCP != YESCODE) {
curENV = (CELL *)(curENV[E_E]);
if (curENV == NULL)
break;
pe = EnvPreg(curCP);
if (pe->ModuleOfPred)
return set_clause_info(curCP, pe);
curCP = (yamop *)(curENV[E_CP]);
}
}
return TermNil;
}
static Term all_calls(bool internal USES_REGS) {
Term ts[6];
Functor f = Yap_MkFunctor(AtomLocalSp, 6);
@ -1671,8 +1741,7 @@ void Yap_dump_stack(void) {
}
#endif
#endif
Yap_detect_bug_location(P, FIND_PRED_FROM_ANYWHERE
, 256);
Yap_detect_bug_location(P, FIND_PRED_FROM_ANYWHERE, 256);
fprintf(stderr, "%%\n%% PC: %s\n", (char *)HR);
Yap_detect_bug_location(CP, FIND_PRED_FROM_ANYWHERE, 256);
fprintf(stderr, "%% Continuation: %s\n", (char *)HR);
@ -1777,7 +1846,8 @@ void DumpActiveGoals(USES_REGS1) {
if (mod == PROLOG_MODULE)
mod = TermProlog;
Term t = Yap_MkNewApplTerm(f, pe->ArityOfPE);
Yap_plwrite(Yap_PredicateIndicator(t,mod),GLOBAL_Stream+2, 0, 0, GLOBAL_MaxPriority);
Yap_plwrite(Yap_PredicateIndicator(t, mod), GLOBAL_Stream + 2, 0, 0,
GLOBAL_MaxPriority);
fputc('\n', stderr);
} else {
UNLOCK(pe->PELock);
@ -1812,17 +1882,20 @@ void DumpActiveGoals(USES_REGS1) {
if (mod == IDB_MODULE) {
if (pe->PredFlags & NumberDBPredFlag) {
Int id = pe->src.IndxId;
Yap_plwrite(MkIntegerTerm(id),GLOBAL_Stream+2, 0, 0, GLOBAL_MaxPriority);
Yap_plwrite(MkIntegerTerm(id), GLOBAL_Stream + 2, 0, 0,
GLOBAL_MaxPriority);
} else if (pe->PredFlags & AtomDBPredFlag) {
Atom At = (Atom)pe->FunctorOfPred;
Yap_plwrite(MkAtomTerm(At),GLOBAL_Stream+2, 0, 0, GLOBAL_MaxPriority);
Yap_plwrite(MkAtomTerm(At), GLOBAL_Stream + 2, 0, 0,
GLOBAL_MaxPriority);
} else {
Functor f = pe->FunctorOfPred;
Atom At = NameOfFunctor(f);
arity_t arity = ArityOfFunctor(f);
int i;
Yap_plwrite(MkAtomTerm(At),GLOBAL_Stream+2, 0, 0, GLOBAL_MaxPriority);
Yap_plwrite(MkAtomTerm(At), GLOBAL_Stream + 2, 0, 0,
GLOBAL_MaxPriority);
fputc('(', stderr);
for (i = 0; i < arity; i++) {
if (i > 0)
@ -1835,11 +1908,13 @@ void DumpActiveGoals(USES_REGS1) {
Yap_plwrite(b_ptr->cp_a2, GLOBAL_Stream + 2, 0, 0, GLOBAL_MaxPriority);
fputc(')', stderr);
} else if (pe->ArityOfPE == 0) {
Yap_plwrite(MkAtomTerm((Atom)f),GLOBAL_Stream+2, 0, 0, GLOBAL_MaxPriority);
Yap_plwrite(MkAtomTerm((Atom)f), GLOBAL_Stream + 2, 0, 0,
GLOBAL_MaxPriority);
} else {
Int i = 0, arity = pe->ArityOfPE;
if (opnum == _or_last || opnum == _or_else) {
Yap_plwrite(MkAtomTerm(NameOfFunctor(f)),GLOBAL_Stream+2, 0, 0, GLOBAL_MaxPriority);
Yap_plwrite(MkAtomTerm(NameOfFunctor(f)), GLOBAL_Stream + 2, 0, 0,
GLOBAL_MaxPriority);
fputc('(', stderr);
for (i = 0; i < arity; i++) {
if (i > 0)
@ -1849,7 +1924,8 @@ void DumpActiveGoals(USES_REGS1) {
fputs(") :- ... ( _ ; _ ", stderr);
} else {
Term *args = &(b_ptr->cp_a1);
Yap_plwrite(MkAtomTerm(NameOfFunctor(f)),GLOBAL_Stream+2, 0, 0, GLOBAL_MaxPriority);
Yap_plwrite(MkAtomTerm(NameOfFunctor(f)), GLOBAL_Stream + 2, 0, 0,
GLOBAL_MaxPriority);
fputc('(', stderr);
for (i = 0; i < arity; i++) {
if (i > 0)
@ -1865,8 +1941,7 @@ void DumpActiveGoals(USES_REGS1) {
}
}
void Yap_detect_bug_location(yamop *yap_pc, int where_from,
int psize) {
void Yap_detect_bug_location(yamop *yap_pc, int where_from, int psize) {
Atom pred_name;
UInt pred_arity;
Term pred_module;
@ -1975,8 +2050,7 @@ Term Yap_env_location(yamop *cp, choiceptr b_ptr, CELL *env, Int ignore_first) {
return TermNil;
if (ignore_first <= 0 && pe
// pe->ModuleOfPred != PROLOG_MODULE &&s
&&
!(pe->PredFlags & HiddenPredFlag)) {
&& !(pe->PredFlags & HiddenPredFlag)) {
return build_bug_location(cp, pe);
} else {
if (NULL && b_ptr && b_ptr->cp_env < env) {

View File

@ -39,21 +39,24 @@ void *buf__, *cur__;
#define init_alloc(I) \
void *ov__ = TR, *ocur__ = LOCAL_ScannerStack; \
if (!LOCAL_ScannerStack) LOCAL_ScannerStack = (char *)TR
if (!LOCAL_ScannerStack) \
LOCAL_ScannerStack = (char *)TR
#define mark_stack() \
void *otr__ = TR; void * ost__ = LOCAL_ScannerStack; TR =(tr_fr_ptr)LOCAL_ScannerStack
void *otr__ = TR; \
void *ost__ = LOCAL_ScannerStack; \
TR = (tr_fr_ptr)LOCAL_ScannerStack
#define restore_stack() \
TR = otr__; LOCAL_ScannerStack = ost__
TR = otr__; \
LOCAL_ScannerStack = ost__
#define export_buf(s) {}
#define export_buf(s) \
{}
#define unprotect_stack(s) \
TR = ov__, LOCAL_ScannerStack = ocur__
#define unprotect_stack(s) TR = ov__, LOCAL_ScannerStack = ocur__
// LOCAL_ScannerStack = ov__, TR = ot__
static bool alloc_ovfl(size_t sz) {
return (char *)+(sz + 4096) > (char *)LOCAL_TrailTop;
}
@ -194,8 +197,7 @@ static Int SkipListCodes(unsigned char **bufp, Term *l, Term **tailp,
return length;
}
static unsigned char *latin2utf8(seq_tv_t *inp, size_t
*lengp) {
static unsigned char *latin2utf8(seq_tv_t *inp, size_t *lengp) {
unsigned char *b0 = inp->val.uc;
size_t sz = *lengp = strlen(inp->val.c);
sz *= 2;
@ -214,7 +216,6 @@ static unsigned char *latin2utf8(seq_tv_t *inp, size_t
return buf;
}
static unsigned char *wchar2utf8(seq_tv_t *inp, size_t *lengp) {
*lengp = wcslen(inp->val.w);
size_t sz = *lengp * 4;
@ -306,15 +307,12 @@ unsigned char *Yap_readText(seq_tv_t *inp, size_t *lengp) {
if (!(inp->type & YAP_STRING_TERM)) {
if (IsVarTerm(inp->val.t)) {
LOCAL_Error_TYPE = INSTANTIATION_ERROR;
} else if (!IsAtomTerm(inp->val.t) &&
inp->type == YAP_STRING_ATOM) {
} else if (!IsAtomTerm(inp->val.t) && inp->type == YAP_STRING_ATOM) {
LOCAL_Error_TYPE = TYPE_ERROR_ATOM;
} else if (!IsStringTerm(inp->val.t) &&
inp->type == YAP_STRING_STRING) {
} else if (!IsStringTerm(inp->val.t) && inp->type == YAP_STRING_STRING) {
LOCAL_Error_TYPE = TYPE_ERROR_STRING;
} else if (!IsPairOrNilTerm(inp->val.t) && !IsStringTerm(inp->val.t) &&
inp->type ==
(YAP_STRING_ATOMS_CODES | YAP_STRING_STRING)) {
inp->type == (YAP_STRING_ATOMS_CODES | YAP_STRING_STRING)) {
LOCAL_Error_TYPE = TYPE_ERROR_LIST;
} else if (!IsNumTerm(inp->val.t) &&
(inp->type & (YAP_STRING_INT | YAP_STRING_FLOAT |
@ -342,14 +340,14 @@ unsigned char *Yap_readText(seq_tv_t *inp, size_t *lengp) {
if (IsStringTerm(inp->val.t) && inp->type & YAP_STRING_STRING) {
// this is a term, extract to a buffer, and representation is wide
// Yap_DebugPlWriteln(inp->val.t);
return UStringOfTerm(inp->val.t);
return (unsigned char *)UStringOfTerm(inp->val.t);
}
if (((inp->type & (YAP_STRING_CODES | YAP_STRING_ATOMS)) ==
(YAP_STRING_CODES | YAP_STRING_ATOMS)) && IsPairOrNilTerm(inp->val.t)) {
(YAP_STRING_CODES | YAP_STRING_ATOMS)) &&
IsPairOrNilTerm(inp->val.t)) {
// Yap_DebugPlWriteln(inp->val.t);
return inp->val.uc =
Yap_ListToBuffer(s0, inp->val.t, inp, &wide, lengp
PASS_REGS);
Yap_ListToBuffer(s0, inp->val.t, inp, &wide, lengp PASS_REGS);
// this is a term, extract to a sfer, and representation is wide
}
if (inp->type & YAP_STRING_CODES && IsPairOrNilTerm(inp->val.t)) {
@ -404,8 +402,7 @@ unsigned char *Yap_readText(seq_tv_t *inp, size_t *lengp) {
s = 0;
else
s = Malloc(0);
if (!Yap_mpz_to_string(Yap_BigIntOfTerm(inp->val.t), s, MaxTmp() - 1,
10)) {
if (!Yap_mpz_to_string(Yap_BigIntOfTerm(inp->val.t), s, MaxTmp() - 1, 10)) {
AUX_ERROR(inp->val.t, MaxTmp(PASS_REGS1), s, char);
}
*lengp = strlen(s);
@ -460,14 +457,15 @@ static Term write_strings(unsigned char *s0, seq_tv_t *out,
utf8proc_int32_t chr;
int off;
off = get_utf8(cp, -1, &chr);
if (off > 0) cp += off;
if (off > 0)
cp += off;
else {
// Yap_Error(TYPE_ERROR_TEXT, t, NULL);
cp++;
}
off = put_utf8(buf, chr);
if (off > 0) buf += off;
if (off > 0)
buf += off;
}
if (max >= min)
*buf++ = '\0';
@ -582,7 +580,8 @@ static Atom write_atom(void *s0, seq_tv_t *out, size_t leng USES_REGS) {
{
unsigned char *s = s0;
utf8proc_int32_t chr;
while (*s && get_utf8(s, -1, &chr) == 1) s++;
while (*s && get_utf8(s, -1, &chr) == 1)
s++;
if (*s == '\0')
return out->val.a = Yap_LookupAtom((char *)s0);
s = s0;
@ -614,7 +613,7 @@ size_t write_buffer(unsigned char *s0, seq_tv_t *out, size_t leng USES_REGS) {
if (out->enc == ENC_ISO_UTF8) {
room_end = strlen((char *)s0) + 1;
if (out->val.uc == NULL) {
out->val.uc = malloc(room_end);
out->val.uc = malloc(room_end < 16 ? 16 : room_end);
}
if (out->val.uc != s0) {
strcpy(out->val.c, (char *)s0);
@ -682,8 +681,7 @@ static size_t write_length(const unsigned char *s0, seq_tv_t *out,
return leng;
}
static Term write_number(unsigned char *s, seq_tv_t *out, int size
USES_REGS) {
static Term write_number(unsigned char *s, seq_tv_t *out, int size USES_REGS) {
Term t;
mark_stack();
t = Yap_StringToNumberTerm((char *)s, &out->enc);
@ -695,8 +693,7 @@ static Term string_to_term(void *s, seq_tv_t *out, size_t leng USES_REGS) {
Term o;
mark_stack();
o = out->val.t =
Yap_StringToTerm(s, strlen(s) + 1, &out->enc,
GLOBAL_MaxPriority, NULL);
Yap_StringToTerm(s, strlen(s) + 1, &out->enc, GLOBAL_MaxPriority, NULL);
restore_stack();
return o;
}
@ -707,11 +704,8 @@ bool write_Text(unsigned char *inp, seq_tv_t *out, size_t leng USES_REGS) {
if ((out->val.t = string_to_term(inp, out, leng PASS_REGS)) != 0L)
return out->val.t != 0;
}
if (out->type &
(YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG)) {
if (
(out->val.t = write_number(inp, out, leng PASS_REGS)) !=
0L) {
if (out->type & (YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG)) {
if ((out->val.t = write_number(inp, out, leng PASS_REGS)) != 0L) {
// Yap_DebugPlWriteln(out->val.t);
return true;
@ -721,8 +715,7 @@ bool write_Text(unsigned char *inp, seq_tv_t *out, size_t leng USES_REGS) {
return false;
}
if (out->type & (YAP_STRING_ATOM)) {
if (
write_atom(inp, out, leng PASS_REGS) != NIL) {
if (write_atom(inp, out, leng PASS_REGS) != NIL) {
Atom at = out->val.a;
if (at && (out->type & YAP_STRING_OUTPUT_TERM))
out->val.t = MkAtomTerm(at);
@ -766,8 +759,7 @@ bool write_Text(unsigned char *inp, seq_tv_t *out, size_t leng USES_REGS) {
out->val.t = write_number(inp, out, leng PASS_REGS);
// Yap_DebugPlWriteln(out->val.t);
return out->val.t != 0;
default: {
}
default: {}
}
return false;
}
@ -889,8 +881,9 @@ static unsigned char *concat(int n, unsigned char *sv[] USES_REGS) {
buf = Malloc(room + 1);
buf0 = (unsigned char *)buf;
for (i = 0; i < n; i++) {
buf = strcpy(buf, (char *) sv[i]);
buf += strlen( sv[i] );
char *s = (char *)sv[i];
buf = strcpy(buf, s);
buf += strlen(s);
}
return buf0;
}
@ -983,8 +976,7 @@ bool Yap_Splice_Text(int n, size_t cuts[], seq_tv_t *inp,
return false;
}
l0 = l - l1;
if (cmp_Text(skip_utf8((const unsigned char *) buf, l0), buf1,
l1) !=
if (cmp_Text(skip_utf8((const unsigned char *)buf, l0), buf1, l1) !=
0) {
unprotect_stack(NULL);
return false;
@ -1095,8 +1087,7 @@ const char *Yap_PredIndicatorToUTF8String(PredEntry *ap) {
if (ap->ModuleOfPred == IDB_MODULE) {
if (ap->PredFlags & NumberDBPredFlag) {
Int key = ap->src.IndxId;
snprintf(s, smax - s, "%"
PRIdPTR, key);
snprintf(s, smax - s, "%" PRIdPTR, key);
return LOCAL_FileNameBuf;
} else if (ap->PredFlags & AtomDBPredFlag) {
at = (Atom)(ap->FunctorOfPred);
@ -1119,8 +1110,7 @@ const char *Yap_PredIndicatorToUTF8String(PredEntry *ap) {
return NULL;
}
s += strlen(s);
snprintf(s, smax - s, "/%"
PRIdPTR, arity);
snprintf(s, smax - s, "/%" PRIdPTR, arity);
return s0;
}

View File

@ -20,45 +20,63 @@
#ifdef LOW_LEVEL_TRACER
#include "YapHeap.h"
#include "YapText.h"
#include "Yatom.h"
#include "attvar.h"
#include "clause.h"
#include "tracer.h"
#include "iopreds.h"
#include "tracer.h"
#include "yapio.h"
static void send_tracer_message(char *start, char *name, Int arity, char *mname,
CELL *args) {
static char *send_tracer_message(char *start, char *name, Int arity,
char *mname, CELL *args, char *s, char *top) {
if (name == NULL) {
#ifdef YAPOR
fprintf(stderr, "(%d)%s", worker_id, start);
s += snprintf(s, top - s, "(%d)%s", worker_id, start);
#else
fprintf(stderr, "%s", start);
s += snprintf(s, top - s, "%s", start);
#endif
} else {
int i;
if (arity) {
if (args)
fprintf(stderr, "%s %s:%s(", start, mname, name);
s += snprintf(s, top - s, "%s %s:%s(", start, mname, name);
else
fprintf(stderr, "%s %s:%s/%lu", start, mname, name,
s += snprintf(s, top - s, "%s %s:%s/%lu", start, mname, name,
(unsigned long int)arity);
} else {
fprintf(stderr, "%s %s:%s", start, mname, name);
s += snprintf(s, top - s, "%s %s:%s", start, mname, name);
}
if (args) {
for (i = 0; i < arity; i++) {
if (i > 0)
fprintf(stderr, ",");
Yap_plwrite(args[i], NULL, 15, Handle_vars_f | AttVar_Portray_f,
GLOBAL_MaxPriority);
size_t length = top - (s + 4);
if ((ssize_t)length < 16) {
s[0] = '\0';
return s;
}
if (i > 0) {
*s++ = ',';
}
const char *sn = Yap_TermToString(args[i], NULL, LOCAL_encoding,
Quote_illegal_f | Handle_vars_f);
size_t sz;
if (sn != s) {
if (sn == NULL) {
sn = "<* error *>";
}
strlcpy(s, sn, top - (s + 3));
}
sz = strlen(s);
s += sz;
}
if (arity) {
fprintf(stderr, ")");
*s++ = ')';
}
}
}
fprintf(stderr, "\n");
s[0] = '\0';
return s;
}
#if defined(__GNUC__)
@ -142,7 +160,7 @@ check_area(void)
// static CELL oldv = 0;
void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
void low_level_trace__(yap_low_level_port port, PredEntry *pred, CELL *args) {
CACHE_REGS
char *s;
char *mname;
@ -151,11 +169,7 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
vsc_count++;
// if (HR < ASP ) return;
// fif (vsc_count == 12534) jmp_deb( 2 );
#if __ANDROID__
if (vsc_count == 1)
freopen("log", "w", stderr);
#endif
char buf[512], *top = buf + 511, *b = buf;
// if (!worker_id) return;
LOCK(Yap_low_level_trace_lock);
@ -165,10 +179,10 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
LOCAL_ThreadHandle.thread_inst_count++;
#endif
#ifdef COMMENTED
fprintf(stderr, "in %p\n");
b = snprintf(b, top - b, "in %p\n");
CELL *gc_ENV = ENV;
while (gc_ENV != NULL) { /* no more environments */
fprintf(stderr, "%ld\n", LCL0 - gc_ENV);
b = snprintf(b, top - b, "%ld\n", LCL0 - gc_ENV);
gc_ENV = (CELL *)gc_ENV[E_E]; /* link to prev
* environment */
}
@ -176,7 +190,8 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
{
choiceptr b_p = B;
while (b_p) {
fprintf(stderr, "%p %ld\n", b_p, Yap_op_from_opcode(b_p->cp_ap->opc));
b = snprintf(b, top - b, "%p %ld\n", b_p,
Yap_op_from_opcode(b_p->cp_ap->opc));
b_p = b_p->cp_b;
}
}
@ -193,7 +208,7 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
if (vsc_count % 1LL == 0) {
UInt sz = Yap_regp->H0_[17];
UInt end = sizeof(MP_INT) / sizeof(CELL) + sz + 1;
fprintf(stderr, "VAL %lld %d %x/%x\n", vsc_count, sz, H0[16],
b = snprintf(b, top - b, "VAL %lld %d %x/%x\n", vsc_count, sz, H0[16],
H0[16 + end]);
}
} else
@ -306,10 +321,10 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
printf("\n");
}
#endif
fprintf(stderr, "%lld %ld ", vsc_count, LCL0 - (CELL *)B);
fprintf(stderr, "%ld ", LCL0 - (CELL *)Yap_REGS.CUT_C_TOP);
b += snprintf(b, top - b, "%lld %ld ", vsc_count, LCL0 - (CELL *)B);
b += snprintf(b, top - b, "%ld ", LCL0 - (CELL *)Yap_REGS.CUT_C_TOP);
#if defined(THREADS) || defined(YAPOR)
fprintf(stderr, "(%d)", worker_id);
b += snprintf(b, top - b, "(%d)", worker_id);
#endif
/* check_trail_consistency(); */
if (pred == NULL) {
@ -335,41 +350,42 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
}
/* if ((pred->ModuleOfPred == 0) && (s[0] == '$'))
return; */
send_tracer_message("CALL: ", s, arity, mname, args);
b = send_tracer_message("CALL: ", s, arity, mname, args, b, top);
break;
case try_or:
send_tracer_message("TRY_OR ", NULL, 0, NULL, args);
b = send_tracer_message("TRY_OR ", NULL, 0, NULL, args, b, top);
break;
case retry_or:
send_tracer_message("FAIL ", NULL, 0, NULL, args);
send_tracer_message("RETRY_OR ", NULL, 0, NULL, args);
b = send_tracer_message("FAIL ", NULL, 0, NULL, args, b, top);
b = send_tracer_message("RETRY_OR ", NULL, 0, NULL, args, b, top);
break;
case retry_table_generator:
send_tracer_message("FAIL ", NULL, 0, NULL, args);
b = send_tracer_message("FAIL ", NULL, 0, NULL, args, b, top);
mname = (char *)RepAtom(AtomOfTerm(Yap_Module_Name(pred)))->StrOfAE;
arity = pred->ArityOfPE;
if (arity == 0)
s = (char *)RepAtom((Atom)pred->FunctorOfPred)->StrOfAE;
else
s = (char *)RepAtom(NameOfFunctor((pred->FunctorOfPred)))->StrOfAE;
send_tracer_message("RETRY GENERATOR: ", s, arity, mname, args);
b = send_tracer_message("RETRY GENERATOR: ", s, arity, mname, args, b, top);
break;
case retry_table_consumer:
send_tracer_message("FAIL ", NULL, 0, NULL, args);
b = send_tracer_message("FAIL ", NULL, 0, NULL, args, b, top);
mname = (char *)RepAtom(AtomOfTerm(Yap_Module_Name(pred)))->StrOfAE;
arity = pred->ArityOfPE;
if (arity == 0) {
s = (char *)RepAtom((Atom)pred->FunctorOfPred)->StrOfAE;
send_tracer_message("RETRY CONSUMER: ", s, 0, mname, NULL);
b = send_tracer_message("RETRY CONSUMER: ", s, 0, mname, NULL, b, top);
} else {
s = (char *)RepAtom(NameOfFunctor((pred->FunctorOfPred)))->StrOfAE;
send_tracer_message("RETRY CONSUMER: ", s, pred->ArityOfPE, mname, NULL);
b = send_tracer_message("RETRY CONSUMER: ", s, pred->ArityOfPE, mname,
NULL, b, top);
}
break;
case retry_table_loader:
send_tracer_message("FAIL ", NULL, 0, NULL, args);
b = send_tracer_message("FAIL ", NULL, 0, NULL, args, b, top);
if (pred == UndefCode) {
send_tracer_message("RETRY LOADER ", NULL, 0, NULL, NULL);
b = send_tracer_message("RETRY LOADER ", NULL, 0, NULL, NULL, b, top);
} else {
mname = (char *)RepAtom(AtomOfTerm(Yap_Module_Name(pred)))->StrOfAE;
arity = pred->ArityOfPE;
@ -377,11 +393,11 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
s = (char *)RepAtom((Atom)pred->FunctorOfPred)->StrOfAE;
else
s = (char *)RepAtom(NameOfFunctor((pred->FunctorOfPred)))->StrOfAE;
send_tracer_message("RETRY LOADER: ", s, 0, mname, NULL);
b = send_tracer_message("RETRY LOADER: ", s, 0, mname, NULL, b, top);
}
break;
case retry_pred:
send_tracer_message("FAIL ", NULL, 0, NULL, args);
b = send_tracer_message("FAIL ", NULL, 0, NULL, args, b, top);
if (pred != NULL) {
mname = (char *)RepAtom(AtomOfTerm(Yap_Module_Name(pred)))->StrOfAE;
arity = pred->ArityOfPE;
@ -393,12 +409,18 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
} else {
s = (char *)RepAtom(NameOfFunctor((pred->FunctorOfPred)))->StrOfAE;
}
send_tracer_message("RETRY: ", s, arity, mname, args);
b = send_tracer_message("RETRY: ", s, arity, mname, args, b, top);
}
break;
}
fflush(NULL);
UNLOCK(Yap_low_level_trace_lock);
#if __ANDROID__
__android_log_print(ANDROID_LOG_DEBUG, "YAPDroid", "%s\n", buf);
#else
*b++ = '\n';
*b++ = '\0';
fputs(buf, stderr);
#endif
}
void toggle_low_level_trace(void) {

View File

@ -18,8 +18,6 @@ set(
"${CMAKE_SOURCE_DIR}"
"${CMAKE_SOURCE_DIR}/cmake")
set(LIBYAP_SOURCES ../../externalNativeBuild/swig/yapj.cpp)
include(CheckIncludeFiles)
include(CheckLibraryExists)
include(CheckSymbolExists)
@ -29,6 +27,7 @@ include(MacroOptionalAddSubdirectory)
include(MacroOptionalFindPackage)
include(MacroLogFeature)
include(FindPackageHandleStandardArgs)
include (GNUInstallDirs)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
@ -61,7 +60,26 @@ if (MYSQL_POSTGRES)
if (ANDROID)
set(ALL_SOURCES ../../externalNativeBuild/swig/yapj.cpp)
#
# SWIG_FOUND - set to true if SWIG is found
# SWIG_DIR - t he directory where swig is installed
# SWIG_EXECUTABLE - the path to the swig executable
# SWIG_VERSION - the version number of the swig executable
#
#
set (SWIG_SOURCES ${CMAKE_SOURCE_DIR}/packages/swig/yap.i)
set (SWIG_CXX ${CMAKE_BINARY_DIR}/yap_swig.cpp)
find_host_package (SWIG)
macro_log_feature (SWIG_FOUND "Swig"
"Use SWIG Language Interface "
"http://www.swig.org" ON)
add_custom_command (OUTPUT ${SWIG_CXX}
COMMAND ${SWIG_EXECUTABLE} -c++ -java -package pt.up.yap.lib -outdir ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/../../../../../src/generated/java -I${CMAKE_SOURCE_DIR}/CXX -o ${SWIG_CXX}
${SWIG_SOURCES}
)
ADD_SUBDIRECTORY(os)
ADD_SUBDIRECTORY(OPTYap)
@ -96,6 +114,7 @@ add_library( # Sets the name of the library.
SHARED
${ENGINE_SOURCES}
${SWIG_CXX}
${C_INTERFACE_SOURCES}
${STATIC_SOURCES}
${ALL_SOURCES}
@ -112,6 +131,7 @@ endif (USE_READLINE)
if (ANDROID)
add_dependencies(libYap plmyddas)
target_link_libraries(libYap android log)

View File

@ -1,5 +1,4 @@
#ifndef _YAPDB_H
#define _YAPDB_H
@ -38,6 +37,7 @@ class YAPModule : protected YAPAtomTerm {
YAPModule(Term t) : YAPAtomTerm(t){};
Term t() { return gt(); }
Term curModule() { CACHE_REGS return Yap_CurrentModule(); }
public:
~YAPModule(){};
YAPModule() : YAPAtomTerm(curModule()){};
@ -55,6 +55,7 @@ class YAPModuleProp: public YAPProp {
YAPModuleProp(ModEntry *mod) { m = mod; };
YAPModuleProp(Term tmod) { m = Yap_GetModuleEntry(tmod); };
public:
YAPModuleProp() { CACHE_REGS m = Yap_GetModuleEntry(Yap_CurrentModule()); };
YAPModuleProp(YAPModule tmod);
@ -66,12 +67,15 @@ public:
*/
class YAPFunctor : public YAPProp {
friend class YAPApplTerm;
friend class YAPTerm;
friend class YAPPredicate;
friend class YAPQuery;
Functor f;
/// Constructor: receives Prolog functor and casts it to YAPFunctor
///
/// Notice that this is designed for internal use only.
inline YAPFunctor(Functor ff) { f = ff; }
public:
/// Constructor: receives name as an atom, plus arity
///
@ -83,9 +87,9 @@ public:
/// Notice that this is designed for ISO-LATIN-1 right now
/// Note: Python confuses the 3 constructors,
/// use YAPFunctorFromString
inline YAPFunctor( const char * s, uintptr_t arity, bool isutf8=true)
{ f = Yap_MkFunctor(
Yap_LookupAtom( s ), arity ); }
inline YAPFunctor(const char *s, uintptr_t arity, bool isutf8 = true) {
f = Yap_MkFunctor(Yap_LookupAtom(s), arity);
}
/// Constructor: receives name as a wide string plus arity
///
/// Notice that this is designed for UNICODE right now
@ -93,23 +97,18 @@ public:
/// Note: Python confuses the 3 constructors,
/// use YAPFunctorFromWideString
inline YAPFunctor(const wchar_t *s, uintptr_t arity) {
f = Yap_MkFunctor(
Yap_LookupWideAtom( s ), arity ) ; }
f = Yap_MkFunctor(Yap_LookupWideAtom(s), arity);
}
~YAPFunctor(){};
/// Getter: extract name of functor as an atom
///
/// this is for external usage.
YAPAtom name(void) {
return YAPAtom( NameOfFunctor( f ) );
}
YAPAtom name(void) { return YAPAtom(NameOfFunctor(f)); }
/// Getter: extract arity of functor as an unsigned integer
///
/// this is for external usage.
uintptr_t arity(void) {
return ArityOfFunctor( f );
}
uintptr_t arity(void) { return ArityOfFunctor(f); }
};
/**
@ -119,6 +118,7 @@ public:
*/
class YAPPredicate : public YAPModuleProp {
friend class YAPQuery;
friend class YAPEngine;
protected:
PredEntry *ap;
@ -126,6 +126,8 @@ protected:
/// auxiliary routine to find a predicate in the current module.
PredEntry *getPred(Term &t, Term *&outp);
PredEntry *asPred() { return ap; };
/// String constructor for predicates
///
/// It also communicates the array of arguments t[]
@ -134,7 +136,7 @@ protected:
YAPPredicate(const char *s0, Term &out, Term &names) {
CACHE_REGS
BACKUP_MACHINE_REGS();
Term *outp;
Term *modp = NULL;;
out = Yap_StringToTerm(s0, strlen(s0) + 1, &LOCAL_encoding, 1200, &names);
// extern char *s0;
@ -142,12 +144,11 @@ protected:
// Yap_DebugPlWrite(out);
// delete [] ns;
if (out == 0L)
throw YAPError(SYNTAX_ERROR);
ap = getPred( out, outp);
throw YAPError();
ap = getPred(out, modp);
RECOVER_MACHINE_REGS();
}
/// Term constructor for predicates
///
/// It is just a call to getPred
@ -159,9 +160,7 @@ protected:
/// Cast constructor for predicates,
/// if we have the implementation data.
///
inline YAPPredicate(PredEntry *pe) {
ap = pe;
}
inline YAPPredicate(PredEntry *pe) { ap = pe; }
public:
~YAPPredicate(){};
@ -186,7 +185,6 @@ public:
ap = RepPredProp(PredPropByAtom(at.a, mod.t));
}
/// Name/0 constructor for predicates.
///
YAPPredicate(YAPAtom at);
@ -206,7 +204,6 @@ public:
///
YAPPredicate(YAPAtom at, uintptr_t arity);
/// module of a predicate
///
/// notice that modules are currently treated as atoms, this should change.
@ -220,7 +217,8 @@ public:
/// name of predicate
///
/// notice that we return the atom, not a string.
YAPAtom name() { if (ap->ArityOfPE)
YAPAtom name() {
if (ap->ArityOfPE)
return YAPAtom((Atom)ap->FunctorOfPred);
else
return YAPAtom(NameOfFunctor(ap->FunctorOfPred));
@ -239,24 +237,16 @@ public:
*/
class YAPPrologPredicate : public YAPPredicate {
public:
YAPPrologPredicate(YAPAtom name,
uintptr_t arity,
YAPModule module = YAPModule(),
bool tabled = false,
bool logical_updates = false,
bool local = false,
bool sourced = true,
bool discontiguous = false,
bool multiFile = false,
bool hidden = false,
bool untraceable = false,
bool unspyable = false,
bool meta = false,
bool sync = false,
bool quasi_quotable = false,
size_t mega_clause = 0
);
void *assertClause( YAPTerm clause, bool last=true, YAPTerm source= YAPTerm(TermNil));
YAPPrologPredicate(YAPAtom name, uintptr_t arity,
YAPModule module = YAPModule(), bool tabled = false,
bool logical_updates = false, bool local = false,
bool sourced = true, bool discontiguous = false,
bool multiFile = false, bool hidden = false,
bool untraceable = false, bool unspyable = false,
bool meta = false, bool sync = false,
bool quasi_quotable = false, size_t mega_clause = 0);
void *assertClause(YAPTerm clause, bool last = true,
YAPTerm source = YAPTerm(TermNil));
void *retractClause(YAPTerm skeleton, bool all = false);
void *clause(YAPTerm skeleton, YAPTerm &body);
};
@ -268,50 +258,33 @@ public:
*/
class YAPFLIP : public YAPPredicate {
public:
YAPFLIP(CPredicate call,
YAPAtom name,
uintptr_t arity,
YAPModule module = YAPModule(),
CPredicate retry = 0,
CPredicate cut = 0,
size_t extra = 0,
bool test = false
) : YAPPredicate( name, arity, module) {
YAPFLIP(CPredicate call, YAPAtom name, uintptr_t arity,
YAPModule module = YAPModule(), CPredicate retry = 0,
CPredicate cut = 0, size_t extra = 0, bool test = false)
: YAPPredicate(name, arity, module) {
if (retry) {
Yap_InitCPredBackCut(name.getName(), arity, extra, call, retry, cut, UserCPredFlag);
Yap_InitCPredBackCut(name.getName(), arity, extra, call, retry, cut,
UserCPredFlag);
} else {
if (test) {
YAP_UserCPredicate (name.getName(),
call, arity);
YAP_UserCPredicate(name.getName(), call, arity);
} else {
YAP_UserCPredicate (name.getName(),
call, arity);
YAP_UserCPredicate(name.getName(), call, arity);
}
}
};
YAPFLIP(const char *name,
uintptr_t arity,
YAPModule module = YAPModule(),
bool backtrackable = false
) : YAPPredicate( YAPAtom(name), arity, module) {
YAPFLIP(const char *name, uintptr_t arity, YAPModule module = YAPModule(),
bool backtrackable = false)
: YAPPredicate(YAPAtom(name), arity, module) {
if (backtrackable) {
Yap_InitCPredBackCut(name, arity, 0, 0, 0, 0, UserCPredFlag);
} else {
YAP_UserCPredicate (name,
0, arity);
YAP_UserCPredicate(name, 0, arity);
}
};
bool addCall(CPredicate call) {
return Yap_AddCallToFli( ap, call );
}
bool addRetry(CPredicate call) {
return Yap_AddRetryToFli( ap, call );
}
bool addCut(CPredicate call) {
return Yap_AddCutToFli( ap, call );
}
bool addCall(CPredicate call) { return Yap_AddCallToFli(ap, call); }
bool addRetry(CPredicate call) { return Yap_AddRetryToFli(ap, call); }
bool addCut(CPredicate call) { return Yap_AddCutToFli(ap, call); }
};
#endif

View File

@ -1,6 +1,7 @@
#define YAP_CPP_INTERFACE 1
#include <string>
#include "yapi.hh"
extern "C" {
@ -161,6 +162,17 @@ YAPApplTerm::YAPApplTerm(YAPFunctor f, YAPTerm ts[]) : YAPTerm() {
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(const char *f, std::vector<YAPTerm> ts) : YAPTerm() {
BACKUP_H();
arity_t arity = ts.size();
std::vector<Term> tt(arity);
for (arity_t i = 0; i < arity; i++)
tt[i] = ts[i].term();
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f), arity);
t = Yap_MkApplTerm(ff, arity, &tt[0]);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(YAPFunctor f) : YAPTerm() {
BACKUP_H();
arity_t arity = ArityOfFunctor(f.f);
@ -170,8 +182,6 @@ YAPApplTerm::YAPApplTerm(YAPFunctor f) : YAPTerm() {
YAPFunctor YAPApplTerm::getFunctor() { return YAPFunctor(FunctorOfTerm(gt())); }
static YAPTerm tmp;
YAPTerm &YAPTerm::operator[](arity_t i) {
BACKUP_MACHINE_REGS();
Term t0 = gt();
@ -359,7 +369,7 @@ const char *YAPTerm::text() {
if (!(os = Yap_TermToString(Yap_GetFromSlot(t), &length, enc,
Handle_vars_f))) {
RECOVER_MACHINE_REGS();
return nullptr;
return 0;
}
RECOVER_MACHINE_REGS();
return os;
@ -392,8 +402,36 @@ YAPTerm YAPListTerm::car() {
Term to = gt();
if (IsPairTerm(to))
return YAPTerm(HeadOfTerm(to));
else
throw YAPError(TYPE_ERROR_LIST);
else {
Yap_Error(TYPE_ERROR_LIST, to, "");
throw YAPError();
}
}
YAPTerm::YAPTerm(YAPFunctor f, YAPTerm ts[]) {
CACHE_REGS
BACKUP_H();
Functor fun = f.f;
arity_t arity = ArityOfFunctor(fun);
while (HR + arity > ASP - 1024) {
RECOVER_H();
if (!Yap_dogc(0, NULL PASS_REGS)) {
t = TermNil;
}
BACKUP_H();
}
if (fun == FunctorDot) {
t = AbsPair(HR);
HR[0] = ts[0].term();
HR[1] = ts[1].term();
} else {
t = AbsAppl(HR);
*HR++ = (CELL)fun;
for (arity_t i = 0; i < arity; i++) {
HR[i] = ts[i].term();
}
RECOVER_H();
}
}
YAPListTerm::YAPListTerm(YAPTerm ts[], arity_t n) {
@ -445,8 +483,21 @@ const char *YAPAtom::getName(void) {
}
}
void YAPQuery::initOpenQ() {
void YAPQuery::openQuery() {
CACHE_REGS
arity_t arity = ap->ArityOfPE;
if (arity) {
Term *ts;
Term t = goal.term();
if (IsPairTerm(t)) {
ts = RepPair(t);
} else {
ts = RepAppl(t) + 1;
}
for (arity_t i = 0; i < arity; i++) {
XREGS[i + 1] = ts[i];
}
}
// oq = LOCAL_execution;
// LOCAL_execution = this;
q_open = true;
@ -459,69 +510,73 @@ void YAPQuery::initOpenQ() {
q_handles = Yap_StartSlots();
}
int YAPError::get() { return errNo; }
const char *YAPError::text() { return "YAP Error"; }
void YAPQuery::initQuery(Term t) {
bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
CACHE_REGS
BACKUP_MACHINE_REGS();
arity_t arity = ap->ArityOfPE;
goal = YAPTerm(t);
if (arity) {
q_g = Yap_InitSlots(arity, RepAppl(t) + 1);
arity_t arity = ap.getArity();
bool result;
YAP_dogoalinfo q;
Term terr;
jmp_buf q_env;
std::vector<Term> vt(arity);
for (arity_t i = 0; i < arity; i++)
vt[i] = ts[i].term();
q.CurSlot = Yap_StartSlots();
q.p = P;
q.cp = CP;
// make sure this is safe
if (setjmp(q_env)) {
if ((terr = Yap_PeekException())) {
YAP_LeaveGoal(false, &q);
Yap_CloseHandles(q.CurSlot);
throw YAPError();
}
return false;
}
// don't forget, on success these guys may create slots
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
result = (bool)YAP_EnterGoal(ap.asPred(), &vt[0], &q);
if ((terr = Yap_GetException())) {
YAP_LeaveGoal(false, &q);
throw YAPError();
}
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %d", result);
if (!result) {
YAP_LeaveGoal(false, &q);
} else {
q_g = 0;
YAP_LeaveGoal(FALSE, &q);
}
q_pe = ap;
initOpenQ();
RECOVER_MACHINE_REGS();
}
void YAPQuery::initQuery(YAPAtom at) {
CACHE_REGS
BACKUP_MACHINE_REGS();
PredEntry *ap = RepPredProp(PredPropByAtom(at.a, Yap_CurrentModule()));
goal = YAPAtomTerm(at);
q_g = 0;
q_pe = ap;
initOpenQ();
RECOVER_MACHINE_REGS();
}
void YAPQuery::initQuery(YAPTerm ts[], arity_t arity) {
CACHE_REGS
BACKUP_MACHINE_REGS();
if (arity) {
q_g = Yap_NewSlots(arity);
for (arity_t i = 0; i < arity; i++) {
Yap_PutInSlot(q_g + i, ts[i].term());
}
Term t = Yap_MkApplTerm(ap->FunctorOfPred, ap->ArityOfPE,
Yap_AddressFromSlot(q_g));
goal = YAPTerm(t);
} else {
q_g = 0;
goal = YAPTerm(MkAtomTerm((Atom)ap->FunctorOfPred));
}
initOpenQ();
RECOVER_MACHINE_REGS();
return result;
}
YAPQuery::YAPQuery(YAPFunctor f, YAPTerm mod, YAPTerm ts[])
: YAPPredicate(f, mod) {
/* ignore flags for now */
initQuery(ts, f.arity());
BACKUP_MACHINE_REGS();
goal = YAPTerm(f, ts);
vnames = YAPListTerm();
openQuery();
RECOVER_MACHINE_REGS();
}
YAPQuery::YAPQuery(YAPFunctor f, YAPTerm ts[]) : YAPPredicate(f) {
/* ignore flags for now */
initQuery(ts, f.arity());
BACKUP_MACHINE_REGS();
goal = YAPTerm(f, ts);
vnames = YAPListTerm();
openQuery();
RECOVER_MACHINE_REGS();
}
YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) {
initQuery(ts, p.ap->ArityOfPE);
BACKUP_MACHINE_REGS();
goal = YAPTerm(YAPFunctor(ap->FunctorOfPred), ts);
vnames = YAPListTerm();
openQuery();
RECOVER_MACHINE_REGS();
}
YAPListTerm YAPQuery::namedVars() {
@ -541,38 +596,45 @@ YAPListTerm YAPQuery::namedVarsCopy() {
bool YAPQuery::next() {
CACHE_REGS
bool result;
Term terr;
BACKUP_MACHINE_REGS();
if (!q_open)
return false;
if (setjmp(q_env)) {
if ((terr = Yap_GetException())) {
YAP_LeaveGoal(false, &q_h);
Yap_CloseHandles(q_handles);
throw YAPError();
}
return false;
}
// don't forget, on success these guys may create slots
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
if (q_state == 0) {
result = (bool)YAP_EnterGoal((YAP_PredEntryPtr)ap, q_g, &q_h);
result = (bool)YAP_EnterGoal(ap, nullptr, &q_h);
} else {
LOCAL_AllowRestart = q_open;
result = (bool)YAP_RetryGoal(&q_h);
}
{
if (result)
if (result) {
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "vnames %d %s %d",
q_state, vnames.text(), LOCAL_CurSlot);
else
} else {
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "fail");
}
q_state = 1;
if (Yap_GetException()) {
return false;
if ((terr = Yap_GetException())) {
YAP_LeaveGoal(false, &q_h);
Yap_CloseHandles(q_handles);
throw YAPError();
}
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %d", result);
if (!result) {
YAP_LeaveGoal(FALSE, &q_h);
YAP_LeaveGoal(false, &q_h);
Yap_CloseHandles(q_handles);
q_open = false;
} else {
q_handles = Yap_StartSlots();
@ -612,12 +674,13 @@ void YAPQuery::close() {
RECOVER_MACHINE_REGS();
Yap_ResetException(worker_id);
/* need to implement backtracking here */
if (q_open != 1 || q_state == 0) {
if (q_open != true || q_state == 0) {
RECOVER_MACHINE_REGS();
return;
}
YAP_LeaveGoal(FALSE, &q_h);
q_open = 0;
Yap_CloseHandles(q_handles);
// LOCAL_execution = this;
RECOVER_MACHINE_REGS();
}
@ -674,7 +737,7 @@ void Yap_displayWithJava(int c) {
void YAPEngine::doInit(YAP_file_type_t BootMode) {
if ((BootMode = YAP_Init(&init_args)) == YAP_FOUND_BOOT_ERROR) {
throw(YAPError(SYSTEM_ERROR_INTERNAL));
throw YAPError();
}
/* Begin preprocessor code */
/* live */
@ -767,7 +830,11 @@ PredEntry *YAPPredicate::getPred(Term &t, Term *&outp) {
Term m = Yap_CurrentModule();
t = Yap_StripModule(t, &m);
if (IsVarTerm(t) || IsNumTerm(t)) {
throw YAPError(TYPE_ERROR_NUMBER);
if (IsVarTerm(t))
Yap_Error(INSTANTIATION_ERROR, t, 0);
else if (IsNumTerm(t))
Yap_Error(TYPE_ERROR_CALLABLE, t, 0);
throw YAPError();
}
if (IsAtomTerm(t)) {
ap = RepPredProp(PredPropByAtom(AtomOfTerm(t), m));
@ -782,7 +849,9 @@ PredEntry *YAPPredicate::getPred(Term &t, Term *&outp) {
}
Functor f = FunctorOfTerm(t);
if (IsExtensionFunctor(f)) {
throw YAPError(TYPE_ERROR_NUMBER);
Yap_Error(TYPE_ERROR_CALLABLE, t, 0);
;
throw YAPError();
} else {
ap = RepPredProp(PredPropByFunc(f, m));
outp = RepAppl(t) + 1;
@ -877,3 +946,48 @@ void *YAPPrologPredicate::retractClause(YAPTerm skeleton, bool all) {
return 0;
}
void *YAPPrologPredicate::clause(YAPTerm skeleton, YAPTerm &body) { return 0; }
const char *YAPError::text() {
char buf[256];
std::string s = "";
if (LOCAL_ActiveError.errorFunction) {
s += LOCAL_ActiveError.errorFile;
s += ":";
sprintf(buf, "%ld", (long int)LOCAL_ActiveError.errorLine);
s += buf;
s += ":0 in C-code";
}
if (LOCAL_ActiveError.prologPredLine) {
s += "\n" ;
s+= LOCAL_ActiveError.prologPredFile->StrOfAE ;
s+= ":" ;
sprintf(buf, "%ld", (long int)LOCAL_ActiveError.prologPredLine);
s+= buf; // std::to_string(LOCAL_ActiveError.prologPredLine) ;
// YAPIntegerTerm(LOCAL_ActiveError.prologPredLine).text();
s+= ":0 " ;
s+= LOCAL_ActiveError.prologPredModule ;
s+= ":" ;
s+= (LOCAL_ActiveError.prologPredName)->StrOfAE ;
s+= "/" ;
sprintf(buf, "%ld", (long int)LOCAL_ActiveError.prologPredArity);
s+= // std::to_string(LOCAL_ActiveError.prologPredArity);
buf;
}
s += " error ";
if (LOCAL_ActiveError.classAsText != nullptr)
s += LOCAL_ActiveError.classAsText->StrOfAE;
s += ".";
s += LOCAL_ActiveError.errorAsText->StrOfAE;
s += ".\n";
if (LOCAL_ActiveError.errorTerm) {
Term t = Yap_PopTermFromDB(LOCAL_ActiveError.errorTerm);
if (t) {
s += "error term is: ";
s += YAPTerm(t).text();
s += "\n";
}
}
printf("%s\n", s.c_str());
return s.c_str();
}

View File

@ -3,7 +3,7 @@
#define YAP_CPP_INTERFACE 1
#include <gmpxx.h>
#include <vector>
//! @{
/**
@ -73,8 +73,7 @@ X_API bool init_python(void);
extern PyObject *py_Main;
extern inline PyObject *AtomToPy( const char *s)
{
extern inline PyObject *AtomToPy(const char *s) {
if (strcmp(s, "true") == 0)
return Py_True;
if (strcmp(s, "false") == 0)
@ -97,17 +96,18 @@ extern inline PyObject *AtomToPy( const char *s)
X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, YAP_Arity arity);
/* void UserCPredicateWithArgs(const char *name, int *fn(), unsigned int arity) */
X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, YAP_Arity, YAP_Term);
/* void UserCPredicateWithArgs(const char *name, int *fn(), unsigned int arity)
*/
X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, YAP_Arity,
YAP_Term);
/* void UserBackCPredicate(const char *name, int *init(), int *cont(), int
arity, int extra) */
X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred, YAP_Arity, YAP_Arity);
X_API Term Yap_StringToTerm(const char *s, size_t len, encoding_t *encp, int prio, Term *bindings_p);
X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred,
YAP_Arity, YAP_Arity);
X_API Term Yap_StringToTerm(const char *s, size_t len, encoding_t *encp,
int prio, Term *bindings_p);
}
class YAPEngine;

View File

@ -1,11 +1,33 @@
#ifndef YAPIE_HH
#define YAPIE_HH
class YAPPPredicate;
class YAPTerm;
/// take information on a Prolog error:
class YAPError {
int errNo;
std::string name, errorClass, info;
int swigcode;
public:
YAPError() { errNo = YAP_NO_ERROR; };
YAPError(int err) { errNo = err; };
int get();
/// error handling when receiving the error term
YAPError(){};
/// we just know the error number
/// exact error ID
yap_error_number getID() { return LOCAL_ActiveError.errorNo; };
/// class of error
yap_error_class_number getErrorClass() {
return Yap_errorClass(LOCAL_ActiveError.errorNo);
};
/// where in the code things happened;
const char *getFile() { return LOCAL_ActiveError.errorFile; };
/// predicate things happened;
Int getLine() { return LOCAL_ActiveError.errorLine; };
/// the term that caused the bug
// YAPTerm getCulprit(LOCAL_ActiveError.errorFile){};
/// text describing the Error
const char *text();
};
#endif

View File

@ -17,7 +17,6 @@ class YAPQuery : public YAPPredicate {
bool q_open;
int q_state;
yhandle_t q_g, q_handles;
struct pred_entry *q_pe;
struct yami *q_p, *q_cp;
jmp_buf q_env;
int q_flags;
@ -25,13 +24,10 @@ class YAPQuery : public YAPPredicate {
YAPQuery *oq;
YAPListTerm vnames;
YAPTerm goal;
Term names;
Term t;
// temporaries
Term tgoal, names;
void initOpenQ();
void initQuery(Term t);
void initQuery(YAPAtom at);
void initQuery(YAPTerm ts[], arity_t arity);
void openQuery();
public:
/// main constructor, uses a predicate and an array of terms
@ -56,21 +52,24 @@ public:
/// It is given a string, calls the parser and obtains a Prolog term that
/// should be a callable
/// goal.
inline YAPQuery(const char *s) : YAPPredicate(s, t, names) {
inline YAPQuery(const char *s): YAPPredicate(s, tgoal, names) {
BACKUP_H();
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "got game %d",
LOCAL_CurSlot);
goal = YAPTerm(tgoal);
vnames = YAPListTerm(names);
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "%s", vnames.text());
initQuery(t);
openQuery();
RECOVER_H();
};
/// string constructor with just an atom
///
/// It is given an atom, and a Prolog term that should be a callable
/// goal, say `main`, `init`, `live`.
inline YAPQuery(YAPAtom goal) : YAPPredicate(goal) {
vnames = YAPListTerm(TermNil);
initQuery(goal);
inline YAPQuery(YAPAtom g) : YAPPredicate( g ) {
goal = YAPAtomTerm( g );
vnames = YAPListTerm(names);
openQuery();
};
/// set flags for query execution, currently only for exception handling
@ -164,8 +163,13 @@ public:
if (_callback)
_callback->run(s);
}
/// stop yap
void close() {
Yap_exit(0);
}
/// execute the callback with a text argument.
YAPError hasError() { return yerror.get(); }
bool hasError() { return LOCAL_Error_TYPE != YAP_NO_ERROR; }
/// build a query on the engine
YAPQuery *query(const char *s) { return new YAPQuery(s); };
/// current module for the engine
@ -173,6 +177,8 @@ public:
/// given a handle, fetch a term from the engine
inline YAPTerm getTerm(yhandle_t h) { return YAPTerm(h); }
/// current directory for the engine
bool call(YAPPredicate ap, YAPTerm ts[]);
const char *currentDir() {
char dir[1024];
std::string s = Yap_getcwd(dir, 1024 - 1);

View File

@ -4,6 +4,7 @@
extern "C" Term YAP_ReadBuffer(const char *s, Term *tp);
class YAPError;
/**
* @brief Generic Prolog Term
*/
@ -27,7 +28,7 @@ public:
} /// private method to convert from Term (internal YAP representation) to
/// YAPTerm
// do nothing constructor
YAPTerm() { t = 0; }
YAPTerm() { mk(MkVarTerm()); }
YAPTerm(yhandle_t i) { t = i; };
/// pointer to term
YAPTerm(void *ptr);
@ -36,6 +37,8 @@ public:
Term tp;
mk(YAP_ReadBuffer(s, &tp));
}
/// parse string s and construct a term.
YAPTerm(YAPFunctor f, YAPTerm ts[]);
/// extract the tag of a term, after dereferencing.
YAP_tag_t tag();
/// copy the term ( term copy )
@ -76,7 +79,7 @@ public:
virtual bool isList() { return Yap_IsListTerm(gt()); } /// term is a list
/// extract the argument i of the term, where i in 1...arity
inline YAPTerm getArg(arity_t i) {
virtual YAPTerm getArg(arity_t i) {
BACKUP_MACHINE_REGS();
Term t0 = gt();
YAPTerm tf;
@ -155,9 +158,10 @@ class YAPApplTerm : public YAPTerm {
public:
~YAPApplTerm() {}
YAPApplTerm(YAPFunctor f, YAPTerm ts[]);
YAPApplTerm(const char *s, std::vector<YAPTerm> ts);
YAPApplTerm(YAPFunctor f);
YAPFunctor getFunctor();
inline YAPTerm getArg(arity_t i) {
YAPTerm getArg(arity_t i) {
BACKUP_MACHINE_REGS();
Term t0 = gt();
YAPTerm tf;
@ -254,7 +258,8 @@ public:
else if (to == TermNil)
return YAPListTerm();
/* error */
throw YAPError(TYPE_ERROR_LIST);
Yap_Error(TYPE_ERROR_LIST, t, 0);
throw YAPError();
}
/// copy a list.
///
@ -303,7 +308,7 @@ public:
// Constructor: receives an atom;
YAPAtomTerm(YAPAtom a) : YAPTerm() { mk(MkAtomTerm(a.a)); }
// Constructor: receives a sequence of ISO-LATIN1 codes;
YAPAtomTerm(char *s);
YAPAtomTerm(char s[]);
// Constructor: receives a sequence of up to n ISO-LATIN1 codes;
YAPAtomTerm(char *s, size_t len);
// Constructor: receives a sequence of wchar_ts, whatever they may be;

View File

@ -86,8 +86,6 @@ char* ScannerStack =NULL
struct scanner_extra_alloc* ScannerExtraBlocks =NULL
/// worker control information
/// pointer to an exception term, from throw
struct DB_TERM* BallTerm =NULL RestoreBallTerm(wid)
/// stack limit after which the stack is managed by C-code.
Int CBorder =0
@ -198,12 +196,12 @@ ADDR TrailBase void
ADDR TrailTop void
char* ErrorMessage void
Term Error_Term void
yap_error_number Error_TYPE void
const char* Error_File void
const char* Error_Function void
int Error_Lineno void
size_t Error_Size void
char ErrorSay[MAX_ERROR_MSG_SIZE] void
/** error handling info, designed to be easy to pass to the foreign world */
struct yap_error_descriptor ActiveError void
/// pointer to an exception term, from throw
struct DB_TERM* BallTerm =NULL
jmp_buf IOBotch void
TokEntry* tokptr void
TokEntry* toktide void
@ -307,7 +305,7 @@ UInt exo_arg =0
struct scan_atoms* search_atoms void
struct pred_entry* SearchPreds void
// Slots
/// Slots Status
yhandle_t CurSlot =0
yhandle_t FrozenHandles =0
yhandle_t NSlots =0

11
H/Yap.h
View File

@ -236,7 +236,8 @@ INLINE_ONLY inline EXTERN size_t strnlen(const char *s, size_t maxlen) {
#if !defined(IN_SECOND_QUADRANT)
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
defined(mips) || defined(__mips64) || defined(__aarch64__) || (__DragonFly__)
defined(mips) || defined(__mips64) || defined(__aarch64__) || \
(__DragonFly__)
#if defined(YAPOR) && defined(__alpha)
#define MMAP_ADDR 0x40000000
@ -253,17 +254,15 @@ INLINE_ONLY inline EXTERN size_t strnlen(const char *s, size_t maxlen) {
#endif /* YAPOR && __alpha */
#elif __svr4__ || defined(__SVR4)
#define MMAP_ADDR 0x02000000
#endif /* __linux__ || __FreeBSD__ || __NetBSD__ || mips || __mips64 || __APPLE__ || \
#endif /* __linux__ || __FreeBSD__ || __NetBSD__ || mips || __mips64 || \
__APPLE__ || \
__DragonFly__ */
#endif /* !IN_SECOND_QUADRANT */
/* #define RANDOMIZE_START_ADDRESS 1 */
extern size_t Yap_page_size;
#ifdef USE_SYSTEM_MALLOC
#define HEAP_INIT_BASE 0L
#define AtomBase NULL
@ -463,8 +462,6 @@ extern ADDR Yap_HeapBase;
/* This is ok for Linux, should be ok for everyone */
#define YAP_FILENAME_MAX 1024
#define MAX_ERROR_MSG_SIZE YAP_FILENAME_MAX
/*************************************************************************************************
Debugging Support
*************************************************************************************************/

View File

@ -154,15 +154,13 @@ static Term synerr(Term inp) {
static inline Term filler(Term inp) { return inp; }
static inline Term list_filler(Term inp) {
if (IsVarTerm(inp) ||
IsPairTerm(inp) ||
inp == TermNil)
if (IsVarTerm(inp) || IsPairTerm(inp) || inp == TermNil)
return inp;
Yap_Error(TYPE_ERROR_LIST, inp,
"set_prolog_flag in {codes,string}");
Yap_Error(TYPE_ERROR_LIST, inp, "set_prolog_flag in {codes,string}");
return TermZERO; }
return TermZERO;
}
static Term bqs(Term inp) {
if (inp == TermCodes || inp == TermString || inp == TermSymbolChar)
@ -191,7 +189,9 @@ static inline Term isatom(Term inp) {
return TermZERO;
}
static inline Term options(Term inp) { return Yap_IsGroundTerm(inp) ? inp : TermZERO; }
static inline Term options(Term inp) {
return Yap_IsGroundTerm(inp) ? inp : TermZERO;
}
// INLINE_ONLY inline EXTERN Term ok( Term inp );
@ -347,8 +347,7 @@ static inline Term getBackQuotesFlag(void) {
return GLOBAL_Flags[BACKQUOTED_STRING_FLAG].at;
}
static inline Term
indexingMode(void) { return GLOBAL_Flags[INDEX_FLAG].at; }
static inline Term indexingMode(void) { return GLOBAL_Flags[INDEX_FLAG].at; }
static inline const char *floatFormat(void) {
return RepAtom(AtomOfTerm(GLOBAL_Flags[FLOAT_FORMAT_FLAG].at))->rep.uStrOfAE;
@ -358,9 +357,7 @@ static inline size_t indexingDepth(void) {
return IntOfTerm(GLOBAL_Flags[INDEX_SUB_TERM_SEARCH_DEPTH_FLAG].at);
}
static inline Term gcTrace(void) {
return GLOBAL_Flags[GC_TRACE_FLAG].at;
}
static inline Term gcTrace(void) { return GLOBAL_Flags[GC_TRACE_FLAG].at; }
Term Yap_UnknownFlag(Term mod);

View File

@ -181,7 +181,6 @@ inline static utf8proc_ssize_t strlen_utf8(const utf8proc_uint8_t *pt) {
} else {
pt++;
}
}
return rc;
}
@ -391,8 +390,7 @@ static inline seq_type_t mod_to_bqtype(Term mod USES_REGS) {
// the routines
extern unsigned char *Yap_readText(seq_tv_t *inp, size_t *lengp
USES_REGS);
extern unsigned char *Yap_readText(seq_tv_t *inp, size_t *lengp USES_REGS);
extern bool write_Text(unsigned char *inp, seq_tv_t *out,
size_t leng USES_REGS);
extern bool Yap_CVT_Text(seq_tv_t *inp, seq_tv_t *out USES_REGS);
@ -738,7 +736,6 @@ static inline Atom Yap_UTF8ToAtom(const unsigned char *s USES_REGS) {
return out.val.a;
}
static inline Term Yap_CharsToDiffListOfCodes(const char *s, Term tail,
encoding_t enc USES_REGS) {
seq_tv_t inp, out;
@ -1083,7 +1080,6 @@ static inline Term Yap_NCharsToTBQ(const char *s, size_t len, encoding_t enc,
inp.type = YAP_STRING_CHARS | YAP_STRING_NCHARS;
inp.enc = enc;
out.type = mod_to_bqtype(mod PASS_REGS);
out.max = len;
if (!Yap_CVT_Text(&inp, &out PASS_REGS))
@ -1215,8 +1211,8 @@ static inline size_t Yap_StringToAtomic(Term t0 USES_REGS) {
seq_tv_t inp, out;
inp.val.t = t0;
inp.type = YAP_STRING_STRING;
out.type = YAP_STRING_ATOM | YAP_STRING_INT | YAP_STRING_FLOAT |
YAP_STRING_BIG ;
out.type =
YAP_STRING_ATOM | YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG;
out.val.uc = NULL;
if (!Yap_CVT_Text(&inp, &out PASS_REGS))
return 0L;
@ -1322,6 +1318,17 @@ static inline Term Yap_TextToString(Term t0 USES_REGS) {
return out.val.t;
}
static inline void Yap_OverwriteUTF8BufferToLowCase(void *buf USES_REGS) {
unsigned char *s = (unsigned char *)buf;
while (*s) {
// assumes the two code have always the same size;
utf8proc_int32_t chr;
get_utf8(s, -1, &chr);
chr = utf8proc_tolower(chr);
s += put_utf8(s, chr);
}
}
static inline const unsigned char *Yap_TextToUTF8Buffer(Term t0 USES_REGS) {
seq_tv_t inp, out;
@ -1456,8 +1463,7 @@ static inline Atom Yap_SubtractHeadAtom(Term t1, Term th USES_REGS) {
outv[0].val.t = th;
outv[1].type = YAP_STRING_ATOM;
outv[1].val.t = 0;
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp,
outv PASS_REGS))
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp, outv PASS_REGS))
return (Atom)NULL;
return outv[1].val.a;
}
@ -1470,8 +1476,7 @@ static inline Atom Yap_SubtractTailAtom(Term t1, Term th USES_REGS) {
outv[0].val.t = 0;
outv[1].type = YAP_STRING_ATOM;
outv[1].val.t = th;
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp,
outv PASS_REGS))
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp, outv PASS_REGS))
return (Atom)NULL;
return outv[0].val.a;
}
@ -1501,8 +1506,7 @@ static inline Term Yap_SubtractHeadString(Term t1, Term th USES_REGS) {
outv[0].val.t = th;
outv[1].type = YAP_STRING_STRING;
outv[1].val.t = 0;
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp,
outv PASS_REGS))
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp, outv PASS_REGS))
return 0L;
return outv[1].val.t;
}
@ -1515,8 +1519,7 @@ static inline Term Yap_SubtractTailString(Term t1, Term th USES_REGS) {
outv[0].val.t = 0;
outv[1].type = YAP_STRING_STRING;
outv[1].val.t = th;
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp,
outv PASS_REGS))
if (!Yap_Splice_Text(2, (size_t *)NULL, &inp, outv PASS_REGS))
return 0L;
return outv[0].val.t;
}

View File

@ -620,6 +620,7 @@ typedef struct pred_entry {
#ifdef BEAM
struct Predicates *beamTable;
#endif
struct yami *MetaEntryOfPred; /* allow direct access from meta-calls */
Term ModuleOfPred; /* module for this definition */
UInt TimeStampOfPred;
timestamp_type LastCallOfPred;

View File

@ -278,6 +278,7 @@ typedef struct dbterm_list {
wamreg Yap_emit_x(CELL);
COUNT Yap_compile_cmp_flags(PredEntry *);
void Yap_InitComma(void);
yamop *Yap_InitCommaContinuation(PredEntry *);
/* cdmgr.c */
void Yap_IPred(PredEntry *, UInt, yamop *);

View File

@ -48,7 +48,7 @@
#define HeapLim Yap_heap_regs->HeapLim_
#define FreeBlocks Yap_heap_regs->FreeBlocks_
#if defined(YAPOR) || defined(THREADS)
#define fFreeBlocksLock Yap_heap_regs->FreeBlocksLock_
#define FreeBlocksLock Yap_heap_regs->FreeBlocksLock_
#define HeapUsedLock Yap_heap_regs->HeapUsedLock_
#define HeapTopLock Yap_heap_regs->HeapTopLock_
#define HeapTopOwner Yap_heap_regs->HeapTopOwner_

View File

@ -133,9 +133,6 @@
#define REMOTE_ScannerExtraBlocks(wid) REMOTE(wid)->ScannerExtraBlocks_
#define LOCAL_BallTerm LOCAL->BallTerm_
#define REMOTE_BallTerm(wid) REMOTE(wid)->BallTerm_
#define LOCAL_CBorder LOCAL->CBorder_
#define REMOTE_CBorder(wid) REMOTE(wid)->CBorder_
@ -295,18 +292,12 @@
#define REMOTE_ErrorMessage(wid) REMOTE(wid)->ErrorMessage_
#define LOCAL_Error_Term LOCAL->Error_Term_
#define REMOTE_Error_Term(wid) REMOTE(wid)->Error_Term_
#define LOCAL_Error_TYPE LOCAL->Error_TYPE_
#define REMOTE_Error_TYPE(wid) REMOTE(wid)->Error_TYPE_
#define LOCAL_Error_File LOCAL->Error_File_
#define REMOTE_Error_File(wid) REMOTE(wid)->Error_File_
#define LOCAL_Error_Function LOCAL->Error_Function_
#define REMOTE_Error_Function(wid) REMOTE(wid)->Error_Function_
#define LOCAL_Error_Lineno LOCAL->Error_Lineno_
#define REMOTE_Error_Lineno(wid) REMOTE(wid)->Error_Lineno_
#define LOCAL_Error_Size LOCAL->Error_Size_
#define REMOTE_Error_Size(wid) REMOTE(wid)->Error_Size_
#define LOCAL_ErrorSay LOCAL->ErrorSay_
#define REMOTE_ErrorSay(wid) REMOTE(wid)->ErrorSay_
#define LOCAL_ActiveError LOCAL->ActiveError_
#define REMOTE_ActiveError(wid) REMOTE(wid)->ActiveError_
#define LOCAL_BallTerm LOCAL->BallTerm_
#define REMOTE_BallTerm(wid) REMOTE(wid)->BallTerm_
#define LOCAL_IOBotch LOCAL->IOBotch_
#define REMOTE_IOBotch(wid) REMOTE(wid)->IOBotch_
#define LOCAL_tokptr LOCAL->tokptr_

View File

@ -1,5 +1,6 @@
/* This file, hlocals.h, was generated automatically by "yap -L misc/buildlocalglobal"
/* This file, hlocals.h, was generated automatically by "yap -L
misc/buildlocalglobal"
please do not update, update H/LOCALS instead */
// Stuff that must be considered local to a thread or worker
@ -75,8 +76,6 @@ typedef struct worker_local {
char *ScannerStack_;
struct scanner_extra_alloc *ScannerExtraBlocks_;
/// worker control information
/// pointer to an exception term, from throw
struct DB_TERM* BallTerm_;
/// stack limit after which the stack is managed by C-code.
Int CBorder_;
/// max number of signals (uint64_t)
@ -147,7 +146,8 @@ typedef struct worker_local {
Int *LabelFirstArray_;
UInt LabelFirstArraySz_;
// Thread Local Area for SWI-Prolog emulation routines.
// struct PL_local_data* PL_local_data_p =Yap_InitThreadIO(wid)
// struct PL_local_data* PL_local_data_p
// =Yap_InitThreadIO(wid)
#ifdef THREADS
struct thandle ThreadHandle_;
#endif /* THREADS */
@ -168,12 +168,10 @@ typedef struct worker_local {
ADDR TrailTop_;
char *ErrorMessage_;
Term Error_Term_;
yap_error_number Error_TYPE_;
const char* Error_File_;
const char* Error_Function_;
int Error_Lineno_;
size_t Error_Size_;
char ErrorSay_[MAX_ERROR_MSG_SIZE];
/** error handling info, designed to be easy to pass to the foreign world */
struct yap_error_descriptor ActiveError_;
/// pointer to an exception term, from throw
struct DB_TERM *BallTerm_;
jmp_buf IOBotch_;
TokEntry *tokptr_;
TokEntry *toktide_;
@ -186,8 +184,8 @@ const char* Error_Function_;
size_t CommentsBuffPos_;
size_t CommentsBuffLim_;
sigjmp_buf RestartEnv_;
char FileNameBuf_[YAP_FILENAME_MAX];
char FileNameBuf2_[YAP_FILENAME_MAX];
char FileNameBuf_[YAP_FILENAME_MAX + 1];
char FileNameBuf2_[YAP_FILENAME_MAX + 1];
// Prolog State
UInt BreakLevel_;
Int PrologMode_;
@ -264,7 +262,7 @@ const char* Error_Function_;
// atom completion
struct scan_atoms *search_atoms_;
struct pred_entry *SearchPreds_;
// Slots
/// Slots Status
yhandle_t CurSlot_;
yhandle_t FrozenHandles_;
yhandle_t NSlots_;

View File

@ -76,8 +76,6 @@ static void InitWorker(int wid) {
REMOTE_ScannerExtraBlocks(wid) = NULL;
REMOTE_BallTerm(wid) = NULL;
REMOTE_CBorder(wid) = 0;
REMOTE_MaxActiveSignals(wid) = 64L;
@ -171,9 +169,7 @@ static void InitWorker(int wid) {
REMOTE_BallTerm(wid) = NULL;

View File

@ -76,8 +76,6 @@ static void RestoreWorker(int wid USES_REGS) {
RestoreBallTerm(wid);
@ -192,8 +190,6 @@ static void RestoreWorker(int wid USES_REGS) {

View File

@ -934,9 +934,18 @@ static void RestoreForeignCode__(USES_REGS1) {
}
}
static void RestoreBallTerm(int wid) {
CACHE_REGS
if (LOCAL_BallTerm) {
LOCAL_BallTerm = DBTermAdjust(LOCAL_BallTerm);
RestoreDBTerm(LOCAL_BallTerm, false, 1 PASS_REGS);
}
}
static void RestoreYapRecords__(USES_REGS1) {
struct record_list *ptr;
RestoreBallTerm(worker_id);
Yap_Records = DBRecordAdjust(Yap_Records);
ptr = Yap_Records;
while (ptr) {
@ -948,14 +957,6 @@ static void RestoreYapRecords__(USES_REGS1) {
}
}
static void RestoreBallTerm(int wid) {
CACHE_REGS
if (LOCAL_BallTerm) {
LOCAL_BallTerm = DBTermAdjust(LOCAL_BallTerm);
RestoreDBTerm(LOCAL_BallTerm, false,1 PASS_REGS);
}
}
#if defined(THREADS) || defined(YAPOR)
#include "rglobals.h"
#endif

View File

@ -27,10 +27,19 @@ typedef enum {
retry_table_loader
} yap_low_level_port;
void low_level_trace(yap_low_level_port, PredEntry *, CELL *);
#ifdef saveregs
#define low_level_trace(Port, pred, args) \
{ \
saveregs(); \
low_level_trace__(Port, pred, args); \
setregs(); \
}
#else
#define low_level_trace(Port, pred, args) low_level_trace__(Port, pred, args)
#endif
void low_level_trace__(yap_low_level_port, PredEntry *, CELL *);
void Yap_InitLowLevelTrace(void);
void toggle_low_level_trace(void);
#endif

View File

@ -140,32 +140,23 @@ if(POLICY CMP0043)
cmake_policy(SET CMP0043 NEW)
endif(POLICY CMP0043)
if (ANDROID)
set (prefix ${CMAKE_SOURCE_DIR}/../app/src/main)
set ( exec_prefix "${prefix}")
set ( libdir "${exec_prefix}/jni/${ANDROID_ABI}")
set ( dlls "${libdir}")
set ( includedir "${prefix}/assets/include")
set ( datarootdir "${prefix}/assets/share")
set ( libpl "${prefix}/assets/share/Yap")
set ( datadir "${datarootdir}")
set ( mandir "${datarootdir}/man")
set ( bindir "${exec_prefix}/bin")
set ( docdir "${exec_prefix}/assets/share/doc/yap")
else()
set ( prefix "${CMAKE_INSTALL_PREFIX}")
set ( exec_prefix "${prefix}")
set ( libdir "${exec_prefix}/lib")
set ( dlls "${exec_prefix}/lib/Yap")
set ( includedir "${prefix}/include")
set ( datarootdir "${prefix}/share")
set ( libpl "${prefix}/share/Yap")
if (ANDROID)
set ( libpl "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/../../../../../build/generated/assets/Yap")
else()
set ( libpl "${datarootdir}/Yap")
endif()
set ( datadir "${datarootdir}")
set ( mandir "${datarootdir}/man")
set ( bindir "${exec_prefix}/bin")
set ( docdir "${exec_prefix}/share/doc/Yap")
endif()
set ( docdir "${exec_prefix}/doc/Yap")
set(YAP_ROOTDIR ${prefix})

View File

@ -345,6 +345,7 @@ check_function_exists(strcasestr HAVE_STRCASESTR)
check_function_exists(strchr HAVE_STRCHR)
check_function_exists(strerror HAVE_STRERROR)
check_function_exists(stricmp HAVE_STRICMP)
check_function_exists(strlcpy HAVE_STRLCPY)
check_function_exists(strlwr HAVE_STRLWR)
check_function_exists(strncasecmp HAVE_STRNCASECMP)
check_function_exists(strncat HAVE_STRNCAT)

View File

@ -2011,6 +2011,9 @@ calls it, or to nothing if 'inline' is not supported under any name. */
#endif
#endif
#ifndef HAVE_STRLCPY
#define strlcpy(X,Y,Z) strcpy(X,Y)
#endif
//#define DEBUG_MALLOC 1
#if DEBUG_MALLOC

View File

@ -36,22 +36,28 @@
#include "YapErrors.h"
struct yami *Yap_Error__(const char *file, const char *function, int lineno, yap_error_number err,YAP_Term wheret, ...);
#define MAX_ERROR_MSG_SIZE 10
#define Yap_NilError( id, ...) Yap_Error__(__FILE__, __FUNCTION__, __LINE__, id, TermNil, __VA_ARGS__)
struct yami *Yap_Error__(const char *file, const char *function, int lineno,
yap_error_number err, YAP_Term wheret, ...);
#define Yap_Error( id, inp, ...) Yap_Error__(__FILE__, __FUNCTION__, __LINE__, id, inp, __VA_ARGS__)
#define Yap_NilError(id, ...) \
Yap_Error__(__FILE__, __FUNCTION__, __LINE__, id, TermNil, __VA_ARGS__)
#define Yap_Error(id, inp, ...) \
Yap_Error__(__FILE__, __FUNCTION__, __LINE__, id, inp, __VA_ARGS__)
#ifdef YAP_TERM_H
/**
* make sure next argument is a bound instance of type
* atom.
*/
#define Yap_ensure_atom( T0, TF ) { if ( (TF = Yap_ensure_atom__(__FILE__, __FUNCTION__, __LINE__, T0 ) == 0L ) return false; }
#define Yap_ensure_atom(T0, TF) \
{ if ( (TF = Yap_ensure_atom__(__FILE__, __FUNCTION__, __LINE__, T0 ) == 0L ) return false; \
}
INLINE_ONLY extern inline Term
Yap_ensure_atom__( const char *fu, const char *fi, int line, Term in )
{
INLINE_ONLY extern inline Term Yap_ensure_atom__(const char *fu, const char *fi,
int line, Term in) {
Term t = Deref(in);
// Term Context = Deref(ARG2);
if (!IsVarTerm(t) && IsAtomTerm(t))
@ -59,7 +65,8 @@ Yap_ensure_atom__( const char *fu, const char *fi, int line, Term in )
if (IsVarTerm(t)) {
Yap_Error__(fu, fi, line, INSTANTIATION_ERROR, t, NULL);
} else {
if ( IsAtomTerm(t) ) return t ;
if (IsAtomTerm(t))
return t;
Yap_Error__(fu, fi, line, TYPE_ERROR_ATOM, t, NULL);
return 0L;
}
@ -138,4 +145,69 @@ Yap_ensure_atom__( const char *fu, const char *fi, int line, Term in )
goto LAB; \
}
/**
* Error stages since it was initially processed.
*
* Notice that some of the stages may be active simultaneouly.
*/
typedef enum yap_error_status {
/// where we like to be
YAP_NO_ERROR_STATUS = 0x0,
/// Prolog discovered the problem
YAP_ERROR_INITIATED_IN_PROLOG = 0x1,
/// The problem was found before the system can cope
YAP_ERROR_INITIATED_IN_BOOT = 0x2,
/// C-helper like must_ found out the problem
YAP_ERROR_INITIATED_IN_HELPER = 0x4,
/// C-builtin crashed
YAP_ERROR_INITIATED_IN_SYSTEM_C = 0x8,
/// user code crashed
YAP_ERROR_INITIATED_IN_USER_C = 0x10,
/// ok, we put a throw to be dispatched
YAP_THROW_THROWN = 0x20,
/// someone caught it
YAP_THROW_CAUGHT = 0x40,
/// error became an exception (usually SWIG bridge)
YAP_ERROR_EXPORTED_TO_CXX = 0x80,
/// handle error in Prolog
YAP_ERROR_BEING_PROCESSED_IN_PROLOG = 0x100
/// go back t
} yap_error_stage_t;
/// all we need to know about an error/throw
typedef struct yap_error_descriptor {
enum yap_error_status status;
yap_error_class_number errorClass;
YAP_Atom errorAsText;
YAP_Atom classAsText;
yap_error_number errorNo;
YAP_Int errorLine;
const char *errorFunction;
const char *errorFile;
YAP_Int prologPredCl;
YAP_UInt prologPredLine;
YAP_UInt prologPredFirstLine;
YAP_UInt prologPredLastLine;
YAP_Atom prologPredName;
YAP_UInt prologPredArity;
YAP_Term prologPredModule;
YAP_Atom prologPredFile;
struct DB_TERM *errorTerm;
char errorComment[MAX_ERROR_MSG_SIZE];
size_t errorMsgLen;
} yap_error_descriptor_t;
/// compatibility with existing code..
#define LOCAL_Error_TYPE LOCAL_ActiveError.errorNo
#define LOCAL_Error_File LOCAL_ActiveError.errorFile
#define LOCAL_Error_Function LOCAL_ActiveError.errorFunction
#define LOCAL_Error_Lineno LOCAL_ActiveError.errorLine
#define LOCAL_Error_Size LOCAL_ActiveError.errorMsgLen
#define LOCAL_ErrorSay LOCAL_ActiveError.errorComment
extern bool Yap_find_prolog_culprit();
extern yap_error_class_number Yap_errorClass(yap_error_number e);
extern const char *Yap_errorName(yap_error_number e);
extern const char *Yap_errorClassName(yap_error_class_number e);
#endif

View File

@ -1,7 +1,6 @@
///
/// @file YapErrors.h
///
/// @adddtogroup YapError
/// /// @adddtogroup YapError
///
/// The file YapErrors.h contains a list with all the error classes known
/// internally to the YAP system.
@ -149,6 +148,7 @@ E(SYSTEM_ERROR_JIT_NOT_AVAILABLE, SYSTEM_ERROR_CLASS, "jit_not_available")
E(SYSTEM_ERROR_OPERATING_SYSTEM, SYSTEM_ERROR_CLASS, "operating_system_error")
E(SYSTEM_ERROR_SAVED_STATE, SYSTEM_ERROR_CLASS, "saved_state_error")
E(ERROR_EVENT, EVENT, "error")
E(ABORT_EVENT, EVENT, "abort")
E(THROW_EVENT, EVENT, "throw")
E(CALL_COUNTER_UNDERFLOW_EVENT, EVENT, "call_counter_underflow")

View File

@ -1896,14 +1896,14 @@ extern X_API YAP_PredEntryPtr YAP_FunctorToPredInModule(YAP_Functor,
extern X_API YAP_PredEntryPtr YAP_AtomToPredInModule(YAP_Atom, YAP_Module);
/* int YAP_EnterGoal(void) */
extern X_API YAP_Bool YAP_EnterGoal(YAP_PredEntryPtr, YAP_handle_t,
extern X_API YAP_Bool YAP_EnterGoal(YAP_PredEntryPtr, YAP_Term *,
YAP_dogoalinfo *);
/* int YAP_RetryGoal(void) */
extern X_API YAP_Bool YAP_RetryGoal(YAP_dogoalinfo *);
/* int YAP_LeaveGoal(void) */
extern X_API YAP_Bool YAP_LeaveGoal(int, YAP_dogoalinfo *);
extern X_API YAP_Bool YAP_LeaveGoal(bool, YAP_dogoalinfo *);
/* int YAP_GoalHasException(YAP_Term *) */
extern X_API YAP_Bool YAP_GoalHasException(YAP_Term *);

View File

@ -72,8 +72,11 @@ MY_add_subdirectory(rltree)
MY_add_subdirectory(system)
MY_add_subdirectory(tries)
MY_add_subdirectory(ytest)
MY_add_custom_target (library SOURCES ${LIBRARY_PL} ) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )
if (ANDROID)
file(INSTALL ${LIBRARY_PL} DESTINATION ${libpl})
else()
install(FILES ${LIBRARY_PL}
DESTINATION ${libpl}
)
endif()

View File

@ -32,11 +32,14 @@ Moyle. All rights reserved.
#include <Yatom.h>
#include <eval.h>
#include "swi.h"
#include <YapHeap.h>
#include <YapHandles.h>
#include <YapText.h>
#include <yapio.h>
#include "swi.h"
#if HAVE_MATH_H
#include <math.h>
#endif
@ -1977,7 +1980,8 @@ X_API int PL_is_pair(term_t ts) {
X_API int PL_skip_list(term_t list, term_t tail, size_t *len) {
CACHE_REGS
Term *l = Yap_AddressFromSlot(list);
Term t0 = Yap_GetFromSlot(list);
Term *l = &t0;
Term *t;
intptr_t length;
@ -2413,14 +2417,15 @@ X_API int PL_next_solution(qid_t qi) {
return 0;
// don't forget, on success these guys must create slots
if (qi->q_state == 0) {
result = YAP_EnterGoal((YAP_PredEntryPtr)qi->q_pe, qi->q_g, &qi->q_h);
result = YAP_EnterGoal((YAP_PredEntryPtr)qi->q_pe,
Yap_GetPtrFromHandle(qi->q_g), &qi->q_h);
} else {
LOCAL_AllowRestart = qi->q_open;
result = YAP_RetryGoal(&qi->q_h);
}
qi->q_state = 1;
if (result == 0) {
YAP_LeaveGoal(FALSE, &qi->q_h);
YAP_LeaveGoal(false, &qi->q_h);
qi->q_open = 0;
}
return result;
@ -2431,7 +2436,7 @@ X_API void PL_cut_query(qid_t qi) {
if (qi->q_open != 1 || qi->q_state == 0)
return;
YAP_LeaveGoal(FALSE, &qi->q_h);
YAP_LeaveGoal(false, &qi->q_h);
qi->q_open = 0;
LOCAL_execution = qi->oq;
Yap_FreeCodeSpace((char *)qi);

View File

@ -58,9 +58,12 @@ set (YAPOS_HEADERS
chartypes.yap
)
if (ANDROID)
file(INSTALL ${YAPOS_PL_SOURCES} DESTINATION ${libpl}/os)
else()
install (FILES ${YAPOS_PL_SOURCES}
DESTINATION ${libpl}/os )
endif()
include(CheckFunctionExists)
@ -118,4 +121,3 @@ endif (READLINE_FOUND)
set( READLINE_LIBS ${READLINE_LIBRARIES} PARENT_SCOPE)
endif (WITH_READLINE)

View File

@ -19,6 +19,8 @@
#define ENCODING_H 1
#include "YapError.h"
typedef enum {
ENC_OCTET = 0, /// binary files
ENC_ISO_LATIN1 = 1, /// US+West Europe
@ -186,9 +188,7 @@ static inline encoding_t enc_id(const char *s, encoding_t enc_bom) {
if (enc_bom != ENC_OCTET)
return enc_bom;
return Yap_DefaultEncoding();
}
else {
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, MkAtomTerm(Yap_LookupAtom(s)), "bad encoding %s", s);
} else {
return Yap_DefaultEncoding();
}
}

View File

@ -32,33 +32,31 @@ static char SccsId[] = "%W% %G%";
#define SYSTEM_STAT stat
#endif
bool Yap_GetFileName(Term t, char *buf, size_t len, encoding_t enc) {
while (IsApplTerm(t) && FunctorOfTerm(t) == FunctorSlash) {
if (!Yap_GetFileName(ArgOfTerm(1, t), buf, len, enc))
return false;
size_t szl = strlen(buf);
buf += szl;
*buf++ = '/';
t = ArgOfTerm(2, t);
len -= (szl + 1);
}
return Yap_TextTermToText(t, buf, len, enc);
}
static Int file_name_extension(USES_REGS1) {
Term t1 = Deref(ARG1);
Term t2 = Deref(ARG2);
Term t3 = Deref(ARG3);
bool use_string = false;
loop:
char f[YAP_FILENAME_MAX + 1];
#if __APPLE__ || _WIN32
bool lowcase = true;
#endif
if (!IsVarTerm((t3))) {
const char *f;
if (IsAtomTerm(t3)) {
f = AtomName(AtomOfTerm(t3));
} else if (IsStringTerm(t3)) {
f = StringOfTerm(t3);
use_string = true;
} else if (IsApplTerm(t3) && FunctorOfTerm(t3) == FunctorSlash) {
// descend a compound term of the form a/b.
Term tn1 = MkVarTerm(), tf1;
Term ts[2];
ts[0] = ArgOfTerm(1, t3);
ts[1] = tn1;
tf1 = Yap_MkApplTerm(FunctorSlash, 2, ts);
if (!Yap_unify(ARG1, tf1)) {
return false;
}
t3 = ArgOfTerm(2, t3);
goto loop;
} else {
Yap_Error(TYPE_ERROR_ATOMIC, t3, "file_name_extension/3");
char *f2;
if (!Yap_GetFileName(t3, f, YAP_FILENAME_MAX, ENC_ISO_UTF8)) {
return false;
}
char *pts = strrchr(f, '/');
@ -68,106 +66,69 @@ loop:
pts = pts1;
#endif
char *ss = strrchr(f, '.');
if (pts > ss)
ss = NULL;
if (use_string) {
char *tmp;
if (!ss) {
return Yap_unify(ARG1, ARG3) && Yap_unify(ARG2, MkStringTerm(""));
}
tmp = malloc((ss - f) + 1);
int i;
for (i=0;i < (ss - f); i++) tmp[i] = ss[i];
tmp[i] = '\0';
if (!Yap_unify(ARG1, MkStringTerm(tmp))) {
free(tmp);
return false;
}
free(tmp);
// without and with dot
if (!Yap_unify(ARG2, MkStringTerm(ss + 1)))
return Yap_unify(ARG2, MkStringTerm(ss));
return true;
if (pts > ss) {
ss = f + strlen(f);
} else if (ss == NULL) {
ss = "";
} else {
char *tmp;
if (!ss) {
return Yap_unify(ARG1, ARG3) &&
Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom("")));
ss++;
}
tmp = malloc((ss - f) + 1);
int i;
for (i=0;i < (ss - f); i++) tmp[i] = ss[i];
tmp[i] = '\0';
if (!Yap_unify(ARG1, MkAtomTerm(Yap_LookupAtom(tmp)))) {
if (tmp != f)
free(tmp);
return false;
}
if (tmp != f)
free(tmp);
// without and with dot
if (!Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(ss + 1))))
return Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(ss)));
return true;
}
} else {
char s[MAXPATHLEN + 1];
const char *f1, *f2;
loop1:
if (IsVarTerm(t1)) {
Yap_Error(INSTANTIATION_ERROR, t1, "access");
return FALSE;
} else if (IsAtomTerm(t1)) {
f1 = AtomName(AtomOfTerm(t1));
} else if (IsStringTerm(t1)) {
f1 = StringOfTerm(t1);
use_string = true;
} else if (IsApplTerm(t1) && FunctorOfTerm(t1) == FunctorSlash) {
// descend a compound term of the form a/b.
Term tn1 = MkVarTerm(), tf1;
Term ts[2];
ts[0] = ArgOfTerm(1, t1);
ts[1] = tn1;
tf1 = Yap_MkApplTerm(FunctorSlash, 2, ts);
if (!Yap_unify(ARG3, tf1)) {
return false;
}
t1 = ArgOfTerm(2, t1);
goto loop1;
} else {
Yap_Error(TYPE_ERROR_ATOMIC, t1, "file_name_extension/3");
return false;
}
if (IsVarTerm(t2)) {
Yap_Error(INSTANTIATION_ERROR, t2, "access");
return FALSE;
} else if (IsAtomTerm(t2)) {
f2 = AtomName(AtomOfTerm(t2));
} else if (IsStringTerm(t1)) {
f2 = StringOfTerm(t2);
use_string = true;
Term t = Yap_MkTextTerm(ss, ENC_ISO_UTF8, t3);
Yap_unify(t2, t);
} else {
Yap_Error(TYPE_ERROR_ATOMIC, t2, "file_name_extension/3");
f2 = ss + (strlen(ss) + 1);
if (!Yap_TextTermToText(t2, f2, YAP_FILENAME_MAX - 1 - (f2 - f),
ENC_ISO_UTF8))
return false;
#if __APPLE__ || _WIN32
Yap_OverwriteUTF8BufferToLowCase(f2);
lowcase = true;
#endif
if (strcmp(f2, ss) != 0 && (ss > f && strcmp(f2, ss - 1) != 0)) {
return false;
}
if (f2[0] == '.') {
strncpy(s, f1, MAXPATHLEN);
strncat(s, f2, MAXPATHLEN);
if (use_string)
return Yap_unify_constant(ARG3, MkStringTerm(s));
else
return Yap_unify_constant(ARG3, MkAtomTerm(Yap_LookupAtom(s)));
} else {
strncpy(s, f1, MAXPATHLEN);
strncat(s, ".", MAXPATHLEN);
strncat(s, f2, MAXPATHLEN);
if (use_string)
return Yap_unify_constant(ARG3, MkStringTerm(s));
else
return Yap_unify_constant(ARG3, MkAtomTerm(Yap_LookupAtom(s)));
}
if (f[0] && ss[0] && ss[0] != '.') {
ss[-1] = '\0';
}
if (IsVarTerm(t1)) {
Term t = Yap_MkTextTerm(f, ENC_ISO_UTF8, t3);
Yap_unify(t1, t);
} else {
char f1[YAP_FILENAME_MAX + 1];
#if __APPLE || _WIN32
Yap_OverwriteUTF8BufferToLowCase(f);
#endif
if (!Yap_GetFileName(t2, f1, YAP_FILENAME_MAX, ENC_ISO_UTF8))
return false;
#if __APPLE__ || _WIN32
if (!lowcase)
Yap_OverwriteUTF8BufferToLowCase(f2);
#endif
if (strcmp(f1, f) != 0) {
return false;
}
}
return true;
} else {
char *f2;
if (!Yap_TextTermToText(t1, f, YAP_FILENAME_MAX - 2, ENC_ISO_UTF8)) {
return false;
}
f2 = f + strlen(f);
if (!Yap_TextTermToText(t2, f2, YAP_FILENAME_MAX - 2 - (f2 - f),
ENC_ISO_UTF8)) {
return false;
}
if (f2[0] != '.') {
memmove(f2 + 1, f2, strlen(f2) + 1);
f2[0] = '.';
}
Term t = Yap_MkTextTerm(f, ENC_ISO_UTF8, t1);
if (!t)
return false;
return Yap_unify(t, t3);
}
}
@ -345,6 +306,29 @@ static Int file_size(USES_REGS1) {
return false;
}
static Int lines_in_file(USES_REGS1) {
Int sno = Yap_CheckStream(ARG1, (Input_Stream_f | Output_Stream_f),
"lines_in_file/2");
if (sno < 0)
return (FALSE);
if (GLOBAL_Stream[sno].status & Seekable_Stream_f &&
!(GLOBAL_Stream[sno].status &
(InMemory_Stream_f | Socket_Stream_f | Pipe_Stream_f))) {
FILE *f = GLOBAL_Stream[sno].file;
size_t count = 0;
int ch;
#if __ANDROID__
#define getw getc
#endif
while ((ch = getw(f)) >= 0) {
if (ch == '\n')
count++;
}
return Yap_unify(ARG3, MkIntegerTerm(count));
}
return false;
}
static Int access_file(USES_REGS1) {
Term tname = Deref(ARG1);
Term tmode = Deref(ARG2);
@ -657,6 +641,8 @@ void Yap_InitFiles(void) {
SafePredFlag);
Yap_InitCPred("same_file", 2, same_file, SafePredFlag | SyncPredFlag);
Yap_InitCPred("$access_file", 2, access_file, SafePredFlag | SyncPredFlag);
Yap_InitCPred("$lines_in_file", 2, lines_in_file,
SafePredFlag | SyncPredFlag);
Yap_InitCPred("access", 1, access_path, SafePredFlag | SyncPredFlag);
Yap_InitCPred("exists_directory", 1, exists_directory,
SafePredFlag | SyncPredFlag);

View File

@ -267,8 +267,8 @@ char *Yap_MemExportStreamPtr(int sno) {
#if MAY_WRITE
char *s;
if (fflush(GLOBAL_Stream[sno].file) == 0) {
fseek(GLOBAL_Stream[sno].file, 0, SEEK_END);
s = GLOBAL_Stream[sno].nbuf;
// s[fseek(GLOBAL_Stream[sno].file, 0, SEEK_END)] = '\0';
return s;
}
return NULL;
@ -282,8 +282,7 @@ char *Yap_MemExportStreamPtr(int sno) {
static Int peek_mem_write_stream(
USES_REGS1) { /* '$peek_mem_write_stream'(+GLOBAL_Stream,?S0,?S) */
Int sno =
Yap_CheckStream(ARG1, (Output_Stream_f |
InMemory_Stream_f), "close/2");
Yap_CheckStream(ARG1, (Output_Stream_f | InMemory_Stream_f), "close/2");
Int i;
Term tf = ARG2;
CELL *HI;

View File

@ -192,8 +192,10 @@ Multivalued variables are translated to binary variables by means of a log
encodimg
*/
#include "simplecudd.h"
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <signal.h>
#include <time.h>
@ -226,14 +228,12 @@ typedef struct _extmanager {
namedvars varmap;
} extmanager;
double ProbBool(extmanager MyManager, DdNode *node, int bits, int nBit,int posBVar,variable v, int comp);
double ProbBool(extmanager MyManager, DdNode *node, int bits, int nBit,
int posBVar, variable v, int comp);
double Prob(extmanager MyManager, DdNode *node, int comp);
int correctPosition(int index, variable v, int posBVar);
double ret_prob(extmanager MyManager, DdNode *bdd);
int argtype(const char *arg);
void printhelp(int argc, char **arg);
parameters loadparam(int argc, char **arg);
@ -247,7 +247,8 @@ double sigmoid(double x, double slope);
void myexpand(extmanager MyManager, DdNode *Current);
double CalcProbability(extmanager MyManager, DdNode *Current);
double CalcProbabilitySigmoid(extmanager MyManager, DdNode *Current);
gradientpair CalcGradient(extmanager MyManager, DdNode *Current, int TargetVar, char *TargetPattern);
gradientpair CalcGradient(extmanager MyManager, DdNode *Current, int TargetVar,
char *TargetPattern);
int patterncalculated(char *pattern, extmanager MyManager, int loc);
char *extractpattern(char *thestr);
@ -268,7 +269,8 @@ int main(int argc, char **arg) {
if (params.errorcnt > 0) {
printhelp(argc, arg);
for (i = 0; i < params.errorcnt; i++) {
fprintf(stderr, "Error: not known or error at parameter %s.\n", arg[params.error[i]]);
fprintf(stderr, "Error: not known or error at parameter %s.\n",
arg[params.error[i]]);
}
return -1;
}
@ -279,13 +281,17 @@ int main(int argc, char **arg) {
return -1;
}
if (params.method != 0 && arg[params.method][0] != 'g' && arg[params.method][0] != 'p' && arg[params.method][0] != 'o' && arg[params.method][0] != 'l') {
if (params.method != 0 && arg[params.method][0] != 'g' &&
arg[params.method][0] != 'p' && arg[params.method][0] != 'o' &&
arg[params.method][0] != 'l') {
printhelp(argc, arg);
fprintf(stderr, "Error: you must choose a calculation method beetween [p]robability, [g]radient, [l]ine search, [o]nline.\n");
fprintf(stderr, "Error: you must choose a calculation method beetween "
"[p]robability, [g]radient, [l]ine search, [o]nline.\n");
return -1;
}
if (params.debug) DEBUGON;
if (params.debug)
DEBUGON;
RAPIDLOADON;
SETMAXBUFSIZE(params.maxbufsize);
#ifndef _WIN32
@ -311,14 +317,18 @@ int main(int argc, char **arg) {
case BDDFILE_SCRIPT:
if (params.inputfile == -1) {
printhelp(argc, arg);
fprintf(stderr, "Error: an input file is necessary for this type of loading file.\n");
fprintf(stderr, "Error: an input file is necessary for this type of "
"loading file.\n");
return -1;
}
MyManager.manager = simpleBDDinit(fileheader.varcnt);
MyManager.t = HIGH(MyManager.manager);
MyManager.f = LOW(MyManager.manager);
MyManager.varmap = InitNamedMultiVars(fileheader.varcnt, fileheader.varstart,fileheader.bvarcnt);
if (LoadMultiVariableData(MyManager.manager,MyManager.varmap, arg[params.inputfile]) == -1) return -1;
MyManager.varmap = InitNamedMultiVars(
fileheader.varcnt, fileheader.varstart, fileheader.bvarcnt);
if (LoadMultiVariableData(MyManager.manager, MyManager.varmap,
arg[params.inputfile]) == -1)
return -1;
start = clock();
bdd = FileGenerateBDD(MyManager.manager, MyManager.varmap, fileheader);
endc = clock();
@ -329,14 +339,16 @@ int main(int argc, char **arg) {
case BDDFILE_NODEDUMP:
if (params.inputfile == -1) {
printhelp(argc, arg);
fprintf(stderr, "Error: an input file is necessary for this type of loading file.\n");
fprintf(stderr, "Error: an input file is necessary for this type of "
"loading file.\n");
return -1;
}
MyManager.manager = simpleBDDinit(fileheader.varcnt);
MyManager.t = HIGH(MyManager.manager);
MyManager.f = LOW(MyManager.manager);
MyManager.varmap = InitNamedVars(fileheader.varcnt, fileheader.varstart);
bdd = LoadNodeDump(MyManager.manager, MyManager.varmap, fileheader.inputfile);
bdd = LoadNodeDump(MyManager.manager, MyManager.varmap,
fileheader.inputfile);
ivarcnt = fileheader.varcnt;
break;
default:
@ -355,7 +367,8 @@ int main(int argc, char **arg) {
code = 0;
/*
if (params.inputfile != -1) {
if (LoadVariableData(MyManager.varmap, arg[params.inputfile]) == -1) return -1;
if (LoadVariableData(MyManager.varmap, arg[params.inputfile]) == -1)
return -1;
if (!all_loaded(MyManager.varmap, 1)) return -1;
}*/
MyManager.his = InitHistory(ivarcnt);
@ -365,34 +378,47 @@ int main(int argc, char **arg) {
for (i = 0; i < MyManager.varmap.varcnt; i++) {
if (MyManager.varmap.vars[i] != NULL) {
varpattern = extractpattern(MyManager.varmap.vars[i]);
if ((varpattern == NULL) || (!patterncalculated(varpattern, MyManager, i))) {
tvalue = CalcGradient(MyManager, bdd, i + MyManager.varmap.varstart, varpattern);
if ((varpattern == NULL) ||
(!patterncalculated(varpattern, MyManager, i))) {
tvalue = CalcGradient(MyManager, bdd,
i + MyManager.varmap.varstart, varpattern);
probability = tvalue.probability;
double factor = sigmoid(MyManager.varmap.dvalue[i], params.sigmoid_slope) * (1 - sigmoid(MyManager.varmap.dvalue[i], params.sigmoid_slope)) * params.sigmoid_slope;
double factor =
sigmoid(MyManager.varmap.dvalue[i], params.sigmoid_slope) *
(1 -
sigmoid(MyManager.varmap.dvalue[i], params.sigmoid_slope)) *
params.sigmoid_slope;
if (varpattern == NULL) {
printf("query_gradient(%s,%s,%1.12f).\n", arg[params.queryid], MyManager.varmap.vars[i], tvalue.gradient * factor);
printf("query_gradient(%s,%s,%1.12f).\n", arg[params.queryid],
MyManager.varmap.vars[i], tvalue.gradient * factor);
} else {
varpattern[strlen(varpattern) - 2] = '\0';
printf("query_gradient(%s,%s,%1.12f).\n", arg[params.queryid], varpattern, tvalue.gradient * factor);
printf("query_gradient(%s,%s,%1.12f).\n", arg[params.queryid],
varpattern, tvalue.gradient * factor);
}
ReInitHistory(MyManager.his, MyManager.varmap.varcnt);
}
if (varpattern != NULL) free(varpattern);
if (varpattern != NULL)
free(varpattern);
} else {
fprintf(stderr, "Error: no variable name given for parameter.\n");
}
}
if (probability < 0.0) {
// no nodes, so we have to calculate probability ourself
tvalue = CalcGradient(MyManager, bdd, 0 + MyManager.varmap.varstart, NULL);
tvalue =
CalcGradient(MyManager, bdd, 0 + MyManager.varmap.varstart, NULL);
probability = tvalue.probability;
}
printf("query_probability(%s,%1.12f).\n", arg[params.queryid], probability);
printf("query_probability(%s,%1.12f).\n", arg[params.queryid],
probability);
break;
case 'l':
tvalue = CalcGradient(MyManager, bdd, 0 + MyManager.varmap.varstart, NULL);
tvalue =
CalcGradient(MyManager, bdd, 0 + MyManager.varmap.varstart, NULL);
probability = tvalue.probability;
printf("query_probability(%s,%1.12f).\n", arg[params.queryid], probability);
printf("query_probability(%s,%1.12f).\n", arg[params.queryid],
probability);
break;
case 'p':
printf("probability(%1.12f).\n", CalcProbability(MyManager, bdd));
@ -406,15 +432,20 @@ int main(int argc, char **arg) {
}
} else {
start = clock();
// simpleNamedBDDtoDot(MyManager.manager, MyManager.varmap, bdd, "bdd.dot");
// simpleNamedBDDtoDot(MyManager.manager, MyManager.varmap, bdd,
//"bdd.dot");
printf("probability(%1.12f).\n", ret_prob(MyManager, bdd));
endt = clock();
elapsedt = ((double)(endt - start)) / CLOCKS_PER_SEC;
printf("elapsed_traversing(%lf).\n", elapsedt);
// myexpand(MyManager, bdd);
}
if (params.savedfile > -1) SaveNodeDump(MyManager.manager, MyManager.varmap, bdd, arg[params.savedfile]);
if (params.exportfile > -1) simpleNamedBDDtoDot(MyManager.manager, MyManager.varmap, bdd, arg[params.exportfile]);
if (params.savedfile > -1)
SaveNodeDump(MyManager.manager, MyManager.varmap, bdd,
arg[params.savedfile]);
if (params.exportfile > -1)
simpleNamedBDDtoDot(MyManager.manager, MyManager.varmap, bdd,
arg[params.exportfile]);
ReInitHistory(MyManager.his, MyManager.varmap.varcnt);
free(MyManager.his);
}
@ -424,8 +455,7 @@ exit(code);
free(MyManager.varmap.dvalue);
free(MyManager.varmap.ivalue);
free(MyManager.varmap.dynvalue);
for (i = 0; i < MyManager.varmap.varcnt; i++)
{
for (i = 0; i < MyManager.varmap.varcnt; i++) {
free(MyManager.varmap.vars[i]);
free(MyManager.varmap.mvars[i].probabilities);
free(MyManager.varmap.mvars[i].booleanVars);
@ -434,50 +464,83 @@ exit(code);
free(MyManager.varmap.mvars);
free(MyManager.varmap.bVar2mVar);
}
if (params.error != NULL) free(params.error);
if (params.error != NULL)
free(params.error);
return code;
}
/* Shell Parameters handling */
int argtype(const char *arg) {
if (strcmp(arg, "-l") == 0 || strcmp(arg, "--load") == 0) return 0;
if (strcmp(arg, "-e") == 0 || strcmp(arg, "--export") == 0) return 2;
if (strcmp(arg, "-m") == 0 || strcmp(arg, "--method") == 0) return 3;
if (strcmp(arg, "-i") == 0 || strcmp(arg, "--input") == 0) return 4;
if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) return 5;
if (strcmp(arg, "-d") == 0 || strcmp(arg, "--debug") == 0) return 6;
if (strcmp(arg, "-id") == 0 || strcmp(arg, "--queryid") == 0) return 7;
if (strcmp(arg, "-t") == 0 || strcmp(arg, "--timeout") == 0) return 8;
if (strcmp(arg, "-sd") == 0 || strcmp(arg, "--savedump") == 0) return 9;
if (strcmp(arg, "-sl") == 0 || strcmp(arg, "--slope") == 0) return 10;
if (strcmp(arg, "-o") == 0 || strcmp(arg, "--online") == 0) return 11;
if (strcmp(arg, "-bs") == 0 || strcmp(arg, "--bufsize") == 0) return 12;
if (strcmp(arg, "-pid") == 0 || strcmp(arg, "--pid") == 0) return 13;
if (strcmp(arg, "-l") == 0 || strcmp(arg, "--load") == 0)
return 0;
if (strcmp(arg, "-e") == 0 || strcmp(arg, "--export") == 0)
return 2;
if (strcmp(arg, "-m") == 0 || strcmp(arg, "--method") == 0)
return 3;
if (strcmp(arg, "-i") == 0 || strcmp(arg, "--input") == 0)
return 4;
if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0)
return 5;
if (strcmp(arg, "-d") == 0 || strcmp(arg, "--debug") == 0)
return 6;
if (strcmp(arg, "-id") == 0 || strcmp(arg, "--queryid") == 0)
return 7;
if (strcmp(arg, "-t") == 0 || strcmp(arg, "--timeout") == 0)
return 8;
if (strcmp(arg, "-sd") == 0 || strcmp(arg, "--savedump") == 0)
return 9;
if (strcmp(arg, "-sl") == 0 || strcmp(arg, "--slope") == 0)
return 10;
if (strcmp(arg, "-o") == 0 || strcmp(arg, "--online") == 0)
return 11;
if (strcmp(arg, "-bs") == 0 || strcmp(arg, "--bufsize") == 0)
return 12;
if (strcmp(arg, "-pid") == 0 || strcmp(arg, "--pid") == 0)
return 13;
return -1;
}
void printhelp(int argc, char **arg) {
fprintf(stderr, "\nUsage: %s -l [filename] -i [filename] -o (-s(d) [filename] -e [filename] -m [method] -id [queryid] -sl [double]) (-t [seconds] -d -h)\n", arg[0]);
fprintf(stderr, "\nUsage: %s -l [filename] -i [filename] -o (-s(d) "
"[filename] -e [filename] -m [method] -id [queryid] -sl "
"[double]) (-t [seconds] -d -h)\n",
arg[0]);
fprintf(stderr, "Generates and traverses a BDD\nMandatory parameters:\n");
fprintf(stderr, "\t-l [filename]\t->\tfilename to load supports two formats:\n\t\t\t\t\t\t1. script with generation instructions\n\t\t\t\t\t\t2. node dump saved file\n");
fprintf(stderr, "\t-i [filename]\t->\tfilename to input problem specifics (mandatory with file formats 1, 2)\n");
fprintf(stderr, "\t-o\t\t->\tgenerates the BDD in online mode instead from a file can be used instead of -l\n");
fprintf(stderr, "\t-l [filename]\t->\tfilename to load supports two "
"formats:\n\t\t\t\t\t\t1. script with generation "
"instructions\n\t\t\t\t\t\t2. node dump saved file\n");
fprintf(stderr, "\t-i [filename]\t->\tfilename to input problem specifics "
"(mandatory with file formats 1, 2)\n");
fprintf(stderr, "\t-o\t\t->\tgenerates the BDD in online mode instead from a "
"file can be used instead of -l\n");
fprintf(stderr, "Optional parameters:\n");
fprintf(stderr, "\t-sd [filename]\t->\tfilename to save generated BDD in node dump format (fast loading, traverse valid only)\n");
fprintf(stderr, "\t-e [filename]\t->\tfilename to export generated BDD in dot format\n");
fprintf(stderr, "\t-m [method]\t->\tthe calculation method to be used: none(default), [p]robability, [g]radient, [o]nline\n");
fprintf(stderr, "\t-id [queryid]\t->\tthe queries identity name (used by gradient) default: %s\n", arg[0]);
fprintf(stderr, "\t-sl [double]\t->\tthe sigmoid slope (used by gradient) default: 1.0\n");
fprintf(stderr, "\t-sd [filename]\t->\tfilename to save generated BDD in "
"node dump format (fast loading, traverse valid only)\n");
fprintf(
stderr,
"\t-e [filename]\t->\tfilename to export generated BDD in dot format\n");
fprintf(stderr, "\t-m [method]\t->\tthe calculation method to be used: "
"none(default), [p]robability, [g]radient, [o]nline\n");
fprintf(stderr, "\t-id [queryid]\t->\tthe queries identity name (used by "
"gradient) default: %s\n",
arg[0]);
fprintf(stderr, "\t-sl [double]\t->\tthe sigmoid slope (used by gradient) "
"default: 1.0\n");
fprintf(stderr, "Extra parameters:\n");
fprintf(stderr, "\t-t [seconds]\t->\tthe seconds (int) for BDD generation timeout default 0 = no timeout\n");
fprintf(stderr, "\t-pid [pid]\t->\ta process id (int) to check for termination default 0 = no process to check works only under POSIX OS\n");
fprintf(stderr, "\t-bs [bytes]\t->\tthe bytes (int) to use as a maximum buffer size to read files default 0 = no max\n");
fprintf(stderr, "\t-d\t\t->\tRun in debug mode (gives extra messages in stderr)\n");
fprintf(stderr, "\t-t [seconds]\t->\tthe seconds (int) for BDD generation "
"timeout default 0 = no timeout\n");
fprintf(stderr, "\t-pid [pid]\t->\ta process id (int) to check for "
"termination default 0 = no process to check works only "
"under POSIX OS\n");
fprintf(stderr, "\t-bs [bytes]\t->\tthe bytes (int) to use as a maximum "
"buffer size to read files default 0 = no max\n");
fprintf(stderr,
"\t-d\t\t->\tRun in debug mode (gives extra messages in stderr)\n");
fprintf(stderr, "\t-h\t\t->\tHelp (displays this message)\n\n");
fprintf(stderr, "Example: %s -l testbdd -i input.txt -m g -id testbdd\n", arg[0]);
fprintf(stderr, "Example: %s -l testbdd -i input.txt -m g -id testbdd\n",
arg[0]);
}
parameters loadparam(int argc, char **arg) {
@ -625,8 +688,11 @@ void pidhandler(int num) {
}
}
s = (char *)malloc(sizeof(char) * (19 + strlen(params.ppid)));
strcpy(s, "ps "); strcat(s, params.ppid); strcat(s, " >/dev/null");
if (system(s) != 0) exit(4);
strcpy(s, "ps ");
strcat(s, params.ppid);
strcat(s, " >/dev/null");
if (system(s) != 0)
exit(4);
#ifndef _WIN32
signal(SIGALRM, pidhandler);
alarm(5);
@ -634,15 +700,11 @@ void pidhandler(int num) {
free(s);
}
void termhandler(int num) {
exit(3);
}
void termhandler(int num) { exit(3); }
/* General Functions */
double sigmoid(double x, double slope) {
return 1 / (1 + exp(-x * slope));
}
double sigmoid(double x, double slope) { return 1 / (1 + exp(-x * slope)); }
/* Debugging traverse function */
@ -653,7 +715,8 @@ void myexpand(extmanager MyManager, DdNode *Current) {
curnode = GetNodeVarNameDisp(MyManager.manager, MyManager.varmap, Current);
printf("%s\n", curnode);
if ((Current != MyManager.t) && (Current != MyManager.f) &&
((Found = GetNode(MyManager.his, MyManager.varmap.varstart, Current)) == NULL)) {
((Found = GetNode(MyManager.his, MyManager.varmap.varstart, Current)) ==
NULL)) {
l = LowNodeOf(MyManager.manager, Current);
h = HighNodeOf(MyManager.manager, Current);
printf("l(%s)->", curnode);
@ -675,16 +738,23 @@ double CalcProbability(extmanager MyManager, DdNode *Current) {
curnode = GetNodeVarNameDisp(MyManager.manager, MyManager.varmap, Current);
fprintf(stderr, "%s\n", curnode);
}
if (Current == MyManager.t) return 1.0;
if (Current == MyManager.f) return 0.0;
if ((Found = GetNode(MyManager.his, MyManager.varmap.varstart, Current)) != NULL) return Found->dvalue;
if (Current == MyManager.t)
return 1.0;
if (Current == MyManager.f)
return 0.0;
if ((Found = GetNode(MyManager.his, MyManager.varmap.varstart, Current)) !=
NULL)
return Found->dvalue;
l = LowNodeOf(MyManager.manager, Current);
h = HighNodeOf(MyManager.manager, Current);
if (params.debug) fprintf(stderr, "l(%s)->", curnode);
if (params.debug)
fprintf(stderr, "l(%s)->", curnode);
lvalue = CalcProbability(MyManager, l);
if (params.debug) fprintf(stderr, "h(%s)->", curnode);
if (params.debug)
fprintf(stderr, "h(%s)->", curnode);
hvalue = CalcProbability(MyManager, h);
tvalue = MyManager.varmap.dvalue[GetIndex(Current) - MyManager.varmap.varstart];
tvalue =
MyManager.varmap.dvalue[GetIndex(Current) - MyManager.varmap.varstart];
tvalue = tvalue * hvalue + lvalue * (1.0 - tvalue);
AddNode(MyManager.his, MyManager.varmap.varstart, Current, tvalue, 0, NULL);
return tvalue;
@ -692,7 +762,8 @@ double CalcProbability(extmanager MyManager, DdNode *Current) {
/* Bernds Algorithm */
gradientpair CalcGradient(extmanager MyManager, DdNode *Current, int TargetVar, char *TargetPattern) {
gradientpair CalcGradient(extmanager MyManager, DdNode *Current, int TargetVar,
char *TargetPattern) {
DdNode *h, *l;
hisnode *Found;
char *curnode;
@ -713,35 +784,46 @@ gradientpair CalcGradient(extmanager MyManager, DdNode *Current, int TargetVar,
tvalue.gradient = 0.0;
return tvalue;
}
if ((Found = GetNode(MyManager.his, MyManager.varmap.varstart, Current)) != NULL) {
if ((Found = GetNode(MyManager.his, MyManager.varmap.varstart, Current)) !=
NULL) {
tvalue.probability = Found->dvalue;
tvalue.gradient = *((double *)Found->dynvalue);
return tvalue;
}
l = LowNodeOf(MyManager.manager, Current);
h = HighNodeOf(MyManager.manager, Current);
if (params.debug) fprintf(stderr, "l(%s)->", curnode);
if (params.debug)
fprintf(stderr, "l(%s)->", curnode);
lvalue = CalcGradient(MyManager, l, TargetVar, TargetPattern);
if (params.debug) fprintf(stderr, "h(%s)->", curnode);
if (params.debug)
fprintf(stderr, "h(%s)->", curnode);
hvalue = CalcGradient(MyManager, h, TargetVar, TargetPattern);
this_probability = sigmoid(MyManager.varmap.dvalue[GetIndex(Current) - MyManager.varmap.varstart], params.sigmoid_slope);
tvalue.probability = this_probability * hvalue.probability + (1 - this_probability) * lvalue.probability;
tvalue.gradient = this_probability * hvalue.gradient + (1 - this_probability) * lvalue.gradient;
this_probability = sigmoid(
MyManager.varmap.dvalue[GetIndex(Current) - MyManager.varmap.varstart],
params.sigmoid_slope);
tvalue.probability = this_probability * hvalue.probability +
(1 - this_probability) * lvalue.probability;
tvalue.gradient = this_probability * hvalue.gradient +
(1 - this_probability) * lvalue.gradient;
if ((GetIndex(Current) == TargetVar) ||
((TargetPattern != NULL) && patternmatch(TargetPattern, MyManager.varmap.vars[GetIndex(Current)]))) {
((TargetPattern != NULL) &&
patternmatch(TargetPattern, MyManager.varmap.vars[GetIndex(Current)]))) {
tvalue.gradient += hvalue.probability - lvalue.probability;
}
gradient = (double *)malloc(sizeof(double));
*gradient = tvalue.gradient;
AddNode(MyManager.his, MyManager.varmap.varstart, Current, tvalue.probability, 0, gradient);
AddNode(MyManager.his, MyManager.varmap.varstart, Current, tvalue.probability,
0, gradient);
return tvalue;
}
char *extractpattern(char *thestr) {
char *p;
int i = 0, sl = strlen(thestr);
while((thestr[i] != '_') && (i < sl)) i++;
if (i == sl) return NULL;
while ((thestr[i] != '_') && (i < sl))
i++;
if (i == sl)
return NULL;
i++;
p = (char *)malloc(sizeof(char) * (i + 2));
strncpy(p, thestr, i);
@ -752,9 +834,11 @@ char * extractpattern(char *thestr) {
int patterncalculated(char *pattern, extmanager MyManager, int loc) {
int i;
if (pattern == NULL) return 0;
if (pattern == NULL)
return 0;
for (i = loc - 1; i > -1; i--)
if (patternmatch(pattern, MyManager.varmap.vars[i])) return 1;
if (patternmatch(pattern, MyManager.varmap.vars[i]))
return 1;
return 0;
}
@ -770,41 +854,34 @@ so that it is not recomputed
double res;
double value;
if (Cudd_IsConstant(node))
{
if (Cudd_IsConstant(node)) {
value = Cudd_V(node);
if (comp)
{
if (comp) {
return 0.0;
}
else
{
} else {
return 1.0;
}
}
else
{
Found = GetNode1(MyManager.varmap.bVar2mVar,MyManager.his, MyManager.varmap.varstart, node);
} else {
Found = GetNode1(MyManager.varmap.bVar2mVar, MyManager.his,
MyManager.varmap.varstart, node);
if (Found!=NULL)
{
if (Found != NULL) {
return Found->dvalue;
}
else
{
} else {
index = Cudd_NodeReadIndex(node);
mVarIndex = MyManager.varmap.bVar2mVar[index];
v = MyManager.varmap.mvars[mVarIndex];
nBit = v.nBit;
res = ProbBool(MyManager, node, 0, nBit, 0, v, comp);
AddNode1(MyManager.varmap.bVar2mVar,MyManager.his, MyManager.varmap.varstart, node, res, 0, NULL);
AddNode1(MyManager.varmap.bVar2mVar, MyManager.his,
MyManager.varmap.varstart, node, res, 0, NULL);
return res;
}
}
}
double ProbBool(extmanager MyManager, DdNode *node, int bits, int nBit,int posBVar,variable v, int comp)
double ProbBool(extmanager MyManager, DdNode *node, int bits, int nBit,
int posBVar, variable v, int comp)
/* explores a group of binary variables making up the multivalued variable v */
{
DdNode *T, *F;
@ -812,46 +889,37 @@ double ProbBool(extmanager MyManager, DdNode *node, int bits, int nBit,int posBV
double *probs;
int index;
probs = v.probabilities;
if (nBit==0)
{
if (bits>=v.nVal)
{
if (nBit == 0) {
if (bits >= v.nVal) {
return 0.0;
}
else
{
} else {
p = probs[bits];
res = p * Prob(MyManager, node, comp);
return res;
}
}
else
{
} else {
index = Cudd_NodeReadIndex(node);
if (correctPosition(index,v,posBVar))
{
if (correctPosition(index, v, posBVar)) {
T = Cudd_T(node);
F = Cudd_E(node);
bits = bits << 1;
res = ProbBool(MyManager, T, bits + 1, nBit - 1, posBVar + 1, v, comp);
comp = (!comp && Cudd_IsComplement(F)) || (comp && !Cudd_IsComplement(F));
res=res+
ProbBool(MyManager,F,bits,nBit-1,posBVar+1,v,comp);
res = res + ProbBool(MyManager, F, bits, nBit - 1, posBVar + 1, v, comp);
return res;
}
else
{
} else {
bits = bits << 1;
res = ProbBool(MyManager, node, bits + 1, nBit - 1, posBVar + 1, v, comp);
res=res+
ProbBool(MyManager,node,bits,nBit-1,posBVar+1,v,comp);
res =
res + ProbBool(MyManager, node, bits, nBit - 1, posBVar + 1, v, comp);
return res;
}
}
}
int correctPosition(int index, variable v, int posBVar)
/* returns 1 is the boolean variable with index posBVar is in the correct position
/* returns 1 is the boolean variable with index posBVar is in the correct
position
currently explored by ProbBool */
{
int bvar;
@ -860,13 +928,11 @@ currently explored by ProbBool */
return (bvar == index);
}
double ret_prob(extmanager MyManager, DdNode * bdd)
{
double ret_prob(extmanager MyManager, DdNode *bdd) {
double prob;
/* dividend is a global variable used by my_hash
it is equal to an unsigned int with binary representation 11..1 */
prob = Prob(MyManager, bdd, Cudd_IsComplement(bdd));
return prob;
}

View File

@ -287,7 +287,7 @@ DdNode *D_BDDXnor(DdManager *manager, DdNode *bdd1, DdNode *bdd2) {
/* file manipulation */
bddfileheader ReadFileHeader(char *filename) {
bddfileheader ReadFileHeader(const char *filename) {
bddfileheader temp;
char *header;
temp.inputfile = NULL;
@ -362,7 +362,7 @@ int CheckFileVersion(const char *version) {
return -1;
}
int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename) {
int simpleBDDtoDot(DdManager *manager, DdNode *bdd, const char *filename) {
DdNode *f[1];
int ret;
FILE *fd;
@ -378,7 +378,7 @@ int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename) {
}
int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd,
char *filename) {
const char *filename) {
DdNode *f[1];
int ret;
FILE *fd;
@ -388,13 +388,14 @@ int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd,
perror(filename);
return -1;
}
ret = Cudd_DumpDot(manager, 1, f, varmap.vars, NULL, fd);
const char *vs = varmap.vars;
ret = Cudd_DumpDot(manager, 1, f, vs, NULL, fd);
fclose(fd);
return ret;
}
int SaveNodeDump(DdManager *manager, namedvars varmap, DdNode *bdd,
char *filename) {
const char *filename) {
hisqueue *Nodes;
FILE *outputfile;
int i;

View File

@ -256,7 +256,7 @@ typedef struct _bddfileheader {
typedef struct {
int nVal, nBit, init;
double *probabilities;
int *booleanVars;
DdNode **booleanVars;
} variable;
typedef struct _namedvars {
@ -357,7 +357,7 @@ void onlinetraverse(DdManager *manager, namedvars varmap, hisqueue *HisQueue,
/* Save-load */
bddfileheader ReadFileHeader(char *filename);
bddfileheader ReadFileHeader(const char *filename);
int CheckFileVersion(const char *version);
DdNode *LoadNodeDump(DdManager *manager, namedvars varmap, FILE *inputfile);
@ -367,16 +367,16 @@ DdNode *GetIfExists(DdManager *manager, namedvars varmap, hisqueue *Nodes,
char *varname, int nodenum);
int SaveNodeDump(DdManager *manager, namedvars varmap, DdNode *bdd,
char *filename);
const char *filename);
void SaveExpand(DdManager *manager, namedvars varmap, hisqueue *Nodes,
DdNode *Current, FILE *outputfile);
void ExpandNodes(hisqueue *Nodes, int index, int nodenum);
/* Export */
int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename);
int simpleBDDtoDot(DdManager *manager, DdNode *bdd, const char *filename);
int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd,
char *filename);
const char *filename);
DdNode *equality(DdManager *mgr, int varIndex, int value, namedvars varmap);
hisnode *GetNodei1(int *bVar2mVar, hisqueue *HisQueue, int varstart,

View File

@ -48,6 +48,7 @@ add_component(myddas
${MYDDAS_UTIL_SOURCES}
${MYDDAS_HEADERS}
)
MY_add_dependencies(myddas plmyddas)
add_subdirectory(pl)

View File

@ -12,13 +12,17 @@ set(MYDDAS_DRIVERS
myddas_driver.ypp
)
if (ANDROID)
set (PREFIX ${libpl} )
else()
set (PREFIX ${CMAKE_CURRENT_BINARY_DIR} )
endif()
get_property(MYDDAS_FLAGS GLOBAL PROPERTY COMPILE_DEFINITIONS)
function(cpp_compile output filename)
get_filename_component(base ${filename} NAME_WE)
set(base_abs ${CMAKE_CURRENT_BINARY_DIR}/${base})
set(base_abs ${PREFIX}/${base})
set(outfile ${base_abs}.yap)
set(${output} ${${output}} ${outfile} PARENT_SCOPE)
IF (MSVC)
@ -61,9 +65,9 @@ foreach (driver ${MYDDAS_DBMS})
cpp_driver(MYDDAS_YAP ${driver} myddas_driver.ypp)
endforeach ()
MY_add_custom_target(plmyddas ALL DEPENDS ${MYDDAS_YAP}
add_custom_target(plmyddas ALL DEPENDS ${MYDDAS_YAP}
) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )
)
MY_install(FILES ${MYDDAS_YAP}
DESTINATION ${libpl}

View File

@ -0,0 +1,3 @@
"""A Prolog kernel for Jupyter"""
__version__ = '0.0.1'

View File

@ -0,0 +1,3 @@
if __name__ == '__main__':
from yapkernel import kernelapp as app
app.launch_new_instance()

View File

@ -0,0 +1,10 @@
:- [library(python)].
main :-
:= import matplotlib.pyplot,
:= Plt = ematplotlib.pyplot,
Plt.plot([1,2,3,4]),
Plt.ylabel(`some numbers`),
Plt.show().

View File

@ -0,0 +1,44 @@
import json
import os
import sys
try:
from jupyter_client.kernelspec import install_kernel_spec
except ImportError:
from IPython.kernel.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {
"argv": [sys.executable,
"-m", "yap_kernel",
"-f", "{connection_file}"],
"display_name": "yap",
"mimetype": "text/x-prolog",
"language": "prolog",
"name": "yap",
}
def install_my_kernel_spec(user=False):
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
# TODO: Copy resources once they're specified
print('Installing IPython kernel spec')
install_kernel_spec(td, 'yap', user=False, replace=True)
def _is_root():
return True
try:
return os.geteuid() == 0
except AttributeError:
return False # assume not an admin on non-Unix platforms
def main(argv=[]):
user = '--user' in argv or not _is_root()
install_my_kernel_spec(user=user)
if __name__ == '__main__':
main(argv=sys.argv)

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,488 @@
"""An Application for launching a kernel"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
import atexit
import os
import sys
import signal
import traceback
import logging
from tornado import ioloop
import zmq
from zmq.eventloop import ioloop as zmq_ioloop
from zmq.eventloop.zmqstream import ZMQStream
from IPython.core.application import (
BaseIPythonApplication, base_flags, base_aliases, catch_config_error
)
from IPython.core.profiledir import ProfileDir
from IPython.core.shellapp import (
InteractiveShellApp, shell_flags, shell_aliases
)
from IPython.utils import io
from ipython_genutils.path import filefind, ensure_dir_exists
from traitlets import (
Any, Instance, Dict, Unicode, Integer, Bool, DottedObjectName, Type, default
)
from ipython_genutils.importstring import import_item
from jupyter_core.paths import jupyter_runtime_dir
from jupyter_client import write_connection_file
from jupyter_client.connect import ConnectionFileMixin
# local imports
from ipykernel.iostream import IOPubThread
from ipykernel.heartbeat import Heartbeat
from .yap_kernel import YAPKernel
from ipykernel.parentpoller import ParentPollerUnix, ParentPollerWindows
from jupyter_client.session import (
Session, session_flags, session_aliases,
)
from ipykernel.zmqshell import ZMQInteractiveShell
#-----------------------------------------------------------------------------
# Flags and Aliases
#-----------------------------------------------------------------------------
kernel_aliases = dict(base_aliases)
kernel_aliases.update({
'ip' : 'YAPKernelApp.ip',
'hb' : 'YAPKernelApp.hb_port',
'shell' : 'YAPKernelApp.shell_port',
'iopub' : 'YAPKernelApp.iopub_port',
'stdin' : 'YAPKernelApp.stdin_port',
'control' : 'YAPKernelApp.control_port',
'f' : 'YAPKernelApp.connection_file',
'transport': 'YAPKernelApp.transport',
})
kernel_flags = dict(base_flags)
kernel_flags.update({
'no-stdout' : (
{'YAPKernelApp' : {'no_stdout' : True}},
"redirect stdout to the null device"),
'no-stderr' : (
{'YAPKernelApp' : {'no_stderr' : True}},
"redirect stderr to the null device"),
'pylab' : (
{'YAPKernelApp' : {'pylab' : 'auto'}},
"""Pre-load matplotlib and numpy for interactive use with
the default matplotlib backend."""),
})
# inherit flags&aliases for any IPython shell apps
kernel_aliases.update(shell_aliases)
kernel_flags.update(shell_flags)
# inherit flags&aliases for Sessions
kernel_aliases.update(session_aliases)
kernel_flags.update(session_flags)
_ctrl_c_message = """\
NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
To exit, you will have to explicitly quit this process, by either sending
"quit" from a client, or using Ctrl-\\ in UNIX-like environments.
To read more about this, see https://github.com/ipython/ipython/issues/2049
"""
#-----------------------------------------------------------------------------
# Application class for starting an IPython Kernel
#-----------------------------------------------------------------------------
class YAPKernelApp(BaseIPythonApplication, InteractiveShellApp,
ConnectionFileMixin):
name='YAP-kernel'
aliases = Dict(kernel_aliases)
flags = Dict(kernel_flags)
classes = [YAPKernel, ZMQInteractiveShell, ProfileDir, Session]
# the kernel class, as an importstring
kernel_class = Type('yap_kernel.yap_kernel.YAPKernel',
klass='ipykernel.kernelbase.Kernel',
help="""The Kernel subclass to be used.
This should allow easy re-use of the IPKernelApp entry point
to configure and launch kernels other than IPython's own.
""").tag(config=True)
kernel = Any()
poller = Any() # don't restrict this even though current pollers are all Threads
heartbeat = Instance(Heartbeat, allow_none=True)
ports = Dict()
subcommands = {
'install': (
'.kernelspec.InstallYAPKernelSpecApp',
'Install the YAP kernel'
),
}
# connection info:
connection_dir = Unicode()
@default('connection_dir')
def _default_connection_dir(self):
return jupyter_runtime_dir()
@property
def abs_connection_file(self):
if os.path.basename(self.connection_file) == self.connection_file:
return os.path.join(self.connection_dir, self.connection_file)
else:
return self.connection_file
# streams, etc.
no_stdout = Bool(False, help="redirect stdout to the null device").tag(config=True)
no_stderr = Bool(False, help="redirect stderr to the null device").tag(config=True)
outstream_class = DottedObjectName('ipykernel.iostream.OutStream',
help="The importstring for the OutStream factory").tag(config=True)
displayhook_class = DottedObjectName('ipykernel.displayhook.ZMQDisplayHook',
help="The importstring for the DisplayHook factory").tag(config=True)
# polling
parent_handle = Integer(int(os.environ.get('JPY_PARENT_PID') or 0),
help="""kill this process if its parent dies. On Windows, the argument
specifies the HANDLE of the parent process, otherwise it is simply boolean.
""").tag(config=True)
interrupt = Integer(int(os.environ.get('JPY_INTERRUPT_EVENT') or 0),
help="""ONLY USED ON WINDOWS
Interrupt this process when the parent is signaled.
""").tag(config=True)
def init_crash_handler(self):
sys.excepthook = self.excepthook
def excepthook(self, etype, evalue, tb):
# write uncaught traceback to 'real' stderr, not zmq-forwarder
traceback.print_exception(etype, evalue, tb, file=sys.__stderr__)
def init_poller(self):
if sys.platform == 'win32':
if self.interrupt or self.parent_handle:
self.poller = ParentPollerWindows(self.interrupt, self.parent_handle)
elif self.parent_handle:
self.poller = ParentPollerUnix()
def _bind_socket(self, s, port):
iface = '%s://%s' % (self.transport, self.ip)
if self.transport == 'tcp':
if port <= 0:
port = s.bind_to_random_port(iface)
else:
s.bind("tcp://%s:%i" % (self.ip, port))
elif self.transport == 'ipc':
if port <= 0:
port = 1
path = "%s-%i" % (self.ip, port)
while os.path.exists(path):
port = port + 1
path = "%s-%i" % (self.ip, port)
else:
path = "%s-%i" % (self.ip, port)
s.bind("ipc://%s" % path)
return port
def write_connection_file(self):
"""write connection info to JSON file"""
cf = self.abs_connection_file
self.log.debug("Writing connection file: %s", cf)
write_connection_file(cf, ip=self.ip, key=self.session.key, transport=self.transport,
shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port,
iopub_port=self.iopub_port, control_port=self.control_port)
def cleanup_connection_file(self):
cf = self.abs_connection_file
self.log.debug("Cleaning up connection file: %s", cf)
try:
os.remove(cf)
except (IOError, OSError):
pass
self.cleanup_ipc_files()
def init_connection_file(self):
if not self.connection_file:
self.connection_file = "kernel-%s.json"%os.getpid()
try:
self.connection_file = filefind(self.connection_file, ['.', self.connection_dir])
except IOError:
self.log.debug("Connection file not found: %s", self.connection_file)
# This means I own it, and I'll create it in this directory:
ensure_dir_exists(os.path.dirname(self.abs_connection_file), 0o700)
# Also, I will clean it up:
atexit.register(self.cleanup_connection_file)
return
try:
self.load_connection_file()
except Exception:
self.log.error("Failed to load connection file: %r", self.connection_file, exc_info=True)
self.exit(1)
def init_sockets(self):
# Create a context, a session, and the kernel sockets.
self.log.info("Starting the kernel at pid: %i", os.getpid())
context = zmq.Context.instance()
# Uncomment this to try closing the context.
# atexit.register(context.term)
self.shell_socket = context.socket(zmq.ROUTER)
self.shell_socket.linger = 1000
self.shell_port = self._bind_socket(self.shell_socket, self.shell_port)
self.log.debug("shell ROUTER Channel on port: %i" % self.shell_port)
self.stdin_socket = context.socket(zmq.ROUTER)
self.stdin_socket.linger = 1000
self.stdin_port = self._bind_socket(self.stdin_socket, self.stdin_port)
self.log.debug("stdin ROUTER Channel on port: %i" % self.stdin_port)
self.control_socket = context.socket(zmq.ROUTER)
self.control_socket.linger = 1000
self.control_port = self._bind_socket(self.control_socket, self.control_port)
self.log.debug("control ROUTER Channel on port: %i" % self.control_port)
self.init_iopub(context)
def init_iopub(self, context):
self.iopub_socket = context.socket(zmq.PUB)
self.iopub_socket.linger = 1000
self.iopub_port = self._bind_socket(self.iopub_socket, self.iopub_port)
self.log.debug("iopub PUB Channel on port: %i" % self.iopub_port)
self.configure_tornado_logger()
self.iopub_thread = IOPubThread(self.iopub_socket, pipe=True)
self.iopub_thread.start()
# backward-compat: wrap iopub socket API in background thread
self.iopub_socket = self.iopub_thread.background_socket
def init_heartbeat(self):
"""start the heart beating"""
# heartbeat doesn't share context, because it mustn't be blocked
# by the GIL, which is accessed by libzmq when freeing zero-copy messages
hb_ctx = zmq.Context()
self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port))
self.hb_port = self.heartbeat.port
self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port)
self.heartbeat.start()
def log_connection_info(self):
"""display connection info, and store ports"""
basename = os.path.basename(self.connection_file)
if basename == self.connection_file or \
os.path.dirname(self.connection_file) == self.connection_dir:
# use shortname
tail = basename
else:
tail = self.connection_file
lines = [
"To connect another client to this kernel, use:",
" --existing %s" % tail,
]
# log connection info
# info-level, so often not shown.
# frontends should use the %connect_info magic
# to see the connection info
for line in lines:
self.log.info(line)
# also raw print to the terminal if no parent_handle (`ipython kernel`)
# unless log-level is CRITICAL (--quiet)
if not self.parent_handle and self.log_level < logging.CRITICAL:
io.rprint(_ctrl_c_message)
for line in lines:
io.rprint(line)
self.ports = dict(shell=self.shell_port, iopub=self.iopub_port,
stdin=self.stdin_port, hb=self.hb_port,
control=self.control_port)
def init_blackhole(self):
"""redirects stdout/stderr to devnull if necessary"""
if self.no_stdout or self.no_stderr:
blackhole = open(os.devnull, 'w')
if self.no_stdout:
sys.stdout = sys.__stdout__ = blackhole
if self.no_stderr:
sys.stderr = sys.__stderr__ = blackhole
def init_io(self):
"""Redirect input streams and set a display hook."""
if self.outstream_class:
outstream_factory = import_item(str(self.outstream_class))
sys.stdout = outstream_factory(self.session, self.iopub_thread, u'stdout')
sys.stderr = outstream_factory(self.session, self.iopub_thread, u'stderr')
if self.displayhook_class:
displayhook_factory = import_item(str(self.displayhook_class))
self.displayhook = displayhook_factory(self.session, self.iopub_socket)
sys.displayhook = self.displayhook
self.patch_io()
def patch_io(self):
"""Patch important libraries that can't handle sys.stdout forwarding"""
try:
import faulthandler
except ImportError:
pass
else:
# Warning: this is a monkeypatch of `faulthandler.enable`, watch for possible
# updates to the upstream API and update accordingly (up-to-date as of Python 3.5):
# https://docs.python.org/3/library/faulthandler.html#faulthandler.enable
# change default file to __stderr__ from forwarded stderr
faulthandler_enable = faulthandler.enable
def enable(file=sys.__stderr__, all_threads=True, **kwargs):
return faulthandler_enable(file=file, all_threads=all_threads, **kwargs)
faulthandler.enable = enable
if hasattr(faulthandler, 'register'):
faulthandler_register = faulthandler.register
def register(signum, file=sys.__stderr__, all_threads=True, chain=False, **kwargs):
return faulthandler_register(signum, file=file, all_threads=all_threads,
chain=chain, **kwargs)
faulthandler.register = register
def init_signal(self):
signal.signal(signal.SIGINT, signal.SIG_IGN)
def init_kernel(self):
"""Create the Kernel object itself"""
shell_stream = ZMQStream(self.shell_socket)
control_stream = ZMQStream(self.control_socket)
kernel_factory = self.kernel_class.instance
kernel = kernel_factory(parent=self, session=self.session,
shell_streams=[shell_stream, control_stream],
iopub_thread=self.iopub_thread,
iopub_socket=self.iopub_socket,
stdin_socket=self.stdin_socket,
log=self.log,
profile_dir=self.profile_dir,
user_ns=self.user_ns,
)
kernel.record_ports({
name + '_port': port for name, port in self.ports.items()
})
self.kernel = kernel
# Allow the displayhook to get the execution count
self.displayhook.get_execution_count = lambda: kernel.execution_count
def init_gui_pylab(self):
"""Enable GUI event loop integration, taking pylab into account."""
# Register inline backend as default
# this is higher priority than matplotlibrc,
# but lower priority than anything else (mpl.use() for instance).
# This only affects matplotlib >= 1.5
if not os.environ.get('MPLBACKEND'):
os.environ['MPLBACKEND'] = 'module://ipykernel.pylab.backend_inline'
# Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
# to ensure that any exception is printed straight to stderr.
# Normally _showtraceback associates the reply with an execution,
# which means frontends will never draw it, as this exception
# is not associated with any execute request.
shell = self.shell
_showtraceback = shell._showtraceback
try:
# replace error-sending traceback with stderr
def print_tb(etype, evalue, stb):
print ("GUI event loop or pylab initialization failed",
file=sys.stderr)
print (shell.InteractiveTB.stb2text(stb), file=sys.stderr)
shell._showtraceback = print_tb
InteractiveShellApp.init_gui_pylab(self)
finally:
shell._showtraceback = _showtraceback
def init_shell(self):
self.shell = getattr(self.kernel, 'shell', None)
if self.shell:
self.shell.configurables.append(self)
def init_extensions(self):
super(YAPKernelApp, self).init_extensions()
# BEGIN HARDCODED WIDGETS HACK
# Ensure ipywidgets extension is loaded if available
extension_man = self.shell.extension_manager
if 'ipywidgets' not in extension_man.loaded:
try:
extension_man.load_extension('ipywidgets')
except ImportError as e:
self.log.debug('ipywidgets package not installed. Widgets will not be available.')
# END HARDCODED WIDGETS HACK
def configure_tornado_logger(self):
""" Configure the tornado logging.Logger.
Must set up the tornado logger or else tornado will call
basicConfig for the root logger which makes the root logger
go to the real sys.stderr instead of the capture streams.
This function mimics the setup of logging.basicConfig.
"""
logger = logging.getLogger('tornado')
handler = logging.StreamHandler()
formatter = logging.Formatter(logging.BASIC_FORMAT)
handler.setFormatter(formatter)
logger.addHandler(handler)
@catch_config_error
def initialize(self, argv=None):
super(YAPKernelApp, self).initialize(argv)
if self.subapp is not None:
return
# register zmq IOLoop with tornado
zmq_ioloop.install()
self.init_blackhole()
self.init_connection_file()
self.init_poller()
self.init_sockets()
self.init_heartbeat()
# writing/displaying connection info must be *after* init_sockets/heartbeat
self.write_connection_file()
# Log connection info after writing connection file, so that the connection
# file is definitely available at the time someone reads the log.
self.log_connection_info()
self.init_io()
self.init_signal()
self.init_kernel()
# shell init steps
self.init_path()
self.init_shell()
if self.shell:
self.init_gui_pylab()
self.init_extensions()
self.init_code()
# flush stdout/stderr, so that anything written to these streams during
# initialization do not get associated with the first execution request
sys.stdout.flush()
sys.stderr.flush()
def start(self):
if self.subapp is not None:
return self.subapp.start()
if self.poller is not None:
self.poller.start()
self.kernel.start()
try:
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
pass
launch_new_instance = YAPKernelApp.launch_instance
def main():
"""Run an IPKernel as an application"""
app = YAPKernelApp.instance()
app.initialize()
app.start()
if __name__ == '__main__':
main()

View File

@ -21,8 +21,9 @@ kernel_json = {
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class YAPKernel(IPythonKernel):
implementation = 'MetaKernel YAP'
implementation = 'YAP Kernel'
implementation_version = '1.0'
language = 'text'
language_version = '0.1'
@ -41,10 +42,14 @@ class YAPKernel(IPythonKernel):
}
def init_yap(self, **kwargs):
# Signal handlers are inherited by forked processes, and we can't easily
# reset it from the subprocess. Since kernelapp ignores SIGINT except in
# message handlers, we need to temporarily reset the SIGINT handler here
# so that yap and its children are interruptible.
# Signal handlers are inherited by
# forked processes,
# and we can't easily
# reset it from the subprocess. Since kernelapp
# ignores SIGINT except in
# message handlers, we need to temporarily
# reset the SIGINT handler
# here so that yap and its children are interruptible.
sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
self.engine = yap.YAPEngine()
@ -64,14 +69,13 @@ class YAPKernel(IPythonKernel):
def get_usage(self):
return "This is the YAP kernel."
def yap_run_cell(self, s, store_history=False, silent=False, shell_futures=True):
def yap_run_cell(self, s, store_history=False, silent=False,
shell_futures=True):
if not self.q:
self.q = self.engine.query(s)
if self.q.next():
myvs = self.q.namedVarsCopy()
wrote = False
if myvs:
i = 0
for peq in myvs:
@ -84,7 +88,7 @@ class YAPKernel(IPythonKernel):
else:
i = bind.numberVars(i, True)
print(name.text() + " = " + bind.text())
wrote = True
else:
print("yes")
if self.q.deterministic():
self.closeq()

View File

@ -1,3 +1,4 @@
import yap
import sys
@ -19,10 +20,19 @@ class T(tuple):
return str(self.name) + str(self.tuple)
def query_prolog(engine, s):
def answer( q ):
try:
return q.next()
except Exception as e:
print( e.args[1] )
return False
q = engine.query(s)
ask = True
while q.next():
while answer(q):
vs = q.namedVarsCopy()
if vs:
i = 0
@ -75,8 +85,9 @@ def live():
except:
print("Unexpected error:", sys.exc_info()[0])
raise
engine.close()
#
# initialize engine
# engine = yap.YAPEngine();
# engine = yap.YAPEngine(yap.YAPParams());
live()

View File

@ -1,19 +1,15 @@
# This is a CMake example for Python and Java
INCLUDE(UseSWIG)
INCLUDE(UseJava)
SET(CMAKE_SWIG_FLAGS -package pt.up.yap.lib)
SET(SWIG_SOURCES
../yap.i
)
# set(ANDROID_SO_OUTDIR ${libdir})
# set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}/android/yaplib/build/generated/source/pt/up/yap/lib)
#set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}/derived)
SET_SOURCE_FILES_PROPERTIES(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON)
include_directories (
@ -22,55 +18,8 @@
${JNI_INCLUDE_DIRS}
)
if ( ${C_COMPILER} MATCHES "Clang")
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-prototypes")
endif()
if ( ${C_COMPILER} MATCHES "GNU")
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-declarations -Wno-strict-aliasing")
endif()
set (CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG "")
if (ANDROID)
SWIG_ADD_MODULE(YAPDroid java ${SWIG_SOURCES} )
ADD_LIBRARY( YAPAndroid OBJECT ${swig_generated_file_fullname})
else()
SWIG_LINK_LIBRARIES (YAPDroid Yap++ )
set (LIBDIR ${CMAKE_SOURCE_DIR}/YAPDroid/app/libs/${ANDROID_ABI})
add_custom_command (TARGET YAPDroid
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory ${LIBDIR}
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:YAPDroid> ${LIBDIR}
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:libYap> ${LIBDIR}
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:Yap++> ${LIBDIR}
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:Yapsqlite3> ${LIBDIR}
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:utf8proc> ${LIBDIR}
COMMAND ${CMAKE_COMMAND} -E copy ${GMP_LIBRARIES} ${LIBDIR}
DEPENDS YAPDroid
)
endif()
# set( LIBDIR ${CMAKE_SOURCE_DIR}/YAPDroid/app/src/main/jniLibs/${ANDROID_ABI})
# add_custom_command(TARGET YAPDroid
# COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_SOURCE_DIR}/YAPDroid/app/src/main/java/pt/up/yap/lib
# COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SWIG_OUTDIR} ${CMAKE_SOURCE_DIR}/YAPDroid/app/src/main/java/pt/up/yap/lib
# COMMAND ${CMAKE_COMMAND} -E make_directory ${LIBDIR}
# COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:YAPDroid> ${LIBDIR}
# COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:libYap> ${LIBDIR}
# COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:Yap++> ${LIBDIR}
# COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:Yapsqlite3> ${LIBDIR}
# COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:utf8proc> ${LIBDIR}
# COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_SOURCE_DIR}/YAPDroid/app/src/main/java/org/sqlite/database
# COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/packages/myddas/sqlite3/Android/src/org/sqlite/database
# ${CMAKE_SOURCE_DIR}/android/app/src/main/java/org/sqlite/database
# POST_BUILD
# )
install(TARGETS YAPDroid
LIBRARY DESTINATION ${dlls}
ARCHIVE DESTINATION ${dlls}
add_custom_command (OUTPUT ${SWIG_CXX}
COMMAND ${SWIG} -java -outdir ${CMAKE_CURRENT_BINARY_DIR} -c++ -addextern -I${CMAKE_SOURCE_DIR}/CXX ${SWIG_SOURCES} -o ${SWIG_CXX}
${SWIG_SOURCES}
)

View File

@ -10,10 +10,8 @@
class YAPPredicate;
class YAPEngine;
#define arity_t uintptr_t
#ifdef SWIGPYTHON
%typemap(out) YAPTerm {
@ -21,9 +19,7 @@ class YAPEngine;
return NULL;
}
}
%extend(out) YAPTerm {
YAPTerm & __getitem__ (size_t i) {
Term t0 = $self->term();
%extend(out) YAPTerm{YAPTerm & __getitem__(size_t i){Term t0 = $self->term();
if (IsApplTerm(t0)) {
Functor f = FunctorOfTerm(t0);
@ -37,7 +33,6 @@ class YAPEngine;
}
return *new YAPTerm();
}
}
%typemap(out) YAPIntegerTerm {
@ -68,7 +63,6 @@ class YAPEngine;
}
}
// translate lists as Python Lists
// Python symbols
// Everthing else let wrapped.
@ -89,46 +83,239 @@ class YAPEngine;
return list;
}
%exception YAPPredicate {
try {
$action
} catch (...) {
PyErr_SetString(PyExc_SyntaxError, "syntax error");
return NULL;
}
}
#endif
%exception query {
try {
$action
}
catch (YAPError YAP_SYMTAX_ERROR) {
SWIG_exception(SWIG_SyntaxError,"Syntax Error exception");
}
catch (...) {
SWIG_exception(SWIG_RuntimeError,"Unknown exception");
}
}
// Language independent exception handler
%exception next {
try {
$action
} catch (YAPError &e) {
yap_error_number en = e.getID();
PyObject *pyerr = PyExc_RuntimeError;
LOCAL_Error_TYPE = YAP_NO_ERROR;
switch (e.getErrorClass()) {
case YAPC_NO_ERROR:
break;
/// bad domain, "first argument often is the predicate.
case DOMAIN_ERROR: {
switch (en) {
case DOMAIN_ERROR_OUT_OF_RANGE:
case DOMAIN_ERROR_NOT_LESS_THAN_ZERO:
pyerr = PyExc_IndexError;
break;
case DOMAIN_ERROR_CLOSE_OPTION:
case DOMAIN_ERROR_ENCODING:
case DOMAIN_ERROR_PROLOG_FLAG:
case DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION:
case DOMAIN_ERROR_READ_OPTION:
case DOMAIN_ERROR_SET_STREAM_OPTION:
pyerr = PyExc_KeyError;
break;
case DOMAIN_ERROR_FILE_ERRORS:
case DOMAIN_ERROR_FILE_TYPE:
case DOMAIN_ERROR_IO_MODE:
case DOMAIN_ERROR_SOURCE_SINK:
case DOMAIN_ERROR_STREAM_POSITION:
pyerr = PyExc_IOError;
break;
default:
pyerr = PyExc_ValueError;
}
catch (...) {
SWIG_exception(SWIG_RuntimeError,"Unknown exception");
} break;
/// bad arithmetic
case EVALUATION_ERROR: {
switch (en) {
case EVALUATION_ERROR_FLOAT_OVERFLOW:
case EVALUATION_ERROR_INT_OVERFLOW:
pyerr = PyExc_OverflowError;
break;
case EVALUATION_ERROR_FLOAT_UNDERFLOW:
case EVALUATION_ERROR_UNDERFLOW:
case EVALUATION_ERROR_ZERO_DIVISOR:
pyerr = PyExc_ArithmeticError;
break;
default:
pyerr = PyExc_RuntimeError;
}
} break;
/// missing object (I/O mostly)
case EXISTENCE_ERROR:
pyerr = PyExc_NotImplementedError;
break;
/// should be bound
case INSTANTIATION_ERROR_CLASS:
pyerr = PyExc_RuntimeError;
break;
/// bad access, I/O
case PERMISSION_ERROR: {
switch (en) {
case PERMISSION_ERROR_INPUT_BINARY_STREAM:
case PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM:
case PERMISSION_ERROR_INPUT_STREAM:
case PERMISSION_ERROR_INPUT_TEXT_STREAM:
case PERMISSION_ERROR_OPEN_SOURCE_SINK:
case PERMISSION_ERROR_OUTPUT_BINARY_STREAM:
case PERMISSION_ERROR_REPOSITION_STREAM:
case PERMISSION_ERROR_OUTPUT_STREAM:
case PERMISSION_ERROR_OUTPUT_TEXT_STREAM:
pyerr = PyExc_OverflowError;
break;
default:
pyerr = PyExc_RuntimeError;
}
} break;
/// something that could not be represented into a type
case REPRESENTATION_ERROR:
pyerr = PyExc_RuntimeError;
break;
/// not enough ....
case RESOURCE_ERROR:
pyerr = PyExc_RuntimeError;
break;
/// bad text
case SYNTAX_ERROR_CLASS:
pyerr = PyExc_SyntaxError;
break;
/// OS or internal
case SYSTEM_ERROR_CLASS:
pyerr = PyExc_RuntimeError;
break;
/// bad typing
case TYPE_ERROR:
pyerr = PyExc_TypeError;
break;
/// should be unbound
case UNINSTANTIATION_ERROR_CLASS:
pyerr = PyExc_RuntimeError;
break;
/// escape hatch
default:
break;
}
PyErr_SetString(pyerr, e.text());
}
}
#else
// Language independent exception handler
%include exception.i
%exception {
try {
$action
} catch (YAPError e) {
yap_error_number en = e.getID();
LOCAL_ERROR_Type = YAP_NO_ERROR;
switch (e.getErrorClass()) {
case YAPC_NO_ERROR:
break;
/// bad domain, "first argument often is the predicate.
case DOMAIN_ERROR: {
switch (en) {
case DOMAIN_ERROR_OUT_OF_RANGE:
case DOMAIN_ERROR_NOT_LESS_THAN_ZERO:
SWIG_exception(SWIG_IndexError, e.text());
break;
case DOMAIN_ERROR_CLOSE_OPTION:
case DOMAIN_ERROR_ENCODING:
case DOMAIN_ERROR_PROLOG_FLAG:
case DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION:
case DOMAIN_ERROR_READ_OPTION:
case DOMAIN_ERROR_SET_STREAM_OPTION:
SWIG_exception(SWIG_AttributeError, e.text());
break;
case DOMAIN_ERROR_FILE_ERRORS:
case DOMAIN_ERROR_FILE_TYPE:
case DOMAIN_ERROR_IO_MODE:
case DOMAIN_ERROR_SOURCE_SINK:
case DOMAIN_ERROR_STREAM_POSITION:
SWIG_exception(SWIG_IOError, e.text());
break;
default:
SWIG_exception(SWIG_ValueError, e.text());
}
} break;
/// bad arithmetic
case EVALUATION_ERROR: {
switch (en) {
case EVALUATION_ERROR_FLOAT_OVERFLOW:
case EVALUATION_ERROR_FLOAT_UNDERFLOW:
case EVALUATION_ERROR_INT_OVERFLOW:
case EVALUATION_ERROR_UNDERFLOW:
SWIG_exception(SWIG_OverflowError, e.text());
break;
case EVALUATION_ERROR_ZERO_DIVISOR:
SWIG_exception(SWIG_DivisionByZero, e.text());
break;
default:
SWIG_exception(SWIG_RuntimeError, e.text());
}
} break;
/// missing object (I/O mostly)
case EXISTENCE_ERROR:
SWIG_exception(SWIG_RuntimeError, e.text());
break;
/// should be bound
case INSTANTIATION_ERROR_CLASS:
SWIG_exception(SWIG_RuntimeError, e.text());
break;
/// bad access, I/O
case PERMISSION_ERROR: {
switch (en) {
case PERMISSION_ERROR_INPUT_BINARY_STREAM:
case PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM:
case PERMISSION_ERROR_INPUT_STREAM:
case PERMISSION_ERROR_INPUT_TEXT_STREAM:
case PERMISSION_ERROR_OPEN_SOURCE_SINK:
case PERMISSION_ERROR_OUTPUT_BINARY_STREAM:
case PERMISSION_ERROR_REPOSITION_STREAM:
case PERMISSION_ERROR_OUTPUT_STREAM:
case PERMISSION_ERROR_OUTPUT_TEXT_STREAM:
SWIG_exception(SWIG_OverflowError, e.text());
break;
default:
SWIG_exception(SWIG_RuntimeError, e.text());
}
} break;
/// something that could not be represented into a type
case REPRESENTATION_ERROR:
SWIG_exception(SWIG_RuntimeError, e.text());
break;
/// not enough ....
case RESOURCE_ERROR:
SWIG_exception(SWIG_RuntimeError, e.text());
break;
/// bad text
case SYNTAX_ERROR_CLASS:
SWIG_exception(SWIG_SyntaxError, e.text());
break;
/// OS or internal
case SYSTEM_ERROR_CLASS:
SWIG_exception(SWIG_RuntimeError, e.text());
break;
/// bad typing
case TYPE_ERROR:
SWIG_exception(SWIG_TypeError, e.text());
break;
/// should be unbound
case UNINSTANTIATION_ERROR_CLASS:
SWIG_exception(SWIG_RuntimeError, e.text());
break;
/// escape hatch
default:
break;
}
}
}
#endif
%{
/* Put header files here or function declarations like below */
#define YAP_CPP_INTERFACE 1
#include "yapi.hh"
extern "C" {
@ -137,17 +324,16 @@ class YAPEngine;
#define Yap_regp regcache
#endif
// we cannot consult YapInterface.h, that conflicts with what we declare, though
// we cannot consult YapInterface.h, that conflicts with what we
// declare, though
// it shouldn't
}
%}
/* turn on director wrapping Callback */
%feature("director") YAPCallback;
// %include "yapi.hh"
%include "yapa.hh"
@ -160,20 +346,6 @@ class YAPEngine;
%include "yapq.hh"
#ifdef SWIGJAVA
%javaexception("java.text.ParseException") YAPPredicate {
try {
$action
} catch (YAPError::SYNTAX_ERROR &e) {
jclass clazz = jenv->FindClass("java/text/ParseException");
jenv->ThrowNew(clazz, "Syntax error");
return $null;
}
}
#endif
%init %{
#ifdef SWIGPYTHON
init_python();

View File

@ -3,36 +3,39 @@ set(PL_SOURCES
arith.yap
arithpreds.yap
arrays.yap
attributes.yap
atoms.yap
attributes.yap
boot.yap
bootlists.yap
bootutils.yap
callcount.yap
checker.yap
consult.yap
control.yap
corout.yap
debug.yap
dbload.yap
debug.yap
depth_bound.yap
dialect.yap
directives.yap
eam.yap
eval.yap
error.yap
errors.yap
eval.yap
flags.yap
grammar.yap
ground.yap
hacks.yap
init.yap
listing.yap
bootlists.yap
load_foreign.yap
messages.yap
meta.yap
modules.yap
newmod.yap
os.yap
pathconf.yap
pl
preddecls.yap
preddyns.yap
preds.yap
@ -43,20 +46,23 @@ set(PL_SOURCES
setof.yap
signals.yap
sort.yap
spy.yap
statistics.yap
strict_iso.yap
swi.yap
tabling.yap
threads.yap
udi.yap
undefined.yap
utils.yap
swi.yap
yapor.yap
yio.yap
)
if (NOT ANDROID)
if (ANDROID)
file(INSTALL ${PL_SOURCES} DESTINATION ${libpl}/pl)
else()
add_custom_target (${YAP_STARTUP} ALL SOURCES ${PL_SOURCES} ${YAPOS_PL_SOURCES} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )
# Create a startup.yss on the top directory.
@ -73,7 +79,7 @@ install (FILES ${CMAKE_TOP_BINARY_DIR}/${YAP_STARTUP}
)
endif (NOT ANDROID)
endif (ANDROID)
install (FILES ${PL_SOURCES}

View File

@ -107,6 +107,7 @@ system_error(Type,Goal,Culprit) :-
fail.
'$LoopError'(_, _) :-
flush_output,
'$close_error',
fail.
'$process_error'('$forward'(Msg), _) :-
@ -114,7 +115,6 @@ system_error(Type,Goal,Culprit) :-
throw( '$forward'(Msg) ).
'$process_error'('$abort', Level) :-
!,
'$process_error'(abort, Level).
'$process_error'(abort, Level) :-
!,
(

View File

@ -405,6 +405,8 @@ o:p(B) :- n:g, X is 2+3, call(B).
'$build_up'(HM, NH, SM, B1, (NH :- B1), BO, ( NH :- BO)) :- HM == SM, !.
'$build_up'(HM, NH, _SM, B1, (NH :- B1), BO, ( HM:NH :- BO)) :- !.
'$expand_clause_body'(V, _NH1, _HM1, _SM, M, call(M:V), call(M:V) ) :-
var(V), !.
'$expand_clause_body'(true, _NH1, _HM1, _SM, _M, true, true ) :- !.
'$expand_clause_body'(B, H, HM, SM, M, B1, BO ) :-
'$module_u_vars'(HM , H, UVars), % collect head variables in

View File

@ -37,7 +37,12 @@ set (LIBRARY_PL
)
if (ANDROID)
file(INSTALL ${LIBRARY_PL} DESTINATION ${libpl})
else()
install(FILES ${LIBRARY_PL}
DESTINATION ${libpl}
)
endif()