diff --git a/C/blobs.c b/C/blobs.c index 7a5b3b5dc..54c61e38e 100644 --- a/C/blobs.c +++ b/C/blobs.c @@ -209,8 +209,8 @@ bool YAP_get_blob(Term t, void **blob, size_t *len, blob_type_t **type) { return TRUE; } -void *YAP_blob_data(Atom x, size_t *len, blob_type_t **type) { - +void *YAP_blob_data(YAP_Atom at, size_t *len, blob_type_t **type) { +Atom x = at; if (!IsBlob(x)) { if (len) diff --git a/C/c_interface.c b/C/c_interface.c index 3bb5ea3bc..f0d9c324d 100755 --- a/C/c_interface.c +++ b/C/c_interface.c @@ -33,7 +33,6 @@ #include #endif -#include #include #if HAVE_STDARG_H @@ -62,7 +61,6 @@ #endif /* YAPOR */ #include "cut_c.h" -#include "threads.h" #if HAVE_MALLOC_H @@ -324,7 +322,7 @@ X_API Int YAP_IntOfTerm(Term t) { } } -X_API Term YAP_MkBigNumTerm(void*big) { +X_API Term YAP_MkBigNumTerm(void *big) { #if USE_GMP Term I; BACKUP_H(); @@ -428,16 +426,16 @@ X_API Term YAP_MkFloatTerm(double n) { X_API YAP_Float YAP_FloatOfTerm(YAP_Term t) { return (FloatOfTerm(t)); } -X_API Term YAP_MkAtomTerm(Atom n) { +X_API Term YAP_MkAtomTerm(YAP_Atom n) { Term t; t = MkAtomTerm(n); return t; } -X_API Atom YAP_AtomOfTerm(Term t) { return (AtomOfTerm(t)); } +X_API YAP_Atom YAP_AtomOfTerm(Term t) { return (AtomOfTerm(t)); } -X_API bool YAP_IsWideAtom(Atom a) { +X_API bool YAP_IsWideAtom(YAP_Atom a) { const unsigned char *s = RepAtom(a)->UStrOfAE; int32_t v; while (*s) { @@ -448,14 +446,14 @@ X_API bool YAP_IsWideAtom(Atom a) { return false; } -X_API const char *YAP_AtomName(Atom a) { +X_API const char *YAP_AtomName(YAP_Atom a) { const char *o; o = AtomName(a); return (o); } -X_API const wchar_t *YAP_WideAtomName(Atom a) { +X_API const wchar_t *YAP_WideAtomName(YAP_Atom a) { int32_t v; const unsigned char *s = RepAtom(a)->UStrOfAE; size_t n = strlen_utf8(s); @@ -470,7 +468,7 @@ X_API const wchar_t *YAP_WideAtomName(Atom a) { return dest; } -X_API Atom YAP_LookupAtom(const char *c) { +X_API YAP_Atom YAP_LookupAtom(const char *c) { CACHE_REGS Atom a; @@ -488,7 +486,7 @@ X_API Atom YAP_LookupAtom(const char *c) { return NULL; } -X_API Atom YAP_LookupWideAtom(const wchar_t *c) { +X_API YAP_Atom YAP_LookupWideAtom(const wchar_t *c) { CACHE_REGS Atom a; @@ -506,7 +504,7 @@ X_API Atom YAP_LookupWideAtom(const wchar_t *c) { return NULL; } -X_API Atom YAP_FullLookupAtom(const char *c) { +X_API YAP_Atom YAP_FullLookupAtom(const char *c) { CACHE_REGS Atom at; @@ -524,7 +522,7 @@ X_API Atom YAP_FullLookupAtom(const char *c) { return NULL; } -X_API size_t YAP_AtomNameLength(Atom at) { +X_API size_t YAP_AtomNameLength(YAP_Atom at) { if (IsBlob(at)) { return RepAtom(at)->rep.blob->length; } @@ -648,7 +646,7 @@ X_API Int YAP_SkipList(Term *l, Term **tailp) { return length; } -X_API Term YAP_MkApplTerm(Functor f, UInt arity, Term args[]) { +X_API Term YAP_MkApplTerm(YAP_Functor f, UInt arity, Term args[]) { CACHE_REGS Term t; BACKUP_H(); @@ -662,7 +660,7 @@ X_API Term YAP_MkApplTerm(Functor f, UInt arity, Term args[]) { return t; } -X_API Term YAP_MkNewApplTerm(Functor f, UInt arity) { +X_API Term YAP_MkNewApplTerm(YAP_Functor f, UInt arity) { CACHE_REGS Term t; BACKUP_H(); @@ -676,7 +674,7 @@ X_API Term YAP_MkNewApplTerm(Functor f, UInt arity) { return t; } -X_API Functor YAP_FunctorOfTerm(Term t) { return (FunctorOfTerm(t)); } +X_API YAP_Functor YAP_FunctorOfTerm(Term t) { return (FunctorOfTerm(t)); } X_API Term YAP_ArgOfTerm(UInt n, Term t) { return (ArgOfTerm(n, t)); } @@ -688,11 +686,11 @@ X_API Term *YAP_ArgsOfTerm(Term t) { return NULL; } -X_API Functor YAP_MkFunctor(Atom a, UInt n) { return (Yap_MkFunctor(a, n)); } +X_API YAP_Functor YAP_MkFunctor(YAP_Atom a, UInt n) { return (Yap_MkFunctor(a, n)); } -X_API Atom YAP_NameOfFunctor(Functor f) { return (NameOfFunctor(f)); } +X_API YAP_Atom YAP_NameOfFunctor(YAP_Functor f) { return (NameOfFunctor(f)); } -X_API UInt YAP_ArityOfFunctor(Functor f) { return (ArityOfFunctor(f)); } +X_API UInt YAP_ArityOfFunctor(YAP_Functor f) { return (ArityOfFunctor(f)); } X_API void *YAP_ExtraSpaceCut(void) { CACHE_REGS @@ -1356,9 +1354,9 @@ X_API void YAP_FreeSpaceFromYap(void *ptr) { Yap_FreeCodeSpace(ptr); } */ X_API char * YAP_StringToBuffer(Term t, char *buf, unsigned int bufsize) { CACHE_REGS - BACKUP_MACHINE_REGS(); - seq_tv_t inp, out; - int l = push_text_stack(); + BACKUP_MACHINE_REGS(); + seq_tv_t inp, out; + int l = push_text_stack(); inp.val.t = t; inp.type = YAP_STRING_ATOMS_CODES | YAP_STRING_STRING | YAP_STRING_ATOM | YAP_STRING_TRUNC | YAP_STRING_MALLOC; @@ -1368,15 +1366,15 @@ YAP_StringToBuffer(Term t, char *buf, unsigned int bufsize) { out.enc = ENC_ISO_UTF8; if (!Yap_CVT_Text(&inp, &out PASS_REGS)) { pop_text_stack(l); - RECOVER_MACHINE_REGS(); - return NULL; + RECOVER_MACHINE_REGS(); + return NULL; } else { - RECOVER_MACHINE_REGS(); - if (buf == out.val.c) { - return buf; - } else { - return pop_output_text_stack(l, out.val.c); - } + RECOVER_MACHINE_REGS(); + if (buf == out.val.c) { + return buf; + } else { + return pop_output_text_stack(l, out.val.c); + } } } @@ -1703,21 +1701,21 @@ X_API void YAP_Error(int myerrno, Term t, const char *buf, ...) { Yap_Error(myerrno, t, tmpbuf); } -X_API PredEntry *YAP_FunctorToPred(Functor func) { +X_API YAP_PredEntryPtr YAP_FunctorToPred(YAP_Functor func) { CACHE_REGS return RepPredProp(PredPropByFunc(func, CurrentModule)); } -X_API PredEntry *YAP_AtomToPred(Atom at) { +X_API YAP_PredEntryPtr YAP_AtomToPred(YAP_Atom at) { CACHE_REGS return RepPredProp(PredPropByAtom(at, CurrentModule)); } -X_API PredEntry *YAP_FunctorToPredInModule(Functor func, Term mod) { +X_API YAP_PredEntryPtr YAP_FunctorToPredInModule(YAP_Functor func, Term mod) { return RepPredProp(PredPropByFunc(func, mod)); } -X_API PredEntry *YAP_AtomToPredInModule(Atom at, Term mod) { +X_API YAP_PredEntryPtr YAP_AtomToPredInModule(YAP_Atom at, Term mod) { return RepPredProp(PredPropByAtom(at, mod)); } @@ -1729,8 +1727,9 @@ static int run_emulator(USES_REGS1) { return out; } -X_API bool YAP_EnterGoal(PredEntry *pe, CELL *ptr, YAP_dogoalinfo *dgi) { +X_API bool YAP_EnterGoal(YAP_PredEntryPtr ape, CELL *ptr, YAP_dogoalinfo *dgi) { CACHE_REGS + PredEntry *pe = ape; bool out; BACKUP_MACHINE_REGS(); @@ -1877,8 +1876,8 @@ X_API Int YAP_RunGoal(Term t) { } X_API Term YAP_AllocExternalDataInStack(size_t bytes) { - CELL *pt; - Term t = Yap_AllocExternalDataInStack(EXTERNAL_BLOB, bytes, &pt); + CELL *pt; + Term t = Yap_AllocExternalDataInStack(EXTERNAL_BLOB, bytes, &pt); if (t == TermNil) return 0L; return t; @@ -1896,12 +1895,12 @@ X_API YAP_opaque_tag_t YAP_NewOpaqueType(struct YAP_opaque_handler_struct *f) { int i; if (!GLOBAL_OpaqueHandlersCount) { GLOBAL_OpaqueHandlers = - malloc(sizeof(YAP_opaque_handler_t) *USER_BLOB_END ); + malloc(sizeof(YAP_opaque_handler_t) * USER_BLOB_END); if (!GLOBAL_OpaqueHandlers) { /* no room */ return -1; } - GLOBAL_OpaqueHandlersCount = USER_BLOB_START; + GLOBAL_OpaqueHandlersCount = USER_BLOB_START; } else if (GLOBAL_OpaqueHandlersCount == USER_BLOB_END) { /* all types used */ return -1; @@ -1912,23 +1911,24 @@ X_API YAP_opaque_tag_t YAP_NewOpaqueType(struct YAP_opaque_handler_struct *f) { } X_API Term YAP_NewOpaqueObject(YAP_opaque_tag_t blob_tag, size_t bytes) { - CELL *pt; - Term t = Yap_AllocExternalDataInStack((CELL) blob_tag, bytes, &pt); - if (t == TermNil) - return 0L; - pt = RepAppl(t); - blob_tag = pt[1]; - if (blob_tag < USER_BLOB_START || - blob_tag >= USER_BLOB_END) { - Yap_Error(SYSTEM_ERROR_INTERNAL, AbsAppl(pt), "clean opaque: bad blob with tag " UInt_FORMAT ,blob_tag); - return FALSE; - } - YAP_opaque_tag_t blob_info = blob_tag; + CELL *pt; + Term t = Yap_AllocExternalDataInStack((CELL) blob_tag, bytes, &pt); + if (t == TermNil) + return 0L; + pt = RepAppl(t); + blob_tag = pt[1]; + if (blob_tag < USER_BLOB_START || + blob_tag >= USER_BLOB_END) { + Yap_Error(SYSTEM_ERROR_INTERNAL, AbsAppl(pt), "clean opaque: bad blob with tag " + UInt_FORMAT, blob_tag); + return FALSE; + } + YAP_opaque_tag_t blob_info = blob_tag; if (GLOBAL_OpaqueHandlers[blob_info].cut_handler || - GLOBAL_OpaqueHandlers[blob_info].fail_handler ) { - *HR++ = t; - *HR++ = TermNil; - TrailTerm(TR) = AbsPair(HR-2); + GLOBAL_OpaqueHandlers[blob_info].fail_handler) { + *HR++ = t; + *HR++ = TermNil; + TrailTerm(TR) = AbsPair(HR - 2); } return t; } @@ -2121,10 +2121,10 @@ X_API int YAP_InitConsult(int mode, const char *fname, char *full, if (mode == YAP_BOOT_MODE) { mode = YAP_CONSULT_MODE; } - char *bfp = Malloc(YAP_FILENAME_MAX+1); + char *bfp = Malloc(YAP_FILENAME_MAX + 1); bfp[0] = '\0'; - if(fname != NULL && fname[0] != 0 ) - strcpy( bfp, fname ); + if (fname != NULL && fname[0] != 0) + strcpy(bfp, fname); bool consulted = (mode == YAP_CONSULT_MODE); const char *fl = Yap_findFile(bfp, NULL, NULL, full, true, YAP_BOOT_PL, true, true); @@ -2132,28 +2132,27 @@ X_API int YAP_InitConsult(int mode, const char *fname, char *full, pop_text_stack(lvl); return -1; } - Yap_init_consult(consulted,bfp); - sno = Yap_OpenStream(fl, "r" ); + Yap_init_consult(consulted, bfp); + sno = Yap_OpenStream(fl,"r"); *osnop = Yap_CheckAlias(AtomLoopStream); if (!Yap_AddAlias(AtomLoopStream, sno)) { Yap_CloseStream(sno); - pop_text_stack(lvl); - sno = -1; + pop_text_stack(lvl); + sno = -1; + return sno; } GLOBAL_Stream[sno].name = Yap_LookupAtom(fl); GLOBAL_Stream[sno].user_name = MkAtomTerm(Yap_LookupAtom(fname)); GLOBAL_Stream[sno].encoding = LOCAL_encoding; - pop_text_stack(lvl); - RECOVER_MACHINE_REGS(); + RECOVER_MACHINE_REGS(); UNLOCK(GLOBAL_Stream[sno].streamlock); return sno; } /// given a stream descriptor or stream alias (see open/3), /// return YAP's internal handle. -X_API void *YAP_GetStreamFromId(int no) -{ - return GLOBAL_Stream+no; +X_API void *YAP_GetStreamFromId(int no) { + return GLOBAL_Stream + no; } X_API FILE *YAP_TermToStream(Term t) { @@ -2195,18 +2194,17 @@ X_API Term YAP_ReadFromStream(int sno) { Term o; BACKUP_MACHINE_REGS(); - o = Yap_read_term(sno, TermNil, 1); + o = Yap_read_term(sno, TermNil, false); RECOVER_MACHINE_REGS(); return o; } X_API Term YAP_ReadClauseFromStream(int sno) { - Term o; BACKUP_MACHINE_REGS(); - o = Yap_read_term(sno, TermNil, -1); + Term t = Yap_read_term(sno, TermNil, true); RECOVER_MACHINE_REGS(); - return o; + return t; } X_API void YAP_Write(Term t, FILE *f, int flags) { @@ -2237,23 +2235,24 @@ X_API char *YAP_WriteBuffer(Term t, char *buf, size_t sze, int flags) { BACKUP_MACHINE_REGS(); int l = push_text_stack(); inp.val.t = t; - inp.type = YAP_STRING_TERM|YAP_STRING_DATUM; + inp.type = YAP_STRING_TERM | YAP_STRING_DATUM; out.type = YAP_STRING_CHARS; out.val.c = buf; out.max = sze - 1; out.enc = LOCAL_encoding; - if (!Yap_CVT_Text(&inp, &out PASS_REGS)) { - RECOVER_MACHINE_REGS(); + if (!Yap_CVT_Text(&inp, &out PASS_REGS)) { + RECOVER_MACHINE_REGS(); pop_text_stack(l); return NULL; } else { - RECOVER_MACHINE_REGS(); - if (buf == out.val.c) { - return buf; - } else { - return pop_output_text_stack(l, out.val.c); - } - }} + RECOVER_MACHINE_REGS(); + if (buf == out.val.c) { + return buf; + } else { + return pop_output_text_stack(l, out.val.c); + } + } +} /// write a a term to n user-provided buffer: make sure not tp @@ -2263,7 +2262,7 @@ X_API int YAP_WriteDynamicBuffer(YAP_Term t, char *buf, size_t sze, char *b; BACKUP_MACHINE_REGS(); - b = Yap_TermToString(t, enc, flags); + b = Yap_TermToBuffer(t, enc, flags); strncpy(buf, b, sze); buf[sze] = 0; RECOVER_MACHINE_REGS(); @@ -2271,376 +2270,411 @@ X_API int YAP_WriteDynamicBuffer(YAP_Term t, char *buf, size_t sze, } X_API char *YAP_CompileClause(Term t) { - CACHE_REGS + CACHE_REGS yamop *codeaddr; - Term mod = CurrentModule; - Term tn = TermNil; + Term mod = CurrentModule; + Term tn = TermNil; - BACKUP_MACHINE_REGS(); + BACKUP_MACHINE_REGS(); - /* allow expansion during stack initialization */ - LOCAL_ErrorMessage = NULL; - ARG1 = t; - YAPEnterCriticalSection(); - codeaddr = Yap_cclause(t, 0, mod, t); - if (codeaddr != NULL) { - t = Deref(ARG1); /* just in case there was an heap overflow */ - if (!Yap_addclause(t, codeaddr, TermAssertz, mod, &tn)) { - YAPLeaveCriticalSection(); - return LOCAL_ErrorMessage; + /* allow expansion during stack initialization */ + LOCAL_ErrorMessage = NULL; + ARG1 = t; + YAPEnterCriticalSection(); + codeaddr = Yap_cclause(t, 0, mod, t); + if (codeaddr != NULL) { + t = Deref(ARG1); /* just in case there was an heap overflow */ + if (!Yap_addclause(t, codeaddr, TermAssertz, mod, &tn)) { + YAPLeaveCriticalSection(); + return LOCAL_ErrorMessage; + } } - } - YAPLeaveCriticalSection(); + YAPLeaveCriticalSection(); - if (Yap_get_signal(YAP_CDOVF_SIGNAL)) { - if (!Yap_locked_growheap(FALSE, 0, NULL)) { - Yap_Error(RESOURCE_ERROR_HEAP, TermNil, "YAP failed to grow heap: %s", - LOCAL_ErrorMessage); + if (Yap_get_signal(YAP_CDOVF_SIGNAL)) { + if (!Yap_locked_growheap(FALSE, 0, NULL)) { + Yap_Error(RESOURCE_ERROR_HEAP, TermNil, "YAP failed to grow heap: %s", + LOCAL_ErrorMessage); + } } - } - RECOVER_MACHINE_REGS(); - return (LOCAL_ErrorMessage); + RECOVER_MACHINE_REGS(); + return (LOCAL_ErrorMessage); } static int yap_lineno = 0; /* do initial boot by consulting the file boot.yap */ static void do_bootfile(const char *b_file USES_REGS) { - Term t; - int bootfile, osno; - Functor functor_query = Yap_MkFunctor(Yap_LookupAtom("?-"), 1); - Functor functor_command1 = Yap_MkFunctor(Yap_LookupAtom(":-"), 1); + Term t; + int boot_stream, osno; + Functor functor_query = Yap_MkFunctor(Yap_LookupAtom("?-"), 1); + Functor functor_command1 = Yap_MkFunctor(Yap_LookupAtom(":-"), 1); - /* consult boot.pl */ + /* consult boot.pl */ char *full = malloc(YAP_FILENAME_MAX + 1); full[0] = '\0'; - /* the consult mode does not matter here, really */ - bootfile = YAP_InitConsult(YAP_BOOT_MODE, b_file, full, &osno); - if (bootfile < 0) { - fprintf(stderr, "[ FATAL ERROR: could not open bootfile %s ]\n", - b_file); - exit(1); - } -free(full); - do { - CACHE_REGS - YAP_Reset(YAP_FULL_RESET); + /* the consult mode does not matter here, really */ + boot_stream = YAP_InitConsult(YAP_BOOT_MODE, b_file, full, &osno); + if (boot_stream < 0) { + fprintf(stderr, "[ FATAL ERROR: could not open boot_stream %s ]\n", + b_file); + exit(1); + } + free(full); + do { + CACHE_REGS + YAP_Reset(YAP_FULL_RESET); Yap_StartSlots(); - t = YAP_ReadClauseFromStream(bootfile); + t = YAP_ReadClauseFromStream(boot_stream); // Yap_DebugPlWriteln(t); if (t == 0) { - fprintf(stderr, - "[ SYNTAX ERROR: while parsing bootfile %s at line %d ]\n", - b_file, yap_lineno); + fprintf(stderr, + "[ SYNTAX ERROR: while parsing boot_stream %s at line %d ]\n", + b_file, yap_lineno); } else if (YAP_IsVarTerm(t) || t == TermNil) { - fprintf(stderr, "[ line %d: term cannot be compiled ]", yap_lineno); + fprintf(stderr, "[ line %d: term cannot be compiled ]", yap_lineno); } else if (YAP_IsPairTerm(t)) { - fprintf(stderr, "[ SYSTEM ERROR: consult not allowed in boot file ]\n"); - fprintf(stderr, "error found at line %d and pos %d", yap_lineno, - fseek(GLOBAL_Stream[bootfile].file, 0L, SEEK_CUR)); + fprintf(stderr, "[ SYSTEM ERROR: consult not allowed in boot file ]\n"); + fprintf(stderr, "error found at line %d and pos %d", yap_lineno, + fseek(GLOBAL_Stream[boot_stream].file, 0L, SEEK_CUR)); } else if (IsApplTerm(t) && (FunctorOfTerm(t) == functor_query || FunctorOfTerm(t) == functor_command1)) { - YAP_RunGoalOnce(ArgOfTerm(1, t)); + YAP_RunGoalOnce(ArgOfTerm(1, t)); } else { - Term ts[2]; - char *ErrorMessage; - Functor fun = Yap_MkFunctor(Yap_LookupAtom("$prepare_clause"), 2); - PredEntry *pe = RepPredProp(PredPropByFunc(fun, PROLOG_MODULE)); + Term ts[2]; + char *ErrorMessage; + Functor fun = Yap_MkFunctor(Yap_LookupAtom("$prepare_clause"), 2); + PredEntry *pe = RepPredProp(PredPropByFunc(fun, PROLOG_MODULE)); - if (pe->OpcodeOfPred != UNDEF_OPCODE && pe->OpcodeOfPred != FAIL_OPCODE) { - ts[0] = t; - RESET_VARIABLE(ts + 1); - if (YAP_RunGoal(Yap_MkApplTerm(fun, 2, ts))) - t = ts[1]; - } - ErrorMessage = YAP_CompileClause(t); - if (ErrorMessage) { - fprintf(stderr, "%s", ErrorMessage); - } + if (pe->OpcodeOfPred != UNDEF_OPCODE && pe->OpcodeOfPred != FAIL_OPCODE) { + ts[0] = t; + RESET_VARIABLE(ts + 1); + if (YAP_RunGoal(Yap_MkApplTerm(fun, 2, ts))) + t = ts[1]; + } + ErrorMessage = YAP_CompileClause(t); + if (ErrorMessage) { + fprintf(stderr, "%s", ErrorMessage); + } } - } while (t != TermEof); + } while (t != TermEof); - YAP_EndConsult(bootfile, &osno); + YAP_EndConsult(boot_stream, &osno); #if DEBUG - if (Yap_output_msg) + if (Yap_output_msg) fprintf(stderr, "Boot loaded\n"); #endif - } +} - /** - YAP_DelayInit() +/** + YAP_DelayInit() - ensures initialization is done after engine creation. - It receives a pointer to function and a string describing - the module. - */ + ensures initialization is done after engine creation. + It receives a pointer to function and a string describing + the module. +*/ - X_API bool YAP_initialized = false; - static int n_mdelays = 0; - static YAP_delaymodule_t *m_delays; +X_API bool YAP_initialized = false; +static int n_mdelays = 0; +static YAP_delaymodule_t *m_delays; - X_API bool YAP_DelayInit(YAP_ModInit_t f, const char s[]) { - if (m_delays) { +X_API bool YAP_DelayInit(YAP_ModInit_t f, const char s[]) { + if (m_delays) { m_delays = realloc(m_delays, (n_mdelays + 1) * sizeof(YAP_delaymodule_t)); - } else { + } else { m_delays = malloc(sizeof(YAP_delaymodule_t)); - } - m_delays[n_mdelays].f = f; - m_delays[n_mdelays].s = s; - n_mdelays++; - return true; } + m_delays[n_mdelays].f = f; + m_delays[n_mdelays].s = s; + n_mdelays++; + return true; +} - bool Yap_LateInit(const char s[]) { - int i; - for (i = 0; i < n_mdelays; i++) { +bool Yap_LateInit(const char s[]) { + int i; + for (i = 0; i < n_mdelays; i++) { if (!strcmp(m_delays[i].s, s)) { - m_delays[i].f(); - return true; + m_delays[i].f(); + return true; } - } - return false; } + return false; +} - static void start_modules(void) { - Term cm = CurrentModule; - size_t i; - for (i = 0; i < n_mdelays; i++) { +static void start_modules(void) { + Term cm = CurrentModule; + size_t i; + for (i = 0; i < n_mdelays; i++) { CurrentModule = MkAtomTerm(YAP_LookupAtom(m_delays[i].s)); m_delays[i].f(); - } - CurrentModule = cm; } + CurrentModule = cm; +} - /// whether Yap is under control of some other system - bool Yap_embedded = true; +/// whether Yap is under control of some other system +bool Yap_embedded = true; - /* this routine is supposed to be called from an external program - that wants to control Yap */ +/* this routine is supposed to be called from an external program + that wants to control Yap */ - X_API YAP_file_type_t YAP_Init(YAP_init_args *yap_init) { - YAP_file_type_t restore_result = yap_init->boot_file_type; - bool do_bootstrap = (restore_result & YAP_CONSULT_MODE); - CELL Trail = 0, Stack = 0, Heap = 0, Atts = 0; - char *boot_file; - Int rc; - const char *yroot; - - boot_file = calloc(YAP_FILENAME_MAX + 1, 1); - /* ignore repeated calls to YAP_Init */ - if (YAP_initialized) +X_API YAP_file_type_t YAP_Init(YAP_init_args *yap_init) { + YAP_file_type_t restore_result = yap_init->boot_file_type; + bool do_bootstrap = (restore_result & YAP_CONSULT_MODE); + CELL Trail = 0, Stack = 0, Heap = 0, Atts = 0; + char *boot_file; + Int rc; + char *yroot; + if (YAP_initialized) return YAP_FOUND_BOOT_ERROR; - Yap_embedded = yap_init->Embedded; - Yap_page_size = Yap_InitPageSize(); /* init memory page size, required by + if (!LOCAL_TextBuffer) + LOCAL_TextBuffer = Yap_InitTextAllocator(); + + yroot = malloc(YAP_FILENAME_MAX + 1); + boot_file = malloc(YAP_FILENAME_MAX + 1); + /* ignore repeated calls to YAP_Init */ + Yap_embedded = yap_init->Embedded; + Yap_page_size = Yap_InitPageSize(); /* init memory page size, required by later functions */ #if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) - Yap_init_yapor_global_local_memory(); + Yap_init_yapor_global_local_memory(); #endif /* YAPOR_COPY || YAPOR_COW || YAPOR_SBA */ - if (!yap_init->Embedded) { + if (!yap_init->Embedded) { GLOBAL_PrologShouldHandleInterrupts = - !yap_init->PrologCannotHandleInterrupts; + !yap_init->PrologCannotHandleInterrupts; Yap_InitSysbits(0); /* init signal handling and time, required by later functions */ GLOBAL_argv = yap_init->Argv; GLOBAL_argc = yap_init->Argc; if (0 && ((YAP_QLY && yap_init->SavedState) || (YAP_BOOT_PL && (yap_init->YapPrologBootFile)))) { - yroot = "."; + strcpy(yroot, "."); } else { - yroot = BootFilePath; + strcpy(yroot, BootFile); } - } - if (yap_init->SavedState == NULL) { - yap_init->SavedState = YAP_STARTUP; - } - if (!LOCAL_TextBuffer) -LOCAL_TextBuffer = Yap_InitTextAllocator(); + } + char *tmp = NULL; + if (yap_init->SavedState == NULL) { + tmp = Malloc(strlen(YAP_STARTUP) + 1); + strncpy(tmp, YAP_STARTUP, strlen(YAP_STARTUP) + 1);; + } + #if __ANDROID__ - //if (yap_init->assetManager) - Yap_InitAssetManager( ); + +//if (yap_init->assetManager) + Yap_InitAssetManager(); + #endif #if USE_DL_MALLOC - if (yap_init->SavedState == NULL) - yap_init->SavedState = YAP_STARTUP; + if (yap_init->SavedState == NULL) + yap_init->SavedState = YAP_STARTUP; #else - yap_init->SavedState = Yap_findFile(yap_init->SavedState, YAP_STARTUP, yap_init->YapLibDir, - boot_file, true, YAP_QLY, true, true); + yap_init->SavedState = Yap_findFile(tmp, YAP_STARTUP, yap_init->YapLibDir, + boot_file, true, YAP_QLY, true, true); #endif - if (yap_init->SavedState == NULL) { + if (yap_init->SavedState == NULL) { restore_result = YAP_BOOT_PL; - } + } - if (restore_result == YAP_BOOT_PL) { + if (restore_result == YAP_BOOT_PL) { #if USE_DL_MALLOC - if (yap_init->YapPrologBootFile == NULL) + if (yap_init->YapPrologBootFile == NULL || + yap_init->YapPrologBootFile[0] == 0) yap_init->YapPrologBootFile = BootFile; -#else - - const char *s = Yap_findFile(yap_init->YapPrologBootFile, BootFile, yroot, boot_file, - true, YAP_BOOT_PL, true, true); - if (s && s[0] != '\0') strcpy(boot_file, s); -#endif - } - - if (yap_init->TrailSize == 0) { - if (Trail == 0) - Trail = DefTrailSpace; - } else { - Trail = yap_init->TrailSize; - } - // Atts = yap_init->AttsSize; - if (yap_init->StackSize == 0) { - Stack = DefStackSpace; - } else { - Stack = yap_init->StackSize; - } -#ifndef USE_SYSTEM_MALLOC - if (yap_init->HeapSize == 0) { - if (Heap == 0) - Heap = DefHeapSpace; - } else { - Heap = yap_init->HeapSize; - } -#endif - - Yap_InitWorkspace(yap_init, Heap, Stack, Trail, Atts, yap_init->MaxTableSpaceSize, - yap_init->NumberWorkers, yap_init->SchedulerLoop, - yap_init->DelayedReleaseLoad); - // - - CACHE_REGS - if (Yap_embedded) - if (yap_init->QuietMode) { - setVerbosity(TermSilent); - } - { - if (yap_init->YapPrologRCFile != NULL) { - /* - This must be done before restore, otherwise - restore will print out messages .... - */ - setBooleanGlobalPrologFlag(HALT_AFTER_CONSULT_FLAG, - yap_init->HaltAfterConsult); + strcpy(boot_file, BootFile); } - /* tell the system who should cope with interrupts */ +#else + strcpy(boot_file, BootFile); + const char *s = Yap_findFile(yap_init->YapPrologBootFile, + BootFile, yroot, boot_file, + true, YAP_BOOT_PL, true, true); + if (s && s[0] != '\0') { + strcpy(boot_file, s); + } +#endif + } + + if (yap_init->TrailSize == 0) { + if (Trail == 0) + Trail = DefTrailSpace; + } else { + Trail = yap_init->TrailSize; + } +// Atts = yap_init->AttsSize; + if (yap_init->StackSize == 0) { + Stack = DefStackSpace; + } else { + Stack = yap_init->StackSize; + } +#ifndef USE_SYSTEM_MALLOC + if (yap_init->HeapSize == 0) { + if (Heap == 0) + Heap = DefHeapSpace; + } else { + Heap = yap_init->HeapSize; + } +#endif + + Yap_InitWorkspace(yap_init, Heap, Stack, Trail, Atts, yap_init + ->MaxTableSpaceSize, + yap_init->NumberWorkers, yap_init->SchedulerLoop, + yap_init->DelayedReleaseLoad); +// + + CACHE_REGS + if (Yap_embedded) + if (yap_init->QuietMode) { + setVerbosity(TermSilent); + } + { + if (yap_init->YapPrologRCFile != NULL) { +/* + This must be done before restore, otherwise + restore will print out messages .... +*/ + setBooleanGlobalPrologFlag(HALT_AFTER_CONSULT_FLAG, + yap_init + ->HaltAfterConsult); + } +/* tell the system who should cope with interrupts */ Yap_ExecutionMode = yap_init->ExecutionMode; if (do_bootstrap) { - restore_result |= YAP_BOOT_PL; + restore_result |= + YAP_BOOT_PL; } else { // try always to boot from the saved state. - if (restore_result == YAP_QLY) { - if (!Yap_SavedInfo(yap_init->SavedState, yap_init->YapLibDir, &Trail, - &Stack, &Heap)) { - restore_result = YAP_BOOT_PL; - } else { - restore_result = - Yap_Restore(yap_init->SavedState, yap_init->YapLibDir); - } - if (restore_result == YAP_FOUND_BOOT_ERROR) { - restore_result = YAP_BOOT_PL; - } - } + if (restore_result == YAP_QLY) { + if (! + Yap_SavedInfo(yap_init + ->SavedState, yap_init->YapLibDir, &Trail, + &Stack, &Heap)) { + restore_result = YAP_BOOT_PL; + } else { + restore_result = + Yap_Restore(yap_init->SavedState, yap_init->YapLibDir); + } + if (restore_result == YAP_FOUND_BOOT_ERROR) { + restore_result = YAP_BOOT_PL; + } + } } GLOBAL_FAST_BOOT_FLAG = yap_init->FastBoot; #if defined(YAPOR) || defined(TABLING) + Yap_init_root_frames(); + #endif /* YAPOR || TABLING */ #ifdef YAPOR Yap_init_yapor_workers(); #if YAPOR_THREADS if (Yap_thread_self() != 0) { #else - if (worker_id != 0) { + if (worker_id != 0) { #endif #if defined(YAPOR_COPY) || defined(YAPOR_SBA) - /* - In the SBA we cannot just happily inherit registers - from the other workers - */ - Yap_InitYaamRegs(worker_id); + /* + In the SBA we cannot just happily inherit registers + from the other workers + */ + Yap_InitYaamRegs(worker_id); #endif /* YAPOR_COPY || YAPOR_SBA */ #ifndef YAPOR_THREADS - Yap_InitPreAllocCodeSpace(0); + Yap_InitPreAllocCodeSpace(0); #endif /* YAPOR_THREADS */ - /* slaves, waiting for work */ - CurrentModule = USER_MODULE; - P = GETWORK_FIRST_TIME; - Yap_exec_absmi(FALSE, YAP_EXEC_ABSMI); - Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, - "abstract machine unexpected exit (YAP_Init)"); - } + /* slaves, waiting for work */ + CurrentModule = USER_MODULE; + P = GETWORK_FIRST_TIME; + Yap_exec_absmi(FALSE, YAP_EXEC_ABSMI); + Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, + "abstract machine unexpected exit (YAP_Init)"); + } #endif /* YAPOR */ - RECOVER_MACHINE_REGS(); - } - /* make sure we do this after restore */ - if (yap_init->MaxStackSize) { - GLOBAL_AllowLocalExpansion = FALSE; - } else { - GLOBAL_AllowLocalExpansion = TRUE; - } - if (yap_init->MaxGlobalSize) { - GLOBAL_AllowGlobalExpansion = FALSE; - } else { - GLOBAL_AllowGlobalExpansion = TRUE; - } - if (yap_init->MaxTrailSize) { - GLOBAL_AllowTrailExpansion = FALSE; - } else { - GLOBAL_AllowTrailExpansion = TRUE; - } - if (yap_init->YapPrologRCFile) { - Yap_PutValue(AtomConsultOnBoot, - MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologRCFile))); - /* - This must be done again after restore, as yap_flags - has been overwritten .... - */ - setBooleanGlobalPrologFlag(HALT_AFTER_CONSULT_FLAG, - yap_init->HaltAfterConsult); - } - if (yap_init->YapPrologTopLevelGoal) { - Yap_PutValue(AtomTopLevelGoal, - MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologTopLevelGoal))); - } - if (yap_init->YapPrologGoal) { - Yap_PutValue(AtomInitGoal, - MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologGoal))); - } - if (yap_init->YapPrologAddPath) { - Yap_PutValue(AtomExtendFileSearchPath, - MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologAddPath))); - } - if (yap_init->YapShareDir) { - setAtomicGlobalPrologFlag(PROLOG_LIBRARY_DIRECTORY_FLAG, - MkAtomTerm(Yap_LookupAtom(yap_init->YapShareDir))); - } - if (yap_init->YapLibDir) { - setAtomicGlobalPrologFlag(PROLOG_FOREIGN_DIRECTORY_FLAG, - MkAtomTerm(Yap_LookupAtom(yap_init->YapLibDir))); - } - if (yap_init->QuietMode) { - setVerbosity(TermSilent); - } - if (restore_result == YAP_QLY) { - setAtomicGlobalPrologFlag(RESOURCE_DATABASE_FLAG, - MkAtomTerm(Yap_LookupAtom(yap_init->SavedState))); - LOCAL_PrologMode &= ~BootMode; - CurrentModule = LOCAL_SourceModule = USER_MODULE; - setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, true); - rc = YAP_QLY; - } else { - if (boot_file[0] == '\0') - strcpy(boot_file, BootFile); - do_bootfile(boot_file PASS_REGS); - setAtomicGlobalPrologFlag( - RESOURCE_DATABASE_FLAG, - MkAtomTerm(Yap_LookupAtom(boot_file))); - setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, false); - } - start_modules(); - YAP_initialized = true; - return YAP_BOOT_PL; - } + RECOVER_MACHINE_REGS(); + } +/* make sure we do this after restore */ + if (yap_init->MaxStackSize) { + GLOBAL_AllowLocalExpansion = FALSE; + } else { + GLOBAL_AllowLocalExpansion = TRUE; + } + if (yap_init->MaxGlobalSize) { + GLOBAL_AllowGlobalExpansion = FALSE; + } else { + GLOBAL_AllowGlobalExpansion = TRUE; + } + if (yap_init->MaxTrailSize) { + GLOBAL_AllowTrailExpansion = FALSE; + } else { + GLOBAL_AllowTrailExpansion = TRUE; + } + if (yap_init->YapPrologRCFile) { + Yap_PutValue(AtomConsultOnBoot, + MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologRCFile)) + ); +/* + This must be done again after restore, as yap_flags + has been overwritten .... +*/ + setBooleanGlobalPrologFlag(HALT_AFTER_CONSULT_FLAG, + yap_init + ->HaltAfterConsult); + } + if (yap_init->YapPrologTopLevelGoal) { + Yap_PutValue(AtomTopLevelGoal, + MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologTopLevelGoal)) + ); + } + if (yap_init->YapPrologGoal) { + Yap_PutValue(AtomInitGoal, + MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologGoal)) + ); + } + if (yap_init->YapPrologAddPath) { + Yap_PutValue(AtomExtendFileSearchPath, + MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologAddPath)) + ); + } + if (yap_init->YapShareDir) { + setAtomicGlobalPrologFlag(PROLOG_LIBRARY_DIRECTORY_FLAG, + MkAtomTerm(Yap_LookupAtom(yap_init->YapShareDir)) + ); + } + if (yap_init->YapLibDir) { + setAtomicGlobalPrologFlag(PROLOG_FOREIGN_DIRECTORY_FLAG, + MkAtomTerm(Yap_LookupAtom(yap_init->YapLibDir)) + ); + } + if (yap_init->QuietMode) { + setVerbosity(TermSilent); + } + if (restore_result == YAP_QLY) { + setAtomicGlobalPrologFlag(RESOURCE_DATABASE_FLAG, + MkAtomTerm(Yap_LookupAtom(yap_init->SavedState)) + ); + LOCAL_PrologMode &= + ~BootMode; + CurrentModule = LOCAL_SourceModule = USER_MODULE; + setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, + true); + rc = YAP_QLY; + } else { + if (boot_file[0] == '\0') + strcpy(boot_file, BootFile + ); + do_bootfile(boot_file PASS_REGS); + setAtomicGlobalPrologFlag( + RESOURCE_DATABASE_FLAG, + MkAtomTerm(Yap_LookupAtom(boot_file)) + ); + setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, + false); + } + + start_modules(); + + YAP_initialized = true; + return + YAP_BOOT_PL; +} #if (DefTrailSpace < MinTrailSpace) #undef DefTrailSpace @@ -2661,858 +2695,852 @@ LOCAL_TextBuffer = Yap_InitTextAllocator(); #define DEFAULT_SCHEDULERLOOP 10 #define DEFAULT_DELAYEDRELEASELOAD 3 - X_API YAP_file_type_t YAP_FastInit(char *saved_state, int argc, char *argv[]) { - YAP_init_args init_args; - YAP_file_type_t out; +X_API YAP_file_type_t YAP_FastInit(char *saved_state, int argc, char *argv[]) { + YAP_init_args init_args; + YAP_file_type_t out; - if ((out = Yap_InitDefaults(&init_args, saved_state, argc, argv)) != - YAP_FOUND_BOOT_ERROR) - out = YAP_Init(&init_args); - if (out == YAP_FOUND_BOOT_ERROR) { - Yap_Error(init_args.ErrorNo, TermNil, init_args.ErrorCause); - } - return out; - } + if ((out = Yap_InitDefaults(&init_args, saved_state, argc, argv)) != + YAP_FOUND_BOOT_ERROR) + out = YAP_Init(&init_args); + if (out == YAP_FOUND_BOOT_ERROR) { + Yap_Error(init_args.ErrorNo, TermNil, init_args.ErrorCause); + } + return out; +} - X_API void YAP_PutValue(Atom at, Term t) { Yap_PutValue(at, t); } +X_API void YAP_PutValue(YAP_Atom at, Term t) { Yap_PutValue(at, t); } - X_API Term YAP_GetValue(Atom at) { return (Yap_GetValue(at)); } +X_API Term YAP_GetValue(YAP_Atom at) { return (Yap_GetValue(at)); } - X_API int YAP_CompareTerms(Term t1, Term t2) { - return Yap_compare_terms(t1, t2); - } +X_API int YAP_CompareTerms(Term t1, Term t2) { + return Yap_compare_terms(t1, t2); +} - X_API int YAP_Reset(yap_reset_t mode) { - int res = TRUE; - BACKUP_MACHINE_REGS(); - res = Yap_Reset(mode); - RECOVER_MACHINE_REGS(); - return res; - } +X_API int YAP_Reset(yap_reset_t mode) { + int res = TRUE; + BACKUP_MACHINE_REGS(); + res = Yap_Reset(mode); + RECOVER_MACHINE_REGS(); + return res; +} - X_API void YAP_Exit(int retval) { Yap_exit(retval); } +X_API void YAP_Exit(int retval) { Yap_exit(retval); } - X_API int YAP_InitSocks(const char *host, long port) { return 0; } +X_API int YAP_InitSocks(const char *host, long port) { return 0; } - X_API void YAP_SetOutputMessage(void) { +X_API void YAP_SetOutputMessage(void) { #if DEBUG - Yap_output_msg = TRUE; + Yap_output_msg = TRUE; #endif - } +} - X_API int YAP_StreamToFileNo(Term t) { return (Yap_StreamToFileNo(t)); } +X_API int YAP_StreamToFileNo(Term t) { return (Yap_StreamToFileNo(t)); } - X_API void YAP_CloseAllOpenStreams(void) { - BACKUP_H(); +X_API void YAP_CloseAllOpenStreams(void) { + BACKUP_H(); - Yap_CloseStreams(FALSE); + Yap_CloseStreams(FALSE); - RECOVER_H(); - } + RECOVER_H(); +} - X_API void YAP_FlushAllStreams(void) { - BACKUP_H(); +X_API void YAP_FlushAllStreams(void) { + BACKUP_H(); - // VSC?? Yap_FlushStreams(); + // VSC?? Yap_FlushStreams(); - RECOVER_H(); - } + RECOVER_H(); +} - X_API void YAP_Throw(Term t) { - BACKUP_MACHINE_REGS(); - Yap_JumpToEnv(t); - RECOVER_MACHINE_REGS(); - } +X_API void YAP_Throw(Term t) { + BACKUP_MACHINE_REGS(); + Yap_JumpToEnv(t); + RECOVER_MACHINE_REGS(); +} - X_API void YAP_AsyncThrow(Term t) { - CACHE_REGS - BACKUP_MACHINE_REGS(); - LOCAL_PrologMode |= AsyncIntMode; - Yap_JumpToEnv(t); - LOCAL_PrologMode &= ~AsyncIntMode; - RECOVER_MACHINE_REGS(); - } +X_API void YAP_AsyncThrow(Term t) { + CACHE_REGS + BACKUP_MACHINE_REGS(); + LOCAL_PrologMode |= AsyncIntMode; + Yap_JumpToEnv(t); + LOCAL_PrologMode &= ~AsyncIntMode; + RECOVER_MACHINE_REGS(); +} - X_API void YAP_Halt(int i) { Yap_exit(i); } +X_API void YAP_Halt(int i) { Yap_exit(i); } - X_API CELL *YAP_TopOfLocalStack(void) { - CACHE_REGS - return (ASP); - } +X_API CELL *YAP_TopOfLocalStack(void) { + CACHE_REGS + return (ASP); +} - X_API void *YAP_Predicate(Atom a, UInt arity, Term m) { - if (arity == 0) { - return ((void *) RepPredProp(PredPropByAtom(a, m))); - } else { - Functor f = Yap_MkFunctor(a, arity); - return ((void *) RepPredProp(PredPropByFunc(f, m))); - } - } +X_API void *YAP_Predicate(YAP_Atom a, UInt arity, Term m) { + if (arity == 0) { + return ((void *) RepPredProp(PredPropByAtom(a, m))); + } else { + Functor f = Yap_MkFunctor(a, arity); + return ((void *) RepPredProp(PredPropByFunc(f, m))); + } +} - X_API void YAP_PredicateInfo(void *p, Atom *a, UInt *arity, Term *m) { - PredEntry *pd = (PredEntry *) p; - if (pd->ArityOfPE) { - *arity = pd->ArityOfPE; - *a = NameOfFunctor(pd->FunctorOfPred); - } else { - *arity = 0; - *a = (Atom) (pd->FunctorOfPred); - } - if (pd->ModuleOfPred) - *m = pd->ModuleOfPred; - else - *m = TermProlog; - } +X_API void YAP_PredicateInfo(void *p, YAP_Atom *a, UInt *arity, Term *m) { + PredEntry *pd = (PredEntry *) p; + if (pd->ArityOfPE) { + *arity = pd->ArityOfPE; + *a = NameOfFunctor(pd->FunctorOfPred); + } else { + *arity = 0; + *a = (Atom) (pd->FunctorOfPred); + } + if (pd->ModuleOfPred) + *m = pd->ModuleOfPred; + else + *m = TermProlog; +} - X_API void YAP_UserCPredicate(const char *name, CPredicate def, arity_t arity) { - Yap_InitCPred(name, arity, def, UserCPredFlag); - } +X_API void YAP_UserCPredicate(const char *name, YAP_UserCPred def, YAP_Arity arity) { + Yap_InitCPred(name, arity, (CPredicate)def, UserCPredFlag); +} - X_API void YAP_UserBackCPredicate_(const char *name, CPredicate init, - CPredicate cont, arity_t arity, - arity_t extra) { - Yap_InitCPredBackCut(name, arity, extra, init, cont, NULL, UserCPredFlag); - } +X_API void YAP_UserBackCPredicate_(const char *name, YAP_UserCPred init, + YAP_UserCPred cont, YAP_Arity arity, + YAP_Arity extra) { + Yap_InitCPredBackCut(name, arity, extra, (CPredicate)init, (CPredicate)cont, NULL, UserCPredFlag); +} - X_API void YAP_UserBackCutCPredicate(const char *name, CPredicate init, - CPredicate cont, CPredicate cut, - arity_t arity, arity_t extra) { - Yap_InitCPredBackCut(name, arity, extra, init, cont, cut, UserCPredFlag); - } +X_API void YAP_UserBackCutCPredicate(const char *name, YAP_UserCPred init, + YAP_UserCPred cont, YAP_UserCPred cut, + YAP_Arity arity, YAP_Arity extra) { + Yap_InitCPredBackCut(name, arity, extra, (CPredicate)init, + (CPredicate)cont, (CPredicate)cut, UserCPredFlag); +} - X_API void YAP_UserBackCPredicate(const char *name, CPredicate init, - CPredicate cont, arity_t arity, - arity_t extra) { - Yap_InitCPredBackCut(name, arity, extra, init, cont, NULL, UserCPredFlag); - } +X_API void YAP_UserBackCPredicate(const char *name, YAP_UserCPred init, + YAP_UserCPred cont, arity_t arity, + arity_t extra) { + Yap_InitCPredBackCut(name, arity, extra, (CPredicate)init, (CPredicate)cont, NULL, UserCPredFlag); +} - X_API void YAP_UserCPredicateWithArgs(const char *a, CPredicate f, - arity_t arity, Term mod) { - CACHE_REGS - PredEntry *pe; - Term cm = CurrentModule; - CurrentModule = mod; - YAP_UserCPredicate(a, f, arity); - if (arity == 0) { - pe = RepPredProp(PredPropByAtom(Yap_LookupAtom(a), mod)); - } else { - Functor f = Yap_MkFunctor(Yap_LookupAtom(a), arity); - pe = RepPredProp(PredPropByFunc(f, mod)); - } - pe->PredFlags |= CArgsPredFlag; - CurrentModule = cm; - } +X_API void YAP_UserCPredicateWithArgs(const char *a, YAP_UserCPred f, + arity_t arity, Term mod) { + CACHE_REGS + Term cm = CurrentModule; + CurrentModule = mod; + Yap_InitCPred(a, arity, (CPredicate)f, UserCPredFlag|CArgsPredFlag ); + CurrentModule = cm; +} - X_API Term YAP_CurrentModule(void) { - CACHE_REGS - return (CurrentModule); - } +X_API Term YAP_CurrentModule(void) { + CACHE_REGS + return (CurrentModule); +} - X_API Term YAP_SetCurrentModule(Term new) { - CACHE_REGS - Term omod = CurrentModule; - LOCAL_SourceModule = CurrentModule = new; - return omod; - } +X_API Term YAP_SetCurrentModule(Term new) { + CACHE_REGS + Term omod = CurrentModule; + LOCAL_SourceModule = CurrentModule = new; + return omod; +} - X_API Term YAP_CreateModule(Atom at) { - Term t; - WRITE_LOCK(RepAtom(at)->ARWLock); - t = Yap_Module(MkAtomTerm(at)); - WRITE_UNLOCK(RepAtom(at)->ARWLock); - return t; - } +X_API Term YAP_CreateModule(YAP_Atom at) { + Term t; + WRITE_LOCK(RepAtom(at)->ARWLock); + t = Yap_Module(MkAtomTerm(at)); + WRITE_UNLOCK(RepAtom(at)->ARWLock); + return t; +} - X_API Term YAP_StripModule(Term t, Term *modp) { - return Yap_StripModule(t, modp); - } +X_API Term YAP_StripModule(Term t, Term *modp) { + return Yap_StripModule(t, modp); +} - X_API int YAP_ThreadSelf(void) { +X_API int YAP_ThreadSelf(void) { #if THREADS - return Yap_thread_self(); + return Yap_thread_self(); #else - return -2; + return -2; #endif - } +} - X_API int YAP_ThreadCreateEngine(struct YAP_thread_attr_struct *attr) { +X_API int YAP_ThreadCreateEngine(struct YAP_thread_attr_struct *attr) { #if THREADS - return Yap_thread_create_engine(attr); + return Yap_thread_create_engine(attr); #else - return -1; + return -1; #endif - } +} - X_API int YAP_ThreadAttachEngine(int wid) { +X_API int YAP_ThreadAttachEngine(int wid) { #if THREADS - return Yap_thread_attach_engine(wid); + return Yap_thread_attach_engine(wid); #else - return FALSE; + return FALSE; #endif - } +} - X_API int YAP_ThreadDetachEngine(int wid) { +X_API int YAP_ThreadDetachEngine(int wid) { #if THREADS - return Yap_thread_detach_engine(wid); + return Yap_thread_detach_engine(wid); #else - return FALSE; + return FALSE; #endif - } +} - X_API int YAP_ThreadDestroyEngine(int wid) { +X_API int YAP_ThreadDestroyEngine(int wid) { #if THREADS - return Yap_thread_destroy_engine(wid); + return Yap_thread_destroy_engine(wid); #else - return FALSE; + return FALSE; #endif - } +} - X_API Term YAP_TermNil(void) { return TermNil; } +X_API Term YAP_TermNil(void) { return TermNil; } - X_API int YAP_IsTermNil(Term t) { return t == TermNil; } +X_API int YAP_IsTermNil(Term t) { return t == TermNil; } - X_API int YAP_AtomGetHold(Atom at) { return Yap_AtomIncreaseHold(at); } +X_API int YAP_AtomGetHold(YAP_Atom at) { return Yap_AtomIncreaseHold(at); } - X_API int YAP_AtomReleaseHold(Atom at) { return Yap_AtomDecreaseHold(at); } +X_API int YAP_AtomReleaseHold(YAP_Atom at) { return Yap_AtomDecreaseHold(at); } - X_API Agc_hook YAP_AGCRegisterHook(Agc_hook hook) { - Agc_hook old = GLOBAL_AGCHook; - GLOBAL_AGCHook = hook; - return old; - } +X_API YAP_agc_hook YAP_AGCRegisterHook(YAP_agc_hook hook) { + YAP_agc_hook old = (YAP_agc_hook)GLOBAL_AGCHook; + GLOBAL_AGCHook = (Agc_hook)hook; + return old; +} - X_API int YAP_HaltRegisterHook(HaltHookFunc hook, void *closure) { - return Yap_HaltRegisterHook(hook, closure); - } +X_API int YAP_HaltRegisterHook(HaltHookFunc hook, void *closure) { + return Yap_HaltRegisterHook(hook, closure); +} - X_API char *YAP_cwd(void) { - CACHE_REGS - char *buf = NULL; - int len; - if (!Yap_getcwd(LOCAL_FileNameBuf, YAP_FILENAME_MAX)) - return FALSE; - len = strlen(LOCAL_FileNameBuf); - buf = Yap_AllocCodeSpace(len + 1); - if (!buf) - return NULL; - strncpy(buf, LOCAL_FileNameBuf, len); - return buf; - } +X_API char *YAP_cwd(void) { + CACHE_REGS + char *buf = NULL; + int len; + if (!Yap_getcwd(LOCAL_FileNameBuf, YAP_FILENAME_MAX)) + return FALSE; + len = strlen(LOCAL_FileNameBuf); + buf = Yap_AllocCodeSpace(len + 1); + if (!buf) + return NULL; + strncpy(buf, LOCAL_FileNameBuf, len); + return buf; +} - X_API Term YAP_FloatsToList(double *dblp, size_t sz) { - CACHE_REGS - Term t; - CELL *oldH; - BACKUP_H(); +X_API Term YAP_FloatsToList(double *dblp, size_t sz) { + CACHE_REGS + Term t; + CELL *oldH; + BACKUP_H(); - if (!sz) - return TermNil; - while (ASP - 1024 < HR + sz * (2 + 2 + SIZEOF_DOUBLE / SIZEOF_INT_P)) { - if ((CELL *) dblp > H0 && (CELL *) dblp < HR) { + if (!sz) + return TermNil; + while (ASP - 1024 < HR + sz * (2 + 2 + SIZEOF_DOUBLE / SIZEOF_INT_P)) { + if ((CELL *) dblp > H0 && (CELL *) dblp < HR) { /* we are in trouble */ LOCAL_OpenArray = (CELL *) dblp; - } - if (!Yap_dogc(0, NULL PASS_REGS)) { + } + if (!Yap_dogc(0, NULL PASS_REGS)) { RECOVER_H(); return 0L; - } - dblp = (double *) LOCAL_OpenArray; - LOCAL_OpenArray = NULL; - } - t = AbsPair(HR); - while (sz) { - oldH = HR; - HR += 2; - oldH[0] = MkFloatTerm(*dblp++); - oldH[1] = AbsPair(HR); - sz--; - } - oldH[1] = TermNil; - RECOVER_H(); - return t; - } + } + dblp = (double *) LOCAL_OpenArray; + LOCAL_OpenArray = NULL; + } + t = AbsPair(HR); + while (sz) { + oldH = HR; + HR += 2; + oldH[0] = MkFloatTerm(*dblp++); + oldH[1] = AbsPair(HR); + sz--; + } + oldH[1] = TermNil; + RECOVER_H(); + return t; +} - X_API Int YAP_ListToFloats(Term t, double *dblp, size_t sz) { - size_t i = 0; +X_API Int YAP_ListToFloats(Term t, double *dblp, size_t sz) { + size_t i = 0; - t = Deref(t); - do { - Term hd; - if (IsVarTerm(t)) + t = Deref(t); + do { + Term hd; + if (IsVarTerm(t)) return -1; - if (t == TermNil) + if (t == TermNil) return i; - if (!IsPairTerm(t)) + if (!IsPairTerm(t)) return -1; - hd = HeadOfTerm(t); - if (IsFloatTerm(hd)) { + hd = HeadOfTerm(t); + if (IsFloatTerm(hd)) { dblp[i++] = FloatOfTerm(hd); - } else { + } else { extern double Yap_gmp_to_float(Term hd); if (IsIntTerm(hd)) - dblp[i++] = IntOfTerm(hd); + dblp[i++] = IntOfTerm(hd); else if (IsLongIntTerm(hd)) - dblp[i++] = LongIntOfTerm(hd); + dblp[i++] = LongIntOfTerm(hd); #if USE_GMP else if (IsBigIntTerm(hd)) - dblp[i++] = Yap_gmp_to_float(hd); + dblp[i++] = Yap_gmp_to_float(hd); #endif else - return -1; - } - if (i == sz) + return -1; + } + if (i == sz) return sz; - t = TailOfTerm(t); - } while (TRUE); - } + t = TailOfTerm(t); + } while (TRUE); +} - X_API Term YAP_IntsToList(Int *dblp, size_t sz) { - CACHE_REGS - Term t; - CELL *oldH; - BACKUP_H(); +X_API Term YAP_IntsToList(Int *dblp, size_t sz) { + CACHE_REGS + Term t; + CELL *oldH; + BACKUP_H(); - if (!sz) - return TermNil; - while (ASP - 1024 < HR + sz * 3) { - if ((CELL *) dblp > H0 && (CELL *) dblp < HR) { + if (!sz) + return TermNil; + while (ASP - 1024 < HR + sz * 3) { + if ((CELL *) dblp > H0 && (CELL *) dblp < HR) { /* we are in trouble */ LOCAL_OpenArray = (CELL *) dblp; - } - if (!Yap_dogc(0, NULL PASS_REGS)) { + } + if (!Yap_dogc(0, NULL PASS_REGS)) { RECOVER_H(); return 0L; - } - dblp = (Int *) LOCAL_OpenArray; - LOCAL_OpenArray = NULL; - } - t = AbsPair(HR); - while (sz) { - oldH = HR; - HR += 2; - oldH[0] = MkIntegerTerm(*dblp++); - oldH[1] = AbsPair(HR); - sz--; - } - oldH[1] = TermNil; - RECOVER_H(); - return t; - } + } + dblp = (Int *) LOCAL_OpenArray; + LOCAL_OpenArray = NULL; + } + t = AbsPair(HR); + while (sz) { + oldH = HR; + HR += 2; + oldH[0] = MkIntegerTerm(*dblp++); + oldH[1] = AbsPair(HR); + sz--; + } + oldH[1] = TermNil; + RECOVER_H(); + return t; +} - X_API Int YAP_ListToInts(Term t, Int *dblp, size_t sz) { - size_t i = 0; +X_API Int YAP_ListToInts(Term t, Int *dblp, size_t sz) { + size_t i = 0; - t = Deref(t); - do { - Term hd; - if (IsVarTerm(t)) + t = Deref(t); + do { + Term hd; + if (IsVarTerm(t)) return -1; - if (t == TermNil) + if (t == TermNil) return i; - if (!IsPairTerm(t)) + if (!IsPairTerm(t)) return -1; - hd = HeadOfTerm(t); - if (!IsIntTerm(hd)) + hd = HeadOfTerm(t); + if (!IsIntTerm(hd)) return -1; - dblp[i++] = IntOfTerm(hd); - if (i == sz) + dblp[i++] = IntOfTerm(hd); + if (i == sz) return sz; - t = TailOfTerm(t); - } while (TRUE); - } + t = TailOfTerm(t); + } while (TRUE); +} - X_API Term YAP_OpenList(int n) { - CACHE_REGS - Term t; - BACKUP_H(); +X_API Term YAP_OpenList(int n) { + CACHE_REGS + Term t; + BACKUP_H(); - while (HR + 2 * n > ASP - 1024) { - if (!Yap_dogc(0, NULL PASS_REGS)) { + while (HR + 2 * n > ASP - 1024) { + if (!Yap_dogc(0, NULL PASS_REGS)) { RECOVER_H(); return FALSE; - } - } - t = AbsPair(HR); - HR += 2 * n; + } + } + t = AbsPair(HR); + HR += 2 * n; - RECOVER_H(); - return t; - } + RECOVER_H(); + return t; +} - X_API Term YAP_ExtendList(Term t0, Term inp) { - Term t; - CELL *ptr = RepPair(t0); - BACKUP_H(); +X_API Term YAP_ExtendList(Term t0, Term inp) { + Term t; + CELL *ptr = RepPair(t0); + BACKUP_H(); - ptr[0] = inp; - ptr[1] = AbsPair(ptr + 2); - t = AbsPair(ptr + 2); + ptr[0] = inp; + ptr[1] = AbsPair(ptr + 2); + t = AbsPair(ptr + 2); - RECOVER_H(); - return t; - } + RECOVER_H(); + return t; +} - X_API int YAP_CloseList(Term t0, Term tail) { - CELL *ptr = RepPair(t0); +X_API int YAP_CloseList(Term t0, Term tail) { + CELL *ptr = RepPair(t0); - RESET_VARIABLE(ptr - 1); - if (!Yap_unify((Term) (ptr - 1), tail)) - return FALSE; - return TRUE; - } + RESET_VARIABLE(ptr - 1); + if (!Yap_unify((Term) (ptr - 1), tail)) + return FALSE; + return TRUE; +} - X_API int YAP_IsAttVar(Term t) { - CACHE_REGS - t = Deref(t); - if (!IsVarTerm(t)) - return FALSE; - return IsAttVar(VarOfTerm(t)); - } +X_API int YAP_IsAttVar(Term t) { + CACHE_REGS + t = Deref(t); + if (!IsVarTerm(t)) + return FALSE; + return IsAttVar(VarOfTerm(t)); +} - X_API Term YAP_AttsOfVar(Term t) { - CACHE_REGS - attvar_record *attv; +X_API Term YAP_AttsOfVar(Term t) { + CACHE_REGS + attvar_record *attv; - t = Deref(t); - if (!IsVarTerm(t)) - return TermNil; - if (!IsAttVar(VarOfTerm(t))) - return TermNil; - attv = RepAttVar(VarOfTerm(t)); - return attv->Atts; - } + t = Deref(t); + if (!IsVarTerm(t)) + return TermNil; + if (!IsAttVar(VarOfTerm(t))) + return TermNil; + attv = RepAttVar(VarOfTerm(t)); + return attv->Atts; +} - X_API int YAP_FileNoFromStream(Term t) { +X_API int YAP_FileNoFromStream(Term t) { - t = Deref(t); - if (IsVarTerm(t)) - return -1; - return Yap_StreamToFileNo(t); - } + t = Deref(t); + if (IsVarTerm(t)) + return -1; + return Yap_StreamToFileNo(t); +} - X_API void *YAP_FileDescriptorFromStream(Term t) { +X_API void *YAP_FileDescriptorFromStream(Term t) { - t = Deref(t); - if (IsVarTerm(t)) - return NULL; - return Yap_FileDescriptorFromStream(t); - } + t = Deref(t); + if (IsVarTerm(t)) + return NULL; + return Yap_FileDescriptorFromStream(t); +} - X_API void *YAP_Record(Term t) { - DBTerm *dbterm; - DBRecordList *dbt; +X_API void *YAP_Record(Term t) { + DBTerm *dbterm; + DBRecordList *dbt; - dbterm = Yap_StoreTermInDB(Deref(t), 0); - if (dbterm == NULL) - return NULL; - dbt = (struct record_list *) Yap_AllocCodeSpace(sizeof(struct record_list)); - while (dbt == NULL) { - if (!Yap_growheap(FALSE, sizeof(struct record_list), NULL)) { + dbterm = Yap_StoreTermInDB(Deref(t), 0); + if (dbterm == NULL) + return NULL; + dbt = (struct record_list *) Yap_AllocCodeSpace(sizeof(struct record_list)); + while (dbt == NULL) { + if (!Yap_growheap(FALSE, sizeof(struct record_list), NULL)) { /* be a good neighbor */ Yap_FreeCodeSpace((void *) dbterm); Yap_Error(RESOURCE_ERROR_HEAP, TermNil, "using YAP_Record"); return NULL; - } - } - if (Yap_Records) { - Yap_Records->prev_rec = dbt; - } - dbt->next_rec = Yap_Records; - dbt->prev_rec = NULL; - dbt->dbrecord = dbterm; - Yap_Records = dbt; - return dbt; - } + } + } + if (Yap_Records) { + Yap_Records->prev_rec = dbt; + } + dbt->next_rec = Yap_Records; + dbt->prev_rec = NULL; + dbt->dbrecord = dbterm; + Yap_Records = dbt; + return dbt; +} - X_API Term YAP_Recorded(void *handle) { - CACHE_REGS - Term t; - DBTerm *dbterm = ((DBRecordList *) handle)->dbrecord; +X_API Term YAP_Recorded(void *handle) { + CACHE_REGS + Term t; + DBTerm *dbterm = ((DBRecordList *) handle)->dbrecord; - BACKUP_MACHINE_REGS(); - do { - LOCAL_Error_TYPE = YAP_NO_ERROR; - t = Yap_FetchTermFromDB(dbterm); - if (LOCAL_Error_TYPE == YAP_NO_ERROR) { + BACKUP_MACHINE_REGS(); + do { + LOCAL_Error_TYPE = YAP_NO_ERROR; + t = Yap_FetchTermFromDB(dbterm); + if (LOCAL_Error_TYPE == YAP_NO_ERROR) { RECOVER_MACHINE_REGS(); return t; - } else if (LOCAL_Error_TYPE == RESOURCE_ERROR_ATTRIBUTED_VARIABLES) { + } else if (LOCAL_Error_TYPE == RESOURCE_ERROR_ATTRIBUTED_VARIABLES) { LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(RESOURCE_ERROR_ATTRIBUTED_VARIABLES, TermNil, - LOCAL_ErrorMessage); - RECOVER_MACHINE_REGS(); - return FALSE; + Yap_Error(RESOURCE_ERROR_ATTRIBUTED_VARIABLES, TermNil, + LOCAL_ErrorMessage); + RECOVER_MACHINE_REGS(); + return FALSE; } - } else { + } else { LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growstack(dbterm->NOfCells * CellSize)) { - Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage); - RECOVER_MACHINE_REGS(); - return FALSE; + Yap_Error(RESOURCE_ERROR_STACK, TermNil, LOCAL_ErrorMessage); + RECOVER_MACHINE_REGS(); + return FALSE; } - } - } while (t == (CELL) 0); - RECOVER_MACHINE_REGS(); - return t; - } + } + } while (t == (CELL) 0); + RECOVER_MACHINE_REGS(); + return t; +} - X_API int YAP_Erase(void *handle) { - DBRecordList *dbr = (DBRecordList *) handle; - if (dbr->next_rec) - dbr->next_rec->prev_rec = dbr->prev_rec; - if (dbr->prev_rec) - dbr->prev_rec->next_rec = dbr->next_rec; - else if (Yap_Records == dbr) { - Yap_Records = dbr->next_rec; - } - Yap_ReleaseTermFromDB(dbr->dbrecord); - Yap_FreeCodeSpace(handle); - return 1; - } +X_API int YAP_Erase(void *handle) { + DBRecordList *dbr = (DBRecordList *) handle; + if (dbr->next_rec) + dbr->next_rec->prev_rec = dbr->prev_rec; + if (dbr->prev_rec) + dbr->prev_rec->next_rec = dbr->next_rec; + else if (Yap_Records == dbr) { + Yap_Records = dbr->next_rec; + } + Yap_ReleaseTermFromDB(dbr->dbrecord); + Yap_FreeCodeSpace(handle); + return 1; +} - X_API yhandle_t YAP_ArgsToSlots(int n) { - CACHE_REGS - return Yap_NewSlots(n); - } +X_API yhandle_t YAP_ArgsToSlots(int n) { + CACHE_REGS + return Yap_NewSlots(n); +} - X_API void YAP_SlotsToArgs(int n, yhandle_t slot) { - CACHE_REGS - CELL *ptr0 = Yap_AddressFromSlot(slot), *ptr1 = &ARG1; - while (n--) { - *ptr1++ = *ptr0++; - } - } +X_API void YAP_SlotsToArgs(int n, yhandle_t slot) { + CACHE_REGS + CELL *ptr0 = Yap_AddressFromSlot(slot), *ptr1 = &ARG1; + while (n--) { + *ptr1++ = *ptr0++; + } +} - X_API void YAP_signal(int sig) { Yap_signal(sig); } +X_API void YAP_signal(int sig) { Yap_signal(sig); } - X_API int YAP_SetYAPFlag(Term flag, Term val) { return setYapFlag(flag, val); } +X_API int YAP_SetYAPFlag(Term flag, Term val) { return setYapFlag(flag, val); } - /* yhandle_t YAP_VarSlotToNumber(yhandle_t) */ - X_API yhandle_t YAP_VarSlotToNumber(yhandle_t s) { - CACHE_REGS - Term *t = (CELL *) Deref(Yap_GetFromSlot(s)); - if (t < HR) - return t - H0; - return t - LCL0; - } +/* yhandle_t YAP_VarSlotToNumber(yhandle_t) */ +X_API yhandle_t YAP_VarSlotToNumber(yhandle_t s) { + CACHE_REGS + Term *t = (CELL *) Deref(Yap_GetFromSlot(s)); + if (t < HR) + return t - H0; + return t - LCL0; +} - /* Term YAP_ModuleUser() */ - X_API Term YAP_ModuleUser(void) { return MkAtomTerm(AtomUser); } +/* Term YAP_ModuleUser() */ +X_API Term YAP_ModuleUser(void) { return MkAtomTerm(AtomUser); } - /* int YAP_PredicateHasClauses() */ - X_API yhandle_t YAP_NumberOfClausesForPredicate(PredEntry *pe) { - return pe->cs.p_code.NOfClauses; - } +/* int YAP_PredicateHasClauses() */ +X_API YAP_handle_t YAP_NumberOfClausesForPredicate(YAP_PredEntryPtr ape) { + PredEntry *pe = ape; + return pe->cs.p_code.NOfClauses; +} - X_API int YAP_MaxOpPriority(Atom at, Term module) { - AtomEntry *ae = RepAtom(at); - OpEntry *info; - WRITE_LOCK(ae->ARWLock); - info = Yap_GetOpPropForAModuleHavingALock(ae, module); - if (!info) { - WRITE_UNLOCK(ae->ARWLock); - return 0; - } - int ret = info->Prefix; - if (info->Infix > ret) - ret = info->Infix; - if (info->Posfix > ret) - ret = info->Posfix; - WRITE_UNLOCK(ae->ARWLock); - return ret; - } +X_API int YAP_MaxOpPriority(YAP_Atom at, Term module) { + AtomEntry *ae = RepAtom(at); + OpEntry *info; + WRITE_LOCK(ae->ARWLock); + info = Yap_GetOpPropForAModuleHavingALock(ae, module); + if (!info) { + WRITE_UNLOCK(ae->ARWLock); + return 0; + } + int ret = info->Prefix; + if (info->Infix > ret) + ret = info->Infix; + if (info->Posfix > ret) + ret = info->Posfix; + WRITE_UNLOCK(ae->ARWLock); + return ret; +} - X_API int YAP_OpInfo(Atom at, Term module, int opkind, int *yap_type, int *prio) { - AtomEntry *ae = RepAtom(at); - OpEntry *info; - int n; +X_API int YAP_OpInfo(YAP_Atom at, Term module, int opkind, int *yap_type, int *prio) { + AtomEntry *ae = RepAtom(at); + OpEntry *info; + int n; - WRITE_LOCK(ae->ARWLock); - info = Yap_GetOpPropForAModuleHavingALock(ae, module); - if (!info) { - /* try system operators */ - info = Yap_GetOpPropForAModuleHavingALock(ae, PROLOG_MODULE); - if (!info) { + WRITE_LOCK(ae->ARWLock); + info = Yap_GetOpPropForAModuleHavingALock(ae, module); + if (!info) { + /* try system operators */ + info = Yap_GetOpPropForAModuleHavingALock(ae, PROLOG_MODULE); + if (!info) { WRITE_UNLOCK(ae->ARWLock); return 0; - } - } - if (opkind == PREFIX_OP) { - SMALLUNSGN p = info->Prefix; - if (!p) { + } + } + if (opkind == PREFIX_OP) { + SMALLUNSGN p = info->Prefix; + if (!p) { WRITE_UNLOCK(ae->ARWLock); return FALSE; - } - if (p & DcrrpFlag) { + } + if (p & DcrrpFlag) { n = 6; *prio = (p ^ DcrrpFlag); - } else { + } else { n = 7; *prio = p; - } - } else if (opkind == INFIX_OP) { - SMALLUNSGN p = info->Infix; - if (!p) { + } + } else if (opkind == INFIX_OP) { + SMALLUNSGN p = info->Infix; + if (!p) { WRITE_UNLOCK(ae->ARWLock); return FALSE; - } - if ((p & DcrrpFlag) && (p & DcrlpFlag)) { + } + if ((p & DcrrpFlag) && (p & DcrlpFlag)) { n = 1; *prio = (p ^ (DcrrpFlag | DcrlpFlag)); - } else if (p & DcrrpFlag) { + } else if (p & DcrrpFlag) { n = 3; *prio = (p ^ DcrrpFlag); - } else if (p & DcrlpFlag) { + } else if (p & DcrlpFlag) { n = 2; *prio = (p ^ DcrlpFlag); - } else { + } else { n = 4; *prio = p; - } - } else { - SMALLUNSGN p = info->Posfix; - if (p & DcrlpFlag) { + } + } else { + SMALLUNSGN p = info->Posfix; + if (p & DcrlpFlag) { n = 4; *prio = (p ^ DcrlpFlag); - } else { + } else { n = 5; *prio = p; - } - } - *yap_type = n; - WRITE_UNLOCK(ae->ARWLock); - return 1; - } + } + } + *yap_type = n; + WRITE_UNLOCK(ae->ARWLock); + return 1; +} - X_API int YAP_Argv(char ***argvp) { - if (argvp) { - *argvp = GLOBAL_argv; - } - return GLOBAL_argc; - } +X_API int YAP_Argv(char ***argvp) { + if (argvp) { + *argvp = GLOBAL_argv; + } + return GLOBAL_argc; +} - X_API YAP_tag_t YAP_TagOfTerm(Term t) { - if (IsVarTerm(t)) { - CELL *pt = VarOfTerm(t); - if (IsUnboundVar(pt)) { +X_API YAP_tag_t YAP_TagOfTerm(Term t) { + if (IsVarTerm(t)) { + CELL *pt = VarOfTerm(t); + if (IsUnboundVar(pt)) { CACHE_REGS - if (IsAttVar(pt)) + if (IsAttVar(pt)) return YAP_TAG_ATT; return YAP_TAG_UNBOUND; - } - return YAP_TAG_REF; - } - if (IsPairTerm(t)) - return YAP_TAG_PAIR; - if (IsAtomOrIntTerm(t)) { - if (IsAtomTerm(t)) + } + return YAP_TAG_REF; + } + if (IsPairTerm(t)) + return YAP_TAG_PAIR; + if (IsAtomOrIntTerm(t)) { + if (IsAtomTerm(t)) return YAP_TAG_ATOM; - return YAP_TAG_INT; - } else { - Functor f = FunctorOfTerm(t); + return YAP_TAG_INT; + } else { + Functor f = FunctorOfTerm(t); - if (IsExtensionFunctor(f)) { + if (IsExtensionFunctor(f)) { if (f == FunctorDBRef) { - return YAP_TAG_DBREF; + return YAP_TAG_DBREF; } if (f == FunctorLongInt) { - return YAP_TAG_LONG_INT; + return YAP_TAG_LONG_INT; } if (f == FunctorBigInt) { - big_blob_type bt = RepAppl(t)[1]; - switch (bt) { - case BIG_INT: - return YAP_TAG_BIG_INT; - case BIG_RATIONAL: - return YAP_TAG_RATIONAL; - default: - return YAP_TAG_OPAQUE; - } + big_blob_type bt = RepAppl(t)[1]; + switch (bt) { + case BIG_INT: + return YAP_TAG_BIG_INT; + case BIG_RATIONAL: + return YAP_TAG_RATIONAL; + default: + return YAP_TAG_OPAQUE; + } } - } - return YAP_TAG_APPL; - } - } + } + return YAP_TAG_APPL; + } +} - int YAP_BPROLOG_exception; - Term YAP_BPROLOG_curr_toam_status; +int YAP_BPROLOG_exception; +Term YAP_BPROLOG_curr_toam_status; - /** - * Output the number of bytes needed to represent a string in UTF-8 - * Note that the terminating zero is not included. No error checking - * is performed (the programmer should have that done). - * - * @param t a list of codes, chars, string or atom. - * - * @return a positive number with the size, or 0. - */ - X_API size_t YAP_UTF8_TextLength(Term t) { - utf8proc_uint8_t dst[8]; - size_t sz = 0; +/** + * Output the number of bytes needed to represent a string in UTF-8 + * Note that the terminating zero is not included. No error checking + * is performed (the programmer should have that done). + * + * @param t a list of codes, chars, string or atom. + * + * @return a positive number with the size, or 0. + */ +X_API size_t YAP_UTF8_TextLength(Term t) { + utf8proc_uint8_t dst[8]; + size_t sz = 0; - if (IsPairTerm(t)) { - while (t != TermNil) { + if (IsPairTerm(t)) { + while (t != TermNil) { int c; Term hd = HeadOfTerm(t); if (IsAtomTerm(hd)) { - Atom at = AtomOfTerm(hd); - unsigned char *s = RepAtom(at)->UStrOfAE; - int32_t ch; - get_utf8(s, 1, &ch); - c = ch; + Atom at = AtomOfTerm(hd); + unsigned char *s = RepAtom(at)->UStrOfAE; + int32_t ch; + get_utf8(s, 1, &ch); + c = ch; } else if (IsIntegerTerm(hd)) { - c = IntegerOfTerm(hd); + c = IntegerOfTerm(hd); } else { - c = '\0'; + c = '\0'; } sz += utf8proc_encode_char(c, dst); t = TailOfTerm(t); - } - } else if (IsAtomTerm(t)) { - Atom at = AtomOfTerm(t); - char *s = RepAtom(at)->StrOfAE; - sz = strlen(s); - } else if (IsStringTerm(t)) { - sz = strlen(StringOfTerm(t)); - } - return sz; - } + } + } else if (IsAtomTerm(t)) { + Atom at = AtomOfTerm(t); + char *s = RepAtom(at)->StrOfAE; + sz = strlen(s); + } else if (IsStringTerm(t)) { + sz = strlen(StringOfTerm(t)); + } + return sz; +} - X_API Int YAP_ListLength(Term t) { - Term *aux; +X_API Int YAP_ListLength(Term t) { + Term *aux; - Int n = Yap_SkipList(&t, &aux); - if (IsVarTerm(*aux)) - return -1; - if (*aux == TermNil) - return n; - return -1; - } + Int n = Yap_SkipList(&t, &aux); + if (IsVarTerm(*aux)) + return -1; + if (*aux == TermNil) + return n; + return -1; +} - X_API Int YAP_NumberVars(Term t, Int nbv) { return Yap_NumberVars(t, nbv, FALSE); } +X_API Int YAP_NumberVars(Term t, Int nbv) { return Yap_NumberVars(t, nbv, FALSE); } - X_API Term YAP_UnNumberVars(Term t) { - /* don't allow sharing of ground terms */ - return Yap_UnNumberTerm(t, FALSE); - } +X_API Term YAP_UnNumberVars(Term t) { + /* don't allow sharing of ground terms */ + return Yap_UnNumberTerm(t, FALSE); +} - X_API int YAP_IsNumberedVariable(Term t) { - return IsApplTerm(t) && FunctorOfTerm(t) == FunctorDollarVar && - IsIntegerTerm(ArgOfTerm(1, t)); - } +X_API int YAP_IsNumberedVariable(Term t) { + return IsApplTerm(t) && FunctorOfTerm(t) == FunctorDollarVar && + IsIntegerTerm(ArgOfTerm(1, t)); +} - X_API size_t YAP_ExportTerm(Term inp, char *buf, size_t len) { - if (!len) - return 0; - return Yap_ExportTerm(inp, buf, len, current_arity()); - } +X_API size_t YAP_ExportTerm(Term inp, char *buf, size_t len) { + if (!len) + return 0; + return Yap_ExportTerm(inp, buf, len, current_arity()); +} - X_API size_t YAP_SizeOfExportedTerm(char *buf) { - if (!buf) - return 0; - return Yap_SizeOfExportedTerm(buf); - } +X_API size_t YAP_SizeOfExportedTerm(char *buf) { + if (!buf) + return 0; + return Yap_SizeOfExportedTerm(buf); +} - X_API Term YAP_ImportTerm(char *buf) { return Yap_ImportTerm(buf); } +X_API Term YAP_ImportTerm(char *buf) { return Yap_ImportTerm(buf); } - X_API int YAP_RequiresExtraStack(size_t sz) { - CACHE_REGS +X_API int YAP_RequiresExtraStack(size_t sz) { + CACHE_REGS - if (sz < 16 * 1024) - sz = 16 * 1024; - if (HR <= ASP - sz) { - return FALSE; - } - BACKUP_H(); - while (HR > ASP - sz) { - CACHE_REGS - RECOVER_H(); - if (!Yap_dogc(0, NULL PASS_REGS)) { + if (sz < 16 * 1024) + sz = 16 * 1024; + if (HR <= ASP - sz) { + return FALSE; + } + BACKUP_H(); + while (HR > ASP - sz) { + CACHE_REGS + RECOVER_H(); + if (!Yap_dogc(0, NULL PASS_REGS)) { return -1; - } - BACKUP_H(); - } - RECOVER_H(); - return TRUE; - } + } + BACKUP_H(); + } + RECOVER_H(); + return TRUE; +} - atom_t *TR_Atoms; - functor_t *TR_Functors; - size_t AtomTranslations, MaxAtomTranslations; - size_t FunctorTranslations, MaxFunctorTranslations; +atom_t *TR_Atoms; +functor_t *TR_Functors; +size_t AtomTranslations, MaxAtomTranslations; +size_t FunctorTranslations, MaxFunctorTranslations; - X_API Int YAP_AtomToInt(Atom At) { - TranslationEntry *te = Yap_GetTranslationProp(At, 0); - if (te != NIL) - return te->Translation; - TR_Atoms[AtomTranslations] = At; - Yap_PutAtomTranslation(At, 0, AtomTranslations); - AtomTranslations++; - if (AtomTranslations == MaxAtomTranslations) { - atom_t *ot = TR_Atoms; - atom_t *nt = (atom_t *) malloc(sizeof(atom_t) * 2 * MaxAtomTranslations); - if (nt == NULL) { +X_API Int YAP_AtomToInt(YAP_Atom At) { + TranslationEntry *te = Yap_GetTranslationProp(At, 0); + if (te != NIL) + return te->Translation; + TR_Atoms[AtomTranslations] = At; + Yap_PutAtomTranslation(At, 0, AtomTranslations); + AtomTranslations++; + if (AtomTranslations == MaxAtomTranslations) { + atom_t *ot = TR_Atoms; + atom_t *nt = (atom_t *) malloc(sizeof(atom_t) * 2 * MaxAtomTranslations); + if (nt == NULL) { Yap_Error(SYSTEM_ERROR_INTERNAL, MkAtomTerm(At), "No more room for translations"); return -1; - } - memcpy(nt, ot, sizeof(atom_t) * MaxAtomTranslations); - TR_Atoms = nt; - free(ot); - MaxAtomTranslations *= 2; - } - return AtomTranslations - 1; - } + } + memcpy(nt, ot, sizeof(atom_t) * MaxAtomTranslations); + TR_Atoms = nt; + free(ot); + MaxAtomTranslations *= 2; + } + return AtomTranslations - 1; +} - X_API Atom YAP_IntToAtom(Int i) { return TR_Atoms[i]; } +X_API YAP_Atom YAP_IntToAtom(Int i) { return TR_Atoms[i]; } - X_API Int YAP_FunctorToInt(Functor f) { - Atom At = NameOfFunctor(f); - arity_t arity = ArityOfFunctor(f); - TranslationEntry *te = Yap_GetTranslationProp(At, arity); - if (te != NIL) - return te->Translation; - TR_Functors[FunctorTranslations] = f; - Yap_PutAtomTranslation(At, arity, FunctorTranslations); - FunctorTranslations++; - if (FunctorTranslations == MaxFunctorTranslations) { - functor_t *nt = (functor_t *) malloc(sizeof(functor_t) * 2 * - MaxFunctorTranslations), - *ot = TR_Functors; - if (nt == NULL) { +X_API Int YAP_FunctorToInt(YAP_Functor f) { + YAP_Atom At = NameOfFunctor(f); + arity_t arity = ArityOfFunctor(f); + TranslationEntry *te = Yap_GetTranslationProp(At, arity); + if (te != NIL) + return te->Translation; + TR_Functors[FunctorTranslations] = f; + Yap_PutAtomTranslation(At, arity, FunctorTranslations); + FunctorTranslations++; + if (FunctorTranslations == MaxFunctorTranslations) { + functor_t *nt = (functor_t *) malloc(sizeof(functor_t) * 2 * + MaxFunctorTranslations), + *ot = TR_Functors; + if (nt == NULL) { Yap_Error(SYSTEM_ERROR_INTERNAL, MkAtomTerm(At), "No more room for translations"); return -1; - } - memcpy(nt, ot, sizeof(functor_t) * MaxFunctorTranslations); - TR_Functors = nt; - free(ot); - MaxFunctorTranslations *= 2; - } - return FunctorTranslations - 1; - } + } + memcpy(nt, ot, sizeof(functor_t) * MaxFunctorTranslations); + TR_Functors = nt; + free(ot); + MaxFunctorTranslations *= 2; + } + return FunctorTranslations - 1; +} - X_API void *YAP_foreign_stream(int sno) { return GLOBAL_Stream[sno].u.private_data; } +X_API void *YAP_foreign_stream(int sno) { return GLOBAL_Stream[sno].u.private_data; } - X_API Functor YAP_IntToFunctor(Int i) { return TR_Functors[i]; } +X_API YAP_Functor YAP_IntToFunctor(Int i) { return TR_Functors[i]; } - X_API void *YAP_shared(void) { return LOCAL_shared; } +X_API void *YAP_shared(void) { return LOCAL_shared; } - X_API PredEntry *YAP_TopGoal(void) { - YAP_Functor f = Yap_MkFunctor(Yap_LookupAtom("yap_query"), 3); - Term tmod = MkAtomTerm(Yap_LookupAtom("yapi")); - PredEntry *p = RepPredProp(Yap_GetPredPropByFunc(f, tmod)); - return p; - } +X_API YAP_PredEntryPtr YAP_TopGoal(void) { + Functor f = Yap_MkFunctor(Yap_LookupAtom("yap_query"), 3); + Term tmod = MkAtomTerm(Yap_LookupAtom("yapi")); + PredEntry *p = RepPredProp(Yap_GetPredPropByFunc(f, tmod)); + return p; +} - void yap_init(void) {} +void yap_init(void) {} #endif // C_INTERFACE_C - /** - @} - */ +/** +@} +*/ diff --git a/C/dbase.c b/C/dbase.c index 67b8f7bc8..b776ed244 100644 --- a/C/dbase.c +++ b/C/dbase.c @@ -4911,17 +4911,17 @@ static Int cont_current_key_integer(USES_REGS1) { return Yap_unify(term, ARG1) && Yap_unify(term, ARG2); } -Term Yap_FetchTermFromDB(DBTerm *ref) { +Term Yap_FetchTermFromDB(void *ref) { CACHE_REGS return GetDBTerm(ref, FALSE PASS_REGS); } -Term Yap_FetchClauseTermFromDB(DBTerm *ref) { +Term Yap_FetchClauseTermFromDB(void *ref) { CACHE_REGS return GetDBTerm(ref, TRUE PASS_REGS); } -Term Yap_PopTermFromDB(DBTerm *ref) { +Term Yap_PopTermFromDB(void *ref) { CACHE_REGS Term t = GetDBTerm(ref, FALSE PASS_REGS); @@ -5304,7 +5304,7 @@ static void ReleaseTermFromDB(DBTerm *ref USES_REGS) { FreeDBSpace((char *)ref); } -void Yap_ReleaseTermFromDB(DBTerm *ref) { +void Yap_ReleaseTermFromDB(void *ref) { CACHE_REGS ReleaseTermFromDB(ref PASS_REGS); } diff --git a/C/errors.c b/C/errors.c index 615c6ea10..523282842 100755 --- a/C/errors.c +++ b/C/errors.c @@ -386,10 +386,10 @@ yamop *Yap_Error__(const char *file, const char *function, int lineno, Yap_RestartYap(1); } LOCAL_ActiveError->errorNo = type; - LOCAL_ActiveError->errorAsText = Yap_LookupAtom(Yap_errorName(type)); + LOCAL_ActiveError->errorAsText = Yap_errorName(type); LOCAL_ActiveError->errorClass = Yap_errorClass(type); LOCAL_ActiveError->classAsText = - Yap_LookupAtom(Yap_errorClassName(LOCAL_ActiveError->errorClass)); + Yap_errorClassName(LOCAL_ActiveError->errorClass); LOCAL_ActiveError->errorLine = lineno; LOCAL_ActiveError->errorFunction = function; LOCAL_ActiveError->errorFile = file; diff --git a/C/exec.c b/C/exec.c index c381f158d..0a30836ff 100755 --- a/C/exec.c +++ b/C/exec.c @@ -2039,10 +2039,10 @@ static Int jump_env(USES_REGS1) { // LOCAL_Error_TYPE = ERROR_EVENT; Term t1 = ArgOfTerm(1, t); if (IsApplTerm(t1) && IsAtomTerm((t2 = ArgOfTerm(1, t1)))) { - LOCAL_ActiveError->errorAsText = AtomOfTerm(t2); - LOCAL_ActiveError->classAsText = NameOfFunctor(FunctorOfTerm(t1)); + LOCAL_ActiveError->errorAsText = RepAtom(AtomOfTerm(t2))->StrOfAE; + LOCAL_ActiveError->classAsText = RepAtom(NameOfFunctor(FunctorOfTerm(t1)))->StrOfAE; } else if (IsAtomTerm(t)) { - LOCAL_ActiveError->errorAsText = AtomOfTerm(t1); + LOCAL_ActiveError->errorAsText = RepAtom(AtomOfTerm(t1))->StrOfAE; LOCAL_ActiveError->classAsText = NULL; } } else { diff --git a/C/scanner.c b/C/scanner.c index 48f077858..8efaa55fe 100755 --- a/C/scanner.c +++ b/C/scanner.c @@ -689,12 +689,12 @@ static int send_error_message(char s[]) { } static wchar_t read_quoted_char(int *scan_nextp, - struct stream_desc *inp_stream) { + struct stream_desc *st) { int ch; /* escape sequence */ do_switch: - ch = getchrq(inp_stream); + ch = getchrq(st); switch (ch) { case 10: return 0; @@ -705,7 +705,7 @@ do_switch: case 'b': return '\b'; case 'c': - while (chtype((ch = getchrq(inp_stream))) == BS) + while (chtype((ch = getchrq(st))) == BS) ; { if (ch == '\\') { @@ -732,7 +732,7 @@ do_switch: wchar_t wc = '\0'; for (i = 0; i < 4; i++) { - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch >= '0' && ch <= '9') { wc += (ch - '0') << ((3 - i) * 4); } else if (ch >= 'a' && ch <= 'f') { @@ -750,7 +750,7 @@ do_switch: wchar_t wc = '\0'; for (i = 0; i < 8; i++) { - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch >= '0' && ch <= '9') { wc += (ch - '0') << ((7 - i) * 4); } else if (ch >= 'a' && ch <= 'f') { @@ -777,7 +777,7 @@ do_switch: if (trueGlobalPrologFlag(ISO_FLAG)) { return send_error_message("invalid escape sequence"); } else { - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch == '?') { /* delete character */ return 127; } else if (ch >= 'a' && ch < 'z') { /* hexa */ @@ -800,13 +800,13 @@ do_switch: /* follow ISO */ { unsigned char so_far = ch - '0'; - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch >= '0' && ch < '8') { /* octal */ so_far = so_far * 8 + (ch - '0'); - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch >= '0' && ch < '8') { /* octal */ so_far = so_far * 8 + (ch - '0'); - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch != '\\') { return send_error_message("invalid octal escape sequence"); } @@ -826,19 +826,19 @@ do_switch: /* hexadecimal character (YAP allows empty hexadecimal */ { unsigned char so_far = 0; - ch = getchrq(inp_stream); + ch = getchrq(st); if (my_isxdigit(ch, 'f', 'F')) { /* hexa */ so_far = so_far * 16 + (chtype(ch) == NU ? ch - '0' : (my_isupper(ch) ? ch - 'A' : ch - 'a') + 10); - ch = getchrq(inp_stream); + ch = getchrq(st); if (my_isxdigit(ch, 'f', 'F')) { /* hexa */ so_far = so_far * 16 + (chtype(ch) == NU ? ch - '0' : (my_isupper(ch) ? ch - 'A' : ch - 'a') + 10); - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch == '\\') { return so_far; } else { @@ -890,7 +890,7 @@ static int num_send_error_message(char s[]) { /* reads a number, either integer or float */ -static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { +static Term get_num(int *chp, int *chbuffp, StreamDesc *st, int sign) { int ch = *chp; Int val = 0L, base = ch - '0'; int might_be_float = TRUE, has_overflow = FALSE; @@ -899,7 +899,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { int max_size = 254, left = 254; *sp++ = ch; - ch = getchr(inp_stream); + ch = getchr(st); /* * because of things like 00'2, 03'2 and even better 12'2, I need to * do this (have mercy) @@ -909,7 +909,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { if (--left == 0) number_overflow(); base = 10 * base + ch - '0'; - ch = getchr(inp_stream); + ch = getchr(st); } if (ch == '\'') { if (base > 36) { @@ -919,7 +919,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { if (--left == 0) number_overflow(); *sp++ = ch; - ch = getchr(inp_stream); + ch = getchr(st); if (base == 0) { CACHE_REGS wchar_t ascii = ch; @@ -927,11 +927,11 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { if (ch == '\\' && Yap_GetModuleEntry(CurrentModule)->flags & M_CHARESCAPE) { - ascii = read_quoted_char(&scan_extra, inp_stream); + ascii = read_quoted_char(&scan_extra, st); } /* a quick way to represent ASCII */ if (scan_extra) - *chp = getchr(inp_stream); + *chp = getchr(st); if (sign == -1) { return MkIntegerTerm(-ascii); } @@ -951,7 +951,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { val = oval * base + chval; if (oval != (val - chval) / base) /* overflow */ has_overflow = (has_overflow || TRUE); - ch = getchr(inp_stream); + ch = getchr(st); } } } else if (ch == 'x' && base == 0) { @@ -959,7 +959,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { if (--left == 0) number_overflow(); *sp++ = ch; - ch = getchr(inp_stream); + ch = getchr(st); while (my_isxdigit(ch, 'F', 'f')) { Int oval = val; int chval = @@ -971,17 +971,17 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { val = val * 16 + chval; if (oval != (val - chval) / 16) /* overflow */ has_overflow = TRUE; - ch = getchr(inp_stream); + ch = getchr(st); } *chp = ch; } else if (ch == 'o' && base == 0) { might_be_float = FALSE; base = 8; - ch = getchr(inp_stream); + ch = getchr(st); } else if (ch == 'b' && base == 0) { might_be_float = FALSE; base = 2; - ch = getchr(inp_stream); + ch = getchr(st); } else { val = base; base = 10; @@ -1002,7 +1002,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { val = val * base + ch - '0'; if (val / base != oval || val - oval * base != ch - '0') /* overflow */ has_overflow = TRUE; - ch = getchr(inp_stream); + ch = getchr(st); } if (might_be_float && (ch == '.' || ch == 'e' || ch == 'E')) { int has_dot = (ch == '.'); @@ -1010,7 +1010,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { unsigned char *dp; int dc; - if (chtype(ch = getchr(inp_stream)) != NU) { + if (chtype(ch = getchr(st)) != NU) { if (ch == 'e' || ch == 'E') { if (trueGlobalPrologFlag(ISO_FLAG)) return num_send_error_message( @@ -1045,21 +1045,21 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { if (--left == 0) number_overflow(); *sp++ = ch; - } while (chtype(ch = getchr(inp_stream)) == NU); + } while (chtype(ch = getchr(st)) == NU); } } if (ch == 'e' || ch == 'E') { if (--left == 0) number_overflow(); *sp++ = ch; - ch = getchr(inp_stream); + ch = getchr(st); if (ch == '-') { if (--left == 0) number_overflow(); *sp++ = '-'; - ch = getchr(inp_stream); + ch = getchr(st); } else if (ch == '+') { - ch = getchr(inp_stream); + ch = getchr(st); } if (chtype(ch) != NU) { CACHE_REGS @@ -1071,7 +1071,7 @@ static Term get_num(int *chp, int *chbuffp, StreamDesc *inp_stream, int sign) { if (--left == 0) number_overflow(); *sp++ = ch; - } while (chtype(ch = getchr(inp_stream)) == NU); + } while (chtype(ch = getchr(st)) == NU); } *sp = '\0'; *chp = ch; @@ -1257,7 +1257,7 @@ const char *Yap_tokText(void *tokptre) { return "."; } -static void open_comment(int ch, StreamDesc *inp_stream USES_REGS) { +static void open_comment(int ch, StreamDesc *st USES_REGS) { CELL *h0 = HR; HR += 5; h0[0] = AbsAppl(h0 + 2); @@ -1272,7 +1272,7 @@ static void open_comment(int ch, StreamDesc *inp_stream USES_REGS) { LOCAL_CommentsTail = h0 + 1; h0 += 2; h0[0] = (CELL)FunctorMinus; - h0[1] = Yap_StreamPosition(inp_stream - GLOBAL_Stream); + h0[1] = Yap_StreamPosition(st - GLOBAL_Stream); h0[2] = TermNil; LOCAL_CommentsNextChar = h0 + 2; LOCAL_CommentsBuff = (wchar_t *)malloc(1024 * sizeof(wchar_t)); @@ -1301,14 +1301,14 @@ static void close_comment(USES_REGS1) { // mark that we reached EOF, // next token will be end_of_file) -static void mark_eof(struct stream_desc *inp_stream) { - inp_stream->status |= Push_Eof_Stream_f; +static void mark_eof(struct stream_desc *st) { + st->status |= Push_Eof_Stream_f; } #define add_ch_to_buff(ch) \ { charp += put_utf8(charp, ch); } -TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, +TokEntry *Yap_tokenizer(struct stream_desc *st, bool store_comments, Term *tposp) { CACHE_REGS @@ -1324,14 +1324,15 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, LOCAL_AnonVarTable = NULL; l = NULL; p = NULL; /* Just to make lint happy */ - ch = getchr(inp_stream); + __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "i %d", st-GLOBAL_Stream); + ch = getchr(st); while (chtype(ch) == BS) { - ch = getchr(inp_stream); + ch = getchr(st); } - *tposp = Yap_StreamPosition(inp_stream - GLOBAL_Stream); - Yap_setCurrentSourceLocation(inp_stream); - LOCAL_StartLineCount = inp_stream->linecount; - LOCAL_StartLinePos = inp_stream->linepos; + *tposp = Yap_StreamPosition(st - GLOBAL_Stream); + Yap_setCurrentSourceLocation(st); + LOCAL_StartLineCount = st->linecount; + LOCAL_StartLinePos = st->linepos; do { int quote, isvar; unsigned char *charp, *mp; @@ -1350,22 +1351,22 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, p = t; restart: while (chtype(ch) == BS) { - ch = getchr(inp_stream); + ch = getchr(st); } - t->TokPos = GetCurInpPos(inp_stream); + t->TokPos = GetCurInpPos(st); switch (chtype(ch)) { case CC: if (store_comments) { - open_comment(ch, inp_stream PASS_REGS); + open_comment(ch, st PASS_REGS); continue_comment: - while ((ch = getchr(inp_stream)) != 10 && chtype(ch) != EF) { + while ((ch = getchr(st)) != 10 && chtype(ch) != EF) { extend_comment(ch PASS_REGS); } extend_comment(ch PASS_REGS); if (chtype(ch) != EF) { - ch = getchr(inp_stream); + ch = getchr(st); if (chtype(ch) == CC) { extend_comment(ch PASS_REGS); goto continue_comment; @@ -1373,7 +1374,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, } close_comment(PASS_REGS1); } else { - while ((ch = getchr(inp_stream)) != 10 && chtype(ch) != EF) + while ((ch = getchr(st)) != 10 && chtype(ch) != EF) ; } if (chtype(ch) != EF) { @@ -1381,15 +1382,15 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, if (t == l) { /* we found a comment before reading characters */ while (chtype(ch) == BS) { - ch = getchr(inp_stream); + ch = getchr(st); } - *tposp = Yap_StreamPosition(inp_stream - GLOBAL_Stream); - Yap_setCurrentSourceLocation(inp_stream); + *tposp = Yap_StreamPosition(st - GLOBAL_Stream); + Yap_setCurrentSourceLocation(st); } goto restart; } else { t->Tok = Ord(kind = eot_tok); - mark_eof(inp_stream); + mark_eof(st); t->TokInfo = TermEof; } break; @@ -1398,14 +1399,14 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, case UL: case LC: { int32_t och = ch; - ch = getchr(inp_stream); + ch = getchr(st); size_t sz = 512; TokImage = Malloc(sz PASS_REGS); scan_name: charp = (unsigned char *)TokImage; isvar = (chtype(och) != LC); add_ch_to_buff(och); - for (; chtype(ch) <= NU; ch = getchr(inp_stream)) { + for (; chtype(ch) <= NU; ch = getchr(st)) { if (charp == TokImage + (sz - 1)) { unsigned char *p0 = TokImage; sz = Yap_Min(sz * 2, sz + MBYTE); @@ -1423,7 +1424,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, return CodeSpaceError(t, p, l); } add_ch_to_buff(ch); - ch = getchr(inp_stream); + ch = getchr(st); } add_ch_to_buff('\0'); if (!isvar) { @@ -1459,7 +1460,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, cha = ch; cherr = 0; CHECK_SPACE(); - if ((t->TokInfo = get_num(&cha, &cherr, inp_stream, sign)) == 0L) { + if ((t->TokInfo = get_num(&cha, &cherr, st, sign)) == 0L) { if (p) { p->Tok = eot_tok; t->TokInfo = TermError; @@ -1471,7 +1472,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, if (cherr) { TokEntry *e; t->Tok = Number_tok; - t->TokPos = GetCurInpPos(inp_stream); + t->TokPos = GetCurInpPos(st); e = (TokEntry *)AllocScannerMemory(sizeof(TokEntry)); if (e == NULL) { return TrailSpaceError(p, l); @@ -1497,7 +1498,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, t->Tok = Ord(Var_tok); t->TokInfo = (Term)Yap_LookupVar("E"); - t->TokPos = GetCurInpPos(inp_stream); + t->TokPos = GetCurInpPos(st); e2 = (TokEntry *)AllocScannerMemory(sizeof(TokEntry)); if (e2 == NULL) { return TrailSpaceError(p, l); @@ -1530,7 +1531,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, if (ch == '(') solo_flag = FALSE; t->TokInfo = MkAtomTerm(AtomE); - t->TokPos = GetCurInpPos(inp_stream); + t->TokPos = GetCurInpPos(st); e2 = (TokEntry *)AllocScannerMemory(sizeof(TokEntry)); if (e2 == NULL) { return TrailSpaceError(p, l); @@ -1557,7 +1558,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, charp = TokImage; quote = ch; len = 0; - ch = getchrq(inp_stream); + ch = getchrq(st); size_t sz = 1024; while (TRUE) { @@ -1577,23 +1578,23 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, break; } if (ch == quote) { - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch != quote) break; add_ch_to_buff(ch); - ch = getchrq(inp_stream); + ch = getchrq(st); } else if (ch == '\\' && Yap_GetModuleEntry(CurrentModule)->flags & M_CHARESCAPE) { int scan_next = TRUE; - if ((ch = read_quoted_char(&scan_next, inp_stream))) { + if ((ch = read_quoted_char(&scan_next, st))) { add_ch_to_buff(ch); } if (scan_next) { - ch = getchrq(inp_stream); + ch = getchrq(st); } } else { add_ch_to_buff(ch); - ch = getchrq(inp_stream); + ch = getchrq(st); } ++len; } @@ -1628,9 +1629,9 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, if (ch == '\0') { int pch; t->Tok = Ord(kind = eot_tok); - pch = Yap_peek(inp_stream - GLOBAL_Stream); + pch = Yap_peek(st - GLOBAL_Stream); if (chtype(pch) == EF) { - mark_eof(inp_stream); + mark_eof(st); t->TokInfo = TermEof; } else { t->TokInfo = TermNewLine; @@ -1638,11 +1639,11 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, t->TokInfo = TermEof; return l; } else - ch = getchr(inp_stream); + ch = getchr(st); break; case SY: { int pch; - if (ch == '.' && (pch = Yap_peek(inp_stream - GLOBAL_Stream)) && + if (ch == '.' && (pch = Yap_peek(st - GLOBAL_Stream)) && (chtype(pch) == BS || chtype(pch) == EF || pch == '%')) { t->Tok = Ord(kind = eot_tok); // consume... @@ -1655,7 +1656,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, if (ch == '`') goto quoted_string; och = ch; - ch = getchr(inp_stream); + ch = getchr(st); if (och == '.') { if (chtype(ch) == BS || chtype(ch) == EF || ch == '%') { t->Tok = Ord(kind = eot_tok); @@ -1664,7 +1665,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, return l; } if (chtype(ch) == EF) { - mark_eof(inp_stream); + mark_eof(st); t->TokInfo = TermEof; } else { t->TokInfo = TermNewLine; @@ -1675,12 +1676,12 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, if (och == '/' && ch == '*') { if (store_comments) { CHECK_SPACE(); - open_comment('/', inp_stream PASS_REGS); + open_comment('/', st PASS_REGS); while ((och != '*' || ch != '/') && chtype(ch) != EF) { och = ch; CHECK_SPACE(); extend_comment(ch PASS_REGS); - ch = getchr(inp_stream); + ch = getchr(st); } if (chtype(ch) != EF) { CHECK_SPACE(); @@ -1690,7 +1691,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, } else { while ((och != '*' || ch != '/') && chtype(ch) != EF) { och = ch; - ch = getchr(inp_stream); + ch = getchr(st); } } if (chtype(ch) == EF) { @@ -1699,15 +1700,15 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, break; } else { /* leave comments */ - ch = getchr(inp_stream); + ch = getchr(st); if (t == l) { /* we found a comment before reading characters */ while (chtype(ch) == BS) { - ch = getchr(inp_stream); + ch = getchr(st); } CHECK_SPACE(); - *tposp = Yap_StreamPosition(inp_stream - GLOBAL_Stream); - Yap_setCurrentSourceLocation(inp_stream); + *tposp = Yap_StreamPosition(st - GLOBAL_Stream); + Yap_setCurrentSourceLocation(st); } } goto restart; @@ -1721,7 +1722,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, return l; } if (chtype(ch) == EF) { - mark_eof(inp_stream); + mark_eof(st); t->TokInfo = TermEof; } else { t->TokInfo = TermNl; @@ -1733,7 +1734,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, TokImage = Malloc(sz); charp = TokImage; add_ch_to_buff(och); - for (; chtype(ch) == SY; ch = getchr(inp_stream)) { + for (; chtype(ch) == SY; ch = getchr(st)) { if (charp >= TokImage + (sz - 10)) { sz = Yap_Min(sz * 2, sz + MBYTE); TokImage = Realloc(TokImage, sz); @@ -1764,7 +1765,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, unsigned char chs[2]; chs[0] = ch; chs[1] = '\0'; - ch = getchr(inp_stream); + ch = getchr(st); t->TokInfo = MkAtomTerm(Yap_ULookupAtom(chs)); t->Tok = Ord(kind = Name_tok); if (ch == '(') @@ -1773,7 +1774,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, case BK: och = ch; - ch = getchr(inp_stream); + ch = getchr(st); { unsigned char chs[10]; TokImage = charp = chs; @@ -1783,12 +1784,12 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, } if (och == '(') { while (chtype(ch) == BS) { - ch = getchr(inp_stream); + ch = getchr(st); } if (ch == ')') { t->TokInfo = TermEmptyBrackets; t->Tok = Ord(kind = Name_tok); - ch = getchr(inp_stream); + ch = getchr(st); solo_flag = FALSE; break; } else if (!solo_flag) { @@ -1797,12 +1798,12 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, } } else if (och == '[') { while (chtype(ch) == BS) { - ch = getchr(inp_stream); + ch = getchr(st); }; if (ch == ']') { t->TokInfo = TermNil; t->Tok = Ord(kind = Name_tok); - ch = getchr(inp_stream); + ch = getchr(st); solo_flag = FALSE; break; } @@ -1827,26 +1828,26 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, cur_qq = qq; } t->TokInfo = (CELL)qq; - if (inp_stream->status & Seekable_Stream_f) { - qq->start.byteno = fseek(inp_stream->file, 0, 0); + if (st->status & Seekable_Stream_f) { + qq->start.byteno = fseek(st->file, 0, 0); } else { - qq->start.byteno = inp_stream->charcount - 1; + qq->start.byteno = st->charcount - 1; } - qq->start.lineno = inp_stream->linecount; - qq->start.linepos = inp_stream->linepos - 1; - qq->start.charno = inp_stream->charcount - 1; + qq->start.lineno = st->linecount; + qq->start.linepos = st->linepos - 1; + qq->start.charno = st->charcount - 1; t->Tok = Ord(kind = QuasiQuotes_tok); - ch = getchr(inp_stream); + ch = getchr(st); solo_flag = FALSE; break; } while (chtype(ch) == BS) { - ch = getchr(inp_stream); + ch = getchr(st); }; if (ch == '}') { t->TokInfo = TermBraces; t->Tok = Ord(kind = Name_tok); - ch = getchr(inp_stream); + ch = getchr(st); solo_flag = FALSE; break; } @@ -1863,16 +1864,16 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, } cur_qq = NULL; t->TokInfo = (CELL)qq; - if (inp_stream->status & Seekable_Stream_f) { - qq->mid.byteno = fseek(inp_stream->file, 0, 0); + if (st->status & Seekable_Stream_f) { + qq->mid.byteno = fseek(st->file, 0, 0); } else { - qq->mid.byteno = inp_stream->charcount - 1; + qq->mid.byteno = st->charcount - 1; } - qq->mid.lineno = inp_stream->linecount; - qq->mid.linepos = inp_stream->linepos - 1; - qq->mid.charno = inp_stream->charcount - 1; + qq->mid.lineno = st->linecount; + qq->mid.linepos = st->linepos - 1; + qq->mid.charno = st->charcount - 1; t->Tok = Ord(kind = QuasiQuotes_tok); - ch = getchr(inp_stream); + ch = getchr(st); sz = 1024; TokImage = Malloc(sz); if (!TokImage) { @@ -1885,11 +1886,11 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, charp = TokImage; quote = ch; len = 0; - ch = getchrq(inp_stream); + ch = getchrq(st); while (TRUE) { if (ch == '|') { - ch = getchrq(inp_stream); + ch = getchrq(st); if (ch != '}') { } else { charp += put_utf8((unsigned char *)charp, och); @@ -1899,13 +1900,13 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, } } else if (chtype(ch) == EF) { Free(TokImage); - mark_eof(inp_stream); + mark_eof(st); t->Tok = Ord(kind = eot_tok); t->TokInfo = TermOutOfHeapError; break; } else { charp += put_utf8(charp, ch); - ch = getchrq(inp_stream); + ch = getchrq(st); } if (charp > (unsigned char *)AuxSp - 1024) { /* Not enough space to read in the string. */ @@ -1925,26 +1926,26 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, strncpy((char *)mp, (const char *)TokImage, len + 1); qq->text = (unsigned char *)mp; Yap_ReleasePreAllocCodeSpace((CODEADDR)TokImage); - if (inp_stream->status & Seekable_Stream_f) { - qq->end.byteno = fseek(inp_stream->file, 0, 0); + if (st->status & Seekable_Stream_f) { + qq->end.byteno = fseek(st->file, 0, 0); } else { - qq->end.byteno = inp_stream->charcount - 1; + qq->end.byteno = st->charcount - 1; } - qq->end.lineno = inp_stream->linecount; - qq->end.linepos = inp_stream->linepos - 1; - qq->end.charno = inp_stream->charcount - 1; + qq->end.lineno = st->linecount; + qq->end.linepos = st->linepos - 1; + qq->end.charno = st->charcount - 1; if (!(t->TokInfo)) { return CodeSpaceError(t, p, l); } Yap_ReleasePreAllocCodeSpace((CODEADDR)TokImage); solo_flag = FALSE; - ch = getchr(inp_stream); + ch = getchr(st); break; } t->Tok = Ord(kind = Ponctuation_tok); break; case EF: - mark_eof(inp_stream); + mark_eof(st); t->Tok = Ord(kind = eot_tok); t->TokInfo = TermEof; return l; @@ -1966,7 +1967,7 @@ TokEntry *Yap_tokenizer(struct stream_desc *inp_stream, bool store_comments, p->TokNext = e; e->Tok = Error_tok; e->TokInfo = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); - e->TokPos = GetCurInpPos(inp_stream); + e->TokPos = GetCurInpPos(st); e->TokNext = NULL; LOCAL_ErrorMessage = NULL; p = e; diff --git a/C/stack.c b/C/stack.c index 8f968dca8..cdd14decc 100644 --- a/C/stack.c +++ b/C/stack.c @@ -1098,7 +1098,7 @@ bool set_clause_info(yamop *codeptr, PredEntry *pp) { LOCAL_ActiveError->prologPredArity = pp->ArityOfPE; } LOCAL_ActiveError->prologPredModule = - (pp->ModuleOfPred ? pp->ModuleOfPred : TermProlog); + (pp->ModuleOfPred ? pp->ModuleOfPred : "prolog"); LOCAL_ActiveError->prologPredFile = pp->src.OwnerFile; if (codeptr->opc == UNDEF_OPCODE) { LOCAL_ActiveError->prologPredFirstLine = 0; diff --git a/C/text.c b/C/text.c index 71ea38488..413551764 100644 --- a/C/text.c +++ b/C/text.c @@ -487,7 +487,7 @@ unsigned char *Yap_readText(seq_tv_t *inp USES_REGS) { #endif if (inp->type & YAP_STRING_TERM) { // Yap_DebugPlWriteln(inp->val.t); - char *s = (char *)Yap_TermToString(inp->val.t, ENC_ISO_UTF8, 0); + char *s = (char *) Yap_TermToBuffer(inp->val.t, ENC_ISO_UTF8, 0); return inp->val.uc = (unsigned char *)s; } if (inp->type & YAP_STRING_CHARS) { diff --git a/C/text.c.new b/C/text.c.new index 9569d2ca4..7c1d67f41 100644 --- a/C/text.c.new +++ b/C/text.c.new @@ -501,7 +501,7 @@ unsigned char *Yap_readText(seq_tv_t *inp, size_t *lengp) { #endif if (inp->type & YAP_STRING_TERM) { // Yap_DebugPlWriteln(inp->val.t); - char *s = (char *)Yap_TermToString(inp->val.t, lengp, ENC_ISO_UTF8, 0); + char *s = (char *) Yap_TermToBuffer(inp->val.t, lengp, ENC_ISO_UTF8, 0); return inp->val.uc = (unsigned char *)s; } if (inp->type & YAP_STRING_CHARS) { diff --git a/C/tracer.c b/C/tracer.c index ab926acc3..d060c5067 100644 --- a/C/tracer.c +++ b/C/tracer.c @@ -87,7 +87,7 @@ static char *send_tracer_message(char *start, char *name, arity_t arity, continue; } } - const char *sn = Yap_TermToString(args[i], LOCAL_encoding, + const char *sn = Yap_TermToBuffer(args[i], LOCAL_encoding, Quote_illegal_f | Handle_vars_f); size_t sz; if (sn == NULL) { diff --git a/C/write.c b/C/write.c index 20ed60bbc..bcf6613a5 100644 --- a/C/write.c +++ b/C/write.c @@ -1255,7 +1255,7 @@ static void wrputref(CODEADDR ref, int Quote_illegal, Yap_CloseSlots(sls); } - char *Yap_TermToString(Term t, encoding_t enc, int flags) { + char *Yap_TermToBuffer(Term t, encoding_t enc, int flags) { CACHE_REGS int sno = Yap_open_buf_write_stream(enc, flags); const char *sf; diff --git a/C/yap-args.c b/C/yap-args.c index 7e646e8b0..f1a91a702 100755 --- a/C/yap-args.c +++ b/C/yap-args.c @@ -147,14 +147,14 @@ static int dump_runtime_variables(void) { return 1; } -YAP_file_type_t Yap_InitDefaults(YAP_init_args *iap, char *saved_state, +X_API YAP_file_type_t Yap_InitDefaults(void *x, char *saved_state, int argc, char *argv[]) { - memset(iap, 0, sizeof(YAP_init_args)); +YAP_init_args *iap = x; + memset(iap, 0, sizeof(YAP_init_args)); #if __ANDROID__ iap->boot_file_type = YAP_BOOT_PL; - iap->SavedState = malloc(strlen(saved_state)+1); - strcpy(iap->SavedState, saved_state); - iap->assetManager = true; + iap->SavedState = NULL; + iap->assetManager = NULL; #else iap->boot_file_type = YAP_QLY; iap->SavedState = saved_state; @@ -498,7 +498,7 @@ X_API YAP_file_type_t YAP_parse_yap_arguments(int argc, char *argv[], } else if (!strncmp("-home=", p, strlen("-home="))) { GLOBAL_Home = p + strlen("-home="); } else if (!strncmp("-cwd=", p, strlen("-cwd="))) { - if (!ChDir(p + strlen("-cwd=")) ) { + if (!Yap_ChDir(p + strlen("-cwd=")) ) { fprintf(stderr, " [ YAP unrecoverable error in setting cwd: %s ]\n", strerror(errno)); } diff --git a/CXX/yapdb.hh b/CXX/yapdb.hh index 01ef66dec..f7d132c19 100644 --- a/CXX/yapdb.hh +++ b/CXX/yapdb.hh @@ -88,7 +88,9 @@ protected: PredEntry *ap; /// auxiliary routine to find a predicate in the current module. - PredEntry *getPred(YAPTerm &t, Term *&outp); + + /// auxiliary routine to find a predicate in the current module. + PredEntry *getPred(YAPTerm &t, CELL *& outp); PredEntry *asPred() { return ap; }; @@ -122,7 +124,7 @@ protected: /// /// It is just a call to getPred inline YAPPredicate(Term t) { - CELL *v = NULL; + CELL *v = nullptr; YAPTerm tt = YAPTerm(t); ap = getPred(tt, v); } @@ -131,7 +133,7 @@ protected: /// /// It is just a call to getPred inline YAPPredicate(YAPTerm t) { - Term *v = nullptr; + CELL *v = nullptr; ap = getPred(t, v); } @@ -275,13 +277,13 @@ public: */ class X_API YAPFLIP : public YAPPredicate { public: - YAPFLIP(CPredicate call, YAPAtom name, uintptr_t arity, - YAPModule module = YAPModule(), CPredicate retry = 0, - CPredicate cut = 0, size_t extra = 0, bool test = false) + YAPFLIP(YAP_UserCPred call, YAPAtom name, YAP_Arity arity, + YAPModule module = YAPModule(), YAP_UserCPred retry = 0, + YAP_UserCPred cut = 0, YAP_Arity extra = 0, bool test = false) : YAPPredicate(name, arity, module) { if (retry) { - Yap_InitCPredBackCut(name.getName(), arity, extra, call, retry, cut, - UserCPredFlag); + YAP_UserBackCutCPredicate(name.getName(), call, retry, cut, arity, extra + ); } else { if (test) { YAP_UserCPredicate(name.getName(), call, arity); diff --git a/CXX/yapi.cpp b/CXX/yapi.cpp index f6fc2f3ea..f7fc1e8fb 100644 --- a/CXX/yapi.cpp +++ b/CXX/yapi.cpp @@ -12,14 +12,14 @@ extern "C" { #include "YapInterface.h" #include "blobs.h" -X_API char *Yap_TermToString(Term t, encoding_t encodingp, +X_API char *Yap_TermToBuffer(Term t, encoding_t encodingp, int flags); X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, arity_t arity); X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, arity_t, YAP_Term); X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred, - arity_t, arity_t); + YAP_Arity, YAP_Arity); #if YAP_PYTHON X_API bool do_init_python(void); @@ -934,17 +934,11 @@ void YAPEngine::doInit(YAP_file_type_t BootMode) } /* Begin preprocessor code */ /* live */ - __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "initialize_prolog"); -#if __ANDROID__ - Yap_AndroidBufp = (char *)malloc(Yap_AndroidMax = 4096); - Yap_AndroidBufp[0] = '\0'; - Yap_AndroidSz = 0; -#endif //yerror = YAPError(); #if YAP_PYTHON do_init_python(); #endif - YAP_PredEntryPtr p = YAP_AtomToPred( YAP_LookupAtom("initialize_prolog") ); + YAPPredicate p = YAPPredicate( YAPAtomTerm("initialize_prolog") ); YAPQuery initq = YAPQuery(YAPPredicate(p), nullptr); if (initq.next()) { @@ -992,7 +986,7 @@ YAPEngine::YAPEngine(int argc, char *argv[], } /// auxiliary routine to find a predicate in the current module. - PredEntry *YAPPredicate::getPred(YAPTerm &tt, Term *&outp) + PredEntry *YAPPredicate::getPred(YAPTerm &tt, CELL * &outp) { CACHE_REGS Term m = Yap_CurrentModule(), t = tt.term(); @@ -1015,9 +1009,11 @@ YAPEngine::YAPEngine(int argc, char *argv[], else if (IsPairTerm(t)) { Term ts[2]; - ts[0] = t; - ts[1] = m; - t = Yap_MkApplTerm(FunctorCsult, 2, ts); + Functor FunctorConsult = Yap_MkFunctor(Yap_LookupAtom("consult"), 1); + ts[1] = t; + ts[0] = m; + t = Yap_MkApplTerm(FunctorModule, 2, ts); + t = Yap_MkApplTerm(FunctorConsult, 1, &t); tt.put(t); outp = RepAppl(t) + 1; } @@ -1110,7 +1106,7 @@ YAPEngine::YAPEngine(int argc, char *argv[], if (LOCAL_ActiveError->prologPredLine) { s += "\n"; - s += LOCAL_ActiveError->prologPredFile->StrOfAE; + s += LOCAL_ActiveError->prologPredFile; s += ":"; sprintf(buf, "%ld", (long int)LOCAL_ActiveError->prologPredLine); s += buf; // std::to_string(LOCAL_ActiveError->prologPredLine) ; @@ -1118,7 +1114,7 @@ YAPEngine::YAPEngine(int argc, char *argv[], s += ":0 "; s += LOCAL_ActiveError->prologPredModule; s += ":"; - s += (LOCAL_ActiveError->prologPredName)->StrOfAE; + s += (LOCAL_ActiveError->prologPredName); s += "/"; sprintf(buf, "%ld", (long int)LOCAL_ActiveError->prologPredArity); s += // std::to_string(LOCAL_ActiveError->prologPredArity); @@ -1126,13 +1122,13 @@ YAPEngine::YAPEngine(int argc, char *argv[], } s += " error "; if (LOCAL_ActiveError->classAsText != nullptr) - s += LOCAL_ActiveError->classAsText->StrOfAE; + s += LOCAL_ActiveError->classAsText; s += "."; - s += LOCAL_ActiveError->errorAsText->StrOfAE; + s += LOCAL_ActiveError->errorAsText; s += ".\n"; if (LOCAL_ActiveError->errorTerm) { - Term t = LOCAL_ActiveError->errorTerm->Entry; + Term t = Yap_PopTermFromDB(LOCAL_ActiveError->errorTerm); if (t) { s += "error term is: "; diff --git a/CXX/yapi.hh b/CXX/yapi.hh index d16c219c0..44bcf5d1c 100644 --- a/CXX/yapi.hh +++ b/CXX/yapi.hh @@ -85,8 +85,16 @@ X_API extern void YAP_UserCPredicate(const char *, YAP_UserCPred, X_API extern void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, YAP_Arity, YAP_Term); -X_API extern void UserBackCPredicate(const char *name, int *init(), int *cont(), - int arity, int extra); +X_API extern void YAP_UserBackCPredicate(const char *name, + YAP_UserCPred init, + YAP_UserCPred cont, + YAP_Arity arity, YAP_Arity extra); + +X_API extern void YAP_UserBackCutCPredicate(const char *name, + YAP_UserCPred init, + YAP_UserCPred cont, + YAP_UserCPred cut, + YAP_Arity arity, YAP_Arity extra); X_API extern YAP_Term YAP_ReadBuffer(const char *s, YAP_Term *tp); diff --git a/CXX/yapq.hh b/CXX/yapq.hh index 090d44d0d..ca0d2c519 100644 --- a/CXX/yapq.hh +++ b/CXX/yapq.hh @@ -185,17 +185,15 @@ public: virtual void run(char *s) {} }; -void YAP_init_args::YAP_init_args() -{ - Yap_InitDefaults(this, NULL, 0, NULL); -} ; - /// @brief Setup all arguments to a new engine struct X_API YAPEngineArgs: YAP_init_args { public: - YAPEngineArgs(): yap_boot_params() { - #if YAP_PYTHON + YAPEngineArgs():yap_boot_params() { + char s[32]; + strcpy(s, "startup.yss" ); + Yap_InitDefaults(this,s,0,nullptr); +#if YAP_PYTHON Embedded = true; python_in_python = Py_IsInitialized(); #endif diff --git a/CXX/yapt.hh b/CXX/yapt.hh index f3ce6f5b7..c88519dc8 100644 --- a/CXX/yapt.hh +++ b/CXX/yapt.hh @@ -241,7 +241,7 @@ public: char *os; BACKUP_MACHINE_REGS(); - if (!(os = Yap_TermToString(Yap_GetFromSlot(t), enc, Handle_vars_f))) { + if (!(os = Yap_TermToBuffer(Yap_GetFromSlot(t), enc, Handle_vars_f))) { RECOVER_MACHINE_REGS(); return 0; } diff --git a/H/Atoms.h b/H/Atoms.h index 0cdcda777..420d0acf3 100644 --- a/H/Atoms.h +++ b/H/Atoms.h @@ -96,7 +96,7 @@ typedef struct ExtraAtomEntryStruct { #define USE_OFFSETS_IN_PROPS 0 #endif -typedef SFLAGS PropFlags; +typedef u_short PropFlags; /* basic property entry structure */ typedef struct PropEntryStruct { diff --git a/H/YapTerm.h b/H/YapTerm.h index 356064a21..eea862360 100644 --- a/H/YapTerm.h +++ b/H/YapTerm.h @@ -17,9 +17,6 @@ #include "YapTermConfig.h" #include "config.h" -typedef void *Functor; -typedef void *Atom; - #endif #if HAVE_STDINT_H @@ -29,6 +26,22 @@ typedef void *Atom; #include #endif +/* truth-values */ +/* stdbool defines the booleam type, bool, + and the constants false and true */ +#if HAVE_STDBOOL_H +#include +#else +#ifndef true +typedef int _Bool; +#define bool _Bool; + +#define false 0 +#define true 1 +#endif +#endif /* HAVE_STDBOOL_H */ + + #define ALIGN_BY_TYPE(X, TYPE) \ (((CELL)(X) + (sizeof(TYPE) - 1)) & ~(sizeof(TYPE) - 1)) @@ -45,59 +58,98 @@ typedef void *Atom; #if defined(PRIdPTR) -typedef intptr_t Int; -typedef uintptr_t UInt; +typedef intptr_t YAP_Int; +typedef uintptr_t YAP_UInt; #elif defined(_WIN64) -typedef int64_t Int; -typedef uint64_t UInt; +typedef int64_t YAP_Int; +typedef uint64_t YAP_UInt; #elif defined(_WIN32) -typedef int32_t Int; -typedef uint32_t UInt; +typedef int32_t YAP_Int; +typedef uint32_t YAP_UInt; #elif SIZEOF_LONG_INT == SIZEOF_INT_P -typedef long int Int; -typedef unsigned long int UInt; +typedef long int YAP_Int; +typedef unsigned long int YAP_UInt; #elif SIZEOF_INT == SIZEOF_INT_P -typedef int Int; -typedef unsigned int UInt; +typedef int YAP_Int; +typedef unsigned int YAP_UInt; #else #error Yap require integer types of the same size as a pointer #endif -/* */ typedef short int Short; -/* */ typedef unsigned short int UShort; +/* */ typedef short int YAP_Short; +/* */ typedef unsigned short int YAP_UShort; -typedef UInt CELL; +typedef YAP_UInt YAP_CELL; +typedef YAP_UInt YAP_Term; + +/* Type definitions */ + + +#ifndef TRUE +#define TRUE true +#endif +#ifndef FALSE +#endif + +typedef bool YAP_Bool; +#define FALSE false + +typedef YAP_Int YAP_handle_t; + + +typedef double YAP_Float; + +typedef void *YAP_Atom; + +typedef void *YAP_Functor; + +#ifdef YAP_H + +typedef YAP_Int Int; +typedef YAP_UInt UInt; +typedef YAP_Short Short; +typedef YAP_UShort UShort; typedef uint16_t BITS16; typedef int16_t SBITS16; typedef uint32_t BITS32; +typedef YAP_CELL CELL; + +typedef YAP_Term Term; + #define WordSize sizeof(BITS16) #define CellSize sizeof(CELL) #define SmallSize sizeof(SMALLUNSGN) +typedef YAP_Int Int; +typedef YAP_Float Float; +typedef YAP_handle_t yhandle_t; + +#endif + +#include "YapError.h" + +#include "../os/encoding.h" + +typedef encoding_t YAP_encoding_t; + #include "YapFormat.h" /************************************************************************************************* type casting macros *************************************************************************************************/ -typedef UInt Term; - -typedef Int yhandle_t; - -typedef double Float; - #if SIZEOF_INT < SIZEOF_INT_P #define SHORT_INTS 1 #else diff --git a/H/Yapproto.h b/H/Yapproto.h index 183a4e27c..a9a2aaa07 100755 --- a/H/Yapproto.h +++ b/H/Yapproto.h @@ -416,7 +416,7 @@ extern AAssetManager *Yap_assetManager; extern void *Yap_openAssetFile(const char *path); extern bool Yap_isAsset(const char *path); #endif -extern const char *Yap_getcwd(const char *, size_t); +extern const char *Yap_getcwd( char *, size_t); extern void Yap_cputime_interval(Int *, Int *); extern void Yap_systime_interval(Int *, Int *); extern void Yap_InitSysbits(int wid); diff --git a/H/Yatom.h b/H/Yatom.h index 3b0c8b4ed..507e9bfbd 100755 --- a/H/Yatom.h +++ b/H/Yatom.h @@ -1306,10 +1306,10 @@ void Yap_UpdateTimestamps(PredEntry *); void Yap_ErDBE(DBRef); DBTerm *Yap_StoreTermInDB(Term, int); DBTerm *Yap_StoreTermInDBPlusExtraSpace(Term, UInt, UInt *); -Term Yap_FetchTermFromDB(DBTerm *); -Term Yap_FetchClauseTermFromDB(DBTerm *); -Term Yap_PopTermFromDB(DBTerm *); -void Yap_ReleaseTermFromDB(DBTerm *); +Term Yap_FetchTermFromDB(void *); +Term Yap_FetchClauseTermFromDB(void *); +Term Yap_PopTermFromDB(void *); +void Yap_ReleaseTermFromDB(void *); /* init.c */ Atom Yap_GetOp(OpEntry *, int *, int); @@ -1598,8 +1598,8 @@ bool Yap_PutException(Term t); INLINE_ONLY inline EXTERN bool Yap_HasException(void) { return LOCAL_BallTerm != NULL; } -INLINE_ONLY inline EXTERN DBTerm *Yap_RefToException(void) { - DBTerm *dbt = LOCAL_BallTerm; +INLINE_ONLY inline EXTERN void *Yap_RefToException(void) { + void *dbt = LOCAL_BallTerm; LOCAL_BallTerm = NULL; return dbt; } diff --git a/include/VFS.h b/include/VFS.h index 198339c78..717f7d961 100644 --- a/include/VFS.h +++ b/include/VFS.h @@ -80,7 +80,7 @@ typedef struct vfs { const char *suffix; bool (*chDir)(struct vfs *me, const char *s); /** operations */ - void *(*open)(int sno, const char *fname, const char *io_mode); /// open an object + void *(*open)(struct vfs *,int sno, const char *fname, const char *io_mode); /// open an object /// in this space, usual w,r,a,b flags plus B (store in a buffer) bool (*close)(int sno); /// close the object int (*get_char)(int sno); /// get an octet to the stream @@ -92,7 +92,7 @@ typedef struct vfs { const char *(*nextdir)(void *d); /// walk to the next entry in a directory object bool (*closedir)(void *d); ; /// close access a directory object - bool (*stat)(const char *s, + bool (*stat)(struct vfs *,const char *s, vfs_stat *); /// obtain size, age, permissions of a file. bool (*isdir)(struct vfs *,const char *s); /// verify whether is directory. bool (*exists)(struct vfs *, const char *s); /// verify whether a file exists. diff --git a/include/YapDefs.h b/include/YapDefs.h index 3f11e3218..cdbee67cc 100755 --- a/include/YapDefs.h +++ b/include/YapDefs.h @@ -50,23 +50,10 @@ #include #include -#ifdef YAP_H /* The YAP main types */ #include "YapTerm.h" -/** - This term can never be constructed as a valid term, so it is - used as a "BAD" term -*/ -#define TermZERO ((Term)0) - -#else - -#include "YapConfig.h" - -#endif /* YAP_H */ - #if HAVE_STDINT_H #include #endif @@ -74,21 +61,6 @@ #include #endif -/* truth-values */ -/* stdbool defines the booleam type, bool, - and the constants false and true */ -#if HAVE_STDBOOL_H -#include -#else -#ifndef true -typedef int _Bool; -#define bool _Bool; - -#define false 0 -#define true 1 -#endif -#endif /* HAVE_STDBOOL_H */ - /** FALSE and TRUE are the pre-standard versions, still widely used. @@ -103,79 +75,26 @@ typedef int _Bool; typedef bool YAP_Bool; #endif -#ifdef YAP_H -/* if Yap.h is available, just reexport */ +/** + This term can never be constructed as a valid term, so it is + used as a "BAD" term +*/ +#define TermZERO ((Term)0) -#define YAP_CELL CELL -#define YAP_Term Term +#include "YapConfig.h" -#define YAP_Arity arity_t -#define YAP_Module Term - -#define YAP_Functor Functor - -#define YAP_Atom Atom - -#define YAP_Int Int - -#define YAP_UInt UInt - -#define YAP_Float Float - -#define YAP_handle_t yhandle_t - -#define YAP_PredEntryPtr struct pred_entry * - -#define YAP_UserCPred CPredicate - -#define YAP_agc_hook Agc_hook - -#define YAP_encoding_t encoding_t - -#else - -/* Type definitions */ -#if defined(PRIdPTR) -typedef uintptr_t YAP_UInt; -typedef intptr_t YAP_Int; -#elif _WIN64 -typedef int64_t YAP_Int; -typedef uint64_t YAP_UInt; -#elif _WIN32 -typedef int32_t YAP_Int; -typedef uint32_t YAP_UInt; -#else -typedef long int YAP_Int; -typedef unsigned long int YAP_UInt; -#endif - -typedef YAP_UInt YAP_CELL; - -typedef YAP_CELL YAP_Term; +typedef void *YAP_PredEntryPtr; typedef size_t YAP_Arity; typedef YAP_Term YAP_Module; -typedef struct FunctorEntry *YAP_Functor; - -typedef struct AtomEntry *YAP_Atom; - -typedef double YAP_Float; - -#ifndef TRUE -#define TRUE 1 -#endif -#ifndef FALSE -#define FALSE 0 -#endif - typedef YAP_Int YAP_handle_t; -typedef struct YAP_pred_entry *YAP_PredEntryPtr; +typedef void *YAP_PredEntryPtr; typedef YAP_Bool (*YAP_UserCPred)(void); @@ -187,8 +106,6 @@ typedef int (*YAP_agc_hook)(void *_Atom); typedef encoding_t YAP_encoding_t; -#endif - #if __ANDROID__ #include #include @@ -257,6 +174,10 @@ typedef enum { #define YAP_RECONSULT_MODE 1 #define YAP_BOOT_MODE 2 + +X_API YAP_file_type_t Yap_InitDefaults(void *init_args, char saved_state[], + int Argc, char *Argv[]); + typedef struct yap_boot_params { //> boot type as suggested by the user YAP_file_type_t boot_file_type; @@ -351,16 +272,8 @@ typedef struct yap_boot_params { int ErrorNo; //> errorstring char *ErrorCause; -#ifdef __cplusplus -void YAP_init_args(); -#endif } YAP_init_args; -#ifdef YAP_H -YAP_file_type_t Yap_InitDefaults(YAP_init_args *init_args, char saved_state[], - int Argc, char **Argv); -#endif - /* this should be opaque to the user */ typedef struct { unsigned long b; //> choice-point at entry diff --git a/include/YapError.h b/include/YapError.h index b89e01eb4..526956b46 100644 --- a/include/YapError.h +++ b/include/YapError.h @@ -176,48 +176,48 @@ INLINE_ONLY extern inline Term Yap_ensure_atom__(const char *fu, const char *fi, /// go back t } yap_error_stage_t; - /// a Prolo goal that caused a bug + /// a Prolog goal that caused a bug typedef struct error_prolog_source { - YAP_Int prologPredCl; - YAP_UInt prologPredLine; - YAP_UInt prologPredFirstLine; - YAP_UInt prologPredLastLine; - YAP_Atom prologPredName; - YAP_UInt prologPredArity; - YAP_Term prologPredModule; - YAP_Atom prologPredFile; - struct DB_TERM *errorGoal; + intptr_t prologPredCl; + uintptr_t prologPredLine; + uintptr_t prologPredFirstLine; + uintptr_t prologPredLastLine; + const char * prologPredName; + uintptr_t prologPredArity; + const char * prologPredModule; + const char * prologPredFile; + void *errorGoal; struct error_prolog_source *errorParent; } error_prolog_source_t; /// all we need to know about an error/throw - typedef struct yap_error_descriptor { + typedef struct error_descriptor { enum yap_error_status status; yap_error_class_number errorClass; - YAP_Atom errorAsText; - YAP_Atom classAsText; + const char * errorAsText; + const char * classAsText; yap_error_number errorNo; - YAP_Int errorLine; + intptr_t errorLine; const char *errorFunction; const char *errorFile; // struct error_prolog_source *errorSource; - YAP_Int prologPredCl; - YAP_UInt prologPredLine; - YAP_UInt prologPredFirstLine; - YAP_UInt prologPredLastLine; - YAP_Atom prologPredName; - YAP_UInt prologPredArity; - YAP_Term prologPredModule; - YAP_Atom prologPredFile; - YAP_UInt prologParserLine; - YAP_UInt prologParserFirstLine; - YAP_UInt prologParserLastLine; - YAP_Atom prologParserName; - YAP_Atom prologParserFile; - YAP_Bool prologConsulting; - struct DB_TERM *errorTerm; - YAP_Term rawErrorTerm, rawExtraErrorTerm; + intptr_t prologPredCl; + uintptr_t prologPredLine; + uintptr_t prologPredFirstLine; + uintptr_t prologPredLastLine; + const char * prologPredName; + uintptr_t prologPredArity; + const char * prologPredModule; + const char * prologPredFile; + uintptr_t prologParserLine; + uintptr_t prologParserFirstLine; + uintptr_t prologParserLastLine; + const char * prologParserName; + const char * prologParserFile; + bool prologConsulting; + void *errorTerm; + uintptr_t rawErrorTerm, rawExtraErrorTerm; char *errorMsg; size_t errorMsgLen; struct yap_error_descriptor *top_error; diff --git a/include/YapInterface.h b/include/YapInterface.h index 547b1e59d..52853a40f 100755 --- a/include/YapInterface.h +++ b/include/YapInterface.h @@ -268,18 +268,19 @@ extern X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, extern X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred, YAP_Arity, YAP_Arity); -/* YAP_Int YAP_ListLength(YAP_Term t) */ -extern X_API YAP_Int YAP_ListLength(YAP_Term); - -extern X_API size_t YAP_UTF8_TextLength(YAP_Term t); /* void UserBackCPredicate(char *name, int *init(), int *cont(), int *cut(), int arity, int extra) */ -extern X_API void YAP_UserBackCutCPredicate(const char *, YAP_UserCPred, +extern X_API void YAP_UserBackCutCPredicate(const char *name, YAP_UserCPred, YAP_UserCPred, YAP_UserCPred, YAP_Arity, YAP_Arity); +/* YAP_Int YAP_ListLength(YAP_Term t) */ +extern X_API YAP_Int YAP_ListLength(YAP_Term); + +extern X_API size_t YAP_UTF8_TextLength(YAP_Term t); + /* void CallProlog(YAP_Term t) */ extern X_API YAP_Int YAP_CallProlog(YAP_Term t); @@ -399,7 +400,7 @@ extern X_API YAP_Term YAP_ReadFromStream(int s); /// read a Prolog clause from a Prolog opened stream $s$. Similar to /// YAP_ReadFromStream() but takes /// default options from read_clause/3. -extern X_API YAP_Term YAP_ReadFromStream(int s); +extern X_API YAP_Term YAP_ReadClauseFromStream(int s); extern X_API void YAP_Write(YAP_Term t, FILE *s, int); diff --git a/include/YapStreams.h b/include/YapStreams.h index 92ee8d0f7..60e330158 100644 --- a/include/YapStreams.h +++ b/include/YapStreams.h @@ -136,9 +136,9 @@ FILE *open_memstream(char **buf, size_t *len); #endif #if __ANDROID__ - -#undef HAVE_FMEMOPEN -#undef HAVE_OPEN_MEMSTREAM +//extern FILE * fmemopen(void *buf, size_t size, const char *mode); +#define HAVE_FMEMOPEN 1 +#define HAVE_OPEN_MEMSTREAM 1 #endif #if HAVE_FMEMOPEN diff --git a/os/CMakeLists.txt b/os/CMakeLists.txt index 6188d1425..ccc16e8ed 100644 --- a/os/CMakeLists.txt +++ b/os/CMakeLists.txt @@ -7,7 +7,10 @@ set (YAPOS_SOURCES console.c files.c fmem.c - fmemopen.c + # fmemopen.c + #android/fmemopen.c + # android/fopencookie.c + # android/open_memstream.c format.c iopreds.c mem.c diff --git a/os/assets.c b/os/assets.c index 96f713869..2d8639b73 100644 --- a/os/assets.c +++ b/os/assets.c @@ -35,197 +35,190 @@ static char SccsId[] = "%W% %G%"; #if __ANDROID__ + #include #include -AAssetManager * Yap_assetManager; +AAssetManager *Yap_assetManager; -jboolean Java_pt_up_yap_app_YAPDroid_setAssetManager(JNIEnv* env, jclass clazz, jobject assetManager) -{ +jboolean +Java_pt_up_yap_app_YAPDroid_setAssetManager(JNIEnv *env, jclass clazz, jobject assetManager) { Yap_assetManager = AAssetManager_fromJava(env, assetManager); -return true; + return true; } static void * -open_asset__( int sno, const char *fname, const char *io_mode) -{ - int mode; - const void *buf; - VFS_t *me = GLOBAL_Stream[sno].vfs; - if (strstr(fname,"/assets") == fname) { - // we're in - if ( Yap_assetManager == NULL) { - PlIOError(PERMISSION_ERROR_OPEN_SOURCE_SINK, TermNil, - "asset manager", - fname); - return NULL; - } - if (strchr(io_mode, 'w') || strchr(io_mode, 'a')) { - PlIOError(PERMISSION_ERROR_OPEN_SOURCE_SINK, TermNil, - "%s: no writing but flags are %s", - fname, io_mode); - return NULL; - } - if (strchr(io_mode, 'B')) - mode = AASSET_MODE_BUFFER; - else { - mode = AASSET_MODE_UNKNOWN; - } - AAsset *a = AAssetManager_open( Yap_assetManager, fname, mode); - // try not to use it as an asset - off64_t sz = AAsset_getLength64(a), sz0 = 0; - int fd; - StreamDesc *st = GLOBAL_Stream+sno; - if ((fd = AAsset_openFileDescriptor64(a, &sz0, &sz)) >= 0) { - // can use it as red-only file - st->file = fdopen(fd, "r"); - st->vfs = me; - st->vfs_handle = a; - return a; - } else if ((buf = AAsset_getBuffer(a))) { - // copy to memory - bool rc = Yap_set_stream_to_buf(st, buf, sz); - if (rc) AAsset_close(a); - return st; - } - // should be done, but if not - GLOBAL_Stream[sno].vfs_handle= a; - st->vfs = me; - return a; - } - return NULL; +open_asset__(VFS_t *me, int sno, const char *fname, const char *io_mode) { + int mode; + const void *buf; + if (strchr(io_mode, 'B')) + mode = AASSET_MODE_BUFFER; + else { + mode = AASSET_MODE_UNKNOWN; + } + fname += strlen(me->prefix) + 1; + AAsset *a = AAssetManager_open(Yap_assetManager, fname, mode); + if (!a) + return NULL; + // try not to use it as an asset + off64_t sz = AAsset_getLength64(a), sz0 = 0; + int fd; + StreamDesc *st = GLOBAL_Stream + sno; + if ((buf = AAsset_getBuffer(a))) { + // copy to memory + bool rc = Yap_set_stream_to_buf(st, buf, sz); + if (rc) AAsset_close(a); + st->vfs = NULL; + st->vfs_handle = NULL; + st->status = InMemory_Stream_f|Seekable_Stream_f|Input_Stream_f; + return st; + } else if ((fd = AAsset_openFileDescriptor64(a, &sz0, &sz)) >= 0) { + // can use it as read-only file + st->file = fdopen(fd, "r"); + st->vfs = NULL; + st->vfs_handle = NULL; + st->status = Seekable_Stream_f|Input_Stream_f; + return st; + } else { + // should be done, but if not + GLOBAL_Stream[sno].vfs_handle = a; + st->vfs = me; + st->status = Input_Stream_f; + return a; + } } static bool -close_asset(int sno) -{ - AAsset_close(GLOBAL_Stream[sno].vfs_handle); - return true; +close_asset(int sno) { + AAsset_close(GLOBAL_Stream[sno].vfs_handle); + return true; } -static int64_t seek64(int sno, int64_t offset, int whence) -{ - return AAsset_seek64(GLOBAL_Stream[sno].vfs_handle, offset, whence); +static int64_t seek64(int sno, int64_t offset, int whence) { + return AAsset_seek64(GLOBAL_Stream[sno].vfs_handle, offset, whence); } -static int getc_asset(int sno) -{ - int ch; - if ( AAsset_read (GLOBAL_Stream[sno].vfs_handle, &ch, 1) ) - return ch; - return -1; +static int getc_asset(int sno) { + int ch; + if (AAsset_read(GLOBAL_Stream[sno].vfs_handle, &ch, 1)) + return ch; + return -1; } -static void *opendir_a( VFS_t *me, const char *dirName) -{ - return (void *)AAssetManager_openDir (Yap_assetManager, dirName); +static void *opendir_a(VFS_t *me, const char *dirName) { + dirName += strlen(me->prefix) + 1; + return (void *) AAssetManager_openDir(Yap_assetManager, dirName); } -static const char *readdir_a(void *dirHandle) -{ - return AAssetDir_getNextFileName ((AAssetDir *)dirHandle); +static const char *readdir_a(void *dirHandle) { + return AAssetDir_getNextFileName((AAssetDir *) dirHandle); } -static bool closedir_a(void *dirHandle) -{ - AAssetDir_close ((AAssetDir *)dirHandle); - return true; +static bool closedir_a(void *dirHandle) { + AAssetDir_close((AAssetDir *) dirHandle); + return true; } -static bool stat_a(VFS_t *me, const char *fname, vfs_stat *out) -{ - struct stat bf; - if (stat( "/assets", &bf)) { - - out->st_dev = bf.st_dev; - out->st_uid = bf.st_uid; - out->st_gid = bf.st_gid; - memcpy(&out->st_atimespec, (const void *)&out->st_atimespec, sizeof(struct timespec)); - memcpy(&out->st_mtimespec,(const void *) &out->st_mtimespec, sizeof(struct timespec)); - memcpy(&out->st_ctimespec, (const void *)&out->st_ctimespec, sizeof(struct timespec)); - memcpy(&out->st_birthtimespec, (const void *)&out->st_birthtimespec, sizeof(struct timespec)); - } - AAsset *a = AAssetManager_open( Yap_assetManager , fname, AASSET_MODE_UNKNOWN); +static bool stat_a(VFS_t *me, const char *fname, vfs_stat *out) { + struct stat bf; + fname += strlen(me->prefix) + 1; + if (stat("/assets", &bf)) { + + out->st_dev = bf.st_dev; + out->st_uid = bf.st_uid; + out->st_gid = bf.st_gid; + memcpy(&out->st_atimespec, (const void *) &out->st_atimespec, sizeof(struct timespec)); + memcpy(&out->st_mtimespec, (const void *) &out->st_mtimespec, sizeof(struct timespec)); + memcpy(&out->st_ctimespec, (const void *) &out->st_ctimespec, sizeof(struct timespec)); + memcpy(&out->st_birthtimespec, (const void *) &out->st_birthtimespec, + sizeof(struct timespec)); + } + AAsset *a = AAssetManager_open(Yap_assetManager, fname, AASSET_MODE_UNKNOWN); // try not to use it as an asset - out->st_size = AAsset_getLength64(a); - AAsset_close(a); - return true; - + out->st_size = AAsset_getLength64(a); + AAsset_close(a); + return true; + } static -bool is_dir_a( VFS_t *me,const char *dirName) -{ - bool rc; +bool is_dir_a(VFS_t *me, const char *dirName) { + bool rc; + dirName += strlen(me->prefix) + 1; // try not to use it as an asset - AAssetDir *d = AAssetManager_openDir ( Yap_assetManager, dirName); + AAssetDir *d = AAssetManager_openDir(Yap_assetManager, dirName); if (d == NULL) - return false; + return false; rc = (AAssetDir_getNextFileName(d) != NULL); - AAssetDir_close(d); - return rc; + __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "isdir %s <%p>", dirName, d); + AAssetDir_close(d); + return rc; } static -VFS_t *exists_a(VFS_t *me, const char *dirName) -{ +bool exists_a(VFS_t *me, const char *dirName) { + dirName += strlen(me->prefix) + 1; // try not to use it as an asset - AAsset *d = AAssetManager_open ( Yap_assetManager, dirName, AASSET_MODE_UNKNOWN); + AAsset *d = AAssetManager_open(Yap_assetManager, dirName, AASSET_MODE_UNKNOWN); + __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "exists %s <%p>", dirName, d); if (d == NULL) - return NULL; - AAsset_close(d); - return me; + return false; + AAsset_close(d); + return true; } -static bool set_cwd (VFS_t *me, const char *dirName) { +extern char virtual_cwd[YAP_FILENAME_MAX + 1]; + +static bool set_cwd(VFS_t *me, const char *dirName) { chdir("/assets"); - if (me->virtual_cwd) - free((void*)(me->virtual_cwd)); - me->virtual_cwd = malloc( sizeof(dirName) + 1 ); - return me!= NULL; + strcpy(virtual_cwd, dirName); + __android_log_print(ANDROID_LOG_INFO, "YAPDroid", + "chdir %s", virtual_cwd); + Yap_do_low_level_trace=1; + return true; } #endif VFS_t * -Yap_InitAssetManager( void ) -{ +Yap_InitAssetManager(void) { #if __ANDROID__ VFS_t *me; - /* init standard VFS */ - me = (VFS_t *)Yap_AllocCodeSpace(sizeof(struct vfs)); - me->name = "/assets"; - me->vflags = VFS_CAN_EXEC|VFS_CAN_SEEK|VFS_HAS_PREFIX; /// the main flags describing the operation of the Fs. - me->prefix = "/assets"; - /** operations */ - me->open = open_asset__; /// open an object in this space - me->close= close_asset; /// close the object - me->get_char = getc_asset; /// get an octet to the stream - me->put_char = NULL; /// output an octet to the stream - me->seek = seek64; /// jump around the stream - me->opendir = opendir_a; /// open a directory object, if one exists - me->nextdir = readdir_a; /// open a directory object, if one exists - me->closedir = closedir_a; /// close access a directory object - me->stat = stat_a; /// obtain size, age, permissions of a file. - me->isdir = is_dir_a; /// obtain size, age, permissions of a file. - me->exists = exists_a; /// obtain size, age, permissions of a file. - me->chdir = set_cwd; /// chnage working directory. - me->enc = ENC_ISO_UTF8; /// how the file is encoded. - me->parsers = NULL; /// a set of parsers that can read the stream and generate a term - me->writers = NULL; - LOCK(BGL); - me-> next = GLOBAL_VFS; - GLOBAL_VFS = me; - return me; - UNLOCK(BGL); - return me; + /* init standard VFS */ + me = (VFS_t *) Yap_AllocCodeSpace(sizeof(struct vfs)); + me->name = "/assets"; + me->vflags = VFS_CAN_EXEC | VFS_CAN_SEEK | + VFS_HAS_PREFIX; /// the main flags describing the operation of the Fs. + me->prefix = "/assets"; + /** operations */ + me->open = open_asset__; /// open an object in this space + me->close = close_asset; /// close the object + me->get_char = getc_asset; /// get an octet to the stream + me->put_char = NULL; /// output an octet to the stream + me->seek = seek64; /// jump around the stream + me->opendir = opendir_a; /// open a directory object, if one exists + me->nextdir = readdir_a; /// open a directory object, if one exists + me->closedir = closedir_a; /// close access a directory object + me->stat = stat_a; /// obtain size, age, permissions of a file. + me->isdir = is_dir_a; /// obtain size, age, permissions of a file. + me->exists = exists_a; /// obtain size, age, permissions of a file. + me->chdir = set_cwd; /// chnage working directory. + me->enc = ENC_ISO_UTF8; /// how the file is encoded. + me->parsers = NULL; /// a set of parsers that can read the stream and generate a term + me->writers = NULL; + LOCK(BGL); + me->next = GLOBAL_VFS; + GLOBAL_VFS = me; + return me; + UNLOCK(BGL); + return me; #else return NULL; #endif diff --git a/os/encoding.h b/os/encoding.h index f25c4174e..a4141bad5 100644 --- a/os/encoding.h +++ b/os/encoding.h @@ -20,6 +20,11 @@ #define ENCODING_H 1 #include "YapError.h" +#if HAVE_STRING_H + +#include + +#endif typedef enum { ENC_OCTET = 0, /// binary files diff --git a/os/files.c b/os/files.c index b579d832d..0c6841551 100644 --- a/os/files.c +++ b/os/files.c @@ -460,7 +460,7 @@ static Int exists_directory(USES_REGS1) { #if HAVE_STAT struct SYSTEM_STAT ss; - file_name = RepAtom(AtomOfTerm(tname))->StrOfAE; + file_name = Yap_VF(RepAtom(AtomOfTerm(tname))->StrOfAE); if (SYSTEM_STAT(file_name, &ss) != 0) { /* ignore errors while checking a file */ return false; @@ -483,7 +483,7 @@ static Int is_absolute_file_name(USES_REGS1) { /* file_base_name(Stream,N) */ int l = push_text_stack(); const char *buf = Yap_TextTermToText(t PASS_REGS); if (buf) { - rc = Yap_IsAbsolutePath(buf); + rc = Yap_IsAbsolutePath(buf, true); } else { at = AtomOfTerm(t); #if _WIN32 diff --git a/os/fmem.c b/os/fmem.c index 738281f6b..66dfb6b24 100644 --- a/os/fmem.c +++ b/os/fmem.c @@ -114,16 +114,18 @@ bool fill_pads(int sno, int sno0, int total, format_info *fg USES_REGS) return true; } -bool Yap_set_stream_to_buf(StreamDesc *st, const char *buf, encoding_t enc, - size_t nchars) { +bool Yap_set_stream_to_buf(StreamDesc *st, const char *buf, + size_t nchars USES_REGS) { FILE *f; // like any file stream. - st->file = f = fmemopen((void *)buf, nchars, "r"); - st->status = Input_Stream_f | InMemory_Stream_f | Seekable_Stream_f; + st->file = f = fmemopen((char *)buf, nchars, "r"); + st->status = Input_Stream_f | Seekable_Stream_f | InMemory_Stream_f; st->vfs = NULL; - st->encoding = enc; + st->encoding = LOCAL_encoding; Yap_DefaultStreamOps(st); + st->linecount = 0; + st->linepos = st->charcount = 0; return true; } @@ -198,9 +200,7 @@ int Yap_open_buf_write_stream(encoding_t enc, memBufSource src) { // setbuf(st->file, NULL); st->status |= Seekable_Stream_f; #else - st->file = fmemopen((void *)buf, nchars, "w"); - st->nsize = nchars; - st->nbuf = buf; + st->file = fmemopen((void *)st->nbuf, st->nsize, "w"); if (!st->nbuf) { return -1; } @@ -292,17 +292,15 @@ void Yap_MemOps(StreamDesc *st) { st->stream_getc = PlGetc; } -static int sssno; bool Yap_CloseMemoryStream(int sno) { - sssno++; - // if (sssno > 1720) Yap_do_low_level_trace=1; - if ((GLOBAL_Stream[sno].status & Output_Stream_f)) { + if ((GLOBAL_Stream[sno].status & Output_Stream_f) && GLOBAL_Stream[sno].file) { fflush(GLOBAL_Stream[sno].file); fclose(GLOBAL_Stream[sno].file); if (GLOBAL_Stream[sno].status & FreeOnClose_Stream_f) free(GLOBAL_Stream[sno].nbuf); } else { + if (GLOBAL_Stream[sno].file) fclose(GLOBAL_Stream[sno].file); if (GLOBAL_Stream[sno].status & FreeOnClose_Stream_f) free(GLOBAL_Stream[sno].nbuf); diff --git a/os/fmemopen-android.c b/os/fmemopen-android.c index 356de464b..a4c9fa823 100644 --- a/os/fmemopen-android.c +++ b/os/fmemopen-android.c @@ -1,10 +1,12 @@ -* Copyright (C) 2007 Eric Blake +/* Copyright (C) 2007 Eric Blake * Permission to use, copy, modify, and distribute this software * is freely granted, provided that this notice is preserved. * * Modifications for Android written Jul 2009 by Alan Viverette */ +#if __ANDROID__ + /* FUNCTION >---open a stream around a fixed-length string @@ -69,7 +71,7 @@ Supporting OS subroutines required: <>. #include #include #include -#include "stdioext.h" +//#include "stdioext.h" /* Describe details of an open memstream. */ typedef struct fmemcookie { @@ -172,13 +174,13 @@ fmemseek(void *cookie, fpos_t pos, int whence) } else { - if (c->writeonly && c->pos < c->eof) + if (c->writeonly && c->pos < c->eof) { c->buf[c->pos] = c->saved; c->saved = '\0'; } c->pos = offset; - if (c->writeonly && c->pos < c->eof) + if (c->writeonly && c->pos < c->eof) { c->saved = c->buf[c->pos]; c->buf[c->pos] = '\0'; @@ -206,9 +208,9 @@ fmemopen(void *buf, size_t size, const char *mode) int flags; int dummy; - if ((flags = __sflags (mode, &dummy)) == 0) + if ((flags = __sflags (mode, &dummy)) == 0) return NULL; - if (!size || !(buf || flags & __SAPP)) + if (!size || !(buf || flags & __SAPP)) { return NULL; } @@ -225,7 +227,7 @@ fmemopen(void *buf, size_t size, const char *mode) c->max = size; /* 9 modes to worry about. */ /* w/a, buf or no buf: Guarantee a NUL after any file writes. */ - c->writeonly = (flags & __SWR) != 0; + c->writeonly = (flags & __SWR) != 0; c->saved = '\0'; if (!buf) { @@ -233,7 +235,7 @@ fmemopen(void *buf, size_t size, const char *mode) c->buf = (char *) (c + 1); *(char *) buf = '\0'; c->pos = c->eof = 0; - c->append = (flags & __SAPP) != 0; + c->append = (flags & __SAPP) != 0; } else { @@ -244,7 +246,7 @@ fmemopen(void *buf, size_t size, const char *mode) /* a/a+ and buf: position and size at first NUL. */ buf = memchr (c->buf, '\0', size); c->eof = c->pos = buf ? (char *) buf - c->buf : size; - if (!buf && c->writeonly) + if (!buf && c->writeonly) /* a: guarantee a NUL within size even if no writes. */ c->buf[size - 1] = '\0'; c->append = 1; @@ -267,10 +269,12 @@ fmemopen(void *buf, size_t size, const char *mode) fp->_file = -1; fp->_flags = flags; fp->_cookie = c; - fp->_read = flags & (__SRD | __SRW) ? fmemread : NULL; - fp->_write = flags & (__SWR | __SRW) ? fmemwrite : NULL; + fp->_read = flags & (__SRD | __SRW) ? fmemread : NULL; + fp->_write = flags & (__SWR | __SRW) ? fmemwrite : NULL; fp->_seek = fmemseek; fp->_close = fmemclose; return fp; } + +#endif diff --git a/os/iopreds.c b/os/iopreds.c index c557a46dc..e8cae80cf 100644 --- a/os/iopreds.c +++ b/os/iopreds.c @@ -39,42 +39,57 @@ static char SccsId[] = "%W% %G%"; #include "Yatom.h" #include "yapio.h" #include + #if HAVE_UNISTD_H + #include + #endif #if HAVE_STDARG_H + #include + #endif #if HAVE_CTYPE_H -#include #endif #if HAVE_WCTYPE_H -#include #endif #if HAVE_SYS_TIME_H + #include + #endif #if HAVE_SYS_TYPES_H + #include + #endif #ifdef HAVE_SYS_STAT_H + #include + #endif #if HAVE_SYS_SELECT_H && !_MSC_VER && !defined(__MINGW32__) + #include + #endif #ifdef HAVE_UNISTD_H -#include #endif #if HAVE_STRING_H + #include + #endif #if HAVE_SIGNAL_H + #include + #endif #if HAVE_FCNTL_H /* for O_BINARY and O_TEXT in WIN32 */ #include + #endif #ifdef _WIN32 #if HAVE_IO_H @@ -109,301 +124,301 @@ FILE *Yap_stdout; FILE *Yap_stderr; static Term gethdir(Term t) { - CACHE_REGS - Atom aref = AtomOfTerm(t); - char *s = RepAtom(aref)->StrOfAE; - size_t nsz; + CACHE_REGS + Atom aref = AtomOfTerm(t); + char *s = RepAtom(aref)->StrOfAE; + size_t nsz; - s = strncpy(LOCAL_FileNameBuf, RepAtom(aref)->StrOfAE, MAXPATHLEN - 1); - if (!s) { - return false; - } - if (TermDot == t) { - return TermEmptyAtom; - } - nsz = strlen(s); - if (!Yap_dir_separator(s[nsz - 1])) { + s = strncpy(LOCAL_FileNameBuf, RepAtom(aref)->StrOfAE, MAXPATHLEN - 1); + if (!s) { + return false; + } + if (TermDot == t) { + return TermEmptyAtom; + } + nsz = strlen(s); + if (!Yap_dir_separator(s[nsz - 1])) { #if _WIN32 - s[nsz] = '\\'; + s[nsz] = '\\'; #else - s[nsz] = '/'; + s[nsz] = '/'; #endif - s[nsz + 1] = '\0'; - } - return MkAtomTerm(Yap_LookupAtom(s)); + s[nsz + 1] = '\0'; + } + return MkAtomTerm(Yap_LookupAtom(s)); } static Term issolutions(Term t) { - if (t == TermFirst || t == TermAll) - return t; + if (t == TermFirst || t == TermAll) + return t; - if (IsVarTerm(t)) { - Yap_Error(INSTANTIATION_ERROR, t, "solutions in {first, all}."); + if (IsVarTerm(t)) { + Yap_Error(INSTANTIATION_ERROR, t, "solutions in {first, all}."); + return TermZERO; + } + if (IsAtomTerm(t)) { + Yap_Error(DOMAIN_ERROR_SOLUTIONS, t, "solutions in {first, all}"); + return TermZERO; + } + Yap_Error(TYPE_ERROR_ATOM, t, "solutions in {first, all}}"); return TermZERO; - } - if (IsAtomTerm(t)) { - Yap_Error(DOMAIN_ERROR_SOLUTIONS, t, "solutions in {first, all}"); - return TermZERO; - } - Yap_Error(TYPE_ERROR_ATOM, t, "solutions in {first, all}}"); - return TermZERO; } static Term is_file_type(Term t) { - if (t == TermTxt || t == TermProlog || t == TermSource || - t == TermExecutable || t == TermQly || t == TermDirectory) - return t; + if (t == TermTxt || t == TermProlog || t == TermSource || + t == TermExecutable || t == TermQly || t == TermDirectory) + return t; - if (IsVarTerm(t)) { - Yap_Error(INSTANTIATION_ERROR, t, - "file_type in {txt,prolog,exe,directory...}"); + if (IsVarTerm(t)) { + Yap_Error(INSTANTIATION_ERROR, t, + "file_type in {txt,prolog,exe,directory...}"); + return TermZERO; + } + if (IsAtomTerm(t)) { + Yap_Error(DOMAIN_ERROR_FILE_TYPE, t, + "file_type in {txt,prolog,exe,directory...}"); + return TermZERO; + } + Yap_Error(TYPE_ERROR_ATOM, t, "file_type in {txt,prolog,exe,directory...}"); return TermZERO; - } - if (IsAtomTerm(t)) { - Yap_Error(DOMAIN_ERROR_FILE_TYPE, t, - "file_type in {txt,prolog,exe,directory...}"); - return TermZERO; - } - Yap_Error(TYPE_ERROR_ATOM, t, "file_type in {txt,prolog,exe,directory...}"); - return TermZERO; } static Term is_file_errors(Term t) { - if (t == TermFail || t == TermError) - return t; + if (t == TermFail || t == TermError) + return t; - if (IsVarTerm(t)) { - Yap_Error(INSTANTIATION_ERROR, t, "file_error in {fail,error}."); + if (IsVarTerm(t)) { + Yap_Error(INSTANTIATION_ERROR, t, "file_error in {fail,error}."); + return TermZERO; + } + if (IsAtomTerm(t)) { + Yap_Error(DOMAIN_ERROR_FILE_ERRORS, t, "file_error in {fail,error}."); + return TermZERO; + } + Yap_Error(TYPE_ERROR_ATOM, t, "file_error in {fail,error}."); return TermZERO; - } - if (IsAtomTerm(t)) { - Yap_Error(DOMAIN_ERROR_FILE_ERRORS, t, "file_error in {fail,error}."); - return TermZERO; - } - Yap_Error(TYPE_ERROR_ATOM, t, "file_error in {fail,error}."); - return TermZERO; } static void unix_upd_stream_info(StreamDesc *s) { - if (s->status & InMemory_Stream_f) { - s->status |= Seekable_Stream_f; - return; - } - Yap_socketStream(s); + if (s->status & InMemory_Stream_f) { + s->status |= Seekable_Stream_f; + return; + } + Yap_socketStream(s); #if _MSC_VER || defined(__MINGW32__) - { - if (_isatty(_fileno(s->file))) { - s->status |= Tty_Stream_f | Reset_Eof_Stream_f | Promptable_Stream_f; - /* make all console descriptors unbuffered */ - setvbuf(s->file, NULL, _IONBF, 0); + { + if (_isatty(_fileno(s->file))) { + s->status |= Tty_Stream_f | Reset_Eof_Stream_f | Promptable_Stream_f; + /* make all console descriptors unbuffered */ + setvbuf(s->file, NULL, _IONBF, 0); + return; + } +#if _MSC_VER + /* standard error stream should never be buffered */ + else if (StdErrStream == s - GLOBAL_Stream) { + setvbuf(s->file, NULL, _IONBF, 0); + } +#endif + s->status |= Seekable_Stream_f; return; } -#if _MSC_VER - /* standard error stream should never be buffered */ - else if (StdErrStream == s - GLOBAL_Stream) { - setvbuf(s->file, NULL, _IONBF, 0); - } -#endif - s->status |= Seekable_Stream_f; - return; - } #else #if HAVE_ISATTY #if __simplescalar__ - /* isatty does not seem to work with simplescar. I'll assume the first - three streams will probably be ttys (pipes are not thatg different) */ - if (s - Stream < 3) { - s->name = AtomTty; - s->status |= Tty_Stream_f | Reset_Eof_Stream_f | Promptable_Stream_f; - } -#else - { - int filedes; /* visualc */ - if (!s->file) { - s->name = AtomNil; - return; - } - filedes = fileno(s->file); - if (isatty(filedes)) { -#if HAVE_TTYNAME - int rc = ttyname_r(filedes, LOCAL_FileNameBuf, YAP_FILENAME_MAX - 1); - if (rc == 0) - s->name = Yap_LookupAtom(LOCAL_FileNameBuf); - else - s->name = AtomTtys; -#else + /* isatty does not seem to work with simplescar. I'll assume the first + three streams will probably be ttys (pipes are not thatg different) */ + if (s - Stream < 3) { s->name = AtomTty; -#endif s->status |= Tty_Stream_f | Reset_Eof_Stream_f | Promptable_Stream_f; - return; } - } +#else + { + int filedes; /* visualc */ + if (!s->file) { + s->name = AtomNil; + return; + } + filedes = fileno(s->file); + if (isatty(filedes)) { +#if HAVE_TTYNAME + int rc = ttyname_r(filedes, LOCAL_FileNameBuf, YAP_FILENAME_MAX - 1); + if (rc == 0) + s->name = Yap_LookupAtom(LOCAL_FileNameBuf); + else + s->name = AtomTtys; +#else + s->name = AtomTty; +#endif + s->status |= Tty_Stream_f | Reset_Eof_Stream_f | Promptable_Stream_f; + return; + } + } #endif #endif /* HAVE_ISATTY */ #endif /* _MSC_VER */ - s->status |= Seekable_Stream_f; + 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 & (Promptable_Stream_f)) { - Yap_ConsoleOps(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 & (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; - } + else if (st->file != NULL && 0 && !(st->status & InMemory_Stream_f)) { + st->stream_wgetc = get_wchar_from_file; + } #endif - if (GLOBAL_CharConversionTable != NULL) - st->stream_wgetc_for_read = ISOWGetc; - else - st->stream_wgetc_for_read = st->stream_wgetc; - 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 (GLOBAL_CharConversionTable != NULL) + st->stream_wgetc_for_read = ISOWGetc; + else + st->stream_wgetc_for_read = st->stream_wgetc; + 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); + } } static void InitFileIO(StreamDesc *s) { - CACHE_REGS - Yap_DefaultStreamOps(s); + CACHE_REGS + Yap_DefaultStreamOps(s); } static void InitStdStream(int sno, SMALLUNSGN flags, FILE *file, VFS_t *vfsp) { - StreamDesc *s = &GLOBAL_Stream[sno]; - s->file = file; - s->status = flags; - s->linepos = 0; - s->linecount = 1; - s->charcount = 0; - s->vfs = vfsp; - s->encoding = ENC_ISO_UTF8; - INIT_LOCK(s->streamlock); - if (vfsp != NULL) { - s->u.private_data = - vfsp->open(sno, vfsp->name, (sno == StdInStream ? "read" : "write")); - if (s->u.private_data == NULL) { - (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, MkIntTerm(sno), "%s", - vfsp->name)); - return; + StreamDesc *s = &GLOBAL_Stream[sno]; + s->file = file; + s->status = flags; + s->linepos = 0; + s->linecount = 1; + s->charcount = 0; + s->vfs = vfsp; + s->encoding = ENC_ISO_UTF8; + INIT_LOCK(s->streamlock); + if (vfsp != NULL) { + s->u.private_data = + vfsp->open(vfsp, sno, vfsp->name, (sno == StdInStream ? "read" : "write")); + if (s->u.private_data == NULL) { + (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, MkIntTerm(sno), "%s", + vfsp->name)); + return; + } + } else { + unix_upd_stream_info(s); } - } else { - unix_upd_stream_info(s); - } - /* Getting streams to prompt is a mess because we need for cooperation - between readers and writers to the stream :-( - */ - InitFileIO(s); - switch (sno) { - case 0: - s->name = AtomUserIn; - break; - case 1: - s->name = AtomUserOut; - break; - default: - s->name = AtomUserErr; - break; - } - s->user_name = MkAtomTerm(s->name); + /* Getting streams to prompt is a mess because we need for cooperation + between readers and writers to the stream :-( + */ + InitFileIO(s); + switch (sno) { + case 0: + s->name = AtomUserIn; + break; + case 1: + s->name = AtomUserOut; + break; + default: + s->name = AtomUserErr; + break; + } + s->user_name = MkAtomTerm(s->name); #if LIGHT - s->status |= Tty_Stream_f | Promptable_Stream_f; + s->status |= Tty_Stream_f | Promptable_Stream_f; #endif - Yap_DefaultStreamOps(s); + Yap_DefaultStreamOps(s); #if HAVE_SETBUF - if (s->status & Tty_Stream_f && sno == 0) { - /* make sure input is unbuffered if it comes from stdin, this - makes life simpler for interrupt handling */ - setbuf(stdin, NULL); - // fprintf(stderr,"here I am\n"); - } + if (s->status & Tty_Stream_f && sno == 0) { + /* make sure input is unbuffered if it comes from stdin, this + makes life simpler for interrupt handling */ + setbuf(stdin, NULL); + // fprintf(stderr,"here I am\n"); + } #endif /* HAVE_SETBUF */ } void Yap_InitStdStream(int sno, unsigned int flags, FILE *file, VFS_t *vfsp) { - InitStdStream(sno, flags, file, vfsp); + InitStdStream(sno, flags, file, vfsp); } Term Yap_StreamUserName(int sno) { - Term atname; - StreamDesc *s = &GLOBAL_Stream[sno]; - if (s->user_name != 0L) { - return (s->user_name); - } - if ((atname = StreamName(sno))) - return atname; - return TermNil; + Term atname; + StreamDesc *s = &GLOBAL_Stream[sno]; + if (s->user_name != 0L) { + return (s->user_name); + } + if ((atname = StreamName(sno))) + return atname; + return TermNil; } static void InitStdStreams(void) { - CACHE_REGS - if (LOCAL_sockets_io) { - InitStdStream(StdInStream, Input_Stream_f, NULL, NULL); - InitStdStream(StdOutStream, Output_Stream_f, NULL, NULL); - InitStdStream(StdErrStream, Output_Stream_f, NULL, NULL); - } else { - InitStdStream(StdInStream, Input_Stream_f, stdin, NULL); - InitStdStream(StdOutStream, Output_Stream_f, stdout, NULL); - InitStdStream(StdErrStream, Output_Stream_f, stderr, NULL); - } - GLOBAL_Stream[StdInStream].name = Yap_LookupAtom("user_input"); - GLOBAL_Stream[StdOutStream].name = Yap_LookupAtom("user_output"); - GLOBAL_Stream[StdErrStream].name = Yap_LookupAtom("user_error"); + CACHE_REGS + if (LOCAL_sockets_io) { + InitStdStream(StdInStream, Input_Stream_f, NULL, NULL); + InitStdStream(StdOutStream, Output_Stream_f, NULL, NULL); + InitStdStream(StdErrStream, Output_Stream_f, NULL, NULL); + } else { + InitStdStream(StdInStream, Input_Stream_f, stdin, NULL); + InitStdStream(StdOutStream, Output_Stream_f, stdout, NULL); + InitStdStream(StdErrStream, Output_Stream_f, stderr, NULL); + } + GLOBAL_Stream[StdInStream].name = Yap_LookupAtom("user_input"); + GLOBAL_Stream[StdOutStream].name = Yap_LookupAtom("user_output"); + GLOBAL_Stream[StdErrStream].name = Yap_LookupAtom("user_error"); #if USE_READLINE - if (GLOBAL_Stream[StdInStream].status & Tty_Stream_f && - GLOBAL_Stream[StdOutStream].status & Tty_Stream_f && - GLOBAL_Stream[StdErrStream].status & Tty_Stream_f && !Yap_embedded) { - Yap_InitReadline(TermTrue); - } + if (GLOBAL_Stream[StdInStream].status & Tty_Stream_f && + GLOBAL_Stream[StdOutStream].status & Tty_Stream_f && + GLOBAL_Stream[StdErrStream].status & Tty_Stream_f && !Yap_embedded) { + Yap_InitReadline(TermTrue); + } #endif - LOCAL_c_input_stream = StdInStream; - LOCAL_c_output_stream = StdOutStream; - LOCAL_c_error_stream = StdErrStream; + LOCAL_c_input_stream = StdInStream; + LOCAL_c_output_stream = StdOutStream; + LOCAL_c_error_stream = StdErrStream; } void Yap_InitStdStreams(void) { InitStdStreams(); } Int PlIOError__(const char *file, const char *function, int lineno, yap_error_number type, Term culprit, ...) { - if (trueLocalPrologFlag(FILEERRORS_FLAG) || - type == RESOURCE_ERROR_MAX_STREAMS /* do not catch resource errors */) { - va_list args; - const char *format; - char who[1024]; + if (trueLocalPrologFlag(FILEERRORS_FLAG) || + type == RESOURCE_ERROR_MAX_STREAMS /* do not catch resource errors */) { + va_list args; + const char *format; + char who[1024]; - va_start(args, culprit); - format = va_arg(args, char *); - if (format) { - vsnprintf(who, 1023, format, args); + va_start(args, culprit); + format = va_arg(args, char *); + if (format) { + vsnprintf(who, 1023, format, args); + } else { + who[0] = '\0'; + } + va_end(args); + Yap_Error__(file, function, lineno, type, culprit, who); + /* and fail */ + return false; } else { - who[0] = '\0'; + pop_text_stack(0); + memset(LOCAL_ActiveError, 0, sizeof(*LOCAL_ActiveError)); + return false; } - va_end(args); - Yap_Error__(file, function, lineno, type, culprit, who); - /* and fail */ - return false; - } else { - pop_text_stack(0); - memset(LOCAL_ActiveError, 0, sizeof(*LOCAL_ActiveError)); - return false; - } } static int eolflg = 1; @@ -432,244 +447,244 @@ static void InTTYLine(char *line) { #endif void Yap_DebugSetIFile(char *fname) { - if (curfile) - fclose(curfile); - curfile = fopen(fname, "r"); - if (curfile == NULL) { - curfile = stdin; - Yap_Warning("%% YAP open %s for input\n", fname); - } + if (curfile) + fclose(curfile); + curfile = fopen(fname, "r"); + if (curfile == NULL) { + curfile = stdin; + Yap_Warning("%% YAP open %s for input\n", fname); + } } void Yap_DebugEndline() { *lp = 0; } int Yap_DebugGetc() { - int ch; - if (eolflg) { - if (curfile != NULL) { - if (fgets(my_line, 200, curfile) == 0) - curfile = NULL; + int ch; + if (eolflg) { + if (curfile != NULL) { + if (fgets(my_line, 200, curfile) == 0) + curfile = NULL; + } + if (curfile == NULL) + if (fgets(my_line, 200, stdin) == NULL) { + return EOF; + } + eolflg = 0; + lp = my_line; } - if (curfile == NULL) - if (fgets(my_line, 200, stdin) == NULL) { - return EOF; - } - eolflg = 0; - lp = my_line; - } - if ((ch = *lp++) == 0) - ch = '\n', eolflg = 1; - if (Yap_Option['l' - 96]) - putc(ch, Yap_logfile); - return (ch); + if ((ch = *lp++) == 0) + ch = '\n', eolflg = 1; + if (Yap_Option['l' - 96]) + putc(ch, Yap_logfile); + return (ch); } int Yap_DebugPutc(FILE *s, wchar_t ch) { - if (Yap_Option['l' - 96]) - (void)putc(ch, Yap_logfile); - return (putc(ch, s)); + if (Yap_Option['l' - 96]) + (void) putc(ch, Yap_logfile); + return (putc(ch, s)); } int Yap_DebugPuts(FILE *s, const char *sch) { - if (Yap_Option['l' - 96]) - (void)fputs(sch, Yap_logfile); - return fputs(sch, s); + if (Yap_Option['l' - 96]) + (void) fputs(sch, Yap_logfile); + return fputs(sch, s); } void Yap_DebugErrorPuts(const char *s) { Yap_DebugPuts(stderr, s); } void Yap_DebugPlWrite(Term t) { - if (t == 0) - fprintf(stderr, "NULL"); - Yap_plwrite(t, GLOBAL_Stream + 2, 0, 0, GLOBAL_MaxPriority); + if (t == 0) + fprintf(stderr, "NULL"); + Yap_plwrite(t, GLOBAL_Stream + 2, 0, 0, GLOBAL_MaxPriority); } void Yap_DebugPlWriteln(Term t) { - CACHE_REGS - if (t == 0) - fprintf(stderr, "NULL"); - Yap_plwrite(t, NULL, 15, 0, GLOBAL_MaxPriority); - Yap_DebugPutc(GLOBAL_Stream[LOCAL_c_error_stream].file, '.'); - Yap_DebugPutc(GLOBAL_Stream[LOCAL_c_error_stream].file, 10); + CACHE_REGS + if (t == 0) + fprintf(stderr, "NULL"); + Yap_plwrite(t, NULL, 15, 0, GLOBAL_MaxPriority); + Yap_DebugPutc(GLOBAL_Stream[LOCAL_c_error_stream].file, '.'); + Yap_DebugPutc(GLOBAL_Stream[LOCAL_c_error_stream].file, 10); } void Yap_DebugErrorPutc(int c) { - CACHE_REGS - Yap_DebugPutc(GLOBAL_Stream[LOCAL_c_error_stream].file, c); + CACHE_REGS + Yap_DebugPutc(GLOBAL_Stream[LOCAL_c_error_stream].file, c); } void Yap_DebugWriteIndicator(PredEntry *ap) { - CACHE_REGS - Term tmod = ap->ModuleOfPred; - if (!tmod) - tmod = TermProlog; + CACHE_REGS + Term tmod = ap->ModuleOfPred; + if (!tmod) + tmod = TermProlog; #if THREADS - Yap_DebugPlWrite(MkIntegerTerm(worker_id)); - Yap_DebugPutc(stderr, ' '); + Yap_DebugPlWrite(MkIntegerTerm(worker_id)); + Yap_DebugPutc(stderr, ' '); #endif - Yap_DebugPutc(stderr, '>'); - Yap_DebugPutc(stderr, '\t'); - Yap_DebugPlWrite(tmod); - Yap_DebugPutc(stderr, ':'); - if (ap->ModuleOfPred == IDB_MODULE) { - Term t = Deref(ARG1); - if (IsAtomTerm(t)) { - Yap_DebugPlWrite(t); - } else if (IsIntegerTerm(t)) { - Yap_DebugPlWrite(t); + Yap_DebugPutc(stderr, '>'); + Yap_DebugPutc(stderr, '\t'); + Yap_DebugPlWrite(tmod); + Yap_DebugPutc(stderr, ':'); + if (ap->ModuleOfPred == IDB_MODULE) { + Term t = Deref(ARG1); + if (IsAtomTerm(t)) { + Yap_DebugPlWrite(t); + } else if (IsIntegerTerm(t)) { + Yap_DebugPlWrite(t); + } else { + Functor f = FunctorOfTerm(t); + Atom At = NameOfFunctor(f); + Yap_DebugPlWrite(MkAtomTerm(At)); + Yap_DebugPutc(stderr, '/'); + Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); + } } else { - Functor f = FunctorOfTerm(t); - Atom At = NameOfFunctor(f); - Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(stderr, '/'); - Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); + if (ap->ArityOfPE == 0) { + Atom At = (Atom) ap->FunctorOfPred; + Yap_DebugPlWrite(MkAtomTerm(At)); + } else { + Functor f = ap->FunctorOfPred; + Atom At = NameOfFunctor(f); + Yap_DebugPlWrite(MkAtomTerm(At)); + Yap_DebugPutc(stderr, '/'); + Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); + } } - } else { - if (ap->ArityOfPE == 0) { - Atom At = (Atom)ap->FunctorOfPred; - Yap_DebugPlWrite(MkAtomTerm(At)); - } else { - Functor f = ap->FunctorOfPred; - Atom At = NameOfFunctor(f); - Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(stderr, '/'); - Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); - } - } - Yap_DebugPutc(stderr, '\n'); + Yap_DebugPutc(stderr, '\n'); } /* static */ int FilePutc(int sno, int ch) { - StreamDesc *s = &GLOBAL_Stream[sno]; + StreamDesc *s = &GLOBAL_Stream[sno]; #if MAC || _MSC_VER - if (ch == 10) { - ch = '\n'; - } + if (ch == 10) { + ch = '\n'; + } #endif - putc(ch, s->file); + putc(ch, s->file); #if MAC || _MSC_VER - if (ch == 10) { - fflush(s->file); - } + if (ch == 10) { + fflush(s->file); + } #endif - count_output_char(ch, s); - return ((int)ch); + count_output_char(ch, s); + return ((int) ch); } static int NullPutc(int sno, int ch) { - StreamDesc *s = &GLOBAL_Stream[sno]; + StreamDesc *s = &GLOBAL_Stream[sno]; #if MAC || _MSC_VER - if (ch == 10) { - ch = '\n'; - } + if (ch == 10) { + ch = '\n'; + } #endif - count_output_char(ch, s); - return ((int)ch); + count_output_char(ch, s); + return ((int) ch); } int ResetEOF(StreamDesc *s) { - if (s->status & Eof_Error_Stream_f) { - Atom name = s->name; - // Yap_CloseStream(s - GLOBAL_Stream); - Yap_Error(PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM, MkAtomTerm(name), - "GetC"); - return FALSE; - } else if (s->status & Reset_Eof_Stream_f) { - s->status &= ~Push_Eof_Stream_f; - /* reset the eof indicator on file */ - if (feof(s->file)) - clearerr(s->file); - /* reset our function for reading input */ - Yap_DefaultStreamOps(s); - /* next, reset our own error indicator */ - s->status &= ~Eof_Stream_f; - /* try reading again */ - return TRUE; - } else { - s->status |= Past_Eof_Stream_f; - return FALSE; - } + if (s->status & Eof_Error_Stream_f) { + Atom name = s->name; + // Yap_CloseStream(s - GLOBAL_Stream); + Yap_Error(PERMISSION_ERROR_INPUT_PAST_END_OF_STREAM, MkAtomTerm(name), + "GetC"); + return FALSE; + } else if (s->status & Reset_Eof_Stream_f) { + s->status &= ~Push_Eof_Stream_f; + /* reset the eof indicator on file */ + if (feof(s->file)) + clearerr(s->file); + /* reset our function for reading input */ + Yap_DefaultStreamOps(s); + /* next, reset our own error indicator */ + s->status &= ~Eof_Stream_f; + /* try reading again */ + return TRUE; + } else { + s->status |= Past_Eof_Stream_f; + return FALSE; + } } /* handle reading from a stream after having found an EOF */ static int EOFWGetc(int sno) { - register StreamDesc *s = &GLOBAL_Stream[sno]; + register StreamDesc *s = &GLOBAL_Stream[sno]; - if (s->status & Push_Eof_Stream_f) { - /* ok, we have pushed an EOF, send it away */ - s->status &= ~Push_Eof_Stream_f; + if (s->status & Push_Eof_Stream_f) { + /* ok, we have pushed an EOF, send it away */ + s->status &= ~Push_Eof_Stream_f; + return EOF; + } + if (ResetEOF(s)) { + Yap_DefaultStreamOps(s); + return (s->stream_wgetc(sno)); + } return EOF; - } - if (ResetEOF(s)) { - Yap_DefaultStreamOps(s); - return (s->stream_wgetc(sno)); - } - return EOF; } static int EOFGetc(int sno) { - register StreamDesc *s = &GLOBAL_Stream[sno]; + register StreamDesc *s = &GLOBAL_Stream[sno]; - if (s->status & Push_Eof_Stream_f) { - /* ok, we have pushed an EOF, send it away */ - s->status &= ~Push_Eof_Stream_f; - ResetEOF(s); + if (s->status & Push_Eof_Stream_f) { + /* ok, we have pushed an EOF, send it away */ + s->status &= ~Push_Eof_Stream_f; + ResetEOF(s); + return EOF; + } + if (ResetEOF(s)) { + Yap_DefaultStreamOps(s); + return s->stream_getc(sno); + } return EOF; - } - if (ResetEOF(s)) { - Yap_DefaultStreamOps(s); - return s->stream_getc(sno); - } - return EOF; } /* check if we read a LOCAL_newline or an EOF */ int console_post_process_eof(StreamDesc *s) { - CACHE_REGS - if (!ResetEOF(s)) { - s->status |= Eof_Stream_f; - s->stream_getc = EOFGetc; - s->stream_wgetc = EOFWGetc; - s->stream_wgetc_for_read = EOFWGetc; - LOCAL_newline = true; - } - return EOFCHAR; + CACHE_REGS + if (!ResetEOF(s)) { + s->status |= Eof_Stream_f; + s->stream_getc = EOFGetc; + s->stream_wgetc = EOFWGetc; + s->stream_wgetc_for_read = EOFWGetc; + LOCAL_newline = true; + } + return EOFCHAR; } /* check if we read a newline or an EOF */ int post_process_read_wchar(int ch, size_t n, StreamDesc *s) { - if (ch == EOF) { - return post_process_weof(s); - } + if (ch == EOF) { + return post_process_weof(s); + } #if DEBUG - if (GLOBAL_Option[1]) { - static int v; - fprintf(stderr, "%d %C\n", v, ch); - v++; - } + if (GLOBAL_Option[1]) { + static int v; + fprintf(stderr, "%d %C\n", v, ch); + v++; + } #endif - s->charcount += n; - s->linepos += n; - if (ch == '\n') { - ++s->linecount; - s->linepos = 0; - /* don't convert if the stream is binary */ - if (!(s->status & Binary_Stream_f)) - ch = 10; - } - return ch; + s->charcount += n; + s->linepos += n; + if (ch == '\n') { + ++s->linecount; + s->linepos = 0; + /* don't convert if the stream is binary */ + if (!(s->status & Binary_Stream_f)) + ch = 10; + } + return ch; } int post_process_weof(StreamDesc *s) { - if (!ResetEOF(s)) { - s->status |= Eof_Stream_f; - s->stream_wgetc = EOFWGetc; - s->stream_getc = EOFGetc; - s->stream_wgetc_for_read = EOFWGetc; - } - return EOFCHAR; + if (!ResetEOF(s)) { + s->status |= Eof_Stream_f; + s->stream_wgetc = EOFWGetc; + s->stream_getc = EOFGetc; + s->stream_wgetc_for_read = EOFWGetc; + } + return EOFCHAR; } /** @@ -689,14 +704,14 @@ int EOFWPeek(int sno) { return EOFCHAR; } It could be made more efficient by doing our own buffering and avoiding post_process_read_char, something to think about */ int PlGetc(int sno) { - StreamDesc *s = &GLOBAL_Stream[sno]; - return fgetc(s->file); + StreamDesc *s = &GLOBAL_Stream[sno]; + return fgetc(s->file); } // layered version static inline int get_wchar_from_file(int sno) { - return post_process_read_wchar(fgetwc(GLOBAL_Stream[sno].file), 1, - GLOBAL_Stream + sno); + return post_process_read_wchar(fgetwc(GLOBAL_Stream[sno].file), 1, + GLOBAL_Stream + sno); } #ifndef MB_LEN_MAX @@ -704,200 +719,200 @@ static inline int get_wchar_from_file(int sno) { #endif static int handle_write_encoding_error(int sno, wchar_t ch) { - if (GLOBAL_Stream[sno].status & RepError_Xml_f) { - /* use HTML/XML encoding in ASCII */ - int i = ch, digits = 1; - GLOBAL_Stream[sno].stream_putc(sno, '&'); - GLOBAL_Stream[sno].stream_putc(sno, '#'); - while (digits < i) - digits *= 10; - if (digits > i) - digits /= 10; - while (i) { - GLOBAL_Stream[sno].stream_putc(sno, i / digits); - i %= 10; - digits /= 10; + if (GLOBAL_Stream[sno].status & RepError_Xml_f) { + /* use HTML/XML encoding in ASCII */ + int i = ch, digits = 1; + GLOBAL_Stream[sno].stream_putc(sno, '&'); + GLOBAL_Stream[sno].stream_putc(sno, '#'); + while (digits < i) + digits *= 10; + if (digits > i) + digits /= 10; + while (i) { + GLOBAL_Stream[sno].stream_putc(sno, i / digits); + i %= 10; + digits /= 10; + } + GLOBAL_Stream[sno].stream_putc(sno, ';'); + return ch; + } else if (GLOBAL_Stream[sno].status & RepError_Prolog_f) { + /* write quoted */ + GLOBAL_Stream[sno].stream_putc(sno, '\\'); + GLOBAL_Stream[sno].stream_putc(sno, 'u'); + GLOBAL_Stream[sno].stream_putc(sno, ch >> 24); + GLOBAL_Stream[sno].stream_putc(sno, 256 & (ch >> 16)); + GLOBAL_Stream[sno].stream_putc(sno, 256 & (ch >> 8)); + GLOBAL_Stream[sno].stream_putc(sno, 256 & ch); + return ch; + } else { + CACHE_REGS + Yap_Error(REPRESENTATION_ERROR_CHARACTER, MkIntegerTerm(ch), + "charater %ld cannot be encoded in stream %d", + (unsigned long int) ch, sno); + return -1; } - GLOBAL_Stream[sno].stream_putc(sno, ';'); - return ch; - } else if (GLOBAL_Stream[sno].status & RepError_Prolog_f) { - /* write quoted */ - GLOBAL_Stream[sno].stream_putc(sno, '\\'); - GLOBAL_Stream[sno].stream_putc(sno, 'u'); - GLOBAL_Stream[sno].stream_putc(sno, ch >> 24); - GLOBAL_Stream[sno].stream_putc(sno, 256 & (ch >> 16)); - GLOBAL_Stream[sno].stream_putc(sno, 256 & (ch >> 8)); - GLOBAL_Stream[sno].stream_putc(sno, 256 & ch); - return ch; - } else { - CACHE_REGS - Yap_Error(REPRESENTATION_ERROR_CHARACTER, MkIntegerTerm(ch), - "charater %ld cannot be encoded in stream %d", - (unsigned long int)ch, sno); - return -1; - } } int put_wchar(int sno, wchar_t ch) { - /* pass the bucck if we can */ - switch (GLOBAL_Stream[sno].encoding) { - case ENC_OCTET: - return GLOBAL_Stream[sno].stream_putc(sno, ch); - case ENC_ISO_LATIN1: - if (ch >= 0xff) { - return handle_write_encoding_error(sno, ch); - } - return GLOBAL_Stream[sno].stream_putc(sno, ch); - case ENC_ISO_ASCII: - if (ch >= 0x80) { - return handle_write_encoding_error(sno, ch); - } - return GLOBAL_Stream[sno].stream_putc(sno, ch); - case ENC_ISO_ANSI: { - char buf[MB_LEN_MAX]; - mbstate_t mbstate; - int n; + /* pass the bucck if we can */ + switch (GLOBAL_Stream[sno].encoding) { + case ENC_OCTET: + return GLOBAL_Stream[sno].stream_putc(sno, ch); + case ENC_ISO_LATIN1: + if (ch >= 0xff) { + return handle_write_encoding_error(sno, ch); + } + return GLOBAL_Stream[sno].stream_putc(sno, ch); + case ENC_ISO_ASCII: + if (ch >= 0x80) { + return handle_write_encoding_error(sno, ch); + } + return GLOBAL_Stream[sno].stream_putc(sno, ch); + case ENC_ISO_ANSI: { + char buf[MB_LEN_MAX]; + mbstate_t mbstate; + int n; - memset((void *)&mbstate, 0, sizeof(mbstate_t)); - if ((n = wcrtomb(buf, ch, &mbstate)) < 0) { - /* error */ - GLOBAL_Stream[sno].stream_putc(sno, ch); - return -1; - } else { - int i; + memset((void *) &mbstate, 0, sizeof(mbstate_t)); + if ((n = wcrtomb(buf, ch, &mbstate)) < 0) { + /* error */ + GLOBAL_Stream[sno].stream_putc(sno, ch); + return -1; + } else { + int i; - for (i = 0; i < n; i++) { - GLOBAL_Stream[sno].stream_putc(sno, buf[i]); - } - return ch; - } - case ENC_ISO_UTF8: - if (ch < 0x80) { - GLOBAL_Stream[sno].stream_putc(sno, ch); - } else if (ch < 0x800) { - GLOBAL_Stream[sno].stream_putc(sno, 0xC0 | ch >> 6); - GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch & 0x3F)); - } else if (ch < 0x10000) { - GLOBAL_Stream[sno].stream_putc(sno, 0xE0 | ch >> 12); - GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch >> 6 & 0x3F)); - GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch & 0x3F)); - } else if (ch < 0x200000) { - GLOBAL_Stream[sno].stream_putc(sno, 0xF0 | ch >> 18); - GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch >> 12 & 0x3F)); - GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch >> 6 & 0x3F)); - GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch & 0x3F)); - } else { - /* should never happen */ - return -1; - } - return ch; - break; - case ENC_UTF16_LE: { - if (ch < 0x10000) { - GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); - } else { - // computations - uint16_t ich = ch; - uint16_t lead = LEAD_OFFSET + (ich >> 10); - uint16_t trail = 0xDC00 + (ich & 0x3FF); + for (i = 0; i < n; i++) { + GLOBAL_Stream[sno].stream_putc(sno, buf[i]); + } + return ch; + } + case ENC_ISO_UTF8: + if (ch < 0x80) { + GLOBAL_Stream[sno].stream_putc(sno, ch); + } else if (ch < 0x800) { + GLOBAL_Stream[sno].stream_putc(sno, 0xC0 | ch >> 6); + GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch & 0x3F)); + } else if (ch < 0x10000) { + GLOBAL_Stream[sno].stream_putc(sno, 0xE0 | ch >> 12); + GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch >> 6 & 0x3F)); + GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch & 0x3F)); + } else if (ch < 0x200000) { + GLOBAL_Stream[sno].stream_putc(sno, 0xF0 | ch >> 18); + GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch >> 12 & 0x3F)); + GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch >> 6 & 0x3F)); + GLOBAL_Stream[sno].stream_putc(sno, 0x80 | (ch & 0x3F)); + } else { + /* should never happen */ + return -1; + } + return ch; + break; + case ENC_UTF16_LE: { + if (ch < 0x10000) { + GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); + } else { + // computations + uint16_t ich = ch; + uint16_t lead = LEAD_OFFSET + (ich >> 10); + uint16_t trail = 0xDC00 + (ich & 0x3FF); - GLOBAL_Stream[sno].stream_putc(sno, (trail & 0xff)); - GLOBAL_Stream[sno].stream_putc(sno, (trail >> 8)); - GLOBAL_Stream[sno].stream_putc(sno, (lead & 0xff)); - GLOBAL_Stream[sno].stream_putc(sno, (lead >> 8)); - } - return ch; - } - case ENC_UTF16_BE: { - // computations - if (ch < 0x10000) { - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); - GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); - } else { - uint16_t lead = (uint16_t)LEAD_OFFSET + ((uint16_t)ch >> 10); - uint16_t trail = 0xDC00 + ((uint16_t)ch & 0x3FF); + GLOBAL_Stream[sno].stream_putc(sno, (trail & 0xff)); + GLOBAL_Stream[sno].stream_putc(sno, (trail >> 8)); + GLOBAL_Stream[sno].stream_putc(sno, (lead & 0xff)); + GLOBAL_Stream[sno].stream_putc(sno, (lead >> 8)); + } + return ch; + } + case ENC_UTF16_BE: { + // computations + if (ch < 0x10000) { + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); + GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); + } else { + uint16_t lead = (uint16_t) LEAD_OFFSET + ((uint16_t) ch >> 10); + uint16_t trail = 0xDC00 + ((uint16_t) ch & 0x3FF); - GLOBAL_Stream[sno].stream_putc(sno, (lead >> 8)); - GLOBAL_Stream[sno].stream_putc(sno, (lead & 0xff)); - GLOBAL_Stream[sno].stream_putc(sno, (trail >> 8)); - GLOBAL_Stream[sno].stream_putc(sno, (trail & 0xff)); - } - return ch; - } - case ENC_UCS2_LE: { - if (ch >= 0x10000) { - return 0; - } - GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); - return ch; - } - case ENC_UCS2_BE: { - // computations - if (ch < 0x10000) { - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); - GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); - return ch; - } else { - return 0; - } - } + GLOBAL_Stream[sno].stream_putc(sno, (lead >> 8)); + GLOBAL_Stream[sno].stream_putc(sno, (lead & 0xff)); + GLOBAL_Stream[sno].stream_putc(sno, (trail >> 8)); + GLOBAL_Stream[sno].stream_putc(sno, (trail & 0xff)); + } + return ch; + } + case ENC_UCS2_LE: { + if (ch >= 0x10000) { + return 0; + } + GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); + return ch; + } + case ENC_UCS2_BE: { + // computations + if (ch < 0x10000) { + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8)); + GLOBAL_Stream[sno].stream_putc(sno, (ch & 0xff)); + return ch; + } else { + return 0; + } + } - case ENC_ISO_UTF32_BE: - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 24) & 0xff); - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 16) & 0xff); - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8) & 0xff); - GLOBAL_Stream[sno].stream_putc(sno, ch & 0xff); - return ch; - case ENC_ISO_UTF32_LE: - GLOBAL_Stream[sno].stream_putc(sno, ch & 0xff); - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8) & 0xff); - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 16) & 0xff); - GLOBAL_Stream[sno].stream_putc(sno, (ch >> 24) & 0xff); - return ch; - } - } - return -1; + case ENC_ISO_UTF32_BE: + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 24) & 0xff); + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 16) & 0xff); + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8) & 0xff); + GLOBAL_Stream[sno].stream_putc(sno, ch & 0xff); + return ch; + case ENC_ISO_UTF32_LE: + GLOBAL_Stream[sno].stream_putc(sno, ch & 0xff); + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 8) & 0xff); + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 16) & 0xff); + GLOBAL_Stream[sno].stream_putc(sno, (ch >> 24) & 0xff); + return ch; + } + } + return -1; } /* used by user-code to read characters from the current input stream */ int Yap_PlGetchar(void) { - CACHE_REGS - return ( - GLOBAL_Stream[LOCAL_c_input_stream].stream_getc(LOCAL_c_input_stream)); + CACHE_REGS + return ( + GLOBAL_Stream[LOCAL_c_input_stream].stream_getc(LOCAL_c_input_stream)); } int Yap_PlGetWchar(void) { - CACHE_REGS - return get_wchar(LOCAL_c_input_stream); + CACHE_REGS + return get_wchar(LOCAL_c_input_stream); } /* avoid using a variable to call a function */ int Yap_PlFGetchar(void) { - CACHE_REGS - return (PlGetc(LOCAL_c_input_stream)); + CACHE_REGS + return (PlGetc(LOCAL_c_input_stream)); } Term Yap_MkStream(int n) { - Term t[1]; - t[0] = MkIntTerm(n); - return (Yap_MkApplTerm(FunctorStream, 1, t)); + Term t[1]; + t[0] = MkIntTerm(n); + return (Yap_MkApplTerm(FunctorStream, 1, t)); } /* given a stream index, get the corresponding fd */ Int GetStreamFd(int sno) { #if HAVE_SOCKET - if (GLOBAL_Stream[sno].status & Socket_Stream_f) { - return (GLOBAL_Stream[sno].u.socket.fd); - } else + if (GLOBAL_Stream[sno].status & Socket_Stream_f) { + return (GLOBAL_Stream[sno].u.socket.fd); + } else #endif - if (GLOBAL_Stream[sno].status & Pipe_Stream_f) { - return (GLOBAL_Stream[sno].u.pipe.fd); - } else if (GLOBAL_Stream[sno].status & InMemory_Stream_f) { - return (-1); - } - return (fileno(GLOBAL_Stream[sno].file)); + if (GLOBAL_Stream[sno].status & Pipe_Stream_f) { + return (GLOBAL_Stream[sno].u.pipe.fd); + } else if (GLOBAL_Stream[sno].status & InMemory_Stream_f) { + return (-1); + } + return (fileno(GLOBAL_Stream[sno].file)); } Int Yap_GetStreamFd(int sno) { return GetStreamFd(sno); } @@ -905,229 +920,228 @@ Int Yap_GetStreamFd(int sno) { return GetStreamFd(sno); } static int binary_file(const char *file_name) { #if HAVE_STAT #if _MSC_VER || defined(__MINGW32__) - struct _stat ss; - if (_stat(file_name, &ss) != 0) + struct _stat ss; + if (_stat(file_name, &ss) != 0) #else - struct stat ss; - if (stat(file_name, &ss) != 0) + struct stat ss; + if (stat(file_name, &ss) != 0) #endif - { - /* ignore errors while checking a file */ - return (FALSE); - } - return (S_ISDIR(ss.st_mode)); + { + /* ignore errors while checking a file */ + return (FALSE); + } + return (S_ISDIR(ss.st_mode)); #else - return (FALSE); + return (FALSE); #endif } static int write_bom(int sno, StreamDesc *st) { - /* dump encoding */ - switch (st->encoding) { - case ENC_ISO_UTF8: - if (st->stream_putc(sno, 0xEF) < 0) - return false; - if (st->stream_putc(sno, 0xBB) < 0) - return false; - if (st->stream_putc(sno, 0xBF) < 0) - return false; - st->status |= HAS_BOM_f; - return true; - case ENC_UTF16_BE: - case ENC_UCS2_BE: - if (st->stream_putc(sno, 0xFE) < 0) - return false; - if (st->stream_putc(sno, 0xFF) < 0) - return false; - st->status |= HAS_BOM_f; - return true; - case ENC_UTF16_LE: - case ENC_UCS2_LE: - if (st->stream_putc(sno, 0xFF) < 0) - return false; - if (st->stream_putc(sno, 0xFE) < 0) - return false; - st->status |= HAS_BOM_f; - return true; - case ENC_ISO_UTF32_BE: - if (st->stream_putc(sno, 0x00) < 0) - return false; - if (st->stream_putc(sno, 0x00) < 0) - return false; - if (st->stream_putc(sno, 0xFE) < 0) - return false; - if (st->stream_putc(sno, 0xFF) < 0) - return false; - st->status |= HAS_BOM_f; - return true; - case ENC_ISO_UTF32_LE: - if (st->stream_putc(sno, 0xFF) < 0) - return false; - if (st->stream_putc(sno, 0xFE) < 0) - return false; - if (st->stream_putc(sno, 0x00) < 0) - return false; - if (st->stream_putc(sno, 0x00) < 0) - return false; - st->status |= HAS_BOM_f; - return true; - default: - return true; - } + /* dump encoding */ + switch (st->encoding) { + case ENC_ISO_UTF8: + if (st->stream_putc(sno, 0xEF) < 0) + return false; + if (st->stream_putc(sno, 0xBB) < 0) + return false; + if (st->stream_putc(sno, 0xBF) < 0) + return false; + st->status |= HAS_BOM_f; + return true; + case ENC_UTF16_BE: + case ENC_UCS2_BE: + if (st->stream_putc(sno, 0xFE) < 0) + return false; + if (st->stream_putc(sno, 0xFF) < 0) + return false; + st->status |= HAS_BOM_f; + return true; + case ENC_UTF16_LE: + case ENC_UCS2_LE: + if (st->stream_putc(sno, 0xFF) < 0) + return false; + if (st->stream_putc(sno, 0xFE) < 0) + return false; + st->status |= HAS_BOM_f; + return true; + case ENC_ISO_UTF32_BE: + if (st->stream_putc(sno, 0x00) < 0) + return false; + if (st->stream_putc(sno, 0x00) < 0) + return false; + if (st->stream_putc(sno, 0xFE) < 0) + return false; + if (st->stream_putc(sno, 0xFF) < 0) + return false; + st->status |= HAS_BOM_f; + return true; + case ENC_ISO_UTF32_LE: + if (st->stream_putc(sno, 0xFF) < 0) + return false; + if (st->stream_putc(sno, 0xFE) < 0) + return false; + if (st->stream_putc(sno, 0x00) < 0) + return false; + if (st->stream_putc(sno, 0x00) < 0) + return false; + st->status |= HAS_BOM_f; + return true; + default: + return true; + } } static void check_bom(int sno, StreamDesc *st) { - int ch1, ch2, ch3, ch4; + int ch1, ch2, ch3, ch4; - ch1 = fgetc(st->file); - switch (ch1) { - case 0x00: { - ch2 = fgetc(st->file); - if (ch2 != 0x00) { - ungetc(ch1, st->file); - ungetc(ch2, st->file); - return; - } else { - ch3 = fgetc(st->file); - if (ch3 == EOFCHAR || ch3 != 0xFE) { - ungetc(ch1, st->file); - ungetc(ch2, st->file); - ungetc(ch3, st->file); - return; - } else { - ch4 = fgetc(st->file); - if (ch4 == EOFCHAR || ch3 != 0xFF) { - ungetc(ch1, st->file); - ungetc(ch2, st->file); - ungetc(ch3, st->file); - ungetc(ch4, st->file); - return; - } else { - st->status |= HAS_BOM_f; - st->encoding = ENC_ISO_UTF32_BE; - return; + ch1 = fgetc(st->file); + switch (ch1) { + case 0x00: { + ch2 = fgetc(st->file); + if (ch2 != 0x00) { + ungetc(ch1, st->file); + ungetc(ch2, st->file); + return; + } else { + ch3 = fgetc(st->file); + if (ch3 == EOFCHAR || ch3 != 0xFE) { + ungetc(ch1, st->file); + ungetc(ch2, st->file); + ungetc(ch3, st->file); + return; + } else { + ch4 = fgetc(st->file); + if (ch4 == EOFCHAR || ch3 != 0xFF) { + ungetc(ch1, st->file); + ungetc(ch2, st->file); + ungetc(ch3, st->file); + ungetc(ch4, st->file); + return; + } else { + st->status |= HAS_BOM_f; + st->encoding = ENC_ISO_UTF32_BE; + return; + } + } + } } - } - } - } - case 0xFE: { - ch2 = fgetc(st->file); - if (ch2 != 0xFF) { - ungetc(ch1, st->file); - ungetc(ch2, st->file); - return; - } else { - st->status |= HAS_BOM_f; - st->encoding = ENC_UTF16_BE; - return; - } - } - case 0xFF: { - ch2 = fgetc(st->file); - if (ch2 != 0xFE) { - ungetc(ch1, st->file); - ungetc(ch2, st->file); - return; - } else { - ch3 = fgetc(st->file); - if (ch3 != 0x00) { - ungetc(ch3, st->file); - } else { - ch4 = fgetc(st->file); - if (ch4 == 0x00) { - st->status |= HAS_BOM_f; - st->encoding = ENC_ISO_UTF32_LE; - return; - } else { - ungetc(ch4, st->file); - ungetc(0x00, st->file); + case 0xFE: { + ch2 = fgetc(st->file); + if (ch2 != 0xFF) { + ungetc(ch1, st->file); + ungetc(ch2, st->file); + return; + } else { + st->status |= HAS_BOM_f; + st->encoding = ENC_UTF16_BE; + return; + } } - } + case 0xFF: { + ch2 = fgetc(st->file); + if (ch2 != 0xFE) { + ungetc(ch1, st->file); + ungetc(ch2, st->file); + return; + } else { + ch3 = fgetc(st->file); + if (ch3 != 0x00) { + ungetc(ch3, st->file); + } else { + ch4 = fgetc(st->file); + if (ch4 == 0x00) { + st->status |= HAS_BOM_f; + st->encoding = ENC_ISO_UTF32_LE; + return; + } else { + ungetc(ch4, st->file); + ungetc(0x00, st->file); + } + } + } + st->status |= HAS_BOM_f; + st->encoding = ENC_UTF16_LE; + return; + } + case 0xEF: + ch2 = fgetc(st->file); + if (ch2 != 0xBB) { + ungetc(ch1, st->file); + ungetc(ch2, st->file); + return; + } else { + ch3 = fgetc(st->file); + if (ch3 != 0xBF) { + ungetc(ch1, st->file); + ungetc(ch2, st->file); + ungetc(ch3, st->file); + return; + } else { + st->status |= HAS_BOM_f; + st->encoding = ENC_ISO_UTF8; + return; + } + } + default: + ungetc(ch1, st->file); } - st->status |= HAS_BOM_f; - st->encoding = ENC_UTF16_LE; - return; - } - case 0xEF: - ch2 = fgetc(st->file); - if (ch2 != 0xBB) { - ungetc(ch1, st->file); - ungetc(ch2, st->file); - return; - } else { - ch3 = fgetc(st->file); - if (ch3 != 0xBF) { - ungetc(ch1, st->file); - ungetc(ch2, st->file); - ungetc(ch3, st->file); - return; - } else { - st->status |= HAS_BOM_f; - st->encoding = ENC_ISO_UTF8; - return; - } - } - default: - ungetc(ch1, st->file); - } } bool Yap_initStream(int sno, FILE *fd, const char *name, Term file_name, encoding_t encoding, stream_flags_t flags, Atom open_mode, void *vfs) { - StreamDesc *st = &GLOBAL_Stream[sno]; - st->status = flags; + StreamDesc *st = &GLOBAL_Stream[sno]; + st->status = flags; - st->vfs = vfs; - st->charcount = 0; - st->linecount = 1; - if (flags & Binary_Stream_f) { - st->encoding = ENC_OCTET; - } else { - st->encoding = encoding; - } + st->vfs = vfs; + st->charcount = 0; + st->linecount = 1; + if (flags & Binary_Stream_f) { + st->encoding = ENC_OCTET; + } else { + st->encoding = encoding; + } - if (name == NULL) { - char buf[YAP_FILENAME_MAX + 1]; - memset(buf, 0, YAP_FILENAME_MAX + 1); - name = Yap_guessFileName(fd, sno, buf, YAP_FILENAME_MAX); - if (name) - st->name = Yap_LookupAtom(name); - } - st->user_name = file_name; - st->file = fd; - st->linepos = 0; - Yap_DefaultStreamOps(st); - return true; + if (name == NULL) { + char buf[YAP_FILENAME_MAX + 1]; + memset(buf, 0, YAP_FILENAME_MAX + 1); + name = Yap_guessFileName(fd, sno, buf, YAP_FILENAME_MAX); + if (name) + st->name = Yap_LookupAtom(name); + } + st->user_name = file_name; + st->file = fd; + st->linepos = 0; + Yap_DefaultStreamOps(st); + return true; } static bool open_header(int sno, Atom open_mode) { - if (open_mode == AtomWrite) { - const char *ptr; - const char s[] = "#!"; - int ch; + if (open_mode == AtomWrite) { + const char *ptr; + const char s[] = "#!"; + int ch; - ptr = s; - while ((ch = *ptr++)) - GLOBAL_Stream[sno].stream_wputc(sno, ch); - const char *b = Yap_FindExecutable(); - ptr = b; - while ((ch = *ptr++)) - GLOBAL_Stream[sno].stream_wputc(sno, ch); - const char *l = " -L --\n\n YAP script\n#\n# .\n"; - ptr = l; - while ((ch = *ptr++)) - GLOBAL_Stream[sno].stream_wputc(sno, ch); + ptr = s; + while ((ch = *ptr++)) + GLOBAL_Stream[sno].stream_wputc(sno, ch); + const char *b = Yap_FindExecutable(); + ptr = b; + while ((ch = *ptr++)) + GLOBAL_Stream[sno].stream_wputc(sno, ch); + const char *l = " -L --\n\n YAP script\n#\n# .\n"; + ptr = l; + while ((ch = *ptr++)) + GLOBAL_Stream[sno].stream_wputc(sno, ch); - } else if (open_mode == AtomRead) { - // skip header - int ch; - while ((ch = Yap_peek(sno)) == '#') { - while ((ch = GLOBAL_Stream[sno].stream_wgetc(sno)) != 10 && ch != -1) - ; + } else if (open_mode == AtomRead) { + // skip header + int ch; + while ((ch = Yap_peek(sno)) == '#') { + while ((ch = GLOBAL_Stream[sno].stream_wgetc(sno)) != 10 && ch != -1); + } } - } - return true; + return true; } #define OPEN_DEFS() \ @@ -1147,7 +1161,9 @@ static bool open_header(int sno, Atom open_mode) { PAR("wait", booleanFlag, OPEN_WAIT), PAR(NULL, ok, OPEN_END) #define PAR(x, y, z) z -typedef enum open_enum_choices { OPEN_DEFS() } open_choices_t; +typedef enum open_enum_choices { + OPEN_DEFS() +} open_choices_t; #undef PAR @@ -1160,210 +1176,180 @@ static const param_t open_defs[] = {OPEN_DEFS()}; static Int do_open(Term file_name, Term t2, Term tlist USES_REGS) { /* '$open'(+File,+Mode,?Stream,-ReturnCode) */ - Atom open_mode; - int sno; - SMALLUNSGN s; - char io_mode[8]; - StreamDesc *st; - bool avoid_bom = false, needs_bom = false; - const char *fname; - char fbuf[FILENAME_MAX]; - stream_flags_t flags; - FILE *fd; - const char *s_encoding; - encoding_t encoding; - Term tenc; - // original file name - if (IsVarTerm(file_name)) { - Yap_Error(INSTANTIATION_ERROR, file_name, "open/3"); - return FALSE; - } - if (!IsAtomTerm(file_name)) { - if (IsStringTerm(file_name)) { - fname = (char *)StringOfTerm(file_name); + Atom open_mode; + int sno; + StreamDesc *st; + bool avoid_bom = false, needs_bom = false; + const char *fname; + char fbuf[FILENAME_MAX]; + stream_flags_t flags; + const char *s_encoding; + encoding_t encoding; + Term tenc; + char io_mode[8]; + // original file name + if (IsVarTerm(file_name)) { + Yap_Error(INSTANTIATION_ERROR, file_name, "open/3"); + return FALSE; + } + if (!IsAtomTerm(file_name)) { + if (IsStringTerm(file_name)) { + fname = (char *) StringOfTerm(file_name); + } else { + Yap_Error(DOMAIN_ERROR_SOURCE_SINK, file_name, "open/3"); + return FALSE; + } } else { - Yap_Error(DOMAIN_ERROR_SOURCE_SINK, file_name, "open/3"); - return FALSE; + fname = RepAtom(AtomOfTerm(file_name))->StrOfAE; } - } else { - fname = RepAtom(AtomOfTerm(file_name))->StrOfAE; - } - // open mode - if (IsVarTerm(t2)) { - Yap_Error(INSTANTIATION_ERROR, t2, "open/3"); - return FALSE; - } - if (!IsAtomTerm(t2)) { - if (IsStringTerm(t2)) { - open_mode = Yap_LookupAtom(StringOfTerm(t2)); + // open mode + if (IsVarTerm(t2)) { + Yap_Error(INSTANTIATION_ERROR, t2, "open/3"); + return FALSE; + } + if (!IsAtomTerm(t2)) { + if (IsStringTerm(t2)) { + open_mode = Yap_LookupAtom(StringOfTerm(t2)); + } else { + Yap_Error(TYPE_ERROR_ATOM, t2, "open/3"); + return (FALSE); + } } else { - Yap_Error(TYPE_ERROR_ATOM, t2, "open/3"); - return (FALSE); + open_mode = AtomOfTerm(t2); } - } else { - open_mode = AtomOfTerm(t2); - } - // read, write, append - if (open_mode == AtomRead) { - strncpy(io_mode, "rb", 8); - s = Input_Stream_f; - } else if (open_mode == AtomWrite) { - strncpy(io_mode, "w", 8); - s = Output_Stream_f; - } else if (open_mode == AtomAppend) { - strncpy(io_mode, "a", 8); - s = Append_Stream_f | Output_Stream_f; - } else { - Yap_Error(DOMAIN_ERROR_IO_MODE, t2, "open/3"); - return (FALSE); - } - /* get options */ - xarg *args = Yap_ArgListToVector(tlist, open_defs, OPEN_END); - if (args == NULL) { - if (LOCAL_Error_TYPE != YAP_NO_ERROR) { - if (LOCAL_Error_TYPE == DOMAIN_ERROR_PROLOG_FLAG) - LOCAL_Error_TYPE = DOMAIN_ERROR_OPEN_OPTION; - Yap_Error(LOCAL_Error_TYPE, tlist, "option handling in open/3"); + /* get options */ + xarg *args = Yap_ArgListToVector(tlist, open_defs, OPEN_END); + if (args == NULL) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE == DOMAIN_ERROR_PROLOG_FLAG) + LOCAL_Error_TYPE = DOMAIN_ERROR_OPEN_OPTION; + Yap_Error(LOCAL_Error_TYPE, tlist, "option handling in open/3"); + } + return false; } - return false; - } - /* done */ - sno = GetFreeStreamD(); - if (sno < 0) { - free(args); - return PlIOError(RESOURCE_ERROR_MAX_STREAMS, TermNil, "open/3"); - } - st = &GLOBAL_Stream[sno]; - st->user_name = file_name; - flags = s; - // user requested encoding? - if (args[OPEN_ALIAS].used) { - Atom al = AtomOfTerm(args[OPEN_ALIAS].tvalue); - if (!Yap_AddAlias(al, sno)) { - free(args); - return false; + /* done */ + sno = GetFreeStreamD(); + if (sno < 0) { + free(args); + return PlIOError(RESOURCE_ERROR_MAX_STREAMS, TermNil, "open/3"); + } + st = &GLOBAL_Stream[sno]; + st->user_name = file_name; + flags = 0; + // user requested encoding? + if (args[OPEN_ALIAS].used) { + Atom al = AtomOfTerm(args[OPEN_ALIAS].tvalue); + if (!Yap_AddAlias(al, sno)) { + free(args); + return false; + } + } + if (args[OPEN_ENCODING].used) { + tenc = args[OPEN_ENCODING].tvalue; + s_encoding = RepAtom(AtomOfTerm(tenc))->StrOfAE; + } else { + s_encoding = "default"; + } + // default encoding, no bom yet + encoding = enc_id(s_encoding, ENC_OCTET); + // only set encoding after getting BOM + bool ok = (args[OPEN_EXPAND_FILENAME].used + ? args[OPEN_EXPAND_FILENAME].tvalue == TermTrue + : false) || + trueGlobalPrologFlag(OPEN_EXPANDS_FILENAME_FLAG); + // expand file name? + fname = Yap_AbsoluteFile(fname, fbuf, ok); + if (fname) { + st->name = Yap_LookupAtom(fname); + } else { + PlIOError(EXISTENCE_ERROR_SOURCE_SINK, ARG1, NULL); } - } - if (args[OPEN_ENCODING].used) { - tenc = args[OPEN_ENCODING].tvalue; - s_encoding = RepAtom(AtomOfTerm(tenc))->StrOfAE; - } else { - s_encoding = "default"; - } - // default encoding, no bom yet - encoding = enc_id(s_encoding, ENC_OCTET); - // only set encoding after getting BOM - bool ok = (args[OPEN_EXPAND_FILENAME].used - ? args[OPEN_EXPAND_FILENAME].tvalue == TermTrue - : false) || - trueGlobalPrologFlag(OPEN_EXPANDS_FILENAME_FLAG); - // expand file name? - fname = Yap_AbsoluteFile(fname, fbuf, ok); - if (fname) { - st->name = Yap_LookupAtom(fname); - } else { - PlIOError(EXISTENCE_ERROR_SOURCE_SINK, ARG1, NULL); - } - // Skip scripts that start with !#/.. or similar - bool script = - (args[OPEN_SCRIPT].used ? args[OPEN_SCRIPT].tvalue == TermTrue : false); - // binary type - if (args[OPEN_TYPE].used) { - Term t = args[OPEN_TYPE].tvalue; - bool bin = (t == TermBinary); - if (bin) { + // Skip scripts that start with !#/.. or similar + bool script = + (args[OPEN_SCRIPT].used ? args[OPEN_SCRIPT].tvalue == TermTrue : false); + // binary type + if (args[OPEN_TYPE].used) { + Term t = args[OPEN_TYPE].tvalue; + bool bin = (t == TermBinary); + if (bin) { #ifdef _WIN32 - strncat(io_mode, "b", 8); + strncat(io_mode, "b", 8); #endif - flags |= Binary_Stream_f; - encoding = ENC_OCTET; - avoid_bom = true; - needs_bom = false; - } else if (t == TermText) { + flags |= Binary_Stream_f; + encoding = ENC_OCTET; + avoid_bom = true; + needs_bom = false; + } else if (t == TermText) { #ifdef _WIN32 - strncat(io_mode, "t", 8); + strncat(io_mode, "t", 8); #endif - /* note that this matters for UNICODE style conversions */ + /* note that this matters for UNICODE style conversions */ + } else { + Yap_Error(DOMAIN_ERROR_STREAM, tlist, + "type is ~a, must be one of binary or text", t); + } + } + // BOM mess + if (encoding == ENC_UTF16_BE || encoding == ENC_UTF16_LE || + encoding == ENC_UCS2_BE || encoding == ENC_UCS2_LE || + encoding == ENC_ISO_UTF32_BE || encoding == ENC_ISO_UTF32_LE) { + needs_bom = true; + } + if (args[OPEN_BOM].used) { + if (args[OPEN_BOM].tvalue == TermTrue) { + avoid_bom = false; + needs_bom = true; + } else if (args[OPEN_BOM].tvalue == TermFalse) { + avoid_bom = true; + needs_bom = false; + } + } + if (st - GLOBAL_Stream < 3) { + flags |= RepError_Prolog_f; + } + if (open_mode == AtomRead) { + strncpy(io_mode, "rb", 8); + } else if (open_mode == AtomWrite) { + strncpy(io_mode, "w", 8); + } else if (open_mode == AtomAppend) { + strncpy(io_mode, "a", 8); } else { - Yap_Error(DOMAIN_ERROR_STREAM, tlist, - "type is ~a, must be one of binary or text", t); + Yap_Error(DOMAIN_ERROR_IO_MODE, MkAtomTerm(open_mode), "open/3"); + return -2; } - } - // BOM mess - if (encoding == ENC_UTF16_BE || encoding == ENC_UTF16_LE || - encoding == ENC_UCS2_BE || encoding == ENC_UCS2_LE || - encoding == ENC_ISO_UTF32_BE || encoding == ENC_ISO_UTF32_LE) { - needs_bom = true; - } - if (args[OPEN_BOM].used) { - if (args[OPEN_BOM].tvalue == TermTrue) { - avoid_bom = false; - needs_bom = true; - } else if (args[OPEN_BOM].tvalue == TermFalse) { - avoid_bom = true; - needs_bom = false; + if (Yap_OpenStream(RepAtom(AtomOfTerm(file_name))->StrOfAE, io_mode) < 0) { +return false; } - } - if (st - GLOBAL_Stream < 3) { - flags |= RepError_Prolog_f; - } - struct vfs *vfsp = NULL; - if ((vfsp = vfs_owner(fname)) != NULL) { - st->u.private_data = vfsp->open(sno, fname, io_mode); - fd = NULL; - if (st->u.private_data == NULL) - return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, "%s", fname)); - st->vfs = vfsp; - } else if ((fd = fopen(fname, io_mode)) == NULL || - (!(flags & Binary_Stream_f) && binary_file(fname))) { - strncpy(LOCAL_FileNameBuf, fname, MAXPATHLEN); - if (fname != fbuf) - freeBuffer((void *)fname); - fname = LOCAL_FileNameBuf; - UNLOCK(st->streamlock); - free(args); - if (errno == ENOENT && !strchr(io_mode, 'r')) { - return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, "%s: %s", fname, - strerror(errno))); - } else { - return (PlIOError(PERMISSION_ERROR_OPEN_SOURCE_SINK, file_name, "%s: %s", - fname, strerror(errno))); - } - } #if MAC - if (open_mode == AtomWrite) { - Yap_SetTextFile(RepAtom(AtomOfTerm(file_name))->StrOfAE); - } + if (open_mode == AtomWrite) { + Yap_SetTextFile(RepAtom(AtomOfTerm(file_name))->StrOfAE); + } #endif - // __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "open %s", fname); - flags &= ~(Free_Stream_f); - if (!Yap_initStream(sno, fd, fname, file_name, encoding, flags, open_mode, - vfsp)) - return false; - if (open_mode == AtomWrite) { - if (needs_bom && !write_bom(sno, st)) - return false; - } else if (open_mode == AtomRead && !avoid_bom) { - check_bom(sno, st); // can change encoding - } - // follow declaration unless there is v - if (st->status & HAS_BOM_f) - st->encoding = enc_id(s_encoding, st->encoding); - else - st->encoding = encoding; - Yap_DefaultStreamOps(st); - if (script) - open_header(sno, open_mode); - if (fname != fbuf) - freeBuffer(fname); + // __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "open %s", fname); + flags &= ~(Free_Stream_f); + Yap_DefaultStreamOps(st); + if (needs_bom && !write_bom(sno, st)) { + return false; + } else if (open_mode == AtomRead && !avoid_bom) { + check_bom(sno, st); // can change encoding + } + // follow declaration unless there is v + if (st->status & HAS_BOM_f) + st->encoding = enc_id(s_encoding, st->encoding); + else + st->encoding = encoding; + if (script) + open_header(sno, open_mode); + if (fname != fbuf) + freeBuffer(fname); - free(args); - UNLOCK(st->streamlock); - { - Term t = Yap_MkStream(sno); - return (Yap_unify(ARG3, t)); - } + free(args); + UNLOCK(st->streamlock); + { + Term t = Yap_MkStream(sno); + return (Yap_unify(ARG3, t)); + } } /** @pred open(+ _F_,+ _M_,- _S_) is iso @@ -1387,7 +1373,7 @@ writable. */ static Int open3(USES_REGS1) { /* '$open'(+File,+Mode,?Stream,-ReturnCode) */ - return do_open(Deref(ARG1), Deref(ARG2), TermNil PASS_REGS); + return do_open(Deref(ARG1), Deref(ARG2), TermNil PASS_REGS); } /** @pred open(+ _F_,+ _M_,- _S_,+ _Opts_) is iso @@ -1469,144 +1455,155 @@ open_expands_filename. */ static Int open4(USES_REGS1) { /* '$open'(+File,+Mode,?Stream,-ReturnCode) */ - return do_open(Deref(ARG1), Deref(ARG2), Deref(ARG4) PASS_REGS); + return do_open(Deref(ARG1), Deref(ARG2), Deref(ARG4) PASS_REGS); } static Int p_file_expansion(USES_REGS1) { /* '$file_expansion'(+File,-Name) */ - Term file_name = Deref(ARG1); + Term file_name = Deref(ARG1); - /* we know file_name is bound */ - if (IsVarTerm(file_name)) { - PlIOError(INSTANTIATION_ERROR, file_name, "absolute_file_name/3"); - return (FALSE); - } - if (!Yap_findFile(RepAtom(AtomOfTerm(file_name))->StrOfAE, NULL, NULL, - LOCAL_FileNameBuf, true, YAP_ANY_FILE, true, false)) - return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, - "absolute_file_name/3")); - return (Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)))); + /* we know file_name is bound */ + if (IsVarTerm(file_name)) { + PlIOError(INSTANTIATION_ERROR, file_name, "absolute_file_name/3"); + return (FALSE); + } + if (!Yap_findFile(RepAtom(AtomOfTerm(file_name))->StrOfAE, NULL, NULL, + LOCAL_FileNameBuf, true, YAP_ANY_FILE, true, false)) + return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, file_name, + "absolute_file_name/3")); + return (Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)))); } static Int p_open_null_stream(USES_REGS1) { - Term t; - StreamDesc *st; - int sno = GetFreeStreamD(); - if (sno < 0) - return (PlIOError(SYSTEM_ERROR_INTERNAL, TermNil, - "new stream not available for open_null_stream/1")); - st = &GLOBAL_Stream[sno]; - st->status = Append_Stream_f | Output_Stream_f | Null_Stream_f; + Term t; + StreamDesc *st; + int sno = GetFreeStreamD(); + if (sno < 0) + return (PlIOError(SYSTEM_ERROR_INTERNAL, TermNil, + "new stream not available for open_null_stream/1")); + st = &GLOBAL_Stream[sno]; + st->status = Append_Stream_f | Output_Stream_f | Null_Stream_f; #if _WIN32 - st->file = fopen("NUL", "w"); + st->file = fopen("NUL", "w"); #else - st->file = fopen("/dev/null", "w"); + st->file = fopen("/dev/null", "w"); #endif - if (st->file == NULL) { - Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, - "Could not open NULL stream (/dev/null,NUL)"); - return false; - } - st->linepos = 0; - st->charcount = 0; - st->linecount = 1; - st->stream_putc = NullPutc; - st->stream_wputc = put_wchar; - st->stream_getc = PlGetc; - st->stream_wgetc = get_wchar; - st->stream_wgetc_for_read = get_wchar; - st->user_name = MkAtomTerm(st->name = AtomDevNull); - UNLOCK(st->streamlock); - t = Yap_MkStream(sno); - return (Yap_unify(ARG1, t)); + if (st->file == NULL) { + Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, + "Could not open NULL stream (/dev/null,NUL)"); + return false; + } + st->linepos = 0; + st->charcount = 0; + st->linecount = 1; + st->stream_putc = NullPutc; + st->stream_wputc = put_wchar; + st->stream_getc = PlGetc; + st->stream_wgetc = get_wchar; + st->stream_wgetc_for_read = get_wchar; + st->user_name = MkAtomTerm(st->name = AtomDevNull); + UNLOCK(st->streamlock); + t = Yap_MkStream(sno); + return (Yap_unify(ARG1, t)); } -int Yap_OpenStream(const char *fname, const char * io_mode) { - CACHE_REGS - int sno; - StreamDesc *st; - Atom at; - struct vfs *vfsp; - FILE *fd; - int flags; +int Yap_OpenStream(const char *fname, const char *io_mode) { + CACHE_REGS + int sno; + StreamDesc *st; + Atom at; + struct vfs *vfsp; + FILE *fd; + int flags; - sno = GetFreeStreamD(); - if (sno < 0) - return (PlIOError(RESOURCE_ERROR_MAX_STREAMS, MkAtomTerm(Yap_LookupAtom(fname)), - "new stream not available for opening")); - st = GLOBAL_Stream+sno; - vfsp = NULL; - if ((vfsp = vfs_owner(fname)) != NULL) { - st->u.private_data = vfsp->open(sno, fname, io_mode); - UNLOCK(st->streamlock); - fd = NULL; - if (st->u.private_data == NULL) - return (PlIOError(EXISTENCE_ERROR_SOURCE_SINK, MkAtomTerm(Yap_LookupAtom(fname)), "%s", fname)); - st->vfs = vfsp; - } else if ((fd = fopen(fname, io_mode)) == NULL || - (!strchr(io_mode, 'b') && binary_file(fname))) { - UNLOCK(st->streamlock); - if (errno == ENOENT && !strchr(io_mode, 'r')) { - return PlIOError(EXISTENCE_ERROR_SOURCE_SINK, MkAtomTerm(Yap_LookupAtom(fname)), "%s: %s", fname, - strerror(errno)); - } else { - return PlIOError(PERMISSION_ERROR_OPEN_SOURCE_SINK, MkAtomTerm(Yap_LookupAtom(fname)), "%s: %s", - fname, strerror(errno)); + sno = GetFreeStreamD(); + if (sno < 0) { + PlIOError(RESOURCE_ERROR_MAX_STREAMS, MkAtomTerm(Yap_LookupAtom(fname)), + "new stream not available for opening"); + return -1; } - } - if (strchr(io_mode, 'r')) { - if (strchr(io_mode, 'a')) { - at = AtomAppend; - flags = Append_Stream_f | Output_Stream_f; - } else { - at = AtomWrite; - flags = Output_Stream_f; + st = GLOBAL_Stream + sno; + // read, write, append + st->file = NULL; + fname = Yap_VF(fname); + if ((vfsp = vfs_owner(fname)) != NULL ) { + if (!vfsp->open(vfsp, sno, fname, io_mode)) { + UNLOCK(st->streamlock); + PlIOError(EXISTENCE_ERROR_SOURCE_SINK, + MkAtomTerm(Yap_LookupAtom(fname)), "%s", fname); + return -1; + } + } else if ((fd = fopen(fname, io_mode)) == NULL || + (!strchr(io_mode, 'b') && binary_file(fname))) { + UNLOCK(st->streamlock); + if (errno == ENOENT && !strchr(io_mode, 'r')) { + PlIOError(EXISTENCE_ERROR_SOURCE_SINK, MkAtomTerm(Yap_LookupAtom(fname)), "%s: %s", + fname, + strerror(errno)); + } else { + PlIOError(PERMISSION_ERROR_OPEN_SOURCE_SINK, MkAtomTerm(Yap_LookupAtom(fname)), + "%s: %s", + fname, strerror(errno)); + } + return -1; } - } else { - at = AtomRead; - flags = Input_Stream_f; - } - Yap_initStream(sno, fd, fname, fname, LOCAL_encoding, flags, at, NULL); - return sno; + flags = st->status; + if (strchr(io_mode, 'w')) { + if (strchr(io_mode, 'a')) { + at = AtomAppend; + flags |= Append_Stream_f | Output_Stream_f; + } else { + at = AtomWrite; + flags |= Output_Stream_f; + } + } else { + at = AtomRead; + flags |= Input_Stream_f; + } + Atom name = Yap_LookupAtom(fname); + Yap_initStream(sno, st->file, name, MkAtomTerm( name ), LOCAL_encoding, st->status, at, NULL); + __android_log_print(ANDROID_LOG_INFO, "YAPDroid", + "exists %s <%d>", fname, sno); + return sno + ; } int Yap_FileStream(FILE *fd, char *name, Term file_name, int flags) { - CACHE_REGS - int sno; - Atom at; + CACHE_REGS + int sno; + Atom at; - sno = GetFreeStreamD(); - if (sno < 0) - return (PlIOError(RESOURCE_ERROR_MAX_STREAMS, file_name, - "new stream not available for opening")); - if (flags & Output_Stream_f) { - if (flags & Append_Stream_f) - at = AtomAppend; - else - at = AtomWrite; - } else - at = AtomRead; - Yap_initStream(sno, fd, name, file_name, LOCAL_encoding, flags, at, NULL); - return sno; + sno = GetFreeStreamD(); + if (sno < 0) + return (PlIOError(RESOURCE_ERROR_MAX_STREAMS, file_name, + "new stream not available for opening")); + if (flags & Output_Stream_f) { + if (flags & Append_Stream_f) + at = AtomAppend; + else + at = AtomWrite; + } else + at = AtomRead; + Yap_initStream(sno, fd, name, file_name, LOCAL_encoding, flags, at, NULL); + return sno; } -int FileStream(FILE* fd, char *name, Term file_name, int flags ) -{ - int sno; - Atom at; +int FileStream(FILE *fd, char *name, Term file_name, int flags) { + int sno; + Atom at; - sno = GetFreeStreamD(); - if (sno < 0) - return (PlIOError(RESOURCE_ERROR_MAX_STREAMS, name, - "new stream not available for opening")); - if (flags & Output_Stream_f) { - if (flags & Append_Stream_f) - at = AtomAppend; - else - at = AtomWrite; - } else - at = AtomRead; - Yap_initStream(sno, fd, name, file_name, LOCAL_encoding, flags, at, NULL); - return sno; + sno = GetFreeStreamD(); + if (sno < 0) + return (PlIOError(RESOURCE_ERROR_MAX_STREAMS, MkAtomTerm(Yap_LookupAtom(name)), + "new stream not available for opening")); + if (flags & Output_Stream_f) { + if (flags & Append_Stream_f) + at = AtomAppend; + else + at = AtomWrite; + } else + at = AtomRead; + Yap_initStream(sno, fd, name, file_name, LOCAL_encoding, flags, at, NULL); + return sno; } #define CheckStream(arg, kind, msg) \ @@ -1614,117 +1611,117 @@ int FileStream(FILE* fd, char *name, Term file_name, int flags ) static int CheckStream__(const char *file, const char *f, int line, Term arg, int kind, const char *msg) { - int sno = -1; - arg = Deref(arg); - if (IsVarTerm(arg)) { - Yap_Error(INSTANTIATION_ERROR, arg, msg); - return -1; - } else if (IsAtomTerm(arg)) { - Atom sname = AtomOfTerm(arg); + int sno = -1; + arg = Deref(arg); + if (IsVarTerm(arg)) { + Yap_Error(INSTANTIATION_ERROR, arg, msg); + return -1; + } else if (IsAtomTerm(arg)) { + Atom sname = AtomOfTerm(arg); - if (sname == AtomUser) { - if (kind & Input_Stream_f) { - if (kind & (Output_Stream_f | Append_Stream_f)) { - PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_STREAM, arg, - "ambiguous use of 'user' as a stream"); - return (-1); + if (sname == AtomUser) { + if (kind & Input_Stream_f) { + if (kind & (Output_Stream_f | Append_Stream_f)) { + PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_STREAM, arg, + "ambiguous use of 'user' as a stream"); + return (-1); + } + sname = AtomUserIn; + } else { + sname = AtomUserOut; + } + } + if ((sno = Yap_CheckAlias(sname)) < 0) { + UNLOCK(GLOBAL_Stream[sno].streamlock); + PlIOError__(file, f, line, EXISTENCE_ERROR_STREAM, arg, msg); + return -1; + } else { + LOCK(GLOBAL_Stream[sno].streamlock); + } + } else if (IsApplTerm(arg) && FunctorOfTerm(arg) == FunctorStream) { + arg = ArgOfTerm(1, arg); + if (!IsVarTerm(arg) && IsIntegerTerm(arg)) { + sno = IntegerOfTerm(arg); } - sname = AtomUserIn; - } else { - sname = AtomUserOut; - } } - if ((sno = Yap_CheckAlias(sname)) < 0) { - UNLOCK(GLOBAL_Stream[sno].streamlock); - PlIOError__(file, f, line, EXISTENCE_ERROR_STREAM, arg, msg); - return -1; - } else { - LOCK(GLOBAL_Stream[sno].streamlock); + if (sno < 0) { + Yap_Error(DOMAIN_ERROR_STREAM_OR_ALIAS, arg, msg); + return -1; } - } else if (IsApplTerm(arg) && FunctorOfTerm(arg) == FunctorStream) { - arg = ArgOfTerm(1, arg); - if (!IsVarTerm(arg) && IsIntegerTerm(arg)) { - sno = IntegerOfTerm(arg); + if (GLOBAL_Stream[sno].status & Free_Stream_f) { + PlIOError__(file, f, line, EXISTENCE_ERROR_STREAM, arg, msg); + return -1; } - } - if (sno < 0) { - Yap_Error(DOMAIN_ERROR_STREAM_OR_ALIAS, arg, msg); - return -1; - } - if (GLOBAL_Stream[sno].status & Free_Stream_f) { - PlIOError__(file, f, line, EXISTENCE_ERROR_STREAM, arg, msg); - return -1; - } - LOCK(GLOBAL_Stream[sno].streamlock); - if ((GLOBAL_Stream[sno].status & Input_Stream_f) && - !(kind & Input_Stream_f)) { - UNLOCK(GLOBAL_Stream[sno].streamlock); - PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_STREAM, arg, msg); - return -1; - } - if ((GLOBAL_Stream[sno].status & (Append_Stream_f | Output_Stream_f)) && - !(kind & Output_Stream_f)) { - UNLOCK(GLOBAL_Stream[sno].streamlock); - PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_STREAM, arg, msg); - return -1; - } - return sno; + LOCK(GLOBAL_Stream[sno].streamlock); + if ((GLOBAL_Stream[sno].status & Input_Stream_f) && + !(kind & Input_Stream_f)) { + UNLOCK(GLOBAL_Stream[sno].streamlock); + PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_STREAM, arg, msg); + return -1; + } + if ((GLOBAL_Stream[sno].status & (Append_Stream_f | Output_Stream_f)) && + !(kind & Output_Stream_f)) { + UNLOCK(GLOBAL_Stream[sno].streamlock); + PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_STREAM, arg, msg); + return -1; + } + return sno; } int Yap_CheckStream__(const char *file, const char *f, int line, Term arg, int kind, const char *msg) { - return CheckStream__(file, f, line, arg, kind, msg); + return CheckStream__(file, f, line, arg, kind, msg); } int Yap_CheckTextStream__(const char *file, const char *f, int line, Term arg, int kind, const char *msg) { - int sno; - if ((sno = CheckStream__(file, f, line, arg, kind, msg)) < 0) - return -1; - if ((GLOBAL_Stream[sno].status & Binary_Stream_f)) { - UNLOCK(GLOBAL_Stream[sno].streamlock); - 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); - return -1; - } - return sno; + int sno; + if ((sno = CheckStream__(file, f, line, arg, kind, msg)) < 0) + return -1; + if ((GLOBAL_Stream[sno].status & Binary_Stream_f)) { + UNLOCK(GLOBAL_Stream[sno].streamlock); + 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); + return -1; + } + return sno; } int Yap_CheckBinaryStream__(const char *file, const char *f, int line, Term arg, int kind, const char *msg) { - int sno; - if ((sno = CheckStream__(file, f, line, arg, kind, msg)) < 0) - return -1; - if (!(GLOBAL_Stream[sno].status & Binary_Stream_f)) { - UNLOCK(GLOBAL_Stream[sno].streamlock); - if (kind == Input_Stream_f) - PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_TEXT_STREAM, arg, msg); - else - PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_TEXT_STREAM, arg, msg); - return -1; - } - return sno; + int sno; + if ((sno = CheckStream__(file, f, line, arg, kind, msg)) < 0) + return -1; + if (!(GLOBAL_Stream[sno].status & Binary_Stream_f)) { + UNLOCK(GLOBAL_Stream[sno].streamlock); + if (kind == Input_Stream_f) + PlIOError__(file, f, line, PERMISSION_ERROR_INPUT_TEXT_STREAM, arg, msg); + else + PlIOError__(file, f, line, PERMISSION_ERROR_OUTPUT_TEXT_STREAM, arg, msg); + return -1; + } + return sno; } /* used from C-interface */ int Yap_GetFreeStreamDForReading(void) { - int sno = GetFreeStreamD(); - StreamDesc *s; + int sno = GetFreeStreamD(); + StreamDesc *s; - if (sno < 0) + if (sno < 0) + return sno; + s = GLOBAL_Stream + sno; + s->status |= User_Stream_f | Input_Stream_f; + s->charcount = 0; + s->linecount = 1; + s->linepos = 0; + Yap_DefaultStreamOps(s); + UNLOCK(s->streamlock); return sno; - s = GLOBAL_Stream + sno; - s->status |= User_Stream_f | Input_Stream_f; - s->charcount = 0; - s->linecount = 1; - s->linepos = 0; - Yap_DefaultStreamOps(s); - UNLOCK(s->streamlock); - return sno; } /** @@ -1735,11 +1732,11 @@ int Yap_GetFreeStreamDForReading(void) { */ static Int always_prompt_user(USES_REGS1) { - StreamDesc *s = GLOBAL_Stream + StdInStream; + StreamDesc *s = GLOBAL_Stream + StdInStream; - s->status |= Promptable_Stream_f; - Yap_DefaultStreamOps(s); - return (TRUE); + s->status |= Promptable_Stream_f; + Yap_DefaultStreamOps(s); + return (TRUE); } static Int close1 /** @pred close(+ _S_) is iso @@ -1752,18 +1749,18 @@ static Int close1 /** @pred close(+ _S_) is iso */ - (USES_REGS1) { /* '$close'(+GLOBAL_Stream) */ - Int sno = CheckStream( - ARG1, (Input_Stream_f | Output_Stream_f | Socket_Stream_f), "close/2"); - if (sno < 0) - return (FALSE); - if (sno <= StdErrStream) { + (USES_REGS1) { /* '$close'(+GLOBAL_Stream) */ + Int sno = CheckStream( + ARG1, (Input_Stream_f | Output_Stream_f | Socket_Stream_f), "close/2"); + if (sno < 0) + return (FALSE); + if (sno <= StdErrStream) { + UNLOCK(GLOBAL_Stream[sno].streamlock); + return TRUE; + } + Yap_CloseStream(sno); UNLOCK(GLOBAL_Stream[sno].streamlock); - return TRUE; - } - Yap_CloseStream(sno); - UNLOCK(GLOBAL_Stream[sno].streamlock); - return (TRUE); + return (TRUE); } #define CLOSE_DEFS() \ @@ -1771,7 +1768,9 @@ static Int close1 /** @pred close(+ _S_) is iso #define PAR(x, y, z) z -typedef enum close_enum_choices { CLOSE_DEFS() } close_choices_t; +typedef enum close_enum_choices { + CLOSE_DEFS() +} close_choices_t; #undef PAR @@ -1791,45 +1790,46 @@ YAP currently ignores these options. */ static Int close2(USES_REGS1) { /* '$close'(+GLOBAL_Stream) */ - Int sno = CheckStream( - ARG1, (Input_Stream_f | Output_Stream_f | Socket_Stream_f), "close/2"); - Term tlist; - if (sno < 0) - return (FALSE); - if (sno <= StdErrStream) { - UNLOCK(GLOBAL_Stream[sno].streamlock); - return TRUE; - } - xarg *args = - Yap_ArgListToVector((tlist = Deref(ARG2)), close_defs, CLOSE_END); - if (args == NULL) { - if (LOCAL_Error_TYPE != YAP_NO_ERROR) { - if (LOCAL_Error_TYPE == DOMAIN_ERROR_PROLOG_FLAG) - LOCAL_Error_TYPE = DOMAIN_ERROR_CLOSE_OPTION; - Yap_Error(LOCAL_Error_TYPE, tlist, NULL); + Int sno = CheckStream( + ARG1, (Input_Stream_f | Output_Stream_f | Socket_Stream_f), "close/2"); + Term tlist; + if (sno < 0) + return (FALSE); + if (sno <= StdErrStream) { + UNLOCK(GLOBAL_Stream[sno].streamlock); + return TRUE; } - return false; - return FALSE; - } - // if (args[CLOSE_FORCE].used) { - // } - Yap_CloseStream(sno); - UNLOCK(GLOBAL_Stream[sno].streamlock); - return (TRUE); + xarg *args = + Yap_ArgListToVector((tlist = Deref(ARG2)), close_defs, CLOSE_END); + if (args == NULL) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE == DOMAIN_ERROR_PROLOG_FLAG) + LOCAL_Error_TYPE = DOMAIN_ERROR_CLOSE_OPTION; + Yap_Error(LOCAL_Error_TYPE, tlist, NULL); + } + return false; + return FALSE; + } + // if (args[CLOSE_FORCE].used) { + // } + Yap_CloseStream(sno); + UNLOCK(GLOBAL_Stream[sno].streamlock); + return (TRUE); } Term read_line(int sno) { - CACHE_REGS - Term tail; - Int ch; + CACHE_REGS + Term tail; + Int ch; - if ((ch = GLOBAL_Stream[sno].stream_wgetc(sno)) == 10) { - return (TermNil); - } - tail = read_line(sno); - return (MkPairTerm(MkIntTerm(ch), tail)); + if ((ch = GLOBAL_Stream[sno].stream_wgetc(sno)) == 10) { + return (TermNil); + } + tail = read_line(sno); + return (MkPairTerm(MkIntTerm(ch), tail)); } + #define ABSOLUTE_FILE_NAME_DEFS() \ PAR("access", isatom, ABSOLUTE_FILE_NAME_ACCESS) \ , PAR("expand", booleanFlag, ABSOLUTE_FILE_NAME_EXPAND), \ @@ -1846,7 +1846,7 @@ Term read_line(int sno) { #define PAR(x, y, z) z typedef enum ABSOLUTE_FILE_NAME_enum_ { - ABSOLUTE_FILE_NAME_DEFS() + ABSOLUTE_FILE_NAME_DEFS() } absolute_file_name_choices_t; #undef PAR @@ -1855,147 +1855,147 @@ typedef enum ABSOLUTE_FILE_NAME_enum_ { { x, y, z } static const param_t absolute_file_name_search_defs[] = { - ABSOLUTE_FILE_NAME_DEFS()}; + ABSOLUTE_FILE_NAME_DEFS()}; #undef PAR static Int abs_file_parameters(USES_REGS1) { - Term t[ABSOLUTE_FILE_NAME_END]; - Term tlist = Deref(ARG1), tf; - /* get options */ - xarg *args = Yap_ArgListToVector(tlist, absolute_file_name_search_defs, - ABSOLUTE_FILE_NAME_END); - if (args == NULL) { - if (LOCAL_Error_TYPE != YAP_NO_ERROR) { - if (LOCAL_Error_TYPE == DOMAIN_ERROR_PROLOG_FLAG) - LOCAL_Error_TYPE = DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION; - Yap_Error(LOCAL_Error_TYPE, tlist, NULL); + Term t[ABSOLUTE_FILE_NAME_END]; + Term tlist = Deref(ARG1), tf; + /* get options */ + xarg *args = Yap_ArgListToVector(tlist, absolute_file_name_search_defs, + ABSOLUTE_FILE_NAME_END); + if (args == NULL) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE == DOMAIN_ERROR_PROLOG_FLAG) + LOCAL_Error_TYPE = DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION; + Yap_Error(LOCAL_Error_TYPE, tlist, NULL); + } + return false; } - return false; - } - /* done */ - if (args[ABSOLUTE_FILE_NAME_EXTENSIONS].used) { - t[ABSOLUTE_FILE_NAME_EXTENSIONS] = - args[ABSOLUTE_FILE_NAME_EXTENSIONS].tvalue; - } else { - t[ABSOLUTE_FILE_NAME_EXTENSIONS] = TermNil; - } - if (args[ABSOLUTE_FILE_NAME_RELATIVE_TO].used) { - t[ABSOLUTE_FILE_NAME_RELATIVE_TO] = - gethdir(args[ABSOLUTE_FILE_NAME_RELATIVE_TO].tvalue); - } else { - t[ABSOLUTE_FILE_NAME_RELATIVE_TO] = gethdir(TermDot); - } - if (args[ABSOLUTE_FILE_NAME_FILE_TYPE].used) - t[ABSOLUTE_FILE_NAME_FILE_TYPE] = args[ABSOLUTE_FILE_NAME_FILE_TYPE].tvalue; - else - t[ABSOLUTE_FILE_NAME_FILE_TYPE] = TermTxt; - if (args[ABSOLUTE_FILE_NAME_ACCESS].used) - t[ABSOLUTE_FILE_NAME_ACCESS] = args[ABSOLUTE_FILE_NAME_ACCESS].tvalue; - else - t[ABSOLUTE_FILE_NAME_ACCESS] = TermNone; - if (args[ABSOLUTE_FILE_NAME_FILE_ERRORS].used) - t[ABSOLUTE_FILE_NAME_FILE_ERRORS] = - args[ABSOLUTE_FILE_NAME_FILE_ERRORS].tvalue; - else - t[ABSOLUTE_FILE_NAME_FILE_ERRORS] = TermError; - if (args[ABSOLUTE_FILE_NAME_SOLUTIONS].used) - t[ABSOLUTE_FILE_NAME_SOLUTIONS] = args[ABSOLUTE_FILE_NAME_SOLUTIONS].tvalue; - else - t[ABSOLUTE_FILE_NAME_SOLUTIONS] = TermFirst; - if (args[ABSOLUTE_FILE_NAME_EXPAND].used) - t[ABSOLUTE_FILE_NAME_EXPAND] = args[ABSOLUTE_FILE_NAME_EXPAND].tvalue; - else - t[ABSOLUTE_FILE_NAME_EXPAND] = TermFalse; - if (args[ABSOLUTE_FILE_NAME_GLOB].used) { - t[ABSOLUTE_FILE_NAME_GLOB] = args[ABSOLUTE_FILE_NAME_GLOB].tvalue; - t[ABSOLUTE_FILE_NAME_EXPAND] = TermTrue; - } else - t[ABSOLUTE_FILE_NAME_GLOB] = TermEmptyAtom; - if (args[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH].used) - t[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH] = - args[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH].tvalue; - else - t[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH] = - (trueGlobalPrologFlag(VERBOSE_FILE_SEARCH_FLAG) ? TermTrue : TermFalse); - tf = Yap_MkApplTerm(Yap_MkFunctor(AtomOpt, ABSOLUTE_FILE_NAME_END), - ABSOLUTE_FILE_NAME_END, t); - return (Yap_unify(ARG2, tf)); + /* done */ + if (args[ABSOLUTE_FILE_NAME_EXTENSIONS].used) { + t[ABSOLUTE_FILE_NAME_EXTENSIONS] = + args[ABSOLUTE_FILE_NAME_EXTENSIONS].tvalue; + } else { + t[ABSOLUTE_FILE_NAME_EXTENSIONS] = TermNil; + } + if (args[ABSOLUTE_FILE_NAME_RELATIVE_TO].used) { + t[ABSOLUTE_FILE_NAME_RELATIVE_TO] = + gethdir(args[ABSOLUTE_FILE_NAME_RELATIVE_TO].tvalue); + } else { + t[ABSOLUTE_FILE_NAME_RELATIVE_TO] = gethdir(TermDot); + } + if (args[ABSOLUTE_FILE_NAME_FILE_TYPE].used) + t[ABSOLUTE_FILE_NAME_FILE_TYPE] = args[ABSOLUTE_FILE_NAME_FILE_TYPE].tvalue; + else + t[ABSOLUTE_FILE_NAME_FILE_TYPE] = TermTxt; + if (args[ABSOLUTE_FILE_NAME_ACCESS].used) + t[ABSOLUTE_FILE_NAME_ACCESS] = args[ABSOLUTE_FILE_NAME_ACCESS].tvalue; + else + t[ABSOLUTE_FILE_NAME_ACCESS] = TermNone; + if (args[ABSOLUTE_FILE_NAME_FILE_ERRORS].used) + t[ABSOLUTE_FILE_NAME_FILE_ERRORS] = + args[ABSOLUTE_FILE_NAME_FILE_ERRORS].tvalue; + else + t[ABSOLUTE_FILE_NAME_FILE_ERRORS] = TermError; + if (args[ABSOLUTE_FILE_NAME_SOLUTIONS].used) + t[ABSOLUTE_FILE_NAME_SOLUTIONS] = args[ABSOLUTE_FILE_NAME_SOLUTIONS].tvalue; + else + t[ABSOLUTE_FILE_NAME_SOLUTIONS] = TermFirst; + if (args[ABSOLUTE_FILE_NAME_EXPAND].used) + t[ABSOLUTE_FILE_NAME_EXPAND] = args[ABSOLUTE_FILE_NAME_EXPAND].tvalue; + else + t[ABSOLUTE_FILE_NAME_EXPAND] = TermFalse; + if (args[ABSOLUTE_FILE_NAME_GLOB].used) { + t[ABSOLUTE_FILE_NAME_GLOB] = args[ABSOLUTE_FILE_NAME_GLOB].tvalue; + t[ABSOLUTE_FILE_NAME_EXPAND] = TermTrue; + } else + t[ABSOLUTE_FILE_NAME_GLOB] = TermEmptyAtom; + if (args[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH].used) + t[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH] = + args[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH].tvalue; + else + t[ABSOLUTE_FILE_NAME_VERBOSE_FILE_SEARCH] = + (trueGlobalPrologFlag(VERBOSE_FILE_SEARCH_FLAG) ? TermTrue : TermFalse); + tf = Yap_MkApplTerm(Yap_MkFunctor(AtomOpt, ABSOLUTE_FILE_NAME_END), + ABSOLUTE_FILE_NAME_END, t); + return (Yap_unify(ARG2, tf)); } static Int get_abs_file_parameter(USES_REGS1) { - Term t = Deref(ARG1), topts = Deref(ARG2); - /* get options */ - /* done */ - int i = Yap_ArgKey(AtomOfTerm(t), absolute_file_name_search_defs, - ABSOLUTE_FILE_NAME_END); - if (i >= 0) - return Yap_unify(ARG3, ArgOfTerm(i + 1, topts)); - Yap_Error(DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION, ARG1, NULL); - return false; + Term t = Deref(ARG1), topts = Deref(ARG2); + /* get options */ + /* done */ + int i = Yap_ArgKey(AtomOfTerm(t), absolute_file_name_search_defs, + ABSOLUTE_FILE_NAME_END); + if (i >= 0) + return Yap_unify(ARG3, ArgOfTerm(i + 1, topts)); + Yap_Error(DOMAIN_ERROR_ABSOLUTE_FILE_NAME_OPTION, ARG1, NULL); + return false; } void Yap_InitPlIO(struct yap_boot_params *argi) { - Int i; + Int i; if (argi->inp > 0) - Yap_stdin = fdopen(argi->inp - 1, "r"); - else if (argi->inp) - Yap_stdin = NULL; - else - Yap_stdin = stdin; - if (argi->out > 0) - Yap_stdout = fdopen(argi->out - 1, "a"); - else if (argi->out) - Yap_stdout = NULL; - else - Yap_stdout = stdout; - if (argi->err > 0) - Yap_stderr = fdopen(argi->err - 1, "a"); - else if (argi->out) - Yap_stdout = NULL; - else - Yap_stderr = stderr; - GLOBAL_Stream = - (StreamDesc *)Yap_AllocCodeSpace(sizeof(StreamDesc) * MaxStreams); - for (i = 0; i < MaxStreams; ++i) { - INIT_LOCK(GLOBAL_Stream[i].streamlock); - GLOBAL_Stream[i].status = Free_Stream_f; - } - InitStdStreams(); + Yap_stdin = fdopen(argi->inp - 1, "r"); + else if (argi->inp) + Yap_stdin = NULL; + else + Yap_stdin = stdin; + if (argi->out > 0) + Yap_stdout = fdopen(argi->out - 1, "a"); + else if (argi->out) + Yap_stdout = NULL; + else + Yap_stdout = stdout; + if (argi->err > 0) + Yap_stderr = fdopen(argi->err - 1, "a"); + else if (argi->out) + Yap_stdout = NULL; + else + Yap_stderr = stderr; + GLOBAL_Stream = + (StreamDesc *) Yap_AllocCodeSpace(sizeof(StreamDesc) * MaxStreams); + for (i = 0; i < MaxStreams; ++i) { + INIT_LOCK(GLOBAL_Stream[i].streamlock); + GLOBAL_Stream[i].status = Free_Stream_f; + } + InitStdStreams(); } void Yap_InitIOPreds(void) { - /* here the Input/Output predicates */ - Yap_InitCPred("always_prompt_user", 0, always_prompt_user, - SafePredFlag | SyncPredFlag); - Yap_InitCPred("close", 1, close1, SafePredFlag | SyncPredFlag); - Yap_InitCPred("close", 2, close2, SafePredFlag | SyncPredFlag); - Yap_InitCPred("open", 4, open4, SyncPredFlag); - Yap_InitCPred("open", 3, open3, SyncPredFlag); - Yap_InitCPred("abs_file_parameters", 2, abs_file_parameters, - SyncPredFlag | HiddenPredFlag); - Yap_InitCPred("get_abs_file_parameter", 3, get_abs_file_parameter, - SafePredFlag | SyncPredFlag | HiddenPredFlag); - Yap_InitCPred("$file_expansion", 2, p_file_expansion, - SafePredFlag | SyncPredFlag | HiddenPredFlag); - Yap_InitCPred("$open_null_stream", 1, p_open_null_stream, - SafePredFlag | SyncPredFlag | HiddenPredFlag); - Yap_InitIOStreams(); - Yap_InitCharsio(); - Yap_InitChtypes(); - Yap_InitConsole(); - Yap_InitReadUtil(); - Yap_InitMems(); - Yap_InitPipes(); - Yap_InitFiles(); - Yap_InitWriteTPreds(); - Yap_InitReadTPreds(); - Yap_InitFormat(); - Yap_InitRandomPreds(); + /* here the Input/Output predicates */ + Yap_InitCPred("always_prompt_user", 0, always_prompt_user, + SafePredFlag | SyncPredFlag); + Yap_InitCPred("close", 1, close1, SafePredFlag | SyncPredFlag); + Yap_InitCPred("close", 2, close2, SafePredFlag | SyncPredFlag); + Yap_InitCPred("open", 4, open4, SyncPredFlag); + Yap_InitCPred("open", 3, open3, SyncPredFlag); + Yap_InitCPred("abs_file_parameters", 2, abs_file_parameters, + SyncPredFlag | HiddenPredFlag); + Yap_InitCPred("get_abs_file_parameter", 3, get_abs_file_parameter, + SafePredFlag | SyncPredFlag | HiddenPredFlag); + Yap_InitCPred("$file_expansion", 2, p_file_expansion, + SafePredFlag | SyncPredFlag | HiddenPredFlag); + Yap_InitCPred("$open_null_stream", 1, p_open_null_stream, + SafePredFlag | SyncPredFlag | HiddenPredFlag); + Yap_InitIOStreams(); + Yap_InitCharsio(); + Yap_InitChtypes(); + Yap_InitConsole(); + Yap_InitReadUtil(); + Yap_InitMems(); + Yap_InitPipes(); + Yap_InitFiles(); + Yap_InitWriteTPreds(); + Yap_InitReadTPreds(); + Yap_InitFormat(); + Yap_InitRandomPreds(); #if USE_READLINE - Yap_InitReadlinePreds(); + Yap_InitReadlinePreds(); #endif - Yap_InitSockets(); - Yap_InitSignalPreds(); - Yap_InitSysPreds(); - Yap_InitTimePreds(); + Yap_InitSockets(); + Yap_InitSignalPreds(); + Yap_InitSysPreds(); + Yap_InitTimePreds(); } diff --git a/os/iopreds.h b/os/iopreds.h index 012fe39b7..736901836 100644 --- a/os/iopreds.h +++ b/os/iopreds.h @@ -80,7 +80,7 @@ Int Yap_CloseSocket(int, socket_info, socket_domain); #endif /* USE_SOCKET */ extern bool Yap_clearInput(int sno); -extern Term Yap_read_term(int inp_stream, Term opts, bool clauatse); +extern Term Yap_read_term(int inp_stream, Term opts, bool clause); extern Term Yap_Parse(UInt prio, encoding_t enc, Term cmod); extern void init_read_data(ReadData _PL_rd, struct stream_desc *s); @@ -216,7 +216,7 @@ INLINE_ONLY inline EXTERN void count_output_char(int ch, StreamDesc *s) { inline static Term StreamName(int i) { return (GLOBAL_Stream[i].user_name); } -inline static Atom StreamFullName(int i) { return (GLOBAL_Stream[i].name); } +inline static Atom StreamFullName(int i) { return (Atom)(GLOBAL_Stream[i].name); } inline static void console_count_output_char(int ch, StreamDesc *s) { CACHE_REGS diff --git a/os/readterm.c b/os/readterm.c index bda712c89..fb143e238 100644 --- a/os/readterm.c +++ b/os/readterm.c @@ -829,13 +829,13 @@ static parser_state_t initParser(Term opts, FEnv *fe, REnv *re, int inp_stream, return YAP_SCANNING; } -static parser_state_t scan(REnv *re, FEnv *fe, int inp_stream) { +static parser_state_t scan(REnv *re, FEnv *fe, int sno) { CACHE_REGS /* preserve value of H after scanning: otherwise we may lose strings and floats */ LOCAL_tokptr = LOCAL_toktide = - Yap_tokenizer(GLOBAL_Stream + inp_stream, false, &fe->tpos); + Yap_tokenizer(GLOBAL_Stream + sno, false, &fe->tpos); #if DEBUG if (GLOBAL_Option[2]) { TokEntry *t = LOCAL_tokptr; @@ -857,7 +857,7 @@ static parser_state_t scan(REnv *re, FEnv *fe, int inp_stream) { LOCAL_Error_TYPE = SYNTAX_ERROR; return YAP_PARSING_ERROR; } - return scanEOF(fe, inp_stream); + return scanEOF(fe, sno); } static parser_state_t scanError(REnv *re, FEnv *fe, int inp_stream) { @@ -956,7 +956,7 @@ static parser_state_t parse(REnv *re, FEnv *fe, int inp_stream) { * * */ -Term Yap_read_term(int inp_stream, Term opts, bool clause) { +Term Yap_read_term(int sno, Term opts, bool clause) { FEnv fe; REnv re; #if EMACS @@ -968,23 +968,23 @@ Term Yap_read_term(int inp_stream, Term opts, bool clause) { while (true) { switch (state) { case YAP_START_PARSING: - state = initParser(opts, &fe, &re, inp_stream, clause); + state = initParser(opts, &fe, &re, sno, clause); if (state == YAP_PARSING_FINISHED) { pop_text_stack(lvl); return 0; } break; case YAP_SCANNING: - state = scan(&re, &fe, inp_stream); + state = scan(&re, &fe, sno); break; case YAP_SCANNING_ERROR: - state = scanError(&re, &fe, inp_stream); + state = scanError(&re, &fe, sno); break; case YAP_PARSING: - state = parse(&re, &fe, inp_stream); + state = parse(&re, &fe, sno); break; case YAP_PARSING_ERROR: - state = parseError(&re, &fe, inp_stream); + state = parseError(&re, &fe, sno); break; case YAP_PARSING_FINISHED: { CACHE_REGS @@ -1021,17 +1021,17 @@ static Int static Int read_term( USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ - int inp_stream; + int sno; Term out; /* needs to change LOCAL_output_stream for write */ - inp_stream = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); - if (inp_stream == -1) { + sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); + if (sno == -1) { return (FALSE); } - out = Yap_read_term(inp_stream, add_output(ARG2, ARG3), false); - UNLOCK(GLOBAL_Stream[inp_stream].streamlock); + out = Yap_read_term(sno, add_output(ARG2, ARG3), false); + UNLOCK(GLOBAL_Stream[sno].streamlock); return out != 0L; } @@ -1060,7 +1060,7 @@ static const param_t read_clause_defs[] = {READ_CLAUSE_DEFS()}; #undef PAR static xarg *setClauseReadEnv(Term opts, FEnv *fe, struct renv *re, - int inp_stream) { + int sno) { CACHE_REGS xarg *args = Yap_ArgListToVector(opts, read_clause_defs, READ_CLAUSE_END); @@ -1082,7 +1082,7 @@ static xarg *setClauseReadEnv(Term opts, FEnv *fe, struct renv *re, fe->cmod = PROLOG_MODULE; } re->bq = getBackQuotesFlag(); - fe->enc = GLOBAL_Stream[inp_stream].encoding; + fe->enc = GLOBAL_Stream[sno].encoding; fe->sp = 0; fe->qq = 0; if (args[READ_CLAUSE_OUTPUT].used) { @@ -1118,12 +1118,12 @@ static xarg *setClauseReadEnv(Term opts, FEnv *fe, struct renv *re, fe->vp = 0; } fe->ce = Yap_CharacterEscapes(fe->cmod); - re->seekable = (GLOBAL_Stream[inp_stream].status & Seekable_Stream_f) != 0; + re->seekable = (GLOBAL_Stream[sno].status & Seekable_Stream_f) != 0; if (re->seekable) { #if HAVE_FGETPOS - fgetpos(GLOBAL_Stream[inp_stream].file, &re->rpos); + fgetpos(GLOBAL_Stream[sno].file, &re->rpos); #else - re->cpos = GLOBAL_Stream[inp_stream].charcount; + re->cpos = GLOBAL_Stream[sno].charcount; #endif } re->prio = LOCAL_default_priority; @@ -1166,15 +1166,15 @@ static Int read_clause2(USES_REGS1) { */ static Int read_clause( USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ - int inp_stream; + int sno; Term out; /* needs to change LOCAL_output_stream for write */ - inp_stream = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); - if (inp_stream < 0) + sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); + if (sno < 0) return false; - out = Yap_read_term(inp_stream, add_output(ARG2, ARG3), true); - UNLOCK(GLOBAL_Stream[inp_stream].streamlock); + out = Yap_read_term(sno, add_output(ARG2, ARG3), true); + UNLOCK(GLOBAL_Stream[sno].streamlock); return out != 0; } @@ -1191,20 +1191,20 @@ static Int read_clause( */ #if 0 static Int start_mega(USES_REGS1) { - int inp_stream; + int sno; Term out; Term t3 = Deref(ARG3); yhandle_t h = Yap_InitSlot(ARG2); TokENtry *tok; arity_t srity = 0; /* needs to change LOCAL_output_stream for write */ - inp_stream = Yap_CheckTextStream(ARG1, Input_Stream_f, "read_exo/3"); - if (inp_stream < 0) + sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "read_exo/3"); + if (sno < 0) return false; /* preserve value of H after scanning: otherwise we may lose strings and floats */ LOCAL_tokptr = LOCAL_toktide = - x Yap_tokenizer(GLOBAL_Stream + inp_stream, false, &tpos); + x Yap_tokenizer(GLOBAL_Stream + sno, false, &tpos); if (tokptr->Tok == Name_tok && (next = tokptr->TokNext) != NULL && next->Tok == Ponctuation_tok && next->TokInfo == TermOpenBracket) { bool start = true; @@ -1253,16 +1253,16 @@ static Int source_location(USES_REGS1) { */ static Int read2( USES_REGS1) { /* '$read2'(+Flag,?Term,?Module,?Vars,-Pos,-Err,+Stream) */ - int inp_stream; + int sno; Int out; /* needs to change LOCAL_output_stream for write */ - inp_stream = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); - if (inp_stream == -1) { + sno = Yap_CheckTextStream(ARG1, Input_Stream_f, "read/3"); + if (sno == -1) { return (FALSE); } - out = Yap_read_term(inp_stream, add_output(ARG2, TermNil), false); - UNLOCK(GLOBAL_Stream[inp_stream].streamlock); + out = Yap_read_term(sno, add_output(ARG2, TermNil), false); + UNLOCK(GLOBAL_Stream[sno].streamlock); return out; } diff --git a/os/streams.c b/os/streams.c index f343884af..681c9b5df 100644 --- a/os/streams.c +++ b/os/streams.c @@ -959,7 +959,8 @@ static void CloseStream(int sno) { CACHE_REGS fflush(NULL); - if (!(GLOBAL_Stream[sno].status & + if (GLOBAL_Stream[sno].file && + !(GLOBAL_Stream[sno].status & (Null_Stream_f | Socket_Stream_f | InMemory_Stream_f | Pipe_Stream_f))) fclose(GLOBAL_Stream[sno].file); #if HAVE_SOCKET diff --git a/os/sysbits.c b/os/sysbits.c index f1aa12a04..8250ad79c 100644 --- a/os/sysbits.c +++ b/os/sysbits.c @@ -34,13 +34,6 @@ static void FileError(yap_error_number type, Term where, const char *format, } } -/// Allocate a temporary buffer -static char *getFileNameBuffer(void) { - - return Yap_AllocAtomSpace(YAP_FILENAME_MAX); -} - -static void freeFileNameBuffer(char *s) { Yap_FreeCodeSpace(s); } static Int p_sh(USES_REGS1); static Int p_shell(USES_REGS1); @@ -52,7 +45,6 @@ static Int p_putenv(USES_REGS1); static Term do_glob(const char *spec, bool ok_to); #ifdef MACYAP -static int chdir(char *); /* #define signal skel_signal */ #endif /* MACYAP */ static const char *expandVars(const char *spec, char *u); @@ -103,8 +95,9 @@ static bool is_directory(const char *FileName) { bool Yap_Exists(const char *f) { VFS_t *vfs; + f = Yap_VFAlloc(f); if ((vfs = vfs_owner(f))) { - return vfs->exists(vfs,f) != NULL; + return vfs->exists(vfs,f); } #if _WIN32 if (_access(f, 0) == 0) @@ -114,8 +107,9 @@ bool Yap_Exists(const char *f) { } return false; #elif HAVE_ACCESS - if (access(f, F_OK) == 0) - return true; + if (access(f, F_OK) == 0) { + return true; + } if (errno == EINVAL) { Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "bad flags to access"); } @@ -147,10 +141,13 @@ int Yap_dir_separator(int ch) { return dir_separator(ch); } char *libdir = NULL; #endif -bool Yap_IsAbsolutePath(const char *p0) { +bool Yap_IsAbsolutePath(const char *p0, bool expand) { // verify first if expansion is needed: ~/ or $HOME/ - const char *p = expandVars(p0, LOCAL_FileNameBuf); + const char *p = p0; bool nrc; + if (expand) { + p = expandVars(p0, LOCAL_FileNameBuf); + } #if _WIN32 || __MINGW32__ nrc = !PathIsRelative(p); #else @@ -266,7 +263,7 @@ static const char *PlExpandVars(const char *source, const char *root, pop_text_stack(lvl); return NULL; } - if (root && !Yap_IsAbsolutePath(source)) { + if (root && !Yap_IsAbsolutePath(source, false)) { strncpy(result, root, YAP_FILENAME_MAX); if (root[strlen(root) - 1] != '/') strncat(result, "/", YAP_FILENAME_MAX); @@ -346,7 +343,9 @@ static char *PrologPath(const char *Y, char *X) { return (char *)Y; } #define HAVE_REALPATH 1 #endif - bool ChDir(const char *path) { +char virtual_cwd[YAP_FILENAME_MAX + 1]; + + bool Yap_ChDir(const char *path) { bool rc = false; char qp[FILENAME_MAX + 1]; const char *qpath = Yap_AbsoluteFile(path, qp, true); @@ -370,14 +369,15 @@ static char *PrologPath(const char *Y, char *X) { return (char *)Y; } return rc; } + static const char *myrealpath(const char *path, char *out) { - if (!out) - out = LOCAL_FileNameBuf; -#if _WIN32 + int lvl = push_text_stack(); + #if _WIN32 DWORD retval = 0; // notice that the file does not need to exist retval = GetFullPathName(path, YAP_FILENAME_MAX, out, NULL); + pop_text_stack(lvl); if (retval == 0) { Yap_WinError("Generating a full path name for a file"); return NULL; @@ -388,12 +388,13 @@ static const char *myrealpath(const char *path, char *out) { char *rc = realpath(path, NULL); if (rc) { + pop_text_stack(lvl); return rc; } // rc = NULL; if (errno == ENOENT || errno == EACCES) { - char base[YAP_FILENAME_MAX + 1]; - strncpy(base, path, YAP_FILENAME_MAX - 1); + char *base= Malloc(YAP_FILENAME_MAX + 1); + strncpy(base, path, YAP_FILENAME_MAX ); rc = realpath(dirname(base), out); if (rc) { @@ -417,6 +418,7 @@ static const char *myrealpath(const char *path, char *out) { } #endif strcat(rc, b); + rc = pop_output_text_stack(lvl, rc); return rc; } } @@ -424,6 +426,7 @@ static const char *myrealpath(const char *path, char *out) { #endif out = malloc(strlen(path) + 1); strcpy(out, path); + pop_text_stack(lvl); return out; } @@ -929,7 +932,7 @@ static Int make_directory(USES_REGS1) { #if defined(__MINGW32__) || _MSC_VER if (_mkdir(fd) == -1) { #else - if (mkdir(fd, 0777) == -1) { + if (mkdir(Yap_VFAlloc(fd), 0777) == -1) { #endif /* return an error number */ return false; // errno? @@ -938,7 +941,7 @@ static Int make_directory(USES_REGS1) { } static Int p_rmdir(USES_REGS1) { - const char *fd = AtomName(AtomOfTerm(ARG1)); + const char *fd = Yap_VFAlloc(AtomName(AtomOfTerm(ARG1))); #if defined(__MINGW32__) || _MSC_VER if (_rmdir(fd) == -1) { #else @@ -1136,7 +1139,14 @@ static int volume_header(char *file) { int Yap_volume_header(char *file) { return volume_header(file); } -const char *Yap_getcwd(const char *cwd, size_t cwdlen) { +const char *Yap_getcwd(char *cwd, size_t cwdlen) { + if (virtual_cwd[0]) { + if (!cwd) { + cwd = malloc(cwdlen+1); + } + strcpy( cwd, virtual_cwd); + return cwd; + } #if _WIN32 || defined(__MINGW32__) if (GetCurrentDirectory(cwdlen, (char *)cwd) == 0) { Yap_WinError("GetCurrentDirectory failed"); @@ -1166,7 +1176,7 @@ static Int working_directory(USES_REGS1) { } if (t2 == TermEmptyAtom || t2 == TermDot) return true; - return ChDir(RepAtom(AtomOfTerm(t2))->StrOfAE); + return Yap_ChDir(RepAtom(AtomOfTerm(t2))->StrOfAE); } /** Yap_findFile(): tries to locate a file, no expansion should be performed/ @@ -1188,11 +1198,21 @@ const char *Yap_findFile(const char *isource, const char *idef, YAP_file_type_t ftype, bool expand_root, bool in_lib) { char *save_buffer = NULL; - const char *root = iroot, *source = isource; + char *root, *source; int rc = FAIL_RESTORE; - int try - = 0; + int try = 0; bool abspath = false; + int lvl = push_text_stack(); + root = Malloc(YAP_FILENAME_MAX+1); + source= Malloc(YAP_FILENAME_MAX+1); + if (iroot && iroot[0]) + strcpy(root, iroot); + else + root[0] = 0; + if (isource && isource[0]) + strcpy(source, isource); + else + source[0] = 0; //__android_log_print(ANDROID_LOG_ERROR, "YAPDroid " __FUNCTION__, // "try=%d %s %s", try, isource, iroot) ; } while (rc == FAIL_RESTORE) { @@ -1201,21 +1221,28 @@ const char *Yap_findFile(const char *isource, const char *idef, // { CACHE_REGS switch (try ++) { case 0: // path or file name is given; - root = iroot; - if (idef || isource) { - source = (isource ? isource : idef); + if (!source[0] && idef && idef[0]) { + strcpy(source, idef); } - if (source) { - abspath = Yap_IsAbsolutePath(source); + if (source[0]) { + abspath = Yap_IsAbsolutePath(source, expand_root); } - if (!abspath && !root && ftype == YAP_BOOT_PL) { - root = YAP_PL_SRCDIR; + if (!abspath && !root[0] && ftype == YAP_BOOT_PL) { + strcpy(root, YAP_PL_SRCDIR); } break; case 1: // library directory is given in command line if (in_lib && ftype == YAP_SAVED_STATE) { - root = iroot; - source = (isource ? isource : idef); + if (iroot && iroot[0]) + strcpy(root, iroot); + else + root[0] = 0; + if (isource && isource[0]) + strcpy(source, isource); + else if (idef && idef[0]) + strcpy(source, idef); + else + source[0] = 0; } else { done = true; } @@ -1223,35 +1250,44 @@ const char *Yap_findFile(const char *isource, const char *idef, case 2: // use environment variable YAPLIBDIR #if HAVE_GETENV if (in_lib) { + const char *eroot; + if (ftype == YAP_SAVED_STATE || ftype == YAP_OBJ) { - root = getenv("YAPLIBDIR"); + eroot = getenv("YAPLIBDIR"); } else if (ftype == YAP_BOOT_PL) { - root = getenv("YAPSHAREDIR" - "/pl"); - if (root == NULL) { + eroot = getenv("YAPSHAREDIR"); + if (eroot == NULL) { continue; } else { - save_buffer = getFileNameBuffer(); - strncpy(save_buffer, root, YAP_FILENAME_MAX); - strncat(save_buffer, "/pl", YAP_FILENAME_MAX); + strncpy(root, eroot, YAP_FILENAME_MAX); + strncat(root, "/pl", YAP_FILENAME_MAX); } } - source = (isource ? isource : idef); + if (isource && isource[0]) + strcpy(source, isource); + else if (idef && idef[0]) + strcpy(source, idef); + else + source[0] = 0; } else #endif done = true; break; case 3: // use compilation variable YAPLIBDIR if (in_lib) { - source = (isource ? isource : idef); + if (isource && isource[0]) + strcpy(source, isource); + else if (idef && idef[0]) + strcpy(source, idef); + else + source[0] = 0; if (ftype == YAP_PL) { - root = YAP_SHAREDIR; + strcpy(root,YAP_SHAREDIR); } else if (ftype == YAP_BOOT_PL) { - root = malloc(YAP_FILENAME_MAX+1); strcpy(root, YAP_SHAREDIR); strcat(root,"/pl"); } else { - root = YAP_LIBDIR; + strcpy(root,YAP_LIBDIR); } } else done = true; @@ -1260,9 +1296,9 @@ const char *Yap_findFile(const char *isource, const char *idef, case 4: // WIN stuff: registry #if __WINDOWS if (in_lib) { - source = (ftype == YAP_PL || ftype == YAP_QLY ? "library" : "startup"); - source = Yap_RegistryGetString(source); - root = NULL; + const char *key = (ftype == YAP_PL || ftype == YAP_QLY ? "library" : "startup"); + strcpy( source, Yap_RegistryGetString(source) ); + root[0] = 0; } else #endif done = true; @@ -1278,44 +1314,50 @@ const char *Yap_findFile(const char *isource, const char *idef, const char *pt = Yap_FindExecutable(); if (pt) { - if (ftype == YAP_BOOT_PL) { + if (ftype == YAP_BOOT_PL) { #if __ANDROID__ - root = "../../../files/Yap/pl"; + strcpy(root, "../../../files/Yap/pl"); #else - root = "../../share/Yap/pl"; + root = "../../share/Yap/pl"; #endif - } else { - root = (ftype == YAP_SAVED_STATE || ftype == YAP_OBJ - ? "../../lib/Yap" - : "../../share/Yap"); - } - if (root == iroot) { - done = true; - continue; - } - if (!save_buffer) - save_buffer = getFileNameBuffer(); - if (Yap_findFile(source, NULL, root, save_buffer, access, ftype, + } else { + strcpy(root, (ftype == YAP_SAVED_STATE || ftype == YAP_OBJ + ? "../../lib/Yap" + : "../../share/Yap")); + } + if (strcmp(root, iroot) == 0) { + done = true; + continue; + } + if (!save_buffer) { + save_buffer = Malloc(YAP_FILENAME_MAX + 1); + + save_buffer[0] = 0; + } + if (Yap_findFile(source, NULL, root, save_buffer, access, ftype, expand_root, in_lib)) - root = save_buffer; + strcpy(root, save_buffer); else done = true; } else { done = true; } - source = (isource ? isource : idef); + if (isource && isource[0]) + strcpy(source, isource); + else if (idef && idef[0]) + strcpy(source, idef); + else + source[0] = 0; } break; case 6: // default, try current directory if (!isource && ftype == YAP_SAVED_STATE) - source = idef; - root = NULL; + strcpy(source, idef); + root[0] = 0; break; default: - if (save_buffer) - freeFileNameBuffer(save_buffer); - - return false; + pop_text_stack(lvl); + return NULL; } if (done) @@ -1324,16 +1366,19 @@ const char *Yap_findFile(const char *isource, const char *idef, // "root= %s %s ", root, source) ; } const char *work = PlExpandVars(source, root, result); - if (save_buffer) - freeFileNameBuffer(save_buffer); // expand names in case you have // to add a prefix if (!access || Yap_Exists(work)) { + work = pop_output_text_stack(lvl,work); return work; // done - } else if (abspath) - return NULL; + } else if (abspath) { + pop_text_stack(lvl); + return NULL; + } } + pop_text_stack(lvl); + return NULL; } @@ -1422,7 +1467,7 @@ static Int p_sh(USES_REGS1) { /* sh */ shell = (char *)getenv("SHELL"); if (shell == NULL) shell = "/bin/sh"; - if (system(shell) < 0) { + if (system(Yap_VFAlloc(shell)) < 0) { #if HAVE_STRERROR Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "%s in sh/0", strerror(errno)); @@ -1628,10 +1673,12 @@ static Int p_mv(USES_REGS1) { /* rename(+OldName,+NewName) */ } else if (!IsAtomTerm(t2)) { Yap_Error(TYPE_ERROR_ATOM, t2, "second argument to rename/2 not atom"); } else { - oldname = (RepAtom(AtomOfTerm(t1)))->StrOfAE; - newname = (RepAtom(AtomOfTerm(t2)))->StrOfAE; + oldname = Yap_VFAlloc((RepAtom(AtomOfTerm(t1)))->StrOfAE); + newname = Yap_VFAlloc((RepAtom(AtomOfTerm(t2)))->StrOfAE); if ((r = link(oldname, newname)) == 0 && (r = unlink(oldname)) != 0) unlink(newname); + free(oldname); + free(newname); if (r != 0) { #if HAVE_STRERROR Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, t2, "%s in rename(%s,%s)", diff --git a/os/writeterm.c b/os/writeterm.c index bc8697446..f61cd85bb 100644 --- a/os/writeterm.c +++ b/os/writeterm.c @@ -678,7 +678,7 @@ static Int term_to_string(USES_REGS1) { Term t2 = Deref(ARG2), rc = false, t1 = Deref(ARG1); const char *s; if (IsVarTerm(t2)) { - s = Yap_TermToString(ARG1,LOCAL_encoding, + s = Yap_TermToBuffer(ARG1, LOCAL_encoding, Quote_illegal_f | Handle_vars_f); if (!s || !MkStringTerm(s)) { Yap_Error(RESOURCE_ERROR_HEAP, t1, @@ -699,7 +699,7 @@ static Int term_to_atom(USES_REGS1) { Term t2 = Deref(ARG2), ctl, rc = false; Atom at; if (IsVarTerm(t2)) { - const char *s = Yap_TermToString(Deref(ARG1), LOCAL_encoding, + const char *s = Yap_TermToBuffer(Deref(ARG1), LOCAL_encoding, Quote_illegal_f | Handle_vars_f); if (!s || !(at = Yap_UTF8ToAtom((const unsigned char *)s))) { Yap_Error(RESOURCE_ERROR_HEAP, t2, diff --git a/os/yapio.h b/os/yapio.h index f7987c58e..8b23eea13 100644 --- a/os/yapio.h +++ b/os/yapio.h @@ -86,9 +86,9 @@ extern int Yap_PlGetWchar(void); extern int Yap_PlFGetchar(void); extern int Yap_GetCharForSIGINT(void); extern Int Yap_StreamToFileNo(Term); -extern int Yap_OpenStream(const char*, const char *); +extern int Yap_OpenStream(const char*, const char*); extern int Yap_FileStream(FILE*, char *, Term, int); -extern char *Yap_TermToString(Term t, encoding_t encoding, int flags); +extern char *Yap_TermToBuffer(Term t, encoding_t encoding, int flags); extern char *Yap_HandleToString(yhandle_t l, size_t sz, size_t *length, encoding_t *encoding, int flags); extern int Yap_GetFreeStreamD(void); @@ -103,7 +103,7 @@ extern int Yap_growheap_in_parser(tr_fr_ptr *, TokEntry **, VarEntry **); extern int Yap_growstack_in_parser(tr_fr_ptr *, TokEntry **, VarEntry **); extern int Yap_growtrail_in_parser(tr_fr_ptr *, TokEntry **, VarEntry **); -extern bool Yap_IsAbsolutePath(const char *p); +extern bool Yap_IsAbsolutePath(const char *p, bool); extern Atom Yap_TemporaryFile(const char *prefix, int *fd); extern const char *Yap_AbsoluteFile(const char *spec, char *obuf, bool expand); @@ -156,12 +156,46 @@ INLINE_ONLY inline EXTERN Term MkCharTerm(Int c) { return MkAtomTerm(Yap_ULookupAtom(cs)); } + + +INLINE_ONLY inline EXTERN char *Yap_VF(const char *path){ + char out[YAP_FILENAME_MAX+1], *p = (char *)path; + extern char virtual_cwd[]; + + if ( virtual_cwd[0] == 0 || Yap_IsAbsolutePath(path, false)) { + return p; + } + strcpy(out, virtual_cwd); + strcat(out, "/" ); + strcat(out, p); + strcpy(p, out); + return p; +} + + +INLINE_ONLY inline EXTERN char *Yap_VFAlloc(const char *path){ + char *out; + extern char virtual_cwd[]; + + out = (char *)malloc(YAP_FILENAME_MAX+1); + if ( virtual_cwd[0] == 0 || !Yap_IsAbsolutePath(path, false)) { + return (char *)path; + } + strcpy(out, virtual_cwd); + strcat(out, "/" ); + strcat(out, path); + return out; +} + /// UT when yap started extern uint64_t Yap_StartOfWTimes; extern bool Yap_HandleSIGINT(void); -extern bool Yap_set_stream_to_buf(StreamDesc *st, const char *buf, size_t nchars USES_REGS); +extern bool Yap_set_stream_to_buf(StreamDesc *st, const char *bufi, + size_t nchars USES_REGS); + + #endif diff --git a/packages/myddas/sqlite3/src/Android/jni/sqlite/JNIHelp.cpp b/packages/myddas/sqlite3/src/Android/jni/sqlite/JNIHelp.cpp index fd5884a80..54ac77abc 100644 --- a/packages/myddas/sqlite3/src/Android/jni/sqlite/JNIHelp.cpp +++ b/packages/myddas/sqlite3/src/Android/jni/sqlite/JNIHelp.cpp @@ -294,8 +294,8 @@ const char* jniStrError(int errnum, char* buf, size_t buflen) { // char *strerror_r(int errnum, char *buf, size_t n); return strerror_r(errnum, buf, buflen); #else - int rc = strerror_r(errnum, buf, buflen); - if (rc != 0) { + char *rc = strerror_r(errnum, buf, buflen); + if (rc != NULL) { // (POSIX only guarantees a value other than 0. The safest // way to implement this function is to use C++ and overload on the // type of strerror_r to accurately distinguish GNU from POSIX.) diff --git a/packages/swig/android/streamer.cpp b/packages/swig/android/streamer.cpp index 389271a81..cd7f6b6f4 100644 --- a/packages/swig/android/streamer.cpp +++ b/packages/swig/android/streamer.cpp @@ -5,6 +5,7 @@ #include "streamer.h" + static AndroidStreamer * streamerInstance = 0; void setStreamer(AndroidStreamer* streamer) { @@ -21,24 +22,29 @@ extern "C" { #include #include #include +#include +#include -VFS_t andstream; +extern void Java_pt_up_yap_lib_streamerJNI_swig_1module_1init__(void); +static VFS_t andstream; +void Java_pt_up_yap_lib_streamerJNI_swig_1module_1init__(void) { + streamerInstance = 0; +} ; static std::string buff0; -int n; static void * -and_open(const char *name, const char *io_mode) { - if (!strcmp(name,"//android/user_output") || - !strcmp(name,"//android/user_error")) +and_open(struct vfs *me, int sno, const char *name, const char *io_mode) { // we assume object is already open, so there is no need to open it. - return streamerInstance; - else - return NULL; + GLOBAL_Stream[sno].vfs_handle = streamerInstance; + GLOBAL_Stream[sno].vfs = me; + GLOBAL_Stream[sno].status = Append_Stream_f | Output_Stream_f; + buff0.clear(); + return streamerInstance; +} } - static bool and_close(int sno) { return true; @@ -46,10 +52,13 @@ and_close(int sno) { static int and_put(int sno, int ch) { -buff0[n++] = ch; - if (ch=='\n' || n == 128) { buff0[n] = '\0'; streamerInstance->display(buff0); n = 0; } +buff0 += ch; + if (ch=='\n' || buff0.length() == 128) { //buff0+= '\0'; + streamerInstance->display(buff0); + } return ch; } + static int and_get(int sno) { return EOF; @@ -62,9 +71,10 @@ static int64_t and_seek(int sno, int64_t where, int how) { static void and_flush(int sno) { -buff0[n] = '\0'; -streamerInstance->display(buff0); n = 0; -} +buff0 += '\0'; +streamerInstance->display(buff0); + + // // Created by vsc on 11-07-2017. @@ -73,13 +83,11 @@ streamerInstance->display(buff0); n = 0; } void -AndroidStreamer::bind() -{ - buff0 = * new std::string[256]; - n = 0; - andstream.name = "//android/user_error"; - andstream.vflags = VFS_CAN_WRITE|VFS_HAS_PREFIX; - andstream.prefix = "//android/"; +AndroidStreamer::bind() { + buff0 = *new std::string[256]; + andstream.name = "/android/user_error"; + andstream.vflags = VFS_CAN_WRITE | VFS_HAS_PREFIX; + andstream.prefix = "/android"; andstream.suffix = NULL; andstream.open = and_open; andstream.close = and_close; @@ -89,8 +97,6 @@ AndroidStreamer::bind() andstream.seek = and_seek; andstream.next = GLOBAL_VFS; GLOBAL_VFS = &andstream; - // NULL; - Yap_InitStdStream(StdOutStream, Output_Stream_f, NULL, &andstream); - Yap_InitStdStream(StdErrStream, Output_Stream_f, NULL, &andstream); + Yap_InitStdStream(StdOutStream, Output_Stream_f | Append_Stream_f, NULL, &andstream); + Yap_InitStdStream(StdErrStream, Output_Stream_f | Append_Stream_f, NULL, &andstream); } - diff --git a/packages/swig/android/streamer.i b/packages/swig/android/streamer.i index 6fc38629b..32f5e32a6 100644 --- a/packages/swig/android/streamer.i +++ b/packages/swig/android/streamer.i @@ -2,6 +2,7 @@ %module(directors="1") streamer %{ #include "streamer.h" + %} %include "std_string.i" @@ -10,7 +11,3 @@ %feature("director") AndroidStreamer; %include "streamer.h" - - - %init %{ - %}