Merge /home/vsc/github/yap-6.3

This commit is contained in:
Vitor Santos Costa 2018-08-07 21:49:03 +01:00
commit 1668763b19
107 changed files with 5070 additions and 16874 deletions

View File

@ -147,6 +147,30 @@ static inline Atom SearchAtom(const unsigned char *p, Atom a) {
return (NIL);
}
Atom
Yap_AtomInUse(const char *atom) { /* lookup atom in atom table */
uint64_t hash;
const unsigned char *p;
Atom a, na = NIL;
size_t sz = AtomHashTableSize;
/* compute hash */
p =( const unsigned char *) atom;
hash = HashFunction(p);
hash = hash % sz;
/* we'll start by holding a read lock in order to avoid contention */
READ_LOCK(HashChain[hash].AERWLock);
a = HashChain[hash].Entry;
/* search atom in chain */
na = SearchAtom(p, a);
if (na != NIL ) {
READ_UNLOCK(HashChain[hash].AERWLock);
return (na);
}
READ_UNLOCK(HashChain[hash].AERWLock);
return NIL;
}
static Atom
LookupAtom(const unsigned char *atom) { /* lookup atom in atom table */
@ -185,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) {
@ -223,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

@ -592,8 +592,9 @@ restart_aux:
The predicate holds when at least one of the arguments is
ground (otherwise, YAP will generate an error event. _A_ must be unifiable with an atom, and the
argument _L_ with the list of the character codes for string _A_.
ground (otherwise, YAP will generate an error event. _A_ must be unifiable
with an atom, and the argument _L_ with the list of the character codes for
string _A_.
*/
@ -620,7 +621,7 @@ restart_aux:
}
/* error handling */
} else {
Yap_ThrowError( TYPE_ERROR_ATOM, t1, NULL);
Yap_ThrowError(TYPE_ERROR_ATOM, t1, NULL);
}
if (LOCAL_Error_TYPE && Yap_HandleError("atom_codes/2")) {
goto restart_aux;
@ -727,14 +728,14 @@ static Int number_chars(USES_REGS1) {
pop_text_stack(l);
return Yap_unify(ARG1, tf);
}
pop_text_stack(l);
pop_text_stack(l);
LOCAL_ActiveError->errorRawTerm = 0;
Yap_ThrowExistingError();
return false;
}
pop_text_stack(l);
pop_text_stack(l);
return true;
}
@ -1377,7 +1378,7 @@ restart_aux:
LOCAL_Error_TYPE = TYPE_ERROR_LIST;
} else {
seq_tv_t *inpv = (seq_tv_t *)Malloc(n * sizeof(seq_tv_t));
seq_tv_t *out = (seq_tv_t *)Malloc( sizeof(seq_tv_t));
seq_tv_t *out = (seq_tv_t *)Malloc(sizeof(seq_tv_t));
int i = 0;
if (!inpv) {
LOCAL_Error_TYPE = RESOURCE_ERROR_HEAP;
@ -1465,9 +1466,7 @@ error:
if (LOCAL_Error_TYPE && Yap_HandleError("atom_concat/3")) {
goto restart_aux;
}
{
return FALSE;
}
{ return FALSE; }
}
static Int atomics_to_string2(USES_REGS1) {
@ -2766,6 +2765,8 @@ void Yap_InitAtomPreds(void) {
Yap_InitCPred("downcase_atom", 2, downcase_text_to_atom, 0);
Yap_InitCPred("upcase_text_to_atom", 2, upcase_text_to_atom, 0);
Yap_InitCPred("upcase_atom", 2, upcase_text_to_atom, 0);
Yap_InitCPred("text_to_string", 2, downcase_text_to_string, 0);
Yap_InitCPred("text_to_atom", 2, downcase_text_to_string, 0);
Yap_InitCPred("downcase_text_to_string", 2, downcase_text_to_string, 0);
Yap_InitCPred("upcase_text_to_string", 2, upcase_text_to_string, 0);
Yap_InitCPred("downcase_text_to_codes", 2, downcase_text_to_codes, 0);

View File

@ -2271,8 +2271,8 @@ X_API int YAP_WriteDynamicBuffer(YAP_Term t, char *buf, size_t sze,
char *b;
BACKUP_MACHINE_REGS();
b = Yap_TermToBuffer(t, enc, flags);
strncpy(buf, b, sze);
b = Yap_TermToBuffer(t, flags);
strncpy(buf, b, sze-1);
buf[sze] = 0;
RECOVER_MACHINE_REGS();
return true;
@ -2371,7 +2371,7 @@ X_API void YAP_FlushAllStreams(void) {
X_API void YAP_Throw(Term t) {
BACKUP_MACHINE_REGS();
LOCAL_ActiveError->errorNo = THROW_EVENT;
LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, LOCAL_encoding, 0);
LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, 0);
Yap_JumpToEnv();
RECOVER_MACHINE_REGS();
}
@ -2381,7 +2381,7 @@ X_API void YAP_AsyncThrow(Term t) {
BACKUP_MACHINE_REGS();
LOCAL_PrologMode |= AsyncIntMode;
LOCAL_ActiveError->errorNo = THROW_EVENT;
LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, LOCAL_encoding, 0);
LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(t, 0);
Yap_JumpToEnv();
LOCAL_PrologMode &= ~AsyncIntMode;
RECOVER_MACHINE_REGS();

View File

@ -17,6 +17,7 @@
#include "absmi.h"
#include "yapio.h"
#include "YapStreams.h"
#if HAVE_STDARG_H
#include <stdarg.h>
#endif
@ -324,7 +325,7 @@ bool Yap_PrintWarning(Term twarning) {
PredEntry *pred = RepPredProp(PredPropByFunc(
FunctorPrintMessage, PROLOG_MODULE)); // PROCEDURE_print_message2;
__android_log_print(ANDROID_LOG_INFO, "YAPDroid ", " warning(%s)",
Yap_TermToBuffer(twarning, ENC_ISO_UTF8,Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f));
Yap_TermToBuffer(twarning, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f));
Term cmod = (CurrentModule == PROLOG_MODULE ? TermProlog : CurrentModule);
bool rc;
Term ts[2], err;
@ -332,7 +333,7 @@ bool Yap_PrintWarning(Term twarning) {
if (LOCAL_PrologMode & InErrorMode && LOCAL_ActiveError &&
(err = LOCAL_ActiveError->errorNo)) {
fprintf(stderr, "%% Warning %s while processing error: %s %s\n",
Yap_TermToBuffer(twarning, ENC_ISO_UTF8,
Yap_TermToBuffer(twarning,
Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f),
Yap_errorClassName(Yap_errorClass(err)), Yap_errorName(err));
return false;
@ -589,7 +590,7 @@ 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;
}
@ -648,7 +649,7 @@ bool Yap_MkErrorRecord(yap_error_descriptor_t *r, const char *file,
r->culprit = NULL;
} else {
r->culprit = Yap_TermToBuffer(
where, ENC_ISO_UTF8, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f);
where, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f);
}
if (LOCAL_consult_level > 0) {
r->prologParserFile = Yap_ConsultingFile(PASS_REGS1)->StrOfAE;
@ -960,7 +961,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 +1152,7 @@ yap_error_descriptor_t *Yap_UserError(Term t, yap_error_descriptor_t *i) {
n = t2;
}
i->errorGoal = Yap_TermToBuffer(
n, ENC_ISO_UTF8, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f);
n, Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f);
}
Yap_prolog_add_culprit(i PASS_REGS);
return i;

View File

@ -1,4 +1,4 @@
/*************************************************************************
/*************************************************************************
* *
* YAP Prolog *
* *
@ -1460,7 +1460,7 @@ static bool exec_absmi(bool top, yap_reset_t reset_mode USES_REGS) {
*/
/* reset the registers so that we don't have trash in abstract
* machine */
pop_text_stack(i+1);
pop_text_stack(i + 1);
Yap_set_fpu_exceptions(
getAtomicGlobalPrologFlag(ARITHMETIC_EXCEPTIONS_FLAG));
P = (yamop *)FAILCODE;
@ -1470,12 +1470,12 @@ static bool exec_absmi(bool top, yap_reset_t reset_mode USES_REGS) {
} break;
case 3: { /* saved state */
// LOCAL_ActiveError = err_info;
pop_text_stack(i+1);
pop_text_stack(i + 1);
LOCAL_CBorder = OldBorder;
LOCAL_RestartEnv = sighold;
LOCAL_PrologMode = UserMode;
LOCAL_DoingUndefp = false;
Yap_CloseSlots(sls);
LOCAL_DoingUndefp = false;
Yap_CloseSlots(sls);
return false;
}
case 4:
@ -1485,16 +1485,16 @@ Yap_CloseSlots(sls);
// LOCAL_ActiveError = err_info;
while (B) {
LOCAL_ActiveError->errorNo = ABORT_EVENT;
pop_text_stack(i+1);
pop_text_stack(i + 1);
Yap_CloseSlots(sls);
Yap_JumpToEnv();
}
LOCAL_PrologMode = UserMode;
LOCAL_DoingUndefp = false;
P = (yamop *)FAILCODE;
LOCAL_DoingUndefp = false;
P = (yamop *)FAILCODE;
LOCAL_RestartEnv = sighold;
Yap_CloseSlots(sls);
pop_text_stack(i+1);
pop_text_stack(i + 1);
return false;
break;
case 5:
@ -1517,15 +1517,15 @@ Yap_CloseSlots(sls);
(CELL *)(B->cp_b) > LCL0 - LOCAL_CBorder) {
LOCAL_RestartEnv = sighold;
LOCAL_CBorder = OldBorder;
pop_text_stack(i+1);
return false;
pop_text_stack(i + 1);
return false;
}
P = FAILCODE;
}
}
YENV = ASP;
YENV[E_CB] = Unsigned(B);
pop_text_stack(i+1);
pop_text_stack(i + 1);
out = Yap_absmi(0);
/* make sure we don't leave a FAIL signal hanging around */
Yap_get_signal(YAP_FAIL_SIGNAL);
@ -1533,7 +1533,7 @@ Yap_CloseSlots(sls);
CalculateStackGap(PASS_REGS1);
LOCAL_CBorder = OldBorder;
LOCAL_RestartEnv = sighold;
pop_text_stack(i+1);
pop_text_stack(i + 1);
return out;
}
@ -2116,7 +2116,8 @@ static Int jump_env(USES_REGS1) {
}
// Yap_DebugPlWriteln(t);
// char *buf = Yap_TermToBuffer(t, ENC_ISO_UTF8,
// Quote_illegal_f | Ignore_ops_f | Unfold_cyclics_f);
// Quote_illegal_f | Ignore_ops_f |
// Unfold_cyclics_f);
// __android_log_print(ANDROID_LOG_INFO, "YAPDroid ", " throw(%s)", buf);
LOCAL_ActiveError = Yap_UserError(t0, LOCAL_ActiveError);
bool out = JumpToEnv(PASS_REGS1);
@ -2124,7 +2125,7 @@ static Int jump_env(USES_REGS1) {
LCL0 - (CELL *)B > LOCAL_CBorder) {
// we're failing up to the top layer
}
pop_text_stack(LOCAL_MallocDepth+1);
pop_text_stack(LOCAL_MallocDepth + 1);
return out;
}

226
C/flags.c
View File

