bug fices

This commit is contained in:
Vítor Santos Costa 2016-01-03 02:06:09 +00:00
parent 7a7354fb2b
commit 661f33ac7e
133 changed files with 6000 additions and 9890 deletions

View File

@ -70,6 +70,7 @@ inline static ModEntry *GetModuleEntry(Atom at)
new->NextME = CurrentModules; new->NextME = CurrentModules;
CurrentModules = new; CurrentModules = new;
new->AtomOfME = ae; new->AtomOfME = ae;
new->OwnerFile = Yap_ConsultingFile( PASS_REGS1);
AddPropToAtom(ae, (PropEntry *)new); AddPropToAtom(ae, (PropEntry *)new);
if (CurrentModule == 0L || (oat = GetModuleEntry(AtomOfTerm(CurrentModule))) == new) { if (CurrentModule == 0L || (oat = GetModuleEntry(AtomOfTerm(CurrentModule))) == new) {
Yap_setModuleFlags(new, NULL); Yap_setModuleFlags(new, NULL);
@ -85,6 +86,8 @@ Term Yap_getUnknownModule(ModEntry *m) {
return TermError; return TermError;
} else if (m && m->flags & UNKNOWN_WARNING) { } else if (m && m->flags & UNKNOWN_WARNING) {
return TermWarning; return TermWarning;
} else if (m && m->flags & UNKNOWN_FAST_FAIL) {
return TermFastFail;
} else { } else {
return TermFail; return TermFail;
} }
@ -92,13 +95,7 @@ Term Yap_getUnknownModule(ModEntry *m) {
bool Yap_getUnknown ( Term mod) { bool Yap_getUnknown ( Term mod) {
ModEntry *m = LookupModule( mod ); ModEntry *m = LookupModule( mod );
if (m && m->flags & UNKNOWN_ERROR) { return Yap_getUnknownModule( m );
return TermError;
} else if (m && m->flags & UNKNOWN_WARNING) {
return TermWarning;
} else {
return TermFail;
}
} }
@ -131,8 +128,10 @@ Term Yap_Module_Name(PredEntry *ap) {
} }
static ModEntry *LookupSystemModule(Term a) { static ModEntry *LookupSystemModule(Term a) {
CACHE_REGS
Atom at; Atom at;
ModEntry *me; ModEntry *me;
/* prolog module */ /* prolog module */
if (a == 0) { if (a == 0) {
@ -141,6 +140,7 @@ static ModEntry *LookupSystemModule(Term a) {
at = AtomOfTerm(a); at = AtomOfTerm(a);
me = GetModuleEntry(at); me = GetModuleEntry(at);
me->flags |= M_SYSTEM; me->flags |= M_SYSTEM;
me->OwnerFile = Yap_ConsultingFile( PASS_REGS1 );
return me;} return me;}
@ -316,7 +316,7 @@ static Int init_ground_module(USES_REGS1) {
} }
/** /**
* @pred is_system_module( + _Mod_) * @pred system_module( + _Mod_)
* *
* @param module * @param module
* *
@ -335,7 +335,7 @@ static Int is_system_module( USES_REGS1 )
return Yap_isSystemModule( t ); return Yap_isSystemModule( t );
} }
static Int system_module( USES_REGS1 ) static Int new_system_module( USES_REGS1 )
{ {
ModEntry *me; ModEntry *me;
Term t; Term t;
@ -348,6 +348,7 @@ static Int system_module( USES_REGS1 )
return false; return false;
} }
me = LookupSystemModule( t ); me = LookupSystemModule( t );
me->OwnerFile = Yap_ConsultingFile( PASS_REGS1);
return me != NULL; return me != NULL;
} }
@ -495,8 +496,8 @@ void Yap_InitModulesC(void) {
Yap_InitCPred("$yap_strip_module", 3, yap_strip_module, Yap_InitCPred("$yap_strip_module", 3, yap_strip_module,
SafePredFlag | SyncPredFlag); SafePredFlag | SyncPredFlag);
Yap_InitCPred("context_module", 1, context_module, 0); Yap_InitCPred("context_module", 1, context_module, 0);
Yap_InitCPred("system_module", 1, system_module, SafePredFlag); Yap_InitCPred("$is_system_module", 1, is_system_module, SafePredFlag);
Yap_InitCPred("is_system_module", 1, is_system_module, SafePredFlag); Yap_InitCPred("new_system_module", 1, new_system_module, SafePredFlag);
Yap_InitCPredBack("$all_current_modules", 1, 1, init_current_module, Yap_InitCPredBack("$all_current_modules", 1, 1, init_current_module,
cont_current_module, SafePredFlag | SyncPredFlag); cont_current_module, SafePredFlag | SyncPredFlag);
Yap_InitCPredBack("$ground_module", 3, 1, init_ground_module, Yap_InitCPredBack("$ground_module", 3, 1, init_ground_module,

View File

@ -745,34 +745,46 @@ static Term ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) {
case String_tok: /* build list on the heap */ case String_tok: /* build list on the heap */
{ {
Volatile char *p = (char *)LOCAL_tokptr->TokInfo; Volatile char *p = (char *)LOCAL_tokptr->TokInfo;
// we may be operating under a syntax error
yap_error_number oerr = LOCAL_Error_TYPE;
LOCAL_Error_TYPE = YAP_NO_ERROR;
t = Yap_CharsToTDQ(p, CurrentModule, LOCAL_encoding PASS_REGS); t = Yap_CharsToTDQ(p, CurrentModule, LOCAL_encoding PASS_REGS);
if (!t) { if (!t) {
syntax_msg("could not convert \"%s\"", (char *)LOCAL_tokptr->TokInfo); syntax_msg("could not convert \"%s\"", (char *)LOCAL_tokptr->TokInfo);
FAIL; FAIL;
} }
LOCAL_Error_TYPE = oerr;
NextToken; NextToken;
} break; } break;
case WString_tok: /* build list on the heap */ case WString_tok: /* build list on the heap */
{ {
Volatile wchar_t *p = (wchar_t *)LOCAL_tokptr->TokInfo; Volatile wchar_t *p = (wchar_t *)LOCAL_tokptr->TokInfo;
// we may be operating under a syntax error
yap_error_number oerr = LOCAL_Error_TYPE;
LOCAL_Error_TYPE = YAP_NO_ERROR;
t = Yap_WCharsToTDQ(p, CurrentModule PASS_REGS); t = Yap_WCharsToTDQ(p, CurrentModule PASS_REGS);
if (!t) { if (!t) {
syntax_msg("could not convert \'%S\'", (wchar_t *)LOCAL_tokptr->TokInfo); syntax_msg("could not convert \'%S\'", (wchar_t *)LOCAL_tokptr->TokInfo);
FAIL; FAIL;
} }
NextToken; LOCAL_Error_TYPE = oerr;
NextToken;
} break; } break;
case BQString_tok: /* build list on the heap */ case BQString_tok: /* build list on the heap */
{ {
Volatile char *p = (char *)LOCAL_tokptr->TokInfo; Volatile char *p = (char *)LOCAL_tokptr->TokInfo;
// we may be operating under a syntax error
yap_error_number oerr = LOCAL_Error_TYPE;
LOCAL_Error_TYPE = YAP_NO_ERROR;
t = Yap_CharsToTBQ(p, CurrentModule, LOCAL_encoding PASS_REGS); t = Yap_CharsToTBQ(p, CurrentModule, LOCAL_encoding PASS_REGS);
if (!t) { if (!t) {
syntax_msg("could not convert \'%s\"", (char *)LOCAL_tokptr->TokInfo); syntax_msg("could not convert \'%s\"", (char *)LOCAL_tokptr->TokInfo);
FAIL; FAIL;
} }
LOCAL_Error_TYPE = oerr;
NextToken; NextToken;
} break; } break;
@ -780,10 +792,14 @@ static Term ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) {
{ {
Volatile wchar_t *p = (wchar_t *)LOCAL_tokptr->TokInfo; Volatile wchar_t *p = (wchar_t *)LOCAL_tokptr->TokInfo;
t = Yap_WCharsToTBQ(p, CurrentModule PASS_REGS); t = Yap_WCharsToTBQ(p, CurrentModule PASS_REGS);
// we may be operating under a syntax error
yap_error_number oerr = LOCAL_Error_TYPE;
LOCAL_Error_TYPE = YAP_NO_ERROR;
if (!t) { if (!t) {
syntax_msg("could not convert \"%S\"", (wchar_t *)LOCAL_tokptr->TokInfo); syntax_msg("could not convert \"%S\"", (wchar_t *)LOCAL_tokptr->TokInfo);
FAIL; FAIL;
} }
LOCAL_Error_TYPE = oerr;
NextToken; NextToken;
} break; } break;

View File

@ -698,7 +698,7 @@ read_tag(FILE *stream)
return ch; return ch;
} }
static UInt static pred_flags_t
read_predFlags(FILE *stream) read_predFlags(FILE *stream)
{ {
pred_flags_t v; pred_flags_t v;
@ -1018,23 +1018,30 @@ read_pred(FILE *stream, Term mod) {
ap = LookupPredEntry((PredEntry *)read_UInt(stream)); ap = LookupPredEntry((PredEntry *)read_UInt(stream));
flags = read_predFlags(stream); flags = read_predFlags(stream);
#if 0
if (ap->ArityOfPE && ap->ModuleOfPred != IDB_MODULE)
// __android_log_print(ANDROID_LOG_INFO, "YAP ", " %s/%ld %llx %llx\n", NameOfFunctor(ap->FunctorOfPred)->StrOfAE, ap->ArityOfPE, ap->PredFlags, flags);
printf(" %s/%ld %llx %llx\n", NameOfFunctor(ap->FunctorOfPred)->StrOfAE, ap->ArityOfPE, ap->PredFlags, flags);
else if (ap->ModuleOfPred != IDB_MODULE)
//__android_log_print(ANDROID_LOG_INFO, "YAP "," %s/%ld %llx %llx\n", ((Atom)(ap->FunctorOfPred))->StrOfAE, ap->ArityOfPE, flags);
printf(" %s/%ld %llx %llx\n", ((Atom)(ap->FunctorOfPred))->StrOfAE, ap->ArityOfPE, ap->PredFlags, flags);
//else
// __android_log_print(ANDROID_LOG_INFO, "YAP "," number\n");
#endif
if (flags & ForeignPredFlags) {
if (!(ap->PredFlags & ForeignPredFlags))
QLYR_ERROR(INCONSISTENT_CPRED);
if (flags & MetaPredFlag)
ap->PredFlags |= MetaPredFlag;
return;
}
nclauses = read_UInt(stream); nclauses = read_UInt(stream);
if (ap->PredFlags & IndexedPredFlag) { if (ap->PredFlags & IndexedPredFlag) {
Yap_RemoveIndexation(ap); Yap_RemoveIndexation(ap);
} }
#if 0 //fl1 = flags & ((pred_flags_t)STATIC_PRED_FLAGS|(UInt)EXTRA_PRED_FLAGS);
if (ap->ArityOfPE && ap->ModuleOfPred != IDB_MODULE) //ap->PredFlags &= ~((UInt)STATIC_PRED_FLAGS|(UInt)EXTRA_PRED_FLAGS);
__android_log_print(ANDROID_LOG_INFO, "YAP ", " %s/%ld %lx\n", NameOfFunctor(ap->FunctorOfPred)->StrOfAE, ap->ArityOfPE, flags); ap->PredFlags = flags & ~StatePredFlags;
/* printf(" %s/%ld %lx\n", NameOfFunctor(ap->FunctorOfPred)->StrOfAE, ap->ArityOfPE, flags); */
else if (ap->ModuleOfPred != IDB_MODULE)
__android_log_print(ANDROID_LOG_INFO, "YAP "," %s/%ld %lx\n", ((Atom)(ap->FunctorOfPred))->StrOfAE, ap->ArityOfPE, flags);
/* printf(" %s/%ld %lx\n", ((Atom)(ap->FunctorOfPred))->StrOfAE, ap->ArityOfPE, flags); */
else
__android_log_print(ANDROID_LOG_INFO, "YAP "," number\n");
#endif
fl1 = flags & ((pred_flags_t)STATIC_PRED_FLAGS|(UInt)EXTRA_PRED_FLAGS);
ap->PredFlags &= ~((UInt)STATIC_PRED_FLAGS|(UInt)EXTRA_PRED_FLAGS);
ap->PredFlags |= fl1;
if (flags & NumberDBPredFlag) { if (flags & NumberDBPredFlag) {
ap->src.IndxId = read_UInt(stream); ap->src.IndxId = read_UInt(stream);
} else { } else {
@ -1046,9 +1053,9 @@ read_pred(FILE *stream, Term mod) {
} }
ap->TimeStampOfPred = read_UInt(stream); ap->TimeStampOfPred = read_UInt(stream);
/* multifile predicates cannot reside in module 0 */ /* multifile predicates cannot reside in module 0 */
if (flags & MultiFileFlag && ap->ModuleOfPred == PROLOG_MODULE) { // if (flags & MultiFileFlag && ap->ModuleOfPred == PROLOG_MODULE) {
ap->ModuleOfPred = TermProlog; // ap->ModuleOfPred = TermProlog;
} // }
if (nclauses) if (nclauses)
read_clauses(stream, ap, nclauses, flags); read_clauses(stream, ap, nclauses, flags);
#if DEBUG #if DEBUG

View File

@ -698,6 +698,8 @@ static size_t
save_pred(FILE *stream, PredEntry *ap) { save_pred(FILE *stream, PredEntry *ap) {
CHECK(save_UInt(stream, (UInt)ap)); CHECK(save_UInt(stream, (UInt)ap));
CHECK(save_predFlags(stream, ap->PredFlags)); CHECK(save_predFlags(stream, ap->PredFlags));
if (ap->PredFlags & ForeignPredFlags)
return 1;
CHECK(save_UInt(stream, ap->cs.p_code.NOfClauses)); CHECK(save_UInt(stream, ap->cs.p_code.NOfClauses));
CHECK(save_UInt(stream, ap->src.IndxId)); CHECK(save_UInt(stream, ap->src.IndxId));
CHECK(save_UInt(stream, ap->TimeStampOfPred)); CHECK(save_UInt(stream, ap->TimeStampOfPred));
@ -706,11 +708,8 @@ save_pred(FILE *stream, PredEntry *ap) {
static int static int
clean_pred(PredEntry *pp USES_REGS) { clean_pred(PredEntry *pp USES_REGS) {
if (pp->PredFlags & (AsmPredFlag|CPredFlag)) { if (pp->PredFlags & ForeignPredFlags) {
/* assembly */ return true;
if (pp->CodeOfPred) {
CleanClauses(pp->CodeOfPred, pp->CodeOfPred, pp PASS_REGS);
}
} else { } else {
CleanClauses(pp->cs.p_code.FirstClause, pp->cs.p_code.LastClause, pp PASS_REGS); CleanClauses(pp->cs.p_code.FirstClause, pp->cs.p_code.LastClause, pp PASS_REGS);
} }

View File

@ -455,7 +455,7 @@ save_regs(int mode USES_REGS)
if (putcellptr(CellPtr(HeapTop)) < 0) if (putcellptr(CellPtr(HeapTop)) < 0)
return -1; return -1;
/* and the space it ocuppies */ /* and the space it ocuppies */
if (putout(Unsigned(Yap_heap_regs->heap_used)) < 0) if (putout(Unsigned(HeapUsed)) < 0)
return -1; return -1;
/* Then the start of the free code */ /* Then the start of the free code */
if (putcellptr(CellPtr(FreeBlocks)) < 0) if (putcellptr(CellPtr(FreeBlocks)) < 0)
@ -1035,6 +1035,8 @@ get_coded(int flag, OPCODE old_ops[] USES_REGS)
return 1; return 1;
} }
/* restore some heap registers */ /* restore some heap registers */
static void static void
restore_heap_regs( USES_REGS1 ) restore_heap_regs( USES_REGS1 )
@ -1043,7 +1045,7 @@ restore_heap_regs( USES_REGS1 )
HeapTop = AddrAdjust(HeapTop); HeapTop = AddrAdjust(HeapTop);
*((YAP_SEG_SIZE *) HeapTop) = InUseFlag; *((YAP_SEG_SIZE *) HeapTop) = InUseFlag;
} }
HeapMax = Yap_heap_regs->heap_used = OldHeapUsed; HeapMax = HeapUsed = OldHeapUsed;
HeapLim = LOCAL_GlobalBase; HeapLim = LOCAL_GlobalBase;
} }

View File

@ -8,14 +8,14 @@
* * * *
************************************************************************** **************************************************************************
* * * *
* File: signal.c * * File: signal.c *
* comments: Signal Handling & Debugger Support * * comments: Signal Handling & Debugger Support *
* * * *
* * * *
* * * *
*************************************************************************/ *************************************************************************/
#ifdef SCCS #ifdef SCCS
static char SccsId[] = "%W% %G%"; static char SccsId[] = "%W% %G%";
#endif #endif
#define HAS_CACHE_REGS 1 #define HAS_CACHE_REGS 1
@ -51,59 +51,59 @@ static char SccsId[] = "%W% %G%";
#include <tracer.h> #include <tracer.h>
#endif #endif
/* /*
* The InteractSIGINT function is called after a normal interrupt had been caught. * The InteractSIGINT function is called after a normal interrupt had been
* caught.
* It allows 6 possibilities: abort, continue, trace, debug, help, exit. * It allows 6 possibilities: abort, continue, trace, debug, help, exit.
*/ */
static yap_signals static yap_signals InteractSIGINT(int ch) {
InteractSIGINT(int ch) {
#ifdef HAVE_SETBUF #ifdef HAVE_SETBUF
/* make sure we are not waiting for the end of line */ /* make sure we are not waiting for the end of line */
setbuf (stdin, NULL); setbuf(stdin, NULL);
#endif #endif
switch (ch) { switch (ch) {
case 'a': case 'a':
/* abort computation */ /* abort computation */
return YAP_ABORT_SIGNAL; return YAP_ABORT_SIGNAL;
case 'b': case 'b':
/* continue */ /* continue */
return YAP_BREAK_SIGNAL; return YAP_BREAK_SIGNAL;
case 'c': case 'c':
/* continue */ /* continue */
return YAP_NO_SIGNAL; return YAP_NO_SIGNAL;
case 'd': case 'd':
/* enter debug mode */ /* enter debug mode */
return YAP_DEBUG_SIGNAL; return YAP_DEBUG_SIGNAL;
case 'e': case 'e':
/* exit */ /* exit */
Yap_exit(1); Yap_exit(1);
return YAP_EXIT_SIGNAL; return YAP_EXIT_SIGNAL;
case 'g': case 'g':
/* stack dump */ /* stack dump */
return YAP_STACK_DUMP_SIGNAL; return YAP_STACK_DUMP_SIGNAL;
case 't': case 't':
/* start tracing */ /* start tracing */
return YAP_TRACE_SIGNAL; return YAP_TRACE_SIGNAL;
#ifdef LOW_LEVEL_TRACER #ifdef LOW_LEVEL_TRACER
case 'T': case 'T':
toggle_low_level_trace(); toggle_low_level_trace();
return YAP_NO_SIGNAL; return YAP_NO_SIGNAL;
#endif #endif
case 's': case 's':
/* show some statistics */ /* show some statistics */
return YAP_STATISTICS_SIGNAL; return YAP_STATISTICS_SIGNAL;
case EOF: case EOF:
return YAP_NO_SIGNAL; return YAP_NO_SIGNAL;
case 'h': case 'h':
case '?': case '?':
default: default:
/* show an helpful message */ /* show an helpful message */
fprintf(stderr, "Please press one of:\n"); fprintf(stderr, "Please press one of:\n");
fprintf(stderr, " a for abort\n c for continue\n d for debug\n"); fprintf(stderr, " a for abort\n c for continue\n d for debug\n");
fprintf(stderr, " e for exit\n g for stack dump\n s for statistics\n t for trace\n"); fprintf(stderr, " e for exit\n g for stack dump\n s for statistics\n t "
fprintf(stderr, " b for break\n"); "for trace\n");
return YAP_NO_SIGNAL; fprintf(stderr, " b for break\n");
return YAP_NO_SIGNAL;
} }
} }
@ -111,162 +111,146 @@ InteractSIGINT(int ch) {
This function talks to the user about a signal. We assume we are in This function talks to the user about a signal. We assume we are in
the context of the main Prolog thread (trivial in Unix, but hard in WIN32) the context of the main Prolog thread (trivial in Unix, but hard in WIN32)
*/ */
static yap_signals static yap_signals ProcessSIGINT(void) {
ProcessSIGINT(void)
{
CACHE_REGS CACHE_REGS
int ch, out; int ch, out;
#if _WIN32 #if _WIN32
if (!_isatty(0)) { if (!_isatty(0)) {
return YAP_INT_SIGNAL; return YAP_INT_SIGNAL;
} }
#elif HAVE_ISATTY #elif HAVE_ISATTY
if (!isatty(0)) { if (!isatty(0)) {
return YAP_INT_SIGNAL; return YAP_INT_SIGNAL;
} }
#endif #endif
LOCAL_PrologMode |= AsyncIntMode; LOCAL_PrologMode |= AsyncIntMode;
do { do {
ch = Yap_GetCharForSIGINT(); ch = Yap_GetCharForSIGINT();
} while (!(out = InteractSIGINT(ch))); } while (!(out = InteractSIGINT(ch)));
LOCAL_PrologMode &= ~AsyncIntMode; LOCAL_PrologMode &= ~AsyncIntMode;
return(out); return (out);
} }
inline static void inline static void do_signal(int wid, yap_signals sig USES_REGS) {
do_signal(int wid, yap_signals sig USES_REGS)
{
#if THREADS #if THREADS
__sync_fetch_and_or ( &REMOTE(wid)->Signals_, SIGNAL_TO_BIT(sig)); __sync_fetch_and_or(&REMOTE(wid)->Signals_, SIGNAL_TO_BIT(sig));
if (!REMOTE_InterruptsDisabled(wid)) { if (!REMOTE_InterruptsDisabled(wid)) {
REMOTE_ThreadHandle(wid).current_yaam_regs->CreepFlag_ = REMOTE_ThreadHandle(wid).current_yaam_regs->CreepFlag_ =
Unsigned(REMOTE_ThreadHandle(wid).current_yaam_regs->LCL0_); Unsigned(REMOTE_ThreadHandle(wid).current_yaam_regs->LCL0_);
} }
#else #else
LOCAL_Signals |= SIGNAL_TO_BIT(sig); LOCAL_Signals |= SIGNAL_TO_BIT(sig);
if (!LOCAL_InterruptsDisabled) { if (!LOCAL_InterruptsDisabled) {
CreepFlag = CreepFlag = Unsigned(LCL0);
Unsigned(LCL0);
} }
#endif #endif
} }
inline static bool get_signal(yap_signals sig USES_REGS) {
inline static int
get_signal(yap_signals sig USES_REGS)
{
#if THREADS #if THREADS
uint64_t old; uint64_t old;
// first, clear the Creep Flag, now if someone sets it it is their problem // first, clear the Creep Flag, now if someone sets it it is their problem
CalculateStackGap( PASS_REGS1 ); CalculateStackGap(PASS_REGS1);
// reset the flag // reset the flag
if ( (old =__sync_fetch_and_and( &LOCAL_Signals, ~SIGNAL_TO_BIT(sig) ) ) != if ((old = __sync_fetch_and_and(&LOCAL_Signals, ~SIGNAL_TO_BIT(sig))) !=
SIGNAL_TO_BIT(sig)) { SIGNAL_TO_BIT(sig)) {
if (!LOCAL_InterruptsDisabled && LOCAL_Signals != 0) { if (!LOCAL_InterruptsDisabled && LOCAL_Signals != 0) {
CreepFlag = (CELL)LCL0; CreepFlag = (CELL)LCL0;
} }
if (!(old & SIGNAL_TO_BIT(sig)) ) { if (!(old & SIGNAL_TO_BIT(sig))) {
// not there? // not there?
return FALSE; return FALSE;
} }
// more likely case, we have other interrupts. // more likely case, we have other interrupts.
return TRUE; return TRUE;
} }
// success, we are good // success, we are good
return TRUE; return TRUE;
// should we set the flag? // should we set the flag?
#else #else
if (LOCAL_Signals & SIGNAL_TO_BIT(sig)) { if (LOCAL_Signals & SIGNAL_TO_BIT(sig)) {
LOCAL_Signals &= ~SIGNAL_TO_BIT(sig); LOCAL_Signals &= ~SIGNAL_TO_BIT(sig);
if (!LOCAL_InterruptsDisabled && LOCAL_Signals != 0) { if (!LOCAL_InterruptsDisabled && LOCAL_Signals != 0) {
CreepFlag = (CELL)LCL0; CreepFlag = (CELL)LCL0;
} else { } else {
CalculateStackGap( PASS_REGS1 ); CalculateStackGap(PASS_REGS1);
} }
return TRUE; return TRUE;
} else { } else {
return FALSE; return FALSE;
} }
#endif #endif
} }
/** /**
Function called to handle delayed interrupts. Function called to handle delayed interrupts.
*/ */
int int Yap_HandleInterrupts(void) {
Yap_HandleInterrupts( void )
{
CACHE_REGS CACHE_REGS
yap_signals sig; yap_signals sig;
if ( get_signal( YAP_INT_SIGNAL PASS_REGS )) { if (get_signal(YAP_INT_SIGNAL PASS_REGS)) {
if ( (sig = ProcessSIGINT()) != YAP_NO_SIGNAL ) if ((sig = ProcessSIGINT()) != YAP_NO_SIGNAL)
do_signal(worker_id, sig PASS_REGS); do_signal(worker_id, sig PASS_REGS);
LOCAL_PrologMode &= ~InterruptMode; LOCAL_PrologMode &= ~InterruptMode;
return 1; return 1;
} }
return 0; return 0;
} }
static Int static Int p_creep(USES_REGS1) {
p_creep( USES_REGS1 ) Atom at;
{ PredEntry *pred;
Atom at;
PredEntry *pred;
at = AtomCreep; at = AtomCreep;
pred = RepPredProp(PredPropByFunc(Yap_MkFunctor(at, 1),0)); pred = RepPredProp(PredPropByFunc(Yap_MkFunctor(at, 1), 0));
CreepCode = pred; CreepCode = pred;
do_signal(worker_id, YAP_CREEP_SIGNAL PASS_REGS); do_signal(worker_id, YAP_CREEP_SIGNAL PASS_REGS);
return TRUE; return TRUE;
} }
static Int static Int p_creep_fail(USES_REGS1) {
p_creep_fail( USES_REGS1 ) Atom at;
{ PredEntry *pred;
Atom at;
PredEntry *pred;
at = AtomCreep; at = AtomCreep;
pred = RepPredProp(PredPropByFunc(Yap_MkFunctor(at, 1),0)); pred = RepPredProp(PredPropByFunc(Yap_MkFunctor(at, 1), 0));
CreepCode = pred; CreepCode = pred;
do_signal(worker_id, YAP_CREEP_SIGNAL PASS_REGS); do_signal(worker_id, YAP_CREEP_SIGNAL PASS_REGS);
return FALSE; return FALSE;
} }
static Int stop_creeping( USES_REGS1 ) static Int stop_creeping(USES_REGS1) {
{ if (get_signal(YAP_CREEP_SIGNAL PASS_REGS)) {
get_signal( YAP_CREEP_SIGNAL PASS_REGS ); return Yap_unify(ARG1, TermTrue);
}
return Yap_unify(ARG1, TermFalse);
}
static Int disable_debugging(USES_REGS1) {
get_signal(YAP_CREEP_SIGNAL PASS_REGS);
return true; return true;
} }
static Int static Int creep_allowed(USES_REGS1) {
creep_allowed( USES_REGS1 )
{
if (PP != NULL) { if (PP != NULL) {
get_signal(YAP_CREEP_SIGNAL PASS_REGS); get_signal(YAP_CREEP_SIGNAL PASS_REGS);
return true; return true;
} }
return false; return false;
} }
void void Yap_signal(yap_signals sig) {
Yap_signal(yap_signals sig)
{
CACHE_REGS CACHE_REGS
do_signal(worker_id, sig PASS_REGS); do_signal(worker_id, sig PASS_REGS);
} }
#ifdef DEBUG #ifdef DEBUG
static Int static Int p_debug(USES_REGS1);
p_debug( USES_REGS1 );
#endif #endif
void void Yap_external_signal(int wid, yap_signals sig) {
Yap_external_signal(int wid, yap_signals sig)
{
#if THREADS #if THREADS
REGSTORE *regcache = REMOTE_ThreadHandle(wid).current_yaam_regs; REGSTORE *regcache = REMOTE_ThreadHandle(wid).current_yaam_regs;
#endif #endif
@ -274,195 +258,177 @@ Yap_external_signal(int wid, yap_signals sig)
LOCAL_PrologMode &= ~InterruptMode; LOCAL_PrologMode &= ~InterruptMode;
} }
int int Yap_get_signal__(yap_signals sig USES_REGS) {
Yap_get_signal__(yap_signals sig USES_REGS)
{
return get_signal(sig PASS_REGS); return get_signal(sig PASS_REGS);
} }
// the caller holds the lock. // the caller holds the lock.
int int Yap_has_signals__(yap_signals sig1, yap_signals sig2 USES_REGS) {
Yap_has_signals__(yap_signals sig1, yap_signals sig2 USES_REGS) return LOCAL_Signals & (SIGNAL_TO_BIT(sig1) | SIGNAL_TO_BIT(sig2));
{
return LOCAL_Signals & (SIGNAL_TO_BIT(sig1)|SIGNAL_TO_BIT(sig2));
} }
int Yap_only_has_signals__(yap_signals sig1, yap_signals sig2 USES_REGS) {
int uint64_t sigs = LOCAL_Signals;
Yap_only_has_signals__(yap_signals sig1, yap_signals sig2 USES_REGS)
{
uint64_t sigs = LOCAL_Signals;
return sigs & (SIGNAL_TO_BIT(sig1) | SIGNAL_TO_BIT(sig2)) && return sigs & (SIGNAL_TO_BIT(sig1) | SIGNAL_TO_BIT(sig2)) &&
! (sigs & ~(SIGNAL_TO_BIT(sig1) | SIGNAL_TO_BIT(sig2))) ; !(sigs & ~(SIGNAL_TO_BIT(sig1) | SIGNAL_TO_BIT(sig2)));
} }
#ifdef DEBUG #ifdef DEBUG
volatile int volat = 0; volatile int volat = 0;
static Int static Int p_debug(USES_REGS1) { /* $debug(+Flag) */
p_debug( USES_REGS1 ) int i = IntOfTerm(Deref(ARG1));
{ /* $debug(+Flag) */
int i = IntOfTerm(Deref(ARG1));
while (volat == 0) { while (volat == 0) {
} }
if (i >= 'a' && i <= 'z') if (i >= 'a' && i <= 'z')
GLOBAL_Option[i - 96] = !GLOBAL_Option[i - 96]; GLOBAL_Option[i - 96] = !GLOBAL_Option[i - 96];
return (1); return 1;
} }
void Yap_loop(void); void Yap_loop(void);
void Yap_debug_end_loop(void); void Yap_debug_end_loop(void);
void Yap_loop(void) void Yap_loop(void) {
{ while (volat == 0)
while (volat == 0); ;
} }
void Yap_debug_end_loop(void) void Yap_debug_end_loop(void) { volat = 1; }
{
volat = 1;
}
#endif #endif
static Int static Int first_signal(USES_REGS1) {
first_signal( USES_REGS1 )
{
Atom at; Atom at;
yap_signals sig; yap_signals sig;
while (TRUE) { while (TRUE) {
uint64_t mask = LOCAL_Signals; uint64_t mask = LOCAL_Signals;
if (mask == 0) if (mask == 0)
return FALSE; return FALSE;
#if HAVE___BUILTIN_FFSLL #if HAVE___BUILTIN_FFSLL
sig = __builtin_ffsll(mask); sig = __builtin_ffsll(mask);
#elif HAVE_FFSLL #elif HAVE_FFSLL
sig = ffsll(mask); sig = ffsll(mask);
#else #else
sig = Yap_msb( mask PASS_REGS)+1; sig = Yap_msb(mask PASS_REGS) + 1;
#endif #endif
if (get_signal(sig PASS_REGS)) { if (get_signal(sig PASS_REGS)) {
break; break;
} }
} }
loop: loop:
switch (sig) { switch (sig) {
case YAP_INT_SIGNAL: case YAP_INT_SIGNAL:
sig = ProcessSIGINT(); sig = ProcessSIGINT();
if (sig == YAP_INT_SIGNAL) { if (sig == YAP_INT_SIGNAL) {
at = AtomSigInt; at = AtomSigInt;
break;
}
if (sig != YAP_NO_SIGNAL)
goto loop;
return FALSE;
case YAP_ABORT_SIGNAL:
/* abort computation */
LOCAL_PrologMode &= ~AsyncIntMode;
if (LOCAL_PrologMode & (GCMode|ConsoleGetcMode|CritMode)) {
LOCAL_PrologMode |= AbortMode;
return -1;
} else {
Yap_Error(ABORT_EVENT, TermNil, "abort from console");
}
Yap_RestartYap( 1 );
return FALSE;
case YAP_CREEP_SIGNAL:
at = AtomSigCreep;
break;
case YAP_TRACE_SIGNAL:
at = AtomSigTrace;
break;
case YAP_DEBUG_SIGNAL:
at = AtomSigDebug;
break;
case YAP_BREAK_SIGNAL:
at = AtomSigBreak;
break;
case YAP_FAIL_SIGNAL:
at = AtomFail;
break;
case YAP_STACK_DUMP_SIGNAL:
at = AtomSigStackDump;
break;
case YAP_STATISTICS_SIGNAL:
at = AtomSigStatistics;
break; break;
}
if (sig != YAP_NO_SIGNAL)
goto loop;
return FALSE;
case YAP_ABORT_SIGNAL:
/* abort computation */
LOCAL_PrologMode &= ~AsyncIntMode;
if (LOCAL_PrologMode & (GCMode | ConsoleGetcMode | CritMode)) {
LOCAL_PrologMode |= AbortMode;
return -1;
} else {
Yap_Error(ABORT_EVENT, TermNil, "abort from console");
}
Yap_RestartYap(1);
return FALSE;
case YAP_CREEP_SIGNAL:
at = AtomSigCreep;
break;
case YAP_TRACE_SIGNAL:
at = AtomSigTrace;
break;
case YAP_DEBUG_SIGNAL:
at = AtomSigDebug;
break;
case YAP_BREAK_SIGNAL:
at = AtomSigBreak;
break;
case YAP_FAIL_SIGNAL:
at = AtomFail;
break;
case YAP_STACK_DUMP_SIGNAL:
at = AtomSigStackDump;
break;
case YAP_STATISTICS_SIGNAL:
at = AtomSigStatistics;
break;
#ifdef SIGALRM #ifdef SIGALRM
case YAP_ALARM_SIGNAL: case YAP_ALARM_SIGNAL:
#endif #endif
case YAP_WINTIMER_SIGNAL: case YAP_WINTIMER_SIGNAL:
at = AtomSigAlarm; at = AtomSigAlarm;
break; break;
#ifdef SIGVTALRM #ifdef SIGVTALRM
case YAP_VTALARM_SIGNAL: case YAP_VTALARM_SIGNAL:
at = AtomSigVTAlarm; at = AtomSigVTAlarm;
break; break;
#endif #endif
case YAP_EXIT_SIGNAL: case YAP_EXIT_SIGNAL:
Yap_exit(1); Yap_exit(1);
return FALSE; return FALSE;
case YAP_WAKEUP_SIGNAL: case YAP_WAKEUP_SIGNAL:
at = AtomSigWakeUp; at = AtomSigWakeUp;
break; break;
case YAP_ITI_SIGNAL: case YAP_ITI_SIGNAL:
at = AtomSigIti; at = AtomSigIti;
break; break;
#ifdef SIGPIPE #ifdef SIGPIPE
case YAP_PIPE_SIGNAL: case YAP_PIPE_SIGNAL:
at = AtomSigPipe; at = AtomSigPipe;
break; break;
#endif #endif
#ifdef SIGHUP #ifdef SIGHUP
case YAP_HUP_SIGNAL: case YAP_HUP_SIGNAL:
at = AtomSigHup; at = AtomSigHup;
break; break;
#endif #endif
#ifdef SIGUSR1 #ifdef SIGUSR1
case YAP_USR1_SIGNAL: case YAP_USR1_SIGNAL:
at = AtomSigUsr1; at = AtomSigUsr1;
break; break;
#endif #endif
#ifdef SIGUSR2 #ifdef SIGUSR2
case YAP_USR2_SIGNAL: case YAP_USR2_SIGNAL:
at = AtomSigUsr2; at = AtomSigUsr2;
break; break;
#endif #endif
#ifdef SIGFPE #ifdef SIGFPE
case YAP_FPE_SIGNAL: case YAP_FPE_SIGNAL:
at = AtomSigFPE; at = AtomSigFPE;
break; break;
#endif #endif
default: default:
return FALSE; return FALSE;
} }
return Yap_unify(ARG1, MkAtomTerm(at)); return Yap_unify(ARG1, MkAtomTerm(at));
} }
static Int static Int continue_signals(USES_REGS1) { return first_signal(PASS_REGS1); }
continue_signals( USES_REGS1 )
{
return first_signal( PASS_REGS1 );
}
void void Yap_InitSignalCPreds(void) {
Yap_InitSignalCPreds(void)
{
/* Basic predicates for the debugger */ /* Basic predicates for the debugger */
Yap_InitCPred("$creep", 0, p_creep, SafePredFlag); Yap_InitCPred("$creep", 0, p_creep, SafePredFlag);
Yap_InitCPred("$creep_fail", 0, p_creep_fail, SafePredFlag); Yap_InitCPred("$creep_fail", 0, p_creep_fail, SafePredFlag);
Yap_InitCPred("$stop_creeping", 0, stop_creeping, NoTracePredFlag|HiddenPredFlag|SafePredFlag); Yap_InitCPred("$stop_creeping", 1, stop_creeping,
Yap_InitCPred("$disable_debugging", 0, stop_creeping, NoTracePredFlag|HiddenPredFlag|SafePredFlag); NoTracePredFlag | HiddenPredFlag | SafePredFlag);
Yap_InitCPred ("$first_signal", 1, first_signal, SafePredFlag|SyncPredFlag); Yap_InitCPred("$disable_debugging", 0, disable_debugging,
Yap_InitCPred ("$continue_signals", 0, continue_signals, SafePredFlag|SyncPredFlag); NoTracePredFlag | HiddenPredFlag | SafePredFlag);
Yap_InitCPred("$first_signal", 1, first_signal, SafePredFlag | SyncPredFlag);
Yap_InitCPred("$continue_signals", 0, continue_signals,
SafePredFlag | SyncPredFlag);
Yap_InitCPred("creep_allowed", 0, creep_allowed, 0); Yap_InitCPred("creep_allowed", 0, creep_allowed, 0);
#ifdef DEBUG #ifdef DEBUG
Yap_InitCPred("sys_debug", 1, p_debug, SafePredFlag|SyncPredFlag); Yap_InitCPred("sys_debug", 1, p_debug, SafePredFlag | SyncPredFlag);
#endif #endif
} }
void *Yap_InitSignals(int wid) void *Yap_InitSignals(int wid) {
{ void *ptr = (void *)malloc(sizeof(UInt) * REMOTE_MaxActiveSignals(wid));
void *ptr = (void *)malloc(sizeof(UInt)*REMOTE_MaxActiveSignals(wid));
return ptr; return ptr;
} }

View File

@ -1,3 +1,4 @@
/************************************************************************* /*************************************************************************
* * * *
* YAP Prolog * * YAP Prolog *
@ -981,15 +982,7 @@ static PredEntry *firstModulePred(PredEntry *npp, Term task) {
return npp; return npp;
} }
static PredEntry *firstModulesPred(PredEntry *npp, Term task) { static PredEntry *firstModulesPred(PredEntry *npp, ModEntry *m, Term task) {
ModEntry *m;
if (npp) {
m = Yap_GetModuleEntry(npp->ModuleOfPred);
npp = npp->NextPredOfModule;
} else {
m = CurrentModules;
npp = m->PredForME;
}
do { do {
while (npp && !valid_prop(AbsPredProp(npp), task)) while (npp && !valid_prop(AbsPredProp(npp), task))
npp = npp->NextPredOfModule; npp = npp->NextPredOfModule;
@ -998,7 +991,8 @@ static PredEntry *firstModulesPred(PredEntry *npp, Term task) {
m = m->NextME; m = m->NextME;
if (m) { if (m) {
npp = m->PredForME; npp = m->PredForME;
} } else
return NULL;
} while (npp || m); } while (npp || m);
return npp; return npp;
} }
@ -1017,21 +1011,19 @@ static Int cont_current_predicate(USES_REGS1) {
pp = AddressOfTerm(EXTRA_CBACK_ARG(4, 1)); pp = AddressOfTerm(EXTRA_CBACK_ARG(4, 1));
if (IsNonVarTerm(t3)) { if (IsNonVarTerm(t3)) {
PropEntry *np, *p; PropEntry *np, *p;
if (IsNonVarTerm(t2)) { if (IsNonVarTerm(t2)) {
// module and functor known, should be easy // module and functor known, should be easy
if (IsAtomTerm(t2)) { if (IsAtomTerm(t2)) {
if ((p = Yap_GetPredPropByAtom(AtomOfTerm(t3), t2)) && if ((p = Yap_GetPredPropByAtom(AtomOfTerm(t3), t2)) &&
valid_prop(p, task) valid_prop(p, task)) {
) {
cut_succeed(); cut_succeed();
} else { } else {
cut_fail(); cut_fail();
} }
} else { } else {
if ((p = Yap_GetPredPropByFunc(FunctorOfTerm(t3), t2)) && if ((p = Yap_GetPredPropByFunc(FunctorOfTerm(t3), t2)) &&
valid_prop(p, task) valid_prop(p, task)) {
) {
cut_succeed(); cut_succeed();
} else { } else {
cut_fail(); cut_fail();
@ -1050,19 +1042,21 @@ static Int cont_current_predicate(USES_REGS1) {
if (p == NIL) if (p == NIL)
cut_fail(); cut_fail();
pp = RepPredProp(p); pp = RepPredProp(p);
} }
np = followLinkedListOfProps(p->NextOfPE, task); np = followLinkedListOfProps(p->NextOfPE, task);
Term mod = pp->ModuleOfPred; Term mod = pp->ModuleOfPred;
if (mod == PROLOG_MODULE) if (mod == PROLOG_MODULE)
mod = TermProlog; mod = TermProlog;
bool b = Yap_unify(t2, mod); bool b = Yap_unify(t2, mod);
if (!np) { if (!np) {
if (b) cut_succeed(); if (b)
else cut_fail(); cut_succeed();
else
cut_fail();
} else { } else {
EXTRA_CBACK_ARG(4, 1) = MkAddressTerm(RepPredProp(np)); EXTRA_CBACK_ARG(4, 1) = MkAddressTerm(RepPredProp(np));
B->cp_h = HR; B->cp_h = HR;
return b; return b;
} }
} else if (IsNonVarTerm(t1)) { } else if (IsNonVarTerm(t1)) {
PropEntry *np, *p; PropEntry *np, *p;
@ -1080,6 +1074,7 @@ static Int cont_current_predicate(USES_REGS1) {
p = getPredProp(RepAtom(at)->PropsOfAE, task); p = getPredProp(RepAtom(at)->PropsOfAE, task);
} else { } else {
Yap_Error(TYPE_ERROR_CALLABLE, t1, "current_predicate/2"); Yap_Error(TYPE_ERROR_CALLABLE, t1, "current_predicate/2");
return false;
} }
if (!p) if (!p)
cut_fail(); cut_fail();
@ -1117,18 +1112,21 @@ static Int cont_current_predicate(USES_REGS1) {
} }
} else { } else {
// operating across all modules. // operating across all modules.
PredEntry *npp; PredEntry *npp = pp;
ModEntry *me;
if (!pp) { if (!pp) {
pp = firstModulesPred(CurrentModules->PredForME, task); pp = firstModulesPred(CurrentModules->PredForME, CurrentModules, task);
if (!pp)
cut_fail();
} }
npp = firstModulesPred(pp, task); if (!pp)
cut_fail();
if (pp->ModuleOfPred == PROLOG_MODULE)
me = Yap_GetModuleEntry(TermProlog);
else
me = Yap_GetModuleEntry(pp->ModuleOfPred);
npp = firstModulesPred(pp->NextPredOfModule, me, task);
if (!npp) if (!npp)
will_cut = true; will_cut = true;
// just try next one // just try next module.
else { else {
EXTRA_CBACK_ARG(4, 1) = MkAddressTerm(npp); EXTRA_CBACK_ARG(4, 1) = MkAddressTerm(npp);
B->cp_h = HR; B->cp_h = HR;
@ -1800,9 +1798,7 @@ void Yap_InitCPreds(void) {
#ifdef ANALYST #ifdef ANALYST
Yap_InitAnalystPreds(); Yap_InitAnalystPreds();
#endif #endif
#ifdef LOW_LEVEL_TRACER
Yap_InitLowLevelTrace(); Yap_InitLowLevelTrace();
#endif
Yap_InitEval(); Yap_InitEval();
Yap_InitGrowPreds(); Yap_InitGrowPreds();
Yap_InitLowProf(); Yap_InitLowProf();

View File

@ -30,6 +30,7 @@ static char SccsId[] = "%W% %G%";
#include "yapio.h" #include "yapio.h"
#include "blobs.h" #include "blobs.h"
#include <stdio.h> #include <stdio.h>
#include <unistd.h>
#if HAVE_STRING_H #if HAVE_STRING_H
#include <string.h> #include <string.h>
#endif #endif
@ -1565,7 +1566,9 @@ p_thread_unlock( USES_REGS1 )
intptr_t intptr_t
system_thread_id(void) system_thread_id(void)
{ {
#if HAVE_SYS_GETTID #if defined(__APPLE__)
return syscall(SYS_thread_selfid);
#elif HAVE_SYS_GETTID || defined(__APPLE__)
return syscall( SYS_GETTID ); return syscall( SYS_GETTID );
#elif HAVE_GETTID_SYSCALL #elif HAVE_GETTID_SYSCALL
return syscall(__NR_gettid); return syscall(__NR_gettid);

View File

@ -50,7 +50,8 @@ static void send_tracer_message(char *start, char *name, Int arity, char *mname,
for (i = 0; i < arity; i++) { for (i = 0; i < arity; i++) {
if (i > 0) if (i > 0)
fprintf(stderr, ","); fprintf(stderr, ",");
Yap_plwrite(args[i], NULL, 15, Handle_vars_f | AttVar_Portray_f, GLOBAL_MaxPriority); Yap_plwrite(args[i], NULL, 15, Handle_vars_f | AttVar_Portray_f,
GLOBAL_MaxPriority);
} }
if (arity) { if (arity) {
fprintf(stderr, ")"); fprintf(stderr, ")");
@ -174,8 +175,8 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
// if (!worker_id) return; // if (!worker_id) return;
LOCK(Yap_heap_regs->low_level_trace_lock); LOCK(Yap_heap_regs->low_level_trace_lock);
sc = Yap_heap_regs; sc = Yap_heap_regs;
// if (vsc_count == 161862) jmp_deb(1); // if (vsc_count == 161862) jmp_deb(1);
#ifdef THREADS #ifdef THREADS
LOCAL_ThreadHandle.thread_inst_count++; LOCAL_ThreadHandle.thread_inst_count++;
#endif #endif
#ifdef COMMENTED #ifdef COMMENTED
@ -319,7 +320,7 @@ void low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) {
printf("\n"); printf("\n");
} }
#endif #endif
fprintf(stderr, "%lld %ld ", vsc_count, LCL0-(CELL*)B); fprintf(stderr, "%lld %ld ", vsc_count, LCL0 - (CELL *)B);
#if defined(THREADS) || defined(YAPOR) #if defined(THREADS) || defined(YAPOR)
fprintf(stderr, "(%d)", worker_id); fprintf(stderr, "(%d)", worker_id);
#endif #endif
@ -475,6 +476,8 @@ static Int vsc_go(USES_REGS1) {
void Yap_InitLowLevelTrace(void) { void Yap_InitLowLevelTrace(void) {
Yap_InitCPred("start_low_level_trace", 0, start_low_level_trace, Yap_InitCPred("start_low_level_trace", 0, start_low_level_trace,
SafePredFlag); SafePredFlag);
Yap_InitCPred("$start_low_level_trace", 0, start_low_level_trace,
SafePredFlag);
/** @pred start_low_level_trace /** @pred start_low_level_trace
@ -488,6 +491,7 @@ Begin display of messages at procedure entry and retry.
#endif #endif
Yap_InitCPred("stop_low_level_trace", 0, stop_low_level_trace, SafePredFlag); Yap_InitCPred("stop_low_level_trace", 0, stop_low_level_trace, SafePredFlag);
Yap_InitCPred("show_low_level_trace", 0, show_low_level_trace, SafePredFlag); Yap_InitCPred("show_low_level_trace", 0, show_low_level_trace, SafePredFlag);
Yap_InitCPred("$stop_low_level_trace", 0, stop_low_level_trace, SafePredFlag);
Yap_InitCPred("total_choicepoints", 1, total_choicepoints, SafePredFlag); Yap_InitCPred("total_choicepoints", 1, total_choicepoints, SafePredFlag);
Yap_InitCPred("reset_total_choicepoints", 0, reset_total_choicepoints, Yap_InitCPred("reset_total_choicepoints", 0, reset_total_choicepoints,
SafePredFlag); SafePredFlag);
@ -495,4 +499,14 @@ Begin display of messages at procedure entry and retry.
Yap_InitCPred("vsc_go", 0, vsc_go, SafePredFlag); Yap_InitCPred("vsc_go", 0, vsc_go, SafePredFlag);
} }
#else
static null(USES_REGS1) { return true; }
void Yap_InitLowLevelTrace(void) {
Yap_InitCPred("$start_low_level_trace", 0, null,
SafePredFlag | HiddenPredFlag);
Yap_InitCPred("$stop_low_level_trace", 0, null,
SafePredFlag | HiddenPredFlag);
}
#endif #endif

View File

@ -444,26 +444,28 @@ static int legalAtom(unsigned char *s) /* Is this a legal atom ? */
return (s[1] == '}' && !s[2]); return (s[1] == '}' && !s[2]);
} else if (Yap_chtype[ch] == SL) { } else if (Yap_chtype[ch] == SL) {
return (!s[1]); return (!s[1]);
} else if (ch == '`') {
return false;
} else if ((ch == ',' || ch == '.') && !s[1]) { } else if ((ch == ',' || ch == '.') && !s[1]) {
return false; return false;
} else { } else {
if (ch == '/') { if (ch == '/') {
if (s[1] == '*') if (s[1] == '*')
return FALSE; return false;
} }
while (ch) { while (ch) {
if (Yap_chtype[ch] != SY) { if (Yap_chtype[ch] != SY) {
return FALSE; return false;
} }
ch = *++s; ch = *++s;
} }
} }
return TRUE; return true;
} else } else
while ((ch = *++s) != 0) while ((ch = *++s) != 0)
if (Yap_chtype[ch] > NU) if (Yap_chtype[ch] > NU)
return FALSE; return false;
return (TRUE); return true;
} }
static wtype static wtype
@ -709,7 +711,7 @@ static Term from_pointer(CELL *ptr0, struct rewind_term *rwt,
if (!IsAtomicTerm(t) && !IsVarTerm(t)) { if (!IsAtomicTerm(t) && !IsVarTerm(t)) {
while (x) { while (x) {
if (Yap_GetDerefedFromSlot(x->u_sd.s.old PASS_REGS) == t) if (Yap_GetDerefedFromSlot(x->u_sd.s.old) == t)
return TermFoundVar; return TermFoundVar;
x = x->parent; x = x->parent;
} }
@ -736,8 +738,8 @@ static CELL *restore_from_write(struct rewind_term *rwt,
CELL *ptr; CELL *ptr;
if (wglb->Keep_terms) { if (wglb->Keep_terms) {
ptr = (CELL *)Yap_GetPtrFromSlot(rwt->u_sd.s.ptr PASS_REGS); ptr = Yap_GetPtrFromSlot(rwt->u_sd.s.ptr );
Yap_RecoverSlots(2, rwt->u_sd.s.old PASS_REGS); Yap_RecoverSlots(2, rwt->u_sd.s.old );
// printf("leak=%d %d\n", LOCALCurSlot,rwt->u_sd.s.old) ; // printf("leak=%d %d\n", LOCALCurSlot,rwt->u_sd.s.old) ;
} else { } else {
ptr = rwt->u_sd.d.ptr; ptr = rwt->u_sd.d.ptr;
@ -1232,7 +1234,7 @@ void Yap_plwrite(Term t, StreamDesc *mywrite, int max_depth, int flags,
CACHE_REGS CACHE_REGS
struct write_globs wglb; struct write_globs wglb;
struct rewind_term rwt; struct rewind_term rwt;
yhandle_t sls = Yap_CurrentSlot(PASS_REGS1); yhandle_t sls = Yap_CurrentSlot();
if (!mywrite) { if (!mywrite) {
CACHE_REGS CACHE_REGS

View File

@ -28,14 +28,18 @@ set(YAP_MAJOR_VERSION 6)
set(YAP_MINOR_VERSION 3) set(YAP_MINOR_VERSION 3)
set(YAP_PATCH_VERSION 4) set(YAP_PATCH_VERSION 4)
set(YAP_SYSTEM_OPTIONS "attributed_variables" )
if (WIN32) if (WIN32)
set (YAP_ARCH $ENV{PROCESSOR_ARCHITECTURE}) set (YAP_ARCH $ENV{PROCESSOR_ARCHITECTURE})
set(YAP_SYSTEM_OPTIONS "windows " ${YAP_SYSTEM_OPTIONS})
endif() endif()
if (UNIX) if (UNIX)
find_program (UNAME uname) find_program (UNAME uname)
execute_process ( execute_process (
COMMAND ${UNAME} -m COMMAND ${UNAME} -m
OUTPUT_VARIABLE YAP_ARCH OUTPUT_STRIP_TRAILING_WHITESPACE ) OUTPUT_VARIABLE YAP_ARCH OUTPUT_STRIP_TRAILING_WHITESPACE )
set(YAP_SYSTEM_OPTIONS "unix " ${YAP_SYSTEM_OPTIONS})
endif() endif()
set(YAP_FULL_VERSION set(YAP_FULL_VERSION
@ -92,21 +96,22 @@ if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
#cmake_policy( NO_POLICY_SCOPE ) #cmake_policy( NO_POLICY_SCOPE )
endif() endif()
set (BUILD_SHARED_LIBS ON)
## define system ## define system
include (Sources) include (Sources)
add_library(libYap SHARED add_library(libYap
${ENGINE_SOURCES} ${ENGINE_SOURCES}
${C_INTERFACE_SOURCES} ${C_INTERFACE_SOURCES}
${STATIC_SOURCES} ${STATIC_SOURCES}
${OPTYAP_SOURCES} ${OPTYAP_SOURCES}
${HEADERS} ${HEADERS}
$<TARGET_OBJECTS:libYAPOs> $<TARGET_OBJECTS:libYAPOs>
$<TARGET_OBJECTS:libOPTYap> $<TARGET_OBJECTS:libOPTYap>
# $<TARGET_OBJECTS:myddas> $<TARGET_OBJECTS:myddas>
) )
set_property(DIRECTORY PROPERTY CXX_STANDARD 11) set_property(DIRECTORY PROPERTY CXX_STANDARD 11)
@ -249,15 +254,14 @@ if (HAVE_GCC)
endif (HAVE_GCC) endif (HAVE_GCC)
# #
set (BUILD_SHARED_LIBS ON)
#option (YAP_SWI_IO ON) #option (YAP_SWI_IO ON)
OPTION (WITH_CALL_TRACER OPTION (WITH_CALL_TRACER
"support for procedure-call tracing" ON) "support for procedure-call tracing" ON)
#TODO: #TODO:
if (WITH_CALL_TRACER) if (WITH_CALL_TRACER)
set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:LOW_LEVEL_TRACER=1> ) set(YAP_SYSTEM_OPTIONS "call_tracer " ${YAP_SYSTEM_OPTIONS})
set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:LOW_LEVEL_TRACER=1> )
endif (WITH_CALL_TRACER) endif (WITH_CALL_TRACER)
#set( CMAKE_REQUIRED_LIBRARIES ${READLINE_LIBS} ${CMAKE_REQUIRED_LIBRARIES} ) #set( CMAKE_REQUIRED_LIBRARIES ${READLINE_LIBS} ${CMAKE_REQUIRED_LIBRARIES} )
@ -275,6 +279,7 @@ macro_log_feature (GMP_FOUND
"libgmp" "libgmp"
"GNU big integers and rationals" "GNU big integers and rationals"
"http://gmplib.org") "http://gmplib.org")
set(YAP_SYSTEM_OPTIONS "big_numbers " ${YAP_SYSTEM_OPTIONS})
if (GMP_FOUND) if (GMP_FOUND)
include_directories (${GMP_INCLUDE_DIR}) include_directories (${GMP_INCLUDE_DIR})
#add_executable(test ${SOURCES}) #add_executable(test ${SOURCES})
@ -323,7 +328,8 @@ if (WITH_Threads)
check_function_exists( pthread_mutexattr_settype HAVE_PTHREAD_MUTEXATTR_SETTYPE ) check_function_exists( pthread_mutexattr_settype HAVE_PTHREAD_MUTEXATTR_SETTYPE )
check_function_exists( pthread_setconcurrency HAVE_PTHREAD_SETCONCURRENCY ) check_function_exists( pthread_setconcurrency HAVE_PTHREAD_SETCONCURRENCY )
endif (CMAKE_USE_PTHREADS_INIT) endif (CMAKE_USE_PTHREADS_INIT)
set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS THREADS=1) set(YAP_SYSTEM_OPTIONS "threads " ${YAP_SYSTEM_OPTIONS})
set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS THREADS=1)
# #
# Please note that the compiler flag can only be used with the imported # Please note that the compiler flag can only be used with the imported
# target. Use of both the imported target as well as this switch is highly # target. Use of both the imported target as well as this switch is highly
@ -344,7 +350,6 @@ IF(WITH_Pthread_Lockin)
set_DIRECTORY_properties(PROPERTIES APPEND COMPILE_DEFINITIONS USE_PTHREAD_LOCKING=1) set_DIRECTORY_properties(PROPERTIES APPEND COMPILE_DEFINITIONS USE_PTHREAD_LOCKING=1)
ENDIF() ENDIF()
# #
# include OS and I/o stuff # include OS and I/o stuff
# #
@ -353,7 +358,7 @@ ENDIF()
# #
add_subDIRECTORY (OPTYap) add_subDIRECTORY (OPTYap)
#add_subDIRECTORY (packages/myddas) add_subDIRECTORY (packages/myddas)
add_subDIRECTORY (os) add_subDIRECTORY (os)
@ -369,6 +374,7 @@ ADD_SUBDIRECTORY(swi/library)
# ADD_SUBDIRECTORY(os) # ADD_SUBDIRECTORY(os)
# ADD_SUBDIRECTORY(packages) # ADD_SUBDIRECTORY(packages)
option (WITH_JIT option (WITH_JIT
"just in Time Clause Compilation" OFF) "just in Time Clause Compilation" OFF)
if (WITH_JIT) if (WITH_JIT)
@ -397,7 +403,7 @@ add_subDIRECTORY (packages/cplint)
add_subDIRECTORY (packages/raptor) add_subDIRECTORY (packages/raptor)
add_subDIRECTORY (docs) # add_subDIRECTORY (docs)
# add_subDIRECTORY (packages/cuda) # add_subDIRECTORY (packages/cuda)

View File

@ -428,7 +428,7 @@ YAPQuery::initQuery( YAPTerm ts[], arity_t arity )
if (arity) { if (arity) {
q_g = Yap_NewSlots( arity ); q_g = Yap_NewSlots( arity );
for (arity_t i=0; i < arity; i++) { for (arity_t i=0; i < arity; i++) {
Yap_PutInSlot(q_g+i, ts[i].term() PASS_REGS); Yap_PutInSlot(q_g+i, ts[i].term());
} }
Term t = Yap_MkApplTerm(ap->FunctorOfPred, ap->ArityOfPE, Yap_AddressFromSlot(q_g)); Term t = Yap_MkApplTerm(ap->FunctorOfPred, ap->ArityOfPE, Yap_AddressFromSlot(q_g));
goal = YAPTerm( t ); goal = YAPTerm( t );

View File

@ -1,2 +1,2 @@
#define GIT_SHA1 "036876299f12a4761f8d1de2dfba9709d5c91739" #define GIT_SHA1 "60a8efb467c383c47e440c3552cca7d179f66c2e"
const char g_GIT_SHA1[] = GIT_SHA1; const char g_GIT_SHA1[] = GIT_SHA1;

28
H/Yap.h
View File

@ -376,6 +376,17 @@ typedef volatile int lockvar;
#include "Regs.h" #include "Regs.h"
/*************************************************************************************************
OPTYAP includes
*************************************************************************************************/
#if defined(YAPOR) || defined(TABLING)
#include "opt.structs.h"
#include "opt.proto.h"
#include "opt.macros.h"
#endif /* YAPOR || TABLING */
/************************************************************************************************* /*************************************************************************************************
variables concerned with Error Handling variables concerned with Error Handling
*************************************************************************************************/ *************************************************************************************************/
@ -733,17 +744,6 @@ typedef struct scratch_block_struct {
/* scanner types */ /* scanner types */
#include "ScannerTypes.h" #include "ScannerTypes.h"
/*************************************************************************************************
OPTYAP includes
*************************************************************************************************/
#if defined(YAPOR) || defined(TABLING)
#include "opt.structs.h"
#include "opt.proto.h"
#include "opt.macros.h"
#endif /* YAPOR || TABLING */
/************************************************************************************************* /*************************************************************************************************
GLOBAL and LOCAL variables GLOBAL and LOCAL variables
*************************************************************************************************/ *************************************************************************************************/
@ -771,10 +771,8 @@ extern struct worker_local Yap_local;
#include <stdio.h> #include <stdio.h>
#define YP_FILE FILE #define YP_FILE FILE
#include "hglobals.h"
#include "dglobals.h" #include <YapHeap.h>
#include "hlocals.h"
#include "dlocals.h"
/************************************************************************************************* /*************************************************************************************************

View File

@ -25,37 +25,66 @@
// INLINE_ONLY inline EXTERN bool nat( Term inp ); // INLINE_ONLY inline EXTERN bool nat( Term inp );
#define SYSTEM_OPTION_0 "attributed_variables,rational_trees]"
#if THREADS
#define SYSTEM_OPTION_1 "threads,"
#endif
#if USE_GMP
#define SYSTEM_OPTION_3 "big_numbers,"
#endif
#if DEPTH_LIMIT
#define SYSTEM_OPTION_4 "depth_limit,"
#endif
#if LOW_LEVEL_TRACE
#define SYSTEM_OPTION_5 "low_level_tracer,"
#endif
#if YAPOR
#define SYSTEM_OPTION_6 "or_parallelism,"
#endif
#if USE_READLINE
#define SYSTEM_OPTION_7 "readline,"
#endif
#if TABLING
#define SYSTEM_OPTION_8 "tabling,"
#endif
static inline bool nat(Term inp) { static inline bool nat(Term inp) {
if (IsVarTerm(inp)) { if (IsVarTerm(inp)) {
Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag: value must be %s", "bound"); Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag: value must be %s",
"bound");
return false; return false;
} }
if (IsIntTerm(inp)) { if (IsIntTerm(inp)) {
Int i = IntOfTerm(inp); Int i = IntOfTerm(inp);
if (i >= 0) if (i >= 0)
return true; return true;
Yap_Error(DOMAIN_ERROR_NOT_LESS_THAN_ZERO, inp, "set_prolog_flag: value must be %s", ">= 0"); Yap_Error(DOMAIN_ERROR_NOT_LESS_THAN_ZERO, inp,
"set_prolog_flag: value must be %s", ">= 0");
return false; return false;
} }
Yap_Error(TYPE_ERROR_INTEGER, inp, "set_prolog_flag: value must be %s", "integer"); Yap_Error(TYPE_ERROR_INTEGER, inp, "set_prolog_flag: value must be %s",
"integer");
return false; return false;
} }
static inline bool at2n(Term inp) { static inline bool at2n(Term inp) {
Yap_Error(PERMISSION_ERROR_READ_ONLY_FLAG, inp, "set_prolog_flag %s", "flag is read-only"); Yap_Error(PERMISSION_ERROR_READ_ONLY_FLAG, inp, "set_prolog_flag %s",
"flag is read-only");
return false; return false;
} }
static inline bool isfloat(Term inp) { static inline bool isfloat(Term inp) {
if (IsVarTerm(inp)) { if (IsVarTerm(inp)) {
Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag: value must be %s", "integer"); Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag: value must be %s",
"integer");
return false; return false;
} }
if (IsFloatTerm(inp)) { if (IsFloatTerm(inp)) {
return true; return true;
} }
Yap_Error(TYPE_ERROR_FLOAT, inp, "set_prolog_flag: value must be %s", "floating-point"); Yap_Error(TYPE_ERROR_FLOAT, inp, "set_prolog_flag: value must be %s",
"floating-point");
return false; return false;
} }
@ -63,20 +92,24 @@ INLINE_ONLY inline EXTERN bool ro(Term inp);
INLINE_ONLY inline EXTERN bool ro(Term inp) { INLINE_ONLY inline EXTERN bool ro(Term inp) {
if (IsVarTerm(inp)) { if (IsVarTerm(inp)) {
Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag: value must be %s", "bound"); Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag: value must be %s",
"bound");
return false; return false;
} }
Yap_Error(PERMISSION_ERROR_READ_ONLY_FLAG, inp, "set_prolog_flag %s", "flag is read-only"); Yap_Error(PERMISSION_ERROR_READ_ONLY_FLAG, inp, "set_prolog_flag %s",
"flag is read-only");
return false; return false;
} }
INLINE_ONLY inline EXTERN bool aro(Term inp) { INLINE_ONLY inline EXTERN bool aro(Term inp) {
if (IsVarTerm(inp)) { if (IsVarTerm(inp)) {
Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag %s", "value must be bound"); Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag %s",
"value must be bound");
return false; return false;
} }
Yap_Error(PERMISSION_ERROR_READ_ONLY_FLAG, inp, "set_prolog_flag %s", "flag is read-only"); Yap_Error(PERMISSION_ERROR_READ_ONLY_FLAG, inp, "set_prolog_flag %s",
"flag is read-only");
return false; return false;
} }
@ -87,8 +120,9 @@ static inline bool boolean(Term inp) {
if (inp == TermTrue || inp == TermFalse || inp == TermOn || inp == TermOff) if (inp == TermTrue || inp == TermFalse || inp == TermOn || inp == TermOff)
return true; return true;
if (IsVarTerm(inp)) { if (IsVarTerm(inp)) {
Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag %s", "value must be bound"); Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag %s",
; "value must be bound");
;
return false; return false;
} }
if (IsAtomTerm(inp)) { if (IsAtomTerm(inp)) {
@ -134,7 +168,8 @@ static bool bqs(Term inp) {
static inline bool isatom(Term inp) { static inline bool isatom(Term inp) {
if (IsVarTerm(inp)) { if (IsVarTerm(inp)) {
Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag %s", "value must be bound"); Yap_Error(INSTANTIATION_ERROR, inp, "set_prolog_flag %s",
"value must be bound");
return false; return false;
} }
if (IsAtomTerm(inp)) if (IsAtomTerm(inp))
@ -143,6 +178,8 @@ static inline bool isatom(Term inp) {
return false; return false;
} }
static inline bool options(Term inp) { return Yap_IsGroundTerm(inp); }
// INLINE_ONLY inline EXTERN bool ok( Term inp ); // INLINE_ONLY inline EXTERN bool ok( Term inp );
static inline bool ok(Term inp) { return true; } static inline bool ok(Term inp) { return true; }

View File

@ -63,7 +63,7 @@ Prolog exceptions. If enabled:
~~~~ ~~~~
?- X is 2/0. ?- X is 2/0.
ERROR!! ERROR!!
ZERO DIVISOR ERROR- X is Exp ZERO DIVISO]]R ERROR- X is Exp
~~~~ ~~~~
If disabled: If disabled:
@ -364,7 +364,7 @@ bound to `off` disable strict mode, and keep the current language
mode. The default for YAP is `off`. mode. The default for YAP is `off`.
Under strict ISO Prolog mode all calls to non-ISO built-ins generate an Under strict ISO Prolog mode all calls to non-ISO built-ins generate an
error. Compilation of clauses that would call non-ISO built-ins will error. Compilation of clauses that would call non-ISO built-ins will
§§also generate errors. Pre-processing for grammar rules is also also generate errors. Pre-processing for grammar rules is also
disabled. Module expansion is still performed. disabled. Module expansion is still performed.
Arguably, ISO Prolog does not provide all the functionality required Arguably, ISO Prolog does not provide all the functionality required
from a modern Prolog system. Moreover, because most Prolog from a modern Prolog system. Moreover, because most Prolog
@ -376,10 +376,9 @@ will work the same way in every Prolog and in every platform. We thus
believe this mode is mostly useful when investigating how a program believe this mode is mostly useful when investigating how a program
depends on a Prolog's platform specific features. depends on a Prolog's platform specific features.
*/ */
YAP_FLAG(SYSTEM_OPTIONS_FLAG, "system_options", false, ro, YAP_FLAG(SYSTEM_OPTIONS_FLAG, "system_options", false, options,
"[big_numbers,coroutining,depth_limit,low_level_tracer,rational_" SYSTEM_OPTIONS,
"trees,threads,tabling]",
NULL), /**< `system_options ` NULL), /**< `system_options `
This read only flag tells which options were used to compile This read only flag tells which options were used to compile
@ -411,8 +410,8 @@ presented. Only the first solution is considered and the goal is not
backtracked into. backtracked into.
*/ */
YAP_FLAG(TOPLEVEL_PROMPT_FLAG, "toplevel_prompt", true, isatom, YAP_FLAG(TOPLEVEL_PROMPT_FLAG, "toplevel_prompt", true, isatom, "?- ",
"?- ", mkprompt), mkprompt),
YAP_FLAG(TTY_CONTROL_FLAG, "tty_control", true, boolean, "true", NULL), YAP_FLAG(TTY_CONTROL_FLAG, "tty_control", true, boolean, "true", NULL),
YAP_FLAG(UNIX_FLAG, "unix", false, ro, "true", NULL), /**< `unix` YAP_FLAG(UNIX_FLAG, "unix", false, ro, "true", NULL), /**< `unix`
@ -445,7 +444,8 @@ follows immediate semantics.
Yap_unknown), /**< `unknown is iso` Yap_unknown), /**< `unknown is iso`
Corresponds to calling the unknown/2 built-in. Possible ISO values Corresponds to calling the unknown/2 built-in. Possible ISO values
are `error`, `fail`, and `warning`. Yap includes the following extensions: `fast_fail` does not invoke any handler. are `error`, `fail`, and `warning`. Yap includes the following extensions:
`fast_fail` does not invoke any handler.
*/ */
YAP_FLAG(VARIABLE_NAMES_MAY_END_WITH_QUOTES_FLAG, YAP_FLAG(VARIABLE_NAMES_MAY_END_WITH_QUOTES_FLAG,
"variable_names_may_end_with_quotes", true, boolean, "false", "variable_names_may_end_with_quotes", true, boolean, "false",

View File

@ -67,61 +67,80 @@ static inline void Yap_RebootSlots__(int wid USES_REGS) {
/// @brief declares a new set of slots. /// @brief declares a new set of slots.
/// Used to tell how many slots we had when we entered a segment of code. /// Used to tell how many slots we had when we entered a segment of code.
//#define Yap_StartSlots() ( printf("[<<<%s,%s,%d-%ld\n",__FILE__,__FUNCTION__,__LINE__,LOCAL_CurSlot)?Yap_StartSlots__(PASS_REGS1): -1) //#define Yap_StartSlots() (
// printf("[<<<%s,%s,%d-%ld\n",__FILE__,__FUNCTION__,__LINE__,LOCAL_CurSlot)?Yap_StartSlots__(PASS_REGS1):
//-1)
#define Yap_StartSlots() Yap_StartSlots__(PASS_REGS1) #define Yap_StartSlots() Yap_StartSlots__(PASS_REGS1)
static inline yhandle_t Yap_StartSlots__(USES_REGS1) { INLINE_ONLY inline EXTERN yhandle_t Yap_StartSlots__(USES_REGS1);
INLINE_ONLY inline EXTERN yhandle_t Yap_StartSlots__(USES_REGS1) {
// // fprintf(stderr, " StartSlots = %ld", LOCAL_CurSlot); // // fprintf(stderr, " StartSlots = %ld", LOCAL_CurSlot);
// fprintf(stderr,"SS %s:%d\n", __FUNCTION__, __LINE__);; // fprintf(stderr,"SS %s:%d\n", __FILE__, __LINE__);;
if (LOCAL_CurSlot < 0) { if (LOCAL_CurSlot < 0) {
Yap_Error(SYSTEM_ERROR_INTERNAL, 0L, " StartSlots = %ld", LOCAL_CurSlot); Yap_Error(SYSTEM_ERROR_INTERNAL, 0L, " StartSlots = %ld", LOCAL_CurSlot);
} }
return LOCAL_CurSlot; return LOCAL_CurSlot;
} }
/// @brief reset slots to a well-known position in the stack /// @brief reset slots to a well-known position in the stack
//#define Yap_CloseSlots(slot) ( printf("- %s,%s,%d %ld>>>]\n",__FILE__,__FUNCTION__,__LINE__, slot)?Yap_CloseSlots__(slot PASS_REGS):-1) //#define Yap_CloseSlots(slot) ( printf("- %s,%s,%d
//%ld>>>]\n",__FILE__,__FUNCTION__,__LINE__, slot)?Yap_CloseSlots__(slot
// PASS_REGS):-1)
#define Yap_CloseSlots(slot) Yap_CloseSlots__(slot PASS_REGS) #define Yap_CloseSlots(slot) Yap_CloseSlots__(slot PASS_REGS)
static inline void Yap_CloseSlots__(yhandle_t slot USES_REGS) { INLINE_ONLY inline EXTERN void Yap_CloseSlots__(yhandle_t slot USES_REGS);
// fprintf(stderr,"CS %s:%d\n", __FUNCTION__, __LINE__);; INLINE_ONLY inline EXTERN void Yap_CloseSlots__(yhandle_t slot USES_REGS) {
// fprintf(stderr,"CS %s:%d\n", __FILE__, __LINE__);;
LOCAL_CurSlot = slot; LOCAL_CurSlot = slot;
} }
#define Yap_CurrentSlot() Yap_CurrentSlot__(PASS_REGS1)
/// @brief report the current position of the slots, assuming that they occupy /// @brief report the current position of the slots, assuming that they occupy
/// the top of the stack. /// the top of the stack.
static inline yhandle_t Yap_CurrentSlot(USES_REGS1) { return LOCAL_CurSlot; } INLINE_ONLY inline EXTERN yhandle_t Yap_CurrentSlot__(USES_REGS1);
INLINE_ONLY inline EXTERN yhandle_t Yap_CurrentSlot__(USES_REGS1) {
return LOCAL_CurSlot;
}
#define Yap_GetFromSlot(slot) Yap_GetFromSlot__(slot PASS_REGS) #define Yap_GetFromSlot(slot) Yap_GetFromSlot__(slot PASS_REGS)
/// @brief read from a slot. /// @brief read from a slot.
static inline Term Yap_GetFromSlot__(yhandle_t slot USES_REGS) { INLINE_ONLY inline EXTERN Term Yap_GetFromSlot__(yhandle_t slot USES_REGS);
// fprintf(stderr,"GS %s:%d\n", __FUNCTION__, __LINE__);; INLINE_ONLY inline EXTERN Term Yap_GetFromSlot__(yhandle_t slot USES_REGS) {
return (Deref(LOCAL_SlotBase[slot])); // fprintf(stderr, "GS %s:%d\n", __FILE__, __LINE__);
return Deref(LOCAL_SlotBase[slot]);
} }
#define Yap_GetDerefedFromSlot( slot ) Yap_GetDerefedFromSlot__(slot PASS_REGS)
/// @brief read from a slot. but does not try to dereference the slot. /// @brief read from a slot. but does not try to dereference the slot.
static inline Term Yap_GetDerefedFromSlot(yhandle_t slot USES_REGS) { INLINE_ONLY inline EXTERN Term Yap_GetDerefedFromSlot__(yhandle_t slot USES_REGS);
// fprintf(stderr,"GDS %s:%d\n", __FUNCTION__, __LINE__); INLINE_ONLY inline EXTERN Term Yap_GetDerefedFromSlot__(yhandle_t slot USES_REGS) {
// fprintf(stderr,"GDS %s:%d\n", __FILE__, __LINE__);
return LOCAL_SlotBase[slot]; return LOCAL_SlotBase[slot];
} }
#define Yap_GetPtrFromSlot( slot ) Yap_GetPtrFromSlot__(slot PASS_REGS)
/// @brief read the object in a slot. but do not try to dereference the slot. /// @brief read the object in a slot. but do not try to dereference the slot.
static inline Term Yap_GetPtrFromSlot(yhandle_t slot USES_REGS) { INLINE_ONLY inline EXTERN Term *Yap_GetPtrFromSlot__(yhandle_t slot USES_REGS);
// fprintf(stderr,"GPS %s:%d\n", __FUNCTION__, __LINE__); INLINE_ONLY inline EXTERN Term *Yap_GetPtrFromSlot__(yhandle_t slot USES_REGS) {
return LOCAL_SlotBase[slot]; // fprintf(stderr,"GPS %s:%d\n", __FILE__, __LINE__);
return (Term *)LOCAL_SlotBase[slot];
} }
#define Yap_AddressFromSlot(slot) Yap_AddressFromSlot__(slot PASS_REGS) #define Yap_AddressFromSlot(slot) Yap_AddressFromSlot__(slot PASS_REGS)
/// @brief get the memory address of a slot INLINE_ONLY inline EXTERN CELL *Yap_AddressFromSlot__(yhandle_t slot USES_REGS);
static inline Term *Yap_AddressFromSlot__(yhandle_t slot USES_REGS) { INLINE_ONLY inline EXTERN CELL *Yap_AddressFromSlot__(yhandle_t slot USES_REGS) {
/// @brief get the memory address of a slot
return LOCAL_SlotBase + slot; return LOCAL_SlotBase + slot;
} }
#define Yap_PutInSlot(slot, t) Yap_PutInSlot__(slot, t PASS_REGS)
/// @brief store term in a slot /// @brief store term in a slot
static inline void Yap_PutInSlot(yhandle_t slot, Term t USES_REGS) { INLINE_ONLY inline EXTERN void Yap_PutInSlot__(yhandle_t slot, Term t USES_REGS);
// fprintf(stderr,"PS %s:%d\n", __FUNCTION__, __LINE__); INLINE_ONLY inline EXTERN void Yap_PutInSlot__(yhandle_t slot, Term t USES_REGS) {
// fprintf(stderr,"PS %s:%d\n", __FILE__, __LINE__);
LOCAL_SlotBase[slot] = t; LOCAL_SlotBase[slot] = t;
} }
@ -129,7 +148,7 @@ static inline void Yap_PutInSlot(yhandle_t slot, Term t USES_REGS) {
#define max(X, Y) (X > Y ? X : Y) #define max(X, Y) (X > Y ? X : Y)
#endif #endif
static inline void ensure_slots(int N USES_REGS) { INLINE_ONLY inline EXTERN void ensure_slots(int N USES_REGS) {
if (LOCAL_CurSlot + N >= LOCAL_NSlots) { if (LOCAL_CurSlot + N >= LOCAL_NSlots) {
size_t inc = max(16 * 1024, LOCAL_NSlots / 2); // measured in cells size_t inc = max(16 * 1024, LOCAL_NSlots / 2); // measured in cells
inc = max(inc, N + 16); // measured in cells inc = max(inc, N + 16); // measured in cells
@ -147,12 +166,15 @@ static inline void ensure_slots(int N USES_REGS) {
} }
/// @brief create a new slot with term t /// @brief create a new slot with term t
//#define Yap_InitSlot(t) ( printf("+%d %s,%s,%d>>>]\n",1,__FILE__,__FUNCTION__,__LINE__)?Yap_InitSlot__(t PASS_REGS):-1) // #define Yap_InitSlot(t) \
// (printf("+%d %ld %s,%s,%d>>>]\n", 1, LOCAL_CurSlot,__FILE__, __FUNCTION__, __LINE__) \
// ? Yap_InitSlot__(t PASS_REGS) \
// : -1)
#define Yap_InitSlot(t) Yap_InitSlot__(t PASS_REGS) #define Yap_InitSlot(t) Yap_InitSlot__(t PASS_REGS)
static inline yhandle_t Yap_InitSlot__(Term t USES_REGS) { INLINE_ONLY inline EXTERN yhandle_t Yap_InitSlot__(Term t USES_REGS);
INLINE_ONLY inline EXTERN yhandle_t Yap_InitSlot__(Term t USES_REGS) {
yhandle_t old_slots = LOCAL_CurSlot; yhandle_t old_slots = LOCAL_CurSlot;
// fprintf(stderr,"IS %s:%d\n", __FUNCTION__, __LINE__);
ensure_slots(1 PASS_REGS); ensure_slots(1 PASS_REGS);
LOCAL_SlotBase[old_slots] = t; LOCAL_SlotBase[old_slots] = t;
@ -160,14 +182,14 @@ static inline yhandle_t Yap_InitSlot__(Term t USES_REGS) {
return old_slots; return old_slots;
} }
//#define Yap_NewSlots(n) ( printf("+%d %s,%s,%d>>>]\n",n,__FILE__,__FUNCTION__,__LINE__)?Yap_NewSlots__(n PASS_REGS):-1) //#define Yap_NewSlots(n) ( printf("+%d %ld %s,%s,%d>>>]\n",n,LOCAL_CurSlot,__FILE__,__FUNCTION__,__LINE__) ?Yap_NewSlots__(n PASS_REGS):-1)
#define Yap_NewSlots(n) Yap_NewSlots__(n PASS_REGS) #define Yap_NewSlots(n) Yap_NewSlots__(n PASS_REGS)
/// @brief allocate n empty new slots INLINE_ONLY inline EXTERN yhandle_t Yap_NewSlots__(int n USES_REGS);
static inline yhandle_t Yap_NewSlots__(int n USES_REGS) { INLINE_ONLY inline EXTERN yhandle_t Yap_NewSlots__(int n USES_REGS) {
yhandle_t old_slots = LOCAL_CurSlot; yhandle_t old_slots = LOCAL_CurSlot;
int i; int i;
// fprintf(stderr,"NS %s:%d\n", __FUNCTION__, __LINE__); //fprintf(stderr, "NS %s:%d\n", __FILE__, __LINE__);
ensure_slots(n PASS_REGS); ensure_slots(n PASS_REGS);
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
@ -177,15 +199,17 @@ static inline yhandle_t Yap_NewSlots__(int n USES_REGS) {
return old_slots; return old_slots;
} }
//#define Yap_InitSlots(n, ts) ( printf("+%d %s,%s,%d>>>]\n",n,__FILE__,__FUNCTION__,__LINE__)?Yap_InitSlots__(n, ts PASS_REGS):-1) //#define Yap_InitSlots(n, ts) \
// (printf("+%d %d %s,%s,%d>>>]\n", n, LOCAL_CurSlot, __FILE__, __FUNCTION__, __LINE__) \
// ? Yap_InitSlots__(n, ts PASS_REGS) \
// : -1)
#define Yap_InitSlots(n, ts) Yap_InitSlots__(n, ts PASS_REGS) #define Yap_InitSlots(n, ts) Yap_InitSlots__(n, ts PASS_REGS)
/// @brief create n new slots with terms ts[] /// @brief create n new slots with terms ts[]
static inline yhandle_t Yap_InitSlots__(int n, Term *ts USES_REGS) { INLINE_ONLY inline EXTERN yhandle_t Yap_InitSlots__(int n, Term *ts USES_REGS);
INLINE_ONLY inline EXTERN yhandle_t Yap_InitSlots__(int n, Term *ts USES_REGS) {
yhandle_t old_slots = LOCAL_CurSlot; yhandle_t old_slots = LOCAL_CurSlot;
int i; int i;
// fprintf(stderr,"1S %s:%d\n", __FUNCTION__, __LINE__);
ensure_slots(n PASS_REGS); ensure_slots(n PASS_REGS);
for (i = 0; i < n; i++) for (i = 0; i < n; i++)
LOCAL_SlotBase[old_slots + i] = ts[i]; LOCAL_SlotBase[old_slots + i] = ts[i];
@ -193,19 +217,23 @@ static inline yhandle_t Yap_InitSlots__(int n, Term *ts USES_REGS) {
return old_slots; return old_slots;
} }
#define Yap_RecoverSlots(n, ts) Yap_RecoverSlots__(n, ts PASS_REGS)
/// @brief Succeeds if it is to recover the space allocated for $n$ contiguos /// @brief Succeeds if it is to recover the space allocated for $n$ contiguos
/// slots starting at topSlot. /// slots starting at topSlot.
static inline bool Yap_RecoverSlots(int n, yhandle_t topSlot USES_REGS) { static inline bool Yap_RecoverSlots__(int n, yhandle_t topSlot USES_REGS);
if (topSlot+n < LOCAL_CurSlot) static inline bool Yap_RecoverSlots__(int n, yhandle_t topSlot USES_REGS) {
if (topSlot + n < LOCAL_CurSlot)
return false; return false;
#ifdef DEBUG #ifdef DEBUG
if (n > LOCAL_CurSlot) { if (n > LOCAL_CurSlot) {
Yap_Error(SYSTEM_ERROR_INTERNAL, 0 , "Inconsistent slot state in Yap_RecoverSlots.", 0); Yap_Error(SYSTEM_ERROR_INTERNAL, 0,
"Inconsistent slot state in Yap_RecoverSlots.", 0);
return false; return false;
} }
#endif #endif
LOCAL_CurSlot -= n; LOCAL_CurSlot -= n;
// fprintf(stderr,"RS %s:%d\n", __FUNCTION__, __LINE__); //fprintf(stderr,"RS %ld %s:%d\n", LOCAL_CurSlot, __FILE__, __LINE__);
return true; return true;
} }

View File

@ -72,7 +72,7 @@ typedef struct swi_reverse_hash {
//#define GC_MAVARS_HASH_SIZE 512 //#define GC_MAVARS_HASH_SIZE 512
// //
//typedef struct gc_ma_hash_entry_struct { // typedef struct gc_ma_hash_entry_struct {
// UInt timestmp; // UInt timestmp;
//#ifdef TABLING //#ifdef TABLING
// tr_fr_ptr loc; // tr_fr_ptr loc;
@ -85,12 +85,12 @@ typedef struct swi_reverse_hash {
typedef void (*HaltHookFunc)(int, void *); typedef void (*HaltHookFunc)(int, void *);
typedef struct halt_hook { typedef struct halt_hook {
void * environment; void *environment;
HaltHookFunc hook; HaltHookFunc hook;
struct halt_hook *next; struct halt_hook *next;
} halt_hook_entry; } halt_hook_entry;
int Yap_HaltRegisterHook(HaltHookFunc, void *); int Yap_HaltRegisterHook(HaltHookFunc, void *);
typedef struct atom_hash_entry { typedef struct atom_hash_entry {
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
@ -99,7 +99,7 @@ typedef struct atom_hash_entry {
Atom Entry; Atom Entry;
} AtomHashEntry; } AtomHashEntry;
//typedef struct scratch_block_struct { // typedef struct scratch_block_struct {
// char *ptr; // char *ptr;
// UInt sz, msz; // UInt sz, msz;
//} scratch_block; //} scratch_block;
@ -112,7 +112,7 @@ typedef struct record_list {
/* SWI Emulation */ /* SWI Emulation */
#define SWI_BUF_SIZE 512 #define SWI_BUF_SIZE 512
#define SWI_TMP_BUF_SIZE 2*SWI_BUF_SIZE #define SWI_TMP_BUF_SIZE 2 * SWI_BUF_SIZE
#define SWI_BUF_RINGS 16 #define SWI_BUF_RINGS 16
/* ricardo /* ricardo
@ -151,21 +151,51 @@ typedef struct thandle {
} yap_thandle; } yap_thandle;
#endif */ #endif */
//typedef int (*Agc_hook)(Atom); // typedef int (*Agc_hook)(Atom);
/******************* /*******************
this is the data base: everything here should be possible to restore this is the data base: everything here should be possible to restore
********************/ ********************/
#if YAPOR
typedef struct various_codes { typedef struct various_codes {
/* memory allocation and management */ /* memory allocation and management */
special_functors funcs; special_functors funcs;
#include "hstruct.h" #include "heap/hstruct.h"
} all_heap_codes; } all_heap_codes;
//#include "hglobals.h" #include "heap/hglobals.h"
//#include "hlocals.h"
#include "heap/dhstruct.h"
#include "heap/dglobals.h"
#else
typedef struct various_codes {
/* memory allocation and management */
special_functors funcs;
#include "tatoms.h"
} all_heap_codes;
#if __INIT_C__
#define EXTERNAL
#else
#define EXTERNAL extern
#endif
#include "heap/h0struct.h"
#include "heap/h0globals.h"
#endif
#include "heap/hlocals.h"
#include "heap/dlocals.h"
/* ricardo /* ricardo
#if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) #if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA)
@ -191,74 +221,56 @@ extern struct worker_local Yap_local;
#ifdef USE_SYSTEM_MALLOC #ifdef USE_SYSTEM_MALLOC
extern struct various_codes *Yap_heap_regs; extern struct various_codes *Yap_heap_regs;
#else #else
#define Yap_heap_regs ((all_heap_codes *)HEAP_INIT_BASE) #define Yap_heap_regs ((all_heap_codes *)HEAP_INIT_BASE)
#endif #endif
#include "dhstruct.h"
//#include "dglobals.h"
//#include "dlocals.h"
/** /**
* gc-P: how to start-up the grbage collector in C-code * gc-P: how to start-up the grbage collector in C-code
*/ */
static inline static inline yamop *gc_P(yamop *p, yamop *cp) {
yamop * return (p && p->opc == EXECUTE_CPRED_OPCODE ? cp : p);
gc_P(yamop *p, yamop *cp)
{
return (p->opc == EXECUTE_CPRED_OPCODE ? cp : p);
} }
/** /**
Yap_CurrentModule: access the current module for looking Yap_CurrentModule: access the current module for looking
up predicates up predicates
*/ */
#define Yap_CurrentModule() Yap_CurrentModule__ (PASS_REGS1) #define Yap_CurrentModule() Yap_CurrentModule__(PASS_REGS1)
INLINE_ONLY inline EXTERN Term Yap_CurrentModule__ (USES_REGS1) ; INLINE_ONLY inline EXTERN Term Yap_CurrentModule__(USES_REGS1);
INLINE_ONLY inline EXTERN Term INLINE_ONLY inline EXTERN Term Yap_CurrentModule__(USES_REGS1) {
Yap_CurrentModule__ (USES_REGS1) if (CurrentModule)
{ return CurrentModule;
if (CurrentModule) return CurrentModule;
return TermProlog; return TermProlog;
} }
/******************* /*******************
these are the global variables: they need not be restored... these are the global variables: they need not be restored...
********************/ ********************/
#define UPDATE_MODE_IMMEDIATE 0 #define UPDATE_MODE_IMMEDIATE 0
#define UPDATE_MODE_LOGICAL 1 #define UPDATE_MODE_LOGICAL 1
#define UPDATE_MODE_LOGICAL_ASSERT 2 #define UPDATE_MODE_LOGICAL_ASSERT 2
/* initially allow for files with up to 1024 predicates. This number /* initially allow for files with up to 1024 predicates. This number
is extended whenever needed */ is extended whenever needed */
#define InitialConsultCapacity 1024 #define InitialConsultCapacity 1024
#if (defined(USE_SYSTEM_MALLOC) && HAVE_MALLINFO) || USE_DL_MALLOC
#if (defined(USE_SYSTEM_MALLOC) && HAVE_MALLINFO)||USE_DL_MALLOC
UInt Yap_givemallinfo(void); UInt Yap_givemallinfo(void);
#endif #endif
ADDR Yap_ExpandPreAllocCodeSpace(UInt, void *, int); ADDR Yap_ExpandPreAllocCodeSpace(UInt, void *, int);
#define Yap_ReleasePreAllocCodeSpace(x) #define Yap_ReleasePreAllocCodeSpace(x)
ADDR Yap_InitPreAllocCodeSpace(int); ADDR Yap_InitPreAllocCodeSpace(int);
#include "inline-only.h" #include "inline-only.h"
INLINE_ONLY EXTERN inline ADDR INLINE_ONLY EXTERN inline ADDR Yap_PreAllocCodeSpace(void);
Yap_PreAllocCodeSpace(void);
INLINE_ONLY EXTERN inline ADDR INLINE_ONLY EXTERN inline ADDR Yap_PreAllocCodeSpace(void) {
Yap_PreAllocCodeSpace(void)
{
CACHE_REGS CACHE_REGS
return AuxBase; return AuxBase;
} }

View File

@ -22,7 +22,7 @@
YAP_FLAG( AUTOLOAD_FLAG, "autoload", true, boolean, "false" , NULL ), YAP_FLAG( AUTOLOAD_FLAG, "autoload", true, boolean, "false" , NULL ),
YAP_FLAG( BREAK_LEVEL_FLAG, "break_level", true, nat, "0" , NULL ), YAP_FLAG( BREAK_LEVEL_FLAG, "break_level", true, nat, "0" , NULL ),
YAP_FLAG( ENCODING_FLAG, "encoding", true, isatom, "text" , getenc ), YAP_FLAG( ENCODING_FLAG, "encoding", true, isatom, "utf-8" , getenc ),
YAP_FLAG( FILEERRORS_FLAG, "fileerrors", true, boolean, "true" , NULL ), /**< `fileerrors` YAP_FLAG( FILEERRORS_FLAG, "fileerrors", true, boolean, "true" , NULL ), /**< `fileerrors`
If `on` `fileerrors` is `on`, if `off` (default) If `on` `fileerrors` is `on`, if `off` (default)

View File

@ -56,7 +56,7 @@ typedef enum {
extern char_kind_t Yap_chtype0[]; extern char_kind_t Yap_chtype0[];
#define Yap_chtype (Yap_chtype0+1) #define Yap_chtype (Yap_chtype0 + 1)
char_kind_t Yap_wide_chtype(int ch); char_kind_t Yap_wide_chtype(int ch);
@ -483,8 +483,7 @@ static inline Term Yap_AtomToNumber(Term t0 USES_REGS) {
inp.val.t = t0; inp.val.t = t0;
inp.type = YAP_STRING_ATOM; inp.type = YAP_STRING_ATOM;
out.val.uc = NULL; out.val.uc = NULL;
out.type = out.type = YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG;
YAP_STRING_INT | YAP_STRING_FLOAT | YAP_STRING_BIG;
if (!Yap_CVT_Text(&inp, &out PASS_REGS)) if (!Yap_CVT_Text(&inp, &out PASS_REGS))
return 0L; return 0L;
return out.val.t; return out.val.t;
@ -1213,11 +1212,9 @@ static inline Term Yap_StringToNumber(Term t0 USES_REGS) {
} }
static inline Term Yap_UTF8ToString(const char *s USES_REGS) { static inline Term Yap_UTF8ToString(const char *s USES_REGS) {
return MkStringTerm( s ); return MkStringTerm(s);
} }
static inline Term Yap_WCharsToListOfCodes(const wchar_t *s USES_REGS) { static inline Term Yap_WCharsToListOfCodes(const wchar_t *s USES_REGS) {
seq_tv_t inp, out; seq_tv_t inp, out;
inp.val.w0 = s; inp.val.w0 = s;

View File

@ -124,7 +124,7 @@ Atom Yap_ConsultingFile(USES_REGS1);
struct pred_entry *Yap_PredForChoicePt(choiceptr bptr, op_numbers *op); struct pred_entry *Yap_PredForChoicePt(choiceptr bptr, op_numbers *op);
void Yap_InitCdMgr(void); void Yap_InitCdMgr(void);
struct pred_entry *Yap_PredFromClause(Term t USES_REGS); struct pred_entry *Yap_PredFromClause(Term t USES_REGS);
bool Yap_discontiguous(struct pred_entry *ap USES_REGS); bool Yap_discontiguous(struct pred_entry *ap, Term mode USES_REGS);
bool Yap_multiple(struct pred_entry *ap, int mode USES_REGS); bool Yap_multiple(struct pred_entry *ap, int mode USES_REGS);
void Yap_init_consult(int, const char *); void Yap_init_consult(int, const char *);
void Yap_end_consult(void); void Yap_end_consult(void);
@ -136,6 +136,7 @@ void Yap_AssertzClause(struct pred_entry *, yamop *);
void Yap_HidePred(struct pred_entry *pe); void Yap_HidePred(struct pred_entry *pe);
int Yap_SetNoTrace(char *name, UInt arity, Term tmod); int Yap_SetNoTrace(char *name, UInt arity, Term tmod);
bool Yap_unknown(Term tflagvalue); bool Yap_unknown(Term tflagvalue);
struct pred_entry *Yap_MkLogPred(struct pred_entry *pe);
/* cmppreds.c */ /* cmppreds.c */
Int Yap_compare_terms(Term, Term); Int Yap_compare_terms(Term, Term);
@ -319,7 +320,7 @@ void Yap_InitModulesC(void);
struct mod_entry *Yap_GetModuleEntry(Term tmod); struct mod_entry *Yap_GetModuleEntry(Term tmod);
Term Yap_GetModuleFromEntry(struct mod_entry *me); Term Yap_GetModuleFromEntry(struct mod_entry *me);
bool Yap_CharacterEscapes(Term mt); bool Yap_CharacterEscapes(Term mt);
bool Yap_constPred( struct pred_entry *pt); bool Yap_constPred(struct pred_entry *pt);
bool Yap_isSystemModule(Term mod); bool Yap_isSystemModule(Term mod);
#if HAVE_MPI #if HAVE_MPI

1971
H/Yatom.h

File diff suppressed because it is too large Load Diff

View File

@ -26,127 +26,126 @@
typedef union CONSULT_OBJ { typedef union CONSULT_OBJ {
const unsigned char *filename; const unsigned char *filename;
int mode; int mode;
Prop p; Prop p;
UInt c; UInt c;
} consult_obj; } consult_obj;
/* Either we are assembling clauses or indexing code */ /* Either we are assembling clauses or indexing code */
#define ASSEMBLING_CLAUSE 0 #define ASSEMBLING_CLAUSE 0
#define ASSEMBLING_INDEX 1 #define ASSEMBLING_INDEX 1
#define ASSEMBLING_EINDEX 2 #define ASSEMBLING_EINDEX 2
#define NextDynamicClause(X) (((yamop *)X)->y_u.Otapl.d) #define NextDynamicClause(X) (((yamop *)X)->y_u.Otapl.d)
#define PredFirstClause 0 #define PredFirstClause 0
#define PredMiddleClause 1 #define PredMiddleClause 1
#define PredLastClause 2 #define PredLastClause 2
typedef struct logic_upd_index { typedef struct logic_upd_index {
CELL ClFlags; CELL ClFlags;
UInt ClRefCount; UInt ClRefCount;
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
/* A lock for manipulating the clause */ /* A lock for manipulating the clause */
// lockvar ClLock; // lockvar ClLock;
#endif #endif
UInt ClSize; UInt ClSize;
struct logic_upd_index *ParentIndex; struct logic_upd_index *ParentIndex;
struct logic_upd_index *SiblingIndex; struct logic_upd_index *SiblingIndex;
struct logic_upd_index *PrevSiblingIndex; struct logic_upd_index *PrevSiblingIndex;
struct logic_upd_index *ChildIndex; struct logic_upd_index *ChildIndex;
/* The instructions, at least one of the form sl */ /* The instructions, at least one of the form sl */
PredEntry *ClPred; PredEntry *ClPred;
yamop ClCode[MIN_ARRAY]; yamop ClCode[MIN_ARRAY];
} LogUpdIndex; } LogUpdIndex;
/* The ordering of the first 3 fields should be compatible with dbrefs */ /* The ordering of the first 3 fields should be compatible with dbrefs */
typedef struct logic_upd_clause { typedef struct logic_upd_clause {
Functor Id; /* allow pointers to this struct to id */ Functor Id; /* allow pointers to this struct to id */
/* as dbref */ /* as dbref */
/* A set of flags describing info on the clause */ /* A set of flags describing info on the clause */
/* A set of flags describing info on the clause */ /* A set of flags describing info on the clause */
CELL ClFlags; CELL ClFlags;
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
/* A lock for manipulating the clause */ /* A lock for manipulating the clause */
// lockvar ClLock; // lockvar ClLock;
#endif #endif
UInt ClSize; UInt ClSize;
/* extra clause information for logical update indices and facts */ /* extra clause information for logical update indices and facts */
/* indices that may still backtrack to this clause */ /* indices that may still backtrack to this clause */
UInt ClRefCount; UInt ClRefCount;
/* data for clauses with environments */ /* data for clauses with environments */
yamop *ClExt; yamop *ClExt;
union { union {
DBTerm *ClSource; DBTerm *ClSource;
Int ClLine; Int ClLine;
} lusl; } lusl;
/* doubly linked list of clauses */ /* doubly linked list of clauses */
struct logic_upd_clause *ClPrev, *ClNext; struct logic_upd_clause *ClPrev, *ClNext;
/* parent pointer */ /* parent pointer */
PredEntry *ClPred; PredEntry *ClPred;
UInt ClTimeStart, ClTimeEnd; UInt ClTimeStart, ClTimeEnd;
/* The instructions, at least one of the form sl */ /* The instructions, at least one of the form sl */
yamop ClCode[MIN_ARRAY]; yamop ClCode[MIN_ARRAY];
} LogUpdClause; } LogUpdClause;
#include "inline-only.h" #include "inline-only.h"
INLINE_ONLY inline EXTERN int VALID_TIMESTAMP(UInt, struct logic_upd_clause *); INLINE_ONLY inline EXTERN int VALID_TIMESTAMP(UInt, struct logic_upd_clause *);
INLINE_ONLY inline EXTERN int INLINE_ONLY inline EXTERN int VALID_TIMESTAMP(UInt timestamp,
VALID_TIMESTAMP(UInt timestamp, struct logic_upd_clause *cl) struct logic_upd_clause *cl) {
{
return IN_BETWEEN(cl->ClTimeStart, timestamp, cl->ClTimeEnd); return IN_BETWEEN(cl->ClTimeStart, timestamp, cl->ClTimeEnd);
} }
typedef struct dynamic_clause { typedef struct dynamic_clause {
/* A set of flags describing info on the clause */ /* A set of flags describing info on the clause */
CELL ClFlags; CELL ClFlags;
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
/* A lock for manipulating the clause */ /* A lock for manipulating the clause */
lockvar ClLock; lockvar ClLock;
#endif #endif
UInt ClSize; UInt ClSize;
Int ClLine; Int ClLine;
UInt ClRefCount; UInt ClRefCount;
yamop *ClPrevious; /* immediate update clause */ yamop *ClPrevious; /* immediate update clause */
/* The instructions, at least one of the form sl */ /* The instructions, at least one of the form sl */
yamop ClCode[MIN_ARRAY]; yamop ClCode[MIN_ARRAY];
} DynamicClause; } DynamicClause;
typedef struct static_index { typedef struct static_index {
/* A set of flags describing info on the clause */ /* A set of flags describing info on the clause */
CELL ClFlags; CELL ClFlags;
UInt ClSize; UInt ClSize;
struct static_index *SiblingIndex; struct static_index *SiblingIndex;
struct static_index *ChildIndex; struct static_index *ChildIndex;
/* The instructions, at least one of the form sl */ /* The instructions, at least one of the form sl */
PredEntry *ClPred; PredEntry *ClPred;
yamop ClCode[MIN_ARRAY]; yamop ClCode[MIN_ARRAY];
} StaticIndex; } StaticIndex;
typedef struct static_clause { typedef struct static_clause {
/* A set of flags describing info on the clause */ /* A set of flags describing info on the clause */
CELL ClFlags; CELL ClFlags;
UInt ClSize; UInt ClSize;
union { union {
DBTerm *ClSource; DBTerm *ClSource;
Int ClLine; Int ClLine;
} usc; } usc;
struct static_clause *ClNext; struct static_clause *ClNext;
/* The instructions, at least one of the form sl */ /* The instructions, at least one of the form sl */
yamop ClCode[MIN_ARRAY]; yamop ClCode[MIN_ARRAY];
} StaticClause; } StaticClause;
typedef struct static_mega_clause { typedef struct static_mega_clause {
/* A set of flags describing info on the clause */ /* A set of flags describing info on the clause */
CELL ClFlags; CELL ClFlags;
UInt ClSize; UInt ClSize;
PredEntry *ClPred; PredEntry *ClPred;
UInt ClItemSize; UInt ClItemSize;
Int ClLine; Int ClLine;
struct static_mega_clause *ClNext; struct static_mega_clause *ClNext;
/* The instructions, at least one of the form sl */ /* The instructions, at least one of the form sl */
yamop ClCode[MIN_ARRAY]; yamop ClCode[MIN_ARRAY];
} MegaClause; } MegaClause;
typedef union clause_obj { typedef union clause_obj {
@ -191,43 +190,43 @@ typedef struct index_t {
UInt udi_arg; UInt udi_arg;
} Index_t; } Index_t;
INLINE_ONLY EXTERN inline BITS32 EXO_ADDRESS_TO_OFFSET(struct index_t *it, CELL *ptr); INLINE_ONLY EXTERN inline BITS32 EXO_ADDRESS_TO_OFFSET(struct index_t *it,
CELL *ptr);
INLINE_ONLY EXTERN inline BITS32 INLINE_ONLY EXTERN inline BITS32 EXO_ADDRESS_TO_OFFSET(struct index_t *it,
EXO_ADDRESS_TO_OFFSET(struct index_t *it, CELL* ptr) CELL *ptr) {
{ return (ptr - it->cls) / it->arity + 1;
return (ptr-it->cls)/it->arity+1;
} }
INLINE_ONLY EXTERN inline CELL *EXO_OFFSET_TO_ADDRESS(struct index_t *it, BITS32 off); INLINE_ONLY EXTERN inline CELL *EXO_OFFSET_TO_ADDRESS(struct index_t *it,
BITS32 off);
INLINE_ONLY EXTERN inline CELL * INLINE_ONLY EXTERN inline CELL *EXO_OFFSET_TO_ADDRESS(struct index_t *it,
EXO_OFFSET_TO_ADDRESS(struct index_t *it, BITS32 off) BITS32 off) {
{
if (off == 0L) if (off == 0L)
return (CELL *)NULL; return (CELL *)NULL;
return (it->cls)+(off-1)*it->arity; return (it->cls) + (off - 1) * it->arity;
} }
INLINE_ONLY EXTERN inline BITS32 ADDRESS_TO_LINK(struct index_t *it, BITS32 *ptr); INLINE_ONLY EXTERN inline BITS32 ADDRESS_TO_LINK(struct index_t *it,
BITS32 *ptr);
INLINE_ONLY EXTERN inline BITS32 INLINE_ONLY EXTERN inline BITS32 ADDRESS_TO_LINK(struct index_t *it,
ADDRESS_TO_LINK(struct index_t *it, BITS32* ptr) BITS32 *ptr) {
{ return ptr - it->links;
return ptr-it->links;
} }
INLINE_ONLY EXTERN inline BITS32 *LINK_TO_ADDRESS(struct index_t *it, BITS32 off); INLINE_ONLY EXTERN inline BITS32 *LINK_TO_ADDRESS(struct index_t *it,
BITS32 off);
INLINE_ONLY EXTERN inline BITS32 * INLINE_ONLY EXTERN inline BITS32 *LINK_TO_ADDRESS(struct index_t *it,
LINK_TO_ADDRESS(struct index_t *it, BITS32 off) BITS32 off) {
{ return it->links + off;
return it->links+off;
} }
typedef void (*CRefitExoIndex)(struct index_t **ip, UInt b[] USES_REGS); typedef void (*CRefitExoIndex)(struct index_t **ip, UInt b[] USES_REGS);
typedef yamop * (*CEnterExoIndex)(struct index_t *it USES_REGS); typedef yamop *(*CEnterExoIndex)(struct index_t *it USES_REGS);
typedef int (*CRetryExoIndex)(struct index_t *it USES_REGS); typedef int (*CRetryExoIndex)(struct index_t *it USES_REGS);
typedef struct dbterm_list { typedef struct dbterm_list {
/* a list of dbterms associated with a clause */ /* a list of dbterms associated with a clause */
@ -237,72 +236,81 @@ typedef struct dbterm_list {
struct dbterm_list *next_dbl; struct dbterm_list *next_dbl;
} DBTermList; } DBTermList;
#define ClauseCodeToDynamicClause(p) ((DynamicClause *)((CODEADDR)(p)-(CELL)(((DynamicClause *)NULL)->ClCode))) #define ClauseCodeToDynamicClause(p) \
#define ClauseCodeToStaticClause(p) ((StaticClause *)((CODEADDR)(p)-(CELL)(((StaticClause *)NULL)->ClCode))) ((DynamicClause *)((CODEADDR)(p) - (CELL)(((DynamicClause *)NULL)->ClCode)))
#define ClauseCodeToLogUpdClause(p) ((LogUpdClause *)((CODEADDR)(p)-(CELL)(((LogUpdClause *)NULL)->ClCode))) #define ClauseCodeToStaticClause(p) \
#define ClauseCodeToMegaClause(p) ((MegaClause *)((CODEADDR)(p)-(CELL)(((MegaClause *)NULL)->ClCode))) ((StaticClause *)((CODEADDR)(p) - (CELL)(((StaticClause *)NULL)->ClCode)))
#define ClauseCodeToLogUpdIndex(p) ((LogUpdIndex *)((CODEADDR)(p)-(CELL)(((LogUpdIndex *)NULL)->ClCode))) #define ClauseCodeToLogUpdClause(p) \
#define ClauseCodeToStaticIndex(p) ((StaticIndex *)((CODEADDR)(p)-(CELL)(((StaticIndex *)NULL)->ClCode))) ((LogUpdClause *)((CODEADDR)(p) - (CELL)(((LogUpdClause *)NULL)->ClCode)))
#define ClauseCodeToMegaClause(p) \
((MegaClause *)((CODEADDR)(p) - (CELL)(((MegaClause *)NULL)->ClCode)))
#define ClauseCodeToLogUpdIndex(p) \
((LogUpdIndex *)((CODEADDR)(p) - (CELL)(((LogUpdIndex *)NULL)->ClCode)))
#define ClauseCodeToStaticIndex(p) \
((StaticIndex *)((CODEADDR)(p) - (CELL)(((StaticIndex *)NULL)->ClCode)))
#define ClauseFlagsToDynamicClause(p) ((DynamicClause *)(p)) #define ClauseFlagsToDynamicClause(p) ((DynamicClause *)(p))
#define ClauseFlagsToLogUpdClause(p) ((LogUpdClause *)((CODEADDR)(p)-(CELL)(&(((LogUpdClause *)NULL)->ClFlags)))) #define ClauseFlagsToLogUpdClause(p) \
#define ClauseFlagsToLogUpdIndex(p) ((LogUpdIndex *)((CODEADDR)(p)-(CELL)(&(((LogUpdIndex *)NULL)->ClFlags)))) ((LogUpdClause *)((CODEADDR)(p) - (CELL)(&(((LogUpdClause *)NULL)->ClFlags))))
#define ClauseFlagsToStaticClause(p) ((StaticClause *)(p)) #define ClauseFlagsToLogUpdIndex(p) \
((LogUpdIndex *)((CODEADDR)(p) - (CELL)(&(((LogUpdIndex *)NULL)->ClFlags))))
#define ClauseFlagsToStaticClause(p) ((StaticClause *)(p))
#define DynamicFlags(X) (ClauseCodeToDynamicClause(X)->ClFlags) #define DynamicFlags(X) (ClauseCodeToDynamicClause(X)->ClFlags)
#define DynamicLock(X) (ClauseCodeToDynamicClause(X)->ClLock) #define DynamicLock(X) (ClauseCodeToDynamicClause(X)->ClLock)
#if MULTIPLE_STACKS #if MULTIPLE_STACKS
#define INIT_CLREF_COUNT(X) (X)->ClRefCount = 0 #define INIT_CLREF_COUNT(X) (X)->ClRefCount = 0
#define INC_CLREF_COUNT(X) (X)->ClRefCount++ #define INC_CLREF_COUNT(X) (X)->ClRefCount++
#define DEC_CLREF_COUNT(X) (X)->ClRefCount-- #define DEC_CLREF_COUNT(X) (X)->ClRefCount--
#define CL_IN_USE(X) ((X)->ClRefCount) #define CL_IN_USE(X) ((X)->ClRefCount)
#else #else
#define INIT_CLREF_COUNT(X) #define INIT_CLREF_COUNT(X)
#define INC_CLREF_COUNT(X) #define INC_CLREF_COUNT(X)
#define DEC_CLREF_COUNT(X) #define DEC_CLREF_COUNT(X)
#define CL_IN_USE(X) ((X)->ClFlags & InUseMask || (X)->ClRefCount) #define CL_IN_USE(X) ((X)->ClFlags & InUseMask || (X)->ClRefCount)
#endif #endif
/* amasm.c */ /* amasm.c */
wamreg Yap_emit_x(CELL); wamreg Yap_emit_x(CELL);
COUNT Yap_compile_cmp_flags(PredEntry *); COUNT Yap_compile_cmp_flags(PredEntry *);
void Yap_InitComma(void); void Yap_InitComma(void);
/* cdmgr.c */ /* cdmgr.c */
void Yap_IPred(PredEntry *, UInt, yamop *); void Yap_IPred(PredEntry *, UInt, yamop *);
int Yap_addclause(Term,yamop *,int,Term,Term*); bool Yap_addclause(Term, yamop *, int, Term, Term *);
void Yap_add_logupd_clause(PredEntry *,LogUpdClause *,int); void Yap_add_logupd_clause(PredEntry *, LogUpdClause *, int);
void Yap_kill_iblock(ClauseUnion *,ClauseUnion *,PredEntry *); void Yap_kill_iblock(ClauseUnion *, ClauseUnion *, PredEntry *);
void Yap_EraseStaticClause(StaticClause *, PredEntry *, Term); void Yap_EraseStaticClause(StaticClause *, PredEntry *, Term);
ClauseUnion *Yap_find_owner_index(yamop *, PredEntry *); ClauseUnion *Yap_find_owner_index(yamop *, PredEntry *);
/* dbase.c */ /* dbase.c */
void Yap_ErCl(DynamicClause *); void Yap_ErCl(DynamicClause *);
void Yap_ErLogUpdCl(LogUpdClause *); void Yap_ErLogUpdCl(LogUpdClause *);
void Yap_ErLogUpdIndex(LogUpdIndex *); void Yap_ErLogUpdIndex(LogUpdIndex *);
Int Yap_Recordz(Atom, Term); Int Yap_Recordz(Atom, Term);
Int Yap_db_nth_recorded( PredEntry *, Int USES_REGS ); Int Yap_db_nth_recorded(PredEntry *, Int USES_REGS);
Int Yap_unify_immediate_ref(DBRef ref USES_REGS ); Int Yap_unify_immediate_ref(DBRef ref USES_REGS);
/* exec.c */ /* exec.c */
Term Yap_cp_as_integer(choiceptr); Term Yap_cp_as_integer(choiceptr);
/* index.c */ /* index.c */
yamop *Yap_PredIsIndexable(PredEntry *, UInt, yamop *); yamop *Yap_PredIsIndexable(PredEntry *, UInt, yamop *);
yamop *Yap_ExpandIndex(PredEntry *, UInt); yamop *Yap_ExpandIndex(PredEntry *, UInt);
void Yap_CleanUpIndex(struct logic_upd_index *); void Yap_CleanUpIndex(struct logic_upd_index *);
void Yap_CleanKids(struct logic_upd_index *); void Yap_CleanKids(struct logic_upd_index *);
void Yap_AddClauseToIndex(PredEntry *,yamop *,int); void Yap_AddClauseToIndex(PredEntry *, yamop *, int);
void Yap_RemoveClauseFromIndex(PredEntry *,yamop *); void Yap_RemoveClauseFromIndex(PredEntry *, yamop *);
LogUpdClause *Yap_NthClause(PredEntry *,Int); LogUpdClause *Yap_NthClause(PredEntry *, Int);
LogUpdClause *Yap_FollowIndexingCode(PredEntry *,yamop *, Term *, yamop *,yamop *); LogUpdClause *Yap_FollowIndexingCode(PredEntry *, yamop *, Term *, yamop *,
yamop *);
/* exo.c */ /* exo.c */
yamop *Yap_ExoLookup(PredEntry *ap USES_REGS); yamop *Yap_ExoLookup(PredEntry *ap USES_REGS);
CELL Yap_NextExo(choiceptr cpt, struct index_t *it); CELL Yap_NextExo(choiceptr cpt, struct index_t *it);
# #
#if USE_THREADED_CODE #if USE_THREADED_CODE
@ -311,24 +319,21 @@ CELL Yap_NextExo(choiceptr cpt, struct index_t *it);
INLINE_ONLY inline EXTERN int rtable_hash_op(OPCODE opc, int hash_mask); INLINE_ONLY inline EXTERN int rtable_hash_op(OPCODE opc, int hash_mask);
INLINE_ONLY inline EXTERN int INLINE_ONLY inline EXTERN int rtable_hash_op(OPCODE opc, int hash_mask) {
rtable_hash_op(OPCODE opc, int hash_mask) { return ((((CELL)opc) >> 3) & hash_mask);
return((((CELL)opc) >> 3) & hash_mask);
} }
INLINE_ONLY inline EXTERN op_numbers Yap_op_from_opcode(OPCODE opc); INLINE_ONLY inline EXTERN op_numbers Yap_op_from_opcode(OPCODE opc);
/* given an opcode find the corresponding opnumber. This should make /* given an opcode find the corresponding opnumber. This should make
switches on ops a much easier operation */ switches on ops a much easier operation */
INLINE_ONLY inline EXTERN op_numbers INLINE_ONLY inline EXTERN op_numbers Yap_op_from_opcode(OPCODE opc) {
Yap_op_from_opcode(OPCODE opc) int j = rtable_hash_op(opc, OP_HASH_SIZE - 1);
{
int j = rtable_hash_op(opc,OP_HASH_SIZE-1);
while (OP_RTABLE[j].opc != opc) { while (OP_RTABLE[j].opc != opc) {
if (!OP_RTABLE[j].opc) if (!OP_RTABLE[j].opc)
return _Nstop; return _Nstop;
if (j == OP_HASH_SIZE-1) { if (j == OP_HASH_SIZE - 1) {
j = 0; j = 0;
} else { } else {
j++; j++;
@ -337,26 +342,23 @@ Yap_op_from_opcode(OPCODE opc)
return OP_RTABLE[j].opnum; return OP_RTABLE[j].opnum;
} }
#else #else
static inline op_numbers static inline op_numbers Yap_op_from_opcode(OPCODE opc) {
Yap_op_from_opcode(OPCODE opc) return ((op_numbers)opc);
{
return((op_numbers)opc);
} }
#endif /* USE_THREADED_CODE */ #endif /* USE_THREADED_CODE */
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
static inline int same_lu_block(yamop **, yamop *); static inline int same_lu_block(yamop **, yamop *);
static inline int static inline int same_lu_block(yamop **paddr, yamop *p) {
same_lu_block(yamop **paddr, yamop *p)
{
yamop *np = *paddr; yamop *np = *paddr;
if (np != p) { if (np != p) {
OPCODE jmp_op = Yap_opcode(_jump_if_nonvar); OPCODE jmp_op = Yap_opcode(_jump_if_nonvar);
while (np->opc == jmp_op) { while (np->opc == jmp_op) {
np = NEXTOP(np, xll); np = NEXTOP(np, xll);
if (np == p) return TRUE; if (np == p)
return TRUE;
} }
return FALSE; return FALSE;
} else { } else {
@ -365,86 +367,69 @@ same_lu_block(yamop **paddr, yamop *p)
} }
#endif #endif
#define Yap_MkStaticRefTerm(cp, ap) __Yap_MkStaticRefTerm((cp), (ap) PASS_REGS) #define Yap_MkStaticRefTerm(cp, ap) __Yap_MkStaticRefTerm((cp), (ap)PASS_REGS)
static inline Term static inline Term __Yap_MkStaticRefTerm(StaticClause *cp,
__Yap_MkStaticRefTerm(StaticClause *cp, PredEntry *ap USES_REGS) PredEntry *ap USES_REGS) {
{
Term t[2]; Term t[2];
t[0] = MkIntegerTerm((Int)cp); t[0] = MkIntegerTerm((Int)cp);
t[1] = MkIntegerTerm((Int)ap); t[1] = MkIntegerTerm((Int)ap);
return Yap_MkApplTerm(FunctorStaticClause,2,t); return Yap_MkApplTerm(FunctorStaticClause, 2, t);
} }
static inline StaticClause * static inline StaticClause *Yap_ClauseFromTerm(Term t) {
Yap_ClauseFromTerm(Term t) return (StaticClause *)IntegerOfTerm(ArgOfTerm(1, t));
{
return (StaticClause *)IntegerOfTerm(ArgOfTerm(1,t));
} }
#define Yap_MkMegaRefTerm(ap, ipc) __Yap_MkMegaRefTerm((ap), (ipc) PASS_REGS) #define Yap_MkMegaRefTerm(ap, ipc) __Yap_MkMegaRefTerm((ap), (ipc)PASS_REGS)
static inline Term static inline Term __Yap_MkMegaRefTerm(PredEntry *ap, yamop *ipc USES_REGS) {
__Yap_MkMegaRefTerm(PredEntry *ap,yamop *ipc USES_REGS)
{
Term t[2]; Term t[2];
t[0] = MkIntegerTerm((Int)ap); t[0] = MkIntegerTerm((Int)ap);
t[1] = MkIntegerTerm((Int)ipc); t[1] = MkIntegerTerm((Int)ipc);
return Yap_MkApplTerm(FunctorMegaClause,2,t); return Yap_MkApplTerm(FunctorMegaClause, 2, t);
} }
static inline yamop * static inline yamop *Yap_MegaClauseFromTerm(Term t) {
Yap_MegaClauseFromTerm(Term t) return (yamop *)IntegerOfTerm(ArgOfTerm(2, t));
{
return (yamop *)IntegerOfTerm(ArgOfTerm(2,t));
} }
static inline PredEntry * static inline PredEntry *Yap_MegaClausePredicateFromTerm(Term t) {
Yap_MegaClausePredicateFromTerm(Term t) return (PredEntry *)IntegerOfTerm(ArgOfTerm(1, t));
{
return (PredEntry *)IntegerOfTerm(ArgOfTerm(1,t));
} }
#define Yap_MkExoRefTerm(ap, i) __Yap_MkExoRefTerm((ap), (i) PASS_REGS) #define Yap_MkExoRefTerm(ap, i) __Yap_MkExoRefTerm((ap), (i)PASS_REGS)
static inline Term static inline Term __Yap_MkExoRefTerm(PredEntry *ap, Int i USES_REGS) {
__Yap_MkExoRefTerm(PredEntry *ap,Int i USES_REGS)
{
Term t[2]; Term t[2];
t[0] = MkIntegerTerm((Int)ap); t[0] = MkIntegerTerm((Int)ap);
t[1] = MkIntegerTerm((Int)i); t[1] = MkIntegerTerm((Int)i);
return Yap_MkApplTerm(FunctorExoClause,2,t); return Yap_MkApplTerm(FunctorExoClause, 2, t);
} }
static inline Int static inline Int Yap_ExoClauseFromTerm(Term t) {
Yap_ExoClauseFromTerm(Term t) return IntegerOfTerm(ArgOfTerm(2, t));
{
return IntegerOfTerm(ArgOfTerm(2,t));
} }
static inline PredEntry * static inline PredEntry *Yap_ExoClausePredicateFromTerm(Term t) {
Yap_ExoClausePredicateFromTerm(Term t) return (PredEntry *)IntegerOfTerm(ArgOfTerm(1, t));
{
return (PredEntry *)IntegerOfTerm(ArgOfTerm(1,t));
} }
/****************************************************************** /******************************************************************
EXECUTING PROLOG CLAUSES EXECUTING PROLOG CLAUSES
******************************************************************/ ******************************************************************/
bool bool Yap_search_for_static_predicate_in_use(PredEntry *p,
Yap_search_for_static_predicate_in_use(PredEntry *p, bool check_everything); bool check_everything);
static inline bool static inline bool Yap_static_in_use(PredEntry *p, bool check_everything) {
Yap_static_in_use(PredEntry *p, bool check_everything)
{
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
return TRUE; return TRUE;
#else #else
pred_flags_t pflags = p->PredFlags; pred_flags_t pflags = p->PredFlags;
if (pflags & (DynamicPredFlag|LogUpdatePredFlag)) { if (pflags & (DynamicPredFlag | LogUpdatePredFlag)) {
return FALSE; return FALSE;
} }
if (STATIC_PREDICATES_MARKED) { if (STATIC_PREDICATES_MARKED) {
@ -464,24 +449,24 @@ typedef enum {
FIND_PRED_FROM_ENV FIND_PRED_FROM_ENV
} find_pred_type; } find_pred_type;
Int Yap_PredForCode(yamop *, find_pred_type, Atom *, UInt *, Term *); Int Yap_PredForCode(yamop *, find_pred_type, Atom *, UInt *, Term *);
PredEntry *Yap_PredEntryForCode(yamop *, find_pred_type, void* *, void* *); PredEntry *Yap_PredEntryForCode(yamop *, find_pred_type, void **, void **);
LogUpdClause *Yap_new_ludbe(Term, PredEntry *, UInt); LogUpdClause *Yap_new_ludbe(Term, PredEntry *, UInt);
Term Yap_LUInstance(LogUpdClause *, UInt); Term Yap_LUInstance(LogUpdClause *, UInt);
/* udi.c */ /* udi.c */
int Yap_new_udi_clause(PredEntry *, yamop *, Term); int Yap_new_udi_clause(PredEntry *, yamop *, Term);
yamop *Yap_udi_search(PredEntry *); yamop *Yap_udi_search(PredEntry *);
Term Yap_bug_location(yamop *p, yamop *cp, choiceptr b_ptr, CELL *env); Term Yap_bug_location(yamop *p, yamop *cp, choiceptr b_ptr, CELL *env);
Term Yap_pc_location(yamop *p, choiceptr b_ptr, CELL *env); Term Yap_pc_location(yamop *p, choiceptr b_ptr, CELL *env);
Term Yap_env_location(yamop *p, choiceptr b_ptr, CELL *env, Int ignore_first); Term Yap_env_location(yamop *p, choiceptr b_ptr, CELL *env, Int ignore_first);
#if LOW_PROF #if LOW_PROF
void Yap_InformOfRemoval(void *); void Yap_InformOfRemoval(void *);
void Yap_dump_code_area_for_profiler(void); void Yap_dump_code_area_for_profiler(void);
#else #else
#define Yap_InformOfRemoval(X) #define Yap_InformOfRemoval(X)
#endif #endif
#endif #endif

View File

@ -1,146 +0,0 @@
/* This file, dglobals.h, was generated automatically by "yap -L misc/buildlocalglobal"
please do not update, update misc/GLOBALS instead */
#define GLOBAL_Initialised Yap_global->Initialised_
#define GLOBAL_InitialisedFromPL Yap_global->InitialisedFromPL_
#define GLOBAL_PL_Argc Yap_global->PL_Argc_
#define GLOBAL_PL_Argv Yap_global->PL_Argv_
#define GLOBAL_FAST_BOOT_FLAG Yap_global->FAST_BOOT_FLAG_
#define GLOBAL_HaltHooks Yap_global->HaltHooks_
#define GLOBAL_JIT_finalizer Yap_global->JIT_finalizer_
#define GLOBAL_AllowLocalExpansion Yap_global->AllowLocalExpansion_
#define GLOBAL_AllowGlobalExpansion Yap_global->AllowGlobalExpansion_
#define GLOBAL_AllowTrailExpansion Yap_global->AllowTrailExpansion_
#define GLOBAL_SizeOfOverflow Yap_global->SizeOfOverflow_
#define GLOBAL_AGcThreshold Yap_global->AGcThreshold_
#define GLOBAL_AGCHook Yap_global->AGCHook_
#if __ANDROID__
#define GLOBAL_assetManager Yap_global->assetManager_
#define GLOBAL_AssetsWD Yap_global->AssetsWD_
#endif
#if THREADS
#define GLOBAL_NOfThreads Yap_global->NOfThreads_
#define GLOBAL_NOfThreadsCreated Yap_global->NOfThreadsCreated_
#define GLOBAL_ThreadsTotalTime Yap_global->ThreadsTotalTime_
#define GLOBAL_ThreadHandlesLock Yap_global->ThreadHandlesLock_
#endif
#if defined(YAPOR) || defined(THREADS)
#define GLOBAL_BGL Yap_global->BGL_
#endif
#if defined(YAPOR) || defined(TABLING)
#define GLOBAL_optyap_data Yap_global->optyap_data_
#endif /* YAPOR || TABLING */
#define GLOBAL_PrologShouldHandleInterrupts Yap_global->PrologShouldHandleInterrupts_
#if defined(THREADS)
#define GLOBAL_master_thread Yap_global->master_thread_
#define GLOBAL_named_mboxes Yap_global->named_mboxes_
#define GLOBAL_mboxq_lock Yap_global->mboxq_lock_
#define GLOBAL_mbox_count Yap_global->mbox_count_
#define GLOBAL_WithMutex Yap_global->WithMutex_
#endif /* THREADS */
#define GLOBAL_Stream Yap_global->Stream_
#if defined(THREADS)||defined(YAPOR)
#define GLOBAL_StreamDescLock Yap_global->StreamDescLock_
#endif
#define GLOBAL_argv Yap_global->argv_
#define GLOBAL_argc Yap_global->argc_
#ifdef COROUTINING
#define GLOBAL_attas Yap_global->attas_
#endif
#define GLOBAL_agc_calls Yap_global->agc_calls_
#define GLOBAL_agc_collected Yap_global->agc_collected_
#define GLOBAL_tot_agc_time Yap_global->tot_agc_time_
#define GLOBAL_tot_agc_recovered Yap_global->tot_agc_recovered_
#if HAVE_MMAP
#define GLOBAL_mmap_arrays Yap_global->mmap_arrays_
#endif
#ifdef DEBUG
#define GLOBAL_Option Yap_global->Option_
#define GLOBAL_logfile Yap_global->logfile_
#endif
#if defined(COFF) || defined(A_OUT)
#define GLOBAL_Executable Yap_global->Executable_
#endif
#define GLOBAL_OpaqueHandlersCount Yap_global->OpaqueHandlersCount_
#define GLOBAL_OpaqueHandlers Yap_global->OpaqueHandlers_
#if __simplescalar__
#define GLOBAL_pwd Yap_global->pwd_
#endif
#define GLOBAL_RestoreFile Yap_global->RestoreFile_
#define GLOBAL_ProfCalls Yap_global->ProfCalls_
#define GLOBAL_ProfGCs Yap_global->ProfGCs_
#define GLOBAL_ProfHGrows Yap_global->ProfHGrows_
#define GLOBAL_ProfSGrows Yap_global->ProfSGrows_
#define GLOBAL_ProfMallocs Yap_global->ProfMallocs_
#define GLOBAL_ProfIndexing Yap_global->ProfIndexing_
#define GLOBAL_ProfOn Yap_global->ProfOn_
#define GLOBAL_ProfOns Yap_global->ProfOns_
#define GLOBAL_ProfilerRoot Yap_global->ProfilerRoot_
#define GLOBAL_ProfilerNil Yap_global->ProfilerNil_
#define GLOBAL_DIRNAME Yap_global->DIRNAME_
#if LOW_PROF
#define GLOBAL_ProfilerOn Yap_global->ProfilerOn_
#define GLOBAL_FProf Yap_global->FProf_
#define GLOBAL_FPreds Yap_global->FPreds_
#endif /* LOW_PROF */
#if THREADS
#define GLOBAL_FreeMutexes Yap_global->FreeMutexes_
#define GLOBAL_mutex_backbone Yap_global->mutex_backbone_
#define GLOBAL_MUT_ACCESS Yap_global->MUT_ACCESS_
#endif
#define GLOBAL_Home Yap_global->Home_
#define GLOBAL_CharConversionTable Yap_global->CharConversionTable_
#define GLOBAL_CharConversionTable2 Yap_global->CharConversionTable2_
#define GLOBAL_LastWTimePtr Yap_global->LastWTimePtr_
#define GLOBAL_MaxPriority Yap_global->MaxPriority_

View File

@ -1,493 +0,0 @@
/* This file, dlocals.h, was generated automatically by "yap -L misc/buildlocalglobal"
please do not update, update misc/LOCALS instead */
#define LOCAL_FileAliases LOCAL->FileAliases_
#define REMOTE_FileAliases(wid) REMOTE(wid)->FileAliases_
#define LOCAL_NOfFileAliases LOCAL->NOfFileAliases_
#define REMOTE_NOfFileAliases(wid) REMOTE(wid)->NOfFileAliases_
#define LOCAL_SzOfFileAliases LOCAL->SzOfFileAliases_
#define REMOTE_SzOfFileAliases(wid) REMOTE(wid)->SzOfFileAliases_
#define LOCAL_c_input_stream LOCAL->c_input_stream_
#define REMOTE_c_input_stream(wid) REMOTE(wid)->c_input_stream_
#define LOCAL_c_output_stream LOCAL->c_output_stream_
#define REMOTE_c_output_stream(wid) REMOTE(wid)->c_output_stream_
#define LOCAL_c_error_stream LOCAL->c_error_stream_
#define REMOTE_c_error_stream(wid) REMOTE(wid)->c_error_stream_
#define LOCAL_sockets_io LOCAL->sockets_io_
#define REMOTE_sockets_io(wid) REMOTE(wid)->sockets_io_
#define LOCAL_within_print_message LOCAL->within_print_message_
#define REMOTE_within_print_message(wid) REMOTE(wid)->within_print_message_
#define LOCAL_newline LOCAL->newline_
#define REMOTE_newline(wid) REMOTE(wid)->newline_
#define LOCAL_AtPrompt LOCAL->AtPrompt_
#define REMOTE_AtPrompt(wid) REMOTE(wid)->AtPrompt_
#define LOCAL_Prompt LOCAL->Prompt_
#define REMOTE_Prompt(wid) REMOTE(wid)->Prompt_
#define LOCAL_encoding LOCAL->encoding_
#define REMOTE_encoding(wid) REMOTE(wid)->encoding_
#define LOCAL_quasi_quotations LOCAL->quasi_quotations_
#define REMOTE_quasi_quotations(wid) REMOTE(wid)->quasi_quotations_
#define LOCAL_default_priority LOCAL->default_priority_
#define REMOTE_default_priority(wid) REMOTE(wid)->default_priority_
#define LOCAL_eot_before_eof LOCAL->eot_before_eof_
#define REMOTE_eot_before_eof(wid) REMOTE(wid)->eot_before_eof_
#define LOCAL_max_depth LOCAL->max_depth_
#define REMOTE_max_depth(wid) REMOTE(wid)->max_depth_
#define LOCAL_max_list LOCAL->max_list_
#define REMOTE_max_list(wid) REMOTE(wid)->max_list_
#define LOCAL_max_write_args LOCAL->max_write_args_
#define REMOTE_max_write_args(wid) REMOTE(wid)->max_write_args_
#define LOCAL_OldASP LOCAL->OldASP_
#define REMOTE_OldASP(wid) REMOTE(wid)->OldASP_
#define LOCAL_OldLCL0 LOCAL->OldLCL0_
#define REMOTE_OldLCL0(wid) REMOTE(wid)->OldLCL0_
#define LOCAL_OldTR LOCAL->OldTR_
#define REMOTE_OldTR(wid) REMOTE(wid)->OldTR_
#define LOCAL_OldGlobalBase LOCAL->OldGlobalBase_
#define REMOTE_OldGlobalBase(wid) REMOTE(wid)->OldGlobalBase_
#define LOCAL_OldH LOCAL->OldH_
#define REMOTE_OldH(wid) REMOTE(wid)->OldH_
#define LOCAL_OldH0 LOCAL->OldH0_
#define REMOTE_OldH0(wid) REMOTE(wid)->OldH0_
#define LOCAL_OldTrailBase LOCAL->OldTrailBase_
#define REMOTE_OldTrailBase(wid) REMOTE(wid)->OldTrailBase_
#define LOCAL_OldTrailTop LOCAL->OldTrailTop_
#define REMOTE_OldTrailTop(wid) REMOTE(wid)->OldTrailTop_
#define LOCAL_OldHeapBase LOCAL->OldHeapBase_
#define REMOTE_OldHeapBase(wid) REMOTE(wid)->OldHeapBase_
#define LOCAL_OldHeapTop LOCAL->OldHeapTop_
#define REMOTE_OldHeapTop(wid) REMOTE(wid)->OldHeapTop_
#define LOCAL_ClDiff LOCAL->ClDiff_
#define REMOTE_ClDiff(wid) REMOTE(wid)->ClDiff_
#define LOCAL_GDiff LOCAL->GDiff_
#define REMOTE_GDiff(wid) REMOTE(wid)->GDiff_
#define LOCAL_HDiff LOCAL->HDiff_
#define REMOTE_HDiff(wid) REMOTE(wid)->HDiff_
#define LOCAL_GDiff0 LOCAL->GDiff0_
#define REMOTE_GDiff0(wid) REMOTE(wid)->GDiff0_
#define LOCAL_GSplit LOCAL->GSplit_
#define REMOTE_GSplit(wid) REMOTE(wid)->GSplit_
#define LOCAL_LDiff LOCAL->LDiff_
#define REMOTE_LDiff(wid) REMOTE(wid)->LDiff_
#define LOCAL_TrDiff LOCAL->TrDiff_
#define REMOTE_TrDiff(wid) REMOTE(wid)->TrDiff_
#define LOCAL_XDiff LOCAL->XDiff_
#define REMOTE_XDiff(wid) REMOTE(wid)->XDiff_
#define LOCAL_DelayDiff LOCAL->DelayDiff_
#define REMOTE_DelayDiff(wid) REMOTE(wid)->DelayDiff_
#define LOCAL_BaseDiff LOCAL->BaseDiff_
#define REMOTE_BaseDiff(wid) REMOTE(wid)->BaseDiff_
#define LOCAL_ReductionsCounter LOCAL->ReductionsCounter_
#define REMOTE_ReductionsCounter(wid) REMOTE(wid)->ReductionsCounter_
#define LOCAL_PredEntriesCounter LOCAL->PredEntriesCounter_
#define REMOTE_PredEntriesCounter(wid) REMOTE(wid)->PredEntriesCounter_
#define LOCAL_RetriesCounter LOCAL->RetriesCounter_
#define REMOTE_RetriesCounter(wid) REMOTE(wid)->RetriesCounter_
#define LOCAL_ReductionsCounterOn LOCAL->ReductionsCounterOn_
#define REMOTE_ReductionsCounterOn(wid) REMOTE(wid)->ReductionsCounterOn_
#define LOCAL_PredEntriesCounterOn LOCAL->PredEntriesCounterOn_
#define REMOTE_PredEntriesCounterOn(wid) REMOTE(wid)->PredEntriesCounterOn_
#define LOCAL_RetriesCounterOn LOCAL->RetriesCounterOn_
#define REMOTE_RetriesCounterOn(wid) REMOTE(wid)->RetriesCounterOn_
#define LOCAL_ConsultSp LOCAL->ConsultSp_
#define REMOTE_ConsultSp(wid) REMOTE(wid)->ConsultSp_
#define LOCAL_ConsultCapacity LOCAL->ConsultCapacity_
#define REMOTE_ConsultCapacity(wid) REMOTE(wid)->ConsultCapacity_
#define LOCAL_ConsultBase LOCAL->ConsultBase_
#define REMOTE_ConsultBase(wid) REMOTE(wid)->ConsultBase_
#define LOCAL_ConsultLow LOCAL->ConsultLow_
#define REMOTE_ConsultLow(wid) REMOTE(wid)->ConsultLow_
#define LOCAL_VarNames LOCAL->VarNames_
#define REMOTE_VarNames(wid) REMOTE(wid)->VarNames_
#define LOCAL_SourceFileName LOCAL->SourceFileName_
#define REMOTE_SourceFileName(wid) REMOTE(wid)->SourceFileName_
#define LOCAL_SourceFileLineno LOCAL->SourceFileLineno_
#define REMOTE_SourceFileLineno(wid) REMOTE(wid)->SourceFileLineno_
#define LOCAL_GlobalArena LOCAL->GlobalArena_
#define REMOTE_GlobalArena(wid) REMOTE(wid)->GlobalArena_
#define LOCAL_GlobalArenaOverflows LOCAL->GlobalArenaOverflows_
#define REMOTE_GlobalArenaOverflows(wid) REMOTE(wid)->GlobalArenaOverflows_
#define LOCAL_ArenaOverflows LOCAL->ArenaOverflows_
#define REMOTE_ArenaOverflows(wid) REMOTE(wid)->ArenaOverflows_
#define LOCAL_DepthArenas LOCAL->DepthArenas_
#define REMOTE_DepthArenas(wid) REMOTE(wid)->DepthArenas_
#define LOCAL_ArithError LOCAL->ArithError_
#define REMOTE_ArithError(wid) REMOTE(wid)->ArithError_
#define LOCAL_LastAssertedPred LOCAL->LastAssertedPred_
#define REMOTE_LastAssertedPred(wid) REMOTE(wid)->LastAssertedPred_
#define LOCAL_TmpPred LOCAL->TmpPred_
#define REMOTE_TmpPred(wid) REMOTE(wid)->TmpPred_
#define LOCAL_ScannerStack LOCAL->ScannerStack_
#define REMOTE_ScannerStack(wid) REMOTE(wid)->ScannerStack_
#define LOCAL_ScannerExtraBlocks LOCAL->ScannerExtraBlocks_
#define REMOTE_ScannerExtraBlocks(wid) REMOTE(wid)->ScannerExtraBlocks_
#define LOCAL_BallTerm LOCAL->BallTerm_
#define REMOTE_BallTerm(wid) REMOTE(wid)->BallTerm_
#define LOCAL_MaxActiveSignals LOCAL->MaxActiveSignals_
#define REMOTE_MaxActiveSignals(wid) REMOTE(wid)->MaxActiveSignals_
#define LOCAL_Signals LOCAL->Signals_
#define REMOTE_Signals(wid) REMOTE(wid)->Signals_
#define LOCAL_IPredArity LOCAL->IPredArity_
#define REMOTE_IPredArity(wid) REMOTE(wid)->IPredArity_
#define LOCAL_ProfEnd LOCAL->ProfEnd_
#define REMOTE_ProfEnd(wid) REMOTE(wid)->ProfEnd_
#define LOCAL_UncaughtThrow LOCAL->UncaughtThrow_
#define REMOTE_UncaughtThrow(wid) REMOTE(wid)->UncaughtThrow_
#define LOCAL_DoingUndefp LOCAL->DoingUndefp_
#define REMOTE_DoingUndefp(wid) REMOTE(wid)->DoingUndefp_
#define LOCAL_StartCharCount LOCAL->StartCharCount_
#define REMOTE_StartCharCount(wid) REMOTE(wid)->StartCharCount_
#define LOCAL_StartLineCount LOCAL->StartLineCount_
#define REMOTE_StartLineCount(wid) REMOTE(wid)->StartLineCount_
#define LOCAL_StartLinePos LOCAL->StartLinePos_
#define REMOTE_StartLinePos(wid) REMOTE(wid)->StartLinePos_
#define LOCAL_ScratchPad LOCAL->ScratchPad_
#define REMOTE_ScratchPad(wid) REMOTE(wid)->ScratchPad_
#ifdef COROUTINING
#define LOCAL_WokenGoals LOCAL->WokenGoals_
#define REMOTE_WokenGoals(wid) REMOTE(wid)->WokenGoals_
#define LOCAL_AttsMutableList LOCAL->AttsMutableList_
#define REMOTE_AttsMutableList(wid) REMOTE(wid)->AttsMutableList_
#endif
#define LOCAL_GcGeneration LOCAL->GcGeneration_
#define REMOTE_GcGeneration(wid) REMOTE(wid)->GcGeneration_
#define LOCAL_GcPhase LOCAL->GcPhase_
#define REMOTE_GcPhase(wid) REMOTE(wid)->GcPhase_
#define LOCAL_GcCurrentPhase LOCAL->GcCurrentPhase_
#define REMOTE_GcCurrentPhase(wid) REMOTE(wid)->GcCurrentPhase_
#define LOCAL_GcCalls LOCAL->GcCalls_
#define REMOTE_GcCalls(wid) REMOTE(wid)->GcCalls_
#define LOCAL_TotGcTime LOCAL->TotGcTime_
#define REMOTE_TotGcTime(wid) REMOTE(wid)->TotGcTime_
#define LOCAL_TotGcRecovered LOCAL->TotGcRecovered_
#define REMOTE_TotGcRecovered(wid) REMOTE(wid)->TotGcRecovered_
#define LOCAL_LastGcTime LOCAL->LastGcTime_
#define REMOTE_LastGcTime(wid) REMOTE(wid)->LastGcTime_
#define LOCAL_LastSSTime LOCAL->LastSSTime_
#define REMOTE_LastSSTime(wid) REMOTE(wid)->LastSSTime_
#define LOCAL_OpenArray LOCAL->OpenArray_
#define REMOTE_OpenArray(wid) REMOTE(wid)->OpenArray_
#define LOCAL_total_marked LOCAL->total_marked_
#define REMOTE_total_marked(wid) REMOTE(wid)->total_marked_
#define LOCAL_total_oldies LOCAL->total_oldies_
#define REMOTE_total_oldies(wid) REMOTE(wid)->total_oldies_
#define LOCAL_current_B LOCAL->current_B_
#define REMOTE_current_B(wid) REMOTE(wid)->current_B_
#define LOCAL_prev_HB LOCAL->prev_HB_
#define REMOTE_prev_HB(wid) REMOTE(wid)->prev_HB_
#define LOCAL_HGEN LOCAL->HGEN_
#define REMOTE_HGEN(wid) REMOTE(wid)->HGEN_
#define LOCAL_iptop LOCAL->iptop_
#define REMOTE_iptop(wid) REMOTE(wid)->iptop_
#if defined(GC_NO_TAGS)
#define LOCAL_bp LOCAL->bp_
#define REMOTE_bp(wid) REMOTE(wid)->bp_
#endif
#define LOCAL_sTR LOCAL->sTR_
#define REMOTE_sTR(wid) REMOTE(wid)->sTR_
#define LOCAL_sTR0 LOCAL->sTR0_
#define REMOTE_sTR0(wid) REMOTE(wid)->sTR0_
#define LOCAL_new_TR LOCAL->new_TR_
#define REMOTE_new_TR(wid) REMOTE(wid)->new_TR_
#define LOCAL_cont_top0 LOCAL->cont_top0_
#define REMOTE_cont_top0(wid) REMOTE(wid)->cont_top0_
#define LOCAL_cont_top LOCAL->cont_top_
#define REMOTE_cont_top(wid) REMOTE(wid)->cont_top_
#define LOCAL_discard_trail_entries LOCAL->discard_trail_entries_
#define REMOTE_discard_trail_entries(wid) REMOTE(wid)->discard_trail_entries_
#define LOCAL_gc_ma_hash_table LOCAL->gc_ma_hash_table_
#define REMOTE_gc_ma_hash_table(wid) REMOTE(wid)->gc_ma_hash_table_
#define LOCAL_gc_ma_h_top LOCAL->gc_ma_h_top_
#define REMOTE_gc_ma_h_top(wid) REMOTE(wid)->gc_ma_h_top_
#define LOCAL_gc_ma_h_list LOCAL->gc_ma_h_list_
#define REMOTE_gc_ma_h_list(wid) REMOTE(wid)->gc_ma_h_list_
#define LOCAL_gc_timestamp LOCAL->gc_timestamp_
#define REMOTE_gc_timestamp(wid) REMOTE(wid)->gc_timestamp_
#define LOCAL_db_vec LOCAL->db_vec_
#define REMOTE_db_vec(wid) REMOTE(wid)->db_vec_
#define LOCAL_db_vec0 LOCAL->db_vec0_
#define REMOTE_db_vec0(wid) REMOTE(wid)->db_vec0_
#define LOCAL_db_root LOCAL->db_root_
#define REMOTE_db_root(wid) REMOTE(wid)->db_root_
#define LOCAL_db_nil LOCAL->db_nil_
#define REMOTE_db_nil(wid) REMOTE(wid)->db_nil_
#define LOCAL_gc_restore LOCAL->gc_restore_
#define REMOTE_gc_restore(wid) REMOTE(wid)->gc_restore_
#define LOCAL_extra_gc_cells LOCAL->extra_gc_cells_
#define REMOTE_extra_gc_cells(wid) REMOTE(wid)->extra_gc_cells_
#define LOCAL_extra_gc_cells_base LOCAL->extra_gc_cells_base_
#define REMOTE_extra_gc_cells_base(wid) REMOTE(wid)->extra_gc_cells_base_
#define LOCAL_extra_gc_cells_top LOCAL->extra_gc_cells_top_
#define REMOTE_extra_gc_cells_top(wid) REMOTE(wid)->extra_gc_cells_top_
#define LOCAL_extra_gc_cells_size LOCAL->extra_gc_cells_size_
#define REMOTE_extra_gc_cells_size(wid) REMOTE(wid)->extra_gc_cells_size_
#define LOCAL_DynamicArrays LOCAL->DynamicArrays_
#define REMOTE_DynamicArrays(wid) REMOTE(wid)->DynamicArrays_
#define LOCAL_StaticArrays LOCAL->StaticArrays_
#define REMOTE_StaticArrays(wid) REMOTE(wid)->StaticArrays_
#define LOCAL_GlobalVariables LOCAL->GlobalVariables_
#define REMOTE_GlobalVariables(wid) REMOTE(wid)->GlobalVariables_
#define LOCAL_AllowRestart LOCAL->AllowRestart_
#define REMOTE_AllowRestart(wid) REMOTE(wid)->AllowRestart_
#define LOCAL_CMemFirstBlock LOCAL->CMemFirstBlock_
#define REMOTE_CMemFirstBlock(wid) REMOTE(wid)->CMemFirstBlock_
#define LOCAL_CMemFirstBlockSz LOCAL->CMemFirstBlockSz_
#define REMOTE_CMemFirstBlockSz(wid) REMOTE(wid)->CMemFirstBlockSz_
#define LOCAL_nperm LOCAL->nperm_
#define REMOTE_nperm(wid) REMOTE(wid)->nperm_
#define LOCAL_LabelFirstArray LOCAL->LabelFirstArray_
#define REMOTE_LabelFirstArray(wid) REMOTE(wid)->LabelFirstArray_
#define LOCAL_LabelFirstArraySz LOCAL->LabelFirstArraySz_
#define REMOTE_LabelFirstArraySz(wid) REMOTE(wid)->LabelFirstArraySz_
#ifdef THREADS
#define LOCAL_ThreadHandle LOCAL->ThreadHandle_
#define REMOTE_ThreadHandle(wid) REMOTE(wid)->ThreadHandle_
#endif /* THREADS */
#if defined(YAPOR) || defined(TABLING)
#define LOCAL_optyap_data LOCAL->optyap_data_
#define REMOTE_optyap_data(wid) REMOTE(wid)->optyap_data_
#define LOCAL_TabMode LOCAL->TabMode_
#define REMOTE_TabMode(wid) REMOTE(wid)->TabMode_
#endif /* YAPOR || TABLING */
#define LOCAL_InterruptsDisabled LOCAL->InterruptsDisabled_
#define REMOTE_InterruptsDisabled(wid) REMOTE(wid)->InterruptsDisabled_
#define LOCAL_execution LOCAL->execution_
#define REMOTE_execution(wid) REMOTE(wid)->execution_
#if LOW_LEVEL_TRACER
#define LOCAL_total_choicepoints LOCAL->total_choicepoints_
#define REMOTE_total_choicepoints(wid) REMOTE(wid)->total_choicepoints_
#endif
#define LOCAL_consult_level LOCAL->consult_level_
#define REMOTE_consult_level(wid) REMOTE(wid)->consult_level_
#define LOCAL_LocalBase LOCAL->LocalBase_
#define REMOTE_LocalBase(wid) REMOTE(wid)->LocalBase_
#define LOCAL_GlobalBase LOCAL->GlobalBase_
#define REMOTE_GlobalBase(wid) REMOTE(wid)->GlobalBase_
#define LOCAL_TrailBase LOCAL->TrailBase_
#define REMOTE_TrailBase(wid) REMOTE(wid)->TrailBase_
#define LOCAL_TrailTop LOCAL->TrailTop_
#define REMOTE_TrailTop(wid) REMOTE(wid)->TrailTop_
#define LOCAL_ErrorMessage LOCAL->ErrorMessage_
#define REMOTE_ErrorMessage(wid) REMOTE(wid)->ErrorMessage_
#define LOCAL_Error_Term LOCAL->Error_Term_
#define REMOTE_Error_Term(wid) REMOTE(wid)->Error_Term_
#define LOCAL_Error_TYPE LOCAL->Error_TYPE_
#define REMOTE_Error_TYPE(wid) REMOTE(wid)->Error_TYPE_
#define LOCAL_Error_File LOCAL->Error_File_
#define REMOTE_Error_File(wid) REMOTE(wid)->Error_File_
#define LOCAL_Error_Function LOCAL->Error_Function_
#define REMOTE_Error_Function(wid) REMOTE(wid)->Error_Function_
#define LOCAL_Error_Lineno LOCAL->Error_Lineno_
#define REMOTE_Error_Lineno(wid) REMOTE(wid)->Error_Lineno_
#define LOCAL_Error_Size LOCAL->Error_Size_
#define REMOTE_Error_Size(wid) REMOTE(wid)->Error_Size_
#define LOCAL_ErrorSay LOCAL->ErrorSay_
#define REMOTE_ErrorSay(wid) REMOTE(wid)->ErrorSay_
#define LOCAL_IOBotch LOCAL->IOBotch_
#define REMOTE_IOBotch(wid) REMOTE(wid)->IOBotch_
#define LOCAL_tokptr LOCAL->tokptr_
#define REMOTE_tokptr(wid) REMOTE(wid)->tokptr_
#define LOCAL_toktide LOCAL->toktide_
#define REMOTE_toktide(wid) REMOTE(wid)->toktide_
#define LOCAL_VarTable LOCAL->VarTable_
#define REMOTE_VarTable(wid) REMOTE(wid)->VarTable_
#define LOCAL_AnonVarTable LOCAL->AnonVarTable_
#define REMOTE_AnonVarTable(wid) REMOTE(wid)->AnonVarTable_
#define LOCAL_Comments LOCAL->Comments_
#define REMOTE_Comments(wid) REMOTE(wid)->Comments_
#define LOCAL_CommentsTail LOCAL->CommentsTail_
#define REMOTE_CommentsTail(wid) REMOTE(wid)->CommentsTail_
#define LOCAL_CommentsNextChar LOCAL->CommentsNextChar_
#define REMOTE_CommentsNextChar(wid) REMOTE(wid)->CommentsNextChar_
#define LOCAL_CommentsBuff LOCAL->CommentsBuff_
#define REMOTE_CommentsBuff(wid) REMOTE(wid)->CommentsBuff_
#define LOCAL_CommentsBuffPos LOCAL->CommentsBuffPos_
#define REMOTE_CommentsBuffPos(wid) REMOTE(wid)->CommentsBuffPos_
#define LOCAL_CommentsBuffLim LOCAL->CommentsBuffLim_
#define REMOTE_CommentsBuffLim(wid) REMOTE(wid)->CommentsBuffLim_
#define LOCAL_RestartEnv LOCAL->RestartEnv_
#define REMOTE_RestartEnv(wid) REMOTE(wid)->RestartEnv_
#define LOCAL_FileNameBuf LOCAL->FileNameBuf_
#define REMOTE_FileNameBuf(wid) REMOTE(wid)->FileNameBuf_
#define LOCAL_FileNameBuf2 LOCAL->FileNameBuf2_
#define REMOTE_FileNameBuf2(wid) REMOTE(wid)->FileNameBuf2_
#define LOCAL_BreakLevel LOCAL->BreakLevel_
#define REMOTE_BreakLevel(wid) REMOTE(wid)->BreakLevel_
#define LOCAL_PrologMode LOCAL->PrologMode_
#define REMOTE_PrologMode(wid) REMOTE(wid)->PrologMode_
#define LOCAL_CritLocks LOCAL->CritLocks_
#define REMOTE_CritLocks(wid) REMOTE(wid)->CritLocks_
#define LOCAL_Flags LOCAL->Flags_
#define REMOTE_Flags(wid) REMOTE(wid)->Flags_
#define LOCAL_flagCount LOCAL->flagCount_
#define REMOTE_flagCount(wid) REMOTE(wid)->flagCount_
#ifdef ANALYST
#define LOCAL_opcount LOCAL->opcount_
#define REMOTE_opcount(wid) REMOTE(wid)->opcount_
#define LOCAL_2opcount LOCAL->2opcount_
#define REMOTE_2opcount(wid) REMOTE(wid)->2opcount_
#endif /* ANALYST */
#define LOCAL_s_dbg LOCAL->s_dbg_
#define REMOTE_s_dbg(wid) REMOTE(wid)->s_dbg_
#define LOCAL_matherror LOCAL->matherror_
#define REMOTE_matherror(wid) REMOTE(wid)->matherror_
#define LOCAL_mathtt LOCAL->mathtt_
#define REMOTE_mathtt(wid) REMOTE(wid)->mathtt_
#define LOCAL_mathstring LOCAL->mathstring_
#define REMOTE_mathstring(wid) REMOTE(wid)->mathstring_
#define LOCAL_CurrentError LOCAL->CurrentError_
#define REMOTE_CurrentError(wid) REMOTE(wid)->CurrentError_
#define LOCAL_heap_overflows LOCAL->heap_overflows_
#define REMOTE_heap_overflows(wid) REMOTE(wid)->heap_overflows_
#define LOCAL_total_heap_overflow_time LOCAL->total_heap_overflow_time_
#define REMOTE_total_heap_overflow_time(wid) REMOTE(wid)->total_heap_overflow_time_
#define LOCAL_stack_overflows LOCAL->stack_overflows_
#define REMOTE_stack_overflows(wid) REMOTE(wid)->stack_overflows_
#define LOCAL_total_stack_overflow_time LOCAL->total_stack_overflow_time_
#define REMOTE_total_stack_overflow_time(wid) REMOTE(wid)->total_stack_overflow_time_
#define LOCAL_delay_overflows LOCAL->delay_overflows_
#define REMOTE_delay_overflows(wid) REMOTE(wid)->delay_overflows_
#define LOCAL_total_delay_overflow_time LOCAL->total_delay_overflow_time_
#define REMOTE_total_delay_overflow_time(wid) REMOTE(wid)->total_delay_overflow_time_
#define LOCAL_trail_overflows LOCAL->trail_overflows_
#define REMOTE_trail_overflows(wid) REMOTE(wid)->trail_overflows_
#define LOCAL_total_trail_overflow_time LOCAL->total_trail_overflow_time_
#define REMOTE_total_trail_overflow_time(wid) REMOTE(wid)->total_trail_overflow_time_
#define LOCAL_atom_table_overflows LOCAL->atom_table_overflows_
#define REMOTE_atom_table_overflows(wid) REMOTE(wid)->atom_table_overflows_
#define LOCAL_total_atom_table_overflow_time LOCAL->total_atom_table_overflow_time_
#define REMOTE_total_atom_table_overflow_time(wid) REMOTE(wid)->total_atom_table_overflow_time_
#ifdef LOAD_DYLD
#define LOCAL_dl_errno LOCAL->dl_errno_
#define REMOTE_dl_errno(wid) REMOTE(wid)->dl_errno_
#endif
#ifdef LOW_LEVEL_TRACER
#define LOCAL_do_trace_primitives LOCAL->do_trace_primitives_
#define REMOTE_do_trace_primitives(wid) REMOTE(wid)->do_trace_primitives_
#endif
#define LOCAL_ExportAtomHashChain LOCAL->ExportAtomHashChain_
#define REMOTE_ExportAtomHashChain(wid) REMOTE(wid)->ExportAtomHashChain_
#define LOCAL_ExportAtomHashTableSize LOCAL->ExportAtomHashTableSize_
#define REMOTE_ExportAtomHashTableSize(wid) REMOTE(wid)->ExportAtomHashTableSize_
#define LOCAL_ExportAtomHashTableNum LOCAL->ExportAtomHashTableNum_
#define REMOTE_ExportAtomHashTableNum(wid) REMOTE(wid)->ExportAtomHashTableNum_
#define LOCAL_ExportFunctorHashChain LOCAL->ExportFunctorHashChain_
#define REMOTE_ExportFunctorHashChain(wid) REMOTE(wid)->ExportFunctorHashChain_
#define LOCAL_ExportFunctorHashTableSize LOCAL->ExportFunctorHashTableSize_
#define REMOTE_ExportFunctorHashTableSize(wid) REMOTE(wid)->ExportFunctorHashTableSize_
#define LOCAL_ExportFunctorHashTableNum LOCAL->ExportFunctorHashTableNum_
#define REMOTE_ExportFunctorHashTableNum(wid) REMOTE(wid)->ExportFunctorHashTableNum_
#define LOCAL_ExportPredEntryHashChain LOCAL->ExportPredEntryHashChain_
#define REMOTE_ExportPredEntryHashChain(wid) REMOTE(wid)->ExportPredEntryHashChain_
#define LOCAL_ExportPredEntryHashTableSize LOCAL->ExportPredEntryHashTableSize_
#define REMOTE_ExportPredEntryHashTableSize(wid) REMOTE(wid)->ExportPredEntryHashTableSize_
#define LOCAL_ExportPredEntryHashTableNum LOCAL->ExportPredEntryHashTableNum_
#define REMOTE_ExportPredEntryHashTableNum(wid) REMOTE(wid)->ExportPredEntryHashTableNum_
#define LOCAL_ExportDBRefHashChain LOCAL->ExportDBRefHashChain_
#define REMOTE_ExportDBRefHashChain(wid) REMOTE(wid)->ExportDBRefHashChain_
#define LOCAL_ExportDBRefHashTableSize LOCAL->ExportDBRefHashTableSize_
#define REMOTE_ExportDBRefHashTableSize(wid) REMOTE(wid)->ExportDBRefHashTableSize_
#define LOCAL_ExportDBRefHashTableNum LOCAL->ExportDBRefHashTableNum_
#define REMOTE_ExportDBRefHashTableNum(wid) REMOTE(wid)->ExportDBRefHashTableNum_
#define LOCAL_ImportAtomHashChain LOCAL->ImportAtomHashChain_
#define REMOTE_ImportAtomHashChain(wid) REMOTE(wid)->ImportAtomHashChain_
#define LOCAL_ImportAtomHashTableSize LOCAL->ImportAtomHashTableSize_
#define REMOTE_ImportAtomHashTableSize(wid) REMOTE(wid)->ImportAtomHashTableSize_
#define LOCAL_ImportAtomHashTableNum LOCAL->ImportAtomHashTableNum_
#define REMOTE_ImportAtomHashTableNum(wid) REMOTE(wid)->ImportAtomHashTableNum_
#define LOCAL_ImportFunctorHashChain LOCAL->ImportFunctorHashChain_
#define REMOTE_ImportFunctorHashChain(wid) REMOTE(wid)->ImportFunctorHashChain_
#define LOCAL_ImportFunctorHashTableSize LOCAL->ImportFunctorHashTableSize_
#define REMOTE_ImportFunctorHashTableSize(wid) REMOTE(wid)->ImportFunctorHashTableSize_
#define LOCAL_ImportFunctorHashTableNum LOCAL->ImportFunctorHashTableNum_
#define REMOTE_ImportFunctorHashTableNum(wid) REMOTE(wid)->ImportFunctorHashTableNum_
#define LOCAL_ImportOPCODEHashChain LOCAL->ImportOPCODEHashChain_
#define REMOTE_ImportOPCODEHashChain(wid) REMOTE(wid)->ImportOPCODEHashChain_
#define LOCAL_ImportOPCODEHashTableSize LOCAL->ImportOPCODEHashTableSize_
#define REMOTE_ImportOPCODEHashTableSize(wid) REMOTE(wid)->ImportOPCODEHashTableSize_
#define LOCAL_ImportPredEntryHashChain LOCAL->ImportPredEntryHashChain_
#define REMOTE_ImportPredEntryHashChain(wid) REMOTE(wid)->ImportPredEntryHashChain_
#define LOCAL_ImportPredEntryHashTableSize LOCAL->ImportPredEntryHashTableSize_
#define REMOTE_ImportPredEntryHashTableSize(wid) REMOTE(wid)->ImportPredEntryHashTableSize_
#define LOCAL_ImportPredEntryHashTableNum LOCAL->ImportPredEntryHashTableNum_
#define REMOTE_ImportPredEntryHashTableNum(wid) REMOTE(wid)->ImportPredEntryHashTableNum_
#define LOCAL_ImportDBRefHashChain LOCAL->ImportDBRefHashChain_
#define REMOTE_ImportDBRefHashChain(wid) REMOTE(wid)->ImportDBRefHashChain_
#define LOCAL_ImportDBRefHashTableSize LOCAL->ImportDBRefHashTableSize_
#define REMOTE_ImportDBRefHashTableSize(wid) REMOTE(wid)->ImportDBRefHashTableSize_
#define LOCAL_ImportDBRefHashTableNum LOCAL->ImportDBRefHashTableNum_
#define REMOTE_ImportDBRefHashTableNum(wid) REMOTE(wid)->ImportDBRefHashTableNum_
#define LOCAL_ImportFAILCODE LOCAL->ImportFAILCODE_
#define REMOTE_ImportFAILCODE(wid) REMOTE(wid)->ImportFAILCODE_
#if __ANDROID__
#define LOCAL_assetManager LOCAL->assetManager_
#define REMOTE_assetManager(wid) REMOTE(wid)->assetManager_
#define LOCAL_InAssetDir LOCAL->InAssetDir_
#define REMOTE_InAssetDir(wid) REMOTE(wid)->InAssetDir_
#endif
#define LOCAL_ibnds LOCAL->ibnds_
#define REMOTE_ibnds(wid) REMOTE(wid)->ibnds_
#define LOCAL_exo_it LOCAL->exo_it_
#define REMOTE_exo_it(wid) REMOTE(wid)->exo_it_
#define LOCAL_exo_base LOCAL->exo_base_
#define REMOTE_exo_base(wid) REMOTE(wid)->exo_base_
#define LOCAL_exo_arity LOCAL->exo_arity_
#define REMOTE_exo_arity(wid) REMOTE(wid)->exo_arity_
#define LOCAL_exo_arg LOCAL->exo_arg_
#define REMOTE_exo_arg(wid) REMOTE(wid)->exo_arg_
#define LOCAL_search_atoms LOCAL->search_atoms_
#define REMOTE_search_atoms(wid) REMOTE(wid)->search_atoms_
#define LOCAL_CurSlot LOCAL->CurSlot_
#define REMOTE_CurSlot(wid) REMOTE(wid)->CurSlot_
#define LOCAL_NSlots LOCAL->NSlots_
#define REMOTE_NSlots(wid) REMOTE(wid)->NSlots_
#define LOCAL_SlotBase LOCAL->SlotBase_
#define REMOTE_SlotBase(wid) REMOTE(wid)->SlotBase_
#define LOCAL_Mutexes LOCAL->Mutexes_
#define REMOTE_Mutexes(wid) REMOTE(wid)->Mutexes_
#define LOCAL_SourceModule LOCAL->SourceModule_
#define REMOTE_SourceModule(wid) REMOTE(wid)->SourceModule_
#define LOCAL_Including LOCAL->Including_
#define REMOTE_Including(wid) REMOTE(wid)->Including_
#define LOCAL_MAX_SIZE LOCAL->MAX_SIZE_
#define REMOTE_MAX_SIZE(wid) REMOTE(wid)->MAX_SIZE_

View File

@ -20,6 +20,7 @@
AtomArrayOverflow = Yap_LookupAtom("array_overflow"); AtomArrayOverflow = Yap_LookupAtom("array_overflow");
AtomArrayType = Yap_LookupAtom("array_type"); AtomArrayType = Yap_LookupAtom("array_type");
AtomArrow = Yap_LookupAtom("->"); AtomArrow = Yap_LookupAtom("->");
AtomAttributedModule = Yap_LookupAtom("attributes_module");
AtomDoubleArrow = Yap_LookupAtom("-->"); AtomDoubleArrow = Yap_LookupAtom("-->");
AtomAssert = Yap_LookupAtom(":-"); AtomAssert = Yap_LookupAtom(":-");
AtomEmptyBrackets = Yap_LookupAtom("()"); AtomEmptyBrackets = Yap_LookupAtom("()");
@ -509,6 +510,7 @@
FunctorPlus = Yap_MkFunctor(AtomPlus,2); FunctorPlus = Yap_MkFunctor(AtomPlus,2);
FunctorPortray = Yap_MkFunctor(AtomPortray,1); FunctorPortray = Yap_MkFunctor(AtomPortray,1);
FunctorPrintMessage = Yap_MkFunctor(AtomPrintMessage,2); FunctorPrintMessage = Yap_MkFunctor(AtomPrintMessage,2);
FunctorProcedure = Yap_MkFunctor(AtomProcedure,5);
FunctorPrologConstraint = Yap_MkFunctor(AtomProlog,2); FunctorPrologConstraint = Yap_MkFunctor(AtomProlog,2);
FunctorQuery = Yap_MkFunctor(AtomQuery,1); FunctorQuery = Yap_MkFunctor(AtomQuery,1);
FunctorRecordedWithKey = Yap_MkFunctor(AtomRecordedWithKey,6); FunctorRecordedWithKey = Yap_MkFunctor(AtomRecordedWithKey,6);

View File

@ -1,301 +0,0 @@
/* This file, ihstruct.h, was generated automatically by "yap -L misc/buildheap"
please do not update, update misc/HEAPFIELDS instead */
#if USE_DL_MALLOC
#if defined(YAPOR) || defined(THREADS)
INIT_LOCK(DLMallocLock);
#endif
#endif
#if USE_DL_MALLOC || (USE_SYSTEM_MALLOC && HAVE_MALLINFO)
#ifndef HeapUsed
#define HeapUsed Yap_givemallinfo()
#endif
#else
#endif
#if defined(YAPOR) || defined(THREADS)
INIT_LOCK(FreeBlocksLock);
INIT_LOCK(HeapUsedLock);
INIT_LOCK(HeapTopLock);
HeapTopOwner = -1;
#endif
MaxStack = 0;
MaxTrail = 0;
#if USE_THREADED_CODE
#endif
EXECUTE_CPRED_OP_CODE = Yap_opcode(_execute_cpred);
EXPAND_OP_CODE = Yap_opcode(_expand_index);
FAIL_OPCODE = Yap_opcode(_op_fail);
INDEX_OPCODE = Yap_opcode(_index_pred);
LOCKPRED_OPCODE = Yap_opcode(_lock_pred);
ORLAST_OPCODE = Yap_opcode(_or_last);
UNDEF_OPCODE = Yap_opcode(_undef_p);
RETRY_USERC_OPCODE = Yap_opcode(_retry_userc);
EXECUTE_CPRED_OPCODE = Yap_opcode(_execute_cpred);
InitInvisibleAtoms();
InitWideAtoms();
InitAtoms();
#include "iatoms.h"
#ifdef EUROTRA
TermDollarU = MkAtomTerm(AtomDollarU);
#endif
USER_MODULE = MkAtomTerm(AtomUser);
IDB_MODULE = MkAtomTerm(AtomIDB);
ATTRIBUTES_MODULE = MkAtomTerm(AtomAttributes);
CHARSIO_MODULE = MkAtomTerm(AtomCharsio);
CHTYPE_MODULE = MkAtomTerm(AtomChType);
TERMS_MODULE = MkAtomTerm(AtomTerms);
SYSTEM_MODULE = MkAtomTerm(AtomSystem);
READUTIL_MODULE = MkAtomTerm(AtomReadutil);
HACKS_MODULE = MkAtomTerm(AtomYapHacks);
ARG_MODULE = MkAtomTerm(AtomArg);
GLOBALS_MODULE = MkAtomTerm(AtomNb);
SWI_MODULE = MkAtomTerm(AtomSwi);
DBLOAD_MODULE = MkAtomTerm(AtomDBLoad);
RANGE_MODULE = MkAtomTerm(AtomRange);
ERROR_MODULE = MkAtomTerm(AtomError);
CurrentModules = NULL;
Yap_InitModules();
HIDDEN_PREDICATES = NULL;
Yap_InitPlIO();
GLOBAL_Flags = 0;
Yap_InitFlags(true);
Yap_ExecutionMode = INTERPRETED;
InitPredHash();
#if defined(YAPOR) || defined(THREADS)
#endif
PredsInHashTable = 0;
CreepCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomCreep,1),PROLOG_MODULE));
UndefCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomUndefp,2),PROLOG_MODULE));
SpyCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomSpy,1),PROLOG_MODULE));
PredFail = RepPredProp(PredPropByAtom(AtomFail,PROLOG_MODULE));
PredTrue = RepPredProp(PredPropByAtom(AtomTrue,PROLOG_MODULE));
#ifdef COROUTINING
WakeUpCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomWakeUpGoal,2),PROLOG_MODULE));
#endif
PredGoalExpansion = RepPredProp(PredPropByFunc(FunctorGoalExpansion,USER_MODULE));
PredMetaCall = RepPredProp(PredPropByFunc(FunctorMetaCall,PROLOG_MODULE));
PredTraceMetaCall = RepPredProp(PredPropByFunc(FunctorTraceMetaCall,PROLOG_MODULE));
PredDollarCatch = RepPredProp(PredPropByFunc(FunctorCatch,PROLOG_MODULE));
PredRecordedWithKey = RepPredProp(PredPropByFunc(FunctorRecordedWithKey,PROLOG_MODULE));
PredLogUpdClause = RepPredProp(PredPropByFunc(FunctorDoLogUpdClause,PROLOG_MODULE));
PredLogUpdClauseErase = RepPredProp(PredPropByFunc(FunctorDoLogUpdClauseErase,PROLOG_MODULE));
PredLogUpdClause0 = RepPredProp(PredPropByFunc(FunctorDoLogUpdClause,PROLOG_MODULE));
PredStaticClause = RepPredProp(PredPropByFunc(FunctorDoStaticClause,PROLOG_MODULE));
PredThrow = RepPredProp(PredPropByFunc(FunctorThrow,PROLOG_MODULE));
PredHandleThrow = RepPredProp(PredPropByFunc(FunctorHandleThrow,PROLOG_MODULE));
PredIs = RepPredProp(PredPropByFunc(FunctorIs,PROLOG_MODULE));
PredSafeCallCleanup = RepPredProp(PredPropByFunc(FunctorSafeCallCleanup,PROLOG_MODULE));
PredRestoreRegs = RepPredProp(PredPropByFunc(FunctorRestoreRegs,PROLOG_MODULE));
PredCommentHook = RepPredProp(PredPropByFunc(FunctorCommentHook,PROLOG_MODULE));
#ifdef YAPOR
PredGetwork = RepPredProp(PredPropByAtom(AtomGetwork,PROLOG_MODULE));
PredGetworkSeq = RepPredProp(PredPropByAtom(AtomGetworkSeq,PROLOG_MODULE));
#endif /* YAPOR */
#ifdef LOW_LEVEL_TRACER
Yap_do_low_level_trace = FALSE;
#if defined(YAPOR) || defined(THREADS)
INIT_LOCK(Yap_low_level_trace_lock);
#endif
#endif
Yap_ClauseSpace = 0;
Yap_IndexSpace_Tree = 0;
Yap_IndexSpace_EXT = 0;
Yap_IndexSpace_SW = 0;
Yap_LUClauseSpace = 0;
Yap_LUIndexSpace_Tree = 0;
Yap_LUIndexSpace_CP = 0;
Yap_LUIndexSpace_EXT = 0;
Yap_LUIndexSpace_SW = 0;
DUMMYCODE->opc = Yap_opcode(_op_fail);
FAILCODE->opc = Yap_opcode(_op_fail);
NOCODE->opc = Yap_opcode(_Nstop);
InitEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail);
InitEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail);
InitOtaplInst(RTRYCODE,_retry_and_mark,PredFail);
#ifdef BEAM
BEAM_RETRY_CODE->opc = Yap_opcode(_beam_retry_code);
#endif /* BEAM */
#ifdef YAPOR
InitOtaplInst(GETWORK,_getwork,PredGetwork);
InitOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq);
GETWORK_FIRST_TIME->opc = Yap_opcode(_getwork_first_time);
#endif /* YAPOR */
#ifdef TABLING
InitOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail);
InitOtaplInst(TRY_ANSWER,_table_try_answer,PredFail);
InitOtaplInst(ANSWER_RESOLUTION,_table_answer_resolution,PredFail);
InitOtaplInst(COMPLETION,_table_completion,PredFail);
#ifdef THREADS_CONSUMER_SHARING
InitOtaplInst(ANSWER_RESOLUTION_COMPLETION,_table_answer_resolution_completion,PredFail);
#endif /* THREADS_CONSUMER_SHARING */
#endif /* TABLING */
P_before_spy = NULL;
RETRY_C_RECORDEDP_CODE = NULL;
RETRY_C_RECORDED_K_CODE = NULL;
PROFILING = FALSE;
CALL_COUNTING = FALSE;
optimizer_on = TRUE;
compile_mode = 0;
profiling = FALSE;
call_counting = FALSE;
compile_arrays = FALSE;
#if defined(YAPOR) || defined(THREADS)
INIT_LOCK(DBTermsListLock);
#endif
DBTermsList = NULL;
ExpandClausesFirst = NULL;
ExpandClausesLast = NULL;
Yap_ExpandClauses = 0;
#if defined(YAPOR) || defined(THREADS)
INIT_LOCK(ExpandClausesListLock);
INIT_LOCK(OpListLock);
#endif
#ifdef DEBUG
Yap_NewCps = 0L;
Yap_LiveCps = 0L;
Yap_DirtyCps = 0L;
Yap_FreedCps = 0L;
#endif
Yap_expand_clauses_sz = 0L;
UdiControlBlocks = NULL;
STATIC_PREDICATES_MARKED = FALSE;
INT_KEYS = NULL;
INT_LU_KEYS = NULL;
INT_BB_KEYS = NULL;
INT_KEYS_SIZE = INT_KEYS_DEFAULT_SIZE;
INT_KEYS_TIMESTAMP = 0L;
INT_BB_KEYS_SIZE = INT_KEYS_DEFAULT_SIZE;
UPDATE_MODE = UPDATE_MODE_LOGICAL;
InitDBErasedMarker();
InitLogDBErasedMarker();
DeadStaticClauses = NULL;
DeadMegaClauses = NULL;
DeadStaticIndices = NULL;
DBErasedList = NULL;
DBErasedIList = NULL;
#if defined(YAPOR) || defined(THREADS)
INIT_LOCK(DeadStaticClausesLock);
INIT_LOCK(DeadMegaClausesLock);
INIT_LOCK(DeadStaticIndicesLock);
#endif
#ifdef COROUTINING
NUM_OF_ATTS = 1;
#endif
OpList = NULL;
ForeignCodeLoaded = NULL;
ForeignCodeBase = NULL;
ForeignCodeTop = NULL;
ForeignCodeMax = NULL;
Yap_Records = NULL;
InitSWIAtoms();
InitEmptyWakeups();
MaxEmptyWakeups = 0;
BlobTypes = NULL;
Blobs = NULL;
NOfBlobs = 0;
NOfBlobsMax = 256;
#if defined(YAPOR) || defined(THREADS)
INIT_LOCK(Blobs_Lock);
#endif

View File

@ -1,277 +0,0 @@
/* This file, ilocals.h, was generated automatically by "yap -L misc/buildlocalglobal"
please do not update, update misc/LOCALS instead */
static void InitWorker(int wid) {
REMOTE_FileAliases(wid) = Yap_InitStandardAliases();
REMOTE_c_input_stream(wid) = 0;
REMOTE_c_output_stream(wid) = 1;
REMOTE_c_error_stream(wid) = 2;
REMOTE_sockets_io(wid) = false;
REMOTE_within_print_message(wid) = false;
REMOTE_newline(wid) = true;
REMOTE_AtPrompt(wid) = AtomNil;
REMOTE_encoding(wid) = Yap_DefaultEncoding();
REMOTE_quasi_quotations(wid) = false;
REMOTE_default_priority(wid) = 1200;
REMOTE_eot_before_eof(wid) = false;
REMOTE_max_depth(wid) = 0;
REMOTE_max_list(wid) = 0;
REMOTE_max_write_args(wid) = 0;
REMOTE_OldASP(wid) = NULL;
REMOTE_OldLCL0(wid) = NULL;
REMOTE_OldTR(wid) = NULL;
REMOTE_OldGlobalBase(wid) = NULL;
REMOTE_OldH(wid) = NULL;
REMOTE_OldH0(wid) = NULL;
REMOTE_OldTrailBase(wid) = NULL;
REMOTE_OldTrailTop(wid) = NULL;
REMOTE_OldHeapBase(wid) = NULL;
REMOTE_OldHeapTop(wid) = NULL;
REMOTE_ClDiff(wid) = 0L;
REMOTE_GDiff(wid) = 0L;
REMOTE_HDiff(wid) = 0L;
REMOTE_GDiff0(wid) = 0L;
REMOTE_GSplit(wid) = NULL;
REMOTE_LDiff(wid) = 0L;
REMOTE_TrDiff(wid) = 0L;
REMOTE_XDiff(wid) = 0L;
REMOTE_DelayDiff(wid) = 0L;
REMOTE_BaseDiff(wid) = 0L;
REMOTE_ReductionsCounter(wid) = 0L;
REMOTE_PredEntriesCounter(wid) = 0L;
REMOTE_RetriesCounter(wid) = 0L;
REMOTE_ReductionsCounterOn(wid) = 0L;
REMOTE_PredEntriesCounterOn(wid) = 0L;
REMOTE_RetriesCounterOn(wid) = 0L;
REMOTE_ConsultSp(wid) = NULL;
REMOTE_ConsultBase(wid) = NULL;
REMOTE_ConsultLow(wid) = NULL;
REMOTE_VarNames(wid) = ((Term)0);
REMOTE_SourceFileName(wid) = NULL;
REMOTE_SourceFileLineno(wid) = 0;
REMOTE_GlobalArena(wid) = 0L;
REMOTE_GlobalArenaOverflows(wid) = 0L;
REMOTE_ArenaOverflows(wid) = 0L;
REMOTE_DepthArenas(wid) = 0;
REMOTE_ArithError(wid) = FALSE;
REMOTE_LastAssertedPred(wid) = NULL;
REMOTE_TmpPred(wid) = NULL;
REMOTE_ScannerStack(wid) = NULL;
REMOTE_ScannerExtraBlocks(wid) = NULL;
REMOTE_BallTerm(wid) = NULL;
REMOTE_MaxActiveSignals(wid) = 64L;
REMOTE_Signals(wid) = 0L;
REMOTE_IPredArity(wid) = 0L;
REMOTE_ProfEnd(wid) = NULL;
REMOTE_UncaughtThrow(wid) = FALSE;
REMOTE_DoingUndefp(wid) = FALSE;
REMOTE_StartCharCount(wid) = 0L;
REMOTE_StartLineCount(wid) = 0L;
REMOTE_StartLinePos(wid) = 0L;
InitScratchPad(wid);
#ifdef COROUTINING
REMOTE_WokenGoals(wid) = 0L;
REMOTE_AttsMutableList(wid) = 0L;
#endif
REMOTE_GcGeneration(wid) = 0L;
REMOTE_GcPhase(wid) = 0L;
REMOTE_GcCurrentPhase(wid) = 0L;
REMOTE_GcCalls(wid) = 0L;
REMOTE_TotGcTime(wid) = 0L;
REMOTE_TotGcRecovered(wid) = 0L;
REMOTE_LastGcTime(wid) = 0L;
REMOTE_LastSSTime(wid) = 0L;
REMOTE_OpenArray(wid) = NULL;
REMOTE_total_marked(wid) = 0L;
REMOTE_total_oldies(wid) = 0L;
REMOTE_current_B(wid) = NULL;
REMOTE_prev_HB(wid) = NULL;
REMOTE_HGEN(wid) = NULL;
REMOTE_iptop(wid) = NULL;
#if defined(GC_NO_TAGS)
REMOTE_bp(wid) = NULL;
#endif
REMOTE_sTR(wid) = NULL;
REMOTE_sTR0(wid) = NULL;
REMOTE_new_TR(wid) = NULL;
REMOTE_cont_top0(wid) = NULL;
REMOTE_cont_top(wid) = NULL;
REMOTE_discard_trail_entries(wid) = 0;
REMOTE_gc_ma_h_top(wid) = NULL;
REMOTE_gc_ma_h_list(wid) = NULL;
REMOTE_gc_timestamp(wid) = 0L;
REMOTE_db_vec(wid) = NULL;
REMOTE_db_vec0(wid) = NULL;
REMOTE_db_root(wid) = NULL;
REMOTE_db_nil(wid) = NULL;
REMOTE_extra_gc_cells_size(wid) = 256;
REMOTE_DynamicArrays(wid) = NULL;
REMOTE_StaticArrays(wid) = NULL;
REMOTE_GlobalVariables(wid) = NULL;
REMOTE_AllowRestart(wid) = FALSE;
REMOTE_CMemFirstBlock(wid) = NULL;
REMOTE_CMemFirstBlockSz(wid) = 0L;
REMOTE_nperm(wid) = 0L;
REMOTE_LabelFirstArray(wid) = NULL;
REMOTE_LabelFirstArraySz(wid) = 0L;
#ifdef THREADS
InitThreadHandle(wid);
#endif /* THREADS */
#if defined(YAPOR) || defined(TABLING)
Yap_init_local_optyap_data(wid);
REMOTE_TabMode(wid) = 0L;
#endif /* YAPOR || TABLING */
REMOTE_InterruptsDisabled(wid) = FALSE;
REMOTE_execution(wid) = NULL;
#if LOW_LEVEL_TRACER
REMOTE_total_choicepoints(wid) = 0;
#endif
REMOTE_consult_level(wid) = 0;
REMOTE_BreakLevel(wid) = 0;
REMOTE_PrologMode(wid) = BootMode;
REMOTE_CritLocks(wid) = 0;
#ifdef ANALYST
#endif /* ANALYST */
REMOTE_matherror(wid) = YAP_NO_ERROR;
REMOTE_mathstring(wid) = NULL;
REMOTE_CurrentError(wid) = YAP_NO_ERROR;
REMOTE_heap_overflows(wid) = 0;
REMOTE_total_heap_overflow_time(wid) = 0;
REMOTE_stack_overflows(wid) = 0;
REMOTE_total_stack_overflow_time(wid) = 0;
REMOTE_delay_overflows(wid) = 0;
REMOTE_total_delay_overflow_time(wid) = 0;
REMOTE_trail_overflows(wid) = 0;
REMOTE_total_trail_overflow_time(wid) = 0;
REMOTE_atom_table_overflows(wid) = 0;
REMOTE_total_atom_table_overflow_time(wid) = 0;
#ifdef LOAD_DYLD
REMOTE_dl_errno(wid) = 0;
#endif
#ifdef LOW_LEVEL_TRACER
REMOTE_do_trace_primitives(wid) = TRUE;
#endif
REMOTE_ExportAtomHashChain(wid) = NULL;
REMOTE_ExportAtomHashTableSize(wid) = 0;
REMOTE_ExportAtomHashTableNum(wid) = 0;
REMOTE_ExportFunctorHashChain(wid) = NULL;
REMOTE_ExportFunctorHashTableSize(wid) = 0;
REMOTE_ExportFunctorHashTableNum(wid) = 0;
REMOTE_ExportPredEntryHashChain(wid) = NULL;
REMOTE_ExportPredEntryHashTableSize(wid) = 0;
REMOTE_ExportPredEntryHashTableNum(wid) = 0;
REMOTE_ExportDBRefHashChain(wid) = NULL;
REMOTE_ExportDBRefHashTableSize(wid) = 0;
REMOTE_ExportDBRefHashTableNum(wid) = 0;
REMOTE_ImportAtomHashChain(wid) = NULL;
REMOTE_ImportAtomHashTableSize(wid) = 0;
REMOTE_ImportAtomHashTableNum(wid) = 0;
REMOTE_ImportFunctorHashChain(wid) = NULL;
REMOTE_ImportFunctorHashTableSize(wid) = 0;
REMOTE_ImportFunctorHashTableNum(wid) = 0;
REMOTE_ImportOPCODEHashChain(wid) = NULL;
REMOTE_ImportOPCODEHashTableSize(wid) = 0;
REMOTE_ImportPredEntryHashChain(wid) = NULL;
REMOTE_ImportPredEntryHashTableSize(wid) = 0;
REMOTE_ImportPredEntryHashTableNum(wid) = 0;
REMOTE_ImportDBRefHashChain(wid) = NULL;
REMOTE_ImportDBRefHashTableSize(wid) = 0;
REMOTE_ImportDBRefHashTableNum(wid) = 0;
REMOTE_ImportFAILCODE(wid) = NULL;
#if __ANDROID__
REMOTE_assetManager(wid) = GLOBAL_assetManager;
REMOTE_InAssetDir(wid) = NULL;
#endif
REMOTE_exo_it(wid) = NULL;
REMOTE_exo_base(wid) = NULL;
REMOTE_exo_arity(wid) = 0;
REMOTE_exo_arg(wid) = 0;
REMOTE_CurSlot(wid) = 0;
REMOTE_NSlots(wid) = 0;
REMOTE_SlotBase(wid) = InitHandles(wid);
REMOTE_Mutexes(wid) = NULL;
REMOTE_SourceModule(wid) = 0;
REMOTE_Including(wid) = TermNil;
REMOTE_MAX_SIZE(wid) = 1024L;
}

View File

@ -104,7 +104,7 @@ typedef enum {
#define STATIC_PRED_FLAGS (SourcePredFlag|DynamicPredFlag|LogUpdatePredFlag|CompiledPredFlag|MultiFileFlag|TabledPredFlag|MegaClausePredFlag|CountPredFlag|ProfiledPredFlag|ThreadLocalPredFlag|AtomDBPredFlag|ModuleTransparentPredFlag|NumberDBPredFlag|MetaPredFlag|SyncPredFlag|BackCPredFlag) #define STATIC_PRED_FLAGS (SourcePredFlag|DynamicPredFlag|LogUpdatePredFlag|CompiledPredFlag|MultiFileFlag|TabledPredFlag|MegaClausePredFlag|CountPredFlag|ProfiledPredFlag|ThreadLocalPredFlag|AtomDBPredFlag|ModuleTransparentPredFlag|NumberDBPredFlag|MetaPredFlag|SyncPredFlag|BackCPredFlag)
#define EXTRA_PRED_FLAGS (QuasiQuotationPredFlag|NoTracePredFlag|NoSpyPredFlag) #define EXTRA_PRED_FLAGS (QuasiQuotationPredFlag|NoTracePredFlag|NoSpyPredFlag)
#define SYSTEM_PRED_FLAGS (BackCPredFlag|UserCPredFlag|CArgsPredFlag|AsmPredFlag|CPredFlag|BinaryPredFlag|StandardPredFlag) #define SYSTEM_PRED_FLAGS (BackCPredFlag|UserCPredFlag|CArgsPredFlag|AsmPredFlag|CPredFlag|BinaryPredFlag)
#define CHECK(F) { size_t r = (F); if (!r) return r; } #define CHECK(F) { size_t r = (F); if (!r) return r; }
#define RCHECK(F) if(!(F)) { QLYR_ERROR(MISMATCH); return; } #define RCHECK(F) if(!(F)) { QLYR_ERROR(MISMATCH); return; }

View File

@ -20,6 +20,7 @@
AtomArrayOverflow = AtomAdjust(AtomArrayOverflow); AtomArrayOverflow = AtomAdjust(AtomArrayOverflow);
AtomArrayType = AtomAdjust(AtomArrayType); AtomArrayType = AtomAdjust(AtomArrayType);
AtomArrow = AtomAdjust(AtomArrow); AtomArrow = AtomAdjust(AtomArrow);
AtomAttributedModule = AtomAdjust(AtomAttributedModule);
AtomDoubleArrow = AtomAdjust(AtomDoubleArrow); AtomDoubleArrow = AtomAdjust(AtomDoubleArrow);
AtomAssert = AtomAdjust(AtomAssert); AtomAssert = AtomAdjust(AtomAssert);
AtomEmptyBrackets = AtomAdjust(AtomEmptyBrackets); AtomEmptyBrackets = AtomAdjust(AtomEmptyBrackets);
@ -509,6 +510,7 @@
FunctorPlus = FuncAdjust(FunctorPlus); FunctorPlus = FuncAdjust(FunctorPlus);
FunctorPortray = FuncAdjust(FunctorPortray); FunctorPortray = FuncAdjust(FunctorPortray);
FunctorPrintMessage = FuncAdjust(FunctorPrintMessage); FunctorPrintMessage = FuncAdjust(FunctorPrintMessage);
FunctorProcedure = FuncAdjust(FunctorProcedure);
FunctorPrologConstraint = FuncAdjust(FunctorPrologConstraint); FunctorPrologConstraint = FuncAdjust(FunctorPrologConstraint);
FunctorQuery = FuncAdjust(FunctorQuery); FunctorQuery = FuncAdjust(FunctorQuery);
FunctorRecordedWithKey = FuncAdjust(FunctorRecordedWithKey); FunctorRecordedWithKey = FuncAdjust(FunctorRecordedWithKey);

View File

@ -1,146 +0,0 @@
/* This file, rglobals.h, was generated automatically by "yap -L misc/buildlocalglobal"
please do not update, update misc/GLOBALS instead */
static void RestoreGlobal(void) {
#if __ANDROID__
#endif
#if THREADS
REINIT_LOCK(GLOBAL_ThreadHandlesLock);
#endif
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(GLOBAL_BGL);
#endif
#if defined(YAPOR) || defined(TABLING)
#endif /* YAPOR || TABLING */
#if defined(THREADS)
REINIT_LOCK(GLOBAL_mboxq_lock);
#endif /* THREADS */
#if defined(THREADS)||defined(YAPOR)
REINIT_LOCK(GLOBAL_StreamDescLock);
#endif
#ifdef COROUTINING
#endif
#if HAVE_MMAP
#endif
#ifdef DEBUG
#endif
#if defined(COFF) || defined(A_OUT)
#endif
#if __simplescalar__
#endif
#if LOW_PROF
#endif /* LOW_PROF */
#if THREADS
REINIT_LOCK(GLOBAL_MUT_ACCESS);
#endif
}

1296
H/rheap.h

File diff suppressed because it is too large Load Diff

View File

@ -1,301 +0,0 @@
/* This file, rhstruct.h, was generated automatically by "yap -L misc/buildheap"
please do not update, update misc/HEAPFIELDS instead */
#if USE_DL_MALLOC
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(DLMallocLock);
#endif
#endif
#if USE_DL_MALLOC || (USE_SYSTEM_MALLOC && HAVE_MALLINFO)
#ifndef HeapUsed
#define HeapUsed Yap_givemallinfo()
#endif
#else
#endif
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(FreeBlocksLock);
REINIT_LOCK(HeapUsedLock);
REINIT_LOCK(HeapTopLock);
#endif
#if USE_THREADED_CODE
OP_RTABLE = OpRTableAdjust(OP_RTABLE);
#endif
EXECUTE_CPRED_OP_CODE = Yap_opcode(_execute_cpred);
EXPAND_OP_CODE = Yap_opcode(_expand_index);
FAIL_OPCODE = Yap_opcode(_op_fail);
INDEX_OPCODE = Yap_opcode(_index_pred);
LOCKPRED_OPCODE = Yap_opcode(_lock_pred);
ORLAST_OPCODE = Yap_opcode(_or_last);
UNDEF_OPCODE = Yap_opcode(_undef_p);
RETRY_USERC_OPCODE = Yap_opcode(_retry_userc);
EXECUTE_CPRED_OPCODE = Yap_opcode(_execute_cpred);
RestoreInvisibleAtoms();
RestoreWideAtoms();
RestoreAtoms();
#include "ratoms.h"
#ifdef EUROTRA
TermDollarU = AtomTermAdjust(TermDollarU);
#endif
USER_MODULE = AtomTermAdjust(USER_MODULE);
IDB_MODULE = AtomTermAdjust(IDB_MODULE);
ATTRIBUTES_MODULE = AtomTermAdjust(ATTRIBUTES_MODULE);
CHARSIO_MODULE = AtomTermAdjust(CHARSIO_MODULE);
CHTYPE_MODULE = AtomTermAdjust(CHTYPE_MODULE);
TERMS_MODULE = AtomTermAdjust(TERMS_MODULE);
SYSTEM_MODULE = AtomTermAdjust(SYSTEM_MODULE);
READUTIL_MODULE = AtomTermAdjust(READUTIL_MODULE);
HACKS_MODULE = AtomTermAdjust(HACKS_MODULE);
ARG_MODULE = AtomTermAdjust(ARG_MODULE);
GLOBALS_MODULE = AtomTermAdjust(GLOBALS_MODULE);
SWI_MODULE = AtomTermAdjust(SWI_MODULE);
DBLOAD_MODULE = AtomTermAdjust(DBLOAD_MODULE);
RANGE_MODULE = AtomTermAdjust(RANGE_MODULE);
ERROR_MODULE = AtomTermAdjust(ERROR_MODULE);
CurrentModules = ModEntryPtrAdjust(CurrentModules);
RestoreHiddenPredicates();
RestoreFlags(GLOBAL_flagCount);
RestorePredHash();
#if defined(YAPOR) || defined(THREADS)
#endif
CreepCode = PtoPredAdjust(CreepCode);
UndefCode = PtoPredAdjust(UndefCode);
SpyCode = PtoPredAdjust(SpyCode);
PredFail = PtoPredAdjust(PredFail);
PredTrue = PtoPredAdjust(PredTrue);
#ifdef COROUTINING
WakeUpCode = PtoPredAdjust(WakeUpCode);
#endif
PredGoalExpansion = PtoPredAdjust(PredGoalExpansion);
PredMetaCall = PtoPredAdjust(PredMetaCall);
PredTraceMetaCall = PtoPredAdjust(PredTraceMetaCall);
PredDollarCatch = PtoPredAdjust(PredDollarCatch);
PredRecordedWithKey = PtoPredAdjust(PredRecordedWithKey);
PredLogUpdClause = PtoPredAdjust(PredLogUpdClause);
PredLogUpdClauseErase = PtoPredAdjust(PredLogUpdClauseErase);
PredLogUpdClause0 = PtoPredAdjust(PredLogUpdClause0);
PredStaticClause = PtoPredAdjust(PredStaticClause);
PredThrow = PtoPredAdjust(PredThrow);
PredHandleThrow = PtoPredAdjust(PredHandleThrow);
PredIs = PtoPredAdjust(PredIs);
PredSafeCallCleanup = PtoPredAdjust(PredSafeCallCleanup);
PredRestoreRegs = PtoPredAdjust(PredRestoreRegs);
PredCommentHook = PtoPredAdjust(PredCommentHook);
#ifdef YAPOR
PredGetwork = PtoPredAdjust(PredGetwork);
PredGetworkSeq = PtoPredAdjust(PredGetworkSeq);
#endif /* YAPOR */
#ifdef LOW_LEVEL_TRACER
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(Yap_low_level_trace_lock);
#endif
#endif
DUMMYCODE->opc = Yap_opcode(_op_fail);
FAILCODE->opc = Yap_opcode(_op_fail);
NOCODE->opc = Yap_opcode(_Nstop);
RestoreEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail);
RestoreEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail);
RestoreOtaplInst(RTRYCODE,_retry_and_mark,PredFail);
#ifdef BEAM
BEAM_RETRY_CODE->opc = Yap_opcode(_beam_retry_code);
#endif /* BEAM */
#ifdef YAPOR
RestoreOtaplInst(GETWORK,_getwork,PredGetwork);
RestoreOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq);
GETWORK_FIRST_TIME->opc = Yap_opcode(_getwork_first_time);
#endif /* YAPOR */
#ifdef TABLING
RestoreOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail);
RestoreOtaplInst(TRY_ANSWER,_table_try_answer,PredFail);
RestoreOtaplInst(ANSWER_RESOLUTION,_table_answer_resolution,PredFail);
RestoreOtaplInst(COMPLETION,_table_completion,PredFail);
#ifdef THREADS_CONSUMER_SHARING
RestoreOtaplInst(ANSWER_RESOLUTION_COMPLETION,_table_answer_resolution_completion,PredFail);
#endif /* THREADS_CONSUMER_SHARING */
#endif /* TABLING */
P_before_spy = PtoOpAdjust(P_before_spy);
RETRY_C_RECORDEDP_CODE = PtoOpAdjust(RETRY_C_RECORDEDP_CODE);
RETRY_C_RECORDED_K_CODE = PtoOpAdjust(RETRY_C_RECORDED_K_CODE);
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(DBTermsListLock);
#endif
RestoreDBTermsList();
RestoreExpandList();
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(ExpandClausesListLock);
REINIT_LOCK(OpListLock);
#endif
#ifdef DEBUG
#endif
RestoreUdiControlBlocks();
RestoreIntKeys();
RestoreIntLUKeys();
RestoreIntBBKeys();
RestoreDBErasedMarker();
RestoreLogDBErasedMarker();
RestoreDeadStaticClauses();
RestoreDeadMegaClauses();
RestoreDeadStaticIndices();
RestoreDBErasedList();
RestoreDBErasedIList();
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(DeadStaticClausesLock);
REINIT_LOCK(DeadMegaClausesLock);
REINIT_LOCK(DeadStaticIndicesLock);
#endif
#ifdef COROUTINING
#endif
OpList = OpListAdjust(OpList);
RestoreForeignCode();
RestoreYapRecords();
RestoreSWIAtoms();
RestoreEmptyWakeups();
RestoreBlobTypes();
RestoreBlobs();
#if defined(YAPOR) || defined(THREADS)
REINIT_LOCK(Blobs_Lock);
#endif

View File

@ -1,277 +0,0 @@
/* This file, rlocals.h, was generated automatically by "yap -L misc/buildlocalglobal"
please do not update, update misc/LOCALS instead */
static void RestoreWorker(int wid USES_REGS) {
REMOTE_GlobalArena(wid) = TermToGlobalOrAtomAdjust(REMOTE_GlobalArena(wid));
RestoreBallTerm(wid);
#ifdef COROUTINING
REMOTE_WokenGoals(wid) = TermToGlobalAdjust(REMOTE_WokenGoals(wid));
REMOTE_AttsMutableList(wid) = TermToGlobalAdjust(REMOTE_AttsMutableList(wid));
#endif
REMOTE_GcGeneration(wid) = TermToGlobalAdjust(REMOTE_GcGeneration(wid));
REMOTE_GcPhase(wid) = TermToGlobalAdjust(REMOTE_GcPhase(wid));
#if defined(GC_NO_TAGS)
#endif
REMOTE_DynamicArrays(wid) = PtoArrayEAdjust(REMOTE_DynamicArrays(wid));
REMOTE_StaticArrays(wid) = PtoArraySAdjust(REMOTE_StaticArrays(wid));
REMOTE_GlobalVariables(wid) = PtoGlobalEAdjust(REMOTE_GlobalVariables(wid));
#ifdef THREADS
#endif /* THREADS */
#if defined(YAPOR) || defined(TABLING)
#endif /* YAPOR || TABLING */
#if LOW_LEVEL_TRACER
#endif
#ifdef ANALYST
#endif /* ANALYST */
#ifdef LOAD_DYLD
#endif
#ifdef LOW_LEVEL_TRACER
#endif
#if __ANDROID__
#endif
}

View File

@ -56,6 +56,9 @@
Atom AtomArrow_; Atom AtomArrow_;
#define AtomArrow Yap_heap_regs->AtomArrow_ #define AtomArrow Yap_heap_regs->AtomArrow_
#define TermArrow MkAtomTerm( Yap_heap_regs->AtomArrow_ ) #define TermArrow MkAtomTerm( Yap_heap_regs->AtomArrow_ )
Atom AtomAttributedModule_;
#define AtomAttributedModule Yap_heap_regs->AtomAttributedModule_
#define TermAttributedModule MkAtomTerm( Yap_heap_regs->AtomAttributedModule_ )
Atom AtomDoubleArrow_; Atom AtomDoubleArrow_;
#define AtomDoubleArrow Yap_heap_regs->AtomDoubleArrow_ #define AtomDoubleArrow Yap_heap_regs->AtomDoubleArrow_
#define TermDoubleArrow MkAtomTerm( Yap_heap_regs->AtomDoubleArrow_ ) #define TermDoubleArrow MkAtomTerm( Yap_heap_regs->AtomDoubleArrow_ )
@ -1426,6 +1429,8 @@
#define FunctorPortray Yap_heap_regs->FunctorPortray_ #define FunctorPortray Yap_heap_regs->FunctorPortray_
Functor FunctorPrintMessage_; Functor FunctorPrintMessage_;
#define FunctorPrintMessage Yap_heap_regs->FunctorPrintMessage_ #define FunctorPrintMessage Yap_heap_regs->FunctorPrintMessage_
Functor FunctorProcedure_;
#define FunctorProcedure Yap_heap_regs->FunctorProcedure_
Functor FunctorPrologConstraint_; Functor FunctorPrologConstraint_;
#define FunctorPrologConstraint Yap_heap_regs->FunctorPrologConstraint_ #define FunctorPrologConstraint Yap_heap_regs->FunctorPrologConstraint_
Functor FunctorQuery_; Functor FunctorQuery_;

View File

@ -35,7 +35,8 @@ if (WITH_TABLING)
#this macro should realy be in config.h or other like it #this macro should realy be in config.h or other like it
#and it is used across several files outside OPTYap #and it is used across several files outside OPTYap
set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS TABLING=1) set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS TABLING=1)
include_directories (OPTYap) include_directories (OPTYap )
set(YAP_SYSTEM_OPTIONS "tabling " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
endif(WITH_TABLING) endif(WITH_TABLING)
option (WITH_YAPOR "Experimental Support for Or-parallelism" OFF) option (WITH_YAPOR "Experimental Support for Or-parallelism" OFF)
@ -43,33 +44,37 @@ option (WITH_YAPOR "Experimental Support for Or-parallelism" OFF)
OPTION (WITH_YAPOR_COPY "Copy-based Or-parallelism" OFF) OPTION (WITH_YAPOR_COPY "Copy-based Or-parallelism" OFF)
if (WITH_YAPOR_COPY) if (WITH_YAPOR_COPY)
set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_COPY=1;USE_DL_MALLOC=1) set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_COPY=1;USE_DL_MALLOC=1)
set(WITH_YAPOR ON) set(WITH_YAPOR ON)
endif (WITH_YAPOR_COPY) set(YAP_SYSTEM_OPTIONS "or_parallelism " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
endif (WITH_YAPOR_COPY)
OPTION (WITH_YAPOR_THOR "Thread-based Or-parallelism" OFF) OPTION (WITH_YAPOR_THOR "Thread-based Or-parallelism" OFF)
if (WITH_YAPOR_THOR) if (WITH_YAPOR_THOR)
set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_THREADS=1;USE_SYSTEM_MALLOC=1) set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_THREADS=1;USE_SYSTEM_MALLOC=1)
set(WITH_YAPOR ON) set(WITH_YAPOR ON)
set(YAP_SYSTEM_OPTIONS "or_parallelism " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
endif (WITH_YAPOR_THOR) endif (WITH_YAPOR_THOR)
OPTION (WITH_YAPOR_ACOW "Process-based Copy-On-Write Or-parallelism" OFF) OPTION (WITH_YAPOR_ACOW "Process-based Copy-On-Write Or-parallelism" OFF)
if (WITH_YAPOR_ACOW) if (WITH_YAPOR_ACOW)
set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_COW=1;USE_SYSTEM_MALLOC=1) set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_COW=1;USE_SYSTEM_MALLOC=1)
set(WITH_YAPOR ON) set(WITH_YAPOR ON)
set(YAP_SYSTEM_OPTIONS "or_parallelism " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
endif (WITH_YAPOR_ACOW) endif (WITH_YAPOR_ACOW)
OPTION (WITH_YAPOR_SBA "Sparse Bind Array-based Or-parallelism" OFF) OPTION (WITH_YAPOR_SBA "Sparse Bind Array-based Or-parallelism" OFF)
if (WITH_YAPOR_SBA) if (WITH_YAPOR_SBA)
set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_SBA=1;USE_SYSTEM_MALLOC=1) set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR_SBA=1;USE_SYSTEM_MALLOC=1)
set(WITH_YAPOR ON) set(WITH_YAPOR ON)
set(YAP_SYSTEM_OPTIONS "or_parallelism, " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
endif (WITH_YAPOR_SBA) endif (WITH_YAPOR_SBA)
if (WITH_YAPOR) if (WITH_YAPOR)
set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR=1) set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS YAPOR=1)
else() else()
set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS USE_SYSTEM_MALLOC=1) set_property(DIRECTORY .. APPEND PROPERTY COMPILE_DEFINITIONS USE_SYSTEM_MALLOC=1)
endif () endif ()
@ -77,7 +82,8 @@ endif ()
set (POSITION_INDEPENDENT_CODE TRUE) set (POSITION_INDEPENDENT_CODE TRUE)
add_library (libOPTYap OBJECT add_library (libOPTYap OBJECT
${OPTYap_SOURCES} ) ${OPTYap_SOURCES} )
set_target_properties(libOPTYap set_target_properties(libOPTYap
PROPERTIES PROPERTIES

View File

@ -24,7 +24,7 @@
#include <signal.h> #include <signal.h>
#ifdef YAPOR #ifdef YAPOR
#include "or.macros.h" #include "or.macros.h"
#endif /* YAPOR */ #endif /* YAPOR */
#ifdef TABLING #ifdef TABLING
#include "tab.macros.h" #include "tab.macros.h"
#elif !defined(YAPOR_COW) #elif !defined(YAPOR_COW)
@ -34,43 +34,42 @@
#include "sys/wait.h" #include "sys/wait.h"
#endif /* YAPOR_COW */ #endif /* YAPOR_COW */
/********************* /*********************
** Macros ** ** Macros **
*********************/ *********************/
#ifdef USE_PAGES_MALLOC #ifdef USE_PAGES_MALLOC
#define STRUCTS_PER_PAGE(STR_TYPE) ((Yap_page_size - ADJUST_SIZE(sizeof(struct page_header))) / ADJUST_SIZE(sizeof(STR_TYPE))) #define STRUCTS_PER_PAGE(STR_TYPE) \
((Yap_page_size - ADJUST_SIZE(sizeof(struct page_header))) / \
ADJUST_SIZE(sizeof(STR_TYPE)))
#define INIT_GLOBAL_PAGE_ENTRY(PG,STR_TYPE) \ #define INIT_GLOBAL_PAGE_ENTRY(PG, STR_TYPE) \
INIT_LOCK(PgEnt_lock(PG)); \ INIT_LOCK(PgEnt_lock(PG)); \
PgEnt_pages_in_use(PG) = 0; \ PgEnt_pages_in_use(PG) = 0; \
PgEnt_strs_in_use(PG) = 0; \ PgEnt_strs_in_use(PG) = 0; \
PgEnt_strs_per_page(PG) = STRUCTS_PER_PAGE(STR_TYPE); \ PgEnt_strs_per_page(PG) = STRUCTS_PER_PAGE(STR_TYPE); \
PgEnt_first(PG) = NULL; \ PgEnt_first(PG) = NULL; \
PgEnt_last(PG) = NULL; PgEnt_last(PG) = NULL;
#define INIT_LOCAL_PAGE_ENTRY(PG,STR_TYPE) \ #define INIT_LOCAL_PAGE_ENTRY(PG, STR_TYPE) \
PgEnt_pages_in_use(PG) = 0; \ PgEnt_pages_in_use(PG) = 0; \
PgEnt_strs_in_use(PG) = 0; \ PgEnt_strs_in_use(PG) = 0; \
PgEnt_strs_per_page(PG) = STRUCTS_PER_PAGE(STR_TYPE); \ PgEnt_strs_per_page(PG) = STRUCTS_PER_PAGE(STR_TYPE); \
PgEnt_first(PG) = NULL; \ PgEnt_first(PG) = NULL; \
PgEnt_last(PG) = NULL; PgEnt_last(PG) = NULL;
#else #else
#define INIT_GLOBAL_PAGE_ENTRY(PG,STR_TYPE) PgEnt_strs_in_use(PG) = 0 #define INIT_GLOBAL_PAGE_ENTRY(PG, STR_TYPE) PgEnt_strs_in_use(PG) = 0
#define INIT_LOCAL_PAGE_ENTRY(PG,STR_TYPE) PgEnt_strs_in_use(PG) = 0 #define INIT_LOCAL_PAGE_ENTRY(PG, STR_TYPE) PgEnt_strs_in_use(PG) = 0
#endif /* USE_PAGES_MALLOC */ #endif /* USE_PAGES_MALLOC */
/******************************* /*******************************
** Global functions ** ** Global functions **
*******************************/ *******************************/
void Yap_init_global_optyap_data(int max_table_size, int n_workers, int sch_loop, int delay_load) { void Yap_init_global_optyap_data(int max_table_size, int n_workers,
int sch_loop, int delay_load) {
int i; int i;
/* global data related to memory management */ /* global data related to memory management */
#ifdef USE_PAGES_MALLOC #ifdef USE_PAGES_MALLOC
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_alloc, void *); INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_alloc, void *);
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_void, void *); INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_void, void *);
@ -94,29 +93,34 @@ void Yap_init_global_optyap_data(int max_table_size, int n_workers, int sch_loop
#endif /* TABLING */ #endif /* TABLING */
#ifdef YAPOR #ifdef YAPOR
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_or_fr, struct or_frame); INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_or_fr, struct or_frame);
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_qg_sol_fr, struct query_goal_solution_frame); INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_qg_sol_fr,
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_qg_ans_fr, struct query_goal_answer_frame); struct query_goal_solution_frame);
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_qg_ans_fr,
struct query_goal_answer_frame);
#ifdef TABLING #ifdef TABLING
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_susp_fr, struct suspension_frame); INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_susp_fr, struct suspension_frame);
#endif #endif
#ifdef TABLING_INNER_CUTS #ifdef TABLING_INNER_CUTS
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_tg_sol_fr, struct table_subgoal_solution_frame); INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_tg_sol_fr,
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_tg_ans_fr, struct table_subgoal_answer_frame); struct table_subgoal_solution_frame);
INIT_GLOBAL_PAGE_ENTRY(GLOBAL_pages_tg_ans_fr,
struct table_subgoal_answer_frame);
#endif #endif
#endif /* YAPOR */ #endif /* YAPOR */
#ifdef YAPOR #ifdef YAPOR
/* global static data */ /* global static data */
GLOBAL_number_workers= n_workers; GLOBAL_number_workers = n_workers;
GLOBAL_worker_pid(0) = getpid(); GLOBAL_worker_pid(0) = getpid();
for (i = 1; i < GLOBAL_number_workers; i++) GLOBAL_worker_pid(i) = 0; for (i = 1; i < GLOBAL_number_workers; i++)
GLOBAL_worker_pid(i) = 0;
GLOBAL_scheduler_loop = sch_loop; GLOBAL_scheduler_loop = sch_loop;
GLOBAL_delayed_release_load = delay_load; GLOBAL_delayed_release_load = delay_load;
/* global data related to or-parallelism */ /* global data related to or-parallelism */
ALLOC_OR_FRAME(GLOBAL_root_or_fr); ALLOC_OR_FRAME(GLOBAL_root_or_fr);
BITMAP_clear(GLOBAL_bm_present_workers); BITMAP_clear(GLOBAL_bm_present_workers);
for (i = 0; i < GLOBAL_number_workers; i++) for (i = 0; i < GLOBAL_number_workers; i++)
BITMAP_insert(GLOBAL_bm_present_workers, i); BITMAP_insert(GLOBAL_bm_present_workers, i);
BITMAP_copy(GLOBAL_bm_idle_workers, GLOBAL_bm_present_workers); BITMAP_copy(GLOBAL_bm_idle_workers, GLOBAL_bm_present_workers);
BITMAP_clear(GLOBAL_bm_root_cp_workers); BITMAP_clear(GLOBAL_bm_root_cp_workers);
@ -146,7 +150,8 @@ void Yap_init_global_optyap_data(int max_table_size, int n_workers, int sch_loop
GLOBAL_root_tab_ent = NULL; GLOBAL_root_tab_ent = NULL;
#ifdef LIMIT_TABLING #ifdef LIMIT_TABLING
if (max_table_size) if (max_table_size)
GLOBAL_max_pages = ((max_table_size - 1) * 1024 * 1024 / SHMMAX + 1) * SHMMAX / Yap_page_size; GLOBAL_max_pages = ((max_table_size - 1) * 1024 * 1024 / SHMMAX + 1) *
SHMMAX / Yap_page_size;
else else
GLOBAL_max_pages = -1; GLOBAL_max_pages = -1;
GLOBAL_first_sg_fr = NULL; GLOBAL_first_sg_fr = NULL;
@ -154,7 +159,8 @@ void Yap_init_global_optyap_data(int max_table_size, int n_workers, int sch_loop
GLOBAL_check_sg_fr = NULL; GLOBAL_check_sg_fr = NULL;
#endif /* LIMIT_TABLING */ #endif /* LIMIT_TABLING */
#ifdef YAPOR #ifdef YAPOR
new_dependency_frame(GLOBAL_root_dep_fr, FALSE, NULL, NULL, NULL, NULL, FALSE, NULL); new_dependency_frame(GLOBAL_root_dep_fr, FALSE, NULL, NULL, NULL, NULL, FALSE,
NULL);
#endif /* YAPOR */ #endif /* YAPOR */
for (i = 0; i < MAX_TABLE_VARS; i++) { for (i = 0; i < MAX_TABLE_VARS; i++) {
CELL *pt = GLOBAL_table_var_enumerator_addr(i); CELL *pt = GLOBAL_table_var_enumerator_addr(i);
@ -169,14 +175,13 @@ void Yap_init_global_optyap_data(int max_table_size, int n_workers, int sch_loop
return; return;
} }
void Yap_init_local_optyap_data(int wid) { void Yap_init_local_optyap_data(int wid) {
#if defined(YAPOR_THREADS) || defined(THREADS_CONSUMER_SHARING) #if defined(YAPOR_THREADS) || defined(THREADS_CONSUMER_SHARING)
CACHE_REGS CACHE_REGS
#endif /* YAPOR_THREADS || THREADS_CONSUMER_SHARING */ #endif /* YAPOR_THREADS || THREADS_CONSUMER_SHARING */
#if defined(TABLING) && (defined(YAPOR) || defined(THREADS)) #if defined(TABLING) && (defined(YAPOR) || defined(THREADS))
/* local data related to memory management */ /* local data related to memory management */
#ifdef YAPOR #ifdef YAPOR
REMOTE_next_free_ans_node(wid) = NULL; REMOTE_next_free_ans_node(wid) = NULL;
#elif THREADS #elif THREADS
@ -203,7 +208,7 @@ void Yap_init_local_optyap_data(int wid) {
#ifdef YAPOR #ifdef YAPOR
/* local data related to or-parallelism */ /* local data related to or-parallelism */
Set_REMOTE_top_cp(wid, (choiceptr) LOCAL_LocalBase); Set_REMOTE_top_cp(wid, (choiceptr)LOCAL_LocalBase);
REMOTE_top_or_fr(wid) = GLOBAL_root_or_fr; REMOTE_top_or_fr(wid) = GLOBAL_root_or_fr;
REMOTE_load(wid) = 0; REMOTE_load(wid) = 0;
REMOTE_share_request(wid) = MAX_WORKERS; REMOTE_share_request(wid) = MAX_WORKERS;
@ -217,11 +222,11 @@ void Yap_init_local_optyap_data(int wid) {
#ifdef TABLING #ifdef TABLING
/* local data related to tabling */ /* local data related to tabling */
REMOTE_top_sg_fr(wid) = NULL; REMOTE_top_sg_fr(wid) = NULL;
REMOTE_top_dep_fr(wid) = NULL; REMOTE_top_dep_fr(wid) = NULL;
#ifdef YAPOR #ifdef YAPOR
REMOTE_top_dep_fr(wid) = GLOBAL_root_dep_fr; REMOTE_top_dep_fr(wid) = GLOBAL_root_dep_fr;
Set_REMOTE_top_cp_on_stack(wid, (choiceptr) LOCAL_LocalBase); /* ??? */ Set_REMOTE_top_cp_on_stack(wid, (choiceptr)LOCAL_LocalBase); /* ??? */
REMOTE_top_susp_or_fr(wid) = GLOBAL_root_or_fr; REMOTE_top_susp_or_fr(wid) = GLOBAL_root_or_fr;
#endif /* YAPOR */ #endif /* YAPOR */
#ifdef THREADS_CONSUMER_SHARING #ifdef THREADS_CONSUMER_SHARING
@ -234,7 +239,6 @@ void Yap_init_local_optyap_data(int wid) {
return; return;
} }
void Yap_init_root_frames(void) { void Yap_init_root_frames(void) {
CACHE_REGS CACHE_REGS
@ -244,7 +248,7 @@ void Yap_init_root_frames(void) {
INIT_LOCK(OrFr_lock(or_fr)); INIT_LOCK(OrFr_lock(or_fr));
OrFr_alternative(or_fr) = NULL; OrFr_alternative(or_fr) = NULL;
BITMAP_copy(OrFr_members(or_fr), GLOBAL_bm_present_workers); BITMAP_copy(OrFr_members(or_fr), GLOBAL_bm_present_workers);
SetOrFr_node(or_fr, (choiceptr) LOCAL_LocalBase); SetOrFr_node(or_fr, (choiceptr)LOCAL_LocalBase);
OrFr_nearest_livenode(or_fr) = NULL; OrFr_nearest_livenode(or_fr) = NULL;
OrFr_depth(or_fr) = 0; OrFr_depth(or_fr) = 0;
Set_OrFr_pend_prune_cp(or_fr, NULL); Set_OrFr_pend_prune_cp(or_fr, NULL);
@ -265,23 +269,26 @@ void Yap_init_root_frames(void) {
#ifdef TABLING #ifdef TABLING
/* root global trie node */ /* root global trie node */
new_global_trie_node(GLOBAL_root_gt, 0, NULL, NULL, NULL); new_global_trie_node(GLOBAL_root_gt, 0, NULL, NULL, NULL);
/* root dependency frame */ /* root dependency frame */
#ifdef YAPOR #ifdef YAPOR
DepFr_cons_cp(GLOBAL_root_dep_fr) = B; /* with YAPOR, at that point, LOCAL_top_dep_fr shouldn't be the same as GLOBAL_root_dep_fr ? */ DepFr_cons_cp(GLOBAL_root_dep_fr) = B; /* with YAPOR, at that point,
LOCAL_top_dep_fr shouldn't be the
same as GLOBAL_root_dep_fr ? */
#else #else
new_dependency_frame(LOCAL_top_dep_fr, FALSE, NULL, NULL, B, NULL, FALSE, NULL); new_dependency_frame(LOCAL_top_dep_fr, FALSE, NULL, NULL, B, NULL, FALSE,
NULL);
#endif /* YAPOR */ #endif /* YAPOR */
#endif /* TABLING */ #endif /* TABLING */
} }
void itos(int i, char *s) { void itos(int i, char *s) {
int n,r,j; int n, r, j;
n = 10; n = 10;
while (n <= i) n *= 10; while (n <= i)
n *= 10;
j = 0; j = 0;
while (n > 1) { while (n > 1) {
n = n / 10; n = n / 10;
r = i / n; r = i / n;
i = i - r * n; i = i - r * n;
s[j++] = r + '0'; s[j++] = r + '0';

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -128,26 +128,26 @@ set(C_INTERFACE_SOURCES
H/compile.h H/compile.h
H/corout.h H/corout.h
H/dlmalloc.h H/dlmalloc.h
H/dglobals.h H/heap/dglobals.h
H/dlocals.h H/heap/dlocals.h
H/dhstruct.h H/heap/dhstruct.h
H/eval.h H/eval.h
H/heapgc.h H/heapgc.h
H/hglobals.h H/heap/hglobals.h
H/hlocals.h H/heap/hlocals.h
H/hstruct.h H/heap/hstruct.h
H/iglobals.h H/heap/iglobals.h
H/ihstruct.h H/heap/ihstruct.h
H/ilocals.h H/heap/ilocals.h
H/index.h H/index.h
H/inline-only.h H/inline-only.h
H/iswiatoms.h H/iswiatoms.h
H/qly.h H/qly.h
H/rclause.h H/rclause.h
H/rglobals.h H/heap/rglobals.h
H/rlocals.h H/heap/rlocals.h
H/rheap.h H/rheap.h
H/rhstruct.h H/heap/rhstruct.h
H/threads.h H/threads.h
H/tracer.h H/tracer.h
H/trim_trail.h H/trim_trail.h

View File

@ -8,6 +8,7 @@
#define CONFIG_H #define CONFIG_H
/* config.h.in. Generated from configure.in by autoheader. */ /* config.h.in. Generated from configure.in by autoheader. */
#define SYSTEM_OPTIONS "${YAP_SYSTEM_OPTIONS}"
/* Define if building universal (internal helper macro) */ /* Define if building universal (internal helper macro) */
#ifndef AC_APPLE_UNIVERSAL_BUILD #ifndef AC_APPLE_UNIVERSAL_BUILD

View File

@ -1,156 +1,153 @@
BEGIN_ERROR_CLASSES() BEGIN_ERROR_CLASSES()
ECLASS(NO_ERROR, "no_error", 0) ECLASS(NO_ERROR, "no_error", 0)
ECLASS(DOMAIN_ERROR, "domain_error", 2) ECLASS(DOMAIN_ERROR, "domain_error", 2)
ECLASS(EVALUATION_ERROR, "evaluation_error", 2) ECLASS(EVALUATION_ERROR, "evaluation_error", 2)
ECLASS(EXISTENCE_ERROR, "existence_error", 2) ECLASS(EXISTENCE_ERROR, "existence_error", 2)
ECLASS(INSTANTIATION_ERROR_CLASS, "instantiation_error", 0) ECLASS(INSTANTIATION_ERROR_CLASS, "instantiation_error", 0)
ECLASS(PERMISSION_ERROR, "permission_error", 3) ECLASS(PERMISSION_ERROR, "permission_error", 3)
ECLASS(REPRESENTATION_ERROR, "representation_error", 2) ECLASS(REPRESENTATION_ERROR, "representation_error", 2)
ECLASS(RESOURCE_ERROR, "resource_error", 2) ECLASS(RESOURCE_ERROR, "resource_error", 2)
ECLASS(SYNTAX_ERROR_CLASS, "syntax_error", 2) ECLASS(SYNTAX_ERROR_CLASS, "syntax_error", 2)
ECLASS(SYSTEM_ERROR_CLASS, "system_error", 2) ECLASS(SYSTEM_ERROR_CLASS, "system_error", 2)
ECLASS(TYPE_ERROR, "type_error", 2) ECLASS(TYPE_ERROR, "type_error", 2)
ECLASS(UNINSTANTIATION_ERROR_CLASS, "uninstantiation_error", 1) ECLASS(UNINSTANTIATION_ERROR_CLASS, "uninstantiation_error", 1)
ECLASS(EVENT, "event", 2) ECLASS(EVENT, "event", 2)
END_ERROR_CLASSES(); END_ERROR_CLASSES();
BEGIN_ERRORS() BEGIN_ERRORS()
/* ISO_ERRORS */ /* ISO_ERRORS */
E0(YAP_NO_ERROR, NO_ERROR) E0(YAP_NO_ERROR, NO_ERROR)
E(DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION, DOMAIN_ERROR, "absolute_file_name_option") E(DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION, DOMAIN_ERROR,
E(DOMAIN_ERROR_ARRAY_OVERFLOW, DOMAIN_ERROR, "array_overflow") "absolute_file_name_option")
E(DOMAIN_ERROR_ARRAY_TYPE, DOMAIN_ERROR, "array_type") E(DOMAIN_ERROR_ARRAY_OVERFLOW, DOMAIN_ERROR, "array_overflow")
E(DOMAIN_ERROR_FILE_ERRORS, DOMAIN_ERROR, "file_errors") E(DOMAIN_ERROR_ARRAY_TYPE, DOMAIN_ERROR, "array_type")
E(DOMAIN_ERROR_FILE_TYPE, DOMAIN_ERROR, "file_type") E(DOMAIN_ERROR_FILE_ERRORS, DOMAIN_ERROR, "file_errors")
E(DOMAIN_ERROR_IO_MODE, DOMAIN_ERROR, "io_mode") E(DOMAIN_ERROR_FILE_TYPE, DOMAIN_ERROR, "file_type")
E(DOMAIN_ERROR_MUTABLE, DOMAIN_ERROR, "mutable") E(DOMAIN_ERROR_IO_MODE, DOMAIN_ERROR, "io_mode")
E(DOMAIN_ERROR_NON_EMPTY_LIST, DOMAIN_ERROR, "non_empty_list") E(DOMAIN_ERROR_MUTABLE, DOMAIN_ERROR, "mutable")
E(DOMAIN_ERROR_NOT_LESS_THAN_ZERO, DOMAIN_ERROR, "not_less_than_zero") E(DOMAIN_ERROR_NON_EMPTY_LIST, DOMAIN_ERROR, "non_empty_list")
E(DOMAIN_ERROR_NOT_NL, DOMAIN_ERROR, "not_nl") E(DOMAIN_ERROR_NOT_LESS_THAN_ZERO, DOMAIN_ERROR, "not_less_than_zero")
E(DOMAIN_ERROR_NOT_ZERO, DOMAIN_ERROR, "not_zero") E(DOMAIN_ERROR_NOT_NL, DOMAIN_ERROR, "not_nl")
E(DOMAIN_ERROR_OUT_OF_RANGE, DOMAIN_ERROR, "out_of_range") E(DOMAIN_ERROR_NOT_ZERO, DOMAIN_ERROR, "not_zero")
E(DOMAIN_ERROR_OPERATOR_PRIORITY, DOMAIN_ERROR, "operator_priority") E(DOMAIN_ERROR_OUT_OF_RANGE, DOMAIN_ERROR, "out_of_range")
E(DOMAIN_ERROR_OPERATOR_SPECIFIER, DOMAIN_ERROR, "operator_specifier") E(DOMAIN_ERROR_OPERATOR_PRIORITY, DOMAIN_ERROR, "operator_priority")
E(DOMAIN_ERROR_PROLOG_FLAG, DOMAIN_ERROR, "prolog_flag") E(DOMAIN_ERROR_OPERATOR_SPECIFIER, DOMAIN_ERROR, "operator_specifier")
E(DOMAIN_ERROR_RADIX, DOMAIN_ERROR, "radix") E(DOMAIN_ERROR_PROLOG_FLAG, DOMAIN_ERROR, "prolog_flag")
E(DOMAIN_ERROR_READ_OPTION, DOMAIN_ERROR, "read_option") E(DOMAIN_ERROR_RADIX, DOMAIN_ERROR, "radix")
E(DOMAIN_ERROR_SHIFT_COUNT_OVERFLOW, DOMAIN_ERROR, "shift_count_overflow") E(DOMAIN_ERROR_READ_OPTION, DOMAIN_ERROR, "read_option")
E(DOMAIN_ERROR_SOURCE_SINK, DOMAIN_ERROR, "source_sink") E(DOMAIN_ERROR_SHIFT_COUNT_OVERFLOW, DOMAIN_ERROR, "shift_count_overflow")
E(DOMAIN_ERROR_SOLUTIONS, DOMAIN_ERROR, "solutions") E(DOMAIN_ERROR_SOURCE_SINK, DOMAIN_ERROR, "source_sink")
E(DOMAIN_ERROR_STREAM, DOMAIN_ERROR, "stream") E(DOMAIN_ERROR_SOLUTIONS, DOMAIN_ERROR, "solutions")
E(DOMAIN_ERROR_STREAM_ENCODING, DOMAIN_ERROR, "stream_encoding") E(DOMAIN_ERROR_STREAM, DOMAIN_ERROR, "stream")
E(DOMAIN_ERROR_STREAM_OR_ALIAS, DOMAIN_ERROR, "stream_or_alias") E(DOMAIN_ERROR_STREAM_ENCODING, DOMAIN_ERROR, "stream_encoding")
E(DOMAIN_ERROR_STREAM_POSITION, DOMAIN_ERROR, "stream_position") E(DOMAIN_ERROR_STREAM_OR_ALIAS, DOMAIN_ERROR, "stream_or_alias")
E(DOMAIN_ERROR_TIMEOUT_SPEC, DOMAIN_ERROR, "timeout_spec") E(DOMAIN_ERROR_STREAM_POSITION, DOMAIN_ERROR, "stream_position")
E(DOMAIN_ERROR_SYNTAX_ERROR_HANDLER, DOMAIN_ERROR, "syntax_error_handler") E(DOMAIN_ERROR_TIMEOUT_SPEC, DOMAIN_ERROR, "timeout_spec")
E(DOMAIN_ERROR_WRITE_OPTION, DOMAIN_ERROR, "write_option") E(DOMAIN_ERROR_SYNTAX_ERROR_HANDLER, DOMAIN_ERROR, "syntax_error_handler")
E(DOMAIN_ERROR_WRITE_OPTION, DOMAIN_ERROR, "write_option")
E(EVALUATION_ERROR_FLOAT_OVERFLOW, EVALUATION_ERROR, "float_overflow") E(EVALUATION_ERROR_FLOAT_OVERFLOW, EVALUATION_ERROR, "float_overflow")
E(EVALUATION_ERROR_FLOAT_UNDERFLOW, EVALUATION_ERROR, "float_underflow") E(EVALUATION_ERROR_FLOAT_UNDERFLOW, EVALUATION_ERROR, "float_underflow")
E(EVALUATION_ERROR_INT_OVERFLOW, EVALUATION_ERROR, "int_overflow") E(EVALUATION_ERROR_INT_OVERFLOW, EVALUATION_ERROR, "int_overflow")
E(EVALUATION_ERROR_UNDEFINED, EVALUATION_ERROR, "undefined") E(EVALUATION_ERROR_UNDEFINED, EVALUATION_ERROR, "undefined")
E(EVALUATION_ERROR_UNDERFLOW, EVALUATION_ERROR, "underflow") E(EVALUATION_ERROR_UNDERFLOW, EVALUATION_ERROR, "underflow")
E(EVALUATION_ERROR_ZERO_DIVISOR, EVALUATION_ERROR, "zero_divisor") E(EVALUATION_ERROR_ZERO_DIVISOR, EVALUATION_ERROR, "zero_divisor")
E(EXISTENCE_ERROR_ARRAY, EXISTENCE_ERROR, "array") E(EXISTENCE_ERROR_ARRAY, EXISTENCE_ERROR, "array")
E(EXISTENCE_ERROR_KEY, EXISTENCE_ERROR, "key, ") E(EXISTENCE_ERROR_KEY, EXISTENCE_ERROR, "key, ")
E(EXISTENCE_ERROR_MUTEX, EXISTENCE_ERROR, "mutex, ") E(EXISTENCE_ERROR_MUTEX, EXISTENCE_ERROR, "mutex, ")
E(EXISTENCE_ERROR_SOURCE_SINK, EXISTENCE_ERROR, "source_sink") E(EXISTENCE_ERROR_SOURCE_SINK, EXISTENCE_ERROR, "source_sink")
E(EXISTENCE_ERROR_STREAM, EXISTENCE_ERROR, "stream") E(EXISTENCE_ERROR_STREAM, EXISTENCE_ERROR, "stream")
E(EXISTENCE_ERROR_VARIABLE, EXISTENCE_ERROR, "variable") E(EXISTENCE_ERROR_VARIABLE, EXISTENCE_ERROR, "variable")
E0(INSTANTIATION_ERROR, INSTANTIATION_ERROR_CLASS) E0(INSTANTIATION_ERROR, INSTANTIATION_ERROR_CLASS)
E2(PERMISSION_ERROR_ACCESS_PRIVATE_PROCEDURE, PERMISSION_ERROR, "access","private_procedure") E2(PERMISSION_ERROR_ACCESS_PRIVATE_PROCEDURE, PERMISSION_ERROR, "access",
E2(PERMISSION_ERROR_NEW_ALIAS_FOR_STREAM, PERMISSION_ERROR, "private_procedure")
"add_alias", "stream") E2(PERMISSION_ERROR_NEW_ALIAS_FOR_STREAM, PERMISSION_ERROR, "add_alias",
E2(PERMISSION_ERROR_CREATE_ARRAY, PERMISSION_ERROR, "create", "array") "stream")
E2(PERMISSION_ERROR_CREATE_OPERATOR, PERMISSION_ERROR, "create", "operator") E2(PERMISSION_ERROR_CREATE_ARRAY, PERMISSION_ERROR, "create", "array")
E2(PERMISSION_ERROR_INPUT_BINARY_STREAM, PERMISSION_ERROR, E2(PERMISSION_ERROR_CREATE_OPERATOR, PERMISSION_ERROR, "create", "operator")
"input", "binary_stream") E2(PERMISSION_ERROR_INPUT_BINARY_STREAM, PERMISSION_ERROR, "input",
E2(PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM, PERMISSION_ERROR, "binary_stream")
"input", "past_end_of_stream") E2(PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM, PERMISSION_ERROR, "input",
E2(PERMISSION_ERROR_INPUT_STREAM, PERMISSION_ERROR, "input","stream") "past_end_of_stream")
E2(PERMISSION_ERROR_INPUT_TEXT_STREAM, PERMISSION_ERROR, E2(PERMISSION_ERROR_INPUT_STREAM, PERMISSION_ERROR, "input", "stream")
"input","text_stream") E2(PERMISSION_ERROR_INPUT_TEXT_STREAM, PERMISSION_ERROR, "input", "text_stream")
E2(PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE, PERMISSION_ERROR, E2(PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE, PERMISSION_ERROR, "modify",
"modify","static_procedure") "static_procedure")
E2(PERMISSION_ERROR_OPEN_SOURCE_SINK, PERMISSION_ERROR, "open","source_sink") E2(PERMISSION_ERROR_OPEN_SOURCE_SINK, PERMISSION_ERROR, "open", "source_sink")
E2(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, PERMISSION_ERROR, E2(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, PERMISSION_ERROR, "output",
"output","binary_stream") "binary_stream")
E2(PERMISSION_ERROR_OUTPUT_STREAM, PERMISSION_ERROR, "output","stream") E2(PERMISSION_ERROR_OUTPUT_STREAM, PERMISSION_ERROR, "output", "stream")
E2(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, PERMISSION_ERROR, E2(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, PERMISSION_ERROR, "output",
"output","text_stream") "text_stream")
E2(PERMISSION_ERROR_READ_ONLY_FLAG, PERMISSION_ERROR, "read_only","flag") E2(PERMISSION_ERROR_READ_ONLY_FLAG, PERMISSION_ERROR, "read_only", "flag")
E2(PERMISSION_ERROR_RESIZE_ARRAY, PERMISSION_ERROR, "resize","array") E2(PERMISSION_ERROR_RESIZE_ARRAY, PERMISSION_ERROR, "resize", "array")
E2(PERMISSION_ERROR_REPOSITION_STREAM, PERMISSION_ERROR, E2(PERMISSION_ERROR_REPOSITION_STREAM, PERMISSION_ERROR, "reposition", "stream")
"reposition","stream")
E(REPRESENTATION_ERROR_CHARACTER, REPRESENTATION_ERROR, "character") E(REPRESENTATION_ERROR_CHARACTER, REPRESENTATION_ERROR, "character")
E(REPRESENTATION_ERROR_CHARACTER_CODE, REPRESENTATION_ERROR, E(REPRESENTATION_ERROR_CHARACTER_CODE, REPRESENTATION_ERROR, "character_code")
"character_code") E(REPRESENTATION_ERROR_INT, REPRESENTATION_ERROR, "int")
E(REPRESENTATION_ERROR_INT, REPRESENTATION_ERROR, "int") E(REPRESENTATION_ERROR_MAX_ARITY, REPRESENTATION_ERROR, "max_arity")
E(REPRESENTATION_ERROR_MAX_ARITY, REPRESENTATION_ERROR, "max_arity") E(REPRESENTATION_ERROR_VARIABLE, REPRESENTATION_ERROR, "variable")
E(REPRESENTATION_ERROR_VARIABLE, REPRESENTATION_ERROR, "variable")
E(RESOURCE_ERROR_HUGE_INT, RESOURCE_ERROR, "huge_int") E(RESOURCE_ERROR_HUGE_INT, RESOURCE_ERROR, "huge_int")
E(RESOURCE_ERROR_MAX_STREAMS, RESOURCE_ERROR, "max_streams") E(RESOURCE_ERROR_MAX_STREAMS, RESOURCE_ERROR, "max_streams")
E(RESOURCE_ERROR_MAX_THREADS, RESOURCE_ERROR, "max_threads") E(RESOURCE_ERROR_MAX_THREADS, RESOURCE_ERROR, "max_threads")
E(RESOURCE_ERROR_AUXILIARY_STACK, RESOURCE_ERROR, "auxiliary_stack") E(RESOURCE_ERROR_AUXILIARY_STACK, RESOURCE_ERROR, "auxiliary_stack")
E(RESOURCE_ERROR_ATTRIBUTED_VARIABLES, RESOURCE_ERROR, E(RESOURCE_ERROR_ATTRIBUTED_VARIABLES, RESOURCE_ERROR, "attributed_variables")
"attributed_variables") E(RESOURCE_ERROR_HEAP, RESOURCE_ERROR, "database_space")
E(RESOURCE_ERROR_HEAP, RESOURCE_ERROR, "database_space") E(RESOURCE_ERROR_TRAIL, RESOURCE_ERROR, "trail_space")
E(RESOURCE_ERROR_TRAIL, RESOURCE_ERROR, "trail_space") E(RESOURCE_ERROR_STACK, RESOURCE_ERROR, "stack_space")
E(RESOURCE_ERROR_STACK, RESOURCE_ERROR, "stack_space")
E(SYNTAX_ERROR, SYNTAX_ERROR_CLASS, "syntax_error") E(SYNTAX_ERROR, SYNTAX_ERROR_CLASS, "syntax_error")
E(SYSTEM_ERROR_INTERNAL, SYSTEM_ERROR_CLASS, "internal") E(SYSTEM_ERROR_INTERNAL, SYSTEM_ERROR_CLASS, "internal")
E(SYSTEM_ERROR_COMPILER, SYSTEM_ERROR_CLASS, "compiler") E(SYSTEM_ERROR_COMPILER, SYSTEM_ERROR_CLASS, "compiler")
E(SYSTEM_ERROR_FATAL, SYSTEM_ERROR_CLASS, "fatal") E(SYSTEM_ERROR_FATAL, SYSTEM_ERROR_CLASS, "fatal")
E(SYSTEM_ERROR_JIT_NOT_AVAILABLE, SYSTEM_ERROR_CLASS, "jit_not_available") E(SYSTEM_ERROR_JIT_NOT_AVAILABLE, SYSTEM_ERROR_CLASS, "jit_not_available")
E(SYSTEM_ERROR_OPERATING_SYSTEM, SYSTEM_ERROR_CLASS, "operating_system_error") E(SYSTEM_ERROR_OPERATING_SYSTEM, SYSTEM_ERROR_CLASS, "operating_system_error")
E(SYSTEM_ERROR_SAVED_STATE, SYSTEM_ERROR_CLASS, "saved_state_error") E(SYSTEM_ERROR_SAVED_STATE, SYSTEM_ERROR_CLASS, "saved_state_error")
E(ABORT_EVENT, EVENT, "abort") E(ABORT_EVENT, EVENT, "abort")
E(CALL_COUNTER_UNDERFLOW_EVENT, EVENT, "call_counter_underflow") E(CALL_COUNTER_UNDERFLOW_EVENT, EVENT, "call_counter_underflow")
E(PRED_ENTRY_COUNTER_UNDERFLOW_EVENT, EVENT, E(PRED_ENTRY_COUNTER_UNDERFLOW_EVENT, EVENT, "pred_entry_counter_underflow")
"pred_entry_counter_underflow") E(RETRY_COUNTER_UNDERFLOW_EVENT, EVENT, "retry_counter_underflow")
E(RETRY_COUNTER_UNDERFLOW_EVENT, EVENT, "retry_counter_underflow") E(INTERRUPT_EVENT, EVENT, "interrupt")
E(INTERRUPT_EVENT, EVENT, "interrupt")
E(TYPE_ERROR_ARRAY, TYPE_ERROR, "array") E(TYPE_ERROR_ARRAY, TYPE_ERROR, "array")
E(TYPE_ERROR_ATOM, TYPE_ERROR, "atom") E(TYPE_ERROR_ATOM, TYPE_ERROR, "atom")
E(TYPE_ERROR_ATOMIC, TYPE_ERROR, "atomic") E(TYPE_ERROR_ATOMIC, TYPE_ERROR, "atomic")
E(TYPE_ERROR_BIGNUM, TYPE_ERROR, "bignum") E(TYPE_ERROR_BIGNUM, TYPE_ERROR, "bignum")
E(TYPE_ERROR_BYTE, TYPE_ERROR, "byte") E(TYPE_ERROR_BYTE, TYPE_ERROR, "byte")
E(TYPE_ERROR_CALLABLE, TYPE_ERROR, "callable") E(TYPE_ERROR_CALLABLE, TYPE_ERROR, "callable")
E(TYPE_ERROR_CHAR, TYPE_ERROR, "char") E(TYPE_ERROR_CHAR, TYPE_ERROR, "char")
E(TYPE_ERROR_CHARACTER, TYPE_ERROR, "character") E(TYPE_ERROR_CHARACTER, TYPE_ERROR, "character")
E(TYPE_ERROR_CHARACTER_CODE, TYPE_ERROR, "character_code") E(TYPE_ERROR_CHARACTER_CODE, TYPE_ERROR, "character_code")
E(TYPE_ERROR_COMPOUND, TYPE_ERROR, "compound") E(TYPE_ERROR_COMPOUND, TYPE_ERROR, "compound")
E(TYPE_ERROR_DBREF, TYPE_ERROR, "dbref") E(TYPE_ERROR_DBREF, TYPE_ERROR, "dbref")
E(TYPE_ERROR_DBTERM, TYPE_ERROR, "dbterm") E(TYPE_ERROR_DBTERM, TYPE_ERROR, "dbterm")
E(TYPE_ERROR_EVALUABLE, TYPE_ERROR, "evaluable") E(TYPE_ERROR_EVALUABLE, TYPE_ERROR, "evaluable")
E(TYPE_ERROR_FLOAT, TYPE_ERROR, "float") E(TYPE_ERROR_FLOAT, TYPE_ERROR, "float")
E(TYPE_ERROR_INTEGER, TYPE_ERROR, "integer") E(TYPE_ERROR_INTEGER, TYPE_ERROR, "integer")
E(TYPE_ERROR_KEY, TYPE_ERROR, "key") E(TYPE_ERROR_KEY, TYPE_ERROR, "key")
E(TYPE_ERROR_LIST, TYPE_ERROR, "list") E(TYPE_ERROR_LIST, TYPE_ERROR, "list")
E(TYPE_ERROR_NUMBER, TYPE_ERROR, "number") E(TYPE_ERROR_NUMBER, TYPE_ERROR, "number")
E(TYPE_ERROR_PARAMETER, TYPE_ERROR, "parameter") E(TYPE_ERROR_PARAMETER, TYPE_ERROR, "parameter")
E(TYPE_ERROR_PREDICATE_INDICATOR, TYPE_ERROR, "predicate_indicator") E(TYPE_ERROR_PREDICATE_INDICATOR, TYPE_ERROR, "predicate_indicator")
E(TYPE_ERROR_PTR, TYPE_ERROR, "pointer") E(TYPE_ERROR_PTR, TYPE_ERROR, "pointer")
E(TYPE_ERROR_REFERENCE, TYPE_ERROR, "reference") E(TYPE_ERROR_REFERENCE, TYPE_ERROR, "reference")
E(TYPE_ERROR_STRING, TYPE_ERROR, "string") E(TYPE_ERROR_STRING, TYPE_ERROR, "string")
E(TYPE_ERROR_TEXT, TYPE_ERROR, "text") E(TYPE_ERROR_TEXT, TYPE_ERROR, "text")
E(TYPE_ERROR_UBYTE, TYPE_ERROR, "ubyte") E(TYPE_ERROR_UBYTE, TYPE_ERROR, "ubyte")
E(TYPE_ERROR_UCHAR, TYPE_ERROR, "uchar") E(TYPE_ERROR_UCHAR, TYPE_ERROR, "uchar")
E0(UNINSTANTIATION_ERROR, UNINSTANTIATION_ERROR_CLASS)
END_ERRORS(); E0(UNINSTANTIATION_ERROR, UNINSTANTIATION_ERROR_CLASS)
END_ERRORS();

View File

@ -9,11 +9,11 @@ set (LIBRARY_PL
avl.yap avl.yap
bhash.yap bhash.yap
charsio.yap charsio.yap
clauses.yap
coinduction.yap coinduction.yap
dbqueues.yap dbqueues.yap
dbusage.yap dbusage.yap
dgraphs.yap dgraphs.yap
error.yap
exo_interval.yap exo_interval.yap
expand_macros.yap expand_macros.yap
gensym.yap gensym.yap
@ -70,6 +70,7 @@ add_subdirectory(regex)
add_subdirectory(rltree) add_subdirectory(rltree)
add_subdirectory(system) add_subdirectory(system)
add_subdirectory(tries) add_subdirectory(tries)
add_subdirectory(ytest)
add_custom_target (library SOURCES ${LIBRARY_PL} ) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} ) add_custom_target (library SOURCES ${LIBRARY_PL} ) # WORKING_DIRECTORY ${CMAKE_BINARY_DIR} )

View File

@ -1,4 +1,4 @@
/** s/**
* @file dbqueues.yap * @file dbqueues.yap
* @author VITOR SANTOS COSTA <vsc@VITORs-MBP.lan> * @author VITOR SANTOS COSTA <vsc@VITORs-MBP.lan>
* @date Tue Nov 17 15:01:49 2015 * @date Tue Nov 17 15:01:49 2015
@ -25,9 +25,9 @@ A library to implement queues of NB Terms
*/ */
:- unhide('$init_nb_queue'). :- unhide_atom('$init_nb_queue').
:- unhide('$nb_enqueue'). :- unhide_atom('$nb_enqueue').
:- unhide('$nb_dequeue'). :- unhide_atom('$nb_dequeue').
nb_enqueue(Name,El) :- var(Name), nb_enqueue(Name,El) :- var(Name),

View File

@ -1,324 +0,0 @@
% SWI emulation.
% written in an on-demand basis.
%% @defgroup swi Compatibility with SWI-Prolog and Other Prolog systems
/**
@defgroup System SWI Dialect Support
This library provides a number of SWI-Prolog builtins that are not by
default in YAP. This support is loaded with the
~~~~~
expects_dialect(swi)
~~~~~
command.
@{
*/
/** @pred time_file(+ _File_,- _Time_)
Unify the last modification time of _File_ with
_Time_. _Time_ is a floating point number expressing the seconds
elapsed since Jan 1, 1970.
*/
/** @pred concat_atom(+ _List_,- _Atom_)
_List_ is a list of atoms, integers or floating point numbers. Succeeds
if _Atom_ can be unified with the concatenated elements of _List_. If
_List_ has exactly 2 elements it is equivalent to `atom_concat/3`,
allowing for variables in the list.
*/
:- module(system, [concat_atom/2,
concat_atom/3,
read_clause/1,
chdir/1,
compile_aux_clauses/1,
convert_time/2,
convert_time/8,
'$declare_module'/5,
'$set_predicate_attribute'/3,
stamp_date_time/3,
date_time_stamp/2,
time_file/2,
flag/3,
require/1,
normalize_space/2,
current_flag/1
]).
:- reexport(library(charsio),[
write_to_chars/2,
read_from_chars/2
]).
:- reexport(library(lists),[append/2,
append/3,
delete/3,
member/2,
flatten/2,
intersection/3,
last/2,
memberchk/2,
max_list/2,
min_list/2,
nextto/3,
permutation/2,
reverse/2,
select/3,
selectchk/3,
sublist/2,
sumlist/2,
nth1/4,
nth0/4,
nth1/3,
nth0/3]).
:- reexport(library(apply),[maplist/2,
maplist/3,
maplist/4,
maplist/5,
include/3,
exclude/3,
partition/4,
partition/5
]).
:- reexport(library(system),
[datime/1,
mktime/2,
file_property/2,
delete_file/1]).
:- reexport(library(arg),
[genarg/3]).
:- reexport(library(apply_macros),
[]).
:- reexport(library(terms),
[subsumes/2,
subsumes_chk/2,
term_hash/2,
unifiable/3,
cyclic_term/1,
variant/2]).
:- use_module(library(error),[must_be/2]).
:- source.
:- style_check(all).
:- yap_flag(unknown,error).
:- yap_flag(open_expands_filename,false).
:- yap_flag(autoload,true).
:- set_prolog_flag(user_flags,silent).
% Time is given as a float in SWI-Prolog.
swi_get_time(FSecs) :- datime(Datime), mktime(Datime, Secs), FSecs is Secs*1.0.
goal_expansion(atom_concat(A,B),atomic_concat(A,B)).
/** @pred atom_concat(? _A1_,? _A2_,? _A12_) is iso
The predicate holds when the third argument unifies with an atom, and
the first and second unify with atoms such that their representations
concatenated are the representation for _A12_.
If _A1_ and _A2_ are unbound, the built-in will find all the atoms
that concatenated give _A12_.
*/
goal_expansion(atom_concat(A,B,C),atomic_concat(A,B,C)).
%goal_expansion(arg(A,_,_),_) :- nonvar(A), !, fail.
goal_expansion(arg(A,B,C),genarg(A,B,C)).
% make sure we also use
:- user:library_directory(X),
atom(X),
atom_concat([X,'/dialect/swi'],SwiDir),
\+ user:library_directory(SwiDir),
asserta(user:library_directory(SwiDir)),
fail
;
true.
:- multifile
user:file_search_path/2.
:- dynamic
user:file_search_path/2.
/** @pred concat_atom(? _List_,+ _Separator_,? _Atom_)
Creates an atom just like concat_atom/2, but inserts _Separator_
between each pair of atoms. For example:
~~~~~
?- concat_atom([gnu, gnat], ', ', A).
A = 'gnu, gnat'
~~~~~
(Unimplemented) This predicate can also be used to split atoms by
instantiating _Separator_ and _Atom_:
~~~~~
?- concat_atom(L, -, 'gnu-gnat').
L = [gnu, gnat]
~~~~~
*/
concat_atom([A|List], Separator, New) :- var(List), !,
atom_codes(Separator,[C]),
atom_codes(New, NewChars),
split_atom_by_chars(NewChars,C,L,L,A,List).
concat_atom(List, Separator, New) :-
add_separator_to_list(List, Separator, NewList),
atomic_concat(NewList, New).
split_atom_by_chars([],_,[],L,A,[]):-
atom_codes(A,L).
split_atom_by_chars([C|NewChars],C,[],L,A,[NA|Atoms]) :- !,
atom_codes(A,L),
split_atom_by_chars(NewChars,C,NL,NL,NA,Atoms).
split_atom_by_chars([C1|NewChars],C,[C1|LF],LAtom,Atom,Atoms) :-
split_atom_by_chars(NewChars,C,LF,LAtom,Atom,Atoms).
add_separator_to_list([], _, []).
add_separator_to_list([T], _, [T]) :- !.
add_separator_to_list([H|T], Separator, [H,Separator|NT]) :-
add_separator_to_list(T, Separator, NT).
concat_atom(List, New) :-
atomic_concat(List, New).
bindings_message(V) -->
{ cvt_bindings(V, Bindings) },
prolog:message(query(_YesNo,Bindings)), !.
cvt_bindings([],[]).
cvt_bindings([[Name|Value]|L],[AName=Value|Bindings]) :-
atom_codes(AName, Name),
cvt_bindings(L,Bindings).
/** @pred chdir(+ _Dir_)
Compatibility predicate. New code should use working_directory/2.
*/
chdir(X) :- cd(X).
%% convert_time(+Stamp, -String)
%
% Convert a time-stamp as obtained though get_time/1 into a textual
% representation using the C-library function ctime(). The value is
% returned as a SWI-Prolog string object (see section 4.23). See
% also convert_time/8.
%
% @deprecated Use format_time/3.
convert_time(Stamp, String) :-
format_time(string(String), '%+', Stamp).
%% convert_time(+Stamp, -Y, -Mon, -Day, -Hour, -Min, -Sec, -MilliSec)
%
% Convert a time stamp, provided by get_time/1, time_file/2,
% etc. Year is unified with the year, Month with the month number
% (January is 1), Day with the day of the month (starting with 1),
% Hour with the hour of the day (0--23), Minute with the minute
% (0--59). Second with the second (0--59) and MilliSecond with the
% milliseconds (0--999). Note that the latter might not be accurate
% or might always be 0, depending on the timing capabilities of the
% system. See also convert_time/2.
%
% @deprecated Use stamp_date_time/3.
convert_time(Stamp, Y, Mon, Day, Hour, Min, Sec, MilliSec) :-
stamp_date_time(Stamp,
date(Y, Mon, Day,
Hour, Min, FSec,
_, _, _),
local),
Sec is integer(float_integer_part(FSec)),
MilliSec is integer(float_fractional_part(FSec)*1000).
compile_aux_clauses([]).
compile_aux_clauses([(:- G)|Cls]) :- !,
prolog_load_context(module, M),
once(M:G),
compile_aux_clauses(Cls).
compile_aux_clauses([Cl|Cls]) :-
prolog_load_context(module, M),
assert_static(M:Cl),
compile_aux_clauses(Cls).
flag(Key, Old, New) :-
recorded(Key, Old, R), !,
(
Old \== New
->
erase(R),
recorda(Key, New, _)
;
true
).
flag(Key, 0, New) :-
functor(Key, N, Ar),
functor(K, N, Ar),
assert(flag(K)),
recorda(K, New, _).
current_flag(Key) :-
swi:flag(Key).
require(F) :-
must_be(list, F),
% notice that this must be used as a declaration.
prolog_load_context(module, Mod),
required_predicates(F, Mod).
required_predicates([], _).
required_predicates([F|Fs], M) :-
required_predicate(F, M),
required_predicates(Fs, M).
required_predicate(Na/Ar, M) :-
functor(G, Na, Ar),
(
predicate_property(M:G, _) ->
true
;
autoloader:find_predicate(G, _)
).
/**
@}
*/

View File

@ -117,9 +117,6 @@ allowing for variables in the list.
cyclic_term/1, cyclic_term/1,
variant/2]). variant/2]).
:- use_module(library(error),[must_be/2]).
:- source. :- source.
:- style_check(all). :- style_check(all).

View File

@ -102,7 +102,7 @@ PL_put_blob(term_t t, void *blob, size_t len, PL_blob_t *type)
if (type->acquire) { if (type->acquire) {
type->acquire(AtomToSWIAtom(AbsAtom(ae))); type->acquire(AtomToSWIAtom(AbsAtom(ae)));
} }
Yap_PutInSlot(t, MkAtomTerm(AbsAtom(ae)) PASS_REGS); Yap_PutInSlot(t, MkAtomTerm(AbsAtom(ae)));
return ret; return ret;
} }

View File

@ -371,7 +371,7 @@ X_API void PL_reset_term_refs(term_t after)
{ {
CACHE_REGS CACHE_REGS
term_t new = Yap_NewSlots(1); term_t new = Yap_NewSlots(1);
Yap_RecoverSlots(after-new, new PASS_REGS); Yap_RecoverSlots(after-new, new);
} }
/** @} /** @}
@ -430,10 +430,10 @@ X_API int PL_get_arg(int index, term_t ts, term_t a)
if ( !IsApplTerm(t) ) { if ( !IsApplTerm(t) ) {
if (IsPairTerm(t)) { if (IsPairTerm(t)) {
if (index == 1){ if (index == 1){
Yap_PutInSlot(a,HeadOfTerm(t) PASS_REGS); Yap_PutInSlot(a,HeadOfTerm(t));
return 1; return 1;
} else if (index == 2) { } else if (index == 2) {
Yap_PutInSlot(a,TailOfTerm(t) PASS_REGS); Yap_PutInSlot(a,TailOfTerm(t));
return 1; return 1;
} }
} }
@ -444,7 +444,7 @@ X_API int PL_get_arg(int index, term_t ts, term_t a)
return 0; return 0;
if (index < 1 || index > ArityOfFunctor(f)) if (index < 1 || index > ArityOfFunctor(f))
return 0; return 0;
Yap_PutInSlot(a,ArgOfTerm(index, t) PASS_REGS); Yap_PutInSlot(a,ArgOfTerm(index, t));
return 1; return 1;
} }
} }
@ -792,8 +792,8 @@ X_API int PL_get_list(term_t ts, term_t h, term_t tl)
if (IsVarTerm(t) || !IsPairTerm(t) ) { if (IsVarTerm(t) || !IsPairTerm(t) ) {
return 0; return 0;
} }
Yap_PutInSlot(h,HeadOfTerm(t) PASS_REGS); Yap_PutInSlot(h,HeadOfTerm(t));
Yap_PutInSlot(tl,TailOfTerm(t) PASS_REGS); Yap_PutInSlot(tl,TailOfTerm(t));
return 1; return 1;
} }
@ -808,7 +808,7 @@ X_API int PL_get_head(term_t ts, term_t h)
if (!YAP_IsPairTerm(t) ) { if (!YAP_IsPairTerm(t) ) {
return 0; return 0;
} }
Yap_PutInSlot(h,YAP_HeadOfTerm(t) PASS_REGS); Yap_PutInSlot(h,YAP_HeadOfTerm(t));
return 1; return 1;
} }
@ -925,7 +925,7 @@ X_API int PL_get_tail(term_t ts, term_t tl)
if (!YAP_IsPairTerm(t) ) { if (!YAP_IsPairTerm(t) ) {
return 0; return 0;
} }
Yap_PutInSlot(tl,YAP_TailOfTerm(t) PASS_REGS); Yap_PutInSlot(tl,YAP_TailOfTerm(t) );
return 1; return 1;
} }
@ -1035,7 +1035,7 @@ X_API int PL_cons_functor(term_t d, functor_t f,...)
Functor ff = SWIFunctorToFunctor(f); Functor ff = SWIFunctorToFunctor(f);
if (IsAtomTerm((Term)ff)) { if (IsAtomTerm((Term)ff)) {
Yap_PutInSlot(d, (YAP_Term)f PASS_REGS); Yap_PutInSlot(d, (YAP_Term)f );
return TRUE; return TRUE;
} }
arity = ArityOfFunctor(ff); arity = ArityOfFunctor(ff);
@ -1056,7 +1056,7 @@ X_API int PL_cons_functor(term_t d, functor_t f,...)
Yap_unify(tmp[i],Yap_GetFromSlot(va_arg(ap, term_t))); Yap_unify(tmp[i],Yap_GetFromSlot(va_arg(ap, term_t)));
} }
va_end (ap); va_end (ap);
Yap_PutInSlot(d,t PASS_REGS); Yap_PutInSlot(d,t );
return TRUE; return TRUE;
} }
@ -1068,7 +1068,7 @@ X_API int PL_cons_functor_v(term_t d, functor_t f, term_t a0)
Functor ff = SWIFunctorToFunctor(f); Functor ff = SWIFunctorToFunctor(f);
if (IsAtomTerm((Term)ff)) { if (IsAtomTerm((Term)ff)) {
Yap_PutInSlot(d, (YAP_Term)f PASS_REGS); Yap_PutInSlot(d, (YAP_Term)f );
return TRUE; return TRUE;
} }
arity = ArityOfFunctor(ff); arity = ArityOfFunctor(ff);
@ -1088,7 +1088,7 @@ X_API int PL_cons_functor_v(term_t d, functor_t f, term_t a0)
Yap_unify(tmp[i] , Yap_GetFromSlot(a0 ) ); Yap_unify(tmp[i] , Yap_GetFromSlot(a0 ) );
a0++; a0++;
} }
Yap_PutInSlot(d,t PASS_REGS); Yap_PutInSlot(d,t );
return TRUE; return TRUE;
} }
@ -1101,14 +1101,14 @@ X_API int PL_cons_list(term_t d, term_t h, term_t t)
return FALSE; return FALSE;
} }
} }
Yap_PutInSlot(d,MkPairTerm(Yap_GetFromSlot(h),Yap_GetFromSlot(t)) PASS_REGS); Yap_PutInSlot(d,MkPairTerm(Yap_GetFromSlot(h),Yap_GetFromSlot(t)));
return true; return true;
} }
X_API int PL_put_atom(term_t t, atom_t a) X_API int PL_put_atom(term_t t, atom_t a)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,MkAtomTerm(SWIAtomToAtom(a)) PASS_REGS); Yap_PutInSlot(t,MkAtomTerm(SWIAtomToAtom(a)));
return TRUE; return TRUE;
} }
@ -1121,7 +1121,8 @@ X_API int PL_put_atom_chars(term_t t, const char *s)
return FALSE; return FALSE;
} }
Yap_AtomIncreaseHold(at); Yap_AtomIncreaseHold(at);
Yap_PutInSlot(t,MkAtomTerm(at) PASS_REGS); Yap_PutInSlot(t,MkAtomTerm(at));
return TRUE; return TRUE;
} }
@ -1134,14 +1135,14 @@ X_API int PL_put_atom_nchars(term_t t, size_t len, const char *s)
return FALSE; return FALSE;
} }
Yap_AtomIncreaseHold(at); Yap_AtomIncreaseHold(at);
Yap_PutInSlot(t,MkAtomTerm(at) PASS_REGS); Yap_PutInSlot(t,MkAtomTerm(at));
return TRUE; return TRUE;
} }
X_API int PL_put_float(term_t t, double fl) X_API int PL_put_float(term_t t, double fl)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,YAP_MkFloatTerm(fl) PASS_REGS); Yap_PutInSlot(t,YAP_MkFloatTerm(fl) );
return TRUE; return TRUE;
} }
@ -1152,7 +1153,7 @@ X_API int PL_put_functor(term_t t, functor_t f)
CACHE_REGS CACHE_REGS
if (IsAtomTerm((Term)ff)) { if (IsAtomTerm((Term)ff)) {
Yap_PutInSlot(t,(Term)ff PASS_REGS); Yap_PutInSlot(t,(Term)ff);
} else { } else {
arity = ArityOfFunctor(ff); arity = ArityOfFunctor(ff);
if (Unsigned(HR)+arity > Unsigned(ASP)-CreepFlag) { if (Unsigned(HR)+arity > Unsigned(ASP)-CreepFlag) {
@ -1160,10 +1161,9 @@ X_API int PL_put_functor(term_t t, functor_t f)
return FALSE; return FALSE;
} }
} }
if (arity == 2 && ff == FunctorDot) if (arity == 2 && ff == FunctorDot){
Yap_PutInSlot(t,YAP_MkNewPairTerm() PASS_REGS); } else
else Yap_PutInSlot(t,YAP_MkNewApplTerm((YAP_Functor)ff,arity) );
Yap_PutInSlot(t,YAP_MkNewApplTerm((YAP_Functor)ff,arity) PASS_REGS);
} }
return TRUE; return TRUE;
} }
@ -1171,14 +1171,14 @@ X_API int PL_put_functor(term_t t, functor_t f)
X_API int PL_put_integer(term_t t, long n) X_API int PL_put_integer(term_t t, long n)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,YAP_MkIntTerm(n) PASS_REGS); Yap_PutInSlot(t,YAP_MkIntTerm(n));
return TRUE; return TRUE;
} }
X_API int PL_put_boolean(term_t t, uintptr_t n) X_API int PL_put_boolean(term_t t, uintptr_t n)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,(n==0?TermFalse:TermTrue) PASS_REGS); Yap_PutInSlot(t,(n==0?TermFalse:TermTrue));
return TRUE; return TRUE;
} }
@ -1186,7 +1186,7 @@ X_API int PL_put_int64(term_t t, int64_t n)
{ {
CACHE_REGS CACHE_REGS
#if SIZEOF_INT_P==8 #if SIZEOF_INT_P==8
Yap_PutInSlot(t,MkIntegerTerm(n) PASS_REGS); Yap_PutInSlot(t,MkIntegerTerm(n) );
return TRUE; return TRUE;
#elif USE_GMP #elif USE_GMP
char s[64]; char s[64];
@ -1221,21 +1221,21 @@ X_API int PL_put_int64(term_t t, int64_t n)
X_API int PL_put_intptr(term_t t, intptr_t n) X_API int PL_put_intptr(term_t t, intptr_t n)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,YAP_MkIntTerm(n) PASS_REGS); Yap_PutInSlot(t,YAP_MkIntTerm(n));
return TRUE; return TRUE;
} }
X_API int PL_put_uintptr(term_t t, uintptr_t n) X_API int PL_put_uintptr(term_t t, uintptr_t n)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,YAP_MkIntTerm(n) PASS_REGS); Yap_PutInSlot(t,YAP_MkIntTerm(n) );
return TRUE; return TRUE;
} }
X_API int PL_put_list(term_t t) X_API int PL_put_list(term_t t)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,YAP_MkNewPairTerm() PASS_REGS); Yap_PutInSlot(t,YAP_MkNewPairTerm() );
if (Unsigned(HR) > Unsigned(ASP)-CreepFlag) { if (Unsigned(HR) > Unsigned(ASP)-CreepFlag) {
if (!do_gc(0)) { if (!do_gc(0)) {
return FALSE; return FALSE;
@ -1252,14 +1252,14 @@ X_API int PL_put_list_chars(term_t t, const char *s)
if (LOCAL_Error_TYPE && !Yap_SWIHandleError( "PL_put_string_nchars" )) if (LOCAL_Error_TYPE && !Yap_SWIHandleError( "PL_put_string_nchars" ))
return FALSE; return FALSE;
} }
Yap_PutInSlot(t, nt PASS_REGS); Yap_PutInSlot(t, nt);
return TRUE; return TRUE;
} }
X_API void PL_put_nil(term_t t) X_API void PL_put_nil(term_t t)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,TermNil PASS_REGS); Yap_PutInSlot(t,TermNil);
} }
/* void PL_put_pointer(term_t -t, void *ptr) /* void PL_put_pointer(term_t -t, void *ptr)
@ -1269,7 +1269,7 @@ X_API int PL_put_pointer(term_t t, void *ptr)
{ {
CACHE_REGS CACHE_REGS
YAP_Term tptr = YAP_MkIntTerm((YAP_Int)ptr); YAP_Term tptr = YAP_MkIntTerm((YAP_Int)ptr);
Yap_PutInSlot(t,tptr PASS_REGS); Yap_PutInSlot(t,tptr );
return TRUE; return TRUE;
} }
@ -1282,7 +1282,7 @@ X_API int PL_put_string_chars(term_t t, const char *chars)
if (LOCAL_Error_TYPE && !Yap_SWIHandleError( "PL_putPL_put_string_chars" )) if (LOCAL_Error_TYPE && !Yap_SWIHandleError( "PL_putPL_put_string_chars" ))
return FALSE; return FALSE;
} }
Yap_PutInSlot(t, nt PASS_REGS); Yap_PutInSlot(t, nt);
return TRUE; return TRUE;
} }
@ -1295,21 +1295,21 @@ X_API int PL_put_string_nchars(term_t t, size_t len, const char *chars)
if (LOCAL_Error_TYPE && !Yap_SWIHandleError( "PL_putPL_put_string_chars" )) if (LOCAL_Error_TYPE && !Yap_SWIHandleError( "PL_putPL_put_string_chars" ))
return FALSE; return FALSE;
} }
Yap_PutInSlot(t, nt PASS_REGS); Yap_PutInSlot(t, nt);
return TRUE; return TRUE;
} }
X_API int PL_put_term(term_t d, term_t s) X_API int PL_put_term(term_t d, term_t s)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(d,Yap_GetFromSlot(s ) PASS_REGS); Yap_PutInSlot(d,Yap_GetFromSlot(s ) );
return TRUE; return TRUE;
} }
X_API int PL_put_variable(term_t t) X_API int PL_put_variable(term_t t)
{ {
CACHE_REGS CACHE_REGS
Yap_PutInSlot(t,MkVarTerm() PASS_REGS); Yap_PutInSlot(t,MkVarTerm());
return TRUE; return TRUE;
} }
@ -1518,8 +1518,8 @@ X_API int PL_unify_list(term_t tt, term_t h, term_t tail)
} else if (!IsPairTerm(t)) { } else if (!IsPairTerm(t)) {
return FALSE; return FALSE;
} }
Yap_PutInSlot(h,HeadOfTerm(t) PASS_REGS); Yap_PutInSlot(h,HeadOfTerm(t));
Yap_PutInSlot(tail,TailOfTerm(t) PASS_REGS); Yap_PutInSlot(tail,TailOfTerm(t) );
return TRUE; return TRUE;
} }
@ -2207,7 +2207,7 @@ PL_recorded_external
Term t = Yap_ImportTerm((void *)tp); Term t = Yap_ImportTerm((void *)tp);
if (t == 0) if (t == 0)
return FALSE; return FALSE;
Yap_PutInSlot(ts, t PASS_REGS); Yap_PutInSlot(ts, t );
return TRUE; return TRUE;
} }
@ -2234,7 +2234,7 @@ PL_recorded(record_t db, term_t ts)
Term t = YAP_Recorded((void *)db); Term t = YAP_Recorded((void *)db);
if (t == ((CELL)0)) if (t == ((CELL)0))
return FALSE; return FALSE;
Yap_PutInSlot(ts,t PASS_REGS); Yap_PutInSlot(ts,t );
return TRUE; return TRUE;
} }
@ -2311,7 +2311,7 @@ PL_exception(qid_t q)
if (YAP_GoalHasException(&t)) { if (YAP_GoalHasException(&t)) {
CACHE_REGS CACHE_REGS
term_t to = Yap_NewSlots(1); term_t to = Yap_NewSlots(1);
Yap_PutInSlot(to,t PASS_REGS); Yap_PutInSlot(to,t );
return to; return to;
} else { } else {
return 0L; return 0L;
@ -2391,7 +2391,7 @@ PL_strip_module(term_t raw, module_t *m, term_t plain)
if (!t) if (!t)
return FALSE; return FALSE;
*m = Yap_GetModuleEntry(m0); *m = Yap_GetModuleEntry(m0);
Yap_PutInSlot(plain, t PASS_REGS); Yap_PutInSlot(plain, t );
return TRUE; return TRUE;
} }

View File

@ -15,11 +15,22 @@
%% %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- module( expand_macros,
[compile_aux/2,
pred_name/4,
transformation_id/1,
allowed_expansion/1,
allowed_module/2] ).
:- use_module(library(lists), [append/3]). :- use_module(library(lists), [append/3]).
:- use_module(library(charsio), [format_to_chars/3, read_from_chars/2]). :- use_module(library(charsio), [format_to_chars/3, read_from_chars/2]).
:- use_module(library(error), [must_be/2]). :- use_module(library(error), [must_be/2]).
:- use_module(library(occurs), [sub_term/2]). :- use_module(library(occurs), [sub_term/2]).
:- multifile allowed_module/2.
:- dynamic number_of_expansions/1. :- dynamic number_of_expansions/1.
number_of_expansions(0). number_of_expansions(0).
@ -32,15 +43,18 @@ number_of_expansions(0).
compile_aux([Clause|Clauses], Module) :- compile_aux([Clause|Clauses], Module) :-
% compile the predicat declaration if needed % compile the predicat declaration if needed
( Clause = (Head :- _) (
; Clause = Head ), Clause = (Head :- _)
;
Clause = Head
),
!, !,
functor(Head, F, N), functor(Head, F, N),
( current_predicate(Module:F/N) ( current_predicate(Module:F/N)
-> ->
true true
; ;
% format("*** Creating auxiliary predicate ~q~n", [F/N]), % format'*** Creating auxiliary predicate ~q~n', [F/N]),
% checklist(portray_clause, [Clause|Clauses]), % checklist(portray_clause, [Clause|Clauses]),
compile_term([Clause|Clauses], Module) compile_term([Clause|Clauses], Module)
). ).
@ -84,15 +98,17 @@ harmless_dcgexception(instantiation_error). % ex: phrase(([1],x:X,[3]),L)
harmless_dcgexception(type_error(callable,_)). % ex: phrase(27,L) harmless_dcgexception(type_error(callable,_)). % ex: phrase(27,L)
'$expand':allowed_expansion(QExpand) :- allowed_expansion(QExpand) :-
strip_module(QExpand, Mod, Pred), strip_module(QExpand, Mod, Pred),
goal_expansion_allowed(Pred, Mod). goal_expansion_allowed(Pred, Mod).
goal_expansion_allowed(Pred, Mod) :- goal_expansion_allowed(Pred, Mod) :-
allowed_module(Pred,Mod), allowed_module(Pred,Mod),
once( prolog_load_context(_, _) ), % make sure we are compiling. once( prolog_load_context(_, _) ), % make sure we are compiling.
\+ current_prolog_flag(xref, true).
allowed_module(checklist(_,_),expand_macros). allowed_module(checklist(_,_),expand_macros).
allowed_module(checklist(_,_),apply_macros). allowed_module(checklist(_,_),apply_macros).
allowed_module(checklist(_,_),maplist). allowed_module(checklist(_,_),maplist).
@ -147,5 +163,3 @@ allowed_module(checknodes(_,_),maplist).
allowed_module(sumnodes(_,_,_,_),expand_macros). allowed_module(sumnodes(_,_,_,_),expand_macros).
allowed_module(sumnodes(_,_,_,_),apply_macros). allowed_module(sumnodes(_,_,_,_),apply_macros).
allowed_module(sumnodes(_,_,_,_),maplist). allowed_module(sumnodes(_,_,_,_),maplist).
allowed_module(phrase(_,_),_).
allowed_module(phrase(_,_,_),_).

View File

@ -2,10 +2,10 @@
* @file hacks.yap * @file hacks.yap
* @author VITOR SANTOS COSTA <vsc@VITORs-MBP.lan> * @author VITOR SANTOS COSTA <vsc@VITORs-MBP.lan>
* @date Tue Nov 17 19:00:25 2015 * @date Tue Nov 17 19:00:25 2015
* *
* @brief Prolog hacking * @brief Prolog hacking
* *
* *
*/ */
:- module(yap_hacks, [ :- module(yap_hacks, [
@ -21,7 +21,7 @@
enable_interrupts/0, enable_interrupts/0,
disable_interrupts/0, disable_interrupts/0,
virtual_alarm/3, virtual_alarm/3,
fully_strip_module/3, fully_strip_module/3,
context_variables/1 context_variables/1
]). ]).
@ -31,7 +31,7 @@
* *
* Manipulate the Prolog stacks, including setting and resetting * Manipulate the Prolog stacks, including setting and resetting
* choice-points. * choice-points.
* *
*/ */
@ -68,5 +68,3 @@ virtual_alarm(Interval.USecs, Goal, Left.LUSecs) :-
fully_strip_module(T,M,S) :- fully_strip_module(T,M,S) :-
'$hacks':fully_strip_module(T,M,S). '$hacks':fully_strip_module(T,M,S).

View File

@ -2,10 +2,10 @@
* @file library/lists.yap * @file library/lists.yap
* @author Bob Welham, Lawrence Byrd, and R. A. O'Keefe. Contributions from Vitor Santos Costa, Jan Wielemaker and others. * @author Bob Welham, Lawrence Byrd, and R. A. O'Keefe. Contributions from Vitor Santos Costa, Jan Wielemaker and others.
* @date 1999 * @date 1999
* *
* @brief List Manipulation Predicates * @brief List Manipulation Predicates
* *
* *
*/ */
% This file has been included as an YAP library by Vitor Santos Costa, 1999 % This file has been included as an YAP library by Vitor Santos Costa, 1999
@ -48,55 +48,51 @@
]). ]).
:- use_module(library(error),
[must_be/2]).
/** @defgroup lists List Manipulation /** @defgroup lists List Manipulation
@ingroup library @ingroup library
@{ @{
The following list manipulation routines are available once included The following list manipulation routines are available once included
with the `use_module(library(lists))` command. with the `use_module(library(lists))` command.
*/ */
/** @pred list_concat(+ _Lists_,? _List_) /** @pred list_concat(+ _Lists_,? _List_)
True when _Lists_ is a list of lists and _List_ is the True when _Lists_ is a list of lists and _List_ is the
concatenation of _Lists_. concatenation of _Lists_.
*/ */
/** @pred max_list(? _Numbers_, ? _Max_) /** @pred max_list(? _Numbers_, ? _Max_)
True when _Numbers_ is a list of numbers, and _Max_ is the maximum. True when _Numbers_ is a list of numbers, and _Max_ is the maximum.
*/ */
/** @pred min_list(? _Numbers_, ? _Min_) /** @pred min_list(? _Numbers_, ? _Min_)
True when _Numbers_ is a list of numbers, and _Min_ is the minimum. True when _Numbers_ is a list of numbers, and _Min_ is the minimum.
*/ */
/** @pred nth(? _N_, ? _List_, ? _Elem_) /** @pred nth(? _N_, ? _List_, ? _Elem_)
The same as nth1/3. The same as nth1/3.
*/ */
/** @pred nth(? _N_, ? _List_, ? _Elem_, ? _Rest_) /** @pred nth(? _N_, ? _List_, ? _Elem_, ? _Rest_)
Same as `nth1/4`. Same as `nth1/4`.
*/ */
/** @pred nth0(? _N_, ? _List_, ? _Elem_) /** @pred nth0(? _N_, ? _List_, ? _Elem_)
True when _Elem_ is the Nth member of _List_, True when _Elem_ is the Nth member of _List_,
@ -105,7 +101,7 @@ N elements and unify _Elem_ with the next.) It can only be used to
select a particular element given the list and index. For that select a particular element given the list and index. For that
task it is more efficient than member/2 task it is more efficient than member/2
*/ */
/** @pred nth0(? _N_, ? _List_, ? _Elem_, ? _Rest_) /** @pred nth0(? _N_, ? _List_, ? _Elem_, ? _Rest_)
@ -117,9 +113,9 @@ it yields _List_, e.g. `nth0(2, List, c, [a,b,d,e])` unifies List with
`[a,b,c,d,e]`. `nth/4` is the same except that it counts from 1. `nth0/4` `[a,b,c,d,e]`. `nth/4` is the same except that it counts from 1. `nth0/4`
can be used to insert _Elem_ after the Nth element of _Rest_. can be used to insert _Elem_ after the Nth element of _Rest_.
*/ */
/** @pred nth1(+ _Index_,? _List_,? _Elem_) /** @pred nth1(+ _Index_,? _List_,? _Elem_)
Succeeds when the _Index_-th element of _List_ unifies with Succeeds when the _Index_-th element of _List_ unifies with
@ -130,15 +126,15 @@ instantiated to atoms or integers. The environment variable will be
passed to `shell/[0-2]` and can be requested using `getenv/2`. passed to `shell/[0-2]` and can be requested using `getenv/2`.
They also influence expand_file_name/2. They also influence expand_file_name/2.
*/ */
/** @pred nth1(? _N_, ? _List_, ? _Elem_) /** @pred nth1(? _N_, ? _List_, ? _Elem_)
The same as nth0/3, except that it counts from The same as nth0/3, except that it counts from
1, that is `nth(1, [H|_], H)`. 1, that is `nth(1, [H|_], H)`.
*/ */
/** @pred nth1(? _N_, ? _List_, ? _Elem_, ? _Rest_) /** @pred nth1(? _N_, ? _List_, ? _Elem_, ? _Rest_)
@ -149,33 +145,33 @@ insert _Elem_ before the Nth (counting from 1) element of
_Rest_, when it yields _List_, e.g. `nth(3, List, c, [a,b,d,e])` unifies List with `[a,b,c,d,e]`. `nth/4` _Rest_, when it yields _List_, e.g. `nth(3, List, c, [a,b,d,e])` unifies List with `[a,b,c,d,e]`. `nth/4`
can be used to insert _Elem_ after the Nth element of _Rest_. can be used to insert _Elem_ after the Nth element of _Rest_.
*/ */
/** @pred numlist(+ _Low_, + _High_, + _List_) /** @pred numlist(+ _Low_, + _High_, + _List_)
If _Low_ and _High_ are integers with _Low_ =< If _Low_ and _High_ are integers with _Low_ =<
_High_, unify _List_ to a list `[Low, Low+1, ...High]`. See _High_, unify _List_ to a list `[Low, Low+1, ...High]`. See
also between/3. also between/3.
*/ */
/** @pred permutation(+ _List_,? _Perm_) /** @pred permutation(+ _List_,? _Perm_)
True when _List_ and _Perm_ are permutations of each other. True when _List_ and _Perm_ are permutations of each other.
*/ */
/** @pred remove_duplicates(+ _List_, ? _Pruned_) /** @pred remove_duplicates(+ _List_, ? _Pruned_)
Removes duplicated elements from _List_. Beware: if the _List_ has Removes duplicated elements from _List_. Beware: if the _List_ has
non-ground elements, the result may surprise you. non-ground elements, the result may surprise you.
*/ */
/** @pred same_length(? _List1_, ? _List2_) /** @pred same_length(? _List1_, ? _List2_)
True when _List1_ and _List2_ are both lists and have the same number True when _List1_ and _List2_ are both lists and have the same number
@ -192,7 +188,7 @@ in which case the arguments will be bound to lists of length 0, 1, 2, ...
% %
% Concatenate a list of lists. Is true if Lists is a list of % Concatenate a list of lists. Is true if Lists is a list of
% lists, and List is the concatenation of these lists. % lists, and List is the concatenation of these lists.
% %
% @param ListOfLists must be a list of -possibly- partial lists % @param ListOfLists must be a list of -possibly- partial lists
append(ListOfLists, List) :- append(ListOfLists, List) :-
@ -207,7 +203,7 @@ append_([L1,L2|[L3|LL]], L) :-
append(L1,L2,LI), append(L1,L2,LI),
append_([LI|[L3|LL]],L). append_([LI|[L3|LL]],L).
/** @pred last(+ _List_,? _Last_) /** @pred last(+ _List_,? _Last_)
True when _List_ is a list and _Last_ is identical to its last element. True when _List_ is a list and _Last_ is identical to its last element.
@ -282,7 +278,7 @@ generate_nth(I, IN, [_|List], El) :-
% nth0(+N, ?List, ?Elem, ?Rest) unifies Elem with the Nth element of List, % nth0(+N, ?List, ?Elem, ?Rest) unifies Elem with the Nth element of List,
% counting from 0, and Rest with the other elements. It can be used % counting from 0, and Rest with the other elements. It can be used
% to select the Nth element of List (yielding Elem and Rest), or to % to select the Nth element of List (yielding Elem and Rest), or to
% insert Elem before the Nth (counting from 1) element of Rest, when % insert Elem before the Nth (counting from 1) element of Rest, when
% it yields List, e.g. nth0(2, List, c, [a,b,d,e]) unifies List with % it yields List, e.g. nth0(2, List, c, [a,b,d,e]) unifies List with
% [a,b,c,d,e]. nth is the same except that it counts from 1. nth % [a,b,c,d,e]. nth is the same except that it counts from 1. nth
@ -348,7 +344,7 @@ permutation(List, [First|Perm]) :-
% prefix(Part, Whole) iff Part is a leading substring of Whole % prefix(Part, Whole) iff Part is a leading substring of Whole
prefix([], _). prefix([], _).
prefix([Elem | Rest_of_part], [Elem | Rest_of_whole]) :- prefix([Elem | Rest_of_part], [Elem | Rest_of_whole]) :-
prefix(Rest_of_part, Rest_of_whole). prefix(Rest_of_part, Rest_of_whole).
% remove_duplicates(List, Pruned) % remove_duplicates(List, Pruned)
@ -385,7 +381,7 @@ same_length([_|List1], [_|List2]) :-
same_length(List1, List2). same_length(List1, List2).
/** @pred selectchk(? _Element_, ? _List_, ? _Residue_) /** @pred selectchk(? _Element_, ? _List_, ? _Residue_)
Semi-deterministic selection from a list. Steadfast: defines as Semi-deterministic selection from a list. Steadfast: defines as
@ -402,7 +398,7 @@ selectchk(Elem, List, Rest) :-
/** @pred select(? _Element_, ? _List_, ? _Residue_) /** @pred select(? _Element_, ? _List_, ? _Residue_)
True when _Set_ is a list, _Element_ occurs in _List_, and True when _Set_ is a list, _Element_ occurs in _List_, and
@ -444,7 +440,7 @@ substitute2([X0|XList], X, Y, [Y|YList]) :-
substitute2([X0|XList], X, Y, [X0|YList]) :- substitute2([X0|XList], X, Y, [X0|YList]) :-
substitute2(XList, X, Y, YList). substitute2(XList, X, Y, YList).
/** @pred suffix(? _Suffix_, ? _List_) /** @pred suffix(? _Suffix_, ? _List_)
Holds when `append(_,Suffix,List)` holds. Holds when `append(_,Suffix,List)` holds.
*/ */
@ -452,14 +448,14 @@ suffix(Suffix, Suffix).
suffix(Suffix, [_|List]) :- suffix(Suffix, [_|List]) :-
suffix(Suffix,List). suffix(Suffix,List).
/** @pred sumlist(? _Numbers_, ? _Total_) /** @pred sumlist(? _Numbers_, ? _Total_)
True when _Numbers_ is a list of integers, and _Total_ is their True when _Numbers_ is a list of integers, and _Total_ is their
sum. The same as sum_list/2, please do use sum_list/2 sum. The same as sum_list/2, please do use sum_list/2
instead. instead.
*/ */
sumlist(Numbers, Total) :- sumlist(Numbers, Total) :-
sumlist(Numbers, 0, Total). sumlist(Numbers, 0, Total).
@ -471,7 +467,7 @@ True when _Numbers_ is a list of numbers, and _Total_ is the sum of their tota
sum_list(Numbers, SoFar, Total) :- sum_list(Numbers, SoFar, Total) :-
sumlist(Numbers, SoFar, Total). sumlist(Numbers, SoFar, Total).
/** @pred sum_list(? _Numbers_, ? _Total_) /** @pred sum_list(? _Numbers_, ? _Total_)
True when _Numbers_ is a list of numbers, and _Total_ is their sum. True when _Numbers_ is a list of numbers, and _Total_ is their sum.
@ -500,7 +496,7 @@ list_concat([H|T], [H|Lf], Li) :-
/** @pred flatten(+ _List_, ? _FlattenedList_) /** @pred flatten(+ _List_, ? _FlattenedList_)
Flatten a list of lists _List_ into a single list Flatten a list of lists _List_ into a single list
@ -515,19 +511,19 @@ no
~~~~~ ~~~~~
*/ */
flatten(X,Y) :- flatten_list(X,Y,[]). flatten(X,Y) :- flatten_list(X,Y,[]).
flatten_list(V) --> {var(V)}, !, [V]. flatten_list(V) --> {var(V)}, !, [V].
flatten_list([]) --> !. flatten_list([]) --> !.
flatten_list([H|T]) --> !, flatten_list(H),flatten_list(T). flatten_list([H|T]) --> !, flatten_list(H),flatten_list(T).
flatten_list(H) --> [H]. flatten_list(H) --> [H].
max_list([H|L],Max) :- max_list([H|L],Max) :-
max_list(L,H,Max). max_list(L,H,Max).
max_list([],Max,Max). max_list([],Max,Max).
max_list([H|L],Max0,Max) :- max_list([H|L],Max0,Max) :-
( (
H > Max0 H > Max0
-> ->
max_list(L,H,Max) max_list(L,H,Max)
; ;
@ -540,7 +536,7 @@ min_list([H|L],Max) :-
min_list([],Max,Max). min_list([],Max,Max).
min_list([H|L],Max0,Max) :- min_list([H|L],Max0,Max) :-
( (
H < Max0 H < Max0
-> ->
min_list(L, H, Max) min_list(L, H, Max)
; ;
@ -548,10 +544,10 @@ min_list([H|L],Max0,Max) :-
). ).
%% numlist(+Low, +High, -List) is semidet. %% numlist(+Low, +High, -List) is semidet.
% %
% List is a list [Low, Low+1, ... High]. Fails if High < Low.% % List is a list [Low, Low+1, ... High]. Fails if High < Low.%
% %
% @error type_error(integer, Low) % @error type_error(integer, Low)
% @error type_error(integer, High) % @error type_error(integer, High)
numlist(L, U, Ns) :- numlist(L, U, Ns) :-
@ -566,7 +562,7 @@ numlist_(L, U, [L|Ns]) :-
numlist_(L2, U, Ns). numlist_(L2, U, Ns).
/** @pred intersection(+ _Set1_, + _Set2_, + _Set3_) /** @pred intersection(+ _Set1_, + _Set2_, + _Set3_)
Succeeds if _Set3_ unifies with the intersection of _Set1_ and Succeeds if _Set3_ unifies with the intersection of _Set1_ and
@ -574,14 +570,14 @@ Succeeds if _Set3_ unifies with the intersection of _Set1_ and
need not be ordered. need not be ordered.
The code was copied from SWI-Prolog's list library. The code was copied from SWI-Prolog's list library.
*/ */
% copied from SWI lists library. % copied from SWI lists library.
intersection([], _, []) :- !. intersection([], _, []) :- !.
intersection([X|T], L, Intersect) :- intersection([X|T], L, Intersect) :-
memberchk(X, L), !, memberchk(X, L), !,
Intersect = [X|R], Intersect = [X|R],
intersection(T, L, R). intersection(T, L, R).
intersection([_|T], L, R) :- intersection([_|T], L, R) :-
intersection(T, L, R). intersection(T, L, R).
@ -624,4 +620,4 @@ close_list([_|T]) :-
close_list(T). close_list(T).
%% @} %% @}

View File

@ -3,10 +3,10 @@
* @author Lawrence Byrd + Richard A. O'Keefe, VITOR SANTOS COSTA <vsc@VITORs-MBP.lan> * @author Lawrence Byrd + Richard A. O'Keefe, VITOR SANTOS COSTA <vsc@VITORs-MBP.lan>
* @author : E. Alphonse from code by Joachim Schimpf, Jan Wielemaker, Vitor Santos Costa * @author : E. Alphonse from code by Joachim Schimpf, Jan Wielemaker, Vitor Santos Costa
* @date 4 August 1984 and Ken Johnson 11-8-87 * @date 4 August 1984 and Ken Johnson 11-8-87
* *
* @brief Macros to apply a predicate to all elements of a list. * @brief Macros to apply a predicate to all elements of a list.
* *
* *
*/ */
:- module(maplist, :- module(maplist,
@ -156,7 +156,6 @@ triple. See the example above.
:- use_module(library(maputils)). :- use_module(library(maputils)).
:- use_module(library(lists), [append/3]). :- use_module(library(lists), [append/3]).
:- use_module(library(charsio), [format_to_chars/3, read_from_chars/2]). :- use_module(library(charsio), [format_to_chars/3, read_from_chars/2]).
:- use_module(library(error), [must_be/2]).
:- use_module(library(occurs), [sub_term/2]). :- use_module(library(occurs), [sub_term/2]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -1245,4 +1244,3 @@ goal_expansion(sumnodes(Meta, Term, AccIn, AccOut), Mod:Goal) :-
/** /**
@} @}
*/ */

View File

@ -20,10 +20,10 @@
* @author original code from RA O'Keefe. * @author original code from RA O'Keefe.
* @author VITOR SANTOS COSTA <vsc@VITORs-MBP.lan> * @author VITOR SANTOS COSTA <vsc@VITORs-MBP.lan>
* @date Wed Nov 18 00:05:21 2015 * @date Wed Nov 18 00:05:21 2015
* *
* @brief Integer Random Number Generator * @brief Integer Random Number Generator
* *
* *
*/ */
:- module(random, [ :- module(random, [
@ -54,13 +54,13 @@ In ROK's words: ``This is algorithm AS 183 from Applied Statistics. I also have
*/ */
/** @pred getrand(- _Key_) /** @pred getrand(- _Key_)
Unify _Key_ with a term of the form `rand(X,Y,Z)` describing the Unify _Key_ with a term of the form `rand(X,Y,Z)` describing the
current state of the random number generator. current state of the random number generator.
*/ */
@ -71,7 +71,7 @@ Unify _Number_ with a number in the range
integers then _NUMBER_ will also be an integer, otherwise integers then _NUMBER_ will also be an integer, otherwise
_NUMBER_ will be a floating-point number. _NUMBER_ will be a floating-point number.
*/ */
@ -85,34 +85,34 @@ The following routines produce random non-negative integers in the range
generated by this random number generator are repeatable. This generator generated by this random number generator are repeatable. This generator
was originally written by Allen Van Gelder and is based on Knuth Vol 2. was originally written by Allen Van Gelder and is based on Knuth Vol 2.
*/ */
/** @pred random(- _Number_) /** @pred random(- _Number_)
Unify _Number_ with a floating-point number in the range `[0...1)`. Unify _Number_ with a floating-point number in the range `[0...1)`.
*/ */
/** @pred randseq(+ _LENGTH_, + _MAX_, - _Numbers_) /** @pred randseq(+ _LENGTH_, + _MAX_, - _Numbers_)
Unify _Numbers_ with a list of _LENGTH_ unique random integers Unify _Numbers_ with a list of _LENGTH_ unique random integers
in the range `[1... _MAX_)`. in the range `[1... _MAX_)`.
*/ */
/** @pred randset(+ _LENGTH_, + _MAX_, - _Numbers_) /** @pred randset(+ _LENGTH_, + _MAX_, - _Numbers_)
Unify _Numbers_ with an ordered list of _LENGTH_ unique random Unify _Numbers_ with an ordered list of _LENGTH_ unique random
integers in the range `[1... _MAX_)`. integers in the range `[1... _MAX_)`.
*/ */
/** @pred setrand(+ _Key_) /** @pred setrand(+ _Key_)
Use a term of the form `rand(X,Y,Z)` to set a new state for the Use a term of the form `rand(X,Y,Z)` to set a new state for the
@ -126,7 +126,6 @@ random number generator. The integer `X` must be in the range
*/ */
:- use_module(library(pairs)). :- use_module(library(pairs)).
:- use_module(library(error)).
:- use_module(library(lists)). :- use_module(library(lists)).
@ -152,25 +151,25 @@ random(L, U, R) :-
). ).
/* There are two versions of this operation. /* There are two versions of this operation.
randset(K, N, S) randset(K, N, S)
generates a random set of K integers in the range 1..N. generates a random set of K integers in the range 1..N.
The result is an ordered list, such as setof might produce. The result is an ordered list, such as setof might produce.
randseq(K, N, L) randseq(K, N, L)
generates a random sequence of K integers, the order is as generates a random sequence of K integers, the order is as
random as we can make it. random as we can make it.
*/ */
randset(K, N, S) :- randset(K, N, S) :-
K >= 0, K >= 0,
K =< N, K =< N,
randset(K, N, [], S). randset(K, N, [], S).
randset(0, _, S, S) :- !. randset(0, _, S, S) :- !.
randset(K, N, Si, So) :- randset(K, N, Si, So) :-
random(X), random(X),
@ -181,13 +180,13 @@ randset(K, N, Si, So) :-
randset(K, N, Si, So) :- randset(K, N, Si, So) :-
M is N-1, M is N-1,
randset(K, M, Si, So). randset(K, M, Si, So).
randseq(K, N, S) :- randseq(K, N, S) :-
randseq(K, N, L, []), randseq(K, N, L, []),
keysort(L, R), keysort(L, R),
strip_keys(R, S). strip_keys(R, S).
randseq(0, _, S, S) :- !. randseq(0, _, S, S) :- !.
randseq(K, N, [Y-N|Si], So) :- randseq(K, N, [Y-N|Si], So) :-
random(X), random(X),
@ -199,8 +198,8 @@ randseq(K, N, [Y-N|Si], So) :-
randseq(K, N, Si, So) :- randseq(K, N, Si, So) :-
M is N-1, M is N-1,
randseq(K, M, Si, So). randseq(K, M, Si, So).
strip_keys([], []) :- !. strip_keys([], []) :- !.
strip_keys([_-K|L], [K|S]) :- strip_keys([_-K|L], [K|S]) :-
strip_keys(L, S). strip_keys(L, S).
@ -212,14 +211,10 @@ setrand(rand(X,Y,Z)) :-
X > 0, X > 0,
X < 30269, X < 30269,
Y > 0, Y > 0,
Y < 30307, Y < 30307,
Z > 0, Z > 0,
Z < 30323, Z < 30323,
setrand(X,Y,Z). setrand(X,Y,Z).
getrand(rand(X,Y,Z)) :- getrand(rand(X,Y,Z)) :-
getrand(X,Y,Z). getrand(X,Y,Z).

View File

@ -3,9 +3,13 @@
run_tests/0, run_tests/0,
test_mode/0, test_mode/0,
op(1150, fx, test), op(1150, fx, test),
op(999, xfx, returns)] ). op(995, xfx, given),
op(990, xfx, returns)] ).
:- use_module( clauses ). :- use_module( library(clauses) ).
:- use_module( library(maplist) ).
:- use_module( library(gensym) ).
:- use_module( library(lists) ).
:- multifile test/1. :- multifile test/1.
@ -17,37 +21,47 @@ user:term_expansion( test( (A, B) ), ytest:test( Lab, Cond, Done ) ) :-
info((A,B), Lab, Cond , Done ). info((A,B), Lab, Cond , Done ).
run_tests :- run_tests :-
run_test(_Lab), source_module(M),
run_test(_Lab,M),
fail. fail.
run_tests :- run_tests :-
show_bad. show_bad.
run_test(Lab) :- run_test(Lab, M) :-
current_module(M,M), test(Lab, (G returns Sols given Program ), Done),
ensure_ground( Done),
format('~w : ',[ Lab ]),
reset( Streams ),
assertall(Program, Refs),
conj2list( Sols, LSols ),
% trace,
catch( do_returns(M:G, LSols, Lab), Ball, end( Ball ) ),
shutdown( Streams, Refs ).
run_test(Lab,M) :-
test(Lab, (G returns Sols ), Done), test(Lab, (G returns Sols ), Done),
ground( Done), ensure_ground( Done),
format('~w : ',[ Lab ]), format('~w : ',[ Lab ]),
reset( Streams ), reset( Streams ),
conj2list( Sols, LSols ), conj2list( Sols, LSols ),
% trace, % trace,
catch( do_returns(M:G, LSols, Lab), Ball, end( Ball ) ), catch( do_returns(M:G, LSols, Lab), Ball, end( Ball ) ),
shutdown( Streams ). shutdown( Streams, _ ).
info((A,B), Lab, Cl, G) :- !, info((A,B), Lab, Cl, G) :- !,
info(A, Lab, Cl, G), info(A, Lab, Cl, G),
info(B, Lab, Cl, G). info(B, Lab, Cl, G).
info(A, _, _, _) :- var(A), !. info(A, _, _, _) :- var(A), !.
info(A returns B, _, (A returns B), g(_,ok)) :- !. info(A returns B, _, (A returns B), g(_,ok)) :- !.
info(A, A, _, g(ok,_)) :- primitive(A), !. info(A, A, _, g(ok,_)) :- primitive(A), !.
info(_A, _, _, _). info(_A, _, _, _).
do_returns(G0 , Sols0, Lab ) :- do_returns(G0 , Sols0, Lab ) :-
counter(I), counter(I),
fetch(I, Sols0, Pattern0, Next), fetch(I, Sols0, Pattern0, Next),
Pattern0 = ( V0 =@= Target0), Pattern0 = ( V0 =@= Target0 ),
copy_term(G0-V0, G-VGF), copy_term(G0-V0, G-VGF),
catch( answer(G, VGF, Target0, Lab, Sol) , Error, Sol = error(G, Error) ), catch( answer(G, VGF, Target0, Lab, Sol) , Error, Sol = error(G, Error) ),
step( _I, Sols, G0, Sol, Lab ), step( _I, Sols, G0, Sol, Lab ),
!. !.
answer(G, V, Target0, Lab, answer(G)) :- answer(G, V, Target0, Lab, answer(G)) :-
@ -56,7 +70,7 @@ answer(G, V, Target0, Lab, answer(G)) :-
-> ->
success(Lab, V) success(Lab, V)
; ;
failure(V, Target0, Lab) failure(V, Target0, Lab)
). ).
step( I, Sols , G0, Sol, Lab ) :- step( I, Sols , G0, Sol, Lab ) :-
@ -107,14 +121,14 @@ inc( I ) :-
nb_getval( counter,( I ) ), nb_getval( counter,( I ) ),
I1 is I+1, I1 is I+1,
nb_setval( counter,( I1 ) ). nb_setval( counter,( I1 ) ).
counter( I ) :- counter( I ) :-
nb_getval( counter,( I ) ). nb_getval( counter,( I ) ).
shutdown( _Streams ) :-
shutdown( _Streams, Refs ) :-
% close_io( Streams ). % close_io( Streams ).
true. maplist( erase, Refs ).
test_error( Ball, e( Ball ) ). test_error( Ball, e( Ball ) ).
@ -148,3 +162,13 @@ end(done) :-
end(Ball) :- end(Ball) :-
writeln( bad:Ball ). writeln( bad:Ball ).
assertall(Cls, REfs) :-
conj2list(Cls, LCls),
maplist( assert, LCls, Refs).
ensure_ground( g(Lab,Ok)) :-
ground(Ok),
gensym( tmp_, Lab ).
ensure_ground( g(Lab,Ok)) :-
ground(Ok),
ground(Lab).

View File

@ -1,3 +1,5 @@
:- [library(hacks)].
'$predicate_flags'(P, M, Flags0, Flags1) :- '$predicate_flags'(P, M, Flags0, Flags1) :-
var(Flags0), var(Flags0),
Flags0 == Flags1, Flags0 == Flags1,
@ -14,7 +16,7 @@
true true
; ;
Flags1 /\ 0x200000 =\= 0, Flags1 /\ 0x200000 =\= 0,
Flags0 /\ 0x200000 =\= 0 Flags0 /\ 0x200000 =\= 0
). ).
'$get_undefined_pred'(G,M,G,M0) :- '$get_undefined_pred'(G,M,G,M0) :-
@ -55,7 +57,6 @@ user:term_expansion( ( :- '$meta_predicate'( _ ) ), [] ).
user:goal_expansion(_:'_user_expand_goal'(A, M, B), user:user_expand_goal(A, M, B) ). user:goal_expansion(_:'_user_expand_goal'(A, M, B), user:user_expand_goal(A, M, B) ).
user_expand_goal(A, M, B) :- user_expand_goal(A, M, B) :-
( (
current_predicate(M:goal_expansion/2), current_predicate(M:goal_expansion/2),
@ -70,8 +71,8 @@ user:goal_expansion(prolog:'$meta_predicate'(N,M,A,D) , user:mt( N, M, A, D) ).
mt(N,M,A,D) :- mt(N,M,A,D) :-
functor(D,N,A), functor(D,N,A),
predicate_property(M:D, meta_predicate(D)). predicate_property(M:D, meta_predicate(D)).
'$full_clause_optimisation'(_H, _M, B, B). '$full_clause_optimisation'(_H, _M, B, B).
'$c_built_in'(G, _SM, _H, G). '$c_built_in'(G, _SM, _H, G).
@ -85,6 +86,4 @@ mt(N,M,A,D) :-
:- hide( expand_goal ). :- hide( expand_goal ).
:- include('pl/meta'). :- include(library(boot/meta)).

View File

@ -1,6 +1,6 @@
// //
// Fields are TAB spaced // Fields are TAB spaced
// Atoms are of the form A Name Normal,FullLookup String // Atoms are of the form A Name Normal,FullLookup String
// Functors are of the form F Name Atom Arity // Functors are of the form F Name Atom Arity
// Terms are of the form T FullName Atom // Terms are of the form T FullName Atom
// //
@ -25,6 +25,7 @@ A ArrayAccess F "$array_arg"
A ArrayOverflow N "array_overflow" A ArrayOverflow N "array_overflow"
A ArrayType N "array_type" A ArrayType N "array_type"
A Arrow N "->" A Arrow N "->"
A AttributedModule N "attributes_module"
A DoubleArrow N "-->" A DoubleArrow N "-->"
A Assert N ":-" A Assert N ":-"
A EmptyBrackets N "()" A EmptyBrackets N "()"
@ -514,6 +515,7 @@ F PermissionError PermissionError 3
F Plus Plus 2 F Plus Plus 2
F Portray Portray 1 F Portray Portray 1
F PrintMessage PrintMessage 2 F PrintMessage PrintMessage 2
F Procedure Procedure 5
F PrologConstraint Prolog 2 F PrologConstraint Prolog 2
F Query Query 1 F Query Query 1
F RecordedWithKey RecordedWithKey 6 F RecordedWithKey RecordedWithKey 6
@ -545,4 +547,3 @@ F UMinus Minus 1
F UPlus Plus 1 F UPlus Plus 1
F VBar VBar 2 F VBar VBar 2
F HiddenVar HiddenVar 1 F HiddenVar HiddenVar 1

View File

@ -25,193 +25,195 @@
// Restore... sets up call to RestoreFunc // Restore... sets up call to RestoreFunc
// //
START_HEAP
/* memory management */ /* memory management */
UInt hole_size Yap_HoleSize void void UInt Yap_HoleSize void void
struct malloc_state *av_ Yap_av void void struct malloc_state *Yap_av void void
#if USE_DL_MALLOC #if USE_DL_MALLOC
struct memory_hole memory_holes[MAX_DLMALLOC_HOLES] Yap_MemoryHoles void void struct Yap_MemoryHoles[MAX_DLMALLOC_HOLES] void void
UInt nof_memory_holes Yap_NOfMemoryHoles void void UInt Yap_NOfMemoryHoles void void
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
lockvar dlmalloc_lock DLMallocLock MkLock lockvar DLMallocLock MkLock
#endif #endif
#endif #endif
#if USE_DL_MALLOC || (USE_SYSTEM_MALLOC && HAVE_MALLINFO) #if USE_DL_MALLOC || (USE_SYSTEM_MALLOC && HAVE_MALLINFO)
#ifndef HeapUsed #ifndef HeapUsed
#define HeapUsed Yap_givemallinfo() #define HeapUsed Yap_givemallinfo()
#endif #endif
Int heap_used NotHeapUsed void void Int NotHeapUsed void void
#else #else
Int heap_used HeapUsed void void Int HeapUsed void void
#endif #endif
Int heap_max HeapMax void void Int HeapMax void void
ADDR heap_top HeapTop void void ADDR HeapTop void void
ADDR heap_lim HeapLim void void ADDR HeapLim void void
struct FREEB *free_blocks FreeBlocks void void struct FREEB *FreeBlocks void void
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
lockvar free_blocks_lock FreeBlocksLock MkLock lockvar FreeBlocksLock MkLock
lockvar heap_used_lock HeapUsedLock MkLock lockvar HeapUsedLock MkLock
lockvar heap_top_lock HeapTopLock MkLock lockvar HeapTopLock MkLock
int heap_top_owner HeapTopOwner =-1 void int HeapTopOwner =-1 void
#endif #endif
UInt MaxStack_ MaxStack =0 void UInt MaxStack =0 void
UInt MaxTrail_ MaxTrail =0 void UInt MaxTrail =0 void
/* execution info */ /* execution info */
/* OPCODE REVERSE TABLE, needed to recover op tables */ /* OPCODE REVERSE TABLE, needed to recover op tables */
#if USE_THREADED_CODE #if USE_THREADED_CODE
op_entry *op_rtable OP_RTABLE void OpRTableAdjust op_entry *OP_RTABLE void OpRTableAdjust
#endif #endif
/* popular opcodes */ /* popular opcodes */
OPCODE execute_cpred_op_code EXECUTE_CPRED_OP_CODE MkOp _execute_cpred OPCODE EXECUTE_CPRED_OP_CODE MkOp _execute_cpred
OPCODE expand_op_code EXPAND_OP_CODE MkOp _expand_index OPCODE EXPAND_OP_CODE MkOp _expand_index
OPCODE fail_op FAIL_OPCODE MkOp _op_fail OPCODE FAIL_OPCODE MkOp _op_fail
OPCODE index_op INDEX_OPCODE MkOp _index_pred OPCODE INDEX_OPCODE MkOp _index_pred
OPCODE lockpred_op LOCKPRED_OPCODE MkOp _lock_pred OPCODE LOCKPRED_OPCODE MkOp _lock_pred
OPCODE orlast_op ORLAST_OPCODE MkOp _or_last OPCODE ORLAST_OPCODE MkOp _or_last
OPCODE undef_op UNDEF_OPCODE MkOp _undef_p OPCODE UNDEF_OPCODE MkOp _undef_p
OPCODE retry_userc_op RETRY_USERC_OPCODE MkOp _retry_userc OPCODE RETRY_USERC_OPCODE MkOp _retry_userc
OPCODE execute_cpred_op EXECUTE_CPRED_OPCODE MkOp _execute_cpred OPCODE EXECUTE_CPRED_OPCODE MkOp _execute_cpred
/* atom tables */ /* atom tables */
UInt n_of_atoms NOfAtoms void void UInt NOfAtoms void void
UInt atom_hash_table_size AtomHashTableSize void void UInt AtomHashTableSize void void
UInt wide_atom_hash_table_size WideAtomHashTableSize void void UInt WideAtomHashTableSize void void
UInt n_of_wide_atoms NOfWideAtoms void void UInt NOfWideAtoms void void
AtomHashEntry invisiblechain INVISIBLECHAIN InitInvisibleAtoms() RestoreInvisibleAtoms() AtomHashEntry INVISIBLECHAIN InitInvisibleAtoms() RestoreInvisibleAtoms()
AtomHashEntry *wide_hash_chain WideHashChain InitWideAtoms() RestoreWideAtoms() AtomHashEntry *WideHashChain InitWideAtoms() RestoreWideAtoms()
AtomHashEntry *hash_chain HashChain InitAtoms() RestoreAtoms() AtomHashEntry *HashChain InitAtoms() RestoreAtoms()
/* use atom defs here */ /* use atom defs here */
ATOMS ATOMS
#ifdef EUROTRA #ifdef EUROTRA
Term term_dollar_u TermDollarU MkAT AtomDollarU Term TermDollarU MkAT AtomDollarU
#endif #endif
//modules //modules
Term user_module USER_MODULE MkAT AtomUser Term USER_MODULE MkAT AtomUser
Term idb_module IDB_MODULE MkAT AtomIDB Term IDB_MODULE MkAT AtomIDB
Term attributes_module ATTRIBUTES_MODULE MkAT AtomAttributes Term ATTRIBUTES_MODULE MkAT AtomAttributes
Term charsio_module CHARSIO_MODULE MkAT AtomCharsio Term CHARSIO_MODULE MkAT AtomCharsio
Term chtype_module CHTYPE_MODULE MkAT AtomChType Term CHTYPE_MODULE MkAT AtomChType
Term terms_module TERMS_MODULE MkAT AtomTerms Term TERMS_MODULE MkAT AtomTerms
Term system_module SYSTEM_MODULE MkAT AtomSystem Term SYSTEM_MODULE MkAT AtomSystem
Term readutil_module READUTIL_MODULE MkAT AtomReadutil Term READUTIL_MODULE MkAT AtomReadutil
Term hacks_module HACKS_MODULE MkAT AtomYapHacks Term HACKS_MODULE MkAT AtomYapHacks
Term arg_module ARG_MODULE MkAT AtomArg Term ARG_MODULE MkAT AtomArg
Term globals_module GLOBALS_MODULE MkAT AtomNb Term GLOBALS_MODULE MkAT AtomNb
Term swi_module SWI_MODULE MkAT AtomSwi Term SWI_MODULE MkAT AtomSwi
Term dbload_module DBLOAD_MODULE MkAT AtomDBLoad Term DBLOAD_MODULE MkAT AtomDBLoad
Term range_module RANGE_MODULE MkAT AtomRange Term RANGE_MODULE MkAT AtomRange
Term error_module ERROR_MODULE MkAT AtomError Term ERROR_MODULE MkAT AtomError
// //
// Module list // Module list
// //
struct mod_entry *current_modules CurrentModules =NULL ModEntryPtrAdjust struct mod_entry *CurrentModules =NULL ModEntryPtrAdjust
// make sure we have the modules set at this point. // make sure we have the modules set at this point.
// don't actually want to define a field // don't actually want to define a field
void void void Yap_InitModules() void void void Yap_InitModules() void
// hidden predicates // hidden predicates
Prop hidden_predicates HIDDEN_PREDICATES =NULL RestoreHiddenPredicates() Prop HIDDEN_PREDICATES =NULL RestoreHiddenPredicates()
// make sure we have the streams set at this point. // make sure we have the streams set at this point.
// don't actually want to define a field // don't actually want to define a field
void void void Yap_InitPlIO() void void void Yap_InitPlIO() void
union flagTerm* GLOBAL_Flags_ GLOBAL_Flags =0 void union flagTerm* GLOBAL_Flags =0 void
UInt GLOBAL_flagCount_ GLOBAL_flagCount Yap_InitFlags(true) RestoreFlags(GLOBAL_flagCount) UInt GLOBAL_flagCount Yap_InitFlags(true) RestoreFlags(GLOBAL_flagCount)
/* Anderson's JIT */ /* Anderson's JIT */
yap_exec_mode execution_mode Yap_ExecutionMode =INTERPRETED void yap_exec_mode Yap_ExecutionMode =INTERPRETED void
/* The Predicate Hash Table: fast access to predicates. */ /* The Predicate Hash Table: fast access to predicates. */
struct pred_entry **pred_hash PredHash InitPredHash() RestorePredHash() struct pred_entry **PredHash InitPredHash() RestorePredHash()
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
rwlock_t pred_hash_rw_lock PredHashRWLock void rwlock_t PredHashRWLock void
#endif #endif
UInt preds_in_hash_table PredsInHashTable =0 void UInt PredsInHashTable =0 void
UInt pred_hash_table_size PredHashTableSize void uint64_t PredHashTableSize =0 void
/* Well-Known Predicates */ /* Well-Known Predicates */
struct pred_entry *creep_code CreepCode MkPred AtomCreep 1 PROLOG_MODULE struct pred_entry *CreepCode MkPred AtomCreep 1 PROLOG_MODULE
struct pred_entry *undef_code UndefCode MkPred AtomUndefp 2 PROLOG_MODULE struct pred_entry *UndefCode MkPred AtomUndefp 2 PROLOG_MODULE
struct pred_entry *spy_code SpyCode MkPred AtomSpy 1 PROLOG_MODULE struct pred_entry *SpyCode MkPred AtomSpy 1 PROLOG_MODULE
struct pred_entry *pred_fail PredFail MkPred AtomFail 0 PROLOG_MODULE struct pred_entry *PredFail MkPred AtomFail 0 PROLOG_MODULE
struct pred_entry *pred_true PredTrue MkPred AtomTrue 0 PROLOG_MODULE struct pred_entry *PredTrue MkPred AtomTrue 0 PROLOG_MODULE
#ifdef COROUTINING #ifdef COROUTINING
struct pred_entry *wake_up_code WakeUpCode MkPred AtomWakeUpGoal 2 PROLOG_MODULE struct pred_entry *WakeUpCode MkPred AtomWakeUpGoal 2 PROLOG_MODULE
#endif #endif
struct pred_entry *pred_goal_expansion PredGoalExpansion MkPred FunctorGoalExpansion USER_MODULE struct pred_entry *PredGoalExpansion MkPred FunctorGoalExpansion USER_MODULE
struct pred_entry *pred_meta_call PredMetaCall MkPred FunctorMetaCall PROLOG_MODULE struct pred_entry *PredMetaCall MkPred FunctorMetaCall PROLOG_MODULE
struct pred_entry *pred_trace_meta_call PredTraceMetaCall MkPred FunctorTraceMetaCall PROLOG_MODULE struct pred_entry *PredTraceMetaCall MkPred FunctorTraceMetaCall PROLOG_MODULE
struct pred_entry *pred_dollar_catch PredDollarCatch MkPred FunctorCatch PROLOG_MODULE struct pred_entry *PredDollarCatch MkPred FunctorCatch PROLOG_MODULE
struct pred_entry *pred_recorded_with_key PredRecordedWithKey MkPred FunctorRecordedWithKey PROLOG_MODULE struct pred_entry *PredRecordedWithKey MkPred FunctorRecordedWithKey PROLOG_MODULE
struct pred_entry *pred_log_upd_clause PredLogUpdClause MkPred FunctorDoLogUpdClause PROLOG_MODULE struct pred_entry *PredLogUpdClause MkPred FunctorDoLogUpdClause PROLOG_MODULE
struct pred_entry *pred_log_upd_clause_erase PredLogUpdClauseErase MkPred FunctorDoLogUpdClauseErase PROLOG_MODULE struct pred_entry *PredLogUpdClauseErase MkPred FunctorDoLogUpdClauseErase PROLOG_MODULE
struct pred_entry *pred_log_upd_clause0 PredLogUpdClause0 MkPred FunctorDoLogUpdClause PROLOG_MODULE struct pred_entry *PredLogUpdClause0 MkPred FunctorDoLogUpdClause PROLOG_MODULE
struct pred_entry *pred_static_clause PredStaticClause MkPred FunctorDoStaticClause PROLOG_MODULE struct pred_entry *PredStaticClause MkPred FunctorDoStaticClause PROLOG_MODULE
struct pred_entry *pred_throw PredThrow MkPred FunctorThrow PROLOG_MODULE struct pred_entry *PredThrow MkPred FunctorThrow PROLOG_MODULE
struct pred_entry *pred_handle_throw PredHandleThrow MkPred FunctorHandleThrow PROLOG_MODULE struct pred_entry *PredHandleThrow MkPred FunctorHandleThrow PROLOG_MODULE
struct pred_entry *pred_is PredIs MkPred FunctorIs PROLOG_MODULE struct pred_entry *PredIs MkPred FunctorIs PROLOG_MODULE
struct pred_entry *pred_safe_call_cleanup PredSafeCallCleanup MkPred FunctorSafeCallCleanup PROLOG_MODULE struct pred_entry *PredSafeCallCleanup MkPred FunctorSafeCallCleanup PROLOG_MODULE
struct pred_entry *pred_restore_regs PredRestoreRegs MkPred FunctorRestoreRegs PROLOG_MODULE struct pred_entry *PredRestoreRegs MkPred FunctorRestoreRegs PROLOG_MODULE
struct pred_entry *pred_comment_hook PredCommentHook MkPred FunctorCommentHook PROLOG_MODULE struct pred_entry *PredCommentHook MkPred FunctorCommentHook PROLOG_MODULE
#ifdef YAPOR #ifdef YAPOR
struct pred_entry *pred_getwork PredGetwork MkPred AtomGetwork 0 PROLOG_MODULE struct pred_entry *PredGetwork MkPred AtomGetwork 0 PROLOG_MODULE
struct pred_entry *pred_getwork_seq PredGetworkSeq MkPred AtomGetworkSeq 0 PROLOG_MODULE
#endif /* YAPOR */ #endif /* YAPOR */
struct pred_entry *PredProcedure MkLogPred FunctorProcedure PROLOG_MODULE
/* low-level tracer */ /* low-level tracer */
#ifdef LOW_LEVEL_TRACER #ifdef LOW_LEVEL_TRACER
int yap_do_low_level_trace Yap_do_low_level_trace =FALSE void int Yap_do_low_level_trace =FALSE void
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
lockvar low_level_trace_lock Yap_low_level_trace_lock MkLock lockvar Yap_low_level_trace_lock MkLock
#endif #endif
#endif #endif
/* code management info */ /* code management info */
UInt clause_space Yap_ClauseSpace =0 void UInt Yap_ClauseSpace =0 void
UInt index_space_Tree Yap_IndexSpace_Tree =0 void UInt Yap_IndexSpace_Tree =0 void
UInt index_space_EXT Yap_IndexSpace_EXT =0 void UInt Yap_IndexSpace_EXT =0 void
UInt index_space_SW Yap_IndexSpace_SW =0 void UInt Yap_IndexSpace_SW =0 void
UInt lu_clause_space Yap_LUClauseSpace =0 void UInt Yap_LUClauseSpace =0 void
UInt lu_index_space_Tree Yap_LUIndexSpace_Tree =0 void UInt Yap_LUIndexSpace_Tree =0 void
UInt lu_index_space_CP Yap_LUIndexSpace_CP =0 void UInt Yap_LUIndexSpace_CP =0 void
UInt lu_index_space_EXT Yap_LUIndexSpace_EXT =0 void UInt Yap_LUIndexSpace_EXT =0 void
UInt lu_index_space_SW Yap_LUIndexSpace_SW =0 void UInt Yap_LUIndexSpace_SW =0 void
/* static code: may be shared by many predicate or may be used for meta-execution */ /* static code: may be shared by many predicate or may be used for meta-execution */
yamop comma_code[5] COMMA_CODE void void yamop COMMA_CODE[5] void void
yamop dummycode[1] DUMMYCODE MkInstE _op_fail yamop DUMMYCODE[1] MkInstE _op_fail
yamop failcode[1] FAILCODE MkInstE _op_fail yamop FAILCODE[1] MkInstE _op_fail
yamop nocode[1] NOCODE MkInstE _Nstop yamop NOCODE[1] MkInstE _Nstop
yamop env_for_trustfail[2] ENV_FOR_TRUSTFAIL InitEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail) RestoreEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail) yamop ENV_FOR_TRUSTFAIL[2] InitEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail) RestoreEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail)
yamop *trustfailcode TRUSTFAILCODE void yamop *TRUSTFAILCODE void
yamop env_for_yescode[2] ENV_FOR_YESCODE InitEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail) RestoreEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail) yamop ENV_FOR_YESCODE[2] InitEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail) RestoreEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail)
yamop *yescode YESCODE void yamop *YESCODE void
yamop rtrycode[1] RTRYCODE InitOtaplInst(RTRYCODE,_retry_and_mark,PredFail) RestoreOtaplInst(RTRYCODE,_retry_and_mark,PredFail) yamop RTRYCODE[1] InitOtaplInst(RTRYCODE,_retry_and_mark,PredFail) RestoreOtaplInst(RTRYCODE,_retry_and_mark,PredFail)
#ifdef BEAM #ifdef BEAM
yamop beam_retry_code[1] BEAM_RETRY_CODE MkInstE _beam_retry_code yamop BEAM_RETRY_CODE[1] MkInstE _beam_retry_code
#endif /* BEAM */ #endif /* BEAM */
#ifdef YAPOR #ifdef YAPOR
yamop getwork_code[1] GETWORK InitOtaplInst(GETWORK,_getwork,PredGetwork) RestoreOtaplInst(GETWORK,_getwork,PredGetwork) yamop GETWORK[1] InitOtaplInst(GETWORK,_getwork,PredGetwork) RestoreOtaplInst(GETWORK,_getwork,PredGetwork)
yamop getwork_seq_code[1] GETWORK_SEQ InitOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq) RestoreOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq) yamop GETWORK_SEQ[1] InitOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq) RestoreOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq)
yamop getwork_first_time[1] GETWORK_FIRST_TIME MkInstE _getwork_first_time yamop GETWORK_FIRST_TIME[1] MkInstE _getwork_first_time
#endif /* YAPOR */ #endif /* YAPOR */
#ifdef TABLING #ifdef TABLING
yamop table_load_answer_code[1] LOAD_ANSWER InitOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail) RestoreOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail) yamop LOAD_ANSWER[1] InitOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail) RestoreOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail)
yamop table_try_answer_code[1] TRY_ANSWER InitOtaplInst(TRY_ANSWER,_table_try_answer,PredFail) RestoreOtaplInst(TRY_ANSWER,_table_try_answer,PredFail) yamop TRY_ANSWER[1] InitOtaplInst(TRY_ANSWER,_table_try_answer,PredFail) RestoreOtaplInst(TRY_ANSWER,_table_try_answer,PredFail)
yamop table_answer_resolution_code[1] ANSWER_RESOLUTION InitOtaplInst(ANSWER_RESOLUTION,_table_answer_resolution,PredFail) RestoreOtaplInst(ANSWER_RESOLUTION,_table_answer_resolution,PredFail) yamop ANSWER_RESOLUTION[1] InitOtaplInst(ANSWER_RESOLUTION,_table_answer_resolution,PredFail) RestoreOtaplInst(ANSWER_RESOLUTION,_table_answer_resolution,PredFail)
yamop table_completion_code[1] COMPLETION InitOtaplInst(COMPLETION,_table_completion,PredFail) RestoreOtaplInst(COMPLETION,_table_completion,PredFail) yamop COMPLETION[1] InitOtaplInst(COMPLETION,_table_completion,PredFail) RestoreOtaplInst(COMPLETION,_table_completion,PredFail)
#ifdef THREADS_CONSUMER_SHARING #ifdef THREADS_CONSUMER_SHARING
yamop table_answer_resolution_completion_code[1] ANSWER_RESOLUTION_COMPLETION InitOtaplInst(ANSWER_RESOLUTION_COMPLETION,_table_answer_resolution_completion,PredFail) RestoreOtaplInst(ANSWER_RESOLUTION_COMPLETION,_table_answer_resolution_completion,PredFail) yamop ANSWER_RESOLUTION_COMPLETION[1] InitOtaplInst(ANSWER_RESOLUTION_COMPLETION,_table_answer_resolution_completion,PredFail) RestoreOtaplInst(ANSWER_RESOLUTION_COMPLETION,_table_answer_resolution_completion,PredFail)
#endif /* THREADS_CONSUMER_SHARING */ #endif /* THREADS_CONSUMER_SHARING */
#endif /* TABLING */ #endif /* TABLING */
@ -219,123 +221,125 @@ yamop table_answer_resolution_completion_code[1] ANSWER_RESOLUTIO
/* PREG just before we enter $spy. We use that to find out the clause which */ /* PREG just before we enter $spy. We use that to find out the clause which */
/* was calling the debugged goal. */ /* was calling the debugged goal. */
/* */ /* */
yamop *debugger_p_before_spy P_before_spy =NULL PtoOpAdjust yamop *P_before_spy =NULL PtoOpAdjust
/* support recorded_k */ /* support recorded_k */
yamop *retry_recordedp_code RETRY_C_RECORDEDP_CODE =NULL PtoOpAdjust yamop *RETRY_C_RECORDEDP_CODE =NULL PtoOpAdjust
yamop *retry_recorded_k_code RETRY_C_RECORDED_K_CODE =NULL PtoOpAdjust yamop *RETRY_C_RECORDED_K_CODE =NULL PtoOpAdjust
R
/* compiler flags */ /* compiler flags */
int system_profiling PROFILING =FALSE void int PROFILING =FALSE void
int system_call_counting CALL_COUNTING =FALSE void int CALL_COUNTING =FALSE void
int compiler_optimizer_on optimizer_on =TRUE void int optimizer_on =TRUE void
int compiler_compile_mode compile_mode =0 void int compile_mode =0 void
int compiler_profiling profiling =FALSE void int profiling =FALSE void
int compiler_call_counting call_counting =FALSE void int call_counting =FALSE void
/********* whether we should try to compile array references ******************/ /********* whether we should try to compile array references ******************/
int compiler_compile_arrays compile_arrays =FALSE void int compile_arrays =FALSE void
/* DBTerms: pre-compiled ground terms */ /* DBTerms: pre-compiled ground terms */
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
lockvar dbterms_list_lock DBTermsListLock MkLock lockvar DBTermsListLock MkLock
#endif #endif
struct dbterm_list *dbterms_list DBTermsList =NULL RestoreDBTermsList() struct dbterm_list *DBTermsList =NULL RestoreDBTermsList()
/* JITI support */ /* JITI support */
yamop *expand_clauses_first ExpandClausesFirst =NULL void yamop *ExpandClausesFirst =NULL void
yamop *expand_clauses_last ExpandClausesLast =NULL RestoreExpandList() yamop *ExpandClausesLast =NULL RestoreExpandList()
UInt expand_clauses Yap_ExpandClauses =0 void UInt Yap_ExpandClauses =0 void
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
lockvar expand_clauses_list_lock ExpandClausesListLock MkLock lockvar ExpandClausesListLock MkLock
lockvar op_list_lock OpListLock MkLock lockvar OpListLock MkLock
#endif #endif
/* instrumentation */ /* instrumentation */
#ifdef DEBUG #ifdef DEBUG
UInt new_cps Yap_NewCps =0L void UInt Yap_NewCps =0L void
UInt live_cps Yap_LiveCps =0L void UInt Yap_LiveCps =0L void
UInt dirty_cps Yap_DirtyCps =0L void UInt Yap_DirtyCps =0L void
UInt freed_cps Yap_FreedCps =0L void UInt Yap_FreedCps =0L void
#endif #endif
UInt expand_clauses_sz Yap_expand_clauses_sz =0L void UInt Yap_expand_clauses_sz =0L void
/* UDI support */ /* UDI support */
struct udi_info *udi_control_blocks UdiControlBlocks =NULL RestoreUdiControlBlocks() struct udi_info *UdiControlBlocks =NULL RestoreUdiControlBlocks()
/* data-base statistics */ /* data-base statistics */
/* system boots in compile mode */ /* system boots in compile mode */
Int static_predicates_marked STATIC_PREDICATES_MARKED =FALSE void Int STATIC_PREDICATES_MARKED =FALSE void
/* Internal Database */ /* Internal Database */
Prop *IntKeys INT_KEYS =NULL RestoreIntKeys() Prop *INT_KEYS =NULL RestoreIntKeys()
Prop *IntLUKeys INT_LU_KEYS =NULL RestoreIntLUKeys() Prop *INT_LU_KEYS =NULL RestoreIntLUKeys()
Prop *IntBBKeys INT_BB_KEYS =NULL RestoreIntBBKeys() Prop *INT_BB_KEYS =NULL RestoreIntBBKeys()
/* Internal Database Statistics */ /* Internal Database Statistics */
UInt int_keys_size INT_KEYS_SIZE =INT_KEYS_DEFAULT_SIZE void UInt INT_KEYS_SIZE =INT_KEYS_DEFAULT_SIZE void
UInt int_keys_timestamp INT_KEYS_TIMESTAMP =0L void UInt INT_KEYS_TIMESTAMP =0L void
UInt int_bb_keys_size INT_BB_KEYS_SIZE =INT_KEYS_DEFAULT_SIZE void UInt INT_BB_KEYS_SIZE =INT_KEYS_DEFAULT_SIZE void
/* Internal Data-Base Control */ /* Internal Data-Base Control */
int update_mode UPDATE_MODE =UPDATE_MODE_LOGICAL void int UPDATE_MODE =UPDATE_MODE_LOGICAL void
/* nasty IDB stuff */ /* nasty IDB stuff */
struct DB_STRUCT *db_erased_marker DBErasedMarker InitDBErasedMarker() RestoreDBErasedMarker() struct DB_STRUCT *DBErasedMarker InitDBErasedMarker() RestoreDBErasedMarker()
struct logic_upd_clause *logdb_erased_marker LogDBErasedMarker InitLogDBErasedMarker() RestoreLogDBErasedMarker() struct logic_upd_clause *LogDBErasedMarker InitLogDBErasedMarker() RestoreLogDBErasedMarker()
/* Dead clauses and IDB entries */ /* Dead clauses and IDB entries */
struct static_clause *dead_static_clauses DeadStaticClauses =NULL RestoreDeadStaticClauses() struct static_clause *DeadStaticClauses =NULL RestoreDeadStaticClauses()
struct static_mega_clause *dead_mega_clauses DeadMegaClauses =NULL RestoreDeadMegaClauses() struct static_mega_clause *DeadMegaClauses =NULL RestoreDeadMegaClauses()
struct static_index *dead_static_indices DeadStaticIndices =NULL RestoreDeadStaticIndices() struct static_index *DeadStaticIndices =NULL RestoreDeadStaticIndices()
struct logic_upd_clause *db_erased_list DBErasedList =NULL RestoreDBErasedList() struct logic_upd_clause *DBErasedList =NULL RestoreDBErasedList()
struct logic_upd_index *db_erased_ilist DBErasedIList =NULL RestoreDBErasedIList() struct logic_upd_index *DBErasedIList =NULL RestoreDBErasedIList()
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
lockvar dead_static_clauses_lock DeadStaticClausesLock MkLock lockvar DeadStaticClausesLock MkLock
lockvar dead_mega_clauses_lock DeadMegaClausesLock MkLock lockvar DeadMegaClausesLock MkLock
lockvar dead_static_indices_lock DeadStaticIndicesLock MkLock lockvar DeadStaticIndicesLock MkLock
#endif #endif
#ifdef COROUTINING #ifdef COROUTINING
/* number of attribute modules */ /* number of attribute modules */
int num_of_atts NUM_OF_ATTS =1 void int NUM_OF_ATTS =1 void
/* initialised by memory allocator */ /* initialised by memory allocator */
UInt atts_size Yap_AttsSize void void UInt Yap_AttsSize void void
#endif #endif
/* Operators */ /* Operators */
struct operator_entry *op_list OpList =NULL OpListAdjust struct operator_entry *OpList =NULL OpListAdjust
/* foreign code loaded */ /* foreign code loaded */
struct ForeignLoadItem *foreign_code_loaded ForeignCodeLoaded =NULL RestoreForeignCode() struct ForeignLoadItem *ForeignCodeLoaded =NULL RestoreForeignCode()
ADDR foreign_code_base ForeignCodeBase =NULL void ADDR ForeignCodeBase =NULL void
ADDR foreign_code_top ForeignCodeTop =NULL void ADDR ForeignCodeTop =NULL void
ADDR foreign_code_max ForeignCodeMax =NULL void ADDR ForeignCodeMax =NULL void
/* recorded terms */ /* recorded terms */
struct record_list *yap_records Yap_Records =NULL RestoreYapRecords() struct record_list *Yap_Records =NULL RestoreYapRecords()
/* SWI atoms and functors */ /* SWI atoms and functors */
Atom *swi_atoms SWI_Atoms InitSWIAtoms() RestoreSWIAtoms() Atom *SWI_Atoms InitSWIAtoms() RestoreSWIAtoms()
Functor *swi_functors SWI_Functors void void Functor *SWI_Functors void void
struct swi_reverse_hash swi_reverse_hash[N_SWI_HASH] SWI_ReverseHash void void swi_rev_hash SWI_ReverseHash[N_SWI_HASH] void void
/* integer access to atoms */ /* integer access to atoms */
Int atom_translations AtomTranslations void void Int AtomTranslations void void
Int max_atom_translations MaxAtomTranslations void void Int MaxAtomTranslations void void
/* integer access to functors */ /* integer access to functors */
Int functor_translations FunctorTranslations void void Int FunctorTranslations void void
Int max_functor_translations MaxFunctorTranslations void void Int MaxFunctorTranslations void void
Atom empty_wakeups[MAX_EMPTY_WAKEUPS] EmptyWakeups InitEmptyWakeups() RestoreEmptyWakeups() Atom EmptyWakeups[MAX_EMPTY_WAKEUPS] InitEmptyWakeups() RestoreEmptyWakeups()
int max_empty_wakeups MaxEmptyWakeups =0 int MaxEmptyWakeups =0
/* SWI blobs */ /* SWI blobs */
struct YAP_blob_t *swi_blob_types BlobTypes =NULL RestoreBlobTypes() struct YAP_blob_t *BlobTypes =NULL RestoreBlobTypes()
struct AtomEntryStruct *swi_blobs Blobs =NULL RestoreBlobs() struct AtomEntryStruct *Blobs =NULL RestoreBlobs()
UInt nofblobs NOfBlobs =0 UInt NOfBlobs =0
UInt nofblobsmax NOfBlobsMax =256 UInt NOfBlobsMax =256
#if defined(YAPOR) || defined(THREADS) #if defined(YAPOR) || defined(THREADS)
lockvar blobs_lock Blobs_Lock MkLock lockvar Blobs_Lock MkLock
#endif #endif
END_HEAP

View File

@ -30,11 +30,9 @@ main :-
%file_filter_with_initialization('misc/LOCALS','H/dlocals.h',gen_dstruct,Warning,['dlocals.h','LOCALS']), %file_filter_with_initialization('misc/LOCALS','H/dlocals.h',gen_dstruct,Warning,['dlocals.h','LOCALS']),
%file_filter_with_initialization('misc/LOCALS','H/rlocals.h',gen_hstruct,Warning,['rlocals.h','LOCALS']), %file_filter_with_initialization('misc/LOCALS','H/rlocals.h',gen_hstruct,Warning,['rlocals.h','LOCALS']),
%file_filter_with_initialization('misc/LOCALS','H/ilocals.h',gen_init,Warning,['ilocals.h','LOCALS']). %file_filter_with_initialization('misc/LOCALS','H/ilocals.h',gen_init,Warning,['ilocals.h','LOCALS']).
warning('~n /* This file, ~a, was generated automatically by \"yap -L misc/buildheap\"~n please do not update, update misc/~a instead */~n~n'). warning('~n /* This file, ~a, was generated automatically by \"yap -L misc/buildheap\"~n please do not update, update misc/~a instead */~n~n').
/* define the field */ /* define the field */
gen_struct(Inp,"") :- gen_struct(Inp,"") :-
Inp = [0'/,0'/|_], !. Inp = [0'/,0'/|_], !.
@ -50,6 +48,12 @@ gen_struct(Inp,Out) :-
gen_struct(Inp,Out) :- gen_struct(Inp,Out) :-
Inp = "END_WORKER_LOCAL", !, Inp = "END_WORKER_LOCAL", !,
Out = "} w_local;". Out = "} w_local;".
gen_struct(Inp,Out) :-
Inp = "START_HEAP", !,
Out = "typedef struct worker_local {".
gen_struct(Inp,Out) :-
Inp = "END_HEAP", !,
Out = "} w_local;".
gen_struct(Inp,Out) :- gen_struct(Inp,Out) :-
Inp = "START_GLOBAL_DATA", !, Inp = "START_GLOBAL_DATA", !,
Out = "typedef struct global_data {". Out = "typedef struct global_data {".
@ -76,7 +80,7 @@ gen_struct(Inp,Out) :-
gen_struct(Inp,_) :- gen_struct(Inp,_) :-
split(Inp," ",[_, _, _| _]), split(Inp," ",[_, _, _| _]),
format(user_error,"OOPS: could not gen_struct for ~s~n",[Inp]). format(user_error,"OOPS: could not gen_struct for ~s~n",[Inp]).
gen_dstruct(Inp,"") :- gen_dstruct(Inp,"") :-
Inp = [0'/,0'/|_], !. Inp = [0'/,0'/|_], !.
gen_dstruct(Inp,"") :- gen_dstruct(Inp,"") :-
@ -145,8 +149,8 @@ cut_c_stuff(Name, RName) :-
cut_mat(Name, RName). cut_mat(Name, RName).
cut_mat([], []). cut_mat([], []).
cut_mat([0'[|_], []) :- !. %' cut_mat([0'[|_], []) :- !. %'
cut_mat(H.Name, H.RName) :- cut_mat([H|Name], [H|RName]) :-
cut_mat(Name, RName). cut_mat(Name, RName).
gen_hstruct(Inp,"") :- gen_hstruct(Inp,"") :-
@ -185,9 +189,9 @@ gen_hstruct(Inp,Out) :-
glue(Inp2, " ", Inp3), glue(Inp2, " ", Inp3),
gen_hstruct(Inp3,Out). gen_hstruct(Inp3,Out).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",["const"|Inp2]), !, split(Inp," ",["const"|Inp2]), !,
glue(Inp2, " ", Inp3), glue(Inp2, " ", Inp3),
gen_hstruct(Inp3,Out). gen_hstruct(Inp3,Out).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field, MacroName, "MkAT", _]), !, split(Inp," ",[_, Field, MacroName, "MkAT", _]), !,
fetch_name(Global,Field,MacroName), fetch_name(Global,Field,MacroName),
@ -257,6 +261,14 @@ gen_init(Inp,Out) :-
Inp = "END_GLOBAL_DATA", !, Inp = "END_GLOBAL_DATA", !,
Out = "}", Out = "}",
retract(globals(all)). retract(globals(all)).
gen_init(Inp,Out) :-
Inp = "START_HEAP", !,
Out = "static void InitGlobal(void) {",
assert(globals(heap)).
gen_init(Inp,Out) :-
Inp = "END_HEAP", !,
Out = "}",
retract(globals(heap)).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
split(Inp," ",["struct"|Inp2]), !, split(Inp," ",["struct"|Inp2]), !,
glue(Inp2, " ", Inp3), glue(Inp2, " ", Inp3),
@ -306,20 +318,20 @@ gen_init(Inp,Out) :-
fetch_name(Global,RField,MacroName), fetch_name(Global,RField,MacroName),
append([" ",Global,"->opc = Yap_opcode(",OP,");"], Out). append([" ",Global,"->opc = Yap_opcode(",OP,");"], Out).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
split(Inp," ",[_, Field, MacroName, "MkPred", Atom, "0", Module]), !, split(Inp," ",[_, Field, MacroName, "MkLogPred", Atom, "0", Module]), !,
cut_c_stuff(Field, RField), cut_c_stuff(Field, RField),
fetch_name(Global,RField,MacroName), fetch_name(Global,RField,MacroName),
append([" ",Global," = RepPredProp(PredPropByAtom(",Atom,",",Module,"));"], Out). append([" ",Global," = Yap_MkLogPred(RepPredProp(PredPropByAtom(",Atom,",",Module,")));"], Out).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
split(Inp," ",[_, Field, MacroName, "MkPred", Atom, Arity, Module]), !, split(Inp," ",[_, Field, MacroName, "MkLogPred", Atom, Arity, Module]), !,
cut_c_stuff(Field, RField), cut_c_stuff(Field, RField),
fetch_name(Global,RField,MacroName), fetch_name(Global,RField,MacroName),
append([" ",Global," = RepPredProp(PredPropByFunc(Yap_MkFunctor(",Atom,",",Arity,"),",Module,"));"], Out). append([" ",Global," = Yap_MkLogPred(RepPredProp(PredPropByFunc(Yap_MkFunctor(",Atom,",",Arity,"),",Module,")));"], Out).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
split(Inp," ",[_, Field, MacroName, "MkPred", Fun, Module]), !, split(Inp," ",[_, Field, MacroName, "MkLogPred", Fun, Module]), !,
cut_c_stuff(Field, RField), cut_c_stuff(Field, RField),
fetch_name(Global,RField,MacroName), fetch_name(Global,RField,MacroName),
append([" ",Global," = RepPredProp(PredPropByFunc(",Fun,",",Module,"));"], Out). append([" ",Global," = Yap_MkLogPred(RepPredProp(PredPropByFunc(",Fun,",",Module,")));"], Out).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
split(Inp," ",[_, Field, MacroName, F0|_]), split(Inp," ",[_, Field, MacroName, F0|_]),
append("=",F,F0), !, append("=",F,F0), !,
@ -329,4 +341,3 @@ gen_init(Inp,Out) :-
gen_init(Inp,_) :- gen_init(Inp,_) :-
split(Inp," ",[_, _, _| _]), split(Inp," ",[_, _, _| _]),
format(user_error,"OOPS: could not gen_init for ~s~n",[Inp]). format(user_error,"OOPS: could not gen_init for ~s~n",[Inp]).

View File

@ -1,12 +1,12 @@
:- use_module(library(lineutils), :- use_module(library(lineutils),
[file_filter_with_init/5, [file_filter_with_init/5,
split/3, split/3,
glue/3]). glue/3]).
:- use_module(library(lists), :- use_module(library(lists),
[append/2, [append/2,
append/3]). append/3]).
:- initialization(main). :- initialization(main).
@ -17,31 +17,33 @@
:- style_check(all). :- style_check(all).
file_filter_with_initialization(A,B,C,D,E) :- file_filter_with_initialization(A,B,C,D,E) :-
file_filter_with_init(A,B,C,D,E). file_filter_with_init(A,B,C,D,E).
main :- main :-
warning(Warning), warning(Warning),
%file_filter_with_initialization('misc/HEAPFIELDS','H/hstruct.h',gen_struct,Warning,['hstruct.h','HEAPFIELDS']), file_filter_with_initialization('misc/HEAPFIELDS','H/heap/hstruct.h',gen_struct,Warning,['hstruct.h','HEAPFIELDS']),
%file_filter_with_initialization('misc/HEAPFIELDS','H/dhstruct.h',gen_dstruct,Warning,['dhstruct.h','HEAPFIELDS']), file_filter_with_initialization('misc/HEAPFIELDS','H/heap/dhstruct.h',gen_dstruct,Warning,['dhstruct.h','HEAPFIELDS']),
%file_filter_with_initialization('misc/HEAPFIELDS','H/rhstruct.h',gen_hstruct,Warning,['rhstruct.h','HEAPFIELDS']), file_filter_with_initialization('misc/HEAPFIELDS','H/heap/h0struct.h',gen_0struct,Warning,['d0hstruct.h','HEAPFIELDS']),
%file_filter_with_initialization('misc/HEAPFIELDS','H/ihstruct.h',gen_init,Warning,['ihstruct.h','HEAPFIELDS']), file_filter_with_initialization('misc/HEAPFIELDS','H/heap/rhstruct.h',gen_hstruct,Warning,['rhstruct.h','HEAPFIELDS']),
file_filter_with_initialization('misc/GLOBALS','H/hglobals.h',gen_struct,Warning,['hglobals.h','GLOBALS']), file_filter_with_initialization('misc/HEAPFIELDS','H/heap/ihstruct.h',gen_init,Warning,['ihstruct.h','HEAPFIELDS']),
file_filter_with_initialization('misc/GLOBALS','H/dglobals.h',gen_dstruct,Warning,['dglobals.h','GLOBALS']), file_filter_with_initialization('misc/GLOBALS','H/heap/h0globals.h',gen_0struct,Warning,['hglobals.h','GLOBALS']),
file_filter_with_initialization('misc/GLOBALS','H/rglobals.h',gen_hstruct,Warning,['rglobals.h','GLOBALS']), file_filter_with_initialization('misc/GLOBALS','H/heap/hglobals.h',gen_struct,Warning,['hglobals.h','GLOBALS']),
file_filter_with_initialization('misc/GLOBALS','H/iglobals.h',gen_init,Warning,['iglobals.h','GLOBALS']), file_filter_with_initialization('misc/GLOBALS','H/heap/dglobals.h',gen_dstruct,Warning,['dglobals.h','GLOBALS']),
file_filter_with_initialization('misc/LOCALS','H/hlocals.h',gen_struct,Warning,['hlocals.h','LOCALS']), file_filter_with_initialization('misc/GLOBALS','H/heap/iglobals.h',gen_init,Warning,['iglobals.h','GLOBALS']),
file_filter_with_initialization('misc/LOCALS','H/dlocals.h',gen_dstruct,Warning,['dlocals.h','LOCALS']), file_filter_with_initialization('misc/GLOBALS','H/heap/i0globals.h',gen_0init,Warning,['iglobals.h','GLOBALS']),
file_filter_with_initialization('misc/LOCALS','H/rlocals.h',gen_hstruct,Warning,['rlocals.h','LOCALS']), file_filter_with_initialization('misc/LOCALS','H/heap/hlocals.h',gen_struct,Warning,['hlocals.h','LOCALS']),
file_filter_with_initialization('misc/LOCALS','H/ilocals.h',gen_init,Warning,['ilocals.h','LOCALS']). file_filter_with_initialization('misc/LOCALS','H/heap/dlocals.h',gen_dstruct,Warning,['dlocals.h','LOCALS']),
file_filter_with_initialization('misc/LOCALS','H/heap/rlocals.h',gen_hstruct,Warning,['rlocals.h','LOCALS']),
file_filter_with_initialization('misc/LOCALS','H/heap/ilocals.h',gen_init,Warning,['ilocals.h','LOCALS']).
warning('~n /* This file, ~a, was generated automatically by \"yap -L misc/buildlocalglobal\"~n please do not update, update misc/~a instead */~n~n'). warning('~n /* This file, ~a, was generated automatically by \"yap -L misc/buildlocalglobal\"~n please do not update, update misc/~a instead */~n~n').
/* define the field */ /* define the field */
gen_struct(Inp,"") :- gen_struct(Inp,Inp) :-
Inp = [0'/,0'/|_], !. Inp = [0'/,0'/|_], !.
gen_struct(Inp,"") :- gen_struct(Inp,Inp) :-
Inp = [0'/,0'*|_], !. Inp = [0'/,0'*|_], !.
gen_struct(Inp, Out) :- gen_struct(Inp, Out) :-
Inp = [0'#|_], !, Out = Inp. % ' Inp = [0'#|_], !, Out = Inp. % '
@ -59,6 +61,12 @@ gen_struct(Inp,Out) :-
gen_struct(Inp,Out) :- gen_struct(Inp,Out) :-
Inp = "END_GLOBAL_DATA", !, Inp = "END_GLOBAL_DATA", !,
Out = "} w_shared;". Out = "} w_shared;".
gen_struct(Inp,Out) :-
Inp = "START_HEAP", !,
Out = "".
gen_struct(Inp,Out) :-
Inp = "END_HEAP", !,
Out = "".
gen_struct(Inp,Out) :- gen_struct(Inp,Out) :-
Inp = "ATOMS", !, Inp = "ATOMS", !,
Out = "#include \"tatoms.h\"". Out = "#include \"tatoms.h\"".
@ -74,7 +82,7 @@ gen_struct(Inp,Out) :-
gen_struct(Inp,"") :- gen_struct(Inp,"") :-
split(Inp," ",["void","void"|_]), !. split(Inp," ",["void","void"|_]), !.
gen_struct(Inp,Out) :- gen_struct(Inp,Out) :-
split(Inp," ",[Type, Field|_]), split(Inp," ",[Type, Field|_]),
split(Field,"[",[RField,VECField]), !, split(Field,"[",[RField,VECField]), !,
append([" ",Type," ",RField,"_","[",VECField,";"], Out). append([" ",Type," ",RField,"_","[",VECField,";"], Out).
gen_struct(Inp,Out) :- gen_struct(Inp,Out) :-
@ -83,7 +91,68 @@ gen_struct(Inp,Out) :-
gen_struct(Inp,_) :- gen_struct(Inp,_) :-
split(Inp," ",[_, _, _| _]), split(Inp," ",[_, _, _| _]),
format(user_error,"OOPS: could not gen_struct for ~s~n",[Inp]). format(user_error,"OOPS: could not gen_struct for ~s~n",[Inp]).
/* define the field */
gen_0struct(Inp,Inp) :-
Inp = [0'/,0'/|_], !.
gen_0struct(Inp,Inp) :-
Inp = [0'/,0'*|_], !.
gen_0struct(Inp, Out) :-
Inp = [0'#|_], !, Out = Inp. % '
gen_0struct(Inp,"") :-
Inp = [0'.|_], !. %'
gen_0struct(Inp,Out) :-
Inp = "START_GLOBAL_DATA", !,
Out = "",
assert(globals(all)).
gen_0struct(Inp,Out) :-
Inp = "END_GLOBAL_DATA", !,
Out = "",
retract(globals(all)).
gen_0struct(Inp,Out) :-
Inp = "START_HEAP", !,
Out = "",
assert(globals(heap)).
gen_0struct(Inp,Out) :-
Inp = "END_HEAP", !,
Out = "",
retract(globals(heap)).
gen_0struct(Inp,Out) :-
Inp = "ATOMS", !,
Out = "#include \"tatoms.h\"".
gen_0struct(Inp,Out) :-
split(Inp," ",["struct",Type, Field|L]), !,
extract("struct", Inp, NInp),
gen_0struct( NInp, NOut ),
extract("EXTERNAL", NOut, IOut),
append("EXTERNAL struct ", IOut, Out).
gen_0struct(Inp,Out) :-
split(Inp," ",["const",Type, Field|L]), !,
extract("const", Inp, NInp),
gen_0struct( NInp, NOut ),
extract("EXTERNAL", NOut, IOut),
append("EXTERNAL const ", IOut, Out).
gen_0struct(Inp,Out) :-
split(Inp," ",["union",Type, Field|L]), !,
extract("union", Inp, NInp),
gen_0struct( NInp, NOut ),
extract("EXTERNAL", NOut, IOut),
append("EXTERNAL union ", IOut, Out).
gen_0struct(Inp,"") :-
split(Inp," ",["void","void"|_]), !.
gen_0struct(Inp,Out) :-
split(Inp," ",[Type, Field|_]),
split(Field,"[",[RField,VECField]), !,
fetch_name(Name, RField),
append(["EXTERNAL ",Type," ",Name,"[",VECField,";"], Out).
gen_0struct(Inp,Out) :-
split(Inp," ",[Type, Field|_]), !,
fetch_name(Name, Field),
append(["EXTERNAL ",Type," ",Name,";"], Out).
gen_0struct(Inp,_) :-
split(Inp," ",[_, _, _| _]),
format(user_error,"OOPS: could not gen_0struct for ~s~n",[Inp]).
gen_dstruct(Inp,"") :- gen_dstruct(Inp,"") :-
Inp = [0'/,0'/|_], !. Inp = [0'/,0'/|_], !.
gen_dstruct(Inp,"") :- gen_dstruct(Inp,"") :-
@ -102,6 +171,12 @@ gen_dstruct(Inp,"") :-
gen_dstruct(Inp,"") :- gen_dstruct(Inp,"") :-
Inp = "END_GLOBAL_DATA", !, Inp = "END_GLOBAL_DATA", !,
retract(globals(all)). retract(globals(all)).
gen_dstruct(Inp,"") :-
Inp = "START_HEAP", !,
assert(globals(heap)).
gen_dstruct(Inp,"") :-
Inp = "END_HEAP", !,
retract(globals(heap)).
gen_dstruct(Inp,Out) :- gen_dstruct(Inp,Out) :-
Inp = "ATOMS", !, Inp = "ATOMS", !,
Out = "". Out = "".
@ -138,6 +213,9 @@ fetch_name(Global,Global2,RField," ") :-
globals(all), !, globals(all), !,
append(["GLOBAL_", RField],Global), append(["GLOBAL_", RField],Global),
append(["Yap_global->", RField,"_"],Global2). append(["Yap_global->", RField,"_"],Global2).
fetch_name(RField,Global2,RField," ") :-
globals(heap), !,
append(["Yap_heap_regs->", RField,"_"],Global2).
fetch_name(Global,Global2,RField," ") :- fetch_name(Global,Global2,RField," ") :-
globals(worker), globals(worker),
append(["LOCAL_", RField],Global), append(["LOCAL_", RField],Global),
@ -161,16 +239,18 @@ fetch_name(Global, RField) :-
fetch_name(Global, RField) :- fetch_name(Global, RField) :-
globals(all), !, globals(all), !,
append(["GLOBAL_", RField],Global). append(["GLOBAL_", RField],Global).
fetch_name(RField, RField) :-
globals(heap), !.
% handle *field[4] % handle *field[4]
cut_c_stuff([0'*|Name], RName) :- !, % 'cut * cut_c_stuff([0'*|Name], RName) :- !, % 'cut *
cut_c_stuff(Name, RName). cut_c_stuff(Name, RName).
cut_c_stuff(Name, RName) :- cut_c_stuff(Name, RName) :-
cut_mat(Name, RName). cut_mat(Name, RName).
cut_mat([], []). cut_mat([], []).
cut_mat([0'[|_], []) :- !. %' cut_mat([0'[|_], []) :- !. %'
cut_mat(H.Name, H.RName) :- cut_mat(H.Name, H.RName) :-
cut_mat(Name, RName). cut_mat(Name, RName).
gen_hstruct(Inp,"") :- gen_hstruct(Inp,"") :-
@ -191,13 +271,21 @@ gen_hstruct(Inp,Out) :-
Out = "}", Out = "}",
retract(globals(worker_init)). retract(globals(worker_init)).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
Inp = "START_GLOBAL_DATA", !, Inp = "START_GLOBAL_DATA", !,
Out = "static void RestoreGlobal(void) {", Out = "static void RestoreGlobal(void) {",
assert(globals(all)). assert(globals(all)).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
Inp = "END_GLOBAL_DATA", !, Inp = "END_GLOBAL_DATA", !,
Out = "}", Out = "}",
retract(globals(all)). retract(globals(all)).
gen_hstruct(Inp,Out) :-
Inp = "START_HEAP", !,
Out = "",
assert(globals(heap)).
gen_hstruct(Inp,Out) :-
Inp = "END_HEAP", !,
Out = "",
retract(globals(heap)).
gen_hstruct(Inp, Out) :- gen_hstruct(Inp, Out) :-
Inp = [0'#|_], !, Out = Inp. % ' Inp = [0'#|_], !, Out = Inp. % '
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
@ -213,18 +301,28 @@ gen_hstruct(Inp,Out) :-
glue(Inp2, " ", Inp3), glue(Inp2, " ", Inp3),
gen_hstruct(Inp3,Out). gen_hstruct(Inp3,Out).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field, "MkAT", _]), !, split(Inp," ",[_, Field, "MkAT", _]),
globals(heap),
!,
fetch_name(Global,Field), fetch_name(Global,Field),
append([" ",Global,Field," = AtomTermAdjust(Yap_heap_regs->",Field,");"], Out). append([" ",Global," = AtomTermAdjust(",Global,");"], Out).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field, "MkPred"| _]), !, globals(heap),
split(Inp," ",[_, Field, "MkPred"| _]),
!,
cut_c_stuff(Field, RField), cut_c_stuff(Field, RField),
fetch_name(Global,RField), fetch_name(Global,RField),
append([" ",Global,RField," = PtoPredAdjust(Yap_heap_regs->",RField,");"], Out). append([" ",Global," = PtoPredAdjust(",Global,");"], Out).
gen_hstruct(Inp,Out) :-
globals(heap),
split(Inp," ",[_, Field, "MkLogPred"| _]), !,
cut_c_stuff(Field, RField),
fetch_name(Global,RField),
append([" ",Global," = PtoPredAdjust(",Global,");"], Out).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field, "MkOp", Name]), !, split(Inp," ",[_, Field, "MkOp", Name]), !,
fetch_name(Global,Field), fetch_name(Global,Field),
append([" ",Global,Field," = Yap_opcode(",Name,");"], Out). append([" ",Global," = Yap_opcode(",Name,");"], Out).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field, "MkLock"]), !, split(Inp," ",[_, Field, "MkLock"]), !,
fetch_name(Global,Field), fetch_name(Global,Field),
@ -232,12 +330,12 @@ gen_hstruct(Inp,Out) :-
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field,"MkRWLock"]), !, split(Inp," ",[_, Field,"MkRWLock"]), !,
fetch_name(Global,Field), fetch_name(Global,Field),
append([" REINIT_RWLOCK(",Global,Field,");"], Out). append([" REINIT_RWLOCK(",Global,");"], Out).
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field,"MkInstE",OP]), !, split(Inp," ",[_, Field,"MkInstE",OP]), !,
cut_c_stuff(Field, RField), cut_c_stuff(Field, RField),
fetch_name(Global,RField), fetch_name(Global,RField),
append([" ",Global,RField,"->opc = Yap_opcode(",OP,");"], Out). append([" ",Global,"->opc = Yap_opcode(",OP,");"], Out).
gen_hstruct(Inp,"") :- gen_hstruct(Inp,"") :-
split(Inp," ",[_, _, _]), !. split(Inp," ",[_, _, _]), !.
gen_hstruct(Inp,"") :- gen_hstruct(Inp,"") :-
@ -246,6 +344,10 @@ gen_hstruct(Inp,Restore) :-
split(Inp," ",[_, _, _, Restore0]), split(Inp," ",[_, _, _, Restore0]),
append("Restore",_,Restore0), !, append("Restore",_,Restore0), !,
append([" ",Restore0,";"],Restore). %' append([" ",Restore0,";"],Restore). %'
gen_hstruct(Inp,Restore) :-
split(Inp," ",[_, _, _, Restore0]),
append("Restore",_,Restore0), !,
append([" ",Restore0,";"],Restore). %'
gen_hstruct(Inp,Out) :- gen_hstruct(Inp,Out) :-
split(Inp," ",[_, Field, _, Adjust]), split(Inp," ",[_, Field, _, Adjust]),
append(Adjust,"Adjust",_), !, append(Adjust,"Adjust",_), !,
@ -274,13 +376,21 @@ gen_init(Inp,Out) :-
Out = "}", Out = "}",
retract(globals(worker_init)). retract(globals(worker_init)).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
Inp = "START_GLOBAL_DATA", !, Inp = "START_GLOBAL_DATA", !,
Out = "static void InitGlobal(void) {", Out = "static void InitGlobal(void) {",
assert(globals(all)). assert(globals(all)).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
Inp = "END_GLOBAL_DATA", !, Inp = "END_GLOBAL_DATA", !,
Out = "}", Out = "}",
retract(globals(all)). retract(globals(all)).
gen_init(Inp,Out) :-
Inp = "START_HEAP", !,
Out = "",
assert(globals(heap)).
gen_init(Inp,Out) :-
Inp = "END_HEAP", !,
Out = "",
retract(globals(heap)).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
split(Inp," ",["struct"|Inp2]), !, split(Inp," ",["struct"|Inp2]), !,
glue(Inp2, " ", Inp3), glue(Inp2, " ", Inp3),
@ -342,6 +452,21 @@ gen_init(Inp,Out) :-
cut_c_stuff(Field, RField), cut_c_stuff(Field, RField),
fetch_name(Global,RField), fetch_name(Global,RField),
append([" ",Global," = RepPredProp(PredPropByFunc(",Fun,",",Module,"));"], Out). append([" ",Global," = RepPredProp(PredPropByFunc(",Fun,",",Module,"));"], Out).
gen_init(Inp,Out) :-
split(Inp," ",[_, Field, "MkLogPred", Atom, "0", Module]), !,
cut_c_stuff(Field, RField),
fetch_name(Global,RField),
append([" ",Global," = Yap_MkLogPred(RepPredProp(PredPropByAtom(",Atom,",",Module,")));"], Out).
gen_init(Inp,Out) :-
split(Inp," ",[_, Field, "MkLogPred", Atom, Arity, Module]), !,
cut_c_stuff(Field, RField),
fetch_name(Global,RField),
append([" ",Global," = Yap_MkLogPred(RepPredProp(PredPropByFunc(Yap_MkFunctor(",Atom,",",Arity,"),",Module,")));"], Out).
gen_init(Inp,Out) :-
split(Inp," ",[_, Field, "MkLogPred", Fun, Module]), !,
cut_c_stuff(Field, RField),
fetch_name(Global,RField),
append([" ",Global," = Yap_MkLogPred(RepPredProp(PredPropByFunc(",Fun,",",Module,")));"], Out).
gen_init(Inp,Out) :- gen_init(Inp,Out) :-
split(Inp," ",[".", Field,F0|_]), !, split(Inp," ",[".", Field,F0|_]), !,
cut_c_stuff(Field, RField), cut_c_stuff(Field, RField),
@ -359,3 +484,18 @@ gen_init(Inp,_) :-
split(Inp," ",[_, _, _| _]), split(Inp," ",[_, _, _| _]),
format(user_error,"OOPS: could not gen_init for ~s~n",[Inp]). format(user_error,"OOPS: could not gen_init for ~s~n",[Inp]).
extract(X, Y, F) :-
append(X, R, Y),
!,
extract(R, F).
extract([0' |H], IF) :- !,
extract( H, IF).
extract([0'\t |H], IF) :- !,
extract( H, IF).
extract(H,H).

View File

@ -69,6 +69,7 @@
;; ; see `prolog-system' below for possible values ;; ; see `prolog-system' below for possible values
;; (setq auto-mode-alist (append '(("\\.pl$" . prolog-mode) ;; (setq auto-mode-alist (append '(("\\.pl$" . prolog-mode)
;; ("\\.yap$" . prolog-mode) ;; ("\\.yap$" . prolog-mode)
;; ("\\.ypp$" . prolog-mode)
;; ("\\.prolog$" . prolog-mode) ;; ("\\.prolog$" . prolog-mode)
;; ("\\.m$" . mercury-mode)) ;; ("\\.m$" . mercury-mode))
;; auto-mode-alist)) ;; auto-mode-alist))
@ -447,9 +448,10 @@ Legal values:
"meta_predicate" "module" "module_transparent" "multifile" "require" "meta_predicate" "module" "module_transparent" "multifile" "require"
"use_module" "volatile")) "use_module" "volatile"))
(yap (yap
("discontiguous" "dynamic" "ensure_loaded" "export" "export_list" "import" ("block" "char_conversion" "discontiguous" "dynamic" "encoding"
"ensure_loaded" "export" "expects_dialect" "export_list" "import"
"meta_predicate" "module" "module_transparent" "multifile" "require" "meta_predicate" "module" "module_transparent" "multifile" "require"
"table" "use_module" "volatile")) "table" "thread_local" "use_module" "wait"))
(gnu (gnu
("built_in" "char_conversion" "discontiguous" "dynamic" "ensure_linked" ("built_in" "char_conversion" "discontiguous" "dynamic" "ensure_linked"
"ensure_loaded" "foreign" "include" "initialization" "multifile" "op" "ensure_loaded" "foreign" "include" "initialization" "multifile" "op"
@ -650,6 +652,7 @@ nil means send actual operating system end of file."
'((eclipse "^[a-zA-Z0-9()]* *\\?- \\|^\\[[a-zA-Z]* [0-9]*\\]:") '((eclipse "^[a-zA-Z0-9()]* *\\?- \\|^\\[[a-zA-Z]* [0-9]*\\]:")
(sicstus "| [ ?][- ] *") (sicstus "| [ ?][- ] *")
(swi "^\\(\\[[a-zA-Z]*\\] \\)?[1-9]?[0-9]*[ ]?\\?- \\|^| +") (swi "^\\(\\[[a-zA-Z]*\\] \\)?[1-9]?[0-9]*[ ]?\\?- \\|^| +")
(yap "^\\(\\[[a-zA-Z]*\\] \\)?[1-9]?[0-9]*[ ]?\\?- \\|^| +")
(t "^ *\\?-")) (t "^ *\\?-"))
"*Alist of prompts of the prolog system command line." "*Alist of prompts of the prolog system command line."
:group 'prolog-inferior :group 'prolog-inferior
@ -657,6 +660,7 @@ nil means send actual operating system end of file."
(defcustom prolog-continued-prompt-regexp (defcustom prolog-continued-prompt-regexp
'((sicstus "^\\(| +\\| +\\)") '((sicstus "^\\(| +\\| +\\)")
(yap` "^\\(| +\\| +\\)")
(t "^|: +")) (t "^|: +"))
"*Alist of regexps matching the prompt when consulting `user'." "*Alist of regexps matching the prompt when consulting `user'."
:group 'prolog-inferior :group 'prolog-inferior

View File

@ -1,831 +0,0 @@
#!/usr/local/bin/yap -L -- $*
#.
:- style_check(all).
:- yap_flag( write_strings, on).
:- yap_flag( gc_trace, verbose ).
:- use_module(library(readutil)).
:- use_module(library(lineutils)).
:- use_module(library(lists)).
:- use_module(library(maplist)).
:- use_module(library(system)).
:- use_module(library(analysis/graphs)).
:- use_module(library(analysis/load)).
:- initialization(main).
:- style_check(all).
:- yap_flag( double_quotes, string ).
%:- yap_flag( dollar_as_lower_case, on ).
:- dynamic
node/4,
edge/1,
public/2,
private/2,
module_on/3,
exported/1,
dir/2,
consulted/2,
op_export/3,
library/1,
undef/2,
c_dep/2,
do_comment/5,
module_file/2.
% @short node(?Module:module, ?Predicate:pred_indicator, ?File:file, ?Generator:atom) is nondet
%
inline( !/0 ).
inline( (\+)/1 ).
inline( (fail)/0 ).
inline( (false)/0 ).
inline( (repeat)/0 ).
inline( (true)/0 ).
inline( []/0 ).
% @short edge(+SourceModule:module, +SourcePredicate:pred_indicator, +TargetPredicate:pred_indicator, +InFile:file) is nondet
%
main :-
init,
fail.
main :-
unix(argv([D])),
Dirs = ['C'-prolog,
'os'-prolog,
'pl'-prolog,
'OPTYap'-prolog,
'library'-user,
% 'swi/console'-user
'packages'-user
],
% maplist(distribute(D), Dirs, Paths),
load( D, Dirs ),
maplist( pl_graphs, Dirs ),
fail.
main :-
%%% phase 4: construct graph
retractall( consulted(_,_) ),
undefs,
doubles,
% pl_exported(pl).
c_links,
mkdocs.
distribute( Root, File-Class, Path-Class) :-
sub_atom(Root,_,_,1,/),
!,
atom_concat(Root, File, Path ).
distribute( Root, File-Class, Path-Class) :-
atom_concat([Root, /, File], Path ).
init :-
retractall(dir(_)),
retractall(edge(_)),
retractall(private(_,_)),
retractall(public(_,_)),
retractall(undef(_,_)),
retractall(consulted(_,_)),
retractall(module_on(_,_,_)),
retractall(op_export(_,_,_)),
retractall(exported(_)),
retractall(do_comment(_,_,_,_,_)).
init :-
user_c_dep(A,B),
do_user_c_dep(A,B),
fail.
init :-
user_skip(A),
do_user_skip(A),
fail.
init :-
user_expand(N,A),
do_user_expand(N,A),
fail.
init :-
catch( make_directory(tmp), _, fail),
fail.
init.
init_loop( _Dirs ).
doubles :-
node(M, P, F-_, _),
node(M1, P, F1-_, _),
M @< M1,
is_public( P, M, F),
is_public( P, M1, F1),
format('~w vs ~w~n', [M:P,M1:P]),
fail.
doubles.
undefs :-
trace,
format('UNDEFINED procedure calls:~n',[]),
setof(M, Target^F^Line^NA^undef( ( Target :- F-M:NA ), Line ), Ms ),
member( Mod, Ms ),
format(' module ~a:~n',[Mod]),
setof(NA, Target^F^Line^undef( ( Target :- F-Mod:NA ), Line ), Ns ),
member( NA, Ns ),
\+ node( Mod , NA , _File1, _ ),
\+ node( prolog , NA , _File2, _ ),
format(' predicate ~w:~n',[NA]),
(
setof(F-Line, Target^undef( ( Target :- F-Mod:NA ), Line ), FLs ),
member(F-L, FLs ),
format(' line ~w, file ~a~n',[L,F]),
fail
;
setof(F-M,Type^node( M, NA, F, Type ) , FMs ),
format(' same name at:~n',[]),
member((F-L)-M, FMs ),
format(' module ~a, file ~a, line ~d~n',[M,F,L]),
fail
).
undefs.
out_list([]) :-
format('[]', []).
out_list([El]) :-
format('[~q]', [El]).
out_list([E1,E2|Es]) :-
format('[~q', [E1]),
maplist(out_el, [E2|Es]),
format(']', []).
out_el( El ) :-
format(',~n ~q',[El]).
pub(M, P) :-
node(M, P, _, _),
P = N/_A,
\+ sub_atom(N,0,1,_,'$').
has_edge(M1, P1, M, F) :-
edge(M1:P1, _P, F:_),
node(M1, P1, _, _),
M1 \= prolog,
M1 \= M,
\+ is_public(P1, M1, _).
mod_priv(M, P) :-
node(M, P, _, _),
node(M, P, _, _),
\+ is_public(P, M, _),
edge(M1:P, _P0, _), M1 \= M.
priv(M, P) :-
node(M, P, F:_, _),
\+ is_public(P, M, _),
edge(_:P, _P1, F1:_), F1 \= F.
% utilities
split_string( S , Cs, N) :-
string_codes(S, S1),
string_codes(Cs, NCs),
split(S1, NCs, Ncs0),
maplist(remove_escapes, Ncs0, Ncs),
maplist(string_codes, N, Ncs).
remove_escapes([0'\\ ,A|Cs], [A|NCs]) :- !, %'
remove_escapes(Cs, NCs).
remove_escapes([A|Cs], [A|NCs]) :-
remove_escapes(Cs, NCs).
remove_escapes( [], [] ).
always_strip_module(V, M, V1) :- var(V), !,
V = M:call(V1).
always_strip_module(M0:A, M0, call(A)) :- var(A), !.
always_strip_module(_:M0:A, M1, B) :- !,
always_strip_module(M0:A, M1, B).
always_strip_module(M0:A, M0, call(A)) :- var(A),!.
always_strip_module(M0:A, M0, A).
c_links :-
open('tmp/foreigns.yap', write, S),
clinks(S),
fail.
c_links :-
open('tmp/foreigns.c', write, S),
cclinks(S),
fail.
clinks(S) :-
module_file( F, NM ),
format( S, 'mod( ~q , ~q ).~n', [NM, F] ),
fail.
clinks(S) :-
system_predicate(C),
functor(C, N, A),
format( S, 'sys ~q/~d.~n', [N, A] ),
fail.
clinks(S) :-
exported( ( Fi0-M:F/A :- Fi1-M1:F1/A ) ),
( M \= M1 -> M \= prolog ; F \= F1 ),
% functor(S0, F, A),
% S0 =.. [F| Args],
% S1 =.. [F1| Args],
% numbervars(Args, 0, _),
format( S, '% ~q <- ~q.~n~q:~q imports ~q:~q. ~n', [Fi0, Fi1, M,F/A, M1,F1/A] ),
fail.
clinks(S) :-
close(S).
cclinks(S) :-
node( M, F/A, File-_Line, c(F)),
% functor( S0, F, A),
% S0 =.. [F| Args],
% S1 =.. [foreign, F| Args],
% numbervars(Args, 0, _),
format( S, '/// @file ~a~n', [File] ),
format( S, '/// @memberof ~a ~a:~a/~d~n', [F, M, F, A] ),
fail.
cclinks(S) :-
close(S).
warn_singletons(_Vars, _Pos).
%%
% comment( +Comment )
%
% Handle documentation comments
%
comment( _Pos - Comment) :-
skip_blanks(1, Comment, N),
doc( Comment, N ),
format( "%s\n", [Comment] ),
!.
comment( _Pos - _Comment).
skip_blanks(I, Comment, N) :-
get_string_code( I, Comment, Code ),
code_type( Code, space ),
I1 is I+1,
skip_blanks(I1, Comment, N).
skip_blanks(N, _Comment, N).
doc( Comment , N ) :-
N1 is N+1,
sub_string( Comment, N1, 3, _, Header ),
( Header == "/**" -> true ; Header == "/*!" ), !, % */
N4 is N+4,
get_string_code( N4, Comment, Code ),
code_type( Code, space ).
doc( Comment, N ) :-
N1 is N+1,
sub_string( Comment, N1, 2, _, Header ),
( Header == "%%" -> true ; Header == "%!" ),
N3 is N+3,
get_string_code( N3, Comment, Code ),
code_type( Code, space ).
%%
% search_file( +Target, +Location, +FileType, -File )
%
%
% Directories into atoms
search_file( Loc , F, Type, FN ) :-
search_file0( Loc , F, Type, FN ),
!.
search_file( Loc , F, _FN ) :-
format('~n~n~n###############~n~n FAILED TO FIND ~w when at ~a~n~n###############~n~n~n', [Loc, F ]),
fail.
%
% handle some special cases.
%
search_file0( F, _, _Type, FN ) :-
doexpand(F, FN), !.
search_file0( A/B, F, Type, FN ) :- !,
term_to_atom(A/B, AB),
search_file0( AB, F, Type, FN ).
% libraries can be anywhere in the source.
search_file0( LibLoc, F, Type, FN ) :-
LibLoc =.. [Dir,File],
!,
( term_to_atom( Dir/File, Full ) ; Full = File ),
search_file0( Full, F, Type, FN ).
%try to use your base
search_file0( Loc , F, c, FN ) :-
atom_concat( D, '.yap', F),
atom_concat( [ D, '/', Loc], F1),
check_suffix( F1 , c, NLoc ),
absolute_file_name( NLoc, FN),
file_base_name( FN, LocNam),
file_directory_name( FN, D),
dir( D, LocNam ).
search_file0( Loc , F, Type, FN ) :-
file_directory_name( F, FD),
check_suffix( Loc , Type, LocS ),
atom_concat( [ FD, '/', LocS], NLoc),
absolute_file_name( NLoc, FN),
file_base_name( FN, LocNam),
file_directory_name( FN, D),
dir( D, LocNam).
search_file0( Loc , _F, Type, FN ) :-
file_base_name( Loc, Loc0),
file_directory_name( Loc, LocD),
check_suffix( Loc0 , Type, LocS ),
dir( D, LocS),
sub_dir( D, DD),
atom_concat( [ DD, '/', LocD], NLoc),
absolute_file_name( NLoc, D),
atom_concat( [D,'/', LocS], FN).
search_file0( Loc , _F, Type, FN ) :-
file_base_name( Loc, Loc0),
check_suffix( Loc0 , Type, LocS ),
dir( D, LocS),
atom_concat( [D,'/', LocS], FN).
% you try using the parent
sub_dir( D, D ).
sub_dir( D, DD) :-
D \= '/',
atom_concat( D, '/..', DD0),
absolute_file_name( DD0, DDA),
sub_dir( DDA, DD).
% files must be called .yap or .pl
% if it is .yap...
check_suffix( Loc , pl, Loc ) :-
atom_concat( _, '.yap', Loc ), !.
%, otherwise, .pl
check_suffix( Loc , pl, Loc ) :-
atom_concat( _, '.pl', Loc ), !.
%, otherwise, .prolog
check_suffix( Loc , pl, Loc ) :-
atom_concat( _, '.prolog', Loc ), !.
%, otherwise, .P
% try adding suffix
check_suffix( Loc0 , pl, Loc ) :-
member( Suf , ['.yap', '.ypp', '.pl' , '.prolog']),
atom_concat( Loc0, Suf, Loc ).
check_suffix( Loc , c, Loc ) :-
atom_concat( _, '.c', Loc ), !.
%, otherwise, .pl
check_suffix( Loc , c, Loc ) :-
atom_concat( _, '.icc', Loc ), !.
%, otherwise, .prolog
check_suffix( Loc , c, Loc ) :-
atom_concat( _, '.cpp', Loc ), !.
%, otherwise, .P
% try adding suffix
check_suffix( Loc0 , c, Loc ) :-
member( Suf , ['.c', '.icc' , '.cpp']),
atom_concat( Loc0, Suf, Loc ).
match_file( LocD, Loc0, Type, FN ) :-
var(LocD), !,
dir( LocD, Loc0 ),
atom_concat( [LocD, '/', Loc0], F ),
absolute_file_name( F, Type, FN ),
exists( FN ).
match_file( SufLocD, Loc0, Type, FN ) :-
dir( LocD, Loc0 ),
atom_concat(_, SufLocD, LocD ),
atom_concat( [LocD, '/', Loc0], Type, FN ).
new_op( F, M, op(X,Y,Z) ) :-
nb_getval( private, true ),
!,
private( F, M, op(X,Y,Z) ),
op( X, Y, Z).
new_op( F, M, op( X, Y, Z) ) :-
public( F, M, op( X, Y, Z) ).
ypp(F, error(syntax_error(syntax_error),[syntax_error(read(_228515),between(K,L,M),_,_L,_)-_]) ) :-
format('SYNTAX ERROR at file ~a, line ~d (~d - ~d).~n', [F,L,K,M] ),
break.
preprocess_file(F,NF) :-
atom_concat(_, '.ypp', F ), !,
atom_concat( [ 'cpp -CC -w -DMYDDAS_MYSQL -DMYDDAS_ODBC -DMYDDAS_STATS -DMYDDAS_TOP_LEVEL -P ',F], OF ),
NF = pipe( OF ).
preprocess_file(F,F).
%%%%%%%
%% declare a concept export1able
public( F, M, op(X,Y,Z) ) :-
retract( private( F, M:op(X,Y,Z) ) ),
fail.
public( F, M, op(X,Y,Z) ) :- !,
assert( op_export(F, _M, op(X,Y,Z) ) ),
assert_new( public( F, M:op(X,Y,Z) ) ),
(
( M == user ; M == prolog )
->
op( X, Y, prolog:Z )
;
op( X, Y, M:Z )
).
public( F, M, M:N/Ar ) :-
retract( private( F, M:N/Ar ) ),
fail.
public( F, M, N/Ar ) :-
assert_new( public( F, M:N/Ar ) ),
\+ node( M, N/Ar, F-_, _ ),
nb_getval( line, L ),
assert( node( M, N/Ar, F-L, prolog ) ), !.
public( _F, _M, _/_Ar ).
public( F, M, M:N//Ar ) :-
Ar2 is Ar+2,
retract( private( F, M:N/Ar2 ) ),
fail.
public( F, M, N//Ar ) :-
Ar2 is Ar+2,
assert_new( public( F, M:N/Ar2 ) ),
\+ node( M, N/Ar2, F-_, _ ),
nb_getval( line, L ),
assert( node( M, N/Ar2, F-L, prolog ) ), !.
public( _F, _M, _//_Ar ).
private( F, M, op(X,Y,Z) ) :-
assert_new( private( F, M:op(X,Y,Z) ) ),
(
( M == user ; M == prolog )
->
op( X, Y, prolog:Z )
;
op( X, Y, M:Z )
), !.
private( _F, _M, op(_X,_Y,_Z) ).
private( F, M, N/Ar ) :-
assert_new( private( F, M:N/Ar ) ),
\+ node( M, N/Ar, F-_, _ ),
nb_getval( line, L ),
assert( node( M, N/Ar, F-L, prolog ) ), !.
private( _F, _M, _N/_Ar ).
private( F, M, N//Ar ) :-
Ar2 is Ar+2,
assert_new( private( F, M:N/Ar2 ) ),
\+ node( M, N/Ar2, F-_, _ ),
nb_getval( line, L ),
assert_new( node( M, N/Ar2, F-L, prolog ) ), !.
private( _F, _M, _N//_Ar ).
is_public( F, M, OP ) :-
public( F, M:OP ).
is_private( F, M, OP ) :-
private( F, M :OP ).
assert_new( G ) :- G, !.
assert_new( G ) :- assert( G ).
error( Error ) :- throw(Error ).
%% mkdocs inserts a file with a sequence of comments into a sequence of Prolog/C files.
%
%
mkdocs :-
open( 'tmp/pages', write, S1),
close( S1 ),
open( 'tmp/bads', write, S2),
close( S2 ),
open( 'tmp/groups', write, S3),
close( S3 ),
open( 'tmp/groups.yap', write, S4),
close( S4 ),
open( 'docs/yapdocs.yap', read, S),
repeat,
(
blanks(S, Comment, Rest)
->
get_comment(S, Rest),
store_comment( Comment ),
fail
;
close(S),
!,
add_comments
).
blanks( S , T, TF) :-
read_line_to_codes(S, T1, T2),
( T1 == end_of_file -> fail;
T2 == [] -> fail;
T1 \== T2, foldl( check, [0'/,0'*,0'*],T1, _) -> TF = T2, T = T1 ; % '
blanks( S , T, TF) ).
get_comment( S , T) :-
read_line_to_codes(S, T, T0),
( T == end_of_file -> T = [];
T0 == [] -> T=[];
diff_end( [0'*,0'/,10],T, T0 ) -> true ;
get_comment( S , T0) ).
check(C, [C0|L], L) :-
C == C0.
diff_end( L, T, [] ) :-
append(_, L, T).
store_comment(Comment) :-
header( Pred, A, Comment, _ ),
atom_codes( P, Pred),
( node( Mod, P/A, File-Line, Type) ->
true
;
format('Missing definition for ~q.~n', [P/A] ),
node( Mod, P/Ar, File-Line, Type),
format(' ~w exists.~n',[Mod:P/Ar]),
fail
),
( node( M1, P/A, _, _), M1 \= Mod -> Dup = true ; Dup = false),
!,
string_codes( C, Comment ),
assert( do_comment( File, Line, C, Type, Dup ) ).
store_comment(Comment) :-
page( Comment, _ ), !,
open( 'tmp/pages', append, S),
format(S, '*******************************~n~n~s~n~n', [Comment]),
close(S).
store_comment(Comment) :-
defgroup( Comment, _ ), !,
open( 'tmp/groups', append, S),
format(S, '*******************************~n~n~s~n~n', [Comment]),
close(S).
store_comment(Comment) :-
open( 'tmp/bads', append, S),
format(S, '*******************************~n~n~s~n~n', [Comment]),
close(S).
defgroup -->
"/**", % */
blanks_or_stars,
"@defgroup".
defgroup -->
"%%", % */
blanks_or_percs,
"@defgroup".
page -->
"/**", % */
blanks,
"@page".
header(Pred, Arity) -->
"/**", % */
blanks,
"@pred",
blanks,
atom(_),
":",
!,
atom(Pred),
atom_pred(Arity).
header(Pred, Arity) -->
"/**", % */
blanks,
"@pred",
blanks,
atom(Pred),
atom_pred(Arity),
!.
header(Pred, 2, Comment, _) :-
split(Comment, [[0'/,0'*,0'*],[0'@,0'p,0'r,0'e,0'd],_,Pred,_,[0'i,0's]|_]), !.
atom_pred(Arity) -->
"/", !,
int( 0, Arity ).
atom_pred(N) -->
"(",
!,
decl(1,N).
atom_pred(0) -->
blanks, !.
int(I0, I) -->
[A],
{ A >= "0", A =< "9" },
!,
{ I1 is I0*10+(A-"0") },
int(I1, I).
int( I, I ) --> [].
decl(I, I) -->
")", !.
decl(I0, I) -->
",", !,
{ I1 is I0+1 },
decl(I1, I).
decl(I0, I) -->
[_],
decl( I0, I).
skip_early_comment(C) -->
[C], !,
skip_early_comment(C).
skip_early_comment(C) -->
( " " ; "\t" ; "\n" ), !,
skip_early_comment(C).
skip_early_comment(C) -->
"@", ( "{" ; "}" ), !,
skip_early_comment(C).
skip_early_comment(_) --> [].
blanks --> " ", !, blanks.
blanks --> "\t", !, blanks.
blanks --> [].
atom([A|As]) -->
[A],
{ A >= "a", A =< "z" },
atom2( As ).
atom2([A|As]) -->
[A],
{ A >= "a", A =< "z" -> true ;
A >= "A", A =< "Z" -> true ;
A >= "0", A =< "9" -> true ;
A =:= "_"
},
!,
atom2( As ).
atom2([]) --> [].
add_comments :-
open('tmp/comments.yap', write, S),
findall(File, do_comment( File, Line, C, Type, Dup), Fs0 ),
(
sort(Fs0, Fs),
member( File, Fs ),
setof(Line-C-Type-Dup, do_comment( File, Line, C, Type, Dup) , Lines0 ),
reverse( Lines0, Lines),
member(Line-Comment-Type-Dup, Lines),
check_comment( Comment, CN, Line, File ),
Line1 is Line-1,
format(S, '#~a~ncat << "EOF" > tmp~n~sEOF~nsed -e "~dr tmp" ~a > x~n\
mv x ~a~n~n',[Dup,CN, Line1, File, File])
;
close(S)
),
fail.
add_comments :-
listing( open_comment ).
check_comment( Comment, CN, _Line, _qFile ) :-
string_codes( Comment, [_,_,_|C]),
check_groups(0,_C,[]),
check_quotes(0,C,[]),
(
append(C0,[0'@,0'},0' ,0'*,0'/,10], C) -> %'
append(C0,[0'*,0'/,10], CN)
;
CN = C
),
!.
check_comment( Comment, Comment, Line, File ) :-
format(user_error,'*** bad comment ~a ~d~n~n~s~n~', [File,Line,Comment]).
check_groups(0) --> [].
check_quotes( 0 ) --> [].
check_quotes( 0 ) -->
"`", !,
check_quotes( 1 ).
check_quotes( 1 ) -->
"`", !,
check_quotes( 0 ).
check_quotes( 1 ) -->
"\"", !, { fail }.
check_quotes( 1 ) -->
"'", !, { fail }. %'
check_quotes( N ) -->
[_],
check_quotes( N ).
%%%
% ops_default sets operators back to YAP default.
%
ops_default :-
abolish( default_ops/1 ),
A = (_,_), functor(A,Comma,2),
findall(op(X,Y,prolog:Z), ( current_op(X,Y,prolog:Z), Z\= Comma ), L),
assert_static( default_ops(L) ).
:- initialization(ops_default, now).
ops_restore :-
A = (_,_), functor(A,Comma,2),
current_op(_X,Y,prolog:Z),
Z\= Comma,
op(0,Y,prolog:Z),
fail.
ops_restore :-
default_ops(L),
maplist( call, L ).
do_user_c_dep(F1, F2) :-
absolute_file_name(F1, A1),
absolute_file_name(F2, A2),
assert(c_dep(A1, A2)).
do_user_skip(F1) :-
absolute_file_name(F1, A1),
assert(doskip(A1)).
do_user_expand(F, F1) :-
absolute_file_name(F1, A1),
assert(doexpand(F, A1)).
user_deps( F, M ) :-
c_dep(F, A2),
c_file(A2 , M),
fail.
user_deps( _F, _M ).
user_c_dep( 'packages/jpl/jpl.pl', 'packages/jpl/src/c/jpl.c' ).
user_c_dep( 'packages/real/real.pl', 'packages/real/real.c' ).
user_c_dep( 'packages/odbc/odbc.pl', 'packages/odbc/odbc.c' ).
user_c_dep( 'packages/clib/unix.pl', 'packages/clib/unix.c' ).
user_c_dep( 'packages/clib/cgi.pl', 'packages/clib/cgi.c' ).
user_c_dep( 'packages/clib/crypt.pl', 'packages/clib/crypt.c' ).
user_c_dep( 'packages/clib/filesex.pl', 'packages/clib/files.c' ).
user_c_dep( 'packages/clib/mime.pl', 'packages/clib/mime.c' ).
user_c_dep( 'packages/clib/socket.pl', 'packages/clib/socket.c' ).
user_c_dep( 'packages/clib/socket.pl', 'packages/clib/winpipe.c' ).
user_c_dep( 'packages/http/http_stream.pl', 'packages/http/cgi_stream.c' ).
user_c_dep( 'packages/http/http_stream.pl', 'packages/http/stream_range.c' ).
user_c_dep( 'packages/http/http_stream.pl', 'packages/http/http_chunked.c' ).
user_c_dep( 'packages/http/http_stream.pl', 'packages/http/http_error.c' ).
user_c_dep( 'packages/swi-minisat2/minisat.pl', 'packages/swi-minisat2/C/pl-minisat.C' ).
user_c_dep( 'packages/gecode/gecode.yap', 'packages/gecode/gecode4_yap.cc' ).
user_c_dep( 'packages/gecode/gecode.yap', 'packages/gecode/4.2.1/gecode_yap_cc_forward_auto_generated.icc' ).
user_c_dep( 'packages/gecode/gecode.yap', 'packages/gecode/4.2.1/gecode_yap_cc_init_auto_generated.icc' ).
user_c_dep( 'packages/gecode/gecode.yap', 'packages/gecode/4.2.1/gecode_yap_cc_impl_auto_generated.icc' ).
user_c_dep( 'packages/semweb/rdf_db.pl', 'packages/semweb/atom_map.c' ).
user_c_dep( 'packages/semweb/rdf_db.pl', 'packages/semweb/resource.c' ).
user_c_dep( 'packages/sgml/sgml.pl', 'packages/sgml/quote.c' ).
user_c_dep( 'swi/library/readutil.pl', 'packages/clib/readutil.c' ).
user_c_dep( 'packages/myddas/pl/myddas.ypp', 'packages/myddas/myddas_shared.c' ).
user_c_dep( 'packages/myddas/pl/myddas.ypp', 'packages/myddas/myddas_odbc.c' ).
user_c_dep( 'packages/myddas/pl/myddas.ypp', 'packages/myddas/myddas_mysql.c' ).
user_c_dep( 'packages/myddas/pl/myddas.ypp', 'packages/myddas/myddas_top_level.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/bpx.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/error.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/fputil.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/gamma.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/glue.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/idtable.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/idtable_preds.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/random.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/termpool.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/vector.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/core/xmalloc.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/em_aux.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/em_aux_ml.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/em_aux_vb.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/em_ml.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/em_preds.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/flags.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/graph.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/graph_aux.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/hindsight.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/util.c' ).
user_c_dep( 'packages/prism/src/prolog/prism.yap', 'packages/prism/src/c/up/viterbi.c' ).
doskip( D):- sub_atom( D, _, _, 0, '~' ).
doskip( D):- sub_atom( D, _, _, 0, '/.' ).
doskip( D):- sub_atom( D, _, _, 0, '/..' ).
doskip( D):- sub_atom( D, _, _, 0, '/.git' ).
doskip( D):- sub_atom( D, _, _, _, '/.#' ).
doskip( D):- sub_atom( D, _, _, 0, '#' ).
doskip( D):- user_skip( D ).
user_skip( 'packages/gecode/3.6.0').
user_skip( 'packages/gecode/3.7.0').
user_skip( 'packages/gecode/3.7.1').
user_skip( 'packages/gecode/3.7.2').
user_skip( 'packages/gecode/3.7.3').
user_skip( 'packages/gecode/4.0.0').
user_skip( 'packages/gecode/4.2.0').
user_skip( 'packages/gecode/4.2.1').
user_skip( 'packages/gecode/gecode3.yap' ).
user_skip( 'packages/gecode/gecode3_yap.cc' ).
user_skip( 'packages/gecode/gecode3_yap_hand_written.yap').
user_skip( 'packages/gecode/gecode3.yap-common.icc').
user_skip( 'packages/prism/src/prolog/core').
user_skip( 'packages/prism/src/prolog/up').
user_skip( 'packages/prism/src/prolog/mp').
user_skip( 'packages/prism/src/prolog/trans').
user_skip( 'packages/prism/src/prolog/bp').
user_skip( 'packages/prism/src/c').
user_expand( library(clpfd), 'library/clp/clpfd.pl' ).

View File

@ -1,3 +1,34 @@
current_predicate 2
X Y _ :- op(test, fx, 1200).
goal_expansion Y goal_expansion(_)
test_mode.
test( ( G :- Sols ) :-
reset_sols,
init_io( Streams ),
catch( do_test(G, Sols), Done, handler( Done ) ).
close_io( Streams ).
do_test(G0, Sols)
copy_term(G0, G),
catch( ( G, answer(G, Sol) ) , Error, test_error(Error, Sol) ),
next_solution( I, Sol, G0, Sol ),
!.
do_test(G, Sols) :-
counter(I),
failure(G, Sols, I).
next_solution( I, Sol , G0, Sols ) :-
inc(I),
fetch(I, Sols, Pattern, Next),
(
Sol =@= Pattern
->
success(I, G0)
;
error(I, G0, Sol )
),
( var(Next) -> throw( done ) ).

View File

@ -53,7 +53,9 @@ if (READLINE_FOUND)
# READLINE_readline_LIBRARY, where to find the READLINE library. # READLINE_readline_LIBRARY, where to find the READLINE library.
# READLINE_ncurses_LIBRARY, where to find the ncurses library [might not be defined] # READLINE_ncurses_LIBRARY, where to find the ncurses library [might not be defined]
set( CMAKE_REQUIRED_INCLUDES ${READLINE_INCLUDE_DIR} ${CMAKE_REQUIRED_INCLUDES} ) include_directories (BEFORE ${READLINE_INCLUDE_DIR})
set(YAP_SYSTEM_OPTIONS "readline " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
set( CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${READLINE_LIBRARIES} ) set( CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${READLINE_LIBRARIES} )
check_include_files( "stdio.h;readline/readline.h" HAVE_READLINE_READLINE_H ) check_include_files( "stdio.h;readline/readline.h" HAVE_READLINE_READLINE_H )
check_include_files( "stdio.h;readline/history.h" HAVE_READLINE_HISTORY_H ) check_include_files( "stdio.h;readline/history.h" HAVE_READLINE_HISTORY_H )
@ -81,15 +83,17 @@ endif (READLINE_FOUND)
set (POSITION_INDEPENDENT_CODE TRUE) set (POSITION_INDEPENDENT_CODE TRUE)
add_library (libYAPOs OBJECT add_library (libYAPOs OBJECT
${YAPOS_SOURCES} ) ${YAPOS_SOURCES}
)
set_target_properties(libYAPOs set_target_properties(libYAPOs
PROPERTIES PROPERTIES
# RPATH ${libdir} VERSION ${LIBYAPTAI_FULL_VERSION} # RPATH ${libdir} VERSION ${LIBYAPTAI_FULL_VERSION}
# SOVERSION ${LIBYAPTAI_MAJOR_VERSION}.${LIBYAPTAI_MINOR_VERSION} # SOVERSION ${LIBYAPTAI_MAJOR_VERSION}.${LIBYAPTAI_MINOR_VERSION}
POSITION_INDEPENDENT_CODE TRUE POSITION_INDEPENDENT_CODE TRUE
OUTPUT_NAME YAPOs OUTPUT_NAME YAPOs
depends dheap
) )
configure_file ("${PROJECT_SOURCE_DIR}/os/YapIOConfig.h.cmake" configure_file ("${PROJECT_SOURCE_DIR}/os/YapIOConfig.h.cmake"
@ -97,6 +101,6 @@ configure_file ("${PROJECT_SOURCE_DIR}/os/YapIOConfig.h.cmake"
set( READLINE_LIBS ${READLINE_LIBRARIES} PARENT_SCOPE) set( READLINE_LIBS ${READLINE_LIBRARIES} PARENT_SCOPE)
#set( CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${GMP_LIBRARIES} ) #set( CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${GMP_LIBRARIES} )

View File

@ -105,8 +105,8 @@ Int Yap_peek(int sno) {
Int ch; Int ch;
s = GLOBAL_Stream + sno; s = GLOBAL_Stream + sno;
if ( s->status & Readline_Stream_f) { if (s->status & Readline_Stream_f) {
ch = Yap_ReadlinePeekChar( sno ); ch = Yap_ReadlinePeekChar(sno);
if (ch == EOFCHAR) { if (ch == EOFCHAR) {
s->stream_getc = EOFPeek; s->stream_getc = EOFPeek;
s->stream_wgetc = EOFWPeek; s->stream_wgetc = EOFWPeek;
@ -118,12 +118,12 @@ Int Yap_peek(int sno) {
olinecount = s->linecount; olinecount = s->linecount;
olinepos = s->linepos; olinepos = s->linepos;
ch = s->stream_wgetc(sno); ch = s->stream_wgetc(sno);
s ->och = ch; s->och = ch;
if (ch == EOFCHAR) { if (ch == EOFCHAR) {
s->stream_getc = EOFPeek; s->stream_getc = EOFPeek;
s->stream_wgetc = EOFWPeek; s->stream_wgetc = EOFWPeek;
s->status |= Push_Eof_Stream_f; s->status |= Push_Eof_Stream_f;
return ch; return ch;
} }
s->charcount = ocharcount; s->charcount = ocharcount;
s->linecount = olinecount; s->linecount = olinecount;
@ -131,40 +131,39 @@ Int Yap_peek(int sno) {
/* buffer the character */ /* buffer the character */
if (s->encoding == LOCAL_encoding) { if (s->encoding == LOCAL_encoding) {
ungetwc(ch, s->file); ungetwc(ch, s->file);
} else if (s->encoding == ENC_OCTET || } else if (s->encoding == ENC_OCTET || s->encoding == ENC_ISO_LATIN1 ||
s->encoding == ENC_ISO_LATIN1|| s->encoding == ENC_ISO_ASCII) {
s->encoding == ENC_ISO_ASCII) {
ungetc(ch, s->file); ungetc(ch, s->file);
} else if (s->encoding == ENC_ISO_UTF8) { } else if (s->encoding == ENC_ISO_UTF8) {
unsigned char cs[8]; unsigned char cs[8];
size_t n = put_utf8(cs, ch ); size_t n = put_utf8(cs, ch);
while (n--) { while (n--) {
ungetc(cs[n-1], s->file); ungetc(cs[n - 1], s->file);
} }
} else if (s->encoding == ENC_UTF16_BE) { } else if (s->encoding == ENC_UTF16_BE) {
/* do the ungetc as if a write .. */ /* do the ungetc as if a write .. */
unsigned long int c = ch; unsigned long int c = ch;
if (c >((1<<16)-1)) { if (c > ((1 << 16) - 1)) {
ungetc(c/1<<16, s->file); ungetc(c / 1 << 16, s->file);
c %= 1<< 16; c %= 1 << 16;
} }
ungetc(c, s->file); ungetc(c, s->file);
} else if (s->encoding == ENC_UTF16_BE) { } else if (s->encoding == ENC_UTF16_BE) {
/* do the ungetc as if a write .. */ /* do the ungetc as if a write .. */
unsigned long int c = ch; unsigned long int c = ch;
if (c > ((1<<16)-1)) { if (c > ((1 << 16) - 1)) {
ungetc(c/1<<16, s->file); ungetc(c / 1 << 16, s->file);
c %= 1<< 16; c %= 1 << 16;
} }
} else if (s->encoding == ENC_UTF16_LE) { } else if (s->encoding == ENC_UTF16_LE) {
/* do the ungetc as if a write .. */ /* do the ungetc as if a write .. */
unsigned long int c = ch; unsigned long int c = ch;
if (c >(( 1<<16)-1)) { if (c > ((1 << 16) - 1)) {
ungetc(c%1<<16, s->file); ungetc(c % 1 << 16, s->file);
c /= 1<< 16; c /= 1 << 16;
} }
ungetc(c, s->file); ungetc(c, s->file);
} else { } else {
int (*f)(int, int) = s->stream_putc; int (*f)(int, int) = s->stream_putc;
s->stream_putc = plUnGetc; s->stream_putc = plUnGetc;
put_wchar(sno, ch); put_wchar(sno, ch);
@ -512,7 +511,7 @@ static Int put_code(USES_REGS1) { /* '$put'(Stream,N) */
return (FALSE); return (FALSE);
if (GLOBAL_Stream[sno].status & Binary_Stream_f) { if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "put/2"); Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "put/2");
return (FALSE); return (FALSE);
} }
@ -552,7 +551,7 @@ static Int put_char_1(USES_REGS1) { /* '$put'(,N) */
LOCK(GLOBAL_Stream[sno].streamlock); LOCK(GLOBAL_Stream[sno].streamlock);
if (GLOBAL_Stream[sno].status & Binary_Stream_f) { if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "put/2"); Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "put/2");
return (FALSE); return (FALSE);
} }
GLOBAL_Stream[sno].stream_wputc(sno, ch); GLOBAL_Stream[sno].stream_wputc(sno, ch);
@ -590,7 +589,7 @@ static Int put_char(USES_REGS1) { /* '$put'(Stream,N) */
return (FALSE); return (FALSE);
if (GLOBAL_Stream[sno].status & Binary_Stream_f) { if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "put/2"); Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "put/2");
return (FALSE); return (FALSE);
} }
GLOBAL_Stream[sno].stream_wputc(sno, (int)IntegerOfTerm(Deref(ARG2))); GLOBAL_Stream[sno].stream_wputc(sno, (int)IntegerOfTerm(Deref(ARG2)));
@ -627,7 +626,7 @@ static Int tab_1(USES_REGS1) { /* nl */
LOCK(GLOBAL_Stream[sno].streamlock); LOCK(GLOBAL_Stream[sno].streamlock);
if (GLOBAL_Stream[sno].status & Binary_Stream_f) { if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "nl/0"); Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "nl/0");
return (FALSE); return (FALSE);
} }
@ -667,7 +666,7 @@ static Int tab(USES_REGS1) { /* nl(Stream) */
if (GLOBAL_Stream[sno].status & Binary_Stream_f) { if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "nl/0"); Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "nl/0");
return (FALSE); return (FALSE);
} }
@ -755,7 +754,7 @@ static Int put_byte(USES_REGS1) { /* '$put_byte'(Stream,N) */
// && strictISOFlag() // && strictISOFlag()
) { ) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, NULL); Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, NULL);
return false; return false;
} }
GLOBAL_Stream[sno].stream_putc(sno, ch); GLOBAL_Stream[sno].stream_putc(sno, ch);
@ -794,7 +793,7 @@ static Int put_byte_1(USES_REGS1) { /* '$put_byte'(Stream,N) */
//&& strictISOFlag() //&& strictISOFlag()
) { ) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_OUTPUT_TEXT_STREAM, ARG1, "get0/2"); Yap_Error(PERMISSION_ERROR_OUTPUT_BINARY_STREAM, ARG1, "get0/2");
return (FALSE); return (FALSE);
} }
GLOBAL_Stream[sno].stream_putc(sno, ch); GLOBAL_Stream[sno].stream_putc(sno, ch);
@ -937,7 +936,7 @@ static Int peek_code(USES_REGS1) { /* at_end_of_stream */
return FALSE; return FALSE;
if (GLOBAL_Stream[sno].status & Binary_Stream_f) { if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_INPUT_BINARY_STREAM, ARG1, "peek_code/2"); Yap_Error(PERMISSION_ERROR_INPUT_TEXT_STREAM, ARG1, "peek_code/2");
return FALSE; return FALSE;
} }
if ((ch = Yap_peek(sno)) < 0) { if ((ch = Yap_peek(sno)) < 0) {
@ -967,7 +966,7 @@ static Int peek_code_1(USES_REGS1) { /* at_end_of_stream */
LOCK(GLOBAL_Stream[sno].streamlock); LOCK(GLOBAL_Stream[sno].streamlock);
if (GLOBAL_Stream[sno].status & Binary_Stream_f) { if (GLOBAL_Stream[sno].status & Binary_Stream_f) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_INPUT_BINARY_STREAM, ARG1, "peek_code/2"); Yap_Error(PERMISSION_ERROR_INPUT_TEXT_STREAM, ARG1, "peek_code/2");
return FALSE; return FALSE;
} }
if ((ch = Yap_peek(sno)) < 0) { if ((ch = Yap_peek(sno)) < 0) {
@ -996,7 +995,7 @@ static Int peek_byte(USES_REGS1) { /* at_end_of_stream */
return (FALSE); return (FALSE);
if (!(GLOBAL_Stream[sno].status & Binary_Stream_f)) { if (!(GLOBAL_Stream[sno].status & Binary_Stream_f)) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_INPUT_STREAM, ARG1, "peek_byte/2"); Yap_Error(PERMISSION_ERROR_INPUT_BINARY_STREAM, ARG1, "peek_byte/2");
return (FALSE); return (FALSE);
} }
if ((ch = dopeek_byte(sno)) < 0) { if ((ch = dopeek_byte(sno)) < 0) {
@ -1026,7 +1025,7 @@ static Int peek_byte_1(USES_REGS1) { /* at_end_of_stream */
LOCK(GLOBAL_Stream[sno].streamlock); LOCK(GLOBAL_Stream[sno].streamlock);
if (!(GLOBAL_Stream[sno].status & Binary_Stream_f)) { if (!(GLOBAL_Stream[sno].status & Binary_Stream_f)) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
Yap_Error(PERMISSION_ERROR_INPUT_TEXT_STREAM, ARG1, "peek_byte/2"); Yap_Error(PERMISSION_ERROR_INPUT_BINARY_STREAM, ARG1, "peek_byte/2");
return (FALSE); return (FALSE);
} }
if ((ch = dopeek_byte(sno)) < 0) { if ((ch = dopeek_byte(sno)) < 0) {

View File

@ -1220,7 +1220,7 @@ static Int format(Term tout, Term tf, Term tas USES_REGS) {
return false; return false;
UNLOCK(GLOBAL_Stream[output_stream].streamlock); UNLOCK(GLOBAL_Stream[output_stream].streamlock);
} else { } else {
yhandle_t sls = Yap_CurrentSlot(PASS_REGS1); yhandle_t sls = Yap_CurrentSlot();
out = doformat(tf, tas, output_stream PASS_REGS); out = doformat(tf, tas, output_stream PASS_REGS);

View File

@ -573,7 +573,7 @@ static int EOFWGetc(int sno) {
return EOF; return EOF;
} }
if (ResetEOF(s)) { if (ResetEOF(s)) {
Yap_ConsoleOps(s); Yap_ConsoleOps(s);
return (s->stream_wgetc(sno)); return (s->stream_wgetc(sno));
} }
return EOF; return EOF;
@ -589,7 +589,7 @@ static int EOFGetc(int sno) {
return EOF; return EOF;
} }
if (ResetEOF(s)) { if (ResetEOF(s)) {
Yap_ConsoleOps(s); Yap_ConsoleOps(s);
return s->stream_getc(sno); return s->stream_getc(sno);
} }
return EOF; return EOF;
@ -646,20 +646,17 @@ int post_process_weof(StreamDesc *s) {
return EOFCHAR; return EOFCHAR;
} }
/** /**
* caled after EOF found a peek, it just calls console_post_process to conclude the job. * caled after EOF found a peek, it just calls console_post_process to conclude
* *the job.
* @param sno *
* * @param sno
*
* @return EOF * @return EOF
*/ */
int EOFPeek(int sno) { int EOFPeek(int sno) { return EOFGetc(sno); }
return EOFGetc( sno );
}
int EOFWPeek(int sno) { int EOFWPeek(int sno) { return EOFWGetc(sno); }
return EOFWGetc( sno );
}
/* standard routine, it should read from anything pointed by a FILE *. /* standard routine, it should read from anything pointed by a FILE *.
It could be made more efficient by doing our own buffering and avoiding It could be made more efficient by doing our own buffering and avoiding
@ -841,7 +838,7 @@ static int get_wchar(int sno) {
if (how_many) { if (how_many) {
/* error */ /* error */
} }
return post_process_weof(GLOBAL_Stream+sno); return post_process_weof(GLOBAL_Stream + sno);
} }
wide_char(); wide_char();
} }
@ -1383,10 +1380,8 @@ do_open(Term file_name, Term t2,
} }
} }
// BOM mess // BOM mess
if ((encoding == ENC_OCTET || if ((encoding == ENC_OCTET || encoding == ENC_ISO_ASCII ||
encoding == ENC_ISO_ASCII || encoding == ENC_ISO_LATIN1 || encoding == ENC_ISO_UTF8 || bin)) {
encoding == ENC_ISO_LATIN1 ||
encoding == ENC_ISO_UTF8 || bin)) {
avoid_bom = true; avoid_bom = true;
} }
if (args[OPEN_BOM].used) { if (args[OPEN_BOM].used) {
@ -1546,7 +1541,7 @@ static int CheckStream__(const char *file, const char *f, int line, Term arg,
if (sname == AtomUser) { if (sname == AtomUser) {
if (kind & Input_Stream_f) { if (kind & Input_Stream_f) {
if (kind & (Output_Stream_f | Append_Stream_f)) { if (kind & (Output_Stream_f | Append_Stream_f)) {
PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_STREAM, arg, PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_STREAM, arg,
"ambiguous use of 'user' as a stream"); "ambiguous use of 'user' as a stream");
return (-1); return (-1);
} }
@ -1581,12 +1576,12 @@ static int CheckStream__(const char *file, const char *f, int line, Term arg,
if ((GLOBAL_Stream[sno].status & Input_Stream_f) && if ((GLOBAL_Stream[sno].status & Input_Stream_f) &&
!(kind & Input_Stream_f)) { !(kind & Input_Stream_f)) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_STREAM, arg, msg); PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_STREAM, arg, msg);
} }
if ((GLOBAL_Stream[sno].status & (Append_Stream_f | Output_Stream_f)) && if ((GLOBAL_Stream[sno].status & (Append_Stream_f | Output_Stream_f)) &&
!(kind & Output_Stream_f)) { !(kind & Output_Stream_f)) {
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_STREAM, arg, msg); PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_STREAM, arg, msg);
} }
return (sno); return (sno);
} }
@ -1602,7 +1597,12 @@ int Yap_CheckTextStream__(const char *file, const char *f, int line, Term arg,
if ((sno = CheckStream__(file, f, line, arg, kind, msg)) < 0) if ((sno = CheckStream__(file, f, line, arg, kind, msg)) < 0)
return -1; return -1;
if ((GLOBAL_Stream[sno].status & Binary_Stream_f)) { if ((GLOBAL_Stream[sno].status & Binary_Stream_f)) {
PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_BINARY_STREAM, arg, msg); if (kind == Input_Stream_f)
PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_BINARY_STREAM, arg,
msg);
else
PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_BINARY_STREAM, arg,
msg);
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);
return -1; return -1;
} }

View File

@ -351,12 +351,12 @@ Term Yap_syntax_error(TokEntry *errtok, int sno) {
tn[0] = Yap_MkApplTerm(FunctorShortSyntaxError, 1, &terr); tn[0] = Yap_MkApplTerm(FunctorShortSyntaxError, 1, &terr);
tn[1] = TermNil; tn[1] = TermNil;
terr = Yap_MkApplTerm(FunctorError, 2, tn); terr = Yap_MkApplTerm(FunctorError, 2, tn);
#if DEBUG #if DEBUG
if (Yap_ExecutionMode == YAP_BOOT_MODE) { if (Yap_ExecutionMode == YAP_BOOT_MODE) {
fprintf(stderr, "SYNTAX ERROR while booting: "); fprintf(stderr, "SYNTAX ERROR while booting: ");
Yap_DebugPlWriteln( terr ); Yap_DebugPlWriteln(terr);
} }
#endif #endif
return terr; return terr;
} }
@ -400,6 +400,7 @@ static xarg *setReadEnv(Term opts, FEnv *fe, struct renv *re, int inp_stream) {
if (args == NULL) { if (args == NULL) {
return NULL; return NULL;
} }
re->bq = getBackQuotesFlag(); re->bq = getBackQuotesFlag();
if (args[READ_MODULE].used) { if (args[READ_MODULE].used) {
CurrentModule = args[READ_MODULE].tvalue; CurrentModule = args[READ_MODULE].tvalue;
@ -456,7 +457,8 @@ static xarg *setReadEnv(Term opts, FEnv *fe, struct renv *re, int inp_stream) {
re->prio = IntegerOfTerm(args[READ_PRIORITY].tvalue); re->prio = IntegerOfTerm(args[READ_PRIORITY].tvalue);
if (re->prio > GLOBAL_MaxPriority) { if (re->prio > GLOBAL_MaxPriority) {
Yap_Error(DOMAIN_ERROR_OPERATOR_PRIORITY, opts, Yap_Error(DOMAIN_ERROR_OPERATOR_PRIORITY, opts,
"max priority in Prolog is %d, not %ld", GLOBAL_MaxPriority, re->prio); "max priority in Prolog is %d, not %ld", GLOBAL_MaxPriority,
re->prio);
} }
} else { } else {
re->prio = LOCAL_default_priority; re->prio = LOCAL_default_priority;
@ -660,7 +662,7 @@ static parser_state_t scan(REnv *re, FEnv *fe, int inp_stream) {
and floats */ and floats */
LOCAL_tokptr = LOCAL_toktide = LOCAL_tokptr = LOCAL_toktide =
Yap_tokenizer(GLOBAL_Stream + inp_stream, false, &fe->tpos); Yap_tokenizer(GLOBAL_Stream + inp_stream, false, &fe->tpos);
if (LOCAL_ErrorMessage) if (LOCAL_ErrorMessage)
return YAP_SCANNING_ERROR; return YAP_SCANNING_ERROR;
if (LOCAL_tokptr->Tok != Ord(eot_tok)) { if (LOCAL_tokptr->Tok != Ord(eot_tok)) {
@ -809,6 +811,16 @@ Term Yap_read_term(int inp_stream, Term opts, int nargs) {
return fe.t; return fe.t;
} }
} }
if (fe.t) {
if (fe.reading_clause &&
!complete_clause_processing(&fe, LOCAL_tokptr, fe.t))
fe.t = 0;
else if (!fe.reading_clause && !complete_processing(&fe, LOCAL_tokptr))
fe.t = 0;
}
#if EMACS
first_char = tokstart->TokPos;
#endif /* EMACS */
return fe.t; return fe.t;
} }
@ -819,7 +831,7 @@ static Int
if ((rc = Yap_read_term(LOCAL_c_input_stream, ARG2, 2)) == 0) if ((rc = Yap_read_term(LOCAL_c_input_stream, ARG2, 2)) == 0)
return FALSE; return FALSE;
Term tf = Yap_GetFromSlot(h); Term tf = Yap_GetFromSlot(h);
Yap_RecoverSlots(1, h PASS_REGS); Yap_RecoverSlots(1, h);
return Yap_unify(tf, rc); return Yap_unify(tf, rc);
} }
@ -837,7 +849,7 @@ static Int read_term(
out = Yap_read_term(inp_stream, ARG3, 3); out = Yap_read_term(inp_stream, ARG3, 3);
UNLOCK(GLOBAL_Stream[inp_stream].streamlock); UNLOCK(GLOBAL_Stream[inp_stream].streamlock);
Term tf = Yap_GetFromSlot(h); Term tf = Yap_GetFromSlot(h);
Yap_RecoverSlots(1, h PASS_REGS); Yap_RecoverSlots(1, h);
return out != 0L && Yap_unify(tf, out); return out != 0L && Yap_unify(tf, out);
} }
@ -987,7 +999,7 @@ static Int read_clause2(USES_REGS1) {
yhandle_t h = Yap_InitSlot(ARG1); yhandle_t h = Yap_InitSlot(ARG1);
rc = Yap_read_term(LOCAL_c_input_stream, Deref(ARG2), -2); rc = Yap_read_term(LOCAL_c_input_stream, Deref(ARG2), -2);
Term tf = Yap_GetFromSlot(h); Term tf = Yap_GetFromSlot(h);
Yap_RecoverSlots(1, h PASS_REGS); Yap_RecoverSlots(1, h);
return rc && Yap_unify(tf, rc); return rc && Yap_unify(tf, rc);
} }
@ -1025,7 +1037,7 @@ static Int read_clause(
out = Yap_read_term(inp_stream, t3, -3); out = Yap_read_term(inp_stream, t3, -3);
UNLOCK(GLOBAL_Stream[inp_stream].streamlock); UNLOCK(GLOBAL_Stream[inp_stream].streamlock);
Term tf = Yap_GetFromSlot(h); Term tf = Yap_GetFromSlot(h);
Yap_RecoverSlots(1, h PASS_REGS); Yap_RecoverSlots(1, h);
return out && Yap_unify(tf, out); return out && Yap_unify(tf, out);
} }
@ -1181,7 +1193,7 @@ Term Yap_StringToTerm(const char *s, size_t len, encoding_t *encp, int prio,
*bindings = Yap_GetFromSlot(sl); *bindings = Yap_GetFromSlot(sl);
} }
if (bindings) { if (bindings) {
Yap_RecoverSlots(sl, 1 PASS_REGS); Yap_RecoverSlots(sl, 1);
} }
return rval; return rval;
} }

View File

@ -241,7 +241,7 @@ read_stream_to_terms(USES_REGS1)
RESET_VARIABLE(HR); RESET_VARIABLE(HR);
RESET_VARIABLE(HR+1); RESET_VARIABLE(HR+1);
hd = (CELL)HR; hd = (CELL)HR;
Yap_PutInSlot(news, (CELL)(HR+1) PASS_REGS); Yap_PutInSlot(news, (CELL)(HR+1));
HR += 2; HR += 2;
while ((hd=Yap_read_term(sno, TermNil, 2)) == 0L) while ((hd=Yap_read_term(sno, TermNil, 2)) == 0L)
; ;
@ -253,7 +253,7 @@ read_stream_to_terms(USES_REGS1)
} else { } else {
CELL *newpt = (CELL*)Yap_GetFromSlot(news); CELL *newpt = (CELL*)Yap_GetFromSlot(news);
*pt =AbsPair(newpt-1); *pt =AbsPair(newpt-1);
Yap_PutInSlot(tails, (CELL)newpt PASS_REGS); Yap_PutInSlot(tails, (CELL)newpt);
} }
} }
UNLOCK(GLOBAL_Stream[sno].streamlock); UNLOCK(GLOBAL_Stream[sno].streamlock);

View File

@ -718,8 +718,8 @@ void Yap_walltime_interval(Int *now,Int *interval)
Yap_ReInitWTime (void) Yap_ReInitWTime (void)
{ {
Yap_InitWTime(); Yap_InitWTime();
if (Yap_global->LastWTimePtr_ != NULL) if (GLOBAL_LastWTimePtr != NULL)
Yap_FreeCodeSpace(Yap_global->LastWTimePtr_); Yap_FreeCodeSpace(GLOBAL_LastWTimePtr);
Yap_InitLastWTime(); Yap_InitLastWTime();
} }

View File

@ -20,7 +20,7 @@ static char SccsId[] = "%W% %G%";
/* /*
* This file includes the definition of a miscellania of standard predicates * This file includes the definition of a miscellania of standard predicates
* for yap refering to: Files and GLOBAL_Streams, Simple Input/Output, * for yap refering to: Files and GLOBAL_Streams, Simple Input/Output,
* *
*/ */
@ -49,7 +49,7 @@ static char SccsId[] = "%W% %G%";
#ifdef HAVE_SYS_STAT_H #ifdef HAVE_SYS_STAT_H
#include <sys/stat.h> #include <sys/stat.h>
#endif #endif
#if HAVE_SYS_SELECT_H && !_MSC_VER && !defined(__MINGW32__) #if HAVE_SYS_SELECT_H && !_MSC_VER && !defined(__MINGW32__)
#include <sys/select.h> #include <sys/select.h>
#endif #endif
#ifdef HAVE_UNISTD_H #ifdef HAVE_UNISTD_H
@ -77,7 +77,7 @@ static char SccsId[] = "%W% %G%";
#if !HAVE_STRNCPY #if !HAVE_STRNCPY
#define strncpy(X,Y,Z) strcpy(X,Y) #define strncpy(X,Y,Z) strcpy(X,Y)
#endif #endif
#if _MSC_VER || defined(__MINGW32__) #if _MSC_VER || defined(__MINGW32__)
#if HAVE_SOCKET #if HAVE_SOCKET
#include <winsock2.h> #include <winsock2.h>
#endif #endif
@ -88,7 +88,7 @@ static char SccsId[] = "%W% %G%";
#endif #endif
#include "iopreds.h" #include "iopreds.h"
#if _MSC_VER || defined(__MINGW32__) #if _MSC_VER || defined(__MINGW32__)
#define SYSTEM_STAT _stat #define SYSTEM_STAT _stat
#else #else
#define SYSTEM_STAT stat #define SYSTEM_STAT stat
@ -102,7 +102,7 @@ static char SccsId[] = "%W% %G%";
int beam_write ( USES_REGS1 ) int beam_write ( USES_REGS1 )
{ {
Yap_StartSlots(); Yap_StartSlots();
Yap_plwrite (ARG1, GLOBAL_Stream+LOCAL_output_stream, 0, 0, 1200); Yap_plwrite (ARG1, GLOBAL_Stream+LOCAL_output_stream, 0, 0, GLOBAL_MaxPriority);
Yap_CloseSlots(); Yap_CloseSlots();
if (EX != 0L) { if (EX != 0L) {
Term ball = Yap_PopTermFromDB(EX); Term ball = Yap_PopTermFromDB(EX);
@ -122,7 +122,7 @@ p_write ( USES_REGS1 )
/* notice: we must have ASP well set when using portray, otherwise /* notice: we must have ASP well set when using portray, otherwise
we cannot make recursive Prolog calls */ we cannot make recursive Prolog calls */
yhandle_t mySlots = Yap_StartSlots(); yhandle_t mySlots = Yap_StartSlots();
Yap_plwrite (ARG2, GLOBAL_Stream+LOCAL_output_stream, 0, flags, 1200); Yap_plwrite (ARG2, GLOBAL_Stream+LOCAL_output_stream, 0, flags, GLOBAL_MaxPriority);
Yap_CloseSlots( mySlots ); Yap_CloseSlots( mySlots );
if (EX != 0L) { if (EX != 0L) {
Term ball = Yap_PopTermFromDB(EX); Term ball = Yap_PopTermFromDB(EX);
@ -159,8 +159,7 @@ p_write2_prio ( USES_REGS1 )
Int flags = IntegerOfTerm(Deref(ARG2)); Int flags = IntegerOfTerm(Deref(ARG2));
int stream_f; int stream_f;
stream_f = Output_Stream_f; LOCAL_output_stream = CheckTextStream(ARG1, Output_Stream_f, "write/2");
LOCAL_output_stream = CheckStream (ARG1, stream_f, "write/2");
if (LOCAL_output_stream == -1) { if (LOCAL_output_stream == -1) {
LOCAL_output_stream = old_output_stream; LOCAL_output_stream = old_output_stream;
return(FALSE); return(FALSE);
@ -185,7 +184,7 @@ static Int
p_write2 ( USES_REGS1 ) p_write2 ( USES_REGS1 )
{ /* '$write'(+Stream,+Flags,?Term) */ { /* '$write'(+Stream,+Flags,?Term) */
int old_output_stream = LOCAL_output_stream; int old_output_stream = LOCAL_output_stream;
LOCAL_output_stream = CheckStream (ARG1, Output_Stream_f, "write/2"); LOCAL_output_stream = CheckTextStream(ARG1, Output_Stream_f, "write/2");
if (LOCAL_output_stream == -1) { if (LOCAL_output_stream == -1) {
LOCAL_output_stream = old_output_stream; LOCAL_output_stream = old_output_stream;
return(FALSE); return(FALSE);
@ -194,7 +193,7 @@ p_write2 ( USES_REGS1 )
/* notice: we must have ASP well set when using portray, otherwise /* notice: we must have ASP well set when using portray, otherwise
we cannot make recursive Prolog calls */ we cannot make recursive Prolog calls */
yhandle_t myslots = Yap_StartSlots(); yhandle_t myslots = Yap_StartSlots();
Yap_plwrite (ARG3, GLOBAL_Stream+LOCAL_output_stream, 0, (int) IntOfTerm (Deref (ARG2)), 1200); Yap_plwrite (ARG3, GLOBAL_Stream+LOCAL_output_stream, 0, (int) IntOfTerm (Deref (ARG2)), GLOBAL_MaxPriority);
Yap_CloseSlots(myslots); Yap_CloseSlots(myslots);
LOCAL_output_stream = old_output_stream; LOCAL_output_stream = old_output_stream;
if (EX != 0L) { if (EX != 0L) {

View File

@ -148,36 +148,8 @@ void Yap_init_socks(char *host, long interface_port);
extern int errno; extern int errno;
#endif #endif
INLINE_ONLY EXTERN UInt inline HashFunction(const unsigned char *); uint64_t HashFunction(const unsigned char *);
INLINE_ONLY EXTERN UInt inline WideHashFunction(wchar_t *); uint64_t WideHashFunction(wchar_t *);
INLINE_ONLY EXTERN inline UInt HashFunction(const unsigned char *CHP) {
/* djb2 */
UInt hash = 5381;
UInt c;
while ((c = (UInt)(*CHP++)) != '\0') {
/* hash = ((hash << 5) + hash) + c; hash * 33 + c */
hash = hash * 33 ^ c;
}
return hash;
/*
UInt OUT=0, i = 1;
while(*CHP != '\0') { OUT += (UInt)(*CHP++); }
return OUT;
*/
}
INLINE_ONLY EXTERN UInt inline WideHashFunction(wchar_t *CHP) {
UInt hash = 5381;
UInt c;
while ((c = *CHP++) != '\0') {
hash = hash * 33 ^ c;
}
return hash;
}
INLINE_ONLY inline EXTERN Term MkCharTerm(Int c); INLINE_ONLY inline EXTERN Term MkCharTerm(Int c);

View File

@ -21,6 +21,7 @@
:- use_module(library(atts)). :- use_module(library(atts)).
:- use_module(library(bhash)). :- use_module(library(bhash)).
:- use_module(library(lists)). :- use_module(library(lists)).
@ -33,7 +34,7 @@
:- attribute key/1, dist/2, evidence/1. :- attribute key/1, dist/2, evidence/1.
:- use_module('clpbn/ve', :- use_module(clpbn/ve,
[ve/3, [ve/3,
check_if_ve_done/1, check_if_ve_done/1,
init_ve_solver/4, init_ve_solver/4,
@ -198,7 +199,7 @@ clpbn_flag(parameter_softening,Before,After) :- !,
retract(parameter_softening(Before)), retract(parameter_softening(Before)),
assert(parameter_softening(After)). assert(parameter_softening(After)).
clpbn_flag(use_factors,Before,After) :- !, clpbn_flag(use_parfactors,Before,After) :- !,
retract(use_parfactors(Before)), retract(use_parfactors(Before)),
assert(use_parfactors(After)). assert(use_parfactors(After)).

View File

@ -248,7 +248,7 @@ This option allows exporting the current model to the href{http://graphmod.ics.u
+ export_graphviz + export_graphviz
This option allows exporting the factor graph's structure into a format that can be parsed by href{http://www.graphviz.org/}{Graphviz}. This option allows exporting the factor graph's structure into a format that xocan be parsed by href{http://www.graphviz.org/}{Graphviz}.
+ Values: `true` or `false` (default). + Values: `true` or `false` (default).
+ Affects: `hve`, `bp`, and `cbp`. + Affects: `hve`, `bp`, and `cbp`.
@ -362,7 +362,7 @@ The options that are available with the `set_pfl_flag/2` predicate can be used i
-> ->
% we're using factor language % we're using factor language
% set appropriate flag % set appropriate flag
set_pfl_flag(use_factors,on) set_pfl_flag(use_parfactors,on)
; ;
% we're within clp(bn), no need to do anything % we're within clp(bn), no need to do anything
true true
@ -504,7 +504,11 @@ new_skolem(Sk, D) :-
functor(Sk, N, A), functor(Sk, N, A),
functor(NSk, N, A), functor(NSk, N, A),
% [f,t] is special for evidence % [f,t] is special for evidence
( D = [f,t] -> assert((evidence(NSk, 1) :- user:NSk)) ; true ), ( D = [f,t] ->
dynamic(N/A),
assert((evidence(NSk, 1) :- user:NSk))
;
true ),
interface_predicate(NSk), interface_predicate(NSk),
assert(skolem(NSk, D)). assert(skolem(NSk, D)).

View File

@ -75,7 +75,8 @@ grounder_compute_reachable_atoms(A,ID,Success) :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
( % go over all proofs for A in interpretation ID ( % go over all proofs for A in interpretation ID
tabled_meta_interpreter(A,ID), tabled_meta_interpreter(A,ID),
writeln(A),
bb_put(dep_proven,true), bb_put(dep_proven,true),
fail; % go to next proof fail; % go to next proof
@ -100,6 +101,8 @@ grounder_compute_reachable_atoms(A,ID,Success) :-
%======================================================================== %========================================================================
tabled_meta_interpreter(X,ID) :-
writeln(ID:X), fail.
tabled_meta_interpreter((X,Y),ID) :- tabled_meta_interpreter((X,Y),ID) :-
!, !,
tabled_meta_interpreter(X,ID), tabled_meta_interpreter(X,ID),
@ -143,9 +146,9 @@ tabled_meta_interpreter(Atom,ID) :-
% we can ignore probabilistic facts and only look for myclauses % we can ignore probabilistic facts and only look for myclauses
% since in ProbLog the requirement is that non-ground facts have to be % since in ProbLog the requirement is that non-ground facts have to be
% ground at query time % ground at query time
current_predicate(user:myclause/3), current_predicate(user:myclause/3),
user:myclause(ID,Atom,Body), user:myclause(ID,Atom,Body),
writeln(Atom:Body),
tabled_meta_interpreter(Body,ID), tabled_meta_interpreter(Body,ID),

View File

@ -228,8 +228,9 @@
:- initialization(( :- initialization((
bb_put(logger_filename,'out.dat'), bb_put(logger_filename,'out.dat'),
bb_put(logger_delimiter,';'), bb_put(logger_delimiter,';'),
bb_put(logger_variables,[]) bb_put(logger_variables,[])
)). )).
%======================================================================== %========================================================================
%= Defines a new variable, possible types are: int, float and time %= Defines a new variable, possible types are: int, float and time

View File

@ -53,7 +53,7 @@ myclause(calls(Person), (person(Person),alarm,hears_alarm(Person))).
%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Training examples % %%% Training examples %
%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%l
example(1). example(1).
example(2). example(2).
@ -64,4 +64,3 @@ known(1,alarm,true).
%%%% Example 2 %%%% Example 2
known(2,earthquake,false). known(2,earthquake,false).
known(2,calls(mary),true). known(2,calls(mary),true).

View File

@ -10,71 +10,71 @@
% http://dtai.cs.kuleuven.be/problog % http://dtai.cs.kuleuven.be/problog
% %
% ProbLog was developed at Katholieke Universiteit Leuven % ProbLog was developed at Katholieke Universiteit Leuven
% %
% Copyright 2009 % Copyright 2009
% Angelika Kimmig, Vitor Santos Costa, Bernd Gutmann % Angelika Kimmig, Vitor Santos Costa, Bernd Gutmann
% %
% Main author of this file: % Main author of this file:
% Bernd Gutmann % Bernd Gutmann
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% Artistic License 2.0 % Artistic License 2.0
% %
% Copyright (c) 2000-2006, The Perl Foundation. % Copyright (c) 2000-2006, The Perl Foundation.
% %
% Everyone is permitted to copy and distribute verbatim copies of this % Everyone is permitted to copy and distribute verbatim copies of this
% license document, but changing it is not allowed. Preamble % license document, but changing it is not allowed. Preamble
% %
% This license establishes the terms under which a given free software % This license establishes the terms under which a given free software
% Package may be copied, modified, distributed, and/or % Package may be copied, modified, distributed, and/or
% redistributed. The intent is that the Copyright Holder maintains some % redistributed. The intent is that the Copyright Holder maintains some
% artistic control over the development of that Package while still % artistic control over the development of that Package while still
% keeping the Package available as open source and free software. % keeping the Package available as open source and free software.
% %
% You are always permitted to make arrangements wholly outside of this % You are always permitted to make arrangements wholly outside of this
% license directly with the Copyright Holder of a given Package. If the % license directly with the Copyright Holder of a given Package. If the
% terms of this license do not permit the full use that you propose to % terms of this license do not permit the full use that you propose to
% make of the Package, you should contact the Copyright Holder and seek % make of the Package, you should contact the Copyright Holder and seek
% a different licensing arrangement. Definitions % a different licensing arrangement. Definitions
% %
% "Copyright Holder" means the individual(s) or organization(s) named in % "Copyright Holder" means the individual(s) or organization(s) named in
% the copyright notice for the entire Package. % the copyright notice for the entire Package.
% %
% "Contributor" means any party that has contributed code or other % "Contributor" means any party that has contributed code or other
% material to the Package, in accordance with the Copyright Holder's % material to the Package, in accordance with the Copyright Holder's
% procedures. % procedures.
% %
% "You" and "your" means any person who would like to copy, distribute, % "You" and "your" means any person who would like to copy, distribute,
% or modify the Package. % or modify the Package.
% %
% "Package" means the collection of files distributed by the Copyright % "Package" means the collection of files distributed by the Copyright
% Holder, and derivatives of that collection and/or of those files. A % Holder, and derivatives of that collection and/or of those files. A
% given Package may consist of either the Standard Version, or a % given Package may consist of either the Standard Version, or a
% Modified Version. % Modified Version.
% %
% "Distribute" means providing a copy of the Package or making it % "Distribute" means providing a copy of the Package or making it
% accessible to anyone else, or in the case of a company or % accessible to anyone else, or in the case of a company or
% organization, to others outside of your company or organization. % organization, to others outside of your company or organization.
% %
% "Distributor Fee" means any fee that you charge for Distributing this % "Distributor Fee" means any fee that you charge for Distributing this
% Package or providing support for this Package to another party. It % Package or providing support for this Package to another party. It
% does not mean licensing fees. % does not mean licensing fees.
% %
% "Standard Version" refers to the Package if it has not been modified, % "Standard Version" refers to the Package if it has not been modified,
% or has been modified only in ways explicitly requested by the % or has been modified only in ways explicitly requested by the
% Copyright Holder. % Copyright Holder.
% %
% "Modified Version" means the Package, if it has been changed, and such % "Modified Version" means the Package, if it has been changed, and such
% changes were not explicitly requested by the Copyright Holder. % changes were not explicitly requested by the Copyright Holder.
% %
% "Original License" means this Artistic License as Distributed with the % "Original License" means this Artistic License as Distributed with the
% Standard Version of the Package, in its current version or as it may % Standard Version of the Package, in its current version or as it may
% be modified by The Perl Foundation in the future. % be modified by The Perl Foundation in the future.
% %
% "Source" form means the source code, documentation source, and % "Source" form means the source code, documentation source, and
% configuration files for the Package. % configuration files for the Package.
% %
% "Compiled" form means the compiled bytecode, object code, binary, or % "Compiled" form means the compiled bytecode, object code, binary, or
% any other form resulting from mechanical transformation or translation % any other form resulting from mechanical transformation or translation
% of the Source form. % of the Source form.
@ -82,34 +82,34 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% Permission for Use and Modification Without Distribution % Permission for Use and Modification Without Distribution
% %
% (1) You are permitted to use the Standard Version and create and use % (1) You are permitted to use the Standard Version and create and use
% Modified Versions for any purpose without restriction, provided that % Modified Versions for any purpose without restriction, provided that
% you do not Distribute the Modified Version. % you do not Distribute the Modified Version.
% %
% Permissions for Redistribution of the Standard Version % Permissions for Redistribution of the Standard Version
% %
% (2) You may Distribute verbatim copies of the Source form of the % (2) You may Distribute verbatim copies of the Source form of the
% Standard Version of this Package in any medium without restriction, % Standard Version of this Package in any medium without restriction,
% either gratis or for a Distributor Fee, provided that you duplicate % either gratis or for a Distributor Fee, provided that you duplicate
% all of the original copyright notices and associated disclaimers. At % all of the original copyright notices and associated disclaimers. At
% your discretion, such verbatim copies may or may not include a % your discretion, such verbatim copies may or may not include a
% Compiled form of the Package. % Compiled form of the Package.
% %
% (3) You may apply any bug fixes, portability changes, and other % (3) You may apply any bug fixes, portability changes, and other
% modifications made available from the Copyright Holder. The resulting % modifications made available from the Copyright Holder. The resulting
% Package will still be considered the Standard Version, and as such % Package will still be considered the Standard Version, and as such
% will be subject to the Original License. % will be subject to the Original License.
% %
% Distribution of Modified Versions of the Package as Source % Distribution of Modified Versions of the Package as Source
% %
% (4) You may Distribute your Modified Version as Source (either gratis % (4) You may Distribute your Modified Version as Source (either gratis
% or for a Distributor Fee, and with or without a Compiled form of the % or for a Distributor Fee, and with or without a Compiled form of the
% Modified Version) provided that you clearly document how it differs % Modified Version) provided that you clearly document how it differs
% from the Standard Version, including, but not limited to, documenting % from the Standard Version, including, but not limited to, documenting
% any non-standard features, executables, or modules, and provided that % any non-standard features, executables, or modules, and provided that
% you do at least ONE of the following: % you do at least ONE of the following:
% %
% (a) make the Modified Version available to the Copyright Holder of the % (a) make the Modified Version available to the Copyright Holder of the
% Standard Version, under the Original License, so that the Copyright % Standard Version, under the Original License, so that the Copyright
% Holder may include your modifications in the Standard Version. (b) % Holder may include your modifications in the Standard Version. (b)
@ -128,7 +128,7 @@
% %
% Distribution of Compiled Forms of the Standard Version or % Distribution of Compiled Forms of the Standard Version or
% Modified Versions without the Source % Modified Versions without the Source
% %
% (5) You may Distribute Compiled forms of the Standard Version without % (5) You may Distribute Compiled forms of the Standard Version without
% the Source, provided that you include complete instructions on how to % the Source, provided that you include complete instructions on how to
% get the Source of the Standard Version. Such instructions must be % get the Source of the Standard Version. Such instructions must be
@ -139,13 +139,13 @@
% within thirty days after you become aware that the instructions are % within thirty days after you become aware that the instructions are
% invalid, then you do not forfeit any of your rights under this % invalid, then you do not forfeit any of your rights under this
% license. % license.
% %
% (6) You may Distribute a Modified Version in Compiled form without the % (6) You may Distribute a Modified Version in Compiled form without the
% Source, provided that you comply with Section 4 with respect to the % Source, provided that you comply with Section 4 with respect to the
% Source of the Modified Version. % Source of the Modified Version.
% %
% Aggregating or Linking the Package % Aggregating or Linking the Package
% %
% (7) You may aggregate the Package (either the Standard Version or % (7) You may aggregate the Package (either the Standard Version or
% Modified Version) with other packages and Distribute the resulting % Modified Version) with other packages and Distribute the resulting
% aggregation provided that you do not charge a licensing fee for the % aggregation provided that you do not charge a licensing fee for the
@ -153,7 +153,7 @@
% components in the aggregation are permitted. The terms of this license % components in the aggregation are permitted. The terms of this license
% apply to the use and Distribution of the Standard or Modified Versions % apply to the use and Distribution of the Standard or Modified Versions
% as included in the aggregation. % as included in the aggregation.
% %
% (8) You are permitted to link Modified and Standard Versions with % (8) You are permitted to link Modified and Standard Versions with
% other works, to embed the Package in a larger work of your own, or to % other works, to embed the Package in a larger work of your own, or to
% build stand-alone binary or bytecode versions of applications that % build stand-alone binary or bytecode versions of applications that
@ -161,7 +161,7 @@
% provided the result does not expose a direct interface to the Package. % provided the result does not expose a direct interface to the Package.
% %
% Items That are Not Considered Part of a Modified Version % Items That are Not Considered Part of a Modified Version
% %
% (9) Works (including, but not limited to, modules and scripts) that % (9) Works (including, but not limited to, modules and scripts) that
% merely extend or make use of the Package, do not, by themselves, cause % merely extend or make use of the Package, do not, by themselves, cause
% the Package to be a Modified Version. In addition, such works are not % the Package to be a Modified Version. In addition, such works are not
@ -169,21 +169,21 @@
% terms of this license. % terms of this license.
% %
% General Provisions % General Provisions
% %
% (10) Any use, modification, and distribution of the Standard or % (10) Any use, modification, and distribution of the Standard or
% Modified Versions is governed by this Artistic License. By using, % Modified Versions is governed by this Artistic License. By using,
% modifying or distributing the Package, you accept this license. Do not % modifying or distributing the Package, you accept this license. Do not
% use, modify, or distribute the Package, if you do not accept this % use, modify, or distribute the Package, if you do not accept this
% license. % license.
% %
% (11) If your Modified Version has been derived from a Modified Version % (11) If your Modified Version has been derived from a Modified Version
% made by someone other than you, you are nevertheless required to % made by someone other than you, you are nevertheless required to
% ensure that your Modified Version complies with the requirements of % ensure that your Modified Version complies with the requirements of
% this license. % this license.
% %
% (12) This license does not grant you the right to use any trademark, % (12) This license does not grant you the right to use any trademark,
% service mark, tradename, or logo of the Copyright Holder. % service mark, tradename, or logo of the Copyright Holder.
% %
% (13) This license includes the non-exclusive, worldwide, % (13) This license includes the non-exclusive, worldwide,
% free-of-charge patent license to make, have made, use, offer to sell, % free-of-charge patent license to make, have made, use, offer to sell,
% sell, import and otherwise transfer the Package with respect to any % sell, import and otherwise transfer the Package with respect to any
@ -193,7 +193,7 @@
% that the Package constitutes direct or contributory patent % that the Package constitutes direct or contributory patent
% infringement, then this Artistic License to you shall terminate on the % infringement, then this Artistic License to you shall terminate on the
% date that such litigation is filed. % date that such litigation is filed.
% %
% (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT % (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT
% HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED % HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED
% WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A % WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
@ -312,7 +312,7 @@ print_ad_intern(_::Fact,[],Mass,Handle) :-
P2 is 1.0 - Mass, P2 is 1.0 - Mass,
format(Handle,'~f :: ~q',[P2,Fact]). format(Handle,'~f :: ~q',[P2,Fact]).
print_ad_intern_one(_::Fact,_::AuxFact,Mass,NewMass,Handle) :- print_ad_intern_one(_::Fact,_::AuxFact,Mass,NewMass,Handle) :-
% ask problog to get the fact_id % ask problog to get the fact_id
once(probabilistic_fact(_,AuxFact,FactID)), once(probabilistic_fact(_,AuxFact,FactID)),
% look in our table for the probability % look in our table for the probability
array_element(factprob,FactID,P), array_element(factprob,FactID,P),
@ -342,7 +342,7 @@ do_learning_intern(0,_) :-
do_learning_intern(Iterations,Epsilon) :- do_learning_intern(Iterations,Epsilon) :-
Iterations>0, Iterations>0,
logger_start_timer(duration), logger_start_timer(duration),
current_iteration(CurrentIteration), current_iteration(CurrentIteration),
!, !,
retractall(current_iteration(_)), retractall(current_iteration(_)),
@ -350,7 +350,7 @@ do_learning_intern(Iterations,Epsilon) :-
NextIteration is CurrentIteration+1, NextIteration is CurrentIteration+1,
assertz(current_iteration(NextIteration)), assertz(current_iteration(NextIteration)),
EndIteration is CurrentIteration+Iterations-1, EndIteration is CurrentIteration+Iterations-1,
format_learning(1,'~nIteration ~d of ~d~n',[CurrentIteration,EndIteration]), format_learning(1,'~nIteration ~d of ~d~n',[CurrentIteration,EndIteration]),
logger_set_variable(iteration,CurrentIteration), logger_set_variable(iteration,CurrentIteration),
@ -358,7 +358,7 @@ do_learning_intern(Iterations,Epsilon) :-
once(llh_testset), once(llh_testset),
once(ground_truth_difference), once(ground_truth_difference),
once(em_one_iteration), once(em_one_iteration),
problog_flag(log_frequency,Log_Frequency), problog_flag(log_frequency,Log_Frequency),
@ -381,11 +381,11 @@ do_learning_intern(Iterations,Epsilon) :-
LLH_Diff is abs(Last_LLH-Current_LLH) LLH_Diff is abs(Last_LLH-Current_LLH)
); ( ); (
logger_get_variable(llh_training_set,Current_LLH), logger_get_variable(llh_training_set,Current_LLH),
assertz(last_llh(Current_LLH)), assertz(last_llh(Current_LLH)),
LLH_Diff is Epsilon+1 LLH_Diff is Epsilon+1
) )
), ),
logger_stop_timer(duration), logger_stop_timer(duration),
logger_write_data, logger_write_data,
RemainingIterations is Iterations-1, RemainingIterations is Iterations-1,
@ -424,12 +424,12 @@ init_learning :-
check_theory, check_theory,
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Delete the stuff from the previous run % Delete the stuff from the previous run
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
problog_flag(reuse_initialized_bdds,Re_Use_Flag), problog_flag(reuse_initialized_bdds,Re_Use_Flag),
( (
Re_Use_Flag==false Re_Use_Flag==false
-> ->
@ -438,7 +438,7 @@ init_learning :-
), ),
empty_output_directory, empty_output_directory,
logger_write_header, logger_write_header,
format_learning(1,'Initializing everything~n',[]), format_learning(1,'Initializing everything~n',[]),
@ -471,7 +471,7 @@ init_learning :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% build BDD script for every example % build BDD script for every example
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
once(init_queries), once(init_queries),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -492,7 +492,7 @@ init_learning :-
%======================================================================== %========================================================================
%= This predicate checks some aspects of the data given by the user. %= This predicate checks some aspects of the data given by the user.
%= You know folks: Garbage in, garbage out. %= You know folks: Garbage in, garbage out.
%= %=
%======================================================================== %========================================================================
check_theory :- check_theory :-
( (
@ -510,7 +510,7 @@ check_theory :-
); );
true true
), ),
( (
(current_predicate(user:example/1),user:example(_)) (current_predicate(user:example/1),user:example(_))
-> ->
@ -584,7 +584,7 @@ check_theory :-
%= %=
%======================================================================== %========================================================================
initialize_fact_probabilities :- initialize_fact_probabilities :-
problog:probclause_id(N), problog:probclause_id(N),
static_array(factprob,N,float), static_array(factprob,N,float),
@ -658,7 +658,7 @@ init_queries :-
assertz(test_set_cluster_list(Test_Set_Cluster_List)). assertz(test_set_cluster_list(Test_Set_Cluster_List)).
%======================================================================== %========================================================================
%= %=
%======================================================================== %========================================================================
init_one_query(QueryID,_Query_Type) :- init_one_query(QueryID,_Query_Type) :-
@ -689,10 +689,8 @@ create_test_query_cluster_list(L2) :-
calc_all_md5(AllCluster,AllCluster2), calc_all_md5(AllCluster,AllCluster2),
findall(a(QueryID1,ClusterID1,Len),(bagof(a(QueryID,ClusterID),member(a(QueryID,ClusterID,_MD5),AllCluster2),L),nth1(1,L,a(QueryID1,ClusterID1)),length(L,Len)),L2), findall(a(QueryID1,ClusterID1,Len),(bagof(a(QueryID,ClusterID),member(a(QueryID,ClusterID,_MD5),AllCluster2),L),nth1(1,L,a(QueryID1,ClusterID1)),length(L,Len)),L2),
!, !,
length(AllCluster,Len1), length(AllCluster,Len1),
length(L2,Len2), length(L2,Len2),
( (
Len1>0 Len1>0
-> ->
@ -717,25 +715,22 @@ create_training_query_cluster_list(L2) :-
), AllCluster), ), AllCluster),
calc_all_md5(AllCluster,AllCluster2), calc_all_md5(AllCluster,AllCluster2),
findall(a(QueryID1,ClusterID1,Len), findall(a(QueryID1,ClusterID1,Len),
( (
bagof(a(QueryID,ClusterID),member(a(QueryID,ClusterID,_MD5),AllCluster2),L), bagof(a(QueryID,ClusterID),member(a(QueryID,ClusterID,_MD5),AllCluster2),L),
nth1(1,L,a(QueryID1,ClusterID1)), nth1(1,L,a(QueryID1,ClusterID1)),
length(L,Len) length(L,Len)
),L2), ),L2),
length(AllCluster,Len1), length(AllCluster,Len1),
length(L2,Len2), length(L2,Len2),
Reduction is Len2/Len1, Reduction is Len2/Len1,
format_learning(3,' ~d cluster after splitting, ~d unique cluster ==> reduction factor of ~4f~n',[Len1,Len2,Reduction]). format_learning(3,' ~d cluster after splitting, ~d unique cluster ==> reduction factor of ~4f~n',[Len1,Len2,Reduction]).
%======================================================================== %========================================================================
%= %=
%======================================================================== %========================================================================
reset_learning :- reset_learning :-
@ -751,7 +746,7 @@ reset_learning :-
close_static_array(factprob), close_static_array(factprob),
close_static_array(factprob_temp), close_static_array(factprob_temp),
close_static_array(factusage), close_static_array(factusage),
close_static_array(known_count_true_training), close_static_array(known_count_true_training),
close_static_array(known_count_false_training), close_static_array(known_count_false_training),
close_static_array(known_count_true_test), close_static_array(known_count_true_test),
@ -760,14 +755,14 @@ reset_learning :-
reset_completion, reset_completion,
empty_bdd_directory, empty_bdd_directory,
empty_output_directory, empty_output_directory,
logger_reset_all_variables logger_reset_all_variables
); );
true true
). ).
%======================================================================== %========================================================================
%= calculate the LLH on the test set and set the variable %= calculate the LLH on the test set and set the variable
%= in the logger module %= in the logger module
%======================================================================== %========================================================================
@ -863,7 +858,7 @@ write_probabilities_file :-
forall(get_fact_probability(ID,_), forall(get_fact_probability(ID,_),
( (
array_element(factprob,ID,Prob), array_element(factprob,ID,Prob),
( (
non_ground_fact(ID) non_ground_fact(ID)
-> ->
@ -885,17 +880,17 @@ write_probabilities_file :-
update_query(QueryID,ClusterID ,Method,Command,PID,Output_File_Name) :- update_query(QueryID,ClusterID ,Method,Command,PID,Output_File_Name) :-
current_iteration(Iteration), current_iteration(Iteration),
create_bdd_input_file_name(Iteration,Input_File_Name), create_bdd_input_file_name(Iteration,Input_File_Name),
create_bdd_output_file_name(QueryID,ClusterID,Iteration,Output_File_Name), create_bdd_output_file_name(QueryID,ClusterID,Iteration,Output_File_Name),
create_bdd_file_name(QueryID,ClusterID,BDD_File_Name), create_bdd_file_name(QueryID,ClusterID,BDD_File_Name),
convert_filename_to_problog_path('problogbdd_lfi',Absolute_Name), convert_filename_to_problog_path('problogbdd_lfi',Absolute_Name),
atomic_concat([Absolute_Name, atomic_concat([Absolute_Name,
' -i "', Input_File_Name, '"', ' -i "', Input_File_Name, '"',
' -l "', BDD_File_Name, '"', ' -l "', BDD_File_Name, '"',
' -m ', Method, ' -m ', Method,
' -id ', QueryID],Command), ' -id ', QueryID],Command),
open( Output_File_Name, write, Stream ), open( Output_File_Name, write, Stream ),
exec(Command,[std, Stream ,std],PID), exec(Command,[std, Stream ,std],PID),
@ -914,7 +909,7 @@ update_query_wait(QueryID,_ClusterID,Count,Symbol,Command,PID,OutputFilename,BDD
); );
true true
), ),
once(my_load_allinone(OutputFilename,QueryID,Count,BDD_Probability)), once(my_load_allinone(OutputFilename,QueryID,Count,BDD_Probability)),
problog_flag(retain_bdd_output,Retain_BDD_Output), problog_flag(retain_bdd_output,Retain_BDD_Output),
@ -1019,7 +1014,7 @@ em_one_iteration :-
KK_Sum is KK_True+KK_False, KK_Sum is KK_True+KK_False,
KK_Sum>0, KK_Sum>0,
% add counts % add counts
add_to_array_element(factprob_temp,FactID,KK_True,_NewValue), add_to_array_element(factprob_temp,FactID,KK_True,_NewValue),
add_to_array_element(factusage,FactID,KK_Sum,_NewCount), add_to_array_element(factusage,FactID,KK_Sum,_NewCount),
@ -1038,7 +1033,7 @@ em_one_iteration :-
LProb is Part1 + KK_False*log(1-P); LProb is Part1 + KK_False*log(1-P);
LProb is Part1 LProb is Part1
), ),
bb_get(dummy,Old), bb_get(dummy,Old),
New is Old+LProb, New is Old+LProb,
bb_put(dummy,New), bb_put(dummy,New),
@ -1056,7 +1051,7 @@ em_one_iteration :-
evaluate_bdds(AllCluster,Handle,Parallel_Processes,'e','.',LLH_From_True_BDDs,LLH), evaluate_bdds(AllCluster,Handle,Parallel_Processes,'e','.',LLH_From_True_BDDs,LLH),
logger_set_variable(llh_training_set,LLH), logger_set_variable(llh_training_set,LLH),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% stop calculate new values % stop calculate new values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@ -1065,7 +1060,7 @@ em_one_iteration :-
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% start copy new values % start copy new values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
problog_flag(pc_numerator,Pseudo_Counts_Numerator), problog_flag(pc_numerator,Pseudo_Counts_Numerator),
problog_flag(pc_denominator,Pseudo_Counts_Denominator), problog_flag(pc_denominator,Pseudo_Counts_Denominator),
@ -1098,7 +1093,7 @@ em_one_iteration :-
%= S : symbol to print after a process finished %= S : symbol to print after a process finished
%= OldLLH : accumulator for LLH %= OldLLH : accumulator for LLH
%= LLH : resulting LLH %= LLH : resulting LLH
%= %=
%= evaluate_bdds(+L,+H,+P,+T,+S,+OldLLH,-LLH) %= evaluate_bdds(+L,+H,+P,+T,+S,+OldLLH,-LLH)
%======================================================================== %========================================================================
@ -1107,7 +1102,7 @@ evaluate_bdds([H|T],Handle,Parallel_Processes,Type,Symbol,OldLLH,LLH) :-
once(slice_n([H|T],Parallel_Processes,ForNow,Later)), once(slice_n([H|T],Parallel_Processes,ForNow,Later)),
logger_start_timer(bdd_evaluation), logger_start_timer(bdd_evaluation),
once(evaluate_bdds_start(ForNow,Type,ForNow_Jobs)), once(evaluate_bdds_start(ForNow,Type,ForNow_Jobs)),
once(evaluate_bdds_stop(ForNow_Jobs,Handle,Symbol,OldLLH,NewLLH)), once(evaluate_bdds_stop(ForNow_Jobs,Handle,Symbol,OldLLH,NewLLH)),
logger_stop_timer(bdd_evaluation), logger_stop_timer(bdd_evaluation),
evaluate_bdds(Later,Handle,Parallel_Processes,Type,Symbol,NewLLH,LLH). evaluate_bdds(Later,Handle,Parallel_Processes,Type,Symbol,NewLLH,LLH).
@ -1142,7 +1137,7 @@ init_flags :-
problog_define_flag(output_directory, problog_flag_validate_directory, 'directory for logfiles etc', Output_Folder,learning_general,flags:learning_output_dir_handler), problog_define_flag(output_directory, problog_flag_validate_directory, 'directory for logfiles etc', Output_Folder,learning_general,flags:learning_output_dir_handler),
problog_define_flag(retain_bdd_output,problog_flag_validate_boolean,'Keep output files from BDD tool',false,learning_general), problog_define_flag(retain_bdd_output,problog_flag_validate_boolean,'Keep output files from BDD tool',false,learning_general),
problog_define_flag(log_frequency, problog_flag_validate_posint, 'log results every nth iteration', 1, learning_general), problog_define_flag(log_frequency, problog_flag_validate_posint, 'log results every nth iteration', 1, learning_general),
problog_define_flag(reuse_initialized_bdds,problog_flag_validate_boolean, 'Reuse BDDs from previous runs',false, learning_general), problog_define_flag(reuse_initialized_bdds,problog_flag_validate_boolean, 'Reuse BDDs from previous runs',false, learning_general),
problog_define_flag(pc_numerator,problog_flag_validate_in_interval_right_open([0.0,+inf]),'Add X to numerator (Pseudocounts)',0.0,learning_general), problog_define_flag(pc_numerator,problog_flag_validate_in_interval_right_open([0.0,+inf]),'Add X to numerator (Pseudocounts)',0.0,learning_general),
problog_define_flag(pc_denominator,problog_flag_validate_in_interval_right_open([0.0,+inf]),'Add X to denominator (Pseudocounts)',0.0,learning_general), problog_define_flag(pc_denominator,problog_flag_validate_in_interval_right_open([0.0,+inf]),'Add X to denominator (Pseudocounts)',0.0,learning_general),
problog_define_flag(parallel_processes,problog_flag_validate_posint,'Number of parallel BDD processes',8,learning_general), problog_define_flag(parallel_processes,problog_flag_validate_posint,'Number of parallel BDD processes',8,learning_general),
@ -1156,7 +1151,7 @@ init_logger :-
logger_define_variable(llh_training_set,float), logger_define_variable(llh_training_set,float),
logger_define_variable(llh_test_set,float), logger_define_variable(llh_test_set,float),
logger_define_variable(bdd_evaluation,time), logger_define_variable(bdd_evaluation,time),
logger_define_variable(ground_truth_diff,float), logger_define_variable(ground_truth_diff,float),
@ -1186,6 +1181,3 @@ init_logger :-
%:- initialization(do_learning(100) ). %:- initialization(do_learning(100) ).

View File

@ -35,12 +35,12 @@ IF (CUDD_FOUND)
${CUDD_INCLUDE_DIR} ${CUDD_INCLUDE_DIR}
${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}
) )
check_include_files( util.h HAVE_UTIL_H ) check_include_files( util.h HAVE_UTIL_H )
check_include_files( cudd/util.h HAVE_CUDD_UTIL_H ) check_include_files( cudd/util.h HAVE_CUDD_UTIL_H )
check_include_files( cudd.h HAVE_CUDD_H ) check_include_files( cudd.h HAVE_CUDD_H )
check_include_files( "stdio.h;cudd/cudd.h" HAVE_CUDD_CUDD_H ) check_include_files( "stdio.h;cudd/cudd.h" HAVE_CUDD_CUDD_H )
check_include_files( cuddInt.h HAVE_CUDDINT_H ) check_include_files( cuddInt.h HAVE_CUDDINT_H )
check_include_files( "stdio.h;cudd/cudd.h;cudd/cuddInt.h" HAVE_CUDD_CUDDINT_H ) check_include_files( "stdio.h;cudd/cudd.h;cudd/cuddInt.h" HAVE_CUDD_CUDDINT_H )
configure_file ("${PROJECT_SOURCE_DIR}/cudd_config.h.cmake" configure_file ("${PROJECT_SOURCE_DIR}/cudd_config.h.cmake"
@ -63,6 +63,7 @@ IF (CUDD_FOUND)
add_subdirectory(simplecudd) add_subdirectory(simplecudd)
add_subdirectory(simplecudd_lfi) add_subdirectory(simplecudd_lfi)
set(YAP_SYSTEM_OPTIONS "cudd " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
install(TARGETS cudd install(TARGETS cudd
LIBRARY DESTINATION ${dlls} LIBRARY DESTINATION ${dlls}
@ -72,7 +73,7 @@ IF (CUDD_FOUND)
INSTALL(FILES ddnnf.yap DESTINATION ${libpl}) INSTALL(FILES ddnnf.yap DESTINATION ${libpl})
INSTALL(FILES simpbool.yap DESTINATION ${libpl}) INSTALL(FILES simpbool.yap DESTINATION ${libpl})
INSTALL(FILES trie_sp.yap DESTINATION ${libpl}) INSTALL(FILES trie_sp.yap DESTINATION ${libpl})
ENDIF (CUDD_FOUND) ENDIF (CUDD_FOUND)
SET (CUDD_FOUND_EXPORT ${CUDD_FOUND} PARENT_SCOPE) SET (CUDD_FOUND_EXPORT ${CUDD_FOUND} PARENT_SCOPE)

View File

@ -2,7 +2,7 @@
/* Define to 1 if you have the <cuddInt.h> header file. */ /* Define to 1 if you have the <cuddInt.h> header file. */
#ifndef HAVE_CUDDINT_H #ifndef HAVE_CUDDINT_H
#define HAVE_CUDDINT_H /* #undef HAVE_CUDDINT_H */
#endif #endif
/* Define to 1 if you have the <cudd/cuddInt.h> header file. */ /* Define to 1 if you have the <cudd/cuddInt.h> header file. */
@ -15,9 +15,9 @@
#define HAVE_CUDD_CUDD_H 1 #define HAVE_CUDD_CUDD_H 1
#endif #endif
/* Define to 1 if you have the <cudd.h> header file. */ /*Define to 1 if you have the <cudd.h> header file. */
#ifndef HAVE_CUDD_H #ifndef HAVE_CUDD_H
#define HAVE_CUDD_H /* #undef HAVE_CUDD_H */
#endif #endif
/* Define to 1 if you have the <cudd/util.h> header file. */ /* Define to 1 if you have the <cudd/util.h> header file. */

View File

@ -254,7 +254,7 @@ int CharIn(const char c, const char *in) {
/* string handling */ /* string handling */
int patternmatch(char *pattern, char *thestr) { int patternmatch(const char *pattern, const char *thestr) {
int i, j = -1, pl = strlen(pattern), sl = strlen(thestr); int i, j = -1, pl = strlen(pattern), sl = strlen(thestr);
for(i = 0; i < pl; i++) { for(i = 0; i < pl; i++) {
if (pattern[i] == '*') { if (pattern[i] == '*') {

View File

@ -200,5 +200,5 @@ int IsRealNumber(char *c);
int IsNumber(const char *c); int IsNumber(const char *c);
char * freadstr(FILE *fd, const char *separators); char * freadstr(FILE *fd, const char *separators);
int CharIn(const char c, const char *in); int CharIn(const char c, const char *in);
int patternmatch(char *pattern, char *thestr); int patternmatch(const char *pattern, const char *thestr);

View File

@ -241,7 +241,7 @@ double CalcExpectedCountsUp(extmanager * MyManager, DdNode *Current, char *query
double CalcExpectedCountsDown(extmanager * MyManager, DdNode *Current, char *query_id); double CalcExpectedCountsDown(extmanager * MyManager, DdNode *Current, char *query_id);
double CalcExpectedCounts(extmanager * MyManager, DdNode *Current, char *query_id, int calcdown_needed); double CalcExpectedCounts(extmanager * MyManager, DdNode *Current, char *query_id, int calcdown_needed);
int patterncalculated(char *pattern, extmanager MyManager, int loc); int patterncalculated(char *pattern, extmanager MyManager, int loc);
char * extractpattern(char *thestr); char * extractpattern(const char *thestr);
int main(int argc, char **arg) { int main(int argc, char **arg) {
extmanager MyManager; extmanager MyManager;
@ -476,7 +476,7 @@ int main(int argc, char **arg) {
free(MyManager.varmap.dynvalue); free(MyManager.varmap.dynvalue);
} }
for (i = 0; i < MyManager.varmap.varcnt; i++) for (i = 0; i < MyManager.varmap.varcnt; i++)
free(MyManager.varmap.vars[i]); free((const char *)MyManager.varmap.vars[i]);
free(MyManager.varmap.vars); free(MyManager.varmap.vars);
} }
if (params.error != NULL) free(params.error); if (params.error != NULL) free(params.error);
@ -1168,7 +1168,7 @@ gradientpair CalcGradient(extmanager MyManager, DdNode *Current, int TargetVar,
return tvalue; return tvalue;
} }
char * extractpattern(char *thestr) { char * extractpattern(const char *thestr) {
char *p; char *p;
int i = 0, sl = strlen(thestr); int i = 0, sl = strlen(thestr);
while((thestr[i] != '_') && (i < sl)) i++; while((thestr[i] != '_') && (i < sl)) i++;

View File

@ -370,7 +370,7 @@ int CheckFileVersion(const char *version) {
return -1; return -1;
} }
int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename) { int simpleBDDtoDot(DdManager *manager, DdNode *bdd, const char *filename) {
DdNode *f[1]; DdNode *f[1];
int ret; int ret;
FILE *fd; FILE *fd;
@ -385,8 +385,8 @@ int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename) {
return ret; return ret;
} }
int simpleNamedBDDtoDot(DdManager *manager, const namedvars varmap, DdNode *bdd, int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd,
char *filename) { const char *filename) {
DdNode *f[1]; DdNode *f[1];
int ret; int ret;
FILE *fd; FILE *fd;
@ -435,7 +435,7 @@ void SaveExpand(DdManager *manager, namedvars varmap, hisqueue *Nodes,
DdNode *Current, FILE *outputfile) { DdNode *Current, FILE *outputfile) {
DdNode *h, *l; DdNode *h, *l;
hisnode *Found; hisnode *Found;
char *curnode; const char *curnode;
int inode; int inode;
if (Current != HIGH(manager) && Current != LOW(manager)) { if (Current != HIGH(manager) && Current != LOW(manager)) {
if ((Found = GetNode(Nodes, varmap.varstart, Current)) == NULL) { if ((Found = GetNode(Nodes, varmap.varstart, Current)) == NULL) {
@ -917,7 +917,7 @@ namedvars InitNamedVars(int varcnt, int varstart) {
int i; int i;
temp.varcnt = varcnt; temp.varcnt = varcnt;
temp.varstart = varstart; temp.varstart = varstart;
temp.vars = (char **)malloc(sizeof(char *) * varcnt); temp.vars = (const char **)malloc(sizeof(char *) * varcnt);
temp.loaded = (int *)malloc(sizeof(int) * varcnt); temp.loaded = (int *)malloc(sizeof(int) * varcnt);
temp.dvalue = (double *)malloc(sizeof(double) * varcnt); temp.dvalue = (double *)malloc(sizeof(double) * varcnt);
temp.ivalue = (int *)malloc(sizeof(int) * varcnt); temp.ivalue = (int *)malloc(sizeof(int) * varcnt);
@ -934,7 +934,7 @@ namedvars InitNamedVars(int varcnt, int varstart) {
void EnlargeNamedVars(namedvars *varmap, int newvarcnt) { void EnlargeNamedVars(namedvars *varmap, int newvarcnt) {
int i; int i;
varmap->vars = (char **)realloc(varmap->vars, sizeof(char *) * newvarcnt); varmap->vars = (const char **)realloc(varmap->vars, sizeof(const char *) * newvarcnt);
varmap->loaded = (int *)realloc(varmap->loaded, sizeof(int) * newvarcnt); varmap->loaded = (int *)realloc(varmap->loaded, sizeof(int) * newvarcnt);
varmap->dvalue = varmap->dvalue =
(double *)realloc(varmap->dvalue, sizeof(double) * newvarcnt); (double *)realloc(varmap->dvalue, sizeof(double) * newvarcnt);
@ -954,7 +954,7 @@ void EnlargeNamedVars(namedvars *varmap, int newvarcnt) {
int AddNamedVarAt(namedvars varmap, const char *varname, int index) { int AddNamedVarAt(namedvars varmap, const char *varname, int index) {
if (varmap.varcnt > index) { if (varmap.varcnt > index) {
varmap.vars[index] = (char *)malloc(sizeof(char) * (strlen(varname) + 1)); varmap.vars[index] = (char *)malloc(sizeof(char) * (strlen(varname) + 1));
strcpy(varmap.vars[index], varname); strcpy(varmap.vars[index], (char *)varname);
return index; return index;
} }
return -1; return -1;
@ -1010,7 +1010,7 @@ int GetNamedVarIndex(const namedvars varmap, const char *varname) {
return -1 * varmap.varcnt; return -1 * varmap.varcnt;
} }
char *GetNodeVarName(DdManager *manager, namedvars varmap, DdNode *node) { const char *GetNodeVarName(DdManager *manager, namedvars varmap, DdNode *node) {
if (node == NULL) if (node == NULL)
return NULL; return NULL;
if (node == HIGH(manager)) if (node == HIGH(manager))
@ -1020,7 +1020,7 @@ char *GetNodeVarName(DdManager *manager, namedvars varmap, DdNode *node) {
return varmap.vars[GetIndex(node) - varmap.varstart]; return varmap.vars[GetIndex(node) - varmap.varstart];
} }
char *GetNodeVarNameDisp(DdManager *manager, namedvars varmap, DdNode *node) { const char *GetNodeVarNameDisp(DdManager *manager, namedvars varmap, DdNode *node) {
if (HIGH(manager) == node) if (HIGH(manager) == node)
return "TRUE"; return "TRUE";
if (LOW(manager) == node) if (LOW(manager) == node)

View File

@ -249,7 +249,7 @@ typedef struct _bddfileheader {
typedef struct _namedvars { typedef struct _namedvars {
int varcnt; int varcnt;
int varstart; int varstart;
char **vars; const char ** vars;
int *loaded; int *loaded;
double *dvalue; double *dvalue;
int *ivalue; int *ivalue;
@ -317,8 +317,8 @@ void SetNamedVarValuesAt(namedvars varmap, int index, double dvalue, int ivalue,
int SetNamedVarValues(namedvars varmap, const char *varname, double dvalue, int ivalue, void *dynvalue); int SetNamedVarValues(namedvars varmap, const char *varname, double dvalue, int ivalue, void *dynvalue);
int GetNamedVarIndex(const namedvars varmap, const char *varname); int GetNamedVarIndex(const namedvars varmap, const char *varname);
int RepairVarcnt(namedvars *varmap); int RepairVarcnt(namedvars *varmap);
char* GetNodeVarName(DdManager *manager, namedvars varmap, DdNode *node); const char* GetNodeVarName(DdManager *manager, namedvars varmap, DdNode *node);
char* GetNodeVarNameDisp(DdManager *manager, namedvars varmap, DdNode *node); const char* GetNodeVarNameDisp(DdManager *manager, namedvars varmap, DdNode *node);
int all_loaded(namedvars varmap, int disp); int all_loaded(namedvars varmap, int disp);
int all_loaded_for_deterministic_variables(namedvars varmap, int disp); int all_loaded_for_deterministic_variables(namedvars varmap, int disp);
@ -351,6 +351,6 @@ void ExpandNodes(hisqueue *Nodes, int index, int nodenum);
/* Export */ /* Export */
int simpleBDDtoDot(DdManager *manager, DdNode *bdd, char *filename); int simpleBDDtoDot(DdManager *manager, DdNode *bdd, const char *filename);
int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd, char *filename); int simpleNamedBDDtoDot(DdManager *manager, namedvars varmap, DdNode *bdd, const char *filename);

View File

@ -22,7 +22,6 @@
:-set_clpbn_flag(bnt_model,propositional). :-set_clpbn_flag(bnt_model,propositional).
/* start of list of parameters that can be set by the user with /* start of list of parameters that can be set by the user with
set(Parameter,Value) */ set(Parameter,Value) */
setting(epsilon_parsing,0.00001). setting(epsilon_parsing,0.00001).

View File

@ -56,6 +56,8 @@ if (Java_Development_FOUND)
set_target_properties(jplYap PROPERTIES set_target_properties(jplYap PROPERTIES
OUTPUT_NAME jpl ) OUTPUT_NAME jpl )
set(YAP_SYSTEM_OPTIONS "jpl " ${YAP_SYSTEM_OPTIONS} PARENT_SCOPE)
install(TARGETS jplYap install(TARGETS jplYap
LIBRARY DESTINATION ${dlls} LIBRARY DESTINATION ${dlls}
) )

View File

@ -81,14 +81,14 @@
jpl_set_element/2 jpl_set_element/2
]). ]).
:- expects_dialect(swi). %:- expects_dialect(swi).
:- use_module(library(lists)). :- use_module(library(lists)).
:- use_module(library(apply)). :- use_module(library(apply)).
:- use_module(library(shlib)). :- use_module(library(shlib)).
% suppress debugging this library % suppress debugging this library
:- set_prolog_flag(generate_debug_info, false). %:- set_prolog_flag(generate_debug_info, false).
%------------------------------------------------------------------------------ %------------------------------------------------------------------------------

View File

@ -81,8 +81,6 @@
jpl_set_element/2 jpl_set_element/2
]). ]).
:- expects_dialect(swi).
:- use_module(library(lists)). :- use_module(library(lists)).
:- use_module(library(apply)). :- use_module(library(apply)).
:- use_module(library(shlib)). :- use_module(library(shlib)).
@ -157,6 +155,8 @@ jpl_tidy_iref_type_cache( Iref) :-
% %
% finally, an attempt will be made to unify Result with the returned result % finally, an attempt will be made to unify Result with the returned result
:- stop_low_level_trace.
jpl_call(X, Mspec, Params, R) :- jpl_call(X, Mspec, Params, R) :-
( jpl_object_to_type(X, Type) % the usual case (goal fails safely if X is var or rubbish) ( jpl_object_to_type(X, Type) % the usual case (goal fails safely if X is var or rubbish)
-> Obj = X, -> Obj = X,

View File

@ -1,79 +0,0 @@
/* MYDDAS */
#ifdef USE_MYDDAS
/* myddas_initialization.c */
MYDDAS_GLOBAL myddas_init_initialize_myddas(void);
MYDDAS_UTIL_CONNECTION myddas_init_initialize_connection(void *,void *,MYDDAS_API,MYDDAS_UTIL_CONNECTION);
MYDDAS_UTIL_PREDICATE myddas_init_initialize_predicate(char *, int, char *,MYDDAS_UTIL_PREDICATE);
#ifdef MYDDAS_STATS
/* myddas_statistics.c */
MYDDAS_GLOBAL myddas_stats_initialize_global_stats(MYDDAS_GLOBAL);
MYDDAS_STATS_STRUCT myddas_stats_initialize_connection_stats(void);
void myddas_stats_delete_stats_list(MYDDAS_STATS_STRUCT);
#endif /* MYDDAS_STATS */
#ifdef MYDDAS_MYSQL
/* myddas_util.c */
void myddas_util_table_write(MYSQL_RES *);
#endif
MYDDAS_API myddas_util_connection_type(void *);
MYDDAS_UTIL_CONNECTION myddas_util_add_connection(void *,void *,MYDDAS_API);
MYDDAS_UTIL_CONNECTION myddas_util_search_connection(void *);
void myddas_util_delete_connection(void *);
MYDDAS_UTIL_CONNECTION myddas_util_add_predicate(char * ,Int , char *,void *);
MYDDAS_UTIL_PREDICATE myddas_util_search_predicate(char * ,Int , char *);
void myddas_util_delete_predicate(MYDDAS_UTIL_PREDICATE);
/* Get's the number of queries to save */
UInt myddas_util_get_total_multi_queries_number(MYDDAS_UTIL_CONNECTION);
void myddas_util_set_total_multi_queries_number(MYDDAS_UTIL_CONNECTION,UInt);
#ifdef MYDDAS_ODBC
/* Return enviromment identifier*/
SQLHENV myddas_util_get_odbc_enviromment(SQLHDBC);
#endif
void * myddas_util_get_list_pred(MYDDAS_UTIL_CONNECTION);
void * myddas_util_get_pred_next(void *);
char * myddas_util_get_pred_module(void *);
char * myddas_util_get_pred_name(void *);
MyddasInt myddas_util_get_pred_arity(void *);
//DELETE THIS WHEN DB_STATS IS COMPLETED
MyddasInt get_myddas_top(void);
#ifdef DEBUG
void check_int(void);
#endif
#endif /* MYDDAS_MYSQL || MYDDAS_ODBC */
/* myddas_mysql.c */
#if defined MYDDAS_MYSQL
void Yap_InitMYDDAS_MySQLPreds(void);
void Yap_InitBackMYDDAS_MySQLPreds(void);
#endif
/* myddas_odbc.c */
#if defined MYDDAS_ODBC
void Yap_InitMYDDAS_ODBCPreds(void);
void Yap_InitBackMYDDAS_ODBCPreds(void);
#endif
/* myddas_odbc.c */
#if defined MYDDAS_SQLITE3
void Yap_InitMYDDAS_SQLITE3Preds(void);
void Yap_InitBackMYDDAS_SQLITE3Preds(void);
#endif
/* Myddas_shared.c */
#if defined USE_MYDDAS
void Yap_MYDDAS_delete_all_myddas_structs(void);
void Yap_InitMYDDAS_SharedPreds(void);
void Yap_InitBackMYDDAS_SharedPreds(void);
#endif
/* myddas_top_level.c */
#if defined MYDDAS_TOP_LEVEL && defined MYDDAS_MYSQL //&& defined HAVE_LIBREADLINE
void Yap_InitMYDDAS_TopLevelPreds(void);
#endif

View File

@ -13,7 +13,7 @@ set( MYDDAS_SOURCES
myddas_shared.c myddas_shared.c
myddas_statistics.c myddas_statistics.c
myddas_top_level.c myddas_top_level.c
myddas_wkb2prolog.c ) )
set( MYDDAS_HEADERS set( MYDDAS_HEADERS
myddas.h myddas.h
@ -21,8 +21,7 @@ set( MYDDAS_HEADERS
myddas_statistics_structs.h myddas_statistics_structs.h
myddas_structs.h myddas_structs.h
myddas_top_level.c myddas_top_level.c
myddas_types.h myddas_types.h )
myddas_wkb2prolog.c )
set( MYDDAS_UTIL_SOURCES set( MYDDAS_UTIL_SOURCES
myddas_util.c myddas_util.c

View File

@ -3,44 +3,46 @@
#ifdef USE_MYDDAS #ifdef USE_MYDDAS
/* myddas_initialization.c */ /* myddas_initialization.c */
MYDDAS_GLOBAL myddas_init_initialize_myddas(void); MYDDAS_GLOBAL myddas_init_initialize_myddas(void);
MYDDAS_UTIL_CONNECTION myddas_init_initialize_connection(void *,void *,MYDDAS_API,MYDDAS_UTIL_CONNECTION); MYDDAS_UTIL_CONNECTION
MYDDAS_UTIL_PREDICATE myddas_init_initialize_predicate(const char *, int, const char *,MYDDAS_UTIL_PREDICATE); myddas_init_initialize_connection(void *, void *, MYDDAS_API,
MYDDAS_UTIL_CONNECTION);
MYDDAS_UTIL_PREDICATE myddas_init_initialize_predicate(const char *, int,
const char *,
MYDDAS_UTIL_PREDICATE);
#ifdef MYDDAS_STATS #ifdef MYDDAS_STATS
/* myddas_statistics.c */ /* myddas_statistics.c */
MYDDAS_GLOBAL myddas_stats_initialize_global_stats(MYDDAS_GLOBAL); MYDDAS_GLOBAL myddas_stats_initialize_global_stats(MYDDAS_GLOBAL);
MYDDAS_STATS_STRUCT myddas_stats_initialize_connection_stats(void); MYDDAS_STATS_STRUCT myddas_stats_initialize_connection_stats(void);
void myddas_stats_delete_stats_list(MYDDAS_STATS_STRUCT); void myddas_stats_delete_stats_list(MYDDAS_STATS_STRUCT);
#endif /* MYDDAS_STATS */ #endif /* MYDDAS_STATS */
#ifdef MYDDAS_MYSQL #ifdef MYDDAS_MYSQL
/* myddas_util.c */ /* myddas_util.c */
void myddas_util_table_write(MYSQL_RES *); void myddas_util_table_write(MYSQL_RES *);
#endif #endif
Short myddas_util_connection_type(void *); MYDDAS_UTIL_CONNECTION myddas_util_search_connection(void *con);
MYDDAS_UTIL_CONNECTION myddas_util_add_connection(void *,void *,MYDDAS_API); MYDDAS_UTIL_CONNECTION myddas_util_add_connection(void *, void *, MYDDAS_API);
MYDDAS_UTIL_CONNECTION myddas_util_search_connection(void *); MYDDAS_UTIL_CONNECTION myddas_util_search_connection(void *);
void myddas_util_delete_connection(void *); void myddas_util_delete_connection(void *);
MYDDAS_UTIL_CONNECTION myddas_util_add_predicate(const char * ,Int , const char *,void *); MYDDAS_UTIL_CONNECTION myddas_util_add_predicate(const char *, Int,
MYDDAS_UTIL_PREDICATE myddas_util_search_predicate(const char * ,Int , const char *); const char *, void *);
void myddas_util_delete_predicate(MYDDAS_UTIL_PREDICATE); MYDDAS_UTIL_PREDICATE myddas_util_search_predicate(const char *, Int,
const char *);
void myddas_util_delete_predicate(MYDDAS_UTIL_PREDICATE);
/* Get's the number of queries to save */ /* Get's the number of queries to save */
UInt myddas_util_get_total_multi_queries_number(MYDDAS_UTIL_CONNECTION); UInt myddas_util_get_total_multi_queries_number(MYDDAS_UTIL_CONNECTION);
void myddas_util_set_total_multi_queries_number(MYDDAS_UTIL_CONNECTION,UInt); void myddas_util_set_total_multi_queries_number(MYDDAS_UTIL_CONNECTION, UInt);
#ifdef MYDDAS_ODBC
/* Return enviromment identifier*/
SQLHENV myddas_util_get_odbc_enviromment(SQLHDBC);
#endif
void * myddas_util_get_list_pred(MYDDAS_UTIL_CONNECTION); void *myddas_util_get_list_pred(MYDDAS_UTIL_CONNECTION);
void * myddas_util_get_pred_next(void *); void *myddas_util_get_pred_next(void *);
const char * myddas_util_get_pred_module(void *); const char *myddas_util_get_pred_module(void *);
const char * myddas_util_get_pred_name(void *); const char *myddas_util_get_pred_name(void *);
MyddasInt myddas_util_get_pred_arity(void *); MyddasInt myddas_util_get_pred_arity(void *);
//DELETE THIS WHEN DB_STATS IS COMPLETED // DELETE THIS WHEN DB_STATS IS COMPLETED
MyddasInt get_myddas_top(void); MyddasInt get_myddas_top(void);
#ifdef DEBUG #ifdef DEBUG
void check_int(void); void check_int(void);
@ -50,30 +52,31 @@ void check_int(void);
/* myddas_mysql.c */ /* myddas_mysql.c */
#if defined MYDDAS_MYSQL #if defined MYDDAS_MYSQL
void Yap_InitMYDDAS_MySQLPreds(void); void Yap_InitMYDDAS_MySQLPreds(void);
void Yap_InitBackMYDDAS_MySQLPreds(void); void Yap_InitBackMYDDAS_MySQLPreds(void);
#endif #endif
/* myddas_odbc.c */ /* myddas_odbc.c */
#if defined MYDDAS_ODBC #if defined MYDDAS_ODBC
void Yap_InitMYDDAS_ODBCPreds(void); void Yap_InitMYDDAS_ODBCPreds(void);
void Yap_InitBackMYDDAS_ODBCPreds(void); void Yap_InitBackMYDDAS_ODBCPreds(void);
#endif #endif
/* myddas_odbc.c */ /* myddas_odbc.c */
#if defined MYDDAS_SQLITE3 #if defined MYDDAS_SQLITE3
void Yap_InitMYDDAS_SQLITE3Preds(void); void Yap_InitMYDDAS_SQLITE3Preds(void);
void Yap_InitBackMYDDAS_SQLITE3Preds(void); void Yap_InitBackMYDDAS_SQLITE3Preds(void);
#endif #endif
/* Myddas_shared.c */ /* Myddas_shared.c */
#if defined USE_MYDDAS #if defined USE_MYDDAS
void Yap_MYDDAS_delete_all_myddas_structs(void); void Yap_MYDDAS_delete_all_myddas_structs(void);
void Yap_InitMYDDAS_SharedPreds(void); void Yap_InitMYDDAS_SharedPreds(void);
void Yap_InitBackMYDDAS_SharedPreds(void); void Yap_InitBackMYDDAS_SharedPreds(void);
#endif #endif
/* myddas_top_level.c */ /* myddas_top_level.c */
#if defined MYDDAS_TOP_LEVEL && defined MYDDAS_MYSQL //&& defined HAVE_LIBREADLINE #if defined MYDDAS_TOP_LEVEL && \
void Yap_InitMYDDAS_TopLevelPreds(void); defined MYDDAS_MYSQL //&& defined HAVE_LIBREADLINE
void Yap_InitMYDDAS_TopLevelPreds(void);
#endif #endif

View File

@ -11,32 +11,34 @@
#endif #endif
MYDDAS_GLOBAL MYDDAS_GLOBAL
myddas_init_initialize_myddas(void){ myddas_init_initialize_myddas(void) {
MYDDAS_GLOBAL global = NULL; MYDDAS_GLOBAL global = NULL;
/* We cannot call MYDDAS_MALLOC were because the global /* We cannot call MYDDAS_MALLOC were because the global
register isn't yet initialized */ register isn't yet initialized */
global = (MYDDAS_GLOBAL) malloc (sizeof(struct myddas_global)); global = (MYDDAS_GLOBAL)malloc(sizeof(struct myddas_global));
#ifdef DEBUGX #ifdef DEBUGX
printf ("MALLOC %p %s %d\n",global,__FILE__,__LINE__); printf("MALLOC %p %s %d\n", global, __FILE__, __LINE__);
#endif #endif
global->myddas_top_connections = NULL; global->myddas_top_connections = NULL;
#ifdef MYDDAS_TOP_LEVEL #ifdef MYDDAS_TOP_LEVEL
global->myddas_top_level_connection = NULL; global->myddas_top_level_connection = NULL;
#endif #endif
#ifdef MYDDAS_STATS #ifdef MYDDAS_STATS
global->myddas_statistics = (MYDDAS_GLOBAL_STATS) malloc (sizeof(struct myddas_global_stats)); global->myddas_statistics =
(MYDDAS_GLOBAL_STATS)malloc(sizeof(struct myddas_global_stats));
#ifdef DEBUG #ifdef DEBUG
printf ("MALLOC %p %s %d\n",global->myddas_statistics,__FILE__,__LINE__); printf("MALLOC %p %s %d\n", global->myddas_statistics, __FILE__, __LINE__);
#endif #endif
global->myddas_statistics->stats = NULL; global->myddas_statistics->stats = NULL;
#endif #endif
#ifdef DEBUG #ifdef DEBUG
/* We first malloc for this struct and the stats struct */ /* We first malloc for this struct and the stats struct */
#ifdef MYDDAS_STATS #ifdef MYDDAS_STATS
global->malloc_called = 2; global->malloc_called = 2;
global->memory_allocated = sizeof(struct myddas_global) + sizeof(struct myddas_global_stats); global->memory_allocated =
sizeof(struct myddas_global) + sizeof(struct myddas_global_stats);
#else #else
global->malloc_called = 1; global->malloc_called = 1;
global->memory_allocated = sizeof(struct myddas_global); global->memory_allocated = sizeof(struct myddas_global);
@ -50,34 +52,32 @@ myddas_init_initialize_myddas(void){
/* Inserts the new node on the front of the list */ /* Inserts the new node on the front of the list */
MYDDAS_UTIL_CONNECTION MYDDAS_UTIL_CONNECTION
myddas_init_initialize_connection(void *conn,void *enviromment, myddas_init_initialize_connection(void *conn, void *enviromment, MYDDAS_API api,
MYDDAS_API api, MYDDAS_UTIL_CONNECTION next) {
MYDDAS_UTIL_CONNECTION next){
CACHE_REGS CACHE_REGS
MYDDAS_UTIL_CONNECTION new = NULL; MYDDAS_UTIL_CONNECTION new = NULL;
MYDDAS_MALLOC(new,struct myddas_list_connection); MYDDAS_MALLOC(new, struct myddas_list_connection);
if (new == NULL) if (new == NULL) {
{ return NULL;
return NULL; }
}
new->api = api; new->api = api;
new->predicates=NULL; new->predicates = NULL;
new->connection=conn; new->connection = conn;
new->odbc_enviromment=enviromment; new->odbc_enviromment = enviromment;
/* It saves n queries, doing at once n+1 queries */ /* It saves n queries, doing at once n+1 queries */
new->total_number_queries=0; //Default new->total_number_queries = 0; // Default
new->actual_number_queries=0; new->actual_number_queries = 0;
new->queries = NULL; new->queries = NULL;
/* List integrity */ /* List integrity */
new->next=next; new->next = next;
new->previous=NULL; new->previous = NULL;
/* If there's already at least one node /* If there's already at least one node
on the list */ on the list */
if (next != NULL) if (next != NULL)
next->previous=new; next->previous = new;
#ifdef MYDDAS_STATS #ifdef MYDDAS_STATS
new->stats = NULL; new->stats = NULL;
@ -88,26 +88,26 @@ myddas_init_initialize_connection(void *conn,void *enviromment,
MYDDAS_UTIL_PREDICATE MYDDAS_UTIL_PREDICATE
myddas_init_initialize_predicate(const char *pred_name, int pred_arity, myddas_init_initialize_predicate(const char *pred_name, int pred_arity,
const char *pred_module, MYDDAS_UTIL_PREDICATE next){ const char *pred_module,
MYDDAS_UTIL_PREDICATE next) {
CACHE_REGS CACHE_REGS
MYDDAS_UTIL_PREDICATE new = NULL; MYDDAS_UTIL_PREDICATE new = NULL;
MYDDAS_MALLOC(new,struct myddas_list_preds); MYDDAS_MALLOC(new, struct myddas_list_preds);
if (new == NULL) if (new == NULL) {
{ return NULL;
return NULL; }
} new->pred_name = pred_name;
new->pred_name=pred_name; new->pred_arity = pred_arity;
new->pred_arity=pred_arity; new->pred_module = pred_module;
new->pred_module=pred_module;
/* List integrity */ /* List integrity */
new->next=next; new->next = next;
new->previous=NULL; new->previous = NULL;
/* If there's already at least one node /* If there's already at least one node
on the list */ on the list */
if (next != NULL) if (next != NULL)
next->previous=new; next->previous = new;
return new; return new;
} }

View File

@ -706,9 +706,6 @@ void
init_myddas(void) init_myddas(void)
{ {
CACHE_REGS CACHE_REGS
#if defined MYDDAS_MYSQL
Yap_InitBackMYDDAS_MySQLPreds();
#endif
#if defined MYDDAS_ODBC #if defined MYDDAS_ODBC
Yap_InitBackMYDDAS_ODBCPreds(); Yap_InitBackMYDDAS_ODBCPreds();
#endif #endif
@ -733,21 +730,6 @@ init_myddas(void)
#if defined MYDDAS_TOP_LEVEL && defined MYDDAS_MYSQL // && defined HAVE_LIBREADLINE #if defined MYDDAS_TOP_LEVEL && defined MYDDAS_MYSQL // && defined HAVE_LIBREADLINE
Yap_InitMYDDAS_TopLevelPreds(); Yap_InitMYDDAS_TopLevelPreds();
#endif #endif
#ifdef MYDDAS_MYSQL_INIT
if (yap_init->myddas) {
Yap_PutValue(AtomMyddasGoal,MkIntegerTerm(yap_init->myddas));
/* Mandatory Fields */
Yap_PutValue(AtomMyddasUser,MkAtomTerm(Yap_LookupAtom(yap_init->myddas_user)));
Yap_PutValue(AtomMyddasDB,MkAtomTerm(Yap_LookupAtom(yap_init->myddas_db)));
/* Non-Mandatory Fields */
if (yap_init->myddas_pass != NULL)
Yap_PutValue(AtomMyddasPass,MkAtomTerm(Yap_LookupAtom(yap_init->myddas_pass)));
if (yap_init->myddas_host != NULL)
Yap_PutValue(AtomMyddasHost,MkAtomTerm(Yap_LookupAtom(yap_init->myddas_host)));
}
#endif
#if USE_MYDDAS #if USE_MYDDAS
#define stringify(X) _stringify(X) #define stringify(X) _stringify(X)
#define _stringify(X) #X #define _stringify(X) #X

View File

@ -12,374 +12,265 @@
#include <mysql/mysql.h> #include <mysql/mysql.h>
#endif /*MYDDAS_MYSQL*/ #endif /*MYDDAS_MYSQL*/
#include "myddas.h"
#include "myddas_util.h" #include "myddas_util.h"
#ifdef MYDDAS_MYSQL
/* Auxilary function to table_write*/
static void
n_print(Int , char );
#endif
/* Type: MYSQL->1 ODBC->2*/ /* Type: MYSQL->1 ODBC->2*/
Short Short myddas_util_connection_type(void *con) {
myddas_util_connection_type(void *con){
MYDDAS_UTIL_CONNECTION con_node = myddas_util_search_connection(con);
MYDDAS_UTIL_CONNECTION con_node =
myddas_util_search_connection(con);
if (con_node == NULL) if (con_node == NULL)
return 0; return 0;
return con_node->api; return con_node->api;
// if (con_node->odbc_enviromment != NULL) /* ODBC */ // if (con_node->odbc_enviromment != NULL) /* ODBC */
// return 2; // return 2;
//else // else
// return 1; // return 1;
} }
MYDDAS_UTIL_PREDICATE MYDDAS_UTIL_PREDICATE
myddas_util_search_predicate(const char *pred_name, Int pred_arity, myddas_util_search_predicate(const char *pred_name, Int pred_arity,
const char *pred_module){ const char *pred_module) {
CACHE_REGS CACHE_REGS
MYDDAS_UTIL_PREDICATE pred=NULL; MYDDAS_UTIL_PREDICATE pred = NULL;
MYDDAS_UTIL_CONNECTION top = Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections; MYDDAS_UTIL_CONNECTION top =
Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections;
for (;top!=NULL;top=top->next) for (; top != NULL; top = top->next) {
{ if ((pred = myddas_util_find_predicate(pred_name, pred_arity, pred_module,
if ((pred=myddas_util_find_predicate(pred_name,pred_arity,pred_module,top->predicates))) top->predicates)))
return pred; return pred;
} }
return NULL; return NULL;
} }
/* When using this function, we must guarante that this predicate /* When using this function, we must guarante that this predicate
it's unique */ it's unique */
MYDDAS_UTIL_CONNECTION MYDDAS_UTIL_CONNECTION
myddas_util_add_predicate(const char *pred_name, Int pred_arity, myddas_util_add_predicate(const char *pred_name, Int pred_arity,
const char *pred_module, void *con){ const char *pred_module, void *con) {
MYDDAS_UTIL_CONNECTION node_con =
myddas_util_search_connection(con);
MYDDAS_UTIL_PREDICATE new =
myddas_init_initialize_predicate(pred_name,pred_arity,pred_module,node_con->predicates);
if (new == NULL)
{
myddas_util_error_message("Could not initialize predicate node",__LINE__,__FILE__);
return NULL;
}
node_con->predicates=new;
return node_con;
}
void MYDDAS_UTIL_CONNECTION node_con = myddas_util_search_connection(con);
myddas_util_delete_predicate(MYDDAS_UTIL_PREDICATE to_delete){
MYDDAS_UTIL_PREDICATE new = myddas_init_initialize_predicate(
pred_name, pred_arity, pred_module, node_con->predicates);
if (new == NULL) {
myddas_util_error_message("Could not initialize predicate node", __LINE__,
__FILE__);
return NULL;
}
node_con->predicates = new;
return node_con;
}
void myddas_util_delete_predicate(MYDDAS_UTIL_PREDICATE to_delete) {
CACHE_REGS CACHE_REGS
if (to_delete->next != NULL) if (to_delete->next != NULL)
to_delete->next->previous = to_delete->previous; to_delete->next->previous = to_delete->previous;
if (to_delete->previous != NULL) if (to_delete->previous != NULL)
to_delete->previous->next = to_delete->next; to_delete->previous->next = to_delete->next;
else //First predicate of the predicate list else // First predicate of the predicate list
{ {
MYDDAS_UTIL_CONNECTION con_node = Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections; MYDDAS_UTIL_CONNECTION con_node =
for(;con_node != NULL; con_node = con_node->next) Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections;
if (con_node->predicates == to_delete) for (; con_node != NULL; con_node = con_node->next)
break; if (con_node->predicates == to_delete)
con_node->predicates = to_delete->next; break;
} con_node->predicates = to_delete->next;
MYDDAS_FREE(to_delete,struct myddas_list_preds); }
MYDDAS_FREE(to_delete, struct myddas_list_preds);
} }
void void myddas_util_delete_connection(void *conn) {
myddas_util_delete_connection(void *conn){
CACHE_REGS CACHE_REGS
MYDDAS_UTIL_CONNECTION to_delete = myddas_util_search_connection(conn); MYDDAS_UTIL_CONNECTION to_delete = myddas_util_search_connection(conn);
if (to_delete == NULL) if (to_delete == NULL)
return; return;
else else {
{ /* Removes the predicates list */
/* Removes the predicates list */ myddas_util_delete_predicate_list(to_delete->predicates);
myddas_util_delete_predicate_list(to_delete->predicates);
#ifdef MYDDAS_STATS #ifdef MYDDAS_STATS
/* Removes the stats list */ /* Removes the stats list */
myddas_stats_delete_stats_list(to_delete->stats); myddas_stats_delete_stats_list(to_delete->stats);
#endif #endif
/* List Integrety */ /* List Integrety */
/* Is the last element of the list */ /* Is the last element of the list */
if ((to_delete->next) != NULL) if ((to_delete->next) != NULL)
to_delete->next->previous = to_delete->previous; to_delete->next->previous = to_delete->previous;
/* Is the first element of the list */ /* Is the first element of the list */
if (to_delete == (Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections)) if (to_delete == (Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections))
Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections = to_delete->next; Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections = to_delete->next;
else else
to_delete->previous->next=to_delete->next; to_delete->previous->next = to_delete->next;
MYDDAS_FREE(to_delete,struct myddas_list_connection); MYDDAS_FREE(to_delete, struct myddas_list_connection);
return; return;
} }
} }
MYDDAS_UTIL_CONNECTION MYDDAS_UTIL_CONNECTION
myddas_util_search_connection(void *conn){ myddas_util_search_connection(void *conn) {
CACHE_REGS CACHE_REGS
MYDDAS_UTIL_CONNECTION list = Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections; MYDDAS_UTIL_CONNECTION list =
Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections;
#ifdef MYDDAS_STATS #ifdef MYDDAS_STATS
if (conn == 0) { /* We want all the statistics */ if (conn == 0) { /* We want all the statistics */
return list; return list;
} }
#endif #endif
for (;list!=NULL;list=list->next) for (; list != NULL; list = list->next)
if (list->connection == conn) if (list->connection == conn)
return list; return list;
return NULL; return NULL;
} }
MYDDAS_UTIL_CONNECTION
myddas_util_add_connection(void *conn, void *enviromment, MYDDAS_API api){
CACHE_REGS
MYDDAS_UTIL_CONNECTION node=NULL;
MYDDAS_UTIL_CONNECTION temp=NULL;
if ((node = myddas_util_search_connection(conn)) != NULL) MYDDAS_UTIL_CONNECTION
{ myddas_util_add_connection(void *conn, void *enviromment, MYDDAS_API api) {
return node; CACHE_REGS
} MYDDAS_UTIL_CONNECTION node = NULL;
//put the new connection node on the top of the list MYDDAS_UTIL_CONNECTION temp = NULL;
temp = myddas_init_initialize_connection(conn,enviromment,api,Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections);
if (temp == NULL) if ((node = myddas_util_search_connection(conn)) != NULL) {
{ return node;
}
// put the new connection node on the top of the list
temp = myddas_init_initialize_connection(
conn, enviromment, api,
Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections);
if (temp == NULL) {
#ifdef DEBUG #ifdef DEBUG
myddas_util_error_message("Could not initialize connection node",__LINE__,__FILE__); myddas_util_error_message("Could not initialize connection node", __LINE__,
#endif __FILE__);
return NULL; #endif
} return NULL;
}
Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections = temp; Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections = temp;
return Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections; return Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections;
} }
#ifdef MYDDAS_ODBC UInt myddas_util_get_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con) {
/* This function searches the MYDDAS list for odbc connections
If there isn't any, it returns NULL. This is a nice way to know
if there is any odbc connections left on the list*/
SQLHENV
myddas_util_get_odbc_enviromment(SQLHDBC connection){
CACHE_REGS
MYDDAS_UTIL_CONNECTION top = Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections;
for (;top != NULL;top=top->next)
if (top->connection == ((void *)connection))
return top->odbc_enviromment;
return NULL;
}
#endif
UInt
myddas_util_get_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con){
return con->total_number_queries; return con->total_number_queries;
} }
void void myddas_util_set_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con,
myddas_util_set_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con, UInt number) {
UInt number){
con->total_number_queries = number; con->total_number_queries = number;
} }
#ifdef MYDDAS_MYSQL #ifdef MYDDAS_MYSQL
/* Auxilary function to table_write*/ /* Auxilary function to table_write*/
static void static void n_print(Int n, char c) {
n_print(Int n, char c) for (; n > 0; n--)
{ printf("%c", c);
for(;n>0;n--) printf("%c",c);
} }
#endif #endif
void myddas_util_error_message(char *message ,Int line,char *file){ void myddas_util_error_message(char *message, Int line, char *file) {
#ifdef DEBUG #ifdef DEBUG
printf ("ERROR: %s at line %d in file %s\n",message,(int)line,file); printf("ERROR: %s at line %d in file %s\n", message, (int)line, file);
#else #else
printf ("ERROR: %s\n",message); printf("ERROR: %s\n", message);
#endif #endif
} }
MYDDAS_UTIL_PREDICATE MYDDAS_UTIL_PREDICATE
myddas_util_find_predicate(const char *pred_name, Int pred_arity, myddas_util_find_predicate(const char *pred_name, Int pred_arity,
const char *pred_module, MYDDAS_UTIL_PREDICATE list){ const char *pred_module,
MYDDAS_UTIL_PREDICATE list) {
for(;list != NULL ; list = list->next) for (; list != NULL; list = list->next)
if (pred_arity == list->pred_arity && if (pred_arity == list->pred_arity && !strcmp(pred_name, list->pred_name) &&
!strcmp(pred_name,list->pred_name) && !strcmp(pred_module, list->pred_module))
!strcmp(pred_module,list->pred_module))
return list; return list;
return NULL; return NULL;
} }
void void myddas_util_delete_predicate_list(MYDDAS_UTIL_PREDICATE preds_list) {
myddas_util_delete_predicate_list(MYDDAS_UTIL_PREDICATE preds_list){
CACHE_REGS CACHE_REGS
MYDDAS_UTIL_PREDICATE to_delete = NULL; MYDDAS_UTIL_PREDICATE to_delete = NULL;
for (;preds_list != NULL;)
{
to_delete = preds_list;
preds_list = preds_list->next;
MYDDAS_FREE(to_delete,struct myddas_list_preds); for (; preds_list != NULL;) {
} to_delete = preds_list;
preds_list = preds_list->next;
MYDDAS_FREE(to_delete, struct myddas_list_preds);
}
return; return;
} }
#ifdef MYDDAS_MYSQL // DELETE THIS WHEN DB_STATS IS COMPLETED
void MyddasInt get_myddas_top(void) {
myddas_util_table_write(MYSQL_RES *res_set){
MYSQL_ROW row;
MYSQL_FIELD *fields;
Int i,f;
if (mysql_num_rows(res_set) == 0)
{
printf ("Empty Set\n");
return;
}
f = mysql_num_fields(res_set);
fields = mysql_fetch_field(res_set);
for(i=0;i<f;i++)
{
printf("+");
if (strlen(fields[i].name)>fields[i].max_length) fields[i].max_length=strlen(fields[i].name);
n_print(fields[i].max_length+2,'-');
}
printf("+\n");
for(i=0;i<f;i++)
{
printf("|");
printf(" %s ",fields[i].name);
n_print(fields[i].max_length - strlen(fields[i].name),' ');
}
printf("|\n");
for(i=0;i<f;i++)
{
printf("+");
n_print(fields[i].max_length+2,'-');
}
printf("+\n");
while ((row = mysql_fetch_row(res_set)) != NULL)
{
for(i=0;i<f;i++)
{
printf("|");
if (row[i] != NULL)
{
printf(" %s ",row[i]);
n_print(fields[i].max_length - strlen(row[i]),' ');
}
else
{
printf(" NULL ");
n_print(fields[i].max_length - 4,' ');
}
}
printf("|\n");
}
for(i=0;i<f;i++)
{
printf("+");
n_print(fields[i].max_length+2,'-');
}
printf("+\n");
}
#endif
//DELETE THIS WHEN DB_STATS IS COMPLETED
MyddasInt
get_myddas_top( void ){
CACHE_REGS CACHE_REGS
if (Yap_REGS.MYDDAS_GLOBAL_POINTER == NULL) if (Yap_REGS.MYDDAS_GLOBAL_POINTER == NULL)
return 0; return 0;
return (Int)Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections; return (Int)Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections;
} }
void * void *myddas_util_get_pred_next(void *pointer) {
myddas_util_get_pred_next(void *pointer){ MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE)pointer;
MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE) pointer; return (void *)(temp->next);
return (void *) (temp->next);
} }
MyddasInt MyddasInt myddas_util_get_pred_arity(void *pointer) {
myddas_util_get_pred_arity(void *pointer){ MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE)pointer;
MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE) pointer;
return temp->pred_arity; return temp->pred_arity;
} }
const char * const char *myddas_util_get_pred_name(void *pointer) {
myddas_util_get_pred_name(void *pointer){ MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE)pointer;
MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE) pointer;
return temp->pred_name; return temp->pred_name;
} }
const char * const char *myddas_util_get_pred_module(void *pointer) {
myddas_util_get_pred_module(void *pointer){ MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE)pointer;
MYDDAS_UTIL_PREDICATE temp = (MYDDAS_UTIL_PREDICATE) pointer;
return temp->pred_module; return temp->pred_module;
} }
void * void *myddas_util_get_list_pred(MYDDAS_UTIL_CONNECTION node) {
myddas_util_get_list_pred(MYDDAS_UTIL_CONNECTION node){
return (void *)(node->predicates); return (void *)(node->predicates);
} }
#ifdef DEBUG #ifdef DEBUG
void check_int( void ){ void check_int(void) {
CACHE_REGS CACHE_REGS
MYDDAS_UTIL_PREDICATE pred = NULL; MYDDAS_UTIL_PREDICATE pred = NULL;
MYDDAS_UTIL_CONNECTION top = Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections; MYDDAS_UTIL_CONNECTION top =
for ( ; top!=NULL ; top=top->next) Yap_REGS.MYDDAS_GLOBAL_POINTER->myddas_top_connections;
{ for (; top != NULL; top = top->next) {
printf ("***************\n"); printf("***************\n");
printf ("===== top =====\n"); printf("===== top =====\n");
printf ("======= %p =====\n",top); printf("======= %p =====\n", top);
printf ("CONN: = %p =====\n",top->connection); printf("CONN: = %p =====\n", top->connection);
printf ("ENV : = %p =====\n",top->odbc_enviromment); printf("ENV : = %p =====\n", top->odbc_enviromment);
printf ("PRED: = %p =====\n",top->predicates); printf("PRED: = %p =====\n", top->predicates);
printf ("======= %p =====\n",top->previous); printf("======= %p =====\n", top->previous);
printf ("======= %p =====\n",top->next); printf("======= %p =====\n", top->next);
if (top->predicates != NULL) if (top->predicates != NULL) {
{ printf("\t******\n");
printf ("\t******\n"); printf("\t===== PREDICATES =====\n");
printf ("\t===== PREDICATES =====\n"); for (pred = top->predicates; pred != NULL; pred = pred->next) {
for (pred = top->predicates ; pred != NULL ; pred = pred->next) printf("\t--------------\n");
{ printf("\t===== %p =====\n", pred);
printf ("\t--------------\n"); printf("\t===== %s =====\n", pred->pred_name);
printf ("\t===== %p =====\n",pred); printf("\t===== %d =====\n", pred->pred_arity);
printf ("\t===== %s =====\n",pred->pred_name); printf("\t===== %s =====\n", pred->pred_module);
printf ("\t===== %d =====\n",pred->pred_arity); printf("\t===== %p =====\n", pred->previous);
printf ("\t===== %s =====\n",pred->pred_module); printf("\t===== %p =====\n", pred->next);
printf ("\t===== %p =====\n",pred->previous); }
printf ("\t===== %p =====\n",pred->next);
}
}
} }
}
return; return;
} }
#endif #endif

View File

@ -1,32 +1,14 @@
#include "myddas_structs.h" #include "myddas_structs.h"
void myddas_util_error_message(char *message ,Int line,char *file); void myddas_util_error_message(char *message, Int line, char *file);
/* Search for the predicate in the given predicate list*/ UInt myddas_util_get_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con);
MYDDAS_UTIL_CONNECTION myddas_util_search_connection(void *conn);
MYDDAS_UTIL_CONNECTION void myddas_util_set_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con,
myddas_init_initialize_connection(void *conn,void *enviromment, UInt number);
MYDDAS_API api,
MYDDAS_UTIL_CONNECTION next);
MYDDAS_UTIL_CONNECTION //void myddas_util_table_write(MYSQL_RES *res_set);
myddas_util_add_connection(void *conn, void *enviromment, MYDDAS_API api);
MYDDAS_UTIL_PREDICATE
myddas_init_initialize_predicate(const char *pred_name, int pred_arity,
const char *pred_module, MYDDAS_UTIL_PREDICATE next);
MYDDAS_UTIL_PREDICATE
myddas_util_find_predicate(const char *pred_name, Int pred_arity,
const char *pred_module, MYDDAS_UTIL_PREDICATE list);
UInt
myddas_util_get_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con);
void
myddas_util_set_total_multi_queries_number(MYDDAS_UTIL_CONNECTION con, UInt number);
void *myddas_util_get_pred_next(void *pointer); void *myddas_util_get_pred_next(void *pointer);
@ -34,8 +16,30 @@ MyddasInt myddas_util_get_pred_arity(void *pointer);
const char *myddas_util_get_pred_name(void *pointer); const char *myddas_util_get_pred_name(void *pointer);
void myddas_util_delete_predicate(MYDDAS_UTIL_PREDICATE to_delete);
const char *myddas_util_get_pred_module(void *pointer); const char *myddas_util_get_pred_module(void *pointer);
void *myddas_util_get_list_pred(MYDDAS_UTIL_CONNECTION node); void *myddas_util_get_list_pred(MYDDAS_UTIL_CONNECTION node);
void myddas_util_delete_predicate_list(MYDDAS_UTIL_PREDICATE preds_list); void myddas_util_delete_predicate_list(MYDDAS_UTIL_PREDICATE preds_list);
MYDDAS_UTIL_CONNECTION myddas_util_search_connection(void *con);
MYDDAS_UTIL_PREDICATE myddas_util_find_predicate(const char *pred_name,
Int pred_arity,
const char *pred_module,
MYDDAS_UTIL_PREDICATE list);
MYDDAS_UTIL_CONNECTION myddas_util_add_connection(void *conn, void *enviromment,
MYDDAS_API api);
void myddas_util_delete_connection(void *conn);
MYDDAS_UTIL_PREDICATE
myddas_init_initialize_predicate(const char *pred_name, int pred_arity,
const char *pred_module,
MYDDAS_UTIL_PREDICATE next);
MYDDAS_UTIL_CONNECTION
myddas_init_initialize_connection(void *conn, void *enviromment, MYDDAS_API api,
MYDDAS_UTIL_CONNECTION next);

View File

@ -1,6 +1,21 @@
#include <string.h> p#include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include "Yap.h" #include "Yap.h"
#include "cut_c.h" #include "cut_c.h"
MYDDAS_UTIL_CONNECTION
myddas_init_initialize_connection(void *conn, void *enviromment, MYDDAS_API api,
MYDDAS_UTIL_CONNECTION next);
MYDDAS_UTIL_CONNECTION
myddas_util_add_connection(void *conn, void *enviromment, MYDDAS_API api);
MYDDAS_UTIL_PREDICATE
myddas_init_initialize_predicate(const char *pred_name, int pred_arity,
const char *pred_module,
MYDDAS_UTIL_PREDICATE next);
MYDDAS_UTIL_PREDICATE
myddas_util_find_predicate(const char *pred_name, Int pred_arity,
const char *pred_module, MYDDAS_UTIL_PREDICATE list);

View File

@ -1,25 +0,0 @@
#ifndef MYDDAS_WKB_H_
#define MYDDAS_WKB_H_
typedef char byte;
typedef unsigned int uint32;
#define WKBXDR 0
#define WKBNDR 1
#define WKBMINTYPE 1
#define WKBPOINT 1
#define WKBLINESTRING 2
#define WKBPOLYGON 3
#define WKBMULTIPOINT 4
#define WKBMULTILINESTRING 5
#define WKBMULTIPOLYGON 6
#define WKBGEOMETRYCOLLECTION 7
#define WKBMAXTYPE 7
#define WKBGEOMETRY 0
#endif /* MYDDAS_WKB_H_ */

View File

@ -1,382 +0,0 @@
#if defined MYDDAS_MYSQL
#include <stdio.h>
#include <stdlib.h>
#include "Yap.h"
#include <netinet/in.h>
#include "myddas_wkb.h"
#include "myddas_wkb2prolog.h"
static void readswap4(uint32 *buf);
static void readswap8(double *buf);
static byte get_hostbyteorder(void);
static byte get_inbyteorder(void);
static uint32 get_wkbType(void);
static Term get_point(char *functor USES_REGS);
static Term get_linestring(char *functor);
static Term get_polygon(char *functor);
static Term get_geometry(uint32 type);
static int swaporder;
static byte inbyteorder, hostbyteorder;
static byte *cursor;
Term wkb2prolog(char *wkb) {
uint32 type;
cursor = wkb;
/*ignore the SRID 4 bytes*/
cursor += 4;
/*byteorder*/
hostbyteorder = get_hostbyteorder();
inbyteorder = get_inbyteorder();
swaporder = 0;
if ( hostbyteorder != inbyteorder )
swaporder = 1;
type = get_wkbType();
return get_geometry(type);
}
static byte get_hostbyteorder(void){
uint16_t host = 5;
uint16_t net;
net = htons(host);
if ( net == host )
return(WKBXDR);
else
return(WKBNDR);
}
static byte get_inbyteorder(void){
byte b = cursor[0];
if (b != WKBNDR && b != WKBXDR) {
fprintf(stderr, "Unknown byteorder: %d\n",b);
exit(0);
}
cursor++;
return(b);
}
static uint32 get_wkbType(void){
uint32 u;
/* read the type */
readswap4(&u);
if (u > WKBMAXTYPE || u < WKBMINTYPE) {
fprintf(stderr, "Unknown type: %d\n",u);
exit(0);
}
return(u);
}
static void readswap4(uint32 *buf){
((byte *) buf)[0] = cursor[0];
((byte *) buf)[1] = cursor[1];
((byte *) buf)[2] = cursor[2];
((byte *) buf)[3] = cursor[3];
if ( swaporder ) {
if ( inbyteorder == WKBXDR ) {
*buf = (uint32)ntohl((u_long)*buf);
} else {
byte u[4];
u[0] = ((byte *) buf)[3];
u[1] = ((byte *) buf)[2];
u[2] = ((byte *) buf)[1];
u[3] = ((byte *) buf)[0];
((byte *) buf)[0] = u[0];
((byte *) buf)[1] = u[1];
((byte *) buf)[2] = u[2];
((byte *) buf)[3] = u[3];
}
}
cursor += 4;
}
static void readswap8(double *buf) {
((byte *) buf)[0] = cursor[0];
((byte *) buf)[1] = cursor[1];
((byte *) buf)[2] = cursor[2];
((byte *) buf)[3] = cursor[3];
((byte *) buf)[4] = cursor[4];
((byte *) buf)[5] = cursor[5];
((byte *) buf)[6] = cursor[6];
((byte *) buf)[7] = cursor[7];
if ( swaporder ) {
if ( inbyteorder == WKBXDR ) {
u_long u[2];
u[0] = ((u_long *) buf)[0];
u[1] = ((u_long *) buf)[1];
((u_long *) buf)[1] = ntohl(u[0]);
((u_long *) buf)[0] = ntohl(u[1]);
} else {
byte u[8];
u[0] = ((byte *) buf)[7];
u[1] = ((byte *) buf)[6];
u[2] = ((byte *) buf)[5];
u[3] = ((byte *) buf)[4];
u[4] = ((byte *) buf)[3];
u[5] = ((byte *) buf)[2];
u[6] = ((byte *) buf)[1];
u[7] = ((byte *) buf)[0];
((byte *) buf)[0] = u[0];
((byte *) buf)[1] = u[1];
((byte *) buf)[2] = u[2];
((byte *) buf)[3] = u[3];
((byte *) buf)[4] = u[4];
((byte *) buf)[5] = u[5];
((byte *) buf)[6] = u[6];
((byte *) buf)[7] = u[7];
}
}
cursor += 8;
}
static Term get_point(char *func USES_REGS){
Term args[2];
Functor functor;
double d;
if(func == NULL)
/*functor "," => (_,_)*/
functor = Yap_MkFunctor(Yap_LookupAtom(","), 2);
else
functor = Yap_MkFunctor(Yap_LookupAtom(func), 2);
/* read the X */
readswap8(&d);
args[0] = MkFloatTerm(d);
/* read the Y */
readswap8(&d);
args[1] = MkFloatTerm(d);
return Yap_MkApplTerm(functor, 2, args);
}
static Term get_linestring(char *func){
CACHE_REGS
Term *c_list;
Term list;
Functor functor;
uint32 n;
int i;
/* read the number of vertices */
readswap4(&n);
/* space for arguments */
c_list = (Term *) calloc(sizeof(Term),n);
for ( i = 0; i < n; i++) {
c_list[i] = get_point(NULL PASS_REGS);
}
list = MkAtomTerm(Yap_LookupAtom("[]"));
for (i = n - 1; i >= 0; i--) {
list = MkPairTerm(c_list[i],list);
}
if(func == NULL)
return list;
else{
functor = Yap_MkFunctor(Yap_LookupAtom(func), 1);
return Yap_MkApplTerm(functor, 1, &list);
}
}
static Term get_polygon(char *func){
CACHE_REGS
uint32 r;
int i;
Functor functor;
Term *c_list;
Term list;
/* read the number of rings */
readswap4(&r);
/* space for rings */
c_list = (Term *) calloc(sizeof(Term),r);
for ( i = 0; i < r; i++ ) {
c_list[i] = get_linestring(NULL);
}
list = MkAtomTerm(Yap_LookupAtom("[]"));
for (i = r - 1; i >= 0; i--) {
list = MkPairTerm(c_list[i],list);
}
if(func == NULL)
return list;
else{
functor = Yap_MkFunctor(Yap_LookupAtom("polygon"), 1);
return Yap_MkApplTerm(functor, 1, &list);
}
}
static Term get_geometry(uint32 type){
CACHE_REGS
switch(type) {
case WKBPOINT:
return get_point("point" PASS_REGS);
case WKBLINESTRING:
return get_linestring("linestring");
case WKBPOLYGON:
return get_polygon("polygon");
case WKBMULTIPOINT:
{
uint32 n;
int i;
Functor functor;
Term *c_list;
Term list;
/* read the number of points */
readswap4(&n);
/* space for points */
c_list = (Term *) calloc(sizeof(Term),n);
for ( i = 0; i < n; i++ ) {
/* read (and ignore) the byteorder and type */
get_inbyteorder();
get_wkbType();
c_list[i] = get_point(NULL PASS_REGS);
}
list = MkAtomTerm(Yap_LookupAtom("[]"));
for (i = n - 1; i >= 0; i--) {
list = MkPairTerm(c_list[i],list);
}
functor = Yap_MkFunctor(Yap_LookupAtom("multipoint"), 1);
return Yap_MkApplTerm(functor, 1, &list);
}
case WKBMULTILINESTRING:
{
uint32 n;
int i;
Functor functor;
Term *c_list;
Term list;
/* read the number of polygons */
readswap4(&n);
/* space for polygons*/
c_list = (Term *) calloc(sizeof(Term),n);
for ( i = 0; i < n; i++ ) {
/* read (and ignore) the byteorder and type */
get_inbyteorder();
get_wkbType();
c_list[i] = get_linestring(NULL);
}
list = MkAtomTerm(Yap_LookupAtom("[]"));
for (i = n - 1; i >= 0; i--) {
list = MkPairTerm(c_list[i],list);
}
functor = Yap_MkFunctor(Yap_LookupAtom("multilinestring"), 1);
return Yap_MkApplTerm(functor, 1, &list);
}
case WKBMULTIPOLYGON:
{
uint32 n;
int i;
Functor functor;
Term *c_list;
Term list;
/* read the number of polygons */
readswap4(&n);
/* space for polygons*/
c_list = (Term *) calloc(sizeof(Term),n);
for ( i = 0; i < n; i++ ) {
/* read (and ignore) the byteorder and type */
get_inbyteorder();
get_wkbType();
c_list[i] = get_polygon(NULL);
}
list = MkAtomTerm(Yap_LookupAtom("[]"));
for (i = n - 1; i >= 0; i--) {
list = MkPairTerm(c_list[i],list);
}
functor = Yap_MkFunctor(Yap_LookupAtom("multipolygon"), 1);
return Yap_MkApplTerm(functor, 1, &list);
}
case WKBGEOMETRYCOLLECTION:
{
uint32 n;
int i;
Functor functor;
Term *c_list;
Term list;
/* read the number of geometries */
readswap4(&n);
/* space for geometries*/
c_list = (Term *) calloc(sizeof(Term),n);
for ( i = 0; i < n; i++ ) {
get_inbyteorder();
c_list[i] = get_geometry(get_wkbType());
}
list = MkAtomTerm(Yap_LookupAtom("[]"));
for (i = n - 1; i >= 0; i--) {
list = MkPairTerm(c_list[i],list);
}
functor = Yap_MkFunctor(Yap_LookupAtom("geometrycollection"), 1);
return Yap_MkApplTerm(functor, 1, &list);
}
}
return MkAtomTerm(Yap_LookupAtom("[]"));
}
#endif /*MYDDAS_MYSQL*/

View File

@ -1,6 +0,0 @@
#ifndef MYDDAS_WKB2PROLOG_H_
# define MYDDAS_WKB2PROLOG_H_
Term wkb2prolog(char *wkb) ;
#endif /* !MYDDAS_WKB2PROLOG_H_ */

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