diff --git a/C/text.c b/C/text.c index 641b03b03..8cfaa7bb5 100644 --- a/C/text.c +++ b/C/text.c @@ -738,9 +738,9 @@ static Term write_number(unsigned char *s, seq_tv_t *out, yap_error_descriptor_t new_error; int i = push_text_stack(); Yap_pushErrorContext(&new_error); - t = Yap_StringToNumberTerm((char *)s, &out->enc, error_on); + t = Yap_StringToNumberTerm((char *)s, &out->enc,true); pop_text_stack(i); - Yap_popErrorContext(true); + Yap_popErrorContext(error_on); return t; } diff --git a/C/yap-args.c b/C/yap-args.c index 3e2e65a42..f7deb5756 100755 --- a/C/yap-args.c +++ b/C/yap-args.c @@ -145,10 +145,9 @@ static void init_globals(YAP_init_args *yap_init) { } } - const char *Yap_BINDIR, *Yap_ROOTDIR, *Yap_SHAREDIR, *Yap_LIBDIR, *Yap_DLLDIR, - *Yap_PLDIR, *Yap_BOOTSTRAP, *Yap_COMMONSDIR, - *Yap_STARTUP, *Yap_INPUT_STARTUP, *Yap_OUTPUT_STARTUP, *Yap_BOOTFILE, *Yap_INCLUDEDIR; + *Yap_PLDIR, *Yap_BOOTSTRAP, *Yap_COMMONSDIR, *Yap_STARTUP, + *Yap_INPUT_STARTUP, *Yap_OUTPUT_STARTUP, *Yap_BOOTFILE, *Yap_INCLUDEDIR; /* do initial boot by consulting the file boot.yap */ static void consult(const char *b_file USES_REGS) { @@ -168,7 +167,7 @@ static void consult(const char *b_file USES_REGS) { c_stream = YAP_InitConsult(YAP_BOOT_MODE, b_file, full, &oactive); if (c_stream < 0) { fprintf(stderr, "[ FATAL ERROR: could not open file %s ]\n", b_file); - pop_text_stack(lvl); + pop_text_stack(lvl); exit(1); } if (!Yap_AddAlias(AtomLoopStream, c_stream)) { @@ -180,7 +179,8 @@ static void consult(const char *b_file USES_REGS) { CACHE_REGS YAP_Reset(YAP_FULL_RESET, false); Yap_StartSlots(); - __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "read %s <%d>", b_file, GLOBAL_Stream[c_stream].linecount); + __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "read %s <%d>", b_file, + GLOBAL_Stream[c_stream].linecount); Term vs = YAP_MkVarTerm(), pos = MkVarTerm(); t = YAP_ReadClauseFromStream(c_stream, vs, pos); // Yap_GetNèwSlot(t); @@ -213,42 +213,30 @@ static void consult(const char *b_file USES_REGS) { /// /// - static const char * sel(bool dir, ...) { - CACHE_REGS - va_list args; - va_start(args ,dir); - while (true) { - bool init = va_arg(args, int); - const char *fmt = va_arg(args, char *); - if (init) { - va_end(args); - return fmt; - - } - } +static const char *sel(bool dir, bool ok1, const char *s1, bool ok2, const char *s2, + ...) { + if (ok1 && s1) + return s1; + if (ok2) + return s2; return NULL; } -static const char * join(const char *s, ...) { +static const char *join(const char *s0, const char *s1) { CACHE_REGS - va_list args; - va_start(args , s); + + if (!s0 || s0[0] == '\0') + return s1; + if (!s1 || s1[0] == '\0') + return s0; // int lvl = push_text_stack(); - char *buf = malloc(FILENAME_MAX+1); - if (s && s[0]) - strcpy(buf, s); - while (true) { - const char *fmt = va_arg(args, char *); - if (fmt == NULL) { - va_end(args); - // return pop_output_text_stack(lvl,buf); - return buf; - } - strcat(buf, fmt); - } + char *buf = malloc(FILENAME_MAX + 1); + strcpy(buf, s0); + strcat(buf, s1); + return buf; } - static void Yap_set_locations(YAP_init_args *iap) { +static void Yap_set_locations(YAP_init_args *iap) { /// ROOT_DIR is the home of the YAP system. It can be: /// -- provided by the user; @@ -257,126 +245,104 @@ static const char * join(const char *s, ...) { /// It is: // --_not useful in Android, WIN32; /// -- DESTDIR/ in Anaconda - /// -- /usr/local in most Unix style systems - Yap_ROOTDIR = sel(true, iap->ROOTDIR != NULL, iap->ROOTDIR, - true, + /// -- /usr/locall in most Unix style systems + Yap_ROOTDIR = sel(true, iap->ROOTDIR != NULL, iap->ROOTDIR, true, #if __ANDROID__ - NULL, + NULL, #else - join(getenv("DESTDIR"),YAP_ROOTDIR, NULL), + join(getenv("DESTDIR"), YAP_ROOTDIR), #endif - false - ); + false); /// BINDIR: where the OS stores header files, namely libYap... - Yap_BINDIR = sel(true, - iap->BINDIR != NULL, iap->BINDIR, - true, + Yap_BINDIR = sel(true, iap->BINDIR != NULL, iap->BINDIR, true, #if __ANDROID__ - NULL, + NULL, #else - join(getenv("DESTDIR"),YAP_BINDIR, NULL), + join(getenv("DESTDIR"), YAP_BINDIR), #endif - false ); + false); /// LIBDIR: where the OS stores dynamic libraries, namely libYap... - Yap_LIBDIR = sel(true, - iap->LIBDIR != NULL, iap->LIBDIR, - true, + Yap_LIBDIR = sel(true, iap->LIBDIR != NULL, iap->LIBDIR, true, #if __ANDROID__ - NULL, + NULL, #else - join(getenv("DESTDIR"),YAP_LIBDIR,NULL), + join(getenv("DESTDIR"), YAP_LIBDIR), #endif - false ); + false); /// DLLDIR: where libraries can find expicitely loaded DLLs - Yap_DLLDIR = sel(true, - iap->DLLDIR != NULL, iap->DLLDIR, - true, + Yap_DLLDIR = sel(true, iap->DLLDIR != NULL, iap->DLLDIR, true, #if __ANDROID__ - NULL + NULL #else - join(getenv("DESTDIR"),YAP_DLLDIR, NULL), + join(getenv("DESTDIR"), YAP_DLLDIR), #endif - false ); + false); /// INCLUDEDIR: where the OS stores header files, namely libYap... - Yap_INCLUDEDIR = sel(true, - iap->INCLUDEDIR != NULL, iap->INCLUDEDIR, - true, + Yap_INCLUDEDIR = sel(true, iap->INCLUDEDIR != NULL, iap->INCLUDEDIR, true, #if __ANDROID__ - NULL, + NULL, #else - join(getenv("DESTDIR"),YAP_INCLUDEDIR, NULL), + join(getenv("DESTDIR"), YAP_INCLUDEDIR), #endif - false ); + false); /// SHAREDIR: where OS & ARCH independent files live - Yap_SHAREDIR = sel(true, - iap->SHAREDIR != NULL, iap->SHAREDIR, - true, + Yap_SHAREDIR = sel(true, iap->SHAREDIR != NULL, iap->SHAREDIR, true, #if __ANDROID__ - "/assets", + "/assets", #else - join(getenv("DESTDIR"),YAP_SHAREDIR, NULL), + join(getenv("DESTDIR"), YAP_SHAREDIR), #endif - false ); + false); /// PLDIR: where we can find Prolog files - Yap_PLDIR = sel(true, - iap->PLDIR != NULL, iap->PLDIR, - true, + Yap_PLDIR = sel(true, iap->PLDIR != NULL, iap->PLDIR, true, #if __ANDROID__ - "/assets/Yap", + "/assets/Yap", #else - join(getenv("DESTDIR"),YAP_PLDIR, NULL), + join(getenv("DESTDIR"), YAP_PLDIR), #endif - false ); + false); /// ``COMMONSDIR: Prolog Commons - Yap_COMMONSDIR = sel(true, - iap->COMMONSDIR != NULL, iap->COMMONSDIR, - true, + Yap_COMMONSDIR = sel(true, iap->COMMONSDIR != NULL, iap->COMMONSDIR, true, #if __ANDROID__ - "/assets/PrologCommons", + "/assets/PrologCommons", #else - join(getenv("DESTDIR"),YAP_SHAREDIR "/PrologCommons", NULL), + join(getenv("DESTDIR"), YAP_SHAREDIR "/PrologCommons"), #endif - false ); - /// BOOTPLDIR: where we can find Prolog bootstrap files - Yap_BOOTSTRAP = sel(true, - iap->BOOTSTRAP != NULL, iap->BOOTSTRAP, - true, + false); + /// BOOTPLDIR: where we can find Prolog bootstrap files + Yap_BOOTSTRAP = sel(true, iap->BOOTSTRAP != NULL, iap->BOOTSTRAP, true, #if __ANDROID__ - "/assets/Yap/pl", + "/assets/Yap/pl", #else - join(getenv("DESTDIR"),YAP_BOOTSTRAP, NULL), + join(getenv("DESTDIR"), YAP_BOOTSTRAP), #endif - false ); - /// BOOTFILE: where we can find the core Prolog bootstrap file - Yap_BOOTFILE = sel(false, - iap->BOOTFILE != NULL, iap->BOOTFILE, - true, + false); + /// BOOTFILE: where we can find the core Prolog bootstrap file + Yap_BOOTFILE = sel(false, iap->BOOTFILE != NULL, iap->BOOTFILE, true, #if __ANDROID__ - "/assets/Yap/pl/boot.yap", + "/assets/Yap/pl/boot.yap", #else - join(getenv("DESTDIR"),YAP_BOOTFILE, NULL), + join(getenv("DESTDIR"), YAP_BOOTFILE), #endif - false ); - /// STARTUP: where we can find the core Prolog bootstrap file - Yap_OUTPUT_STARTUP = sel(false, - iap->OUTPUT_STARTUP != NULL, iap->OUTPUT_STARTUP, - true, + false); + /// STARTUP: where we can find the core Prolog bootstrap file + Yap_OUTPUT_STARTUP = + sel(false, iap->OUTPUT_STARTUP != NULL, iap->OUTPUT_STARTUP, true, #if __ANDROID__ - NULL, + NULL, #else - join(getenv("DESTDIR"),YAP_OUTPUT_STARTUP,NULL), + join(getenv("DESTDIR"), YAP_OUTPUT_STARTUP), #endif - false ); - Yap_INPUT_STARTUP = sel(false, - iap->INPUT_STARTUP != NULL, iap->INPUT_STARTUP, - true, + false); + Yap_INPUT_STARTUP = + sel(false, iap->INPUT_STARTUP != NULL, iap->INPUT_STARTUP, true, #if __ANDROID__ - NULL, + NULL, #else - join(getenv("DESTDIR"),YAP_INPUT_STARTUP,NULL), + join(getenv("DESTDIR"), YAP_INPUT_STARTUP), #endif - false ); - if (Yap_ROOTDIR) + false); + if (Yap_ROOTDIR) setAtomicGlobalPrologFlag(HOME_FLAG, MkAtomTerm(Yap_LookupAtom(Yap_ROOTDIR))); if (Yap_PLDIR) @@ -975,7 +941,7 @@ static void init_hw(YAP_init_args *yap_init, struct ssz_t *spt) { #if __ANDROID__ // if (yap_init->assetManager) - //Yap_InitAssetManager(); + // Yap_InitAssetManager(); #endif @@ -1007,7 +973,7 @@ static YAP_file_type_t end_init(YAP_init_args *yap_init, YAP_file_type_t rc) { return rc; } - static void start_modules(void) { +static void start_modules(void) { Term cm = CurrentModule; size_t i; for (i = 0; i < n_mdelays; i++) { @@ -1017,7 +983,6 @@ static YAP_file_type_t end_init(YAP_init_args *yap_init, YAP_file_type_t rc) { CurrentModule = cm; } - /* this routine is supposed to be called from an external program that wants to control Yap */ @@ -1027,8 +992,8 @@ X_API YAP_file_type_t YAP_Init(YAP_init_args *yap_init) { struct ssz_t minfo; if (YAP_initialized) - /* ignore repeated calls to YAP_Init */ - return YAP_FOUND_BOOT_ERROR; + /* ignore repeated calls to YAP_Init */ + return YAP_FOUND_BOOT_ERROR; if (!LOCAL_TextBuffer) LOCAL_TextBuffer = Yap_InitTextAllocator(); @@ -1058,8 +1023,10 @@ X_API YAP_file_type_t YAP_Init(YAP_init_args *yap_init) { Yap_ExecutionMode = yap_init->ExecutionMode; Yap_set_locations(yap_init); - if (!do_bootstrap && Yap_INPUT_STARTUP && yap_init->boot_file_type != YAP_BOOT_PL && - Yap_SavedInfo(Yap_INPUT_STARTUP, &minfo.Trail, &minfo.Stack, &minfo.Heap) && + if (!do_bootstrap && Yap_INPUT_STARTUP && + yap_init->boot_file_type != YAP_BOOT_PL && + Yap_SavedInfo(Yap_INPUT_STARTUP, &minfo.Trail, &minfo.Stack, + &minfo.Heap) && Yap_Restore(Yap_INPUT_STARTUP)) { setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, true); CurrentModule = LOCAL_SourceModule = USER_MODULE; diff --git a/CMakeLists.txt b/CMakeLists.txt index 30f0d0d97..4c0410eb0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -294,7 +294,7 @@ set(datadir ${CMAKE_INSTALL_PREFIX}/share) #DATADIR}) set(mandir ${CMAKE_INSTALL_PREFIX}/share/man) #MANDIR}) set(docdir ${CMAKE_INSTALL_PREFIX}/share/docs) #MANDIR}) -set(libpl ${datarootdir}/Yap) +set(libpl ${datadir}/Yap) set(dlls ${libdir}/Yap) diff --git a/CXX/yapi.cpp b/CXX/yapi.cpp index 6db3510d5..c30e903e5 100644 --- a/CXX/yapi.cpp +++ b/CXX/yapi.cpp @@ -458,14 +458,14 @@ bool YAPEngine::mgoal(Term t, Term tmod) { CACHE_REGS BACKUP_MACHINE_REGS(); Term *ts = nullptr; - Yap_DebugPlWriteln(tmod); if (IsStringTerm(tmod)) tmod = MkAtomTerm(Yap_LookupAtom(StringOfTerm(tmod))); PredEntry *ap = (new YAPPredicate(t, tmod, ts, "C++"))->ap; - Yap_DebugPlWriteln(t); if (ap == nullptr || ap->OpcodeOfPred == UNDEF_OPCODE) { ap = rewriteUndefEngineQuery(ap, t, tmod); } + if (IsApplTerm(t)) ts = RepAppl(t)+1; + else if (IsPairTerm(t)) ts = RepPair(t); /* legal ap */ arity_t arity = ap->ArityOfPE; @@ -739,12 +739,12 @@ PredEntry *YAPQuery::rewriteUndefQuery() { return ap = PredCall; } -PredEntry *YAPEngine::rewriteUndefEngineQuery(PredEntry *a, Term tgoal, +PredEntry *YAPEngine::rewriteUndefEngineQuery(PredEntry *a, Term &tgoal, Term mod) { Term ts[2]; ts[0] = mod; ts[1] = tgoal; - ARG1 = Yap_MkApplTerm(FunctorModule, 2, ts); + ARG1 = tgoal = Yap_MkApplTerm(FunctorModule, 2, ts); //goal = YAPTerm(Yap_MkApplTerm(FunctorMetaCall, 1, &ARG1)); return PredCall; diff --git a/CXX/yapq.hh b/CXX/yapq.hh index 9afd2561d..cf5f31101 100644 --- a/CXX/yapq.hh +++ b/CXX/yapq.hh @@ -217,12 +217,14 @@ public: inline bool getMaxTrailSize() { return MaxTrailSize; }; - inline void setLibDir(const char *fl) { + inline void setPLDIR(const char *fl) { LIBDIR = (const char *)malloc(strlen(fl) + 1); strcpy((char *)LIBDIR, fl); }; - inline const char *setINPUT_STARTUP(const char *fl) { + inline const char *getPLDIR() { return PLDIR; }; + + inline void setINPUT_STARTUP(const char *fl) { INPUT_STARTUP = (const char *)malloc(strlen(fl) + 1); strcpy((char *)INPUT_STARTUP, fl); }; @@ -290,7 +292,7 @@ private: YAPError yerror; void doInit(YAP_file_type_t BootMode, YAPEngineArgs *cargs); YAP_dogoalinfo q; - PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term t, Term tmod); + PredEntry *rewriteUndefEngineQuery(PredEntry *ap, Term &t, Term tmod); public: /// construct a new engine; may use a variable number of arguments diff --git a/config.h.cmake b/config.h.cmake index b7236931b..2bf5293f7 100644 --- a/config.h.cmake +++ b/config.h.cmake @@ -2002,6 +2002,15 @@ significant byte first (like Motorola and SPARC, unlike Intel). */ #define YAP_DLLDIR "${YAP_LIBDIR}/Yap" #endif +/* run-time boot */ +#ifndef YAP_INPUT_STARTUP +#define YAP_INPUT_STARTUP "${YAP_DLLDIR}/${YAP_STARTUP}" +#endif + +/* init-time boot */ +#ifndef YAP_OUTPUT_STARTUP +#define YAP_OUTPUT_STARTUP "${CMAKE_BINARY_DIR}/${YAP_STARTUP}" +#endif /* name of YAP JIT library */ #ifndef YAP_YAPJITLIB @@ -2009,17 +2018,17 @@ significant byte first (like Motorola and SPARC, unlike Intel). */ #endif #ifndef YAP_SHAREDIR -#define YAP_SHAREDIR "${YAP_ROOTDIR}/share" +#define YAP_SHAREDIR "${YAP_DATADIR}" #endif /* name of YAP PL library */ #ifndef YAP_PLDIR -#define YAP_PLDIR "${YAP_SHAREDIR}/Yap" +#define YAP_PLDIR "${YAP_PLDIR}" #endif /* name of Commons library */ #ifndef YAP_COMMONSDIR -#define YAP COMMONSDIR "${YAP_SHAREDIR}/PrologCommmons" +#define YAP COMMONSDIR "${YAP_DATADIR}/PrologCommmons" #endif @@ -2035,16 +2044,6 @@ significant byte first (like Motorola and SPARC, unlike Intel). */ -/* run-time boot */ -#ifndef YAP_INPUT_STARTUP -#define YAP_INPUT_STARTUP "${YAP_DLLDIR}/${YAP_STARTUP}" -#endif - -/* init-time boot */ -#ifndef YAP_OUTPUT_STARTUP -#define YAP_OUTPUT_STARTUP "${CMAKE_BINARY_DIR}/${YAP_STARTUP}" -#endif - /* HP-UX old socket stuff */ #ifndef _XOPEN_SOURCE #cmakedefine _XOPEN_SOURCE "${_XOPEN_SOURCE}" diff --git a/include/YapError.h b/include/YapError.h index ada04ff9b..579a77c56 100644 --- a/include/YapError.h +++ b/include/YapError.h @@ -1,16 +1,16 @@ /************************************************************************* - * * - * YAP Prolog %W% %G% * - * Yap Prolog was developed at NCCUP - Universidade do Porto * - * * - * Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 * - * * - ************************************************************************** - * * - * File: YapError.h * mods: - ** comments: error header file for YAP * - * version: $Id: Yap.h,v 1.38 2008-06-18 10:02:27 vsc Exp $ * - *************************************************************************/ + * * + * YAP Prolog %W% %G% * + * Yap Prolog was developed at NCCUP - Universidade do Porto * + * * + * Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 * + * * + ************************************************************************** + * * + * File: YapError.h * mods: + ** comments: error header file for YAP * + * version: $Id: Yap.h,v 1.38 2008-06-18 10:02:27 vsc Exp $ * + *************************************************************************/ #ifndef YAP_ERROR_H #define YAP_ERROR_H 1 @@ -37,13 +37,16 @@ #define MAX_ERROR_MSG_SIZE 1024 -extern void Yap_InitError__(const char *file, const char *function, int lineno, yap_error_number e, YAP_Term g, ...); + extern void + Yap_InitError__(const char *file, const char *function, int lineno, + yap_error_number e, YAP_Term g, ...); -extern struct yami *Yap_Error__(const char *file, const char *function, int lineno, - yap_error_number err, YAP_Term wheret, ...); +extern struct yami *Yap_Error__(const char *file, const char *function, + int lineno, yap_error_number err, + YAP_Term wheret, ...); extern void Yap_ThrowError__(const char *file, const char *function, int lineno, - yap_error_number err, YAP_Term wheret, ...) + yap_error_number err, YAP_Term wheret, ...) #ifndef MSC_VER __attribute__((noreturn)) #endif @@ -52,7 +55,7 @@ extern void Yap_ThrowError__(const char *file, const char *function, int lineno, #define Yap_NilError(id, ...) \ Yap_Error__(__FILE__, __FUNCTION__, __LINE__, id, TermNil, __VA_ARGS__) -#define Yap_InitError(id, ...) \ +#define Yap_InitError(id, ...) \ Yap_InitError__(__FILE__, __FUNCTION__, __LINE__, id, TermNil, __VA_ARGS__) #define Yap_Error(id, inp, ...) \ diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt index f39857656..50c709b43 100644 --- a/library/CMakeLists.txt +++ b/library/CMakeLists.txt @@ -55,7 +55,6 @@ set (LIBRARY_PL wgraphs.yap wundgraphs.yap lam_mpi.yap - ypp.yap ytest.yap c_alarms.yap flags.yap diff --git a/os/alias.c b/os/alias.c index 96c8dd97d..2a92e652f 100644 --- a/os/alias.c +++ b/os/alias.c @@ -225,6 +225,12 @@ Yap_SetAlias (Atom arg, int sno) // replace alias if (aliasp->name == arg) { aliasp->alias_stream = sno; + if (arg == AtomUserIn) + LOCAL_c_input_stream = sno; + if (arg == AtomUserOut) + LOCAL_c_output_stream = sno; + if (arg == AtomUserErr) + LOCAL_c_error_stream = sno; return; } aliasp++; @@ -310,6 +316,18 @@ ExistsAliasForStream (int sno, Atom al) while (aliasp < aliasp_max) { if (aliasp->alias_stream == sno && aliasp->name == al) { + if (al == AtomUserIn) { + LOCAL_c_input_stream = StdInStream; + aliasp->alias_stream = StdInStream; + } + if (al == AtomUserOut) { + LOCAL_c_output_stream = StdOutStream; + aliasp->alias_stream = StdOutStream; + } + if (al == AtomUserErr) { + LOCAL_c_error_stream = StdErrStream; + aliasp->alias_stream = StdErrStream; + } return true; } aliasp++; diff --git a/os/encoding.h b/os/encoding.h index a4141bad5..bac5bbf39 100644 --- a/os/encoding.h +++ b/os/encoding.h @@ -26,7 +26,7 @@ #endif -typedef enum { +typedef enum YAP_encoding { ENC_OCTET = 0, /// binary files ENC_ISO_LATIN1 = 1, /// US+West Europe ENC_ISO_ASCII = 2, /// US only diff --git a/os/iopreds.c b/os/iopreds.c index 7522b1aa3..3035c5f33 100644 --- a/os/iopreds.c +++ b/os/iopreds.c @@ -315,57 +315,8 @@ static void unix_upd_stream_info(StreamDesc *s) { s->status |= Seekable_Stream_f; } -void Yap_DefaultStreamOps(StreamDesc *st) { - CACHE_REGS - st->stream_wputc = put_wchar; - if (st->encoding == ENC_ISO_UTF8) - st->stream_wgetc = get_wchar_UTF8; - else - st->stream_wgetc = get_wchar; - if (st->vfs) { - st->stream_putc = st->vfs->put_char; - st->stream_wgetc = st->vfs->get_char; - } else { - st->stream_putc = FilePutc; - st->stream_getc = PlGetc; - } - if (st->status & Pipe_Stream_f) { - Yap_PipeOps(st); - } else if (st->status & InMemory_Stream_f) { - Yap_MemOps(st); - } else if (st->status & Tty_Stream_f) { - Yap_ConsoleOps(st); - } else { - unix_upd_stream_info(st); - } - if (st->status & (Promptable_Stream_f)) { - Yap_ConsoleOps(st); - } -#ifndef _WIN32 - else if (st->file != NULL && 0 && !(st->status & InMemory_Stream_f)) { - st->stream_wgetc = get_wchar_from_file; - } -#endif - if (st->buf.on) { - st->stream_getc = Yap_popChar; - st->stream_wgetc = Yap_popChar; - } -#if USE_READLINE - if (st->status & Readline_Stream_f) { - st->stream_peek = Yap_ReadlinePeekChar; - st->stream_wpeek = Yap_ReadlinePeekChar; - } - /* else { - st->stream_peek = Yap_peekWithGetc; - st->stream_wpeek = Yap_peekWideWithGetwc; - } - } else if (st->status & Seekable_Stream_f) { - st->stream_peek = Yap_peekWithSeek; - st->stream_wpeek = Yap_peekWideWithSeek; - } */ - else -#endif - { +static void default_peek(StreamDesc *st) { + { st->stream_peek = Yap_peekChar; st->stream_wpeek = Yap_peekWide; } @@ -381,6 +332,64 @@ void Yap_DefaultStreamOps(StreamDesc *st) { st->stream_wgetc_for_read = st->stream_wgetc; } +void Yap_DefaultStreamOps(StreamDesc *st) { + CACHE_REGS + + st->stream_wputc = put_wchar; + st->stream_wgetc = get_wchar; + if (st->vfs) { + st->stream_putc = st->vfs->put_char; + st->stream_wputc = st->vfs->put_char; + st->stream_getc = st->vfs->get_char; + st->stream_wgetc = st->vfs->get_char; + default_peek(st); + return; + } else { + if (st->encoding == ENC_ISO_UTF8) + st->stream_wgetc = get_wchar_UTF8; + st->stream_putc = FilePutc; + st->stream_getc = PlGetc; + if (st->status & Pipe_Stream_f) { + Yap_PipeOps(st); + } else if (st->status & InMemory_Stream_f) { + Yap_MemOps(st); + } else if (st->status & Tty_Stream_f) { + Yap_ConsoleOps(st); + } else { + unix_upd_stream_info(st); + } + if (st->status & (Promptable_Stream_f)) { + Yap_ConsoleOps(st); + } +#ifndef _WIN32 + else if (st->file != NULL && 0 && !(st->status & InMemory_Stream_f)) { + st->stream_wgetc = get_wchar_from_file; + } +#endif + if (st->buf.on) { + st->stream_getc = Yap_popChar; + st->stream_wgetc = Yap_popChar; + } + } +#if USE_READLINE + if (st->status & Readline_Stream_f) { + st->stream_peek = Yap_ReadlinePeekChar; + st->stream_wpeek = Yap_ReadlinePeekChar; + } + + /* else { + st->stream_peek = Yap_peekWithGetc; + st->stream_wpeek = Yap_peekWideWithGetwc; + } + } else if (st->status & Seekable_Stream_f) { + st->stream_peek = Yap_peekWithSeek; + st->stream_wpeek = Yap_peekWideWithSeek; + } */ + else +#endif + default_peek(st); +} + static void InitFileIO(StreamDesc *s) { CACHE_REGS Yap_DefaultStreamOps(s); @@ -1279,16 +1288,16 @@ do_open(Term file_name, Term t2, : false) || trueGlobalPrologFlag(OPEN_EXPANDS_FILENAME_FLAG); // expand file name? - int lvl = push_text_stack(); + int lvl = push_text_stack(); const char *fname = Yap_AbsoluteFile(fname0, ok); if (!fname) { - pop_text_stack(lvl); + pop_text_stack(lvl); PlIOError(EXISTENCE_ERROR_SOURCE_SINK, ARG1, NULL); } // Skip scripts that start with !#/.. or similar - pop_text_stack(lvl); + pop_text_stack(lvl); bool script = (args[OPEN_SCRIPT].used ? args[OPEN_SCRIPT].tvalue == TermTrue : false); // binary type @@ -1309,8 +1318,8 @@ do_open(Term file_name, Term t2, #endif /* note that this matters for UNICODE style conversions */ } else { - pop_text_stack(lvl); - Yap_Error(DOMAIN_ERROR_STREAM, tlist, + pop_text_stack(lvl); + Yap_Error(DOMAIN_ERROR_STREAM, tlist, "type is ~a, must be one of binary or text", t); } } @@ -1336,13 +1345,14 @@ do_open(Term file_name, Term t2, } else if (open_mode == AtomAppend) { strncpy(io_mode, "a", 8); } else { - pop_text_stack(lvl); + pop_text_stack(lvl); return false; } if ((sno = Yap_OpenStream(fname, io_mode, file_name)) < 0) { - pop_text_stack(lvl); + pop_text_stack(lvl); return false; } + st = &GLOBAL_Stream[sno]; st->user_name = file_name; // user requested encoding? @@ -1374,11 +1384,11 @@ do_open(Term file_name, Term t2, else st->encoding = encoding; if (script) { - open_header(sno, open_mode); + open_header(sno, open_mode); } - pop_text_stack(lvl); + pop_text_stack(lvl); - free(args); + free(args); UNLOCK(st->streamlock); { Term t = Yap_MkStream(sno); @@ -1501,16 +1511,17 @@ static Int p_file_expansion(USES_REGS1) { /* '$file_expansion'(+File,-Name) */ PlIOError(INSTANTIATION_ERROR, file_name, "absolute_file_name/3"); return (FALSE); } - int lvl = push_text_stack(); - const char *tmp; - if ((tmp=Yap_AbsoluteFile(RepAtom(AtomOfTerm(file_name))->StrOfAE, false)) == NULL) { - pop_text_stack(lvl); - return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, - "absolute_file_name/3")); + int lvl = push_text_stack(); + const char *tmp; + if ((tmp = Yap_AbsoluteFile(RepAtom(AtomOfTerm(file_name))->StrOfAE, + false)) == NULL) { + pop_text_stack(lvl); + return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, + "absolute_file_name/3")); } bool rc = (Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(tmp)))); - pop_text_stack(lvl); - return rc; + pop_text_stack(lvl); + return rc; } static Int p_open_null_stream(USES_REGS1) { @@ -1565,7 +1576,7 @@ int Yap_OpenStream(const char *fname, const char *io_mode, Term user_name) { // read, write, append st->file = NULL; st->status = 0; - //fname = Yap_VF(fname); + // fname = Yap_VF(fname); if ((vfsp = vfs_owner(fname)) != NULL) { if (!vfsp->open(vfsp, sno, fname, "r")) { UNLOCK(st->streamlock); @@ -1573,7 +1584,7 @@ int Yap_OpenStream(const char *fname, const char *io_mode, Term user_name) { "%s", fname); return -1; } - vfsp = GLOBAL_Stream[sno].vfs; + vfsp = GLOBAL_Stream[sno].vfs; } else { fd = st->file = fopen(fname, io_mode); if (fd == NULL) { diff --git a/os/streams.c b/os/streams.c index c72fc9e94..4ff0ec45b 100644 --- a/os/streams.c +++ b/os/streams.c @@ -1109,7 +1109,6 @@ bool Yap_SetOutputStream( Term sd ) Yap_CheckStream(sd, Output_Stream_f | Append_Stream_f, "set_output/2"); if (sno < 0) return false; - LOCAL_c_output_stream = sno; UNLOCK(GLOBAL_Stream[sno].streamlock); Yap_SetAlias(AtomUserOut, sno); return true; diff --git a/os/writeterm.c b/os/writeterm.c index f61cd85bb..3bd01145c 100644 --- a/os/writeterm.c +++ b/os/writeterm.c @@ -600,6 +600,7 @@ static Int writeln(USES_REGS1) { return false; } int output_stream = Yap_CheckTextStream(ARG1, Output_Stream_f, "writeln/2"); + fprintf(stderr,"writeln %d\n", output_stream); if (output_stream < 0) { free(args); return false; diff --git a/packages/python/CMakeLists.txt b/packages/python/CMakeLists.txt index b44c66a60..17787b257 100644 --- a/packages/python/CMakeLists.txt +++ b/packages/python/CMakeLists.txt @@ -1,7 +1,7 @@ #CHECK: PythonLibs, changed to work in WIN32 -set (PYTHON_SOURCES python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c) +set (PYTHON_SOURCES python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c pyio.c) set (PYTHON_HEADERS py4yap.h) set (CMAKE_POSITION_INDEPENDENT_CODE TRUE) diff --git a/packages/python/py4yap.h b/packages/python/py4yap.h index 1cd70f1ad..b6418ed20 100644 --- a/packages/python/py4yap.h +++ b/packages/python/py4yap.h @@ -56,8 +56,10 @@ extern X_API PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o, bool cvt); extern X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0); typedef YAP_Arity arity_t; +extern bool init_python_vfs(void); -extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t, + + extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t, ATOM_comma, ATOM_builtin, ATOM_V, ATOM_A, ATOM_self, ATOM_nil, ATOM_brackets, ATOM_curly_brackets; diff --git a/packages/python/pyio.c b/packages/python/pyio.c new file mode 100644 index 000000000..026ca94f8 --- /dev/null +++ b/packages/python/pyio.c @@ -0,0 +1,122 @@ + + +#include "py4yap.h" +#include + +#include "YapStreams.h" + +VFS_t pystream; + +static void *py_open(VFS_t *me, int sno, const char *name, + const char *io_mode) { +#if HAVE_STRCASESTR + if (strcasestr(name, "/python/") == name) + name += strlen("/python/"); +#else + if (strstr(name, "/python/") == name) + name += strlen("/python/"); +#endif + StreamDesc *st = YAP_RepStreamFromId(sno); + // we assume object is already open, so there is no need to open it. + PyObject *stream = string_to_python(name, true, NULL); + if (stream == Py_None) + return NULL; + Py_INCREF(stream); + st->u.private_data = stream; + st->vfs = me; + st->name = YAP_LookupAtom(name); + st->user_name = YAP_MkAtomTerm(st->name); + return stream; +} + +static bool py_close(int sno) { return true; } + +static int py_put(int sno, int ch) { + // PyObject *pyw; // buffer + // int pyw_kind; + // PyObject *pyw_data; + // PySys_WriteStdout("%C", ch); + // return ch; + char s[2]; + StreamDesc *st = YAP_GetStreamFromId(sno); + // PyUnicode_WRITE(pyw_kind, pyw_data, 0, ch); + PyObject *err, *fput = PyObject_GetAttrString(st->u.private_data, "write"); + s[0] = ch; + s[1] = '\0'; + PyObject_CallMethodObjArgs(st->u.private_data, PyUnicode_FromString("write"), + PyUnicode_FromString(s), NULL); + if ((err = PyErr_Occurred())) { + PyErr_SetString( + err, + "Error in put\n"); // %s:%s:%d!\n", __FILE__, __FUNCTION__, __LINE__); + } + return ch; +} + +static int py_get(int sno) { + StreamDesc *s = YAP_GetStreamFromId(sno); + PyObject *fget = PyObject_GetAttrString(s->u.private_data, "read"); + PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL); + return PyUnicode_READ_CHAR(pyr, 0); +} + +static int py_peek(int sno) { + StreamDesc *s = YAP_GetStreamFromId(sno); + PyObject *fget = PyObject_GetAttrString(s->u.private_data, "peek"); + PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL); + return PyUnicode_READ_CHAR(pyr, 0); +} + +static int64_t py_seek(int sno, int64_t where, int how) { + StreamDesc *s = YAP_GetStreamFromId(sno); + PyObject *fseek = PyObject_GetAttrString(s->u.private_data, "seek"); + PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where), + PyLong_FromLong(how), NULL); + return PyLong_AsLong(pyr); +} + +static void py_flush(int sno) { + StreamDesc *s = YAP_GetStreamFromId(sno); + PyObject *flush = PyObject_GetAttrString(s->u.private_data, "flush"); + PyObject_CallFunction(flush, NULL); +} + +#if 0 +static void python_output(void) { + PyObject *stream = string_to_python("sys.stdout", true, NULL); + StreamDesc *st = YAP_GetStreamFromId(1); + st->u.private_data = stream; + st->vfs = &pystream; + stream = string_to_python("sys.stderr", true, NULL); + st = YAP_GetStreamFromIds(2); + st->u.private_data = stream; + st->vfs = &pystream; +} +#endif + +static bool initialized = false; + +bool init_python_vfs(void) { + // pyw = PyUnicode_FromString("x"); + // pyw_kind = PyUnicode_KIND(pyw); + // pyw_data = PyUnicode_DATA(pyw); + if (initialized) + return false; + initialized = true; + pystream.name = "python stream"; + pystream.vflags = + VFS_CAN_WRITE | VFS_CAN_EXEC | VFS_CAN_READ | VFS_HAS_PREFIX; + pystream.prefix = "/python/"; + pystream.suffix = NULL; + pystream.open = py_open; + pystream.close = py_close; + pystream.get_char = py_get; + pystream.peek_char = py_peek; + pystream.put_char = py_put; + pystream.flush = py_flush; + pystream.seek = py_seek; + pystream.next = GLOBAL_VFS; + GLOBAL_VFS = &pystream; + // NULL; + return true; +} diff --git a/packages/python/pypreds.c b/packages/python/pypreds.c index 4eef7f4f2..8c609f16d 100644 --- a/packages/python/pypreds.c +++ b/packages/python/pypreds.c @@ -680,4 +680,6 @@ install_t install_pypreds(void) { PL_register_foreign("python_import", 2, python_import, 0); PL_register_foreign("python_access", 3, python_access, 0); PL_register_foreign("python_threaded", 0, p_python_threaded, 0); + + init_python_vfs(); } diff --git a/packages/python/python.c b/packages/python/python.c index 2b7b3603e..bcb1b53e6 100644 --- a/packages/python/python.c +++ b/packages/python/python.c @@ -25,130 +25,6 @@ X_API PyObject *py_Sys; PyObject *py_Context; PyObject *py_ModDict; -VFS_t pystream; - -static void * -py_open(VFS_t *me, int sno, const char *name, - const char *io_mode) { -#if HAVE_STRCASESTR - if (strcasestr(name, "/python/") == name) - name += strlen("/python/"); -#else - if (strstr(name, "/python/") == name) - name += strlen("/python/"); -#endif - StreamDesc *st = YAP_RepStreamFromId(sno); - fprintf(stderr,"opened %d\n", sno); - // we assume object is already open, so there is no need to open it. - PyObject *stream = string_to_python(name, true, NULL); - if (stream == Py_None) - return NULL; - Py_INCREF(stream); - st->u.private_data = stream; - st->vfs = me; - if (strchr(io_mode,'r')) - st->status = Input_Stream_f; - else - st->status = Append_Stream_f | Output_Stream_f; - Yap_DefaultStreamOps(st); - return stream; -} - -static bool -py_close(int sno) { - return true; - StreamDesc *s = YAP_GetStreamFromId(sno); - PyObject *fclose = PyObject_GetAttrString(s->u.private_data, "close"); - PyObject *rc = PyObject_CallObject(fclose, NULL); - bool v = (rc == Py_True); - return v; -} - -static int -py_put(int sno, int ch) { - // PyObject *pyw; // buffer - // int pyw_kind; - // PyObject *pyw_data; - - char s[2]; - StreamDesc *st = YAP_GetStreamFromId(sno); - // PyUnicode_WRITE(pyw_kind, pyw_data, 0, ch); - PyObject *err, *fput = PyObject_GetAttrString(st->u.private_data, "write"); - s[0] = ch; - s[1] = '\0'; - PyObject_CallFunctionObjArgs(fput, PyBytes_FromString(s), NULL); - if ((err = PyErr_Occurred())) { - PyErr_SetString( - err, - "Error in put\n"); // %s:%s:%d!\n", __FILE__, __FUNCTION__, __LINE__); - } - return ch; -} - -static int py_get(int sno) { - StreamDesc *s = YAP_GetStreamFromId(sno); - PyObject *fget = PyObject_GetAttrString(s->u.private_data, "read"); - PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL); - return PyUnicode_READ_CHAR(pyr, 0); -} - -static int py_peek(int sno) { - StreamDesc *s = YAP_GetStreamFromId(sno); - PyObject *fget = PyObject_GetAttrString(s->u.private_data, "peek"); - PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL); - return PyUnicode_READ_CHAR(pyr, 0); -} - -static int64_t py_seek(int sno, int64_t where, int how) { - StreamDesc *s = YAP_GetStreamFromId(sno); - PyObject *fseek = PyObject_GetAttrString(s->u.private_data, "seek"); - PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where), - PyLong_FromLong(how), NULL); - return PyLong_AsLong(pyr); -} - -static void py_flush(int sno) { - StreamDesc *s = YAP_GetStreamFromId(sno); - PyObject *flush = PyObject_GetAttrString(s->u.private_data, "flush"); - PyObject_CallFunction(flush, NULL); -} - -#if 0 -static void python_output(void) { - PyObject *stream = string_to_python("sys.stdout", true, NULL); - StreamDesc *st = YAP_GetStreamFromId(1); - st->u.private_data = stream; - st->vfs = &pystream; - stream = string_to_python("sys.stderr", true, NULL); - st = YAP_GetStreamFromIds(2); - st->u.private_data = stream; - st->vfs = &pystream; -} -#endif - -static bool init_python_stream(void) { - // pyw = PyUnicode_FromString("x"); - // pyw_kind = PyUnicode_KIND(pyw); - // pyw_data = PyUnicode_DATA(pyw); - - pystream.name = "python stream"; - pystream.vflags = - VFS_CAN_WRITE | VFS_CAN_EXEC | VFS_CAN_READ | VFS_HAS_PREFIX; - pystream.prefix = "/python/"; - pystream.suffix = NULL; - pystream.open = py_open; - pystream.close = py_close; - pystream.get_char = py_get; - pystream.peek_char = py_peek; - pystream.put_char = py_put; - pystream.flush = py_flush; - pystream.seek = py_seek; - pystream.next = GLOBAL_VFS; - GLOBAL_VFS = &pystream; - // NULL; - return true; -} - X_API PyObject *Py_f2p; extern X_API bool python_in_python; @@ -170,7 +46,7 @@ static void add_modules(void) { Py_f2p = PythonLookup("f2p", NULL); if (Py_f2p) Py_INCREF(Py_f2p); - init_python_stream(); + init_python_vfs(); } static void install_py_constants(void) { diff --git a/packages/python/python.pl b/packages/python/python.pl index 792e44279..42a2ef10d 100644 --- a/packages/python/python.pl +++ b/packages/python/python.pl @@ -31,11 +31,7 @@ release_GIL/0, python_threaded/0, prolog_list_to_python_list/3, - (:=)/2, - (:=)/1, - % (<-)/2, - % (<-)/1, - op(100,fy,$), + op(100,fy,$), op(950,fy,:=), op(950,yfx,:=), op(950,fx,<-), @@ -114,41 +110,60 @@ Data types are :- use_module(library(charsio)). :- dynamic python_mref_cache/2, python_obj_cache/2. +:- multifile user:(:=)/2, + user:(:=)/1, + user:(<-)/1, + user:(<-)/2, user:'()'/1, user:'{}'/1, user:dot_qualified_goal/2, user:import_arg/1. + + +import( F ) :- catch( python:python_import(F), _, fail ). + +user:dot_qualified_goal(Fs) :- catch( python:python_proc(Fs), _, fail ). + +user:F() :- + catch( python:python_proc(F() ), _, fail ). + + +user(P1,P2) :- !, + := P1, + := P2. + +:= F :- catch( python:python_proc(F), _, fail ). + := (P1,P2) :- !, := P1, := P2. -:= import( F ) :- !, python_import(F). -:= F :- python_proc(F). -V <- F :- +user:(:= ) :- catch( python:python_proc(F), _, fail ). + +user:( V := F ) :- + python:python_assign(F, V). + +user:(<- F) :- + catch( python:python_proc(F), _, fail ). + +user:(V <- F) :- V := F. -( V := F ) :- - python_assign(F, V). - -((<- F)) :- - := F. - -python_import(Module) :- - python_import(Module, _). +python:python_import(Module) :- + python:python_import(Module, _). python(Exp, Out) :- Out := Exp. python_command(Cmd) :- - python_run_command(Cmd). - + python:python_run_command(Cmd). start_python :- - python_import('inspect', _), + python:python_import('inspect', _), at_halt(end_python). add_cwd_to_python :- unix(getcwd(Dir)), atom_concat(['sys.path.append(\"',Dir,'\")'], Command), - python_command(Command), - python_command("sys.argv = [\"yap\"]"). + python:python_command(Command), + python:python_command("sys.argv = [\"yap\"]"). % done :- initialization( load_foreign_files(['YAPPython'], [], init_python_dll), now ). diff --git a/packages/python/swig/prolog/yapi.yap b/packages/python/swig/prolog/yapi.yap index bd226da15..e45c49a93 100644 --- a/packages/python/swig/prolog/yapi.yap +++ b/packages/python/swig/prolog/yapi.yap @@ -1,7 +1,7 @@ %% @file yapi.yap %% @brief support yap shell %% -:- start_low_level_trace. +%:- start_low_level_trace. :- module(yapi, [ python_ouput/0, show_answer/2, @@ -60,7 +60,8 @@ argi(N,I,I1) :- atomic_concat(`A`,I,N), I1 is I+1. -python_query( Self, String ) :- +python_query( Caller, String ) :- + Self := Caller.it, atomic_to_term( String, Goal, VarNames ), query_to_answer( Goal, VarNames, Status, Bindings), Self.port := Status, diff --git a/packages/python/swig/yap4py/yapi.py b/packages/python/swig/yap4py/yapi.py index e3afa04fd..8ee768e91 100644 --- a/packages/python/swig/yap4py/yapi.py +++ b/packages/python/swig/yap4py/yapi.py @@ -18,11 +18,11 @@ class Engine( YAPEngine ): if self_contained: yap_lib_path = os.path.dirname(__file__) args.setYapShareDir(os.path.join(yap_lib_path, "prolog")) - args.setYapLibDir(yap_lib_path) + args.setYapPLDIR(yap_lib_path) args.setSavedState(os.path.join(yap_lib_path, "startup.yss")) YAPEngine.__init__(self, args) self.goal(set_prolog_flag('verbose', 'silent')) - self.goal(use_module(library('yapi'))) + self.goal(compile(library('yapi'))) self.goal(set_prolog_flag('verbose', 'normal')) def run(self, g, m=None): @@ -49,19 +49,22 @@ class Predicate( YAPPredicate ): class Goal(object): """Goal is a predicate instantiated under a specific environment """ - def __init__(self, g, engine, module="user",program=None, max_answers=None ): - self.g = g + def __init__(self, engine, g): + self.q = engine.query(g) self.e = engine + self.port = "call" + self.bindings = None def __iter__(self): - return PrologTableIter( self.e, self.g ) + return PrologTableIter( self.e, self ) class PrologTableIter: - def __init__(self, e, query): + def __init__(self, e, g): try: self.e = e - self.q = e.query(python_query(self, query)) + self.g = g + self.q = g.q except: print('Error') @@ -74,8 +77,8 @@ class PrologTableIter: if not self.q: raise StopIteration() if self.q.next(): - rc = self.q.bindings - if self.q.port == "exit": + rc = self.g.bindings + if self.g.port == "exit": self.close() return rc else: @@ -98,7 +101,7 @@ global engine, handler yap_lib_path = os.path.dirname(__file__) -use_module = namedtuple('use_module', 'file') +compile = namedtuple('compile', 'file') bindvars = namedtuple('bindvars', 'list') library = namedtuple('library', 'list') v = namedtuple( 'v', 'slot') @@ -153,7 +156,7 @@ class YAPShell: def query_prolog(self, engine, query): - import pdb; pdb.set_trace() + #import pdb; pdb.set_trace() # # construct a query from a one-line string # q is opaque to Python @@ -174,8 +177,9 @@ class YAPShell: do_ask = True self.e = engine bindings = [] + g = python_query(self, query) if not self.q: - self.it = PrologTableIter( self.e, query ) + self.it = Goal( engine, g ) for bind in self.it: bindings += [bind] if do_ask: diff --git a/packages/python/yap_kernel/setup.py b/packages/python/yap_kernel/setup.py index 1e1d49eed..5ffe87dfd 100644 --- a/packages/python/yap_kernel/setup.py +++ b/packages/python/yap_kernel/setup.py @@ -37,15 +37,15 @@ from distutils.core import setup pjoin = os.path.join here = os.path.abspath(os.path.dirname(__file__)) -packages = [] +packages = ['yap_kernel','yap_ipython'] # pkg_root = pjoin(here, name) -for d, _, _ in os.walk(pjoin(here, 'yap_kernel')): - if os.path.exists(pjoin(d, '__init__.py')): - packages.append(d[len(here)+1:].replace(os.path.sep, '.')) -for d, _, _ in os.walk(pjoin(here, 'yap_ipython')): - if os.path.exists(pjoin(d, '__init__.py')): - packages.append(d[len(here)+1:].replace(os.path.sep, '.')) +# for d, _, _ in os.walk(pjoin(here, 'yap_kernel')): +# if os.path.exists(pjoin(d, '__init__.py')): +# packages.append(d[len(here)+1:].replace(os.path.sep, '.')) +# for d, _, _ in os.walk(pjoin(here, 'yap_ipython')): +# if os.path.exists(pjoin(d, '__init__.py')): +# packages.append(d[len(here)+1:].replace(os.path.sep, '.')) sys.path.insert(0, here) package_data = { diff --git a/packages/python/yap_kernel/yap_ipython/core/interactiveshell.py b/packages/python/yap_kernel/yap_ipython/core/interactiveshell.py index 1f741361d..170260c82 100644 --- a/packages/python/yap_kernel/yap_ipython/core/interactiveshell.py +++ b/packages/python/yap_kernel/yap_ipython/core/interactiveshell.py @@ -2324,8 +2324,8 @@ class InteractiveShell(SingletonConfigurable): Command to execute (can not end in '&', as background processes are not supported. split : bool, optional - If True, split the output into an yap_ipython SList. Otherwise, an - yap_ipython LSString is returned. These are objects similar to normal + If True, split the output into an IPython SList. Otherwise, an + ipython LSString is returned. These are objects similar to normal lists and strings, with a few convenience attributes for easier manipulation of line-based output. You can use '?' on them for details. @@ -2598,7 +2598,7 @@ class InteractiveShell(SingletonConfigurable): with prepended_to_syspath(dname): try: for cell in get_cells(): - result = self.run_cell(cell, silent=True, shell_futures=shell_futures) + result = self.run_cell(cell, silent=False , shell_futures=shell_futures) if raise_exceptions: result.raise_error() elif not result.success: diff --git a/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap b/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap index 17a57f620..5685f68ca 100644 --- a/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap +++ b/packages/python/yap_kernel/yap_ipython/prolog/jupyter.yap @@ -1,3 +1,4 @@ + /** * @file jupyter.yap * @@ -20,30 +21,30 @@ %% ). -%:- reexport(library(yapi)). +:- reexport(library(yapi)). :- use_module(library(lists)). :- use_module(library(maplist)). :- use_module(library(python)). :- python_import(sys). -jupyter_query(Self, Cell, Line ) :- - start_low_level_trace, - setup_call_cleanup( - enter_cell(Self), - jupyter_cell(Self, Cell, Line), - exit_cell(Self) - ). +jupyter_query(Caller, Cell, Line ) :- + jupyter_cell(Caller, Cell, Line). -jupyter_cell(_Self, Cell, _) :- +jupyter_cell(_Caller, Cell, _) :- jupyter_consult(Cell), fail. -jupyter_cell( _Self, _, Line ) :- +jupyter_cell( _Caller, _, Line ) :- blank( Line ), !. -jupyter_cell( _Self, _, [] ) :- !. -jupyter_cell( Self, _, Line ) :- - python_query( Self, Line ). +jupyter_cell( _Caller, _, [] ) :- !. +jupyter_cell( Caller, _, Line ) :- +gated_call( + enter_cell(call), + python_query( Caller, Line ), + Port, + enter_cell(Port) + ). jupyter_consult(Text) :- blank( Text ), @@ -61,18 +62,31 @@ blankc(' '). blankc('\n'). blankc('\t'). -enter_cell(_Self) :- - open('/python/input', read, Input, []), - open('/python/sys.stdout', append, Output, []), - open('/python/sys.stdout', append, Error, []), - set_prolog_flag(user_input, Input), - set_prolog_flag(user_output, Output), - set_prolog_flag(user_error, Error). +enter_cell(retry) :- + enter_cell(call). +enter_cell(call) :- + into_cell. +enter_cell(fail) :- + enter_cell(exit). +enter_cell(answer) :- + enter_cell(exit). +enter_cell(exception(_)) :- + enter_cell(exit). +enter_cell(external_exception(_)). + enter_cell(!). +enter_cell(exit) :- + nb_setval(jupyter_cell, off), + close( user_output). -exit_cell(_Self) :- - close( user_input), - close( user_output), - close( user_error). + +into_cell :- + nb_setval(jupyter_cell, on), + open('/python/sys.input', read, _Input, [bom(false)]), + open('/python/sys.stdout', append, _Output, []), + open('/python/sys.stderr', append, _Error, []), + set_prolog_flag(user_input,_Output), + set_prolog_flag(user_output,_Output), + set_prolog_flag(user_error,_Error). completions(S, Self) :- @@ -188,14 +202,14 @@ errors( Self, Text ) :- close_events( Self ) ). -clauses(Self, Stream) :- +clauses(_Self, Stream) :- repeat, read_clause(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ), % command( Self, Cl ), Cl == end_of_file, !. -goals(Self, Stream) :- +goals(_Self, Stream) :- repeat, read_term(Stream, Cl, [term_position(_Pos), syntax_errors(fail)] ), % command( Self, Cl ), @@ -252,14 +266,14 @@ user:portray_message(_Severity, error(syntax_error(Cause),info(between(_,LN,_), assert( syntax_error(Cause,LN,CharPos,Details) ). user:portray_message(_Severity, error(style_check(_),_) ) :- nb_getval(jupyter_cell, on). - + open_events(Self, Text, Stream) :- Self.errors := [], nb_setval( jupyter, on), open_mem_read_stream( Text, Stream ). :- initialization( nb_setval( jupyter, off ) ). - + close_events( _Self ) :- nb_setval( jupyter, off ), retract( undo(G) ), @@ -271,4 +285,4 @@ close_events( Self ) :- fail. close_events( _ ). -:- ( start_low_level_trace ). +%:- ( start_low_level_trace ). diff --git a/packages/python/yap_kernel/yap_ipython/yapi.py b/packages/python/yap_kernel/yap_ipython/yapi.py index c355f8c9c..fdc8c0957 100644 --- a/packages/python/yap_kernel/yap_ipython/yapi.py +++ b/packages/python/yap_kernel/yap_ipython/yapi.py @@ -9,20 +9,21 @@ from typing import Iterator, List, Tuple, Iterable, Union from traitlets import Bool, Enum, observe, Int try: - from yap4py.yapi import Engine + from yap4py.yapi import Engine, Goal, EngineArgs, PrologTableIter except: print("Could not load _yap dll.") -from yap_ipython.core import interactiveshell from yap_ipython.core.completer import Completer, Completion from yap_ipython.utils.strdispatch import StrDispatch # import yap_ipython.core from traitlets import Instance from yap_ipython.core.inputsplitter import * from yap_ipython.core.inputtransformer import * +from yap_ipython.core.interactiveshell import * from pygments import highlight from pygments.lexers.prolog import PrologLexer from pygments.formatters import HtmlFormatter +from yap_ipython.core import interactiveshell from collections import namedtuple @@ -106,7 +107,6 @@ class YAPInputSplitter(InputSplitter): def validQuery(self, text, line=None): """Return whether a legal query """ - print("valid") if not line: (_,line,_) = self.shell.prolog_cell(text) line = line.strip().rstrip() @@ -114,7 +114,6 @@ class YAPInputSplitter(InputSplitter): return False self.errors = [] self.yapeng.mgoal(errors(self, line),"user") - print(self.errors) return self.errors != [] @@ -279,7 +278,7 @@ class YAPCompleter(Completer): help="""Activate greedy completion PENDING DEPRECTION. this is now mostly taken care of with Jedi. - This will enable completion on elements of lists, results of function calls, etc., + This will enable completion on elements of lists, self.results of function calls, etc., but can be unsafe because the code is actually evaluated on TAB. """ ).tag(config=True) @@ -511,8 +510,9 @@ class YAPRun: self.yapeng = Engine() self.yapeng.goal(use_module(library("jupyter"))) self.q = None - self.run = False - self.shell.port = None + self.port = "call" + self.os = None + self.it = None self.shell.yapeng = self.yapeng self._get_exc_info = shell._get_exc_info @@ -525,27 +525,37 @@ class YAPRun: self.yapeng.mgoal(errors(self,text),"user") return self.errors - def jupyter_query(self, s, mx): + def jupyter_query(self, s): # # construct a self.query from a one-line string # self.q is opaque to Python - iterations = 0 - bindings = [] - program,query,_ = self.prolog_cell(s) - if query == self.shell.os: - q = self.shell.q - self.shell.os = None + program,query,mx = self.prolog_cell(s) + Found = False + + if query != self.os: + self.os = None + self.iterations = 0 + pg = jupyter_query( self, program, query) + self.it = Goal( self.yapeng, pg) else: - q = Goal(jupyter_query(self, query), self.yapeng, module="user",program=program) - for q in q: - bindings += [q.bindings()] - iterations += 1 - if mx == iterations: - break - if q: - self.shell.os = query - self.shell.q = q - return bindings + mx += self.iterations + self.os = s + for answ in self.it: + found = True + self.bindings += [answ] + self.iterations += 1 + if mx == self.iterations: + return True, self.bindings + port = self.it.port + if port == "exit": + self.q = None + self.os = None + return True,self.bindings + if port == "fail": + self.q = none + self.os = None + if self.bindings_message: + return True,self.bindings def _yrun_cell(self, raw_cell, store_history=True, silent=False, @@ -563,7 +573,7 @@ class YAPRun: IPython's machinery, this should be set to False. silent : bool - If True, avoid side-effects, such as implicit displayhooks and +v If True, avoid side-effects, such as implicit displayhooks and and logging. silent=True forces store_history=False. shell_futures : bool If True, the code will share future statements with the interactive @@ -576,7 +586,7 @@ class YAPRun: ------- -`result : :class:`ExecutionResult` +`self.result : :class:`Executionself.result` """ # construct a query from a one-line string @@ -594,22 +604,22 @@ class YAPRun: info = interactiveshell.ExecutionInfo( raw_cell, store_history, silent, shell_futures) - result = interactiveshell.ExecutionResult(info) + self.result = interactiveshell.ExecutionResult(info) if (raw_cell == "") or raw_cell.isspace(): self.shell.last_execution_succeeded = True - return result + return self.result if silent: store_history = False if store_history: - result.execution_count = self.shell.execution_count+1 + self.result .execution_count = self.shell.execution_count+1 def error_before_exec(value): - result.error_before_exec = value + self.result .error_before_exec = value self.shell.last_execution_succeeded = False - return result + return self.result self.shell.events.trigger('pre_execute') if not silent: @@ -646,12 +656,10 @@ class YAPRun: except SyntaxError: self.shell.showsyntaxerror( ) preprocessing_exc_tuple = sys.exc_info() - # Store raw and processed history if store_history: self.shell.history_manager.store_inputs(self.shell.execution_count, cell, raw_cell) - silent = False if not silent: self.shell.logger.log(cell, raw_cell) # # Display the exception if input processing failed. @@ -681,32 +689,33 @@ class YAPRun: line = txt[1] else: line = "" + if len(txt0) == 2: + cell = txt0[1] + else: + cell = "" if linec: self.shell.run_line_magic(magic, line) - if len(txt0) == 2: - cell = txt0[1] - else: - cellArea = "" else: self.shell.run_cell_magic(magic, line, cell) - return + cell = "" # Give the displayhook a reference to our ExecutionResult so it # can fill in the output value. - self.shell.displayhook.exec_result = result + self.shell.displayhook.exec_result = self.result has_raised = False try: + state = None self.shell.bindings = dict = {} - state = self.jupyter_query( cell) + if cell.strip(): + state = self.jupyter_query( cell ) if state: self.shell.last_execution_succeeded = True - result.result = (True, dict) + self.result.result = (True, dict) else: self.shell.last_execution_succeeded = True - result.result = (True, {}) + self.result.result = (True, {}) except Exception as e: - print(e) has_raised = True - result.result = False + self.result.result = False self.shell.last_execution_succeeded = not has_raised @@ -724,10 +733,10 @@ class YAPRun: # Each cell is a *single* input, regardless of how many lines it has self.shell.execution_count += 1 - return result + return self.result def prolog_cell(self,s): - """" + """ Trasform a text into program+query. A query is the last line if the last line is non-empty and does not terminate on a dot. You can also finish with diff --git a/pl/CMakeLists.txt b/pl/CMakeLists.txt index 14e71a8c1..d7a5636f8 100644 --- a/pl/CMakeLists.txt +++ b/pl/CMakeLists.txt @@ -56,6 +56,7 @@ set(PL_BOOT_SOURCES undefined.yap utils.yap yapor.yap + ypp.yap ) add_to_group(PL_BOOT_SOURCES pl_boot_library) @@ -91,8 +92,5 @@ endif() install(FILES ${PL_BOOT_SOURCES} - DESTINATION ${libpl}/pl - ) -install(FILES ../library/ypp.yap - DESTINATION ${libpl}/library + DESTINATION ${libpl}/pll ) diff --git a/pl/boot.yap b/pl/boot.yap index 861ceda6a..d6286f335 100644 --- a/pl/boot.yap +++ b/pl/boot.yap @@ -109,65 +109,6 @@ private(_). % be careful here not to generate an undefined exception.. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - print_message(L,E) :- '$number_of_clauses'(print_message(L,E), prolog_complete, 1), !, @@ -326,7 +267,7 @@ initialize_prolog :- :- [ % lists is often used. '../os/yio.yap', - '../pl/debug.yap', + 'debug.yap', 'checker.yap', 'depth_bound.yap', 'ground.yap', @@ -418,7 +359,7 @@ sub-goal _NG_ will replace _G_ and will be processed in the same :- use_module('corout.yap'). :- use_module('dialect.yap'). :- use_module('dbload.yap'). -:- use_module('../library/ypp.yap'). +:- use_module('ypp.yap'). :- use_module('../os/chartypes.yap'). :- ensure_loaded('../os/edio.yap'). diff --git a/pl/consult.yap b/pl/consult.yap index 87b52dcfe..fb67853a6 100644 --- a/pl/consult.yap +++ b/pl/consult.yap @@ -1,4 +1,4 @@ -/************************************************************************* +s444444444444444444444444444444444444444444444444444444444444444444444444/************************************************************************* * * * YAP Prolog * * * @@ -650,12 +650,17 @@ db_files(Fs) :- '$load_files'(Fs, [consult(db), if(not_loaded)], exo_files(Fs)). +'$csult'(Fs, M) :- + '$skip_list'(_, Fs ,L), + L \== [], + user:dot_qualified_goal(Fs), + !. '$csult'(Fs, M) :- '$extract_minus'(Fs, MFs), !, '$load_files'(M:MFs,[],[M:Fs]). '$csult'(Fs, M) :- '$load_files'(M:Fs,[consult(consult)],[M:Fs]). - + '$extract_minus'([], []). '$extract_minus'([-F|Fs], [F|MFs]) :- '$extract_minus'(Fs, MFs). @@ -1627,6 +1632,8 @@ End of conditional compilation. consult_depth(LV) :- '$show_consult_level'(LV). +:- '$add_multifile'(Name,Arity,Module). + /** @} diff --git a/pl/control.yap b/pl/control.yap index 3e91343b5..fa38c654b 100644 --- a/pl/control.yap +++ b/pl/control.yap @@ -429,7 +429,7 @@ query_to_answer(G, V, Status, Bindings) :- '$answer'( answer, LGs, Vs, Bindings) :- !, '$process_answer'(Vs, LGs, Bindings). -'$answer'(cut, _, _, _). +'$answer'(!, _, _, _). '$answer'(fail,_,_,_). '$answer'(exception(E),_,_,_) :- '$LoopError'(E,error). diff --git a/pl/debug.yap b/pl/debug.yap index cb6bebcf0..d9614e38c 100644 --- a/pl/debug.yap +++ b/pl/debug.yap @@ -469,7 +469,7 @@ be lost. Border < GoalNumber, ( Spy == ignore ; '$pred_being_spied'(G, M) ) ), - writeln(go:G:M), + %writeln(go:G:M), !, '$execute_nonstop'(G,M). '$trace_goal'(G, M, GoalNumber, H) :- diff --git a/pl/directives.yap b/pl/directives.yap index f54db8cc4..64cd8d9e0 100644 --- a/pl/directives.yap +++ b/pl/directives.yap @@ -238,7 +238,7 @@ user_defined_directive(Dir,Action) :- '$thread_initialization'(M:D) :- eraseall('$thread_initialization'), - writeln(M:D), + %writeln(M:D), recorda('$thread_initialization',M:D,_), fail. '$thread_initialization'(M:D) :- diff --git a/pl/modules.yap b/pl/modules.yap index 45f4c5314..aaeab21f2 100644 --- a/pl/modules.yap +++ b/pl/modules.yap @@ -365,7 +365,6 @@ system_module(Mod) :- functor(G0, N, K), '$autoloader_find_predicate'(G0,ExportingMod), ExportingMod \= ImportingMod, - writeln((ExportingMod,ImportingMod,G0,G0, N ,K)), (recordzifnot('$import','$import'(ExportingMod,ImportingMod,G0,G0, N ,K),_) -> true ; true ). @@ -399,7 +398,7 @@ be associated to a new file. */ '$declare_module'(Name, _Super, Context, _File, _Line) :- - add_import_module(Name, Context, start). + addi_mport_module(Name, Context, start). /** @pred abolish_module( + Mod) is det @@ -492,11 +491,9 @@ export_list(Module, List) :- G1=..[N1|Args], ( '$check_import'(M0,ContextMod,N1,K) -> ( ContextMod == prolog -> - writeln((M0,ContextMod,G0,G1,N1,K)), recordzifnot('$import','$import'(M0,user,G0,G1,N1,K),_), fail ; - writeln((M0,ContextMod,G0,G1,N1,K)), recordaifnot('$import','$import'(M0,ContextMod,G0,G1,N1,K),_), fail ; diff --git a/library/ypp.yap b/pl/ypp.yap similarity index 100% rename from library/ypp.yap rename to pl/ypp.yap