Merge remote-tracking branch 'origin/master'

This commit is contained in:
Vítor Santos Costa 2018-09-27 18:28:40 +01:00
commit cbc90a8293
129 changed files with 5907 additions and 17491 deletions

View File

@ -152,7 +152,6 @@ Yap_AtomInUse(const char *atom) { /* lookup atom in atom table */
uint64_t hash;
const unsigned char *p;
Atom a, na = NIL;
AtomEntry *ae;
size_t sz = AtomHashTableSize;
/* compute hash */
@ -165,7 +164,6 @@ Yap_AtomInUse(const char *atom) { /* lookup atom in atom table */
a = HashChain[hash].Entry;
/* search atom in chain */
na = SearchAtom(p, a);
ae = RepAtom(na);
if (na != NIL ) {
READ_UNLOCK(HashChain[hash].AERWLock);
return (na);
@ -211,7 +209,11 @@ LookupAtom(const unsigned char *atom) { /* lookup atom in atom table */
}
#endif
/* add new atom to start of chain */
sz = strlen((const char *)atom);
if (atom[0] == '\0') {
sz = YAP_ALIGN;
} else {
sz = strlen((const char *)atom);
}
size_t asz = (sizeof *ae) + ( sz+1);
ae = malloc(asz);
if (ae == NULL) {
@ -249,8 +251,8 @@ Atom Yap_LookupAtomWithLength(const char *atom,
return NIL;
memmove(ptr, atom, len0);
ptr[len0] = '\0';
at = LookupAtom(ptr);
Yap_FreeCodeSpace(ptr);
at = LookupAtom(ptr);
Yap_FreeCodeSpace(ptr);
return at;
}

View File

@ -42,6 +42,12 @@ static char SccsId[] = "%W% %G%";
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#if HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
@ -383,6 +389,17 @@ void Yap_InitHeap(void *heap_addr) {
HeapMax = 0;
}
// get an approximation to total memory data-base size.
size_t Yap_HeapUsed(void)
{
#if HAVE_MALLINFO
struct mallinfo mi = mallinfo();
return mi.uordblks - (LOCAL_TrailTop-LOCAL_GlobalBase);
#else
return Yap_ClauseSpace+Yap_IndexSpace_Tree+Yap_LUClauseSpace+Yap_LUIndexSpace_CP;
#endif
}
static void InitExStacks(int wid, int Trail, int Stack) {
CACHE_REGS
UInt pm, sa;

View File

@ -112,6 +112,7 @@ static char SccsId[] = "%W% %G%";
#include "Yatom.h"
#include "YapHeap.h"
#include "YapEval.h"
#include "alloc.h"
@ -172,9 +173,11 @@ eval0(Int fi) {
}
case op_heapused:
/// - heapused
/// Heap (data-base) space used, in bytes.
/// Heap (data-base) space used, in bytes. In fact YAP either reports
/// the total memory malloced, or the amount of allocated space in
/// predicates.
///
RINT(HeapUsed);
RINT(Yap_HeapUsed());
case op_localsp:
/// - local
/// Local stack in use, in bytes

View File

@ -1,21 +1,19 @@
/******************************************************************""*******
* *
* YAP Prolog *
* *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 *
* *
**************************************************************************
* *
* File: arrays.c *
* Last rev: *
* mods: *
* comments: Array Manipulation Routines *
* *
*************************************************************************/
* *
* YAP Prolog *
* *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 *
* *
**************************************************************************
* *
* File: arrays.c * Last rev:
** mods: * comments: Array Manipulation Routines *
* *
*************************************************************************/
/**
/**
@file arrays.c
@ -106,9 +104,9 @@ The following predicates manipulate arrays:
*/
#include "Yap.h"
#include "YapEval.h"
#include "Yatom.h"
#include "clause.h"
#include "YapEval.h"
#include "heapgc.h"
#if HAVE_ERRNO_H
#include <errno.h>
@ -373,7 +371,7 @@ static ArrayEntry *GetArrayEntry(Atom at, int owner) {
#if THREADS
&& pp->owner_id != worker_id
#endif
)
)
pp = RepArrayProp(pp->NextOfPE);
READ_UNLOCK(ae->ARWLock);
return pp;
@ -986,7 +984,7 @@ restart:
#if THREADS
&& ((ArrayEntry *)pp)->owner_id != worker_id
#endif
)
)
pp = RepProp(pp->NextOfPE);
if (EndOfPAEntr(pp)) {
if (HR + 1 + size > ASP - 1024) {
@ -1025,22 +1023,49 @@ restart:
return (FALSE);
}
#define CREATE_ARRAY_DEFS() \
PAR("type", isatom, CREATE_ARRAY_TYPE), \
PAR("address", filler, CREATE_ARRAY_ADDRESS), \
PAR("int", filler, CREATE_ARRAY_INT), \
PAR("dbref", filler, CREATE_ARRAY_DBREF), \
PAR("float", filler, CREATE_ARRAY_FLOAT), \
PAR("ptr", filler, CREATE_ARRAY_PTR), \
PAR("atom", filler, CREATE_ARRAY_ATOM), \
PAR("char", filler, CREATE_ARRAY_CHAR), \
PAR("unsigned_char", filler, CREATE_ARRAY_UNSIGNED_CHAR), \
PAR("term", filler, CREATE_ARRAY_TERM), \
PAR("nb_term", filler, CREATE_ARRAY_NB_TERM)
#define PAR(x, y, z) z
typedef enum create_array_enum_choices {
CREATE_ARRAY_DEFS()
} create_array_choices_t;
#undef PAR
#define PAR(x, y, z) \
{ x, y, z }
static const param_t create_array_defs[] = {CREATE_ARRAY_DEFS()};
#undef PAR
/* create an array (+Name, + Size, +Props) */
static Int
/** @pred static_array(+ _Name_, + _Size_, + _Type_)
/** @pred static_array(+ _Name_, + _Size_, + _Type_)
Create a new static array with name _Name_. Note that the _Name_
must be an atom (named array). The _Size_ must evaluate to an
integer. The _Type_ must be bound to one of types mentioned
previously.
*/
create_static_array(USES_REGS1) {
Create a new static array with name _Name_. Note that the _Name_
must be an atom (named array). The _Size_ must evaluate to an
integer. The _Type_ must be bound to one of types mentioned
previously.
*/
static Int create_static_array(USES_REGS1) {
Term ti = Deref(ARG2);
Term t = Deref(ARG1);
Term tprops = Deref(ARG3);
Int size;
static_array_types props;
void *address = NULL;
if (IsVarTerm(ti)) {
Yap_Error(INSTANTIATION_ERROR, ti, "create static array");
@ -1055,40 +1080,62 @@ static Int
return (FALSE);
}
}
if (IsVarTerm(tprops)) {
Yap_Error(INSTANTIATION_ERROR, tprops, "create static array");
return (FALSE);
} else if (IsAtomTerm(tprops)) {
char *atname = (char *)RepAtom(AtomOfTerm(tprops))->StrOfAE;
if (!strcmp(atname, "int"))
props = array_of_ints;
else if (!strcmp(atname, "dbref"))
props = array_of_dbrefs;
else if (!strcmp(atname, "float"))
props = array_of_doubles;
else if (!strcmp(atname, "ptr"))
props = array_of_ptrs;
else if (!strcmp(atname, "atom"))
props = array_of_atoms;
else if (!strcmp(atname, "char"))
props = array_of_chars;
else if (!strcmp(atname, "unsigned_char"))
props = array_of_uchars;
else if (!strcmp(atname, "term"))
props = array_of_terms;
else if (!strcmp(atname, "nb_term"))
props = array_of_nb_terms;
else {
Yap_Error(DOMAIN_ERROR_ARRAY_TYPE, tprops, "create static array");
return (FALSE);
xarg *args =
Yap_ArgListToVector(tprops, create_array_defs, CREATE_ARRAY_NB_TERM,
DOMAIN_ERROR_CREATE_ARRAY_OPTION);
if (args == NULL) {
if (LOCAL_Error_TYPE != YAP_NO_ERROR) {
Yap_Error(LOCAL_Error_TYPE, tprops, NULL);
}
} else {
Yap_Error(TYPE_ERROR_ATOM, tprops, "create static array");
return (FALSE);
return false;
}
if (args[CREATE_ARRAY_TYPE].used) {
tprops = args[CREATE_ARRAY_TYPE].tvalue;
{
char *atname = (char *)RepAtom(AtomOfTerm(tprops))->StrOfAE;
if (!strcmp(atname, "int"))
props = array_of_ints;
else if (!strcmp(atname, "dbref"))
props = array_of_dbrefs;
else if (!strcmp(atname, "float"))
props = array_of_doubles;
else if (!strcmp(atname, "ptr"))
props = array_of_ptrs;
else if (!strcmp(atname, "atom"))
props = array_of_atoms;
else if (!strcmp(atname, "char"))
props = array_of_chars;
else if (!strcmp(atname, "unsigned_char"))
props = array_of_uchars;
else if (!strcmp(atname, "term"))
props = array_of_terms;
else if (!strcmp(atname, "nb_term"))
props = array_of_nb_terms;
}
}
if (args[CREATE_ARRAY_ADDRESS].used) {
address = AddressOfTerm(args[CREATE_ARRAY_ADDRESS].tvalue);
}
if (args[CREATE_ARRAY_INT].used)
props = array_of_ints;
if (args[CREATE_ARRAY_DBREF].used)
props = array_of_dbrefs;
if (args[CREATE_ARRAY_FLOAT].used)
props = array_of_doubles;
if (args[CREATE_ARRAY_PTR].used)
props = array_of_ptrs;
if (args[CREATE_ARRAY_ATOM].used)
props = array_of_atoms;
if (args[CREATE_ARRAY_CHAR].used)
props = array_of_chars;
if (args[CREATE_ARRAY_UNSIGNED_CHAR].used)
props = array_of_uchars;
if (args[CREATE_ARRAY_TERM].used)
props = array_of_terms;
if (args[CREATE_ARRAY_NB_TERM].used)
props = array_of_nb_terms;
StaticArrayEntry *pp;
StaticArrayEntry *pp;
if (IsVarTerm(t)) {
Yap_Error(INSTANTIATION_ERROR, t, "create static array");
return (FALSE);
@ -1104,9 +1151,9 @@ static Int
app = (ArrayEntry *)pp;
if (EndOfPAEntr(pp) || pp->ValueOfVE.ints == NULL) {
pp = CreateStaticArray(ae, size, props, NULL, pp PASS_REGS);
pp = CreateStaticArray(ae, size, props, address, pp PASS_REGS);
if (pp == NULL || pp->ValueOfVE.ints == NULL) {
return TRUE;
return TRUE;
}
} else if (ArrayIsDynamic(app)) {
if (IsVarTerm(app->ValueOfVE) && IsUnboundVar(&app->ValueOfVE)) {
@ -1115,24 +1162,25 @@ static Int
Yap_Error(PERMISSION_ERROR_CREATE_ARRAY, t,
"cannot create static array over dynamic array");
}
} else {
} else {
if (pp->ArrayType != props) {
Yap_Error(TYPE_ERROR_ATOM, t, "create static array %d/%d %d/%d", pp->ArrayEArity,size,pp->ArrayType,props);
pp = NULL;
Yap_Error(TYPE_ERROR_ATOM, t, "create static array %d/%d %d/%d",
pp->ArrayEArity, size, pp->ArrayType, props);
pp = NULL;
} else {
AllocateStaticArraySpace(pp, props, pp->ValueOfVE.ints, size PASS_REGS);
AllocateStaticArraySpace(pp, props, pp->ValueOfVE.ints, size PASS_REGS);
}
}
WRITE_UNLOCK(ae->ARWLock);
if (!pp) {
if (!pp) {
return false;
}
return true;
}
return true;
}
return false;
}
/// create a new vectir in a given name Name. If one exists, destroy prrexisting
/// create a new vector in a given name Name. If one exists, destroy prrexisting
/// onr
StaticArrayEntry *Yap_StaticVector(Atom Name, size_t size,
static_array_types props) {

View File

@ -326,7 +326,7 @@ restart_aux:
return false;
}
// verify if an atom, int, float or bi§gnnum
NewT = Yap_AtomicToListOfCodes(t1 PASS_REGS);
NewT = Yap_AtomSWIToListOfCodes(t1 PASS_REGS);
if (NewT) {
pop_text_stack(l);
return Yap_unify(NewT, ARG2);

View File

@ -193,7 +193,7 @@ static void WakeAttVar(CELL *pt1, CELL reg2 USES_REGS) {
if (!IsVarTerm(attv->Value) || !IsUnboundVar(&attv->Value)) {
/* oops, our goal is on the queue to be woken */
if (!Yap_unify(attv->Value, reg2)) {
AddFailToQueue(PASS_REGS1);
AddFailToQueue(PASS_REGS1);
}
return;
}

View File

@ -1801,67 +1801,16 @@ X_API bool YAP_RetryGoal(YAP_dogoalinfo *dgi) {
return out;
}
X_API bool YAP_LeaveGoal(bool successful, YAP_dogoalinfo *dgi) {
CACHE_REGS
choiceptr myB, handler;
// fprintf(stderr,"LeaveGoal success=%d: H=%d ENV=%p B=%ld myB=%ld TR=%d P=%p CP=%p Slots=%d\n", successful,HR-H0,LCL0-ENV,LCL0-(CELL*)B,dgi->b0,(CELL*)TR-LCL0, P, CP, LOCAL_CurSlot);
BACKUP_MACHINE_REGS();
myB = (choiceptr)(LCL0 - dgi->b0);
handler = B;
while (handler
//&& LOCAL_CBorder > LCL0 - (CELL *)handler
//&& handler->cp_ap != NOCODE
&& handler->cp_b != NULL
&& handler != myB
) {
handler->cp_ap = TRUSTFAILCODE;
handler = handler->cp_b;
}
if (LOCAL_PrologMode & AsyncIntMode) {
Yap_signal(YAP_FAIL_SIGNAL);
}
B = handler;
if (successful) {
Yap_TrimTrail();
CP = dgi->cp;
P = dgi->p;
} else {
Yap_exec_absmi(true, YAP_EXEC_ABSMI);
LOCAL_CurSlot = dgi->CurSlot;
ENV = YENV = B->cp_env;
HR = B->cp_h;
TR = B->cp_tr;
// use the current choicepoint
// B=B->cp_b;
ASP=(CELL*)B;
}
RECOVER_MACHINE_REGS();
// fprintf(stderr,"LeftGoal success=%d: H=%d ENV=%p B=%d TR=%d P=%p CP=%p Slots=%d\n", successful,HR-H0,LCL0-ENV,LCL0-(CELL*)B,(CELL*)TR-LCL0, P, CP, LOCAL_CurSlot);
return TRUE;
}
X_API Int YAP_RunGoal(Term t) {
CACHE_REGS
Term out;
yamop *old_CP = CP;
yhandle_t cslot = LOCAL_CurSlot;
BACKUP_MACHINE_REGS();
LOCAL_AllowRestart = FALSE;
LOCAL_PrologMode = UserMode;
out = Yap_RunTopGoal(t, true);
LOCAL_PrologMode = UserCCallMode;
// should we catch the exception or pass it through?
// We'll pass it through
Yap_RaiseException();
if (out) {
P = (yamop *)ENV[E_CP];
static void completeInnerCall( bool on_cut, yamop *old_CP, yamop *old_P)
{
if (on_cut) {
P = old_P;
ENV = (CELL *)ENV[E_E];
CP = old_CP;
LOCAL_AllowRestart = TRUE;
// we are back to user code again, need slots */
} else {
P = old_P;
ENV = B->cp_env;
ENV = (CELL *)ENV[E_E];
CP = old_CP;
@ -1872,7 +1821,61 @@ X_API Int YAP_RunGoal(Term t) {
SET_ASP(ENV, E_CB * sizeof(CELL));
// make sure the slots are ok.
}
}
X_API bool YAP_LeaveGoal(bool successful, YAP_dogoalinfo *dgi) {
CACHE_REGS
choiceptr myB, handler;
// fprintf(stderr,"LeaveGoal success=%d: H=%d ENV=%p B=%ld myB=%ld TR=%d P=%p CP=%p Slots=%d\n", successful,HR-H0,LCL0-ENV,LCL0-(CELL*)B,dgi->b0,(CELL*)TR-LCL0, P, CP, LOCAL_CurSlot);
BACKUP_MACHINE_REGS();
myB = (choiceptr)(LCL0 - dgi->b);
if (LOCAL_PrologMode & AsyncIntMode) {
Yap_signal(YAP_FAIL_SIGNAL);
}
handler = B;
while (handler
&& LCL0-LOCAL_CBorder > (CELL *)handler
//&& handler->cp_ap != NOCODE
&& handler->cp_b != NULL
&& handler != myB
) {
if (handler < myB ) {
handler->cp_ap = TRUSTFAILCODE;
}
B = handler;
handler = handler->cp_b;
if (successful) {
Yap_TrimTrail();
} else if (!(LOCAL_PrologMode & AsyncIntMode)) {
P=FAILCODE;
Yap_exec_absmi(true, YAP_EXEC_ABSMI);
}
}
if (LOCAL_PrologMode & AsyncIntMode) {
Yap_signal(YAP_FAIL_SIGNAL);
}
P=dgi->p;
CP = dgi->cp;
RECOVER_MACHINE_REGS();
// fprintf(stderr,"LeftGoal success=%d: H=%d ENV=%p B=%d TR=%d P=%p CP=%p Slots=%d\n", successful,HR-H0,LCL0-ENV,LCL0-(CELL*)B,(CELL*)TR-LCL0, P, CP, LOCAL_CurSlot);
return TRUE;
}
X_API Int YAP_RunGoal(Term t) {
CACHE_REGS
Term out;
yhandle_t cslot = LOCAL_CurSlot;
BACKUP_MACHINE_REGS();
LOCAL_AllowRestart = FALSE;
LOCAL_PrologMode = UserMode;
out = Yap_RunTopGoal(t, true);
LOCAL_PrologMode = UserCCallMode;
// should we catch the exception or pass it through?
// We'll pass it through
RECOVER_MACHINE_REGS();
LOCAL_CurSlot = cslot;
return out;
}

289
C/cdmgr.c
View File

@ -1,4 +1,3 @@
/*************************************************************************
* *
* YAP Prolog *
@ -33,10 +32,10 @@ static char SccsId[] = "@(#)cdmgr.c 1.1 05/02/98";
#if HAVE_STRING_H
#include <string.h>
#endif
#include <Yatom.h>
#include <assert.h>
#include <heapgc.h>
#include <iopreds.h>
#include <Yatom.h>
static void retract_all(PredEntry *, int);
static void add_first_static(PredEntry *, yamop *, int);
@ -1387,7 +1386,7 @@ static void expand_consult(void) {
new_cs = new_cl + InitialConsultCapacity;
/* start copying */
memmove((void *)new_cs, (void *)LOCAL_ConsultLow,
OldConsultCapacity * sizeof(consult_obj));
OldConsultCapacity * sizeof(consult_obj));
/* copying done, release old space */
Yap_FreeCodeSpace((char *)LOCAL_ConsultLow);
/* next, set up pointers correctly */
@ -1453,33 +1452,36 @@ static int not_was_reconsulted(PredEntry *p, Term t, int mode) {
return TRUE; /* careful */
}
static yamop * addcl_permission_error(const char *file, const char *function, int lineno, AtomEntry *ap, Int Arity, int in_use) {
static yamop *addcl_permission_error(const char *file, const char *function,
int lineno, AtomEntry *ap, Int Arity,
int in_use) {
CACHE_REGS
Term culprit;
if (Arity == 0)
culprit = MkAtomTerm(AbsAtom(ap));
else
culprit = Yap_MkNewApplTerm(Yap_MkFunctor(AbsAtom(ap),Arity), Arity);
return
(in_use ?
(Arity == 0 ?
Yap_Error__(false, file, function, lineno, PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE, culprit,
"static predicate %s is in use", ap->StrOfAE)
:
Yap_Error__(false, file, function, lineno, PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE, culprit,
"static predicate %s/" Int_FORMAT " is in use", ap->StrOfAE, Arity)
)
:
(Arity == 0 ?
Yap_Error__(false, file, function, lineno, PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE, culprit,
"system predicate %s is in use", ap->StrOfAE)
:
Yap_Error__(false, file, function, lineno, PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE, culprit,
"system predicate %s/" Int_FORMAT, ap->StrOfAE, Arity)
)
);
}
Term culprit;
if (Arity == 0)
culprit = MkAtomTerm(AbsAtom(ap));
else
culprit = Yap_MkNewApplTerm(Yap_MkFunctor(AbsAtom(ap), Arity), Arity);
return (in_use
? (Arity == 0
? Yap_Error__(false, file, function, lineno,
PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE,
culprit, "static predicate %s is in use",
ap->StrOfAE)
: Yap_Error__(
false, file, function, lineno,
PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE, culprit,
"static predicate %s/" Int_FORMAT " is in use",
ap->StrOfAE, Arity))
: (Arity == 0
? Yap_Error__(false, file, function, lineno,
PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE,
culprit, "system predicate %s is in use",
ap->StrOfAE)
: Yap_Error__(false, file, function, lineno,
PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE,
culprit, "system predicate %s/" Int_FORMAT,
ap->StrOfAE, Arity)));
}
PredEntry *Yap_PredFromClause(Term t USES_REGS) {
Term cmod = LOCAL_SourceModule;
@ -1650,7 +1652,7 @@ Atom Yap_source_file_name(void) {
}
/**
* @brief we cannot add clauses to the proceduree
* @brief we cannot add clauses to the procedure
*
* @param p predicate
*
@ -1738,7 +1740,8 @@ bool Yap_addclause(Term t, yamop *cp, Term tmode, Term mod, Term *t4ref)
PELOCK(20, p);
/* we are redefining a prolog module predicate */
if (Yap_constPred(p)) {
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), Arity, FALSE);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), Arity,
FALSE);
UNLOCKPE(30, p);
return false;
}
@ -1768,7 +1771,8 @@ bool Yap_addclause(Term t, yamop *cp, Term tmode, Term mod, Term *t4ref)
disc[2] = Yap_Module_Name(p);
sc[0] = Yap_MkApplTerm(Yap_MkFunctor(AtomDiscontiguous, 3), 3, disc);
sc[1] = MkIntegerTerm(Yap_source_line_no());
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "source %s ", RepAtom(LOCAL_SourceFileName)->StrOfAE);
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "source %s ",
RepAtom(LOCAL_SourceFileName)->StrOfAE);
sc[2] = MkAtomTerm(LOCAL_SourceFileName);
sc[3] = t;
t = Yap_MkApplTerm(Yap_MkFunctor(AtomStyleCheck, 4), 4, sc);
@ -2044,7 +2048,7 @@ static Int p_compile(USES_REGS1) { /* '$compile'(+C,+Flags,+C0,-Ref) */
Yap_addclause(t, code_adr, t1, mod, &ARG5);
YAPLeaveCriticalSection();
}
if (LOCAL_ErrorMessage ) {
if (LOCAL_ErrorMessage) {
Yap_Error(LOCAL_Error_TYPE, ARG1, LOCAL_ErrorMessage);
YAPLeaveCriticalSection();
return false;
@ -2436,12 +2440,14 @@ static Int new_multifile(USES_REGS1) {
}
if (pe->PredFlags & (TabledPredFlag | ForeignPredFlags)) {
UNLOCKPE(26, pe);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__,RepAtom(at), arity, FALSE);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), arity,
FALSE);
return false;
}
if (pe->cs.p_code.NOfClauses) {
UNLOCKPE(26, pe);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__,RepAtom(at), arity, FALSE);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), arity,
FALSE);
return false;
}
pe->PredFlags &= ~UndefPredFlag;
@ -2675,7 +2681,8 @@ static Int mk_dynamic(USES_REGS1) { /* '$make_dynamic'(+P) */
(UserCPredFlag | CArgsPredFlag | NumberDBPredFlag | AtomDBPredFlag |
TestPredFlag | AsmPredFlag | CPredFlag | BinaryPredFlag)) {
UNLOCKPE(30, pe);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__,RepAtom(at), arity, FALSE);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), arity,
FALSE);
return false;
}
if (pe->PredFlags & LogUpdatePredFlag) {
@ -2688,7 +2695,8 @@ static Int mk_dynamic(USES_REGS1) { /* '$make_dynamic'(+P) */
}
if (pe->cs.p_code.NOfClauses != 0) {
UNLOCKPE(26, pe);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), arity, FALSE);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), arity,
FALSE);
return false;
}
if (pe->OpcodeOfPred == UNDEF_OPCODE) {
@ -2738,7 +2746,8 @@ static Int new_meta_pred(USES_REGS1) {
}
if (pe->cs.p_code.NOfClauses) {
UNLOCKPE(26, pe);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), arity, FALSE);
addcl_permission_error(__FILE__, __FUNCTION__, __LINE__, RepAtom(at), arity,
FALSE);
return false;
}
pe->PredFlags |= MetaPredFlag;
@ -3082,133 +3091,101 @@ static Int p_clean_up_dead_clauses(USES_REGS1) {
void Yap_HidePred(PredEntry *pe) {
if (pe->PredFlags & HiddenPredFlag)
return;
pe->PredFlags |= (HiddenPredFlag | NoSpyPredFlag | NoTracePredFlag);
}
if (pe->NextOfPE) {
UInt hash = PRED_HASH(pe->FunctorOfPred, CurrentModule, PredHashTableSize);
READ_LOCK(PredHashRWLock);
PredEntry *p, **op = PredHash+hash;
p = *op;
static Int /* $system_predicate(P) */
p_stash_predicate(USES_REGS1) {
PredEntry *pe;
Term t1 = Deref(ARG1);
Term mod = Deref(ARG2);
restart_system_pred:
if (IsVarTerm(t1))
return (FALSE);
if (IsAtomTerm(t1)) {
Atom a = AtomOfTerm(t1);
pe = RepPredProp(Yap_GetPredPropByAtom(a, mod));
} else if (IsApplTerm(t1)) {
Functor funt = FunctorOfTerm(t1);
if (IsExtensionFunctor(funt)) {
return (FALSE);
}
if (funt == FunctorModule) {
Term nmod = ArgOfTerm(1, t1);
if (IsVarTerm(nmod)) {
Yap_Error(INSTANTIATION_ERROR, ARG1, "hide_predicate/1");
return (FALSE);
while (p) {
if (p == pe) {
*op = p->NextPredOfHash;
break;
}
if (!IsAtomTerm(nmod)) {
Yap_Error(TYPE_ERROR_ATOM, ARG1, "hide_predicate/1");
return (FALSE);
}
t1 = ArgOfTerm(2, t1);
goto restart_system_pred;
op = &p->NextPredOfHash;
p = p->NextPredOfHash;
}
pe = RepPredProp(Yap_GetPredPropByFunc(funt, mod));
} else if (IsPairTerm(t1)) {
return TRUE;
} else
return FALSE;
if (EndOfPAEntr(pe))
return FALSE;
Yap_HidePred(pe);
return TRUE;
}
static Int /* $system_predicate(P) */
hide_predicate(USES_REGS1) {
PredEntry *pe;
Term t1 = Deref(ARG1);
Term mod = Deref(ARG2);
restart_system_pred:
if (IsVarTerm(t1))
return (FALSE);
if (IsAtomTerm(t1)) {
Atom a = AtomOfTerm(t1);
pe = RepPredProp(Yap_GetPredPropByAtom(a, mod));
} else if (IsApplTerm(t1)) {
Functor funt = FunctorOfTerm(t1);
if (IsExtensionFunctor(funt)) {
return (FALSE);
pe->NextPredOfHash = NULL;
}
{
Prop *op, p;
if (pe->ArityOfPE == 0) {
op = &RepAtom(AtomOfTerm((Term)(pe->FunctorOfPred)))->PropsOfAE;
} else {
op = &pe->FunctorOfPred->PropsOfFE;
}
if (funt == FunctorModule) {
Term nmod = ArgOfTerm(1, t1);
if (IsVarTerm(nmod)) {
Yap_Error(INSTANTIATION_ERROR, ARG1, "hide_predicate/1");
return (FALSE);
p = *op;
while (p) {
if (p == AbsPredProp(pe)) {
*op = p->NextOfPE;
break;
}
if (!IsAtomTerm(nmod)) {
Yap_Error(TYPE_ERROR_ATOM, ARG1, "hide_predicate/1");
return (FALSE);
}
t1 = ArgOfTerm(2, t1);
goto restart_system_pred;
op = &p->NextOfPE;
p = p->NextOfPE;
}
pe = RepPredProp(Yap_GetPredPropByFunc(funt, mod));
} else if (IsPairTerm(t1)) {
return true;
} else
return false;
if (EndOfPAEntr(pe))
return false;
pe->PredFlags |= (HiddenPredFlag | NoSpyPredFlag | NoTracePredFlag);
return true;
pe->NextOfPE = RepAtom(AtomFoundVar)->PropsOfAE;
RepAtom(AtomFoundVar)->PropsOfAE = AbsPredProp(pe);
}
{
PredEntry *p,
**op = &Yap_GetModuleEntry(Yap_Module(pe->ModuleOfPred))->PredForME;
p = *op;
while (p) {
if (p == pe) {
*op = p->NextPredOfModule;
break;
}
op = &p->NextPredOfModule;
p = p->NextPredOfModule;
}
pe->NextPredOfModule = NULL;
}
}
static Int /* $hidden_predicate(P) */
p_hidden_predicate(USES_REGS1) {
PredEntry *pe;
Term t1 = Deref(ARG1);
Term mod = Deref(ARG2);
restart_system_pred:
if (IsVarTerm(t1))
return (FALSE);
if (IsAtomTerm(t1)) {
pe = RepPredProp(Yap_GetPredPropByAtom(AtomOfTerm(t1), mod));
} else if (IsApplTerm(t1)) {
Functor funt = FunctorOfTerm(t1);
if (IsExtensionFunctor(funt)) {
return (FALSE);
}
if (funt == FunctorModule) {
Term nmod = ArgOfTerm(1, t1);
if (IsVarTerm(nmod)) {
Yap_Error(INSTANTIATION_ERROR, ARG1, "hide_predicate/1");
return (FALSE);
}
if (!IsAtomTerm(nmod)) {
Yap_Error(TYPE_ERROR_ATOM, ARG1, "hide_predicate/1");
return (FALSE);
}
t1 = ArgOfTerm(2, t1);
goto restart_system_pred;
}
pe = RepPredProp(Yap_GetPredPropByFunc(funt, mod));
} else if (IsPairTerm(t1)) {
return (TRUE);
hide_predicate(USES_REGS1) {
PredEntry *pe =
Yap_get_pred(Deref(ARG1), Deref(ARG2), "while checking for a procedure");
if (pe) {
Yap_HidePred(pe);
return true;
} else
return (FALSE);
if (EndOfPAEntr(pe))
return (FALSE);
return (pe->PredFlags & HiddenPredFlag);
return false;
}
static Int /* $hidden_predicate(P) */
stash_predicate(USES_REGS1) {
PredEntry *pe =
Yap_get_pred(Deref(ARG1), Deref(ARG2), "while checking for a procedure");
if (pe) {
pe->PredFlags |= (HiddenPredFlag | NoSpyPredFlag | NoTracePredFlag);
/*
char ns[1024];
const char *s = (pe->ModuleOfPred == PROLOG_MODULE ?
"__prolog__stash__" :
snprintf(sn,1023,"__%s__".RepAtom(AtomOfTerm( pe->ModuleOfPred ))));
pe->ModuleOfPred = MkAtomTerm(Yap_LookupAtom(s));
*/
return true;
} else
return false;
}
static Int /* $hidden_predicate(P) */
hidden_predicate(USES_REGS1) {
PredEntry *pe =
Yap_get_pred(Deref(ARG1), Deref(ARG2), "while checking for a procedure");
if (pe)
return (pe->PredFlags & HiddenPredFlag);
else
return false;
}
static Int fetch_next_lu_clause(PredEntry *pe, yamop *i_code, Term th, Term tb,
@ -4799,8 +4776,8 @@ void Yap_InitCdMgr(void) {
Yap_InitCPred("$set_pred_module", 2, p_set_pred_module, SafePredFlag);
Yap_InitCPred("$set_pred_owner", 2, p_set_pred_owner, SafePredFlag);
Yap_InitCPred("$hide_predicate", 2, hide_predicate, SafePredFlag);
Yap_InitCPred("$stash_predicate", 2, p_stash_predicate, SafePredFlag);
Yap_InitCPred("$hidden_predicate", 2, p_hidden_predicate, SafePredFlag);
Yap_InitCPred("$stash_predicate", 2, stash_predicate, SafePredFlag);
Yap_InitCPred("$hidden_predicate", 2, hidden_predicate, SafePredFlag);
Yap_InitCPred("$log_update_clause", 4, p_log_update_clause, SyncPredFlag);
Yap_InitCPred("$continue_log_update_clause", 5, p_continue_log_update_clause,
SafePredFlag | SyncPredFlag);

View File

@ -17,6 +17,7 @@
#include "absmi.h"
#include "yapio.h"
#include "YapStreams.h"
#if HAVE_STDARG_H
#include <stdarg.h>
#endif
@ -85,21 +86,24 @@ static bool setErr(const char *q, yap_error_descriptor_t *i, Term t) {
return false;
}
#define query_key_b(k, ks, q, i) \
if (strcmp(ks, q) == 0) { \
#define query_key_b(k, ks, q, i) \
if (strcmp(ks, q) == 0) { \
return i->k ? TermTrue : TermFalse; \
}
#define query_key_i(k, ks, q, i) if (strcmp(ks, q) == 0) { \
#define query_key_i(k, ks, q, i) \
if (strcmp(ks, q) == 0) { \
return MkIntegerTerm(i->k); \
}
#define query_key_s(k, ks, q, i) \
if (strcmp(ks, q) == 0 && i->k) { \
return MkAtomTerm(Yap_LookupAtom(i->k)); } else {return TermNil;}
#define query_key_s(k, ks, q, i) \
if (strcmp(ks, q) == 0 ) \
{ if (i->k) return MkAtomTerm(Yap_LookupAtom(i->k)); else return TermNil; }
#define query_key_t(k, ks, q, i) \
if (strcmp(ks, q) == 0) { \
if (i->k == NULL) return TermNil; \
Term t; if((t = Yap_BufferToTerm(i->k, TermNil) ) == 0 ) return TermNil; return t; }
static Term queryErr(const char *q, yap_error_descriptor_t *i) {
@ -333,7 +337,7 @@ bool Yap_PrintWarning(Term twarning) {
(err = LOCAL_ActiveError->errorNo)) {
fprintf(stderr, "%% Warning %s while processing error: %s %s\n",
Yap_TermToBuffer(twarning,
Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f),
Quote_illegal_f | Ignore_ops_f),
Yap_errorClassName(Yap_errorClass(err)), Yap_errorName(err));
return false;
}
@ -589,10 +593,11 @@ yap_error_descriptor_t *Yap_popErrorContext(bool mdnew, bool pass) {
// last block
LOCAL_ActiveError = ep;
if (e->errorNo && !ep->errorNo && pass) {
yap_error_descriptor_t *epp = ep->top_error;
yap_error_descriptor_t *epp = ep->top_error;
memmove(ep, e, sizeof(*e));
ep->top_error = epp;
}
free(e);
return LOCAL_ActiveError;
}
/**
@ -641,14 +646,14 @@ void Yap_ThrowExistingError(void) {
bool Yap_MkErrorRecord(yap_error_descriptor_t *r, const char *file,
const char *function, int lineno, yap_error_number type,
Term where, const char *s) {
if (!Yap_pc_add_location(r, CP, B, ENV))
Term where, const char *s) {
if (!Yap_pc_add_location(r, P, B, ENV))
Yap_env_add_location(r, CP, B, ENV, 0);
if (where == 0L || where == TermNil || type == INSTANTIATION_ERROR) {
if (where == 0L || where == TermNil) {
r->culprit = NULL;
} else {
r->culprit = Yap_TermToBuffer(
where, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f);
where, Quote_illegal_f | Ignore_ops_f);
}
if (LOCAL_consult_level > 0) {
r->prologParserFile = Yap_ConsultingFile(PASS_REGS1)->StrOfAE;
@ -661,7 +666,6 @@ bool Yap_MkErrorRecord(yap_error_descriptor_t *r, const char *file,
r->errorLine = lineno;
r->errorFunction = function;
r->errorFile = file;
Yap_prolog_add_culprit(r PASS_REGS1);
LOCAL_PrologMode |= InErrorMode;
Yap_ClearExs();
// first, obtain current location
@ -738,7 +742,7 @@ yamop *Yap_Error__(bool throw, const char *file, const char *function,
if (LOCAL_PrologMode & BootMode) {
fprintf(stderr, "%% YAP crashed while booting %s\n", tmpbuf);
} else {
Yap_detect_bug_location(P, FIND_PRED_FROM_ANYWHERE, YAP_BUF_SIZE);
Yap_output_bug_location(P, FIND_PRED_FROM_ANYWHERE, YAP_BUF_SIZE);
if (tmpbuf[0]) {
fprintf(stderr, "%% Bug found while executing %s\n", tmpbuf);
}
@ -960,7 +964,9 @@ yap_error_descriptor_t *Yap_GetException(yap_error_descriptor_t *i) {
return 0;
}
void Yap_PrintException(void) { printErr(LOCAL_ActiveError); }
void Yap_PrintException(yap_error_descriptor_t *i) {
printErr(LOCAL_ActiveError);
}
bool Yap_RaiseException(void) {
if (LOCAL_ActiveError == NULL ||
@ -1149,7 +1155,7 @@ yap_error_descriptor_t *Yap_UserError(Term t, yap_error_descriptor_t *i) {
n = t2;
}
i->errorGoal = Yap_TermToBuffer(
n, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f);
n, Quote_illegal_f | Ignore_ops_f );
}
Yap_prolog_add_culprit(i PASS_REGS);
return i;
@ -1180,22 +1186,22 @@ static Int is_callable(USES_REGS1) {
// Term Context = Deref(ARG2);
while (true) {
if (IsVarTerm(G)) {
Yap_Error(INSTANTIATION_ERROR, G, NULL);
Yap_ThrowError(INSTANTIATION_ERROR, G, NULL);
return false;
}
if (IsApplTerm(G)) {
Functor f = FunctorOfTerm(G);
if (IsExtensionFunctor(f)) {
Yap_Error(TYPE_ERROR_CALLABLE, G, NULL);
Yap_ThrowError(TYPE_ERROR_CALLABLE, G, NULL);
}
if (f == FunctorModule) {
Term tm = ArgOfTerm(1, G);
if (IsVarTerm(tm)) {
Yap_Error(INSTANTIATION_ERROR, G, NULL);
Yap_ThrowError(INSTANTIATION_ERROR, G, NULL);
return false;
}
if (!IsAtomTerm(tm)) {
Yap_Error(TYPE_ERROR_CALLABLE, G, NULL);
Yap_ThrowError(TYPE_ERROR_CALLABLE, G, NULL);
return false;
}
G = ArgOfTerm(2, G);
@ -1205,7 +1211,7 @@ static Int is_callable(USES_REGS1) {
} else if (IsPairTerm(G) || IsAtomTerm(G)) {
return true;
} else {
Yap_Error(TYPE_ERROR_CALLABLE, G, NULL);
Yap_ThrowError(TYPE_ERROR_CALLABLE, G, NULL);
return false;
}
}

View File

@ -1,4 +1,4 @@
/*************************************************************************
/*************************************************************************
* *
* YAP Prolog *
* *
@ -1615,6 +1615,8 @@ void Yap_fail_all(choiceptr bb USES_REGS) {
saved_p = P;
saved_cp = CP;
/* prune away choicepoints */
if (B == bb)
return;
while (B->cp_b && B->cp_b != bb && B->cp_ap != NOCODE) {
B = B->cp_b;
#ifdef YAPOR

View File

@ -109,6 +109,9 @@ static Int set_prolog_flag(USES_REGS1);
#include "YapLFlagInfo.h"
static Term indexer(Term inp) {
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (inp == TermOff || inp == TermSingle || inp == TermCompact ||
inp == TermMulti || inp == TermOn || inp == TermMax)
return inp;
@ -124,6 +127,9 @@ static Term indexer(Term inp) {
static bool dqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags &= ~(DBLQ_CHARS | DBLQ_CODES | DBLQ_ATOM | DBLQ_STRING);
if (IsStringTerm(t2)) {
t2 = MkStringTerm(RepAtom(AtomOfTerm(t2))->StrOfAE);
}
if (IsAtomTerm(t2)) {
if (t2 == TermString) {
new->flags |= DBLQ_STRING;
@ -162,6 +168,9 @@ static bool dqs(Term t2) {
static bool bqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags &= ~(BCKQ_CHARS | BCKQ_CODES | BCKQ_ATOM | BCKQ_STRING);
if (IsStringTerm(t2)) {
t2 = MkStringTerm(RepAtom(AtomOfTerm(t2))->StrOfAE);
}
if (IsAtomTerm(t2)) {
if (t2 == TermString) {
new->flags |= BCKQ_STRING;
@ -197,6 +206,9 @@ static bool bqs(Term t2) {
static bool sqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags &= ~(SNGQ_CHARS | SNGQ_CODES | SNGQ_ATOM | SNGQ_STRING);
if (IsStringTerm(t2)) {
t2 = MkStringTerm(RepAtom(AtomOfTerm(t2))->StrOfAE);
}
if (IsAtomTerm(t2)) {
if (t2 == TermString) {
new->flags |= SNGQ_STRING;
@ -234,6 +246,9 @@ static Term isaccess(Term inp) {
if (inp == TermReadWrite || inp == TermReadOnly)
return inp;
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (IsAtomTerm(inp)) {
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, inp,
"set_prolog_flag access in {read_write,read_only}");
@ -281,6 +296,9 @@ static Term flagscope(Term inp) {
if (inp == TermGlobal || inp == TermThread || inp == TermModule)
return inp;
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (IsAtomTerm(inp)) {
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, inp,
"set_prolog_flag access in {global,module,thread}");
@ -295,8 +313,11 @@ static bool mkprompt(Term inp) {
CACHE_REGS
if (IsVarTerm(inp)) {
return Yap_unify(inp, MkAtomTerm(Yap_LookupAtom(LOCAL_Prompt)));
}
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (!IsAtomTerm(inp)) {
if (!IsAtomTerm(inp)) {
Yap_Error(TYPE_ERROR_ATOM, inp, "set_prolog_flag");
return false;
}
@ -307,6 +328,9 @@ static bool mkprompt(Term inp) {
static bool getenc(Term inp) {
CACHE_REGS
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (!IsVarTerm(inp) && !IsAtomTerm(inp)) {
Yap_Error(TYPE_ERROR_ATOM, inp, "get_encoding");
return false;
@ -338,6 +362,9 @@ static bool typein(Term inp) {
tin = TermProlog;
return Yap_unify(inp, tin);
}
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (!IsAtomTerm(inp)) {
Yap_Error(TYPE_ERROR_ATOM, inp, "set_prolog_flag");
return false;
@ -448,6 +475,9 @@ static bool typein(Term inp) {
if (IsAtomTerm(hd)) {
do {
Term hd = HeadOfTerm(inp);
if (IsStringTerm(hd)) {
hd = MkStringTerm(RepAtom(AtomOfTerm(hd))->StrOfAE);
}
if (!IsAtomTerm(hd)) {
Yap_Error(TYPE_ERROR_TEXT, inp0, "set_prolog_flag in \"...\"");
return false;
@ -486,6 +516,10 @@ x static bool list_atom( Term inp ) {
if (IsPairTerm(inp)) {
Term hd = HeadOfTerm(inp);
do {
if (IsStringTerm(hd)) {
hd = MkStringTerm(RepAtom(AtomOfTerm(hd))->StrOfAE);
}
if (!IsAtomTerm(hd)) {
Yap_Error(TYPE_ERROR_ATOM, inp0, "set_prolog_flag in \"...\"");
return false;
@ -510,6 +544,9 @@ static Term list_option(Term inp) {
do {
Term hd = HeadOfTerm(inp);
inp = TailOfTerm(inp);
if (IsStringTerm(hd)) {
hd = MkStringTerm(RepAtom(AtomOfTerm(hd))->StrOfAE);
}
if (IsAtomTerm(hd)) {
continue;
}
@ -530,6 +567,9 @@ static Term list_option(Term inp) {
Yap_Error(TYPE_ERROR_LIST, inp0, "set_prolog_flag in [...]");
return TermZERO;
} else /* lone option */ {
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (IsAtomTerm(inp)) {
return inp;
} else if (IsApplTerm(inp)) {
@ -1035,6 +1075,9 @@ static Int current_prolog_flag2(USES_REGS1) {
return cont_yap_flag(PASS_REGS1);
}
do_cut(0);
if (IsStringTerm(tflag)) {
tflag = MkStringTerm(RepAtom(AtomOfTerm(tflag))->StrOfAE);
}
if (!IsAtomTerm(tflag)) {
Yap_Error(TYPE_ERROR_ATOM, tflag, "current_prolog_flag/3");
return (FALSE);
@ -1084,6 +1127,10 @@ bool setYapFlag(Term tflag, Term t2) {
Yap_Error(INSTANTIATION_ERROR, tflag, "yap_flag/2");
return (FALSE);
}
if (IsStringTerm(tflag)) {
tflag = MkStringTerm(RepAtom(AtomOfTerm(tflag))->StrOfAE);
}
if (IsApplTerm(tflag) && FunctorOfTerm(tflag) == FunctorModule) {
Term modt;
tflag = Yap_StripModule(tflag, &modt);
@ -1165,11 +1212,20 @@ Term getYapFlag(Term tflag) {
Yap_Error(INSTANTIATION_ERROR, tflag, "yap_flag/2");
return (FALSE);
}
if (IsStringTerm(tflag)) {
tflag = MkStringTerm(RepAtom(AtomOfTerm(tflag))->StrOfAE);
}
if (IsApplTerm(tflag) && FunctorOfTerm(tflag) == FunctorModule) {
Term modt;
tflag = Yap_StripModule(tflag, &modt);
if (IsStringTerm(tflag)) {
tflag = MkStringTerm(RepAtom(AtomOfTerm(tflag))->StrOfAE);
}
if (!isatom(tflag))
return false;
if (IsStringTerm(modt)) {
modt = MkStringTerm(RepAtom(AtomOfTerm(modt))->StrOfAE);
}
if (!isatom(modt))
return false;
return getYapFlagInModule(tflag, modt);
@ -1405,6 +1461,9 @@ static bool setInitialValue(bool bootstrap, flag_func f, const char *s,
GLOBAL_MaxPriority);
if (!t0)
return false;
if (IsStringTerm(t0)) {
t0 = MkStringTerm(RepAtom(AtomOfTerm(t0))->StrOfAE);
}
if (IsAtomTerm(t0) || IsIntTerm(t0)) {
// do yourself flags
if (t0 == MkAtomTerm(AtomQuery)) {
@ -1456,6 +1515,9 @@ do_prolog_flag_property(Term tflag,
Yap_Error(LOCAL_Error_TYPE, opts, NULL);
return false;
}
if (IsStringTerm(tflag)) {
tflag = MkStringTerm(RepAtom(AtomOfTerm(tflag))->StrOfAE);
}
if (!IsAtomTerm(tflag)) {
if (IsApplTerm(tflag) && FunctorOfTerm(tflag) == FunctorModule) {
Term modt = CurrentModule;
@ -1572,6 +1634,9 @@ static Int prolog_flag_property(USES_REGS1) { /* Init current_prolog_flag */
Term t1 = Deref(ARG1);
/* make valgrind happy by always filling in memory */
EXTRA_CBACK_ARG(2, 1) = MkIntTerm(0);
if (IsStringTerm(t1)) {
t1 = MkStringTerm(RepAtom(AtomOfTerm(t1))->StrOfAE);
}
if (IsVarTerm(t1)) {
return (cont_prolog_flag_property(PASS_REGS1));
} else {
@ -1731,7 +1796,7 @@ void Yap_InitFlags(bool bootstrap) {
Obtain the value for a YAP Prolog flag, same as current_prolog_flag/2.
*/
Yap_InitCPredBack("prolog_flag", 3, 1, current_prolog_flag, cont_yap_flag,
Yap_InitCPredBack("prolog_flag", 3, 1, prolog_flag, cont_yap_flag,
0);
Yap_InitCPredBack("yap_flag", 3, 1, yap_flag, cont_yap_flag, 0);
Yap_InitCPredBack("prolog_flag", 2, 1, current_prolog_flag2,

View File

@ -352,9 +352,9 @@ static inline void clean_dirty_tr(tr_fr_ptr TR0 USES_REGS) {
}
#define expand_stack(S0,SP,SF,TYPE) \
size_t sz = SF-S0, used = SP-S0; \
{ size_t sz = SF-S0, used = SP-S0; \
S0 = Realloc(S0, (1024+sz)*sizeof(TYPE) PASS_REGS); \
SP = S0+used; SF = S0+sz;
SP = S0+used; SF = S0+sz; }
static int copy_complex_term(register CELL *pt0, register CELL *pt0_end,
int share, int copy_att_vars, CELL *ptf,
@ -502,7 +502,7 @@ loop:
ptf++;
/* store the terms to visit */
#ifdef RATIONAL_TREES
if (to_visit + 1 >= to_visit_max) {
if (to_visit + 32 >= to_visit_max) {
expand_stack(to_visit0, to_visit, to_visit_max, struct cp_frame);
}
to_visit->start_cp = pt0;

View File

@ -984,6 +984,7 @@ void Yap_InitCPredBack_(const char *Name, arity_t Arity, arity_t Extra,
static void InitStdPreds(struct yap_boot_params *yapi)
{
CurrentModule = PROLOG_MODULE;
Yap_InitCPreds();
Yap_InitBackCPreds();
BACKUP_MACHINE_REGS();

View File

@ -283,3 +283,8 @@ void Yap_ReOpenLoadForeign(void) {
}
CurrentModule = OldModule;
}
X_API bool load_none(void)
{
return true;
}

View File

@ -836,6 +836,7 @@ static void ReadHash(FILE *stream) {
UInt sz = read_UInt(stream);
UInt nrefs = read_UInt(stream);
LogUpdClause *ncl = (LogUpdClause *)Yap_AlwaysAllocCodeSpace(sz);
Yap_LUClauseSpace += sz;
if (!ncl) {
QLYR_ERROR(OUT_OF_CODE_SPACE);
}
@ -874,6 +875,7 @@ static void read_clauses(FILE *stream, PredEntry *pp, UInt nclauses,
nrefs = cl->ClRefCount;
} else {
cl = (LogUpdClause *)Yap_AlwaysAllocCodeSpace(size);
Yap_LUClauseSpace += size;
}
read_bytes(stream, cl, size);
cl->ClFlags &= ~InUseMask;
@ -887,6 +889,7 @@ static void read_clauses(FILE *stream, PredEntry *pp, UInt nclauses,
char *base = (void *)read_UInt(stream);
UInt mask = read_UInt(stream);
UInt size = read_UInt(stream);
Yap_ClauseSpace += size;
MegaClause *cl = (MegaClause *)Yap_AlwaysAllocCodeSpace(size);
if (nclauses) {
@ -918,6 +921,7 @@ static void read_clauses(FILE *stream, PredEntry *pp, UInt nclauses,
char *base = (void *)read_UInt(stream);
UInt size = read_UInt(stream);
DynamicClause *cl = (DynamicClause *)Yap_AlwaysAllocCodeSpace(size);
Yap_LUClauseSpace += size;
LOCAL_HDiff = (char *)cl - base;
read_bytes(stream, cl, size);
@ -948,6 +952,7 @@ static void read_clauses(FILE *stream, PredEntry *pp, UInt nclauses,
char *base = (void *)read_UInt(stream);
UInt size = read_UInt(stream);
StaticClause *cl = (StaticClause *)Yap_AlwaysAllocCodeSpace(size);
Yap_ClauseSpace += size;
LOCAL_HDiff = (char *)cl - base;
read_bytes(stream, cl, size);

View File

@ -1856,9 +1856,9 @@ void Yap_dump_stack(void) {
fprintf(stderr, "%% \n%% -------------------------------------\n%%\n");
fprintf(stderr, "%% Program Position: %s\n\n", Yap_errorName(errno) );
fprintf(stderr, "%% PC: %s\n", (char *)HR);
Yap_detect_bug_location(CP, FIND_PRED_FROM_ANYWHERE, 256);
Yap_output_bug_location(CP, FIND_PRED_FROM_ANYWHERE, 256);
fprintf(stderr, "%% Continuation: %s\n", (char *)HR);
Yap_detect_bug_location(B->cp_ap, FIND_PRED_FROM_ANYWHERE, 256);
Yap_output_bug_location(B->cp_ap, FIND_PRED_FROM_ANYWHERE, 256);
fprintf(stderr, "%% Alternative: %s\n", (char *)HR);
fprintf(stderr, "%% \n%% -------------------------------------\n%%\n");
@ -1916,7 +1916,7 @@ fprintf(stderr, "%% \n%% -------------------------------------\n%%\n");
"Use--Local In Use)\n%%\n");
while (b_ptr != NULL) {
while (env_ptr && env_ptr <= (CELL *)b_ptr) {
Yap_detect_bug_location(ipc, FIND_PRED_FROM_ENV, 256);
Yap_output_bug_location(ipc, FIND_PRED_FROM_ENV, 256);
if (env_ptr == (CELL *)b_ptr && (choiceptr)env_ptr[E_CB] > b_ptr) {
b_ptr = b_ptr->cp_b;
fprintf(stderr, "%% %s\n", tp);
@ -1940,7 +1940,7 @@ fprintf(stderr, "%% \n%% -------------------------------------\n%%\n");
b_ptr->cp_ap->opc != Yap_opcode(_or_last) &&
b_ptr->cp_ap->opc != Yap_opcode(_Nstop)) {
/* we can safely ignore ; because there is always an upper env */
Yap_detect_bug_location(b_ptr->cp_ap, FIND_PRED_FROM_CP, 256);
Yap_output_bug_location(b_ptr->cp_ap, FIND_PRED_FROM_CP, 256);
fprintf(stderr, "%% %s (%luKB--%luKB)\n", tp,
(unsigned long int)((b_ptr->cp_h - H0) * sizeof(CELL) / 1024),
(unsigned long int)((ADDR)LCL0 - (ADDR)b_ptr) / 1024);
@ -2086,7 +2086,12 @@ void DumpActiveGoals(USES_REGS1) {
}
}
void Yap_detect_bug_location(yamop *yap_pc, int where_from, int psize) {
/**
* Used for debugging.
*
*/
void Yap_output_bug_location(yamop *yap_pc, int where_from, int psize) {
Atom pred_name;
UInt pred_arity;
Term pred_module;

View File

@ -176,14 +176,21 @@ void *MallocAtLevel(size_t sz, int atL USES_REGS) {
}
void *Realloc(void *pt, size_t sz USES_REGS) {
sz += sizeof(struct mblock);
struct mblock *old = pt, *o;
old--;
release_block(old);
sz = ALIGN_BY_TYPE(sz + sizeof(struct mblock), CELL);
o = realloc(old, sz);
if (o->next) {
o->next->prev = o;
} else {
LOCAL_TextBuffer->last[o->lvl] = o;
}
if (o->prev) {
o->prev->next = o;
} else {
LOCAL_TextBuffer->first[o->lvl] = o;
}
o->sz = sz;
insert_block(o);
return o + 1;
}
@ -445,6 +452,13 @@ unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) {
Yap_ThrowError(LOCAL_Error_TYPE, inp->val.t, "while reading text in");
}
}
if ((inp->val.t == TermNil) && inp->type & YAP_STRING_PREFER_LIST )
{
out = Malloc(4);
memset(out, 0, 4);
POPRET( out );
}
if (IsAtomTerm(inp->val.t) && inp->type & YAP_STRING_ATOM) {
// this is a term, extract to a buffer, and representation is wide
// Yap_DebugPlWriteln(inp->val.t);
@ -537,7 +551,7 @@ unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) {
#endif
if (inp->type & YAP_STRING_TERM) {
pop_text_stack(lvl);
return Yap_TermToBuffer(inp->val.t, 0);
return (unsigned char *)Yap_TermToBuffer(inp->val.t, 0);
}
if (inp->type & YAP_STRING_CHARS) {
@ -550,10 +564,8 @@ unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) {
POPRET( (char*)latin2utf8(inp));
}
if (inp->enc == ENC_ISO_UTF8) {
pop_text_stack(lvl);
return inp->val.c;
}
return inp->val.uc;
}
if (inp->type & YAP_STRING_WCHARS) {
// printf("%S\n",inp->val.w);

File diff suppressed because it is too large Load Diff

View File

@ -91,15 +91,19 @@ static char *send_tracer_message(char *start, char *name, arity_t arity,
Quote_illegal_f | Handle_vars_f);
size_t sz;
if (sn == NULL) {
sn = "<* error *>";
sn = malloc(strlen("<* error *>")+1);
strcpy((char*)sn, "<* error *>");
}
sz = strlen(sn);
if (max <= sz) {
min = sz + 1024;
expand = true;
free((void*)sn);
continue;
}
strcpy(s, sn);
free((void*)sn);
sn = NULL;
s += sz;
max -= sz;
}

View File

@ -77,12 +77,12 @@ static int
copy_complex_term(CELL *pt0, CELL *pt0_end, int share, int newattvs, CELL *ptf, CELL *HLow USES_REGS)
{
struct cp_frame *to_visit0, *to_visit = (struct cp_frame *)Yap_PreAllocCodeSpace();
struct cp_frame *to_visit0, *to_visit = (struct cp_frame *)Yap_PreAllocCodeSpace() ;
CELL *HB0 = HB;
tr_fr_ptr TR0 = TR;
int ground = TRUE;
HB = HLow;
HB = HR;
to_visit0 = to_visit;
loop:
while (pt0 < pt0_end) {
@ -361,7 +361,7 @@ trail_overflow:
reset_trail(TR0);
LOCAL_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0;
return -3;
}
}
static Term
@ -531,25 +531,279 @@ p_copy_term_no_delays( USES_REGS1 ) /* copy term t to a new instance */
typedef struct bp_frame {
CELL *start_cp;
CELL *end_cp;
CELL *to;
CELL *oldp;
CELL oldv;
} bp_frame_t;
typedef struct copy_frame {
CELL *start_cp;
CELL *end_cp;
CELL *to;
} copy_frame_t;
static Term *
add_to_list( Term *out_e, Term v, Term t USES_REGS)
static Term
add_to_list( Term inp, Term v, Term t PASS_REGS)
{
Term ta[2], tv;
Term ta[2];
ta[0] = v;
ta[1] = t;
*out_e = tv = MkPairTerm(Yap_MkApplTerm( FunctorEq, 2, ta ), TermNil);
return RepPair(tv)+1;
return MkPairTerm(Yap_MkApplTerm( FunctorEq, 2, ta ), inp);
}
static int
break_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, Term *of, Term oi, CELL *HLow USES_REGS)
break_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, Term *vout, Term vin,CELL *HLow USES_REGS)
{
struct bp_frame *to_visit0, *to_visit = (struct bp_frame *)Yap_PreAllocCodeSpace() ;
CELL *HB0 = HB;
tr_fr_ptr TR0 = TR;
HB = HR;
to_visit0 = to_visit;
loop:
while (pt0 < pt0_end) {
register CELL d0;
register CELL *ptd0;
++ pt0;
ptd0 = pt0;
d0 = *ptd0;
deref_head(d0, copy_term_unk);
copy_term_nvar:
{
if (IsPairTerm(d0)) {
CELL *ap2 = RepPair(d0);
fprintf(stderr, "%ld \n", RepPair(ap2[0])- ptf);
if (IsVarTerm(ap2[0]) && IN_BETWEEN(HB, (ap2[0]),HR)) {
Term v = MkVarTerm();
*ptf = v;
vin = add_to_list(vin, (CELL)(ptf), AbsPair(ptf) );
ptf++;
continue;
}
if (to_visit+1 >= (struct bp_frame *)AuxSp) {
goto heap_overflow;
}
*ptf++ = (CELL)(HR);
to_visit->start_cp = pt0;
to_visit->end_cp = pt0_end;
to_visit->to = ptf;
to_visit->oldp = ap2;
d0 = to_visit->oldv = ap2[0];
/* fool the system into thinking we had a variable there */
to_visit ++;
pt0 = ap2;
pt0_end = ap2 + 1;
ptf = HR;
*ap2 = AbsPair(HR);
HR += 2;
if (HR > ASP - 2048) {
goto overflow;
}
if (IsVarTerm(d0) && d0 == (CELL)ap2) {
RESET_VARIABLE(ptf);
ptf++;
continue;
}
d0 = Deref(d0);
if (!IsVarTerm(d0)) {
goto copy_term_nvar;
} else {
*ptf++ = d0;
}
continue;
} else if (IsApplTerm(d0)) {
register Functor f;
register CELL *ap2;
/* store the terms to visit */
ap2 = RepAppl(d0)+1;
f = (Functor)(ap2[-1]);
if (IsExtensionFunctor(f)) {
*ptf++ = d0; /* you can just copy other extensions. */
continue;
}
if (IsApplTerm(ap2[0]) && IN_BETWEEN(HB, RepAppl(ap2[0]),HR)) {
RESET_VARIABLE(ptf);
vin = add_to_list(vin, (CELL)ptf, ap2[0] );
ptf++;
continue;
}
arity_t arity = ArityOfFunctor(f);
if (to_visit+1 >= (struct bp_frame *)AuxSp) {
goto heap_overflow;
}
*ptf++ = AbsAppl(HR);
to_visit->start_cp = pt0;
to_visit->end_cp = pt0_end;
to_visit->to = ptf;
to_visit->oldp = ap2;
d0 = to_visit->oldv = ap2[0];
/* fool the system into thinking we had a variable there */
to_visit ++;
pt0 = ap2;
pt0_end = ap2 + (arity-1);
ptf = HR;
if (HR > ASP - 2048) {
goto overflow;
}
*ptf++ =(CELL)f;
*ap2 = AbsAppl(HR);
HR += (arity+1);
if (IsVarTerm(d0) && d0 == (CELL)(ap2)) {
RESET_VARIABLE(ptf);
ptf++;
continue;
}
d0 = Deref(d0);
if (!IsVarTerm(d0)) {
goto copy_term_nvar;
} else {
*ptf++ = d0;
}
continue;
} else {
/* just copy atoms or integers */
*ptf++ = d0;
}
continue;
}
derefa_body(d0, ptd0, copy_term_unk, copy_term_nvar);
*ptf++ = (CELL) ptd0;
}
/* Do we still have compound terms to visit */
if (to_visit > to_visit0) {
to_visit --;
*to_visit->oldp = to_visit->oldv;
ptf = to_visit->to;
pt0 = to_visit->start_cp;
pt0_end = to_visit->end_cp;
goto loop;
}
/* restore our nice, friendly, term to its original state */
HB = HB0;
*vout = vin;
return true;
overflow:
/* oops, we're in trouble */
HR = HLow;
/* we've done it */
/* restore our nice, friendly, term to its original state */
HB = HB0;
#ifdef RATIONAL_TREES
while (to_visit > to_visit0) {
to_visit --;
pt0 = to_visit->start_cp;
pt0_end = to_visit->end_cp;
ptf = to_visit->to;
*to_visit->oldp = to_visit->oldv;
}
#endif
reset_trail(TR0);
/* follow chain of multi-assigned variables */
return -1;
heap_overflow:
/* oops, we're in trouble */
HR = HLow;
/* we've done it */
/* restore our nice, friendly, term to its original state */
HB = HB0;
#ifdef RATIONAL_TREES
while (to_visit > to_visit0) {
to_visit --;
pt0 = to_visit->start_cp;
pt0_end = to_visit->end_cp;
ptf = to_visit->to;
*to_visit->oldp = to_visit->oldv;
}
#endif
reset_trail(TR0);
LOCAL_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0;
return -3;
}
Term
Yap_BreakRational(Term inp, UInt arity, Term *to, Term ti USES_REGS) {
Term t = Deref(inp);
Term tii = ti;
tr_fr_ptr TR0 = TR;
if (IsVarTerm(t)) {
*to = ti;
return t;
} else if (IsPrimitiveTerm(t)) {
*to = ti;
return t;
} else if (IsPairTerm(t)) {
CELL *ap;
CELL *Hi;
restart_list:
ap = RepPair(t);
Hi = HR;
HR += 2;
{
Int res;
if ((res = break_rationals_complex_term(ap-1, ap+1, Hi, to, ti, Hi PASS_REGS)) < 0) {
HR = Hi;
if ((t = handle_cp_overflow(res, TR0, arity, t))== 0L)
return FALSE;
goto restart_list;
} else if (*to == tii) {
HR = Hi;
return t;
} else {
return AbsPair(Hi);
}
}
} else {
Functor f;
CELL *HB0;
CELL *ap;
restart_appl:
f = FunctorOfTerm(t);
if (IsExtensionFunctor(f)) {
*to = ti;
return t;
}
HB0 = HR;
ap = RepAppl(t);
HR[0] = (CELL)f;
arity = ArityOfFunctor(f);
HR += 1+arity;
{
Int res;
if ((res = break_rationals_complex_term(ap, ap+(arity), HB0+1, to, ti, HB0 PASS_REGS)) < 0) {
HR = HB0;
if ((t = handle_cp_overflow(res, TR0, arity, t))== 0L)
return FALSE;
goto restart_appl;
} else if (*to == ti) {
HR = HB0;
return t;
} else {
return AbsAppl(HB0);
}
}
}
}
static int
break_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, Term *of, Term oi, CELL *HLow USES_REGS)
{
struct copy_frame *to_visit0, *to_visit = (struct copy_frame *)Yap_PreAllocCodeSpace();
@ -586,7 +840,7 @@ break_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, Term *of, Term
if (!IsVarTerm(*newp)) {
Term v = (CELL)newp, t = *newp;
RESET_VARIABLE(newp);
of = add_to_list( of, v, t PASS_REGS);
oi = add_to_list( oi, v, t PASS_REGS);
}
*ptf++ = (CELL)newp;
continue;
@ -667,8 +921,7 @@ break_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, Term *of, Term
/* restore our nice, friendly, term to its original state */
HB = HB0;
reset_trail(TR0);
RESET_VARIABLE(of);
Yap_unify((CELL)of, oi);
*of = oi;
return TRUE;
overflow:
@ -677,14 +930,12 @@ break_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, Term *of, Term
/* we've done it */
/* restore our nice, friendly, term to its original state */
HB = HB0;
#ifdef RATIONAL_TREES
while (to_visit > to_visit0) {
to_visit --;
pt0 = to_visit->start_cp;
pt0_end = to_visit->end_cp;
ptf = to_visit->to;
}
#endif
reset_trail(TR0);
/* follow chain of multi-assigned variables */
return -1;
@ -695,28 +946,27 @@ break_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, Term *of, Term
/* we've done it */
/* restore our nice, friendly, term to its original state */
HB = HB0;
#ifdef RATIONAL_TREES
while (to_visit > to_visit0) {
to_visit --;
pt0 = to_visit->start_cp;
pt0_end = to_visit->end_cp;
ptf = to_visit->to;
}
#endif
reset_trail(TR0);
LOCAL_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0;
return -3;
}
static Term
BreakRational(Term inp, UInt arity, Term *of, Term oi USES_REGS) {
Term
Yap_BreakTerm(Term inp, UInt arity, Term *to, Term ti USES_REGS) {
Term t = Deref(inp);
tr_fr_ptr TR0 = TR;
if (IsVarTerm(t)) {
*to = ti;
return t;
} else if (IsPrimitiveTerm(t)) {
*to = ti;
return t;
} else {
CELL *ap;
@ -728,7 +978,7 @@ BreakRational(Term inp, UInt arity, Term *of, Term oi USES_REGS) {
{
int res;
if ((res = break_rationals_complex_term(ap-1, ap, Hi, of, oi, Hi PASS_REGS)) < 0) {
if ((res = break_complex_term(ap-1, ap, Hi, to, ti, Hi PASS_REGS)) < 0) {
HR = Hi;
if ((t = handle_cp_overflow(res, TR0, arity, t))== 0L)
return FALSE;
@ -739,11 +989,12 @@ BreakRational(Term inp, UInt arity, Term *of, Term oi USES_REGS) {
}
}
static Int
p_break_rational( USES_REGS1 )
{
Term tf;
return Yap_unify(ARG2, BreakRational(ARG1, 4, &tf, ARG4 PASS_REGS)) &&
return Yap_unify(ARG2, Yap_BreakTerm(ARG1, 4, &tf, ARG4 PASS_REGS)) &&
Yap_unify(tf, ARG3);
}
@ -752,7 +1003,7 @@ static Int
p_break_rational3( USES_REGS1 )
{
Term tf;
return Yap_unify(ARG2, BreakRational(ARG1, 4, &tf, TermNil PASS_REGS)) &&
return Yap_unify(ARG2, Yap_BreakTerm(ARG1, 4, &tf, TermNil PASS_REGS)) &&
Yap_unify(tf, ARG3);
}

182
C/write.c
View File

@ -1,4 +1,3 @@
/*************************************************************************
* *
* YAP Prolog *
@ -101,6 +100,11 @@ static bool callPortray(Term t, int sno USES_REGS) {
return false;
}
#define PROTECT(t,F) { \
yhandle_t yt = Yap_InitHandle(t); \
F; \
t = Yap_PopHandle(yt); \
}
static void wrputn(Int, struct write_globs *);
static void wrputf(Float, struct write_globs *);
static void wrputref(CODEADDR, int, struct write_globs *);
@ -375,7 +379,6 @@ int Yap_FormatFloat(Float f, char **s, size_t sz) {
CACHE_REGS
struct write_globs wglb;
int sno;
char *so;
sno = Yap_open_buf_write_stream(GLOBAL_Stream[LOCAL_c_output_stream].encoding,
0);
@ -672,61 +675,6 @@ static void putUnquotedString(Term string, struct write_globs *wglb)
lastw = alphanum;
}
static Term from_pointer(CELL *ptr0, struct rewind_term *rwt,
struct write_globs *wglb) {
CACHE_REGS
Term t;
CELL *ptr = ptr0;
while (IsVarTerm(*ptr) && !IsUnboundVar(ptr))
ptr = (CELL *)*ptr;
t = *ptr;
if (wglb->Keep_terms) {
struct rewind_term *x = rwt->parent;
rwt->u_sd.s.old = Yap_InitSlot(t);
rwt->u_sd.s.ptr = Yap_InitSlot((CELL)ptr0);
if (!IsAtomicTerm(t) && !IsVarTerm(t)) {
while (x) {
if (Yap_GetDerefedFromSlot(x->u_sd.s.old) == t)
return TermFoundVar;
x = x->parent;
}
}
} else {
rwt->u_sd.d.old = t;
rwt->u_sd.d.ptr = ptr0;
if (!IsVarTerm(t) && !IsAtomicTerm(t)) {
struct rewind_term *x = rwt->parent;
while (x) {
if (x->u_sd.d.old == t)
return TermFoundVar;
x = x->parent;
}
}
}
return t;
}
static CELL *restore_from_write(struct rewind_term *rwt,
struct write_globs *wglb) {
CACHE_REGS
CELL *ptr;
if (wglb->Keep_terms) {
ptr = Yap_GetPtrFromSlot(rwt->u_sd.s.ptr);
Yap_RecoverSlots(2, rwt->u_sd.s.old);
// printf("leak=%d %d\n", LOCALCurSlot,rwt->u_sd.s.old) ;
} else {
ptr = rwt->u_sd.d.ptr;
}
rwt->u_sd.s.ptr = 0;
return ptr;
}
/* writes an unbound variable */
static void write_var(CELL *t, struct write_globs *wglb,
struct rewind_term *rwt) {
CACHE_REGS
@ -746,23 +694,17 @@ static void write_var(CELL *t, struct write_globs *wglb,
wglb->Portray_delays = FALSE;
if (ext == attvars_ext) {
yhandle_t h = Yap_InitHandle((CELL)t);
attvar_record *attv = RepAttVar(t);
CELL *l = &attv->Value; /* dirty low-level hack, check atts.h */
wrputs("$AT(", wglb->stream);
write_var(t, wglb, rwt);
wrputc(',', wglb->stream);
writeTerm(from_pointer(l, &nrwt, wglb), 999, 1, FALSE, wglb, &nrwt);
l = restore_from_write(&nrwt, wglb);
wrputc(',', wglb->stream);
attv = RepAttVar((CELL *)Yap_GetFromHandle(h));
l = &attv->Value;
;
PROTECT(*t,writeTerm(*l, 999, 1, FALSE, wglb, &nrwt));
attv = RepAttVar(t);
wrputc(',', wglb->stream);
l++;
writeTerm(from_pointer(l, &nrwt, wglb), 999, 1, FALSE, wglb, &nrwt);
restore_from_write(&nrwt, wglb);
writeTerm(*l, 999, 1, FALSE, wglb, &nrwt);
wrclose_bracket(wglb, TRUE);
}
wglb->Portray_delays = TRUE;
@ -775,24 +717,6 @@ static void write_var(CELL *t, struct write_globs *wglb,
}
}
static Term check_infinite_loop(Term t, struct rewind_term *x,
struct write_globs *wglb) {
CACHE_REGS
if (wglb->Keep_terms) {
while (x) {
if (Yap_GetFromSlot(x->u_sd.s.old) == t)
return TermFoundVar;
x = x->parent;
}
} else {
while (x) {
if (x->u_sd.d.old == t)
return TermFoundVar;
x = x->parent;
}
}
return t;
}
static void write_list(Term t, int direction, int depth,
struct write_globs *wglb, struct rewind_term *rwt) {
@ -805,14 +729,12 @@ static void write_list(Term t, int direction, int depth,
int ndirection;
int do_jump;
writeTerm(from_pointer(RepPair(t), &nrwt, wglb), 999, depth + 1, FALSE,
wglb, &nrwt);
t = AbsPair(restore_from_write(&nrwt, wglb));
PROTECT(t,writeTerm(HeadOfTerm(t), 999, depth + 1, FALSE,
wglb, &nrwt));
ti = TailOfTerm(t);
if (IsVarTerm(ti))
break;
if (!IsPairTerm(ti) ||
!IsPairTerm((ti = check_infinite_loop(ti, rwt, wglb))))
if (!IsPairTerm(ti))
break;
ndirection = RepPair(ti) - RepPair(t);
/* make sure we're not trapped in loops */
@ -843,29 +765,18 @@ static void write_list(Term t, int direction, int depth,
t = ti;
}
if (IsPairTerm(ti)) {
Term nt = from_pointer(RepPair(t) + 1, &nrwt, wglb);
/* we found an infinite loop */
if (IsAtomTerm(nt)) {
if (lastw == symbol || lastw == separator) {
wrputc(' ', wglb->stream);
}
wrputc('|', wglb->stream);
writeTerm(nt, 999, depth, FALSE, wglb, rwt);
} else {
/* keep going on the list */
wrputc(',', wglb->stream);
write_list(nt, direction, depth, wglb, &nrwt);
}
restore_from_write(&nrwt, wglb);
write_list(ti, direction, depth, wglb, &nrwt);
} else if (ti != MkAtomTerm(AtomNil)) {
if (lastw == symbol || lastw == separator) {
wrputc(' ', wglb->stream);
}
wrputc('|', wglb->stream);
lastw = separator;
writeTerm(from_pointer(RepPair(t) + 1, &nrwt, wglb), 999, depth, FALSE,
writeTerm(ti, 999, depth, FALSE,
wglb, &nrwt);
restore_from_write(&nrwt, wglb);
}
}
@ -873,7 +784,6 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
struct write_globs *wglb, struct rewind_term *rwt)
/* term to write */
/* context priority */
{
CACHE_REGS
struct rewind_term nrwt;
@ -897,13 +807,11 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
wrputs("'.'(", wglb->stream);
lastw = separator;
writeTerm(from_pointer(RepPair(t), &nrwt, wglb), 999, depth + 1, FALSE,
wglb, &nrwt);
t = AbsPair(restore_from_write(&nrwt, wglb));
PROTECT( t, writeTerm(HeadOfTerm(t), 999, depth + 1, FALSE,
wglb, &nrwt));
wrputs(",", wglb->stream);
writeTerm(from_pointer(RepPair(t) + 1, &nrwt, wglb), 999, depth + 1,
writeTerm(TailOfTerm(t), 999, depth + 1,
FALSE, wglb, &nrwt);
restore_from_write(&nrwt, wglb);
wrclose_bracket(wglb, TRUE);
return;
}
@ -969,9 +877,8 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
*p++;
lastw = separator;
/* cannot use the term directly with the SBA */
writeTerm(from_pointer(p, &nrwt, wglb), 999, depth + 1, FALSE, wglb,
&nrwt);
p = restore_from_write(&nrwt, wglb) + 1;
PROTECT( t, writeTerm(*p, 999, depth + 1, FALSE, wglb,
&nrwt) );
if (*p)
wrputc(',', wglb->stream);
argno++;
@ -999,9 +906,8 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
} else if (atom == AtomMinus) {
last_minus = TRUE;
}
writeTerm(from_pointer(RepAppl(t) + 1, &nrwt, wglb), rp, depth + 1, TRUE,
writeTerm(tright, rp, depth + 1, TRUE,
wglb, &nrwt);
restore_from_write(&nrwt, wglb);
if (bracket_right) {
wrclose_bracket(wglb, TRUE);
}
@ -1034,9 +940,8 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
if (bracket_left) {
wropen_bracket(wglb, TRUE);
}
writeTerm(from_pointer(RepAppl(t) + offset, &nrwt, wglb), lp, depth + 1,
writeTerm(ArgOfTerm(offset,t), lp, depth + 1,
rinfixarg, wglb, &nrwt);
restore_from_write(&nrwt, wglb);
if (bracket_left) {
wrclose_bracket(wglb, TRUE);
}
@ -1081,9 +986,8 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
if (bracket_left) {
wropen_bracket(wglb, TRUE);
}
writeTerm(from_pointer(RepAppl(t) + 1, &nrwt, wglb), lp, depth + 1,
rinfixarg, wglb, &nrwt);
t = AbsAppl(restore_from_write(&nrwt, wglb) - 1);
PROTECT(t,writeTerm(ArgOfTerm(1,t), lp, depth + 1,
rinfixarg, wglb, &nrwt));
if (bracket_left) {
wrclose_bracket(wglb, TRUE);
}
@ -1102,9 +1006,8 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
if (bracket_right) {
wropen_bracket(wglb, TRUE);
}
writeTerm(from_pointer(RepAppl(t) + 2, &nrwt, wglb), rp, depth + 1, TRUE,
writeTerm(ArgOfTerm(2,t), rp, depth + 1, TRUE,
wglb, &nrwt);
restore_from_write(&nrwt, wglb);
if (bracket_right) {
wrclose_bracket(wglb, TRUE);
}
@ -1144,17 +1047,15 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
} else {
wrputs("'$VAR'(", wglb->stream);
lastw = separator;
writeTerm(from_pointer(RepAppl(t) + 1, &nrwt, wglb), 999, depth + 1,
writeTerm(ArgOfTerm(1, t), 999, depth + 1,
FALSE, wglb, &nrwt);
restore_from_write(&nrwt, wglb);
wrclose_bracket(wglb, TRUE);
}
} else if (!wglb->Ignore_ops && functor == FunctorBraces) {
wrputc('{', wglb->stream);
lastw = separator;
writeTerm(from_pointer(RepAppl(t) + 1, &nrwt, wglb), GLOBAL_MaxPriority,
writeTerm(ArgOfTerm(1, t), GLOBAL_MaxPriority,
depth + 1, FALSE, wglb, &nrwt);
restore_from_write(&nrwt, wglb);
wrputc('}', wglb->stream);
lastw = separator;
} else if (atom == AtomArray) {
@ -1165,35 +1066,37 @@ static void writeTerm(Term t, int p, int depth, int rinfixarg,
wrputs("...", wglb->stream);
break;
}
writeTerm(from_pointer(RepAppl(t) + op, &nrwt, wglb), 999, depth + 1,
writeTerm(ArgOfTerm(op, t), 999, depth + 1,
FALSE, wglb, &nrwt);
t = AbsAppl(restore_from_write(&nrwt, wglb) - op);
if (op != Arity) {
PROTECT(t, writeTerm(ArgOfTerm(op, t), 999, depth + 1,
FALSE, wglb, &nrwt));
wrputc(',', wglb->stream);
lastw = separator;
}
}
writeTerm(ArgOfTerm(op, t), 999, depth + 1,
FALSE, wglb, &nrwt);
wrputc('}', wglb->stream);
lastw = separator;
} else {
putAtom(atom, wglb->Quote_illegal, wglb);
lastw = separator;
wropen_bracket(wglb, FALSE);
for (op = 1; op <= Arity; ++op) {
for (op = 1; op < Arity; ++op) {
if (op == wglb->MaxArgs) {
wrputc('.', wglb->stream);
wrputc('.', wglb->stream);
wrputc('.', wglb->stream);
break;
}
writeTerm(from_pointer(RepAppl(t) + op, &nrwt, wglb), 999, depth + 1,
FALSE, wglb, &nrwt);
restore_from_write(&nrwt, wglb);
if (op != Arity) {
PROTECT(t,writeTerm(ArgOfTerm(op, t), 999, depth + 1,
FALSE, wglb, &nrwt));
wrputc(',', wglb->stream);
lastw = separator;
}
}
writeTerm(ArgOfTerm(op, t), 999, depth + 1,
FALSE, wglb, &nrwt);
wrclose_bracket(wglb, TRUE);
}
}
@ -1233,8 +1136,18 @@ void Yap_plwrite(Term t, StreamDesc *mywrite, int max_depth, int flags,
rwt.parent = NULL;
wglb.Ignore_ops = flags & Ignore_ops_f;
wglb.Write_strings = flags & BackQuote_String_f;
if (!(flags & Ignore_cyclics_f) && false) {
Term ts[2];
ts[0] = Yap_BreakRational(t, 0, ts+1, TermNil PASS_REGS);
//fprintf(stderr, "%lx %lx %lx\n", t, ts[0], ts[1]);
//Yap_DebugPlWriteln(ts[0]);
//ap_DebugPlWriteln(ts[1[);
if (ts[1] != TermNil) {
t = Yap_MkApplTerm( FunctorAtSymbol, 2, ts);
}
}
/* protect slots for portray */
writeTerm(from_pointer(&t, &rwt, &wglb), priority, 1, FALSE, &wglb, &rwt);
writeTerm(t, priority, 1, FALSE, &wglb, &rwt);
if (flags & New_Line_f) {
if (flags & Fullstop_f) {
wrputc('.', wglb.stream);
@ -1248,7 +1161,6 @@ void Yap_plwrite(Term t, StreamDesc *mywrite, int max_depth, int flags,
wrputc(' ', wglb.stream);
}
}
restore_from_write(&rwt, &wglb);
Yap_CloseSlots(sls);
pop_text_stack(lvl);
}

View File

@ -145,11 +145,12 @@ static void init_globals(YAP_init_args *yap_init) {
}
const char *Yap_BINDIR, *Yap_ROOTDIR, *Yap_SHAREDIR, *Yap_LIBDIR, *Yap_DLLDIR,
*Yap_PLDIR, *Yap_BOOTSTRAP, *Yap_COMMONSDIR,
*Yap_INPUT_STARTUP, *Yap_OUTPUT_STARTUP, *Yap_BOOTFILE, *Yap_INCLUDEDIR;
*Yap_PLDIR, *Yap_BOOTSTRAP, *Yap_COMMONSDIR, *Yap_INPUT_STARTUP,
*Yap_OUTPUT_STARTUP, *Yap_BOOTFILE, *Yap_INCLUDEDIR;
/**
* consult loop in C: used to boot the system, butt supports goal execution and recursive consulting.
* consult loop in C: used to boot the system, butt supports goal execution and
* recursive consulting.
*
* */
static bool consult(const char *b_file USES_REGS) {
@ -184,15 +185,15 @@ static bool consult(const char *b_file USES_REGS) {
Term vs = MkVarTerm(), pos = MkVarTerm();
t = YAP_ReadClauseFromStream(c_stream, vs, pos);
// Yap_GetNèwSlot(t);
if (t == TermEof)
break;
if (t == TermEof)
break;
if (t == 0) {
fprintf(stderr, "[ SYNTAX ERROR: while parsing stream %s at line %ld ]\n",
b_file, GLOBAL_Stream[c_stream].linecount);
} else if (IsVarTerm(t) || t == TermNil) {
fprintf(stderr, "[ line: " Int_FORMAT ": term cannot be compiled ]",
GLOBAL_Stream[c_stream].linecount);
} else if (IsApplTerm(t) && (FunctorOfTerm(t) == functor_query ||
} else if (IsApplTerm(t) && (FunctorOfTerm(t) == functor_query ||
FunctorOfTerm(t) == functor_command1)) {
t = ArgOfTerm(1, t);
if (IsApplTerm(t) && FunctorOfTerm(t) == functor_compile2) {
@ -201,13 +202,12 @@ static bool consult(const char *b_file USES_REGS) {
YAP_RunGoalOnce(t);
}
} else {
YAP_CompileClause(t);
YAP_CompileClause(t);
}
yap_error_descriptor_t *errd;
if ((errd =
Yap_GetException(LOCAL_ActiveError))) {
fprintf(stderr, "%s:%ld:0: Error %s %s Found\n", errd->errorFile, (long int) errd->errorLine, errd->classAsText,
errd->errorAsText);
if ((errd = Yap_GetException(LOCAL_ActiveError))) {
fprintf(stderr, "%s:%ld:0: Error %s %s Found\n", errd->errorFile,
(long int)errd->errorLine, errd->classAsText, errd->errorAsText);
}
} while (true);
BACKUP_MACHINE_REGS();
@ -216,14 +216,14 @@ static bool consult(const char *b_file USES_REGS) {
pop_text_stack(lvl);
return false;
}
pop_text_stack(lvl);
return true;
pop_text_stack(lvl);
return true;
}
///
///
static const char *sel(bool dir, bool ok1, const char *s1, bool ok2, const char *s2,
...) {
static const char *sel(bool dir, bool ok1, const char *s1, bool ok2,
const char *s2, ...) {
if (ok1 && s1)
return s1;
if (ok2)
@ -768,7 +768,7 @@ X_API YAP_file_type_t YAP_parse_yap_arguments(int argc, char *argv[],
argv++;
iap->PrologTopLevelGoal = add_end_dot(*argv);
}
iap->HaltAfterBoot = true;
iap->HaltAfterBoot = true;
break;
case 'n':
if (!strcmp("nosignals", p)) {
@ -941,15 +941,15 @@ static void init_hw(YAP_init_args *yap_init, struct ssz_t *spt) {
if (yap_init->Embedded) {
yap_init->install = false;
GLOBAL_PrologShouldHandleInterrupts =
yap_init->PrologCannotHandleInterrupts = true;
yap_init->PrologCannotHandleInterrupts = true;
} else {
GLOBAL_PrologShouldHandleInterrupts =
!yap_init->PrologCannotHandleInterrupts;
!yap_init->PrologCannotHandleInterrupts;
}
Yap_InitSysbits(0); /* init signal handling and time, required by later
functions */
GLOBAL_argv = yap_init->Argv;
GLOBAL_argc = yap_init->Argc;
Yap_InitSysbits(0); /* init signal handling and time, required by later
functions */
GLOBAL_argv = yap_init->Argv;
GLOBAL_argc = yap_init->Argc;
#if __ANDROID__
@ -982,7 +982,8 @@ yap_init->PrologCannotHandleInterrupts = true;
static void end_init(YAP_init_args *iap) {
YAP_initialized = true;
if (iap->HaltAfterBoot) Yap_exit(0);
if (iap->HaltAfterBoot)
Yap_exit(0);
LOCAL_PrologMode &= ~BootMode;
CurrentModule = USER_MODULE;
}
@ -1022,9 +1023,9 @@ X_API void YAP_Init(YAP_init_args *yap_init) {
CACHE_REGS
if (yap_init->QuietMode) {
setVerbosity(TermSilent);
}
if (yap_init->QuietMode) {
setVerbosity(TermSilent);
}
if (yap_init->PrologRCFile != NULL) {
/*
This must be done before restore, otherwise
@ -1037,15 +1038,15 @@ X_API void YAP_Init(YAP_init_args *yap_init) {
Yap_ExecutionMode = yap_init->ExecutionMode;
Yap_set_locations(yap_init);
if (do_bootstrap ||
!try_restore ||
if (do_bootstrap || !try_restore ||
!Yap_SavedInfo(Yap_INPUT_STARTUP, &minfo.Trail, &minfo.Stack,
&minfo.Heap) ) {
&minfo.Heap)) {
init_globals(yap_init);
start_modules();
CurrentModule = PROLOG_MODULE;
TermEof = MkAtomTerm( Yap_LookupAtom("end_of_file"));
CurrentModule = PROLOG_MODULE;
TermEof = MkAtomTerm(Yap_LookupAtom("end_of_file"));
LOCAL_consult_level = -1;
consult(Yap_BOOTSTRAP PASS_REGS);
setAtomicGlobalPrologFlag(RESOURCE_DATABASE_FLAG,
MkAtomTerm(Yap_LookupAtom(Yap_BOOTFILE)));
@ -1056,21 +1057,22 @@ X_API void YAP_Init(YAP_init_args *yap_init) {
start_modules();
if (yap_init->install && Yap_OUTPUT_STARTUP) {
setAtomicGlobalPrologFlag(RESOURCE_DATABASE_FLAG,
MkAtomTerm(Yap_LookupAtom(Yap_INPUT_STARTUP)));
setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, true);
}
setAtomicGlobalPrologFlag(RESOURCE_DATABASE_FLAG,
MkAtomTerm(Yap_LookupAtom(Yap_INPUT_STARTUP)));
setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, true);
}
LOCAL_consult_level = -1;
}
YAP_RunGoalOnce(TermInitProlog);
if (yap_init->install && Yap_OUTPUT_STARTUP) {
Term t = MkAtomTerm(Yap_LookupAtom(Yap_OUTPUT_STARTUP));
Term g = Yap_MkApplTerm(Yap_MkFunctor(Yap_LookupAtom("qsave_program"), 1),
1, &t);
if (yap_init->install && Yap_OUTPUT_STARTUP) {
Term t = MkAtomTerm(Yap_LookupAtom(Yap_OUTPUT_STARTUP));
Term g = Yap_MkApplTerm(Yap_MkFunctor(Yap_LookupAtom("qsave_program"), 1),
1, &t);
YAP_RunGoalOnce(g);
}
YAP_RunGoalOnce(g);
}
end_init(yap_init);
end_init(yap_init);
}
#if (DefTrailSpace < MinTrailSpace)

View File

@ -374,7 +374,7 @@ set(YAP_FOUND ON)
set(YAP_MAJOR_VERSION 6)
set(YAP_MINOR_VERSION 4)
set(YAP_PATCH_VERSION 0)
set(YAP_PATCH_VERSION 1)
set(YAP_FULL_VERSION
${YAP_MAJOR_VERSION}.${YAP_MINOR_VERSION}.${YAP_PATCH_VERSION})
@ -557,7 +557,8 @@ option(WITH_R
"Use R Interface" ON)
IF (WITH_R)
include_directories(packages/real )
find_host_package(LibR)
add_subDIRECTORY(packages/real)
ENDIF (WITH_R)
@ -687,7 +688,8 @@ set_target_properties(libYap
# file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py)
if (PYTHONLIBS_FOUND AND SWIG_FOUND)
add_subdirectory(packages/python/swig)
set( ENV{PYTHONPATH} ${CMAKE_BINARY_DIR}/packages/python/swig:${CMAKE_BINARY_DIR}/packages/python/yap_kernel:. )
add_subdirectory(packages/python/swig)
include(FindPythonModule)
@ -776,7 +778,12 @@ if (WITH_GECODE)
add_subDIRECTORY(packages/gecode)
endif ()
add_subDIRECTORY(packages/real)
option(WITH_LBFGS
"interface with lbfgs" ON)
if (WITH_LBFGS)
add_subDIRECTORY(packages/yap-lbfgs)
endif ()
@ -795,17 +802,16 @@ if (Java_Development_FOUND)
set (STD_CMAKE_FIND_FRAMEWORK ${CMAKE_FIND_FRAMEWORK})
set (CMAKE_FIND_FRAMEWORK LAST) # CMake will find the Java returned by /usr/libexec/java_home.
find_package(JNI)
macro_optional_find_package(JNI ON)
set (CMAKE_FIND_FRAMEWORK ${STD_CMAKE_FIND_FRAMEWORK})
if (NOT JNI_FOUND)
set (JAVA_HOME ${JAVA_INCLUDE_PATH}/..)
endif()
if (JNI_FOUND)
get_filename_component(JAVA_HOME ${JAVA_INCLUDE_PATH} DIRECTORY)
include(UseJava)
#
@ -826,7 +832,8 @@ endif()
# The Java_ADDITIONAL_VERSIONS variable can be used to specify a list
# of version numbers that should be taken into account when searching
# for Java. You need to set this variable before calling
# find_package(JavaLibs).
#
#macro_optional_find_package(JNI ON)
# JNI_INCLUDE_DIRS = the include dirs to use
@ -838,6 +845,7 @@ endif()
# JAVA_INCLUDE_PATH2 = the include path to jni_md.h
# JAVA_AWT_INCLUDE_PATH = the include path to jawt.h
endif (JNI_FOUND)

View File

@ -2,7 +2,6 @@
///
/// @brief C++ Interface to generated code.
#ifndef _YAPDB_H
#define _YAPDB_H
@ -10,7 +9,6 @@
#define YAP_CPP_DB_INTERFACE 1
/**
*
* @defgroup yap-cplus-db-interface Data-Base Component of YAP interface.
@ -55,6 +53,7 @@ public:
YAPModule(YAP_Term t) : YAPAtomTerm(t){};
YAPModule() : YAPAtomTerm(curModule()){};
YAPModule(YAPAtom t) : YAPAtomTerm(t){};
YAPModule(YAPStringTerm t) : YAPAtomTerm(t.getString()){};
Term term() { return gt(); };
};
@ -72,11 +71,10 @@ class X_API YAPModuleProp : public YAPProp {
public:
YAPModuleProp(YAPModule tmod) { m = Yap_GetModuleEntry(tmod.gt()); };
YAPModuleProp() { m = Yap_GetModuleEntry(YAP_CurrentModule()); };
YAPModuleProp() { m = Yap_GetModuleEntry(Yap_CurrentModule()); };
virtual YAPModule module() { return YAPModule(m->AtomOfME); };
};
/**
* @brief Predicates
*
@ -91,32 +89,32 @@ protected:
/// auxiliary routine to find a predicate in the current module.
/// auxiliary routine to find a predicate in the current module.
PredEntry *getPred(Term &t, CELL *& outp);
/// auxiliary routine to find a predicate in the current module.
PredEntry *getPred(Term &t, Term &tm, CELL *&outp);
PredEntry *asPred() { return ap; };
/// Empty constructor for predicates
/// Empty constructor for predicates
///
/// Just do nothing.
inline YAPPredicate() {
}
YAPPredicate(Term &to, Term &tmod, CELL * &ts, const char *pname);
inline YAPPredicate() {}
YAPPredicate(Term &to, Term &tmod, CELL *&ts, const char *pname);
/// Term constructor for predicates
///
/// It is just a call to getPred
inline YAPPredicate(Term t, CELL *&v) {
if (t) {
ap = getPred(t, v);
Term tm = Yap_CurrentModule();
ap = getPred(t, tm, v);
}
}
inline YAPPredicate(Term t) {
inline YAPPredicate(Term t) {
if (t) {
CELL *v = nullptr;
ap = getPred(t, v);
Term tm = Yap_CurrentModule();
ap = getPred(t, tm, v);
}
}
@ -124,13 +122,14 @@ inline YAPPredicate(Term t) {
///
/// It is just a call to getPred
inline YAPPredicate(YAPTerm t, CELL *&v) {
Term tp = t.term();
ap = getPred(tp, v);
Term tp = t.term(), tm = Yap_CurrentModule();
ap = getPred(tp, tm, v);
}
inline YAPPredicate(YAPTerm t) {
CELL *v = nullptr;
Term tp = t.term();
ap = getPred(tp, v);
inline YAPPredicate(YAPTerm t) {
CELL *v = nullptr;
Term tp = t.term();
Term tm = Yap_CurrentModule();
ap = getPred(tp, tm, v);
}
/// Cast constructor for predicates,
@ -138,16 +137,14 @@ inline YAPPredicate(YAPTerm t) {
///
inline YAPPredicate(PredEntry *pe) { ap = pe; }
/// Functor constructor for predicates, is given a specific module.
/// Functor constructor for predicates, is given a specific module.
/// This version avoids manufacturing objects
inline YAPPredicate(Functor f, Term mod) {
ap = RepPredProp(PredPropByFunc(f, mod));
}
public:
/// String constructor for predicates
/// String constructor for predicates
///
/// It also communicates the array of arguments t[]
/// and the array of variables
@ -157,25 +154,25 @@ public:
const char *s = (const char *)s0;
Term tnames = MkVarTerm();
tout =
Yap_BufferToTermWithPrioBindings(s, TermNil, tnames, strlen(s0), 1200);
Yap_BufferToTermWithPrioBindings(s, TermNil, tnames, strlen(s0), 1200);
// fprintf(stderr,"ap=%p arity=%d text=%s", ap, ap->ArityOfPE, s);
// Yap_DebugPlWrite(out);
if (tout == 0L) {
return;
return;
throw YAPError();
}
Term tm = Yap_CurrentModule();
ap = getPred(tout, tm, nts);
tout = Yap_SaveTerm(tout);
names = YAPPairTerm(tnames);
}
ap = getPred(tout, nts);
tout = Yap_SaveTerm(tout);
names = YAPPairTerm(tnames);
}
/// Functor constructor for predicates
///
/// Asssumes that we use the current module.
YAPPredicate(YAPFunctor f) {
CACHE_REGS
ap = RepPredProp(PredPropByFunc(f.f, Yap_CurrentModule()));
ap = RepPredProp(PredPropByFunc(f.f, Yap_CurrentModule()));
}
/// Functor constructor for predicates, is given a specific module.
@ -194,7 +191,6 @@ public:
///
YAPPredicate(YAPAtom at);
/// Mod:Name/Arity constructor for predicates.
///
inline YAPPredicate(YAPAtom at, uintptr_t arity, YAPModule mod) {
@ -214,14 +210,14 @@ public:
///
inline YAPPredicate(const char *at, uintptr_t arity) {
ap = RepPredProp(PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity),
CurrentModule));
Yap_CurrentModule()));
};
/// char */module constructor for predicates.
///
inline YAPPredicate(const char *at, uintptr_t arity, YAPTerm mod) {
ap = RepPredProp(
PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity), mod.term()));
PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity), mod.term()));
};
/// char */module constructor for predicates.
@ -256,7 +252,8 @@ public:
YAPFunctor functor() {
if (ap->ArityOfPE)
return YAPFunctor(ap->FunctorOfPred);
Yap_ThrowError(DOMAIN_ERROR_OUT_OF_RANGE, MkIntTerm(0), "YAPFunctor::functor");
Yap_ThrowError(DOMAIN_ERROR_OUT_OF_RANGE, MkIntTerm(0),
"YAPFunctor::functor");
}
/// arity of predicate
@ -279,7 +276,7 @@ public:
YAPPrologPredicate(YAPAtom s, arity_t arity) : YAPPredicate(s, arity){};
/// add a new clause
bool assertClause(YAPTerm clause, bool last = true,
YAPTerm source = YAPTerm());
YAPTerm source = YAPTerm());
/// add a new tuple
bool assertFact(YAPTerm *tuple, bool last = true);
/// retract at least the first clause matching the predicate.
@ -300,10 +297,9 @@ public:
YAPFLIP(YAP_UserCPred call, YAPAtom name, YAP_Arity arity,
YAPModule module = YAPModule(), YAP_UserCPred retry = 0,
YAP_UserCPred cut = 0, YAP_Arity extra = 0, bool test = false)
: YAPPredicate(name, arity, module) {
: YAPPredicate(name, arity, module) {
if (retry) {
YAP_UserBackCutCPredicate(name.getName(), call, retry, cut, arity, extra
);
YAP_UserBackCutCPredicate(name.getName(), call, retry, cut, arity, extra);
} else {
if (test) {
YAP_UserCPredicate(name.getName(), call, arity);
@ -314,7 +310,7 @@ public:
};
YAPFLIP(const char *name, uintptr_t arity, YAPModule module = YAPModule(),
bool backtrackable = false)
: YAPPredicate(YAPAtom(name), arity, module) {
: YAPPredicate(YAPAtom(name), arity, module) {
if (backtrackable) {
Yap_InitCPredBackCut(name, arity, 0, 0, 0, 0, UserCPredFlag);
} else {

View File

@ -125,6 +125,7 @@ YAPAtomTerm::YAPAtomTerm(char s[]) { // build string
CACHE_REGS
seq_tv_t inp, out;
inp.enc = LOCAL_encoding;
inp.val.c = s;
inp.type = YAP_STRING_CHARS;
out.type = YAP_STRING_ATOM;
@ -142,7 +143,8 @@ YAPAtomTerm::YAPAtomTerm(char *s, size_t len) { // build string
seq_tv_t inp, out;
inp.val.c = s;
inp.type = YAP_STRING_CHARS;
out.type = YAP_STRING_ATOM | YAP_STRING_NCHARS | YAP_STRING_TRUNC;
inp.enc = LOCAL_encoding;
out.type = YAP_STRING_ATOM | YAP_STRING_NCHARS | YAP_STRING_TRUNC;
out.max = len;
if (Yap_CVT_Text(&inp, &out PASS_REGS))
mk(MkAtomTerm(out.val.a));
@ -253,15 +255,78 @@ YAPApplTerm::YAPApplTerm(YAPFunctor f, YAPTerm ts[]) {
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(std::string f, std::vector<YAPTerm> ts) {
YAPApplTerm::YAPApplTerm(const std::string f, std::vector<Term> ts) {
BACKUP_H();
arity_t arity = ts.size();
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()), arity);
Term o = Yap_MkNewApplTerm(ff, arity);
Term *tt = RepAppl(o) + 1;
for (arity_t i = 0; i < arity; i++)
tt[i] = ts[i];
mk(o);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(const std::string f, std::vector<YAPTerm> ts) {
BACKUP_H();
arity_t arity = ts.size();
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()), arity);
Term o = Yap_MkNewApplTerm(ff, arity);
Term *tt = RepAppl(o) + 1;
for (arity_t i = 0; i < arity; i++)
tt[i] = ts[i].term();
mk(o);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(const std::string f, YAPTerm a1) {
BACKUP_H();
arity_t arity = ts.size();
arity_t arity = 1;
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()), arity);
Term o = Yap_MkNewApplTerm(ff, arity);
Term *tt = RepAppl(o) + 1;
for (arity_t i = 0; i < arity; i++)
tt[i] = ts[i].term();
tt[0] = a1.term();
mk(o);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(const std::string f, YAPTerm a1, YAPTerm a2) {
BACKUP_H();
arity_t arity = 2;
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()), arity);
Term o = Yap_MkNewApplTerm(ff, arity);
Term *tt = RepAppl(o) + 1;
tt[0] = a1.term();
tt[1] = a2.term();
mk(o);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(const std::string f, YAPTerm a1, YAPTerm a2, YAPTerm a3) {
BACKUP_H();
arity_t arity = 3;
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()), arity);
Term o = Yap_MkNewApplTerm(ff, arity);
Term *tt = RepAppl(o) + 1;
tt[0] = a1.term();
tt[2] = a2.term();
tt[3] = a3.term();
mk(o);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(const std::string f, YAPTerm a1, YAPTerm a2, YAPTerm a3, YAPTerm a4) {
BACKUP_H();
arity_t arity = 4;
Functor ff = Yap_MkFunctor(Yap_LookupAtom(f.c_str()), arity);
Term o = Yap_MkNewApplTerm(ff, arity);
Term *tt = RepAppl(o) + 1;
tt[0] = a1.term();
tt[2] = a2.term();
tt[3] = a3.term();
tt[4] = a4.term();
mk(o);
RECOVER_H();
}
YAPApplTerm::YAPApplTerm(YAPFunctor f) : YAPTerm() {
@ -517,14 +582,15 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
bool YAPEngine::mgoal(Term t, Term tmod, bool release) {
#if YAP_PYTHON
// std::cerr << "mgoal(in) " << YAPTerm(tmod).text() << ":" << YAPTerm(t).text() << "\n";
// PyThreadState *_save;
//std::cerr << "mgoal " << YAPTerm(t).text() << "\n";
// std::cerr << "mgoal " << YAPTerm(t).text() << "\n";
// _save = PyEval_SaveThread();
#endif
CACHE_REGS
BACKUP_MACHINE_REGS();
Term *ts = nullptr;
Term *ts = nullptr;
q.CurSlot = Yap_StartSlots();
q.p = P;
q.cp = CP;
@ -552,8 +618,8 @@ bool YAPEngine::mgoal(Term t, Term tmod, bool release) {
// don't forget, on success these guys may create slots
//__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
result = (bool)YAP_EnterGoal(ap, nullptr, &q);
//std::cerr << "mgoal " << YAPTerm(t).text() << "\n";
result = (bool)YAP_EnterGoal(ap, nullptr, &q);
// std::cerr << "mgoal " << YAPTerm(tmod).text() << ":" << YAPTerm(t).text() << "\n";
YAP_LeaveGoal(result && !release, &q);
// PyEval_RestoreThread(_save);
@ -574,7 +640,7 @@ void YAPEngine::release() {
Term YAPEngine::fun(Term t) {
CACHE_REGS
BACKUP_MACHINE_REGS();
Term tmod = CurrentModule, *ts = nullptr;
Term tmod = Yap_CurrentModule(), *ts = nullptr;
PredEntry *ap;
arity_t arity;
Functor f;
@ -601,8 +667,10 @@ Term YAPEngine::fun(Term t) {
throw YAPError(SOURCE(), TYPE_ERROR_CALLABLE, t, 0);
return 0L;
}
XREGS[arity + 1] = MkVarTerm();
Term ot = XREGS[arity + 1] = MkVarTerm();
yhandle_t h = Yap_InitHandle(ot);
arity++;
HR += arity;
f = Yap_MkFunctor(name, arity);
ap = (PredEntry *)(PredPropByFunc(f, tmod));
if (ap == nullptr || ap->OpcodeOfPred == UNDEF_OPCODE) {
@ -617,12 +685,16 @@ Term YAPEngine::fun(Term t) {
//__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
bool result = (bool)YAP_EnterGoal(ap, nullptr, &q);
YAPCatchError();
if (result)
ot = Yap_GetFromHandle(h);
else
ot = TermNone;
YAPCatchError();
{
YAP_LeaveGoal(result, &q);
// PyEval_RestoreThread(_save);
RECOVER_MACHINE_REGS();
return result;
return ot;
}
}
@ -874,9 +946,8 @@ YAPPredicate::YAPPredicate(YAPAtom at, uintptr_t arity) {
}
/// auxiliary routine to find a predicate in the current module.
PredEntry *YAPPredicate::getPred(Term &t, CELL *&out) {
PredEntry *YAPPredicate::getPred(Term &t, Term &m, CELL *&out) {
CACHE_REGS
Term m = Yap_CurrentModule();
t = Yap_StripModule(t, &m);
if (IsVarTerm(t) || IsNumTerm(t)) {

View File

@ -96,7 +96,7 @@ public:
inline YAPQuery(const char *s) : YAPPredicate(s, goal, names, (nts = &ARG1)) {
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "got game %ld",
LOCAL_CurSlot);
openQuery();
};
// inline YAPQuery() : YAPPredicate(s, tgoal, tnames)
@ -117,8 +117,8 @@ public:
YAPQuery(YAPTerm t) : YAPPredicate((goal = t.term()), (nts = &ARG1)) {
BACKUP_MACHINE_REGS();
openQuery();
names = YAPPairTerm(TermNil) ;
RECOVER_MACHINE_REGS();
names = YAPPairTerm(TermNil);
RECOVER_MACHINE_REGS();
}
/// set flags for query execution, currently only for exception handling
void setFlag(int flag) { q_flags |= flag; }
@ -177,7 +177,7 @@ public:
YAPEngineArgs() {
// const std::string *s = new std::string("startup.yss");
Embedded = true;
install = false;
install = false;
Yap_InitDefaults(this, nullptr, 0, nullptr);
#if YAP_PYTHON
@ -204,13 +204,13 @@ public:
inline void setMaxTrailSize(bool fl) { MaxTrailSize = fl; };
inline bool getMaxTrailSize() { return MaxTrailSize; };
inline bool getMaxTrailSize() { return MaxTrailSize; };
inline void createSavedState(bool fl) { install = fl; };
inline void createSavedState(bool fl) { install = fl; };
inline bool creatingSavedState() { return install; };
inline bool creatingSavedState() { return install; };
inline void setPLDIR(const char *fl) {
inline void setPLDIR(const char *fl) {
LIBDIR = (const char *)malloc(strlen(fl) + 1);
strcpy((char *)LIBDIR, fl);
};
@ -286,7 +286,7 @@ private:
void doInit(YAP_file_type_t BootMode, YAPEngineArgs *cargs);
YAP_dogoalinfo q;
YAPError e;
PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term &t, Term tmod);
PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term &t, Term tmod);
public:
/// construct a new engine; may use a variable number of arguments
@ -326,23 +326,26 @@ public:
/// build a query from a Prolog term (internal)
YAPQuery *qt(Term t) { return new YAPQuery(YAPTerm(t)); };
/// current module for the engine
YAPModule currentModule() { return YAPModule(); }
Term Yap_CurrentModule() { return CurrentModule; }
/// 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[]);
/// current directory for the engine
bool goal(YAPTerm Yt, YAPModule module, bool release=false)
{ return mgoal(Yt.term(),module.term(), release); };
bool goal(YAPTerm Yt, YAPModule module, bool release = false) {
return mgoal(Yt.term(), module.term(), release);
};
/// ru1n a goal in a module.
///
/// By default, memory will only be fully
/// recovered on backtracking. The release option ensures
/// backtracking is called at the very end.
bool mgoal(Term t, Term tmod, bool release= false);
bool mgoal(Term t, Term tmod, bool release = false);
/// current directory for the engine
bool goal(Term t, bool release=false) { return mgoal(t, CurrentModule, release); }
bool goal(Term t, bool release = false) {
return mgoal(t, Yap_CurrentModule(), release);
}
/// reset Prolog state
void reSet();
/// assune that there are no stack pointers, just release memory
@ -364,7 +367,7 @@ public:
//> output.
YAPTerm funCall(YAPTerm t) { return YAPTerm(fun(t.term())); };
Term fun(Term t);
Term fun(YAPTerm t) { return fun(t.term()); };
//Term fun(YAPTerm t) { return fun(t.term()); };
//> set a StringFlag, usually a path
//>
bool setStringFlag(std::string arg, std::string path) {

View File

@ -29,9 +29,7 @@ class YAPError;
extern "C" {
X_API extern Term YAP_MkCharPTerm( char *n);
X_API extern Term YAP_MkCharPTerm(char *n);
}
/**
@ -46,7 +44,7 @@ class X_API YAPTerm {
friend class YAPApplTerm;
friend class YAPListTerm;
protected:
protected:
yhandle_t t; /// handle to term, equivalent to term_t
public:
@ -93,7 +91,7 @@ public:
// fprintf(stderr,"-%d,%lx,%p ",t,LOCAL_HandleBase[t] ,HR);
/* if (!t)
return;
Yap_DebugPlWriteln(LOCAL_HandleBase[t]);
// Yap_DebugPlWriteln(LOCAL_HandleBase[t]);
LOCAL_HandleBase[t] = TermFreeTerm;
while (LOCAL_HandleBase[LOCAL_CurSlot - 1] == TermFreeTerm) {
LOCAL_CurSlot--;
@ -119,18 +117,18 @@ public:
inline Term term() {
return Deref(gt());
} /// from YAPTerm to Term (internal YAP representation)
YAPTerm arg(int i) {
BACKUP_MACHINE_REGS();
Term t0 = gt();
YAPTerm tf;
if (!IsApplTerm(t0) && !IsPairTerm(t))
return (Term)0;
tf = YAPTerm(ArgOfTerm(i, t0) );
RECOVER_MACHINE_REGS();
return tf;
};
YAPTerm arg(int i) {
BACKUP_MACHINE_REGS();
Term t0 = gt();
YAPTerm tf;
if (!IsApplTerm(t0) && !IsPairTerm(t))
return (Term)0;
tf = YAPTerm(ArgOfTerm(i, t0));
RECOVER_MACHINE_REGS();
return tf;
};
inline void bind(Term b) { LOCAL_HandleBase[t] = b; }
inline void bind(Term b) { LOCAL_HandleBase[t] = b; }
inline void bind(YAPTerm *b) { LOCAL_HandleBase[t] = b->term(); }
/// from YAPTerm to Term (internal YAP representation)
/// fetch a sub-term
@ -201,9 +199,10 @@ public:
virtual bool isGround() { return Yap_IsGroundTerm(gt()); } /// term is ground
virtual bool isList() { return Yap_IsListTerm(gt()); } /// term is a list
/// extract the argument i of the term, where i in 1...arityvoid *Yap_RepStreamFromId(int sno)
/// extract the argument i of the term, where i in 1...arityvoid
/// *Yap_RepStreamFromId(int sno)
virtual Term getArg(arity_t i);
/// extract the arity of the term
/// variables have arity 0
virtual inline arity_t arity() {
@ -226,7 +225,7 @@ public:
char *os;
BACKUP_MACHINE_REGS();
if (!(os = Yap_TermToBuffer(Yap_GetFromSlot(t), Handle_vars_f))) {
if (!(os = Yap_TermToBuffer(Yap_GetFromSlot(t), Handle_vars_f))) {
RECOVER_MACHINE_REGS();
return 0;
}
@ -292,45 +291,53 @@ public:
/**
* @brief Compound Term
*/
class X_API YAPApplTerm : public YAPTerm {
class X_API YAPApplTerm : public YAPTerm {
friend class YAPTerm;
public:
YAPApplTerm(Term t0) { mk(t0); }
YAPApplTerm(Functor f, Term ts[]) {
YAPApplTerm(Term t0) { mk(t0); }
YAPApplTerm(Functor f, Term ts[]) {
BACKUP_MACHINE_REGS();
Term t0 = Yap_MkApplTerm(f, f->ArityOfFE, ts);
mk(t0);
RECOVER_MACHINE_REGS();
};
YAPApplTerm(YAPFunctor f, YAPTerm ts[]);
YAPApplTerm(const std::string s, unsigned int arity) { mk(Yap_MkNewApplTerm(Yap_MkFunctor(Yap_LookupAtom(s.c_str()), arity), arity)); };
YAPApplTerm(const std::string s, unsigned int arity) {
mk(Yap_MkNewApplTerm(Yap_MkFunctor(Yap_LookupAtom(s.c_str()), arity),
arity));
};
YAPApplTerm(const std::string s, std::vector<Term> ts);
YAPApplTerm(const std::string s, std::vector<YAPTerm> ts);
YAPApplTerm(YAPFunctor f);
inline Functor functor() { return FunctorOfTerm(gt()); }
inline YAPFunctor getFunctor() { return YAPFunctor(FunctorOfTerm(gt())); }
YAPApplTerm(const std::string f, YAPTerm a1);
YAPApplTerm(const std::string f, YAPTerm a1, YAPTerm a2);
YAPApplTerm(const std::string f, YAPTerm a1, YAPTerm a2, YAPTerm a3);
YAPApplTerm(const std::string f, YAPTerm a1, YAPTerm a2, YAPTerm a3, YAPTerm a4);
Term getArg(arity_t i) {
BACKUP_MACHINE_REGS();
Term t0 = gt();
Term tf;
tf = ArgOfTerm(i, t0);
RECOVER_MACHINE_REGS();
return tf;
};
void putArg(int i, Term targ) {
//BACKUP_MACHINE_REGS();
Term t0 = gt();
RepAppl(t0)[i] = Deref(targ);
//RECOVER_MACHINE_REGS();
};
void putArg(int i, YAPTerm t) {
//BACKUP_MACHINE_REGS();
Term t0 = gt();
RepAppl(t0)[i] = t.term();
//RECOVER_MACHINE_REGS();
};
virtual bool isVar() { return false; } /// type check for unbound
BACKUP_MACHINE_REGS();
Term t0 = gt();
Term tf;
tf = ArgOfTerm(i, t0);
RECOVER_MACHINE_REGS();
return tf;
};
void putArg(int i, Term targ) {
// BACKUP_MACHINE_REGS();
Term t0 = gt();
RepAppl(t0)[i] = Deref(targ);
// RECOVER_MACHINE_REGS();
};
void putArg(int i, YAPTerm t) {
// BACKUP_MACHINE_REGS();
Term t0 = gt();
RepAppl(t0)[i] = t.term();
// RECOVER_MACHINE_REGS();
};
virtual bool isVar() { return false; } /// type check for unbound
virtual bool isAtom() { return false; } /// type check for atom
virtual bool isInteger() { return false; } /// type check for integer
virtual bool isFloat() { return false; } /// type check for floating-point
@ -465,7 +472,7 @@ public:
* Term Representation of an Atom
*/
class X_API YAPAtomTerm : public YAPTerm {
friend class YAPModule;
friend class YAPModule;
// Constructor: receives a C-atom;
YAPAtomTerm(Term t) : YAPTerm(t) { IsAtomTerm(t); }
@ -479,11 +486,12 @@ public:
YAPAtomTerm(char *s, size_t len);
// Constructor: receives a sequence of wchar_ts, whatever they may be;
YAPAtomTerm(wchar_t *s);
// Constructor: receives a sequence of n wchar_ts, whatever they may be;
YAPAtomTerm(wchar_t *s, size_t len);
// Constructor: receives a std::string;
// YAPAtomTerm(std::string s) { mk(MkAtomTerm(Yap_LookupAtom(s.c_str()))); };
bool isVar() { return false; } /// type check for unbound
// Constructor: receives a sequence of n wchar_ts, whatever they may be;
YAPAtomTerm(wchar_t *s, size_t len);
// Constructor: receives a std::string;
// YAPAtomTerm(std::string s) { mk(MkAtomTerm(Yap_LookupAtom(s.c_str())));
// };
bool isVar() { return false; } /// type check for unbound
bool isAtom() { return true; } /// type check for atom
bool isInteger() { return false; } /// type check for integer
bool isFloat() { return false; } /// type check for floating-point

View File

@ -7,6 +7,7 @@
// This is supported by YAP directly
// A Dot N "."
//
A AtSymbol N "@"
A 3Dots N "..."
A Abol F "$abol"
A Access N "access"
@ -37,6 +38,7 @@ A BeginCurlyBracket N "{"
A EndCurlyBracket N "}"
A EmptyBrackets N "()"
A EmptySquareBrackets N "[]"
A As N "as"
A Asserta N "asserta"
A AssertaStatic N "asserta_static"
A Assertz N "assertz"
@ -186,6 +188,7 @@ A GlobalSp N "global_sp"
A GlobalTrie N "global_trie"
A GoalExpansion N "goal_expansion"
A Hat N "^"
A DoubleHat N "^^"
A HERE N "\n <====HERE====> \n"
A HandleThrow F "$handle_throw"
A Heap N "heap"
@ -269,7 +272,7 @@ A NotLessThanZero N "not_less_than_zero"
A NotNewline N "not_newline"
A NotZero N "not_zero"
A Number N "number"
A Obj N "o__bj__"
A Obj N "__obj__"
A Off N "off"
A Offline N "offline"
A On N "on"
@ -458,8 +461,11 @@ F Arg Arg 3
F ArrayEntry ArrayAccess 3
F Arrow Arrow 2
F DoubleArrow DoubleArrow 2
F As As 2
F Assert1 Assert 1
F Assert Assert 2
F At At 2
F AtSymbol AtSymbol 2
F AtFoundOne FoundVar 2
F Atom Atom 1
F Att1 Att1 3
@ -533,6 +539,7 @@ F GoalExpansion2 GoalExpansion 2
F GoalExpansion GoalExpansion 3
F HandleThrow HandleThrow 3
F Hat Hat 2
F DoubleHat DoubleHat 1
F I I 2
F Id Id 1
F Info1 Info 1

View File

@ -129,4 +129,10 @@ void Yap_ShutdownLoadForeign(void);
#define EAGER_LOADING 1
#define GLOBAL_LOADING 2
/**
* stub can always be called at DLL loading.
*
*/
X_API bool load_none(void);
#endif

View File

@ -119,6 +119,9 @@ INLINE_ONLY Term aro(Term inp) {
// INLINE_ONLY Term booleanFlag( Term inp );
static inline Term booleanFlag(Term inp) {
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (inp == TermTrue || inp == TermOn)
return TermTrue;
if (inp == TermFalse || inp == TermOff)
@ -139,6 +142,9 @@ static inline Term booleanFlag(Term inp) {
}
static Term synerr(Term inp) {
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (inp == TermDec10 || inp == TermFail || inp == TermError ||
inp == TermQuiet)
return inp;
@ -172,12 +178,27 @@ static inline Term isatom(Term inp) {
"value must be bound");
return TermZERO;
}
if (IsStringTerm(inp)) {
inp = MkStringTerm(RepAtom(AtomOfTerm(inp))->StrOfAE);
}
if (IsAtomTerm(inp))
return inp;
Yap_Error(TYPE_ERROR_ATOM, inp, "set_prolog_flag");
return TermZERO;
}
static inline Term isadress(Term inp) {
if (IsVarTerm(inp)) {
Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag %s",
"value must be bound");
return TermZERO;
}
if (IsAddressTerm(inp))
return inp;
Yap_Error(TYPE_ERROR_ATOM, inp, "set_prolog_flag");
return TermZERO;
}
static inline Term options(Term inp) {
return Yap_IsGroundTerm(inp) ? inp : TermZERO;
}

View File

@ -156,10 +156,10 @@ typedef struct various_codes {
} all_heap_codes;
#include "hglobals.h"
#include "generated/hglobals.h"
#include "dhstruct.h"
#include "dglobals.h"
#include "generated/dhstruct.h"
#include "generated/dglobals.h"
#else
typedef struct various_codes {
/* memory allocation and management */
@ -169,15 +169,15 @@ typedef struct various_codes {
} all_heap_codes;
#include "tatoms.h"
#include "generated/tatoms.h"
#include "h0struct.h"
#include "generated/h0struct.h"
#include "h0globals.h"
#include "generated/h0globals.h"
#endif
#include "hlocals.h"
#include "generated/hlocals.h"
#include "dlocals.h"

View File

@ -179,19 +179,20 @@ extern Term Yap_tokRep(void *tokptr);
// standard strings
typedef enum {
YAP_STRING_STRING = 0x1, /// target is a string term
YAP_STRING_CODES = 0x2, /// target is a list of integer codes
YAP_STRING_ATOMS = 0x4, /// target is a list of kength-1 atom
YAP_STRING_ATOMS_CODES = 0x6, /// targt is list of atoms or codes
YAP_STRING_CHARS = 0x8, /// target is a buffer, with byte-sized units
YAP_STRING_WCHARS = 0x10, /// target is a buffer of wide chars
YAP_STRING_ATOM = 0x20, /// tarfet is an ayom
YAP_STRING_INT = 0x40, /// target is an integer term
YAP_STRING_FLOAT = 0x80, /// target is a floar term
YAP_STRING_BIG = 0x100, /// target is an big num term
YAP_STRING_DATUM = 0x200, /// associated with previous 3, use actual object if type, not tern
YAP_STRING_LENGTH = 0x400, /// input: length is fixed; output: return integer with length
typedef enum
{
YAP_STRING_STRING = 0x1, /// target is a string term
YAP_STRING_CODES = 0x2, /// target is a list of integer codes
YAP_STRING_ATOMS = 0x4, /// target is a list of kength-1 atom
YAP_STRING_ATOMS_CODES = 0x6, /// targt is list of atoms or codes
YAP_STRING_CHARS = 0x8, /// target is a buffer, with byte-sized units
YAP_STRING_WCHARS = 0x10, /// target is a buffer of wide chars
YAP_STRING_ATOM = 0x20, /// tarfet is an ayom
YAP_STRING_INT = 0x40, /// target is an integer term
YAP_STRING_FLOAT = 0x80, /// target is a floar term
YAP_STRING_BIG = 0x100, /// target is an big num term
YAP_STRING_DATUM = 0x200, /// associated with previous 3, use actual object if type, not tern
YAP_STRING_LENGTH = 0x400, /// input: length is fixed; output: return integer with length
YAP_STRING_NTH = 0x800, /// input: ignored; output: nth char
YAP_STRING_TERM = 0x1000, // Generic term, if nothing else given
YAP_STRING_DIFF = 0x2000, // difference list
@ -204,7 +205,8 @@ typedef enum {
YAP_STRING_UPCASE = 0x100000, // output on malloced buffer
YAP_STRING_DOWNCASE = 0x200000, // output on malloced buffer
YAP_STRING_IN_TMP = 0x400000, // temporary space has been allocated
YAP_STRING_OUTPUT_TERM = 0x800000 // when we're not sure
YAP_STRING_OUTPUT_TERM = 0x800000, // when we're not sure
YAP_STRING_PREFER_LIST = 0x1000000 // when we're not sure
} enum_seq_type_t;
typedef UInt seq_type_t;
@ -472,7 +474,7 @@ static inline Term Yap_AtomicToListOfCodes(Term t0 USES_REGS) {
seq_tv_t inp, out;
inp.val.t = t0;
inp.type = YAP_STRING_STRING | YAP_STRING_ATOM | YAP_STRING_INT |
YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_TERM;
YAP_STRING_FLOAT | YAP_STRING_BIG ;
out.val.uc = NULL;
out.type = YAP_STRING_CODES;
if (!Yap_CVT_Text(&inp, &out PASS_REGS))
@ -522,8 +524,7 @@ static inline Term Yap_AtomSWIToListOfAtoms(Term t0 USES_REGS) {
inp.val.t = t0;
inp.type = YAP_STRING_ATOM | YAP_STRING_STRING | YAP_STRING_INT |
YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_ATOMS_CODES |
YAP_STRING_TERM;
YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_ATOMS_CODES;
out.val.uc = NULL;
out.type = YAP_STRING_ATOMS;
@ -548,8 +549,8 @@ static inline Term Yap_AtomSWIToListOfCodes(Term t0 USES_REGS) {
inp.val.t = t0;
inp.type = YAP_STRING_ATOM | YAP_STRING_STRING | YAP_STRING_INT |
YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_ATOMS_CODES |YAP_STRING_ATOMS_CODES |YAP_STRING_ATOMS_CODES |
YAP_STRING_TERM;
YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_ATOMS_CODES | YAP_STRING_ATOMS_CODES | YAP_STRING_ATOMS_CODES |
YAP_STRING_TERM ;
out.val.uc = NULL;
out.type = YAP_STRING_CODES;
@ -589,7 +590,7 @@ static inline Term Yap_AtomSWIToString(Term t0 USES_REGS) {
inp.val.t = t0;
inp.type = YAP_STRING_ATOM | YAP_STRING_STRING | YAP_STRING_INT |
YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_ATOMS_CODES;
YAP_STRING_FLOAT | YAP_STRING_BIG | YAP_STRING_ATOMS_CODES ;
out.val.uc = NULL;
out.type = YAP_STRING_STRING;
out.enc = ENC_ISO_UTF8;
@ -959,7 +960,7 @@ static inline Term Yap_ListSWIToString(Term t0 USES_REGS) {
inp.val.t = t0;
inp.type = YAP_STRING_STRING | YAP_STRING_ATOM | YAP_STRING_ATOMS_CODES |
YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG |
YAP_STRING_OUTPUT_TERM;
YAP_STRING_OUTPUT_TERM | YAP_STRING_PREFER_LIST;
out.val.uc = NULL;
out.type = YAP_STRING_STRING;
out.enc = ENC_ISO_UTF8;

View File

@ -391,7 +391,7 @@ extern void Yap_InitSortPreds(void);
/* stack.c */
extern void Yap_InitStInfo(void);
extern void Yap_dump_stack(void);
extern void Yap_detect_bug_location(yamop *yap_pc, int where_from, int psize);
extern void Yap_output_bug_location(yamop *yap_pc, int where_from, int psize);
#if !defined(YAPOR) && !defined(THREADS)
extern bool Yap_search_for_static_predicate_in_use(struct pred_entry *, bool);
@ -493,7 +493,10 @@ extern Int Yap_TermHash(Term, Int, Int, int);
extern Int Yap_NumberVars(Term, Int, bool);
extern Term Yap_TermVariables(Term t, UInt arity USES_REGS);
extern Term Yap_UnNumberTerm(Term, int);
extern Int Yap_SkipList(Term *, Term **);
extern Int Yap_SkipList(Term *, Term **);
extern Term Yap_BreakRational(Term inp, UInt arity, Term *of, Term oi USES_REGS);
extern Term Yap_BreakTerml(Term inp, UInt arity, Term *of, Term oi USES_REGS);
/* yap.c */
/* write.c */

173
H/Yatom.h
View File

@ -20,15 +20,11 @@
#ifndef YATOM_H
#define YATOM_H 1
INLINE_ONLY Atom AbsAtom(AtomEntry *p);
INLINE_ONLY AtomEntry *RepAtom(Atom a);
#ifdef USE_OFFSETS
INLINE_ONLY Atom AbsAtom(AtomEntry *p) {
return (Atom)(Addr(p) - AtomBase);
}
INLINE_ONLY Atom AbsAtom(AtomEntry *p) { return (Atom)(Addr(p) - AtomBase); }
INLINE_ONLY AtomEntry *RepAtom(Atom a) {
return (AtomEntry *) (AtomBase + Unsigned (a);
@ -36,9 +32,7 @@ INLINE_ONLY AtomEntry *RepAtom(Atom a) {
#else
INLINE_ONLY Atom AbsAtom(AtomEntry *p) { return (Atom)(p); }
INLINE_ONLY AtomEntry *RepAtom(Atom a) {
return (AtomEntry *)(a);
}
INLINE_ONLY AtomEntry *RepAtom(Atom a) { return (AtomEntry *)(a); }
#endif
@ -46,9 +40,7 @@ INLINE_ONLY AtomEntry *RepAtom(Atom a) {
INLINE_ONLY Prop AbsProp(PropEntry *p);
INLINE_ONLY Prop AbsProp(PropEntry *p) {
return (Prop)(Addr(p) - AtomBase);
}
INLINE_ONLY Prop AbsProp(PropEntry *p) { return (Prop)(Addr(p) - AtomBase); }
INLINE_ONLY PropEntry *RepProp(Prop p);
@ -64,9 +56,7 @@ INLINE_ONLY Prop AbsProp(PropEntry *p) { return (Prop)(p); }
INLINE_ONLY PropEntry *RepProp(Prop p);
INLINE_ONLY PropEntry *RepProp(Prop p) {
return (PropEntry *)(p);
}
INLINE_ONLY PropEntry *RepProp(Prop p) { return (PropEntry *)(p); }
#endif
@ -88,15 +78,11 @@ INLINE_ONLY Prop AbsFunctorProp(FunctorEntry *p) {
INLINE_ONLY FunctorEntry *RepFunctorProp(Prop p);
INLINE_ONLY FunctorEntry *RepFunctorProp(Prop p) {
return (FunctorEntry *)(p);
}
INLINE_ONLY FunctorEntry *RepFunctorProp(Prop p) { return (FunctorEntry *)(p); }
INLINE_ONLY Prop AbsFunctorProp(FunctorEntry *p);
INLINE_ONLY Prop AbsFunctorProp(FunctorEntry *p) {
return (Prop)(p);
}
INLINE_ONLY Prop AbsFunctorProp(FunctorEntry *p) { return (Prop)(p); }
#endif
@ -172,15 +158,11 @@ INLINE_ONLY Prop AbsGlobalProp(GlobalEntry *p) {
INLINE_ONLY GlobalEntry *RepGlobalProp(Prop p);
INLINE_ONLY GlobalEntry *RepGlobalProp(Prop p) {
return (GlobalEntry *)(p);
}
INLINE_ONLY GlobalEntry *RepGlobalProp(Prop p) { return (GlobalEntry *)(p); }
INLINE_ONLY Prop AbsGlobalProp(GlobalEntry *p);
INLINE_ONLY Prop AbsGlobalProp(GlobalEntry *p) {
return (Prop)(p);
}
INLINE_ONLY Prop AbsGlobalProp(GlobalEntry *p) { return (Prop)(p); }
#endif
@ -221,17 +203,13 @@ INLINE_ONLY ModEntry *RepModProp(Prop p) {
INLINE_ONLY Prop AbsModProp(ModEntry *p);
INLINE_ONLY Prop AbsModProp(ModEntry *p) {
return (Prop)(Addr(p) - AtomBase);
}
INLINE_ONLY Prop AbsModProp(ModEntry *p) { return (Prop)(Addr(p) - AtomBase); }
#else
INLINE_ONLY ModEntry *RepModProp(Prop p);
INLINE_ONLY ModEntry *RepModProp(Prop p) {
return (ModEntry *)(p);
}
INLINE_ONLY ModEntry *RepModProp(Prop p) { return (ModEntry *)(p); }
INLINE_ONLY Prop AbsModProp(ModEntry *p);
@ -245,9 +223,7 @@ INLINE_ONLY Prop AbsModProp(ModEntry *p) { return (Prop)(p); }
INLINE_ONLY bool IsModProperty(int);
INLINE_ONLY bool IsModProperty(int flags) {
return flags == ModProperty;
}
INLINE_ONLY bool IsModProperty(int flags) { return flags == ModProperty; }
/* Flags on module. Most of these flags are copied to the read context
in pl-read.c.
@ -273,10 +249,10 @@ INLINE_ONLY bool IsModProperty(int flags) {
#define UNKNOWN_MASK \
(UNKNOWN_ERROR | UNKNOWN_WARNING | UNKNOWN_FAIL | UNKNOWN_FAST_FAIL | \
UNKNOWN_ABORT | UNKNOWN_HALT)
#define SNGQ_CHARS (0x10000) /* 'ab' --> [a, b] */
#define SNGQ_ATOM (0x20000) /* 'ab' --> ab */
#define SNGQ_STRING (0x40000) /* 'ab' --> "ab" */
#define SNGQ_CODES (0x80000) /* 'ab' --> [0'a, 0'b] */
#define SNGQ_CHARS (0x10000) /* 'ab' --> [a, b] */
#define SNGQ_ATOM (0x20000) /* 'ab' --> ab */
#define SNGQ_STRING (0x40000) /* 'ab' --> "ab" */
#define SNGQ_CODES (0x80000) /* 'ab' --> [0'a, 0'b] */
#define SNGQ_MASK (BCKQ_CHARS | BCKQ_ATOM | BCKQ_STRING | BCKQ_CODES)
Term Yap_getUnknownModule(ModEntry *m);
@ -305,9 +281,7 @@ INLINE_ONLY OpEntry *RepOpProp(Prop p) {
INLINE_ONLY Prop AbsOpProp(OpEntry *p);
INLINE_ONLY Prop AbsOpProp(OpEntry *p) {
return (Prop)(Addr(p) - AtomBase);
}
INLINE_ONLY Prop AbsOpProp(OpEntry *p) { return (Prop)(Addr(p) - AtomBase); }
#else
@ -324,9 +298,7 @@ INLINE_ONLY Prop AbsOpProp(OpEntry *p) { return (Prop)(p); }
INLINE_ONLY bool IsOpProperty(PropFlags);
INLINE_ONLY bool IsOpProperty(PropFlags flags) {
return flags == OpProperty;
}
INLINE_ONLY bool IsOpProperty(PropFlags flags) { return flags == OpProperty; }
typedef enum { INFIX_OP = 0, POSFIX_OP = 1, PREFIX_OP = 2 } op_type;
@ -365,17 +337,13 @@ INLINE_ONLY ExpEntry *RepExpProp(Prop p) {
INLINE_ONLY Prop AbsExpProp(ExpEntry *p);
INLINE_ONLY Prop AbsExpProp(ExpEntry *p) {
return (Prop)(Addr(p) - AtomBase);
}
INLINE_ONLY Prop AbsExpProp(ExpEntry *p) { return (Prop)(Addr(p) - AtomBase); }
#else
INLINE_ONLY ExpEntry *RepExpProp(Prop p);
INLINE_ONLY ExpEntry *RepExpProp(Prop p) {
return (ExpEntry *)(p);
}
INLINE_ONLY ExpEntry *RepExpProp(Prop p) { return (ExpEntry *)(p); }
INLINE_ONLY Prop AbsExpProp(ExpEntry *p);
@ -411,17 +379,13 @@ INLINE_ONLY ValEntry *RepValProp(Prop p) {
INLINE_ONLY Prop AbsValProp(ValEntry *p);
INLINE_ONLY Prop AbsValProp(ValEntry *p) {
return (Prop)(Addr(p) - AtomBase);
}
INLINE_ONLY Prop AbsValProp(ValEntry *p) { return (Prop)(Addr(p) - AtomBase); }
#else
INLINE_ONLY ValEntry *RepValProp(Prop p);
INLINE_ONLY ValEntry *RepValProp(Prop p) {
return (ValEntry *)(p);
}
INLINE_ONLY ValEntry *RepValProp(Prop p) { return (ValEntry *)(p); }
INLINE_ONLY Prop AbsValProp(ValEntry *p);
@ -592,10 +556,7 @@ INLINE_ONLY Prop AbsPredProp(PredEntry *p) {
INLINE_ONLY PredEntry *RepPredProp(Prop p);
INLINE_ONLY PredEntry *RepPredProp(Prop p) {
return (PredEntry *)(p);
}
INLINE_ONLY PredEntry *RepPredProp(Prop p) { return (PredEntry *)(p); }
INLINE_ONLY Prop AbsPredProp(PredEntry *p);
@ -717,8 +678,8 @@ typedef struct DB_STRUCT {
struct DB_STRUCT *p, *n; /* entry's age, negative if from recorda,
positive if it was recordz */
CELL Mask; /* parts that should be cleared */
CELL Key; /* A mask that can be used to check before
you unify */
CELL Key; /* A mask that can be used to check before
you unify */
DBTerm DBT;
} DBStruct;
@ -755,9 +716,7 @@ INLINE_ONLY Term MkDBRefTerm(DBRef p) {
INLINE_ONLY DBRef DBRefOfTerm(Term t);
INLINE_ONLY DBRef DBRefOfTerm(Term t) {
return (DBRef)(((DBRef)(RepAppl(t))));
}
INLINE_ONLY DBRef DBRefOfTerm(Term t) { return (DBRef)(((DBRef)(RepAppl(t)))); }
INLINE_ONLY int IsRefTerm(Term);
@ -767,9 +726,7 @@ INLINE_ONLY int IsRefTerm(Term t) {
INLINE_ONLY CODEADDR RefOfTerm(Term t);
INLINE_ONLY CODEADDR RefOfTerm(Term t) {
return (CODEADDR)(DBRefOfTerm(t));
}
INLINE_ONLY CODEADDR RefOfTerm(Term t) { return (CODEADDR)(DBRefOfTerm(t)); }
typedef struct struct_dbentry {
Prop NextOfPE; /* used to chain properties */
@ -822,9 +779,7 @@ INLINE_ONLY DBProp RepDBProp(Prop p) {
INLINE_ONLY Prop AbsDBProp(DBProp p);
INLINE_ONLY Prop AbsDBProp(DBProp p) {
return (Prop)(Addr(p) - AtomBase);
}
INLINE_ONLY Prop AbsDBProp(DBProp p) { return (Prop)(Addr(p) - AtomBase); }
#else
@ -885,9 +840,7 @@ INLINE_ONLY BlackBoardEntry *RepBBProp(Prop p) {
INLINE_ONLY Prop AbsBBProp(BlackBoardEntry *p);
INLINE_ONLY Prop AbsBBProp(BlackBoardEntry *p) {
return (Prop)(p);
}
INLINE_ONLY Prop AbsBBProp(BlackBoardEntry *p) { return (Prop)(p); }
#endif
@ -924,9 +877,7 @@ INLINE_ONLY Prop AbsHoldProp(HoldEntry *p) {
INLINE_ONLY HoldEntry *RepHoldProp(Prop p);
INLINE_ONLY HoldEntry *RepHoldProp(Prop p) {
return (HoldEntry *)(p);
}
INLINE_ONLY HoldEntry *RepHoldProp(Prop p) { return (HoldEntry *)(p); }
INLINE_ONLY Prop AbsHoldProp(HoldEntry *p);
@ -968,9 +919,7 @@ INLINE_ONLY TranslationEntry *RepTranslationProp(Prop p) {
INLINE_ONLY Prop AbsTranslationProp(TranslationEntry *p);
INLINE_ONLY Prop AbsTranslationProp(TranslationEntry *p) {
return (Prop)(p);
}
INLINE_ONLY Prop AbsTranslationProp(TranslationEntry *p) { return (Prop)(p); }
#endif
#define TranslationProperty 0xfff4
@ -1027,9 +976,7 @@ INLINE_ONLY Prop AbsMutexProp(MutexEntry *p) {
INLINE_ONLY MutexEntry *RepMutexProp(Prop p);
INLINE_ONLY MutexEntry *RepMutexProp(Prop p) {
return (MutexEntry *)(p);
}
INLINE_ONLY MutexEntry *RepMutexProp(Prop p) { return (MutexEntry *)(p); }
INLINE_ONLY Prop AbsMutexProp(MutexEntry *p);
@ -1151,9 +1098,7 @@ INLINE_ONLY Prop AbsStaticArrayProp(StaticArrayEntry *p) {
INLINE_ONLY ArrayEntry *RepArrayProp(Prop p);
INLINE_ONLY ArrayEntry *RepArrayProp(Prop p) {
return (ArrayEntry *)(p);
}
INLINE_ONLY ArrayEntry *RepArrayProp(Prop p) { return (ArrayEntry *)(p); }
INLINE_ONLY Prop AbsArrayProp(ArrayEntry *p);
@ -1167,9 +1112,7 @@ INLINE_ONLY StaticArrayEntry *RepStaticArrayProp(Prop p) {
INLINE_ONLY Prop AbsStaticArrayProp(StaticArrayEntry *p);
INLINE_ONLY Prop AbsStaticArrayProp(StaticArrayEntry *p) {
return (Prop)(p);
}
INLINE_ONLY Prop AbsStaticArrayProp(StaticArrayEntry *p) { return (Prop)(p); }
#endif
#define ArrayProperty ((PropFlags)0xfff7)
@ -1217,9 +1160,7 @@ INLINE_ONLY YAP_BlobPropEntry *RepBlobProp(Prop p) {
INLINE_ONLY Prop AbsBlobProp(YAP_BlobPropEntry *p);
INLINE_ONLY Prop AbsBlobProp(YAP_BlobPropEntry *p) {
return (Prop)(p);
}
INLINE_ONLY Prop AbsBlobProp(YAP_BlobPropEntry *p) { return (Prop)(p); }
#endif
@ -1240,9 +1181,7 @@ INLINE_ONLY bool IsBlob(Atom at) {
INLINE_ONLY bool IsValProperty(PropFlags);
INLINE_ONLY bool IsValProperty(PropFlags flags) {
return flags == ValProperty;
}
INLINE_ONLY bool IsValProperty(PropFlags flags) { return flags == ValProperty; }
/* flag property entry structure */
@ -1270,17 +1209,13 @@ INLINE_ONLY FlagEntry *RepFlagProp(Prop p) {
INLINE_ONLY Prop AbsFlagProp(FlagEntry *p);
INLINE_ONLY Prop AbsValProp(FlagEntry *p) {
return (Prop)(Addr(p) - AtomBase);
}
INLINE_ONLY Prop AbsValProp(FlagEntry *p) { return (Prop)(Addr(p) - AtomBase); }
#else
INLINE_ONLY FlagEntry *RepFlagProp(Prop p);
INLINE_ONLY FlagEntry *RepFlagProp(Prop p) {
return (FlagEntry *)(p);
}
INLINE_ONLY FlagEntry *RepFlagProp(Prop p) { return (FlagEntry *)(p); }
INLINE_ONLY Prop AbsFlagProp(FlagEntry *p);
@ -1297,10 +1232,9 @@ INLINE_ONLY bool IsFlagProperty(PropFlags flags) {
/* Proto types */
extern char *Yap_TermToBuffer(Term t, int flags);
extern Term Yap_BufferToTerm(const char *s, Term opts);
extern Term Yap_BufferToTerm(const char *s, Term opts);
/* cdmgr.c */
extern int Yap_RemoveIndexation(PredEntry *);
@ -1337,17 +1271,14 @@ Prop Yap_GetAPropHavingLock(AtomEntry *, PropFlags);
INLINE_ONLY UInt PRED_HASH(FunctorEntry *, Term, UInt);
INLINE_ONLY UInt PRED_HASH(FunctorEntry *fe, Term cur_mod,
UInt size) {
INLINE_ONLY UInt PRED_HASH(FunctorEntry *fe, Term cur_mod, UInt size) {
return (((CELL)fe + cur_mod) >> 2) % size;
}
INLINE_ONLY Prop GetPredPropByFuncAndModHavingLock(FunctorEntry *,
Term);
INLINE_ONLY Prop GetPredPropByFuncAndModHavingLock(FunctorEntry *, Term);
INLINE_ONLY Prop PredPropByFuncAndMod(FunctorEntry *, Term);
INLINE_ONLY Prop PredPropByAtomAndMod(Atom, Term);
INLINE_ONLY Prop GetPredPropByFuncHavingLock(FunctorEntry *,
Term);
INLINE_ONLY Prop GetPredPropByFuncHavingLock(FunctorEntry *, Term);
INLINE_ONLY Prop PredPropByFunc(Functor fe, Term cur_mod);
INLINE_ONLY Prop PredPropByAtom(Atom at, Term cur_mod);
@ -1355,8 +1286,7 @@ INLINE_ONLY Prop PredPropByAtom(Atom at, Term cur_mod);
Prop Yap_NewThreadPred(struct pred_entry *CACHE_TYPE);
Prop Yap_NewPredPropByFunctor(Functor, Term);
INLINE_ONLY struct pred_entry *
Yap_GetThreadPred(struct pred_entry *CACHE_TYPE);
INLINE_ONLY struct pred_entry *Yap_GetThreadPred(struct pred_entry *CACHE_TYPE);
INLINE_ONLY struct pred_entry *
Yap_GetThreadPred(struct pred_entry *ap USES_REGS) {
@ -1374,8 +1304,7 @@ Yap_GetThreadPred(struct pred_entry *ap USES_REGS) {
}
#endif
INLINE_ONLY Prop GetPredPropByFuncHavingLock(FunctorEntry *fe,
Term cur_mod) {
INLINE_ONLY Prop GetPredPropByFuncHavingLock(FunctorEntry *fe, Term cur_mod) {
PredEntry *p;
if (!(p = RepPredProp(fe->PropsOfFE))) {
@ -1428,8 +1357,8 @@ INLINE_ONLY Prop PredPropByFunc(Functor fe, Term cur_mod)
return Yap_NewPredPropByFunctor(fe, cur_mod);
}
INLINE_ONLY Prop
GetPredPropByFuncAndModHavingLock(FunctorEntry *fe, Term cur_mod) {
INLINE_ONLY Prop GetPredPropByFuncAndModHavingLock(FunctorEntry *fe,
Term cur_mod) {
PredEntry *p;
if (!(p = RepPredProp(fe->PropsOfFE))) {
@ -1574,9 +1503,7 @@ INLINE_ONLY const char *AtomName(Atom at);
*
* @return a ponter to an immutable sequence of characters.
*/
INLINE_ONLY const char *AtomName(Atom at) {
return RepAtom(at)->rep.uStrOfAE;
}
INLINE_ONLY const char *AtomName(Atom at) { return RepAtom(at)->rep.uStrOfAE; }
INLINE_ONLY const char *AtomTermName(Term t);
@ -1599,17 +1526,17 @@ extern Term MkErrorTerm(yap_error_descriptor_t *t);
extern bool Yap_ResetException(yap_error_descriptor_t *i);
extern bool Yap_HasException(void);
extern yap_error_descriptor_t * Yap_GetException();
extern void Yap_PrintException(void);
extern yap_error_descriptor_t *Yap_GetException();
extern void Yap_PrintException(yap_error_descriptor_t *i);
INLINE_ONLY bool Yap_HasException(void) {
return LOCAL_ActiveError->errorNo != YAP_NO_ERROR;
}
INLINE_ONLY Term MkSysError(yap_error_descriptor_t *i) {
Term et = MkAddressTerm(i);
return Yap_MkApplTerm( FunctorException, 1, &et);
return Yap_MkApplTerm(FunctorException, 1, &et);
}
yap_error_descriptor_t *Yap_UserError( Term t, yap_error_descriptor_t *i);
yap_error_descriptor_t *Yap_UserError(Term t, yap_error_descriptor_t *i);
extern bool Yap_RaiseException(void);

View File

@ -96,10 +96,11 @@ typedef struct FREEB {
/* Operating system and architecture dependent page size */
extern size_t Yap_page_size;
void Yap_InitHeap(void *);
UInt Yap_ExtendWorkSpaceThroughHole(UInt);
void Yap_AllocHole(UInt, UInt);
extern void Yap_InitHeap(void *);
extern UInt Yap_ExtendWorkSpaceThroughHole(UInt);
extern void Yap_AllocHole(UInt, UInt);
extern size_t Yap_HeapUsed(void);
;
#if USE_SYSTEM_MMAP && ! defined(__CYGWIN__)
#include <sys/types.h>
@ -107,7 +108,7 @@ void Yap_AllocHole(UInt, UInt);
#elif USE_SYSTEM_SHM
#elif USE_SBRK
@ -120,10 +121,10 @@ void *sbrk(caddr_t);
typedef unsigned size_t;
MALLOC_T malloc(size_t);
void free(MALLOC_T);
MALLOC_T realloc(MALLOC_T,size_t);
MALLOC_T calloc(size_t,size_t);
extern MALLOC_T malloc(size_t);
extern void free(MALLOC_T);
extern MALLOC_T realloc(MALLOC_T,size_t);
extern MALLOC_T calloc(size_t,size_t);
#endif

View File

@ -2,6 +2,7 @@
/* This file, iatoms.h, was generated automatically by "yap -L misc/buildatoms"
{lease do not update, update misc/ATOMS instead */
AtomAtSymbol = Yap_LookupAtom("@"); TermAtSymbol = MkAtomTerm(AtomAtSymbol);
Atom3Dots = Yap_LookupAtom("...");
AtomAbol = Yap_FullLookupAtom("$abol"); TermAbol = MkAtomTerm(AtomAbol);
AtomAccess = Yap_LookupAtom("access"); TermAccess = MkAtomTerm(AtomAccess);
@ -32,6 +33,7 @@
AtomEndCurlyBracket = Yap_LookupAtom("}"); TermEndCurlyBracket = MkAtomTerm(AtomEndCurlyBracket);
AtomEmptyBrackets = Yap_LookupAtom("()"); TermEmptyBrackets = MkAtomTerm(AtomEmptyBrackets);
AtomEmptySquareBrackets = Yap_LookupAtom("[]"); TermEmptySquareBrackets = MkAtomTerm(AtomEmptySquareBrackets);
AtomAs = Yap_LookupAtom("as"); TermAs = MkAtomTerm(AtomAs);
AtomAsserta = Yap_LookupAtom("asserta"); TermAsserta = MkAtomTerm(AtomAsserta);
AtomAssertaStatic = Yap_LookupAtom("asserta_static"); TermAssertaStatic = MkAtomTerm(AtomAssertaStatic);
AtomAssertz = Yap_LookupAtom("assertz"); TermAssertz = MkAtomTerm(AtomAssertz);
@ -181,6 +183,7 @@
AtomGlobalTrie = Yap_LookupAtom("global_trie"); TermGlobalTrie = MkAtomTerm(AtomGlobalTrie);
AtomGoalExpansion = Yap_LookupAtom("goal_expansion"); TermGoalExpansion = MkAtomTerm(AtomGoalExpansion);
AtomHat = Yap_LookupAtom("^"); TermHat = MkAtomTerm(AtomHat);
AtomDoubleHat = Yap_LookupAtom("^^"); TermDoubleHat = MkAtomTerm(AtomDoubleHat);
AtomHERE = Yap_LookupAtom("\n <====HERE====> \n"); TermHERE = MkAtomTerm(AtomHERE);
AtomHandleThrow = Yap_FullLookupAtom("$handle_throw"); TermHandleThrow = MkAtomTerm(AtomHandleThrow);
AtomHeap = Yap_LookupAtom("heap"); TermHeap = MkAtomTerm(AtomHeap);
@ -264,7 +267,7 @@
AtomNotNewline = Yap_LookupAtom("not_newline"); TermNotNewline = MkAtomTerm(AtomNotNewline);
AtomNotZero = Yap_LookupAtom("not_zero"); TermNotZero = MkAtomTerm(AtomNotZero);
AtomNumber = Yap_LookupAtom("number"); TermNumber = MkAtomTerm(AtomNumber);
AtomObj = Yap_LookupAtom("o__bj__"); TermObj = MkAtomTerm(AtomObj);
AtomObj = Yap_LookupAtom("__obj__"); TermObj = MkAtomTerm(AtomObj);
AtomOff = Yap_LookupAtom("off"); TermOff = MkAtomTerm(AtomOff);
AtomOffline = Yap_LookupAtom("offline"); TermOffline = MkAtomTerm(AtomOffline);
AtomOn = Yap_LookupAtom("on"); TermOn = MkAtomTerm(AtomOn);
@ -453,8 +456,11 @@
FunctorArrayEntry = Yap_MkFunctor(AtomArrayAccess,3);
FunctorArrow = Yap_MkFunctor(AtomArrow,2);
FunctorDoubleArrow = Yap_MkFunctor(AtomDoubleArrow,2);
FunctorAs = Yap_MkFunctor(AtomAs,2);
FunctorAssert1 = Yap_MkFunctor(AtomAssert,1);
FunctorAssert = Yap_MkFunctor(AtomAssert,2);
FunctorAt = Yap_MkFunctor(AtomAt,2);
FunctorAtSymbol = Yap_MkFunctor(AtomAtSymbol,2);
FunctorAtFoundOne = Yap_MkFunctor(AtomFoundVar,2);
FunctorAtom = Yap_MkFunctor(AtomAtom,1);
FunctorAtt1 = Yap_MkFunctor(AtomAtt1,3);
@ -528,6 +534,7 @@
FunctorGoalExpansion = Yap_MkFunctor(AtomGoalExpansion,3);
FunctorHandleThrow = Yap_MkFunctor(AtomHandleThrow,3);
FunctorHat = Yap_MkFunctor(AtomHat,2);
FunctorDoubleHat = Yap_MkFunctor(AtomDoubleHat,1);
FunctorI = Yap_MkFunctor(AtomI,2);
FunctorId = Yap_MkFunctor(AtomId,1);
FunctorInfo1 = Yap_MkFunctor(AtomInfo,1);

View File

@ -2,6 +2,7 @@
/* This file, ratoms.h, was generated automatically by "yap -L misc/buildatoms"
{lease do not update, update misc/ATOMS instead */
AtomAtSymbol = AtomAdjust(AtomAtSymbol); TermAtSymbol = MkAtomTerm(AtomAtSymbol);
Atom3Dots = AtomAdjust(Atom3Dots);
AtomAbol = AtomAdjust(AtomAbol); TermAbol = MkAtomTerm(AtomAbol);
AtomAccess = AtomAdjust(AtomAccess); TermAccess = MkAtomTerm(AtomAccess);
@ -32,6 +33,7 @@
AtomEndCurlyBracket = AtomAdjust(AtomEndCurlyBracket); TermEndCurlyBracket = MkAtomTerm(AtomEndCurlyBracket);
AtomEmptyBrackets = AtomAdjust(AtomEmptyBrackets); TermEmptyBrackets = MkAtomTerm(AtomEmptyBrackets);
AtomEmptySquareBrackets = AtomAdjust(AtomEmptySquareBrackets); TermEmptySquareBrackets = MkAtomTerm(AtomEmptySquareBrackets);
AtomAs = AtomAdjust(AtomAs); TermAs = MkAtomTerm(AtomAs);
AtomAsserta = AtomAdjust(AtomAsserta); TermAsserta = MkAtomTerm(AtomAsserta);
AtomAssertaStatic = AtomAdjust(AtomAssertaStatic); TermAssertaStatic = MkAtomTerm(AtomAssertaStatic);
AtomAssertz = AtomAdjust(AtomAssertz); TermAssertz = MkAtomTerm(AtomAssertz);
@ -181,6 +183,7 @@
AtomGlobalTrie = AtomAdjust(AtomGlobalTrie); TermGlobalTrie = MkAtomTerm(AtomGlobalTrie);
AtomGoalExpansion = AtomAdjust(AtomGoalExpansion); TermGoalExpansion = MkAtomTerm(AtomGoalExpansion);
AtomHat = AtomAdjust(AtomHat); TermHat = MkAtomTerm(AtomHat);
AtomDoubleHat = AtomAdjust(AtomDoubleHat); TermDoubleHat = MkAtomTerm(AtomDoubleHat);
AtomHERE = AtomAdjust(AtomHERE); TermHERE = MkAtomTerm(AtomHERE);
AtomHandleThrow = AtomAdjust(AtomHandleThrow); TermHandleThrow = MkAtomTerm(AtomHandleThrow);
AtomHeap = AtomAdjust(AtomHeap); TermHeap = MkAtomTerm(AtomHeap);
@ -453,8 +456,11 @@
FunctorArrayEntry = FuncAdjust(FunctorArrayEntry);
FunctorArrow = FuncAdjust(FunctorArrow);
FunctorDoubleArrow = FuncAdjust(FunctorDoubleArrow);
FunctorAs = FuncAdjust(FunctorAs);
FunctorAssert1 = FuncAdjust(FunctorAssert1);
FunctorAssert = FuncAdjust(FunctorAssert);
FunctorAt = FuncAdjust(FunctorAt);
FunctorAtSymbol = FuncAdjust(FunctorAtSymbol);
FunctorAtFoundOne = FuncAdjust(FunctorAtFoundOne);
FunctorAtom = FuncAdjust(FunctorAtom);
FunctorAtt1 = FuncAdjust(FunctorAtt1);
@ -528,6 +534,7 @@
FunctorGoalExpansion = FuncAdjust(FunctorGoalExpansion);
FunctorHandleThrow = FuncAdjust(FunctorHandleThrow);
FunctorHat = FuncAdjust(FunctorHat);
FunctorDoubleHat = FuncAdjust(FunctorDoubleHat);
FunctorI = FuncAdjust(FunctorI);
FunctorId = FuncAdjust(FunctorId);
FunctorInfo1 = FuncAdjust(FunctorInfo1);

View File

@ -2,6 +2,7 @@
/* This file, tatoms.h, was generated automatically by "yap -L misc/buildatoms"
{lease do not update, update misc/ATOMS instead */
X_API EXTERNAL Atom AtomAtSymbol; X_API EXTERNAL Term TermAtSymbol;
X_API EXTERNAL Atom Atom3Dots;
X_API EXTERNAL Atom AtomAbol; X_API EXTERNAL Term TermAbol;
X_API EXTERNAL Atom AtomAccess; X_API EXTERNAL Term TermAccess;
@ -32,6 +33,7 @@ X_API EXTERNAL Atom AtomBeginCurlyBracket; X_API EXTERNAL Term TermBeginCurlyBra
X_API EXTERNAL Atom AtomEndCurlyBracket; X_API EXTERNAL Term TermEndCurlyBracket;
X_API EXTERNAL Atom AtomEmptyBrackets; X_API EXTERNAL Term TermEmptyBrackets;
X_API EXTERNAL Atom AtomEmptySquareBrackets; X_API EXTERNAL Term TermEmptySquareBrackets;
X_API EXTERNAL Atom AtomAs; X_API EXTERNAL Term TermAs;
X_API EXTERNAL Atom AtomAsserta; X_API EXTERNAL Term TermAsserta;
X_API EXTERNAL Atom AtomAssertaStatic; X_API EXTERNAL Term TermAssertaStatic;
X_API EXTERNAL Atom AtomAssertz; X_API EXTERNAL Term TermAssertz;
@ -181,6 +183,7 @@ X_API EXTERNAL Atom AtomGlobalSp; X_API EXTERNAL Term TermGlobalSp;
X_API EXTERNAL Atom AtomGlobalTrie; X_API EXTERNAL Term TermGlobalTrie;
X_API EXTERNAL Atom AtomGoalExpansion; X_API EXTERNAL Term TermGoalExpansion;
X_API EXTERNAL Atom AtomHat; X_API EXTERNAL Term TermHat;
X_API EXTERNAL Atom AtomDoubleHat; X_API EXTERNAL Term TermDoubleHat;
X_API EXTERNAL Atom AtomHERE; X_API EXTERNAL Term TermHERE;
X_API EXTERNAL Atom AtomHandleThrow; X_API EXTERNAL Term TermHandleThrow;
X_API EXTERNAL Atom AtomHeap; X_API EXTERNAL Term TermHeap;
@ -461,10 +464,16 @@ X_API EXTERNAL Functor FunctorArrow;
X_API EXTERNAL Functor FunctorDoubleArrow;
X_API EXTERNAL Functor FunctorAs;
X_API EXTERNAL Functor FunctorAssert1;
X_API EXTERNAL Functor FunctorAssert;
X_API EXTERNAL Functor FunctorAt;
X_API EXTERNAL Functor FunctorAtSymbol;
X_API EXTERNAL Functor FunctorAtFoundOne;
X_API EXTERNAL Functor FunctorAtom;
@ -611,6 +620,8 @@ X_API EXTERNAL Functor FunctorHandleThrow;
X_API EXTERNAL Functor FunctorHat;
X_API EXTERNAL Functor FunctorDoubleHat;
X_API EXTERNAL Functor FunctorI;
X_API EXTERNAL Functor FunctorId;

View File

@ -1,4 +1,4 @@
l/****************************************************************************
/****************************************************************************
**
** Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
@ -37,29 +37,27 @@ l/****************************************************************************
#include <QPlainTextEdit>
class Console : public QPlainTextEdit
{
Q_OBJECT
class Console : public QPlainTextEdit {
Q_OBJECT
signals:
void getData(const QString &data);
void getData(const QString &data);
public:
explicit Console(QWidget *parent = 0);
explicit Console(QWidget *parent = 0);
void putData(const QString &data);
void putData(const QString &data);
void setLocalEchoEnabled(bool set);
void setLocalEchoEnabled(bool set);
protected:
virtual void keyPressEvent(QKeyEvent *e);
virtual void mousePressEvent(QMouseEvent *e);
virtual void mouseDoubleClickEvent(QMouseEvent *e);
virtual void contextMenuEvent(QContextMenuEvent *e);
virtual void keyPressEvent(QKeyEvent *e);
virtual void mousePressEvent(QMouseEvent *e);
virtual void mouseDoubleClickEvent(QMouseEvent *e);
virtual void contextMenuEvent(QContextMenuEvent *e);
private:
bool localEchoEnabled;
bool localEchoEnabled;
};
#endif // CONSOLE_H

View File

@ -1,16 +1,16 @@
/*************************************************************************
* *
* YAP Prolog %W% %G% *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 *
* *
**************************************************************************
* *
* File: YapError.h * mods:
** comments: error header file for YAP *
* version: $Id: Yap.h,v 1.38 2008-06-18 10:02:27 vsc Exp $ *
*************************************************************************/
* *
* YAP Prolog %W% %G% *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 *
* *
**************************************************************************
* *
* File: YapError.h * mods:
** comments: error header file for YAP *
* version: $Id: Yap.h,v 1.38 2008-06-18 10:02:27 vsc Exp $ *
*************************************************************************/
#ifndef YAP_ERROR_H
#define YAP_ERROR_H 1
@ -38,13 +38,12 @@
#define MAX_ERROR_MSG_SIZE 1024
extern void
Yap_InitError__(const char *file, const char *function, int lineno,
yap_error_number e, YAP_Term g, ...);
extern void Yap_InitError__(const char *file, const char *function, int lineno,
yap_error_number e, YAP_Term g, ...);
extern struct yami *Yap_Error__(bool thrw, const char *file, const char *function,
int lineno, yap_error_number err,
YAP_Term wheret, ...);
extern struct yami *Yap_Error__(bool thrw, const char *file,
const char *function, int lineno,
yap_error_number err, YAP_Term wheret, ...);
extern void Yap_ThrowError__(const char *file, const char *function, int lineno,
yap_error_number err, YAP_Term wheret, ...)
@ -54,13 +53,13 @@ extern void Yap_ThrowError__(const char *file, const char *function, int lineno,
;
#define Yap_NilError(id, ...) \
Yap_Error__(false,__FILE__, __FUNCTION__, __LINE__, id, TermNil, __VA_ARGS__)
Yap_Error__(false, __FILE__, __FUNCTION__, __LINE__, id, TermNil, __VA_ARGS__)
#define Yap_InitError(id, ...) \
Yap_InitError__(__FILE__, __FUNCTION__, __LINE__, id, TermNil, __VA_ARGS__)
#define Yap_Error(id, inp, ...) \
Yap_Error__(false,__FILE__, __FUNCTION__, __LINE__, id, inp, __VA_ARGS__)
Yap_Error__(false, __FILE__, __FUNCTION__, __LINE__, id, inp, __VA_ARGS__)
#define Yap_ThrowError(id, inp, ...) \
Yap_ThrowError__(__FILE__, __FUNCTION__, __LINE__, id, inp, __VA_ARGS__)
@ -74,18 +73,18 @@ extern void Yap_ThrowError__(const char *file, const char *function, int lineno,
{ if ( (TF = Yap_ensure_atom__(__FILE__, __FUNCTION__, __LINE__, T0 ) == 0L ) return false; \
}
INLINE_ONLY Term Yap_ensure_atom__(const char *fu, const char *fi,
int line, Term in) {
INLINE_ONLY 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))
return t;
if (IsVarTerm(t)) {
Yap_Error__(false,fu, fi, line, INSTANTIATION_ERROR, t, NULL);
Yap_Error__(false, fu, fi, line, INSTANTIATION_ERROR, t, NULL);
} else {
if (IsAtomTerm(t))
return t;
Yap_Error__(false,fu, fi, line, TYPE_ERROR_ATOM, t, NULL);
Yap_Error__(false, fu, fi, line, TYPE_ERROR_ATOM, t, NULL);
return 0L;
}
@ -114,8 +113,8 @@ INLINE_ONLY Term Yap_ensure_atom__(const char *fu, const char *fi,
#define AUX_ERROR(t, n, s, TYPE) \
if (s + (n + 1) > (TYPE *)AuxSp) { \
pop_text_stack(lvl); \
LOCAL_Error_TYPE = RESOURCE_ERROR_AUXILIARY_STACK; \
pop_text_stack(lvl); \
LOCAL_Error_TYPE = RESOURCE_ERROR_AUXILIARY_STACK; \
LOCAL_Error_Size = n * sizeof(TYPE); \
return NULL; \
}
@ -225,7 +224,7 @@ INLINE_ONLY Term Yap_ensure_atom__(const char *fu, const char *fi,
const char *prologParserText;
const char *prologParserFile;
bool prologConsulting;
const char *culprit;
const char *culprit;
YAP_Term errorRawTerm, rawExtraErrorTerm;
char *errorMsg;
size_t errorMsgLen;
@ -243,20 +242,24 @@ INLINE_ONLY Term Yap_ensure_atom__(const char *fu, const char *fi,
extern void Yap_CatchError(void);
extern void Yap_ThrowExistingError(void);
extern bool Yap_MkErrorRecord( yap_error_descriptor_t *r,
const char *file, const char *function,
int lineno, yap_error_number type, YAP_Term where,
const char *msg);
extern yap_error_descriptor_t * Yap_pc_add_location(yap_error_descriptor_t *t, void *pc0, void *b_ptr0, void *env0);
extern yap_error_descriptor_t *Yap_env_add_location(yap_error_descriptor_t *t,void *cp0, void * b_ptr0, void *env0, YAP_Int ignore_first);
extern bool Yap_MkErrorRecord(
yap_error_descriptor_t * r, const char *file, const char *function,
int lineno, yap_error_number type, YAP_Term where, const char *msg);
extern yap_error_descriptor_t *Yap_prolog_add_culprit(yap_error_descriptor_t *t);
extern yap_error_descriptor_t *Yap_pc_add_location(
yap_error_descriptor_t * t, void *pc0, void *b_ptr0, void *env0);
extern yap_error_descriptor_t *Yap_env_add_location(
yap_error_descriptor_t * t, void *cp0, void *b_ptr0, void *env0,
YAP_Int ignore_first);
extern yap_error_descriptor_t *Yap_prolog_add_culprit(yap_error_descriptor_t *
t);
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);
extern bool Yap_pushErrorContext(bool pass, yap_error_descriptor_t *new_error);
extern bool Yap_pushErrorContext(bool pass,
yap_error_descriptor_t *new_error);
extern yap_error_descriptor_t *Yap_popErrorContext(bool oerr, bool pass);
#endif

View File

@ -48,12 +48,12 @@ E(DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION, DOMAIN_ERROR,
E(DOMAIN_ERROR_ARRAY_OVERFLOW, DOMAIN_ERROR, "array_overflow")
E(DOMAIN_ERROR_ARRAY_TYPE, DOMAIN_ERROR, "array_type")
E(DOMAIN_ERROR_CLOSE_OPTION, DOMAIN_ERROR, "close_option")
E(DOMAIN_ERROR_CREATE_ARRAY_OPTION, DOMAIN_ERROR, "create_array_option")
E(DOMAIN_ERROR_ENCODING, DOMAIN_ERROR, "encoding")
E(DOMAIN_ERROR_EXPAND_FILENAME_OPTION, DOMAIN_ERROR, "expand_filename")
E(DOMAIN_ERROR_FILE_ERRORS, DOMAIN_ERROR, "file_errors")
E(DOMAIN_ERROR_FILE_TYPE, DOMAIN_ERROR, "file_type")
E(DOMAIN_ERROR_FORMAT_CONTROL_SEQUENCE, DOMAIN_ERROR, "format argument "
"domain")
E(DOMAIN_ERROR_FORMAT_CONTROL_SEQUENCE, DOMAIN_ERROR, "format argument")
E(DOMAIN_ERROR_FORMAT_OUTPUT, DOMAIN_ERROR, "format output")
E(DOMAIN_ERROR_GENERIC_ARGUMENT, DOMAIN_ERROR, "generic_argument")
E(DOMAIN_ERROR_IO_MODE, DOMAIN_ERROR, "io_mode")

View File

@ -34,7 +34,7 @@ The following routines export the YAP internals and architecture.
#define __YAP_PROLOG__ 1
#ifndef YAPVERSION
#define YAPVERSION 60000
#define YAPVERSION YAP_NUMERIC_VERSION
#endif
#include "YapDefs.h"

View File

@ -194,7 +194,7 @@ typedef enum { /* we accept two domains for the moment, IPV6 may follow */
#define Handle_vars_f 0x04
#define Use_portray_f 0x08
#define To_heap_f 0x10
#define Unfold_cyclics_f 0x20
#define Ignore_cyclics_f 0x20
#define Use_SWI_Stream_f 0x40
#define BackQuote_String_f 0x80
#define AttVar_None_f 0x100
@ -265,4 +265,13 @@ typedef struct stream_desc {
encoding_t encoding; /** current encoding for stream */
} StreamDesc;
extern bool Yap_set_stream_to_buf(StreamDesc *st, const char *bufi,
size_t nchars
#ifdef USES_REGS
USES_REGS
#endif
);
#endif

View File

@ -221,8 +221,9 @@ X_API int PL_get_nchars(term_t l, size_t *lengthp, char **s, unsigned flags) {
if (s) {
size_t len = strlen(out.val.c);
if (flags & (BUF_DISCARDABLE | BUF_RING)) {
strncpy(LOCAL_FileNameBuf, out.val.c, YAP_FILENAME_MAX);
if (!*s)
*s = LOCAL_FileNameBuf;
strncpy(*s, out.val.c, YAP_FILENAME_MAX);
pop_text_stack(lvl);
return true;
}
@ -1326,7 +1327,7 @@ YAP long int unify(YAP_Term* a, Term* b) */
X_API int PL_unify_atom_chars(term_t t, const char *s) {
CACHE_REGS
Atom at;
while ((at = Yap_CharsToAtom(s, ENC_ISO_LATIN1 PASS_REGS)) == 0L) {
while ((at = Yap_LookupAtom(s)) == 0L) {
if (LOCAL_Error_TYPE && !Yap_SWIHandleError("PL_unify_atom_nchars"))
return true;
}
@ -1451,16 +1452,28 @@ X_API int PL_unify_list(term_t tt, term_t h, term_t tail) {
}
t = Deref(Yap_GetFromSlot(tt));
if (IsVarTerm(t)) {
Term pairterm = Yap_MkNewPairTerm();
Yap_unify(t, pairterm);
/* avoid calling deref */
t = pairterm;
Term ttail =Yap_GetFromSlot(tail),
pairterm = MkPairTerm(Yap_GetFromSlot(h)
, ttail);
if (tt == tail) {
Yap_PutInSlot(tt, pairterm);
return true;
} else {
return Yap_unify(t, pairterm);
}
} else if (!IsPairTerm(t)) {
return FALSE;
}
Yap_PutInSlot(h, HeadOfTerm(t));
Yap_PutInSlot(tail, TailOfTerm(t));
return TRUE;
bool rc = Yap_unify(h, HeadOfTerm(t));
if (rc) {
if (tt == tail) {
Yap_PutInSlot(tail, TailOfTerm(t));
return true;
} else {
return Yap_unify(Yap_GetFromSlot(tail), TailOfTerm(t));
}
}
return false;
}
/* int PL_unify_list(term_t ?t, term_t +h, term_t -t)
@ -1548,7 +1561,7 @@ YAP long int unify(YAP_Term* a, Term* b) */
X_API int PL_unify_string_chars(term_t t, const char *chars) {
CACHE_REGS
Term chterm;
while ((chterm = Yap_CharsToString(chars, ENC_ISO_LATIN1 PASS_REGS)) == 0L) {
while ((chterm = MkStringTerm(chars)) == 0L) {
if (LOCAL_Error_TYPE && !Yap_SWIHandleError("PL_unify_list_ncodes"))
return FALSE;
}

View File

@ -86,6 +86,7 @@ aux_args([Arg|Args], [Arg|MVars], [PVar|PArgs], [PVar|PVars], ['_'|ProtoArgs]) :
pred_name(Macro, Arity, _ , Name) :-
transformation_id(Id),
atomic_concat(['$$$__Auxiliary_predicate__ for',Macro,'/',Arity,' ',Id], Name).
transformation_id(Id) :-

View File

@ -205,6 +205,17 @@ append_([L1,L2|[L3|LL]], L) :-
append(L1,L2,LI),
append_([LI|[L3|LL]],L).
% reverse(List, Reversed)
% is true when List and Reversed are lists with the same elements
% but in opposite orders. rev/2 is a synonym for reverse/2.
reverse(List, Reversed) :-
reverse(List, [], Reversed).
reverse([], Reversed, Reversed).
reverse([Head|Tail], Sofar, Reversed) :-
reverse(Tail, [Head|Sofar], Reversed).
/** @pred last(+ _List_,? _Last_)
@ -358,17 +369,6 @@ remove_duplicates([Elem|L], [Elem|NL]) :-
delete(L, Elem, Temp),
remove_duplicates(Temp, NL).
% reverse(List, Reversed)
% is true when List and Reversed are lists with the same elements
% but in opposite orders. rev/2 is a synonym for reverse/2.
reverse(List, Reversed) :-
reverse(List, [], Reversed).
reverse([], Reversed, Reversed).
reverse([Head|Tail], Sofar, Reversed) :-
reverse(Tail, [Head|Sofar], Reversed).
% same_length(?List1, ?List2)
% is true when List1 and List2 are both lists and have the same number

View File

@ -15,6 +15,7 @@
maplist/3,
maplist/4,
maplist/5,
maplist/6,
checklist/2,
checknodes/2,
convlist/3,
@ -52,6 +53,7 @@
maplist(2,+,-),
maplist(3,+,+,-),
maplist(4,+,+,+,-),
maplist(5,+,+,+,+,-),
convlist(2,+,-),
convlist(3,?,?,?),
mapnodes(2,+,-),
@ -287,7 +289,8 @@ checklist(Pred, [In|ListIn]) :-
checklist(Pred, ListIn).
/**
@pred maplist(: Pred, ? ListIn)
@pred
ist(: Pred, ? ListIn)
Applies predicate _Pred_( _El_ ) to all
elements _El_ of _ListIn_.
@ -339,6 +342,18 @@ maplist(Pred, [A1|L1], [A2|L2], [A3|L3], [A4|L4]) :-
call(Pred, A1, A2, A3, A4),
maplist(Pred, L1, L2, L3, L4).
/**
@pred maplist(: Pred, ? L1, ? L2, ? L3, ? L4, ? L5)
_L1_, _L2_, _L3_, _L4_ and _L5_ are such that
`call( _Pred_, _A1_, _A2_, _A3_, _A4_,_A5_)` holds
for every corresponding element in lists _L1_, _L2_, _L3_, _L4_ and _L5_.
*/
maplist(_, [], [], [], [], []).
maplist(Pred, [A1|L1], [A2|L2], [A3|L3], [A4|L4], [A5|L5]) :-
call(Pred, A1, A2, A3, A4, A5),
maplist(Pred, L1, L2, L3, L4, L5).
/**
@pred convlist(: Pred, + ListIn, ? ListOut)
@ -793,6 +808,27 @@ goal_expansion(maplist(Meta, L1, L2, L3, L4), Mod:Goal) :-
(RecursionHead :- Apply, RecursiveCall)
], Mod).
goal_expansion(maplist(Meta, L1, L2, L3, L4, L5), Mod:Goal) :-
goal_expansion_allowed,
callable(Meta),
prolog_load_context(module, Mod),
aux_preds(Meta, MetaVars, Pred, PredVars, Proto),
!,
% the new goal
pred_name(maplist, 6, Proto, GoalName),
append(MetaVars, [L1, L2, L3, L4, L5], GoalArgs),
Goal =.. [GoalName|GoalArgs],
% the new predicate declaration
HeadPrefix =.. [GoalName|PredVars],
append_args(HeadPrefix, [[], [], [], [], []], Base),
append_args(HeadPrefix, [[A1|A1s], [A2|A2s], [A3|A3s], [A4|A4s], [A5|A5s]], RecursionHead),
append_args(Pred, [A1, A2, A3, A4, A5], Apply),
append_args(HeadPrefix, [A1s, A2s, A3s, A4s, A5s], RecursiveCall),
compile_aux([
Base,
(RecursionHead :- Apply, RecursiveCall)
], Mod).
goal_expansion(selectlist(Meta, ListIn, ListOut), Mod:Goal) :-
goal_expansion_allowed,
callable(Meta),

View File

@ -83,15 +83,17 @@ pred_name(Macro, Arity, _ , Name) :-
prolog_load_context(term_position, Pos),
stream_position_data( line_count, Pos, Line ), !,
transformation_id(Id),
atomic_concat(['$$$ for ',Macro,'/',Arity,', line ',Line,' in ',File,' ',Id], Name).
pred_name(Macro, Arity, _ , Name) :-
transformation_id(Id),
atomic_concat(['$$$__expansion__ for ',Macro,'/',Arity,' ',Id], Name).
atomic_concat(['$$$ for ',Macro,'/',Arity,', line ',Line,' in ',File,'(',P,') #',Id], Name).
pred_name(Macro, Arity, P , Name) :-
transformation_id(Id),
atomic_concat(['$$$__expansion__ for ',Macro,'/',Arity,'(',P,') #',Id], Name).
transformation_id(Id) :-
retract(number_of_expansions(Id)),
Id1 is Id+1,
assert(number_of_expansions(Id1)).
retract(number_of_expansions(Id)),
!,
Id1 is Id+1,
assert(number_of_expansions(Id1)).
transformation_id(0).
%% goal_expansion_allowed is semidet.
%

View File

@ -745,6 +745,11 @@ rhs(list(RHS), List) :- !,
rhs(lists(RHS), List) :- !,
rhs(RHS, X1),
matrix_to_lists( X1, List ).
rhs('[]'([Args], floats(RHS)), Val) :-
integer(RHS),
integer(Args),
!,
get_float_from_address(RHS,Args,Val).
rhs('[]'(Args, RHS), Val) :-
!,
rhs(RHS, X1),
@ -788,6 +793,11 @@ rhs(S, NS) :-
set_lhs(V, R) :- var(V), !, V = R.
set_lhs(V, R) :- number(V), !, V = R.
set_lhs('[]'([Args], floats(RHS)), Val) :-
!,
integer(RHS),
integer(Args),
set_float_from_address(RHS,Args,Val).
set_lhs('[]'(Args, M), Val) :-
matrix_dims( M, Dims, Bases),
maplist( index(Range), Args, Dims, Bases, NArgs),

View File

@ -3244,6 +3244,30 @@ is_matrix(void)
return TRUE;
}
static YAP_Bool
get_float_from_address(void)
{
YAP_Float *fp = (YAP_Float *)YAP_IntOfTerm(YAP_ARG1);
YAP_Int off = YAP_IntOfTerm(YAP_ARG2);
return YAP_Unify(YAP_ARG3, YAP_MkFloatTerm(fp[off]));
}
static YAP_Bool
set_float_from_address(void)
{
YAP_Float *fp = (YAP_Float *)YAP_IntOfTerm(YAP_ARG1);
YAP_Int off = YAP_IntOfTerm(YAP_ARG2);
YAP_Float f = YAP_FloatOfTerm(YAP_ARG3 );
fp[off] = f;
return true;
}
X_API void init_matrix( void );
X_API void
@ -3302,7 +3326,9 @@ init_matrix(void)
YAP_UserCPredicate("do_matrix_op_to_cols", matrix_op_to_cols, 4);
YAP_UserCPredicate("matrix_m", matrix_m, 2);
YAP_UserCPredicate("matrix", is_matrix, 1);
}
YAP_UserCPredicate("get_float_from_address",get_float_from_address , 3);
YAP_UserCPredicate("set_float_from_address",set_float_from_address , 3);
}
#ifdef _WIN32

View File

@ -50,7 +50,6 @@
shell/0,
shell/1,
shell/2,
sleep/1,
system/0,
system/1,
system/2,
@ -205,18 +204,6 @@ WIN32 environment YAP will use `COMSPEC` if `SHELL` is
undefined, in this case with the option `" /c "`.
*/
/** @pred sleep(+ _Time_)
Block the current thread for _Time_ seconds. When YAP is compiled
without multi-threading support, this predicate blocks the YAP process.
The number of seconds must be a positive number, and it may an integer
or a float. The Unix implementation uses `usleep` if the number of
seconds is below one, and `sleep` if it is over a second. The WIN32
implementation uses `Sleep` for both cases.
*/
/** @pred system

View File

@ -852,73 +852,6 @@ static YAP_Bool plwait(void) {
#endif
}
static YAP_Bool p_sleep(void) {
YAP_Term ts = YAP_ARG1;
#if defined(__MINGW32__) || _MSC_VER
{
unsigned long int secs = 0, usecs = 0, msecs, out;
if (YAP_IsIntTerm(ts)) {
secs = YAP_IntOfTerm(ts);
} else if (YAP_IsFloatTerm(ts)) {
double tfl = YAP_FloatOfTerm(ts);
if (tfl > 1.0)
secs = tfl;
else
usecs = tfl * 1000000;
}
msecs = secs * 1000 + usecs / 1000;
Sleep(msecs);
/* no errors possible */
out = 0;
return (YAP_Unify(YAP_ARG2, YAP_MkIntTerm(out)));
}
#elif HAVE_NANOSLEEP
{
struct timespec req;
int out;
if (YAP_IsFloatTerm(ts)) {
double tfl = YAP_FloatOfTerm(ts);
req.tv_nsec = (tfl - floor(tfl)) * 1000000000;
req.tv_sec = rint(tfl);
} else {
req.tv_nsec = 0;
req.tv_sec = YAP_IntOfTerm(ts);
}
out = nanosleep(&req, NULL);
return (YAP_Unify(YAP_ARG2, YAP_MkIntTerm(out)));
}
#elif HAVE_USLEEP
{
useconds_t usecs;
if (YAP_IsFloatTerm(ts)) {
double tfl = YAP_FloatOfTerm(ts);
usecs = rint(tfl * 1000000);
} else {
usecs = YAP_IntOfTerm(ts) * 1000000;
}
out = usleep(usecs);
return (YAP_Unify(YAP_ARG2, YAP_MkIntTerm(out)));
}
#elif HAVE_SLEEP
{
unsigned int secs, out;
if (YAP_IsFloatTerm(ts)) {
secs = rint(YAP_FloatOfTerm(ts));
} else {
secs = YAP_IntOfTerm(ts);
}
out = sleep(secs);
return (YAP_Unify(YAP_ARG2, YAP_MkIntTerm(out)));
}
#else
YAP_Error(0, 0L, "sleep not available in this configuration");
return FALSE:
#endif
}
/* host info */
static YAP_Bool host_name(void) {
@ -1066,7 +999,6 @@ X_API void init_sys(void) {
YAP_UserCPredicate("tmpnam", p_tmpnam, 2);
YAP_UserCPredicate("tmpdir", p_tmpdir, 2);
YAP_UserCPredicate("rename_file", rename_file, 3);
YAP_UserCPredicate("sleep", p_sleep, 2);
YAP_UserCPredicate("read_link", read_link, 2);
YAP_UserCPredicate("error_message", error_message, 2);
YAP_UserCPredicate("win", win, 0);

View File

@ -135,13 +135,13 @@ void trie_max_stats(YAP_Int *memory, YAP_Int *tries, YAP_Int *entries, YAP_I
void trie_usage(TrEntry trie, YAP_Int *entries, YAP_Int *nodes, YAP_Int *virtual_nodes);
void trie_print(TrEntry trie);
void trie_data_construct(TrNode node);
void trie_set_traverse_mode(YAP_Int mode);
YAP_Int trie_get_traverse_mode(void);
TrData trie_traverse_first(TrEntry trie);
TrData trie_traverse_next(TrData data);
void trie_disable_hash_table(void);
void trie_enable_hash_table(void);
extern void trie_data_construct(TrNode node);
extern void trie_set_traverse_mode(YAP_Int mode);
extern YAP_Int trie_get_traverse_mode(void);
extern TrData trie_traverse_first(TrEntry trie);
extern TrData trie_traverse_next(TrData data);
extern void trie_disable_hash_table(void);
extern void trie_enable_hash_table(void);
YAP_Term trie_to_list(TrEntry trie);

View File

@ -287,32 +287,32 @@ typedef struct trie_hash {
/* API */
/* --------------------------- */
TrEngine core_trie_init_module(void);
TrNode core_trie_open(TrEngine engine);
void core_trie_close(TrEngine engine, TrNode node, void (*destruct_function)(TrNode));
void core_trie_close_all(TrEngine engine, void (*destruct_function)(TrNode));
void core_trie_set_mode(YAP_Int mode);
YAP_Int core_trie_get_mode(void);
TrNode core_trie_put_entry(TrEngine engine, TrNode node, YAP_Term entry, YAP_Int *depth);
TrNode core_trie_check_entry(TrNode node, YAP_Term entry);
YAP_Term core_trie_get_entry(TrNode node);
void core_trie_remove_entry(TrEngine engine, TrNode node, void (*destruct_function)(TrNode));
void core_trie_remove_subtree(TrEngine engine, TrNode node, void (*destruct_function)(TrNode));
void core_trie_add(TrNode node_dest, TrNode node_source, void (*add_function)(TrNode, TrNode));
void core_trie_join(TrEngine engine, TrNode node_dest, TrNode node_source, void (*add_function)(TrNode, TrNode), void (*copy_function)(TrNode, TrNode));
void core_trie_intersect(TrEngine engine, TrNode node_dest, TrNode node_source, void (*add_function)(TrNode, TrNode), void (*destruct_function)(TrNode));
YAP_Int core_trie_count_join(TrNode node1, TrNode node2);
YAP_Int core_trie_count_intersect(TrNode node1, TrNode node2);
void core_trie_save(TrNode node, FILE *file, void (*save_function)(TrNode, FILE *));
TrNode core_trie_load(TrEngine engine, FILE *file, void (*load_function)(TrNode, YAP_Int, FILE *));
void core_trie_stats(TrEngine engine, YAP_Int *memory, YAP_Int *tries, YAP_Int *entries, YAP_Int *nodes);
void core_trie_max_stats(TrEngine engine, YAP_Int *memory, YAP_Int *tries, YAP_Int *entries, YAP_Int *nodes);
void core_trie_usage(TrNode node, YAP_Int *entries, YAP_Int *nodes, YAP_Int *virtual_nodes);
void core_trie_print(TrNode node, void (*print_function)(TrNode));
extern TrEngine core_trie_init_module(void);
extern TrNode core_trie_open(TrEngine engine);
extern void core_trie_close(TrEngine engine, TrNode node, void (*destruct_function)(TrNode));
extern void core_trie_close_all(TrEngine engine, void (*destruct_function)(TrNode));
extern void core_trie_set_mode(YAP_Int mode);
extern YAP_Int core_trie_get_mode(void);
extern TrNode core_trie_put_entry(TrEngine engine, TrNode node, YAP_Term entry, YAP_Int *depth);
extern TrNode core_trie_check_entry(TrNode node, YAP_Term entry);
extern YAP_Term core_trie_get_entry(TrNode node);
extern void core_trie_remove_entry(TrEngine engine, TrNode node, void (*destruct_function)(TrNode));
extern void core_trie_remove_subtree(TrEngine engine, TrNode node, void (*destruct_function)(TrNode));
extern void core_trie_add(TrNode node_dest, TrNode node_source, void (*add_function)(TrNode, TrNode));
extern void core_trie_join(TrEngine engine, TrNode node_dest, TrNode node_source, void (*add_function)(TrNode, TrNode), void (*copy_function)(TrNode, TrNode));
extern void core_trie_intersect(TrEngine engine, TrNode node_dest, TrNode node_source, void (*add_function)(TrNode, TrNode), void (*destruct_function)(TrNode));
extern YAP_Int core_trie_count_join(TrNode node1, TrNode node2);
extern YAP_Int core_trie_count_intersect(TrNode node1, TrNode node2);
extern void core_trie_save(TrNode node, FILE *file, void (*save_function)(TrNode, FILE *));
extern TrNode core_trie_load(TrEngine engine, FILE *file, void (*load_function)(TrNode, YAP_Int, FILE *));
extern void core_trie_stats(TrEngine engine, YAP_Int *memory, YAP_Int *tries, YAP_Int *entries, YAP_Int *nodes);
extern void core_trie_max_stats(TrEngine engine, YAP_Int *memory, YAP_Int *tries, YAP_Int *entries, YAP_Int *nodes);
extern void core_trie_usage(TrNode node, YAP_Int *entries, YAP_Int *nodes, YAP_Int *virtual_nodes);
extern void core_trie_print(TrNode node, void (*print_function)(TrNode));
void core_disable_hash_table(void);
void core_enable_hash_table(void);
extern void core_disable_hash_table(void);
extern void core_enable_hash_table(void);
YAP_Term core_trie_to_list(TrNode node);
extern YAP_Term core_trie_to_list(TrNode node);
#include "core_dbtries.h"

View File

@ -33,7 +33,7 @@
'$is_metapredicate'( G, M) :-
predicate_property(M:G, meta_predicate(_)).
'$imported_predicate'(G,M,G,M0) :-
'$is_imported_predicate'(G,M,G,M0) :-
predicate_property(M:G, imported_from(M0)).
'$is_system_predicate'( call(_), _M) :- !.

218
misc/editors/meta.js Normal file
View File

@ -0,0 +1,218 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.modeInfo = [
{name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
{name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]},
{name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
{name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
{name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
{name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h", "ino"]},
{name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
{name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
{name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
{name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
{name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
{name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
{name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
{name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
{name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
{name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
{name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
{name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
{name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
{name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
{name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
{name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
{name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
{name: "Django", mime: "text/x-django", mode: "django"},
{name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
{name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
{name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
{name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
{name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
{name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
{name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
{name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
{name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
{name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
{name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
{name: "Esper", mime: "text/x-esper", mode: "sql"},
{name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
{name: "FCL", mime: "text/x-fcl", mode: "fcl"},
{name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
{name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
{name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
{name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
{name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
{name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
{name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
{name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/},
{name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
{name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
{name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
{name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
{name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
{name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
{name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"]},
{name: "HTTP", mime: "message/http", mode: "http"},
{name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
{name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]},
{name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
{name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
{name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
{name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
{name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
{name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
{name: "Jinja2", mime: "null", mode: "jinja2"},
{name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
{name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
{name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
{name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
{name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
{name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
{name: "mIRC", mime: "text/mirc", mode: "mirc"},
{name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
{name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
{name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
{name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
{name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
{name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
{name: "MySQL", mime: "text/x-mysql", mode: "sql"},
{name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
{name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
{name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
mode: "ntriples", ext: ["nt", "nq"]},
{name: "Objective-C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
{name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
{name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
{name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
{name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
{name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
{name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
{name: "PHP", mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]},
{name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
{name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
{name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
{name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
{name: "Prolog", mime: "application/x-prolog", mode: "prolog", ext: ["yap", "ypp", "pl", "prolog"]},
{name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
{name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
{name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
{name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
{name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
{name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]},
{name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
{name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
{name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
{name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
{name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
{name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
{name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
{name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
{name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
{name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
{name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
{name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
{name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
{name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
{name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
{name: "Solr", mime: "text/x-solr", mode: "solr"},
{name: "SML", mime: "text/x-sml", mode: "mllike", ext: ["sml", "sig", "fun", "smackspec"]},
{name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
{name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
{name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
{name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
{name: "SQLite", mime: "text/x-sqlite", mode: "sql"},
{name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
{name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]},
{name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
{name: "sTeX", mime: "text/x-stex", mode: "stex"},
{name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"]},
{name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
{name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
{name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
{name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
{name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
{name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
{name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
{name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
{name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
{name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
{name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
{name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
{name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]},
{name: "Twig", mime: "text/x-twig", mode: "twig"},
{name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
{name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
{name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
{name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
{name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
{name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
{name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]},
{name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]},
{name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
{name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
{name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
{name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
{name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
{name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
{name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
];
// Ensure all modes have a mime property for backwards compatibility
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.mimes) info.mime = info.mimes[0];
}
CodeMirror.findModeByMIME = function(mime) {
mime = mime.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.mime == mime) return info;
if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
if (info.mimes[j] == mime) return info;
}
if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml")
if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json")
};
CodeMirror.findModeByExtension = function(ext) {
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.ext) for (var j = 0; j < info.ext.length; j++)
if (info.ext[j] == ext) return info;
}
};
CodeMirror.findModeByFileName = function(filename) {
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.file && info.file.test(filename)) return info;
}
var dot = filename.lastIndexOf(".");
var ext = dot > -1 && filename.substring(dot + 1, filename.length);
if (ext) return CodeMirror.findModeByExtension(ext);
};
CodeMirror.findModeByName = function(name) {
name = name.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.name.toLowerCase() == name) return info;
if (info.alias) for (var j = 0; j < info.alias.length; j++)
if (info.alias[j].toLowerCase() == name) return info;
}
};
});

115
misc/editors/mode.js Normal file
View File

@ -0,0 +1,115 @@
"use strict";
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
Object.defineProperty(exports, "__esModule", { value: true });
var codeeditor_1 = require("@jupyterlab/codeeditor");
var CodeMirror = require("codemirror");
require("codemirror/mode/meta");
require("codemirror/addon/runmode/runmode");
require("./codemirror-ipython");
require("./codemirror-ipythongfm");
// Bundle other common modes
require("codemirror/mode/javascript/javascript");
require("codemirror/mode/css/css");
require("codemirror/mode/prolog/prolog");
require("codemirror/mode/julia/julia");
require("codemirror/mode/r/r");
require("codemirror/mode/markdown/markdown");
require("codemirror/mode/clike/clike");
require("codemirror/mode/shell/shell");
require("codemirror/mode/sql/sql");
var coreutils_1 = require("@jupyterlab/coreutils");
/**
* The namespace for CodeMirror Mode functionality.
*/
var Mode;
(function (Mode) {
/**
* Get the raw list of available modes specs.
*/
function getModeInfo() {
return CodeMirror.modeInfo;
}
Mode.getModeInfo = getModeInfo;
/**
* Running a CodeMirror mode outside of an editor.
*/
function run(code, mode, el) {
CodeMirror.runMode(code, mode, el);
}
Mode.run = run;
/**
* Ensure a codemirror mode is available by name or Codemirror spec.
*
* @param mode - The mode to ensure. If it is a string, uses [findBest]
* to get the appropriate spec.
*
* @returns A promise that resolves when the mode is available.
*/
function ensure(mode) {
var spec = findBest(mode);
// Simplest, cheapest check by mode name.
if (CodeMirror.modes.hasOwnProperty(spec.mode)) {
return Promise.resolve(spec);
}
// Fetch the mode asynchronously.
return new Promise(function (resolve, reject) {
require(["codemirror/mode/" + spec.mode + "/" + spec.mode + ".js"], function () {
resolve(spec);
});
});
}
Mode.ensure = ensure;
/**
* Find a codemirror mode by name or CodeMirror spec.
*/
function findBest(mode) {
var modename = (typeof mode === 'string') ? mode :
mode.mode || mode.name;
var mimetype = (typeof mode !== 'string') ? mode.mime : modename;
var ext = (typeof mode !== 'string') ? mode.ext : [];
return (CodeMirror.findModeByName(modename || '') ||
CodeMirror.findModeByMIME(mimetype || '') ||
findByExtension(ext) ||
CodeMirror.findModeByMIME(codeeditor_1.IEditorMimeTypeService.defaultMimeType) ||
CodeMirror.findModeByMIME('text/plain'));
}
Mode.findBest = findBest;
/**
* Find a codemirror mode by MIME.
*/
function findByMIME(mime) {
return CodeMirror.findModeByMIME(mime);
}
Mode.findByMIME = findByMIME;
/**
* Find a codemirror mode by name.
*/
function findByName(name) {
return CodeMirror.findModeByName(name);
}
Mode.findByName = findByName;
/**
* Find a codemirror mode by filename.
*/
function findByFileName(name) {
var basename = coreutils_1.PathExt.basename(name);
return CodeMirror.findModeByFileName(basename);
}
Mode.findByFileName = findByFileName;
/**
* Find a codemirror mode by extension.
*/
function findByExtension(ext) {
if (typeof ext === 'string') {
return CodeMirror.findModeByExtension(name);
}
for (var i = 0; i < ext.length; i++) {
var mode = CodeMirror.findModeByExtension(ext[i]);
if (mode) {
return mode;
}
}
}
Mode.findByExtension = findByExtension;
})(Mode = exports.Mode || (exports.Mode = {}));

View File

@ -3,9 +3,9 @@
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
mod(require("codemirror/lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
define(["codemirror/lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
@ -23,12 +23,13 @@
*******************************/
var config = { quasiQuotations: false, /* {|Syntax||Quotation|} */
indot: true, /* a.b */
dicts: false, /* tag{k:v, ...} */
unicodeEscape: true, /* \uXXXX and \UXXXXXXXX */
multiLineQuoted: true, /* "...\n..." */
groupedIntegers: false /* 10 000 or 10_000 */
};
v
var quoteType = { '"': "string",
"'": "qatom",
"`": "bqstring"
@ -1216,8 +1217,7 @@
token: function(stream, state) {
var nest;
if ( state.curTerm == null && mode
Config.metainfo ) {
if ( state.curTerm == null && modeConfig.metainfo ) {
state.curTerm = 0;
state.curToken = 0;
}

View File

@ -0,0 +1,188 @@
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
var path = require('path');
var fs = require('fs-extra');
var Handlebars = require('handlebars');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
var Build = require('@jupyterlab/buildutils').Build;
var package_data = require('./package.json');
// Handle the extensions.
var jlab = package_data.jupyterlab;
var extensions = jlab.extensions;
var mimeExtensions = jlab.mimeExtensions;
Build.ensureAssets({
packageNames: Object.keys(mimeExtensions).concat(Object.keys(extensions)),
output: jlab.outputDir
});
fs.ensureDirSync('node_modules/codemirror/mode/prolog');
fs.copySync(path.join(path.resolve(jlab.buildDir),'../../../kernels/yap_kernel/prolog.js'), 'node_modules/codemirror/mode/prolog/prolog.js');
fs.copySync(path.join(path.resolve(jlab.buildDir),'../../../kernels/yap_kernel/meta.js'), 'node_modules/codemirror/mode/meta.js');
// Create the entry point file.
var source = fs.readFileSync('index.js').toString();
var template = Handlebars.compile(source);
var data = {
jupyterlab_extensions: extensions,
jupyterlab_mime_extensions: mimeExtensions,
};
var result = template(data);
// Ensure a clear build directory.
var buildDir = path.resolve(jlab.buildDir);
if (fs.existsSync(buildDir)) {
fs.removeSync(buildDir);
}
fs.ensureDirSync(buildDir);
fs.writeFileSync(path.join(buildDir, 'index.out.js'), result);
fs.copySync('./package.json', path.join(buildDir, 'package.json'));
fs.copySync('./templates/error.html', path.join(buildDir, 'error.html'));
// Set up variables for watch mode.
var localLinked = {};
var ignoreCache = Object.create(null);
Object.keys(jlab.linkedPackages).forEach(function (name) {
var localPath = require.resolve(path.join(name, 'package.json'));
localLinked[name] = path.dirname(localPath);
});
/**
* Sync a local path to a linked package path if they are files and differ.
*/
function maybeSync(localPath, name, rest) {
var stats = fs.statSync(localPath);
if (!stats.isFile(localPath)) {
return;
}
var source = fs.realpathSync(path.join(jlab.linkedPackages[name], rest));
if (source === fs.realpathSync(localPath)) {
return;
}
fs.watchFile(source, { 'interval': 500 }, function(curr) {
if (!curr || curr.nlink === 0) {
return;
}
try {
fs.copySync(source, localPath);
} catch (err) {
console.error(err);
}
});
}
/**
* A WebPack Plugin that copies the assets to the static directory.
*/
function JupyterLabPlugin() { }
JupyterLabPlugin.prototype.apply = function(compiler) {
compiler.plugin('after-emit', function(compilation, callback) {
var staticDir = jlab.staticDir;
if (!staticDir) {
callback();
return;
}
// Ensure a clean static directory on the first emit.
if (this._first && fs.existsSync(staticDir)) {
fs.removeSync(staticDir);
}
this._first = false;
fs.copySync(buildDir, staticDir);
callback();
}.bind(this));
};
JupyterLabPlugin.prototype._first = true;
module.exports = {
entry: {
main: ['whatwg-fetch', path.resolve(buildDir, 'index.out.js')],
vendor: jlab.vendor
},
output: {
path: path.resolve(buildDir),
publicPath: jlab.publicUrl || '{{base_url}}lab/static/',
filename: '[name].[chunkhash].js'
},
module: {
rules: [
{ test: /^codemirror$/, use: 'file-loader' },
{ test: /^JUPYTERLAB_RAW_LOADER_/, use: 'raw-loader' },
{ test: /^JUPYTERLAB_URL_LOADER_/, use: 'url-loader?limit=10000' },
{ test: /^JUPYTERLAB_FILE_LOADER_/, use: 'file-loader' },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.json$/, use: 'json-loader' },
{ test: /\.md$/, use: 'raw-loader' },
{ test: /\.txt$/, use: 'raw-loader' },
{ test: /\.js$/, use: ['source-map-loader'], enforce: 'pre',
// eslint-disable-next-line no-undef
exclude: path.join(process.cwd(), 'node_modules')
},
{ test: /\.(jpg|png|gif)$/, use: 'file-loader' },
{ test: /\.js.map$/, use: 'file-loader' },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
{ test: /\.otf(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }
],
},
watchOptions: {
ignored: function(localPath) {
localPath = path.resolve(localPath);
if (localPath in ignoreCache) {
return ignoreCache[localPath];
}
// Limit the watched files to those in our local linked package dirs.
var ignore = true;
Object.keys(localLinked).some(function (name) {
// Bail if already found.
var rootPath = localLinked[name];
var contained = localPath.indexOf(rootPath + path.sep) !== -1;
if (localPath !== rootPath && !contained) {
return false;
}
var rest = localPath.slice(rootPath.length);
if (rest.indexOf('node_modules') === -1) {
ignore = false;
maybeSync(localPath, name, rest);
}
return true;
});
ignoreCache[localPath] = ignore;
return ignore;
}
},
node: {
fs: 'empty'
},
bail: true,
devtool: 'source-map',
plugins: [
new HtmlWebpackPlugin({
template: path.join('templates', 'template.html'),
title: jlab.name || 'JupyterLab'
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest'
}),
new JupyterLabPlugin({})
]
};

View File

@ -1,3 +1,6 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
@ -11,7 +14,7 @@ else // Plain browser env
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
CodeMirror.defineMode("prolog", function(conf, parserConfig) {
function chain(stream, state, f) {
state.tokenize = f;
@ -19,18 +22,18 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
}
/*******************************
* CONFIG DATA *
* CONFIG DATA *
*******************************/
var config = {
quasiQuotations : false, /* {|Syntax||Quotation|} */
dicts : false, /* tag{k:v, ...} */
unicodeEscape : true, /* \uXXXX and \UXXXXXXXX */
multiLineQuoted : true, /* "...\n..." */
groupedIntegers : false /* 10 000 or 10_000 */
};
var quoteType = {'"' : "string", "'" : "qatom", "`" : "bqstring"};
var quasiQuotations =
parserConfig.quasiQuotations || false; /* {|Syntax||Quotation|} */
var dicts = parserConfig.dicts || false; /* tag{k:v, ...} */
var groupedIntegers = parserConfig.groupedIntegers || false; /* tag{k:v, ...} */
var unicodeEscape =
parserConfig.unicodeEscape || true; /* \uXXXX and \UXXXXXXXX */
var multiLineQuoted = parserConfig.multiLineQuoted || true; /* "...\n..." */
var quoteType = parserConfig.quoteType ||
{'"' : "string", "'" : "qatom", "`" : "bqstring"};
var isSingleEscChar = /[abref\\'"nrtsv]/;
var isOctalDigit = /[0-7]/;
@ -42,7 +45,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
var isControlOp = /^(,|;|->|\*->|\\+|\|)$/;
/*******************************
* CHARACTER ESCAPES *
* CHARACTER ESCAPES *
*******************************/
function readDigits(stream, re, count) {
@ -64,11 +67,11 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
return true;
switch (next) {
case "u":
if (config.unicodeEscape)
return readDigits(stream, isHexDigit, 4); /* SWI */
if (unicodeEscape)
return readDigits(stream, isHexDigit, conf.indentUnit); /* SWI */
return false;
case "U":
if (config.unicodeEscape)
if (unicodeEscape)
return readDigits(stream, isHexDigit, 8); /* SWI */
return false;
case null:
@ -101,11 +104,11 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
return false;
}
}
return config.multiLineQuoted;
return multiLineQuoted;
}
/*******************************
* CONTEXT NESTING *
* CONTEXT NESTING *
*******************************/
function nesting(state) { return state.nesting.slice(-1)[0]; }
@ -126,7 +129,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
var nest = nesting(state);
if (nest && !nest.alignment && nest.arg != undefined) {
if (nest.arg == 0)
nest.alignment = nest.leftCol ? nest.leftCol + 4 : nest.column + 4;
nest.alignment = nest.leftCol ? nest.leftCol + conf.indentUnit : nest.column + conf.indentUnit;
else
nest.alignment = nest.column + 1;
}
@ -158,10 +161,10 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
var type;//, content;
function ret(tp, style, cont) {
type = tp;
content = cont;
// content = cont;
return style;
}
@ -172,7 +175,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
}
/*******************************
* SUB TOKENISERS *
* SUB TOKENISERS *
*******************************/
function plTokenBase(stream, state) {
@ -192,7 +195,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
state.nesting.push({
type : "control",
closeColumn : stream.column(),
alignment : stream.column() + 4
alignment : stream.column() + conf.indentUnit
});
}
return ret("solo", null, "(");
@ -258,7 +261,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
return ret("list_open", "bracket");
break;
case "{":
if (config.quasiQuotations && stream.eat("|")) {
if (quasiQuotations && stream.eat("|")) {
state.nesting.push(
{type : "quasi-quotation", alignment : stream.column() + 1});
return ret("qq_open", "bracket");
@ -272,7 +275,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
}
break;
case "|":
if (config.quasiQuotations) {
if (quasiQuotations) {
if (stream.eat("|")) {
state.tokenize = plTokenQuasiQuotation;
return ret("qq_sep", "bracket");
@ -314,7 +317,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
}
if (/\d/.test(ch) || /[+-]/.test(ch) && stream.eat(/\d/)) {
if (config.groupedIntegers)
if (groupedIntegers)
stream.match(/^\d*((_|\s+)\d+)*(?:\.\d+)?(?:[eE][+\-]?\d+)?/);
else
stream.match(/^\d*(?:\.\d+)?(?:[eE][+\-]?\d+)?/);
@ -342,8 +345,9 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
}
stream.eatWhile(/[\w_]/);
var word = stream.current(), extra = "";
if (stream.peek() == "{" && config.dicts) {
var word = stream.current();
var extra = "";
if (stream.peek() == "{" && dicts) {
state.tagName = word; /* tmp state extension */
state.tagColumn = stream.column();
return ret("tag", "tag", word);
@ -407,7 +411,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
}
return ret("functor", "atom", word);
}
if (stream.peek() == "{" && config.dicts) { /* 'quoted tag'{} */
if (stream.peek() == "{" && dicts) { /* 'quoted tag'{} */
var word = stream.current();
state.tagName = word; /* tmp state extension */
return ret("tag", "tag", word);
@ -443,7 +447,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
}
// /*******************************
// * ACTIVE KEYS *
// * ACTIVE KEYS *
// *******************************/
// /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -451,7 +455,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
// Support if-then-else layout like this:
// goal :-
// ( Condition
// ( Condition
// -> IfTrue
// ; IfFalse
// ).
@ -464,7 +468,7 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
// if ( token.state.goalStart == true )
// { cm.replaceSelection("( ", "end");
// return;
// return;
// }
// return CodeMirror.Pass;
@ -475,32 +479,32 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
// var token = cm.getTokenAt(start, true);
// /* FIXME: These functions are copied from prolog.js. How
// can we reuse these?
// can we reuse these?
// */
// function nesting(state) {
// var len = state.nesting.length;
// if ( len > 0 )
// return state.nesting[len-1];
// return null;
// var len = state.nesting.length;
// if ( len > 0 )
// return state.nesting[len-1];
// return null;
// }
// function isControl(state) { /* our terms are goals */
// var nest = nesting(state);
// if ( nest ) {
// if ( nest.type == "control" ) {
// return true;
// }
// return false;
// } else
// return state.inBody;
// function isControl(state) { /* our terms are goals */
// var nest = nesting(state);
// if ( nest ) {
// if ( nest.type == "control" ) {
// return true;
// }
// return false;
// } else
// return state.inBody;
// }
// if ( start.ch == token.end &&
// token.type == "operator" &&
// token.string == "-" &&
// isControl(token.state) )
// token.type == "operator" &&
// token.string == "-" &&
// isControl(token.state) )
// { cm.replaceSelection("> ", "end");
// return;
// return;
// }
// return CodeMirror.Pass;
@ -511,9 +515,9 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
// var token = cm.getTokenAt(start, true);
// if ( token.start == 0 && start.ch == token.end &&
// !/\S/.test(token.string) )
// !/\S/.test(token.string) )
// { cm.replaceSelection("; ", "end");
// return;
// return;
// }
// return CodeMirror.Pass;
@ -521,15 +525,15 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
// CodeMirror.defineOption("prologKeys", null, function(cm, val, prev) {
// if (prev && prev != CodeMirror.Init)
// cm.removeKeyMap("prolog");
// cm.removeKeyMap("prolog");
// if ( val ) {
// var map = { name: "prolog",
// "'('": "prologStartIfThenElse",
// "'>'": "prologStartThen",
// "';'": "prologStartElse",
// "Ctrl-L": "refreshHighlight"
// };
// cm.addKeyMap(map);
// var map = { name: "prolog",
// "'('": "prologStartIfThenElse",
// "'>'": "prologStartThen",
// "';'": "prologStartElse",
// "Ctrl-L": "refreshHighlight"
// };
// cm.addKeyMap(map);
// }
// });
@ -606,32 +610,6 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
"\\" : {p : 200, t : "fy"}
};
var translType = {
"comment" : "comment",
"var" : "variable-2", /* JavaScript Types */
"atom" : "atom",
"qatom" : "atom",
"bqstring" : "string",
"symbol" : "keyword",
"functor" : "keyword",
"tag" : "tag",
"number" : "number",
"string" : "string",
"code" : "number",
"neg-number" : "number",
"pos-number" : "number",
"list_open" : "bracket",
"list_close" : "bracket",
"qq_open" : "bracket",
"qq_sep" : "operator",
"qq_close" : "bracket",
"dict_open" : "bracket",
"dict_close" : "bracket",
"brace_term_open" : "bracket",
"brace_term_close" : "bracket",
"neck" : "keyword",
"fullstop" : "keyword"
};
var builtins = {
"C" : "prolog",
@ -1181,10 +1159,10 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
};
/*******************************
* RETURN OBJECT *
* RETURN OBJECT *
*******************************/
return {
var external = {
startState : function() {
return {
tokenize : plTokenBase,
@ -1232,30 +1210,32 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
if (builtins[state.curToken] == "prolog")
return "builtin";
//if (ops[state.curToken])
// return "operator";
if (ops[state.curToken])
return "operator";
//if (typeof(parserConfig.enrich) == "function")
// style = parserConfig.enrich(stream, state, type, content, style);
return style;
},
indent : function(state, textAfter) {
if (state.tokenize == plTokenComment)
return CodeMirror.Pass;
var nest;
if ((nest = nesting(state))) {
if (nest.closeColumn && !state.commaAtEOL)
return nest.closeColumn;
if ( (textAfter === ']' || textAfter === ')') && nest.control)
return nest.alignment-1;
return nest.alignment;
}
if (!state.inBody)
return 0;
if (!state.inBody)
return 0;
return 4;
return conf.indentUnit;
},
// theme: "prolog",
@ -1264,7 +1244,9 @@ CodeMirror.defineMode("prolog", function(cm_config, parserConfig) {
blockCommentEnd : "*/",
blockCommentContinue : " * ",
lineComment : "%",
fold : "indent"
};
return external;
});

View File

@ -1,7 +1,11 @@
site_name: 'YAP'
theme: 'readthedocs'
markdown_extensions:
use_directory_urls: false
- smarty
- toc:
permalink: True
- sane_lists
use_directory_urls: false
plugins:
- search
- awesome-pages:

View File

@ -47,7 +47,13 @@ const char *Yap_GetFileName(Term t USES_REGS) {
char *buf = Malloc(YAP_FILENAME_MAX + 1);
if (IsApplTerm(t) && FunctorOfTerm(t) == FunctorSlash) {
snprintf(buf, YAP_FILENAME_MAX, "%s/%s", Yap_GetFileName(ArgOfTerm(1, t)),
Yap_GetFileName(ArgOfTerm(1, t)));
Yap_GetFileName(ArgOfTerm(2, t)));
}
if (IsAtomTerm(t)) {
return RepAtom(AtomOfTerm(t))->StrOfAE;
}
if (IsStringTerm(t)) {
return StringOfTerm(t);
}
return Yap_TextTermToText(t PASS_REGS);
}
@ -90,7 +96,7 @@ static Int file_name_extension(USES_REGS1) {
size_t len_b = strlen(f), lenb_b;
char *candidate = strrchr(f, '.');
char *file = strrchr(f, '/');
if (candidate && file && candidate > file) {
if (candidate && candidate > file) {
lenb_b = candidate - f;
ext = candidate + 1;
} else {

View File

@ -204,8 +204,6 @@ int Yap_open_buf_write_stream(encoding_t enc, memBufSource src) {
st = GLOBAL_Stream + sno;
st->status = Output_Stream_f | InMemory_Stream_f;
if (st->nbuf)
st->status |= FreeOnClose_Stream_f;
st->linepos = 0;
st->charcount = 0;
st->linecount = 1;
@ -213,14 +211,10 @@ int Yap_open_buf_write_stream(encoding_t enc, memBufSource src) {
st->vfs = NULL;
st->buf.on = true;
st->nbuf = NULL;
st->nsize = 0;
st->status |= Seekable_Stream_f;
#if HAVE_OPEN_MEMSTREAM
st->file = open_memstream(&st->nbuf, &st->nsize);
// setbuf(st->file, NULL);
if (!st->nbuf) {
return -1;
}
#else
st->file = fmemopen((void *)st->nbuf, st->nsize, "w+");
#endif
@ -259,18 +253,21 @@ open_mem_write_stream(USES_REGS1) /* $open_mem_write_stream(-Stream) */
* by other writes..
*/
char *Yap_MemExportStreamPtr(int sno) {
if (fflush(GLOBAL_Stream[sno].file) < 0) {
FILE *f = GLOBAL_Stream[sno].file;
if (fflush(f) < 0) {
return NULL;
}
size_t len = fseek(GLOBAL_Stream[sno].file, 0, SEEK_END);
if (fseek(f, 0, SEEK_END) < 0) {
return NULL;
}
size_t len = ftell(f);
char *buf = malloc(len+1);
#if HAVE_OPEN_MEMSTREAM
char *s = GLOBAL_Stream[sno].nbuf;
memcpy(buf, s, len);
// s[fseek(GLOBAL_Stream[sno].file, 0, SEEK_END)] = '\0';
#else
fread(buf, sz, 1, GLOBAL_Stream[sno].file);
fread(buf, len, 1, GLOBAL_Stream[sno].file);
#endif
buf[len] = '\0';
return buf;

File diff suppressed because it is too large Load Diff

View File

@ -1551,11 +1551,7 @@ FILE *Yap_FileDescriptorFromStream(Term t) {
return rc;
}
void
Yap_InitBackIO (
void)
void Yap_InitBackIO(void)
{
Yap_InitCPredBack("stream_property", 2, 2, stream_property,
cont_stream_property, SafePredFlag | SyncPredFlag);

View File

@ -1827,6 +1827,7 @@ static Int p_win_registry_get_value(USES_REGS1) {
return FALSE;
}
char *Yap_RegistryGetString(char *name) {
DWORD type;
BYTE data[MAXREGSTRLEN];
@ -1865,6 +1866,74 @@ char *Yap_RegistryGetString(char *name) {
#endif
static Int p_sleep(USES_REGS1) {
Term ts = ARG1;
#if defined(__MINGW32__) || _MSC_VER
{
unsigned long int secs = 0, usecs = 0, msecs, out;
if (IsIntegerTerm(ts)) {
secs = IntegerOfTerm(ts);
} else if (IsFloatTerm(ts)) {
double tfl = FloatOfTerm(ts);
if (tfl > 1.0)
secs = tfl;
else
usecs = tfl * 1000000;
}
msecs = secs * 1000 + usecs / 1000;
Sleep(msecs);
/* no ers possible */
return true;
}
#elif HAVE_NANOSLEEP
{
struct timespec req;
int out;
if (IsFloatTerm(ts)) {
double tfl = FloatOfTerm(ts);
req.tv_nsec = (tfl - floor(tfl)) * 1000000000;
req.tv_sec = rint(tfl);
} else {
req.tv_nsec = 0;
req.tv_sec = IntOfTerm(ts);
}
out = nanosleep(&req, NULL);
return true;
}
#elif HAVE_USLEEP
{
useconds_t usecs;
if (IsFloatTerm(ts)) {
double tfl = FloatOfTerm(ts);
usecs = rint(tfl * 1000000);
} else {
usecs = IntegrOfTerm(ts) * 1000000;
}
out = usleep(usecs);
return;
}
#elif HAVE_SLEEP
{
unsigned int secs, out;
if (IsFloatTerm(ts)) {
secs = rint(FloatOfTerm(ts));
} else {
secs = IntOfTerm(ts);
}
out = sleep(secs);
return (Yap_unify(ARG2, MkIntTerm(out)));
}
#else
YAP_Error(SYSTEM_ERROR, 0L, "sleep not available in this configuration");
return FALSE:
#endif
}
void Yap_InitSysPreds(void) {
Yap_InitCPred("log_event", 1, p_log_event, SafePredFlag | SyncPredFlag);
Yap_InitCPred("sh", 0, p_sh, SafePredFlag | SyncPredFlag);
@ -1901,5 +1970,7 @@ void Yap_InitSysPreds(void) {
Yap_InitCPred("win_registry_get_value", 3, p_win_registry_get_value, 0);
#endif
Yap_InitCPred("rmdir", 2, p_rmdir, SyncPredFlag);
Yap_InitCPred("sleep", 1, p_sleep, SyncPredFlag);
Yap_InitCPred("make_directory", 1, make_directory, SyncPredFlag);
}

View File

@ -92,8 +92,9 @@ static Term readFromBuffer(const char *s, Term opts) {
Term rval;
int sno;
encoding_t enc = ENC_ISO_UTF8;
sno = Yap_open_buf_read_stream((char *)s, strlen_utf8((unsigned char *)s),
&enc, MEM_BUF_USER, Yap_LookupAtom(Yap_StrPrefix((char *)s,16)), TermNone);
sno = Yap_open_buf_read_stream(
(char *)s, strlen_utf8((unsigned char *)s), &enc, MEM_BUF_USER,
Yap_LookupAtom(Yap_StrPrefix((char *)s, 16)), TermNone);
rval = Yap_read_term(sno, opts, 3);
Yap_CloseStream(sno);
@ -231,7 +232,7 @@ static bool write_term(int output_stream, Term t, xarg *args USES_REGS) {
}
}
if (args[WRITE_CYCLES].used && args[WRITE_CYCLES].tvalue == TermFalse) {
flags |= Unfold_cyclics_f;
flags |= Ignore_cyclics_f;
}
if (args[WRITE_QUOTED].used && args[WRITE_QUOTED].tvalue == TermTrue) {
flags |= Quote_illegal_f;
@ -593,7 +594,6 @@ static Int writeln(USES_REGS1) {
return false;
}
int output_stream = Yap_CheckTextStream(ARG1, Output_Stream_f, "writeln/2");
fprintf(stderr, "writeln %d\n", output_stream);
if (output_stream < 0) {
free(args);
return false;
@ -692,8 +692,8 @@ static Int term_to_atom(USES_REGS1) {
Term t2 = Deref(ARG2), ctl, rc = false;
Atom at;
if (IsVarTerm(t2)) {
const char *s = Yap_TermToBuffer(Deref(ARG1),
Quote_illegal_f | Handle_vars_f);
const char *s =
Yap_TermToBuffer(Deref(ARG1), Quote_illegal_f | Handle_vars_f);
if (!s || !(at = Yap_UTF8ToAtom((const unsigned char *)s))) {
Yap_Error(RESOURCE_ERROR_HEAP, t2,
"Could not get memory from the operating system");
@ -711,9 +711,9 @@ static Int term_to_atom(USES_REGS1) {
Yap_unify(rc, ARG1);
}
char *Yap_TermToBuffer(Term t, int flags) {
char *Yap_TermToBuffer(Term t, int flags) {
CACHE_REGS
int sno = Yap_open_buf_write_stream(LOCAL_encoding,flags);
int sno = Yap_open_buf_write_stream(LOCAL_encoding, flags);
if (sno < 0)
return NULL;

View File

@ -22,8 +22,6 @@
#undef HAVE_LIBREADLINE
#endif
#include "YapStreams.h"
#include <stdio.h>
#include <wchar.h>
@ -196,9 +194,5 @@ extern uint64_t Yap_StartOfWTimes;
extern bool Yap_HandleSIGINT(void);
extern bool Yap_set_stream_to_buf(StreamDesc *st, const char *bufi,
size_t nchars USES_REGS);
#endif

View File

@ -238,11 +238,16 @@
logger_define_variable(Name,Type) :-
bb_get(logger_variables,Variables),
member((Name,_),Variables),
member((Name,Type0),Variables),
!,
throw(error(variable_redefined(logger_define_variable(Name,Type)))).
( Type == Type0
->
write('redefining logger variable '),write(Name),write(' of type '), write(Type0), nl
;
throw(error(variable_redefined(logger_define_variable(Name,Type))))
).
logger_define_variable(Name,Type) :-
ground(Name),
ground(Type),
atomic(Name),
!,
logger_define_variable_intern(Type,Name).
@ -301,7 +306,8 @@ logger_set_delimiter(Delimiter) :-
%= +Name, +Value
%========================================================================
logger_set_variable(Name,Value) :-
logger_set_variable(Name,Value) :- logger_set_variable_again(Name,Value).
/*
atom_concat(logger_data_,Name,Key),
(
bb_get(Key,null)
@ -312,11 +318,12 @@ logger_set_variable(Name,Value) :-
bb_get(Key,_)
->
(
write('logger_set_variable, Variable '),
write(Name),
write(' is already set'),
nl,
fail
true
% write('logger_set_variable, Variable '),
% write(Name),
% write(' is already set'),
% nl %,
% fail
) ; (
write('logger_set_variable, unknown variable '),
write(Name),
@ -325,7 +332,7 @@ logger_set_variable(Name,Value) :-
)
)
),!.
*/
%========================================================================
%= Set the value of the variable name. If the value is already set or
%= the old value is overwritten. If the variable does not exists, an

View File

@ -263,7 +263,7 @@
% this is a test to determine whether YAP provides the needed trie library
:- initialization(
( predicate_property(trie_disable_hash, imported_from(tries)) ->
( predicate_property(trie_disable_hash, imported_from(M)) ->
trie_disable_hash
; print_message(warning,'The predicate tries:trie_disable_hash/0 does not exist. Please update trie library.')
)

File diff suppressed because it is too large Load Diff

View File

@ -207,8 +207,6 @@
:- module(learning,[do_learning/1,
do_learning/2,
set_problog_flag/2,
problog_flag/2,
reset_learning/0
]).
@ -495,49 +493,37 @@ init_learning :-
format_learning(1,'Initializing everything~n',[]),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Delete the BDDs from the previous run if they should
% not be reused
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
(
(
problog_flag(reuse_initialized_bdds,true),
problog_flag(rebuild_bdds,0)
)
->
true;
empty_bdd_directory
),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check, if continuous facts are used.
% if yes, switch to problog_exact
% continuous facts are not supported yet.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% problog_flag(init_method,(_,_,_,_,OldCall)),
%% (
%% (
%% continuous_fact(_),
%% OldCall\=problog_exact_save(_,_,_,_,_)
%% )
%% ->
%% (
%% format_learning(2,'Theory uses continuous facts.~nWill use problog_exact/3 as initalization method.~2n',[]),
%% set_problog_flag(init_method,(Query,Probability,BDDFile,ProbFile,problog_exact_save(Query,Probability,_Status,BDDFile,ProbFile)))
%% );
%% true
%% ),
%% (
%% problog_tabled(_)
%% ->
%% (
%% format_learning(2,'Theory uses tabling.~nWill use problog_exact/3 as initalization method.~2n',[]),
%% set_problog_flag(init_method,(Query,Probability,BDDFile,ProbFile,problog_exact_save(Query,Probability,_Status,BDDFile,ProbFile)))
%% );
%% true
%% ),
set_default_gradient_method,
( problog_flag(continuous_facts, true )
->
problog_flag(init_method,(_,_,_,_,OldCall)),
(
(
continuous_fact(_),
OldCall\=problog_exact_save(_,_,_,_,_)
)
->
(
format_learning(2,'Theory uses continuous facts.~nWill use problog_exact/3 as initalization method.~2n',[]),
set_problog_flag(init_method,(Query,Probability,BDDFile,ProbFile,problog_exact_save(Query,Probability,_Status,BDDFile,ProbFile)))
);
true
)
;
problog_tabled(_)
->
(
format_learning(2,'Theory uses tabling.~nWill use problog_exact/3 as initalization method.~2n',[]),
set_problog_flag(init_method,(Query,Probability,BDDFile,ProbFile,problog_exact_save(Query,Probability,_Status,BDDFile,ProbFile)))
);
true
),
succeeds_n_times(user:test_example(_,_,_,_),TestExampleCount),
format_learning(3,'~q test examples~n',[TestExampleCount]),
@ -563,7 +549,8 @@ init_learning :-
(
(user:example(_,_,P,_),P<1,P>0)
->
set_problog_flag(alpha,1.0);
set_problog_flag(alpha,1.0)
;
(
succeeds_n_times((user:example(_,_,P,=),P=:=1.0),Pos_Count),
succeeds_n_times((user:example(_,_,P,=),P=:=0.0),Neg_Count),
@ -571,6 +558,8 @@ init_learning :-
set_problog_flag(alpha,Alpha)
)
)
;
true
),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -595,6 +584,24 @@ init_learning :-
empty_bdd_directory.
set_default_gradient_method :-
problog_flag(continuous_facts, true),
!,
problog_flag(init_method,OldMethod),
format_learning(2,'Theory uses continuous facts.~nWill use problog_exact/3 as initalization method.~2n',[]),
set_problog_flag(init_method,(Query,Probability,BDDFile,ProbFile,problog_exact_save(Query,Probability,_Status,BDDFile,ProbFile))).
set_default_gradient_method :-
problog_tabled(_), problog_flag(fast_proofs,false),
!,
format_learning(2,'Theory uses tabling.~nWill use problog_exact/3 as initalization method.~2n',[]),
set_problog_flag(init_method,(Query,Probability,BDDFile,ProbFile,problog_exact_save(Query,Probability,_Status,BDDFile,ProbFile))).
set_default_gradient_method :-
problog_flag(init_method,(gene(X,Y),N,Bdd,graph2bdd(X,Y,N,Bdd))),
!.
set_default_gradient_method :-
set_problog_flag(init_method,(Query,1,BDD,
problog_kbest_as_bdd(user:Query,1,BDD))).
%========================================================================
%= This predicate goes over all training and test examples,
%= calls the inference method of ProbLog and stores the resulting
@ -617,40 +624,52 @@ init_one_query(QueryID,Query,Type) :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if BDD file does not exist, call ProbLog
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
writeln(QueryID),
(
recorded(QueryID, _, _)
->
format_learning(3,' Reuse existing BDD ~q~n~n',[QueryID]);
(
format_learning(3,' Reuse existing BDD ~q~n~n',[QueryID])
;
b_setval(problog_required_keep_ground_ids,false),
problog_flag(libbdd_init_method,(Query,Bdd,Call)),
problog_flag(init_method,(Query,N,Bdd,graph2bdd(X,Y,N,Bdd))),
Query =.. [_,X,Y]
->
Bdd = bdd(Dir, Tree, MapList),
% trace,
once(Call),
(
graph2bdd(X,Y,N,Bdd)
->
rb_new(H0),
maplist_to_hash(MapList, H0, Hash),
Tree \= [],
% writeln(Dir:Tree:MapList),
tree_to_grad(Tree, Hash, [], Grad)
;
Bdd = bdd(-1,[],[]),
Grad=[]
),
recordz(QueryID,bdd(Dir, Grad, MapList),_)
;
b_setval(problog_required_keep_ground_ids,false),
rb_new(H0),
problog_flag(init_method,(Query,NOf,Bdd,problog_kbest_as_bdd(Call,1,Bdd))),
strip_module(Call,_,gene(X,Y)),
!,
Bdd = bdd(Dir, Tree, MapList),
% trace,
problog:problog_kbest_as_bdd(user:gene(X,Y),1,Bdd),
maplist_to_hash(MapList, H0, Hash),
Tree \= [],
%put_code(0'.),
writeln(QueryID),
tree_to_grad(Tree, Hash, [], Grad),
recordz(QueryID,bdd(Dir, Grad, MapList),_)
)
),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check wether this BDD is similar to another BDD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
(
problog_flag(check_duplicate_bdds,true)
->
true /* ignore this flag for now */
;
true
),!.
init_one_query(_QueryID,_Query,_Type).
).
init_one_query(_QueryID,_Query,_Type) :-
throw(unsupported_init_method).
%========================================================================
%= updates all values of query_probability/2 and query_gradient/4
%= Updates all values of query_probability/2 and query_gradient/4
%= should be called always before these predicates are accessed
%= if the old values are still valid, nothing happens
%========================================================================
@ -1003,6 +1022,8 @@ inv_sigmoid(T,InvSig) :-
%========================================================================
save_old_probabilities :-
problog_flag(continous_facts, true),
!,
forall(tunable_fact(FactID,_),
(
continuous_fact(FactID)
@ -1021,10 +1042,28 @@ save_old_probabilities :-
)
)
).
save_old_probabilities :-
forall(tunable_fact(FactID,_),
(
get_fact_probability(FactID,OldProbability),
atomic_concat(['old_prob_',FactID],Key),
bb_put(Key,OldProbability)
)
).
save_old_probabilities :-
forall(tunable_fact(FactID,_),
(
get_fact_probability(FactID,OldProbability),
atomic_concat(['old_prob_',FactID],Key),
bb_put(Key,OldProbability)
)
).
forget_old_probabilities :-
problog_flag(continous_facts, true),
!,
forall(tunable_fact(FactID,_),
(
continuous_fact(FactID)
@ -1048,7 +1087,20 @@ forget_old_probabilities :-
)
).
forget_old_probabilities :-
forall(tunable_fact(FactID,_),
(
atomic_concat(['old_prob_',FactID],Key),
atomic_concat(['grad_',FactID],Key2),
bb_delete(Key,_),
bb_delete(Key2,_)
)
).
add_gradient(Learning_Rate) :-
problog_flag(continous_facts, true),
!,
forall(tunable_fact(FactID,_),
(
continuous_fact(FactID)
@ -1088,6 +1140,26 @@ add_gradient(Learning_Rate) :-
)
),
retractall(values_correct).
add_gradient(Learning_Rate) :-
forall(tunable_fact(FactID,_),
(
atomic_concat(['old_prob_',FactID],Key),
atomic_concat(['grad_',FactID],Key2),
bb_get(Key,OldProbability),
bb_get(Key2,GradValue),
inv_sigmoid(OldProbability,OldValue),
%writeln(FactID:OldValue +Learning_Rate*GradValue),
NewValue is OldValue +Learning_Rate*GradValue,
sigmoid(NewValue,NewProbability),
% Prevent "inf" by using values too close to 1.0
Prob_Secure is min(0.999999999,max(0.000000001,NewProbability)),
set_fact_probability(FactID,Prob_Secure)
)
),
retractall(values_correct).
% vsc: avoid silly search
@ -1103,11 +1175,16 @@ gradient_descent :-
save_old_probabilities,
update_values,
reset_gradients,
compute_gradients(Handle).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% start set gradient to zero
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
forall(tunable_fact(FactID,_),
reset_gradients :-
problog_flag(continous_facts, true),
!,
forall(tunable_fact(FactID,_),
(
continuous_fact(FactID)
->
@ -1123,7 +1200,14 @@ gradient_descent :-
bb_put(Key,0.0)
)
)
),
).
reset_gradients :-
forall(tunable_fact(FactID,_),
(
atomic_concat(['grad_',FactID],Key),
bb_put(Key,0.0)
)
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% stop gradient to zero
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -1131,6 +1215,7 @@ gradient_descent :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% start calculate gradient
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
compute_gradients(Handle) :-
bb_put(mse_train_sum, 0.0),
bb_put(mse_train_min, 0.0),
bb_put(mse_train_max, 0.0),
@ -1478,28 +1563,28 @@ my_5_min(V1,V2,V3,V4,V5,F1,F2,F3,F4,F5,VMin,FMin) :-
%========================================================================
init_flags :-
prolog_file_name('queries',Queries_Folder), % get absolute file name for './queries'
prolog_file_name('output',Output_Folder), % get absolute file name for './output'
prolog_file_name(queries,Queries_Folder), % get absolute file name for './queries'
prolog_file_name(output,Output_Folder), % get absolute file name for './output'
problog_define_flag(bdd_directory, problog_flag_validate_directory, 'directory for BDD scripts', Queries_Folder,learning_general),
problog_define_flag(output_directory, problog_flag_validate_directory, 'directory for logfiles etc', Output_Folder,learning_general,flags:learning_output_dir_handler),
problog_define_flag(log_frequency, problog_flag_validate_posint, 'log results every nth iteration', 1, learning_general),
problog_define_flag(rebuild_bdds, problog_flag_validate_nonegint, 'rebuild BDDs every nth iteration', 0, learning_general),
problog_define_flag(reuse_initialized_bdds,problog_flag_validate_boolean, 'Reuse BDDs from previous runs',false, learning_general),
problog_define_flag(check_duplicate_bdds,problog_flag_validate_boolean,'Store intermediate results in hash table',true,learning_general),
problog_define_flag(libbdd_init_method,problog_flag_validate_dummy,'ProbLog predicate to search proofs',(Query,Tree,problog:problog_kbest_as_bdd(Query,100,Tree)),learning_general,flags:learning_libdd_init_handler),
problog_define_flag(init_method,problog_flag_validate_dummy,'ProbLog predicate to search proofs',(Query,Tree,problog:problog_kbest_as_bdd(Query,100,Tree)),learning_general,flags:learning_libdd_init_handler),
problog_define_flag(alpha,problog_flag_validate_number,'weight of negative examples (auto=n_p/n_n)',auto,learning_general,flags:auto_handler),
problog_define_flag(sigmoid_slope,problog_flag_validate_posnumber,'slope of sigmoid function',1.0,learning_general),
% problog_define_flag(continuous_facts,problog_flag_validate_boolean,'support parameter learning of continuous distributions',1.0,learning_general),
problog_define_flag(learning_rate,problog_flag_validate_posnumber,'Default learning rate (If line_search=false)',examples,learning_line_search,flags:examples_handler),
problog_define_flag(line_search, problog_flag_validate_boolean,'estimate learning rate by line search',false,learning_line_search),
problog_define_flag(line_search_never_stop, problog_flag_validate_boolean,'make tiny step if line search returns 0',true,learning_line_search),
problog_define_flag(line_search_tau, problog_flag_validate_indomain_0_1_open,'tau value for line search',0.618033988749,learning_line_search),
writeln(1),
problog_define_flag(line_search_tolerance,problog_flag_validate_posnumber,'tolerance value for line search',0.05,learning_line_search),
problog_define_flag(line_search_interval, problog_flag_validate_dummy,'interval for line search',(0,100),learning_line_search,flags:linesearch_interval_handler).
init_logger :-
logger_define_variable(iteration, int),
logger_define_variable(iteration, int),
logger_define_variable(duration,time),
logger_define_variable(mse_trainingset,float),
logger_define_variable(mse_min_trainingset,float),
@ -1519,5 +1604,7 @@ init_logger :-
logger_define_variable(llh_test_queries,float).
:- initialization(init_flags).
:- initialization(init_logger).

View File

@ -1,15 +1,20 @@
# set(CMAKE_MACOSX_RPATH 1)
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
add_lib(jplYap jpl.h jpl.c hacks.h)
include_directories (${JAVA_INCLUDE_PATH} ${JAVA_INCLUDE_PATH2} ${JAVA_AWT_PATH} )
target_link_libraries(jplYap libYap ${JAVA_JVM_LIBRARY} ${JAVA_AWT_LIBRARY})
if (APPLE)
get_filename_component ( JAVA_AWT_DIR ${JAVA_AWT_LIBRARY} DIRECTORY)
find_library (JLI jli ${JAVA_AWT_DIR}/jli)
endif()
target_link_libraries(jplYap libYap ${JLI} ${JNI_LIBRARIES})
set_target_properties(jplYap PROPERTIES
OUTPUT_NAME jpl
INSTALL_RPATH_USE_LINK_PATH TRUE )
INSTALL_RPATH_USE_LINK_PATH TRUE
)
# set(YAP_SYSTEM_OPTIONS "jpl " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
install(TARGETS jplYap

View File

@ -640,7 +640,7 @@ static JNIEnv*
jni_env(void) /* economically gets a JNIEnv pointer, valid for this thread */
{ JNIEnv *env;
switch( (*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_2) )
switch( (*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_8) )
{ case JNI_OK:
return env;
case JNI_EDETACHED:

View File

@ -15,12 +15,15 @@
* *
*************************************************************************/
#include "Yap.h"
#ifdef USE_MYDDAS
#include "Yatom.h"
#include "cut_c.h"
#include "myddas.h"
#include <stdlib.h>
#ifdef USE_MYDDAS
#include "myddas.h"
#ifdef MYDDAS_STATS
#include "myddas_statistics.h"
#endif
@ -678,30 +681,17 @@ void Yap_MYDDAS_delete_all_myddas_structs(void) {
#endif
}
#endif
void init_myddas(void) {
CACHE_REGS
if (myddas_initialised)
{
return;
}
#if USE_MYDDAS
Term cm=CurrentModule;
CurrentModule = USER_MODULE;
if (myddas_initialised)
return;
#ifdef __ANDROID__
init_sqlite3();
#endif
#if defined MYDDAS_ODBC
Yap_InitBackMYDDAS_ODBCPreds();
#endif
#endif
#if defined MYDDAS_ODBC
Yap_InitMYDDAS_ODBCPreds();
#endif
#if defined USE_MYDDAS
Yap_InitMYDDAS_SharedPreds();
#endif
#if defined MYDDAS_TOP_LEVEL && \
defined MYDDAS_MYSQL // && defined HAVE_LIBREADLINE
Yap_InitMYDDAS_TopLevelPreds();
#endif
#if USE_MYDDAS
#define stringify(X) _stringify(X)
#define _stringify(X) #X
Yap_REGS.MYDDAS_GLOBAL_POINTER = NULL;
@ -709,12 +699,25 @@ void init_myddas(void) {
MkAtomTerm(Yap_LookupAtom(stringify(MYDDAS_VERSION))));
Yap_HaltRegisterHook((HaltHookFunc)Yap_MYDDAS_delete_all_myddas_structs,
NULL);
Yap_InitMYDDAS_SharedPreds();
Yap_InitBackMYDDAS_SharedPreds();
#undef stringify
#undef _stringify
Yap_MYDDAS_delete_all_myddas_structs();
#if defined MYDDAS_ODBC
Yap_InitBackMYDDAS_ODBCPreds();
Yap_InitMYDDAS_ODBCPreds();
#endif
#if defined MYDDAS_TOP_LEVEL && \
defined MYDDAS_MYSQL // && defined HAVE_LIBREADLINE
Yap_InitMYDDAS_TopLevelPreds();
#endif
c_db_initialize_myddas(PASS_REGS1);
myddas_initialised = TRUE;
#ifdef __ANDROID__
init_sqlite3();
#endif
#endif
myddas_initialised = true;
CurrentModule = cm;
}

View File

@ -22,6 +22,7 @@
#ifdef DEBUG
:- yap_flag(single_var_warnings,on).
:- yap_flag(write_strings,on).
#endif
#define SWITCH(Contype, G) \
@ -181,7 +182,7 @@
member/2
]).
:- set(verbose,silent).
:- set_prolog_flag(verbose,silent).
@ -230,108 +231,108 @@ db_open(postgres,Connection,Host/Db/Port,User,Password) :-
integer(Port),!,
db_open(postgres,Connection,Host/Db/Port/_,User,Password). % Var to be NULL, the default socket
db_open(postgres,Connection,Host/Db/Socket,User,Password) :- !,
db_open(postgres,Connection,Host/Db/0/Socket,User,Password). % 0 is default port
db_open(postgres,Connection,Host/Db/0/Socket,User,Password). % 0 is default port
db_open(postgres,Connection,Host/Db,User,Password) :-
db_open(postgres,Connection,Host/Db/0/_,User,Password). % 0 is default port and Var to be NULL, the default socpket
db_open(postgres,Connection,Host/Db/0/_,User,Password). % 0 is default port and Var to be NULL, the default socpket
#endif
#ifdef MYDDAS_ODBC
db_open(odbc,Connection,ODBCEntry,User,Password) :-
'$error_checks'(db_open(odbc,Connection,ODBCEntry,User,Password)),
c_odbc_connect(ODBCEntry,User,Password,Con),
set_value(Connection,Con).
'$error_checks'(db_open(odbc,Connection,ODBCEntry,User,Password)),
c_odbc_connect(ODBCEntry,User,Password,Con),
set_value(Connection,Con).
#endif
%% sqlite3
db_open(sqlite3,Connection,File,User,Password) :-
'$error_checks'(db_open(sqlite3,Connection,File,User,Password)),
c_sqlite3_connect(File,User,Password,Con),
set_value(Connection,Con).
'$error_checks'(db_open(sqlite3,Connection,File,User,Password)),
c_sqlite3_connect(File,User,Password,Con),
set_value(Connection,Con).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% db_close/1
%% db_close/0
%
% close a connection _Con_: all its resources are returned, and all undefined
% predicates are abolished. Default is to close `myddas`.
%% db_close/1
%% db_close/0
%
% close a connection _Con_: all its resources are returned, and all undefined
% predicates are abolished. Default is to close `myddas`.
db_close:-
db_close(myddas).
db_close(myddas).
db_close(Protocol):-
'$error_checks'(db_close(Protocol)),
get_value(Protocol,Con),
c_db_connection_type(Con,ConType),
( '$abolish_all'(Con) ;
set_value(Protocol,[]), % "deletes" atom
C_SWITCH( ConType, disconnect(Con) )
).
'$error_checks'(db_close(Protocol)),
get_value(Protocol,Con),
c_db_connection_type(Con,ConType),
( '$abolish_all'(Con) ;
set_value(Protocol,[]), % "deletes" atom
C_SWITCH( ConType, disconnect(Con) )
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% db_verbose/1
%
%
% db_verbose/1
%
%
db_verbose(X):-
var(X),!,
get_value(db_verbose,X).
var(X),!,
get_value(db_verbose,X).
db_verbose(N):-!,
set_value(db_verbose,N).
%default value
set_value(db_verbose,N).
%default value
:- set_value(db_verbose,0).
:- set_value(db_verbose_filename,myddas_queries).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% db_module/1
%
%
% db_module/1
%
%
db_module(X):-
var(X),!,
get_value(db_module,X).
var(X),!,
get_value(db_module,X).
db_module(ModuleName):-
set_value(db_module,ModuleName).
% default value
set_value(db_module,ModuleName).
% default value
:- db_module(user).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% db_is_database_predicate(+,+,+)
%
%
% db_is_database_predicate(+,+,+)
%
%
db_is_database_predicate(Module,PredName,Arity):-
'$error_checks'(db_is_database_predicate(PredName,Arity,Module)),
c_db_check_if_exists_pred(PredName,Arity,Module).
'$error_checks'(db_is_database_predicate(PredName,Arity,Module)),
c_db_check_if_exists_pred(PredName,Arity,Module).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#ifdef MYDDAS_STATS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% db_stats(+,-)
%
%
% db_stats(+,-)
%
%
db_stats(List):-
db_stats(myddas,List).
db_stats(myddas,List).
db_stats(Protocol,List):-
'$error_checks'(db_stats(Protocol,List)),
NumberOfStats = 10,
'$make_a_list'(NumberOfStats,ListX1),
( var(Protocol) ->
c_db_stats(0,ListX1)
;
get_value(Protocol,Conn),
c_db_stats(Conn,ListX1)
),
'$make_stats_list'(ListX1,List).
'$error_checks'(db_stats(Protocol,List)),
NumberOfStats = 10,
'$make_a_list'(NumberOfStats,ListX1),
( var(Protocol) ->
c_db_stats(0,ListX1)
;
get_value(Protocol,Conn),
c_db_stats(Conn,ListX1)
),
'$make_stats_list'(ListX1,List).
#ifdef DEBUG
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% db_stats_time(+,-)
% Reference is C pointer (memory reference)
% db_stats_time(+,-)
% Reference is C puuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uuuuu;ointer (memory reference)
%
db_stats_time(Reference,Time):-
'$error_checks'(db_stats_time(Reference,Time)),
@ -449,7 +450,6 @@ db_assert(Connection,PredName):-
'$error_checks'(db_insert2(Connection,PredName,Code)),
'$get_values_for_insert'(Code,ValuesList,RelName),
'$make_atom'(['INSERT INTO `',RelName,'` VALUES '|ValuesList],SQL),
get_value(Connection,Con),
c_db_connection_type(Con,ConType),
'$write_or_not'(SQL),
@ -685,17 +685,18 @@ db_describe(Connection,Y,Z) :-
db_datalog_show_tables :-
db_datalog_show_tables(myddas).
db_show_tables :-
'$error_checks'(db_datalog_show_tables),
get_value(myddas,Con),
c_db_connection_type(Con,DBMS),
DBMS:datalog_show_tables.
db_datalog_show_tables(Connection) :-
'$error_checks'(db_datalog_show_tables(Connection) ),
get_value(Connection,Con),
c_db_connection_type(Con,DBMS),
switch( DBMS, datalog_show_tables(Connection) ).
db_datalog_show_tables :-
'$error_checks'(db_datalog_show_tables),
get_value(myddas,Con),
c_db_connection_type(Con,DBMS),
DBMS:datalog_show_tables.
/**
@pred db_show_tables(+,?).

View File

@ -230,7 +230,7 @@ db_abolish(PredName,Arity):-
%
db_listing:-
c_db_connection(Con),
c_db_preds_conn(Con,Module,Name,Arity),
user:c_db_preds_conn(Con,Module,Name,Arity),
listing(Module:Name/Arity),
fail.
db_listing.
@ -243,15 +243,15 @@ db_listing.
%
db_listing(Module:Name/Arity):-!,
c_db_connection(Con),
c_db_preds_conn(Con,Module,Name,Arity),
user:c_db_preds_conn(Con,Module,Name,Arity),
listing(Module:Name/Arity).
db_listing(Name/Arity):-!,
c_db_connection(Con),
c_db_preds_conn(Con,Module,Name,Arity),
user:c_db_preds_conn(Con,Module,Name,Arity),
listing(Module:Name/Arity).
db_listing(Name):-
c_db_connection(Con),
c_db_preds_conn(Con,Module,Name,Arity),
user:c_db_preds_conn(Con,Module,Name,Arity),
listing(Module:Name/Arity).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -260,13 +260,12 @@ db_listing(Name):-
%
table_arity( Con, ConType, RelationName, Arity ) :-
c_db_connection_type(Con,ConType),
writeln( ConType ),
% get relation arity
( ConType == mysql ->
c_db_my_number_of_fields(RelationName,Con,Arity)
;
ConType == postgres ->
c_postgres_number_of_fields(RelationName,Con,Arity)
c_postgres_number_of_fields(RelationName,Con,Arit)
;
ConType == odbc ->
c_odbc_number_of_fields(RelationName,Con,Arity)

View File

@ -28,7 +28,7 @@
#define NAME() 'YAPodbc'
#define MODULE() user
#define INIT() init_odbc
#elif defined( postgres )
#elif defined( postrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrs )
#undef postgres
#define DBMS(x) postgres_##x
#define c_DBMS(x) c_postgres_##x
@ -101,7 +101,6 @@ DBMS(result_set)(store_result):-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DBMS(db_datalog_describe)/2
%

View File

@ -1,4 +1,3 @@
:- stop_low_level_trace.
:- use_module(library(lists)).
@ -14,10 +13,22 @@ main_ :-
fail.
main_ .
:- if( yap_flag(android,true) ).
init :-
db_open(sqlite3, '/data/user/0/pt.up.yap/files/chinook.db', _, _),
!,
writeln('chinook has landed').
init :-
catch(db_open(sqlite3,'chinook.db',_,_), _, fail),
% db_open(sqlite3, 'chinook.db', _, _),
writeln('chinook has landed').
:- else.
init :-
db_open(sqlite3, '/data/user/0/pt.up.yap.yapdroid/files/Yap/chinook.db', _, _),
% db_open(sqlite3, 'chinook.db', _, _),
writeln('chinook has landed').
:-endif.
go :-
writeln(('db_import')),

View File

@ -558,7 +558,7 @@ term_t t0 = python_acquire_GIL();
*s++ = '.';
s[0] = '\0';
} else if (!PL_get_nchars(mname, &len, &s,
CVT_ATOM | CVT_EXCEPTION | REP_UTF8)) {
CVT_ATOM | CVT_STRING| CVT_EXCEPTION | REP_UTF8)) {
python_release_GIL(t0);
pyErrorAndReturn(false, false);
} else {

View File

@ -6,7 +6,7 @@ set (PYTHON_HEADERS py4yap.h)
set (CMAKE_POSITION_INDEPENDENT_CODE TRUE)
include_directories( BEFORE ${PYTHON_INCLUDE_DIRS} ${CMAKE_BINARY_DIR}
${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/os )
${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/os ${CMAKE_SOURCE_DIR}/H ${CMAKE_SOURCE_DIR}/OPTYap )
#talk to python.pl
add_lib(YAPPython pyload.c ${PYTHON_HEADERS} )

View File

@ -1,5 +1,7 @@
#include "Yap.h"
#include "py4yap.h"
extern PyObject *py_Local, *py_Global;
@ -13,6 +15,59 @@ PyObject *YE(term_t t, int line, const char *file, const char *code) {
return NULL;
}
PyObject *YEC(PyObject *f, PyObject *a, PyObject *d, int line, const char *file, const char *code) {
fprintf(stderr, "**** Warning,%s@%s:%d: failed on Python call \n", code,
file, line);
if (f)
PyObject_Print(f, stderr, 0);
else
fprintf(stderr,"<null>");
if (a)
PyObject_Print(a, stderr, 0);
if (d)
PyObject_Print(d, stderr, 0);
fprintf(stderr,"\n");
return NULL;
}
PyObject *YED2(PyObject *f, PyObject *a, PyObject *d, int line, const char *file, const char *code) {
fprintf(stderr, "**** Warning,%s@%s:%d: failed on Python call \n", code,
file, line);
if (f)
PyObject_Print(f, stderr, 0);
else
fprintf(stderr,"<null>");
fprintf(stderr,"(");
if (a)
PyObject_Print(a, stderr, 0);
fprintf(stderr,",");
if (d)
PyObject_Print(d, stderr, 0);
fprintf(stderr,")\n");
return NULL;
}
PyObject *YED1(PyObject *f, PyObject *a, int line, const char *file, const char *code) {
fprintf(stderr, "**** Warning,%s@%s:%d: failed on Python call \n", code,
file, line);
if (f)
PyObject_Print(f, stderr, 0);
else
fprintf(stderr,"<null>");
fprintf(stderr,"(");
if (a)
PyObject_Print(a, stderr, 0);
fprintf(stderr,")\n");
return NULL;
}
void YEM(const char *exp, int line, const char *file, const char *code) {
fprintf(stderr, "**** Warning,%s@%s:%d: failed while executing %s\n", code,
file, line, exp);
@ -50,7 +105,6 @@ static PyObject *s_to_python(const char *s, bool eval, PyObject *p0) {
*/
X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0) {
char *buf = malloc(strlen(s) + 1), *child;
while ((child = strchr(s, '.')) != NULL) {
size_t len = child - s;
@ -62,40 +116,34 @@ X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0) {
return s_to_python(s, eval, p0);
}
static bool copy_to_dictionary(PyObject *dict, term_t targ, term_t taux,
static bool entry_to_dictionary(PyObject *dict, Term targ,
bool eval, bool cvt) {
PyObject *lhs, *rhs;
term_t tleft = PL_new_term_ref(), tright = PL_new_term_ref();
functor_t fun;
AOK(PL_get_functor(targ, &fun), false);
while (fun == FUNCTOR_comma2) {
AOK(PL_get_arg(1, targ, tleft), false);
if (!copy_to_dictionary(dict, tleft, taux, eval, cvt))
return false;
AOK(PL_get_arg(2, targ, targ), false);
return copy_to_dictionary(dict, tright, taux, eval, cvt);
PyObject *lhs = NULL, *rhs;
Term t1, t2;
const char *s;
t1 = ArgOfTerm(1,targ);
if (YAP_IsAtomTerm(t1)) {
s = YAP_AtomName(YAP_AtomOfTerm(t1));
} else if (IsStringTerm(t1)) {
s = YAP_StringOfTerm(t1);
} else if (IsIntegerTerm(t1)) {
lhs = PyLong_FromLong(IntegerOfTerm(t1));
} else {
return false;
}
// PyObject_Print(dict, stderr, 0); fprintf(stderr,"\n");
// Py_DECREF(lhs);
// Py_DECREF(rhs);
AOK(PL_get_arg(1, targ, tleft), false);
lhs = atom_to_python_string(tleft);
if (lhs == NULL) {
return FALSE;
lhs = PyUnicode_FromString(s);
}
AOK(PL_get_arg(2, targ, tright), false);
rhs = term_to_python(tright, eval, NULL, cvt);
t2 = ArgOfTerm(2,targ);
rhs = term_to_python(Yap_InitSlot(t2), eval, NULL, cvt);
if (rhs == NULL) {
PyErr_Print();
return false;
}
return PyDict_SetItem(dict, lhs, rhs) >= 0;
// PyObject_Print(dict, stderr, 0); fprintf(stderr,"\n");
// Py_DECREF(lhs);
// Py_DECREF(rhs);
return PyDict_SetItem(dict, lhs, rhs) == 0;
}
/**
@ -107,9 +155,8 @@ static bool copy_to_dictionary(PyObject *dict, term_t targ, term_t taux,
* @return a Python object descriptor or NULL if failed
*/
PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
// o≈
//
YAP_Term yt = YAP_GetFromSlot(t);
// Yap_DebugPlWriteln(yt);
switch (PL_term_type(t)) {
case PL_VARIABLE: {
if (yt == 0) {
@ -136,7 +183,7 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
o = PyUnicode_FromString(s);
}
if (o) {
//PyDict_SetItemString(py_Atoms, s, Py_None);
// PyDict_SetItemString(py_Atoms, s, Py_None);
Py_INCREF(o);
return o;
}
@ -148,20 +195,20 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
} else if (YAP_IsStringTerm(yt)) {
s = YAP_StringOfTerm(yt);
} else {
return CHECKNULL(t, NULL);
return CHECKNULL(t, NULL);
}
PyObject *pobj = PyUnicode_FromString(s);
PyObject *pobj = PyUnicode_FromString(s);
#if PY_MAJOR_VERSION < 3
if (proper_ascii_string(s)) {
PyObject *o = PyString_FromStringAndSize(s, strlen(s));
return CHECKNULL(t, o);
}
}
#endif
// char *p = malloc(strlen(s)+1);
// strcpy(p, s);
Py_IncRef(pobj);
return CHECKNULL(t, pobj);
// char *p = malloc(strlen(s)+1);
// strcpy(p, s);
Py_IncRef(pobj);
return CHECKNULL(t, pobj);
} break;
case PL_INTEGER: {
int64_t j;
@ -186,46 +233,34 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
}
default:
if (PL_is_pair(t)) {
term_t tail = PL_new_term_ref();
term_t arg = PL_new_term_ref();
Term t0 = Yap_GetFromHandle(t);
Term *tail;
size_t len, i;
if (PL_skip_list(t, tail, &len) && PL_get_nil(tail)) {
if ((len = Yap_SkipList(&t0, &tail)) > 0 && *tail == TermNil) {
PyObject *out, *a;
out = PyList_New(len);
if (!out) {
PL_reset_term_refs(tail);
YAPPy_ThrowError(SYSTEM_ERROR_INTERNAL, t, "list->python");
}
for (i = 0; i < len; i++) {
if (!PL_get_list(t, arg, t)) {
PL_reset_term_refs(tail);
YAPPy_ThrowError(SYSTEM_ERROR_INTERNAL, t, "list->python");
}
a = term_to_python(arg, eval, o, cvt);
Term ai = HeadOfTerm(t0);
a = term_to_python(Yap_InitHandle(ai), eval, o, cvt);
if (a) {
if (PyList_SetItem(out, i, a) < 0) {
YAPPy_ThrowError(SYSTEM_ERROR_INTERNAL, t, "list->python");
}
}
t0 = TailOfTerm(t0);
}
PL_reset_term_refs(tail);
return out;
} else {
PyObject *no = find_obj(o, t, false);
if (no == o)
return NULL;
return term_to_python(t, eval, no, cvt);
PyObject *no = find_term_obj(o, &t0, false);
return yap_to_python(t0, eval, no, cvt);
}
} else {
{
term_t tail = PL_new_term_ref();
functor_t fun;
atom_t name;
int arity;
PyObject *rc;
if (!PL_get_functor(t, &fun)) {
PL_reset_term_refs(tail);
YAPPy_ThrowError(SYSTEM_ERROR_INTERNAL, t, "list->python");
@ -262,11 +297,11 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
PyObject *ip = term_to_python(trhs, eval, o, cvt);
if (PySequence_Check(v)) {
#if PY_MAJOR_VERSION < 3
if (PyLong_Check(ip)) {
if (PyLong_Check(ip)) {
min = PyLong_AsLong(ip);
} else if (PyInt_Check(ip)) {
} else if (PyInt_Check(ip)) {
min = PyInt_asInt(ip);
}
}
#else
if (PyLong_Check(ip)) {
PyObject *o = PySequence_GetItem(v, PyLong_AsLong(ip));
@ -298,7 +333,9 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
}
if (fun == FUNCTOR_brackets1) {
AOK(PL_get_arg(1, t, t), NULL);
return term_to_python(t, true, NULL, true);
PyObject *ys = term_to_python(t, true, o, true), *rc;
CHECK_CALL(ys, PyTuple_New(0), NULL);
return rc;
}
if (fun == FUNCTOR_complex2) {
term_t targ = PL_new_term_ref();
@ -337,39 +374,36 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
return PyComplex_FromDoubles(d1, d2);
}
if (fun == FUNCTOR_curly1) {
term_t targ = PL_new_term_ref(), taux = PL_new_term_ref();
PyObject *dict;
AOK(PL_get_arg(1, t, t), NULL);
PyObject *dict;
Term yt = ArgOfTerm(1,Yap_GetFromHandle(t));
if (!(dict = PyDict_New()))
return NULL;
Py_INCREF(dict);
DebugPrintf("Dict %p\n", dict);
while (PL_is_functor(t, FUNCTOR_comma2)) {
AOK(PL_get_arg(1, t, targ), NULL);
AOK(PL_is_functor(targ, FUNCTOR_colon2), NULL);
AOK(copy_to_dictionary(dict, targ, taux, eval, cvt), NULL);
AOK(PL_get_arg(2, t, t), NULL);
}
if (PL_is_functor(t, FUNCTOR_colon2)) {
AOK(copy_to_dictionary(dict, t, taux, eval, cvt), NULL);
}
return dict;
Py_INCREF(dict);
while (IsApplTerm(yt) && FunctorOfTerm(yt) == FunctorComma) {
if (!entry_to_dictionary(dict, ArgOfTerm(1,yt), eval, cvt))
return NULL;
yt = ArgOfTerm(2,yt);
}
if (entry_to_dictionary(dict, yt, eval, cvt))
return dict;
else
return Py_None;
}
atom_t name;
int arity;
AOK(PL_get_name_arity(t, &name, &arity), NULL);
if (name == ATOM_t) {
int i;
rc = PyTuple_New(arity);
PyObject *rc = PyTuple_New(arity);
for (i = 0; i < arity; i++) {
term_t arg = PL_new_term_ref();
if (!PL_get_arg(i + 1, t, arg)) {
PL_reset_term_refs(arg);
YAPPy_ThrowError(SYSTEM_ERROR_INTERNAL, t, "t(...)->python");
}
PyObject *a = term_to_python(arg, eval, o, cvt);
PyObject *a = term_to_python(arg, eval, NULL, cvt);
if (a) {
if (PyTuple_SetItem(rc, i, a) < 0) {
PL_reset_term_refs(arg);
@ -380,11 +414,9 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
}
}
if (eval)
rc = compound_to_pyeval(t, o, cvt);
return compound_to_pyeval(t, o, cvt);
else
rc = compound_to_pytree(t, o, cvt);
PL_reset_term_refs(tail);
return rc;
return compound_to_pytree(t, o, cvt);
}
}
}
@ -392,8 +424,8 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
}
PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o, bool cvt) {
if (t == 0)
return NULL;
if (t == 0 || t == TermNone)
return Py_None;
term_t yt = YAP_InitSlot(t);
o = term_to_python(yt, eval, o, cvt);
PL_reset_term_refs(yt);

View File

@ -1,5 +1,9 @@
#include "Yap.h"
#include "py4yap.h"
#include <frameobject.h>
void YAPPy_ThrowError__(const char *file, const char *function, int lineno,
@ -28,12 +32,9 @@ void YAPPy_ThrowError__(const char *file, const char *function, int lineno,
}
}
static foreign_t repr_term(PyObject *pVal, term_t t) {
term_t to = PL_new_term_ref(), t1 = PL_new_term_ref();
PL_put_pointer(t1, pVal);
PL_cons_functor(to, FUNCTOR_pointer1, t1);
Py_INCREF(pVal);
return PL_unify(t, to);
static Term repr_term(PyObject *pVal) {
Term t = MkAddressTerm(pVal);
return Yap_MkApplTerm(FunctorObj, 1, &t);
}
foreign_t assign_to_symbol(term_t t, PyObject *e);
@ -50,185 +51,160 @@ foreign_t assign_to_symbol(term_t t, PyObject *e) {
return PyObject_SetAttrString(dic, s, e) == 0;
}
foreign_t python_to_term(PyObject *pVal, term_t t)
{
bool rc = true;
term_t to = PL_new_term_ref();
// fputs(" <<*** ",stderr); PyObject_Print(pVal,stderr,0);
// fputs("<<***\n",stderr);
static Term python_to_term__(PyObject *pVal) {
if (pVal == Py_None) {
// fputs("<<*** ",stderr);Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
// >>***\n",stderr);
rc = true;
//return YAP_MkVarTerm();
// fputs("<<*** ",stderr);Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
return MkAtomTerm(Yap_LookupAtom("none"));
// >>***\n",stderr);
} else if (PyBool_Check(pVal)) {
rc = rc && PL_unify_bool(t, PyObject_IsTrue(pVal));
if(PyObject_IsTrue(pVal)) return TermTrue;
return TermFalse;
} else if (PyLong_Check(pVal)) {
rc = rc && PL_unify_int64(t, PyLong_AsLong(pVal));
return MkIntegerTerm(PyLong_AsLong(pVal));
#if PY_MAJOR_VERSION < 3
} else if (PyInt_Check(pVal)) {
rc = rc && PL_unify_int64(t, PyInt_AsLong(pVal));
return MkIntegerTerm(PyInt_AsLong(pVal));
#endif
} else if (PyFloat_Check(pVal)) {
rc = rc && PL_unify_float(t, PyFloat_AsDouble(pVal));
return MkFloatTerm(PyFloat_AsDouble(pVal));
} else if (PyComplex_Check(pVal)) {
term_t t1 = PL_new_term_ref(), t2 = PL_new_term_ref();
if (!PL_put_float(t1, PyComplex_RealAsDouble(pVal)) ||
!PL_put_float(t2, PyComplex_ImagAsDouble(pVal)) ||
!PL_cons_functor(to, FUNCTOR_complex2, t1, t2)) {
rc = false;
} else {
rc = rc && PL_unify(t, to);
}
} else if (PyUnicode_Check(pVal)) {
Term t[2];
t[0] = MkFloatTerm(PyComplex_RealAsDouble(pVal));
t[1] = MkFloatTerm(PyComplex_ImagAsDouble(pVal));
return Yap_MkApplTerm(FunctorI, 2, t);
}
else if (PyUnicode_Check(pVal)) {
#if PY_MAJOR_VERSION < 3
size_t sz = PyUnicode_GetSize(pVal) + 1;
wchar_t *s = malloc(sizeof(wchar_t) * sz);
sz = PyUnicode_AsWideChar((PyUnicodeObject *)pVal, a, sz - 1);
free(ptr);
size_t sz = PyUnicode_GetSize(pVal) + 1;
wchar_t *s = malloc(sizeof(wchar_t) * sz);
sz = PyUnicode_AsWideChar((PyUnicodeObject *)pVal, a, sz - 1);
free(ptr);
#else
const char *s = PyUnicode_AsUTF8(pVal);
const char *s = PyUnicode_AsUTF8(pVal);
#endif
if (Yap_AtomInUse(s))
#if 0
if (false && Yap_AtomInUse(s))
rc = rc && PL_unify_atom_chars(t, s);
else
rc = rc && PL_unify_string_chars(t, s);
} else if (PyByteArray_Check(pVal)) {
rc = rc && PL_unify_string_chars(t, PyByteArray_AsString(pVal));
#if PY_MAJOR_VERSION < 3
} else if (PyString_Check(pVal)) {
rc = rc && PL_unify_string_chars(t, PyString_AsString(pVal));
#endif
} else if (PyTuple_Check(pVal)) {
Py_ssize_t i, sz = PyTuple_Size(pVal);
functor_t f;
const char *s;
if (sz == 0) {
rc = rc && PL_unify_atom(t, ATOM_brackets);
} else {
if ((s = (Py_TYPE(pVal)->tp_name))) {
if (!strcmp(s, "v")) {
pVal = PyTuple_GetItem(pVal, 0);
if (pVal == NULL) {
pVal = Py_None;
PyErr_Clear();
}
term_t v = YAP_InitSlot(PyLong_AsLong(pVal));
return PL_unify(v, t);
}
if (s[0] == '$') {
char *ns = malloc(strlen(s) + 5);
strcpy(ns, "__");
strcat(ns, s + 1);
strcat(ns, "__");
f = PL_new_functor(PL_new_atom(ns), sz);
} else {
f = PL_new_functor(PL_new_atom(s), sz);
}
} else {
f = PL_new_functor(ATOM_t, sz);
}
if (PL_unify_functor(t, f)) {
for (i = 0; i < sz; i++) {
term_t to = PL_new_term_ref();
if (!PL_get_arg(i + 1, t, to))
rc = false;
PyObject *p = PyTuple_GetItem(pVal, i);
if (p == NULL) {
PyErr_Clear();
p = Py_None;
} else {
rc = rc && python_to_term(p, to);
}
PL_reset_term_refs(to);
}
} else {
rc = false;
}
// fputs(" ||*** ",stderr); Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
// ||***\n",stderr);
if (pyStringToString)
return MkStringTerm(s);
else
return MkAtomTerm(Yap_LookupAtom(s));
}
else if (PyByteArray_Check(pVal)) {
return MkStringTerm(PyByteArray_AsString(pVal));
#if PY_MAJOR_VERSION < 3
}
else if (PyString_Check(pVal)) {
return MkStringTerm(PyString_AsString(pVal));
#endif
}
else if (PyTuple_Check(pVal)) {
Py_ssize_t sz = PyTuple_Size(pVal);
const char *s;
s = Py_TYPE(pVal)->tp_name;
if (s == NULL)
s = "t";
if (sz == 0) {
return MkAtomTerm(YAP_LookupAtom(Py_TYPE(pVal)->tp_name));
}
else {
Functor f = Yap_MkFunctor(Yap_LookupAtom(s), sz);
Term t = Yap_MkNewApplTerm(f, sz);
long i;
CELL *ptr = RepAppl(t) + 1;
for (i = 0; i < sz; i++) {
PyObject *p = PyTuple_GetItem(pVal, i);
if (p == NULL) {
PyErr_Clear();
return false;
}
} else if (PyList_Check(pVal)) {
Py_ssize_t i, sz = PyList_GET_SIZE(pVal);
for (i = 0; i < sz; i++) {
PyObject *obj;
term_t to = PL_new_term_ref();
rc = rc && PL_unify_list(t, to, t);
if ((obj = PyList_GetItem(pVal, i)) == NULL) {
obj = Py_None;
}
rc = rc && python_to_term(obj, to);
PL_reset_term_refs(to);
if (!rc)
return false;
}
return rc && PL_unify_nil(t);
// fputs("[***] ", stderr);
// Yap_DebugPlWrite(yt); fputs("[***]\n", stderr);
} else if (PyDict_Check(pVal)) {
Py_ssize_t pos = 0;
int left = PyDict_Size(pVal);
PyObject *key, *value;
if (left == 0) {
rc = rc && PL_unify_atom(t, ATOM_curly_brackets);
} else {
while (PyDict_Next(pVal, &pos, &key, &value)) {
term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint,
tnew = PL_new_term_ref();
term_t to = PL_new_term_ref();
/* do something interesting with the values... */
if (!python_to_term(key, tkey)) {
continue;
}
if (!python_to_term(value, tval)) {
continue;
}
/* reuse */
tint = tkey;
if (!PL_cons_functor(tint, FUNCTOR_colon2, tkey, tval)) {
rc = false;
continue;
}
if (--left) {
if (!PL_cons_functor(tint, FUNCTOR_comma2, tint, tnew))
PL_reset_term_refs(tkey);
rc = false;
}
if (!PL_unify(to, tint)) {
rc = false;
}
}
rc = rc && PL_unify(t, to);
}
} else {
rc = rc && repr_term(pVal, t);
*ptr++ = python_to_term__(p);
}
return t;
}
// PL_reset_term_refs(to);
// fputs(" ||*** ",stderr); Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
// ||***\n",stderr);
}
else if (PyList_Check(pVal)) {
Py_ssize_t i, sz = PyList_GET_SIZE(pVal);
if (sz == 0)
return repr_term(pVal);
Term t = TermNil;
for (i = sz; i > 0; ) {
-- i;
PyObject *p = PyList_GetItem(pVal, i);
if (p == NULL) {
PyErr_Clear();
return false;
}
if (!python_to_term__(p))
return false;
t = MkPairTerm(python_to_term__(p), t);
}
return t;
}
else if (PyDict_Check(pVal)) {
Py_ssize_t pos = 0, tot = PyDict_Size(pVal);
PyObject *key, *value;
Term f, *opt = &f, t, to;
while (PyDict_Next(pVal, &pos, &key, &value)) {
Term t0[2];
t0[0] = python_to_term__(key);
t0[1] = python_to_term__(value);
to = Yap_MkApplTerm(FunctorModule, 2, t0);
if (pos < tot) {
t = Yap_MkNewApplTerm(FunctorComma, 2);
CELL *pt = RepAppl(t) + 1;
pt[0] = to;
*opt = t;
opt = pt+1;
} else {
if (pos == 0) {
return repr_term(pVal);
}
*opt = to;
break;
}
}
return Yap_MkApplTerm(FunctorBraces, 1, &f);
}
return repr_term(pVal);
return rc;
}
foreign_t python_to_term(PyObject *pVal, term_t t) {
Term o = python_to_term__(pVal);
return YAP_Unify(o,YAP_GetFromSlot(t));
}
// extern bool Yap_do_low_level_trace;
X_API YAP_Term pythonToYAP(PyObject *pVal) {
term_t t = PL_new_term_ref();
if (pVal == NULL || !python_to_term(pVal, t)) {
PL_reset_term_refs(t);
return 0;
}
YAP_Term tt = YAP_GetFromSlot(t);
PL_reset_term_refs(t);
// Yap_do_low_level_trace=1;
/* fputs(" *** ", stderr); */
/* PyObject_Print(pVal, stderr, 0); */
/* fputs("***>>\n", stderr); */
if (pVal == NULL)
Yap_ThrowError(SYSTEM_ERROR_INTERNAL, 0, NULL);
Term t = python_to_term__(pVal);
/* fputs("<< *** ", stderr); */
/* Yap_DebugPlWrite(t); */
/* fputs(" ***\n", stderr); */
// Py_DECREF(pVal);
return tt;
return t;
}
PyObject *py_Local, *py_Global;
/**
* assigns the Python RHS to a Prolog term LHS, ie LHS = RHS
*
@ -247,6 +223,7 @@ PyObject *py_Local, *py_Global;
*python_assign.
*/
bool python_assign(term_t t, PyObject *exp, PyObject *context) {
PyErr_Print();
context = find_obj(context, t, false);
// Yap_DebugPlWriteln(yt);
switch (PL_term_type(t)) {
@ -255,9 +232,10 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
return python_to_term(exp, t);
}
case PL_ATOM: {
case PL_STRING: {
char *s = NULL;
PL_get_atom_chars(t, &s);
size_t l;
PL_get_string_chars(t, &s,&l);
if (!context)
context = py_Main;
if (PyObject_SetAttrString(context, s, exp) == 0)
@ -265,7 +243,15 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
PyErr_Print();
return false;
}
case PL_STRING:
case PL_ATOM: {
char *s = NULL;
PL_get_atom_chars(t, &s);
if (!context)
context = py_Main;
if (PyObject_SetAttrString(context, s, exp) == 0)
return true;
return false;
}
case PL_INTEGER:
case PL_FLOAT:
// domain or type erro?

View File

@ -1,7 +1,15 @@
#undef PASS_REGS
#undef USES_REGS
#ifndef PY4YAP_H
#define PY4YAP_H 1
#define PASS_REGS
#define USES_REGS
#include "Yap.h"
//@{
/** @brief Prolog to Python library
@ -17,6 +25,8 @@
#include <Python.h>
#include <Yap.h>
#include <SWI-Prolog.h>
#ifdef HAVE_STAT
#undef HAVE_STATa
@ -35,7 +45,7 @@
PyObject *find_obj(PyObject *ob, term_t lhs, bool eval);
#if DEBUG_MEMORY||1
#if DEBUG_MEMORY || 1
#define DebugPrintf(s, op) fprintf(stderr, "%s:%d: " s, __FILE__, __LINE__, op)
#else
#define DebugPrintf(s, op)
@ -56,15 +66,14 @@ extern X_API PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o,
bool cvt);
extern X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0);
typedef YAP_Arity arity_t;
extern bool init_python_vfs(void);
extern bool init_python_vfs(void);
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
ATOM_comma, ATOM_builtin, ATOM_V, ATOM_A, ATOM_self, ATOM_nil,
ATOM_brackets, ATOM_curly_brackets;
extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1, FUNCTOR_as2,
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
FUNCTOR_as2, FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
FUNCTOR_float1, FUNCTOR_int1, FUNCTOR_iter1, FUNCTOR_iter2, FUNCTOR_long1,
FUNCTOR_len1, FUNCTOR_curly1, FUNCTOR_ord1, FUNCTOR_range1, FUNCTOR_range2,
FUNCTOR_range3, FUNCTOR_sum1, FUNCTOR_pointer1, FUNCTOR_complex2,
@ -73,17 +82,18 @@ extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1, FUNC
FUNCTOR_dot2;
extern X_API PyObject *py_Main;
extern X_API PyObject *py_Builtin;
extern X_API PyObject *py_Yapex;
extern X_API PyObject *py_Local;
extern X_API PyObject *py_Atoms;
extern X_API PyObject *py_Global;
extern X_API PyObject *py_Context;
extern PyObject *Py_f2p;
extern PyObject *py_Sys;
extern PyObject *py_ModDict;
#define py_ModDict PyImport_GetModuleDict()
#define py_Local PyEval_GetLocals()
#define py_Global PyEval_GetGlobals()
#define py_Builtin PyEval_GetBuiltins()
extern X_API bool python_in_python;
extern bool pyStringToString;
extern bool python_release_GIL(term_t gstate);
extern term_t python_acquire_GIL(void);
@ -124,8 +134,13 @@ static inline int proper_ascii_string(const char *s) {
static inline PyObject *atom_to_python_string(term_t t) {
// Yap_DebugPlWrite(YAP_GetFromSlot(t)); fprintf(stderr, " here I
// am\n");
char *s = NULL;
if (!PL_get_atom_chars(t, &s))
const char *s = NULL;
Term yapt = Yap_GetFromSlot(t);
if (IsStringTerm(yapt))
s = StringOfTerm(yapt);
else if (IsAtomTerm(yapt))
s = RepAtom(AtomOfTerm(yapt))->StrOfAE;
else
return NULL;
/* return __main__,s */
#if PY_MAJOR_VERSION < 3
@ -140,11 +155,33 @@ static inline PyObject *atom_to_python_string(term_t t) {
}
}
#define CHECK_CALL(rc, t, call) \
#define CHECK_CALL(ys, pArgs, pyDict) \
PyErr_Clear(); \
rc = call; \
rc = PyObject_Call(ys, pArgs, pyDict); \
if (rc == NULL || PyErr_Occurred()) { \
YE(t, __LINE__, __FILE__, __FUNCTION__); \
YEC(ys, pArgs, pyDict, __LINE__, __FILE__, __FUNCTION__); \
PyErr_Print(); \
PyErr_Clear(); \
}
extern PyObject *YED2(PyObject *f, PyObject *a, PyObject *d, int line, const char *file, const char *code);
static inline PyObject *CALL_BIP2(PyObject *ys,PyObject * pArg1,PyObject * pArg2)
{ PyErr_Clear(); \
PyObject *rc = PyObject_CallFunctionObjArgs(ys, pArg1, pArg2, NULL); \
if (rc == NULL || PyErr_Occurred()) { \
YED2(ys, pArg1, pArg2, __LINE__, __FILE__, __FUNCTION__); \
PyErr_Print(); \
PyErr_Clear(); \
}
return rc;
}
#define CALL_BIP1(ys, pArg1) \
PyErr_Clear(); \
rc = PyObject_CallFunctionObjArgs(ys, pArg1, NULL); \
if (rc == NULL || PyErr_Occurred()) { \
YED1(ys, pArg1, __LINE__, __FILE__, __FUNCTION__); \
PyErr_Print(); \
PyErr_Clear(); \
}
@ -157,7 +194,10 @@ static inline PyObject *atom_to_python_string(term_t t) {
YEM(#rc, __LINE__, __FILE__, __FUNCTION__); \
}
extern PyObject *YE(term_t t, int line, const char *file, const char *code);
extern PyObject *YED1(PyObject *f, PyObject *a, int line, const char *file, const char *code);
extern PyObject *YE(term_t , int line, const char *file, const char *code);
extern PyObject *YEC(PyObject *c,PyObject *a ,PyObject *d , int line, const char *file, const char *code);
extern void YEM(const char *ex, int line, const char *file, const char *code);
extern void pyErrorHandler__(int line, const char *file, const char *code);
@ -202,6 +242,7 @@ X_API extern bool init_python(void);
X_API extern bool loadt_python(void);
X_API extern bool do_init_python(void);
extern PyObject *find_term_obj(PyObject *ob, YAP_Term *yt, bool eval);
extern PyObject PyInit_yap(void);
extern PyObject *PythonLookup(const char *s, PyObject *o);

View File

@ -12,21 +12,29 @@
#include "py4yap.h"
static PyObject *finalLookup(PyObject *i, const char *s) {
PyObject *rc;
PyObject *os = PyUnicode_FromString(s), *rc = NULL;
if (i == NULL)
return NULL;
if (strcmp(s, "none") == 0)
return Py_None;
if (PyDict_Check(i)) {
if ((rc = PyDict_GetItemString(i, s)))
return rc;
}
if (PyModule_Check(i)) {
if ((rc = PyDict_GetItemString(i, s)))
return rc;
i = PyModule_GetDict(i);
}
if (PyDict_Check(i))
{
if (PyDict_Contains(i, os) == 1) {
rc = PyDict_GetItem(i, os);
}
if (PyObject_HasAttrString(i, s)) {
return PyObject_GetAttrString(i, s);
}
if (!rc && PyObject_HasAttr(i, os)) {
rc = PyObject_GetAttr(i, os);
}
if (rc)
{
Py_IncRef(rc);
return rc;
}
return NULL;
}
@ -50,6 +58,10 @@ PyObject *PythonLookupSpecial(const char *s) {
return NULL;
}
static PyObject *builtin(const char *sp) {
return PyDict_GetItemString(py_Builtin, sp);
}
PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) {
PyObject *out = NULL;
if (!sp)
@ -60,16 +72,17 @@ PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) {
if ((out = finalLookup(py_Context, sp))) {
return out;
}
PyObject *py_Builtin = PyEval_GetBuiltins();
if ((out = finalLookup(py_Builtin, sp))) {
return out;
}
PyObject *py_Local = PyEval_GetLocals();
if ((out = finalLookup(py_Atoms, sp)))
{
return out;
}
if ((out = finalLookup(py_Local, sp)) && out != Py_None) {
return out;
}
PyObject *py_Global = PyEval_GetGlobals();
if ((out = finalLookup(py_Global, sp))) {
if ((out = finalLookup(py_Global, sp))) {
return out;
}
if ((out = finalLookup(py_ModDict, sp))) {
@ -113,6 +126,22 @@ find_obj(PyObject *ob, term_t l, bool eval) {
return ob;
}
PyObject *find_term_obj(PyObject *ob, YAP_Term *yt, bool eval) {
YAP_Term hd;
py_Context = NULL;
// Yap_DebugPlWriteln(yt);
while (YAP_IsPairTerm(*yt)) {
hd = YAP_HeadOfTerm(*yt);
*yt = YAP_TailOfTerm(*yt);
ob = yap_to_python(hd, true, ob, false);
if (!ob) {
return Py_None;
}
}
return ob;
}
/**
* Python abs
*
@ -458,7 +487,7 @@ static PyObject *bip_sum(term_t t) {
}
#if PY_MAJOR_VERSION < 3
if (PyInt_CheckExact(item)) {
764PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter);
PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter);
return 0)f_result += (double)PyInt_AS_LONG(item);
PyFPE_END_PROTECT(f_result) Py_DECREF(item);
continue;
@ -596,7 +625,7 @@ static PyObject *structseq_str(PyObject *iobj) {
for (i = 0; i < ((PyStructSequence *)obj)->ob_base.ob_size; i++) {
PyObject *val, *repr;
char *crepr;
const char *crepr;
val = PyStructSequence_GET_ITEM(obj, i);
repr = PyObject_Str(val);
@ -659,7 +688,7 @@ static PyObject *structseq_repr(PyObject *iobj) {
for (i = 0; i < ((PyStructSequence *)obj)->ob_base.ob_size; i++) {
PyObject *val, *repr;
char *crepr;
const char *crepr;
val = PyStructSequence_GET_ITEM(obj, i);
repr = PyObject_Repr(val);
@ -710,19 +739,29 @@ static bool legal_symbol(const char *s) {
}
PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *tuple) {
PyObject *o, *d = NULL;
if (legal_symbol(s)) {
PyTypeObject *typp;
PyObject *key = PyUnicode_FromString(s);
if (Py_f2p && (d = PyList_GetItem(Py_f2p, arity)) &&
PyDict_Contains(d, key)) {
typp = (PyTypeObject *)PyDict_GetItem(d, key);
Py_INCREF(typp);
PyTypeObject *typp;
PyObject *key = PyUnicode_FromString(s), *d;
if (!legal_symbol(s)) {
if (!Py_f2p) {
PyObject *o1;
o1 = PyTuple_New(2);
PyTuple_SET_ITEM(o1, 0, PyUnicode_FromString(s));
PyTuple_SET_ITEM(o1, 1, tuple);
return o1;
}
size_t l = 0;
if ((l = PyList_Size(Py_f2p)) < arity) {
for (; l < arity; l++) {
PyList_Append(Py_f2p, PyDict_New());
}
}
if ((d = PyList_GetItem(Py_f2p, arity - 1)) && PyDict_Contains(d, key)) {
typp = (PyTypeObject *)d;
} else {
typp = calloc(sizeof(PyTypeObject), 1);
PyStructSequence_Desc *desc = calloc(sizeof(PyStructSequence_Desc), 1);
desc->name = PyMem_Malloc(strlen(s) + 1);
strcpy(desc->name, s);
desc->doc = "YAPTerm";
desc->fields = pnull;
desc->n_in_sequence = arity;
@ -736,11 +775,9 @@ PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *tuple) {
// don't do this: we cannot add a type as an atribute.
// PyModule_AddGObject(py_Main, s, (PyObject *)typp);
if (d && !PyDict_Contains(d, key))
PyDict_SetItem(d, key, (PyObject *)typp);
Py_DECREF(key);
Py_INCREF(typp);
PyDict_SetItem(d, key, (PyObject*)typp);
}
o = PyStructSequence_New(typp);
PyObject *o = PyStructSequence_New(typp);
Py_INCREF(typp);
arity_t i;
for (i = 0; i < arity; i++) {
@ -752,14 +789,10 @@ PyObject *term_to_nametuple(const char *s, arity_t arity, PyObject *tuple) {
}
//((PyStructSequence *)o)->ob_base.ob_size = arity;
// PyObject_Print(o,stderr,0);fputc('\n',stderr);
Py_INCREF(o);
return o;
} else {
PyObject *o1;
o1 = PyTuple_New(2);
PyTuple_SET_ITEM(o1, 0, PyUnicode_FromString(s));
PyTuple_SET_ITEM(o1, 1, tuple);
return o1;
}
return NULL;
}
static PyObject *bip_range(term_t t) {
@ -943,6 +976,7 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
AOK(PL_get_arg(1, t, targ), NULL);
ptr = term_to_python(targ, true, NULL, true);
if (!ptr) return NULL;
return PyObject_Dir(ptr);
{}
}
@ -953,19 +987,16 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
if (!PL_get_arg(1, t, targ))
return NULL;
// Yap_DebugPlWriteln(YAP_GetFromSlot(t));
// Yap_DebugPlWriteln(YAP_GetFromSlot(t));
lhs = term_to_python(targ, true, NULL, true);
AOK(PL_get_arg(2, t, targ), NULL);
rhs = term_to_python(targ, true, NULL, true);
Yap_DebugPlWriteln(YAP_GetFromSlot(targ));
if (PySequence_Check(lhs) && PySequence_Check(rhs)) {
if (PySequence_Check(lhs) && PySequence_Check(rhs)) {
return PySequence_Concat(lhs, rhs);
}
if (!PyNumber_Check(lhs))
return NULL;
if (!PyNumber_Check(rhs))
return NULL;
return PyNumber_Add(lhs, rhs);
if (PyNumber_Check(lhs) && PyNumber_Check(rhs))
return PyNumber_Add(lhs, rhs);
return CALL_BIP2(builtin("+"), lhs, rhs);
} else if (fun == FUNCTOR_sub2) {
term_t targ = PL_new_term_ref();
PyObject *lhs, *rhs;
@ -973,19 +1004,18 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
if (!PL_get_arg(1, t, targ))
return NULL;
lhs = term_to_python(targ, true, NULL, true);
if (!PyNumber_Check(lhs))
return NULL;
if (!PL_get_arg(2, t, targ))
return NULL;
rhs = term_to_python(targ, true, NULL, true);
if (!PyNumber_Check(rhs))
return NULL;
return PyNumber_Subtract(lhs, rhs);
if (PyNumber_Check(rhs) && PyNumber_Check(lhs))
return PyNumber_Subtract(lhs, rhs);
return CALL_BIP2(builtin("-"), lhs, rhs);
} else if (fun == FUNCTOR_mul2) {
term_t targ = PL_new_term_ref();
PyObject *lhs, *rhs;
AOK(PL_get_arg(1, t, targ), NULL);
/* YAP_DebugPlWriteln(YAP_GetTermSlot(arg)); */
(lhs = term_to_python(targ, true, NULL, true));
CHECKNULL(targ, lhs);
AOK(PL_get_arg(2, t, targ), NULL);
@ -998,9 +1028,9 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
PyLong_Check(rhs))) {
return PySequence_Repeat(lhs, get_p_int(rhs, 0));
}
if (!PyNumber_Check(lhs) + !PyNumber_Check(rhs))
return NULL;
return PyNumber_Multiply(lhs, rhs);
if (PyNumber_Check(lhs) && PyNumber_Check(rhs))
return PyNumber_Multiply(lhs, rhs);
return PyObject_CallFunctionObjArgs(builtin("*"), lhs, rhs);
}
if (!arity) {
char *s = NULL;
@ -1008,7 +1038,6 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
AOK(PL_get_atom_chars(t, &s), NULL);
PyObject_Print(o, stderr, 0);
pValue = PyObject_GetAttrString(o, s);
PyObject_Print(pValue, stderr, 0);
if (CHECKNULL(t, pValue) == NULL) {
PyErr_Print();
return NULL;
@ -1016,35 +1045,64 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
return pValue;
} else {
char *s = PL_atom_chars(name);
if (!strcmp(s,"t") || !strcmp(s,"tuple")) {
YAP_Term tt = YAP_GetFromSlot(t), tleft;
int i;
PyObject *rc = PyTuple_New(arity);
PyObject *pArg;
for (i=0;i<arity;i++) {
AOK((tleft = YAP_ArgOfTerm(i+1, tt)), NULL);
pArg = yap_to_python(tleft, true, NULL, true);
if (pArg == NULL) {
pArg = Py_None;
}
/* pArg reference stolen here: */
Py_INCREF(pArg);
PyTuple_SetItem(rc, i, pArg);
}
return rc;
}
PyObject *ys = lookupPySymbol(s, o, NULL), *pArgs;
int i;
term_t tleft = PL_new_term_ref();
bool indict = true;
PyObject *pyDict = PyDict_New();
pArgs = Py_None;
for (i = arity; i > 0; i--) {
PyObject *pArg;
AOK(PL_get_arg(i, t, tleft), NULL);
/* ignore (_) */
if (indict) {
if (PL_get_functor(tleft, &fun) && fun == FUNCTOR_equal2) {
term_t tatt = PL_new_term_ref();
AOK(PL_get_arg(1, tleft, tatt), NULL);
PyObject *key = term_to_python(tatt, true, NULL, true);
AOK(PL_get_arg(2, tleft, tatt), NULL);
PyObject *val = term_to_python(tatt, true, NULL, true);
Term tatt = ArgOfTerm(1,Yap_GetFromSlot(tleft));
const char *sk;
if (IsAtomTerm(tatt))
sk = RepAtom(AtomOfTerm(tatt))->StrOfAE;
else if (IsStringTerm(tatt))
sk = StringOfTerm(tatt);
else
return NULL;
PyObject *key = PyUnicode_FromString(sk);
AOK(PL_get_arg(2, tleft, tleft), NULL);
PyObject *val = term_to_python(tleft, true, o, cvt);
if (val == NULL)
return NULL;
PyDict_SetItem(pyDict, key, val);
} else {
indict = false;
pArgs = PyTuple_New(i);
pArgs = PyTuple_New(i);
}
}
fprintf(stderr,"Tuple %p: %s\n", pyDict, PyUnicode_AsUTF8(PyObject_Str(pyDict)));
if (!indict) {
// fprintf(stderr, "Tuple %p: %s\n", pyDict,
// PyUnicode_AsUTF8(PyObject_Str(pyDict)));
if (!indict) {
if (PL_is_variable(tleft)) {
pArg = Py_None;
} else {
pArg = term_to_python(tleft, true, NULL, true);
pArg = term_to_python(tleft, true, o, cvt);
// PyObject_Print(pArg,fdopen(2,"w"),0);
if (pArg == NULL) {
pArg = Py_None;
@ -1057,23 +1115,23 @@ PyObject *compound_to_pyeval(term_t t, PyObject *context, bool cvt) {
}
}
if (indict) {
if (pArgs == Py_None) {
pArgs = PyTuple_New(0);
}
PyObject *rc;
if (ys && PyCallable_Check(ys)) {
PyObject_Print(ys, stderr, 0);
PyObject_Print(pArgs, stderr, 0);
PyObject_Print(pyDict, stderr, 0);
if ( PyCallable_Check(ys)) {
//PyObject_Print(ys, stderr, 0);
// PyObject_Print(pArgs, stderr, 0);
// PyObject_Print(pyDict, stderr, 0);
// PyObject_Print(pArgs, stderr, 0);
// PyObject_Print(o, stderr, 0);
CHECK_CALL(rc, t, PyObject_Call(ys, pArgs, pyDict));
CHECK_CALL(ys, pArgs, pyDict);
Py_DECREF(pArgs);
Py_DECREF(ys);
PyObject_Print(rc, stderr, 0);
DebugPrintf("CallObject %p\n", rc);
// PyObject_Print(rc, stderr, 0);
// DebugPrintf("CallObject %p\n", rc);
} else {
rc = term_to_nametuple(s, arity, pArgs);
}

View File

@ -8,7 +8,6 @@
YAP_Term TermErrStream, TermOutStream;
static void pyflush(StreamDesc *st) {
#if 0
st->u.w_irl.ptr[0] = '\0';
@ -75,8 +74,7 @@ static void *py_open(VFS_t *me, const char *name, const char *io_mode,
}
StreamDesc *st = YAP_RepStreamFromId(sno);
st->name = YAP_LookupAtom(name);
if (strcmp(name, "sys.stdout") == 0 ||
strcmp(name, "sys.stderr") == 0 ||
if (strcmp(name, "sys.stdout") == 0 || strcmp(name, "sys.stderr") == 0 ||
strcmp(name, "input") == 0) {
st->status |= Tty_Stream_f;
}
@ -129,24 +127,40 @@ static bool py_close(int sno) {
return true;
}
static bool getLine(StreamDesc *rl_iostream, int sno) {
char *myrl_line = NULL;
term_t ctk = python_acquire_GIL();
/* window of vulnerability opened */
myrl_line = PyUnicode_AsUTF8(PyObject_CallFunctionObjArgs(rl_iostream->u.private_data, NULL));
python_release_GIL(ctk);
PyObject *err;
if ((err = PyErr_Occurred())) {
PyErr_SetString(
err,
"Error in getLine\n");
static bool pygetLine(StreamDesc *rl_iostream, int sno) {
// term_t ctk = python_acquire_GIL();
const char *myrl_line;
PyObject *user_line;
StreamDesc *s = YAP_GetStreamFromId(sno);
//term_t tg = python_acquire_GIL();
if (!strcmp(RepAtom(s->name)->StrOfAE,"input") ) {
// note that input may change
PyObject *pystream = PyDict_GetItemString( py_Builtin, "input");
if (pystream == NULL) {
PyObject *err;
if ((err = PyErr_Occurred())) {
PyErr_Print();
Yap_ThrowError(SYSTEM_ERROR_GET_FAILED, YAP_MkIntTerm(sno), err);
}
size_t size = strlen (myrl_line)+1;
rl_iostream->u.irl.ptr = rl_iostream->u.irl.buf =
(const unsigned char *)malloc(size);
memmove((void *)rl_iostream->u.irl.buf, myrl_line, size);
}
user_line = PyObject_CallFunctionObjArgs(pystream, PyUnicode_FromString("?- ") , NULL);
} else {
PyObject *readl = PyObject_GetAttrString(s->u.private_data, "readline");
user_line = PyObject_CallFunction(readl, "?- ");
}
myrl_line = PyUnicode_AsUTF8(user_line);
if (myrl_line == NULL)
return NULL;
PyObject *err;
if ((err = PyErr_Occurred())) {
if (PyErr_GivenExceptionMatches(err, PyExc_EOFError))
return NULL;
PyErr_SetString(err, "Error in getLine\n");
Yap_ThrowError(SYSTEM_ERROR_GET_FAILED, YAP_MkIntTerm(sno), err);
}
rl_iostream->u.irl.ptr = rl_iostream->u.irl.buf = (unsigned char *)myrl_line;
return true;
}
@ -156,16 +170,14 @@ static int py_getc(int sno) {
bool fetch = (s->u.irl.buf == NULL);
if (fetch) {
if (!getLine(s, sno)) {
if (!pygetLine(s, sno)) {
return EOF;
}
}
const unsigned char *ttyptr = s->u.irl.ptr++, *myrl_line = s->u.irl.buf;
const unsigned char *ttyptr = s->u.irl.ptr++;
ch = *ttyptr;
if (ch == '\0') {
ch = '\n';
free((void *)myrl_line);
s->u.irl.ptr = s->u.irl.buf = NULL;
ch = 10;
}
return ch;
}
@ -190,7 +202,7 @@ static int py_peek(int sno) {
}
return ch;
}
if (getLine(s, sno)) {
if (pygetLine(s, sno)) {
ch = s->u.irl.ptr[0];
if (ch == '\0') {
ch = '\n';

View File

@ -1,16 +1,19 @@
#include "Yap.h"
#include "py4yap.h"
PyObject *py_Main;
void pyErrorHandler__(int line, const char *file, const char *code) {
// this code is called if a Python error is found.
//int lvl = push_text_stack();
PyObject *type, *val;
// int lvl = push_text_stack();
// PyErr_Fetch(&type, &val, NULL);
// PyErr_Print();
// Yap_ThrowError__(file,code,line,0, SYSTEM_ERROR_RUNTIME_PYTHON ,"Python Error %s: %s",PyUnicode_AsUTF8(PyObject_Str(type)), PyUnicode_AsUTF8(PyObject_Str(val)));
};
// Yap_ThrowError__(file,code,line,0, SYSTEM_ERROR_RUNTIME_PYTHON ,"Python
// Error %s: %s",PyUnicode_AsUTF8(PyObject_Str(type)),
// PyUnicode_AsUTF8(PyObject_Str(val)));
};
static foreign_t python_len(term_t tobj, term_t tf) {
Py_ssize_t len;
@ -23,6 +26,10 @@ static foreign_t python_len(term_t tobj, term_t tf) {
len = PyObject_Length(o);
pyErrorAndReturn(PL_unify_int64(tf, len));
}
static foreign_t python_clear_errors(void) {
PyErr_Clear();
return true;
}
static foreign_t python_dir(term_t tobj, term_t tf) {
PyObject *dir;
@ -108,7 +115,9 @@ static foreign_t python_slice(term_t parent, term_t indx, term_t tobj) {
p = term_to_python(parent, true, NULL, true);
// Exp
if (!pI || !p) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
} else if ((pF = PySequence_GetSlice(p, 0, 0)) == NULL) {
PyErr_Print();
{ pyErrorAndReturn(false); }
@ -136,14 +145,18 @@ static foreign_t python_apply(term_t tin, term_t targs, term_t keywds,
pF = term_to_python(tin, true, NULL, true);
PyErr_Clear();
if (pF == NULL) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
}
if (PL_is_atom(targs)) {
pArgs = NULL;
} else {
if (!PL_get_name_arity(targs, &aname, &arity)) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
}
if (arity == 1 && PL_get_arg(1, targs, targ) && PL_is_variable(targ)) {
/* ignore (_) */
@ -217,6 +230,25 @@ static foreign_t assign_python(term_t exp, term_t name) {
pyErrorAndReturn(b);
}
static foreign_t python_string_to(term_t f) {
if (PL_is_atom(f)) {
char *s = NULL;
if (!PL_get_chars(f, &s, CVT_ATOM |CVT_STRING | CVT_EXCEPTION | REP_UTF8)) {
pyErrorAndReturn(false);
}
if (!strcmp(s,"atom")) {
pyStringToString = false;
return true;
}
if (!strcmp(s,"string")) {
pyStringToString = true;
return true;
}
}
return false;
}
static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) {
PyErr_Clear();
PyObject *pI, *pArgs, *pOut;
@ -270,7 +302,7 @@ static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) {
Py_DECREF(pI);
if (pOut == NULL) {
PyErr_Print();
{ pyErrorAndReturn(false); }
{ pyErrorAndReturn(false); }
}
{
foreign_t rc = address_to_term(pOut, out);
@ -299,10 +331,12 @@ static foreign_t python_access(term_t obj, term_t f, term_t out) {
{ pyErrorAndReturn(false); }
}
Py_INCREF(pValue);
{ pyErrorAndReturn(python_to_term(pValue, out) ); }
{ pyErrorAndReturn(python_to_term(pValue, out)); }
}
if (!PL_get_name_arity(f, &name, &arity)) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
}
s = PL_atom_chars(name);
if (!s) {
@ -335,7 +369,9 @@ static foreign_t python_access(term_t obj, term_t f, term_t out) {
Py_DECREF(pArgs);
Py_DECREF(pF);
if (pValue == NULL) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
}
{ pyErrorAndReturn(python_to_term(pValue, out)); }
}
@ -347,7 +383,9 @@ static foreign_t python_field(term_t parent, term_t att, term_t tobj) {
int arity;
if (!PL_get_name_arity(att, &name, &arity)) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
} else {
PyObject *p;
@ -356,7 +394,9 @@ static foreign_t python_field(term_t parent, term_t att, term_t tobj) {
p = term_to_python(parent, true, NULL, true);
// Exp
if (!PL_get_name_arity(att, &name, &arity)) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
}
s = PL_atom_chars(name);
if (arity == 1 && !strcmp(s, "()")) {
@ -364,12 +404,16 @@ static foreign_t python_field(term_t parent, term_t att, term_t tobj) {
pyErrorAndReturn(false);
}
if (!PL_get_name_arity(att, &name, &arity)) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
}
s = PL_atom_chars(name);
}
if (!s || !p) {
{ pyErrorAndReturn(false); }
{
pyErrorAndReturn(false);
}
} else if ((pF = PyObject_GetAttrString(p, s)) == NULL) {
PyErr_Clear();
{ pyErrorAndReturn(false); }
@ -539,35 +583,45 @@ static int python_import(term_t mname, term_t mod) {
PyObject *pName;
bool do_as = false;
term_t arg = PL_new_term_ref();
char s0[MAXPATHLEN], *s = s0, *t;
functor_t f;
while (true) {
size_t len;
//PyErr_Clear();
len = (MAXPATHLEN - 1) - (s - s0);
if (PL_is_pair(mname)) {
char *sa = NULL;
if (!PL_get_arg(1, mname, arg) || !PL_get_chars(arg, &sa, CVT_ALL | CVT_EXCEPTION | REP_UTF8) ||
!PL_get_arg(2, mname, mname)) {
pyErrorAndReturn(false);
}
PL_get_chars(arg, &sa, CVT_ALL | CVT_EXCEPTION | REP_UTF8);
strcpy(s, sa);
s += strlen(s);
*s++ = '.';
s[0] = '\0';
} else if (PL_get_functor(mname, &f) && f == FUNCTOR_as2 && PL_get_arg(2, mname,arg) &&
PL_get_chars(arg, &t, CVT_ALL | CVT_EXCEPTION | REP_UTF8)) {
do_as = true;
PL_get_arg(1, mname,mname);
} else if (!PL_get_nchars(mname, &len, &s,
CVT_ALL | CVT_EXCEPTION | REP_UTF8)) {
pyErrorAndReturn(false);
} else {
break;
}
char s0[MAXPATHLEN], *s = s0;
s[0] = '\0';
const char *sn, *as = NULL;
Term t = Deref(ARG1), sm;
if (IsApplTerm(t)) {
Functor f = (Functor)*RepAppl(t);
if (f != FunctorAs)
return false;
do_as = true;
sm = ArgOfTerm(2, t);
if (IsAtomTerm(sm))
as = RepAtom(AtomOfTerm(sm))->StrOfAE;
else if (IsStringTerm(sm))
as = StringOfTerm(sm);
else
return false;
t = ArgOfTerm(1, t);
}
while (IsPairTerm(t)) {
Term ti = HeadOfTerm(t);
t = TailOfTerm(t);
if (IsAtomTerm(ti))
sn = RepAtom(AtomOfTerm(ti))->StrOfAE;
else if (IsStringTerm(ti))
sn = StringOfTerm(ti);
else
return false;
strcat(s, sn);
//get_mod(s);
strcat(s, ".");
}
sm = t;
if (IsAtomTerm(sm))
sn = RepAtom(AtomOfTerm(sm))->StrOfAE;
else if (IsStringTerm(sm))
sn = StringOfTerm(sm);
else
return false;
strcat(s, sn);
term_t t0 = python_acquire_GIL();
#if PY_MAJOR_VERSION < 3
pName = PyString_FromString(s0);
@ -583,16 +637,17 @@ static int python_import(term_t mname, term_t mod) {
Py_XDECREF(pName);
if (pModule == NULL) {
python_release_GIL(t0);
python_release_GIL(t0);
pyErrorAndReturn(false);
}
{
foreign_t rc = address_to_term(pModule, mod);
if (do_as && PyObject_SetAttrString(py_Main, t, pModule) <0)
return false;
python_release_GIL(t0);
if (do_as) {
PyModule_AddObject(py_Main, as, pModule);
}
python_release_GIL(t0);
pyErrorAndReturn(rc);
}
}
@ -658,26 +713,25 @@ term_t python_acquire_GIL(void) {
}
bool python_release_GIL(term_t curBlock) {
int gstateix;
gstatei--;
PL_get_integer(curBlock, &gstateix);
PL_reset_term_refs(curBlock);
if (gstatei != gstateix) {
if (gstateix > gstatei) {
fprintf(stderr, "gstateix(%d) > gstatei(%d)\n", gstateix, gstatei);
return false;
} else {
fprintf(stderr, "gstateix(%d) < gstatei(%d)\n", gstateix, gstatei);
return false;
}
int gstateix;
gstatei--;
PL_get_integer(curBlock, &gstateix);
PL_reset_term_refs(curBlock);
if (gstatei != gstateix) {
if (gstateix > gstatei) {
fprintf(stderr, "gstateix(%d) > gstatei(%d)\n", gstateix, gstatei);
return false;
} else {
fprintf(stderr, "gstateix(%d) < gstatei(%d)\n", gstateix, gstatei);
return false;
}
if (_threaded) {
}
if (_threaded) {
PyGILState_Release(gstates[gstatei]);
}
pyErrorAndReturn(true);
}
install_t install_pypreds(void) {
PL_register_foreign("python_builtin_eval", 3, python_builtin_eval, 0);
PL_register_foreign("python_builtin", 1, python_builtin, 0);
@ -701,6 +755,8 @@ install_t install_pypreds(void) {
PL_register_foreign("python_import", 2, python_import, 0);
PL_register_foreign("python_access", 3, python_access, 0);
PL_register_foreign("python_threaded", 0, p_python_threaded, 0);
PL_register_foreign("python_clear_errors", 0, python_clear_errors, 0);
PL_register_foreign("python_string_to", 1, python_string_to, 0);
init_python_vfs();
}

View File

@ -3,6 +3,8 @@
#include "py4yap.h"
#include <VFS.h>
#define USES_REGS
#include "YapStreams.h"
atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
@ -19,33 +21,33 @@ functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1, FUNCTOR_as2
FUNCTOR_dot2, FUNCTOR_brackets1;
X_API PyObject *py_Atoms;
X_API PyObject *py_Builtin;
X_API PyObject *py_Yapex;
X_API PyObject *py_Sys;
X_API PyObject * pYAPError;
PyObject *py_Context;
PyObject *py_ModDict;
X_API PyObject *Py_f2p;
bool pyStringToString;
extern X_API bool python_in_python;
static void add_modules(void) {
py_Main = PyImport_AddModule("__main__");
py_Atoms= PyDict_New();
if ( PyDict_Contains(PyImport_GetModuleDict(), PyUnicode_FromString("__main__"))) {
py_Main = PyDict_GetItemString(PyImport_GetModuleDict(),"__main__");
} else {
py_Main = PyImport_ImportModule("__main__");
}
Py_INCREF(py_Main);
py_Sys = PyImport_AddModule("sys");
py_Atoms = PyDict_New();
Py_INCREF(py_Sys);
py_Builtin = PyImport_AddModule("__builtin__");
Py_INCREF(py_Builtin);
py_ModDict = PyObject_GetAttrString(py_Sys, "modules");
// py_Yapex = PyImport_ImportModule("yap4py.yapi");
// PyObject *py_Yap =
py_Yapex = PyImport_AddModule("yap4py.yapi");
py_Yapex = PyImport_ImportModule("yap4py.yapi");
if (py_Yapex)
Py_INCREF(py_Yapex);
Py_f2p = PythonLookup("f2p", NULL);
if (Py_f2p)
Py_INCREF(Py_f2p);
if (!Py_f2p)
Py_f2p = PyDict_New();
Py_INCREF(Py_f2p);
init_python_vfs();
}
@ -115,7 +117,7 @@ X_API bool do_init_python(void) {
// PyGILState_STATE gstate = PyGILState_Ensure();
term_t t = PL_new_term_ref();
if (!python_in_python)
if (!Py_IsInitialized())
Py_Initialize();
install_py_constants();
PL_reset_term_refs(t);

View File

@ -28,10 +28,12 @@
array_to_python_tuple/4,
array_to_python_view/5,
python/2,
python_string_to/1,
acquire_GIL/0,
release_GIL/0,
python_threaded/0,
prolog_list_to_python_list/3,
python_clear_errors/0,
op(100,fy,$),
op(950,fy,:=),
op(950,yfx,:=),
@ -116,7 +118,7 @@ Data types are
user:(:=)/1,
% user:(<-)/1,
% user:(<-)/2,
user:'()'/1, user:'{}'/1, user:dot_qualified_goal/2, user:import_arg/1.
user:'()'/1, user:'{}'/1, user:dot_qualified_goal/1, user:import_arg/1.
import( F ) :- catch( python:python_import(F), _, fail ).

View File

@ -54,8 +54,7 @@ endif()
COMMAND ${SWIG_EXECUTABLE} -c++ -python -O -py3 -module "yap" -addextern -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/H/generated -I${CMAKE_SOURCE_DIR}/include
-I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/utf8proc -I.././.. -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/packages/python
-outdir ${CMAKE_CURRENT_BINARY_DIR}/yap4py -I${GMP_INCLUDE_DIRS} -DX_API="" -o ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.cxx -oh ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.hh ${SWIG_SOURCES}
COMMAND ${PYTHON_EXECUTABLE} setup.py sdist ${bdist}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${SWIG_SOURCES} Py4YAP YAP++ yap4py/yapi.cpp YAP4PY_PY
)
@ -70,7 +69,9 @@ endif()
DEPENDS ${PYTHON_SOURCES}
)
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed .
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} setup.py sdist ${bdist}
COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed .
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})"
DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${YAP_INSTALL_DLLDIR} )

View File

@ -3,20 +3,20 @@
%% @brief support yap shell
%%
%:- start_low_level_trace.
:- module(yapi, [
python_ouput/0,
show_answer/2,
show_answer/3,
yap_query/4,
python_query/2,
python_query/3,
python_import/1,
yapi_query/2
]).
%% :- module(yapi, [
%% python_ouput/0,
%% show_answer/2,
%% show_answer/3,
%% yap_query/4,
%% python_query/2,
%% python_query/3,
%% python_import/1,
%% yapi_query/2
%% ]).
:- yap_flag(verbose, silent).
:- use_module(library(python)).
:- use_module(library(python)).
:- use_module( library(lists) ).
:- use_module( library(maplist) ).
@ -71,20 +71,20 @@ argi(N,I,I1) :-
python_query( Caller, String ) :-
atomic_to_term( String, Goal, VarNames ),
query_to_answer( Goal, VarNames, Status, Bindings),
atom_to_string( Status, SStatus ),
Caller.port := SStatus,
Caller.port := Status,
write_query_answer( Bindings ),
nl(user_error),
Caller.answer := {},
maplist(in_dict(Caller.answer), Bindings).
maplist(in_dict(Caller.answer), Bindings).
in_dict(Dict, var([V0,V|Vs])) :- !,
Dict[V] := V0,
in_dict( Dict, var([V0|Vs])).
in_dict(_Dict, var([_],_G)) :- !.
in_dict(Dict, nonvar([V0|Vs],G)) :- !,
Dict[V0] := G,
term_to_atom(G,A,_),
Dict[V0] := A,
in_dict( Dict, nonvar(Vs, G) ).
in_dict(_Dict, nonvar([],_G)) :- !.
in_dict(_, _)

View File

@ -84,10 +84,11 @@ native_sources = ["yap4py/yap_wrap.cxx","yap4py/yapi.cpp"]
extensions = [Extension('_yap', native_sources,
define_macros=[('MAJOR_VERSION', '1'),
('MINOR_VERSION', '0'),
define_macros=[('MAJOR_VERSION', '@YAP_MAJOR_VERSION@'),
('MINOR_VERSION', '@YAP_MINOR_VERSION@'),
('_YAP_NOT_INSTALLED_', '1'),
('YAP_PYTHON', '1'),
('PYTHONSWIG', '1'),
('_GNU_SOURCE', '1')],
runtime_library_dirs=[
abspath(join(sysconfig.get_path('platlib'),'yap4py')), abspath(sysconfig.get_path('platlib')),'${CMAKE_INSTALL_FULL_LIBDIR}'],
@ -103,7 +104,7 @@ extensions = [Extension('_yap', native_sources,
'${CMAKE_SOURCE_DIR}/os',
'${CMAKE_SOURCE_DIR}/utf8proc',
'${CMAKE_SOURCE_DIR}/packages/python',
'../../..',
'${CMAKE_BINARY_DIR}',
'${CMAKE_SOURCE_DIR}/CXX' ]
)]
@ -114,7 +115,7 @@ package_data = {
data_files=[]
version_ns = {'__version__': '6.3.5', 'minor-version': '6', 'minor-version': '3', 'patch': '5'}
version_ns = {'__version__': '${YAP_MAJOR_VERSION}.${YAP_MINOR_VERSION}.${YAP_PATCH_VERSION}', 'major-version': '${YAP_MAJOR_VERSION}', 'minor-version': '${YAP_MINOR_VERSION}', 'patch': '${YAP_PATCH_VERSION}'}
setup_args = dict(
name=name,

View File

@ -6,16 +6,17 @@ import sys
yap_lib_path = dirname(__file__)
compile = namedtuple('compile', 'file')
bindvars = namedtuple('bindvars', 'list')
library = namedtuple('library', 'list')
compile = namedtuple('compile', 'file')
jupyter_query = namedtuple('jupyter_query', 'vars dict')
library = namedtuple('library', 'listfiles')
prolog_library = namedtuple('prolog_library', 'listfiles')
python_query = namedtuple('python_query', 'vars dict')
set_prolog_flag = namedtuple('set_prolog_flag', 'flag new_value')
show_answer = namedtuple('show_answer', 'vars dict')
v0 = namedtuple('v', 'slot')
yap_query = namedtuple('yap_query', 'query owner')
jupyter_query = namedtuple('jupyter_query', 'vars dict')
python_query = namedtuple('python_query', 'vars dict')
yapi_query = namedtuple('yapi_query', 'vars dict')
show_answer = namedtuple('show_answer', 'vars dict')
set_prolog_flag = namedtuple('set_prolog_flag', 'flag new_value')
class Engine( YAPEngine ):
@ -24,23 +25,25 @@ class Engine( YAPEngine ):
# type: (object) -> object
if not args:
args = EngineArgs(**kwargs)
args.setEmbedded(True)
if self_contained:
yap_lib_path = dirname(__file__)
args.setYapShareDir(join(yap_lib_path, "prolog"))
args.setYapPLDIR(yap_lib_path)
args.setSavedState(join(yap_lib_path, "startup.yss"))
YAPEngine.__init__(self, args)
self.goal(set_prolog_flag('verbose', 'silent'),True)
self.goal(compile(library('yapi')), True)
self.goal(set_prolog_flag('verbose', 'normal'), True)
self.run(compile(library('yapi')),m="user",release=True)
def run(self, g, m=None, release=False):
if m:
self.mgoal(g, m, release)
else:
self.goal(release)
self.goal(g, release)
def prolog_library(self, file):
g = prolog_library(file)
self.run(g)
class JupyterEngine( Engine ):
def __init__(self, args=None,self_contained=False,**kwargs):
@ -49,9 +52,13 @@ class JupyterEngine( Engine ):
args = EngineArgs(**kwargs)
args.jupyter = True
Engine.__init__(self, args)
self.goal(set_prolog_flag('verbose', 'silent'),True)
self.goal(compile(library('jupyter')), True)
self.goal(set_prolog_flag('verbose', 'normal'), True)
self.errors = None
try:
self.run(compile(library('jupyter')),"user")
self.run(compile(library('complete')),"user")
self.run(compile(library('verify')),"user")
except:
pass
class EngineArgs( YAPEngineArgs ):
""" Interface to Engine Options class"""

View File

@ -1,271 +1,378 @@
set (PYTHON_SOURCES backcall.py yap_kernel_launcher.py docs/conf.py
yap_kernel/codeutil.py yap_kernel/comm yap_kernel/connect.py
yap_kernel/datapub.py yap_kernel/displayhook.py
yap_kernel/embed.py yap_kernel/_eventloop_macos.py
yap_kernel/eventloops.py yap_kernel/gui yap_kernel/heartbeat.py
yap_kernel/__init__.py yap_kernel/inprocess
yap_kernel/iostream.py yap_kernel/ipkernel.py
yap_kernel/jsonutil.py yap_kernel/kernelapp.py
yap_kernel/kernelbase.py yap_kernel/kernelspec.py
yap_kernel/log.py yap_kernel/__main__.py
yap_kernel/parentpoller.py yap_kernel/pickleutil.py
yap_kernel/pylab yap_kernel/serialize.py yap_kernel/tests
yap_kernel/_version.py yap_kernel/zmqshell.py
yap_ipython/config.py yap_ipython/consoleapp.py yap_ipython/core
yap_ipython/display.py yap_ipython/extensions
yap_ipython/external yap_ipython/frontend.py yap_ipython/html.py
yap_ipython/__init__.py yap_ipython/kernel yap_ipython/lib
yap_ipython/__main__.py yap_ipython/nbconvert.py
yap_ipython/nbformat.py yap_ipython/parallel.py
yap_ipython/paths.py yap_ipython/prolog yap_ipython/qt.py
yap_ipython/sphinxext yap_ipython/terminal yap_ipython/testing
yap_ipython/utils yap_ipython/yapi.py yap_kernel/comm/comm.py
yap_kernel/comm/__init__.py yap_kernel/comm/manager.py
yap_kernel/gui/gtk3embed.py yap_kernel/gui/gtkembed.py
yap_kernel/gui/__init__.py yap_kernel/inprocess/blocking.py
yap_kernel/inprocess/channels.py yap_kernel/inprocess/client.py
yap_kernel/inprocess/constants.py
yap_kernel/inprocess/__init__.py
yap_kernel/inprocess/ipkernel.py yap_kernel/inprocess/manager.py
yap_kernel/inprocess/socket.py yap_kernel/inprocess/tests
yap_kernel/pylab/backend_inline.py yap_kernel/pylab/config.py
yap_kernel/pylab/__init__.py yap_kernel/tests/_asyncio.py
yap_kernel/tests/__init__.py yap_kernel/tests/test_connect.py
yap_kernel/tests/test_embed_kernel.py
yap_kernel/tests/test_eventloop.py yap_kernel/tests/test_io.py
yap_kernel/tests/test_jsonutil.py
yap_kernel/tests/test_kernel.py
yap_kernel/tests/test_kernelspec.py
yap_kernel/tests/test_message_spec.py
yap_kernel/tests/test_pickleutil.py
yap_kernel/tests/test_serialize.py
yap_kernel/tests/test_start_kernel.py
yap_kernel/tests/test_zmq_shell.py yap_kernel/tests/utils.py
yap_ipython/core/alias.py yap_ipython/core/application.py
yap_ipython/core/autocall.py yap_ipython/core/builtin_trap.py
yap_ipython/core/compilerop.py yap_ipython/core/completerlib.py
yap_ipython/core/completer.py yap_ipython/core/crashhandler.py
yap_ipython/core/debugger.py yap_ipython/core/displayhook.py
yap_ipython/core/displaypub.py yap_ipython/core/display.py
yap_ipython/core/display_trap.py yap_ipython/core/error.py
yap_ipython/core/events.py yap_ipython/core/excolors.py
yap_ipython/core/extensions.py yap_ipython/core/formatters.py
yap_ipython/core/getipython.py yap_ipython/core/historyapp.py
yap_ipython/core/history.py yap_ipython/core/hooks.py
yap_ipython/core/__init__.py yap_ipython/core/inputsplitter.py
yap_ipython/core/inputtransformer.py
yap_ipython/core/interactiveshell.py
yap_ipython/core/latex_symbols.py yap_ipython/core/logger.py
yap_ipython/core/macro.py yap_ipython/core/magic_arguments.py
yap_ipython/core/magic.py yap_ipython/core/magics
yap_ipython/core/oinspect.py yap_ipython/core/page.py
yap_ipython/core/payloadpage.py yap_ipython/core/payload.py
yap_ipython/core/prefilter.py yap_ipython/core/profileapp.py
yap_ipython/core/profiledir.py yap_ipython/core/prompts.py
yap_ipython/core/pylabtools.py yap_ipython/core/release.py
yap_ipython/core/shellapp.py yap_ipython/core/splitinput.py
yap_ipython/core/tests yap_ipython/core/ultratb.py
yap_ipython/core/usage.py yap_ipython/extensions/autoreload.py
yap_ipython/extensions/cythonmagic.py
yap_ipython/extensions/__init__.py
yap_ipython/extensions/rmagic.py
yap_ipython/extensions/storemagic.py
yap_ipython/extensions/sympyprinting.py
yap_ipython/extensions/tests yap_ipython/external/decorators
yap_ipython/external/__init__.py yap_ipython/external/mathjax.py
yap_ipython/external/qt_for_kernel.py
yap_ipython/external/qt_loaders.py yap_ipython/kernel/adapter.py
yap_ipython/kernel/channelsabc.py yap_ipython/kernel/channels.py
yap_ipython/kernel/clientabc.py yap_ipython/kernel/client.py
yap_ipython/kernel/connect.py yap_ipython/kernel/__init__.py
yap_ipython/kernel/kernelspecapp.py
yap_ipython/kernel/kernelspec.py yap_ipython/kernel/launcher.py
yap_ipython/kernel/__main__.py yap_ipython/kernel/managerabc.py
yap_ipython/kernel/manager.py
yap_ipython/kernel/multikernelmanager.py
yap_ipython/kernel/restarter.py yap_ipython/kernel/threaded.py
yap_ipython/lib/backgroundjobs.py yap_ipython/lib/clipboard.py
yap_ipython/lib/deepreload.py yap_ipython/lib/demo.py
yap_ipython/lib/display.py yap_ipython/lib/editorhooks.py
yap_ipython/lib/guisupport.py yap_ipython/lib/__init__.py
yap_ipython/lib/inputhookglut.py
yap_ipython/lib/inputhookgtk3.py yap_ipython/lib/inputhookgtk.py
yap_ipython/lib/inputhook.py yap_ipython/lib/inputhookpyglet.py
yap_ipython/lib/inputhookqt4.py yap_ipython/lib/inputhookwx.py
yap_ipython/lib/kernel.py yap_ipython/lib/latextools.py
yap_ipython/lib/lexers.py yap_ipython/lib/pretty.py
yap_ipython/lib/security.py yap_ipython/lib/tests
yap_ipython/prolog/jupyter.yap
yap_ipython/sphinxext/custom_doctests.py
yap_ipython/sphinxext/__init__.py
yap_ipython/sphinxext/ipython_console_highlighting.py
yap_ipython/sphinxext/ipython_directive.py
yap_ipython/terminal/console.py yap_ipython/terminal/debugger.py
yap_ipython/terminal/embed.py yap_ipython/terminal/__init__.py
yap_ipython/terminal/interactiveshell.py
yap_ipython/terminal/ipapp.py yap_ipython/terminal/magics.py
yap_ipython/terminal/prompts.py
yap_ipython/terminal/pt_inputhooks
yap_ipython/terminal/ptshell.py yap_ipython/terminal/ptutils.py
yap_ipython/terminal/shortcuts.py yap_ipython/terminal/tests
yap_ipython/testing/decorators.py
yap_ipython/testing/globalipapp.py
yap_ipython/testing/__init__.py
yap_ipython/testing/iptestcontroller.py
yap_ipython/testing/iptest.py yap_ipython/testing/ipunittest.py
yap_ipython/testing/__main__.py yap_ipython/testing/plugin
yap_ipython/testing/skipdoctest.py yap_ipython/testing/tests
yap_ipython/testing/tools.py yap_ipython/utils/capture.py
yap_ipython/utils/colorable.py yap_ipython/utils/coloransi.py
yap_ipython/utils/contexts.py yap_ipython/utils/daemonize.py
yap_ipython/utils/data.py yap_ipython/utils/decorators.py
yap_ipython/utils/dir2.py yap_ipython/utils/encoding.py
yap_ipython/utils/eventful.py yap_ipython/utils/frame.py
yap_ipython/utils/generics.py yap_ipython/utils/importstring.py
yap_ipython/utils/__init__.py yap_ipython/utils/io.py
yap_ipython/utils/ipstruct.py yap_ipython/utils/jsonutil.py
yap_ipython/utils/localinterfaces.py yap_ipython/utils/log.py
yap_ipython/utils/module_paths.py yap_ipython/utils/openpy.py
yap_ipython/utils/path.py yap_ipython/utils/pickleutil.py
yap_ipython/utils/_process_cli.py
yap_ipython/utils/_process_common.py
yap_ipython/utils/_process_posix.py yap_ipython/utils/process.py
yap_ipython/utils/_process_win32_controller.py
yap_ipython/utils/_process_win32.py
yap_ipython/utils/py3compat.py yap_ipython/utils/PyColorize.py
yap_ipython/utils/sentinel.py yap_ipython/utils/shimmodule.py
yap_ipython/utils/signatures.py yap_ipython/utils/strdispatch.py
yap_ipython/utils/_sysinfo.py yap_ipython/utils/sysinfo.py
yap_ipython/utils/syspathcontext.py yap_ipython/utils/tempdir.py
yap_ipython/utils/terminal.py yap_ipython/utils/tests
yap_ipython/utils/text.py yap_ipython/utils/timing.py
yap_ipython/utils/tokenize2.py yap_ipython/utils/tokenutil.py
yap_ipython/utils/traitlets.py yap_ipython/utils/tz.py
yap_ipython/utils/ulinecache.py yap_ipython/utils/version.py
yap_ipython/utils/wildcard.py
yap_kernel/inprocess/tests/__init__.py
yap_kernel/inprocess/tests/test_kernelmanager.py
yap_kernel/inprocess/tests/test_kernel.py
yap_ipython/core/magics/auto.py yap_ipython/core/magics/basic.py
yap_ipython/core/magics/code.py
yap_ipython/core/magics/config.py
yap_ipython/core/magics/display.py
yap_ipython/core/magics/execution.py
yap_ipython/core/magics/extension.py
yap_ipython/core/magics/history.py
yap_ipython/core/magics/__init__.py
yap_ipython/core/magics/logging.py
yap_ipython/core/magics/namespace.py
yap_ipython/core/magics/osm.py yap_ipython/core/magics/pylab.py
yap_ipython/core/magics/script.py
yap_ipython/core/tests/bad_all.py
yap_ipython/core/tests/daft_extension
yap_ipython/core/tests/__init__.py
yap_ipython/core/tests/nonascii2.py
yap_ipython/core/tests/nonascii.py
yap_ipython/core/tests/print_argv.py
yap_ipython/core/tests/refbug.py
yap_ipython/core/tests/simpleerr.py
yap_ipython/core/tests/tclass.py
yap_ipython/core/tests/test_alias.py
yap_ipython/core/tests/test_application.py
yap_ipython/core/tests/test_autocall.py
yap_ipython/core/tests/test_compilerop.py
yap_ipython/core/tests/test_completerlib.py
yap_ipython/core/tests/test_completer.py
yap_ipython/core/tests/test_debugger.py
yap_ipython/core/tests/test_displayhook.py
yap_ipython/core/tests/test_display.py
yap_ipython/core/tests/test_events.py
yap_ipython/core/tests/test_extension.py
yap_ipython/core/tests/test_formatters.py
yap_ipython/core/tests/test_handlers.py
yap_ipython/core/tests/test_history.py
yap_ipython/core/tests/test_hooks.py
yap_ipython/core/tests/test_imports.py
yap_ipython/core/tests/test_inputsplitter.py
yap_ipython/core/tests/test_inputtransformer.py
yap_ipython/core/tests/test_interactiveshell.py
yap_ipython/core/tests/test_iplib.py
yap_ipython/core/tests/test_logger.py
yap_ipython/core/tests/test_magic_arguments.py
yap_ipython/core/tests/test_magic.py
yap_ipython/core/tests/test_magic_terminal.py
yap_ipython/core/tests/test_oinspect.py
yap_ipython/core/tests/test_page.py
yap_ipython/core/tests/test_paths.py
yap_ipython/core/tests/test_prefilter.py
yap_ipython/core/tests/test_profile.py
yap_ipython/core/tests/test_prompts.py
yap_ipython/core/tests/test_pylabtools.py
yap_ipython/core/tests/test_run.py
yap_ipython/core/tests/test_shellapp.py
yap_ipython/core/tests/test_splitinput.py
yap_ipython/core/tests/test_ultratb.py
yap_ipython/extensions/tests/__init__.py
yap_ipython/extensions/tests/test_autoreload.py
yap_ipython/extensions/tests/test_storemagic.py
yap_ipython/external/decorators/_decorators.py
yap_ipython/external/decorators/__init__.py
yap_ipython/external/decorators/_numpy_testing_noseclasses.py
yap_ipython/lib/tests/__init__.py
yap_ipython/lib/tests/test_backgroundjobs.py
yap_ipython/lib/tests/test_clipboard.py
yap_ipython/lib/tests/test_deepreload.py
yap_ipython/lib/tests/test_display.py
yap_ipython/lib/tests/test_editorhooks.py
yap_ipython/lib/tests/test_imports.py
yap_ipython/lib/tests/test_latextools.py
yap_ipython/lib/tests/test_lexers.py
yap_ipython/lib/tests/test_pretty.py
yap_ipython/lib/tests/test_security.py
yap_ipython/terminal/pt_inputhooks/glut.py
yap_ipython/terminal/pt_inputhooks/gtk3.py
yap_ipython/terminal/pt_inputhooks/gtk.py
yap_ipython/terminal/pt_inputhooks/__init__.py
yap_ipython/terminal/pt_inputhooks/osx.py
yap_ipython/terminal/pt_inputhooks/pyglet.py
yap_ipython/terminal/pt_inputhooks/qt.py
yap_ipython/terminal/pt_inputhooks/tk.py
yap_ipython/terminal/pt_inputhooks/wx.py
yap_ipython/terminal/tests/__init__.py
yap_ipython/terminal/tests/test_embed.py
yap_ipython/terminal/tests/test_help.py
yap_ipython/terminal/tests/test_interactivshell.py
yap_ipython/testing/plugin/dtexample.py
yap_ipython/testing/plugin/__init__.py
yap_ipython/testing/plugin/ipdoctest.py
yap_ipython/testing/plugin/iptest.py
yap_ipython/testing/plugin/setup.py
yap_ipython/testing/plugin/show_refs.py
yap_ipython/testing/plugin/simple.py
yap_ipython/testing/plugin/simplevars.py
yap_ipython/testing/plugin/test_ipdoctest.py
yap_ipython/testing/plugin/test_refs.py
yap_ipython/testing/tests/__init__.py
yap_ipython/testing/tests/test_decorators.py
yap_ipython/testing/tests/test_ipunittest.py
yap_ipython/testing/tests/test_tools.py
yap_ipython/utils/tests/__init__.py
yap_ipython/utils/tests/test_capture.py
yap_ipython/utils/tests/test_decorators.py
yap_ipython/utils/tests/test_dir2.py
yap_ipython/utils/tests/test_imports.py
yap_ipython/utils/tests/test_importstring.py
yap_ipython/utils/tests/test_io.py
yap_ipython/utils/tests/test_module_paths.py
yap_ipython/utils/tests/test_openpy.py
yap_ipython/utils/tests/test_path.py
yap_ipython/utils/tests/test_process.py
yap_ipython/utils/tests/test_pycolorize.py
yap_ipython/utils/tests/test_shimmodule.py
yap_ipython/utils/tests/test_sysinfo.py
yap_ipython/utils/tests/test_tempdir.py
yap_ipython/utils/tests/test_text.py
yap_ipython/utils/tests/test_tokenutil.py
yap_ipython/utils/tests/test_wildcard.py
yap_ipython/core/tests/daft_extension/daft_extension.py
__init__.py )
set (PYTHON_SOURCES backcall/__init__.py
core/yap_kernel/__init__.py
core/yap_kernel/getipython.py
core/__init__.py
_version.py
yap_kernel/datapub.py
yap_kernel/serialize.py
yap_kernel/embed.py
yap_kernel/_version.py
yap_kernel/connect.py
yap_kernel/iostream.py
yap_kernel/log.py
yap_kernel/parentpoller.py
yap_kernel/jsonutil.py
yap_kernel/ipkernel.py
yap_kernel/kernelspec.py
yap_kernel/eventloops.py
yap_kernel/_eventloop_macos.py
yap_kernel/inprocess/ipkernel.py
yap_kernel/inprocess/client.py
yap_kernel/inprocess/constants.py
yap_kernel/inprocess/tests/test_kernelmanager.py
yap_kernel/inprocess/tests/__init__.py
yap_kernel/inprocess/tests/test_kernel.py
yap_kernel/inprocess/__init__.py
yap_kernel/inprocess/blocking.py
yap_kernel/inprocess/channels.py
yap_kernel/inprocess/socket.py
yap_kernel/inprocess/manager.py
yap_kernel/tests/test_jsonutil.py
yap_kernel/tests/test_zmq_shell.py
yap_kernel/tests/test_pickleutil.py
yap_kernel/tests/test_embed_kernel.py
yap_kernel/tests/test_connect.py
yap_kernel/tests/test_start_kernel.py
yap_kernel/tests/_asyncio.py
yap_kernel/tests/__init__.py
yap_kernel/tests/test_io.py
yap_kernel/tests/test_kernelspec.py
yap_kernel/tests/test_message_spec.py
yap_kernel/tests/utils.py
yap_kernel/tests/test_kernel.py
yap_kernel/tests/test_serialize.py
yap_kernel/tests/test_eventloop.py
yap_kernel/__init__.py
yap_kernel/comm/comm.py
yap_kernel/comm/__init__.py
yap_kernel/comm/manager.py
yap_kernel/zmqshell.py
yap_kernel/gui/gtk3embed.py
yap_kernel/gui/__init__.py
yap_kernel/gui/gtkembed.py
yap_kernel/codeutil.py
yap_kernel/heartbeat.py
yap_kernel/kernelapp.py
yap_kernel/displayhook.py
yap_kernel/pickleutil.py
yap_kernel/kernelbase.py
yap_kernel/pylab/backend_inline.py
yap_kernel/pylab/config.py
yap_kernel/pylab/__init__.py
yap_kernel/__main__.py
yap_kernel.py
kernelspec.py
__init__.py
yap_kernel_launcher.py
docs/conf.py
backcall.py
setup.py
interactiveshell.py
examples/embedding/internal_ipkernel.py
examples/embedding/ipkernel_qtapp.py
examples/embedding/inprocess_terminal.py
examples/embedding/ipkernel_wxapp.py
examples/embedding/inprocess_qtconsole.py
kernelapp.py
yap_ipython/config.py
yap_ipython/core/prefilter.py
yap_ipython/core/magic.py
yap_ipython/core/historyapp.py
yap_ipython/core/hooks.py
yap_ipython/core/completerlib.py
yap_ipython/core/alias.py
yap_ipython/core/release.py
yap_ipython/core/display_trap.py
yap_ipython/core/profiledir.py
yap_ipython/core/error.py
yap_ipython/core/formatters.py
yap_ipython/core/events.py
yap_ipython/core/tests/print_argv.py
yap_ipython/core/tests/test_extension.py
yap_ipython/core/tests/test_shellapp.py
yap_ipython/core/tests/test_compilerop.py
yap_ipython/core/tests/test_handlers.py
yap_ipython/core/tests/nonascii.py
yap_ipython/core/tests/simpleerr.py
yap_ipython/core/tests/refbug.py
yap_ipython/core/tests/tclass.py
yap_ipython/core/tests/test_pylabtools.py
yap_ipython/core/tests/test_magic_terminal.py
yap_ipython/core/tests/test_run.py
yap_ipython/core/tests/test_imports.py
yap_ipython/core/tests/test_prompts.py
yap_ipython/core/tests/test_display.py
yap_ipython/core/tests/bad_all.py
yap_ipython/core/tests/test_page.py
yap_ipython/core/tests/test_interactiveshell.py
yap_ipython/core/tests/test_ultratb.py
yap_ipython/core/tests/__init__.py
yap_ipython/core/tests/daft_extension/daft_extension.py
yap_ipython/core/tests/test_profile.py
yap_ipython/core/tests/test_iplib.py
yap_ipython/core/tests/test_magic_arguments.py
yap_ipython/core/tests/test_displayhook.py
yap_ipython/core/tests/test_magic.py
yap_ipython/core/tests/test_hooks.py
yap_ipython/core/tests/test_inputsplitter.py
yap_ipython/core/tests/test_alias.py
yap_ipython/core/tests/test_inputtransformer.py
yap_ipython/core/tests/test_prefilter.py
yap_ipython/core/tests/test_paths.py
yap_ipython/core/tests/test_splitinput.py
yap_ipython/core/tests/test_completerlib.py
yap_ipython/core/tests/test_completer.py
yap_ipython/core/tests/test_application.py
yap_ipython/core/tests/test_debugger.py
yap_ipython/core/tests/test_events.py
yap_ipython/core/tests/test_autocall.py
yap_ipython/core/tests/test_history.py
yap_ipython/core/tests/test_oinspect.py
yap_ipython/core/tests/nonascii2.py
yap_ipython/core/tests/test_formatters.py
yap_ipython/core/tests/test_logger.py
yap_ipython/core/magics/logging.py
yap_ipython/core/magics/execution.py
yap_ipython/core/magics/config.py
yap_ipython/core/magics/pylab.py
yap_ipython/core/magics/osm.py
yap_ipython/core/magics/code.py
yap_ipython/core/magics/__init__.py
yap_ipython/core/magics/display.py
yap_ipython/core/magics/basic.py
yap_ipython/core/magics/extension.py
yap_ipython/core/magics/namespace.py
yap_ipython/core/magics/script.py
yap_ipython/core/magics/auto.py
yap_ipython/core/magics/history.py
yap_ipython/core/inputtransformer.py
yap_ipython/core/splitinput.py
yap_ipython/core/__init__.py
yap_ipython/core/page.py
yap_ipython/core/shellapp.py
yap_ipython/core/logger.py
yap_ipython/core/excolors.py
yap_ipython/core/completer.py
yap_ipython/core/ultratb.py
yap_ipython/core/backcall.py
yap_ipython/core/display.py
yap_ipython/core/prompts.py
yap_ipython/core/debugger.py
yap_ipython/core/payload.py
yap_ipython/core/application.py
yap_ipython/core/extensions.py
yap_ipython/core/builtin_trap.py
yap_ipython/core/displaypub.py
yap_ipython/core/pylabtools.py
yap_ipython/core/interactiveshell.py
yap_ipython/core/autocall.py
yap_ipython/core/getipython.py
yap_ipython/core/inputsplitter.py
yap_ipython/core/oinspect.py
yap_ipython/core/latex_symbols.py
yap_ipython/core/profileapp.py
yap_ipython/core/payloadpage.py
yap_ipython/core/displayhook.py
yap_ipython/core/magic_arguments.py
yap_ipython/core/usage.py
yap_ipython/core/macro.py
yap_ipython/core/crashhandler.py
yap_ipython/core/compilerop.py
yap_ipython/core/history.py
yap_ipython/sphinxext/__init__.py
yap_ipython/sphinxext/custom_doctests.py
yap_ipython/sphinxext/ipython_console_highlighting.py
yap_ipython/sphinxext/ipython_directive.py
yap_ipython/nbformat.py
yap_ipython/paths.py
yap_ipython/nbconvert.py
yap_ipython/qt.py
yap_ipython/html.py
yap_ipython/frontend.py
yap_ipython/__init__.py
yap_ipython/terminal/pt_inputhooks/glut.py
yap_ipython/terminal/pt_inputhooks/gtk.py
yap_ipython/terminal/pt_inputhooks/gtk3.py
yap_ipython/terminal/pt_inputhooks/qt.py
yap_ipython/terminal/pt_inputhooks/__init__.py
yap_ipython/terminal/pt_inputhooks/tk.py
yap_ipython/terminal/pt_inputhooks/pyglet.py
yap_ipython/terminal/pt_inputhooks/osx.py
yap_ipython/terminal/pt_inputhooks/wx.py
yap_ipython/terminal/ptutils.py
yap_ipython/terminal/console.py
yap_ipython/terminal/embed.py
yap_ipython/terminal/shortcuts.py
yap_ipython/terminal/tests/__init__.py
yap_ipython/terminal/tests/test_embed.py
yap_ipython/terminal/tests/test_interactivshell.py
yap_ipython/terminal/tests/test_help.py
yap_ipython/terminal/__init__.py
yap_ipython/terminal/ipapp.py
yap_ipython/terminal/prompts.py
yap_ipython/terminal/debugger.py
yap_ipython/terminal/interactiveshell.py
yap_ipython/terminal/magics.py
yap_ipython/terminal/ptshell.py
yap_ipython/utils/shimmodule.py
yap_ipython/utils/colorable.py
yap_ipython/utils/tempdir.py
yap_ipython/utils/_process_win32_controller.py
yap_ipython/utils/module_paths.py
yap_ipython/utils/py3compat.py
yap_ipython/utils/tokenutil.py
yap_ipython/utils/version.py
yap_ipython/utils/encoding.py
yap_ipython/utils/openpy.py
yap_ipython/utils/_process_cli.py
yap_ipython/utils/tz.py
yap_ipython/utils/terminal.py
yap_ipython/utils/log.py
yap_ipython/utils/dir2.py
yap_ipython/utils/jsonutil.py
yap_ipython/utils/coloransi.py
yap_ipython/utils/daemonize.py
yap_ipython/utils/io.py
yap_ipython/utils/_process_posix.py
yap_ipython/utils/tests/test_pycolorize.py
yap_ipython/utils/tests/test_decorators.py
yap_ipython/utils/tests/test_tempdir.py
yap_ipython/utils/tests/test_importstring.py
yap_ipython/utils/tests/test_imports.py
yap_ipython/utils/tests/__init__.py
yap_ipython/utils/tests/test_dir2.py
yap_ipython/utils/tests/test_io.py
yap_ipython/utils/tests/test_process.py
yap_ipython/utils/tests/test_sysinfo.py
yap_ipython/utils/tests/test_text.py
yap_ipython/utils/tests/test_tokenutil.py
yap_ipython/utils/tests/test_openpy.py
yap_ipython/utils/tests/test_capture.py
yap_ipython/utils/tests/test_module_paths.py
yap_ipython/utils/tests/test_shimmodule.py
yap_ipython/utils/tests/test_path.py
yap_ipython/utils/tests/test_wildcard.py
yap_ipython/utils/__init__.py
yap_ipython/utils/traitlets.py
yap_ipython/utils/ipstruct.py
yap_ipython/utils/strdispatch.py
yap_ipython/utils/wildcard.py
yap_ipython/utils/capture.py
yap_ipython/utils/localinterfaces.py
yap_ipython/utils/timing.py
yap_ipython/utils/signatures.py
yap_ipython/utils/frame.py
yap_ipython/utils/text.py
yap_ipython/utils/_sysinfo.py
yap_ipython/utils/eventful.py
yap_ipython/utils/sysinfo.py
yap_ipython/utils/process.py
yap_ipython/utils/PyColorize.py
yap_ipython/utils/_process_common.py
yap_ipython/utils/contexts.py
yap_ipython/utils/pickleutil.py
yap_ipython/utils/syspathcontext.py
yap_ipython/utils/path.py
yap_ipython/utils/importstring.py
yap_ipython/utils/_process_win32.py
yap_ipython/utils/generics.py
yap_ipython/utils/sentinel.py
yap_ipython/utils/tokenize2.py
yap_ipython/utils/ulinecache.py
yap_ipython/utils/data.py
yap_ipython/utils/decorators.py
yap_ipython/display.py
yap_ipython/yapi.py
yap_ipython/extensions/rmagic.py
yap_ipython/extensions/cythonmagic.py
yap_ipython/extensions/tests/test_autoreload.py
yap_ipython/extensions/tests/__init__.py
yap_ipython/extensions/tests/test_storemagic.py
yap_ipython/extensions/__init__.py
yap_ipython/extensions/storemagic.py
yap_ipython/extensions/sympyprinting.py
yap_ipython/extensions/autoreload.py
yap_ipython/testing/skipdoctest.py
yap_ipython/testing/iptestcontroller.py
yap_ipython/testing/tools.py
yap_ipython/testing/tests/test_ipunittest.py
yap_ipython/testing/tests/test_decorators.py
yap_ipython/testing/tests/__init__.py
yap_ipython/testing/tests/test_tools.py
yap_ipython/testing/plugin/test_ipdoctest.py
yap_ipython/testing/plugin/dtexample.py
yap_ipython/testing/plugin/show_refs.py
yap_ipython/testing/plugin/__init__.py
yap_ipython/testing/plugin/iptest.py
yap_ipython/testing/plugin/test_refs.py
yap_ipython/testing/plugin/setup.py
yap_ipython/testing/plugin/ipdoctest.py
yap_ipython/testing/plugin/simplevars.py
yap_ipython/testing/plugin/simple.py
yap_ipython/testing/__init__.py
yap_ipython/testing/globalipapp.py
yap_ipython/testing/iptest.py
yap_ipython/testing/ipunittest.py
yap_ipython/testing/__main__.py
yap_ipython/testing/decorators.py
yap_ipython/lib/inputhookpyglet.py
yap_ipython/lib/inputhookgtk.py
yap_ipython/lib/inputhookglut.py
yap_ipython/lib/guisupport.py
yap_ipython/lib/kernel.py
yap_ipython/lib/latextools.py
yap_ipython/lib/inputhookwx.py
yap_ipython/lib/inputhookgtk3.py
yap_ipython/lib/security.py
yap_ipython/lib/tests/test_pretty.py
yap_ipython/lib/tests/test_security.py
yap_ipython/lib/tests/test_backgroundjobs.py
yap_ipython/lib/tests/test_deepreload.py
yap_ipython/lib/tests/test_imports.py
yap_ipython/lib/tests/test_display.py
yap_ipython/lib/tests/test_clipboard.py
yap_ipython/lib/tests/__init__.py
yap_ipython/lib/tests/test_lexers.py
yap_ipython/lib/tests/test_latextools.py
yap_ipython/lib/tests/test_editorhooks.py
yap_ipython/lib/__init__.py
yap_ipython/lib/display.py
yap_ipython/lib/inputhookqt4.py
yap_ipython/lib/pretty.py
yap_ipython/lib/deepreload.py
yap_ipython/lib/inputhook.py
yap_ipython/lib/clipboard.py
yap_ipython/lib/demo.py
yap_ipython/lib/editorhooks.py
yap_ipython/lib/backgroundjobs.py
yap_ipython/lib/lexers.py
yap_ipython/consoleapp.py
yap_ipython/external/mathjax.py
yap_ipython/external/decorators/__init__.py
yap_ipython/external/decorators/_decorators.py
yap_ipython/external/decorators/_numpy_testing_noseclasses.py
yap_ipython/external/__init__.py
yap_ipython/external/qt_loaders.py
yap_ipython/external/qt_for_kernel.py
yap_ipython/parallel.py
yap_ipython/__main__.py
yap_ipython/kernel/clientabc.py
yap_ipython/kernel/threaded.py
yap_ipython/kernel/multikernelmanager.py
yap_ipython/kernel/connect.py
yap_ipython/kernel/adapter.py
yap_ipython/kernel/client.py
yap_ipython/kernel/kernelspec.py
yap_ipython/kernel/__init__.py
yap_ipython/kernel/managerabc.py
yap_ipython/kernel/kernelspecapp.py
yap_ipython/kernel/channelsabc.py
yap_ipython/kernel/launcher.py
yap_ipython/kernel/channels.py
yap_ipython/kernel/restarter.py
yap_ipython/kernel/__main__.py
yap_ipython/kernel/manager.py
__main__.py )
set (EXTRAS MANIFEST.in YAP_KERNEL.md setup.py setup.cfg README.md )
@ -288,12 +395,6 @@ set(FILES ${PYTHON_SOURCES} ${PL_SOURCES} ${EXTRAS} ${RESOURCES})
set(SETUP_PY ${CMAKE_CURRENT_BINARY_DIR}/setup.py)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz
COMMAND ${CMAKE_COMMAND} -E tar czf ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz ${FILES}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DEPENDS ${FILES}
)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png
COMMAND ${CMAKE_COMMAND} -E make_directory yap_kernel/resources
@ -316,19 +417,29 @@ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolo
DEPENDS ${CMAKE_SOURCE_DIR}/misc/editors/yap.js
)
foreach(f ${FILES})
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${f}
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/${f} ${CMAKE_CURRENT_BINARY_DIR}/${f}
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${f}
)
list(APPEND OUTS ${CMAKE_CURRENT_BINARY_DIR}/${f} )
endforeach()
add_custom_target(YAP_KERNEL ALL
COMMAND ${CMAKE_COMMAND} -E tar xzf ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png yap.tgz ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/kernel.js ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js ${CMAKE_CURRENT_BINARY_DIR}/yap.tgz
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/kernel.js ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js ${OUTS} YAP4PY
)
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist
COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed --no-deps .
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist
COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed --no-deps .
COMMAND ${PYTHON_EXECUTABLE} -m yap_kernel.kernelspec
ERROR_VARIABLE setupErr
OUTPUT_VARIABLE setupOut
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
install(FILES ${PL_SOURCES} DESTINATION ${libpl} )
install(FILES ${PL_SOURCES} DESTINATION ${libpl} )

View File

@ -1,6 +1,51 @@
A Jupyter Kernel for YAP (#yap_kernel)
=======================
This kernel supports interaction with YAP Prolog.
This Jupyter kernel supports interaction with YAP Prolog. The kernel
patches IPython and PyKernel so that the user interacts with the
Prolog interpreter. Most of the original kernels are unaffected by the
changes.
You will need `python3` and `jupyter notebook`to use this package, plus:
- `setuptools`;
- `wheel`
- `pip`
The configuration script should recognize whether these Python
packages are installed.
See `tut.ipynb` for details on how to use the system.
Both `jupyter notebook` and `jupyter lab` rely on the Javascript
editor ` CodeMirror` for editing tasks such as highlighting, inlining,
and folding. Unfortunately, `CodeMirror` does not support the Prolog
language. Starting from Wielemaker's excellent `CodeMirror` module for
`swish`, YAP includes a codemirror for Prolog, designed to fit easily
with any `CodeMirror`-based application.
+ `Jupyter lab` includes a complex dependency mechanism, that always
tries to download from the Internet. We do a first build to ensure
all packages are there, set the build offline, patch the different
copies of codemirror, and build locally.
~~~~
CM=$HOME/github/CodeMirror
PYLIB=$HOME/.local/lib/python3.6/site-packages
PYSHARE=$HOME/.local/share
cd $PYLIB/jupyterlab
jupyter lab build
cp commands.py commands.py.bk
sed 's/.node., YARN_PATH,/\"node", YARN_PATH, "--offline",/g' commands.py
cd $PYSHARE/jupyter/lab/staging/node_modules/codemirror/mode
split -n l/5 meta.js
cat xaa xab > meta.js
echo ' {name: "Prolog", mime: "text\/x-prolog", mode: "prolog", ext: ["yap","pl", "ypp", "prolog"]}' >> meta.js
cat xac xad xae >> meta.js
cp -a $CM/mode/prolog prolog
cd $PYLIB/jupyterlab
jupyter lab build
mv commands.py.bk commands.py
~~~~

View File

@ -0,0 +1,5 @@
version_info = (6, 3, 4, 'dev0')
__version__ = '.'.join(map(str, version_info))
kernel_protocol_version_info = (5, 1)
kernel_protocol_version = '%s.%s' % kernel_protocol_version_info

View File

@ -4,12 +4,12 @@
* @brief Prolog completer.
*/
:- module( completer,
[completions/2 ]).
%% %% :- module( completer,
%% %% [completions/2 ]).
:- use_module(library(lists)).
:- use_module(library(maplist)).
:- use_module(library(python)).
:- use_module(library(python)).
%% completions( +Text, +PythonCell )
%

View File

@ -1,3 +1,4 @@
/**
* @file jupyter.yap4py
*
@ -5,39 +6,41 @@
*/
:- yap_flag(gc_trace,verbose).
% :- module( jupyter,
% [jupyter_query/3,
% errors/2,
% ready/2,
% completion/2,
% ]
%% ).
/*
:- module( jupyter,
[jupyter_query/3,
blank/1,
streams/1
]
).
*/
:- use_module(library(hacks)).
:- use_module(library(lists)).
:- use_module(library(maplist)).
:- use_module(library(python)).
:- use_module(library(yapi)).
:- use_module(library(complete)).
%% :- reexport(library(python)).
%% :- reexport(library(yapi)).
%% :- reexport(library(complete)).
%% :- reexport(library(verify)).
:- python_import(sys).
jupyter_query(Caller, Cell, Line ) :-
jupyter_cell(Caller, Cell, Line).
jupyter_cell(Caller, Cell, Line).
jupyter_cell(_Caller, Cell, _Line) :-
jupyter_consult(Cell), %stack_dump,
fail.
jupyter_cell( _Caller, _, '' ) :- !.
jupyter_cell( _Caller, _, ¨¨ ) :- !.
jupyter_cell( _Caller, _, Line ) :-
blank( Line ),
!.
jupyter_cell( Caller, _, Line ) :-
Self := Caller.query,
jupyter_cell(Caller, _, Line ) :-
Query = Caller,
catch(
python_query(Self,Line),
python_query(Query,Line),
E=error(A,B),
system_error(A,B)
).
@ -83,111 +86,15 @@ blank(Text) :-
string_codes(Text, L),
maplist( code_type(space), L).
streams(false) :-
streams(false) :-
close(user_input),
close(user_output),
close(user_error).
streams(true) :-
open('/python/input', read, Input, [alias(user_input),bom(false),script(false)]),
open('/python/sys.stdout', append, Output, [alias(user_output)]),
open('/python/sys.stderr', append, Error, [alias(user_error)]).
ready(_Self, Line ) :-
blank( Line ),
!.
ready(Self, Line ) :-
errors( Self, Line ),
\+ syntax_error(_,_).
errors( Self, Text ) :-
setup_call_cleanup(
open_events( Self, Text, Stream),
goals(Self, Stream),
close_events( Self )
).
clauses(_Self, Stream) :-
repeat,
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
% command( Self, Cl ),
Cl == end_of_file,
!.
goals(_Self, Stream) :-
repeat,
read_term(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
% command( Self, Cl ),
Cl == end_of_file,
!.
command(_, end_of_file) :- !.
command( _Self, ( :- op(Prio,Assoc,Name) ) ) :-
addop(Prio,Assoc,Name).
command( _Self, ( :- module(Name, Exports) )) :-
retract( active_module( M0 ) ),
atom_concat( '__m0_', Name, M ),
assert( active_module(M) ),
assert( undo( active_module(M0) ) ),
maplist( addop2(M), Exports).
addop(Prio,Assoc,Name) :-
(
current_op(OPrio, SimilarAssoc, Name),
op(Prio, Assoc, Name),
matched_op(Assoc, SimilarAssoc)
->
assertz( undo(op( OPrio, Assoc, Name ) ) )
;
assertz( undo(op( 0, Assoc, Name ) ) )
).
addop2(M, op(Prio, Assoc, Name)) :-
addop( Prio, Assoc, M:Name ).
matched_op(A, B) :-
optype( A, T),
optype( B, T).
optype(fx,pre).
optype(fy,pre).
optype(xfx,in).
optype(xfy,in).
optype(yfx,in).
optype(yfy,in).
optype(xf,pos).
optype(yf,pos).
:- dynamic user:portray_message/2.
:- multifile user:portray_message/2.
:- dynamic syntax_error/4, undo/1.
user:portray_message(_Severity, error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
nb_getval(jupyter_cell, on),
assert( syntax_error(Cause,LN,CharPos,Details) ).
user:portray_message(_Severity, error(style_check(_),_) ) :-
nb_getval(jupyter_cell, on).
open_events(Self, Text, Stream) :-
Self.errors := [],
nb_setval( jupyter, on),
open_mem_read_stream( Text, Stream ).
:- initialization( nb_setval( jupyter, off ) ).
close_events( _Self ) :-
nb_setval( jupyter, off ),
retract( undo(G) ),
call(G),
fail.
close_events( Self ) :-
retract( syntax_error( C, L, N, A )),
Self.errors := [t(C,L,N,A)] + Self.errors,
fail.
close_events( _ ).
open('/python/input', read, _Input, [alias(user_input),bom(false),script(false)]),
open('/python/sys.stdout', append, _Output, [alias(user_output)]),
open('/python/sys.stderr', append, _Error, [alias(user_error)]).
:- if( current_prolog_flag(apple, true) ).
@ -206,4 +113,4 @@ plot_inline :-
:- endif.
%:- ( start_low_level_trace ).
%y:- ( start_low_level_trace ).

View File

@ -5,58 +5,175 @@
*/
% :- module( verify,
% [all_clear/4,
% errors/2,
% ready/2,
s % completion/2,
% ]
%% ).
%% :- module( verify,
%% [errors/2,
%% ready/2]
%% ).
:- use_module(library(hacks)).
%% :- use_module(library(jupyter)).
:- use_module(library(lists)).
:- use_module(library(maplist)).
:- use_module(library(python)).
:- use_module(library(yapi)).
:- use_module(library(python)).
%% :- use_module(library(yapi)).
:- python_import(sys).
:- dynamic jupyter/1.
jupyter( []).
p_errors( Errors, Cell) :-
blank( Cell ),
!.
p_errors( Errors, Cell) :-
no_errors( Errors , Cell ).
ready( Engine, Query) :-
errors( Engine , Cell ),
Es := Engine.errors,
not Es == [].
no_errors( _Errors , Text ) :-
blank(Text).
no_errors( Errors , Text ) :-
setup_call_cleanup(
open_esh( Errors , Text, Stream),
esh(Errors , Stream),
close_esh( Errors , Stream )
).
syntax(_Errors , E) :- writeln(user_error, E), fail.
syntax(Errors , error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
Errors.errors := [t(Cause,LN,CharPos,Details)] + Errors.errors,
!.
syntax(_Errors , E) :- throw(E).
open_esh(_Errors , Text, Stream) :-
open_mem_read_stream( Text, Stream ).
esh(Errors , Stream) :-
repeat,
catch(
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
Error,
syntax(Errors , Error)
),
Cl == end_of_file,
errors( _Engine , Text ) :-
blank(Text),
!.
errors( Engine , Text ) :-
%start_low_level_trace,
setup_call_cleanup(
open_esh( Engine , Text, Stream, Name ),
esh(Engine , Name, Stream),
close_esh( Engine , Stream )
),
fail.
errors( _Engine , _Text ).
open_esh(Engine , Text, Stream, Name) :-
Engine.errors := [],
retractall(jupyter(_)),
assertz(jupyter(Engine)),
b_setval( jupyter, Engine),
Name := Engine.stream_name,
open_mem_read_stream( Text, Stream ).
esh(Engine , Name, Stream) :-
repeat,
catch(
read_clause(Stream, Cl, [ syntax_errors(dec10)]),
error(C,E),
p3_message(C,Engine,E)
),
Cl == end_of_file,
!.
:- multifile user:portray_message/2.
user:portray_message(S,E) :-
jupyter(En),
En \= [],
python_clear_errors,
p3_message(S,En,E).
close_esh( _Engine , Stream ) :-
retractall(jupyter(_)),
assertz(jupyter([])),
close(Stream).
close_esh( _Errors , Stream ) :-
close(Stream).
p3_message( _Severity, Engine, error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
python_clear_errors,
!,
Engine.errors := [t(Cause,LN,CharPos,Details)]+Engine.errors.
p3_message(error, Engine, E) :-
python_clear_errors,
!.
p3_message(warning, Engine, E) :-
!.
p3_message(error, Engine, E) :-
Engine.errors := [E] + Engine.errors.
p3_message(warning, Engine, E) :-
Engine.errors := [E] + Engine.errors.
%% ready(_Self, Line ) :-
%% blank( Line ),
%% !.
%% ready(Self, Line ) :-
%% errors( Self, Line ),
%% \+ syntax_error(_,_).
%% errors( Self, Text ) :-
%% setup_call_cleanup(
%% open_events( Self, Text, Stream),
%% goals(Self, Stream),
%% close_events( Self )
%% ).
%% clauses(_Self, Stream) :-
%% repeat,
%% read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
%% % command( Self, Cl ),
%% Cl == end_of_file,
%% !.
%% goals(_Self, Stream) :-
%% repeat,
%% read_term(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
%% % command( Self, Cl ),
%% Cl == end_of_file,
%% !.
%% command(_, end_of_file) :- !.
%% command( _Self, ( :- op(Prio,Assoc,Name) ) ) :-
%% addop(Prio,Assoc,Name).
%% command( _Self, ( :- module(Name, Exports) )) :-
%% retract( active_module( M0 ) ),
%% atom_concat( '__m0_', Name, M ),
%% assert( active_module(M) ),
%% assert( undo( active_module(M0) ) ),
%% maplist( addop2(M), Exports).
%% addop(Prio,Assoc,Name) :-
%% (
%% current_op(OPrio, SimilarAssoc, Name),
%% op(Prio, Assoc, Name),
%% matched_op(Assoc, SimilarAssoc)
%% ->
%% assertz( undo(op( OPrio, Assoc, Name ) ) )
%% ;
%% assertz( undo(op( 0, Assoc, Name ) ) )
%% ).
%% addop2(M, op(Prio, Assoc, Name)) :-
%% addop( Prio, Assoc, M:Name ).
%% matched_op(A, B) :-
%% optype( A, T),
%% optype( B, T).
%% optype(fx,pre).
%% optype(fy,pre).
%% optype(xfx,in).
%% optype(xfy,in).
%% optype(yfx,in).
%% optype(yfy,in).
%% optype(xf,pos).
%% optype(yf,pos).
%% :- dynamic syntax_error/4, undo/1.
%%
%% open_events(Self, Text, Stream) :-
%% Self.errors := [],
%% nb_setval( jupyter, on),
%% open_mem_read_stream( Text, Stream ).
%% :- initialization( nb_setval( jupyter, off ) ).
%% close_events( _Self ) :-
%% nb_setval( jupyter, off ),
%% retract( undo(G) ),
%% call(G),
%% fail.
%% close_events( Self ) :-
%% retract( syntax_error( C, L, N, A )),
%% Self.errors := [t(C,L,N,A)] + Self.errors,
%% fail.
%% close_events( _ ).

View File

@ -16,6 +16,7 @@ from yap_ipython.core.interactiveshell import *
from yap_ipython.core import interactiveshell
from collections import namedtuple
import traceback
use_module = namedtuple('use_module', 'file')
bindvars = namedtuple('bindvars', 'list')
@ -513,12 +514,26 @@ class YAPRun:
self.yapeng = JupyterEngine()
global engine
engine = self.yapeng
self.errors = []
self.query = None
self.os = None
self.it = None
self.port = None
self.answers = None
self.bindings = dicts = []
self.shell.yapeng = self.yapeng
self._get_exc_info = shell._get_exc_info
def showtraceback(self, exc_info):
try:
(etype, value, tb) = e
traceback.print_exception(etype, value, tb)
except:
print(e)
pass
def syntaxErrors(self, text):
"""Return whether a legal query
"""
@ -541,38 +556,49 @@ class YAPRun:
# sys.settrace(tracefunc)
if self.query and self.os == program+squery:
howmany += self.iterations
found = howmany != 0
else:
if self.query:
self.query.close()
self.query = None
self.port = None
self.answers = None
self.os = program+squery
self.iterations = 0
self.bindings = []
pg = jupyter_query( self, program, squery)
self.query = self.yapeng.query(pg)
self.query.answer = {}
self.answers = []
self.port = "call"
self.answer = {}
while self.query.next():
answer = self.query.answer
#sys.stderr.write('B '+str( self.answer) +'\n')
#sys.stderr.write('C '+ str(self.port) +'\n'+'\n')
found = True
self.bindings += [answer]
self.answers += [self.answer]
self.iterations += 1
if self.query.port == "exit":
if self.port == "exit":
self.os = None
sys.stderr.writeln('Done, with', self.bindings)
return True,self.bindings
#sys.stderr.write('Done, with'+str(self.answers)+'\n')
self.result.result = True,self.bindings
return self.result
if stop or howmany == self.iterations:
return True, self.bindings
self.result.result = True, self.answers
return self.result
if found:
sys.stderr.writeln('Done, with ', self.bindings)
sys.stderr.write('Done, with '+str(self.answers)+'\n')
else:
self.os = None
self.query.close()
self.query = None
sys.stderr.write('Fail\n')
return True,self.bindings
self.result.result = True,self.bindings
return self.result
except Exception as e:
sys.stderr.write('Exception after', self.bindings, '\n')
sys.stderr.write('Exception '+str(e)+'in query '+ str(self.query)+
':'+pg+'\n '+str( self.bindings)+ '\n')
has_raised = True
return False,[]
self.result.result = False
return self.result
def _yrun_cell(self, raw_cell, store_history=True, silent=False,
@ -623,6 +649,7 @@ class YAPRun:
raw_cell, store_history, silent, shell_futures)
self.result = interactiveshell.ExecutionResult(info)
self.result.error_before_exec = None
if (raw_cell == "") or raw_cell.isspace():
self.shell.last_execution_succeeded = True
@ -634,7 +661,7 @@ class YAPRun:
if store_history:
self.result.execution_count = self.shell.execution_count+1
def error_before_exec(value):
def error_before_exec(self, value):
self.result.error_before_exec = value
self.shell.last_execution_succeeded = False
return self.result
@ -653,10 +680,10 @@ class YAPRun:
# except SyntaxError:
# preprocessing_exc_tuple = self.shell.syntax_error() # sys.exc_info()
cell = raw_cell # cell has to exist so it can be stored/logged
for i in self.syntaxErrors(raw_cell):
for i in self.errors:
try:
(what,lin,_,text) = i
e = SyntaxError(what, ("<string>", lin, 1, text))
(_,lin,pos,text) = i
e = SyntaxError(what, (self.cell_name, lin, pos, text+'\n'))
raise e
except SyntaxError:
self.shell.showsyntaxerror( )
@ -672,13 +699,13 @@ class YAPRun:
self.showtraceback(preprocessing_exc_tuple)
if store_history:
self.shell.execution_count += 1
return error_before_exec(preprocessing_exc_tuple[2])
return self.error_before_exec(preprocessing_exc_tuple[2])
# Our own compiler remembers the __future__ environment. If we want to
# run code with a separate __future__ environment, use the default
# compiler
# compiler = self.shell.compile if shell_futures else CachingCompiler()
cell_name = str( self.shell.execution_count)
self.cell_name = str( self.shell.execution_count)
if cell[0] == '%':
if cell[1] == '%':
linec = False
@ -700,15 +727,14 @@ class YAPRun:
cell = ""
else:
body = txt0[1]+'\n'+txt0[2]
self.shell.run_cell_magic(magic, line, body)
cell = ""
self.result = True, self.shell.run_cell_magic(magic, line, body)
return self.result
# Give the displayhook a reference to our ExecutionResult so it
# can fill in the output value.
self.shell.displayhook.exec_result = self.result
has_raised = False
try:
self.yapeng.mgoal(streams(True),"user", True)
self.bindings = dicts = []
if cell.strip('\n \t'):
#create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
@ -727,14 +753,17 @@ class YAPRun:
self.jupyter_query( cell )
# state = tracer.runfunc(jupyter_query( self, cell ) )
self.shell.last_execution_succeeded = True
self.result.result = (True, dicts)
except Exception as e:
has_raised = True
self.result.result = False
self.yapeng.mgoal(streams(False),"user", True)
try:
(etype, value, tb) = e
traceback.print_exception(etype, value, tb)
except:
print(e)
pass
self.yapeng.mgoal(streams(False),"user", True)
self.shell.last_execution_succeeded = not has_raised
# Reset this so later displayed values do not modify the
@ -751,6 +780,7 @@ class YAPRun:
# Each cell is a *single* input, regardless of how many lines it has
self.shell.execution_count += 1
self.yapeng.mgoal(streams(False),"user", True)
return self.result
def clean_end(self,s):
@ -775,7 +805,7 @@ class YAPRun:
its = 0
for ch in n:
if not ch.isdigit():
raise SyntaxError()
raise SyntaxError("expected positive number", (self.cellname,s.strip.lines()+1,s.count('\n'),n))
its = its*10+ (ord(ch) - ord('0'))
stop = False
else:
@ -792,7 +822,7 @@ class YAPRun:
last line if the last line is non-empty and does not terminate
on a dot. You can also finish with
- `;`: you request all solutions
- `*`: you request all solutions
- ';'[N]: you want an answer; optionally you want N answers
If the line terminates on a `*/` or starts on a `%` we assume the line
@ -804,3 +834,6 @@ class YAPRun:
return s,'',False,0
(query, _,loop, sols) = self.clean_end(query)
return (program, query, loop, sols)
global
globals = {}

Some files were not shown because too many files have changed in this diff Show More