jupyter-related-fixes

This commit is contained in:
Vitor Santos Costa 2018-07-10 23:21:19 +01:00
parent 387d7cc3fb
commit 2e8dd92d89
28 changed files with 641 additions and 452 deletions

View File

@ -147,6 +147,32 @@ static inline Atom SearchAtom(const unsigned char *p, Atom a) {
return (NIL); return (NIL);
} }
Atom
Yap_AtomInUse(const char *atom) { /* lookup atom in atom table */
uint64_t hash;
const unsigned char *p;
Atom a, na = NIL;
AtomEntry *ae;
size_t sz = AtomHashTableSize;
/* compute hash */
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);
ae = RepAtom(na);
if (na != NIL ) {
READ_UNLOCK(HashChain[hash].AERWLock);
return (na);
}
READ_UNLOCK(HashChain[hash].AERWLock);
return NIL;
}
static Atom static Atom
LookupAtom(const unsigned char *atom) { /* lookup atom in atom table */ LookupAtom(const unsigned char *atom) { /* lookup atom in atom table */

View File

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

View File

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

View File

@ -80,22 +80,29 @@ static void newFlag(Term fl, Term val);
static Int current_prolog_flag(USES_REGS1); static Int current_prolog_flag(USES_REGS1);
static Int set_prolog_flag(USES_REGS1); static Int set_prolog_flag(USES_REGS1);
#include "Yatom.h"
#include "YapEval.h" #include "YapEval.h"
#include "Yatom.h"
#include "yapio.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 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 START_GLOBAL_FLAGS static flag_info global_flags_setup[] = {
#define END_GLOBAL_FLAGS GZERO_FLAG}; #define END_GLOBAL_FLAGS \
GZERO_FLAG \
} \
#define GZERO_FLAG { NULL, false, NULL, NULL, NULL } ;
#define LZERO_FLAG { NULL, false, NULL, NULL, NULL }
#define GZERO_FLAG \
{ NULL, false, NULL, NULL, NULL }
#define LZERO_FLAG \
{ NULL, false, NULL, NULL, NULL }
#include "YapGFlagInfo.h" #include "YapGFlagInfo.h"
@ -111,8 +118,7 @@ static Term indexer(Term inp) {
"set_prolog_flag index in {off,single,compact,multi,on,max}"); "set_prolog_flag index in {off,single,compact,multi,on,max}");
return TermZERO; return TermZERO;
} }
Yap_Error(TYPE_ERROR_ATOM, inp, Yap_Error(TYPE_ERROR_ATOM, inp, "set_prolog_flag index to an atom");
"set_prolog_flag index to an atom");
return TermZERO; return TermZERO;
} }
@ -133,13 +139,15 @@ static bool dqf1(ModEntry *new, Term t2 USES_REGS) {
return true; return true;
} }
/* bad argument, but still an atom */ /* bad argument, but still an atom */
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted " Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2,
"bad option %s for backquoted "
"string flag, use one string, " "string flag, use one string, "
"atom, codes or chars", "atom, codes or chars",
RepAtom(AtomOfTerm(t2))->StrOfAE); RepAtom(AtomOfTerm(t2))->StrOfAE);
return false; return false;
} else { } else {
Yap_Error(TYPE_ERROR_ATOM, t2, "set_prolog_flag(double_quotes, %s), should " Yap_Error(TYPE_ERROR_ATOM, t2,
"set_prolog_flag(double_quotes, %s), should "
"be {string,atom,codes,chars}", "be {string,atom,codes,chars}",
RepAtom(AtomOfTerm(t2))->StrOfAE); RepAtom(AtomOfTerm(t2))->StrOfAE);
return false; return false;
@ -168,7 +176,8 @@ static bool bqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags |= BCKQ_CHARS; new->flags |= BCKQ_CHARS;
return true; return true;
} }
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted " Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2,
"bad option %s for backquoted "
"string flag, use one string, " "string flag, use one string, "
"atom, codes or chars", "atom, codes or chars",
RepAtom(AtomOfTerm(t2))->StrOfAE); RepAtom(AtomOfTerm(t2))->StrOfAE);
@ -186,7 +195,6 @@ static bool bqs(Term t2) {
return bqf1(new, t2 PASS_REGS); return bqf1(new, t2 PASS_REGS);
} }
static bool sqf1(ModEntry *new, Term t2 USES_REGS) { static bool sqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags &= ~(SNGQ_CHARS | SNGQ_CODES | SNGQ_ATOM | SNGQ_STRING); new->flags &= ~(SNGQ_CHARS | SNGQ_CODES | SNGQ_ATOM | SNGQ_STRING);
if (IsAtomTerm(t2)) { if (IsAtomTerm(t2)) {
@ -203,7 +211,8 @@ static bool sqf1(ModEntry *new, Term t2 USES_REGS) {
new->flags |= SNGQ_CHARS; new->flags |= SNGQ_CHARS;
return true; return true;
} }
Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2, "bad option %s for backquoted " Yap_Error(DOMAIN_ERROR_OUT_OF_RANGE, t2,
"bad option %s for backquoted "
"string flag, use one string, " "string flag, use one string, "
"atom, codes or chars", "atom, codes or chars",
RepAtom(AtomOfTerm(t2))->StrOfAE); RepAtom(AtomOfTerm(t2))->StrOfAE);
@ -215,7 +224,6 @@ static bool sqf1(ModEntry *new, Term t2 USES_REGS) {
} }
} }
static bool sqf(Term t2) { static bool sqf(Term t2) {
CACHE_REGS CACHE_REGS
ModEntry *new = Yap_GetModuleEntry(CurrentModule); ModEntry *new = Yap_GetModuleEntry(CurrentModule);
@ -239,7 +247,8 @@ static Term isaccess(Term inp) {
static Term stream(Term inp) { static Term stream(Term inp) {
if (IsVarTerm(inp)) if (IsVarTerm(inp))
return inp; return inp;
if (Yap_CheckStream(inp, Input_Stream_f | Output_Stream_f | Append_Stream_f | if (Yap_CheckStream(inp,
Input_Stream_f | Output_Stream_f | Append_Stream_f |
Socket_Stream_f, Socket_Stream_f,
"yap_flag/3") >= 0) "yap_flag/3") >= 0)
return inp; return inp;
@ -782,7 +791,6 @@ static bool setYapFlagInModule(Term tflag, Term t2, Term mod) {
return bqf1(me, t2 PASS_REGS); return bqf1(me, t2 PASS_REGS);
} else if (fv->FlagOfVE == SINGLE_QUOTES_FLAG) { } else if (fv->FlagOfVE == SINGLE_QUOTES_FLAG) {
return sqf1(me, t2 PASS_REGS); return sqf1(me, t2 PASS_REGS);
} }
// bad key? // bad key?
return false; return false;
@ -850,8 +858,7 @@ static Int cont_yap_flag(USES_REGS1) {
Term modt = CurrentModule; Term modt = CurrentModule;
tflag = Yap_StripModule(tflag, &modt); tflag = Yap_StripModule(tflag, &modt);
while (i != gmax && i != UNKNOWN_FLAG && i != CHARACTER_ESCAPES_FLAG && while (i != gmax && i != UNKNOWN_FLAG && i != CHARACTER_ESCAPES_FLAG &&
i != BACK_QUOTES_FLAG && i != BACK_QUOTES_FLAG && i != SINGLE_QUOTES_FLAG &&
i != SINGLE_QUOTES_FLAG &&
i != DOUBLE_QUOTES_FLAG) i != DOUBLE_QUOTES_FLAG)
i++; i++;
if (i == gmax) if (i == gmax)
@ -1056,14 +1063,16 @@ void Yap_setModuleFlags(ModEntry *new, ModEntry *cme) {
Atom at = new->AtomOfME; Atom at = new->AtomOfME;
if (at == AtomProlog || CurrentModule == PROLOG_MODULE) { if (at == AtomProlog || CurrentModule == PROLOG_MODULE) {
new->flags = new->flags = M_SYSTEM | UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES |
M_SYSTEM | UNKNOWN_ERROR | M_CHARESCAPE | DBLQ_CODES | BCKQ_STRING |SNGQ_ATOM; BCKQ_STRING | SNGQ_ATOM;
if (at == AtomUser) 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) { } else if (cme && cme->flags && cme != new) {
new->flags = cme->flags; new->flags = cme->flags;
} else { } 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); // printf("cme=%s new=%s flags=%x\n",cme,at->StrOfAE,new->flags);
} }
@ -1392,7 +1401,8 @@ static bool setInitialValue(bool bootstrap, flag_func f, const char *s,
} }
CACHE_REGS CACHE_REGS
const char *us = (const char *)s; const char *us = (const char *)s;
t0 = Yap_BufferToTermWithPrioBindings(us, TermNil, 0L, strlen(s) + 1, GLOBAL_MaxPriority); t0 = Yap_BufferToTermWithPrioBindings(us, TermNil, 0L, strlen(s) + 1,
GLOBAL_MaxPriority);
if (!t0) if (!t0)
return false; return false;
if (IsAtomTerm(t0) || IsIntTerm(t0)) { if (IsAtomTerm(t0) || IsIntTerm(t0)) {
@ -1439,7 +1449,8 @@ do_prolog_flag_property(Term tflag,
xarg *args; xarg *args;
prolog_flag_property_choices_t i; prolog_flag_property_choices_t i;
bool rc = true; bool rc = true;
args = Yap_ArgList2ToVector(opts, prolog_flag_property_defs, args =
Yap_ArgList2ToVector(opts, prolog_flag_property_defs,
PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG); PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG);
if (args == NULL) { if (args == NULL) {
Yap_Error(LOCAL_Error_TYPE, opts, NULL); Yap_Error(LOCAL_Error_TYPE, opts, NULL);
@ -1527,8 +1538,7 @@ static Int cont_prolog_flag_property(USES_REGS1) { /* current_prolog_flag */
lab = MkAtomTerm(Yap_LookupAtom(local_flags_setup[i - gmax].name)); lab = MkAtomTerm(Yap_LookupAtom(local_flags_setup[i - gmax].name));
} else { } else {
if (i == UNKNOWN_FLAG || i == CHARACTER_ESCAPES_FLAG || if (i == UNKNOWN_FLAG || i == CHARACTER_ESCAPES_FLAG ||
i == SINGLE_QUOTES_FLAG || i == SINGLE_QUOTES_FLAG || i == DOUBLE_QUOTES_FLAG ||
i == DOUBLE_QUOTES_FLAG ||
i == BACK_QUOTES_FLAG) { i == BACK_QUOTES_FLAG) {
Term labs[2]; Term labs[2];
labs[0] = MkVarTerm(); labs[0] = MkVarTerm();
@ -1607,7 +1617,8 @@ static Int do_create_prolog_flag(USES_REGS1) {
prolog_flag_property_choices_t i; prolog_flag_property_choices_t i;
Term tflag = Deref(ARG1), tval = Deref(ARG2), opts = Deref(ARG3); Term tflag = Deref(ARG1), tval = Deref(ARG2), opts = Deref(ARG3);
args = Yap_ArgList2ToVector(opts, prolog_flag_property_defs, args =
Yap_ArgList2ToVector(opts, prolog_flag_property_defs,
PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG); PROLOG_FLAG_PROPERTY_END, DOMAIN_ERROR_PROLOG_FLAG);
if (args == NULL) { if (args == NULL) {
Yap_Error(LOCAL_Error_TYPE, opts, NULL); Yap_Error(LOCAL_Error_TYPE, opts, NULL);
@ -1722,7 +1733,7 @@ void Yap_InitFlags(bool bootstrap) {
*/ */
Yap_InitCPredBack("prolog_flag", 3, 1, current_prolog_flag, cont_yap_flag, Yap_InitCPredBack("prolog_flag", 3, 1, current_prolog_flag, cont_yap_flag,
0); 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, Yap_InitCPredBack("prolog_flag", 2, 1, current_prolog_flag2,
cont_current_prolog_flag, 0); cont_current_prolog_flag, 0);
Yap_InitCPredBack("current_prolog_flag", 2, 1, current_prolog_flag2, Yap_InitCPredBack("current_prolog_flag", 2, 1, current_prolog_flag2,

View File

@ -533,8 +533,7 @@ unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) {
#endif #endif
if (inp->type & YAP_STRING_TERM) { if (inp->type & YAP_STRING_TERM) {
// Yap_DebugPlWriteln(inp->val.t); // Yap_DebugPlWriteln(inp->val.t);
char *s = (char *)Yap_TermToBuffer(inp->val.t, ENC_ISO_UTF8, 0); char *s = (char *)Yap_TermToBuffer(inp->val.t, 0);
return inp->val.uc = pop_output_text_stack(lvl, s);
} }
if (inp->type & YAP_STRING_CHARS) { if (inp->type & YAP_STRING_CHARS) {
pop_text_stack(lvl); pop_text_stack(lvl);

View File

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

View File

@ -1255,9 +1255,9 @@ void Yap_plwrite(Term t, StreamDesc *mywrite, int max_depth, int flags,
pop_text_stack(lvl); pop_text_stack(lvl);
} }
char *Yap_TermToBuffer(Term t, encoding_t enc, int flags) { char *Yap_TermToBuffer(Term t, int flags) {
CACHE_REGS CACHE_REGS
int sno = Yap_open_buf_write_stream(enc, flags); int sno = Yap_open_buf_write_stream(LOCAL_encoding,flags);
const char *sf; const char *sf;
if (sno < 0) if (sno < 0)
@ -1266,17 +1266,13 @@ char *Yap_TermToBuffer(Term t, encoding_t enc, int flags) {
return NULL; return NULL;
else else
t = Deref(t); t = Deref(t);
if (enc)
GLOBAL_Stream[sno].encoding = enc;
else
GLOBAL_Stream[sno].encoding = LOCAL_encoding; GLOBAL_Stream[sno].encoding = LOCAL_encoding;
GLOBAL_Stream[sno].status |= CloseOnException_Stream_f; GLOBAL_Stream[sno].status |= CloseOnException_Stream_f;
Yap_plwrite(t, GLOBAL_Stream + sno, 0, flags, GLOBAL_MaxPriority); Yap_plwrite(t, GLOBAL_Stream + sno, 0, flags, GLOBAL_MaxPriority);
sf = Yap_MemExportStreamPtr(sno); sf = Yap_MemExportStreamPtr(sno);
size_t len = strlen(sf); size_t len = strlen(sf);
char *new = malloc(len + 1); char *new = realloc((void*)sf,len + 1);
strcpy(new, sf);
Yap_CloseStream(sno); Yap_CloseStream(sno);
return new; return new;
} }

View File

@ -19,7 +19,7 @@ extern "C" {
#include "YapInterface.h" #include "YapInterface.h"
#include "iopreds.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_UserCPredicate(const char *, YAP_UserCPred, arity_t arity);
X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, arity_t, X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, arity_t,
@ -30,12 +30,9 @@ X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred,
#if YAP_PYTHON #if YAP_PYTHON
X_API bool do_init_python(void); X_API bool do_init_python(void);
#endif #endif
} }
static void YAPCatchError() static void YAPCatchError() {
{
if (LOCAL_CommittedError != nullptr && if (LOCAL_CommittedError != nullptr &&
LOCAL_CommittedError->errorNo != YAP_NO_ERROR) { LOCAL_CommittedError->errorNo != YAP_NO_ERROR) {
// Yap_PopTermFromDB(info->errorTerm); // Yap_PopTermFromDB(info->errorTerm);
@ -522,8 +519,7 @@ bool YAPEngine::mgoal(Term t, Term tmod, bool release) {
#if YAP_PYTHON #if YAP_PYTHON
// PyThreadState *_save; // PyThreadState *_save;
std::cerr << "mgoal " << YAPTerm(t).text() << "\n";
//std::cerr << "mgoal " << YAPTerm(t).text() << "\n";
// _save = PyEval_SaveThread(); // _save = PyEval_SaveThread();
#endif #endif
CACHE_REGS CACHE_REGS
@ -557,6 +553,8 @@ bool YAPEngine::mgoal(Term t, Term tmod, bool release) {
//__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec "); //__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exec ");
result = (bool)YAP_EnterGoal(ap, nullptr, &q); result = (bool)YAP_EnterGoal(ap, nullptr, &q);
std::cerr << "mgoal " << YAPTerm(t).text() << "\n";
YAP_LeaveGoal(result && !release, &q); YAP_LeaveGoal(result && !release, &q);
// PyEval_RestoreThread(_save); // PyEval_RestoreThread(_save);
RECOVER_MACHINE_REGS(); RECOVER_MACHINE_REGS();
@ -666,7 +664,6 @@ goal = YAPApplTerm(f, nts);
} }
#endif #endif
YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) { YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) {
BACKUP_MACHINE_REGS(); BACKUP_MACHINE_REGS();
try { try {
@ -682,7 +679,6 @@ YAPQuery::YAPQuery(YAPPredicate p, YAPTerm ts[]) : YAPPredicate(p.ap) {
} }
names = TermNil; names = TermNil;
} catch (...) { } catch (...) {
} }
RECOVER_MACHINE_REGS(); RECOVER_MACHINE_REGS();
} }
@ -721,8 +717,7 @@ if (!result) {
} }
PredEntry *YAPQuery::rewriteUndefQuery() { PredEntry *YAPQuery::rewriteUndefQuery() {
ARG1 = goal = Yap_SaveTerm(Yap_MkApplTerm(FunctorCall ARG1 = goal = Yap_SaveTerm(Yap_MkApplTerm(FunctorCall, 1, &goal));
, 1, &goal));
return ap = PredCall; return ap = PredCall;
} }

View File

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

View File

@ -56,16 +56,14 @@ opportunity. Initial value is 10,000. May be changed. A value of 0
~~~ ~~~
*/ */
YAP_FLAG(ANSWER_FORMAT_FLAG, "answer_format", true, isatom, "~p", NULL), YAP_FLAG(ANSWER_FORMAT_FLAG, "answer_format", true, isatom, "~p", NULL),
/**< how to present answers, default is `~p`. */ /**< how to present answers, default is `~p`. */
#if __ANDROID__ #if __ANDROID__
YAP_FLAG(ANDROID_FLAG, "android", false, booleanFlag, "true", NULL), /**< 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 #endif
#if __APPLE__ #if __APPLE__
YAP_FLAG(APPLE_FLAG, "apple", false, booleanFlag, "true", NULL), /**< YAP_FLAG(APPLE_FLAG, "apple", false, booleanFlag, "true", NULL), /**<
read-only boolean, a machine running an Apple Operating System */ read-only boolean, a machine running an Apple Operating System */
@ -132,12 +130,14 @@ opportunity. Initial value is 10,000. May be changed. A value of 0
Writable flag telling whether a character escapes are enabled, Writable flag telling whether a character escapes are enabled,
`true`, or disabled, `false`. The default value for this flag is `true`, or disabled, `false`. The default value for this flag is
`true`. */ `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 ` /**< `compiled_at `
Read-only flag that gives the time when the main YAP binary was compiled. It Read-only flag that gives the time when the main YAP binary was compiled.
is obtained staight from the __TIME__ macro, as defined in the C99. 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, */
YAP_FLAG(COMPILED_AT_FLAG, "compiled_at", false, isatom, YAP_COMPILED_AT,
NULL), NULL),
YAP_FLAG(DEBUG_FLAG, "debug", true, booleanFlag, "false", NULL), YAP_FLAG(DEBUG_FLAG, "debug", true, booleanFlag, "false", NULL),
/**< /**<
@ -159,11 +159,14 @@ opportunity. Initial value is 10,000. May be changed. A value of 0
NULL), NULL),
YAP_FLAG(DEBUGGER_SHOW_CONTEXT_FLAG, "debugger_show_context", true, YAP_FLAG(DEBUGGER_SHOW_CONTEXT_FLAG, "debugger_show_context", true,
booleanFlag, "false", NULL), 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), YAP_FLAG(DIALECT_FLAG, "dialect", false, ro, "yap", NULL),
/**< /**<
@ -297,6 +300,8 @@ vxu `on` consider `$` a lower case character.
value `toward_zero` for the current version of YAP. value `toward_zero` for the current version of YAP.
*/ */
YAP_FLAG(ISO_FLAG, "iso", true, booleanFlag, "false", NULL), 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), YAP_FLAG(LANGUAGE_FLAG, "language", true, isatom, "yap", NULL),
/**< `language ` /**< `language `
@ -354,9 +359,8 @@ vxu `on` consider `$` a lower case character.
program. This is for compatibility with old software that program. This is for compatibility with old software that
might expect module-independent operators. might expect module-independent operators.
*/ */
YAP_FLAG(MODULE_INDEPENDENT_OPERATORS_FLAG, YAP_FLAG(MODULE_INDEPENDENT_OPERATORS_FLAG, "module_independent_operators",
"module_independent_operators", true, booleanFlag, true, booleanFlag, "false", NULL),
"false", NULL),
YAP_FLAG(OPTIMISE_FLAG, "optimise", 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), YAP_FLAG(OS_ARGV_FLAG, "os_argv", false, os_argv, "@boot", NULL),
@ -389,6 +393,15 @@ vxu `on` consider `$` a lower case character.
enable the use of the readline library for console interactions, true by enable the use of the readline library for console interactions, true by
default if readline was found. */ 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", YAP_FLAG(REPORT_ERROR_FLAG, "report_error", true, booleanFlag, "true",
NULL), NULL),
YAP_FLAG(RESOURCE_DATABASE_FLAG, "resource_database", false, isatom, YAP_FLAG(RESOURCE_DATABASE_FLAG, "resource_database", false, isatom,
@ -424,6 +437,15 @@ vxu `on` consider `$` a lower case character.
/**< `single_quoted text is usuallly interpreted as atoms. This flagTerm /**< `single_quoted text is usuallly interpreted as atoms. This flagTerm
allows other inerpretations such as strings_contains_strings */ 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), YAP_FLAG(SIGNALS_FLAG, "signals", true, booleanFlag, "true", NULL),
/**< `signals` /**< `signals`
@ -482,8 +504,7 @@ vxu `on` consider `$` a lower case character.
*/ */
YAP_FLAG(THREADS_FLAG, "threads", false, ro, "MAX_THREADS", NULL), YAP_FLAG(THREADS_FLAG, "threads", false, ro, "MAX_THREADS", NULL),
YAP_FLAG(TIMEZONE_FLAG, "timezone", false, ro, "18000", NULL), YAP_FLAG(TIMEZONE_FLAG, "timezone", false, ro, "18000", NULL),
YAP_FLAG(TOPLEVEL_HOOK_FLAG, "toplevel_hook", true, YAP_FLAG(TOPLEVEL_HOOK_FLAG, "toplevel_hook", true, booleanFlag, "true",
booleanFlag, "true",
NULL), NULL),
/**< `toplevel_hook ` /**< `toplevel_hook `
@ -527,9 +548,9 @@ vxu `on` consider `$` a lower case character.
are `silent`, `warning` and `error`. The first two create the flag are `silent`, `warning` and `error`. The first two create the flag
on-the-fly, with `warning` printing a message. The value `error` is 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 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 flag. See also `create_prolog_flag/3`. The default is`error`, and
are encouraged to use `create_prolog_flag/3` to create flags for their developers are encouraged to use `create_prolog_flag/3` to create flags for
library. their library.
*/ */
YAP_FLAG(UNKNOWN_FLAG, "unknown", true, isatom, "error", Yap_unknown), YAP_FLAG(UNKNOWN_FLAG, "unknown", true, isatom, "error", Yap_unknown),
/**< `unknown is iso` /**< `unknown is iso`

View File

@ -10,10 +10,8 @@
* * * *
************************************************************************** **************************************************************************
* * * *
* File: YapLFlagInfo.h * * File: YapLFlagInfo.h * Last rev:
* Last rev: * ** mods: * comments: local flag enumeration. *
* mods: *
* comments: local flag enumeration. *
* * * *
*************************************************************************/ *************************************************************************/
@ -34,48 +32,47 @@ START_LOCAL_FLAGS
YAP_FLAG(AUTOLOAD_FLAG, "autoload", true, booleanFlag, "false", NULL), YAP_FLAG(AUTOLOAD_FLAG, "autoload", true, booleanFlag, "false", NULL),
/** + `read-only flag, that tells if Prolog is in an inner top-level */ /** + `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(BREAK_LEVEL_FLAG, "break_level", true, nat, "0", NULL),
YAP_FLAG( CALL_COUNTING_FLAG, "call_counting", true, booleanFlag, "true" , NULL ), /** + `call_counting` 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; calls: number of predicate calls since execution started or
retries: number of retries for predicates called since execution started or since counters were reset; since system was reset; retries: number of retries for predicates
calls_and_retries: count both on predicate calls and retries. called since execution started or since counters were reset;
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 calls_and_retries: count both on predicate calls and
stopping. 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) If `on` `fileerrors` is `on`, if `off` (default)
`fileerrors` is disabled. `fileerrors` is disabled.
*/ */
YAP_FLAG(ENCODING_FLAG, "encoding", true, isatom, "utf-8", getenc), YAP_FLAG(ENCODING_FLAG, "encoding", true, isatom, "utf-8", getenc),
YAP_FLAG( FILEERRORS_FLAG, "fileerrors", true, booleanFlag, "true" , NULL ), /** + `fileerrors` YAP_FLAG(FILEERRORS_FLAG, "fileerrors", true, booleanFlag, "true",
NULL), /** + `fileerrors`
If `on` `fileerrors` is `on`, if `off` (default) If `on` `fileerrors` is `on`, if `off` (default)
`fileerrors` is disabled. `fileerrors` is disabled.
*/ */
YAP_FLAG( LANGUAGE_MODE_FLAG, "language_mode", true, isatom, "yap" , NULL ), /** + `language_mode` YAP_FLAG(LANGUAGE_MODE_FLAG, "language_mode", true, isatom, "yap",
NULL), /** + `language_mode`
wweter native mode or trying to emulate a different Prolog. wweter native mode or trying to emulate a different Prolog.
*/ */
YAP_FLAG( REDEFINE_WARNINGS_FLAG, "redefine_warnings", true, booleanFlag, "true" , NULL ), /** + `redefine_warnings ` 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`. `off`.
*/ */
YAP_FLAG( STREAM_TYPE_CHECK_FLAG, "stream_type_check", true, isatom, "loose" , NULL ), YAP_FLAG(STREAM_TYPE_CHECK_FLAG, "stream_type_check", true, isatom, "loose",
YAP_FLAG( SYNTAX_ERRORS_FLAG, "syntax_errors", true, synerr, "error" , NULL ), /** + `syntax_errors` 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`: `read/2`, or `read_term/3`:
@ -88,14 +85,16 @@ Report the syntax error and generate an error (default).
+ `quiet` + `quiet`
Just fail 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 which must be an atom. If unbound, unify the argument with the current
working module. 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 this stream. If the second argument is unbound, unify the argument with
@ -126,8 +125,10 @@ prompts from the system were redirected to the stream
automatically redirects the user_error alias to the original automatically redirects the user_error alias to the original
`stderr`. `stderr`.
*/ */
YAP_FLAG( USER_INPUT_FLAG, "user_input", true, stream, "user_input" , set_input_stream ), YAP_FLAG(USER_INPUT_FLAG, "user_input", true, stream, "user_input",
YAP_FLAG( USER_OUTPUT_FLAG, "user_output", true, stream, "user_output" , set_output_stream ), 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

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

View File

@ -1298,7 +1298,7 @@ INLINE_ONLY bool IsFlagProperty(PropFlags flags) {
/* Proto types */ /* Proto types */
extern char *Yap_TermToBuffer(Term t, encoding_t encoding, int flags); extern char *Yap_TermToBuffer(Term t, int flags);
extern Term Yap_BufferToTerm(const char *s, Term opts); extern Term Yap_BufferToTerm(const char *s, Term opts);

View File

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

View File

@ -817,6 +817,14 @@ X_API int PL_unify_bool(term_t t, int a) {
return Yap_unify(Yap_GetFromSlot(t), iterm); 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 #if USE_GMP
/******************************* /*******************************
@ -1272,7 +1280,7 @@ YAP: NO EQUIVALENT */
X_API int PL_raise_exception(term_t exception) { X_API int PL_raise_exception(term_t exception) {
CACHE_REGS CACHE_REGS
LOCAL_Error_TYPE = THROW_EVENT; 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_PutException(Yap_GetFromSlot(exception));
Yap_RaiseException(); Yap_RaiseException();
return 0; return 0;
@ -1320,7 +1328,7 @@ X_API int PL_unify_atom_chars(term_t t, const char *s) {
Atom at; Atom at;
while ((at = Yap_CharsToAtom(s, ENC_ISO_LATIN1 PASS_REGS)) == 0L) { while ((at = Yap_CharsToAtom(s, ENC_ISO_LATIN1 PASS_REGS)) == 0L) {
if (LOCAL_Error_TYPE && !Yap_SWIHandleError("PL_unify_atom_nchars")) if (LOCAL_Error_TYPE && !Yap_SWIHandleError("PL_unify_atom_nchars"))
return FALSE; return true;
} }
Yap_AtomIncreaseHold(at); Yap_AtomIncreaseHold(at);
return Yap_unify(Yap_GetFromSlot(t), MkAtomTerm(at)); return Yap_unify(Yap_GetFromSlot(t), MkAtomTerm(at));

View File

@ -672,7 +672,7 @@ static Int term_to_string(USES_REGS1) {
Term t2 = Deref(ARG2), rc = false, t1 = Deref(ARG1); Term t2 = Deref(ARG2), rc = false, t1 = Deref(ARG1);
const char *s; const char *s;
if (IsVarTerm(t2)) { 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)) { if (!s || !MkStringTerm(s)) {
Yap_Error(RESOURCE_ERROR_HEAP, t1, Yap_Error(RESOURCE_ERROR_HEAP, t1,
"Could not get memory from the operating system"); "Could not get memory from the operating system");
@ -692,7 +692,7 @@ static Int term_to_atom(USES_REGS1) {
Term t2 = Deref(ARG2), ctl, rc = false; Term t2 = Deref(ARG2), ctl, rc = false;
Atom at; Atom at;
if (IsVarTerm(t2)) { if (IsVarTerm(t2)) {
const char *s = Yap_TermToBuffer(Deref(ARG1), LOCAL_encoding, const char *s = Yap_TermToBuffer(Deref(ARG1),
Quote_illegal_f | Handle_vars_f); Quote_illegal_f | Handle_vars_f);
if (!s || !(at = Yap_UTF8ToAtom((const unsigned char *)s))) { if (!s || !(at = Yap_UTF8ToAtom((const unsigned char *)s))) {
Yap_Error(RESOURCE_ERROR_HEAP, t2, Yap_Error(RESOURCE_ERROR_HEAP, t2,

View File

@ -89,7 +89,7 @@ extern int Yap_GetCharForSIGINT(void);
extern Int Yap_StreamToFileNo(Term); extern Int Yap_StreamToFileNo(Term);
extern int Yap_OpenStream(Term tin, const char* io_mode, Term user_name, encoding_t enc); 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 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, extern char *Yap_HandleToString(yhandle_t l, size_t sz, size_t *length,
encoding_t *encoding, int flags); encoding_t *encoding, int flags);
extern int Yap_GetFreeStreamD(void); extern int Yap_GetFreeStreamD(void);

View File

@ -50,7 +50,8 @@ foreign_t assign_to_symbol(term_t t, PyObject *e) {
return PyObject_SetAttrString(dic, s, e) == 0; return PyObject_SetAttrString(dic, s, e) == 0;
} }
static int python_to_term__(PyObject *pVal, term_t t) { foreign_t python_to_term(PyObject *pVal, term_t t)
{
bool rc = true; bool rc = true;
term_t to = PL_new_term_ref(); term_t to = PL_new_term_ref();
// fputs(" <<*** ",stderr); PyObject_Print(pVal,stderr,0); // fputs(" <<*** ",stderr); PyObject_Print(pVal,stderr,0);
@ -89,13 +90,10 @@ static int python_to_term__(PyObject *pVal, term_t t) {
#else #else
const char *s = PyUnicode_AsUTF8(pVal); const char *s = PyUnicode_AsUTF8(pVal);
#endif #endif
// if (PyDict_GetItemString(py_Atoms, s)) if (Yap_AtomInUse(s))
// rc = rc && PL_unify_atom_chars(t, s); rc = rc && PL_unify_atom_chars(t, s);
// else else
rc = rc = rc && PL_unify_string_chars(t, s);
rc && (PL_is_string(t) ? PL_unify_string_chars(t, s)
: PL_is_variable(t) ? PL_unify_atom_chars(t, s)
: PL_unify_atom_chars(t, s));
} else if (PyByteArray_Check(pVal)) { } else if (PyByteArray_Check(pVal)) {
rc = rc && PL_unify_string_chars(t, PyByteArray_AsString(pVal)); rc = rc && PL_unify_string_chars(t, PyByteArray_AsString(pVal));
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
@ -133,14 +131,17 @@ static int python_to_term__(PyObject *pVal, term_t t) {
} }
if (PL_unify_functor(t, f)) { if (PL_unify_functor(t, f)) {
for (i = 0; i < sz; i++) { for (i = 0; i < sz; i++) {
term_t to = PL_new_term_ref();
if (!PL_get_arg(i + 1, t, to)) if (!PL_get_arg(i + 1, t, to))
rc = false; rc = false;
PyObject *p = PyTuple_GetItem(pVal, i); PyObject *p = PyTuple_GetItem(pVal, i);
if (p == NULL) { if (p == NULL) {
PyErr_Clear(); PyErr_Clear();
p = Py_None; p = Py_None;
} else {
rc = rc && python_to_term(p, to);
} }
rc = rc && python_to_term__(p, to); PL_reset_term_refs(to);
} }
} else { } else {
rc = false; rc = false;
@ -153,11 +154,13 @@ static int python_to_term__(PyObject *pVal, term_t t) {
for (i = 0; i < sz; i++) { for (i = 0; i < sz; i++) {
PyObject *obj; PyObject *obj;
term_t to = PL_new_term_ref();
rc = rc && PL_unify_list(t, to, t); rc = rc && PL_unify_list(t, to, t);
if ((obj = PyList_GetItem(pVal, i)) == NULL) { if ((obj = PyList_GetItem(pVal, i)) == NULL) {
obj = Py_None; obj = Py_None;
} }
rc = rc && python_to_term__(obj, to); rc = rc && python_to_term(obj, to);
PL_reset_term_refs(to);
if (!rc) if (!rc)
return false; return false;
} }
@ -166,7 +169,6 @@ static int python_to_term__(PyObject *pVal, term_t t) {
// Yap_DebugPlWrite(yt); fputs("[***]\n", stderr); // Yap_DebugPlWrite(yt); fputs("[***]\n", stderr);
} else if (PyDict_Check(pVal)) { } else if (PyDict_Check(pVal)) {
Py_ssize_t pos = 0; Py_ssize_t pos = 0;
term_t to = PL_new_term_ref(), ti = to;
int left = PyDict_Size(pVal); int left = PyDict_Size(pVal);
PyObject *key, *value; PyObject *key, *value;
@ -176,11 +178,12 @@ static int python_to_term__(PyObject *pVal, term_t t) {
while (PyDict_Next(pVal, &pos, &key, &value)) { while (PyDict_Next(pVal, &pos, &key, &value)) {
term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint, term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint,
tnew = PL_new_term_ref(); tnew = PL_new_term_ref();
term_t to = PL_new_term_ref();
/* do something interesting with the values... */ /* do something interesting with the values... */
if (!python_to_term__(key, tkey)) { if (!python_to_term(key, tkey)) {
continue; continue;
} }
if (!python_to_term__(value, tval)) { if (!python_to_term(value, tval)) {
continue; continue;
} }
/* reuse */ /* reuse */
@ -194,25 +197,26 @@ static int python_to_term__(PyObject *pVal, term_t t) {
PL_reset_term_refs(tkey); PL_reset_term_refs(tkey);
rc = false; rc = false;
} }
if (!PL_unify(ti, tint)) { if (!PL_unify(to, tint)) {
rc = false; rc = false;
} }
ti = tnew;
PL_reset_term_refs(tkey);
} }
rc = rc && PL_unify(t, to); rc = rc && PL_unify(t, to);
} }
} else { } else {
rc = rc && repr_term(pVal, t); rc = rc && repr_term(pVal, t);
} }
PL_reset_term_refs(to);
return rc; return rc;
} }
X_API YAP_Term pythonToYAP(PyObject *pVal) { X_API YAP_Term pythonToYAP(PyObject *pVal) {
term_t t = PL_new_term_ref(); term_t t = PL_new_term_ref();
if (pVal == NULL || !python_to_term__(pVal, t)) { if (pVal == NULL || !python_to_term(pVal, t)) {
PL_reset_term_refs(t); PL_reset_term_refs(t);
return 0; return 0;
} }
@ -224,13 +228,6 @@ X_API YAP_Term pythonToYAP(PyObject *pVal) {
PyObject *py_Local, *py_Global; PyObject *py_Local, *py_Global;
X_API foreign_t python_to_term(PyObject *pVal, term_t t) {
yap_error_descriptor_t *ctx = malloc(sizeof(yap_error_descriptor_t));
bool newxp = Yap_pushErrorContext(true, ctx);
int rc = python_to_term(pVal, t);
Yap_popErrorContext(newxp, true);
return rc;
}
/** /**
* assigns the Python RHS to a Prolog term LHS, ie LHS = RHS * assigns the Python RHS to a Prolog term LHS, ie LHS = RHS

View File

@ -41,6 +41,18 @@ class Engine( YAPEngine ):
self.goal(release) self.goal(release)
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.goal(set_prolog_flag('verbose', 'silent'),True)
self.goal(compile(library('jupyter')), True)
self.goal(set_prolog_flag('verbose', 'normal'), True)
class EngineArgs( YAPEngineArgs ): class EngineArgs( YAPEngineArgs ):
""" Interface to Engine Options class""" """ Interface to Engine Options class"""
def __init__(self, args=None,**kwargs): def __init__(self, args=None,**kwargs):

View File

@ -281,6 +281,7 @@ set (RENAMED_RESOURCES
) )
set (PL_SOURCES yap_ipython/prolog/jupyter.yap yap_ipython/prolog/complete.yap 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(FILES ${PYTHON_SOURCES} ${PL_SOURCES} ${EXTRAS} ${RESOURCES})

View File

@ -4,6 +4,7 @@
* @brief JUpyter support. * @brief JUpyter support.
*/ */
:- yap_flag(gc_trace,verbose).
% :- module( jupyter, % :- module( jupyter,
% [jupyter_query/3, % [jupyter_query/3,
@ -20,16 +21,11 @@
:- use_module(library(python)). :- use_module(library(python)).
:- use_module(library(yapi)). :- use_module(library(yapi)).
:- use_module(library(complete)). :- use_module(library(complete)).
:- use_module(library(verify)).
:- python_import(sys). :- python_import(sys).
jupyter_query(Caller, Prog, Query ) :- jupyter_query(Caller, Cell, Line ) :-
catch( jupyter_cell(Caller, Cell, Line).
jupyter_cell(Caller, Prog, Query),
error(L,E),
system_error(L,E)
).
jupyter_cell(_Caller, Cell, _Line) :- jupyter_cell(_Caller, Cell, _Line) :-
jupyter_consult(Cell), %stack_dump, jupyter_consult(Cell), %stack_dump,
@ -38,16 +34,44 @@ jupyter_cell( _Caller, _, '' ) :- !.
jupyter_cell( _Caller, _, Line ) :- jupyter_cell( _Caller, _, Line ) :-
blank( Line ), blank( Line ),
!. !.
jupyter_cell( Self, _, Line ) :- jupyter_cell( Caller, _, Line ) :-
%Self := Caller.query, Self := Caller.query,
python_query(Self,Line). catch(
python_query(Self,Line),
E=error(A,B),
system_error(A,B)
).
jupyter_cell(_,_,_).
restreams(call) :-
streams(true).
restreams(fail) :-
streams(false).
restreams(answer).
restreams(exit) :-
streams(false).
restreams(!).
restreams(external_exception(_)).
restreams(exception).
jupyter_consult(Text) :- jupyter_consult(Text) :-
blank( Text ), blank( Text ),
!. !.
jupyter_consult(Cell) :- jupyter_consult(Cell) :-
% Name = 'Inp',
% stream_property(Stream, file_name(Name) ),
% setup_call_cleanup(
catch(
(
Options = [],
open_mem_read_stream( Cell, Stream), open_mem_read_stream( Cell, Stream),
load_files(user:'jupyter cell',[stream(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) :- blank(Text) :-
atom(Text), atom(Text),
@ -60,17 +84,112 @@ jupyter_consult(Cell) :-
string_codes(Text, L), string_codes(Text, L),
maplist( code_type(space), L). maplist( code_type(space), L).
streams(false) :- streams(false) :-
nb_setval(jupyter_cell, false),
close(user_input), close(user_input),
close(user_output), close(user_output),
close(user_error). close(user_error).
streams(true) :- streams(true) :-
nb_setval(jupyter_cell, true), open('/python/input', read, Input, [alias(user_input),bom(false),script(false)]),
open('/python/input', read, _Input, [alias(user_input),bom(false),script(false)]), open('/python/sys.stdout', append, Output, [alias(user_output)]),
open('/python/sys.stdout', append, _Output, [alias(user_output)]), open('/python/sys.stderr', append, Error, [alias(user_error)]).
open('/python/sys.stderr', append, _Error, [alias(user_error)]).
ready(_Self, Line ) :-
blank( Line ),
!.
ready(Self, Line ) :-
errors( Self, Line ),
\+ syntax_error(_,_).
errors( Self, Text ) :-
setup_call_cleanup(
open_events( Self, Text, Stream),
goals(Self, Stream),
close_events( Self )
).
clauses(_Self, Stream) :-
repeat,
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
% command( Self, Cl ),
Cl == end_of_file,
!.
goals(_Self, Stream) :-
repeat,
read_term(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
% command( Self, Cl ),
Cl == end_of_file,
!.
command(_, end_of_file) :- !.
command( _Self, ( :- op(Prio,Assoc,Name) ) ) :-
addop(Prio,Assoc,Name).
command( _Self, ( :- module(Name, Exports) )) :-
retract( active_module( M0 ) ),
atom_concat( '__m0_', Name, M ),
assert( active_module(M) ),
assert( undo( active_module(M0) ) ),
maplist( addop2(M), Exports).
addop(Prio,Assoc,Name) :-
(
current_op(OPrio, SimilarAssoc, Name),
op(Prio, Assoc, Name),
matched_op(Assoc, SimilarAssoc)
->
assertz( undo(op( OPrio, Assoc, Name ) ) )
;
assertz( undo(op( 0, Assoc, Name ) ) )
).
addop2(M, op(Prio, Assoc, Name)) :-
addop( Prio, Assoc, M:Name ).
matched_op(A, B) :-
optype( A, T),
optype( B, T).
optype(fx,pre).
optype(fy,pre).
optype(xfx,in).
optype(xfy,in).
optype(yfx,in).
optype(yfy,in).
optype(xf,pos).
optype(yf,pos).
:- dynamic user:portray_message/2.
:- multifile user:portray_message/2.
:- dynamic syntax_error/4, undo/1.
user:portray_message(_Severity, error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
nb_getval(jupyter_cell, on),
assert( syntax_error(Cause,LN,CharPos,Details) ).
user:portray_message(_Severity, error(style_check(_),_) ) :-
nb_getval(jupyter_cell, on).
open_events(Self, Text, Stream) :-
Self.errors := [],
nb_setval( jupyter, on),
open_mem_read_stream( Text, Stream ).
:- initialization( nb_setval( jupyter, off ) ).
close_events( _Self ) :-
nb_setval( jupyter, off ),
retract( undo(G) ),
call(G),
fail.
close_events( Self ) :-
retract( syntax_error( C, L, N, A )),
Self.errors := [t(C,L,N,A)] + Self.errors,
fail.
close_events( _ ).
:- if( current_prolog_flag(apple, true) ). :- if( current_prolog_flag(apple, true) ).

View File

@ -22,45 +22,41 @@ s % completion/2,
:- python_import(sys). :- python_import(sys).
all_clear( Self, _Cell, P, Q) :- p_errors( Errors, Cell) :-
no_errors( Self, P ), blank( Cell ),
yap_flag(singleton_variables, Old, false), !.
no_errors( Self, Q ), p_errors( Errors, Cell) :-
yap_flag(singleton_variables, _, Old). no_errors( Errors , Cell ).
no_errors( _Self, Text ) :- no_errors( _Errors , Text ) :-
blank(Text). blank(Text).
no_errors( Self, Text ) :- no_errors( Errors , Text ) :-
setup_call_cleanup( setup_call_cleanup(
open_esh( Self, Text, Stream), open_esh( Errors , Text, Stream),
esh(Self, Stream), esh(Errors , Stream),
close_esh( Self, Stream ) close_esh( Errors , Stream )
). ).
syntax(_Self, E) :- writeln(user_error, E), fail. syntax(_Errors , E) :- writeln(user_error, E), fail.
syntax(Self, error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :- syntax(Errors , error(syntax_error(Cause),info(between(_,LN,_), _FileName, CharPos, Details))) :-
Self.errors := [t(Cause,LN,CharPos,Details)] + Self.errors, Errors.errors := [t(Cause,LN,CharPos,Details)] + Errors.errors,
!. !.
syntax(_Self, E) :- throw(E). syntax(_Errors , E) :- throw(E).
open_esh(Self, Text, Stream) :- open_esh(_Errors , Text, Stream) :-
Self.errors := [],
open_mem_read_stream( Text, Stream ). open_mem_read_stream( Text, Stream ).
esh(Self, Stream) :- esh(Errors , Stream) :-
repeat, repeat,
catch( catch(
read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ), read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ),
Error, Error,
syntax(Self, Error) syntax(Errors , Error)
), ),
Cl == end_of_file, Cl == end_of_file,
!, !.
V := Self.errors,
V == [].
close_esh( _Self, Stream ) :- close_esh( _Errors , Stream ) :-
close(Stream). close(Stream).

View File

@ -23,11 +23,11 @@ library = namedtuple('library', 'list')
v = namedtuple('_', 'slot') v = namedtuple('_', 'slot')
load_files = namedtuple('load_files', 'file ofile args') load_files = namedtuple('load_files', 'file ofile args')
python_query = namedtuple('python_query', 'query_mgr string') python_query = namedtuple('python_query', 'query_mgr string')
jupyter_query = namedtuple('jupyter_query', 'self text p q') jupyter_query = namedtuple('jupyter_query', 'self text query')
enter_cell = namedtuple('enter_cell', 'self' ) enter_cell = namedtuple('enter_cell', 'self' )
exit_cell = namedtuple('exit_cell', 'self' ) exit_cell = namedtuple('exit_cell', 'self' )
completions = namedtuple('completions', 'txt self' ) completions = namedtuple('completions', 'txt self' )
errors = namedtuple('errors', 'self text p q' ) errors = namedtuple('errors', 'self text' )
streams = namedtuple('streams', ' text' ) streams = namedtuple('streams', ' text' )
nostreams = namedtuple('nostreams', ' text' ) nostreams = namedtuple('nostreams', ' text' )
@ -114,7 +114,7 @@ class YAPInputSplitter(InputSplitter):
if not line: if not line:
line = text.rstrip() line = text.rstrip()
self.errors = [] self.errors = []
engine.mgoal(errors(self, text ,text,''),"user",True) engine.mgoal(errors(self, line),"user",True)
return self.errors != [] return self.errors != []
@ -510,17 +510,16 @@ class YAPRun:
def __init__(self, shell): def __init__(self, shell):
self.shell = shell self.shell = shell
self.yapeng = Engine() self.yapeng = JupyterEngine()
global engine global engine
engine = self.yapeng engine = self.yapeng
self.yapeng.goal(use_module(library("jupyter")),True)
self.query = None self.query = None
self.os = None self.os = None
self.it = None self.it = None
self.shell.yapeng = self.yapeng self.shell.yapeng = self.yapeng
self._get_exc_info = shell._get_exc_info self._get_exc_info = shell._get_exc_info
def syntaxErrors(self, text,program,query): def syntaxErrors(self, text):
"""Return whether a legal query """Return whether a legal query
""" """
if not text: if not text:
@ -528,7 +527,8 @@ class YAPRun:
if text == self.os: if text == self.os:
return self.errors return self.errors
self.errors=[] self.errors=[]
self.yapeng.mgoal(errors(self,text,program,query),"user",True) (text,_,_,_) = self.clean_end(text)
self.yapeng.mgoal(errors(self,text),"user",True)
return self.errors return self.errors
def jupyter_query(self, s): def jupyter_query(self, s):
@ -572,7 +572,6 @@ class YAPRun:
except Exception as e: except Exception as e:
sys.stderr.write('Exception after', self.bindings, '\n') sys.stderr.write('Exception after', self.bindings, '\n')
has_raised = True has_raised = True
self.yapeng.mgoal(streams(False),"user", True)
return False,[] return False,[]
@ -654,8 +653,7 @@ class YAPRun:
# except SyntaxError: # except SyntaxError:
# preprocessing_exc_tuple = self.shell.syntax_error() # sys.exc_info() # preprocessing_exc_tuple = self.shell.syntax_error() # sys.exc_info()
cell = raw_cell # cell has to exist so it can be stored/logged cell = raw_cell # cell has to exist so it can be stored/logged
(text,program,query,_) = self.clean_end(raw_cell) for i in self.syntaxErrors(raw_cell):
for i in self.syntaxErrors(raw_cell,raw_cell,''):
try: try:
(what,lin,_,text) = i (what,lin,_,text) = i
e = SyntaxError(what, ("<string>", lin, 1, text)) e = SyntaxError(what, ("<string>", lin, 1, text))
@ -730,13 +728,13 @@ class YAPRun:
# state = tracer.runfunc(jupyter_query( self, cell ) ) # state = tracer.runfunc(jupyter_query( self, cell ) )
self.shell.last_execution_succeeded = True self.shell.last_execution_succeeded = True
self.result.result = (True, dicts) self.result.result = (True, dicts)
self.yapeng.mgoal(streams(False),"user", True)
except Exception as e: except Exception as e:
has_raised = True has_raised = True
self.result.result = False self.result.result = False
self.yapeng.mgoal(streams(False),"user", True) self.yapeng.mgoal(streams(False),"user", True)
self.yapeng.mgoal(streams(False),"user", True)
self.shell.last_execution_succeeded = not has_raised self.shell.last_execution_succeeded = not has_raised
# Reset this so later displayed values do not modify the # Reset this so later displayed values do not modify the

View File

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

View File

@ -221,7 +221,9 @@ SWI-compatible option where if _Autoload_ is `true` undefined
% register(true, false) => implemented % register(true, false) => implemented
% %
load_files(Files,Opts) :- load_files(Files,Opts) :-
'$load_files'(Files,Opts,load_files(Files,Opts)). once( '$load_files'(Files,Opts,load_files(Files,Opts)) ),
fail.
load_files(_Files,_Opts).
'$lf_option'(autoload, 1, false). '$lf_option'(autoload, 1, false).
'$lf_option'(derived_from, 2, false). '$lf_option'(derived_from, 2, false).
@ -272,8 +274,7 @@ load_files(Files,Opts) :-
setarg( Id, TOpts, Val ). setarg( Id, TOpts, Val ).
'$load_files'(Files, Opts, Call) :- '$load_files'(Files, Opts, Call) :-
( '__NB_getval__'('$lf_status', OldTOpts, fail), nonvar(OldTOpts) -> ( '__NB_getval__'('$lf_status', OldTOpts, fail), nonvar(OldTOpts) - '$lf_opt'(autoload, OldTOpts, OldAutoload)
'$lf_opt'(autoload, OldTOpts, OldAutoload)
; ;
'$lf_option'(last_opt, LastOpt), '$lf_option'(last_opt, LastOpt),
functor( OldTOpts, opt, LastOpt ), functor( OldTOpts, opt, LastOpt ),
@ -544,10 +545,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. _F_ must be a list containing the names of the files to load.
*/ */
ensure_loaded(Fs) :- ensure_loaded(Fs) :-
'$load_files'(Fs, [if(not_loaded)],ensure_loaded(Fs)). load_files(Fs, [if(not_loaded)]).
compile(Fs) :- compile(Fs) :-
'$load_files'(Fs, [], compile(Fs)). load_files(Fs, []).
/** /**
@pred [ _F_ ] @pred [ _F_ ]
@ -581,9 +582,9 @@ consult(Fs) :-
'$consult'(Fs,Module) :- '$consult'(Fs,Module) :-
current_prolog_flag(language_mode, iso), % SICStus Prolog compatibility current_prolog_flag(language_mode, iso), % SICStus Prolog compatibility
!, !,
'$load_files'(Module:Fs,[],consult(Fs)). load_files(Module:Fs,[]).
'$consult'(Fs, Module) :- '$consult'(Fs, Module) :-
'$load_files'(Module:Fs,[consult(consult)],consult(Fs)). load_files(Module:Fs,[consult(consult)]).
/** /**
@ -616,7 +617,7 @@ Example:
*/ */
reconsult(Fs) :- reconsult(Fs) :-
'$load_files'(Fs, [], reconsult(Fs)). load_files(Fs, []).
/* exo_files(+ _Files_) /* exo_files(+ _Files_)
@ -636,7 +637,7 @@ different forms of indexing, as shown in @cite x.
*/ */
exo_files(Fs) :- exo_files(Fs) :-
'$load_files'(Fs, [consult(exo), if(not_loaded)], exo_files(Fs)). load_files(Fs, [consult(exo), if(not_loaded)]).
/** /**
@ -667,7 +668,7 @@ 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/1 itself is just a call to load_files/2.
*/ */
db_files(Fs) :- 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) :- '$csult'(Fs, _M) :-
@ -677,9 +678,9 @@ db_files(Fs) :-
!. !.
'$csult'(Fs, M) :- '$csult'(Fs, M) :-
'$extract_minus'(Fs, MFs), !, '$extract_minus'(Fs, MFs), !,
'$load_files'(M:MFs,[],[M:Fs]). load_files(M:MFs,[]).
'$csult'(Fs, M) :- '$csult'(Fs, M) :-
'$load_files'(M:Fs,[consult(consult)],[M:Fs]). load_files(M:Fs,[consult(consult)]).
'$extract_minus'([], []). '$extract_minus'([], []).
'$extract_minus'([-F|Fs], [F|MFs]) :- '$extract_minus'([-F|Fs], [F|MFs]) :-

View File

@ -176,23 +176,23 @@ considered.
'$exec_directive'(set_prolog_flag(F,V), _, _, _, _) :- '$exec_directive'(set_prolog_flag(F,V), _, _, _, _) :-
set_prolog_flag(F,V). set_prolog_flag(F,V).
'$exec_directive'(ensure_loaded(Fs), _, M, _, _) :- '$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), _, _, _, _) :- '$exec_directive'(char_conversion(IN,OUT), _, _, _, _) :-
char_conversion(IN,OUT). char_conversion(IN,OUT).
'$exec_directive'(public(P), _, M, _, _) :- '$exec_directive'(public(P), _, M, _, _) :-
'$public'(P, M). '$public'(P, M).
'$exec_directive'(compile(Fs), _, M, _, _) :- '$exec_directive'(compile(Fs), _, M, _, _) :-
'$load_files'(M:Fs, [], compile(Fs)). load_files(M:Fs, []).
'$exec_directive'(reconsult(Fs), _, M, _, _) :- '$exec_directive'(reconsult(Fs), _, M, _, _) :-
'$load_files'(M:Fs, [], reconsult(Fs)). load_files(M:Fs, []).
'$exec_directive'(consult(Fs), _, M, _, _) :- '$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, _, _) :- '$exec_directive'(use_module(F), _, M, _, _) :-
use_module(M:F). use_module(M:F).
'$exec_directive'(reexport(F), _, M, _, _) :- '$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, _, _) :- '$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, _, _) :- '$exec_directive'(use_module(F, Is), _, M, _, _) :-
use_module(M:F, Is). use_module(M:F, Is).
'$exec_directive'(use_module(Mod,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_. * Generate a system error _Error_, informing the possible cause _Cause_.
* *
*/ */
system_error(Type,Goal) :- prolog:system_error(Type,Goal) :-
'$do_error'(Type,Goal). '$do_error'(Type,Goal).

View File

@ -259,11 +259,11 @@ location( error(_,Info), Level, LC ) -->
{ '$error_descriptor'(Info, Desc) }, { '$error_descriptor'(Info, Desc) },
{ {
'$query_exception'(prologPredFile, Desc, File), query_exception(prologPredFile, Desc, File),
'$query_exception'(prologPredLine, Desc, FilePos), query_exception(prologPredLine, Desc, FilePos),
'$query_exception'(prologPredModule, Desc, M), query_exception(prologPredModule, Desc, M),
'$query_exception'(prologPredName, Desc, Na), query_exception(prologPredName, Desc, Na),
'$query_exception'(prologPredArity, Desc, Ar) query_exception(prologPredArity, Desc, Ar)
}, },
!, !,
display_consulting( File, Level, Info, LC ), display_consulting( File, Level, Info, LC ),
@ -271,9 +271,9 @@ location( error(_,Info), Level, LC ) -->
location( error(_,Info), Level, LC ) --> location( error(_,Info), Level, LC ) -->
{ '$error_descriptor'(Info, Desc) }, { '$error_descriptor'(Info, Desc) },
{ {
'$query_exception'(errorFile, Desc, File), query_exception(errorFile, Desc, File),
'$query_exception'(errorLine, Desc, FilePos), query_exception(errorLine, Desc, FilePos),
'$query_exception'(errorFunction, Desc, F) query_exception(errorFunction, Desc, F)
}, },
!, !,
display_consulting( File, Level, Info, LC ), display_consulting( File, Level, Info, LC ),
@ -295,6 +295,10 @@ main_message( error(syntax_error(Msg),info(between(L0,LM,LF),_Stream, _Pos, Term
[' ~a: failed_processing syntax error term ~q' - [Level,Term]], [' ~a: failed_processing syntax error term ~q' - [Level,Term]],
[nl] [nl]
). ).
main_message( error(syntax_error(_Msg), Info), Level, LC ) -->
!,
[' ~a: syntax error ~s' - [Level,Msg]],
[nl].
main_message(style_check(singleton(SVs),_Pos,_File,P), _Level, _LC) --> main_message(style_check(singleton(SVs),_Pos,_File,P), _Level, _LC) -->
!, !,
% {writeln(ci)}, % {writeln(ci)},
@ -342,8 +346,8 @@ main_message(error(uninstantiation_error(T),_), Level, _LC) -->
display_consulting( F, Level, Info, LC) --> display_consulting( F, Level, Info, LC) -->
{ LC > 0, { LC > 0,
'$error_descriptor'(Info, Desc), '$error_descriptor'(Info, Desc),
'$query_exception'(prologParserFile, Desc, F0), query_exception(prologParserFile, Desc, F0),
'$query_exception'(prologarserLine, Desc, L), query_exception(prologarserLine, Desc, L),
F \= F0 F \= F0
}, !, }, !,
[ '~a:~d:0: ~a raised at:'-[F0,L,Level], nl ]. [ '~a:~d:0: ~a raised at:'-[F0,L,Level], nl ].
@ -358,7 +362,7 @@ display_consulting(_F, _, _, _LC) -->
caller( Info, _) --> caller( Info, _) -->
{ '$error_descriptor'(Info, Desc) }, { '$error_descriptor'(Info, Desc) },
({ '$query_exception'(errorGoal, Desc, Call), ({ query_exception(errorGoal, Desc, Call),
Call = M:(H :- G) Call = M:(H :- G)
} }
-> ->
@ -372,12 +376,12 @@ caller( Info, _) -->
; ;
[] []
), ),
{ '$query_exception'(prologPredFile, Desc, File), { query_exception(prologPredFile, Desc, File),
File \= [], File \= [],
'$query_exception'(prologPredLine, Desc, FilePos), query_exception(prologPredLine, Desc, FilePos),
'$query_exception'(prologPredModule, Desc, M), query_exception(prologPredModule, Desc, M),
'$query_exception'(prologPredName, Desc, Na), query_exception(prologPredName, Desc, Na),
'$query_exception'(prologPredArity, Desc, Ar) query_exception(prologPredArity, Desc, Ar)
}, },
!, !,
[nl], [nl],
@ -388,10 +392,10 @@ caller( _, _) -->
c_goal( Info, Level ) --> c_goal( Info, Level ) -->
{ '$error_descriptor'(Info, Desc) }, { '$error_descriptor'(Info, Desc) },
{ '$query_exception'(errorFile, Desc, File), { query_exception(errorFile, Desc, File),
Func \= [], Func \= [],
'$query_exception'(errorFunction, Desc, File), query_exception(errorFunction, Desc, File),
'$query_exception'(errorLine, Desc, Line) query_exception(errorLine, Desc, Line)
}, },
!, !,
['~*|~a raised at C-function ~a() in ~a:~d:0: '-[10, Level, Func, File, Line]], ['~*|~a raised at C-function ~a() in ~a:~d:0: '-[10, Level, Func, File, Line]],
@ -620,7 +624,7 @@ domain_error(Domain, Opt) -->
extra_info( error(_,Extra), _ ) --> extra_info( error(_,Extra), _ ) -->
{ {
'$query_exception'(prologPredFile, Extra, Msg), query_exception(prologPredFile, Extra, Msg),
Msg \= [] Msg \= []
}, },
!, !,
@ -1048,6 +1052,12 @@ prolog:print_message(_Severity, _Term) :-
'$error_descriptor'( exception(Info), Info ). '$error_descriptor'( exception(Info), Info ).
query_exception(K0,[H|L],V) :-
(atom(K0) -> atom_to_string(K0, K) ; K = K0),
!,
lists:member(K=V,[H|L]).
query_exception(K,V) :-
'$query_exception'(K,V).
/** /**
@} @}