@ -1,19 +1,19 @@
/*************************************************************************
* *
* YAP Prolog *
* *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 2015- *
* *
**************************************************************************
* *
* File: flags.c *
* Last rev: *
* mods: *
* comments: abstract machine definitions *
* *
*************************************************************************/
* *
* YAP Prolog *
* *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 2015- *
* *
**************************************************************************
* *
* File: flags.c *
* Last rev: *
* mods: *
* comments: abstract machine definitions *
* *
*************************************************************************/
/** @file C/flags.c
@ -80,28 +80,38 @@ static void newFlag(Term fl, Term val);
static Int current_prolog_flag(USES_REGS1);
static Int set_prolog_flag(USES_REGS1);
#include "Yatom.h"
#include "YapEval.h"
#include "Yatom.h"
#include "yapio.h"
#define YAP_FLAG(ID, NAME, WRITABLE, DEF, INIT, HELPER) { NAME, WRITABLE, DEF, INIT, HELPER }
#define YAP_FLAG(ID, NAME, WRITABLE, DEF, INIT, HELPER) \
{ NAME, WRITABLE, DEF, INIT, HELPER }
#define START_LOCAL_FLAGS static flag_info local_flags_setup[] = {
#define END_LOCAL_FLAGS LZERO_FLAG};
#define END_LOCAL_FLAGS \
LZERO_FLAG \
} \
;
#define START_GLOBAL_FLAGS static flag_info global_flags_setup[] = {
#define END_GLOBAL_FLAGS GZERO_FLAG};
#define GZERO_FLAG { NULL, false, NULL, NULL, NULL }
#define LZERO_FLAG { NULL, false, NULL, NULL, NULL }
#define END_GLOBAL_FLAGS \
GZERO_FLAG \
} \
;
#define GZERO_FLAG \
{ NULL, false, NULL, NULL, NULL }
#define LZERO_FLAG \
{ NULL, false, NULL, NULL, NULL }
#include "YapGFlagInfo.h"
#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;
@ -111,13 +121,15 @@ static Term indexer(Term inp) {
"set_prolog_flag index in {off,single,compact,multi,on,max}");
return TermZERO;
}
Yap_Error(TYPE_ERROR_ATOM, inp,
"set_prolog_flag in {dec10,error,fail,quiet}");
Yap_Error(TYPE_ERROR_ATOM, inp, "set_prolog_flag index to an atom");
return TermZERO;
}
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;
@ -133,14 +145,16 @@ static bool dqf1(ModEntry *new, Term t2 USES_REGS) {
return true;
}
/* bad argument, but still an atom */
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted "
"string flag, use one string, "
"atom, codes or chars",
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2,
"bad option %s for backquoted "
"string flag, use one string, "
"atom, codes or chars",
RepAtom(AtomOfTerm(t2))->StrOfAE);
return false;
} else {
Yap_Error(TYPE_ERROR_ATOM, t2, "set_prolog_flag(double_quotes, %s), should "
"be {string,atom,codes,chars}",
Yap_Error(TYPE_ERROR_ATOM, t2,
"set_prolog_flag(double_quotes, %s), should "
"be {string,atom,codes,chars}",
RepAtom(AtomOfTerm(t2))->StrOfAE);
return false;
}
@ -154,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;
@ -168,9 +185,10 @@ static bool bqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags |= BCKQ_CHARS;
return true;
}
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted "
"string flag, use one string, "
"atom, codes or chars",
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2,
"bad option %s for backquoted "
"string flag, use one string, "
"atom, codes or chars",
RepAtom(AtomOfTerm(t2))->StrOfAE);
return false;
} else {
@ -186,9 +204,11 @@ static bool bqs(Term t2) {
return bqf1(new, t2 PASS_REGS);
}
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;
@ -203,9 +223,10 @@ static bool sqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags |= SNGQ_CHARS;
return true;
}
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted "
"string flag, use one string, "
"atom, codes or chars",
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2,
"bad option %s for backquoted "
"string flag, use one string, "
"atom, codes or chars",
RepAtom(AtomOfTerm(t2))->StrOfAE);
return false;
} else {
@ -215,7 +236,6 @@ static bool sqf1(ModEntry *new, Term t2 USES_REGS) {
}
}
static bool sqf(Term t2) {
CACHE_REGS
ModEntry *new = Yap_GetModuleEntry(CurrentModule);
@ -226,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}");
@ -239,8 +262,9 @@ static Term isaccess(Term inp) {
static Term stream(Term inp) {
if (IsVarTerm(inp))
return inp;
if (Yap_CheckStream(inp, Input_Stream_f | Output_Stream_f | Append_Stream_f |
Socket_Stream_f,
if (Yap_CheckStream(inp,
Input_Stream_f | Output_Stream_f | Append_Stream_f |
Socket_Stream_f,
"yap_flag/3") >= 0)
return inp;
return 0;
@ -249,19 +273,19 @@ static Term stream(Term inp) {
static bool set_error_stream(Term inp) {
if (IsVarTerm(inp))
return Yap_unify(inp, Yap_StreamUserName(LOCAL_c_error_stream));
return Yap_SetErrorStream( inp );
return Yap_SetErrorStream(inp);
}
static bool set_input_stream(Term inp) {
if (IsVarTerm(inp))
return Yap_unify(inp, Yap_StreamUserName(LOCAL_c_input_stream));
return Yap_SetInputStream( inp );
return Yap_SetInputStream(inp);
}
static bool set_output_stream(Term inp) {
if (IsVarTerm(inp))
return Yap_unify(inp, Yap_StreamUserName(LOCAL_c_output_stream));
return Yap_SetOutputStream( inp );
return Yap_SetOutputStream(inp);
}
static Term isground(Term inp) {
@ -272,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}");
@ -286,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;
}
@ -298,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;
@ -329,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;
@ -439,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;
@ -477,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;
@ -501,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;
}
@ -521,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)) {
@ -731,10 +780,10 @@ static bool setYapFlagInModule(Term tflag, Term t2, Term mod) {
if (IsVarTerm(tout)) {
Term t;
while ((t = Yap_PopTermFromDB(tarr[fv->FlagOfVE].DBT)) == 0) {
if (!Yap_gc(2, ENV, gc_P(P, CP))) {
Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage);
return false;
}
if (!Yap_gc(2, ENV, gc_P(P, CP))) {
Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage);
return false;
}
}
} else if (IsAtomOrIntTerm(t2))
tarr[fv->FlagOfVE].at = t2;
@ -782,7 +831,6 @@ static bool setYapFlagInModule(Term tflag, Term t2, Term mod) {
return bqf1(me, t2 PASS_REGS);
} else if (fv->FlagOfVE == SINGLE_QUOTES_FLAG) {
return sqf1(me, t2 PASS_REGS);
}
// bad key?
return false;
@ -850,8 +898,7 @@ static Int cont_yap_flag(USES_REGS1) {
Term modt = CurrentModule;
tflag = Yap_StripModule(tflag, &modt);
while (i != gmax && i != UNKNOWN_FLAG && i != CHARACTER_ESCAPES_FLAG &&
i != BACK_QUOTES_FLAG &&
i != SINGLE_QUOTES_FLAG &&
i != BACK_QUOTES_FLAG && i != SINGLE_QUOTES_FLAG &&
i != DOUBLE_QUOTES_FLAG)
i++;
if (i == gmax)
@ -1028,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);
@ -1056,14 +1106,16 @@ void Yap_setModuleFlags(ModEntry *new, ModEntry *cme) {
Atom at = new->AtomOfME;
if (at == AtomProlog || CurrentModule == PROLOG_MODULE) {
new->flags =
M_SYSTEM | UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING |SNGQ_ATOM;
new->flags = M_SYSTEM | UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES |
BCKQ_STRING | SNGQ_ATOM;
if (at == AtomUser)
new->flags = UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING |SNGQ_ATOM;
new->flags =
UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING | SNGQ_ATOM;
} else if (cme && cme->flags && cme != new) {
new->flags = cme->flags;
} else {
new->flags = (UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING |SNGQ_ATOM);
new->flags =
(UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING | SNGQ_ATOM);
}
// printf("cme=%s new=%s flags=%x\n",cme,at->StrOfAE,new->flags);
}
@ -1075,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);
@ -1156,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);
@ -1391,10 +1456,14 @@ static bool setInitialValue(bool bootstrap, flag_func f, const char *s,
return false;
}
CACHE_REGS
const char *us = (const char *)s;
t0 = Yap_BufferToTermWithPrioBindings(us, TermNil, 0L, strlen(s) + 1, GLOBAL_MaxPriority);
const char *us = (const char *)s;
t0 = Yap_BufferToTermWithPrioBindings(us, TermNil, 0L, strlen(s) + 1,
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)) {
@ -1439,12 +1508,16 @@ do_prolog_flag_property(Term tflag,
xarg *args;
prolog_flag_property_choices_t i;
bool rc = true;
args = Yap_ArgList2ToVector(opts, prolog_flag_property_defs,
PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG);
args =
Yap_ArgList2ToVector(opts, prolog_flag_property_defs,
PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG);
if (args == NULL) {
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;
@ -1527,9 +1600,8 @@ static Int cont_prolog_flag_property(USES_REGS1) { /* current_prolog_flag */
lab = MkAtomTerm(Yap_LookupAtom(local_flags_setup[i - gmax].name));
} else {
if (i == UNKNOWN_FLAG || i == CHARACTER_ESCAPES_FLAG ||
i == SINGLE_QUOTES_FLAG ||
i == DOUBLE_QUOTES_FLAG ||
i == BACK_QUOTES_FLAG) {
i == SINGLE_QUOTES_FLAG || i == DOUBLE_QUOTES_FLAG ||
i == BACK_QUOTES_FLAG) {
Term labs[2];
labs[0] = MkVarTerm();
labs[1] = MkAtomTerm(Yap_LookupAtom(global_flags_setup[i].name));
@ -1562,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 {
@ -1607,8 +1682,9 @@ static Int do_create_prolog_flag(USES_REGS1) {
prolog_flag_property_choices_t i;
Term tflag = Deref(ARG1), tval = Deref(ARG2), opts = Deref(ARG3);
args = Yap_ArgList2ToVector(opts, prolog_flag_property_defs,
PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG);
args =
Yap_ArgList2ToVector(opts, prolog_flag_property_defs,
PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG);
if (args == NULL) {
Yap_Error(LOCAL_Error_TYPE, opts, NULL);
return false;
@ -1660,15 +1736,15 @@ static Int do_create_prolog_flag(USES_REGS1) {
}
/**
* Init System Prolog flags. This is done in two phases:
* early on, it takes care of the atomic flags that are required by other
*modules;
* later, it looks at flags that are structured terms
*
* @param bootstrap: wether this is done before stack initialization, or
*afterwards.
* Complex terms can only be built in the second step.
*/
* Init System Prolog flags. This is done in two phases:
* early on, it takes care of the atomic flags that are required by other
*modules;
* later, it looks at flags that are structured terms
*
* @param bootstrap: wether this is done before stack initialization, or
*afterwards.
* Complex terms can only be built in the second step.
*/
void Yap_InitFlags(bool bootstrap) {
CACHE_REGS
@ -1720,9 +1796,9 @@ 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, 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,
cont_current_prolog_flag, 0);
Yap_InitCPredBack("current_prolog_flag", 2, 1, current_prolog_flag2,

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;
}

176
C/text.c
View File

@ -215,10 +215,7 @@ void *Yap_InitTextAllocator(void) {
return new;
}
static size_t MaxTmp(USES_REGS1) {
return 1025;
}
static size_t MaxTmp(USES_REGS1) { return 1025; }
static Term Globalize(Term v USES_REGS) {
if (!IsVarTerm(v = Deref(v))) {
@ -231,7 +228,8 @@ static Term Globalize(Term v USES_REGS) {
return v;
}
static void *codes2buf(Term t0, void *b0, bool get_codes, bool fixed USES_REGS) {
static void *codes2buf(Term t0, void *b0, bool get_codes,
bool fixed USES_REGS) {
unsigned char *st0, *st, ar[16];
Term t = t0;
size_t length = 0;
@ -242,13 +240,14 @@ static void *codes2buf(Term t0, void *b0, bool get_codes, bool fixed USES_REGS)
return st0;
}
if (!IsPairTerm(t)) {
Yap_ThrowError(TYPE_ERROR_LIST, t, "scanning list of codes");
return NULL;
Yap_ThrowError(TYPE_ERROR_LIST, t, "scanning list of codes");
return NULL;
}
bool codes = IsIntegerTerm(HeadOfTerm(t));
if (get_codes !=codes && fixed) {
if (get_codes != codes && fixed) {
if (codes) {
Yap_ThrowError(TYPE_ERROR_INTEGER, HeadOfTerm(t), "scanning list of codes");
Yap_ThrowError(TYPE_ERROR_INTEGER, HeadOfTerm(t),
"scanning list of codes");
} else {
Yap_ThrowError(TYPE_ERROR_ATOM, HeadOfTerm(t), "scanning list of atoms");
}
@ -266,7 +265,8 @@ static void *codes2buf(Term t0, void *b0, bool get_codes, bool fixed USES_REGS)
}
Int code = IntegerOfTerm(hd);
if (code < 0) {
Yap_ThrowError(REPRESENTATION_ERROR_CHARACTER_CODE, hd, "scanning list of character codes, found %d", code);
Yap_ThrowError(REPRESENTATION_ERROR_CHARACTER_CODE, hd,
"scanning list of character codes, found %d", code);
return NULL;
}
length += put_utf8(ar, code);
@ -420,137 +420,151 @@ static yap_error_number gen_type_error(int flags) {
// static int cnt;
unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) {
#define POPRET(x) return pop_output_text_stack(lvl, x)
int lvl = push_text_stack();
char *out = NULL;
yap_error_number err0 = LOCAL_Error_TYPE;
/* we know what the term is */
if (!(inp->type & (YAP_STRING_CHARS | YAP_STRING_WCHARS))) {
if (!(inp->type & YAP_STRING_TERM)) {
if (IsVarTerm(inp->val.t)) {
LOCAL_Error_TYPE = INSTANTIATION_ERROR;
LOCAL_ActiveError->errorRawTerm = inp->val.t;
} else if (!IsAtomTerm(inp->val.t) && inp->type == YAP_STRING_ATOM) {
LOCAL_Error_TYPE = TYPE_ERROR_ATOM;
LOCAL_ActiveError->errorRawTerm = inp->val.t;
} else if (!IsStringTerm(inp->val.t) && inp->type == YAP_STRING_STRING) {
LOCAL_Error_TYPE = TYPE_ERROR_STRING;
LOCAL_ActiveError->errorRawTerm = inp->val.t;
} else if (!IsPairOrNilTerm(inp->val.t) && !IsStringTerm(inp->val.t) &&
inp->type == (YAP_STRING_ATOMS_CODES | YAP_STRING_STRING)) {
LOCAL_ActiveError->errorRawTerm = inp->val.t;
LOCAL_Error_TYPE = TYPE_ERROR_LIST;
LOCAL_ActiveError->errorRawTerm = inp->val.t;
} else if (!IsPairOrNilTerm(inp->val.t) && !IsStringTerm(inp->val.t) &&
!IsAtomTerm(inp->val.t) && !(inp->type & YAP_STRING_DATUM)) {
LOCAL_Error_TYPE = TYPE_ERROR_TEXT;
LOCAL_ActiveError->errorRawTerm = inp->val.t;
}
}
if (err0 != LOCAL_Error_TYPE) {
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);
Atom at = AtomOfTerm(inp->val.t);
if (RepAtom(at)->UStrOfAE[0] == 0) {
unsigned char *o = Malloc(4);
memset(o, 0, 4);
return pop_output_text_stack(lvl, o);
out = Malloc(4);
memset(out, 0, 4);
POPRET( out );
}
if (inp->type & YAP_STRING_WITH_BUFFER) {
pop_text_stack(lvl);
return at->UStrOfAE;
}
size_t sz = strlen(at->StrOfAE);
void *o = Malloc(sz + 1);
strcpy(o, at->StrOfAE);
return pop_output_text_stack(lvl, o);
{
size_t sz = strlen(at->StrOfAE);
out = Malloc(sz + 1);
strcpy(out, at->StrOfAE);
POPRET( out );
}
}
if (IsStringTerm(inp->val.t) && inp->type & YAP_STRING_STRING) {
// this is a term, extract to a buffer, and representation is wide
// Yap_DebugPlWriteln(inp->val.t);
const char *s = StringOfTerm(inp->val.t);
if (s[0] == 0) {
char *o = Malloc(4);
memset(o, 0, 4);
return pop_output_text_stack(lvl, o);
out = Malloc(4);
memset(out, 0, 4);
POPRET( out );
}
if (inp->type & YAP_STRING_WITH_BUFFER) {
pop_text_stack(lvl);
return (unsigned char *)UStringOfTerm(inp->val.t);
}
{
inp->type |= YAP_STRING_IN_TMP;
size_t sz = strlen(s);
out = Malloc(sz + 1);
strcpy(out, s);
POPRET( out );
}
} else if (IsPairOrNilTerm(inp->val.t)) {
if (((inp->type & (YAP_STRING_CODES | YAP_STRING_ATOMS)) ==
(YAP_STRING_CODES | YAP_STRING_ATOMS))) {
// Yap_DebugPlWriteln(inp->val.t);
out = (char *)Yap_ListToBuffer(NULL, inp->val.t, inp PASS_REGS);
POPRET( out );
// this is a term, extract to a sfer, and representation is wide
}
if (inp->type & YAP_STRING_CODES) {
// Yap_DebugPlWriteln(inp->val.t);
out = (char *)Yap_ListOfCodesToBuffer(NULL, inp->val.t, inp PASS_REGS);
// this is a term, extract to a sfer, and representation is wide
POPRET( out );
}
if (inp->type & YAP_STRING_ATOMS) {
// Yap_DebugPlWriteln(inp->val.t);
out = (char *)Yap_ListOfAtomsToBuffer(NULL, inp->val.t, inp PASS_REGS);
// this is a term, extract to a buffer, and representation is wide
POPRET( out );
}
if (inp->type & YAP_STRING_WITH_BUFFER)
return (unsigned char *)UStringOfTerm(inp->val.t);
inp->type |= YAP_STRING_IN_TMP;
size_t sz = strlen(s);
char *o = Malloc(sz + 1);
strcpy(o, s);
return pop_output_text_stack(lvl, o);
}
if (((inp->type & (YAP_STRING_CODES | YAP_STRING_ATOMS)) ==
(YAP_STRING_CODES | YAP_STRING_ATOMS)) &&
IsPairOrNilTerm(inp->val.t)) {
// Yap_DebugPlWriteln(inp->val.t);
return pop_output_text_stack(
lvl, Yap_ListToBuffer(NULL, inp->val.t, inp PASS_REGS));
// this is a term, extract to a sfer, and representation is wide
}
if (inp->type & YAP_STRING_CODES && IsPairOrNilTerm(inp->val.t)) {
// Yap_DebugPlWriteln(inp->val.t);
return pop_output_text_stack(
lvl, Yap_ListOfCodesToBuffer(NULL, inp->val.t, inp PASS_REGS));
// this is a term, extract to a sfer, and representation is wide
}
if (inp->type & YAP_STRING_ATOMS && IsPairOrNilTerm(inp->val.t)) {
// Yap_DebugPlWriteln(inp->val.t);
return pop_output_text_stack(
lvl, Yap_ListOfAtomsToBuffer(NULL, inp->val.t, inp PASS_REGS));
// this is a term, extract to a buffer, and representation is wide
}
if (inp->type & YAP_STRING_INT && IsIntegerTerm(inp->val.t)) {
// ASCII, so both LATIN1 and UTF-8
// Yap_DebugPlWriteln(inp->val.t);
char *s;
s = Malloc(2 * MaxTmp(PASS_REGS1));
if (snprintf(s, MaxTmp(PASS_REGS1) - 1, Int_FORMAT,
out = Malloc(2 * MaxTmp(PASS_REGS1));
if (snprintf(out, MaxTmp(PASS_REGS1) - 1, Int_FORMAT,
IntegerOfTerm(inp->val.t)) < 0) {
AUX_ERROR(inp->val.t, 2 * MaxTmp(PASS_REGS1), s, char);
AUX_ERROR(inp->val.t, 2 * MaxTmp(PASS_REGS1), out, char);
}
return pop_output_text_stack(lvl, s);
POPRET( out );
}
if (inp->type & YAP_STRING_FLOAT && IsFloatTerm(inp->val.t)) {
char *s;
// Yap_DebugPlWriteln(inp->val.t);
if (!Yap_FormatFloat(FloatOfTerm(inp->val.t), &s, 1024)) {
out = Malloc(2 * MaxTmp(PASS_REGS1));
if (!Yap_FormatFloat(FloatOfTerm(inp->val.t), &out, 1024)) {
pop_text_stack(lvl);
return NULL;
}
return pop_output_text_stack(lvl, s);
}
POPRET(out);
}
#if USE_GMP
if (inp->type & YAP_STRING_BIG && IsBigIntTerm(inp->val.t)) {
// Yap_DebugPlWriteln(inp->val.t);
char *s;
s = Malloc(MaxTmp());
if (!Yap_mpz_to_string(Yap_BigIntOfTerm(inp->val.t), s, MaxTmp() - 1, 10)) {
AUX_ERROR(inp->val.t, MaxTmp(PASS_REGS1), s, char);
out = Malloc(MaxTmp());
if (!Yap_mpz_to_string(Yap_BigIntOfTerm(inp->val.t), out, MaxTmp() - 1,
10)) {
AUX_ERROR(inp->val.t, MaxTmp(PASS_REGS1), out, char);
}
return inp->val.uc = pop_output_text_stack(lvl, s);
POPRET(out);
}
#endif
if (inp->type & YAP_STRING_TERM) {
// Yap_DebugPlWriteln(inp->val.t);
char *s = (char *)Yap_TermToBuffer(inp->val.t, ENC_ISO_UTF8, 0);
return inp->val.uc = pop_output_text_stack(lvl, s);
}
if (inp->type & YAP_STRING_CHARS) {
pop_text_stack(lvl);
if (inp->enc == ENC_ISO_LATIN1) {
return latin2utf8(inp);
} else if (inp->enc == ENC_ISO_ASCII) {
return inp->val.uc;
} else { // if (inp->enc == ENC_ISO_UTF8) {
return Yap_TermToBuffer(inp->val.t, 0);
}
if (inp->type & YAP_STRING_CHARS) {
if (inp->enc == ENC_ISO_ASCII) {
pop_text_stack(lvl);
return inp->val.uc;
}
if (inp->enc == ENC_ISO_LATIN1) {
POPRET( (char*)latin2utf8(inp));
}
pop_text_stack(lvl);
return inp->val.c;
}
pop_text_stack(lvl);
if (inp->type & YAP_STRING_WCHARS) {
// printf("%S\n",inp->val.w);
return wchar2utf8(inp);
POPRET( (char *)wchar2utf8(inp) );
}
pop_text_stack(lvl);
return NULL;
}

File diff suppressed because it is too large Load Diff

View File

@ -87,7 +87,7 @@ static char *send_tracer_message(char *start, char *name, arity_t arity,
continue;
}
}
const char *sn = Yap_TermToBuffer(args[i], LOCAL_encoding,
const char *sn = Yap_TermToBuffer(args[i],
Quote_illegal_f | Handle_vars_f);
size_t sz;
if (sn == NULL) {

View File

@ -372,7 +372,7 @@ handle_cp_overflow(int res, tr_fr_ptr TR0, UInt arity, Term t)
switch(res) {
case -1:
if (!Yap_gcl((ASP-HR)*sizeof(CELL), arity+1, ENV, gc_P(P,CP))) {
Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage);
Yap_Error(RESOURCE_ERROR_STACK, TermFoundVar, LOCAL_ErrorMessage);
return 0L;
}
return Deref(XREGS[arity+1]);
@ -1349,7 +1349,7 @@ static Term vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, Ter
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -1377,7 +1377,7 @@ static Term vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, Ter
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -1683,7 +1683,7 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
}
{
CELL *npt0 = RepPair(d0);
if(IsAtomicTerm(Deref(npt0[0]))) {
if(Deref(npt0[0]) == TermFoundVar) {
pt0 = npt0;
pt0_end = pt0 + 1;
continue;
@ -1694,7 +1694,7 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
to_visit->end = pt0_end;
to_visit->oval = *pt0;
to_visit ++;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -1722,7 +1722,7 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
to_visit->end = pt0_end;
to_visit->oval = *pt0;
to_visit ++;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -1741,7 +1741,7 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
derefa_body(d0, ptd0, attvars_in_term_unk, attvars_in_term_nvar);
if (IsAttVar(ptd0)) {
/* do or pt2 are unbound */
*ptd0 = TermNil;
*ptd0 = TermFoundVar;
/* next make sure noone will see this as a variable again */
if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) {
/* Trail overflow */
@ -1767,7 +1767,7 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
to_visit->end = pt0_end;
to_visit->oval = *pt0;
to_visit ++;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -1963,7 +1963,7 @@ static Term vars_within_complex_term(register CELL *pt0, register CELL *pt0_end,
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2160,7 +2160,7 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2188,7 +2188,7 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2205,7 +2205,7 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end,
derefa_body(d0, ptd0, vars_within_term_unk, vars_within_term_nvar);
/* do or pt2 are unbound */
*ptd0 = TermNil;
*ptd0 = TermFoundVar;
/* leave an empty slot to fill in later */
if (HR+1024 > ASP) {
goto global_overflow;
@ -2350,7 +2350,7 @@ static Term free_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2378,7 +2378,7 @@ static Term free_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2395,7 +2395,7 @@ static Term free_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end
derefa_body(d0, ptd0, vars_within_term_unk, vars_within_term_nvar);
/* do or pt2 are unbound */
*ptd0 = TermNil;
*ptd0 = TermFoundVar;
/* leave an empty slot to fill in later */
if (HR+1024 > ASP) {
goto global_overflow;
@ -2507,7 +2507,7 @@ static Term bind_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2535,7 +2535,7 @@ static Term bind_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2706,7 +2706,7 @@ static Term non_singletons_in_complex_term(register CELL *pt0, register CELL *pt
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2735,7 +2735,7 @@ static Term non_singletons_in_complex_term(register CELL *pt0, register CELL *pt
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
/* store the terms to visit */
if (pt0 < pt0_end) {
@ -2864,7 +2864,7 @@ static Int ground_complex_term(register CELL *pt0, register CELL *pt0_end USES_R
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -2892,7 +2892,7 @@ static Int ground_complex_term(register CELL *pt0, register CELL *pt0_end USES_R
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
/* store the terms to visit */
if (pt0 < pt0_end) {
@ -3043,7 +3043,7 @@ static Int sz_ground_complex_term(register CELL *pt0, register CELL *pt0_end, in
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -3072,7 +3072,7 @@ static Int sz_ground_complex_term(register CELL *pt0, register CELL *pt0_end, in
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
/* store the terms to visit */
if (pt0 < pt0_end) {
@ -3191,7 +3191,7 @@ static Int var_in_complex_term(register CELL *pt0,
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -3221,7 +3221,7 @@ static Int var_in_complex_term(register CELL *pt0,
to_visit[1] = pt0_end;
to_visit[2] = (CELL *)*pt0;
to_visit += 3;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
/* store the terms to visit */
if (pt0 < pt0_end) {
@ -3251,7 +3251,7 @@ static Int var_in_complex_term(register CELL *pt0,
return(TRUE);
}
/* do or pt2 are unbound */
*ptd0 = TermNil;
*ptd0 = TermFoundVar;
/* next make sure noone will see this as a variable again */
TrailTerm(TR++) = (CELL)ptd0;
}
@ -4628,7 +4628,7 @@ loop:
to_visit->end = pt0_end;
to_visit->oval = *pt0;
to_visit ++;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#else
if (pt0 < pt0_end) {
to_visit[0] = pt0;
@ -4661,7 +4661,7 @@ loop:
to_visit->end = pt0_end;
to_visit->oval = *pt0;
to_visit ++;
*pt0 = TermNil;
*pt0 = TermFoundVar;
#endif
d0 = ArityOfFunctor(f);
pt0 = ap2;

View File

@ -375,7 +375,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);
@ -384,9 +383,7 @@ int Yap_FormatFloat(Float f, char **s, size_t sz) {
wglb.lw = separator;
wglb.stream = GLOBAL_Stream + sno;
wrputf(f, &wglb);
so = Yap_MemExportStreamPtr(sno);
*s = BaseMalloc(strlen(so) + 1);
strcpy(*s, so);
*s = Yap_MemExportStreamPtr(sno);
Yap_CloseStream(sno);
return true;
}
@ -1255,28 +1252,3 @@ void Yap_plwrite(Term t, StreamDesc *mywrite, int max_depth, int flags,
pop_text_stack(lvl);
}
char *Yap_TermToBuffer(Term t, encoding_t enc, int flags) {
CACHE_REGS
int sno = Yap_open_buf_write_stream(enc, flags);
const char *sf;
if (sno < 0)
return NULL;
if (t == 0)
return NULL;
else
t = Deref(t);
if (enc)
GLOBAL_Stream[sno].encoding = enc;
else
GLOBAL_Stream[sno].encoding = LOCAL_encoding;
GLOBAL_Stream[sno].status |= CloseOnException_Stream_f;
Yap_plwrite(t, GLOBAL_Stream + sno, 0, flags, GLOBAL_MaxPriority);
sf = Yap_MemExportStreamPtr(sno);
size_t len = strlen(sf);
char *new = malloc(len + 1);
strcpy(new, sf);
Yap_CloseStream(sno);
return new;
}

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,29 +202,28 @@ 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);
}
} while (true);
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);
}
BACKUP_MACHINE_REGS();
YAP_EndConsult(c_stream, &osno, full);
if (!Yap_AddAlias(AtomLoopStream, osno)) {
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})
@ -554,10 +554,11 @@ IF (WITH_PYTHON)
ENDIF (WITH_PYTHON)
option(WITH_R
"Allow YAP->R" ON)
"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,6 @@ if (WITH_GECODE)
add_subDIRECTORY(packages/gecode)
endif ()
add_subDIRECTORY(packages/real)
@ -795,17 +796,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 +826,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 +839,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

@ -19,7 +19,7 @@ extern "C" {
#include "YapInterface.h"
#include "iopreds.h"
X_API char *Yap_TermToBuffer(Term t, encoding_t encodingp, int flags);
X_API char *Yap_TermToBuffer(Term t, int flags);
X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, arity_t arity);
X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, arity_t,
@ -30,35 +30,32 @@ X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred,
#if YAP_PYTHON
X_API bool do_init_python(void);
#endif
}
static void YAPCatchError()
{
if (LOCAL_CommittedError != nullptr &&
LOCAL_CommittedError->errorNo != YAP_NO_ERROR ) {
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( );
Term es[2];
es[0] = TermError;
es[1] = MkErrorTerm(LOCAL_CommittedError);
Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2);
YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es));
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( SOURCE(), );
} else if (LOCAL_ActiveError != nullptr &&
LOCAL_ActiveError->errorNo != YAP_NO_ERROR ) {
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( );
Term es[2];
es[0] = TermError;
es[1] = MkErrorTerm(LOCAL_ActiveError);
Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2);
YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es));
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( SOURCE(), );
}
static void YAPCatchError() {
if (LOCAL_CommittedError != nullptr &&
LOCAL_CommittedError->errorNo != YAP_NO_ERROR) {
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( );
Term es[2];
es[0] = TermError;
es[1] = MkErrorTerm(LOCAL_CommittedError);
Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2);
YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es));
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( SOURCE(), );
} else if (LOCAL_ActiveError != nullptr &&
LOCAL_ActiveError->errorNo != YAP_NO_ERROR) {
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( );
Term es[2];
es[0] = TermError;
es[1] = MkErrorTerm(LOCAL_ActiveError);
Functor f = Yap_MkFunctor(Yap_LookupAtom("print_message"), 2);
YAP_RunGoalOnce(Yap_MkApplTerm(f, 2, es));
// Yap_PopTermFromDB(info->errorTerm);
// throw throw YAPError( SOURCE(), );
}
}
YAPPredicate::YAPPredicate(Term &t, Term &tmod, CELL *&ts, const char *pname) {
@ -128,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;
@ -145,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));
@ -256,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() {
@ -334,7 +396,7 @@ std::vector<Term> YAPPairTerm::listToArray() {
if (l < 0) {
throw YAPError(SOURCE(), TYPE_ERROR_LIST, (t), nullptr);
}
std::vector<Term> o = * new std::vector<Term>(l);
std::vector<Term> o = *new std::vector<Term>(l);
int i = 0;
Term t = gt();
while (t != TermNil) {
@ -483,7 +545,7 @@ const char *YAPAtom::getName(void) { return Yap_AtomToUTF8Text(a); }
void YAPQuery::openQuery() {
CACHE_REGS
if (ap == NULL || ap->OpcodeOfPred == UNDEF_OPCODE) {
if (ap == NULL || ap->OpcodeOfPred == UNDEF_OPCODE) {
ap = rewriteUndefQuery();
}
setNext();
@ -512,7 +574,7 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
YAPCatchError();
Yap_CloseHandles(q.CurSlot);
pop_text_stack(q.lvl+1);
pop_text_stack(q.lvl + 1);
RECOVER_MACHINE_REGS();
return result;
@ -520,47 +582,49 @@ 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;
q.CurSlot = Yap_StartSlots();
q.p = P;
q.cp = CP;
PredEntry *ap = nullptr;
if (IsStringTerm(tmod))
tmod = MkAtomTerm(Yap_LookupAtom(StringOfTerm(tmod)));
YAPPredicate *p = new YAPPredicate(t, tmod, ts, "C++");
if (p == nullptr || (ap = p->ap) == nullptr ||
ap->OpcodeOfPred == UNDEF_OPCODE) {
ap = rewriteUndefEngineQuery(ap, t, tmod);
}
if (IsApplTerm(t))
ts = RepAppl(t) + 1;
else if (IsPairTerm(t))
ts = RepPair(t);
/* legal ap */
arity_t arity = ap->ArityOfPE;
Term *ts = nullptr;
q.CurSlot = Yap_StartSlots();
q.p = P;
q.cp = CP;
PredEntry *ap = nullptr;
if (IsStringTerm(tmod))
tmod = MkAtomTerm(Yap_LookupAtom(StringOfTerm(tmod)));
YAPPredicate *p = new YAPPredicate(t, tmod, ts, "C++");
if (p == nullptr || (ap = p->ap) == nullptr ||
ap->OpcodeOfPred == UNDEF_OPCODE) {
ap = rewriteUndefEngineQuery(ap, t, tmod);
}
if (IsApplTerm(t))
ts = RepAppl(t) + 1;
else if (IsPairTerm(t))
ts = RepPair(t);
/* legal ap */
arity_t arity = ap->ArityOfPE;
for (arity_t i = 0; i < arity; i++) {
XREGS[i + 1] = ts[i];
}
ts = nullptr;
bool result;
// allow Prolog style exception handling
// don't forget, on success these guys may create slots
//__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
for (arity_t i = 0; i < arity; i++) {
XREGS[i + 1] = ts[i];
}
ts = nullptr;
bool result;
// allow Prolog style exception handling
// 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);
YAP_LeaveGoal(result && !release, &q);
// PyEval_RestoreThread(_save);
RECOVER_MACHINE_REGS();
return result;
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);
RECOVER_MACHINE_REGS();
return result;
}
/**
* called when a query must be terminated and its state fully recovered,
@ -576,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;
@ -666,31 +730,29 @@ goal = YAPApplTerm(f, nts);
}
#endif
YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) {
BACKUP_MACHINE_REGS();
try {
arity_t arity = p.ap->ArityOfPE;
if (arity) {
goal = YAPApplTerm(YAPFunctor(p.ap->FunctorOfPred), ts).term();
for (arity_t i = 0; i < arity; i++)
XREGS[i + 1] = ts[i].term();
openQuery();
} else {
goal = MkAtomTerm((Atom)(p.ap->FunctorOfPred));
openQuery();
if (arity) {
goal = YAPApplTerm(YAPFunctor(p.ap->FunctorOfPred), ts).term();
for (arity_t i = 0; i < arity; i++)
XREGS[i + 1] = ts[i].term();
openQuery();
} else {
goal = MkAtomTerm((Atom)(p.ap->FunctorOfPred));
openQuery();
}
names = TermNil;
} catch (...) {
}
names = TermNil;
} catch (...) {
}
RECOVER_MACHINE_REGS();
RECOVER_MACHINE_REGS();
}
bool YAPQuery::next() {
CACHE_REGS
bool result = false;
//std::cerr << "next " << YAPTerm(goal).text() << "\n";
// std::cerr << "next " << YAPTerm(goal).text() << "\n";
sigjmp_buf buf, *oldp = LOCAL_RestartEnv;
e = nullptr;
@ -702,7 +764,7 @@ bool YAPQuery::next() {
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
if (q_state == 0) {
//Yap_do_low_level_trace = 1;
// Yap_do_low_level_trace = 1;
result = (bool)YAP_EnterGoal(ap, nullptr, &q_h);
} else {
LOCAL_AllowRestart = q_open;
@ -710,19 +772,18 @@ bool YAPQuery::next() {
}
q_state = 1;
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %d", result);
if (!result) {
if (!result) {
YAP_LeaveGoal(result, &q_h);
q_open = false;
}
YAPCatchError();
YAPCatchError();
RECOVER_MACHINE_REGS();
LOCAL_RestartEnv = oldp;
return result;
}
PredEntry *YAPQuery::rewriteUndefQuery() {
ARG1 = goal = Yap_SaveTerm(Yap_MkApplTerm(FunctorCall
, 1, &goal));
ARG1 = goal = Yap_SaveTerm(Yap_MkApplTerm(FunctorCall, 1, &goal));
return ap = PredCall;
}
@ -879,9 +940,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)) {
@ -894,7 +954,7 @@ PredEntry *YAPPredicate::getPred(Term &t, CELL *&out) {
ap = RepPredProp(PredPropByAtom(AtomOfTerm(t), m));
return ap;
} else if (IsPairTerm(t)) {
Term ts[2], *s = ( out ? out : ts );
Term ts[2], *s = (out ? out : ts);
Functor FunctorConsult = Yap_MkFunctor(Yap_LookupAtom("consult"), 1);
s[1] = t;
s[0] = m;
@ -909,7 +969,7 @@ PredEntry *YAPPredicate::getPred(Term &t, CELL *&out) {
} else {
ap = RepPredProp(PredPropByFunc(f, m));
if (out)
memmove( out, RepAppl(t) + 1, ap->ArityOfPE*sizeof(CELL) );
memmove(out, RepAppl(t) + 1, ap->ArityOfPE * sizeof(CELL));
else
out = RepAppl(t) + 1;
}
@ -1017,12 +1077,12 @@ std::stringstream s;
void YAPEngine::reSet() {
/* ignore flags for now */
if (B && B->cp_b && B->cp_ap != NOCODE )
YAP_LeaveGoal(false, &q);
if (B && B->cp_b && B->cp_ap != NOCODE)
YAP_LeaveGoal(false, &q);
LOCAL_ActiveError->errorNo = YAP_NO_ERROR;
if (LOCAL_CommittedError) {
LOCAL_CommittedError->errorNo = YAP_NO_ERROR;
free(LOCAL_CommittedError );
free(LOCAL_CommittedError);
LOCAL_CommittedError = NULL;
}
}

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

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() {
@ -223,19 +222,15 @@ public:
/// return a string with a textual representation of the term
virtual const char *text() {
CACHE_REGS
encoding_t enc = LOCAL_encoding;
char *os;
BACKUP_MACHINE_REGS();
if (!(os = Yap_TermToBuffer(Yap_GetFromSlot(t), enc, Handle_vars_f))) {
if (!(os = Yap_TermToBuffer(Yap_GetFromSlot(t), Handle_vars_f))) {
RECOVER_MACHINE_REGS();
return 0;
}
RECOVER_MACHINE_REGS();
size_t length = strlen(os);
char *sm = (char *)malloc(length + 1);
strcpy(sm, os);
return sm;
return os;
};
/// return a handle to the term
@ -296,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
@ -469,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); }
@ -483,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

@ -37,6 +37,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"
@ -269,7 +270,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,6 +459,7 @@ 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 AtFoundOne FoundVar 2

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,17 +142,20 @@ 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;
if (IsAtomTerm(inp)) {
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, inp,
Yap_ThrowError(DOMAIN_ERROR_OUT_OF_RANGE, inp,
"set_prolog_flag in {dec10,error,fail,quiet}");
return TermZERO;
}
Yap_Error(TYPE_ERROR_ATOM, inp,
"set_prolog_flag in {dec10,error,fail,quiet}");
Yap_ThrowError(TYPE_ERROR_ATOM, inp,
"syntax_error flag must be atom");
return TermZERO;
}
@ -172,6 +178,9 @@ 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");

View File

@ -56,29 +56,26 @@ opportunity. Initial value is 10,000. May be changed. A value of 0
~~~
*/
YAP_FLAG(ANSWER_FORMAT_FLAG, "answer_format", true, isatom, "~p", NULL),
/**< how to present answers, default is `~p`. */
#if __ANDROID__
YAP_FLAG(ANDROID_FLAG, "android", false, booleanFlag, "true", NULL), /**<
read-only boolean, a machine running an Google's Android version of the Linux Operating System */
read-only boolean, a machine running an Google's Android version of the
Linux Operating System */
#endif
#if __APPLE__
YAP_FLAG(APPLE_FLAG, "apple", false, booleanFlag, "true", NULL), /**<
read-only boolean, a machine running an Apple Operating System */
#endif
YAP_FLAG(ARCH_FLAG, "arch", false, isatom, YAP_ARCH, NULL), /**<
read-only atom, it describes the ISA used in this version of YAP.
Available from YAP_AEH.
Available from YAP_ARCH.
*/
YAP_FLAG(ARGV_FLAG, "argv", false, argv, "@boot", NULL),
YAP_FLAG(ARITHMETIC_EXCEPTIONS_FLAG, "arithmetic_exceptions", true,
booleanFlag, "true", NULL),
/**< `arithmetic_exceptions`
/**<
Read-write flag telling whether arithmetic exceptions generate
Prolog exceptions. If enabled:
@ -99,7 +96,7 @@ opportunity. Initial value is 10,000. May be changed. A value of 0
ProbLog.
*/
YAP_FLAG(BACK_QUOTES_FLAG, "back_quotes", true, isatom, "true", bqs),
/**>
/**<
If _Value_ is unbound, tell whether a back quoted list of characters
token is converted to a list of atoms, `chars`, to a list of integers,
`codes`, or to a single atom, `atom`. If _Value_ is bound, set to
@ -132,20 +129,22 @@ opportunity. Initial value is 10,000. May be changed. A value of 0
Writable flag telling whether a character escapes are enabled,
`true`, or disabled, `false`. The default value for this flag is
`true`. */
YAP_FLAG(COLON_SETS_CALLING_CONTEXT_FLAG, "colon_sets_calling_context", true, booleanFlag, "true", NULL),
YAP_FLAG(COLON_SETS_CALLING_CONTEXT_FLAG, "colon_sets_calling_context",
true, booleanFlag, "true", NULL),
/**< `compiled_at `
Read-only flag that gives the time when the main YAP binary was compiled. It
is obtained staight from the __TIME__ macro, as defined in the C99.
*/ YAP_FLAG(COMPILED_AT_FLAG, "compiled_at", false, isatom, YAP_COMPILED_AT,
Read-only flag that gives the time when the main YAP binary was compiled.
It is obtained staight from the __TIME__ macro, as defined in the C99.
*/
YAP_FLAG(COMPILED_AT_FLAG, "compiled_at", false, isatom, YAP_COMPILED_AT,
NULL),
YAP_FLAG(DEBUG_FLAG, "debug", true, booleanFlag, "false", NULL),
/**<
/**<
If _Value_ is unbound, tell whether debugging is `true` or
`false`. If _Value_ is bound to `true` enable debugging, and if
it is bound to `false` disable debugging.
*/
If _Value_ is unbound, tell whether debugging is `true` or
`false`. If _Value_ is bound to `true` enable debugging, and if
it is bound to `false` disable debugging.
*/
YAP_FLAG(DEBUG_INFO_FLAG, "debug_info", true, booleanFlag, "true", NULL),
YAP_FLAG(DEBUG_ON_ERROR_FLAG, "debug_on_error", true, booleanFlag, "true",
NULL),
@ -155,15 +154,18 @@ opportunity. Initial value is 10,000. May be changed. A value of 0
*/
YAP_FLAG(DEBUGGER_PRINT_OPTIONS_FLAG, "debugger_print_options", true,
list_option,
"[quoted(true),numbervars(true),portrayed(true),max_depth(10)]",
"[quoted(true),numbervars(true),portrayed(true),max_depth(10)]",
NULL),
YAP_FLAG(DEBUGGER_SHOW_CONTEXT_FLAG, "debugger_show_context", true,
booleanFlag, "false", NULL),
YAP_FLAG(DEFAULT_PARENT_MODULE_FLAG, "default_parent_module", true, isatom, "user", NULL),
YAP_FLAG(DEFAULT_PARENT_MODULE_FLAG, "default_parent_module", true, isatom,
"user", NULL),
/**<
* A module to be inherited by all other modules. Default is user that reexports prolog.
* A module to be inherited by all other modules. Default is user that
* reexports prolog.
*
* Set it to `prolog` for SICStus Prolog like resolution, to `user` for SWI-like.
* Set it to `prolog` for SICStus Prolog like resolution, to `user` for
* SWI-like.
*/
YAP_FLAG(DIALECT_FLAG, "dialect", false, ro, "yap", NULL),
/**<
@ -275,11 +277,11 @@ vxu `on` consider `$` a lower case character.
*/
YAP_FLAG(INDEX_SUB_TERM_SEARCH_DEPTH_FLAG, "index_sub_term_search_depth",
true, nat, "0", NULL),
/**< `Index_sub_term_search_depth `
/**< `Index_sub_term_search_depth `
Maximum bound on searching sub-terms for indexing, if `0` (default) no
bound.
*/
Maximum bound on searching sub-terms for indexing, if `0` (default) no
bound.
*/
YAP_FLAG(INFORMATIONAL_MESSAGES_FLAG, "informational_messages", true,
isatom, "normal", NULL),
/**< `informational_messages `
@ -297,6 +299,8 @@ vxu `on` consider `$` a lower case character.
value `toward_zero` for the current version of YAP.
*/
YAP_FLAG(ISO_FLAG, "iso", true, booleanFlag, "false", NULL),
YAP_FLAG(JUPYTER_FLAG, "jupyter", false, booleanFlag, "true", NULL), /**<
read-only boolean, a machine running Jupyter */
YAP_FLAG(LANGUAGE_FLAG, "language", true, isatom, "yap", NULL),
/**< `language `
@ -322,7 +326,7 @@ vxu `on` consider `$` a lower case character.
Read-only flag telling the maximum arity of a functor. Takes the value
`unbounded` for the current version of YAP.
*/
YAP_FLAG(MAX_TAGGED_INTEGER_FLAG, "max_tagged_integer", false, at2n,
YAP_FLAG(MAX_TAGGED_INTEGER_FLAG, "max_tagged_integer", false, at2n,
"INT_MAX", NULL),
YAP_FLAG(MAX_THREADS_FLAG, "max_threads", false, at2n, "MAX_THREADS", NULL),
YAP_FLAG(MAX_WORKERS_FLAG, "max_workers", false, at2n, "MAX_WORKERS", NULL),
@ -348,15 +352,14 @@ vxu `on` consider `$` a lower case character.
providing access to shared libraries (`.so` files) or to dynamic link
libraries (`.DLL` files).
*/
/**< `module_independent_operators `
/**< `module_independent_operators `
If `true` an operator declaration will be valid for every module in the
program. This is for compatibility with old software that
might expect module-independent operators.
*/
YAP_FLAG(MODULE_INDEPENDENT_OPERATORS_FLAG,
"module_independent_operators", true, booleanFlag,
"false", NULL),
If `true` an operator declaration will be valid for every module in the
program. This is for compatibility with old software that
might expect module-independent operators.
*/
YAP_FLAG(MODULE_INDEPENDENT_OPERATORS_FLAG, "module_independent_operators",
true, booleanFlag, "false", NULL),
YAP_FLAG(OPTIMISE_FLAG, "optimise", true, booleanFlag, "false", NULL),
YAP_FLAG(OS_ARGV_FLAG, "os_argv", false, os_argv, "@boot", NULL),
@ -372,14 +375,14 @@ vxu `on` consider `$` a lower case character.
*/
YAP_FLAG(PROMPT_ALTERNATIVES_ON_FLAG, "prompt_alternatives_on", true,
isatom, "determinism", NULL),
/**< `prompt_alternatives_on(atom,
changeable) `
/**< `prompt_alternatives_on(atom,
changeable) `
SWI-Compatible option, determines prompting for alternatives in the Prolog
toplevel. Default is <tt>groundness</tt>, YAP prompts for alternatives if
and only if the query contains variables. The alternative, default in
SWI-Prolog is <tt>determinism</tt> which implies the system prompts for
alternatives if the goal succeeded while leaving choicepoints. */
SWI-Compatible option, determines prompting for alternatives in the Prolog
toplevel. Default is <tt>groundness</tt>, YAP prompts for alternatives if
and only if the query contains variables. The alternative, default in
SWI-Prolog is <tt>determinism</tt> which implies the system prompts for
alternatives if the goal succeeded while leaving choicepoints. */
YAP_FLAG(QUASI_QUOTATIONS_FLAG, "quasi_quotations", true, booleanFlag,
"true", NULL),
YAP_FLAG(READLINE_FLAG, "readline", true, booleanFlag, "false",
@ -389,6 +392,15 @@ vxu `on` consider `$` a lower case character.
enable the use of the readline library for console interactions, true by
default if readline was found. */
YAP_FLAG(REDEFINE_WARNINGS_FLAG, "redefine_warnings", true, booleanFlag,
"true", NULL), /**<
If _Value_ is unbound, tell whether warnings for procedures defined
in several different files are `on` or
`off`. If _Value_ is bound to `on` enable these warnings,
and if it is bound to `off` disable them. The default for YAP is
`off`, unless we are in `sicstus` or `iso` mode.
*/
YAP_FLAG(REPORT_ERROR_FLAG, "report_error", true, booleanFlag, "true",
NULL),
YAP_FLAG(RESOURCE_DATABASE_FLAG, "resource_database", false, isatom,
@ -424,6 +436,15 @@ vxu `on` consider `$` a lower case character.
/**< `single_quoted text is usuallly interpreted as atoms. This flagTerm
allows other inerpretations such as strings_contains_strings */
YAP_FLAG(SINGLE_VAR_WARNINGS_FLAG, "single_var_warnings", true, booleanFlag,
"true", NULL), /**<
If `true` (default `true`) YAP checks for singleton
variables when loading files. A singleton variable is a
variable that appears ony once in a clause. The name
must start with a capital letter, variables whose name
starts with underscore are never considered singleton.
*/
YAP_FLAG(SIGNALS_FLAG, "signals", true, booleanFlag, "true", NULL),
/**< `signals`
@ -482,8 +503,7 @@ vxu `on` consider `$` a lower case character.
*/
YAP_FLAG(THREADS_FLAG, "threads", false, ro, "MAX_THREADS", NULL),
YAP_FLAG(TIMEZONE_FLAG, "timezone", false, ro, "18000", NULL),
YAP_FLAG(TOPLEVEL_HOOK_FLAG, "toplevel_hook", true,
booleanFlag, "true",
YAP_FLAG(TOPLEVEL_HOOK_FLAG, "toplevel_hook", true, booleanFlag, "true",
NULL),
/**< `toplevel_hook `
@ -493,7 +513,7 @@ vxu `on` consider `$` a lower case character.
backtracked into.
*/
YAP_FLAG(TOPLEVEL_PRINT_ANON_FLAG, "toplevel_print_anon", true, booleanFlag,
YAP_FLAG(TOPLEVEL_PRINT_ANON_FLAG, "toplevel_print_anon", true, booleanFlag,
"true", NULL),
YAP_FLAG(TOPLEVEL_PRINT_OPTIONS_FLAG, "toplevel_print_options", true,
list_option, "[quoted(true),numbervars(true),portrayed(true)]",
@ -527,9 +547,9 @@ vxu `on` consider `$` a lower case character.
are `silent`, `warning` and `error`. The first two create the flag
on-the-fly, with `warning` printing a message. The value `error` is
consistent with ISO: it raises an existence error and does not create the
flag. See also `create_prolog_flag/3`. The default is`error`, and developers
are encouraged to use `create_prolog_flag/3` to create flags for their
library.
flag. See also `create_prolog_flag/3`. The default is`error`, and
developers are encouraged to use `create_prolog_flag/3` to create flags for
their library.
*/
YAP_FLAG(UNKNOWN_FLAG, "unknown", true, isatom, "error", Yap_unknown),
/**< `unknown is iso`

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

@ -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 2015- *
* *
**************************************************************************
* *
* File: YapLFlagInfo.h *
* Last rev: *
* mods: *
* comments: local flag enumeration. *
* *
*************************************************************************/
* *
* YAP Prolog *
* *
* Yap Prolog was developed at NCCUP - Universidade do Porto *
* *
* Copyright L.Damas, V.S.Costa and Universidade do Porto 2015- *
* *
**************************************************************************
* *
* File: YapLFlagInfo.h * Last rev:
** mods: * comments: local flag enumeration. *
* *
*************************************************************************/
/** @file YapLFlagInfo.h
@ -30,74 +28,75 @@
START_LOCAL_FLAGS
/** + `autoload`: set the system to look for undefined procedures */
YAP_FLAG( AUTOLOAD_FLAG, "autoload", true, booleanFlag, "false" , NULL ),
/** + `read-only flag, that tells if Prolog is in an inner top-level */
YAP_FLAG( BREAK_LEVEL_FLAG, "break_level", true, nat, "0" , NULL ),
YAP_FLAG( CALL_COUNTING_FLAG, "call_counting", true, booleanFlag, "true" , NULL ), /** + `call_counting`
/** + `autoload`: set the system to look for undefined procedures */
YAP_FLAG(AUTOLOAD_FLAG, "autoload", true, booleanFlag, "false", NULL),
/** + `read-only flag, that tells if Prolog is in an inner top-level */
YAP_FLAG(BREAK_LEVEL_FLAG, "break_level", true, nat, "0", NULL),
YAP_FLAG(CALL_COUNTING_FLAG, "call_counting", true, booleanFlag, "true",
NULL), /** + `call_counting`
Predicates compiled with this flag set maintain a counter on the numbers of proceduree calls and of retries. These counters are decreasing counters, and they can be used as timers. Three counters are available:
Predicates compiled with this flag set maintain a counter
on the numbers of proceduree calls and of retries. These counters
are decreasing counters, and they can be used as timers. Three
counters are available:
calls: number of predicate calls since execution started or since system was reset;
retries: number of retries for predicates called since execution started or since counters were reset;
calls_and_retries: count both on predicate calls and retries.
These counters can be used to find out how many calls a certain goal takes to execute. They can also be force the computatiom yp
stopping.
calls: number of predicate calls since execution started or
since system was reset; retries: number of retries for predicates
called since execution started or since counters were reset;
calls_and_retries: count both on predicate calls and
retries. These counters can be used to find out how many calls a
certain goal takes to execute. They can also be force the
computatiom yp stopping.
If `on` `fileerrors` is `on`, if `off` (default)
`fileerrors` is disabled.
*/
YAP_FLAG( ENCODING_FLAG, "encoding", true, isatom, "utf-8" , getenc ),
YAP_FLAG( FILEERRORS_FLAG, "fileerrors", true, booleanFlag, "true" , NULL ), /** + `fileerrors`
If `on` `fileerrors` is `on`, if `off` (default)
`fileerrors` is disabled.
*/
YAP_FLAG(ENCODING_FLAG, "encoding", true, isatom, "utf-8", getenc),
YAP_FLAG(FILEERRORS_FLAG, "fileerrors", true, booleanFlag, "true",
NULL), /** + `fileerrors`
If `on` `fileerrors` is `on`, if `off` (default)
`fileerrors` is disabled.
*/
YAP_FLAG( LANGUAGE_MODE_FLAG, "language_mode", true, isatom, "yap" , NULL ), /** + `language_mode`
If `on` `fileerrors` is `on`, if `off` (default)
`fileerrors` is disabled.
*/
YAP_FLAG(LANGUAGE_MODE_FLAG, "language_mode", true, isatom, "yap",
NULL), /** + `language_mode`
wweter native mode or trying to emulate a different Prolog.
*/
YAP_FLAG( REDEFINE_WARNINGS_FLAG, "redefine_warnings", true, booleanFlag, "true" , NULL ), /** + `redefine_warnings `
wweter native mode or trying to emulate a different Prolog.
*/
YAP_FLAG(STACK_DUMP_ON_ERROR_FLAG, "stack_dump_on_error", true, booleanFlag,
"true", NULL), /** + `stack_dump_on_error `
If _Value_ is unbound, tell whether warnings for procedures defined
in several different files are `on` or
`off`. If _Value_ is bound to `on` enable these warnings,
and if it is bound to `off` disable them. The default for YAP is
`off`, unless we are in `sicstus` or `iso` mode.
*/
YAP_FLAG( SINGLE_VAR_WARNINGS_FLAG, "single_var_warnings", true, booleanFlag, "true" , NULL ), /** + `single_var_warnings`
If `true` (default `true`) YAP checks for singleton variables when loading files. A singleton variable is a variable that appears ony once in a clause. The name must start with a capital letter, variables whose name starts with underscore are never considered singleton.
*/
YAP_FLAG( STACK_DUMP_ON_ERROR_FLAG, "stack_dump_on_error", true, booleanFlag, "false" , NULL ), /** + `stack_dump_on_error `
If `true` show a stack dump when YAP finds an error. The default is
If `true` show a stack dump when YAP finds an error. The default is
`off`.
*/
YAP_FLAG( STREAM_TYPE_CHECK_FLAG, "stream_type_check", true, isatom, "loose" , NULL ),
YAP_FLAG( SYNTAX_ERRORS_FLAG, "syntax_errors", true, synerr, "error" , NULL ), /** + `syntax_errors`
*/
YAP_FLAG(STREAM_TYPE_CHECK_FLAG, "stream_type_check", true, isatom, "loose",
NULL),
YAP_FLAG(SYNTAX_ERRORS_FLAG, "syntax_errors", true, synerr, "error",
NULL), /** + `syntax_errors`
Control action to be taken after syntax errors while executing read/1,
Control action to be taken after syntax errors while executing read/1,
`read/2`, or `read_term/3`:
+ `dec10`
+ `dec10`
Report the syntax error and retry reading the term.
+ `fail`
+ `fail`
Report the syntax error and fail.
+ `error`
+ `error`
Report the syntax error and generate an error (default).
+ `quiet`
+ `quiet`
Just fail
*/
YAP_FLAG( TYPEIN_MODULE_FLAG, "typein_module", true, isatom, "user" , typein ), /** + `typein_module `
*/
YAP_FLAG(TYPEIN_MODULE_FLAG, "typein_module", true, isatom, "user",
typein), /** + `typein_module `
If bound, set the current working or type-in module to the argument,
If bound, set the current working or type-in module to the argument,
which must be an atom. If unbound, unify the argument with the current
working module.
*/
YAP_FLAG( USER_ERROR_FLAG, "user_error", true, stream, "user_error" , set_error_stream ), /** + `user_error1`
*/
YAP_FLAG(USER_ERROR_FLAG, "user_error", true, stream, "user_error",
set_error_stream), /** + `user_error1`
If the second argument is bound to a stream, set user_error to
If the second argument is bound to a stream, set user_error to
this stream. If the second argument is unbound, unify the argument with
the current user_error stream.
By default, the user_error stream is set to a stream
@ -105,30 +104,32 @@ corresponding to the Unix `stderr` stream.
The next example shows how to use this flag:
~~~{.prolog}
?- open( '/dev/null', append, Error,
[alias(mauri_tripa)] ).
?- open( '/dev/null', append, Error,
[alias(mauri_tripa)] ).
Error = '$stream'(3) ? ;
Error = '$stream'(3) ? ;
no
?- set_prolog_flag(user_error, mauri_tripa).
no
?- set_prolog_flag(user_error, mauri_tripa).
close(mauri_tripa).
close(mauri_tripa).
yes
?-
yes
?-
~~~
We execute three commands. First, we open a stream in write mode and
We execute three commands. First, we open a stream in write mode and
give it an alias, in this case `mauri_tripa`. Next, we set
user_error to the stream via the alias. Note that after we did so
prompts from the system were redirected to the stream
`mauri_tripa`. Last, we close the stream. At this point, YAP
automatically redirects the user_error alias to the original
`stderr`.
*/
YAP_FLAG( USER_INPUT_FLAG, "user_input", true, stream, "user_input" , set_input_stream ),
YAP_FLAG( USER_OUTPUT_FLAG, "user_output", true, stream, "user_output" , set_output_stream ),
*/
YAP_FLAG(USER_INPUT_FLAG, "user_input", true, stream, "user_input",
set_input_stream),
YAP_FLAG(USER_OUTPUT_FLAG, "user_output", true, stream, "user_output",
set_output_stream),
END_LOCAL_FLAGS
END_LOCAL_FLAGS
/// @}
/// @}

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

@ -35,6 +35,7 @@ extern int Yap_HasOp(Atom);
extern struct operator_entry *
Yap_GetOpPropForAModuleHavingALock(struct AtomEntryStruct *, Term);
extern Atom Yap_LookupAtom(const char *);
extern Atom Yap_AtomInUse(const char *atom);
extern Atom Yap_ULookupAtom(const unsigned char *);
extern Atom Yap_LookupAtomWithLength(const char *, size_t);
extern Atom Yap_FullLookupAtom(const char *);

175
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 char *Yap_TermToBuffer(Term t, encoding_t encoding, 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

@ -32,6 +32,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);
@ -264,7 +265,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,6 +454,7 @@
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);
FunctorAtFoundOne = Yap_MkFunctor(AtomFoundVar,2);

View File

@ -32,6 +32,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);
@ -453,6 +454,7 @@
FunctorArrayEntry = FuncAdjust(FunctorArrayEntry);
FunctorArrow = FuncAdjust(FunctorArrow);
FunctorDoubleArrow = FuncAdjust(FunctorDoubleArrow);
FunctorAs = FuncAdjust(FunctorAs);
FunctorAssert1 = FuncAdjust(FunctorAssert1);
FunctorAssert = FuncAdjust(FunctorAssert);
FunctorAtFoundOne = FuncAdjust(FunctorAtFoundOne);

View File

@ -32,6 +32,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;
@ -461,6 +462,8 @@ 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;

View File

@ -1,7 +1,7 @@
#
# FindLibR.cmake
#
# Copyright (C) 2009-11 by RStudio, Inc.
# Copyright (C) 2009-18 by RStudio, Inc.
#
# This program is licensed to you under the terms of version 3 of the
# GNU Affero General Public License. This program is distributed WITHOUT
@ -21,11 +21,24 @@
if(APPLE)
find_library(LIBR_LIBRARIES R)
if(LIBR_LIBRARIES)
if(LIBR_LIBRARIES MATCHES ".*\\.framework")
set(LIBR_HOME "${LIBR_LIBRARIES}/Resources" CACHE PATH "R home directory")
set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory")
set(LIBR_DOC_DIR "${LIBR_HOME}/doc" CACHE PATH "R doc directory")
set(LIBR_EXECUTABLE "${LIBR_HOME}/R" CACHE PATH "R executable")
else()
get_filename_component(_LIBR_LIBRARIES "${LIBR_LIBRARIES}" REALPATH)
get_filename_component(_LIBR_LIBRARIES_DIR "${_LIBR_LIBRARIES}" PATH)
set(LIBR_EXECUTABLE "${_LIBR_LIBRARIES_DIR}/../bin/R")
execute_process(
COMMAND ${LIBR_EXECUTABLE} "--slave" "--vanilla" "-e" "cat(R.home())"
OUTPUT_VARIABLE LIBR_HOME
)
set(LIBR_HOME ${LIBR_HOME} CACHE PATH "R home directory")
set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory")
set(LIBR_DOC_DIR "${LIBR_HOME}/doc" CACHE PATH "R doc directory")
set(LIBR_LIB_DIR "${LIBR_HOME}/lib" CACHE PATH "R lib directory")
endif()
# detection for UNIX & Win32
@ -103,12 +116,15 @@ else()
set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory")
set(LIBR_DOC_DIR "${LIBR_HOME}/doc" CACHE PATH "R doc directory")
# set library hint path based on whether we are doing a special session 64 build
if(LIBR_FIND_WINDOWS_64BIT)
set(LIBRARY_ARCH_HINT_PATH "${LIBR_HOME}/bin/x64")
else()
set(LIBRARY_ARCH_HINT_PATH "${LIBR_HOME}/bin/i386")
endif()
# set library hint path for 64-bit build
set(LIBR_ARCH "x64")
set(LIBRARY_ARCH_HINT_PATH "${LIBR_HOME}/bin/x64")
# call dll2lib.R to ensure export files are generated
execute_process(
COMMAND "${LIBR_HOME}/bin/${LIBR_ARCH}/Rscript.exe" "dll2lib.R"
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tools"
RESULT_VARIABLE LIBR_DLL2LIB_RESULT)
endif()
@ -173,6 +189,7 @@ find_package_handle_standard_args(LibR DEFAULT_MSG
if(LIBR_FOUND)
message(STATUS "Found R: ${LIBR_HOME}")
get_filename_component(LIBR_BIN_DIR "${LIBR_EXECUTABLE}" PATH CACHE)
endif()
# mark low-level variables from FIND_* calls as advanced

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

@ -203,6 +203,8 @@ typedef struct yap_boot_params {
const char *INPUT_STARTUP;
//> bootstrapping mode: YAP is not properly installed
bool install;
//> jupyter mode: YAP is in space
bool jupyter;
//> generats a saved space at this path
const char *OUTPUT_STARTUP;
//> if NON-0, minimal size for Heap or Code Area

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

@ -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

@ -70,7 +70,6 @@ Moyle. All rights reserved.
static atom_t ATOM_nil;
extern int PL_unify_termv(term_t l, va_list args);
extern X_API Atom YAP_AtomFromSWIAtom(atom_t at);
extern X_API atom_t YAP_SWIAtomFromAtom(Atom at);
@ -222,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;
}
@ -818,6 +818,14 @@ X_API int PL_unify_bool(term_t t, int a) {
return Yap_unify(Yap_GetFromSlot(t), iterm);
}
X_API int PL_put_bool(term_t t, int a) {
CACHE_REGS
CELL *pt = Yap_AddressFromHandle( t );
Term iterm = (a ? MkAtomTerm(AtomTrue) : MkAtomTerm(AtomFalse));
*pt = iterm;
return true;
}
#if USE_GMP
/*******************************
@ -1273,7 +1281,7 @@ YAP: NO EQUIVALENT */
X_API int PL_raise_exception(term_t exception) {
CACHE_REGS
LOCAL_Error_TYPE = THROW_EVENT;
LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(Yap_GetFromHandle(exception), LOCAL_encoding, TermNil);
LOCAL_ActiveError->errorGoal = Yap_TermToBuffer(Yap_GetFromHandle(exception), 0);
//Yap_PutException(Yap_GetFromSlot(exception));
Yap_RaiseException();
return 0;
@ -1319,9 +1327,9 @@ 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 FALSE;
return true;
}
Yap_AtomIncreaseHold(at);
return Yap_unify(Yap_GetFromSlot(t), MkAtomTerm(at));
@ -1444,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)
@ -1541,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

@ -85,13 +85,16 @@ pred_name(Macro, Arity, _ , Name) :-
transformation_id(Id),
atomic_concat(['$$$ for ',Macro,'/',Arity,', line ',Line,' in ',File,' ',Id], Name).
pred_name(Macro, Arity, _ , Name) :-
transformation_id(Id),
transformation_id(Id),
stop_low_level_trace,
atomic_concat(['$$$__expansion__ for ',Macro,'/',Arity,' ',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

@ -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

@ -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

@ -221,16 +221,16 @@ Yap_SetAlias (Atom arg, int sno)
CACHE_REGS
AliasDesc aliasp = GLOBAL_FileAliases, aliasp_max = GLOBAL_FileAliases+GLOBAL_NOfFileAliases;
while (aliasp < aliasp_max) {
// replace alias
if (aliasp->name == arg) {
aliasp->alias_stream = sno;
if (arg == AtomUserIn)
LOCAL_c_input_stream = sno;
if (arg == AtomUserOut)
LOCAL_c_output_stream = sno;
if (arg == AtomUserErr)
LOCAL_c_error_stream = sno;
while (aliasp < aliasp_max) {
// replace alias
if (aliasp->name == arg) {
aliasp->alias_stream = sno;
return;
}
aliasp++;
@ -317,16 +317,16 @@ ExistsAliasForStream (int sno, Atom al)
while (aliasp < aliasp_max) {
if (aliasp->alias_stream == sno && aliasp->name == al) {
if (al == AtomUserIn) {
LOCAL_c_input_stream = StdInStream;
aliasp->alias_stream = StdInStream;
}
LOCAL_c_input_stream = sno;
aliasp->alias_stream = sno;
} else
if (al == AtomUserOut) {
LOCAL_c_output_stream = StdOutStream;
aliasp->alias_stream = StdOutStream;
LOCAL_c_output_stream = sno;
aliasp->alias_stream = sno;
}
if (al == AtomUserErr) {
LOCAL_c_error_stream = StdErrStream;
aliasp->alias_stream = StdErrStream;
LOCAL_c_error_stream = sno;
aliasp->alias_stream = sno;
}
return true;
}
@ -387,6 +387,12 @@ Yap_AddAlias (Atom arg, int sno)
AliasDesc aliasp = GLOBAL_FileAliases, aliasp_max = GLOBAL_FileAliases+GLOBAL_NOfFileAliases;
if (arg == AtomUserIn)
LOCAL_c_input_stream = sno;
else if (arg == AtomUserOut)
LOCAL_c_output_stream = sno;
else if (arg == AtomUserErr)
LOCAL_c_error_stream = sno;
while (aliasp < aliasp_max) {
if (aliasp->name == arg) {
aliasp->alias_stream = sno;
@ -394,6 +400,7 @@ Yap_AddAlias (Atom arg, int sno)
}
aliasp++;
}
/* we have not found an alias neither a hole */
if (aliasp == GLOBAL_FileAliases+GLOBAL_SzOfFileAliases)
ExtendAliasArray();

View File

@ -990,16 +990,11 @@ leaving the current stream position unaltered.
*/
static Int peek_code(USES_REGS1) { /* at_end_of_stream */
/* the next character is a EOF */
int sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "peek/2");
int sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "peek_code/2");
Int ch;
if (sno < 0)
return FALSE;
if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_INPUT_TEXT_STREAM, ARG1, "peek_code/2");
return FALSE;
}
if ((ch = Yap_peek(sno)) < 0) {
#ifdef PEEK_EOF
UNLOCK(GLOBAL_Stream[sno].streamlock);

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

@ -203,7 +203,9 @@ int Yap_open_buf_write_stream(encoding_t enc, memBufSource src) {
return -1;
st = GLOBAL_Stream + sno;
st->status = Output_Stream_f | InMemory_Stream_f | FreeOnClose_Stream_f;
st->status = Output_Stream_f | InMemory_Stream_f;
if (src)
st->status |= FreeOnClose_Stream_f;
st->linepos = 0;
st->charcount = 0;
st->linecount = 1;
@ -211,16 +213,12 @@ 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);
st->status |= Seekable_Stream_f;
#else
st->file = fmemopen((void *)st->nbuf, st->nsize, "w");
if (!st->nbuf) {
return -1;
}
st->file = fmemopen((void *)st->nbuf, st->nsize, "w+");
#endif
Yap_DefaultStreamOps(st);
UNLOCK(st->streamlock);
@ -257,35 +255,44 @@ open_mem_write_stream(USES_REGS1) /* $open_mem_write_stream(-Stream) */
* by other writes..
*/
char *Yap_MemExportStreamPtr(int sno) {
char *s;
if (fflush(GLOBAL_Stream[sno].file) == 0) {
s = GLOBAL_Stream[sno].nbuf;
// s[fseek(GLOBAL_Stream[sno].file, 0, SEEK_END)] = '\0';
return s;
FILE *f = GLOBAL_Stream[sno].file;
if (fflush(f) < 0) {
return NULL;
}
return NULL;
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);
#endif
buf[len] = '\0';
return buf;
}
static Int peek_mem_write_stream(
USES_REGS1) { /* '$peek_mem_write_stream'(+GLOBAL_Stream,?S0,?S) */
Int sno =
Yap_CheckStream(ARG1, (Output_Stream_f | InMemory_Stream_f), "close/2");
Int i;
Term tf = ARG2;
CELL *HI;
const char *ptr;
char *ptr;
int ch;
if (sno < 0)
return (FALSE);
restart:
char *p = ptr = Yap_MemExportStreamPtr(sno);
restart:
HI = HR;
if (fflush(GLOBAL_Stream[sno].file) == 0) {
i = fseek(GLOBAL_Stream[sno].file, 0, SEEK_END);
ptr = GLOBAL_Stream[sno].nbuf;
}
while (i > 0) {
--i;
tf = MkPairTerm(MkIntTerm(ptr[i]), tf);
while ((ch = *p++)) {
HR[0] = MkIntTerm(ch);
HR[1] = AbsPair(HR+2);
HR += 2;
if (HR + 1024 >= ASP) {
UNLOCK(GLOBAL_Stream[sno].streamlock);
HR = HI;
@ -294,14 +301,14 @@ restart:
Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage);
return (FALSE);
}
i = GLOBAL_Stream[sno].u.mem_string.pos;
tf = ARG2;
LOCK(GLOBAL_Stream[sno].streamlock);
goto restart;
}
}
HR[-1] = tf;
UNLOCK(GLOBAL_Stream[sno].streamlock);
return (Yap_unify(ARG3, tf));
free(ptr);
return (Yap_unify(ARG3, AbsPair(HI)));
}
void Yap_MemOps(StreamDesc *st) {

View File

@ -1129,12 +1129,14 @@ static void check_bom(int sno, StreamDesc *st) {
bool Yap_initStream(int sno, FILE *fd, const char *name, const char *io_mode,
Term file_name, encoding_t encoding, stream_flags_t flags,
void *vfs) {
// fprintf(stderr,"+ %s --> %d\n", name, sno);
StreamDesc *st = &GLOBAL_Stream[sno];
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "init %s %s:%s stream <%d>",
io_mode, CurrentModule == 0? "prolog": RepAtom(AtomOfTerm(CurrentModule))->StrOfAE,
name,
sno);
if (io_mode == NULL)
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "init %s %s:%s stream <%d>", io_mode,
CurrentModule == 0 ? "prolog"
: RepAtom(AtomOfTerm(CurrentModule))->StrOfAE,
name, sno);
if (io_mode == NULL)
Yap_Error(PERMISSION_ERROR_NEW_ALIAS_FOR_STREAM, MkIntegerTerm(sno),
"File opened with NULL Permissions");
if (strchr(io_mode, 'a')) {
@ -1231,13 +1233,10 @@ typedef enum open_enum_choices { OPEN_DEFS() } open_choices_t;
static const param_t open_defs[] = {OPEN_DEFS()};
#undef PAR
static bool fill_stream(int sno, StreamDesc *st, Term tin, const char *io_mode, Term user_name,
encoding_t enc)
{
static bool fill_stream(int sno, StreamDesc *st, Term tin, const char *io_mode,
Term user_name, encoding_t enc) {
struct vfs *vfsp = NULL;
const char *fname;
if (IsAtomTerm(tin))
fname = RepAtom(AtomOfTerm(tin))->StrOfAE;
@ -1289,9 +1288,10 @@ static bool fill_stream(int sno, StreamDesc *st, Term tin, const char *io_mode,
return false;
}
buf = pop_output_text_stack(i, buf);
Atom nat = Yap_LookupAtom(Yap_StrPrefix(buf,32));
Atom nat = Yap_LookupAtom(Yap_StrPrefix(buf, 32));
sno = Yap_open_buf_read_stream(buf, strlen(buf) + 1, &LOCAL_encoding,
MEM_BUF_MALLOC, nat, MkAtomTerm(NameOfFunctor(f)));
MEM_BUF_MALLOC, nat,
MkAtomTerm(NameOfFunctor(f)));
return Yap_OpenBufWriteStream(PASS_REGS1);
}
} else if (!strcmp(RepAtom(NameOfFunctor(f))->StrOfAE, "popen")) {
@ -1363,9 +1363,9 @@ static Int do_open(Term file_name, Term t2, Term tlist USES_REGS) {
} else {
open_mode = AtomOfTerm(t2);
}
/* get options */
xarg *args = Yap_ArgListToVector(tlist, open_defs, OPEN_END,
DOMAIN_ERROR_OPEN_OPTION);
/* get options */
xarg *args =
Yap_ArgListToVector(tlist, open_defs, OPEN_END, DOMAIN_ERROR_OPEN_OPTION);
if (args == NULL) {
if (LOCAL_Error_TYPE != YAP_NO_ERROR) {
Yap_Error(LOCAL_Error_TYPE, tlist, "option handling in open/3");
@ -1374,7 +1374,7 @@ static Int do_open(Term file_name, Term t2, Term tlist USES_REGS) {
}
/* done */
st->status = 0;
const char *s_encoding;
const char *s_encoding;
if (args[OPEN_ENCODING].used) {
tenc = args[OPEN_ENCODING].tvalue;
s_encoding = RepAtom(AtomOfTerm(tenc))->StrOfAE;
@ -1435,14 +1435,14 @@ static Int do_open(Term file_name, Term t2, Term tlist USES_REGS) {
"type is ~a, must be one of binary or text", t);
}
}
st = &GLOBAL_Stream[sno];
if (!fill_stream(sno, st, file_name,io_mode,st->user_name,st->encoding)) {
if (!fill_stream(sno, st, file_name, io_mode, st->user_name, st->encoding)) {
return false;
}
if (args[OPEN_BOM].used) {
if (args[OPEN_BOM].used) {
if (args[OPEN_BOM].tvalue == TermTrue) {
avoid_bom = false;
needs_bom = true;
@ -1670,9 +1670,8 @@ int Yap_OpenStream(Term tin, const char *io_mode, Term user_name,
st = GLOBAL_Stream + sno;
// fname = Yap_VF(fname);
if (fill_stream(sno, st, tin,io_mode,user_name,enc))
return sno;
if (fill_stream(sno, st, tin, io_mode, user_name, enc))
return sno;
return -1;
}
@ -1867,13 +1866,13 @@ static Int always_prompt_user(USES_REGS1) {
return (TRUE);
}
/** @pred close(+ _S_) is iso
/** @pred close(+ _S_) is iso
Closes the stream _S_. If _S_ does not stand for a stream
currently opened an error is reported. The streams user_input,
user_output, and user_error can never be closed.
*/
static Int close1(USES_REGS1) { /* '$close'(+GLOBAL_Stream) */
static Int close1(USES_REGS1) { /* '$close'(+GLOBAL_Stream) */
int sno = CheckStream(
ARG1, (Input_Stream_f | Output_Stream_f | Socket_Stream_f), "close/2");
if (sno < 0)

File diff suppressed because it is too large Load Diff

View File

@ -683,7 +683,7 @@ static xarg *generate_property(int sno, Term t2,
}
static Int cont_stream_property(USES_REGS1) { /* current_stream */
bool det;
bool det = false;
xarg *args;
int i = IntOfTerm(EXTRA_CBACK_ARG(2, 1));
stream_property_choices_t p = STREAM_PROPERTY_END;
@ -705,7 +705,7 @@ static Int cont_stream_property(USES_REGS1) { /* current_stream */
if (LOCAL_Error_TYPE != YAP_NO_ERROR) {
if (LOCAL_Error_TYPE == DOMAIN_ERROR_GENERIC_ARGUMENT)
LOCAL_Error_TYPE = DOMAIN_ERROR_STREAM_PROPERTY_OPTION;
Yap_Error(LOCAL_Error_TYPE, t2, NULL);
Yap_ThrowError(LOCAL_Error_TYPE, t2, NULL);
return false;
}
cut_fail();
@ -714,16 +714,17 @@ static Int cont_stream_property(USES_REGS1) { /* current_stream */
if (IsAtomTerm(args[STREAM_PROPERTY_ALIAS].tvalue)) {
// one solution only
i = Yap_CheckAlias(AtomOfTerm(args[STREAM_PROPERTY_ALIAS].tvalue));
free(args) UNLOCK(GLOBAL_Stream[i].streamlock);
UNLOCK(GLOBAL_Stream[i].streamlock);
if (i < 0 || !Yap_unify(ARG1, Yap_MkStream(i))) {
free(args);
cut_fail();
}
cut_succeed();
det = true;
}
LOCK(GLOBAL_Stream[i].streamlock);
rc = do_stream_property(i, args PASS_REGS);
UNLOCK(GLOBAL_Stream[i].streamlock);
if (IsVarTerm(t1)) {
if (!det && IsVarTerm(t1)) {
if (rc)
rc = Yap_unify(ARG1, Yap_MkStream(i));
if (p == STREAM_PROPERTY_END) {
@ -743,7 +744,7 @@ static Int cont_stream_property(USES_REGS1) { /* current_stream */
}
} else {
// done
det = (p == STREAM_PROPERTY_END);
det = det || (p == STREAM_PROPERTY_END);
}
free(args);
if (rc) {
@ -998,7 +999,8 @@ static void CloseStream(int sno) {
// __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "close stream <%d>",
// sno);
VFS_t *me;
if ((me = GLOBAL_Stream[sno].vfs) != NULL &&
//fprintf( stderr, "- %d\n",sno);
if ((me = GLOBAL_Stream[sno].vfs) != NULL &&
GLOBAL_Stream[sno].file == NULL) {
if (me->close) {
me->close(sno);
@ -1549,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);
@ -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;
@ -672,7 +672,7 @@ static Int term_to_string(USES_REGS1) {
Term t2 = Deref(ARG2), rc = false, t1 = Deref(ARG1);
const char *s;
if (IsVarTerm(t2)) {
s = Yap_TermToBuffer(ARG1, LOCAL_encoding, Quote_illegal_f | Handle_vars_f);
s = Yap_TermToBuffer(t1, Quote_illegal_f | Handle_vars_f);
if (!s || !MkStringTerm(s)) {
Yap_Error(RESOURCE_ERROR_HEAP, t1,
"Could not get memory from the operating system");
@ -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), LOCAL_encoding,
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,6 +711,25 @@ static Int term_to_atom(USES_REGS1) {
Yap_unify(rc, ARG1);
}
char *Yap_TermToBuffer(Term t, int flags) {
CACHE_REGS
int sno = Yap_open_buf_write_stream(LOCAL_encoding, flags);
if (sno < 0)
return NULL;
if (t == 0)
return NULL;
else
t = Deref(t);
GLOBAL_Stream[sno].encoding = LOCAL_encoding;
GLOBAL_Stream[sno].status |= CloseOnException_Stream_f;
Yap_plwrite(t, GLOBAL_Stream + sno, 0, flags, GLOBAL_MaxPriority);
char *new = Yap_MemExportStreamPtr(sno);
Yap_CloseStream(sno);
return new;
}
void Yap_InitWriteTPreds(void) {
Yap_InitCPred("write_term", 2, write_term2, SyncPredFlag);
Yap_InitCPred("write_term", 3, write_term3, SyncPredFlag);

View File

@ -22,8 +22,6 @@
#undef HAVE_LIBREADLINE
#endif
#include "YapStreams.h"
#include <stdio.h>
#include <wchar.h>
@ -89,7 +87,7 @@ extern int Yap_GetCharForSIGINT(void);
extern Int Yap_StreamToFileNo(Term);
extern int Yap_OpenStream(Term tin, const char* io_mode, Term user_name, encoding_t enc);
extern int Yap_FileStream(FILE*, char *, Term, int, VFS_t *);
extern char *Yap_TermToBuffer(Term t, encoding_t encoding, int flags);
extern char *Yap_TermToBuffer(Term t, int flags);
extern char *Yap_HandleToString(yhandle_t l, size_t sz, size_t *length,
encoding_t *encoding, int flags);
extern int Yap_GetFreeStreamD(void);
@ -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

File diff suppressed because it is too large Load Diff

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

@ -5,8 +5,8 @@ set (PYTHON_SOURCES python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c pyio.c)
set (PYTHON_HEADERS py4yap.h)
set (CMAKE_POSITION_INDEPENDENT_CODE TRUE)
include_directories( ${CMAKE_BINARY_DIR} ${PYTHON_INCLUDE_DIRS}
${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/os )
include_directories( BEFORE ${PYTHON_INCLUDE_DIRS} ${CMAKE_BINARY_DIR}
${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,4 +1,5 @@
#include "Yap.h"
#include "py4yap.h"
@ -13,6 +14,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 +104,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;
@ -107,12 +160,11 @@ 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 (t == 0) {
if (yt == 0) {
Yap_ThrowError(SYSTEM_ERROR_INTERNAL, yt, "in term_to_python");
}
PyObject *out = PyTuple_New(1);
@ -136,7 +188,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;
}
@ -150,19 +202,18 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
} else {
return CHECKNULL(t, NULL);
}
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);
} else
#endif
{
// char *p = malloc(strlen(s)+1);
// strcpy(p, s);
PyObject *pobj = PyUnicode_FromString(s);
Py_IncRef(pobj);
return CHECKNULL(t, pobj);
}
#endif
// char *p = malloc(strlen(s)+1);
// strcpy(p, s);
Py_IncRef(pobj);
return CHECKNULL(t, pobj);
} break;
case PL_INTEGER: {
int64_t j;
@ -187,37 +238,30 @@ 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);
PyObject *no = find_term_obj(o, &t0, false);
if (no == o)
return NULL;
return term_to_python(t, eval, no, cvt);
return yap_to_python(t0, eval, no, cvt);
}
} else {
{
@ -263,11 +307,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));
@ -299,7 +343,10 @@ 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;
PyObject_Print(ys,stderr,0);fprintf(stderr, "--- \n");
CHECK_CALL(ys, PyTuple_New(0), NULL);
return rc;
}
if (fun == FUNCTOR_complex2) {
term_t targ = PL_new_term_ref();
@ -344,7 +391,7 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
AOK(PL_get_arg(1, t, t), NULL);
if (!(dict = PyDict_New()))
return NULL;
Py_INCREF(dict);
Py_INCREF(dict);
DebugPrintf("Dict %p\n", dict);
while (PL_is_functor(t, FUNCTOR_comma2)) {
@ -361,6 +408,7 @@ PyObject *term_to_python(term_t t, bool eval, PyObject *o, bool cvt) {
return dict;
}
AOK(PL_get_name_arity(t, &name, &arity), NULL);
if (name == ATOM_t) {
int i;
rc = PyTuple_New(arity);
@ -406,8 +454,8 @@ PyObject *deref_term_to_python(term_t t) {
// am\n");
YAP_Term yt = YAP_GetFromSlot(t);
if (YAP_IsVarTerm(yt)) {
char s[32];
char *o = YAP_WriteBuffer(yt, s, 31, 0);
char b[1024];
char *o = YAP_WriteBuffer(yt, b, 1023, 0);
PyObject *p = PyUnicode_FromString(o);
return p;
}

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);
@ -46,177 +47,155 @@ foreign_t assign_to_symbol(term_t t, PyObject *e) {
PyObject *dic;
if (!lookupPySymbol(s, NULL, &dic))
dic = py_Main;
Py_INCREF(e);
Py_INCREF(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("
// >>***\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 (PyDict_GetItemString(py_Atoms, s))
// rc = rc && PL_unify_atom_chars(t, s);
// else
#if 0
if (false && Yap_AtomInUse(s))
rc = rc && PL_unify_atom_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));
else
#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++) {
if (!PL_get_arg(i + 1, t, to))
rc = false;
PyObject *p = PyTuple_GetItem(pVal, i);
if (p == NULL) {
PyErr_Clear();
p = Py_None;
}
rc = rc && python_to_term(p, to);
}
} else {
rc = false;
}
// fputs(" ||*** ",stderr); Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
// ||***\n",stderr);
return MkStringTerm(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;
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);
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;
term_t to = PL_new_term_ref(), ti = to;
int left = PyDict_Size(pVal);
PyObject *key, *value;
if (left == 0) {
rc = rc && PL_unify_atom(t, ATOM_curly_brackets);
} else {
while (PyDict_Next(pVal, &pos, &key, &value)) {
term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint,
tnew = PL_new_term_ref();
/* do something interesting with the values... */
if (!python_to_term(key, tkey)) {
continue;
}
if (!python_to_term(value, tval)) {
continue;
}
/* reuse */
tint = tkey;
if (!PL_cons_functor(tint, FUNCTOR_colon2, tkey, tval)) {
rc = false;
continue;
}
if (--left) {
if (!PL_cons_functor(tint, FUNCTOR_comma2, tint, tnew))
PL_reset_term_refs(tkey);
rc = false;
}
if (!PL_unify(ti, tint)) {
rc = false;
}
ti = tnew;
PL_reset_term_refs(tkey);
}
rc = rc && PL_unify(t, to);
}
} else {
rc = rc && repr_term(pVal, t);
*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 = PyTuple_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;
int left = PyDict_Size(pVal);
PyObject *key, *value;
Term f, *opt = &f, t;
if (left == 0) {
return repr_term(pVal);
} else {
while (PyDict_Next(pVal, &pos, &key, &value)) {
Term t0[2], to;
t0[0] = python_to_term__(key);
t0[1] = python_to_term__(value);
to = Yap_MkApplTerm(FunctorModule, 2, t0);
if (left--) {
t = Yap_MkNewApplTerm(FunctorComma, 2);
*opt = t;
CELL *pt = RepAppl(t) + 1;
pt[0] = to;
opt = pt + 1;
} else {
*opt = t = to;
}
}
return Yap_MkApplTerm(FunctorBraces, 1, &t);
}
}else {
return repr_term(pVal);
}
PL_reset_term_refs(to);
return rc;
}
X_API YAP_Term pythonToYAP(PyObject *pVal) {
foreign_t python_to_term(PyObject *pVal, term_t t) {
Term o = python_to_term__(pVal);
return YAP_Unify(o,YAP_GetFromSlot(t));
}
term_t t = PL_new_term_ref();
if (pVal == NULL || !python_to_term(pVal, t)) {
PL_reset_term_refs(t);
return 0;
}
YAP_Term tt = YAP_GetFromSlot(t);
PL_reset_term_refs(t);
//Py_DECREF(pVal);
return tt;
// extern bool Yap_do_low_level_trace;
X_API YAP_Term pythonToYAP(PyObject *pVal) {
// 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 t;
}
PyObject *py_Local, *py_Global;
@ -247,6 +226,17 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
return python_to_term(exp, t);
}
case PL_STRING: {
char *s = NULL;
size_t l;
PL_get_string_chars(t, &s,&l);
if (!context)
context = py_Main;
if (PyObject_SetAttrString(context, s, exp) == 0)
return true;
PyErr_Print();
return false;
}
case PL_ATOM: {
char *s = NULL;
PL_get_atom_chars(t, &s);
@ -257,7 +247,6 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
PyErr_Print();
return false;
}
case PL_STRING:
case PL_INTEGER:
case PL_FLOAT:
// domain or type erro?
@ -317,7 +306,7 @@ bool python_assign(term_t t, PyObject *exp, PyObject *context) {
if (PySequence_Check(o) && PyInt_Check(i)) {
long int j;
j = PyInt_AsLong(i);
return PySequence_SetItem(o, i, exp) == 0;
return PySequence_SetItem(o, i, exp) == 0;
}
#endif
if (PyDict_Check(o)) {

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,
@ -140,11 +149,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 +188,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 +236,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

@ -50,6 +50,11 @@ PyObject *PythonLookupSpecial(const char *s) {
return NULL;
}
static PyObject *builtin(const char *sp) {
PyObject *py_Builtin = PyEval_GetBuiltins();
return PyDict_GetItemString(py_Builtin, sp);
}
PyObject *lookupPySymbol(const char *sp, PyObject *pContext, PyObject **duc) {
PyObject *out = NULL;
if (!sp)
@ -113,6 +118,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
*
@ -596,7 +617,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 +680,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 +731,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 +767,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 +781,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) {
@ -953,17 +978,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));
lhs = term_to_python(targ, true, NULL, true);
AOK(PL_get_arg(2, t, targ), NULL);
rhs = term_to_python(targ, true, NULL, true);
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;
@ -971,19 +995,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);
@ -996,9 +1019,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;
@ -1006,7 +1029,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;
@ -1014,35 +1036,62 @@ 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);
PyDict_SetItem(pyDict, key, val);
} else {
indict = false;
pArgs = PyTuple_New(i);
}
}
DebugPrintf("Tuple %p\n", pyDict);
// 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;
@ -1055,23 +1104,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);
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,39 @@ 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_Builtins, "input");
if (pystream == NULL) {
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, NULL);
} else {
PyObject *readl = PyObject_GetAttrString(s->u.private_data, "readline");
user_line = PyObject_CallFunction(readl, NULL);
}
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 = myrl_line;
return true;
}
@ -156,16 +169,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 +201,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,13 +1,20 @@
#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.
fprintf(stderr, " Python error detcted at %s %s:%d\n\n", code, file, line);
PyErr_Print();
}
// int lvl = push_text_stack();
PyObject *type, *val;
// 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)));
};
static foreign_t python_len(term_t tobj, term_t tf) {
Py_ssize_t len;
@ -20,6 +27,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;
@ -105,7 +116,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); }
@ -133,14 +146,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 (_) */
@ -267,7 +284,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);
@ -296,10 +313,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) {
@ -332,7 +351,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)); }
}
@ -344,7 +365,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;
@ -353,7 +376,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, "()")) {
@ -361,12 +386,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); }
@ -523,6 +552,27 @@ static foreign_t python_export(term_t t, term_t pl) {
pyErrorAndReturn(rc);
}
static bool get_mod(const char *s0)
{
PyObject *pName;
term_t t0 = python_acquire_GIL();
#if PY_MAJOR_VERSION < 3
pName = PyString_FromString(s0);
#else
pName = PyUnicode_FromString(s0);
#endif
if (pName == NULL) {
python_release_GIL(t0);
}
PyObject *pModule = PyImport_Import(pName);
Py_XDECREF(pName);
python_release_GIL(t0);
return pModule;
}
/**
* @pred python_import(MName, Mod)
* Import a python module to the YAP environment.
@ -536,35 +586,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);
@ -580,16 +640,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) {
PyObject_SetAttrString(py_Main, as, pModule);
}
python_release_GIL(t0);
pyErrorAndReturn(rc);
}
}
@ -655,26 +716,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);
@ -698,6 +758,7 @@ 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);
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,
@ -22,6 +24,7 @@ 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;
@ -44,8 +47,9 @@ static void add_modules(void) {
if (py_Yapex)
Py_INCREF(py_Yapex);
Py_f2p = PythonLookup("f2p", NULL);
if (Py_f2p)
Py_INCREF(Py_f2p);
if (!Py_f2p)
Py_f2p = PyList_New(0);
Py_INCREF(Py_f2p);
init_python_vfs();
}

View File

@ -32,6 +32,7 @@
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 +117,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,22 +25,40 @@ 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):
# type: (object) -> object
if not args:
args = EngineArgs(**kwargs)
args.jupyter = True
Engine.__init__(self, args)
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 )
@ -273,26 +380,21 @@ set (RESOURCES
#yap_kernel/resources/logo-32x32.png
#yap_kernel/resourcess/logo-64x64.png
)
set (RENAMED_RESOURCES
set (RENAMED_RESOURCES
yap_kernel/resources/logo-32x32.png
yap_kernel/resources/logo-64x64.png
# yap_kernel/resources/codemirror/mode/prolog/prolog.js
)
set (PL_SOURCES yap_ipython/prolog/jupyter.yap yap_ipython/prolog/complete.yap
yap_ipython/prolog/verify.yap
)
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
@ -315,17 +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

@ -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,41 +1,49 @@
/**
* @file jupyter.yap4py
*
* @brief JUpyter support.
*/
% :- module( jupyter,
% [jupyter_query/3,
% errors/2,
% ready/2,
% completion/2,
% ]
%% ).
:- yap_flag(gc_trace,verbose).
/*
:- 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,
python_query(Self,Line).
jupyter_cell(Caller, _, Line ) :-
Query = Caller,
catch(
python_query(Query,Line),
E=error(A,B),
system_error(A,B)
).
restreams(call) :-
streams(true).
@ -55,139 +63,38 @@ jupyter_consult(Cell) :-
% Name = 'Inp',
% stream_property(Stream, file_name(Name) ),
% setup_call_cleanup(
open_mem_read_stream( Cell, Stream),
load_files(user:'jupyter cell',[stream(Stream)]).
catch(
(
Options = [],
open_mem_read_stream( Cell, Stream),
load_files(user:'jupyter cell',[stream(Stream)| Options])
),
E=error(A,B),
(close(Stream), system_error(A,B))
),
fail.
jupyter_consult(_Cell).
blank(Text) :-
atom(Text),
!,
atom_codes(Text, L),
maplist( code_type(space), L).
blank(Text) :-
string(Text),
!,
string_codes(Text, L),
maplist( code_type(space), L).
:- dynamic cell_stream/1.
streams(false) :-
nb_setval(jupyter_cell, false),
retract(cell_stream(S)),
close(S),
fail.
streams(false).
streams(false) :-
close(user_input),
close(user_output),
close(user_error).
streams(true) :-
streams( false ),
nb_setval(jupyter_cell, true),
% \+ current_stream('/python/input',_,_),
open('/python/input', read, Input, [alias(user_input),bom(false),script(false)]),
assert( cell_stream( Input) ),
set_prolog_flag(user_input,Input),
fail.
streams(true) :-
% \+ current_stream('/python/sys.stdout',_,_),
open('/python/sys.stdout', append, Output, [alias(user_output)]),
set_prolog_flag(user_output, Output),
assert( cell_stream( Output) ),
fail.
streams(true) :-
% \+ current_stream('/python/sys.stderr',_,_),
open('/python/sys.stderr', append, Error, [alias(user_error)]),
assert( cell_stream( Error) ),
set_prolog_flag(user_error, Error),
fail.
streams(true).
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

@ -0,0 +1,179 @@
/**
* @file jupyter.yap4py
*
* @brief JUpyter support.
*/
%% :- 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)).
:- dynamic jupyter/1.
jupyter( []).
ready( Engine, Query) :-
errors( Engine , Cell ),
Es := Engine.errors,
not Es == [].
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).
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')
@ -510,16 +511,29 @@ class YAPRun:
def __init__(self, shell):
self.shell = shell
self.yapeng = Engine()
self.yapeng = JupyterEngine()
global engine
engine = self.yapeng
self.yapeng.goal(use_module(library("jupyter")),True)
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
"""
@ -542,39 +556,48 @@ 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)+' after '+str( self.bindings)+ '\n')
has_raised = True
self.yapeng.mgoal(streams(False),"user", True)
return False,[]
self.result.result = False
return self.result
def _yrun_cell(self, raw_cell, store_history=True, silent=False,
@ -636,7 +659,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
@ -655,10 +678,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( )
@ -674,13 +697,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
@ -702,14 +725,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.bindings = dicts = []
self.yapeng.mgoal(streams(True),"user", True)
if cell.strip('\n \t'):
#create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
@ -725,16 +748,19 @@ class YAPRun:
# run the new command using the given tracer
#
# tracer.runfunc(f,self,cell,state)
self.yapeng.mgoal(streams(True),"user", True)
self.jupyter_query( cell )
self.yapeng.mgoal(streams(False),"user", True)
# 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
try:
(etype, value, tb) = e
traceback.print_exception(etype, value, tb)
except:
print(e)
pass
self.shell.last_execution_succeeded = not has_raised
@ -752,6 +778,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):
@ -771,12 +798,12 @@ class YAPRun:
else:
taken = l0-(i-1)
n = s[i+1:].strip()
s = s[:i-1]
s = s[:i]
if n:
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:
@ -793,7 +820,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

View File

@ -203,7 +203,7 @@ class YAPKernel(KernelBase):
self._forward_input(allow_stdin)
reply_content = {}
import trace;
# import trace;
try:
res = shell.run_cell(code, store_history=store_history, silent=silent)
finally:

View File

@ -2,50 +2,37 @@
# PROJECT ( YAP_REAL C )
#
# - This module locates an installed R distribution.
#
# Defines the following:
# R_COMMAND - Path to R command
# R_HOME - Path to 'R home', as reported by R
# R_INCLUDE_DIR - Path to R include directory
# R_LIBRARY_BASE - Path to R library
# R_LIBRARY_BLAS - Path to Rblas / blas library
# R_LIBRARY_LAPACK - Path to Rlapack / lapack library
# R_LIBRARY_READLINE - Path to readline library
# R_LIBRARIES - Array of: R_LIBRARY_BASE, R_LIBRARY_BLAS, R_LIBRARY_LAPACK, R_LIBRARY_BASE [, R_LIBRARY_READLINE]
#
# VTK_R_HOME - (deprecated, use R_HOME instead) Path to 'R home', as reported by R
#
# Variable search order:
# 1. Attempt to locate and set R_COMMAND
# If unsuccessful, generate error and prompt user to manually set R_COMMAND
# 2. Use R_COMMAND to set R_HOME
# 3. Locate other libraries in the priority:
# 1. Within a user-built instance of R at R_HOME
# 2. Within an installed instance of R
# 3. Within external system libraries
#
if (R_LIBRARIES AND R_INCLUDE_DIR)
set(REAL_SOURCES real.c)
# LIBR_FOUND
# LIBR_HOME
# LIBLIBR_INCLUDE_DIRSS
# LIBR_DOC_DIR
# LIBR_LIBRARIES
if (LIBR_LIBRARIES AND LIBR_INCLUDE_DIRS)
set_package_properties(R PROPERTIES
DESCRIPTION "The R Project for Statistical Computing."
URL "https://www.r-project.org/")
add_lib(real ${REAL_SOURCES})
target_link_libraries (real ${R_LIBRARIES} libYap)
target_link_libraries (real ${LIBR_LIBRARIES} libYap)
include_directories (
${CMAKE_CURRENT_BINARY_DIR}
${R_INCLUDE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_BINARY_DIR}
${CMAKE_SOURCE_DIR}/include
${LIBR_INCLUDE_DIRS}
)
list (APPEND CMAKE_REQUIRED_INCLUDES
${CMAKE_CURRENT_BINARY_DIR}
${R_INCLUDE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_SOURCE_DIR}/include
${LIBR_INCLUDE_DIRS}
)
check_include_files( "stdio.h;R.h" HAVE_R_H )
check_include_files( "R.h,;Rembedded.h" HAVE_R_EMBEDDED_H )
check_include_files( "R.h,;Rembeddred.h" HAVE_R_EMBEDDED_H )
check_include_files( "Rembedded.h;Rinterface.h" HAVE_R_INTERFACE_H )
configure_file ("rconfig.h.cmake" "rconfig.h" )

View File

@ -66,6 +66,7 @@
:- use_module(library(readutil)).
:- use_module(library(debug)).
:- use_module(library(system)).
:- use_module(library(readutil)).
:- dynamic( real:r_started/1 ).
@ -111,6 +112,15 @@ init_r_env :-
install_in_ms_windows(ToR).
:- endif.
init_r_env :-
current_prolog_flag(unix, true),
open(popen('R RHOME'),read,S),
read_line_to_codes(S,Lc),
close(S),
Lc \= end_of_file,
!,
atom_codes(RH,Lc),
setenv('R_HOME',RH).
init_r_env :-
current_prolog_flag(unix, true),
% typical Linux 64 bit setup (fedora)

View File

@ -36,12 +36,12 @@ DEPENDS pllibpl ${pl_os_library}
)
add_custom_command (OUTPUT ${CMAKE_SWIG_OUTPUT}/swig_streamer.cpp
COMMAND ${SWIG_EXECUTABLE} -c++ -java -package ${SWIG_MODULE_NAME} -outdir ${CMAKE_SWIG_OUTDIR} -addextern -I${CMAKE_CURRENT_SOURCE_DIR} -o ${CMAKE_SWIG_OUTPUT}/swig_streamer.cpp -oh ${CMAKE_SWIG_OUTPUT}/swig_streamer.hh streamer.i
COMMAND ${SWIG_EXECUTABLE} -c++ -java -package ${SWIG_MODULE_NAME} -O -outdir ${CMAKE_SWIG_OUTDIR} -addextern -I${CMAKE_CURRENT_SOURCE_DIR} -o ${CMAKE_SWIG_OUTPUT}/swig_streamer.cpp -oh ${CMAKE_SWIG_OUTPUT}/swig_streamer.hh streamer.i
DEPENDS streamer.i
)
add_custom_command (OUTPUT ${CMAKE_SWIG_OUTPUT}/yap_swig.cpp
COMMAND ${SWIG_EXECUTABLE} -c++ -java -package ${SWIG_MODULE_NAME} -outdir ${CMAKE_SWIG_OUTDIR} -addextern -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/include -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_BINARY_DIR} -I${GMP_INCLUDE_DIRS} -DX_API="" -o ${CMAKE_SWIG_OUTPUT}/yap_swig.cpp -oh ${CMAKE_SWIG_OUTPUT}/yap_swig.hh ${SWIG_SOURCES}
COMMAND ${SWIG_EXECUTABLE} -c++ -java -package ${SWIG_MODULE_NAME} -O -outdir ${CMAKE_SWIG_OUTDIR} -addextern -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/include -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_BINARY_DIR} -I${GMP_INCLUDE_DIRS} -DX_API="" -o ${CMAKE_SWIG_OUTPUT}/yap_swig.cpp -oh ${CMAKE_SWIG_OUTPUT}/yap_swig.hh ${SWIG_SOURCES}
DEPENDS pllibos ${SWIG_SOURCES} YAP++)

View File

@ -2,7 +2,7 @@
/* example.i */
#if PYTHONSWIG
#if defined(SWIGPYTHON)
%module(directors = "1", package="yap4py") yap
#else
%module(directors = "1") yap
@ -31,44 +31,13 @@ class YAPAtom;
class YAPPredicate;
class YAPEngine;
%{
#if defined(SWIGPYTHON)
#include <cmath>
#include <gmpxx.h>
extern "C"{
#include "Yap.h"
X_API extern Term YAP_MkCharPTerm( char *n);
#ifdef SWIGPYTHON
#include <py4yap.h>
extern inline PyObject *AtomToPy(const char *s) {
if (strcmp(s, "true") == 0)
return Py_True;
if (strcmp(s, "false") == 0)
return Py_False;
if (strcmp(s, "none") == 0)
return Py_None;
if (strcmp(s, "[]") == 0)
return PyList_New(0);
else if (strcmp(s, "{}") == 0)
return PyDict_New();
/* return __main__,s */
else if (PyObject_HasAttrString(py_Main, s)) {
return PyObject_GetAttrString(py_Main, s);
}
// no way to translate
return NULL;
}
#endif
}
%pythoncode %{
YAPError = _yap.YAPError
%}
#ifdef SWIGPYTHON
%typemap(typecheck) Term* {
$1 = PySequence_Check($input);
}
@ -135,146 +104,25 @@ X_API extern Term YAP_MkCharPTerm( char *n);
}
return $result; }
// Language independent exception handler
%exception next {
%exception {
try {
$action
} catch (YAPError &e) {
yap_error_number en = e.getID();
PyObject *pyerr = PyExc_RuntimeError;
YAPPycatch(e);
SWIG_fail;
}
}
LOCAL_Error_TYPE = YAP_NO_ERROR;
switch (e.getErrorClass()) {
case YAPC_NO_ERROR:
break;
/// bad domain, "first argument often is the predicate.
case DOMAIN_ERROR: {
switch (en) {
case DOMAIN_ERROR_OUT_OF_RANGE:
pyerr = PyExc_GeneratorExit;
break;
case DOMAIN_ERROR_NOT_LESS_THAN_ZERO:
pyerr = PyExc_IndexError;
break;
case DOMAIN_ERROR_CLOSE_OPTION:
case DOMAIN_ERROR_ENCODING:
case DOMAIN_ERROR_PROLOG_FLAG:
case DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION:
case DOMAIN_ERROR_READ_OPTION:
case DOMAIN_ERROR_SET_STREAM_OPTION:
pyerr = PyExc_KeyError;
break;
case DOMAIN_ERROR_FILE_ERRORS:
case DOMAIN_ERROR_FILE_TYPE:
case DOMAIN_ERROR_IO_MODE:
case DOMAIN_ERROR_SOURCE_SINK:
case DOMAIN_ERROR_STREAM_POSITION:
pyerr = PyExc_IOError;
break;
default:
pyerr = PyExc_ValueError;
}
} break;
/// bad arithmetic
case EVALUATION_ERROR: {
switch (en) {
case EVALUATION_ERROR_FLOAT_OVERFLOW:
case EVALUATION_ERROR_INT_OVERFLOW:
pyerr = PyExc_OverflowError;
break;
case EVALUATION_ERROR_FLOAT_UNDERFLOW:
case EVALUATION_ERROR_UNDERFLOW:
case EVALUATION_ERROR_ZERO_DIVISOR:
pyerr = PyExc_ArithmeticError;
break;
default:
pyerr = PyExc_RuntimeError;
}
} break;
/// missing object (I/O mostly)
case EXISTENCE_ERROR:
pyerr = PyExc_NotImplementedError;
break;
/// should be bound
case INSTANTIATION_ERROR_CLASS:
pyerr = PyExc_RuntimeError;
break;
/// bad access, I/O
case PERMISSION_ERROR: {
switch (en) {
case PERMISSION_ERROR_INPUT_BINARY_STREAM:
case PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM:
case PERMISSION_ERROR_INPUT_STREAM:
case PERMISSION_ERROR_INPUT_TEXT_STREAM:
case PERMISSION_ERROR_OPEN_SOURCE_SINK:
case PERMISSION_ERROR_OUTPUT_BINARY_STREAM:
case PERMISSION_ERROR_REPOSITION_STREAM:
case PERMISSION_ERROR_OUTPUT_STREAM:
case PERMISSION_ERROR_OUTPUT_TEXT_STREAM:
pyerr = PyExc_OverflowError;
break;
default:
pyerr = PyExc_RuntimeError;
}
} break;
/// something that could not be represented into a type
case REPRESENTATION_ERROR:
pyerr = PyExc_RuntimeError;
break;
/// not enough ....
case RESOURCE_ERROR:
pyerr = PyExc_RuntimeError;
break;
/// bad text
case SYNTAX_ERROR_CLASS:
pyerr = PyExc_SyntaxError;
break;
/// OS or internal
case SYSTEM_ERROR_CLASS:
pyerr = PyExc_RuntimeError;
break;
/// bad typing
case TYPE_ERROR:
pyerr = PyExc_TypeError;
break;
/// should be unbound
case UNINSTANTIATION_ERROR_CLASS:
pyerr = PyExc_RuntimeError;
break;
/// escape hatch
default:
break;
}
PyErr_SetString(pyerr, e.text().c_str());
}
}
%typecheck(2) Int { $1 = PyLong_Check($input); }
%typecheck(3) double { $1 = PyFloat_Check($input); }
%typecheck(2) const char * { $1 = PyUnicode_Check($input); }
#else
%typecheck(1) Term { $1 = !PyUnicode_Check($input); }
%typecheck(1) YAP_Term { $1 = PyUnicode_Check($input); }
%typemap(in) arity_t { (jlong)($input); }
%typecheck(2) Int { $1 = PyLong_Check($input); }
%typecheck(3) double { $1 = PyFloat_Check($input); }
%typecheck(2) const char * { $1 = PyUnicode_Check($input); }
%typecheck(1) Term { $1 = !PyUnicode_Check($input); }
%typecheck(1) YAP_Term { $1 = PyUnicode_Check($input); }
%typecheck(0) YAPTerm { $1 = !PyUnicode_Check($input); }
%typemap(in) jlong %{
$1 = (jlong)$input;
%}
%typemap(out) arity_t { *(jlong *)&$result = $1; }
// Language independent exception handler
// simplified version
%include <exception.i>
%typecheck(0) YAPTerm { $1 = !PyUnicode_Check($input); }
%exception {
try {
@ -289,15 +137,31 @@ X_API extern Term YAP_MkCharPTerm( char *n);
}
#endif
#else
%{
/* Put header files here or function declarations like below */
%typemap(in) arity_t { (jlong)($input); }
%typemap(in) jlong %{
$1 = (jlong)$input;
%}
%typemap(out) arity_t { *(jlong *)&$result = $1; }
// Language independent exception handler
// simplified version
%include <exception.i>
#endif
%{
/* Put header files here or function declarations like below */
#include "yapi.hh"
extern "C" {
extern void Yap_PrintException(yap_error_descriptor_t *i);
#if THREADS
#define Yap_regp regcache
@ -310,10 +174,156 @@ X_API extern Term YAP_MkCharPTerm( char *n);
extern void init_sqlite();
%}
#define X_API
#include <cmath>
#include <gmpxx.h>
extern "C"{
#include "Yap.h"
X_API extern Term YAP_MkCharPTerm( char *n);
#if defined(SWIGPYTHON)
#include <py4yap.h>
X_API extern PyObject * pYAPError;
extern inline PyObject *AtomToPy(const char *s) {
if (strcmp(s, "true") == 0)
return Py_True;
if (strcmp(s, "false") == 0)
return Py_False;
if (strcmp(s, "none") == 0)
return Py_None;
if (strcmp(s, "[]") == 0)
return PyList_New(0);
else if (strcmp(s, "{}") == 0)
return PyDict_New();
/* return __main__,s */
else if (PyObject_HasAttrString(py_Main, s)) {
return PyObject_GetAttrString(py_Main, s);
}
// no way to translate
return NULL;
}
static void
YAPPycatch(YAPError &e)
{
yap_error_number en = e.getID();
switch (e.getErrorClass()) {
case YAPC_NO_ERROR:
break;
/// bad domain, "first argument often is the predicate.
case DOMAIN_ERROR: {
switch (en) {
case DOMAIN_ERROR_OUT_OF_RANGE:
pYAPError = PyExc_GeneratorExit;
break;
case DOMAIN_ERROR_NOT_LESS_THAN_ZERO:
pYAPError = PyExc_IndexError;
break;
case DOMAIN_ERROR_CLOSE_OPTION:
case DOMAIN_ERROR_ENCODING:
case DOMAIN_ERROR_PROLOG_FLAG:
case DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION:
case DOMAIN_ERROR_READ_OPTION:
case DOMAIN_ERROR_SET_STREAM_OPTION:
pYAPError = PyExc_KeyError;
break;
case DOMAIN_ERROR_FILE_ERRORS:
case DOMAIN_ERROR_FILE_TYPE:
case DOMAIN_ERROR_IO_MODE:
case DOMAIN_ERROR_SOURCE_SINK:
case DOMAIN_ERROR_STREAM_POSITION:
pYAPError = PyExc_IOError;
break;
default:
pYAPError = PyExc_ValueError;
}
} break;
/// bad arithmetic
case EVALUATION_ERROR: {
switch (en) {
case EVALUATION_ERROR_FLOAT_OVERFLOW:
case EVALUATION_ERROR_INT_OVERFLOW:
pYAPError = PyExc_OverflowError;
break;
case EVALUATION_ERROR_FLOAT_UNDERFLOW:
case EVALUATION_ERROR_UNDERFLOW:
case EVALUATION_ERROR_ZERO_DIVISOR:
pYAPError = PyExc_ArithmeticError;
break;
default:
pYAPError = PyExc_RuntimeError;
}
} break;
/// missing object (I/O mostly)
case EXISTENCE_ERROR:
pYAPError = PyExc_NotImplementedError;
break;
/// should be bound
case INSTANTIATION_ERROR_CLASS:
pYAPError = PyExc_RuntimeError;
break;
/// bad access, I/O
case PERMISSION_ERROR: {
switch (en) {
case PERMISSION_ERROR_INPUT_BINARY_STREAM:
case PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM:
case PERMISSION_ERROR_INPUT_STREAM:
case PERMISSION_ERROR_INPUT_TEXT_STREAM:
case PERMISSION_ERROR_OPEN_SOURCE_SINK:
case PERMISSION_ERROR_OUTPUT_BINARY_STREAM:
case PERMISSION_ERROR_REPOSITION_STREAM:
case PERMISSION_ERROR_OUTPUT_STREAM:
case PERMISSION_ERROR_OUTPUT_TEXT_STREAM:
pYAPError = PyExc_OverflowError;
break;
default:
pYAPError = PyExc_RuntimeError;
}
} break;
/// something that could not be represented into a type
case REPRESENTATION_ERROR:
pYAPError = PyExc_RuntimeError;
break;
/// not enough ....
case RESOURCE_ERROR:
pYAPError = PyExc_RuntimeError;
break;
/// bad text
case SYNTAX_ERROR_CLASS:
pYAPError = PyExc_SyntaxError;
break;
/// OS or internal
case SYSTEM_ERROR_CLASS:
pYAPError = PyExc_RuntimeError;
break;
/// bad typing
case TYPE_ERROR:
pYAPError = PyExc_TypeError;
break;
/// should be unbound
case UNINSTANTIATION_ERROR_CLASS:
pYAPError = PyExc_RuntimeError;
break;
/// escape hatch
default:
break;
}
PyErr_SetString(pYAPError, e.text().c_str());
}
#endif
}
%}
/* turn on director wrapping Callback */
//%feature("director") YAPCallback;
@ -333,12 +343,17 @@ X_API extern Term YAP_MkCharPTerm( char *n);
%template(TermVector) vector<Term>;
%feature("novaluewrapper") vector<Term>;
//%template(YAPTermVector) vector<YAPTerm>;
//%feature("novaluewrapper") vector<YAPTerm>;
%template(YAPTermVector) vector<YAPTerm>;
%feature("novaluewrapper") vector<YAPTerm>;
};
%init %{
#ifdef SWIGYTHON
PyObject * pYAPError = PyErr_NewException("_yap.YAPError", NULL, NULL);
Py_INCREF(pYAPError);
PyModule_AddObject(m, "YAPError", pYAPError);
#endif
%}

View File

@ -302,8 +302,7 @@ absolute_file_name(File0,File) :-
!,
F.
'$cat_file_name'(File, S) -->
{string(File), string_to_codes(File, S) },
!,
{string(File), string_codes(File, S) },
S.

View File

@ -121,9 +121,11 @@ print_message(L,E) :-
).
'$undefp0'([M|G], _Action) :-
stream_property( loop_stream, file_name(F)),
stream_property( loop_stream, line_number(L)),
format(user_error,'~a:~d error undefined: call to ~w~n',[F,L,M:G]),
stream_property( loop_stream, [file_name(F), line_number(L)]),
format(user_error,'~a:~d error undefined:',[F,L]),
fail
;
format(user_error,' call to ~w~n',[M:G]),
fail.
:- '$undefp_handler'('$undefp0'(_,_),prolog).
@ -262,6 +264,7 @@ initialize_prolog :-
:- c_compile( 'preds.yap' ).
:- c_compile( 'modules.yap' ).
:- c_compile( 'grammar.yap' ).
:- c_compile( 'protect.yap' ).
:- ['absf.yap'].
@ -314,11 +317,7 @@ initialize_prolog :-
:- multifile prolog:'$system_predicate'/2.
:- ['protect.yap'].
version(yap,[6,4]).
:- op(1150,fx,(mode)).
:- '$opdec'(1150,fx,(mode),prolog).
:- dynamic 'extensions_to_present_answer'/1.
@ -479,4 +478,8 @@ If this hook preodicate succeeds it must instantiate the _Action_ argument to t
:- ensure_loaded('../pl/pathconf.yap').
:- yap_flag(user:unknown,error).
:- ensure_loaded('../android.yap').
%% @}

View File

@ -220,8 +220,10 @@ SWI-compatible option where if _Autoload_ is `true` undefined
% compilation_mode(compact,source,assert_all) => implemented
% register(true, false) => implemented
%
load_files(Files,Opts) :-
'$load_files'(Files,Opts,load_files(Files,Opts)).
load_files(Files0,Opts) :-
'$yap_strip_module'(Files0,M,Files),
'$load_files'(Files,M,Opts,M:load_files(Files,Opts)).
'$lf_option'(autoload, 1, false).
'$lf_option'(derived_from, 2, false).
@ -232,7 +234,14 @@ load_files(Files,Opts) :-
'$lf_option'(qcompile, 7, Current) :-
'__NB_getval__'('$qcompile', Current, Current = never).
'$lf_option'(silent, 8, _).
'$lf_option'(skip_unix_header, 9, true).
'$lf_option'(skip_unix_header, 9, Skip) :-
stream_property(Stream,[alias(loop_stream),tty(TTy),reposition(Rep)]),
( Rep == true
->
(TTy = true -> Skip = false ; Skip = true)
;
Skip = false
).
'$lf_option'(compilation_mode, 10, Flag) :-
current_prolog_flag(source, YFlag),
( YFlag == false -> Flag = compact ; Flag = source ).
@ -271,42 +280,72 @@ load_files(Files,Opts) :-
'$lf_option'(Op, Id, _),
setarg( Id, TOpts, Val ).
'$load_files'(Files, Opts, Call) :-
( '__NB_getval__'('$lf_status', OldTOpts, fail), nonvar(OldTOpts) ->
'$lf_opt'(autoload, OldTOpts, OldAutoload)
;
'$lf_option'(last_opt, LastOpt),
functor( OldTOpts, opt, LastOpt ),
'$lf_opt'('$context_module', OldTOpts, user)
),
'$lf_option'(last_opt, LastOpt),
functor( TOpts, opt, LastOpt ),
( source_location(ParentF, Line) -> true ; ParentF = user_input, Line = -1 ),
'$lf_opt'('$location', TOpts, ParentF:Line),
'$lf_opt'('$files', TOpts, Files),
'$lf_opt'('$call', TOpts, Call),
'$lf_opt'('$options', TOpts, Opts),
'$lf_opt'('$parent_topts', TOpts, OldTOpts),
'$process_lf_opts'(Opts,TOpts,Files,Call),
'$lf_default_opts'(1, LastOpt, TOpts),
'$lf_opt'(stream, TOpts, Stream),
( nonvar(Stream) ->
'$set_lf_opt'('$from_stream', TOpts, true )
;
'$check_files'(Files,load_files(Files,Opts))
),
'$check_use_module'(Call,UseModule),
'$lf_opt'('$use_module', TOpts, UseModule),
'$current_module'(M0),
( '$lf_opt'(autoload, TOpts, Autoload),
var(Autoload) ->
Autoload = OldAutoload
;
true
),
% make sure we can run consult
'$init_consult',
'$lf'(Files, M0, Call, TOpts).
'$load_files'([user], M,Opts, Call) :-
current_input(S),
'$load_files__'(user, M, [stream(S)|Opts], Call).
'$load_files'(user, M,Opts, Call) :-
current_input(S),
'$load_files__'(user, M, [stream(S)|Opts], Call).
'$load_files'([-user], M,Opts, Call) :-
current_input(S),
'$load_files__'(user, M, [consult(reconsult),stream(S)|Opts], Call).
'$load_files'(-user, M,Opts, Call) :-
current_input(S),
'$load_files__'(user, M, [consult(reconsult),stream(S)|Opts], Call).
'$load_files'([user_input], M,Opts, Call) :-
current_input(S),
'$load_files__'(user_input, M, [stream(S)|Opts], Call).
'$load_files'(user_input, M,Opts, Call) :-
current_input(S),
'$load_files__'(user_input, M, [stream(S)|Opts], Call).
'$load_files'([-user_input], M,Opts, Call) :-
current_input(S),
'$load_files__'(user_input, M, [consult(reconsult),stream(S)|Opts], Call).
'$load_files'(-user_input, M,Opts, Call) :-
'$load_files__'(user_input, M, [consult(reconsult),stream(S)|Opts], Call).
'$load_files'(Files, M, Opts, Call) :-
'$load_files__'(Files, M, Opts, Call).
'$load_files__'(Files, M, Opts, Call) :-
'$lf_option'(last_opt, LastOpt),
'$show_consult_level'(LC),
( LC > 0
->
'__NB_getval__'('$lf_status', OldTOpts, fail),
nonvar(OldTOpts),
'$lf_opt'(autoload, OldTOpts, OldAutoload),
'$lf_opt'('$context_module', OldTOpts, OldContextModule)
;
current_prolog_flag(autoload, OldAutoload),
functor( OldTOpts, opt, LastOpt ),
'$lf_opt'(autoload, OldTOpts, OldAutoload),
'$lf_opt'('$context_module', OldTOpts, OldContextModule)
),
functor( TOpts, opt, LastOpt ),
( source_location(ParentF, Line) -> true ; ParentF = user_input, Line = -1 ),
'$lf_opt'('$location', TOpts, ParentF:Line),
'$lf_opt'('$files', TOpts, Files),
'$lf_opt'('$call', TOpts, Call),
'$lf_opt'('$options', TOpts, Opts),
'$lf_opt'('$parent_topts', TOpts, OldTOpts),
'$process_lf_opts'(Opts,TOpts,Files,Call),
'$lf_default_opts'(1, LastOpt, TOpts),
'$lf_opt'(stream, TOpts, Stream),
( nonvar(Stream) ->
'$set_lf_opt'('$from_stream', TOpts, true )
;
'$check_files'(Files,load_files(Files,Opts))
),
'$check_use_module'(Call,UseModule),
'$lf_opt'('$use_module', TOpts, UseModule),
( '$lf_opt'(autoload, TOpts, Autoload),
var(Autoload) ->
Autoload = OldAutoload
;
true
),
% make sure we can run consult
'$init_consult',
'$lf'(Files, M, Call, TOpts).
'$check_files'(Files, Call) :-
var(Files), !,
@ -428,32 +467,12 @@ load_files(Files,Opts) :-
'$lf'(V,_,Call, _ ) :- var(V), !,
'$do_error'(instantiation_error,Call).
'$lf'([], _, _, _) :- !.
'$lf'(M:X, _, Call, TOpts) :- !,
(
atom(M)
->
'$lf'(X, M, Call, TOpts)
;
'$do_error'(type_error(atom,M),Call)
).
'$lf'([F|Fs], Mod, Call, TOpts) :- !,
% clean up after each consult
( '$lf'(F,Mod,Call, TOpts), fail;
'$lf'(Fs, Mod, Call, TOpts), fail;
true
).
'$lf'(user, Mod, Call, TOpts) :-
!,
stream_property( S, alias( user_input )),
'$set_lf_opt'('$from_stream', TOpts, true),
'$set_lf_opt'( stream , TOpts, S),
'$lf'(S, Mod, Call, TOpts).
'$lf'(user_input, Mod, Call, TOpts ) :-
!,
stream_property( S, alias( user_input )),
'$set_lf_opt'('$from_stream', TOpts, true),
'$set_lf_opt'( stream , TOpts, S),
'$lf'(S, Mod, Call, TOpts).
'$lf'(File, Mod, Call, TOpts) :-
'$lf_opt'(stream, TOpts, Stream),
b_setval('$user_source_file', File),
@ -544,10 +563,10 @@ When the files are not module files, ensure_loaded/1 loads them
_F_ must be a list containing the names of the files to load.
*/
ensure_loaded(Fs) :-
'$load_files'(Fs, [if(not_loaded)],ensure_loaded(Fs)).
load_files(Fs, [if(not_loaded)]).
compile(Fs) :-
'$load_files'(Fs, [], compile(Fs)).
load_files(Fs, []).
/**
@pred [ _F_ ]
@ -581,9 +600,9 @@ consult(Fs) :-
'$consult'(Fs,Module) :-
current_prolog_flag(language_mode, iso), % SICStus Prolog compatibility
!,
'$load_files'(Module:Fs,[],consult(Fs)).
load_files(Module:Fs,[]).
'$consult'(Fs, Module) :-
'$load_files'(Module:Fs,[consult(consult)],consult(Fs)).
load_files(Module:Fs,[consult(consult)]).
/**
@ -616,7 +635,7 @@ Example:
*/
reconsult(Fs) :-
'$load_files'(Fs, [], reconsult(Fs)).
load_files(Fs, []).
/* exo_files(+ _Files_)
@ -636,7 +655,7 @@ different forms of indexing, as shown in @cite x.
*/
exo_files(Fs) :-
'$load_files'(Fs, [consult(exo), if(not_loaded)], exo_files(Fs)).
load_files(Fs, [consult(exo), if(not_loaded)]).
/**
@ -667,19 +686,19 @@ YAP implements load_db/1 as a two-step non-optimised process. First,
db_files/1 itself is just a call to load_files/2.
*/
db_files(Fs) :-
'$load_files'(Fs, [consult(db), if(not_loaded)], exo_files(Fs)).
load_files(Fs, [consult(db), if(not_loaded)]).
'$csult'(Fs, _M) :-
'$skip_list'(_, Fs ,L),
L \== [],
user:dot_qualified_goal(Fs),
!.
!,
user:dot_qualified_goal(Fs).
'$csult'(Fs, M) :-
'$extract_minus'(Fs, MFs), !,
'$load_files'(M:MFs,[],[M:Fs]).
load_files(M:MFs,[]).
'$csult'(Fs, M) :-
'$load_files'(M:Fs,[consult(consult)],[M:Fs]).
load_files(M:Fs,[consult(consult)]).
'$csult_in_mod'(M, -F ) :- $load_files'(M:F,[],[M:F])
'$csult_in_mod'(M, F ) :- $load_files'(M:F,[consult(consult)],[M:F])
@ -1102,7 +1121,7 @@ just goes through every loaded file and verifies whether reloading is needed.
make :-
recorded('$lf_loaded','$lf_loaded'(F1,_M,reconsult,_,_,_,_),_),
'$load_files'(F1, [if(changed)],make),
load_files(F1, [if(changed)]),
fail.
make.
@ -1263,11 +1282,11 @@ use_module(M,F,Is) :-
'$use_module'(M,M1,F,Is) :-
nonvar(F), !,
( var(M) ->
'$load_files'(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is)),
load_files(M1:F, [if(not_loaded),must_be_module(true),imports(Is)]),
absolute_file_name( F, F1, [expand(true),file_type(prolog)] ),
recorded('$module','$module'(F1,M,_,_,_),_)
;
'$load_files'(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is))
load_files(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is))
).
'$use_module'(M,M1,F,Is) :-
nonvar(M), !,
@ -1275,11 +1294,11 @@ use_module(M,F,Is) :-
(
recorded('$module','$module'(F0,M,_,_,_),_)
->
'$load_files'(M1:F0, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is))
load_files(M1:F0, [if(not_loaded),must_be_module(true),imports(Is)])
;
nonvar(F0)
->
'$load_files'(M1:F, [if(not_loaded),must_be_module(true),imports(Is)], use_module(M,F,Is))
load_files(M1:F, [if(not_loaded),must_be_module(true),imports(Is)])
;
'$do_error'(instantiation_error,use_module(M,F,Is))
).
@ -1655,7 +1674,12 @@ End of conditional compilation.
consult_depth(LV) :- '$show_consult_level'(LV).
:- '$add_multifile'(dot_qualified_goal,2,user).
prolog_library(File) :-
yap_flag(verbose,Old,silent),
ensure_loaded(library(File)),
yap_flag(verbose,_,Old).
:- '$add_multifile'(dot_qualified_goal,1,user).
/**
@}

View File

@ -125,7 +125,7 @@ Call goal _H_ once per each solution of goal _H_. If goal
_H_ has no solutions, call goal _I_.
The built-in `if/3` is similar to `->/3`, with the difference
that it will backtrack over the test https://wiki.python.org/moin/HandlingExceptionsgoal. Consider the following
that it will backtrack over the test. Consider the following
small data-base:
~~~~~{.prolog}

View File

@ -45,7 +45,6 @@
'$include'/2,
'$initialization'/1,
'$initialization'/2,
'$load_files'/3,
'$require'/2,
'$set_encoding'/1,
'$use_module'/3]).
@ -176,23 +175,23 @@ considered.
'$exec_directive'(set_prolog_flag(F,V), _, _, _, _) :-
set_prolog_flag(F,V).
'$exec_directive'(ensure_loaded(Fs), _, M, _, _) :-
'$load_files'(M:Fs, [if(changed)], ensure_loaded(Fs)).
load_files(M:Fs, [if(changed)]).
'$exec_directive'(char_conversion(IN,OUT), _, _, _, _) :-
char_conversion(IN,OUT).
'$exec_directive'(public(P), _, M, _, _) :-
'$public'(P, M).
'$exec_directive'(compile(Fs), _, M, _, _) :-
'$load_files'(M:Fs, [], compile(Fs)).
load_files(M:Fs, []).
'$exec_directive'(reconsult(Fs), _, M, _, _) :-
'$load_files'(M:Fs, [], reconsult(Fs)).
load_files(M:Fs, []).
'$exec_directive'(consult(Fs), _, M, _, _) :-
'$load_files'(M:Fs, [consult(consult)], consult(Fs)).
load_files(M:Fs, [consult(consult)]).
'$exec_directive'(use_module(F), _, M, _, _) :-
use_module(M:F).
'$exec_directive'(reexport(F), _, M, _, _) :-
'$load_files'(M:F, [if(not_loaded), silent(true), reexport(true),must_be_module(true)], reexport(F)).
load_files(M:F, [if(not_loaded), silent(true), reexport(true),must_be_module(true)]).
'$exec_directive'(reexport(F,Spec), _, M, _, _) :-
'$load_files'(M:F, [if(changed), silent(true), imports(Spec), reexport(true),must_be_module(true)], reexport(F, Spec)).
load_files(M:F, [if(changed), silent(true), imports(Spec), reexport(true),must_be_module(true)]).
'$exec_directive'(use_module(F, Is), _, M, _, _) :-
use_module(M:F, Is).
'$exec_directive'(use_module(Mod,F,Is), _, _, _, _) :-

View File

@ -57,7 +57,7 @@ Errors are terms of the form:
* Generate a system error _Error_, informing the possible cause _Cause_.
*
*/
system_error(Type,Goal) :-
prolog:system_error(Type,Goal) :-
'$do_error'(Type,Goal).

View File

@ -232,9 +232,9 @@ beautify_hidden_goal('$process_directive'(Gs,_Mode,_VL),prolog) -->
[(:- Gs)].
beautify_hidden_goal('$loop'(Stream,Option),prolog) -->
[execute_load_file(Stream, consult=Option)].
beautify_hidden_goal('$load_files'(Files,Opts,?),prolog) -->
[load_files(Files,Opts)].
beautify_hidden_goal('$load_files'(_,_,Name),prolog) -->
beautify_hidden_goal('$load_files'(Files,M,Opts,?),prolog) -->
[load_files(M:Files,Opts)].
beautify_hidden_goal('$load_files'(_,_,_,Name),prolog) -->
[Name].
beautify_hidden_goal('$reconsult'(Files,Mod),prolog) -->
[reconsult(Mod:Files)].

View File

@ -9,6 +9,11 @@
/**
* @ingroup ModuleBuiltins
* @{
*
* YAP follows the following protovol:
* - predicate is in current module;
* - predicate is in user
* - predicate will be autoloaded, SWI style.
*/
:- '$mk_dynamic'('$parent_module'(_,_),prolog).
@ -22,7 +27,6 @@
'$pred_exists'(G, user).
% autoload
'$get_undefined_predicates'(G, ImportingMod, G0, ExportingMod) :-
recorded('$dialect',swi,_),
prolog_flag(autoload, true),
prolog_flag(unknown, OldUnk, fail),
(
@ -38,7 +42,7 @@
'$get_undefined_predicates'(G, ImportingMod, G0, ExportingMod) :-
'$parent_module'(ImportingMod,ExportingModI),
'$continue_imported'(ExportingMod, ExportingModI, G0, G).
'$get_undefined_predicates'(G, ImportingMod, G0, ExportingMod) :-
'$get_undefined_predicates'(G, _ImportingMod, G0, ExportingMod) :-
yap_flag(default_parent_module,ExportingModI),
'$continue_imported'(ExportingMod, ExportingModI, G0, G).
@ -58,6 +62,75 @@
'$get_undefined_predicates'(G, ImportingMod, G0, ExportingMod),
ExportingMod \= ImportingMod.
% be careful here not to generate an undefined exception.
'$generate_imported_predicate'(G, ImportingMod, G0, ExportingMod) :-
(
recorded('$import','$import'(ExportingModI,ImportingMod,G0I,G,_,_),_)
;
'$parent_module'(ImportingMod,ExportingModI),
\+ recorded('$import','$import'(ExportingModI,ImportingMod,G0I,G,_,_),_)
),
ImportingMod \= ExportingModI,
(
'$undefined'(G, ExportingModI)
->
'$generate_imported_predicate'(G, ExportingModI, G0, ExportingMod)
;
G=G0,
ExportingModI=ExportingMod
).
/**
*
* @pred '$continue_imported'(+ModIn, +ModOut, +PredIn ,+PredOut)
*
* @return
*/
'$continue_imported'(Mod,Mod,Pred,Pred) :-
'$pred_exists'(Pred, Mod),
!.
'$continue_imported'(FM,Mod,FPred,Pred) :-
recorded('$import','$import'(IM,Mod,IPred,Pred,_,_),_),
'$continue_imported'(FM, IM, FPred, IPred), !.
'$continue_imported'(FM,Mod,FPred,Pred) :-
prolog:'$parent_module'(Mod,IM),
'$continue_imported'(FM, IM, FPred, Pred).
'$autoload'(G, _ImportingMod, ExportingMod, Dialect) :-
functor(G, Name, Arity),
'$pred_exists'(index(Name,Arity,ExportingMod,_),Dialect),
call(Dialect:index(Name,Arity,ExportingMod,_)),
!.
'$autoload'(G, ImportingMod, ExportingMod, _Dialect) :-
functor(G, N, K),
functor(G0, N, K),
'$autoloader_find_predicate'(G0,ExportingMod),
ExportingMod \= ImportingMod,
(recordzifnot('$import','$import'(ExportingMod,ImportingMod,G0,G0, N ,K),_) -> true ; true ).
'$autoloader_find_predicate'(G,ExportingModI) :-
'__NB_getval__'('$autoloader_set', true, false), !,
autoloader:find_predicate(G,ExportingModI).
'$autoloader_find_predicate'(G,ExportingModI) :-
yap_flag(autoload, true, false),
yap_flag( unknown, Unknown, fail),
yap_flag(debug, Debug, false), !,
load_files([library(autoloader),
autoloader:library('INDEX'),
swi:library('dialect/swi/INDEX')],
[autoload(true),if(not_loaded)]),
nb_setval('$autoloader_set', true),
yap_flag(autoload, _, true),
yap_flag( unknown, _, Unknown),
yap_flag( debug, _, Debug),
autoloader:find_predicate(G,ExportingModI).
/**
*
* @}

View File

@ -33,17 +33,20 @@
nb_setval('$chr_toplevel_show_store',false).
'$init_consult' :-
set_value('$open_expands_filename',true),
nb_setval('$assert_all',off),
nb_setval('$if_level',0),
nb_setval('$endif',off),
nb_setval('$initialization_goals',off),
nb_setval('$included_file',[]),
nb_setval('$loop_streams',[]),
\+ '$undefined'('$init_preds',prolog),
'$init_preds',
fail.
'$init_consult'.
set_value('$open_expands_filename',true),
nb_setval('$assert_all',off),
nb_setval('$if_level',0),
nb_setval('$endif',off),
nb_setval('$initialization_goals',off),
nb_setval('$included_file',[]),
nb_setval('$loop_streams',[]),
(
'$undefined'('$init_preds',prolog)
->
true
;
'$init_preds'
).
'$init_win_graphics' :-
'$undefined'(window_title(_,_), system), !.

View File

@ -39,11 +39,6 @@
*/
maplist_(_, [], []).
maplist_(Pred, [A1|L1], [A2|L2]) :-
call(Pred, A1, A2),
maplist_(Pred, L1, L2).
/** @pred load_foreign_files( _Files_, _Libs_, _InitRoutine_)
should be used, from inside YAP, to load object files produced by the C
@ -74,8 +69,8 @@ load_foreign_files(Objs,Libs,Entry) :-
access(read),
expand(true),
file_errors(fail)], NewObjs),
maplist_( '$load_lib', Libs, NewLibs),
'$load_foreign_files'(NewObjs,NewLibs,Entry),
'$load_libs'( Libs ),
'$load_foreign_files'(NewObjs,[],Entry),
!,
prolog_load_context(file, F),
ignore( recordzifnot( '$load_foreign_done', [F, M], _) ).
@ -95,7 +90,10 @@ load_foreign_files(Objs,Libs,Entry) :-
'$name_object'(I, P, O) :-
absolute_file_name(I, O, P).
'$load_lib'(_,L,L).
'$load_libs'([]).
'$load_libs'([File|Files]) :-
open_shared_object(File, _Handle),
'$load_libs'(Files).
/** @pred load_absolute_foreign_files( Files, Libs, InitRoutine)

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