This commit is contained in:
Vitor Santos Costa 2016-09-30 17:11:13 -05:00
parent 41ccbf7367
commit 43d3579c57
19 changed files with 397 additions and 411 deletions

View File

@ -3336,6 +3336,8 @@ X_API Int YAP_FunctorToInt(Functor f) {
X_API Functor YAP_IntToFunctor(Int i) { return TR_Functors[i]; }
X_API void *YAP_shared(void) { return LOCAL_shared; }
void yap_init(void) {}
#endif // C_INTERFACE_C

View File

@ -214,6 +214,24 @@ public:
///
YAPPredicate(YAPAtom at, uintptr_t arity);
/// char */module constructor for predicates.
///
inline YAPPredicate(const char *at, uintptr_t arity) {
ap = RepPredProp(PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity), CurrentModule));
};
/// char */module constructor for predicates.
///
inline YAPPredicate(const char *at, uintptr_t arity, YAPTerm mod) {
ap = RepPredProp(PredPropByFunc(Yap_MkFunctor(Yap_LookupAtom(at), arity), mod.t));
};
/// char */module constructor for predicates.
///
inline YAPPredicate(const char *at, YAPTerm mod) {
ap = RepPredProp(PredPropByAtom(Yap_LookupAtom(at), mod.t));
}
/// module of a predicate
///
/// notice that modules are currently treated as atoms, this should change.
@ -248,10 +266,13 @@ public:
*/
class YAPPrologPredicate : public YAPPredicate {
public:
YAPPrologPredicate(YAPTerm t);
YAPPrologPredicate(YAPTerm t) : YAPPredicate(t) {};
YAPPrologPredicate(const char *s, arity_t arity): YAPPredicate(s, arity) {};
/// add a new clause
void *assertClause(YAPTerm clause, bool last = true,
YAPTerm source = YAPTerm());
/// add a new tuple
void *assertFact(YAPTerm *tuple, bool last = true);
/// retract at least the first clause matching the predicate.
void *retractClause(YAPTerm skeleton, bool all = false);
/// return the Nth clause (if source is available)

View File

@ -462,28 +462,7 @@ YAPVarTerm::YAPVarTerm() {
}
const char *YAPAtom::getName(void) {
if (IsWideAtom(a)) {
// return an UTF-8 version
size_t sz = 512;
wchar_t *ptr = a->WStrOfAE;
utf8proc_int32_t ch = -1;
char *s = new char[sz], *op = s;
while (ch) {
ch = *ptr++;
op += put_utf8((unsigned char *)op, ch);
}
sz = strlen(s) + 1;
char *os = new char[sz];
memcpy(os, s, sz);
delete[] s;
return os;
} else if (IsBlob(a)) {
size_t sz = 1024;
char *s = new char[sz + 1];
return Yap_blob_to_string(RepAtom(a), s, sz);
} else {
return (char *)a->StrOfAE;
}
return Yap_AtomToUTF8Text( a, nullptr );
}
void YAPQuery::openQuery() {
@ -554,7 +533,7 @@ bool YAPEngine::call(YAPPredicate ap, YAPTerm ts[]) {
return result;
}
bool YAPEngine::call(YAPTerm Yt) {
bool YAPEngine::goal(YAPTerm Yt) {
CACHE_REGS
BACKUP_MACHINE_REGS();
Term t = Yt.term(), terr, tmod = CurrentModule, *ts = nullptr;
@ -676,8 +655,10 @@ bool YAPQuery::next() {
}
q_state = 1;
if ((terr = Yap_GetException())) {
Yap_DebugPlWriteln(terr);
YAP_LeaveGoal(false, &q_h);
Yap_CloseHandles(q_handles);
q_open = false;
throw YAPError();
}
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "out %d", result);
@ -909,8 +890,6 @@ PredEntry *YAPPredicate::getPred(Term &t, Term *&outp) {
return ap;
}
YAPPrologPredicate::YAPPrologPredicate(YAPTerm t) : YAPPredicate(t) {}
void *YAPPrologPredicate::assertClause(YAPTerm cl, bool last, YAPTerm source) {
CACHE_REGS
@ -922,7 +901,7 @@ void *YAPPrologPredicate::assertClause(YAPTerm cl, bool last, YAPTerm source) {
sourcet = source.gt();
else
sourcet = TermZERO;
yamop *codeaddr = Yap_cclause(tt, PP->ArityOfPE, Yap_CurrentModule(),
yamop *codeaddr = Yap_cclause(tt, ap->ArityOfPE, Yap_CurrentModule(),
sourcet); /* vsc: give the number of arguments
to cclause in case there is overflow */
if (LOCAL_ErrorMessage) {
@ -937,6 +916,29 @@ void *YAPPrologPredicate::assertClause(YAPTerm cl, bool last, YAPTerm source) {
return tref;
}
void *YAPPrologPredicate::assertFact(YAPTerm *cl, bool last) {
CACHE_REGS
arity_t i;
RECOVER_MACHINE_REGS();
Term tt = AbsAppl(HR);
*HR++ = (CELL)(ap->FunctorOfPred);
for (i = 0; i < ap->ArityOfPE; i++,cl++)
*HR++ = cl->gt();
yamop *codeaddr = Yap_cclause(tt, ap->ArityOfPE, Yap_CurrentModule(),
tt); /* vsc: give the number of arguments
to cclause in case there is overflow */
if (LOCAL_ErrorMessage) {
RECOVER_MACHINE_REGS();
return 0;
}
Term *tref = &tt;
if (Yap_addclause(tt, codeaddr, (last ? TermAssertz : TermAsserta),
Yap_CurrentModule(), tref)) {
RECOVER_MACHINE_REGS();
}
return tref;
}
void *YAPPrologPredicate::retractClause(YAPTerm skeleton, bool all) {
return 0;
}

View File

@ -179,7 +179,7 @@ public:
/// current directory for the engine
bool call(YAPPredicate ap, YAPTerm ts[]);
/// current directory for the engine
bool call(YAPTerm t);
bool goal(YAPTerm t);
const char *currentDir() {
char dir[1024];
@ -191,6 +191,11 @@ public:
std::string s = Yap_version();
return s.c_str();
};
#ifdef SWIGPYTHON
inline void share(PyObject *arg) {
LOCAL_shared = arg;
};
#endif
};
#endif /* YAPQ_HH */

View File

@ -322,5 +322,6 @@ size_t MAX_SIZE =1024L
/* last call to walltime. */
uint64_t LastWTime =0
void* shared =NULL
END_WORKER_LOCAL

View File

@ -481,4 +481,6 @@
#define LOCAL_LastWTime LOCAL->LastWTime_
#define REMOTE_LastWTime(wid) REMOTE(wid)->LastWTime_
#define LOCAL_shared LOCAL->shared_
#define REMOTE_shared(wid) REMOTE(wid)->shared_

View File

@ -1,277 +1,276 @@
/* This file, hlocals.h, was generated automatically by "yap -L
misc/buildlocalglobal"
please do not update, update H/LOCALS instead */
/* This file, hlocals.h, was generated automatically by "yap -L misc/buildlocalglobal"
please do not update, update H/LOCALS instead */
// Stuff that must be considered local to a thread or worker
typedef struct worker_local {
// Streams
int c_input_stream_;
int c_output_stream_;
int c_error_stream_;
bool sockets_io_;
bool within_print_message_;
//
// Used by the prompts to check if they are after a newline, and then a
// prompt should be output, or if we are in the middle of a line.
//
bool newline_;
Atom AtPrompt_;
char Prompt_[MAX_PROMPT + 1];
encoding_t encoding_;
bool quasi_quotations_;
UInt default_priority_;
bool eot_before_eof_;
UInt max_depth_;
UInt max_list_;
UInt max_write_args_;
// Restore info
CELL *OldASP_;
CELL *OldLCL0_;
tr_fr_ptr OldTR_;
CELL *OldGlobalBase_;
CELL *OldH_;
CELL *OldH0_;
ADDR OldTrailBase_;
ADDR OldTrailTop_;
ADDR OldHeapBase_;
ADDR OldHeapTop_;
Int ClDiff_;
Int GDiff_;
Int HDiff_;
Int GDiff0_;
CELL *GSplit_;
Int LDiff_;
Int TrDiff_;
Int XDiff_;
Int DelayDiff_;
Int BaseDiff_;
// Reduction counters
YAP_ULONG_LONG ReductionsCounter_;
YAP_ULONG_LONG PredEntriesCounter_;
YAP_ULONG_LONG RetriesCounter_;
int ReductionsCounterOn_;
int PredEntriesCounterOn_;
int RetriesCounterOn_;
// support for consulting files
/* current consult stack */
union CONSULT_OBJ *ConsultSp_;
/* current maximum number of cells in consult stack */
UInt ConsultCapacity_;
/* top of consult stack */
union CONSULT_OBJ *ConsultBase_;
/* low-water mark for consult */
union CONSULT_OBJ *ConsultLow_;
Term VarNames_;
Atom SourceFileName_;
UInt SourceFileLineno_;
// global variables
Term GlobalArena_;
UInt GlobalArenaOverflows_;
Int ArenaOverflows_;
Int DepthArenas_;
int ArithError_;
struct pred_entry *LastAssertedPred_;
struct pred_entry *TmpPred_;
char *ScannerStack_;
struct scanner_extra_alloc *ScannerExtraBlocks_;
/// worker control information
/// stack limit after which the stack is managed by C-code.
Int CBorder_;
/// max number of signals (uint64_t)
UInt MaxActiveSignals_;
/// actual life signals
uint64_t Signals_;
/// indexing help data?
UInt IPredArity_;
yamop *ProfEnd_;
int DoingUndefp_;
Int StartCharCount_;
Int StartLineCount_;
Int StartLinePos_;
scratch_block ScratchPad_;
#ifdef COROUTINING
Term WokenGoals_;
Term AttsMutableList_;
// Streams
int c_input_stream_;
int c_output_stream_;
int c_error_stream_;
bool sockets_io_;
bool within_print_message_;
//
// Used by the prompts to check if they are after a newline, and then a
// prompt should be output, or if we are in the middle of a line.
//
bool newline_;
Atom AtPrompt_;
char Prompt_[MAX_PROMPT+1];
encoding_t encoding_;
bool quasi_quotations_;
UInt default_priority_;
bool eot_before_eof_;
UInt max_depth_;
UInt max_list_;
UInt max_write_args_;
// Restore info
CELL* OldASP_;
CELL* OldLCL0_;
tr_fr_ptr OldTR_;
CELL* OldGlobalBase_;
CELL* OldH_;
CELL* OldH0_;
ADDR OldTrailBase_;
ADDR OldTrailTop_;
ADDR OldHeapBase_;
ADDR OldHeapTop_;
Int ClDiff_;
Int GDiff_;
Int HDiff_;
Int GDiff0_;
CELL* GSplit_;
Int LDiff_;
Int TrDiff_;
Int XDiff_;
Int DelayDiff_;
Int BaseDiff_;
// Reduction counters
YAP_ULONG_LONG ReductionsCounter_;
YAP_ULONG_LONG PredEntriesCounter_;
YAP_ULONG_LONG RetriesCounter_;
int ReductionsCounterOn_;
int PredEntriesCounterOn_;
int RetriesCounterOn_;
// support for consulting files
/* current consult stack */
union CONSULT_OBJ* ConsultSp_;
/* current maximum number of cells in consult stack */
UInt ConsultCapacity_;
/* top of consult stack */
union CONSULT_OBJ* ConsultBase_;
/* low-water mark for consult */
union CONSULT_OBJ* ConsultLow_;
Term VarNames_;
Atom SourceFileName_;
UInt SourceFileLineno_;
//global variables
Term GlobalArena_;
UInt GlobalArenaOverflows_;
Int ArenaOverflows_;
Int DepthArenas_;
int ArithError_;
struct pred_entry* LastAssertedPred_;
struct pred_entry* TmpPred_;
char* ScannerStack_;
struct scanner_extra_alloc* ScannerExtraBlocks_;
/// worker control information
/// stack limit after which the stack is managed by C-code.
Int CBorder_;
/// max number of signals (uint64_t)
UInt MaxActiveSignals_;
/// actual life signals
uint64_t Signals_;
/// indexing help data?
UInt IPredArity_;
yamop* ProfEnd_;
int DoingUndefp_;
Int StartCharCount_;
Int StartLineCount_;
Int StartLinePos_;
scratch_block ScratchPad_;
#ifdef COROUTINING
Term WokenGoals_;
Term AttsMutableList_;
#endif
// gc_stuff
Term GcGeneration_;
Term GcPhase_;
UInt GcCurrentPhase_;
UInt GcCalls_;
Int TotGcTime_;
YAP_ULONG_LONG TotGcRecovered_;
Int LastGcTime_;
Int LastSSTime_;
CELL *OpenArray_;
/* in a single gc */
Int total_marked_;
Int total_oldies_;
struct choicept *current_B_;
CELL *prev_HB_;
CELL *HGEN_;
CELL **iptop_;
// gc_stuff
Term GcGeneration_;
Term GcPhase_;
UInt GcCurrentPhase_;
UInt GcCalls_;
Int TotGcTime_;
YAP_ULONG_LONG TotGcRecovered_;
Int LastGcTime_;
Int LastSSTime_;
CELL* OpenArray_;
/* in a single gc */
Int total_marked_;
Int total_oldies_;
struct choicept* current_B_;
CELL* prev_HB_;
CELL* HGEN_;
CELL** iptop_;
#if defined(GC_NO_TAGS)
char *bp_;
char* bp_;
#endif
tr_fr_ptr sTR_;
tr_fr_ptr sTR0_;
tr_fr_ptr new_TR_;
struct gc_mark_continuation *cont_top0_;
struct gc_mark_continuation *cont_top_;
int discard_trail_entries_;
gc_ma_hash_entry gc_ma_hash_table_[GC_MAVARS_HASH_SIZE];
gc_ma_hash_entry *gc_ma_h_top_;
gc_ma_hash_entry *gc_ma_h_list_;
UInt gc_timestamp_;
ADDR db_vec_;
ADDR db_vec0_;
struct RB_red_blk_node *db_root_;
struct RB_red_blk_node *db_nil_;
sigjmp_buf gc_restore_;
CELL *extra_gc_cells_;
CELL *extra_gc_cells_base_;
CELL *extra_gc_cells_top_;
UInt extra_gc_cells_size_;
struct array_entry *DynamicArrays_;
struct static_array_entry *StaticArrays_;
struct global_entry *GlobalVariables_;
int AllowRestart_;
// Thread Local Area for Fast Storage of Intermediate Compiled Code
struct mem_blk *CMemFirstBlock_;
UInt CMemFirstBlockSz_;
// Variable used by the compiler to store number of permanent vars in a clause
int nperm_;
// Thread Local Area for Labels
Int *LabelFirstArray_;
UInt LabelFirstArraySz_;
tr_fr_ptr sTR_;
tr_fr_ptr sTR0_;
tr_fr_ptr new_TR_;
struct gc_mark_continuation* cont_top0_;
struct gc_mark_continuation* cont_top_;
int discard_trail_entries_;
gc_ma_hash_entry gc_ma_hash_table_[GC_MAVARS_HASH_SIZE];
gc_ma_hash_entry* gc_ma_h_top_;
gc_ma_hash_entry* gc_ma_h_list_;
UInt gc_timestamp_;
ADDR db_vec_;
ADDR db_vec0_;
struct RB_red_blk_node* db_root_;
struct RB_red_blk_node* db_nil_;
sigjmp_buf gc_restore_;
CELL* extra_gc_cells_;
CELL* extra_gc_cells_base_;
CELL* extra_gc_cells_top_;
UInt extra_gc_cells_size_;
struct array_entry* DynamicArrays_;
struct static_array_entry* StaticArrays_;
struct global_entry* GlobalVariables_;
int AllowRestart_;
// Thread Local Area for Fast Storage of Intermediate Compiled Code
struct mem_blk* CMemFirstBlock_;
UInt CMemFirstBlockSz_;
// Variable used by the compiler to store number of permanent vars in a clause
int nperm_;
// Thread Local Area for Labels
Int* LabelFirstArray_;
UInt LabelFirstArraySz_;
// Thread Local Area for SWI-Prolog emulation routines.
// struct PL_local_data* PL_local_data_p
// =Yap_InitThreadIO(wid)
// struct PL_local_data* PL_local_data_p =Yap_InitThreadIO(wid)
#ifdef THREADS
struct thandle ThreadHandle_;
struct thandle ThreadHandle_;
#endif /* THREADS */
#if defined(YAPOR) || defined(TABLING)
struct local_optyap_data optyap_data_;
UInt TabMode_;
struct local_optyap_data optyap_data_;
UInt TabMode_;
#endif /* YAPOR || TABLING */
int InterruptsDisabled_;
struct open_query_struct *execution_;
int InterruptsDisabled_;
struct open_query_struct* execution_;
#if LOW_LEVEL_TRACER
Int total_choicepoints_;
Int total_choicepoints_;
#endif
int consult_level_;
// Variables related to memory allocation
ADDR LocalBase_;
ADDR GlobalBase_;
ADDR TrailBase_;
ADDR TrailTop_;
char *ErrorMessage_;
Term Error_Term_;
/** error handling info, designed to be easy to pass to the foreign world */
struct yap_error_descriptor ActiveError_;
/// pointer to an exception term, from throw
struct DB_TERM *BallTerm_;
jmp_buf IOBotch_;
TokEntry *tokptr_;
TokEntry *toktide_;
VarEntry *VarTable_;
VarEntry *AnonVarTable_;
Term Comments_;
CELL *CommentsTail_;
CELL *CommentsNextChar_;
wchar_t *CommentsBuff_;
size_t CommentsBuffPos_;
size_t CommentsBuffLim_;
sigjmp_buf RestartEnv_;
char FileNameBuf_[YAP_FILENAME_MAX + 1];
char FileNameBuf2_[YAP_FILENAME_MAX + 1];
// Prolog State
UInt BreakLevel_;
Int PrologMode_;
int CritLocks_;
// Prolog execution and state flags
union flagTerm *Flags_;
UInt flagCount_;
// analyst.c
int consult_level_;
// Variables related to memory allocation
ADDR LocalBase_;
ADDR GlobalBase_;
ADDR TrailBase_;
ADDR TrailTop_;
char* ErrorMessage_;
Term Error_Term_;
/** error handling info, designed to be easy to pass to the foreign world */
struct yap_error_descriptor ActiveError_;
/// pointer to an exception term, from throw
struct DB_TERM* BallTerm_;
jmp_buf IOBotch_;
TokEntry* tokptr_;
TokEntry* toktide_;
VarEntry* VarTable_;
VarEntry* AnonVarTable_;
Term Comments_;
CELL* CommentsTail_;
CELL* CommentsNextChar_;
wchar_t* CommentsBuff_;
size_t CommentsBuffPos_;
size_t CommentsBuffLim_;
sigjmp_buf RestartEnv_;
char FileNameBuf_[YAP_FILENAME_MAX+1];
char FileNameBuf2_[YAP_FILENAME_MAX+1];
// Prolog State
UInt BreakLevel_;
Int PrologMode_;
int CritLocks_;
// Prolog execution and state flags
union flagTerm* Flags_;
UInt flagCount_;
//analyst.c
/* used to find out how many instructions of each kind are executed */
#ifdef ANALYST
YAP_ULONG_LONG opcount_[_std_top + 1];
YAP_ULONG_LONG 2opcount [_std_top + 1][_std_top + 1] _;
YAP_ULONG_LONG opcount_[_std_top+1];
YAP_ULONG_LONG 2opcount[_std_top+1][_std_top+1]_;
#endif /* ANALYST */
// dbase.c
struct db_globs *s_dbg_;
// eval.c
yap_error_number matherror_;
Term mathtt_;
char *mathstring_;
yap_error_number CurrentError_;
// grow.c
int heap_overflows_;
Int total_heap_overflow_time_;
int stack_overflows_;
Int total_stack_overflow_time_;
int delay_overflows_;
Int total_delay_overflow_time_;
int trail_overflows_;
Int total_trail_overflow_time_;
int atom_table_overflows_;
Int total_atom_table_overflow_time_;
// load_dyld
//dbase.c
struct db_globs* s_dbg_;
//eval.c
yap_error_number matherror_;
Term mathtt_;
char* mathstring_;
yap_error_number CurrentError_;
//grow.c
int heap_overflows_;
Int total_heap_overflow_time_;
int stack_overflows_;
Int total_stack_overflow_time_;
int delay_overflows_;
Int total_delay_overflow_time_;
int trail_overflows_;
Int total_trail_overflow_time_;
int atom_table_overflows_;
Int total_atom_table_overflow_time_;
//load_dyld
#ifdef LOAD_DYLD
int dl_errno_;
int dl_errno_;
#endif
// tracer.c
//tracer.c
#ifdef LOW_LEVEL_TRACER
int do_trace_primitives_;
int do_trace_primitives_;
#endif
// quick loader
struct export_atom_hash_entry_struct *ExportAtomHashChain_;
UInt ExportAtomHashTableSize_;
UInt ExportAtomHashTableNum_;
struct export_functor_hash_entry_struct *ExportFunctorHashChain_;
UInt ExportFunctorHashTableSize_;
UInt ExportFunctorHashTableNum_;
struct export_pred_entry_hash_entry_struct *ExportPredEntryHashChain_;
UInt ExportPredEntryHashTableSize_;
UInt ExportPredEntryHashTableNum_;
struct export_dbref_hash_entry_struct *ExportDBRefHashChain_;
UInt ExportDBRefHashTableSize_;
UInt ExportDBRefHashTableNum_;
struct import_atom_hash_entry_struct **ImportAtomHashChain_;
UInt ImportAtomHashTableSize_;
UInt ImportAtomHashTableNum_;
struct import_functor_hash_entry_struct **ImportFunctorHashChain_;
UInt ImportFunctorHashTableSize_;
UInt ImportFunctorHashTableNum_;
struct import_opcode_hash_entry_struct **ImportOPCODEHashChain_;
UInt ImportOPCODEHashTableSize_;
struct import_pred_entry_hash_entry_struct **ImportPredEntryHashChain_;
UInt ImportPredEntryHashTableSize_;
UInt ImportPredEntryHashTableNum_;
struct import_dbref_hash_entry_struct **ImportDBRefHashChain_;
UInt ImportDBRefHashTableSize_;
UInt ImportDBRefHashTableNum_;
yamop *ImportFAILCODE_;
// exo indexing
UInt ibnds_[256];
struct index_t *exo_it_;
CELL *exo_base_;
UInt exo_arity_;
UInt exo_arg_;
// atom completion
struct scan_atoms *search_atoms_;
struct pred_entry *SearchPreds_;
/// Slots Status
yhandle_t CurSlot_;
yhandle_t FrozenHandles_;
yhandle_t NSlots_;
CELL *SlotBase_;
// Mutexes
struct swi_mutex *Mutexes_;
Term SourceModule_;
Term Including_;
size_t MAX_SIZE_;
/* last call to walltime. */
uint64_t LastWTime_;
//quick loader
struct export_atom_hash_entry_struct *ExportAtomHashChain_;
UInt ExportAtomHashTableSize_;
UInt ExportAtomHashTableNum_;
struct export_functor_hash_entry_struct *ExportFunctorHashChain_;
UInt ExportFunctorHashTableSize_;
UInt ExportFunctorHashTableNum_;
struct export_pred_entry_hash_entry_struct *ExportPredEntryHashChain_;
UInt ExportPredEntryHashTableSize_;
UInt ExportPredEntryHashTableNum_;
struct export_dbref_hash_entry_struct *ExportDBRefHashChain_;
UInt ExportDBRefHashTableSize_;
UInt ExportDBRefHashTableNum_;
struct import_atom_hash_entry_struct **ImportAtomHashChain_;
UInt ImportAtomHashTableSize_;
UInt ImportAtomHashTableNum_;
struct import_functor_hash_entry_struct **ImportFunctorHashChain_;
UInt ImportFunctorHashTableSize_;
UInt ImportFunctorHashTableNum_;
struct import_opcode_hash_entry_struct **ImportOPCODEHashChain_;
UInt ImportOPCODEHashTableSize_;
struct import_pred_entry_hash_entry_struct **ImportPredEntryHashChain_;
UInt ImportPredEntryHashTableSize_;
UInt ImportPredEntryHashTableNum_;
struct import_dbref_hash_entry_struct **ImportDBRefHashChain_;
UInt ImportDBRefHashTableSize_;
UInt ImportDBRefHashTableNum_;
yamop *ImportFAILCODE_;
// exo indexing
UInt ibnds_[256];
struct index_t* exo_it_;
CELL* exo_base_;
UInt exo_arity_;
UInt exo_arg_;
// atom completion
struct scan_atoms* search_atoms_;
struct pred_entry* SearchPreds_;
/// Slots Status
yhandle_t CurSlot_;
yhandle_t FrozenHandles_;
yhandle_t NSlots_;
CELL* SlotBase_;
// Mutexes
struct swi_mutex* Mutexes_;
Term SourceModule_;
Term Including_;
size_t MAX_SIZE_;
/* last call to walltime. */
uint64_t LastWTime_;
void* shared_;
} w_local;

View File

@ -272,4 +272,5 @@ static void InitWorker(int wid) {
REMOTE_MAX_SIZE(wid) = 1024L;
REMOTE_LastWTime(wid) = 0;
REMOTE_shared(wid) = NULL;
}

View File

@ -270,6 +270,7 @@ static void RestoreWorker(int wid USES_REGS) {
}

View File

@ -43,7 +43,7 @@ set ( DEF_TRAILSPACE 0 )
set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS DEPTH_LIMIT=1;COROUTINING=1;RATIONAL_TREES=1 )
# inform we are compiling YAP
set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS "_YAP_NOT_INSTALLED_=1;HAVE_CONFIG_H=1" )
set_property( DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS "_YAP_NOT_INSTALLED_=1;HAVE_CONFIG_H=1;_GNU_SOURCE" )
# Compilation model
# target_compile_definitions(libYap PUBLIC _XOPEN_SOURCE=700 )

View File

@ -49,7 +49,11 @@ PyObject *term_to_python(term_t t, bool eval) {
else if (strcmp(s, "{}") == 0)
o = PyDict_New();
/* return __main__,s */
else if (PyObject_HasAttrString(py_Main, s)) {
else if ((o = PyRun_String(s, Py_single_input,
PyEval_GetGlobals(), PyEval_GetLocals()))) {
Py_IncRef(o);
return o;
} else if (PyObject_HasAttrString(py_Main, s)) {
o = PyObject_GetAttrString(py_Main, s);
} else {
o = PyUnicode_FromString(s);

View File

@ -183,7 +183,12 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
#endif
} else if (PyTuple_Check(pVal)) {
Py_ssize_t i, sz = PyTuple_Size(pVal);
functor_t f = PL_new_functor(ATOM_t, sz);
functor_t f;
const char *s;
if ((s = (Py_TYPE(pVal)->tp_name)))
f = PL_new_functor(PL_new_atom(s), sz);
else
f = PL_new_functor(ATOM_t, sz);
if (!PL_unify_functor(t, f))
return FALSE;
for (i = 0; i < sz; i++) {

View File

@ -934,7 +934,7 @@ PyObject *compound_to_pytree(term_t t, functor_t fun) {
term_t tleft = PL_new_term_ref();
PyObject *o = py_Main;
while (fun == FUNCTOR_dot2) {
if (!PL_get_arg(1, t, tleft))
if (!PL_get_arg(1, t, tleft))
return FALSE;
o = find_obj(o, tleft);
if (!o)

View File

@ -45,8 +45,11 @@ static foreign_t python_f(term_t tmod, term_t fname, term_t tf) {
return FALSE;
}
pModule = PyImport_Import(pName);
} else if (!(pModule = term_to_python(tmod, true)))
PyErr_Clear();
} else if (!(pModule = term_to_python(tmod, true))) {
PyErr_Clear();
return FALSE;
}
if (!PL_get_nchars(fname, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
return FALSE;
}
@ -263,6 +266,7 @@ static foreign_t python_apply(term_t tin, term_t targs, term_t keywds,
term_t targ = PL_new_term_ref();
pF = term_to_python(tin, true);
PyErr_Clear();
if (pF == NULL) {
return false;
}
@ -567,6 +571,7 @@ static foreign_t python_run_script(term_t cmd, term_t fun) {
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
PyErr_Clear();
Py_DECREF(pName);
if (pModule != NULL) {
@ -617,6 +622,10 @@ static foreign_t python_export(term_t t, term_t pl) {
return rc;
}
static foreign_t p_python_within_python(void) {
return python_in_python;
}
static int python_import(term_t mname, term_t mod) {
PyObject *pName, *pModule;
term_t arg = PL_new_term_ref();
@ -650,6 +659,7 @@ static int python_import(term_t mname, term_t mod) {
return false;
}
pModule = PyImport_Import(pName);
PyErr_Clear();
Py_DECREF(pName);
if (pModule == NULL) {
#if EXTRA_MESSSAGES
@ -689,4 +699,5 @@ install_t install_pypreds(void) {
PL_register_foreign("python_main_module", 1, python_main_module, 0);
PL_register_foreign("python_import", 2, python_import, 0);
PL_register_foreign("python_access", 3, python_access, 0);
PL_register_foreign("python_within_python", 0, p_python_within_python, 0);
}

View File

@ -4,7 +4,7 @@
int assign_python(PyObject *root, term_t t, PyObject *e);
atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
ATOM_comma, ATOM_builtin, ATOM_A, ATOM_V;
ATOM_comma, ATOM_builtin, ATOM_A, ATOM_V, ATOM_self;
functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
@ -29,6 +29,8 @@ int assign_python(PyObject *root, term_t t, PyObject *e);
PyObject *ActiveModules[32];
int active_modules = 0;
bool python_in_python;
static void install_py_constants(void) {
FUNCTOR_dot2 = PL_new_functor(PL_new_atom("."), 2);
// FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2);
@ -42,6 +44,7 @@ static void install_py_constants(void) {
ATOM_false = PL_new_atom("false");
ATOM_dot = PL_new_atom(".");
ATOM_none = PL_new_atom("none");
ATOM_self = PL_new_atom("self");
ATOM_t = PL_new_atom("t");
FUNCTOR_abs1 = PL_new_functor(PL_new_atom("abs"), 1);
FUNCTOR_all1 = PL_new_functor(PL_new_atom("all"), 1);
@ -85,24 +88,28 @@ foreign_t end_python(void) {
X_API bool init_python(void) {
char **argv;
python_in_python = false;
if (YAP_DelayInit(init_python, "python")) {
// wait for YAP_Init
return false;
}
term_t t = PL_new_term_ref();
YAP_Argv(&argv);
if (argv) {
if (!Py_IsInitialized()) {
python_in_python = true;
YAP_Argv(&argv);
if (argv) {
#if PY_MAJOR_VERSION < 3
Py_SetProgramName(argv[0]);
Py_SetProgramName(argv[0]);
#else
wchar_t *buf = Py_DecodeLocale(argv[0], NULL);
wchar_t *buf = Py_DecodeLocale(argv[0], NULL);
Py_SetProgramName(buf);
#endif
}
Py_Initialize();
}
Py_Initialize();
install_py_constants();
PL_reset_term_refs(t);
install_pypreds();
install_pl2pl();
return true;
return !python_in_python;
}

View File

@ -21,7 +21,7 @@
typedef YAP_Arity arity_t;
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
ATOM_comma, ATOM_builtin, ATOM_V, ATOM_A;
ATOM_comma, ATOM_builtin, ATOM_V, ATOM_A, ATOM_self;
extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
@ -37,6 +37,8 @@ extern PyObject *py_Builtin;
extern PyObject *py_Yapex;
extern PyObject *py_F2P;
extern bool python_in_python;
static inline Py_ssize_t get_p_int(PyObject *o, Py_ssize_t def) {
if (o == NULL)
return def;

View File

@ -14,11 +14,40 @@ class YAPEngine;
#ifdef SWIGPYTHON
%typemap(out) YAPTerm {
if ($1.handle() == 0) {
return NULL;
}
%typemap(typecheck) YAPTerm* {
$1 = PySequence_Check($input);
}
// Map a Python sequence into any sized C double array
%typemap(in) YAPTerm* {
int i;
if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
$1 = nullptr;
} else {
int sz = PyObject_Length($input);
std::vector<YAPTerm> v(sz);
for (i =0; i < sz; i++) {
PyObject *o = PySequence_GetItem($input,i);
v[i] = YAPTerm(pythonToYAP(o));
Py_DECREF(o);
}
$1 = &v[0];
}
}
%typemap(typecheck) YAPTerm {
$1 = true;
}
%typemap(in) YAPTerm { $1 = YAPTerm(pythonToYAP($input)); }
%typemap(out) YAPTerm {$result = term_to_python($1.handle(), false);}
%extend(out) YAPTerm{YAPTerm & __getitem__(size_t i){Term t0 = $self->term();
if (IsApplTerm(t0)) {
@ -30,120 +59,11 @@ if (IsApplTerm(t0)) {
return *new YAPTerm(HeadOfTerm(t0));
else if (i == 1)
return *new YAPTerm(TailOfTerm(t0));
}
return *new YAPTerm();
}
}
%typemap(in) YAPIntegerTerm {
#if PY_MAJOR_VERSION < 3
$1 = YAPIntegerTerm(PyInt_AsLong($input));
#else
$1 = YAPIntegerTerm(PyLong_AsLong($input));
#endif
}
%typemap(out) YAPIntegerTerm {
Term t = $input.term();
Int j = IntegerOfTerm(t);
#if PY_MAJOR_VERSION < 3
return PyInt_FromLong(j);
#else
return PyLong_FromLong(j);
#endif
}
%typemap(in) YAPFloatTerm {
$1 = YAPFloatTerm( PyFloat_AsDouble($input) );
}
%typemap(out) YAPFloatTerm {
Term t = $1nput.term();
Int double j = FloatOfTerm(t);
$1 = PyFloat_FromDouble(j);
}
// translate well-known names and existing
// Python symbols
// Everthing else let wrapped.
// as a term
%typemap(out) YAPAtomTerm {
const char *s = RepAtom(AtomOfTerm($1nput.term()))->StrOfAE;
PyObject *p;
if ((p = AtomToPy(s))) {
$1 = p;
} else {
$1 = Py_None;
}
}
// translate lists as Python Lists
// Python symbols
// Everthing else let wrapped.
// as a termpc
%typemap(in) YAPListTerm {
PyObject *p = $input;
Int len = PyTuple_Size(p);
if (len == 0) {
$1 = YAPListTerm(TermNil);
} else {
t = AbsPair(HR);
for (Int i = 0; i < len; i++) {
HR += 2;
HR[-2] = pythonToYAP(PyTuple_GetItem(p, i));
HR[-1] = AbsPair(HR+2);
}
HR[-1] = TermNil;
$1 = YAPListTerm(t);
}
}
}
%typemap(typecheck) YAPListTerm {
PyObject *it = $input;
$1 = PyTuple_CheckExact(it);
}
%typemap(in) YAPApplTerm {
char *o = Py_TYPE(p)->tp_name;
Int len = PyTuple_Size(p);
if (len == 0) {
$1 = nullptr;
} else {
Term t = MkNewApplTerm(Yap_MkFunctor(Yap_LookupAtom(o),len),len);
for (Int i = 0; i < len; i++) {
o[i] = pythonToYAP(PyTuple_GetItem(p, i));
}
$1 = YAPApplTerm(t);
}
}
%typemap(typecheck) YAPApplTerm {
PyObject *p = $input;
$1 = (PyTuple_Check(p) && !PyTuple_CheckExact(p));
}
// translate lists as Python Lists
// Python symbols
// Everthing else let wrapped.
// as a term
%typemap(out) YAPListTerm {
Term l = $1.term(), *end;
PyObject *list;
Int len = Yap_SkipList(&l, &end);
$result = list = PyList_New(len);
for (Int i = 0; i < len; i++) {
Term a = HeadOfTerm(l);
YAPTerm *argp1 = new YAPTerm(a);
PyObject *obj0 =
SWIG_NewPointerObj(SWIG_as_voidptr(argp1), SWIGTYPE_p_YAPTerm, 0 | 0);
l = TailOfTerm(l);
PyList_SetItem(list, i, obj0);
}
return list;
}
// Language independent exception handler

View File

@ -322,6 +322,9 @@ Succeeds once.
*/
true :- true.
live :-
'$live'.
'$live' :-
'$init_system',
'$do_live'.

View File

@ -251,7 +251,7 @@ current_op(X,Y,Z) :-
prolog :-
'$live'.
live.
%%% current ....