--- /dev/null
+/* Jim - A small embeddable Tcl interpreter\r
+ * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>\r
+ * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>\r
+ *\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * A copy of the license is also included in the source distribution\r
+ * of Jim, as a TXT file name called LICENSE.\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ */\r
+\r
+#define __JIM_CORE__\r
+#define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */\r
+\r
+#ifdef __ECOS\r
+#include <pkgconf/jimtcl.h>\r
+#endif\r
+#ifndef JIM_ANSIC\r
+#define JIM_DYNLIB /* Dynamic library support for UNIX and WIN32 */\r
+#endif /* JIM_ANSIC */\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <stdarg.h>\r
+#include <ctype.h>\r
+#include <limits.h>\r
+#include <assert.h>\r
+#include <errno.h>\r
+#include <time.h>\r
+\r
+/* Include the platform dependent libraries for\r
+ * dynamic loading of libraries. */\r
+#ifdef JIM_DYNLIB\r
+#if defined(_WIN32) || defined(WIN32)\r
+#ifndef WIN32\r
+#define WIN32 1\r
+#endif\r
+#define STRICT\r
+#define WIN32_LEAN_AND_MEAN\r
+#include <windows.h>\r
+#if _MSC_VER >= 1000\r
+#pragma warning(disable:4146)\r
+#endif /* _MSC_VER */\r
+#else\r
+#include <dlfcn.h>\r
+#endif /* WIN32 */\r
+#endif /* JIM_DYNLIB */\r
+\r
+#ifdef __ECOS\r
+#include <cyg/jimtcl/jim.h>\r
+#else\r
+#include "jim.h"\r
+#endif\r
+\r
+#ifdef HAVE_BACKTRACE\r
+#include <execinfo.h>\r
+#endif\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Global variables\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* A shared empty string for the objects string representation.\r
+ * Jim_InvalidateStringRep knows about it and don't try to free. */\r
+static char *JimEmptyStringRep = (char*) "";\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Required prototypes of not exported functions\r
+ * ---------------------------------------------------------------------------*/\r
+static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf);\r
+static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags);\r
+static void JimRegisterCoreApi(Jim_Interp *interp);\r
+\r
+static Jim_HashTableType JimVariablesHashTableType;\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Utility functions\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/*\r
+ * Convert a string to a jim_wide INTEGER.\r
+ * This function originates from BSD.\r
+ *\r
+ * Ignores `locale' stuff. Assumes that the upper and lower case\r
+ * alphabets and digits are each contiguous.\r
+ */\r
+#ifdef HAVE_LONG_LONG\r
+#define JimIsAscii(c) (((c) & ~0x7f) == 0)\r
+static jim_wide JimStrtoll(const char *nptr, char **endptr, register int base)\r
+{\r
+ register const char *s;\r
+ register unsigned jim_wide acc;\r
+ register unsigned char c;\r
+ register unsigned jim_wide qbase, cutoff;\r
+ register int neg, any, cutlim;\r
+\r
+ /*\r
+ * Skip white space and pick up leading +/- sign if any.\r
+ * If base is 0, allow 0x for hex and 0 for octal, else\r
+ * assume decimal; if base is already 16, allow 0x.\r
+ */\r
+ s = nptr;\r
+ do {\r
+ c = *s++;\r
+ } while (isspace(c));\r
+ if (c == '-') {\r
+ neg = 1;\r
+ c = *s++;\r
+ } else {\r
+ neg = 0;\r
+ if (c == '+')\r
+ c = *s++;\r
+ }\r
+ if ((base == 0 || base == 16) &&\r
+ c == '0' && (*s == 'x' || *s == 'X')) {\r
+ c = s[1];\r
+ s += 2;\r
+ base = 16;\r
+ }\r
+ if (base == 0)\r
+ base = c == '0' ? 8 : 10;\r
+\r
+ /*\r
+ * Compute the cutoff value between legal numbers and illegal\r
+ * numbers. That is the largest legal value, divided by the\r
+ * base. An input number that is greater than this value, if\r
+ * followed by a legal input character, is too big. One that\r
+ * is equal to this value may be valid or not; the limit\r
+ * between valid and invalid numbers is then based on the last\r
+ * digit. For instance, if the range for quads is\r
+ * [-9223372036854775808..9223372036854775807] and the input base\r
+ * is 10, cutoff will be set to 922337203685477580 and cutlim to\r
+ * either 7 (neg==0) or 8 (neg==1), meaning that if we have\r
+ * accumulated a value > 922337203685477580, or equal but the\r
+ * next digit is > 7 (or 8), the number is too big, and we will\r
+ * return a range error.\r
+ *\r
+ * Set any if any `digits' consumed; make it negative to indicate\r
+ * overflow.\r
+ */\r
+ qbase = (unsigned)base;\r
+ cutoff = neg ? (unsigned jim_wide)-(LLONG_MIN + LLONG_MAX) + LLONG_MAX\r
+ : LLONG_MAX;\r
+ cutlim = (int)(cutoff % qbase);\r
+ cutoff /= qbase;\r
+ for (acc = 0, any = 0;; c = *s++) {\r
+ if (!JimIsAscii(c))\r
+ break;\r
+ if (isdigit(c))\r
+ c -= '0';\r
+ else if (isalpha(c))\r
+ c -= isupper(c) ? 'A' - 10 : 'a' - 10;\r
+ else\r
+ break;\r
+ if (c >= base)\r
+ break;\r
+ if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))\r
+ any = -1;\r
+ else {\r
+ any = 1;\r
+ acc *= qbase;\r
+ acc += c;\r
+ }\r
+ }\r
+ if (any < 0) {\r
+ acc = neg ? LLONG_MIN : LLONG_MAX;\r
+ errno = ERANGE;\r
+ } else if (neg)\r
+ acc = -acc;\r
+ if (endptr != 0)\r
+ *endptr = (char *)(any ? s - 1 : nptr);\r
+ return (acc);\r
+}\r
+#endif\r
+\r
+/* Glob-style pattern matching. */\r
+static int JimStringMatch(const char *pattern, int patternLen,\r
+ const char *string, int stringLen, int nocase)\r
+{\r
+ while(patternLen) {\r
+ switch(pattern[0]) {\r
+ case '*':\r
+ while (pattern[1] == '*') {\r
+ pattern++;\r
+ patternLen--;\r
+ }\r
+ if (patternLen == 1)\r
+ return 1; /* match */\r
+ while(stringLen) {\r
+ if (JimStringMatch(pattern+1, patternLen-1,\r
+ string, stringLen, nocase))\r
+ return 1; /* match */\r
+ string++;\r
+ stringLen--;\r
+ }\r
+ return 0; /* no match */\r
+ break;\r
+ case '?':\r
+ if (stringLen == 0)\r
+ return 0; /* no match */\r
+ string++;\r
+ stringLen--;\r
+ break;\r
+ case '[':\r
+ {\r
+ int not, match;\r
+\r
+ pattern++;\r
+ patternLen--;\r
+ not = pattern[0] == '^';\r
+ if (not) {\r
+ pattern++;\r
+ patternLen--;\r
+ }\r
+ match = 0;\r
+ while(1) {\r
+ if (pattern[0] == '\\') {\r
+ pattern++;\r
+ patternLen--;\r
+ if (pattern[0] == string[0])\r
+ match = 1;\r
+ } else if (pattern[0] == ']') {\r
+ break;\r
+ } else if (patternLen == 0) {\r
+ pattern--;\r
+ patternLen++;\r
+ break;\r
+ } else if (pattern[1] == '-' && patternLen >= 3) {\r
+ int start = pattern[0];\r
+ int end = pattern[2];\r
+ int c = string[0];\r
+ if (start > end) {\r
+ int t = start;\r
+ start = end;\r
+ end = t;\r
+ }\r
+ if (nocase) {\r
+ start = tolower(start);\r
+ end = tolower(end);\r
+ c = tolower(c);\r
+ }\r
+ pattern += 2;\r
+ patternLen -= 2;\r
+ if (c >= start && c <= end)\r
+ match = 1;\r
+ } else {\r
+ if (!nocase) {\r
+ if (pattern[0] == string[0])\r
+ match = 1;\r
+ } else {\r
+ if (tolower((int)pattern[0]) == tolower((int)string[0]))\r
+ match = 1;\r
+ }\r
+ }\r
+ pattern++;\r
+ patternLen--;\r
+ }\r
+ if (not)\r
+ match = !match;\r
+ if (!match)\r
+ return 0; /* no match */\r
+ string++;\r
+ stringLen--;\r
+ break;\r
+ }\r
+ case '\\':\r
+ if (patternLen >= 2) {\r
+ pattern++;\r
+ patternLen--;\r
+ }\r
+ /* fall through */\r
+ default:\r
+ if (!nocase) {\r
+ if (pattern[0] != string[0])\r
+ return 0; /* no match */\r
+ } else {\r
+ if (tolower((int)pattern[0]) != tolower((int)string[0]))\r
+ return 0; /* no match */\r
+ }\r
+ string++;\r
+ stringLen--;\r
+ break;\r
+ }\r
+ pattern++;\r
+ patternLen--;\r
+ if (stringLen == 0) {\r
+ while(*pattern == '*') {\r
+ pattern++;\r
+ patternLen--;\r
+ }\r
+ break;\r
+ }\r
+ }\r
+ if (patternLen == 0 && stringLen == 0)\r
+ return 1;\r
+ return 0;\r
+}\r
+\r
+int JimStringCompare(const char *s1, int l1, const char *s2, int l2,\r
+ int nocase)\r
+{\r
+ unsigned char *u1 = (unsigned char*) s1, *u2 = (unsigned char*) s2;\r
+\r
+ if (nocase == 0) {\r
+ while(l1 && l2) {\r
+ if (*u1 != *u2)\r
+ return (int)*u1-*u2;\r
+ u1++; u2++; l1--; l2--;\r
+ }\r
+ if (!l1 && !l2) return 0;\r
+ return l1-l2;\r
+ } else {\r
+ while(l1 && l2) {\r
+ if (tolower((int)*u1) != tolower((int)*u2))\r
+ return tolower((int)*u1)-tolower((int)*u2);\r
+ u1++; u2++; l1--; l2--;\r
+ }\r
+ if (!l1 && !l2) return 0;\r
+ return l1-l2;\r
+ }\r
+}\r
+\r
+/* Search 's1' inside 's2', starting to search from char 'index' of 's2'.\r
+ * The index of the first occurrence of s1 in s2 is returned. \r
+ * If s1 is not found inside s2, -1 is returned. */\r
+int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int index)\r
+{\r
+ int i;\r
+\r
+ if (!l1 || !l2 || l1 > l2) return -1;\r
+ if (index < 0) index = 0;\r
+ s2 += index;\r
+ for (i = index; i <= l2-l1; i++) {\r
+ if (memcmp(s2, s1, l1) == 0)\r
+ return i;\r
+ s2++;\r
+ }\r
+ return -1;\r
+}\r
+\r
+int Jim_WideToString(char *buf, jim_wide wideValue)\r
+{\r
+ const char *fmt = "%" JIM_WIDE_MODIFIER;\r
+ return sprintf(buf, fmt, wideValue);\r
+}\r
+\r
+int Jim_StringToWide(const char *str, jim_wide *widePtr, int base)\r
+{\r
+ char *endptr;\r
+\r
+#ifdef HAVE_LONG_LONG\r
+ *widePtr = JimStrtoll(str, &endptr, base);\r
+#else\r
+ *widePtr = strtol(str, &endptr, base);\r
+#endif\r
+ if (str[0] == '\0')\r
+ return JIM_ERR;\r
+ if (endptr[0] != '\0') {\r
+ while(*endptr) {\r
+ if (!isspace((int)*endptr))\r
+ return JIM_ERR;\r
+ endptr++;\r
+ }\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_StringToIndex(const char *str, int *intPtr)\r
+{\r
+ char *endptr;\r
+\r
+ *intPtr = strtol(str, &endptr, 10);\r
+ if (str[0] == '\0')\r
+ return JIM_ERR;\r
+ if (endptr[0] != '\0') {\r
+ while(*endptr) {\r
+ if (!isspace((int)*endptr))\r
+ return JIM_ERR;\r
+ endptr++;\r
+ }\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* The string representation of references has two features in order\r
+ * to make the GC faster. The first is that every reference starts\r
+ * with a non common character '~', in order to make the string matching\r
+ * fater. The second is that the reference string rep his 32 characters\r
+ * in length, this allows to avoid to check every object with a string\r
+ * repr < 32, and usually there are many of this objects. */\r
+\r
+#define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)\r
+\r
+static int JimFormatReference(char *buf, Jim_Reference *refPtr, jim_wide id)\r
+{\r
+ const char *fmt = "<reference.<%s>.%020" JIM_WIDE_MODIFIER ">";\r
+ sprintf(buf, fmt, refPtr->tag, id);\r
+ return JIM_REFERENCE_SPACE;\r
+}\r
+\r
+int Jim_DoubleToString(char *buf, double doubleValue)\r
+{\r
+ char *s;\r
+ int len;\r
+\r
+ len = sprintf(buf, "%.17g", doubleValue);\r
+ s = buf;\r
+ while(*s) {\r
+ if (*s == '.') return len;\r
+ s++;\r
+ }\r
+ /* Add a final ".0" if it's a number. But not\r
+ * for NaN or InF */\r
+ if (isdigit((int)buf[0])\r
+ || ((buf[0] == '-' || buf[0] == '+')\r
+ && isdigit((int)buf[1]))) {\r
+ s[0] = '.';\r
+ s[1] = '0';\r
+ s[2] = '\0';\r
+ return len+2;\r
+ }\r
+ return len;\r
+}\r
+\r
+int Jim_StringToDouble(const char *str, double *doublePtr)\r
+{\r
+ char *endptr;\r
+\r
+ *doublePtr = strtod(str, &endptr);\r
+ if (str[0] == '\0' || endptr[0] != '\0')\r
+ return JIM_ERR;\r
+ return JIM_OK;\r
+}\r
+\r
+static jim_wide JimPowWide(jim_wide b, jim_wide e)\r
+{\r
+ jim_wide i, res = 1;\r
+ if ((b==0 && e!=0) || (e<0)) return 0;\r
+ for(i=0; i<e; i++) {res *= b;}\r
+ return res;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Special functions\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* Note that 'interp' may be NULL if not available in the\r
+ * context of the panic. It's only useful to get the error\r
+ * file descriptor, it will default to stderr otherwise. */\r
+void Jim_Panic(Jim_Interp *interp, const char *fmt, ...)\r
+{\r
+ va_list ap;\r
+ FILE *fp = interp ? interp->stderr_ : stderr;\r
+\r
+ va_start(ap, fmt);\r
+ fprintf(fp, JIM_NL "JIM INTERPRETER PANIC: ");\r
+ vfprintf(fp, fmt, ap);\r
+ fprintf(fp, JIM_NL JIM_NL);\r
+ va_end(ap);\r
+#ifdef HAVE_BACKTRACE\r
+ {\r
+ void *array[40];\r
+ int size, i;\r
+ char **strings;\r
+\r
+ size = backtrace(array, 40);\r
+ strings = backtrace_symbols(array, size);\r
+ for (i = 0; i < size; i++)\r
+ fprintf(fp,"[backtrace] %s" JIM_NL, strings[i]);\r
+ fprintf(fp,"[backtrace] Include the above lines and the output" JIM_NL);\r
+ fprintf(fp,"[backtrace] of 'nm <executable>' in the bug report." JIM_NL);\r
+ }\r
+#endif\r
+ abort();\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Memory allocation\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* Macro used for memory debugging.\r
+ * In order for they to work you have to rename Jim_Alloc into _Jim_Alloc\r
+ * and similary for Jim_Realloc and Jim_Free */\r
+#if 0\r
+#define Jim_Alloc(s) (printf("%s %d: Jim_Alloc(%d)\n",__FILE__,__LINE__,s),_Jim_Alloc(s))\r
+#define Jim_Free(p) (printf("%s %d: Jim_Free(%p)\n",__FILE__,__LINE__,p),_Jim_Free(p))\r
+#define Jim_Realloc(p,s) (printf("%s %d: Jim_Realloc(%p,%d)\n",__FILE__,__LINE__,p,s),_Jim_Realloc(p,s))\r
+#endif\r
+\r
+void *Jim_Alloc(int size)\r
+{\r
+ /* We allocate zero length arrayes, etc. to use a single orthogonal codepath */\r
+ if (size==0)\r
+ size=1;\r
+ void *p = malloc(size);\r
+ if (p == NULL)\r
+ Jim_Panic(NULL,"malloc: Out of memory");\r
+ return p;\r
+}\r
+\r
+void Jim_Free(void *ptr) {\r
+ free(ptr);\r
+}\r
+\r
+void *Jim_Realloc(void *ptr, int size)\r
+{\r
+ /* We allocate zero length arrayes, etc. to use a single orthogonal codepath */\r
+ if (size==0)\r
+ size=1;\r
+ void *p = realloc(ptr, size);\r
+ if (p == NULL)\r
+ Jim_Panic(NULL,"realloc: Out of memory");\r
+ return p;\r
+}\r
+\r
+char *Jim_StrDup(const char *s)\r
+{\r
+ int l = strlen(s);\r
+ char *copy = Jim_Alloc(l+1);\r
+\r
+ memcpy(copy, s, l+1);\r
+ return copy;\r
+}\r
+\r
+char *Jim_StrDupLen(const char *s, int l)\r
+{\r
+ char *copy = Jim_Alloc(l+1);\r
+ \r
+ memcpy(copy, s, l+1);\r
+ copy[l] = 0; /* Just to be sure, original could be substring */\r
+ return copy;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Time related functions\r
+ * ---------------------------------------------------------------------------*/\r
+/* Returns microseconds of CPU used since start. */\r
+static jim_wide JimClock(void)\r
+{\r
+#if (defined WIN32) && !(defined JIM_ANSIC)\r
+ LARGE_INTEGER t, f;\r
+ QueryPerformanceFrequency(&f);\r
+ QueryPerformanceCounter(&t);\r
+ return (long)((t.QuadPart * 1000000) / f.QuadPart);\r
+#else /* !WIN32 */\r
+ clock_t clocks = clock();\r
+\r
+ return (long)(clocks*(1000000/CLOCKS_PER_SEC));\r
+#endif /* WIN32 */\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Hash Tables\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* -------------------------- private prototypes ---------------------------- */\r
+static int JimExpandHashTableIfNeeded(Jim_HashTable *ht);\r
+static unsigned int JimHashTableNextPower(unsigned int size);\r
+static int JimInsertHashEntry(Jim_HashTable *ht, const void *key);\r
+\r
+/* -------------------------- hash functions -------------------------------- */\r
+\r
+/* Thomas Wang's 32 bit Mix Function */\r
+unsigned int Jim_IntHashFunction(unsigned int key)\r
+{\r
+ key += ~(key << 15);\r
+ key ^= (key >> 10);\r
+ key += (key << 3);\r
+ key ^= (key >> 6);\r
+ key += ~(key << 11);\r
+ key ^= (key >> 16);\r
+ return key;\r
+}\r
+\r
+/* Identity hash function for integer keys */\r
+unsigned int Jim_IdentityHashFunction(unsigned int key)\r
+{\r
+ return key;\r
+}\r
+\r
+/* Generic hash function (we are using to multiply by 9 and add the byte\r
+ * as Tcl) */\r
+unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)\r
+{\r
+ unsigned int h = 0;\r
+ while(len--)\r
+ h += (h<<3)+*buf++;\r
+ return h;\r
+}\r
+\r
+/* ----------------------------- API implementation ------------------------- */\r
+/* reset an hashtable already initialized with ht_init().\r
+ * NOTE: This function should only called by ht_destroy(). */\r
+static void JimResetHashTable(Jim_HashTable *ht)\r
+{\r
+ ht->table = NULL;\r
+ ht->size = 0;\r
+ ht->sizemask = 0;\r
+ ht->used = 0;\r
+ ht->collisions = 0;\r
+}\r
+\r
+/* Initialize the hash table */\r
+int Jim_InitHashTable(Jim_HashTable *ht, Jim_HashTableType *type,\r
+ void *privDataPtr)\r
+{\r
+ JimResetHashTable(ht);\r
+ ht->type = type;\r
+ ht->privdata = privDataPtr;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Resize the table to the minimal size that contains all the elements,\r
+ * but with the invariant of a USER/BUCKETS ration near to <= 1 */\r
+int Jim_ResizeHashTable(Jim_HashTable *ht)\r
+{\r
+ int minimal = ht->used;\r
+\r
+ if (minimal < JIM_HT_INITIAL_SIZE)\r
+ minimal = JIM_HT_INITIAL_SIZE;\r
+ return Jim_ExpandHashTable(ht, minimal);\r
+}\r
+\r
+/* Expand or create the hashtable */\r
+int Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)\r
+{\r
+ Jim_HashTable n; /* the new hashtable */\r
+ unsigned int realsize = JimHashTableNextPower(size), i;\r
+\r
+ /* the size is invalid if it is smaller than the number of\r
+ * elements already inside the hashtable */\r
+ if (ht->used >= size)\r
+ return JIM_ERR;\r
+\r
+ Jim_InitHashTable(&n, ht->type, ht->privdata);\r
+ n.size = realsize;\r
+ n.sizemask = realsize-1;\r
+ n.table = Jim_Alloc(realsize*sizeof(Jim_HashEntry*));\r
+\r
+ /* Initialize all the pointers to NULL */\r
+ memset(n.table, 0, realsize*sizeof(Jim_HashEntry*));\r
+\r
+ /* Copy all the elements from the old to the new table:\r
+ * note that if the old hash table is empty ht->size is zero,\r
+ * so Jim_ExpandHashTable just creates an hash table. */\r
+ n.used = ht->used;\r
+ for (i = 0; i < ht->size && ht->used > 0; i++) {\r
+ Jim_HashEntry *he, *nextHe;\r
+\r
+ if (ht->table[i] == NULL) continue;\r
+ \r
+ /* For each hash entry on this slot... */\r
+ he = ht->table[i];\r
+ while(he) {\r
+ unsigned int h;\r
+\r
+ nextHe = he->next;\r
+ /* Get the new element index */\r
+ h = Jim_HashKey(ht, he->key) & n.sizemask;\r
+ he->next = n.table[h];\r
+ n.table[h] = he;\r
+ ht->used--;\r
+ /* Pass to the next element */\r
+ he = nextHe;\r
+ }\r
+ }\r
+ assert(ht->used == 0);\r
+ Jim_Free(ht->table);\r
+\r
+ /* Remap the new hashtable in the old */\r
+ *ht = n;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Add an element to the target hash table */\r
+int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)\r
+{\r
+ int index;\r
+ Jim_HashEntry *entry;\r
+\r
+ /* Get the index of the new element, or -1 if\r
+ * the element already exists. */\r
+ if ((index = JimInsertHashEntry(ht, key)) == -1)\r
+ return JIM_ERR;\r
+\r
+ /* Allocates the memory and stores key */\r
+ entry = Jim_Alloc(sizeof(*entry));\r
+ entry->next = ht->table[index];\r
+ ht->table[index] = entry;\r
+\r
+ /* Set the hash entry fields. */\r
+ Jim_SetHashKey(ht, entry, key);\r
+ Jim_SetHashVal(ht, entry, val);\r
+ ht->used++;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Add an element, discarding the old if the key already exists */\r
+int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)\r
+{\r
+ Jim_HashEntry *entry;\r
+\r
+ /* Try to add the element. If the key\r
+ * does not exists Jim_AddHashEntry will suceed. */\r
+ if (Jim_AddHashEntry(ht, key, val) == JIM_OK)\r
+ return JIM_OK;\r
+ /* It already exists, get the entry */\r
+ entry = Jim_FindHashEntry(ht, key);\r
+ /* Free the old value and set the new one */\r
+ Jim_FreeEntryVal(ht, entry);\r
+ Jim_SetHashVal(ht, entry, val);\r
+ return JIM_OK;\r
+}\r
+\r
+/* Search and remove an element */\r
+int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)\r
+{\r
+ unsigned int h;\r
+ Jim_HashEntry *he, *prevHe;\r
+\r
+ if (ht->size == 0)\r
+ return JIM_ERR;\r
+ h = Jim_HashKey(ht, key) & ht->sizemask;\r
+ he = ht->table[h];\r
+\r
+ prevHe = NULL;\r
+ while(he) {\r
+ if (Jim_CompareHashKeys(ht, key, he->key)) {\r
+ /* Unlink the element from the list */\r
+ if (prevHe)\r
+ prevHe->next = he->next;\r
+ else\r
+ ht->table[h] = he->next;\r
+ Jim_FreeEntryKey(ht, he);\r
+ Jim_FreeEntryVal(ht, he);\r
+ Jim_Free(he);\r
+ ht->used--;\r
+ return JIM_OK;\r
+ }\r
+ prevHe = he;\r
+ he = he->next;\r
+ }\r
+ return JIM_ERR; /* not found */\r
+}\r
+\r
+/* Destroy an entire hash table */\r
+int Jim_FreeHashTable(Jim_HashTable *ht)\r
+{\r
+ unsigned int i;\r
+\r
+ /* Free all the elements */\r
+ for (i = 0; i < ht->size && ht->used > 0; i++) {\r
+ Jim_HashEntry *he, *nextHe;\r
+\r
+ if ((he = ht->table[i]) == NULL) continue;\r
+ while(he) {\r
+ nextHe = he->next;\r
+ Jim_FreeEntryKey(ht, he);\r
+ Jim_FreeEntryVal(ht, he);\r
+ Jim_Free(he);\r
+ ht->used--;\r
+ he = nextHe;\r
+ }\r
+ }\r
+ /* Free the table and the allocated cache structure */\r
+ Jim_Free(ht->table);\r
+ /* Re-initialize the table */\r
+ JimResetHashTable(ht);\r
+ return JIM_OK; /* never fails */\r
+}\r
+\r
+Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)\r
+{\r
+ Jim_HashEntry *he;\r
+ unsigned int h;\r
+\r
+ if (ht->size == 0) return NULL;\r
+ h = Jim_HashKey(ht, key) & ht->sizemask;\r
+ he = ht->table[h];\r
+ while(he) {\r
+ if (Jim_CompareHashKeys(ht, key, he->key))\r
+ return he;\r
+ he = he->next;\r
+ }\r
+ return NULL;\r
+}\r
+\r
+Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)\r
+{\r
+ Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));\r
+\r
+ iter->ht = ht;\r
+ iter->index = -1;\r
+ iter->entry = NULL;\r
+ iter->nextEntry = NULL;\r
+ return iter;\r
+}\r
+\r
+Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)\r
+{\r
+ while (1) {\r
+ if (iter->entry == NULL) {\r
+ iter->index++;\r
+ if (iter->index >=\r
+ (signed)iter->ht->size) break;\r
+ iter->entry = iter->ht->table[iter->index];\r
+ } else {\r
+ iter->entry = iter->nextEntry;\r
+ }\r
+ if (iter->entry) {\r
+ /* We need to save the 'next' here, the iterator user\r
+ * may delete the entry we are returning. */\r
+ iter->nextEntry = iter->entry->next;\r
+ return iter->entry;\r
+ }\r
+ }\r
+ return NULL;\r
+}\r
+\r
+/* ------------------------- private functions ------------------------------ */\r
+\r
+/* Expand the hash table if needed */\r
+static int JimExpandHashTableIfNeeded(Jim_HashTable *ht)\r
+{\r
+ /* If the hash table is empty expand it to the intial size,\r
+ * if the table is "full" dobule its size. */\r
+ if (ht->size == 0)\r
+ return Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);\r
+ if (ht->size == ht->used)\r
+ return Jim_ExpandHashTable(ht, ht->size*2);\r
+ return JIM_OK;\r
+}\r
+\r
+/* Our hash table capability is a power of two */\r
+static unsigned int JimHashTableNextPower(unsigned int size)\r
+{\r
+ unsigned int i = JIM_HT_INITIAL_SIZE;\r
+\r
+ if (size >= 2147483648U)\r
+ return 2147483648U;\r
+ while(1) {\r
+ if (i >= size)\r
+ return i;\r
+ i *= 2;\r
+ }\r
+}\r
+\r
+/* Returns the index of a free slot that can be populated with\r
+ * an hash entry for the given 'key'.\r
+ * If the key already exists, -1 is returned. */\r
+static int JimInsertHashEntry(Jim_HashTable *ht, const void *key)\r
+{\r
+ unsigned int h;\r
+ Jim_HashEntry *he;\r
+\r
+ /* Expand the hashtable if needed */\r
+ if (JimExpandHashTableIfNeeded(ht) == JIM_ERR)\r
+ return -1;\r
+ /* Compute the key hash value */\r
+ h = Jim_HashKey(ht, key) & ht->sizemask;\r
+ /* Search if this slot does not already contain the given key */\r
+ he = ht->table[h];\r
+ while(he) {\r
+ if (Jim_CompareHashKeys(ht, key, he->key))\r
+ return -1;\r
+ he = he->next;\r
+ }\r
+ return h;\r
+}\r
+\r
+/* ----------------------- StringCopy Hash Table Type ------------------------*/\r
+\r
+static unsigned int JimStringCopyHTHashFunction(const void *key)\r
+{\r
+ return Jim_GenHashFunction(key, strlen(key));\r
+}\r
+\r
+static const void *JimStringCopyHTKeyDup(void *privdata, const void *key)\r
+{\r
+ int len = strlen(key);\r
+ char *copy = Jim_Alloc(len+1);\r
+ JIM_NOTUSED(privdata);\r
+\r
+ memcpy(copy, key, len);\r
+ copy[len] = '\0';\r
+ return copy;\r
+}\r
+\r
+static void *JimStringKeyValCopyHTValDup(void *privdata, const void *val)\r
+{\r
+ int len = strlen(val);\r
+ char *copy = Jim_Alloc(len+1);\r
+ JIM_NOTUSED(privdata);\r
+\r
+ memcpy(copy, val, len);\r
+ copy[len] = '\0';\r
+ return copy;\r
+}\r
+\r
+static int JimStringCopyHTKeyCompare(void *privdata, const void *key1,\r
+ const void *key2)\r
+{\r
+ JIM_NOTUSED(privdata);\r
+\r
+ return strcmp(key1, key2) == 0;\r
+}\r
+\r
+static void JimStringCopyHTKeyDestructor(void *privdata, const void *key)\r
+{\r
+ JIM_NOTUSED(privdata);\r
+\r
+ Jim_Free((void*)key); /* ATTENTION: const cast */\r
+}\r
+\r
+static void JimStringKeyValCopyHTValDestructor(void *privdata, void *val)\r
+{\r
+ JIM_NOTUSED(privdata);\r
+\r
+ Jim_Free((void*)val); /* ATTENTION: const cast */\r
+}\r
+\r
+static Jim_HashTableType JimStringCopyHashTableType = {\r
+ JimStringCopyHTHashFunction, /* hash function */\r
+ JimStringCopyHTKeyDup, /* key dup */\r
+ NULL, /* val dup */\r
+ JimStringCopyHTKeyCompare, /* key compare */\r
+ JimStringCopyHTKeyDestructor, /* key destructor */\r
+ NULL /* val destructor */\r
+};\r
+\r
+/* This is like StringCopy but does not auto-duplicate the key.\r
+ * It's used for intepreter's shared strings. */\r
+static Jim_HashTableType JimSharedStringsHashTableType = {\r
+ JimStringCopyHTHashFunction, /* hash function */\r
+ NULL, /* key dup */\r
+ NULL, /* val dup */\r
+ JimStringCopyHTKeyCompare, /* key compare */\r
+ JimStringCopyHTKeyDestructor, /* key destructor */\r
+ NULL /* val destructor */\r
+};\r
+\r
+/* This is like StringCopy but also automatically handle dynamic\r
+ * allocated C strings as values. */\r
+static Jim_HashTableType JimStringKeyValCopyHashTableType = {\r
+ JimStringCopyHTHashFunction, /* hash function */\r
+ JimStringCopyHTKeyDup, /* key dup */\r
+ JimStringKeyValCopyHTValDup, /* val dup */\r
+ JimStringCopyHTKeyCompare, /* key compare */\r
+ JimStringCopyHTKeyDestructor, /* key destructor */\r
+ JimStringKeyValCopyHTValDestructor, /* val destructor */\r
+};\r
+\r
+typedef struct AssocDataValue {\r
+ Jim_InterpDeleteProc *delProc;\r
+ void *data;\r
+} AssocDataValue;\r
+\r
+static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)\r
+{\r
+ AssocDataValue *assocPtr = (AssocDataValue *)data;\r
+ if (assocPtr->delProc != NULL)\r
+ assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);\r
+ Jim_Free(data);\r
+}\r
+\r
+static Jim_HashTableType JimAssocDataHashTableType = {\r
+ JimStringCopyHTHashFunction, /* hash function */\r
+ JimStringCopyHTKeyDup, /* key dup */\r
+ NULL, /* val dup */\r
+ JimStringCopyHTKeyCompare, /* key compare */\r
+ JimStringCopyHTKeyDestructor, /* key destructor */\r
+ JimAssocDataHashTableValueDestructor /* val destructor */\r
+};\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Stack - This is a simple generic stack implementation. It is used for\r
+ * example in the 'expr' expression compiler.\r
+ * ---------------------------------------------------------------------------*/\r
+void Jim_InitStack(Jim_Stack *stack)\r
+{\r
+ stack->len = 0;\r
+ stack->maxlen = 0;\r
+ stack->vector = NULL;\r
+}\r
+\r
+void Jim_FreeStack(Jim_Stack *stack)\r
+{\r
+ Jim_Free(stack->vector);\r
+}\r
+\r
+int Jim_StackLen(Jim_Stack *stack)\r
+{\r
+ return stack->len;\r
+}\r
+\r
+void Jim_StackPush(Jim_Stack *stack, void *element) {\r
+ int neededLen = stack->len+1;\r
+ if (neededLen > stack->maxlen) {\r
+ stack->maxlen = neededLen*2;\r
+ stack->vector = Jim_Realloc(stack->vector, sizeof(void*)*stack->maxlen);\r
+ }\r
+ stack->vector[stack->len] = element;\r
+ stack->len++;\r
+}\r
+\r
+void *Jim_StackPop(Jim_Stack *stack)\r
+{\r
+ if (stack->len == 0) return NULL;\r
+ stack->len--;\r
+ return stack->vector[stack->len];\r
+}\r
+\r
+void *Jim_StackPeek(Jim_Stack *stack)\r
+{\r
+ if (stack->len == 0) return NULL;\r
+ return stack->vector[stack->len-1];\r
+}\r
+\r
+void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr))\r
+{\r
+ int i;\r
+\r
+ for (i = 0; i < stack->len; i++)\r
+ freeFunc(stack->vector[i]);\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Parser\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* Token types */\r
+#define JIM_TT_NONE -1 /* No token returned */\r
+#define JIM_TT_STR 0 /* simple string */\r
+#define JIM_TT_ESC 1 /* string that needs escape chars conversion */\r
+#define JIM_TT_VAR 2 /* var substitution */\r
+#define JIM_TT_DICTSUGAR 3 /* Syntax sugar for [dict get], $foo(bar) */\r
+#define JIM_TT_CMD 4 /* command substitution */\r
+#define JIM_TT_SEP 5 /* word separator */\r
+#define JIM_TT_EOL 6 /* line separator */\r
+\r
+/* Additional token types needed for expressions */\r
+#define JIM_TT_SUBEXPR_START 7\r
+#define JIM_TT_SUBEXPR_END 8\r
+#define JIM_TT_EXPR_NUMBER 9\r
+#define JIM_TT_EXPR_OPERATOR 10\r
+\r
+/* Parser states */\r
+#define JIM_PS_DEF 0 /* Default state */\r
+#define JIM_PS_QUOTE 1 /* Inside "" */\r
+\r
+/* Parser context structure. The same context is used both to parse\r
+ * Tcl scripts and lists. */\r
+struct JimParserCtx {\r
+ const char *prg; /* Program text */\r
+ const char *p; /* Pointer to the point of the program we are parsing */\r
+ int len; /* Left length of 'prg' */\r
+ int linenr; /* Current line number */\r
+ const char *tstart;\r
+ const char *tend; /* Returned token is at tstart-tend in 'prg'. */\r
+ int tline; /* Line number of the returned token */\r
+ int tt; /* Token type */\r
+ int eof; /* Non zero if EOF condition is true. */\r
+ int state; /* Parser state */\r
+ int comment; /* Non zero if the next chars may be a comment. */\r
+};\r
+\r
+#define JimParserEof(c) ((c)->eof)\r
+#define JimParserTstart(c) ((c)->tstart)\r
+#define JimParserTend(c) ((c)->tend)\r
+#define JimParserTtype(c) ((c)->tt)\r
+#define JimParserTline(c) ((c)->tline)\r
+\r
+static int JimParseScript(struct JimParserCtx *pc);\r
+static int JimParseSep(struct JimParserCtx *pc);\r
+static int JimParseEol(struct JimParserCtx *pc);\r
+static int JimParseCmd(struct JimParserCtx *pc);\r
+static int JimParseVar(struct JimParserCtx *pc);\r
+static int JimParseBrace(struct JimParserCtx *pc);\r
+static int JimParseStr(struct JimParserCtx *pc);\r
+static int JimParseComment(struct JimParserCtx *pc);\r
+static char *JimParserGetToken(struct JimParserCtx *pc,\r
+ int *lenPtr, int *typePtr, int *linePtr);\r
+\r
+/* Initialize a parser context.\r
+ * 'prg' is a pointer to the program text, linenr is the line\r
+ * number of the first line contained in the program. */\r
+void JimParserInit(struct JimParserCtx *pc, const char *prg, \r
+ int len, int linenr)\r
+{\r
+ pc->prg = prg;\r
+ pc->p = prg;\r
+ pc->len = len;\r
+ pc->tstart = NULL;\r
+ pc->tend = NULL;\r
+ pc->tline = 0;\r
+ pc->tt = JIM_TT_NONE;\r
+ pc->eof = 0;\r
+ pc->state = JIM_PS_DEF;\r
+ pc->linenr = linenr;\r
+ pc->comment = 1;\r
+}\r
+\r
+int JimParseScript(struct JimParserCtx *pc)\r
+{\r
+ while(1) { /* the while is used to reiterate with continue if needed */\r
+ if (!pc->len) {\r
+ pc->tstart = pc->p;\r
+ pc->tend = pc->p-1;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_EOL;\r
+ pc->eof = 1;\r
+ return JIM_OK;\r
+ }\r
+ switch(*(pc->p)) {\r
+ case '\\':\r
+ if (*(pc->p+1) == '\n')\r
+ return JimParseSep(pc);\r
+ else {\r
+ pc->comment = 0;\r
+ return JimParseStr(pc);\r
+ }\r
+ break;\r
+ case ' ':\r
+ case '\t':\r
+ case '\r':\r
+ if (pc->state == JIM_PS_DEF)\r
+ return JimParseSep(pc);\r
+ else {\r
+ pc->comment = 0;\r
+ return JimParseStr(pc);\r
+ }\r
+ break;\r
+ case '\n':\r
+ case ';':\r
+ pc->comment = 1;\r
+ if (pc->state == JIM_PS_DEF)\r
+ return JimParseEol(pc);\r
+ else\r
+ return JimParseStr(pc);\r
+ break;\r
+ case '[':\r
+ pc->comment = 0;\r
+ return JimParseCmd(pc);\r
+ break;\r
+ case '$':\r
+ pc->comment = 0;\r
+ if (JimParseVar(pc) == JIM_ERR) {\r
+ pc->tstart = pc->tend = pc->p++; pc->len--;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_STR;\r
+ return JIM_OK;\r
+ } else\r
+ return JIM_OK;\r
+ break;\r
+ case '#':\r
+ if (pc->comment) {\r
+ JimParseComment(pc);\r
+ continue;\r
+ } else {\r
+ return JimParseStr(pc);\r
+ }\r
+ default:\r
+ pc->comment = 0;\r
+ return JimParseStr(pc);\r
+ break;\r
+ }\r
+ return JIM_OK;\r
+ }\r
+}\r
+\r
+int JimParseSep(struct JimParserCtx *pc)\r
+{\r
+ pc->tstart = pc->p;\r
+ pc->tline = pc->linenr;\r
+ while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' ||\r
+ (*pc->p == '\\' && *(pc->p+1) == '\n')) {\r
+ if (*pc->p == '\\') {\r
+ pc->p++; pc->len--;\r
+ pc->linenr++;\r
+ }\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_SEP;\r
+ return JIM_OK;\r
+}\r
+\r
+int JimParseEol(struct JimParserCtx *pc)\r
+{\r
+ pc->tstart = pc->p;\r
+ pc->tline = pc->linenr;\r
+ while (*pc->p == ' ' || *pc->p == '\n' ||\r
+ *pc->p == '\t' || *pc->p == '\r' || *pc->p == ';') {\r
+ if (*pc->p == '\n')\r
+ pc->linenr++;\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_EOL;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Todo. Don't stop if ']' appears inside {} or quoted.\r
+ * Also should handle the case of puts [string length "]"] */\r
+int JimParseCmd(struct JimParserCtx *pc)\r
+{\r
+ int level = 1;\r
+ int blevel = 0;\r
+\r
+ pc->tstart = ++pc->p; pc->len--;\r
+ pc->tline = pc->linenr;\r
+ while (1) {\r
+ if (pc->len == 0) {\r
+ break;\r
+ } else if (*pc->p == '[' && blevel == 0) {\r
+ level++;\r
+ } else if (*pc->p == ']' && blevel == 0) {\r
+ level--;\r
+ if (!level) break;\r
+ } else if (*pc->p == '\\') {\r
+ pc->p++; pc->len--;\r
+ } else if (*pc->p == '{') {\r
+ blevel++;\r
+ } else if (*pc->p == '}') {\r
+ if (blevel != 0)\r
+ blevel--;\r
+ } else if (*pc->p == '\n')\r
+ pc->linenr++;\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_CMD;\r
+ if (*pc->p == ']') {\r
+ pc->p++; pc->len--;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+int JimParseVar(struct JimParserCtx *pc)\r
+{\r
+ int brace = 0, stop = 0, ttype = JIM_TT_VAR;\r
+\r
+ pc->tstart = ++pc->p; pc->len--; /* skip the $ */\r
+ pc->tline = pc->linenr;\r
+ if (*pc->p == '{') {\r
+ pc->tstart = ++pc->p; pc->len--;\r
+ brace = 1;\r
+ }\r
+ if (brace) {\r
+ while (!stop) {\r
+ if (*pc->p == '}' || pc->len == 0) {\r
+ stop = 1;\r
+ if (pc->len == 0)\r
+ continue;\r
+ }\r
+ else if (*pc->p == '\n')\r
+ pc->linenr++;\r
+ pc->p++; pc->len--;\r
+ }\r
+ if (pc->len == 0)\r
+ pc->tend = pc->p-1;\r
+ else\r
+ pc->tend = pc->p-2;\r
+ } else {\r
+ while (!stop) {\r
+ if (!((*pc->p >= 'a' && *pc->p <= 'z') ||\r
+ (*pc->p >= 'A' && *pc->p <= 'Z') ||\r
+ (*pc->p >= '0' && *pc->p <= '9') || *pc->p == '_'))\r
+ stop = 1;\r
+ else {\r
+ pc->p++; pc->len--;\r
+ }\r
+ }\r
+ /* Parse [dict get] syntax sugar. */\r
+ if (*pc->p == '(') {\r
+ while (*pc->p != ')' && pc->len) {\r
+ pc->p++; pc->len--;\r
+ if (*pc->p == '\\' && pc->len >= 2) {\r
+ pc->p += 2; pc->len -= 2;\r
+ }\r
+ }\r
+ if (*pc->p != '\0') {\r
+ pc->p++; pc->len--;\r
+ }\r
+ ttype = JIM_TT_DICTSUGAR;\r
+ }\r
+ pc->tend = pc->p-1;\r
+ }\r
+ /* Check if we parsed just the '$' character.\r
+ * That's not a variable so an error is returned\r
+ * to tell the state machine to consider this '$' just\r
+ * a string. */\r
+ if (pc->tstart == pc->p) {\r
+ pc->p--; pc->len++;\r
+ return JIM_ERR;\r
+ }\r
+ pc->tt = ttype;\r
+ return JIM_OK;\r
+}\r
+\r
+int JimParseBrace(struct JimParserCtx *pc)\r
+{\r
+ int level = 1;\r
+\r
+ pc->tstart = ++pc->p; pc->len--;\r
+ pc->tline = pc->linenr;\r
+ while (1) {\r
+ if (*pc->p == '\\' && pc->len >= 2) {\r
+ pc->p++; pc->len--;\r
+ if (*pc->p == '\n')\r
+ pc->linenr++;\r
+ } else if (*pc->p == '{') {\r
+ level++;\r
+ } else if (pc->len == 0 || *pc->p == '}') {\r
+ level--;\r
+ if (pc->len == 0 || level == 0) {\r
+ pc->tend = pc->p-1;\r
+ if (pc->len != 0) {\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tt = JIM_TT_STR;\r
+ return JIM_OK;\r
+ }\r
+ } else if (*pc->p == '\n') {\r
+ pc->linenr++;\r
+ }\r
+ pc->p++; pc->len--;\r
+ }\r
+ return JIM_OK; /* unreached */\r
+}\r
+\r
+int JimParseStr(struct JimParserCtx *pc)\r
+{\r
+ int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||\r
+ pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR);\r
+ if (newword && *pc->p == '{') {\r
+ return JimParseBrace(pc);\r
+ } else if (newword && *pc->p == '"') {\r
+ pc->state = JIM_PS_QUOTE;\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tstart = pc->p;\r
+ pc->tline = pc->linenr;\r
+ while (1) {\r
+ if (pc->len == 0) {\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ return JIM_OK;\r
+ }\r
+ switch(*pc->p) {\r
+ case '\\':\r
+ if (pc->state == JIM_PS_DEF &&\r
+ *(pc->p+1) == '\n') {\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ return JIM_OK;\r
+ }\r
+ if (pc->len >= 2) {\r
+ pc->p++; pc->len--;\r
+ }\r
+ break;\r
+ case '$':\r
+ case '[':\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ return JIM_OK;\r
+ case ' ':\r
+ case '\t':\r
+ case '\n':\r
+ case '\r':\r
+ case ';':\r
+ if (pc->state == JIM_PS_DEF) {\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ return JIM_OK;\r
+ } else if (*pc->p == '\n') {\r
+ pc->linenr++;\r
+ }\r
+ break;\r
+ case '"':\r
+ if (pc->state == JIM_PS_QUOTE) {\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ pc->p++; pc->len--;\r
+ pc->state = JIM_PS_DEF;\r
+ return JIM_OK;\r
+ }\r
+ break;\r
+ }\r
+ pc->p++; pc->len--;\r
+ }\r
+ return JIM_OK; /* unreached */\r
+}\r
+\r
+int JimParseComment(struct JimParserCtx *pc)\r
+{\r
+ while (*pc->p) {\r
+ if (*pc->p == '\n') {\r
+ pc->linenr++;\r
+ if (*(pc->p-1) != '\\') {\r
+ pc->p++; pc->len--;\r
+ return JIM_OK;\r
+ }\r
+ }\r
+ pc->p++; pc->len--;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* xdigitval and odigitval are helper functions for JimParserGetToken() */\r
+static int xdigitval(int c)\r
+{\r
+ if (c >= '0' && c <= '9') return c-'0';\r
+ if (c >= 'a' && c <= 'f') return c-'a'+10;\r
+ if (c >= 'A' && c <= 'F') return c-'A'+10;\r
+ return -1;\r
+}\r
+\r
+static int odigitval(int c)\r
+{\r
+ if (c >= '0' && c <= '7') return c-'0';\r
+ return -1;\r
+}\r
+\r
+/* Perform Tcl escape substitution of 's', storing the result\r
+ * string into 'dest'. The escaped string is guaranteed to\r
+ * be the same length or shorted than the source string.\r
+ * Slen is the length of the string at 's', if it's -1 the string\r
+ * length will be calculated by the function.\r
+ *\r
+ * The function returns the length of the resulting string. */\r
+static int JimEscape(char *dest, const char *s, int slen)\r
+{\r
+ char *p = dest;\r
+ int i, len;\r
+ \r
+ if (slen == -1)\r
+ slen = strlen(s);\r
+\r
+ for (i = 0; i < slen; i++) {\r
+ switch(s[i]) {\r
+ case '\\':\r
+ switch(s[i+1]) {\r
+ case 'a': *p++ = 0x7; i++; break;\r
+ case 'b': *p++ = 0x8; i++; break;\r
+ case 'f': *p++ = 0xc; i++; break;\r
+ case 'n': *p++ = 0xa; i++; break;\r
+ case 'r': *p++ = 0xd; i++; break;\r
+ case 't': *p++ = 0x9; i++; break;\r
+ case 'v': *p++ = 0xb; i++; break;\r
+ case '\0': *p++ = '\\'; i++; break;\r
+ case '\n': *p++ = ' '; i++; break;\r
+ default:\r
+ if (s[i+1] == 'x') {\r
+ int val = 0;\r
+ int c = xdigitval(s[i+2]);\r
+ if (c == -1) {\r
+ *p++ = 'x';\r
+ i++;\r
+ break;\r
+ }\r
+ val = c;\r
+ c = xdigitval(s[i+3]);\r
+ if (c == -1) {\r
+ *p++ = val;\r
+ i += 2;\r
+ break;\r
+ }\r
+ val = (val*16)+c;\r
+ *p++ = val;\r
+ i += 3;\r
+ break;\r
+ } else if (s[i+1] >= '0' && s[i+1] <= '7')\r
+ {\r
+ int val = 0;\r
+ int c = odigitval(s[i+1]);\r
+ val = c;\r
+ c = odigitval(s[i+2]);\r
+ if (c == -1) {\r
+ *p++ = val;\r
+ i ++;\r
+ break;\r
+ }\r
+ val = (val*8)+c;\r
+ c = odigitval(s[i+3]);\r
+ if (c == -1) {\r
+ *p++ = val;\r
+ i += 2;\r
+ break;\r
+ }\r
+ val = (val*8)+c;\r
+ *p++ = val;\r
+ i += 3;\r
+ } else {\r
+ *p++ = s[i+1];\r
+ i++;\r
+ }\r
+ break;\r
+ }\r
+ break;\r
+ default:\r
+ *p++ = s[i];\r
+ break;\r
+ }\r
+ }\r
+ len = p-dest;\r
+ *p++ = '\0';\r
+ return len;\r
+}\r
+\r
+/* Returns a dynamically allocated copy of the current token in the\r
+ * parser context. The function perform conversion of escapes if\r
+ * the token is of type JIM_TT_ESC.\r
+ *\r
+ * Note that after the conversion, tokens that are grouped with\r
+ * braces in the source code, are always recognizable from the\r
+ * identical string obtained in a different way from the type.\r
+ *\r
+ * For exmple the string:\r
+ *\r
+ * {expand}$a\r
+ * \r
+ * will return as first token "expand", of type JIM_TT_STR\r
+ *\r
+ * While the string:\r
+ *\r
+ * expand$a\r
+ *\r
+ * will return as first token "expand", of type JIM_TT_ESC\r
+ */\r
+char *JimParserGetToken(struct JimParserCtx *pc,\r
+ int *lenPtr, int *typePtr, int *linePtr)\r
+{\r
+ const char *start, *end;\r
+ char *token;\r
+ int len;\r
+\r
+ start = JimParserTstart(pc);\r
+ end = JimParserTend(pc);\r
+ if (start > end) {\r
+ if (lenPtr) *lenPtr = 0;\r
+ if (typePtr) *typePtr = JimParserTtype(pc);\r
+ if (linePtr) *linePtr = JimParserTline(pc);\r
+ token = Jim_Alloc(1);\r
+ token[0] = '\0';\r
+ return token;\r
+ }\r
+ len = (end-start)+1;\r
+ token = Jim_Alloc(len+1);\r
+ if (JimParserTtype(pc) != JIM_TT_ESC) {\r
+ /* No escape conversion needed? Just copy it. */\r
+ memcpy(token, start, len);\r
+ token[len] = '\0';\r
+ } else {\r
+ /* Else convert the escape chars. */\r
+ len = JimEscape(token, start, len);\r
+ }\r
+ if (lenPtr) *lenPtr = len;\r
+ if (typePtr) *typePtr = JimParserTtype(pc);\r
+ if (linePtr) *linePtr = JimParserTline(pc);\r
+ return token;\r
+}\r
+\r
+/* The following functin is not really part of the parsing engine of Jim,\r
+ * but it somewhat related. Given an string and its length, it tries\r
+ * to guess if the script is complete or there are instead " " or { }\r
+ * open and not completed. This is useful for interactive shells\r
+ * implementation and for [info complete].\r
+ *\r
+ * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,\r
+ * '{' on scripts incomplete missing one or more '}' to be balanced.\r
+ * '"' on scripts incomplete missing a '"' char.\r
+ *\r
+ * If the script is complete, 1 is returned, otherwise 0. */\r
+int Jim_ScriptIsComplete(const char *s, int len, char *stateCharPtr)\r
+{\r
+ int level = 0;\r
+ int state = ' ';\r
+\r
+ while(len) {\r
+ switch (*s) {\r
+ case '\\':\r
+ if (len > 1)\r
+ s++;\r
+ break;\r
+ case '"':\r
+ if (state == ' ') {\r
+ state = '"';\r
+ } else if (state == '"') {\r
+ state = ' ';\r
+ }\r
+ break;\r
+ case '{':\r
+ if (state == '{') {\r
+ level++;\r
+ } else if (state == ' ') {\r
+ state = '{';\r
+ level++;\r
+ }\r
+ break;\r
+ case '}':\r
+ if (state == '{') {\r
+ level--;\r
+ if (level == 0)\r
+ state = ' ';\r
+ }\r
+ break;\r
+ }\r
+ s++;\r
+ len--;\r
+ }\r
+ if (stateCharPtr)\r
+ *stateCharPtr = state;\r
+ return state == ' ';\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Tcl Lists parsing\r
+ * ---------------------------------------------------------------------------*/\r
+static int JimParseListSep(struct JimParserCtx *pc);\r
+static int JimParseListStr(struct JimParserCtx *pc);\r
+\r
+int JimParseList(struct JimParserCtx *pc)\r
+{\r
+ if (pc->len == 0) {\r
+ pc->tstart = pc->tend = pc->p;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_EOL;\r
+ pc->eof = 1;\r
+ return JIM_OK;\r
+ }\r
+ switch(*pc->p) {\r
+ case ' ':\r
+ case '\n':\r
+ case '\t':\r
+ case '\r':\r
+ if (pc->state == JIM_PS_DEF)\r
+ return JimParseListSep(pc);\r
+ else\r
+ return JimParseListStr(pc);\r
+ break;\r
+ default:\r
+ return JimParseListStr(pc);\r
+ break;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+int JimParseListSep(struct JimParserCtx *pc)\r
+{\r
+ pc->tstart = pc->p;\r
+ pc->tline = pc->linenr;\r
+ while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == '\n')\r
+ {\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_SEP;\r
+ return JIM_OK;\r
+}\r
+\r
+int JimParseListStr(struct JimParserCtx *pc)\r
+{\r
+ int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||\r
+ pc->tt == JIM_TT_NONE);\r
+ if (newword && *pc->p == '{') {\r
+ return JimParseBrace(pc);\r
+ } else if (newword && *pc->p == '"') {\r
+ pc->state = JIM_PS_QUOTE;\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tstart = pc->p;\r
+ pc->tline = pc->linenr;\r
+ while (1) {\r
+ if (pc->len == 0) {\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ return JIM_OK;\r
+ }\r
+ switch(*pc->p) {\r
+ case '\\':\r
+ pc->p++; pc->len--;\r
+ break;\r
+ case ' ':\r
+ case '\t':\r
+ case '\n':\r
+ case '\r':\r
+ if (pc->state == JIM_PS_DEF) {\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ return JIM_OK;\r
+ } else if (*pc->p == '\n') {\r
+ pc->linenr++;\r
+ }\r
+ break;\r
+ case '"':\r
+ if (pc->state == JIM_PS_QUOTE) {\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ pc->p++; pc->len--;\r
+ pc->state = JIM_PS_DEF;\r
+ return JIM_OK;\r
+ }\r
+ break;\r
+ }\r
+ pc->p++; pc->len--;\r
+ }\r
+ return JIM_OK; /* unreached */\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Jim_Obj related functions\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* Return a new initialized object. */\r
+Jim_Obj *Jim_NewObj(Jim_Interp *interp)\r
+{\r
+ Jim_Obj *objPtr;\r
+\r
+ /* -- Check if there are objects in the free list -- */\r
+ if (interp->freeList != NULL) {\r
+ /* -- Unlink the object from the free list -- */\r
+ objPtr = interp->freeList;\r
+ interp->freeList = objPtr->nextObjPtr;\r
+ } else {\r
+ /* -- No ready to use objects: allocate a new one -- */\r
+ objPtr = Jim_Alloc(sizeof(*objPtr));\r
+ }\r
+\r
+ /* Object is returned with refCount of 0. Every\r
+ * kind of GC implemented should take care to don't try\r
+ * to scan objects with refCount == 0. */\r
+ objPtr->refCount = 0;\r
+ /* All the other fields are left not initialized to save time.\r
+ * The caller will probably want set they to the right\r
+ * value anyway. */\r
+\r
+ /* -- Put the object into the live list -- */\r
+ objPtr->prevObjPtr = NULL;\r
+ objPtr->nextObjPtr = interp->liveList;\r
+ if (interp->liveList)\r
+ interp->liveList->prevObjPtr = objPtr;\r
+ interp->liveList = objPtr;\r
+\r
+ return objPtr;\r
+}\r
+\r
+/* Free an object. Actually objects are never freed, but\r
+ * just moved to the free objects list, where they will be\r
+ * reused by Jim_NewObj(). */\r
+void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ /* Check if the object was already freed, panic. */\r
+ if (objPtr->refCount != 0) {\r
+ Jim_Panic(interp,"!!!Object %p freed with bad refcount %d", objPtr,\r
+ objPtr->refCount);\r
+ }\r
+ /* Free the internal representation */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ /* Free the string representation */\r
+ if (objPtr->bytes != NULL) {\r
+ if (objPtr->bytes != JimEmptyStringRep)\r
+ Jim_Free(objPtr->bytes);\r
+ }\r
+ /* Unlink the object from the live objects list */\r
+ if (objPtr->prevObjPtr)\r
+ objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;\r
+ if (objPtr->nextObjPtr)\r
+ objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;\r
+ if (interp->liveList == objPtr)\r
+ interp->liveList = objPtr->nextObjPtr;\r
+ /* Link the object into the free objects list */\r
+ objPtr->prevObjPtr = NULL;\r
+ objPtr->nextObjPtr = interp->freeList;\r
+ if (interp->freeList)\r
+ interp->freeList->prevObjPtr = objPtr;\r
+ interp->freeList = objPtr;\r
+ objPtr->refCount = -1;\r
+}\r
+\r
+/* Invalidate the string representation of an object. */\r
+void Jim_InvalidateStringRep(Jim_Obj *objPtr)\r
+{\r
+ if (objPtr->bytes != NULL) {\r
+ if (objPtr->bytes != JimEmptyStringRep)\r
+ Jim_Free(objPtr->bytes);\r
+ }\r
+ objPtr->bytes = NULL;\r
+}\r
+\r
+#define Jim_SetStringRep(o, b, l) \\r
+ do { (o)->bytes = b; (o)->length = l; } while (0)\r
+\r
+/* Set the initial string representation for an object.\r
+ * Does not try to free an old one. */\r
+void Jim_InitStringRep(Jim_Obj *objPtr, const char *bytes, int length)\r
+{\r
+ if (length == 0) {\r
+ objPtr->bytes = JimEmptyStringRep;\r
+ objPtr->length = 0;\r
+ } else {\r
+ objPtr->bytes = Jim_Alloc(length+1);\r
+ objPtr->length = length;\r
+ memcpy(objPtr->bytes, bytes, length);\r
+ objPtr->bytes[length] = '\0';\r
+ }\r
+}\r
+\r
+/* Duplicate an object. The returned object has refcount = 0. */\r
+Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ Jim_Obj *dupPtr;\r
+\r
+ dupPtr = Jim_NewObj(interp);\r
+ if (objPtr->bytes == NULL) {\r
+ /* Object does not have a valid string representation. */\r
+ dupPtr->bytes = NULL;\r
+ } else {\r
+ Jim_InitStringRep(dupPtr, objPtr->bytes, objPtr->length);\r
+ }\r
+ if (objPtr->typePtr != NULL) {\r
+ if (objPtr->typePtr->dupIntRepProc == NULL) {\r
+ dupPtr->internalRep = objPtr->internalRep;\r
+ } else {\r
+ objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);\r
+ }\r
+ dupPtr->typePtr = objPtr->typePtr;\r
+ } else {\r
+ dupPtr->typePtr = NULL;\r
+ }\r
+ return dupPtr;\r
+}\r
+\r
+/* Return the string representation for objPtr. If the object\r
+ * string representation is invalid, calls the method to create\r
+ * a new one starting from the internal representation of the object. */\r
+const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)\r
+{\r
+ if (objPtr->bytes == NULL) {\r
+ /* Invalid string repr. Generate it. */\r
+ if (objPtr->typePtr->updateStringProc == NULL) {\r
+ Jim_Panic(NULL,"UpdataStringProc called against '%s' type.",\r
+ objPtr->typePtr->name);\r
+ }\r
+ objPtr->typePtr->updateStringProc(objPtr);\r
+ }\r
+ if (lenPtr)\r
+ *lenPtr = objPtr->length;\r
+ return objPtr->bytes;\r
+}\r
+\r
+/* Just returns the length of the object's string rep */\r
+int Jim_Length(Jim_Obj *objPtr)\r
+{\r
+ int len;\r
+\r
+ Jim_GetString(objPtr, &len);\r
+ return len;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * String Object\r
+ * ---------------------------------------------------------------------------*/\r
+static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);\r
+static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType stringObjType = {\r
+ "string",\r
+ NULL,\r
+ DupStringInternalRep,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)\r
+{\r
+ JIM_NOTUSED(interp);\r
+\r
+ /* This is a bit subtle: the only caller of this function\r
+ * should be Jim_DuplicateObj(), that will copy the\r
+ * string representaion. After the copy, the duplicated\r
+ * object will not have more room in teh buffer than\r
+ * srcPtr->length bytes. So we just set it to length. */\r
+ dupPtr->internalRep.strValue.maxLength = srcPtr->length;\r
+}\r
+\r
+int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ /* Get a fresh string representation. */\r
+ (void) Jim_GetString(objPtr, NULL);\r
+ /* Free any other internal representation. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ /* Set it as string, i.e. just set the maxLength field. */\r
+ objPtr->typePtr = &stringObjType;\r
+ objPtr->internalRep.strValue.maxLength = objPtr->length;\r
+ return JIM_OK;\r
+}\r
+\r
+Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)\r
+{\r
+ Jim_Obj *objPtr = Jim_NewObj(interp);\r
+\r
+ if (len == -1)\r
+ len = strlen(s);\r
+ /* Alloc/Set the string rep. */\r
+ if (len == 0) {\r
+ objPtr->bytes = JimEmptyStringRep;\r
+ objPtr->length = 0;\r
+ } else {\r
+ objPtr->bytes = Jim_Alloc(len+1);\r
+ objPtr->length = len;\r
+ memcpy(objPtr->bytes, s, len);\r
+ objPtr->bytes[len] = '\0';\r
+ }\r
+\r
+ /* No typePtr field for the vanilla string object. */\r
+ objPtr->typePtr = NULL;\r
+ return objPtr;\r
+}\r
+\r
+/* This version does not try to duplicate the 's' pointer, but\r
+ * use it directly. */\r
+Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)\r
+{\r
+ Jim_Obj *objPtr = Jim_NewObj(interp);\r
+\r
+ if (len == -1)\r
+ len = strlen(s);\r
+ Jim_SetStringRep(objPtr, s, len);\r
+ objPtr->typePtr = NULL;\r
+ return objPtr;\r
+}\r
+\r
+/* Low-level string append. Use it only against objects\r
+ * of type "string". */\r
+void StringAppendString(Jim_Obj *objPtr, const char *str, int len)\r
+{\r
+ int needlen;\r
+\r
+ if (len == -1)\r
+ len = strlen(str);\r
+ needlen = objPtr->length + len;\r
+ if (objPtr->internalRep.strValue.maxLength < needlen ||\r
+ objPtr->internalRep.strValue.maxLength == 0) {\r
+ if (objPtr->bytes == JimEmptyStringRep) {\r
+ objPtr->bytes = Jim_Alloc((needlen*2)+1);\r
+ } else {\r
+ objPtr->bytes = Jim_Realloc(objPtr->bytes, (needlen*2)+1);\r
+ }\r
+ objPtr->internalRep.strValue.maxLength = needlen*2;\r
+ }\r
+ memcpy(objPtr->bytes + objPtr->length, str, len);\r
+ objPtr->bytes[objPtr->length+len] = '\0';\r
+ objPtr->length += len;\r
+}\r
+\r
+/* Low-level wrapper to append an object. */\r
+void StringAppendObj(Jim_Obj *objPtr, Jim_Obj *appendObjPtr)\r
+{\r
+ int len;\r
+ const char *str;\r
+\r
+ str = Jim_GetString(appendObjPtr, &len);\r
+ StringAppendString(objPtr, str, len);\r
+}\r
+\r
+/* Higher level API to append strings to objects. */\r
+void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str,\r
+ int len)\r
+{\r
+ if (Jim_IsShared(objPtr))\r
+ Jim_Panic(interp,"Jim_AppendString called with shared object");\r
+ if (objPtr->typePtr != &stringObjType)\r
+ SetStringFromAny(interp, objPtr);\r
+ StringAppendString(objPtr, str, len);\r
+}\r
+\r
+void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ Jim_Obj *appendObjPtr)\r
+{\r
+ int len;\r
+ const char *str;\r
+\r
+ str = Jim_GetString(appendObjPtr, &len);\r
+ Jim_AppendString(interp, objPtr, str, len);\r
+}\r
+\r
+void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)\r
+{\r
+ va_list ap;\r
+\r
+ if (objPtr->typePtr != &stringObjType)\r
+ SetStringFromAny(interp, objPtr);\r
+ va_start(ap, objPtr);\r
+ while (1) {\r
+ char *s = va_arg(ap, char*);\r
+\r
+ if (s == NULL) break;\r
+ Jim_AppendString(interp, objPtr, s, -1);\r
+ }\r
+ va_end(ap);\r
+}\r
+\r
+int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr, int nocase)\r
+{\r
+ const char *aStr, *bStr;\r
+ int aLen, bLen, i;\r
+\r
+ if (aObjPtr == bObjPtr) return 1;\r
+ aStr = Jim_GetString(aObjPtr, &aLen);\r
+ bStr = Jim_GetString(bObjPtr, &bLen);\r
+ if (aLen != bLen) return 0;\r
+ if (nocase == 0)\r
+ return memcmp(aStr, bStr, aLen) == 0;\r
+ for (i = 0; i < aLen; i++) {\r
+ if (tolower((int)aStr[i]) != tolower((int)bStr[i]))\r
+ return 0;\r
+ }\r
+ return 1;\r
+}\r
+\r
+int Jim_StringMatchObj(Jim_Obj *patternObjPtr, Jim_Obj *objPtr,\r
+ int nocase)\r
+{\r
+ const char *pattern, *string;\r
+ int patternLen, stringLen;\r
+\r
+ pattern = Jim_GetString(patternObjPtr, &patternLen);\r
+ string = Jim_GetString(objPtr, &stringLen);\r
+ return JimStringMatch(pattern, patternLen, string, stringLen, nocase);\r
+}\r
+\r
+int Jim_StringCompareObj(Jim_Obj *firstObjPtr,\r
+ Jim_Obj *secondObjPtr, int nocase)\r
+{\r
+ const char *s1, *s2;\r
+ int l1, l2;\r
+\r
+ s1 = Jim_GetString(firstObjPtr, &l1);\r
+ s2 = Jim_GetString(secondObjPtr, &l2);\r
+ return JimStringCompare(s1, l1, s2, l2, nocase);\r
+}\r
+\r
+/* Convert a range, as returned by Jim_GetRange(), into\r
+ * an absolute index into an object of the specified length.\r
+ * This function may return negative values, or values\r
+ * bigger or equal to the length of the list if the index\r
+ * is out of range. */\r
+static int JimRelToAbsIndex(int len, int index)\r
+{\r
+ if (index < 0)\r
+ return len + index;\r
+ return index;\r
+}\r
+\r
+/* Convert a pair of index as normalize by JimRelToAbsIndex(),\r
+ * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable\r
+ * for implementation of commands like [string range] and [lrange].\r
+ *\r
+ * The resulting range is guaranteed to address valid elements of\r
+ * the structure. */\r
+static void JimRelToAbsRange(int len, int first, int last,\r
+ int *firstPtr, int *lastPtr, int *rangeLenPtr)\r
+{\r
+ int rangeLen;\r
+\r
+ if (first > last) {\r
+ rangeLen = 0;\r
+ } else {\r
+ rangeLen = last-first+1;\r
+ if (rangeLen) {\r
+ if (first < 0) {\r
+ rangeLen += first;\r
+ first = 0;\r
+ }\r
+ if (last >= len) {\r
+ rangeLen -= (last-(len-1));\r
+ last = len-1;\r
+ }\r
+ }\r
+ }\r
+ if (rangeLen < 0) rangeLen = 0;\r
+\r
+ *firstPtr = first;\r
+ *lastPtr = last;\r
+ *rangeLenPtr = rangeLen;\r
+}\r
+\r
+Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,\r
+ Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)\r
+{\r
+ int first, last;\r
+ const char *str;\r
+ int len, rangeLen;\r
+\r
+ if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||\r
+ Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)\r
+ return NULL;\r
+ str = Jim_GetString(strObjPtr, &len);\r
+ first = JimRelToAbsIndex(len, first);\r
+ last = JimRelToAbsIndex(len, last);\r
+ JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);\r
+ return Jim_NewStringObj(interp, str+first, rangeLen);\r
+}\r
+\r
+static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)\r
+{\r
+ char *buf = Jim_Alloc(strObjPtr->length+1);\r
+ int i;\r
+\r
+ memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);\r
+ for (i = 0; i < strObjPtr->length; i++)\r
+ buf[i] = tolower(buf[i]);\r
+ return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);\r
+}\r
+\r
+static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)\r
+{\r
+ char *buf = Jim_Alloc(strObjPtr->length+1);\r
+ int i;\r
+\r
+ memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);\r
+ for (i = 0; i < strObjPtr->length; i++)\r
+ buf[i] = toupper(buf[i]);\r
+ return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);\r
+}\r
+\r
+/* This is the core of the [format] command.\r
+ * TODO: Export it, make it real... for now only %s and %%\r
+ * specifiers supported. */\r
+Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr,\r
+ int objc, Jim_Obj *const *objv)\r
+{\r
+ const char *fmt;\r
+ int fmtLen;\r
+ Jim_Obj *resObjPtr;\r
+\r
+ fmt = Jim_GetString(fmtObjPtr, &fmtLen);\r
+ resObjPtr = Jim_NewStringObj(interp, "", 0);\r
+ while (fmtLen) {\r
+ const char *p = fmt;\r
+ char spec[2], c;\r
+ jim_wide wideValue;\r
+\r
+ while (*fmt != '%' && fmtLen) {\r
+ fmt++; fmtLen--;\r
+ }\r
+ Jim_AppendString(interp, resObjPtr, p, fmt-p);\r
+ if (fmtLen == 0)\r
+ break;\r
+ fmt++; fmtLen--; /* skip '%' */\r
+ if (*fmt != '%') {\r
+ if (objc == 0) {\r
+ Jim_FreeNewObj(interp, resObjPtr);\r
+ Jim_SetResultString(interp,\r
+ "not enough arguments for all format specifiers", -1);\r
+ return NULL;\r
+ } else {\r
+ objc--;\r
+ }\r
+ }\r
+ switch(*fmt) {\r
+ case 's':\r
+ Jim_AppendObj(interp, resObjPtr, objv[0]);\r
+ objv++;\r
+ break;\r
+ case 'c':\r
+ if (Jim_GetWide(interp, objv[0], &wideValue) == JIM_ERR) {\r
+ Jim_FreeNewObj(interp, resObjPtr);\r
+ return NULL;\r
+ }\r
+ c = (char) wideValue;\r
+ Jim_AppendString(interp, resObjPtr, &c, 1);\r
+ break;\r
+ case 'd':\r
+ if (Jim_GetWide(interp, objv[0], &wideValue) == JIM_ERR) {\r
+ Jim_FreeNewObj(interp, resObjPtr);\r
+ return NULL;\r
+ }\r
+ Jim_AppendObj(interp, resObjPtr, objv[0]);\r
+ break;\r
+ case '%':\r
+ Jim_AppendString(interp, resObjPtr, "%" , 1);\r
+ break;\r
+ default:\r
+ spec[0] = *fmt; spec[1] = '\0';\r
+ Jim_FreeNewObj(interp, resObjPtr);\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad field specifier \"", spec, "\"", NULL);\r
+ return NULL;\r
+ }\r
+ fmt++;\r
+ fmtLen--;\r
+ }\r
+ return resObjPtr;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Compared String Object\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* This is strange object that allows to compare a C literal string\r
+ * with a Jim object in very short time if the same comparison is done\r
+ * multiple times. For example every time the [if] command is executed,\r
+ * Jim has to check if a given argument is "else". This comparions if\r
+ * the code has no errors are true most of the times, so we can cache\r
+ * inside the object the pointer of the string of the last matching\r
+ * comparison. Because most C compilers perform literal sharing,\r
+ * so that: char *x = "foo", char *y = "foo", will lead to x == y,\r
+ * this works pretty well even if comparisons are at different places\r
+ * inside the C code. */\r
+\r
+static Jim_ObjType comparedStringObjType = {\r
+ "compared-string",\r
+ NULL,\r
+ NULL,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+/* The only way this object is exposed to the API is via the following\r
+ * function. Returns true if the string and the object string repr.\r
+ * are the same, otherwise zero is returned.\r
+ *\r
+ * Note: this isn't binary safe, but it hardly needs to be.*/\r
+int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ const char *str)\r
+{\r
+ if (objPtr->typePtr == &comparedStringObjType &&\r
+ objPtr->internalRep.ptr == str)\r
+ return 1;\r
+ else {\r
+ const char *objStr = Jim_GetString(objPtr, NULL);\r
+ if (strcmp(str, objStr) != 0) return 0;\r
+ if (objPtr->typePtr != &comparedStringObjType) {\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &comparedStringObjType;\r
+ }\r
+ objPtr->internalRep.ptr = (char*)str; /*ATTENTION: const cast */\r
+ return 1;\r
+ }\r
+}\r
+\r
+int qsortCompareStringPointers(const void *a, const void *b)\r
+{\r
+ char * const *sa = (char * const *)a;\r
+ char * const *sb = (char * const *)b;\r
+ return strcmp(*sa, *sb);\r
+}\r
+\r
+int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ const char **tablePtr, int *indexPtr, const char *name, int flags)\r
+{\r
+ const char **entryPtr = NULL;\r
+ char **tablePtrSorted;\r
+ int i, count = 0;\r
+\r
+ *indexPtr = -1;\r
+ for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {\r
+ if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {\r
+ *indexPtr = i;\r
+ return JIM_OK;\r
+ }\r
+ count++; /* If nothing matches, this will reach the len of tablePtr */\r
+ }\r
+ if (flags & JIM_ERRMSG) {\r
+ if (name == NULL)\r
+ name = "option";\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad ", name, " \"", Jim_GetString(objPtr, NULL), "\": must be one of ",\r
+ NULL);\r
+ tablePtrSorted = Jim_Alloc(sizeof(char*)*count);\r
+ memcpy(tablePtrSorted, tablePtr, sizeof(char*)*count);\r
+ qsort(tablePtrSorted, count, sizeof(char*), qsortCompareStringPointers);\r
+ for (i = 0; i < count; i++) {\r
+ if (i+1 == count && count > 1)\r
+ Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);\r
+ Jim_AppendString(interp, Jim_GetResult(interp),\r
+ tablePtrSorted[i], -1);\r
+ if (i+1 != count)\r
+ Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);\r
+ }\r
+ Jim_Free(tablePtrSorted);\r
+ }\r
+ return JIM_ERR;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Source Object\r
+ *\r
+ * This object is just a string from the language point of view, but\r
+ * in the internal representation it contains the filename and line number\r
+ * where this given token was read. This information is used by\r
+ * Jim_EvalObj() if the object passed happens to be of type "source".\r
+ *\r
+ * This allows to propagate the information about line numbers and file\r
+ * names and give error messages with absolute line numbers.\r
+ *\r
+ * Note that this object uses shared strings for filenames, and the\r
+ * pointer to the filename together with the line number is taken into\r
+ * the space for the "inline" internal represenation of the Jim_Object,\r
+ * so there is almost memory zero-overhead.\r
+ *\r
+ * Also the object will be converted to something else if the given\r
+ * token it represents in the source file is not something to be\r
+ * evaluated (not a script), and will be specialized in some other way,\r
+ * so the time overhead is alzo null.\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);\r
+static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);\r
+\r
+static Jim_ObjType sourceObjType = {\r
+ "source",\r
+ FreeSourceInternalRep,\r
+ DupSourceInternalRep,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ Jim_ReleaseSharedString(interp,\r
+ objPtr->internalRep.sourceValue.fileName);\r
+}\r
+\r
+void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)\r
+{\r
+ dupPtr->internalRep.sourceValue.fileName =\r
+ Jim_GetSharedString(interp,\r
+ srcPtr->internalRep.sourceValue.fileName);\r
+ dupPtr->internalRep.sourceValue.lineNumber =\r
+ dupPtr->internalRep.sourceValue.lineNumber;\r
+ dupPtr->typePtr = &sourceObjType;\r
+}\r
+\r
+static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ const char *fileName, int lineNumber)\r
+{\r
+ if (Jim_IsShared(objPtr))\r
+ Jim_Panic(interp,"JimSetSourceInfo called with shared object");\r
+ if (objPtr->typePtr != NULL)\r
+ Jim_Panic(interp,"JimSetSourceInfo called with typePtr != NULL");\r
+ objPtr->internalRep.sourceValue.fileName =\r
+ Jim_GetSharedString(interp, fileName);\r
+ objPtr->internalRep.sourceValue.lineNumber = lineNumber;\r
+ objPtr->typePtr = &sourceObjType;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Script Object\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+#define JIM_CMDSTRUCT_EXPAND -1\r
+\r
+static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);\r
+static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);\r
+static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType scriptObjType = {\r
+ "script",\r
+ FreeScriptInternalRep,\r
+ DupScriptInternalRep,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+/* The ScriptToken structure represents every token into a scriptObj.\r
+ * Every token contains an associated Jim_Obj that can be specialized\r
+ * by commands operating on it. */\r
+typedef struct ScriptToken {\r
+ int type;\r
+ Jim_Obj *objPtr;\r
+ int linenr;\r
+} ScriptToken;\r
+\r
+/* This is the script object internal representation. An array of\r
+ * ScriptToken structures, with an associated command structure array.\r
+ * The command structure is a pre-computed representation of the\r
+ * command length and arguments structure as a simple liner array\r
+ * of integers.\r
+ * \r
+ * For example the script:\r
+ *\r
+ * puts hello\r
+ * set $i $x$y [foo]BAR\r
+ *\r
+ * will produce a ScriptObj with the following Tokens:\r
+ *\r
+ * ESC puts\r
+ * SEP\r
+ * ESC hello\r
+ * EOL\r
+ * ESC set\r
+ * EOL\r
+ * VAR i\r
+ * SEP\r
+ * VAR x\r
+ * VAR y\r
+ * SEP\r
+ * CMD foo\r
+ * ESC BAR\r
+ * EOL\r
+ *\r
+ * This is a description of the tokens, separators, and of lines.\r
+ * The command structure instead represents the number of arguments\r
+ * of every command, followed by the tokens of which every argument\r
+ * is composed. So for the example script, the cmdstruct array will\r
+ * contain:\r
+ *\r
+ * 2 1 1 4 1 1 2 2\r
+ *\r
+ * Because "puts hello" has two args (2), composed of single tokens (1 1)\r
+ * While "set $i $x$y [foo]BAR" has four (4) args, the first two\r
+ * composed of single tokens (1 1) and the last two of double tokens\r
+ * (2 2).\r
+ *\r
+ * The precomputation of the command structure makes Jim_Eval() faster,\r
+ * and simpler because there aren't dynamic lengths / allocations.\r
+ *\r
+ * -- {expand} handling --\r
+ *\r
+ * Expand is handled in a special way. When a command\r
+ * contains at least an argument with the {expand} prefix,\r
+ * the command structure presents a -1 before the integer\r
+ * describing the number of arguments. This is used in order\r
+ * to send the command exection to a different path in case\r
+ * of {expand} and guarantee a fast path for the more common\r
+ * case. Also, the integers describing the number of tokens\r
+ * are expressed with negative sign, to allow for fast check\r
+ * of what's an {expand}-prefixed argument and what not.\r
+ *\r
+ * For example the command:\r
+ *\r
+ * list {expand}{1 2}\r
+ *\r
+ * Will produce the following cmdstruct array:\r
+ *\r
+ * -1 2 1 -2\r
+ *\r
+ * -- the substFlags field of the structure --\r
+ *\r
+ * The scriptObj structure is used to represent both "script" objects\r
+ * and "subst" objects. In the second case, the cmdStruct related\r
+ * fields are not used at all, but there is an additional field used\r
+ * that is 'substFlags': this represents the flags used to turn\r
+ * the string into the intenral representation used to perform the\r
+ * substitution. If this flags are not what the application requires\r
+ * the scriptObj is created again. For example the script:\r
+ *\r
+ * subst -nocommands $string\r
+ * subst -novariables $string\r
+ *\r
+ * Will recreate the internal representation of the $string object\r
+ * two times.\r
+ */\r
+typedef struct ScriptObj {\r
+ int len; /* Length as number of tokens. */\r
+ int commands; /* number of top-level commands in script. */\r
+ ScriptToken *token; /* Tokens array. */\r
+ int *cmdStruct; /* commands structure */\r
+ int csLen; /* length of the cmdStruct array. */\r
+ int substFlags; /* flags used for the compilation of "subst" objects */\r
+ int inUse; /* Used to share a ScriptObj. Currently\r
+ only used by Jim_EvalObj() as protection against\r
+ shimmering of the currently evaluated object. */\r
+ char *fileName;\r
+} ScriptObj;\r
+\r
+void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ int i;\r
+ struct ScriptObj *script = (void*) objPtr->internalRep.ptr;\r
+\r
+ script->inUse--;\r
+ if (script->inUse != 0) return;\r
+ for (i = 0; i < script->len; i++) {\r
+ if (script->token[i].objPtr != NULL)\r
+ Jim_DecrRefCount(interp, script->token[i].objPtr);\r
+ }\r
+ Jim_Free(script->token);\r
+ Jim_Free(script->cmdStruct);\r
+ Jim_Free(script->fileName);\r
+ Jim_Free(script);\r
+}\r
+\r
+void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)\r
+{\r
+ JIM_NOTUSED(interp);\r
+ JIM_NOTUSED(srcPtr);\r
+\r
+ /* Just returns an simple string. */\r
+ dupPtr->typePtr = NULL;\r
+}\r
+\r
+/* Add a new token to the internal repr of a script object */\r
+static void ScriptObjAddToken(Jim_Interp *interp, struct ScriptObj *script,\r
+ char *strtoken, int len, int type, char *filename, int linenr)\r
+{\r
+ int prevtype;\r
+ struct ScriptToken *token;\r
+\r
+ prevtype = (script->len == 0) ? JIM_TT_EOL : \\r
+ script->token[script->len-1].type;\r
+ /* Skip tokens without meaning, like words separators\r
+ * following a word separator or an end of command and\r
+ * so on. */\r
+ if (prevtype == JIM_TT_EOL) {\r
+ if (type == JIM_TT_EOL || type == JIM_TT_SEP) {\r
+ Jim_Free(strtoken);\r
+ return;\r
+ }\r
+ } else if (prevtype == JIM_TT_SEP) {\r
+ if (type == JIM_TT_SEP) {\r
+ Jim_Free(strtoken);\r
+ return;\r
+ } else if (type == JIM_TT_EOL) {\r
+ /* If an EOL is following by a SEP, drop the previous\r
+ * separator. */\r
+ script->len--;\r
+ Jim_DecrRefCount(interp, script->token[script->len].objPtr);\r
+ }\r
+ } else if (prevtype != JIM_TT_EOL && prevtype != JIM_TT_SEP &&\r
+ type == JIM_TT_ESC && len == 0)\r
+ {\r
+ /* Don't add empty tokens used in interpolation */\r
+ Jim_Free(strtoken);\r
+ return;\r
+ }\r
+ /* Make space for a new istruction */\r
+ script->len++;\r
+ script->token = Jim_Realloc(script->token,\r
+ sizeof(ScriptToken)*script->len);\r
+ /* Initialize the new token */\r
+ token = script->token+(script->len-1);\r
+ token->type = type;\r
+ /* Every object is intially as a string, but the\r
+ * internal type may be specialized during execution of the\r
+ * script. */\r
+ token->objPtr = Jim_NewStringObjNoAlloc(interp, strtoken, len);\r
+ /* To add source info to SEP and EOL tokens is useless because\r
+ * they will never by called as arguments of Jim_EvalObj(). */\r
+ if (filename && type != JIM_TT_SEP && type != JIM_TT_EOL)\r
+ JimSetSourceInfo(interp, token->objPtr, filename, linenr);\r
+ Jim_IncrRefCount(token->objPtr);\r
+ token->linenr = linenr;\r
+}\r
+\r
+/* Add an integer into the command structure field of the script object. */\r
+static void ScriptObjAddInt(struct ScriptObj *script, int val)\r
+{\r
+ script->csLen++;\r
+ script->cmdStruct = Jim_Realloc(script->cmdStruct,\r
+ sizeof(int)*script->csLen);\r
+ script->cmdStruct[script->csLen-1] = val;\r
+}\r
+\r
+/* Search a Jim_Obj contained in 'script' with the same stinrg repr.\r
+ * of objPtr. Search nested script objects recursively. */\r
+static Jim_Obj *ScriptSearchLiteral(Jim_Interp *interp, ScriptObj *script,\r
+ ScriptObj *scriptBarrier, Jim_Obj *objPtr)\r
+{\r
+ int i;\r
+\r
+ for (i = 0; i < script->len; i++) {\r
+ if (script->token[i].objPtr != objPtr &&\r
+ Jim_StringEqObj(script->token[i].objPtr, objPtr, 0)) {\r
+ return script->token[i].objPtr;\r
+ }\r
+ /* Enter recursively on scripts only if the object\r
+ * is not the same as the one we are searching for\r
+ * shared occurrences. */\r
+ if (script->token[i].objPtr->typePtr == &scriptObjType &&\r
+ script->token[i].objPtr != objPtr) {\r
+ Jim_Obj *foundObjPtr;\r
+\r
+ ScriptObj *subScript =\r
+ script->token[i].objPtr->internalRep.ptr;\r
+ /* Don't recursively enter the script we are trying\r
+ * to make shared to avoid circular references. */\r
+ if (subScript == scriptBarrier) continue;\r
+ if (subScript != script) {\r
+ foundObjPtr =\r
+ ScriptSearchLiteral(interp, subScript,\r
+ scriptBarrier, objPtr);\r
+ if (foundObjPtr != NULL)\r
+ return foundObjPtr;\r
+ }\r
+ }\r
+ }\r
+ return NULL;\r
+}\r
+\r
+/* Share literals of a script recursively sharing sub-scripts literals. */\r
+static void ScriptShareLiterals(Jim_Interp *interp, ScriptObj *script,\r
+ ScriptObj *topLevelScript)\r
+{\r
+ int i, j;\r
+\r
+ return;\r
+ /* Try to share with toplevel object. */\r
+ if (topLevelScript != NULL) {\r
+ for (i = 0; i < script->len; i++) {\r
+ Jim_Obj *foundObjPtr;\r
+ char *str = script->token[i].objPtr->bytes;\r
+\r
+ if (script->token[i].objPtr->refCount != 1) continue;\r
+ if (script->token[i].objPtr->typePtr == &scriptObjType) continue;\r
+ if (strchr(str, ' ') || strchr(str, '\n')) continue;\r
+ foundObjPtr = ScriptSearchLiteral(interp,\r
+ topLevelScript,\r
+ script, /* barrier */\r
+ script->token[i].objPtr);\r
+ if (foundObjPtr != NULL) {\r
+ Jim_IncrRefCount(foundObjPtr);\r
+ Jim_DecrRefCount(interp,\r
+ script->token[i].objPtr);\r
+ script->token[i].objPtr = foundObjPtr;\r
+ }\r
+ }\r
+ }\r
+ /* Try to share locally */\r
+ for (i = 0; i < script->len; i++) {\r
+ char *str = script->token[i].objPtr->bytes;\r
+\r
+ if (script->token[i].objPtr->refCount != 1) continue;\r
+ if (strchr(str, ' ') || strchr(str, '\n')) continue;\r
+ for (j = 0; j < script->len; j++) {\r
+ if (script->token[i].objPtr !=\r
+ script->token[j].objPtr &&\r
+ Jim_StringEqObj(script->token[i].objPtr,\r
+ script->token[j].objPtr, 0))\r
+ {\r
+ Jim_IncrRefCount(script->token[j].objPtr);\r
+ Jim_DecrRefCount(interp,\r
+ script->token[i].objPtr);\r
+ script->token[i].objPtr =\r
+ script->token[j].objPtr;\r
+ }\r
+ }\r
+ }\r
+}\r
+\r
+/* This method takes the string representation of an object\r
+ * as a Tcl script, and generates the pre-parsed internal representation\r
+ * of the script. */\r
+int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)\r
+{\r
+ int scriptTextLen;\r
+ const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);\r
+ struct JimParserCtx parser;\r
+ struct ScriptObj *script = Jim_Alloc(sizeof(*script));\r
+ ScriptToken *token;\r
+ int args, tokens, start, end, i;\r
+ int initialLineNumber;\r
+ int propagateSourceInfo = 0;\r
+\r
+ script->len = 0;\r
+ script->csLen = 0;\r
+ script->commands = 0;\r
+ script->token = NULL;\r
+ script->cmdStruct = NULL;\r
+ script->inUse = 1;\r
+ /* Try to get information about filename / line number */\r
+ if (objPtr->typePtr == &sourceObjType) {\r
+ script->fileName =\r
+ Jim_StrDup(objPtr->internalRep.sourceValue.fileName);\r
+ initialLineNumber = objPtr->internalRep.sourceValue.lineNumber;\r
+ propagateSourceInfo = 1;\r
+ } else {\r
+ script->fileName = Jim_StrDup("?");\r
+ initialLineNumber = 1;\r
+ }\r
+\r
+ JimParserInit(&parser, scriptText, scriptTextLen, initialLineNumber);\r
+ while(!JimParserEof(&parser)) {\r
+ char *token;\r
+ int len, type, linenr;\r
+\r
+ JimParseScript(&parser);\r
+ token = JimParserGetToken(&parser, &len, &type, &linenr);\r
+ ScriptObjAddToken(interp, script, token, len, type,\r
+ propagateSourceInfo ? script->fileName : NULL,\r
+ linenr);\r
+ }\r
+ token = script->token;\r
+\r
+ /* Compute the command structure array\r
+ * (see the ScriptObj struct definition for more info) */\r
+ start = 0; /* Current command start token index */\r
+ end = -1; /* Current command end token index */\r
+ while (1) {\r
+ int expand = 0; /* expand flag. set to 1 on {expand} form. */\r
+ int interpolation = 0; /* set to 1 if there is at least one\r
+ argument of the command obtained via\r
+ interpolation of more tokens. */\r
+ /* Search for the end of command, while\r
+ * count the number of args. */\r
+ start = ++end;\r
+ if (start >= script->len) break;\r
+ args = 1; /* Number of args in current command */\r
+ while (token[end].type != JIM_TT_EOL) {\r
+ if (end == 0 || token[end-1].type == JIM_TT_SEP ||\r
+ token[end-1].type == JIM_TT_EOL)\r
+ {\r
+ if (token[end].type == JIM_TT_STR &&\r
+ token[end+1].type != JIM_TT_SEP &&\r
+ token[end+1].type != JIM_TT_EOL &&\r
+ (!strcmp(token[end].objPtr->bytes, "expand") ||\r
+ !strcmp(token[end].objPtr->bytes, "*")))\r
+ expand++;\r
+ }\r
+ if (token[end].type == JIM_TT_SEP)\r
+ args++;\r
+ end++;\r
+ }\r
+ interpolation = !((end-start+1) == args*2);\r
+ /* Add the 'number of arguments' info into cmdstruct.\r
+ * Negative value if there is list expansion involved. */\r
+ if (expand)\r
+ ScriptObjAddInt(script, -1);\r
+ ScriptObjAddInt(script, args);\r
+ /* Now add info about the number of tokens. */\r
+ tokens = 0; /* Number of tokens in current argument. */\r
+ expand = 0;\r
+ for (i = start; i <= end; i++) {\r
+ if (token[i].type == JIM_TT_SEP ||\r
+ token[i].type == JIM_TT_EOL)\r
+ {\r
+ if (tokens == 1 && expand)\r
+ expand = 0;\r
+ ScriptObjAddInt(script,\r
+ expand ? -tokens : tokens);\r
+\r
+ expand = 0;\r
+ tokens = 0;\r
+ continue;\r
+ } else if (tokens == 0 && token[i].type == JIM_TT_STR &&\r
+ (!strcmp(token[i].objPtr->bytes, "expand") ||\r
+ !strcmp(token[i].objPtr->bytes, "*")))\r
+ {\r
+ expand++;\r
+ }\r
+ tokens++;\r
+ }\r
+ }\r
+ /* Perform literal sharing, but only for objects that appear\r
+ * to be scripts written as literals inside the source code,\r
+ * and not computed at runtime. Literal sharing is a costly\r
+ * operation that should be done only against objects that\r
+ * are likely to require compilation only the first time, and\r
+ * then are executed multiple times. */\r
+ if (propagateSourceInfo && interp->framePtr->procBodyObjPtr) {\r
+ Jim_Obj *bodyObjPtr = interp->framePtr->procBodyObjPtr;\r
+ if (bodyObjPtr->typePtr == &scriptObjType) {\r
+ ScriptObj *bodyScript =\r
+ bodyObjPtr->internalRep.ptr;\r
+ ScriptShareLiterals(interp, script, bodyScript);\r
+ }\r
+ } else if (propagateSourceInfo) {\r
+ ScriptShareLiterals(interp, script, NULL);\r
+ }\r
+ /* Free the old internal rep and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ Jim_SetIntRepPtr(objPtr, script);\r
+ objPtr->typePtr = &scriptObjType;\r
+ return JIM_OK;\r
+}\r
+\r
+ScriptObj *Jim_GetScript(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ if (objPtr->typePtr != &scriptObjType) {\r
+ SetScriptFromAny(interp, objPtr);\r
+ }\r
+ return (ScriptObj*) Jim_GetIntRepPtr(objPtr);\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Commands\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* Commands HashTable Type.\r
+ *\r
+ * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */\r
+static void Jim_CommandsHT_ValDestructor(void *interp, void *val)\r
+{\r
+ Jim_Cmd *cmdPtr = (void*) val;\r
+\r
+ if (cmdPtr->cmdProc == NULL) {\r
+ Jim_DecrRefCount(interp, cmdPtr->argListObjPtr);\r
+ Jim_DecrRefCount(interp, cmdPtr->bodyObjPtr);\r
+ if (cmdPtr->staticVars) {\r
+ Jim_FreeHashTable(cmdPtr->staticVars);\r
+ Jim_Free(cmdPtr->staticVars);\r
+ }\r
+ } else if (cmdPtr->delProc != NULL) {\r
+ /* If it was a C coded command, call the delProc if any */\r
+ cmdPtr->delProc(interp, cmdPtr->privData);\r
+ }\r
+ Jim_Free(val);\r
+}\r
+\r
+static Jim_HashTableType JimCommandsHashTableType = {\r
+ JimStringCopyHTHashFunction, /* hash function */\r
+ JimStringCopyHTKeyDup, /* key dup */\r
+ NULL, /* val dup */\r
+ JimStringCopyHTKeyCompare, /* key compare */\r
+ JimStringCopyHTKeyDestructor, /* key destructor */\r
+ Jim_CommandsHT_ValDestructor /* val destructor */\r
+};\r
+\r
+/* ------------------------- Commands related functions --------------------- */\r
+\r
+int Jim_CreateCommand(Jim_Interp *interp, const char *cmdName,\r
+ Jim_CmdProc cmdProc, void *privData, Jim_DelCmdProc delProc)\r
+{\r
+ Jim_HashEntry *he;\r
+ Jim_Cmd *cmdPtr;\r
+\r
+ he = Jim_FindHashEntry(&interp->commands, cmdName);\r
+ if (he == NULL) { /* New command to create */\r
+ cmdPtr = Jim_Alloc(sizeof(*cmdPtr));\r
+ cmdPtr->cmdProc = cmdProc;\r
+ cmdPtr->privData = privData;\r
+ cmdPtr->delProc = delProc;\r
+ Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);\r
+ } else {\r
+ Jim_InterpIncrProcEpoch(interp);\r
+ /* Free the arglist/body objects if it was a Tcl procedure */\r
+ cmdPtr = he->val;\r
+ if (cmdPtr->cmdProc == NULL) {\r
+ Jim_DecrRefCount(interp, cmdPtr->argListObjPtr);\r
+ Jim_DecrRefCount(interp, cmdPtr->bodyObjPtr);\r
+ if (cmdPtr->staticVars) {\r
+ Jim_FreeHashTable(cmdPtr->staticVars);\r
+ Jim_Free(cmdPtr->staticVars);\r
+ }\r
+ cmdPtr->staticVars = NULL;\r
+ } else if (cmdPtr->delProc != NULL) {\r
+ /* If it was a C coded command, call the delProc if any */\r
+ cmdPtr->delProc(interp, cmdPtr->privData);\r
+ }\r
+ cmdPtr->cmdProc = cmdProc;\r
+ cmdPtr->privData = privData;\r
+ }\r
+ /* There is no need to increment the 'proc epoch' because\r
+ * creation of a new procedure can never affect existing\r
+ * cached commands. We don't do negative caching. */\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_CreateProcedure(Jim_Interp *interp, const char *cmdName,\r
+ Jim_Obj *argListObjPtr, Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr,\r
+ int arityMin, int arityMax)\r
+{\r
+ Jim_Cmd *cmdPtr;\r
+\r
+ cmdPtr = Jim_Alloc(sizeof(*cmdPtr));\r
+ cmdPtr->cmdProc = NULL; /* Not a C coded command */\r
+ cmdPtr->argListObjPtr = argListObjPtr;\r
+ cmdPtr->bodyObjPtr = bodyObjPtr;\r
+ Jim_IncrRefCount(argListObjPtr);\r
+ Jim_IncrRefCount(bodyObjPtr);\r
+ cmdPtr->arityMin = arityMin;\r
+ cmdPtr->arityMax = arityMax;\r
+ cmdPtr->staticVars = NULL;\r
+ \r
+ /* Create the statics hash table. */\r
+ if (staticsListObjPtr) {\r
+ int len, i;\r
+\r
+ Jim_ListLength(interp, staticsListObjPtr, &len);\r
+ if (len != 0) {\r
+ cmdPtr->staticVars = Jim_Alloc(sizeof(Jim_HashTable));\r
+ Jim_InitHashTable(cmdPtr->staticVars, &JimVariablesHashTableType,\r
+ interp);\r
+ for (i = 0; i < len; i++) {\r
+ Jim_Obj *objPtr, *initObjPtr, *nameObjPtr;\r
+ Jim_Var *varPtr;\r
+ int subLen;\r
+\r
+ Jim_ListIndex(interp, staticsListObjPtr, i, &objPtr, JIM_NONE);\r
+ /* Check if it's composed of two elements. */\r
+ Jim_ListLength(interp, objPtr, &subLen);\r
+ if (subLen == 1 || subLen == 2) {\r
+ /* Try to get the variable value from the current\r
+ * environment. */\r
+ Jim_ListIndex(interp, objPtr, 0, &nameObjPtr, JIM_NONE);\r
+ if (subLen == 1) {\r
+ initObjPtr = Jim_GetVariable(interp, nameObjPtr,\r
+ JIM_NONE);\r
+ if (initObjPtr == NULL) {\r
+ Jim_SetResult(interp,\r
+ Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "variable for initialization of static \"",\r
+ Jim_GetString(nameObjPtr, NULL),\r
+ "\" not found in the local context",\r
+ NULL);\r
+ goto err;\r
+ }\r
+ } else {\r
+ Jim_ListIndex(interp, objPtr, 1, &initObjPtr, JIM_NONE);\r
+ }\r
+ varPtr = Jim_Alloc(sizeof(*varPtr));\r
+ varPtr->objPtr = initObjPtr;\r
+ Jim_IncrRefCount(initObjPtr);\r
+ varPtr->linkFramePtr = NULL;\r
+ if (Jim_AddHashEntry(cmdPtr->staticVars,\r
+ Jim_GetString(nameObjPtr, NULL),\r
+ varPtr) != JIM_OK)\r
+ {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "static variable name \"",\r
+ Jim_GetString(objPtr, NULL), "\"",\r
+ " duplicated in statics list", NULL);\r
+ Jim_DecrRefCount(interp, initObjPtr);\r
+ Jim_Free(varPtr);\r
+ goto err;\r
+ }\r
+ } else {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "too many fields in static specifier \"",\r
+ objPtr, "\"", NULL);\r
+ goto err;\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ /* Add the new command */\r
+\r
+ /* it may already exist, so we try to delete the old one */\r
+ if (Jim_DeleteHashEntry(&interp->commands, cmdName) != JIM_ERR) {\r
+ /* There was an old procedure with the same name, this requires\r
+ * a 'proc epoch' update. */\r
+ Jim_InterpIncrProcEpoch(interp);\r
+ }\r
+ /* If a procedure with the same name didn't existed there is no need\r
+ * to increment the 'proc epoch' because creation of a new procedure\r
+ * can never affect existing cached commands. We don't do\r
+ * negative caching. */\r
+ Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);\r
+ return JIM_OK;\r
+\r
+err:\r
+ Jim_FreeHashTable(cmdPtr->staticVars);\r
+ Jim_Free(cmdPtr->staticVars);\r
+ Jim_DecrRefCount(interp, argListObjPtr);\r
+ Jim_DecrRefCount(interp, bodyObjPtr);\r
+ Jim_Free(cmdPtr);\r
+ return JIM_ERR;\r
+}\r
+\r
+int Jim_DeleteCommand(Jim_Interp *interp, const char *cmdName)\r
+{\r
+ if (Jim_DeleteHashEntry(&interp->commands, cmdName) == JIM_ERR)\r
+ return JIM_ERR;\r
+ Jim_InterpIncrProcEpoch(interp);\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_RenameCommand(Jim_Interp *interp, const char *oldName, \r
+ const char *newName)\r
+{\r
+ Jim_Cmd *cmdPtr;\r
+ Jim_HashEntry *he;\r
+ Jim_Cmd *copyCmdPtr;\r
+\r
+ if (newName[0] == '\0') /* Delete! */\r
+ return Jim_DeleteCommand(interp, oldName);\r
+ /* Rename */\r
+ he = Jim_FindHashEntry(&interp->commands, oldName);\r
+ if (he == NULL)\r
+ return JIM_ERR; /* Invalid command name */\r
+ cmdPtr = he->val;\r
+ copyCmdPtr = Jim_Alloc(sizeof(Jim_Cmd));\r
+ *copyCmdPtr = *cmdPtr;\r
+ /* In order to avoid that a procedure will get arglist/body/statics\r
+ * freed by the hash table methods, fake a C-coded command\r
+ * setting cmdPtr->cmdProc as not NULL */\r
+ cmdPtr->cmdProc = (void*)1;\r
+ /* Also make sure delProc is NULL. */\r
+ cmdPtr->delProc = NULL;\r
+ /* Destroy the old command, and make sure the new is freed\r
+ * as well. */\r
+ Jim_DeleteHashEntry(&interp->commands, oldName);\r
+ Jim_DeleteHashEntry(&interp->commands, newName);\r
+ /* Now the new command. We are sure it can't fail because\r
+ * the target name was already freed. */\r
+ Jim_AddHashEntry(&interp->commands, newName, copyCmdPtr);\r
+ /* Increment the epoch */\r
+ Jim_InterpIncrProcEpoch(interp);\r
+ return JIM_OK;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Command object\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+static int SetCommandFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType commandObjType = {\r
+ "command",\r
+ NULL,\r
+ NULL,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+int SetCommandFromAny(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ Jim_HashEntry *he;\r
+ const char *cmdName;\r
+\r
+ /* Get the string representation */\r
+ cmdName = Jim_GetString(objPtr, NULL);\r
+ /* Lookup this name into the commands hash table */\r
+ he = Jim_FindHashEntry(&interp->commands, cmdName);\r
+ if (he == NULL)\r
+ return JIM_ERR;\r
+\r
+ /* Free the old internal repr and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &commandObjType;\r
+ objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;\r
+ objPtr->internalRep.cmdValue.cmdPtr = (void*)he->val;\r
+ return JIM_OK;\r
+}\r
+\r
+/* This function returns the command structure for the command name\r
+ * stored in objPtr. It tries to specialize the objPtr to contain\r
+ * a cached info instead to perform the lookup into the hash table\r
+ * every time. The information cached may not be uptodate, in such\r
+ * a case the lookup is performed and the cache updated. */\r
+Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)\r
+{\r
+ if ((objPtr->typePtr != &commandObjType ||\r
+ objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch) &&\r
+ SetCommandFromAny(interp, objPtr) == JIM_ERR) {\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "invalid command name \"", objPtr->bytes, "\"",\r
+ NULL);\r
+ }\r
+ return NULL;\r
+ }\r
+ return objPtr->internalRep.cmdValue.cmdPtr;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Variables\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* Variables HashTable Type.\r
+ *\r
+ * Keys are dynamic allocated strings, Values are Jim_Var structures. */\r
+static void JimVariablesHTValDestructor(void *interp, void *val)\r
+{\r
+ Jim_Var *varPtr = (void*) val;\r
+\r
+ Jim_DecrRefCount(interp, varPtr->objPtr);\r
+ Jim_Free(val);\r
+}\r
+\r
+static Jim_HashTableType JimVariablesHashTableType = {\r
+ JimStringCopyHTHashFunction, /* hash function */\r
+ JimStringCopyHTKeyDup, /* key dup */\r
+ NULL, /* val dup */\r
+ JimStringCopyHTKeyCompare, /* key compare */\r
+ JimStringCopyHTKeyDestructor, /* key destructor */\r
+ JimVariablesHTValDestructor /* val destructor */\r
+};\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Variable object\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+#define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */\r
+\r
+static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType variableObjType = {\r
+ "variable",\r
+ NULL,\r
+ NULL,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+/* Return true if the string "str" looks like syntax sugar for [dict]. I.e.\r
+ * is in the form "varname(key)". */\r
+static int Jim_NameIsDictSugar(const char *str, int len)\r
+{\r
+ if (len == -1)\r
+ len = strlen(str);\r
+ if (len && str[len-1] == ')' && strchr(str, '(') != NULL)\r
+ return 1;\r
+ return 0;\r
+}\r
+\r
+/* This method should be called only by the variable API.\r
+ * It returns JIM_OK on success (variable already exists),\r
+ * JIM_ERR if it does not exists, JIM_DICT_GLUE if it's not\r
+ * a variable name, but syntax glue for [dict] i.e. the last\r
+ * character is ')' */\r
+int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)\r
+{\r
+ Jim_HashEntry *he;\r
+ const char *varName;\r
+ int len;\r
+\r
+ /* Check if the object is already an uptodate variable */\r
+ if (objPtr->typePtr == &variableObjType &&\r
+ objPtr->internalRep.varValue.callFrameId == interp->framePtr->id)\r
+ return JIM_OK; /* nothing to do */\r
+ /* Get the string representation */\r
+ varName = Jim_GetString(objPtr, &len);\r
+ /* Make sure it's not syntax glue to get/set dict. */\r
+ if (Jim_NameIsDictSugar(varName, len))\r
+ return JIM_DICT_SUGAR;\r
+ /* Lookup this name into the variables hash table */\r
+ he = Jim_FindHashEntry(&interp->framePtr->vars, varName);\r
+ if (he == NULL) {\r
+ /* Try with static vars. */\r
+ if (interp->framePtr->staticVars == NULL)\r
+ return JIM_ERR;\r
+ if (!(he = Jim_FindHashEntry(interp->framePtr->staticVars, varName)))\r
+ return JIM_ERR;\r
+ }\r
+ /* Free the old internal repr and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &variableObjType;\r
+ objPtr->internalRep.varValue.callFrameId = interp->framePtr->id;\r
+ objPtr->internalRep.varValue.varPtr = (void*)he->val;\r
+ return JIM_OK;\r
+}\r
+\r
+/* -------------------- Variables related functions ------------------------- */\r
+static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr,\r
+ Jim_Obj *valObjPtr);\r
+static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr);\r
+\r
+/* For now that's dummy. Variables lookup should be optimized\r
+ * in many ways, with caching of lookups, and possibly with\r
+ * a table of pre-allocated vars in every CallFrame for local vars.\r
+ * All the caching should also have an 'epoch' mechanism similar\r
+ * to the one used by Tcl for procedures lookup caching. */\r
+\r
+int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)\r
+{\r
+ const char *name;\r
+ Jim_Var *var;\r
+ int err;\r
+\r
+ if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {\r
+ /* Check for [dict] syntax sugar. */\r
+ if (err == JIM_DICT_SUGAR)\r
+ return JimDictSugarSet(interp, nameObjPtr, valObjPtr);\r
+ /* New variable to create */\r
+ name = Jim_GetString(nameObjPtr, NULL);\r
+\r
+ var = Jim_Alloc(sizeof(*var));\r
+ var->objPtr = valObjPtr;\r
+ Jim_IncrRefCount(valObjPtr);\r
+ var->linkFramePtr = NULL;\r
+ /* Insert the new variable */\r
+ Jim_AddHashEntry(&interp->framePtr->vars, name, var);\r
+ /* Make the object int rep a variable */\r
+ Jim_FreeIntRep(interp, nameObjPtr);\r
+ nameObjPtr->typePtr = &variableObjType;\r
+ nameObjPtr->internalRep.varValue.callFrameId =\r
+ interp->framePtr->id;\r
+ nameObjPtr->internalRep.varValue.varPtr = var;\r
+ } else {\r
+ var = nameObjPtr->internalRep.varValue.varPtr;\r
+ if (var->linkFramePtr == NULL) {\r
+ Jim_IncrRefCount(valObjPtr);\r
+ Jim_DecrRefCount(interp, var->objPtr);\r
+ var->objPtr = valObjPtr;\r
+ } else { /* Else handle the link */\r
+ Jim_CallFrame *savedCallFrame;\r
+\r
+ savedCallFrame = interp->framePtr;\r
+ interp->framePtr = var->linkFramePtr;\r
+ err = Jim_SetVariable(interp, var->objPtr, valObjPtr);\r
+ interp->framePtr = savedCallFrame;\r
+ if (err != JIM_OK)\r
+ return err;\r
+ }\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)\r
+{\r
+ Jim_Obj *nameObjPtr;\r
+ int result;\r
+\r
+ nameObjPtr = Jim_NewStringObj(interp, name, -1);\r
+ Jim_IncrRefCount(nameObjPtr);\r
+ result = Jim_SetVariable(interp, nameObjPtr, objPtr);\r
+ Jim_DecrRefCount(interp, nameObjPtr);\r
+ return result;\r
+}\r
+\r
+int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)\r
+{\r
+ Jim_CallFrame *savedFramePtr;\r
+ int result;\r
+\r
+ savedFramePtr = interp->framePtr;\r
+ interp->framePtr = interp->topFramePtr;\r
+ result = Jim_SetVariableStr(interp, name, objPtr);\r
+ interp->framePtr = savedFramePtr;\r
+ return result;\r
+}\r
+\r
+int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)\r
+{\r
+ Jim_Obj *nameObjPtr, *valObjPtr;\r
+ int result;\r
+\r
+ nameObjPtr = Jim_NewStringObj(interp, name, -1);\r
+ valObjPtr = Jim_NewStringObj(interp, val, -1);\r
+ Jim_IncrRefCount(nameObjPtr);\r
+ Jim_IncrRefCount(valObjPtr);\r
+ result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);\r
+ Jim_DecrRefCount(interp, nameObjPtr);\r
+ Jim_DecrRefCount(interp, valObjPtr);\r
+ return result;\r
+}\r
+\r
+int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,\r
+ Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)\r
+{\r
+ const char *varName;\r
+ int len;\r
+\r
+ /* Check for cycles. */\r
+ if (interp->framePtr == targetCallFrame) {\r
+ Jim_Obj *objPtr = targetNameObjPtr;\r
+ Jim_Var *varPtr;\r
+ /* Cycles are only possible with 'uplevel 0' */\r
+ while(1) {\r
+ if (Jim_StringEqObj(objPtr, nameObjPtr, 0)) {\r
+ Jim_SetResultString(interp,\r
+ "can't upvar from variable to itself", -1);\r
+ return JIM_ERR;\r
+ }\r
+ if (SetVariableFromAny(interp, objPtr) != JIM_OK)\r
+ break;\r
+ varPtr = objPtr->internalRep.varValue.varPtr;\r
+ if (varPtr->linkFramePtr != targetCallFrame) break;\r
+ objPtr = varPtr->objPtr;\r
+ }\r
+ }\r
+ varName = Jim_GetString(nameObjPtr, &len);\r
+ if (Jim_NameIsDictSugar(varName, len)) {\r
+ Jim_SetResultString(interp,\r
+ "Dict key syntax invalid as link source", -1);\r
+ return JIM_ERR;\r
+ }\r
+ /* Perform the binding */\r
+ Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);\r
+ /* We are now sure 'nameObjPtr' type is variableObjType */\r
+ nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Return the Jim_Obj pointer associated with a variable name,\r
+ * or NULL if the variable was not found in the current context.\r
+ * The same optimization discussed in the comment to the\r
+ * 'SetVariable' function should apply here. */\r
+Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)\r
+{\r
+ int err;\r
+\r
+ /* All the rest is handled here */\r
+ if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {\r
+ /* Check for [dict] syntax sugar. */\r
+ if (err == JIM_DICT_SUGAR)\r
+ return JimDictSugarGet(interp, nameObjPtr);\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "can't read \"", nameObjPtr->bytes,\r
+ "\": no such variable", NULL);\r
+ }\r
+ return NULL;\r
+ } else {\r
+ Jim_Var *varPtr;\r
+ Jim_Obj *objPtr;\r
+ Jim_CallFrame *savedCallFrame;\r
+\r
+ varPtr = nameObjPtr->internalRep.varValue.varPtr;\r
+ if (varPtr->linkFramePtr == NULL)\r
+ return varPtr->objPtr;\r
+ /* The variable is a link? Resolve it. */\r
+ savedCallFrame = interp->framePtr;\r
+ interp->framePtr = varPtr->linkFramePtr;\r
+ objPtr = Jim_GetVariable(interp, varPtr->objPtr, JIM_NONE);\r
+ if (objPtr == NULL && flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "can't read \"", nameObjPtr->bytes,\r
+ "\": no such variable", NULL);\r
+ }\r
+ interp->framePtr = savedCallFrame;\r
+ return objPtr;\r
+ }\r
+}\r
+\r
+Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr,\r
+ int flags)\r
+{\r
+ Jim_CallFrame *savedFramePtr;\r
+ Jim_Obj *objPtr;\r
+\r
+ savedFramePtr = interp->framePtr;\r
+ interp->framePtr = interp->topFramePtr;\r
+ objPtr = Jim_GetVariable(interp, nameObjPtr, flags);\r
+ interp->framePtr = savedFramePtr;\r
+\r
+ return objPtr;\r
+}\r
+\r
+Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)\r
+{\r
+ Jim_Obj *nameObjPtr, *varObjPtr;\r
+\r
+ nameObjPtr = Jim_NewStringObj(interp, name, -1);\r
+ Jim_IncrRefCount(nameObjPtr);\r
+ varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);\r
+ Jim_DecrRefCount(interp, nameObjPtr);\r
+ return varObjPtr;\r
+}\r
+\r
+Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name,\r
+ int flags)\r
+{\r
+ Jim_CallFrame *savedFramePtr;\r
+ Jim_Obj *objPtr;\r
+\r
+ savedFramePtr = interp->framePtr;\r
+ interp->framePtr = interp->topFramePtr;\r
+ objPtr = Jim_GetVariableStr(interp, name, flags);\r
+ interp->framePtr = savedFramePtr;\r
+\r
+ return objPtr;\r
+}\r
+\r
+/* Unset a variable.\r
+ * Note: On success unset invalidates all the variable objects created\r
+ * in the current call frame incrementing. */\r
+int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)\r
+{\r
+ const char *name;\r
+ Jim_Var *varPtr;\r
+ int err;\r
+ \r
+ if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {\r
+ /* Check for [dict] syntax sugar. */\r
+ if (err == JIM_DICT_SUGAR)\r
+ return JimDictSugarSet(interp, nameObjPtr, NULL);\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "can't unset \"", nameObjPtr->bytes,\r
+ "\": no such variable", NULL);\r
+ return JIM_ERR; /* var not found */\r
+ }\r
+ varPtr = nameObjPtr->internalRep.varValue.varPtr;\r
+ /* If it's a link call UnsetVariable recursively */\r
+ if (varPtr->linkFramePtr) {\r
+ int retval;\r
+\r
+ Jim_CallFrame *savedCallFrame;\r
+\r
+ savedCallFrame = interp->framePtr;\r
+ interp->framePtr = varPtr->linkFramePtr;\r
+ retval = Jim_UnsetVariable(interp, varPtr->objPtr, JIM_NONE);\r
+ interp->framePtr = savedCallFrame;\r
+ if (retval != JIM_OK && flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "can't unset \"", nameObjPtr->bytes,\r
+ "\": no such variable", NULL);\r
+ }\r
+ return retval;\r
+ } else {\r
+ name = Jim_GetString(nameObjPtr, NULL);\r
+ if (Jim_DeleteHashEntry(&interp->framePtr->vars, name)\r
+ != JIM_OK) return JIM_ERR;\r
+ /* Change the callframe id, invalidating var lookup caching */\r
+ JimChangeCallFrameId(interp, interp->framePtr);\r
+ return JIM_OK;\r
+ }\r
+}\r
+\r
+/* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */\r
+\r
+/* Given a variable name for [dict] operation syntax sugar,\r
+ * this function returns two objects, the first with the name\r
+ * of the variable to set, and the second with the rispective key.\r
+ * For example "foo(bar)" will return objects with string repr. of\r
+ * "foo" and "bar".\r
+ *\r
+ * The returned objects have refcount = 1. The function can't fail. */\r
+static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)\r
+{\r
+ const char *str, *p;\r
+ char *t;\r
+ int len, keyLen, nameLen;\r
+ Jim_Obj *varObjPtr, *keyObjPtr;\r
+\r
+ str = Jim_GetString(objPtr, &len);\r
+ p = strchr(str, '(');\r
+ p++;\r
+ keyLen = len-((p-str)+1);\r
+ nameLen = (p-str)-1;\r
+ /* Create the objects with the variable name and key. */\r
+ t = Jim_Alloc(nameLen+1);\r
+ memcpy(t, str, nameLen);\r
+ t[nameLen] = '\0';\r
+ varObjPtr = Jim_NewStringObjNoAlloc(interp, t, nameLen);\r
+\r
+ t = Jim_Alloc(keyLen+1);\r
+ memcpy(t, p, keyLen);\r
+ t[keyLen] = '\0';\r
+ keyObjPtr = Jim_NewStringObjNoAlloc(interp, t, keyLen);\r
+\r
+ Jim_IncrRefCount(varObjPtr);\r
+ Jim_IncrRefCount(keyObjPtr);\r
+ *varPtrPtr = varObjPtr;\r
+ *keyPtrPtr = keyObjPtr;\r
+}\r
+\r
+/* Helper of Jim_SetVariable() to deal with dict-syntax variable names.\r
+ * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */\r
+static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ Jim_Obj *valObjPtr)\r
+{\r
+ Jim_Obj *varObjPtr, *keyObjPtr;\r
+ int err = JIM_OK;\r
+\r
+ JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);\r
+ err = Jim_SetDictKeysVector(interp, varObjPtr, &keyObjPtr, 1,\r
+ valObjPtr);\r
+ Jim_DecrRefCount(interp, varObjPtr);\r
+ Jim_DecrRefCount(interp, keyObjPtr);\r
+ return err;\r
+}\r
+\r
+/* Helper of Jim_GetVariable() to deal with dict-syntax variable names */\r
+static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ Jim_Obj *varObjPtr, *keyObjPtr, *dictObjPtr, *resObjPtr;\r
+\r
+ JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);\r
+ dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);\r
+ if (!dictObjPtr) {\r
+ resObjPtr = NULL;\r
+ goto err;\r
+ }\r
+ if (Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_ERRMSG)\r
+ != JIM_OK) {\r
+ resObjPtr = NULL;\r
+ }\r
+err:\r
+ Jim_DecrRefCount(interp, varObjPtr);\r
+ Jim_DecrRefCount(interp, keyObjPtr);\r
+ return resObjPtr;\r
+}\r
+\r
+/* --------- $var(INDEX) substitution, using a specialized object ----------- */\r
+\r
+static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);\r
+static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr,\r
+ Jim_Obj *dupPtr);\r
+\r
+static Jim_ObjType dictSubstObjType = {\r
+ "dict-substitution",\r
+ FreeDictSubstInternalRep,\r
+ DupDictSubstInternalRep,\r
+ NULL,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);\r
+ Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);\r
+}\r
+\r
+void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr,\r
+ Jim_Obj *dupPtr)\r
+{\r
+ JIM_NOTUSED(interp);\r
+\r
+ dupPtr->internalRep.dictSubstValue.varNameObjPtr =\r
+ srcPtr->internalRep.dictSubstValue.varNameObjPtr;\r
+ dupPtr->internalRep.dictSubstValue.indexObjPtr =\r
+ srcPtr->internalRep.dictSubstValue.indexObjPtr;\r
+ dupPtr->typePtr = &dictSubstObjType;\r
+}\r
+\r
+/* This function is used to expand [dict get] sugar in the form\r
+ * of $var(INDEX). The function is mainly used by Jim_EvalObj()\r
+ * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an\r
+ * object that is *guaranteed* to be in the form VARNAME(INDEX).\r
+ * The 'index' part is [subst]ituted, and is used to lookup a key inside\r
+ * the [dict]ionary contained in variable VARNAME. */\r
+Jim_Obj *Jim_ExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ Jim_Obj *varObjPtr, *keyObjPtr, *dictObjPtr, *resObjPtr;\r
+ Jim_Obj *substKeyObjPtr = NULL;\r
+\r
+ if (objPtr->typePtr != &dictSubstObjType) {\r
+ JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &dictSubstObjType;\r
+ objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;\r
+ objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;\r
+ }\r
+ if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,\r
+ &substKeyObjPtr, JIM_NONE)\r
+ != JIM_OK) {\r
+ substKeyObjPtr = NULL;\r
+ goto err;\r
+ }\r
+ Jim_IncrRefCount(substKeyObjPtr);\r
+ dictObjPtr = Jim_GetVariable(interp,\r
+ objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_ERRMSG);\r
+ if (!dictObjPtr) {\r
+ resObjPtr = NULL;\r
+ goto err;\r
+ }\r
+ if (Jim_DictKey(interp, dictObjPtr, substKeyObjPtr, &resObjPtr, JIM_ERRMSG)\r
+ != JIM_OK) {\r
+ resObjPtr = NULL;\r
+ goto err;\r
+ }\r
+err:\r
+ if (substKeyObjPtr) Jim_DecrRefCount(interp, substKeyObjPtr);\r
+ return resObjPtr;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * CallFrame\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp)\r
+{\r
+ Jim_CallFrame *cf;\r
+ if (interp->freeFramesList) {\r
+ cf = interp->freeFramesList;\r
+ interp->freeFramesList = cf->nextFramePtr;\r
+ } else {\r
+ cf = Jim_Alloc(sizeof(*cf));\r
+ cf->vars.table = NULL;\r
+ }\r
+\r
+ cf->id = interp->callFrameEpoch++;\r
+ cf->parentCallFrame = NULL;\r
+ cf->argv = NULL;\r
+ cf->argc = 0;\r
+ cf->procArgsObjPtr = NULL;\r
+ cf->procBodyObjPtr = NULL;\r
+ cf->nextFramePtr = NULL;\r
+ cf->staticVars = NULL;\r
+ if (cf->vars.table == NULL)\r
+ Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);\r
+ return cf;\r
+}\r
+\r
+/* Used to invalidate every caching related to callframe stability. */\r
+static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf)\r
+{\r
+ cf->id = interp->callFrameEpoch++;\r
+}\r
+\r
+#define JIM_FCF_NONE 0 /* no flags */\r
+#define JIM_FCF_NOHT 1 /* don't free the hash table */\r
+static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf,\r
+ int flags)\r
+{\r
+ if (cf->procArgsObjPtr) Jim_DecrRefCount(interp, cf->procArgsObjPtr);\r
+ if (cf->procBodyObjPtr) Jim_DecrRefCount(interp, cf->procBodyObjPtr);\r
+ if (!(flags & JIM_FCF_NOHT))\r
+ Jim_FreeHashTable(&cf->vars);\r
+ else {\r
+ int i;\r
+ Jim_HashEntry **table = cf->vars.table, *he;\r
+\r
+ for (i = 0; i < JIM_HT_INITIAL_SIZE; i++) {\r
+ he = table[i];\r
+ while (he != NULL) {\r
+ Jim_HashEntry *nextEntry = he->next;\r
+ Jim_Var *varPtr = (void*) he->val;\r
+\r
+ Jim_DecrRefCount(interp, varPtr->objPtr);\r
+ Jim_Free(he->val);\r
+ Jim_Free((void*)he->key); /* ATTENTION: const cast */\r
+ Jim_Free(he);\r
+ table[i] = NULL;\r
+ he = nextEntry;\r
+ }\r
+ }\r
+ cf->vars.used = 0;\r
+ }\r
+ cf->nextFramePtr = interp->freeFramesList;\r
+ interp->freeFramesList = cf;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * References\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* References HashTable Type.\r
+ *\r
+ * Keys are jim_wide integers, dynamically allocated for now but in the\r
+ * future it's worth to cache this 8 bytes objects. Values are poitners\r
+ * to Jim_References. */\r
+static void JimReferencesHTValDestructor(void *interp, void *val)\r
+{\r
+ Jim_Reference *refPtr = (void*) val;\r
+\r
+ Jim_DecrRefCount(interp, refPtr->objPtr);\r
+ if (refPtr->finalizerCmdNamePtr != NULL) {\r
+ Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);\r
+ }\r
+ Jim_Free(val);\r
+}\r
+\r
+unsigned int JimReferencesHTHashFunction(const void *key)\r
+{\r
+ /* Only the least significant bits are used. */\r
+ const jim_wide *widePtr = key;\r
+ unsigned int intValue = (unsigned int) *widePtr;\r
+ return Jim_IntHashFunction(intValue);\r
+}\r
+\r
+unsigned int JimReferencesHTDoubleHashFunction(const void *key)\r
+{\r
+ /* Only the least significant bits are used. */\r
+ const jim_wide *widePtr = key;\r
+ unsigned int intValue = (unsigned int) *widePtr;\r
+ return intValue; /* identity function. */\r
+}\r
+\r
+const void *JimReferencesHTKeyDup(void *privdata, const void *key)\r
+{\r
+ void *copy = Jim_Alloc(sizeof(jim_wide));\r
+ JIM_NOTUSED(privdata);\r
+\r
+ memcpy(copy, key, sizeof(jim_wide));\r
+ return copy;\r
+}\r
+\r
+int JimReferencesHTKeyCompare(void *privdata, const void *key1, \r
+ const void *key2)\r
+{\r
+ JIM_NOTUSED(privdata);\r
+\r
+ return memcmp(key1, key2, sizeof(jim_wide)) == 0;\r
+}\r
+\r
+void JimReferencesHTKeyDestructor(void *privdata, const void *key)\r
+{\r
+ JIM_NOTUSED(privdata);\r
+\r
+ Jim_Free((void*)key);\r
+}\r
+\r
+static Jim_HashTableType JimReferencesHashTableType = {\r
+ JimReferencesHTHashFunction, /* hash function */\r
+ JimReferencesHTKeyDup, /* key dup */\r
+ NULL, /* val dup */\r
+ JimReferencesHTKeyCompare, /* key compare */\r
+ JimReferencesHTKeyDestructor, /* key destructor */\r
+ JimReferencesHTValDestructor /* val destructor */\r
+};\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Reference object type and References API\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+static void UpdateStringOfReference(struct Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType referenceObjType = {\r
+ "reference",\r
+ NULL,\r
+ NULL,\r
+ UpdateStringOfReference,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+void UpdateStringOfReference(struct Jim_Obj *objPtr)\r
+{\r
+ int len;\r
+ char buf[JIM_REFERENCE_SPACE+1];\r
+ Jim_Reference *refPtr;\r
+\r
+ refPtr = objPtr->internalRep.refValue.refPtr;\r
+ len = JimFormatReference(buf, refPtr, objPtr->internalRep.refValue.id);\r
+ objPtr->bytes = Jim_Alloc(len+1);\r
+ memcpy(objPtr->bytes, buf, len+1);\r
+ objPtr->length = len;\r
+}\r
+\r
+/* returns true if 'c' is a valid reference tag character.\r
+ * i.e. inside the range [_a-zA-Z0-9] */\r
+static int isrefchar(int c)\r
+{\r
+ if (c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||\r
+ (c >= '0' && c <= '9')) return 1;\r
+ return 0;\r
+}\r
+\r
+int SetReferenceFromAny(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ jim_wide wideValue;\r
+ int i, len;\r
+ const char *str, *start, *end;\r
+ char refId[21];\r
+ Jim_Reference *refPtr;\r
+ Jim_HashEntry *he;\r
+\r
+ /* Get the string representation */\r
+ str = Jim_GetString(objPtr, &len);\r
+ /* Check if it looks like a reference */\r
+ if (len < JIM_REFERENCE_SPACE) goto badformat;\r
+ /* Trim spaces */\r
+ start = str;\r
+ end = str+len-1;\r
+ while (*start == ' ') start++;\r
+ while (*end == ' ' && end > start) end--;\r
+ if (end-start+1 != JIM_REFERENCE_SPACE) goto badformat;\r
+ /* <reference.<1234567>.%020> */\r
+ if (memcmp(start, "<reference.<", 12) != 0) goto badformat;\r
+ if (start[12+JIM_REFERENCE_TAGLEN] != '>' || end[0] != '>') goto badformat;\r
+ /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */\r
+ for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {\r
+ if (!isrefchar(start[12+i])) goto badformat;\r
+ }\r
+ /* Extract info from the refernece. */\r
+ memcpy(refId, start+14+JIM_REFERENCE_TAGLEN, 20);\r
+ refId[20] = '\0';\r
+ /* Try to convert the ID into a jim_wide */\r
+ if (Jim_StringToWide(refId, &wideValue, 10) != JIM_OK) goto badformat;\r
+ /* Check if the reference really exists! */\r
+ he = Jim_FindHashEntry(&interp->references, &wideValue);\r
+ if (he == NULL) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "Invalid reference ID \"", str, "\"", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ refPtr = he->val;\r
+ /* Free the old internal repr and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &referenceObjType;\r
+ objPtr->internalRep.refValue.id = wideValue;\r
+ objPtr->internalRep.refValue.refPtr = refPtr;\r
+ return JIM_OK;\r
+\r
+badformat:\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "expected reference but got \"", str, "\"", NULL);\r
+ return JIM_ERR;\r
+}\r
+\r
+/* Returns a new reference pointing to objPtr, having cmdNamePtr\r
+ * as finalizer command (or NULL if there is no finalizer).\r
+ * The returned reference object has refcount = 0. */\r
+Jim_Obj *Jim_NewReference(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *tagPtr,\r
+ Jim_Obj *cmdNamePtr)\r
+{\r
+ struct Jim_Reference *refPtr;\r
+ jim_wide wideValue = interp->referenceNextId;\r
+ Jim_Obj *refObjPtr;\r
+ const char *tag;\r
+ int tagLen, i;\r
+\r
+ /* Perform the Garbage Collection if needed. */\r
+ Jim_CollectIfNeeded(interp);\r
+\r
+ refPtr = Jim_Alloc(sizeof(*refPtr));\r
+ refPtr->objPtr = objPtr;\r
+ Jim_IncrRefCount(objPtr);\r
+ refPtr->finalizerCmdNamePtr = cmdNamePtr;\r
+ if (cmdNamePtr)\r
+ Jim_IncrRefCount(cmdNamePtr);\r
+ Jim_AddHashEntry(&interp->references, &wideValue, refPtr);\r
+ refObjPtr = Jim_NewObj(interp);\r
+ refObjPtr->typePtr = &referenceObjType;\r
+ refObjPtr->bytes = NULL;\r
+ refObjPtr->internalRep.refValue.id = interp->referenceNextId;\r
+ refObjPtr->internalRep.refValue.refPtr = refPtr;\r
+ interp->referenceNextId++;\r
+ /* Set the tag. Trimmered at JIM_REFERENCE_TAGLEN. Everything\r
+ * that does not pass the 'isrefchar' test is replaced with '_' */\r
+ tag = Jim_GetString(tagPtr, &tagLen);\r
+ if (tagLen > JIM_REFERENCE_TAGLEN)\r
+ tagLen = JIM_REFERENCE_TAGLEN;\r
+ for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {\r
+ if (i < tagLen)\r
+ refPtr->tag[i] = tag[i];\r
+ else\r
+ refPtr->tag[i] = '_';\r
+ }\r
+ refPtr->tag[JIM_REFERENCE_TAGLEN] = '\0';\r
+ return refObjPtr;\r
+}\r
+\r
+Jim_Reference *Jim_GetReference(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ if (objPtr->typePtr != &referenceObjType &&\r
+ SetReferenceFromAny(interp, objPtr) == JIM_ERR)\r
+ return NULL;\r
+ return objPtr->internalRep.refValue.refPtr;\r
+}\r
+\r
+int Jim_SetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr)\r
+{\r
+ Jim_Reference *refPtr;\r
+\r
+ if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)\r
+ return JIM_ERR;\r
+ Jim_IncrRefCount(cmdNamePtr);\r
+ if (refPtr->finalizerCmdNamePtr)\r
+ Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);\r
+ refPtr->finalizerCmdNamePtr = cmdNamePtr;\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_GetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr)\r
+{\r
+ Jim_Reference *refPtr;\r
+\r
+ if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)\r
+ return JIM_ERR;\r
+ *cmdNamePtrPtr = refPtr->finalizerCmdNamePtr;\r
+ return JIM_OK;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * References Garbage Collection\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* This the hash table type for the "MARK" phase of the GC */\r
+static Jim_HashTableType JimRefMarkHashTableType = {\r
+ JimReferencesHTHashFunction, /* hash function */\r
+ JimReferencesHTKeyDup, /* key dup */\r
+ NULL, /* val dup */\r
+ JimReferencesHTKeyCompare, /* key compare */\r
+ JimReferencesHTKeyDestructor, /* key destructor */\r
+ NULL /* val destructor */\r
+};\r
+\r
+/* #define JIM_DEBUG_GC 1 */\r
+\r
+/* Performs the garbage collection. */\r
+int Jim_Collect(Jim_Interp *interp)\r
+{\r
+ Jim_HashTable marks;\r
+ Jim_HashTableIterator *htiter;\r
+ Jim_HashEntry *he;\r
+ Jim_Obj *objPtr;\r
+ int collected = 0;\r
+\r
+ /* Avoid recursive calls */\r
+ if (interp->lastCollectId == -1) {\r
+ /* Jim_Collect() already running. Return just now. */\r
+ return 0;\r
+ }\r
+ interp->lastCollectId = -1;\r
+\r
+ /* Mark all the references found into the 'mark' hash table.\r
+ * The references are searched in every live object that\r
+ * is of a type that can contain references. */\r
+ Jim_InitHashTable(&marks, &JimRefMarkHashTableType, NULL);\r
+ objPtr = interp->liveList;\r
+ while(objPtr) {\r
+ if (objPtr->typePtr == NULL ||\r
+ objPtr->typePtr->flags & JIM_TYPE_REFERENCES) {\r
+ const char *str, *p;\r
+ int len;\r
+\r
+ /* If the object is of type reference, to get the\r
+ * Id is simple... */\r
+ if (objPtr->typePtr == &referenceObjType) {\r
+ Jim_AddHashEntry(&marks,\r
+ &objPtr->internalRep.refValue.id, NULL);\r
+#ifdef JIM_DEBUG_GC\r
+ fprintf(interp->stdout_,\r
+ "MARK (reference): %d refcount: %d" JIM_NL, \r
+ (int) objPtr->internalRep.refValue.id,\r
+ objPtr->refCount);\r
+#endif\r
+ objPtr = objPtr->nextObjPtr;\r
+ continue;\r
+ }\r
+ /* Get the string repr of the object we want\r
+ * to scan for references. */\r
+ p = str = Jim_GetString(objPtr, &len);\r
+ /* Skip objects too little to contain references. */\r
+ if (len < JIM_REFERENCE_SPACE) {\r
+ objPtr = objPtr->nextObjPtr;\r
+ continue;\r
+ }\r
+ /* Extract references from the object string repr. */\r
+ while(1) {\r
+ int i;\r
+ jim_wide id;\r
+ char buf[21];\r
+\r
+ if ((p = strstr(p, "<reference.<")) == NULL)\r
+ break;\r
+ /* Check if it's a valid reference. */\r
+ if (len-(p-str) < JIM_REFERENCE_SPACE) break;\r
+ if (p[41] != '>' || p[19] != '>' || p[20] != '.') break;\r
+ for (i = 21; i <= 40; i++)\r
+ if (!isdigit((int)p[i]))\r
+ break;\r
+ /* Get the ID */\r
+ memcpy(buf, p+21, 20);\r
+ buf[20] = '\0';\r
+ Jim_StringToWide(buf, &id, 10);\r
+\r
+ /* Ok, a reference for the given ID\r
+ * was found. Mark it. */\r
+ Jim_AddHashEntry(&marks, &id, NULL);\r
+#ifdef JIM_DEBUG_GC\r
+ fprintf(interp->stdout_,"MARK: %d" JIM_NL, (int)id);\r
+#endif\r
+ p += JIM_REFERENCE_SPACE;\r
+ }\r
+ }\r
+ objPtr = objPtr->nextObjPtr;\r
+ }\r
+\r
+ /* Run the references hash table to destroy every reference that\r
+ * is not referenced outside (not present in the mark HT). */\r
+ htiter = Jim_GetHashTableIterator(&interp->references);\r
+ while ((he = Jim_NextHashEntry(htiter)) != NULL) {\r
+ const jim_wide *refId;\r
+ Jim_Reference *refPtr;\r
+\r
+ refId = he->key;\r
+ /* Check if in the mark phase we encountered\r
+ * this reference. */\r
+ if (Jim_FindHashEntry(&marks, refId) == NULL) {\r
+#ifdef JIM_DEBUG_GC\r
+ fprintf(interp->stdout_,"COLLECTING %d" JIM_NL, (int)*refId);\r
+#endif\r
+ collected++;\r
+ /* Drop the reference, but call the\r
+ * finalizer first if registered. */\r
+ refPtr = he->val;\r
+ if (refPtr->finalizerCmdNamePtr) {\r
+ char *refstr = Jim_Alloc(JIM_REFERENCE_SPACE+1);\r
+ Jim_Obj *objv[3], *oldResult;\r
+\r
+ JimFormatReference(refstr, refPtr, *refId);\r
+\r
+ objv[0] = refPtr->finalizerCmdNamePtr;\r
+ objv[1] = Jim_NewStringObjNoAlloc(interp,\r
+ refstr, 32);\r
+ objv[2] = refPtr->objPtr;\r
+ Jim_IncrRefCount(objv[0]);\r
+ Jim_IncrRefCount(objv[1]);\r
+ Jim_IncrRefCount(objv[2]);\r
+\r
+ /* Drop the reference itself */\r
+ Jim_DeleteHashEntry(&interp->references, refId);\r
+\r
+ /* Call the finalizer. Errors ignored. */\r
+ oldResult = interp->result;\r
+ Jim_IncrRefCount(oldResult);\r
+ Jim_EvalObjVector(interp, 3, objv);\r
+ Jim_SetResult(interp, oldResult);\r
+ Jim_DecrRefCount(interp, oldResult);\r
+\r
+ Jim_DecrRefCount(interp, objv[0]);\r
+ Jim_DecrRefCount(interp, objv[1]);\r
+ Jim_DecrRefCount(interp, objv[2]);\r
+ } else {\r
+ Jim_DeleteHashEntry(&interp->references, refId);\r
+ }\r
+ }\r
+ }\r
+ Jim_FreeHashTableIterator(htiter);\r
+ Jim_FreeHashTable(&marks);\r
+ interp->lastCollectId = interp->referenceNextId;\r
+ interp->lastCollectTime = time(NULL);\r
+ return collected;\r
+}\r
+\r
+#define JIM_COLLECT_ID_PERIOD 5000\r
+#define JIM_COLLECT_TIME_PERIOD 300\r
+\r
+void Jim_CollectIfNeeded(Jim_Interp *interp)\r
+{\r
+ jim_wide elapsedId;\r
+ int elapsedTime;\r
+ \r
+ elapsedId = interp->referenceNextId - interp->lastCollectId;\r
+ elapsedTime = time(NULL) - interp->lastCollectTime;\r
+\r
+\r
+ if (elapsedId > JIM_COLLECT_ID_PERIOD ||\r
+ elapsedTime > JIM_COLLECT_TIME_PERIOD) {\r
+ Jim_Collect(interp);\r
+ }\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Interpreter related functions\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+Jim_Interp *Jim_CreateInterp(void)\r
+{\r
+ Jim_Interp *i = Jim_Alloc(sizeof(*i));\r
+ Jim_Obj *pathPtr;\r
+\r
+ i->errorLine = 0;\r
+ i->errorFileName = Jim_StrDup("");\r
+ i->numLevels = 0;\r
+ i->maxNestingDepth = JIM_MAX_NESTING_DEPTH;\r
+ i->returnCode = JIM_OK;\r
+ i->exitCode = 0;\r
+ i->procEpoch = 0;\r
+ i->callFrameEpoch = 0;\r
+ i->liveList = i->freeList = NULL;\r
+ i->scriptFileName = Jim_StrDup("");\r
+ i->referenceNextId = 0;\r
+ i->lastCollectId = 0;\r
+ i->lastCollectTime = time(NULL);\r
+ i->freeFramesList = NULL;\r
+ i->prngState = NULL;\r
+ i->evalRetcodeLevel = -1;\r
+ i->stdin_ = stdin;\r
+ i->stdout_ = stdout;\r
+ i->stderr_ = stderr;\r
+\r
+ /* Note that we can create objects only after the\r
+ * interpreter liveList and freeList pointers are\r
+ * initialized to NULL. */\r
+ Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);\r
+ Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);\r
+ Jim_InitHashTable(&i->sharedStrings, &JimSharedStringsHashTableType,\r
+ NULL);\r
+ Jim_InitHashTable(&i->stub, &JimStringCopyHashTableType, NULL);\r
+ Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);\r
+ Jim_InitHashTable(&i->packages, &JimStringKeyValCopyHashTableType, NULL);\r
+ i->framePtr = i->topFramePtr = JimCreateCallFrame(i);\r
+ i->emptyObj = Jim_NewEmptyStringObj(i);\r
+ i->result = i->emptyObj;\r
+ i->stackTrace = Jim_NewListObj(i, NULL, 0);\r
+ i->unknown = Jim_NewStringObj(i, "unknown", -1);\r
+ Jim_IncrRefCount(i->emptyObj);\r
+ Jim_IncrRefCount(i->result);\r
+ Jim_IncrRefCount(i->stackTrace);\r
+ Jim_IncrRefCount(i->unknown);\r
+\r
+ /* Initialize key variables every interpreter should contain */\r
+ pathPtr = Jim_NewStringObj(i, "./", -1);\r
+ Jim_SetVariableStr(i, "jim_libpath", pathPtr);\r
+ Jim_SetVariableStrWithStr(i, "jim_interactive", "0");\r
+\r
+ /* Export the core API to extensions */\r
+ JimRegisterCoreApi(i);\r
+ return i;\r
+}\r
+\r
+/* This is the only function Jim exports directly without\r
+ * to use the STUB system. It is only used by embedders\r
+ * in order to get an interpreter with the Jim API pointers\r
+ * registered. */\r
+Jim_Interp *ExportedJimCreateInterp(void)\r
+{\r
+ return Jim_CreateInterp();\r
+}\r
+\r
+void Jim_FreeInterp(Jim_Interp *i)\r
+{\r
+ Jim_CallFrame *cf = i->framePtr, *prevcf, *nextcf;\r
+ Jim_Obj *objPtr, *nextObjPtr;\r
+\r
+ Jim_DecrRefCount(i, i->emptyObj);\r
+ Jim_DecrRefCount(i, i->result);\r
+ Jim_DecrRefCount(i, i->stackTrace);\r
+ Jim_DecrRefCount(i, i->unknown);\r
+ Jim_Free((void*)i->errorFileName);\r
+ Jim_Free((void*)i->scriptFileName);\r
+ Jim_FreeHashTable(&i->commands);\r
+ Jim_FreeHashTable(&i->references);\r
+ Jim_FreeHashTable(&i->stub);\r
+ Jim_FreeHashTable(&i->assocData);\r
+ Jim_FreeHashTable(&i->packages);\r
+ Jim_Free(i->prngState);\r
+ /* Free the call frames list */\r
+ while(cf) {\r
+ prevcf = cf->parentCallFrame;\r
+ JimFreeCallFrame(i, cf, JIM_FCF_NONE);\r
+ cf = prevcf;\r
+ }\r
+ /* Check that the live object list is empty, otherwise\r
+ * there is a memory leak. */\r
+ if (i->liveList != NULL) {\r
+ Jim_Obj *objPtr = i->liveList;\r
+ \r
+ fprintf(i->stdout_,JIM_NL "-------------------------------------" JIM_NL);\r
+ fprintf(i->stdout_,"Objects still in the free list:" JIM_NL);\r
+ while(objPtr) {\r
+ const char *type = objPtr->typePtr ?\r
+ objPtr->typePtr->name : "";\r
+ fprintf(i->stdout_,"%p \"%-10s\": '%.20s' (refCount: %d)" JIM_NL,\r
+ objPtr, type,\r
+ objPtr->bytes ? objPtr->bytes\r
+ : "(null)", objPtr->refCount);\r
+ if (objPtr->typePtr == &sourceObjType) {\r
+ fprintf(i->stdout_, "FILE %s LINE %d" JIM_NL,\r
+ objPtr->internalRep.sourceValue.fileName,\r
+ objPtr->internalRep.sourceValue.lineNumber);\r
+ }\r
+ objPtr = objPtr->nextObjPtr;\r
+ }\r
+ fprintf(stdout, "-------------------------------------" JIM_NL JIM_NL);\r
+ Jim_Panic(i,"Live list non empty freeing the interpreter! Leak?");\r
+ }\r
+ /* Free all the freed objects. */\r
+ objPtr = i->freeList;\r
+ while (objPtr) {\r
+ nextObjPtr = objPtr->nextObjPtr;\r
+ Jim_Free(objPtr);\r
+ objPtr = nextObjPtr;\r
+ }\r
+ /* Free cached CallFrame structures */\r
+ cf = i->freeFramesList;\r
+ while(cf) {\r
+ nextcf = cf->nextFramePtr;\r
+ if (cf->vars.table != NULL)\r
+ Jim_Free(cf->vars.table);\r
+ Jim_Free(cf);\r
+ cf = nextcf;\r
+ }\r
+ /* Free the sharedString hash table. Make sure to free it\r
+ * after every other Jim_Object was freed. */\r
+ Jim_FreeHashTable(&i->sharedStrings);\r
+ /* Free the interpreter structure. */\r
+ Jim_Free(i);\r
+}\r
+\r
+/* Store the call frame relative to the level represented by\r
+ * levelObjPtr into *framePtrPtr. If levelObjPtr == NULL, the\r
+ * level is assumed to be '1'.\r
+ *\r
+ * If a newLevelptr int pointer is specified, the function stores\r
+ * the absolute level integer value of the new target callframe into\r
+ * *newLevelPtr. (this is used to adjust interp->numLevels\r
+ * in the implementation of [uplevel], so that [info level] will\r
+ * return a correct information).\r
+ *\r
+ * This function accepts the 'level' argument in the form\r
+ * of the commands [uplevel] and [upvar].\r
+ *\r
+ * For a function accepting a relative integer as level suitable\r
+ * for implementation of [info level ?level?] check the\r
+ * GetCallFrameByInteger() function. */\r
+int Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,\r
+ Jim_CallFrame **framePtrPtr, int *newLevelPtr)\r
+{\r
+ long level;\r
+ const char *str;\r
+ Jim_CallFrame *framePtr;\r
+\r
+ if (newLevelPtr) *newLevelPtr = interp->numLevels;\r
+ if (levelObjPtr) {\r
+ str = Jim_GetString(levelObjPtr, NULL);\r
+ if (str[0] == '#') {\r
+ char *endptr;\r
+ /* speedup for the toplevel (level #0) */\r
+ if (str[1] == '0' && str[2] == '\0') {\r
+ if (newLevelPtr) *newLevelPtr = 0;\r
+ *framePtrPtr = interp->topFramePtr;\r
+ return JIM_OK;\r
+ }\r
+\r
+ level = strtol(str+1, &endptr, 0);\r
+ if (str[1] == '\0' || endptr[0] != '\0' || level < 0)\r
+ goto badlevel;\r
+ /* An 'absolute' level is converted into the\r
+ * 'number of levels to go back' format. */\r
+ level = interp->numLevels - level;\r
+ if (level < 0) goto badlevel;\r
+ } else {\r
+ if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0)\r
+ goto badlevel;\r
+ }\r
+ } else {\r
+ str = "1"; /* Needed to format the error message. */\r
+ level = 1;\r
+ }\r
+ /* Lookup */\r
+ framePtr = interp->framePtr;\r
+ if (newLevelPtr) *newLevelPtr = (*newLevelPtr)-level;\r
+ while (level--) {\r
+ framePtr = framePtr->parentCallFrame;\r
+ if (framePtr == NULL) goto badlevel;\r
+ }\r
+ *framePtrPtr = framePtr;\r
+ return JIM_OK;\r
+badlevel:\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad level \"", str, "\"", NULL);\r
+ return JIM_ERR;\r
+}\r
+\r
+/* Similar to Jim_GetCallFrameByLevel() but the level is specified\r
+ * as a relative integer like in the [info level ?level?] command. */\r
+static int JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr,\r
+ Jim_CallFrame **framePtrPtr)\r
+{\r
+ jim_wide level;\r
+ jim_wide relLevel; /* level relative to the current one. */\r
+ Jim_CallFrame *framePtr;\r
+\r
+ if (Jim_GetWide(interp, levelObjPtr, &level) != JIM_OK)\r
+ goto badlevel;\r
+ if (level > 0) {\r
+ /* An 'absolute' level is converted into the\r
+ * 'number of levels to go back' format. */\r
+ relLevel = interp->numLevels - level;\r
+ } else {\r
+ relLevel = -level;\r
+ }\r
+ /* Lookup */\r
+ framePtr = interp->framePtr;\r
+ while (relLevel--) {\r
+ framePtr = framePtr->parentCallFrame;\r
+ if (framePtr == NULL) goto badlevel;\r
+ }\r
+ *framePtrPtr = framePtr;\r
+ return JIM_OK;\r
+badlevel:\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad level \"", Jim_GetString(levelObjPtr, NULL), "\"", NULL);\r
+ return JIM_ERR;\r
+}\r
+\r
+static void JimSetErrorFileName(Jim_Interp *interp, char *filename)\r
+{\r
+ Jim_Free((void*)interp->errorFileName);\r
+ interp->errorFileName = Jim_StrDup(filename);\r
+}\r
+\r
+static void JimSetErrorLineNumber(Jim_Interp *interp, int linenr)\r
+{\r
+ interp->errorLine = linenr;\r
+}\r
+\r
+static void JimResetStackTrace(Jim_Interp *interp)\r
+{\r
+ Jim_DecrRefCount(interp, interp->stackTrace);\r
+ interp->stackTrace = Jim_NewListObj(interp, NULL, 0);\r
+ Jim_IncrRefCount(interp->stackTrace);\r
+}\r
+\r
+static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,\r
+ const char *filename, int linenr)\r
+{\r
+ if (Jim_IsShared(interp->stackTrace)) {\r
+ interp->stackTrace =\r
+ Jim_DuplicateObj(interp, interp->stackTrace);\r
+ Jim_IncrRefCount(interp->stackTrace);\r
+ }\r
+ Jim_ListAppendElement(interp, interp->stackTrace,\r
+ Jim_NewStringObj(interp, procname, -1));\r
+ Jim_ListAppendElement(interp, interp->stackTrace,\r
+ Jim_NewStringObj(interp, filename, -1));\r
+ Jim_ListAppendElement(interp, interp->stackTrace,\r
+ Jim_NewIntObj(interp, linenr));\r
+}\r
+\r
+int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc *delProc, void *data)\r
+{\r
+ AssocDataValue *assocEntryPtr = (AssocDataValue *)Jim_Alloc(sizeof(AssocDataValue));\r
+ assocEntryPtr->delProc = delProc;\r
+ assocEntryPtr->data = data;\r
+ return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);\r
+}\r
+\r
+void *Jim_GetAssocData(Jim_Interp *interp, const char *key)\r
+{\r
+ Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);\r
+ if (entryPtr != NULL) {\r
+ AssocDataValue *assocEntryPtr = (AssocDataValue *)entryPtr->val;\r
+ return assocEntryPtr->data;\r
+ }\r
+ return NULL;\r
+}\r
+\r
+int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)\r
+{\r
+ return Jim_DeleteHashEntry(&interp->assocData, key);\r
+}\r
+\r
+int Jim_GetExitCode(Jim_Interp *interp) {\r
+ return interp->exitCode;\r
+}\r
+\r
+FILE *Jim_SetStdin(Jim_Interp *interp, FILE *fp)\r
+{\r
+ if (fp != NULL) interp->stdin_ = fp;\r
+ return interp->stdin_;\r
+}\r
+\r
+FILE *Jim_SetStdout(Jim_Interp *interp, FILE *fp)\r
+{\r
+ if (fp != NULL) interp->stdout_ = fp;\r
+ return interp->stdout_;\r
+}\r
+\r
+FILE *Jim_SetStderr(Jim_Interp *interp, FILE *fp)\r
+{\r
+ if (fp != NULL) interp->stderr_ = fp;\r
+ return interp->stderr_;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Shared strings.\r
+ * Every interpreter has an hash table where to put shared dynamically\r
+ * allocate strings that are likely to be used a lot of times.\r
+ * For example, in the 'source' object type, there is a pointer to\r
+ * the filename associated with that object. Every script has a lot\r
+ * of this objects with the identical file name, so it is wise to share\r
+ * this info.\r
+ *\r
+ * The API is trivial: Jim_GetSharedString(interp, "foobar")\r
+ * returns the pointer to the shared string. Every time a reference\r
+ * to the string is no longer used, the user should call\r
+ * Jim_ReleaseSharedString(interp, stringPointer). Once no one is using\r
+ * a given string, it is removed from the hash table.\r
+ * ---------------------------------------------------------------------------*/\r
+const char *Jim_GetSharedString(Jim_Interp *interp, const char *str)\r
+{\r
+ Jim_HashEntry *he = Jim_FindHashEntry(&interp->sharedStrings, str);\r
+\r
+ if (he == NULL) {\r
+ char *strCopy = Jim_StrDup(str);\r
+\r
+ Jim_AddHashEntry(&interp->sharedStrings, strCopy, (void*)1);\r
+ return strCopy;\r
+ } else {\r
+ long refCount = (long) he->val;\r
+\r
+ refCount++;\r
+ he->val = (void*) refCount;\r
+ return he->key;\r
+ }\r
+}\r
+\r
+void Jim_ReleaseSharedString(Jim_Interp *interp, const char *str)\r
+{\r
+ long refCount;\r
+ Jim_HashEntry *he = Jim_FindHashEntry(&interp->sharedStrings, str);\r
+\r
+ if (he == NULL)\r
+ Jim_Panic(interp,"Jim_ReleaseSharedString called with "\r
+ "unknown shared string '%s'", str);\r
+ refCount = (long) he->val;\r
+ refCount--;\r
+ if (refCount == 0) {\r
+ Jim_DeleteHashEntry(&interp->sharedStrings, str);\r
+ } else {\r
+ he->val = (void*) refCount;\r
+ }\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Integer object\r
+ * ---------------------------------------------------------------------------*/\r
+#define JIM_INTEGER_SPACE 24\r
+\r
+static void UpdateStringOfInt(struct Jim_Obj *objPtr);\r
+static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);\r
+\r
+static Jim_ObjType intObjType = {\r
+ "int",\r
+ NULL,\r
+ NULL,\r
+ UpdateStringOfInt,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+void UpdateStringOfInt(struct Jim_Obj *objPtr)\r
+{\r
+ int len;\r
+ char buf[JIM_INTEGER_SPACE+1];\r
+\r
+ len = Jim_WideToString(buf, objPtr->internalRep.wideValue);\r
+ objPtr->bytes = Jim_Alloc(len+1);\r
+ memcpy(objPtr->bytes, buf, len+1);\r
+ objPtr->length = len;\r
+}\r
+\r
+int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)\r
+{\r
+ jim_wide wideValue;\r
+ const char *str;\r
+\r
+ /* Get the string representation */\r
+ str = Jim_GetString(objPtr, NULL);\r
+ /* Try to convert into a jim_wide */\r
+ if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "expected integer but got \"", str, "\"", NULL);\r
+ }\r
+ return JIM_ERR;\r
+ }\r
+ if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) &&\r
+ errno == ERANGE) {\r
+ Jim_SetResultString(interp,\r
+ "Integer value too big to be represented", -1);\r
+ return JIM_ERR;\r
+ }\r
+ /* Free the old internal repr and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &intObjType;\r
+ objPtr->internalRep.wideValue = wideValue;\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide *widePtr)\r
+{\r
+ if (objPtr->typePtr != &intObjType &&\r
+ SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)\r
+ return JIM_ERR;\r
+ *widePtr = objPtr->internalRep.wideValue;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Get a wide but does not set an error if the format is bad. */\r
+static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ jim_wide *widePtr)\r
+{\r
+ if (objPtr->typePtr != &intObjType &&\r
+ SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)\r
+ return JIM_ERR;\r
+ *widePtr = objPtr->internalRep.wideValue;\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)\r
+{\r
+ jim_wide wideValue;\r
+ int retval;\r
+\r
+ retval = Jim_GetWide(interp, objPtr, &wideValue);\r
+ if (retval == JIM_OK) {\r
+ *longPtr = (long) wideValue;\r
+ return JIM_OK;\r
+ }\r
+ return JIM_ERR;\r
+}\r
+\r
+void Jim_SetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide wideValue)\r
+{\r
+ if (Jim_IsShared(objPtr))\r
+ Jim_Panic(interp,"Jim_SetWide called with shared object");\r
+ if (objPtr->typePtr != &intObjType) {\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &intObjType;\r
+ }\r
+ Jim_InvalidateStringRep(objPtr);\r
+ objPtr->internalRep.wideValue = wideValue;\r
+}\r
+\r
+Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)\r
+{\r
+ Jim_Obj *objPtr;\r
+\r
+ objPtr = Jim_NewObj(interp);\r
+ objPtr->typePtr = &intObjType;\r
+ objPtr->bytes = NULL;\r
+ objPtr->internalRep.wideValue = wideValue;\r
+ return objPtr;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Double object\r
+ * ---------------------------------------------------------------------------*/\r
+#define JIM_DOUBLE_SPACE 30\r
+\r
+static void UpdateStringOfDouble(struct Jim_Obj *objPtr);\r
+static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType doubleObjType = {\r
+ "double",\r
+ NULL,\r
+ NULL,\r
+ UpdateStringOfDouble,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+void UpdateStringOfDouble(struct Jim_Obj *objPtr)\r
+{\r
+ int len;\r
+ char buf[JIM_DOUBLE_SPACE+1];\r
+\r
+ len = Jim_DoubleToString(buf, objPtr->internalRep.doubleValue);\r
+ objPtr->bytes = Jim_Alloc(len+1);\r
+ memcpy(objPtr->bytes, buf, len+1);\r
+ objPtr->length = len;\r
+}\r
+\r
+int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ double doubleValue;\r
+ const char *str;\r
+\r
+ /* Get the string representation */\r
+ str = Jim_GetString(objPtr, NULL);\r
+ /* Try to convert into a double */\r
+ if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "expected number but got '", str, "'", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ /* Free the old internal repr and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &doubleObjType;\r
+ objPtr->internalRep.doubleValue = doubleValue;\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)\r
+{\r
+ if (objPtr->typePtr != &doubleObjType &&\r
+ SetDoubleFromAny(interp, objPtr) == JIM_ERR)\r
+ return JIM_ERR;\r
+ *doublePtr = objPtr->internalRep.doubleValue;\r
+ return JIM_OK;\r
+}\r
+\r
+void Jim_SetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double doubleValue)\r
+{\r
+ if (Jim_IsShared(objPtr))\r
+ Jim_Panic(interp,"Jim_SetDouble called with shared object");\r
+ if (objPtr->typePtr != &doubleObjType) {\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &doubleObjType;\r
+ }\r
+ Jim_InvalidateStringRep(objPtr);\r
+ objPtr->internalRep.doubleValue = doubleValue;\r
+}\r
+\r
+Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)\r
+{\r
+ Jim_Obj *objPtr;\r
+\r
+ objPtr = Jim_NewObj(interp);\r
+ objPtr->typePtr = &doubleObjType;\r
+ objPtr->bytes = NULL;\r
+ objPtr->internalRep.doubleValue = doubleValue;\r
+ return objPtr;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * List object\r
+ * ---------------------------------------------------------------------------*/\r
+static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);\r
+static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);\r
+static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);\r
+static void UpdateStringOfList(struct Jim_Obj *objPtr);\r
+static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+/* Note that while the elements of the list may contain references,\r
+ * the list object itself can't. This basically means that the\r
+ * list object string representation as a whole can't contain references\r
+ * that are not presents in the single elements. */\r
+static Jim_ObjType listObjType = {\r
+ "list",\r
+ FreeListInternalRep,\r
+ DupListInternalRep,\r
+ UpdateStringOfList,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ int i;\r
+\r
+ for (i = 0; i < objPtr->internalRep.listValue.len; i++) {\r
+ Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);\r
+ }\r
+ Jim_Free(objPtr->internalRep.listValue.ele);\r
+}\r
+\r
+void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)\r
+{\r
+ int i;\r
+ JIM_NOTUSED(interp);\r
+\r
+ dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;\r
+ dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;\r
+ dupPtr->internalRep.listValue.ele =\r
+ Jim_Alloc(sizeof(Jim_Obj*)*srcPtr->internalRep.listValue.maxLen);\r
+ memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,\r
+ sizeof(Jim_Obj*)*srcPtr->internalRep.listValue.len);\r
+ for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {\r
+ Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);\r
+ }\r
+ dupPtr->typePtr = &listObjType;\r
+}\r
+\r
+/* The following function checks if a given string can be encoded\r
+ * into a list element without any kind of quoting, surrounded by braces,\r
+ * or using escapes to quote. */\r
+#define JIM_ELESTR_SIMPLE 0\r
+#define JIM_ELESTR_BRACE 1\r
+#define JIM_ELESTR_QUOTE 2\r
+static int ListElementQuotingType(const char *s, int len)\r
+{\r
+ int i, level, trySimple = 1;\r
+\r
+ /* Try with the SIMPLE case */\r
+ if (len == 0) return JIM_ELESTR_BRACE;\r
+ if (s[0] == '"' || s[0] == '{') {\r
+ trySimple = 0;\r
+ goto testbrace;\r
+ }\r
+ for (i = 0; i < len; i++) {\r
+ switch(s[i]) {\r
+ case ' ':\r
+ case '$':\r
+ case '"':\r
+ case '[':\r
+ case ']':\r
+ case ';':\r
+ case '\\':\r
+ case '\r':\r
+ case '\n':\r
+ case '\t':\r
+ case '\f':\r
+ case '\v':\r
+ trySimple = 0;\r
+ case '{':\r
+ case '}':\r
+ goto testbrace;\r
+ }\r
+ }\r
+ return JIM_ELESTR_SIMPLE;\r
+\r
+testbrace:\r
+ /* Test if it's possible to do with braces */\r
+ if (s[len-1] == '\\' ||\r
+ s[len-1] == ']') return JIM_ELESTR_QUOTE;\r
+ level = 0;\r
+ for (i = 0; i < len; i++) {\r
+ switch(s[i]) {\r
+ case '{': level++; break;\r
+ case '}': level--;\r
+ if (level < 0) return JIM_ELESTR_QUOTE;\r
+ break;\r
+ case '\\':\r
+ if (s[i+1] == '\n')\r
+ return JIM_ELESTR_QUOTE;\r
+ else\r
+ if (s[i+1] != '\0') i++;\r
+ break;\r
+ }\r
+ }\r
+ if (level == 0) {\r
+ if (!trySimple) return JIM_ELESTR_BRACE;\r
+ for (i = 0; i < len; i++) {\r
+ switch(s[i]) {\r
+ case ' ':\r
+ case '$':\r
+ case '"':\r
+ case '[':\r
+ case ']':\r
+ case ';':\r
+ case '\\':\r
+ case '\r':\r
+ case '\n':\r
+ case '\t':\r
+ case '\f':\r
+ case '\v':\r
+ return JIM_ELESTR_BRACE;\r
+ break;\r
+ }\r
+ }\r
+ return JIM_ELESTR_SIMPLE;\r
+ }\r
+ return JIM_ELESTR_QUOTE;\r
+}\r
+\r
+/* Returns the malloc-ed representation of a string\r
+ * using backslash to quote special chars. */\r
+char *BackslashQuoteString(const char *s, int len, int *qlenPtr)\r
+{\r
+ char *q = Jim_Alloc(len*2+1), *p;\r
+\r
+ p = q;\r
+ while(*s) {\r
+ switch (*s) {\r
+ case ' ':\r
+ case '$':\r
+ case '"':\r
+ case '[':\r
+ case ']':\r
+ case '{':\r
+ case '}':\r
+ case ';':\r
+ case '\\':\r
+ *p++ = '\\';\r
+ *p++ = *s++;\r
+ break;\r
+ case '\n': *p++ = '\\'; *p++ = 'n'; s++; break;\r
+ case '\r': *p++ = '\\'; *p++ = 'r'; s++; break;\r
+ case '\t': *p++ = '\\'; *p++ = 't'; s++; break;\r
+ case '\f': *p++ = '\\'; *p++ = 'f'; s++; break;\r
+ case '\v': *p++ = '\\'; *p++ = 'v'; s++; break;\r
+ default:\r
+ *p++ = *s++;\r
+ break;\r
+ }\r
+ }\r
+ *p = '\0';\r
+ *qlenPtr = p-q;\r
+ return q;\r
+}\r
+\r
+void UpdateStringOfList(struct Jim_Obj *objPtr)\r
+{\r
+ int i, bufLen, realLength;\r
+ const char *strRep;\r
+ char *p;\r
+ int *quotingType;\r
+ Jim_Obj **ele = objPtr->internalRep.listValue.ele;\r
+\r
+ /* (Over) Estimate the space needed. */\r
+ quotingType = Jim_Alloc(sizeof(int)*objPtr->internalRep.listValue.len+1);\r
+ bufLen = 0;\r
+ for (i = 0; i < objPtr->internalRep.listValue.len; i++) {\r
+ int len;\r
+\r
+ strRep = Jim_GetString(ele[i], &len);\r
+ quotingType[i] = ListElementQuotingType(strRep, len);\r
+ switch (quotingType[i]) {\r
+ case JIM_ELESTR_SIMPLE: bufLen += len; break;\r
+ case JIM_ELESTR_BRACE: bufLen += len+2; break;\r
+ case JIM_ELESTR_QUOTE: bufLen += len*2; break;\r
+ }\r
+ bufLen++; /* elements separator. */\r
+ }\r
+ bufLen++;\r
+\r
+ /* Generate the string rep. */\r
+ p = objPtr->bytes = Jim_Alloc(bufLen+1);\r
+ realLength = 0;\r
+ for (i = 0; i < objPtr->internalRep.listValue.len; i++) {\r
+ int len, qlen;\r
+ const char *strRep = Jim_GetString(ele[i], &len);\r
+ char *q;\r
+\r
+ switch(quotingType[i]) {\r
+ case JIM_ELESTR_SIMPLE:\r
+ memcpy(p, strRep, len);\r
+ p += len;\r
+ realLength += len;\r
+ break;\r
+ case JIM_ELESTR_BRACE:\r
+ *p++ = '{';\r
+ memcpy(p, strRep, len);\r
+ p += len;\r
+ *p++ = '}';\r
+ realLength += len+2;\r
+ break;\r
+ case JIM_ELESTR_QUOTE:\r
+ q = BackslashQuoteString(strRep, len, &qlen);\r
+ memcpy(p, q, qlen);\r
+ Jim_Free(q);\r
+ p += qlen;\r
+ realLength += qlen;\r
+ break;\r
+ }\r
+ /* Add a separating space */\r
+ if (i+1 != objPtr->internalRep.listValue.len) {\r
+ *p++ = ' ';\r
+ realLength ++;\r
+ }\r
+ }\r
+ *p = '\0'; /* nul term. */\r
+ objPtr->length = realLength;\r
+ Jim_Free(quotingType);\r
+}\r
+\r
+int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)\r
+{\r
+ struct JimParserCtx parser;\r
+ const char *str;\r
+ int strLen;\r
+\r
+ /* Get the string representation */\r
+ str = Jim_GetString(objPtr, &strLen);\r
+\r
+ /* Free the old internal repr just now and initialize the\r
+ * new one just now. The string->list conversion can't fail. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &listObjType;\r
+ objPtr->internalRep.listValue.len = 0;\r
+ objPtr->internalRep.listValue.maxLen = 0;\r
+ objPtr->internalRep.listValue.ele = NULL;\r
+\r
+ /* Convert into a list */\r
+ JimParserInit(&parser, str, strLen, 1);\r
+ while(!JimParserEof(&parser)) {\r
+ char *token;\r
+ int tokenLen, type;\r
+ Jim_Obj *elementPtr;\r
+\r
+ JimParseList(&parser);\r
+ if (JimParserTtype(&parser) != JIM_TT_STR &&\r
+ JimParserTtype(&parser) != JIM_TT_ESC)\r
+ continue;\r
+ token = JimParserGetToken(&parser, &tokenLen, &type, NULL);\r
+ elementPtr = Jim_NewStringObjNoAlloc(interp, token, tokenLen);\r
+ ListAppendElement(objPtr, elementPtr);\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, \r
+ int len)\r
+{\r
+ Jim_Obj *objPtr;\r
+ int i;\r
+\r
+ objPtr = Jim_NewObj(interp);\r
+ objPtr->typePtr = &listObjType;\r
+ objPtr->bytes = NULL;\r
+ objPtr->internalRep.listValue.ele = NULL;\r
+ objPtr->internalRep.listValue.len = 0;\r
+ objPtr->internalRep.listValue.maxLen = 0;\r
+ for (i = 0; i < len; i++) {\r
+ ListAppendElement(objPtr, elements[i]);\r
+ }\r
+ return objPtr;\r
+}\r
+\r
+/* Return a vector of Jim_Obj with the elements of a Jim list, and the\r
+ * length of the vector. Note that the user of this function should make\r
+ * sure that the list object can't shimmer while the vector returned\r
+ * is in use, this vector is the one stored inside the internal representation\r
+ * of the list object. This function is not exported, extensions should\r
+ * always access to the List object elements using Jim_ListIndex(). */\r
+static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *argc,\r
+ Jim_Obj ***listVec)\r
+{\r
+ Jim_ListLength(interp, listObj, argc);\r
+ assert(listObj->typePtr == &listObjType);\r
+ *listVec = listObj->internalRep.listValue.ele;\r
+}\r
+\r
+/* ListSortElements type values */\r
+enum {JIM_LSORT_ASCII, JIM_LSORT_NOCASE, JIM_LSORT_ASCII_DECR,\r
+ JIM_LSORT_NOCASE_DECR};\r
+\r
+/* Sort the internal rep of a list. */\r
+static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)\r
+{\r
+ return Jim_StringCompareObj(*lhsObj, *rhsObj, 0);\r
+}\r
+\r
+static int ListSortStringDecr(Jim_Obj **lhsObj, Jim_Obj **rhsObj)\r
+{\r
+ return Jim_StringCompareObj(*lhsObj, *rhsObj, 0) * -1;\r
+}\r
+\r
+static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)\r
+{\r
+ return Jim_StringCompareObj(*lhsObj, *rhsObj, 1);\r
+}\r
+\r
+static int ListSortStringNoCaseDecr(Jim_Obj **lhsObj, Jim_Obj **rhsObj)\r
+{\r
+ return Jim_StringCompareObj(*lhsObj, *rhsObj, 1) * -1;\r
+}\r
+\r
+/* Sort a list *in place*. MUST be called with non-shared objects. */\r
+static void ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, int type)\r
+{\r
+ typedef int (qsort_comparator)(const void *, const void *);\r
+ int (*fn)(Jim_Obj**, Jim_Obj**);\r
+ Jim_Obj **vector;\r
+ int len;\r
+\r
+ if (Jim_IsShared(listObjPtr))\r
+ Jim_Panic(interp,"Jim_ListSortElements called with shared object");\r
+ if (listObjPtr->typePtr != &listObjType)\r
+ SetListFromAny(interp, listObjPtr);\r
+\r
+ vector = listObjPtr->internalRep.listValue.ele;\r
+ len = listObjPtr->internalRep.listValue.len;\r
+ switch (type) {\r
+ case JIM_LSORT_ASCII: fn = ListSortString; break;\r
+ case JIM_LSORT_NOCASE: fn = ListSortStringNoCase; break;\r
+ case JIM_LSORT_ASCII_DECR: fn = ListSortStringDecr; break;\r
+ case JIM_LSORT_NOCASE_DECR: fn = ListSortStringNoCaseDecr; break;\r
+ default:\r
+ fn = NULL; /* avoid warning */\r
+ Jim_Panic(interp,"ListSort called with invalid sort type");\r
+ }\r
+ qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *)fn);\r
+ Jim_InvalidateStringRep(listObjPtr);\r
+}\r
+\r
+/* This is the low-level function to append an element to a list.\r
+ * The higher-level Jim_ListAppendElement() performs shared object\r
+ * check and invalidate the string repr. This version is used\r
+ * in the internals of the List Object and is not exported.\r
+ *\r
+ * NOTE: this function can be called only against objects\r
+ * with internal type of List. */\r
+void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)\r
+{\r
+ int requiredLen = listPtr->internalRep.listValue.len + 1;\r
+\r
+ if (requiredLen > listPtr->internalRep.listValue.maxLen) {\r
+ int maxLen = requiredLen * 2;\r
+\r
+ listPtr->internalRep.listValue.ele =\r
+ Jim_Realloc(listPtr->internalRep.listValue.ele,\r
+ sizeof(Jim_Obj*)*maxLen);\r
+ listPtr->internalRep.listValue.maxLen = maxLen;\r
+ }\r
+ listPtr->internalRep.listValue.ele[listPtr->internalRep.listValue.len] =\r
+ objPtr;\r
+ listPtr->internalRep.listValue.len ++;\r
+ Jim_IncrRefCount(objPtr);\r
+}\r
+\r
+/* This is the low-level function to insert elements into a list.\r
+ * The higher-level Jim_ListInsertElements() performs shared object\r
+ * check and invalidate the string repr. This version is used\r
+ * in the internals of the List Object and is not exported.\r
+ *\r
+ * NOTE: this function can be called only against objects\r
+ * with internal type of List. */\r
+void ListInsertElements(Jim_Obj *listPtr, int index, int elemc,\r
+ Jim_Obj *const *elemVec)\r
+{\r
+ int currentLen = listPtr->internalRep.listValue.len;\r
+ int requiredLen = currentLen + elemc;\r
+ int i;\r
+ Jim_Obj **point;\r
+\r
+ if (requiredLen > listPtr->internalRep.listValue.maxLen) {\r
+ int maxLen = requiredLen * 2;\r
+\r
+ listPtr->internalRep.listValue.ele =\r
+ Jim_Realloc(listPtr->internalRep.listValue.ele,\r
+ sizeof(Jim_Obj*)*maxLen);\r
+ listPtr->internalRep.listValue.maxLen = maxLen;\r
+ }\r
+ point = listPtr->internalRep.listValue.ele + index;\r
+ memmove(point+elemc, point, (currentLen-index) * sizeof(Jim_Obj*));\r
+ for (i=0; i < elemc; ++i) {\r
+ point[i] = elemVec[i];\r
+ Jim_IncrRefCount(point[i]);\r
+ }\r
+ listPtr->internalRep.listValue.len += elemc;\r
+}\r
+\r
+/* Appends every element of appendListPtr into listPtr.\r
+ * Both have to be of the list type. */\r
+void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)\r
+{\r
+ int i, oldLen = listPtr->internalRep.listValue.len;\r
+ int appendLen = appendListPtr->internalRep.listValue.len;\r
+ int requiredLen = oldLen + appendLen;\r
+\r
+ if (requiredLen > listPtr->internalRep.listValue.maxLen) {\r
+ int maxLen = requiredLen * 2;\r
+\r
+ listPtr->internalRep.listValue.ele =\r
+ Jim_Realloc(listPtr->internalRep.listValue.ele,\r
+ sizeof(Jim_Obj*)*maxLen);\r
+ listPtr->internalRep.listValue.maxLen = maxLen;\r
+ }\r
+ for (i = 0; i < appendLen; i++) {\r
+ Jim_Obj *objPtr = appendListPtr->internalRep.listValue.ele[i];\r
+ listPtr->internalRep.listValue.ele[oldLen+i] = objPtr;\r
+ Jim_IncrRefCount(objPtr);\r
+ }\r
+ listPtr->internalRep.listValue.len += appendLen;\r
+}\r
+\r
+void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)\r
+{\r
+ if (Jim_IsShared(listPtr))\r
+ Jim_Panic(interp,"Jim_ListAppendElement called with shared object");\r
+ if (listPtr->typePtr != &listObjType)\r
+ SetListFromAny(interp, listPtr);\r
+ Jim_InvalidateStringRep(listPtr);\r
+ ListAppendElement(listPtr, objPtr);\r
+}\r
+\r
+void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)\r
+{\r
+ if (Jim_IsShared(listPtr))\r
+ Jim_Panic(interp,"Jim_ListAppendList called with shared object");\r
+ if (listPtr->typePtr != &listObjType)\r
+ SetListFromAny(interp, listPtr);\r
+ Jim_InvalidateStringRep(listPtr);\r
+ ListAppendList(listPtr, appendListPtr);\r
+}\r
+\r
+void Jim_ListLength(Jim_Interp *interp, Jim_Obj *listPtr, int *intPtr)\r
+{\r
+ if (listPtr->typePtr != &listObjType)\r
+ SetListFromAny(interp, listPtr);\r
+ *intPtr = listPtr->internalRep.listValue.len;\r
+}\r
+\r
+void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int index,\r
+ int objc, Jim_Obj *const *objVec)\r
+{\r
+ if (Jim_IsShared(listPtr))\r
+ Jim_Panic(interp,"Jim_ListInsertElement called with shared object");\r
+ if (listPtr->typePtr != &listObjType)\r
+ SetListFromAny(interp, listPtr);\r
+ if (index >= 0 && index > listPtr->internalRep.listValue.len)\r
+ index = listPtr->internalRep.listValue.len;\r
+ else if (index < 0 ) \r
+ index = 0;\r
+ Jim_InvalidateStringRep(listPtr);\r
+ ListInsertElements(listPtr, index, objc, objVec);\r
+}\r
+\r
+int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int index,\r
+ Jim_Obj **objPtrPtr, int flags)\r
+{\r
+ if (listPtr->typePtr != &listObjType)\r
+ SetListFromAny(interp, listPtr);\r
+ if ((index >= 0 && index >= listPtr->internalRep.listValue.len) ||\r
+ (index < 0 && (-index-1) >= listPtr->internalRep.listValue.len)) {\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResultString(interp,\r
+ "list index out of range", -1);\r
+ }\r
+ return JIM_ERR;\r
+ }\r
+ if (index < 0)\r
+ index = listPtr->internalRep.listValue.len+index;\r
+ *objPtrPtr = listPtr->internalRep.listValue.ele[index];\r
+ return JIM_OK;\r
+}\r
+\r
+static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int index,\r
+ Jim_Obj *newObjPtr, int flags)\r
+{\r
+ if (listPtr->typePtr != &listObjType)\r
+ SetListFromAny(interp, listPtr);\r
+ if ((index >= 0 && index >= listPtr->internalRep.listValue.len) ||\r
+ (index < 0 && (-index-1) >= listPtr->internalRep.listValue.len)) {\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResultString(interp,\r
+ "list index out of range", -1);\r
+ }\r
+ return JIM_ERR;\r
+ }\r
+ if (index < 0)\r
+ index = listPtr->internalRep.listValue.len+index;\r
+ Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[index]);\r
+ listPtr->internalRep.listValue.ele[index] = newObjPtr;\r
+ Jim_IncrRefCount(newObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* Modify the list stored into the variable named 'varNamePtr'\r
+ * setting the element specified by the 'indexc' indexes objects in 'indexv',\r
+ * with the new element 'newObjptr'. */\r
+int Jim_SetListIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,\r
+ Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)\r
+{\r
+ Jim_Obj *varObjPtr, *objPtr, *listObjPtr;\r
+ int shared, i, index;\r
+\r
+ varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);\r
+ if (objPtr == NULL)\r
+ return JIM_ERR;\r
+ if ((shared = Jim_IsShared(objPtr)))\r
+ varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);\r
+ for (i = 0; i < indexc-1; i++) {\r
+ listObjPtr = objPtr;\r
+ if (Jim_GetIndex(interp, indexv[i], &index) != JIM_OK)\r
+ goto err;\r
+ if (Jim_ListIndex(interp, listObjPtr, index, &objPtr,\r
+ JIM_ERRMSG) != JIM_OK) {\r
+ goto err;\r
+ }\r
+ if (Jim_IsShared(objPtr)) {\r
+ objPtr = Jim_DuplicateObj(interp, objPtr);\r
+ ListSetIndex(interp, listObjPtr, index, objPtr, JIM_NONE);\r
+ }\r
+ Jim_InvalidateStringRep(listObjPtr);\r
+ }\r
+ if (Jim_GetIndex(interp, indexv[indexc-1], &index) != JIM_OK)\r
+ goto err;\r
+ if (ListSetIndex(interp, objPtr, index, newObjPtr, JIM_ERRMSG) == JIM_ERR)\r
+ goto err;\r
+ Jim_InvalidateStringRep(objPtr);\r
+ Jim_InvalidateStringRep(varObjPtr);\r
+ if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)\r
+ goto err;\r
+ Jim_SetResult(interp, varObjPtr);\r
+ return JIM_OK;\r
+err:\r
+ if (shared) {\r
+ Jim_FreeNewObj(interp, varObjPtr);\r
+ }\r
+ return JIM_ERR;\r
+}\r
+\r
+Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)\r
+{\r
+ int i;\r
+\r
+ /* If all the objects in objv are lists without string rep.\r
+ * it's possible to return a list as result, that's the\r
+ * concatenation of all the lists. */\r
+ for (i = 0; i < objc; i++) {\r
+ if (objv[i]->typePtr != &listObjType || objv[i]->bytes)\r
+ break;\r
+ }\r
+ if (i == objc) {\r
+ Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);\r
+ for (i = 0; i < objc; i++)\r
+ Jim_ListAppendList(interp, objPtr, objv[i]);\r
+ return objPtr;\r
+ } else {\r
+ /* Else... we have to glue strings together */\r
+ int len = 0, objLen;\r
+ char *bytes, *p;\r
+\r
+ /* Compute the length */\r
+ for (i = 0; i < objc; i++) {\r
+ Jim_GetString(objv[i], &objLen);\r
+ len += objLen;\r
+ }\r
+ if (objc) len += objc-1;\r
+ /* Create the string rep, and a stinrg object holding it. */\r
+ p = bytes = Jim_Alloc(len+1);\r
+ for (i = 0; i < objc; i++) {\r
+ const char *s = Jim_GetString(objv[i], &objLen);\r
+ while (objLen && (*s == ' ' || *s == '\t' || *s == '\n'))\r
+ {\r
+ s++; objLen--; len--;\r
+ }\r
+ while (objLen && (s[objLen-1] == ' ' ||\r
+ s[objLen-1] == '\n' || s[objLen-1] == '\t')) {\r
+ objLen--; len--;\r
+ }\r
+ memcpy(p, s, objLen);\r
+ p += objLen;\r
+ if (objLen && i+1 != objc) {\r
+ *p++ = ' ';\r
+ } else if (i+1 != objc) {\r
+ /* Drop the space calcuated for this\r
+ * element that is instead null. */\r
+ len--;\r
+ }\r
+ }\r
+ *p = '\0';\r
+ return Jim_NewStringObjNoAlloc(interp, bytes, len);\r
+ }\r
+}\r
+\r
+/* Returns a list composed of the elements in the specified range.\r
+ * first and start are directly accepted as Jim_Objects and\r
+ * processed for the end?-index? case. */\r
+Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)\r
+{\r
+ int first, last;\r
+ int len, rangeLen;\r
+\r
+ if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||\r
+ Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)\r
+ return NULL;\r
+ Jim_ListLength(interp, listObjPtr, &len); /* will convert into list */\r
+ first = JimRelToAbsIndex(len, first);\r
+ last = JimRelToAbsIndex(len, last);\r
+ JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);\r
+ return Jim_NewListObj(interp,\r
+ listObjPtr->internalRep.listValue.ele+first, rangeLen);\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Dict object\r
+ * ---------------------------------------------------------------------------*/\r
+static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);\r
+static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);\r
+static void UpdateStringOfDict(struct Jim_Obj *objPtr);\r
+static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+/* Dict HashTable Type.\r
+ *\r
+ * Keys and Values are Jim objects. */\r
+\r
+unsigned int JimObjectHTHashFunction(const void *key)\r
+{\r
+ const char *str;\r
+ Jim_Obj *objPtr = (Jim_Obj*) key;\r
+ int len, h;\r
+\r
+ str = Jim_GetString(objPtr, &len);\r
+ h = Jim_GenHashFunction((unsigned char*)str, len);\r
+ return h;\r
+}\r
+\r
+int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)\r
+{\r
+ JIM_NOTUSED(privdata);\r
+\r
+ return Jim_StringEqObj((Jim_Obj*)key1, (Jim_Obj*)key2, 0);\r
+}\r
+\r
+static void JimObjectHTKeyValDestructor(void *interp, void *val)\r
+{\r
+ Jim_Obj *objPtr = val;\r
+\r
+ Jim_DecrRefCount(interp, objPtr);\r
+}\r
+\r
+static Jim_HashTableType JimDictHashTableType = {\r
+ JimObjectHTHashFunction, /* hash function */\r
+ NULL, /* key dup */\r
+ NULL, /* val dup */\r
+ JimObjectHTKeyCompare, /* key compare */\r
+ (void(*)(void*, const void*)) /* ATTENTION: const cast */\r
+ JimObjectHTKeyValDestructor, /* key destructor */\r
+ JimObjectHTKeyValDestructor /* val destructor */\r
+};\r
+\r
+/* Note that while the elements of the dict may contain references,\r
+ * the list object itself can't. This basically means that the\r
+ * dict object string representation as a whole can't contain references\r
+ * that are not presents in the single elements. */\r
+static Jim_ObjType dictObjType = {\r
+ "dict",\r
+ FreeDictInternalRep,\r
+ DupDictInternalRep,\r
+ UpdateStringOfDict,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ JIM_NOTUSED(interp);\r
+\r
+ Jim_FreeHashTable(objPtr->internalRep.ptr);\r
+ Jim_Free(objPtr->internalRep.ptr);\r
+}\r
+\r
+void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)\r
+{\r
+ Jim_HashTable *ht, *dupHt;\r
+ Jim_HashTableIterator *htiter;\r
+ Jim_HashEntry *he;\r
+\r
+ /* Create a new hash table */\r
+ ht = srcPtr->internalRep.ptr;\r
+ dupHt = Jim_Alloc(sizeof(*dupHt));\r
+ Jim_InitHashTable(dupHt, &JimDictHashTableType, interp);\r
+ if (ht->size != 0)\r
+ Jim_ExpandHashTable(dupHt, ht->size);\r
+ /* Copy every element from the source to the dup hash table */\r
+ htiter = Jim_GetHashTableIterator(ht);\r
+ while ((he = Jim_NextHashEntry(htiter)) != NULL) {\r
+ const Jim_Obj *keyObjPtr = he->key;\r
+ Jim_Obj *valObjPtr = he->val;\r
+\r
+ Jim_IncrRefCount((Jim_Obj*)keyObjPtr); /* ATTENTION: const cast */\r
+ Jim_IncrRefCount(valObjPtr);\r
+ Jim_AddHashEntry(dupHt, keyObjPtr, valObjPtr);\r
+ }\r
+ Jim_FreeHashTableIterator(htiter);\r
+\r
+ dupPtr->internalRep.ptr = dupHt;\r
+ dupPtr->typePtr = &dictObjType;\r
+}\r
+\r
+void UpdateStringOfDict(struct Jim_Obj *objPtr)\r
+{\r
+ int i, bufLen, realLength;\r
+ const char *strRep;\r
+ char *p;\r
+ int *quotingType, objc;\r
+ Jim_HashTable *ht;\r
+ Jim_HashTableIterator *htiter;\r
+ Jim_HashEntry *he;\r
+ Jim_Obj **objv;\r
+\r
+ /* Trun the hash table into a flat vector of Jim_Objects. */\r
+ ht = objPtr->internalRep.ptr;\r
+ objc = ht->used*2;\r
+ objv = Jim_Alloc(objc*sizeof(Jim_Obj*));\r
+ htiter = Jim_GetHashTableIterator(ht);\r
+ i = 0;\r
+ while ((he = Jim_NextHashEntry(htiter)) != NULL) {\r
+ objv[i++] = (Jim_Obj*)he->key; /* ATTENTION: const cast */\r
+ objv[i++] = he->val;\r
+ }\r
+ Jim_FreeHashTableIterator(htiter);\r
+ /* (Over) Estimate the space needed. */\r
+ quotingType = Jim_Alloc(sizeof(int)*objc);\r
+ bufLen = 0;\r
+ for (i = 0; i < objc; i++) {\r
+ int len;\r
+\r
+ strRep = Jim_GetString(objv[i], &len);\r
+ quotingType[i] = ListElementQuotingType(strRep, len);\r
+ switch (quotingType[i]) {\r
+ case JIM_ELESTR_SIMPLE: bufLen += len; break;\r
+ case JIM_ELESTR_BRACE: bufLen += len+2; break;\r
+ case JIM_ELESTR_QUOTE: bufLen += len*2; break;\r
+ }\r
+ bufLen++; /* elements separator. */\r
+ }\r
+ bufLen++;\r
+\r
+ /* Generate the string rep. */\r
+ p = objPtr->bytes = Jim_Alloc(bufLen+1);\r
+ realLength = 0;\r
+ for (i = 0; i < objc; i++) {\r
+ int len, qlen;\r
+ const char *strRep = Jim_GetString(objv[i], &len);\r
+ char *q;\r
+\r
+ switch(quotingType[i]) {\r
+ case JIM_ELESTR_SIMPLE:\r
+ memcpy(p, strRep, len);\r
+ p += len;\r
+ realLength += len;\r
+ break;\r
+ case JIM_ELESTR_BRACE:\r
+ *p++ = '{';\r
+ memcpy(p, strRep, len);\r
+ p += len;\r
+ *p++ = '}';\r
+ realLength += len+2;\r
+ break;\r
+ case JIM_ELESTR_QUOTE:\r
+ q = BackslashQuoteString(strRep, len, &qlen);\r
+ memcpy(p, q, qlen);\r
+ Jim_Free(q);\r
+ p += qlen;\r
+ realLength += qlen;\r
+ break;\r
+ }\r
+ /* Add a separating space */\r
+ if (i+1 != objc) {\r
+ *p++ = ' ';\r
+ realLength ++;\r
+ }\r
+ }\r
+ *p = '\0'; /* nul term. */\r
+ objPtr->length = realLength;\r
+ Jim_Free(quotingType);\r
+ Jim_Free(objv);\r
+}\r
+\r
+int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)\r
+{\r
+ struct JimParserCtx parser;\r
+ Jim_HashTable *ht;\r
+ Jim_Obj *objv[2];\r
+ const char *str;\r
+ int i, strLen;\r
+\r
+ /* Get the string representation */\r
+ str = Jim_GetString(objPtr, &strLen);\r
+\r
+ /* Free the old internal repr just now and initialize the\r
+ * new one just now. The string->list conversion can't fail. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ ht = Jim_Alloc(sizeof(*ht));\r
+ Jim_InitHashTable(ht, &JimDictHashTableType, interp);\r
+ objPtr->typePtr = &dictObjType;\r
+ objPtr->internalRep.ptr = ht;\r
+\r
+ /* Convert into a dict */\r
+ JimParserInit(&parser, str, strLen, 1);\r
+ i = 0;\r
+ while(!JimParserEof(&parser)) {\r
+ char *token;\r
+ int tokenLen, type;\r
+\r
+ JimParseList(&parser);\r
+ if (JimParserTtype(&parser) != JIM_TT_STR &&\r
+ JimParserTtype(&parser) != JIM_TT_ESC)\r
+ continue;\r
+ token = JimParserGetToken(&parser, &tokenLen, &type, NULL);\r
+ objv[i++] = Jim_NewStringObjNoAlloc(interp, token, tokenLen);\r
+ if (i == 2) {\r
+ i = 0;\r
+ Jim_IncrRefCount(objv[0]);\r
+ Jim_IncrRefCount(objv[1]);\r
+ if (Jim_AddHashEntry(ht, objv[0], objv[1]) != JIM_OK) {\r
+ Jim_HashEntry *he;\r
+ he = Jim_FindHashEntry(ht, objv[0]);\r
+ Jim_DecrRefCount(interp, objv[0]);\r
+ /* ATTENTION: const cast */\r
+ Jim_DecrRefCount(interp, (Jim_Obj*)he->val);\r
+ he->val = objv[1];\r
+ }\r
+ }\r
+ }\r
+ if (i) {\r
+ Jim_FreeNewObj(interp, objv[0]);\r
+ objPtr->typePtr = NULL;\r
+ Jim_FreeHashTable(ht);\r
+ Jim_SetResultString(interp, "invalid dictionary value: must be a list with an even number of elements", -1);\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* Dict object API */\r
+\r
+/* Add an element to a dict. objPtr must be of the "dict" type.\r
+ * The higer-level exported function is Jim_DictAddElement().\r
+ * If an element with the specified key already exists, the value\r
+ * associated is replaced with the new one.\r
+ *\r
+ * if valueObjPtr == NULL, the key is instead removed if it exists. */\r
+static void DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)\r
+{\r
+ Jim_HashTable *ht = objPtr->internalRep.ptr;\r
+\r
+ if (valueObjPtr == NULL) { /* unset */\r
+ Jim_DeleteHashEntry(ht, keyObjPtr);\r
+ return;\r
+ }\r
+ Jim_IncrRefCount(keyObjPtr);\r
+ Jim_IncrRefCount(valueObjPtr);\r
+ if (Jim_AddHashEntry(ht, keyObjPtr, valueObjPtr) != JIM_OK) {\r
+ Jim_HashEntry *he = Jim_FindHashEntry(ht, keyObjPtr);\r
+ Jim_DecrRefCount(interp, keyObjPtr);\r
+ /* ATTENTION: const cast */\r
+ Jim_DecrRefCount(interp, (Jim_Obj*)he->val);\r
+ he->val = valueObjPtr;\r
+ }\r
+}\r
+\r
+/* Add an element, higher-level interface for DictAddElement().\r
+ * If valueObjPtr == NULL, the key is removed if it exists. */\r
+int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,\r
+ Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)\r
+{\r
+ if (Jim_IsShared(objPtr))\r
+ Jim_Panic(interp,"Jim_DictAddElement called with shared object");\r
+ if (objPtr->typePtr != &dictObjType) {\r
+ if (SetDictFromAny(interp, objPtr) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);\r
+ Jim_InvalidateStringRep(objPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)\r
+{\r
+ Jim_Obj *objPtr;\r
+ int i;\r
+\r
+ if (len % 2)\r
+ Jim_Panic(interp,"Jim_NewDicObj() 'len' argument must be even");\r
+\r
+ objPtr = Jim_NewObj(interp);\r
+ objPtr->typePtr = &dictObjType;\r
+ objPtr->bytes = NULL;\r
+ objPtr->internalRep.ptr = Jim_Alloc(sizeof(Jim_HashTable));\r
+ Jim_InitHashTable(objPtr->internalRep.ptr, &JimDictHashTableType, interp);\r
+ for (i = 0; i < len; i += 2)\r
+ DictAddElement(interp, objPtr, elements[i], elements[i+1]);\r
+ return objPtr;\r
+}\r
+\r
+/* Return the value associated to the specified dict key */\r
+int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,\r
+ Jim_Obj **objPtrPtr, int flags)\r
+{\r
+ Jim_HashEntry *he;\r
+ Jim_HashTable *ht;\r
+\r
+ if (dictPtr->typePtr != &dictObjType) {\r
+ if (SetDictFromAny(interp, dictPtr) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ ht = dictPtr->internalRep.ptr;\r
+ if ((he = Jim_FindHashEntry(ht, keyPtr)) == NULL) {\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "key \"", Jim_GetString(keyPtr, NULL),\r
+ "\" not found in dictionary", NULL);\r
+ }\r
+ return JIM_ERR;\r
+ }\r
+ *objPtrPtr = he->val;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Return the value associated to the specified dict keys */\r
+int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,\r
+ Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)\r
+{\r
+ Jim_Obj *objPtr;\r
+ int i;\r
+\r
+ if (keyc == 0) {\r
+ *objPtrPtr = dictPtr;\r
+ return JIM_OK;\r
+ }\r
+\r
+ for (i = 0; i < keyc; i++) {\r
+ if (Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags)\r
+ != JIM_OK)\r
+ return JIM_ERR;\r
+ dictPtr = objPtr;\r
+ }\r
+ *objPtrPtr = objPtr;\r
+ return JIM_OK;\r
+}\r
+\r
+/* Modify the dict stored into the variable named 'varNamePtr'\r
+ * setting the element specified by the 'keyc' keys objects in 'keyv',\r
+ * with the new value of the element 'newObjPtr'.\r
+ *\r
+ * If newObjPtr == NULL the operation is to remove the given key\r
+ * from the dictionary. */\r
+int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,\r
+ Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr)\r
+{\r
+ Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;\r
+ int shared, i;\r
+\r
+ varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);\r
+ if (objPtr == NULL) {\r
+ if (newObjPtr == NULL) /* Cannot remove a key from non existing var */\r
+ return JIM_ERR;\r
+ varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);\r
+ if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {\r
+ Jim_FreeNewObj(interp, varObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ if ((shared = Jim_IsShared(objPtr)))\r
+ varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);\r
+ for (i = 0; i < keyc-1; i++) {\r
+ dictObjPtr = objPtr;\r
+\r
+ /* Check if it's a valid dictionary */\r
+ if (dictObjPtr->typePtr != &dictObjType) {\r
+ if (SetDictFromAny(interp, dictObjPtr) != JIM_OK)\r
+ goto err;\r
+ }\r
+ /* Check if the given key exists. */\r
+ Jim_InvalidateStringRep(dictObjPtr);\r
+ if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,\r
+ newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK)\r
+ {\r
+ /* This key exists at the current level.\r
+ * Make sure it's not shared!. */\r
+ if (Jim_IsShared(objPtr)) {\r
+ objPtr = Jim_DuplicateObj(interp, objPtr);\r
+ DictAddElement(interp, dictObjPtr, keyv[i], objPtr);\r
+ }\r
+ } else {\r
+ /* Key not found. If it's an [unset] operation\r
+ * this is an error. Only the last key may not\r
+ * exist. */\r
+ if (newObjPtr == NULL)\r
+ goto err;\r
+ /* Otherwise set an empty dictionary\r
+ * as key's value. */\r
+ objPtr = Jim_NewDictObj(interp, NULL, 0);\r
+ DictAddElement(interp, dictObjPtr, keyv[i], objPtr);\r
+ }\r
+ }\r
+ if (Jim_DictAddElement(interp, objPtr, keyv[keyc-1], newObjPtr)\r
+ != JIM_OK)\r
+ goto err;\r
+ Jim_InvalidateStringRep(objPtr);\r
+ Jim_InvalidateStringRep(varObjPtr);\r
+ if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)\r
+ goto err;\r
+ Jim_SetResult(interp, varObjPtr);\r
+ return JIM_OK;\r
+err:\r
+ if (shared) {\r
+ Jim_FreeNewObj(interp, varObjPtr);\r
+ }\r
+ return JIM_ERR;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Index object\r
+ * ---------------------------------------------------------------------------*/\r
+static void UpdateStringOfIndex(struct Jim_Obj *objPtr);\r
+static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType indexObjType = {\r
+ "index",\r
+ NULL,\r
+ NULL,\r
+ UpdateStringOfIndex,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+void UpdateStringOfIndex(struct Jim_Obj *objPtr)\r
+{\r
+ int len;\r
+ char buf[JIM_INTEGER_SPACE+1];\r
+\r
+ if (objPtr->internalRep.indexValue >= 0)\r
+ len = sprintf(buf, "%d", objPtr->internalRep.indexValue);\r
+ else if (objPtr->internalRep.indexValue == -1)\r
+ len = sprintf(buf, "end");\r
+ else {\r
+ len = sprintf(buf, "end%d", objPtr->internalRep.indexValue+1);\r
+ }\r
+ objPtr->bytes = Jim_Alloc(len+1);\r
+ memcpy(objPtr->bytes, buf, len+1);\r
+ objPtr->length = len;\r
+}\r
+\r
+int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ int index, end = 0;\r
+ const char *str;\r
+\r
+ /* Get the string representation */\r
+ str = Jim_GetString(objPtr, NULL);\r
+ /* Try to convert into an index */\r
+ if (!strcmp(str, "end")) {\r
+ index = 0;\r
+ end = 1;\r
+ } else {\r
+ if (!strncmp(str, "end-", 4)) {\r
+ str += 4;\r
+ end = 1;\r
+ }\r
+ if (Jim_StringToIndex(str, &index) != JIM_OK) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad index \"", Jim_GetString(objPtr, NULL), "\": "\r
+ "must be integer or end?-integer?", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ if (end) {\r
+ if (index < 0)\r
+ index = INT_MAX;\r
+ else\r
+ index = -(index+1);\r
+ } else if (!end && index < 0)\r
+ index = -INT_MAX;\r
+ /* Free the old internal repr and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &indexObjType;\r
+ objPtr->internalRep.indexValue = index;\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)\r
+{\r
+ /* Avoid shimmering if the object is an integer. */\r
+ if (objPtr->typePtr == &intObjType) {\r
+ jim_wide val = objPtr->internalRep.wideValue;\r
+ if (!(val < LONG_MIN) && !(val > LONG_MAX)) {\r
+ *indexPtr = (val < 0) ? -INT_MAX : (long)val;;\r
+ return JIM_OK;\r
+ }\r
+ }\r
+ if (objPtr->typePtr != &indexObjType &&\r
+ SetIndexFromAny(interp, objPtr) == JIM_ERR)\r
+ return JIM_ERR;\r
+ *indexPtr = objPtr->internalRep.indexValue;\r
+ return JIM_OK;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Return Code Object.\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType returnCodeObjType = {\r
+ "return-code",\r
+ NULL,\r
+ NULL,\r
+ NULL,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ const char *str;\r
+ int strLen, returnCode;\r
+ jim_wide wideValue;\r
+\r
+ /* Get the string representation */\r
+ str = Jim_GetString(objPtr, &strLen);\r
+ /* Try to convert into an integer */\r
+ if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)\r
+ returnCode = (int) wideValue;\r
+ else if (!JimStringCompare(str, strLen, "ok", 2, JIM_NOCASE))\r
+ returnCode = JIM_OK;\r
+ else if (!JimStringCompare(str, strLen, "error", 5, JIM_NOCASE))\r
+ returnCode = JIM_ERR;\r
+ else if (!JimStringCompare(str, strLen, "return", 6, JIM_NOCASE))\r
+ returnCode = JIM_RETURN;\r
+ else if (!JimStringCompare(str, strLen, "break", 5, JIM_NOCASE))\r
+ returnCode = JIM_BREAK;\r
+ else if (!JimStringCompare(str, strLen, "continue", 8, JIM_NOCASE))\r
+ returnCode = JIM_CONTINUE;\r
+ else if (!JimStringCompare(str, strLen, "eval", 4, JIM_NOCASE))\r
+ returnCode = JIM_EVAL;\r
+ else if (!JimStringCompare(str, strLen, "exit", 4, JIM_NOCASE))\r
+ returnCode = JIM_EXIT;\r
+ else {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "expected return code but got '", str, "'",\r
+ NULL);\r
+ return JIM_ERR;\r
+ }\r
+ /* Free the old internal repr and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ objPtr->typePtr = &returnCodeObjType;\r
+ objPtr->internalRep.returnCode = returnCode;\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)\r
+{\r
+ if (objPtr->typePtr != &returnCodeObjType &&\r
+ SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)\r
+ return JIM_ERR;\r
+ *intPtr = objPtr->internalRep.returnCode;\r
+ return JIM_OK;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Expression Parsing\r
+ * ---------------------------------------------------------------------------*/\r
+static int JimParseExprOperator(struct JimParserCtx *pc);\r
+static int JimParseExprNumber(struct JimParserCtx *pc);\r
+static int JimParseExprIrrational(struct JimParserCtx *pc);\r
+\r
+/* Exrp's Stack machine operators opcodes. */\r
+\r
+/* Binary operators (numbers) */\r
+#define JIM_EXPROP_BINARY_NUM_FIRST 0 /* first */\r
+#define JIM_EXPROP_MUL 0\r
+#define JIM_EXPROP_DIV 1\r
+#define JIM_EXPROP_MOD 2\r
+#define JIM_EXPROP_SUB 3\r
+#define JIM_EXPROP_ADD 4\r
+#define JIM_EXPROP_LSHIFT 5\r
+#define JIM_EXPROP_RSHIFT 6\r
+#define JIM_EXPROP_ROTL 7\r
+#define JIM_EXPROP_ROTR 8\r
+#define JIM_EXPROP_LT 9\r
+#define JIM_EXPROP_GT 10\r
+#define JIM_EXPROP_LTE 11\r
+#define JIM_EXPROP_GTE 12\r
+#define JIM_EXPROP_NUMEQ 13\r
+#define JIM_EXPROP_NUMNE 14\r
+#define JIM_EXPROP_BITAND 15\r
+#define JIM_EXPROP_BITXOR 16\r
+#define JIM_EXPROP_BITOR 17\r
+#define JIM_EXPROP_LOGICAND 18\r
+#define JIM_EXPROP_LOGICOR 19\r
+#define JIM_EXPROP_LOGICAND_LEFT 20\r
+#define JIM_EXPROP_LOGICOR_LEFT 21\r
+#define JIM_EXPROP_POW 22\r
+#define JIM_EXPROP_BINARY_NUM_LAST 22 /* last */\r
+\r
+/* Binary operators (strings) */\r
+#define JIM_EXPROP_STREQ 23\r
+#define JIM_EXPROP_STRNE 24\r
+\r
+/* Unary operators (numbers) */\r
+#define JIM_EXPROP_NOT 25\r
+#define JIM_EXPROP_BITNOT 26\r
+#define JIM_EXPROP_UNARYMINUS 27\r
+#define JIM_EXPROP_UNARYPLUS 28\r
+#define JIM_EXPROP_LOGICAND_RIGHT 29\r
+#define JIM_EXPROP_LOGICOR_RIGHT 30\r
+\r
+/* Ternary operators */\r
+#define JIM_EXPROP_TERNARY 31\r
+\r
+/* Operands */\r
+#define JIM_EXPROP_NUMBER 32\r
+#define JIM_EXPROP_COMMAND 33\r
+#define JIM_EXPROP_VARIABLE 34\r
+#define JIM_EXPROP_DICTSUGAR 35\r
+#define JIM_EXPROP_SUBST 36\r
+#define JIM_EXPROP_STRING 37\r
+\r
+/* Operators table */\r
+typedef struct Jim_ExprOperator {\r
+ const char *name;\r
+ int precedence;\r
+ int arity;\r
+ int opcode;\r
+} Jim_ExprOperator;\r
+\r
+/* name - precedence - arity - opcode */\r
+static struct Jim_ExprOperator Jim_ExprOperators[] = {\r
+ {"!", 300, 1, JIM_EXPROP_NOT},\r
+ {"~", 300, 1, JIM_EXPROP_BITNOT},\r
+ {"unarymin", 300, 1, JIM_EXPROP_UNARYMINUS},\r
+ {"unaryplus", 300, 1, JIM_EXPROP_UNARYPLUS},\r
+\r
+ {"**", 250, 2, JIM_EXPROP_POW},\r
+\r
+ {"*", 200, 2, JIM_EXPROP_MUL},\r
+ {"/", 200, 2, JIM_EXPROP_DIV},\r
+ {"%", 200, 2, JIM_EXPROP_MOD},\r
+\r
+ {"-", 100, 2, JIM_EXPROP_SUB},\r
+ {"+", 100, 2, JIM_EXPROP_ADD},\r
+\r
+ {"<<<", 90, 3, JIM_EXPROP_ROTL},\r
+ {">>>", 90, 3, JIM_EXPROP_ROTR},\r
+ {"<<", 90, 2, JIM_EXPROP_LSHIFT},\r
+ {">>", 90, 2, JIM_EXPROP_RSHIFT},\r
+\r
+ {"<", 80, 2, JIM_EXPROP_LT},\r
+ {">", 80, 2, JIM_EXPROP_GT},\r
+ {"<=", 80, 2, JIM_EXPROP_LTE},\r
+ {">=", 80, 2, JIM_EXPROP_GTE},\r
+\r
+ {"==", 70, 2, JIM_EXPROP_NUMEQ},\r
+ {"!=", 70, 2, JIM_EXPROP_NUMNE},\r
+\r
+ {"eq", 60, 2, JIM_EXPROP_STREQ},\r
+ {"ne", 60, 2, JIM_EXPROP_STRNE},\r
+\r
+ {"&", 50, 2, JIM_EXPROP_BITAND},\r
+ {"^", 49, 2, JIM_EXPROP_BITXOR},\r
+ {"|", 48, 2, JIM_EXPROP_BITOR},\r
+\r
+ {"&&", 10, 2, JIM_EXPROP_LOGICAND},\r
+ {"||", 10, 2, JIM_EXPROP_LOGICOR},\r
+\r
+ {"?", 5, 3, JIM_EXPROP_TERNARY},\r
+ /* private operators */\r
+ {NULL, 10, 2, JIM_EXPROP_LOGICAND_LEFT},\r
+ {NULL, 10, 1, JIM_EXPROP_LOGICAND_RIGHT},\r
+ {NULL, 10, 2, JIM_EXPROP_LOGICOR_LEFT},\r
+ {NULL, 10, 1, JIM_EXPROP_LOGICOR_RIGHT},\r
+};\r
+\r
+#define JIM_EXPR_OPERATORS_NUM \\r
+ (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))\r
+\r
+int JimParseExpression(struct JimParserCtx *pc)\r
+{\r
+ /* Discard spaces and quoted newline */\r
+ while(*(pc->p) == ' ' ||\r
+ *(pc->p) == '\t' ||\r
+ *(pc->p) == '\r' ||\r
+ *(pc->p) == '\n' ||\r
+ (*(pc->p) == '\\' && *(pc->p+1) == '\n')) {\r
+ pc->p++; pc->len--;\r
+ }\r
+\r
+ if (pc->len == 0) {\r
+ pc->tstart = pc->tend = pc->p;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_EOL;\r
+ pc->eof = 1;\r
+ return JIM_OK;\r
+ }\r
+ switch(*(pc->p)) {\r
+ case '(':\r
+ pc->tstart = pc->tend = pc->p;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_SUBEXPR_START;\r
+ pc->p++; pc->len--;\r
+ break;\r
+ case ')':\r
+ pc->tstart = pc->tend = pc->p;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_SUBEXPR_END;\r
+ pc->p++; pc->len--;\r
+ break;\r
+ case '[':\r
+ return JimParseCmd(pc);\r
+ break;\r
+ case '$':\r
+ if (JimParseVar(pc) == JIM_ERR)\r
+ return JimParseExprOperator(pc);\r
+ else\r
+ return JIM_OK;\r
+ break;\r
+ case '-':\r
+ if ((pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_EXPR_OPERATOR) &&\r
+ isdigit((int)*(pc->p+1)))\r
+ return JimParseExprNumber(pc);\r
+ else\r
+ return JimParseExprOperator(pc);\r
+ break;\r
+ case '0': case '1': case '2': case '3': case '4':\r
+ case '5': case '6': case '7': case '8': case '9': case '.':\r
+ return JimParseExprNumber(pc);\r
+ break;\r
+ case '"':\r
+ case '{':\r
+ /* Here it's possible to reuse the List String parsing. */\r
+ pc->tt = JIM_TT_NONE; /* Make sure it's sensed as a new word. */\r
+ return JimParseListStr(pc);\r
+ break;\r
+ case 'N': case 'I':\r
+ case 'n': case 'i':\r
+ if (JimParseExprIrrational(pc) == JIM_ERR)\r
+ return JimParseExprOperator(pc);\r
+ break;\r
+ default:\r
+ return JimParseExprOperator(pc);\r
+ break;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+int JimParseExprNumber(struct JimParserCtx *pc)\r
+{\r
+ int allowdot = 1;\r
+ int allowhex = 0;\r
+\r
+ pc->tstart = pc->p;\r
+ pc->tline = pc->linenr;\r
+ if (*pc->p == '-') {\r
+ pc->p++; pc->len--;\r
+ }\r
+ while ( isdigit((int)*pc->p) \r
+ || (allowhex && isxdigit((int)*pc->p) )\r
+ || (allowdot && *pc->p == '.') \r
+ || (pc->p-pc->tstart == 1 && *pc->tstart == '0' &&\r
+ (*pc->p == 'x' || *pc->p == 'X'))\r
+ )\r
+ {\r
+ if ((*pc->p == 'x') || (*pc->p == 'X')) {\r
+ allowhex = 1;\r
+ allowdot = 0;\r
+ }\r
+ if (*pc->p == '.')\r
+ allowdot = 0;\r
+ pc->p++; pc->len--;\r
+ if (!allowdot && *pc->p == 'e' && *(pc->p+1) == '-') {\r
+ pc->p += 2; pc->len -= 2;\r
+ }\r
+ }\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_EXPR_NUMBER;\r
+ return JIM_OK;\r
+}\r
+\r
+int JimParseExprIrrational(struct JimParserCtx *pc)\r
+{\r
+ const char *Tokens[] = {"NaN", "nan", "NAN", "Inf", "inf", "INF", NULL};\r
+ const char **token;\r
+ for (token = Tokens; *token != NULL; token++) {\r
+ int len = strlen(*token);\r
+ if (strncmp(*token, pc->p, len) == 0) {\r
+ pc->tstart = pc->p;\r
+ pc->tend = pc->p + len - 1;\r
+ pc->p += len; pc->len -= len;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_EXPR_NUMBER;\r
+ return JIM_OK;\r
+ }\r
+ }\r
+ return JIM_ERR;\r
+}\r
+\r
+int JimParseExprOperator(struct JimParserCtx *pc)\r
+{\r
+ int i;\r
+ int bestIdx = -1, bestLen = 0;\r
+\r
+ /* Try to get the longest match. */\r
+ for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {\r
+ const char *opname;\r
+ int oplen;\r
+\r
+ opname = Jim_ExprOperators[i].name;\r
+ if (opname == NULL) continue;\r
+ oplen = strlen(opname);\r
+\r
+ if (strncmp(opname, pc->p, oplen) == 0 && oplen > bestLen) {\r
+ bestIdx = i;\r
+ bestLen = oplen;\r
+ }\r
+ }\r
+ if (bestIdx == -1) return JIM_ERR;\r
+ pc->tstart = pc->p;\r
+ pc->tend = pc->p + bestLen - 1;\r
+ pc->p += bestLen; pc->len -= bestLen;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_EXPR_OPERATOR;\r
+ return JIM_OK;\r
+}\r
+\r
+struct Jim_ExprOperator *JimExprOperatorInfo(const char *opname)\r
+{\r
+ int i;\r
+ for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++)\r
+ if (Jim_ExprOperators[i].name &&\r
+ strcmp(opname, Jim_ExprOperators[i].name) == 0)\r
+ return &Jim_ExprOperators[i];\r
+ return NULL;\r
+}\r
+\r
+struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)\r
+{\r
+ int i;\r
+ for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++)\r
+ if (Jim_ExprOperators[i].opcode == opcode)\r
+ return &Jim_ExprOperators[i];\r
+ return NULL;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Expression Object\r
+ * ---------------------------------------------------------------------------*/\r
+static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);\r
+static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);\r
+static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType exprObjType = {\r
+ "expression",\r
+ FreeExprInternalRep,\r
+ DupExprInternalRep,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+/* Expr bytecode structure */\r
+typedef struct ExprByteCode {\r
+ int *opcode; /* Integer array of opcodes. */\r
+ Jim_Obj **obj; /* Array of associated Jim Objects. */\r
+ int len; /* Bytecode length */\r
+ int inUse; /* Used for sharing. */\r
+} ExprByteCode;\r
+\r
+void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ int i;\r
+ ExprByteCode *expr = (void*) objPtr->internalRep.ptr;\r
+\r
+ expr->inUse--;\r
+ if (expr->inUse != 0) return;\r
+ for (i = 0; i < expr->len; i++)\r
+ Jim_DecrRefCount(interp, expr->obj[i]);\r
+ Jim_Free(expr->opcode);\r
+ Jim_Free(expr->obj);\r
+ Jim_Free(expr);\r
+}\r
+\r
+void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)\r
+{\r
+ JIM_NOTUSED(interp);\r
+ JIM_NOTUSED(srcPtr);\r
+\r
+ /* Just returns an simple string. */\r
+ dupPtr->typePtr = NULL;\r
+}\r
+\r
+/* Add a new instruction to an expression bytecode structure. */\r
+static void ExprObjAddInstr(Jim_Interp *interp, ExprByteCode *expr,\r
+ int opcode, char *str, int len)\r
+{\r
+ expr->opcode = Jim_Realloc(expr->opcode, sizeof(int)*(expr->len+1));\r
+ expr->obj = Jim_Realloc(expr->obj, sizeof(Jim_Obj*)*(expr->len+1));\r
+ expr->opcode[expr->len] = opcode;\r
+ expr->obj[expr->len] = Jim_NewStringObjNoAlloc(interp, str, len);\r
+ Jim_IncrRefCount(expr->obj[expr->len]);\r
+ expr->len++;\r
+}\r
+\r
+/* Check if an expr program looks correct. */\r
+static int ExprCheckCorrectness(ExprByteCode *expr)\r
+{\r
+ int i;\r
+ int stacklen = 0;\r
+\r
+ /* Try to check if there are stack underflows,\r
+ * and make sure at the end of the program there is\r
+ * a single result on the stack. */\r
+ for (i = 0; i < expr->len; i++) {\r
+ switch(expr->opcode[i]) {\r
+ case JIM_EXPROP_NUMBER:\r
+ case JIM_EXPROP_STRING:\r
+ case JIM_EXPROP_SUBST:\r
+ case JIM_EXPROP_VARIABLE:\r
+ case JIM_EXPROP_DICTSUGAR:\r
+ case JIM_EXPROP_COMMAND:\r
+ stacklen++;\r
+ break;\r
+ case JIM_EXPROP_NOT:\r
+ case JIM_EXPROP_BITNOT:\r
+ case JIM_EXPROP_UNARYMINUS:\r
+ case JIM_EXPROP_UNARYPLUS:\r
+ /* Unary operations */\r
+ if (stacklen < 1) return JIM_ERR;\r
+ break;\r
+ case JIM_EXPROP_ADD:\r
+ case JIM_EXPROP_SUB:\r
+ case JIM_EXPROP_MUL:\r
+ case JIM_EXPROP_DIV:\r
+ case JIM_EXPROP_MOD:\r
+ case JIM_EXPROP_LT:\r
+ case JIM_EXPROP_GT:\r
+ case JIM_EXPROP_LTE:\r
+ case JIM_EXPROP_GTE:\r
+ case JIM_EXPROP_ROTL:\r
+ case JIM_EXPROP_ROTR:\r
+ case JIM_EXPROP_LSHIFT:\r
+ case JIM_EXPROP_RSHIFT:\r
+ case JIM_EXPROP_NUMEQ:\r
+ case JIM_EXPROP_NUMNE:\r
+ case JIM_EXPROP_STREQ:\r
+ case JIM_EXPROP_STRNE:\r
+ case JIM_EXPROP_BITAND:\r
+ case JIM_EXPROP_BITXOR:\r
+ case JIM_EXPROP_BITOR:\r
+ case JIM_EXPROP_LOGICAND:\r
+ case JIM_EXPROP_LOGICOR:\r
+ case JIM_EXPROP_POW:\r
+ /* binary operations */\r
+ if (stacklen < 2) return JIM_ERR;\r
+ stacklen--;\r
+ break;\r
+ default:\r
+ Jim_Panic(NULL,"Default opcode reached ExprCheckCorrectness");\r
+ break;\r
+ }\r
+ }\r
+ if (stacklen != 1) return JIM_ERR;\r
+ return JIM_OK;\r
+}\r
+\r
+static void ExprShareLiterals(Jim_Interp *interp, ExprByteCode *expr,\r
+ ScriptObj *topLevelScript)\r
+{\r
+ int i;\r
+\r
+ return;\r
+ for (i = 0; i < expr->len; i++) {\r
+ Jim_Obj *foundObjPtr;\r
+\r
+ if (expr->obj[i] == NULL) continue;\r
+ foundObjPtr = ScriptSearchLiteral(interp, topLevelScript,\r
+ NULL, expr->obj[i]);\r
+ if (foundObjPtr != NULL) {\r
+ Jim_IncrRefCount(foundObjPtr);\r
+ Jim_DecrRefCount(interp, expr->obj[i]);\r
+ expr->obj[i] = foundObjPtr;\r
+ }\r
+ }\r
+}\r
+\r
+/* This procedure converts every occurrence of || and && opereators\r
+ * in lazy unary versions.\r
+ *\r
+ * a b || is converted into:\r
+ *\r
+ * a <offset> |L b |R\r
+ *\r
+ * a b && is converted into:\r
+ *\r
+ * a <offset> &L b &R\r
+ *\r
+ * "|L" checks if 'a' is true:\r
+ * 1) if it is true pushes 1 and skips <offset> istructions to reach\r
+ * the opcode just after |R.\r
+ * 2) if it is false does nothing.\r
+ * "|R" checks if 'b' is true:\r
+ * 1) if it is true pushes 1, otherwise pushes 0.\r
+ *\r
+ * "&L" checks if 'a' is true:\r
+ * 1) if it is true does nothing.\r
+ * 2) If it is false pushes 0 and skips <offset> istructions to reach\r
+ * the opcode just after &R\r
+ * "&R" checks if 'a' is true:\r
+ * if it is true pushes 1, otherwise pushes 0.\r
+ */\r
+static void ExprMakeLazy(Jim_Interp *interp, ExprByteCode *expr)\r
+{\r
+ while (1) {\r
+ int index = -1, leftindex, arity, i, offset;\r
+ Jim_ExprOperator *op;\r
+\r
+ /* Search for || or && */\r
+ for (i = 0; i < expr->len; i++) {\r
+ if (expr->opcode[i] == JIM_EXPROP_LOGICAND ||\r
+ expr->opcode[i] == JIM_EXPROP_LOGICOR) {\r
+ index = i;\r
+ break;\r
+ }\r
+ }\r
+ if (index == -1) return;\r
+ /* Search for the end of the first operator */\r
+ leftindex = index-1;\r
+ arity = 1;\r
+ while(arity) {\r
+ switch(expr->opcode[leftindex]) {\r
+ case JIM_EXPROP_NUMBER:\r
+ case JIM_EXPROP_COMMAND:\r
+ case JIM_EXPROP_VARIABLE:\r
+ case JIM_EXPROP_DICTSUGAR:\r
+ case JIM_EXPROP_SUBST:\r
+ case JIM_EXPROP_STRING:\r
+ break;\r
+ default:\r
+ op = JimExprOperatorInfoByOpcode(expr->opcode[i]);\r
+ if (op == NULL) {\r
+ Jim_Panic(interp,"Default reached in ExprMakeLazy()");\r
+ }\r
+ arity += op->arity;\r
+ break;\r
+ }\r
+ arity--;\r
+ leftindex--;\r
+ }\r
+ leftindex++;\r
+ expr->opcode = Jim_Realloc(expr->opcode, sizeof(int)*(expr->len+2));\r
+ expr->obj = Jim_Realloc(expr->obj, sizeof(Jim_Obj*)*(expr->len+2));\r
+ memmove(&expr->opcode[leftindex+2], &expr->opcode[leftindex],\r
+ sizeof(int)*(expr->len-leftindex));\r
+ memmove(&expr->obj[leftindex+2], &expr->obj[leftindex],\r
+ sizeof(Jim_Obj*)*(expr->len-leftindex));\r
+ expr->len += 2;\r
+ index += 2;\r
+ offset = (index-leftindex)-1;\r
+ Jim_DecrRefCount(interp, expr->obj[index]);\r
+ if (expr->opcode[index] == JIM_EXPROP_LOGICAND) {\r
+ expr->opcode[leftindex+1] = JIM_EXPROP_LOGICAND_LEFT;\r
+ expr->opcode[index] = JIM_EXPROP_LOGICAND_RIGHT;\r
+ expr->obj[leftindex+1] = Jim_NewStringObj(interp, "&L", -1);\r
+ expr->obj[index] = Jim_NewStringObj(interp, "&R", -1);\r
+ } else {\r
+ expr->opcode[leftindex+1] = JIM_EXPROP_LOGICOR_LEFT;\r
+ expr->opcode[index] = JIM_EXPROP_LOGICOR_RIGHT;\r
+ expr->obj[leftindex+1] = Jim_NewStringObj(interp, "|L", -1);\r
+ expr->obj[index] = Jim_NewStringObj(interp, "|R", -1);\r
+ }\r
+ expr->opcode[leftindex] = JIM_EXPROP_NUMBER;\r
+ expr->obj[leftindex] = Jim_NewIntObj(interp, offset);\r
+ Jim_IncrRefCount(expr->obj[index]);\r
+ Jim_IncrRefCount(expr->obj[leftindex]);\r
+ Jim_IncrRefCount(expr->obj[leftindex+1]);\r
+ }\r
+}\r
+\r
+/* This method takes the string representation of an expression\r
+ * and generates a program for the Expr's stack-based VM. */\r
+int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)\r
+{\r
+ int exprTextLen;\r
+ const char *exprText = Jim_GetString(objPtr, &exprTextLen);\r
+ struct JimParserCtx parser;\r
+ int i, shareLiterals;\r
+ ExprByteCode *expr = Jim_Alloc(sizeof(*expr));\r
+ Jim_Stack stack;\r
+ Jim_ExprOperator *op;\r
+\r
+ /* Perform literal sharing with the current procedure\r
+ * running only if this expression appears to be not generated\r
+ * at runtime. */\r
+ shareLiterals = objPtr->typePtr == &sourceObjType;\r
+\r
+ expr->opcode = NULL;\r
+ expr->obj = NULL;\r
+ expr->len = 0;\r
+ expr->inUse = 1;\r
+\r
+ Jim_InitStack(&stack);\r
+ JimParserInit(&parser, exprText, exprTextLen, 1);\r
+ while(!JimParserEof(&parser)) {\r
+ char *token;\r
+ int len, type;\r
+\r
+ if (JimParseExpression(&parser) != JIM_OK) {\r
+ Jim_SetResultString(interp, "Syntax error in expression", -1);\r
+ goto err;\r
+ }\r
+ token = JimParserGetToken(&parser, &len, &type, NULL);\r
+ if (type == JIM_TT_EOL) {\r
+ Jim_Free(token);\r
+ break;\r
+ }\r
+ switch(type) {\r
+ case JIM_TT_STR:\r
+ ExprObjAddInstr(interp, expr, JIM_EXPROP_STRING, token, len);\r
+ break;\r
+ case JIM_TT_ESC:\r
+ ExprObjAddInstr(interp, expr, JIM_EXPROP_SUBST, token, len);\r
+ break;\r
+ case JIM_TT_VAR:\r
+ ExprObjAddInstr(interp, expr, JIM_EXPROP_VARIABLE, token, len);\r
+ break;\r
+ case JIM_TT_DICTSUGAR:\r
+ ExprObjAddInstr(interp, expr, JIM_EXPROP_DICTSUGAR, token, len);\r
+ break;\r
+ case JIM_TT_CMD:\r
+ ExprObjAddInstr(interp, expr, JIM_EXPROP_COMMAND, token, len);\r
+ break;\r
+ case JIM_TT_EXPR_NUMBER:\r
+ ExprObjAddInstr(interp, expr, JIM_EXPROP_NUMBER, token, len);\r
+ break;\r
+ case JIM_TT_EXPR_OPERATOR:\r
+ op = JimExprOperatorInfo(token);\r
+ while(1) {\r
+ Jim_ExprOperator *stackTopOp;\r
+\r
+ if (Jim_StackPeek(&stack) != NULL) {\r
+ stackTopOp = JimExprOperatorInfo(Jim_StackPeek(&stack));\r
+ } else {\r
+ stackTopOp = NULL;\r
+ }\r
+ if (Jim_StackLen(&stack) && op->arity != 1 &&\r
+ stackTopOp && stackTopOp->precedence >= op->precedence)\r
+ {\r
+ ExprObjAddInstr(interp, expr, stackTopOp->opcode,\r
+ Jim_StackPeek(&stack), -1);\r
+ Jim_StackPop(&stack);\r
+ } else {\r
+ break;\r
+ }\r
+ }\r
+ Jim_StackPush(&stack, token);\r
+ break;\r
+ case JIM_TT_SUBEXPR_START:\r
+ Jim_StackPush(&stack, Jim_StrDup("("));\r
+ Jim_Free(token);\r
+ break;\r
+ case JIM_TT_SUBEXPR_END:\r
+ {\r
+ int found = 0;\r
+ while(Jim_StackLen(&stack)) {\r
+ char *opstr = Jim_StackPop(&stack);\r
+ if (!strcmp(opstr, "(")) {\r
+ Jim_Free(opstr);\r
+ found = 1;\r
+ break;\r
+ }\r
+ op = JimExprOperatorInfo(opstr);\r
+ ExprObjAddInstr(interp, expr, op->opcode, opstr, -1);\r
+ }\r
+ if (!found) {\r
+ Jim_SetResultString(interp,\r
+ "Unexpected close parenthesis", -1);\r
+ goto err;\r
+ }\r
+ }\r
+ Jim_Free(token);\r
+ break;\r
+ default:\r
+ Jim_Panic(interp,"Default reached in SetExprFromAny()");\r
+ break;\r
+ }\r
+ }\r
+ while (Jim_StackLen(&stack)) {\r
+ char *opstr = Jim_StackPop(&stack);\r
+ op = JimExprOperatorInfo(opstr);\r
+ if (op == NULL && !strcmp(opstr, "(")) {\r
+ Jim_Free(opstr);\r
+ Jim_SetResultString(interp, "Missing close parenthesis", -1);\r
+ goto err;\r
+ }\r
+ ExprObjAddInstr(interp, expr, op->opcode, opstr, -1);\r
+ }\r
+ /* Check program correctness. */\r
+ if (ExprCheckCorrectness(expr) != JIM_OK) {\r
+ Jim_SetResultString(interp, "Invalid expression", -1);\r
+ goto err;\r
+ }\r
+\r
+ /* Free the stack used for the compilation. */\r
+ Jim_FreeStackElements(&stack, Jim_Free);\r
+ Jim_FreeStack(&stack);\r
+\r
+ /* Convert || and && operators in unary |L |R and &L &R for lazyness */\r
+ ExprMakeLazy(interp, expr);\r
+\r
+ /* Perform literal sharing */\r
+ if (shareLiterals && interp->framePtr->procBodyObjPtr) {\r
+ Jim_Obj *bodyObjPtr = interp->framePtr->procBodyObjPtr;\r
+ if (bodyObjPtr->typePtr == &scriptObjType) {\r
+ ScriptObj *bodyScript = bodyObjPtr->internalRep.ptr;\r
+ ExprShareLiterals(interp, expr, bodyScript);\r
+ }\r
+ }\r
+\r
+ /* Free the old internal rep and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ Jim_SetIntRepPtr(objPtr, expr);\r
+ objPtr->typePtr = &exprObjType;\r
+ return JIM_OK;\r
+\r
+err: /* we jump here on syntax/compile errors. */\r
+ Jim_FreeStackElements(&stack, Jim_Free);\r
+ Jim_FreeStack(&stack);\r
+ Jim_Free(expr->opcode);\r
+ for (i = 0; i < expr->len; i++) {\r
+ Jim_DecrRefCount(interp,expr->obj[i]);\r
+ }\r
+ Jim_Free(expr->obj);\r
+ Jim_Free(expr);\r
+ return JIM_ERR;\r
+}\r
+\r
+ExprByteCode *Jim_GetExpression(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ if (objPtr->typePtr != &exprObjType) {\r
+ if (SetExprFromAny(interp, objPtr) != JIM_OK)\r
+ return NULL;\r
+ }\r
+ return (ExprByteCode*) Jim_GetIntRepPtr(objPtr);\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Expressions evaluation.\r
+ * Jim uses a specialized stack-based virtual machine for expressions,\r
+ * that takes advantage of the fact that expr's operators\r
+ * can't be redefined.\r
+ *\r
+ * Jim_EvalExpression() uses the bytecode compiled by\r
+ * SetExprFromAny() method of the "expression" object.\r
+ *\r
+ * On success a Tcl Object containing the result of the evaluation\r
+ * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is\r
+ * returned.\r
+ * On error the function returns a retcode != to JIM_OK and set a suitable\r
+ * error on the interp.\r
+ * ---------------------------------------------------------------------------*/\r
+#define JIM_EE_STATICSTACK_LEN 10\r
+\r
+int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr,\r
+ Jim_Obj **exprResultPtrPtr)\r
+{\r
+ ExprByteCode *expr;\r
+ Jim_Obj **stack, *staticStack[JIM_EE_STATICSTACK_LEN];\r
+ int stacklen = 0, i, error = 0, errRetCode = JIM_ERR;\r
+\r
+ Jim_IncrRefCount(exprObjPtr);\r
+ expr = Jim_GetExpression(interp, exprObjPtr);\r
+ if (!expr) {\r
+ Jim_DecrRefCount(interp, exprObjPtr);\r
+ return JIM_ERR; /* error in expression. */\r
+ }\r
+ /* In order to avoid that the internal repr gets freed due to\r
+ * shimmering of the exprObjPtr's object, we make the internal rep\r
+ * shared. */\r
+ expr->inUse++;\r
+\r
+ /* The stack-based expr VM itself */\r
+\r
+ /* Stack allocation. Expr programs have the feature that\r
+ * a program of length N can't require a stack longer than\r
+ * N. */\r
+ if (expr->len > JIM_EE_STATICSTACK_LEN)\r
+ stack = Jim_Alloc(sizeof(Jim_Obj*)*expr->len);\r
+ else\r
+ stack = staticStack;\r
+\r
+ /* Execute every istruction */\r
+ for (i = 0; i < expr->len; i++) {\r
+ Jim_Obj *A, *B, *objPtr;\r
+ jim_wide wA, wB, wC;\r
+ double dA, dB, dC;\r
+ const char *sA, *sB;\r
+ int Alen, Blen, retcode;\r
+ int opcode = expr->opcode[i];\r
+\r
+ if (opcode == JIM_EXPROP_NUMBER || opcode == JIM_EXPROP_STRING) {\r
+ stack[stacklen++] = expr->obj[i];\r
+ Jim_IncrRefCount(expr->obj[i]);\r
+ } else if (opcode == JIM_EXPROP_VARIABLE) {\r
+ objPtr = Jim_GetVariable(interp, expr->obj[i], JIM_ERRMSG);\r
+ if (objPtr == NULL) {\r
+ error = 1;\r
+ goto err;\r
+ }\r
+ stack[stacklen++] = objPtr;\r
+ Jim_IncrRefCount(objPtr);\r
+ } else if (opcode == JIM_EXPROP_SUBST) {\r
+ if ((retcode = Jim_SubstObj(interp, expr->obj[i],\r
+ &objPtr, JIM_NONE)) != JIM_OK)\r
+ {\r
+ error = 1;\r
+ errRetCode = retcode;\r
+ goto err;\r
+ }\r
+ stack[stacklen++] = objPtr;\r
+ Jim_IncrRefCount(objPtr);\r
+ } else if (opcode == JIM_EXPROP_DICTSUGAR) {\r
+ objPtr = Jim_ExpandDictSugar(interp, expr->obj[i]);\r
+ if (objPtr == NULL) {\r
+ error = 1;\r
+ goto err;\r
+ }\r
+ stack[stacklen++] = objPtr;\r
+ Jim_IncrRefCount(objPtr);\r
+ } else if (opcode == JIM_EXPROP_COMMAND) {\r
+ if ((retcode = Jim_EvalObj(interp, expr->obj[i])) != JIM_OK) {\r
+ error = 1;\r
+ errRetCode = retcode;\r
+ goto err;\r
+ }\r
+ stack[stacklen++] = interp->result;\r
+ Jim_IncrRefCount(interp->result);\r
+ } else if (opcode >= JIM_EXPROP_BINARY_NUM_FIRST &&\r
+ opcode <= JIM_EXPROP_BINARY_NUM_LAST)\r
+ {\r
+ /* Note that there isn't to increment the\r
+ * refcount of objects. the references are moved\r
+ * from stack to A and B. */\r
+ B = stack[--stacklen];\r
+ A = stack[--stacklen];\r
+\r
+ /* --- Integer --- */\r
+ if ((A->typePtr == &doubleObjType && !A->bytes) ||\r
+ (B->typePtr == &doubleObjType && !B->bytes) ||\r
+ JimGetWideNoErr(interp, A, &wA) != JIM_OK ||\r
+ JimGetWideNoErr(interp, B, &wB) != JIM_OK) {\r
+ goto trydouble;\r
+ }\r
+ Jim_DecrRefCount(interp, A);\r
+ Jim_DecrRefCount(interp, B);\r
+ switch(expr->opcode[i]) {\r
+ case JIM_EXPROP_ADD: wC = wA+wB; break;\r
+ case JIM_EXPROP_SUB: wC = wA-wB; break;\r
+ case JIM_EXPROP_MUL: wC = wA*wB; break;\r
+ case JIM_EXPROP_LT: wC = wA<wB; break;\r
+ case JIM_EXPROP_GT: wC = wA>wB; break;\r
+ case JIM_EXPROP_LTE: wC = wA<=wB; break;\r
+ case JIM_EXPROP_GTE: wC = wA>=wB; break;\r
+ case JIM_EXPROP_LSHIFT: wC = wA<<wB; break;\r
+ case JIM_EXPROP_RSHIFT: wC = wA>>wB; break;\r
+ case JIM_EXPROP_NUMEQ: wC = wA==wB; break;\r
+ case JIM_EXPROP_NUMNE: wC = wA!=wB; break;\r
+ case JIM_EXPROP_BITAND: wC = wA&wB; break;\r
+ case JIM_EXPROP_BITXOR: wC = wA^wB; break;\r
+ case JIM_EXPROP_BITOR: wC = wA|wB; break;\r
+ case JIM_EXPROP_POW: wC = JimPowWide(wA,wB); break;\r
+ case JIM_EXPROP_LOGICAND_LEFT:\r
+ if (wA == 0) {\r
+ i += (int)wB;\r
+ wC = 0;\r
+ } else {\r
+ continue;\r
+ }\r
+ break;\r
+ case JIM_EXPROP_LOGICOR_LEFT:\r
+ if (wA != 0) {\r
+ i += (int)wB;\r
+ wC = 1;\r
+ } else {\r
+ continue;\r
+ }\r
+ break;\r
+ case JIM_EXPROP_DIV:\r
+ if (wB == 0) goto divbyzero;\r
+ wC = wA/wB;\r
+ break;\r
+ case JIM_EXPROP_MOD:\r
+ if (wB == 0) goto divbyzero;\r
+ wC = wA%wB;\r
+ break;\r
+ case JIM_EXPROP_ROTL: {\r
+ /* uint32_t would be better. But not everyone has inttypes.h?*/\r
+ unsigned long uA = (unsigned long)wA;\r
+#ifdef _MSC_VER\r
+ wC = _rotl(uA,(unsigned long)wB);\r
+#else\r
+ const unsigned int S = sizeof(unsigned long) * 8;\r
+ wC = (unsigned long)((uA<<wB)|(uA>>(S-wB)));\r
+#endif\r
+ break;\r
+ }\r
+ case JIM_EXPROP_ROTR: {\r
+ unsigned long uA = (unsigned long)wA;\r
+#ifdef _MSC_VER\r
+ wC = _rotr(uA,(unsigned long)wB);\r
+#else\r
+ const unsigned int S = sizeof(unsigned long) * 8;\r
+ wC = (unsigned long)((uA>>wB)|(uA<<(S-wB)));\r
+#endif\r
+ break;\r
+ }\r
+\r
+ default:\r
+ wC = 0; /* avoid gcc warning */\r
+ break;\r
+ }\r
+ stack[stacklen] = Jim_NewIntObj(interp, wC);\r
+ Jim_IncrRefCount(stack[stacklen]);\r
+ stacklen++;\r
+ continue;\r
+trydouble:\r
+ /* --- Double --- */\r
+ if (Jim_GetDouble(interp, A, &dA) != JIM_OK ||\r
+ Jim_GetDouble(interp, B, &dB) != JIM_OK) {\r
+ Jim_DecrRefCount(interp, A);\r
+ Jim_DecrRefCount(interp, B);\r
+ error = 1;\r
+ goto err;\r
+ }\r
+ Jim_DecrRefCount(interp, A);\r
+ Jim_DecrRefCount(interp, B);\r
+ switch(expr->opcode[i]) {\r
+ case JIM_EXPROP_ROTL:\r
+ case JIM_EXPROP_ROTR:\r
+ case JIM_EXPROP_LSHIFT:\r
+ case JIM_EXPROP_RSHIFT:\r
+ case JIM_EXPROP_BITAND:\r
+ case JIM_EXPROP_BITXOR:\r
+ case JIM_EXPROP_BITOR:\r
+ case JIM_EXPROP_MOD:\r
+ case JIM_EXPROP_POW:\r
+ Jim_SetResultString(interp,\r
+ "Got floating-point value where integer was expected", -1);\r
+ error = 1;\r
+ goto err;\r
+ break;\r
+ case JIM_EXPROP_ADD: dC = dA+dB; break;\r
+ case JIM_EXPROP_SUB: dC = dA-dB; break;\r
+ case JIM_EXPROP_MUL: dC = dA*dB; break;\r
+ case JIM_EXPROP_LT: dC = dA<dB; break;\r
+ case JIM_EXPROP_GT: dC = dA>dB; break;\r
+ case JIM_EXPROP_LTE: dC = dA<=dB; break;\r
+ case JIM_EXPROP_GTE: dC = dA>=dB; break;\r
+ case JIM_EXPROP_NUMEQ: dC = dA==dB; break;\r
+ case JIM_EXPROP_NUMNE: dC = dA!=dB; break;\r
+ case JIM_EXPROP_LOGICAND_LEFT:\r
+ if (dA == 0) {\r
+ i += (int)dB;\r
+ dC = 0;\r
+ } else {\r
+ continue;\r
+ }\r
+ break;\r
+ case JIM_EXPROP_LOGICOR_LEFT:\r
+ if (dA != 0) {\r
+ i += (int)dB;\r
+ dC = 1;\r
+ } else {\r
+ continue;\r
+ }\r
+ break;\r
+ case JIM_EXPROP_DIV:\r
+ if (dB == 0) goto divbyzero;\r
+ dC = dA/dB;\r
+ break;\r
+ default:\r
+ dC = 0; /* avoid gcc warning */\r
+ break;\r
+ }\r
+ stack[stacklen] = Jim_NewDoubleObj(interp, dC);\r
+ Jim_IncrRefCount(stack[stacklen]);\r
+ stacklen++;\r
+ } else if (opcode == JIM_EXPROP_STREQ || opcode == JIM_EXPROP_STRNE) {\r
+ B = stack[--stacklen];\r
+ A = stack[--stacklen];\r
+ sA = Jim_GetString(A, &Alen);\r
+ sB = Jim_GetString(B, &Blen);\r
+ switch(expr->opcode[i]) {\r
+ case JIM_EXPROP_STREQ:\r
+ if (Alen == Blen && memcmp(sA, sB, Alen) ==0)\r
+ wC = 1;\r
+ else\r
+ wC = 0;\r
+ break;\r
+ case JIM_EXPROP_STRNE:\r
+ if (Alen != Blen || memcmp(sA, sB, Alen) != 0)\r
+ wC = 1;\r
+ else\r
+ wC = 0;\r
+ break;\r
+ default:\r
+ wC = 0; /* avoid gcc warning */\r
+ break;\r
+ }\r
+ Jim_DecrRefCount(interp, A);\r
+ Jim_DecrRefCount(interp, B);\r
+ stack[stacklen] = Jim_NewIntObj(interp, wC);\r
+ Jim_IncrRefCount(stack[stacklen]);\r
+ stacklen++;\r
+ } else if (opcode == JIM_EXPROP_NOT ||\r
+ opcode == JIM_EXPROP_BITNOT ||\r
+ opcode == JIM_EXPROP_LOGICAND_RIGHT ||\r
+ opcode == JIM_EXPROP_LOGICOR_RIGHT) {\r
+ /* Note that there isn't to increment the\r
+ * refcount of objects. the references are moved\r
+ * from stack to A and B. */\r
+ A = stack[--stacklen];\r
+\r
+ /* --- Integer --- */\r
+ if ((A->typePtr == &doubleObjType && !A->bytes) ||\r
+ JimGetWideNoErr(interp, A, &wA) != JIM_OK) {\r
+ goto trydouble_unary;\r
+ }\r
+ Jim_DecrRefCount(interp, A);\r
+ switch(expr->opcode[i]) {\r
+ case JIM_EXPROP_NOT: wC = !wA; break;\r
+ case JIM_EXPROP_BITNOT: wC = ~wA; break;\r
+ case JIM_EXPROP_LOGICAND_RIGHT:\r
+ case JIM_EXPROP_LOGICOR_RIGHT: wC = (wA != 0); break;\r
+ default:\r
+ wC = 0; /* avoid gcc warning */\r
+ break;\r
+ }\r
+ stack[stacklen] = Jim_NewIntObj(interp, wC);\r
+ Jim_IncrRefCount(stack[stacklen]);\r
+ stacklen++;\r
+ continue;\r
+trydouble_unary:\r
+ /* --- Double --- */\r
+ if (Jim_GetDouble(interp, A, &dA) != JIM_OK) {\r
+ Jim_DecrRefCount(interp, A);\r
+ error = 1;\r
+ goto err;\r
+ }\r
+ Jim_DecrRefCount(interp, A);\r
+ switch(expr->opcode[i]) {\r
+ case JIM_EXPROP_NOT: dC = !dA; break;\r
+ case JIM_EXPROP_LOGICAND_RIGHT:\r
+ case JIM_EXPROP_LOGICOR_RIGHT: dC = (dA != 0); break;\r
+ case JIM_EXPROP_BITNOT:\r
+ Jim_SetResultString(interp,\r
+ "Got floating-point value where integer was expected", -1);\r
+ error = 1;\r
+ goto err;\r
+ break;\r
+ default:\r
+ dC = 0; /* avoid gcc warning */\r
+ break;\r
+ }\r
+ stack[stacklen] = Jim_NewDoubleObj(interp, dC);\r
+ Jim_IncrRefCount(stack[stacklen]);\r
+ stacklen++;\r
+ } else {\r
+ Jim_Panic(interp,"Unknown opcode in Jim_EvalExpression");\r
+ }\r
+ }\r
+err:\r
+ /* There is no need to decerement the inUse field because\r
+ * this reference is transfered back into the exprObjPtr. */\r
+ Jim_FreeIntRep(interp, exprObjPtr);\r
+ exprObjPtr->typePtr = &exprObjType;\r
+ Jim_SetIntRepPtr(exprObjPtr, expr);\r
+ Jim_DecrRefCount(interp, exprObjPtr);\r
+ if (!error) {\r
+ *exprResultPtrPtr = stack[0];\r
+ Jim_IncrRefCount(stack[0]);\r
+ errRetCode = JIM_OK;\r
+ }\r
+ for (i = 0; i < stacklen; i++) {\r
+ Jim_DecrRefCount(interp, stack[i]);\r
+ }\r
+ if (stack != staticStack)\r
+ Jim_Free(stack);\r
+ return errRetCode;\r
+divbyzero:\r
+ error = 1;\r
+ Jim_SetResultString(interp, "Division by zero", -1);\r
+ goto err;\r
+}\r
+\r
+int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)\r
+{\r
+ int retcode;\r
+ jim_wide wideValue;\r
+ double doubleValue;\r
+ Jim_Obj *exprResultPtr;\r
+\r
+ retcode = Jim_EvalExpression(interp, exprObjPtr, &exprResultPtr);\r
+ if (retcode != JIM_OK)\r
+ return retcode;\r
+ if (JimGetWideNoErr(interp, exprResultPtr, &wideValue) != JIM_OK) {\r
+ if (Jim_GetDouble(interp, exprResultPtr, &doubleValue) != JIM_OK)\r
+ {\r
+ Jim_DecrRefCount(interp, exprResultPtr);\r
+ return JIM_ERR;\r
+ } else {\r
+ Jim_DecrRefCount(interp, exprResultPtr);\r
+ *boolPtr = doubleValue != 0;\r
+ return JIM_OK;\r
+ }\r
+ }\r
+ Jim_DecrRefCount(interp, exprResultPtr);\r
+ *boolPtr = wideValue != 0;\r
+ return JIM_OK;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * ScanFormat String Object\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* This Jim_Obj will held a parsed representation of a format string passed to\r
+ * the Jim_ScanString command. For error diagnostics, the scanformat string has\r
+ * to be parsed in its entirely first and then, if correct, can be used for\r
+ * scanning. To avoid endless re-parsing, the parsed representation will be\r
+ * stored in an internal representation and re-used for performance reason. */\r
+ \r
+/* A ScanFmtPartDescr will held the information of /one/ part of the whole\r
+ * scanformat string. This part will later be used to extract information\r
+ * out from the string to be parsed by Jim_ScanString */\r
+ \r
+typedef struct ScanFmtPartDescr {\r
+ char type; /* Type of conversion (e.g. c, d, f) */\r
+ char modifier; /* Modify type (e.g. l - long, h - short */\r
+ size_t width; /* Maximal width of input to be converted */\r
+ int pos; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */ \r
+ char *arg; /* Specification of a CHARSET conversion */\r
+ char *prefix; /* Prefix to be scanned literally before conversion */\r
+} ScanFmtPartDescr;\r
+\r
+/* The ScanFmtStringObj will held the internal representation of a scanformat\r
+ * string parsed and separated in part descriptions. Furthermore it contains\r
+ * the original string representation of the scanformat string to allow for\r
+ * fast update of the Jim_Obj's string representation part.\r
+ *\r
+ * As add-on the internal object representation add some scratch pad area\r
+ * for usage by Jim_ScanString to avoid endless allocating and freeing of\r
+ * memory for purpose of string scanning.\r
+ *\r
+ * The error member points to a static allocated string in case of a mal-\r
+ * formed scanformat string or it contains '0' (NULL) in case of a valid\r
+ * parse representation.\r
+ *\r
+ * The whole memory of the internal representation is allocated as a single\r
+ * area of memory that will be internally separated. So freeing and duplicating\r
+ * of such an object is cheap */\r
+\r
+typedef struct ScanFmtStringObj {\r
+ jim_wide size; /* Size of internal repr in bytes */\r
+ char *stringRep; /* Original string representation */\r
+ size_t count; /* Number of ScanFmtPartDescr contained */\r
+ size_t convCount; /* Number of conversions that will assign */\r
+ size_t maxPos; /* Max position index if XPG3 is used */\r
+ const char *error; /* Ptr to error text (NULL if no error */\r
+ char *scratch; /* Some scratch pad used by Jim_ScanString */\r
+ ScanFmtPartDescr descr[1]; /* The vector of partial descriptions */\r
+} ScanFmtStringObj;\r
+\r
+\r
+static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);\r
+static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);\r
+static void UpdateStringOfScanFmt(Jim_Obj *objPtr);\r
+\r
+static Jim_ObjType scanFmtStringObjType = {\r
+ "scanformatstring",\r
+ FreeScanFmtInternalRep,\r
+ DupScanFmtInternalRep,\r
+ UpdateStringOfScanFmt,\r
+ JIM_TYPE_NONE,\r
+};\r
+\r
+void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ JIM_NOTUSED(interp);\r
+ Jim_Free((char*)objPtr->internalRep.ptr);\r
+ objPtr->internalRep.ptr = 0;\r
+}\r
+\r
+void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)\r
+{\r
+ size_t size = (size_t)((ScanFmtStringObj*)srcPtr->internalRep.ptr)->size;\r
+ ScanFmtStringObj *newVec = (ScanFmtStringObj*)Jim_Alloc(size);\r
+\r
+ JIM_NOTUSED(interp);\r
+ memcpy(newVec, srcPtr->internalRep.ptr, size);\r
+ dupPtr->internalRep.ptr = newVec;\r
+ dupPtr->typePtr = &scanFmtStringObjType;\r
+}\r
+\r
+void UpdateStringOfScanFmt(Jim_Obj *objPtr)\r
+{\r
+ char *bytes = ((ScanFmtStringObj*)objPtr->internalRep.ptr)->stringRep;\r
+\r
+ objPtr->bytes = Jim_StrDup(bytes);\r
+ objPtr->length = strlen(bytes);\r
+}\r
+\r
+/* SetScanFmtFromAny will parse a given string and create the internal\r
+ * representation of the format specification. In case of an error\r
+ * the error data member of the internal representation will be set\r
+ * to an descriptive error text and the function will be left with\r
+ * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat\r
+ * specification */\r
+\r
+static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)\r
+{\r
+ ScanFmtStringObj *fmtObj;\r
+ char *buffer;\r
+ int maxCount, i, approxSize, lastPos = -1;\r
+ const char *fmt = objPtr->bytes;\r
+ int maxFmtLen = objPtr->length;\r
+ const char *fmtEnd = fmt + maxFmtLen;\r
+ int curr;\r
+\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ /* Count how many conversions could take place maximally */\r
+ for (i=0, maxCount=0; i < maxFmtLen; ++i)\r
+ if (fmt[i] == '%')\r
+ ++maxCount;\r
+ /* Calculate an approximation of the memory necessary */\r
+ approxSize = sizeof(ScanFmtStringObj) /* Size of the container */\r
+ + (maxCount + 1) * sizeof(ScanFmtPartDescr) /* Size of all partials */\r
+ + maxFmtLen * sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */\r
+ + maxFmtLen * sizeof(char) + 1 /* Original stringrep */\r
+ + maxFmtLen * sizeof(char) /* Arg for CHARSETs */\r
+ + (maxCount +1) * sizeof(char) /* '\0' for every partial */\r
+ + 1; /* safety byte */\r
+ fmtObj = (ScanFmtStringObj*)Jim_Alloc(approxSize);\r
+ memset(fmtObj, 0, approxSize);\r
+ fmtObj->size = approxSize;\r
+ fmtObj->maxPos = 0;\r
+ fmtObj->scratch = (char*)&fmtObj->descr[maxCount+1];\r
+ fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;\r
+ memcpy(fmtObj->stringRep, fmt, maxFmtLen);\r
+ buffer = fmtObj->stringRep + maxFmtLen + 1;\r
+ objPtr->internalRep.ptr = fmtObj;\r
+ objPtr->typePtr = &scanFmtStringObjType;\r
+ for (i=0, curr=0; fmt < fmtEnd; ++fmt) {\r
+ int width=0, skip;\r
+ ScanFmtPartDescr *descr = &fmtObj->descr[curr];\r
+ fmtObj->count++;\r
+ descr->width = 0; /* Assume width unspecified */ \r
+ /* Overread and store any "literal" prefix */\r
+ if (*fmt != '%' || fmt[1] == '%') {\r
+ descr->type = 0;\r
+ descr->prefix = &buffer[i];\r
+ for (; fmt < fmtEnd; ++fmt) {\r
+ if (*fmt == '%') {\r
+ if (fmt[1] != '%') break;\r
+ ++fmt;\r
+ }\r
+ buffer[i++] = *fmt;\r
+ }\r
+ buffer[i++] = 0;\r
+ } \r
+ /* Skip the conversion introducing '%' sign */\r
+ ++fmt; \r
+ /* End reached due to non-conversion literal only? */\r
+ if (fmt >= fmtEnd)\r
+ goto done;\r
+ descr->pos = 0; /* Assume "natural" positioning */\r
+ if (*fmt == '*') {\r
+ descr->pos = -1; /* Okay, conversion will not be assigned */\r
+ ++fmt;\r
+ } else\r
+ fmtObj->convCount++; /* Otherwise count as assign-conversion */\r
+ /* Check if next token is a number (could be width or pos */\r
+ if (sscanf(fmt, "%d%n", &width, &skip) == 1) {\r
+ fmt += skip;\r
+ /* Was the number a XPG3 position specifier? */\r
+ if (descr->pos != -1 && *fmt == '$') {\r
+ int prev;\r
+ ++fmt;\r
+ descr->pos = width;\r
+ width = 0;\r
+ /* Look if "natural" postioning and XPG3 one was mixed */\r
+ if ((lastPos == 0 && descr->pos > 0)\r
+ || (lastPos > 0 && descr->pos == 0)) {\r
+ fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";\r
+ return JIM_ERR;\r
+ }\r
+ /* Look if this position was already used */\r
+ for (prev=0; prev < curr; ++prev) {\r
+ if (fmtObj->descr[prev].pos == -1) continue;\r
+ if (fmtObj->descr[prev].pos == descr->pos) {\r
+ fmtObj->error = "same \"%n$\" conversion specifier "\r
+ "used more than once";\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ /* Try to find a width after the XPG3 specifier */\r
+ if (sscanf(fmt, "%d%n", &width, &skip) == 1) {\r
+ descr->width = width;\r
+ fmt += skip;\r
+ }\r
+ if (descr->pos > 0 && (size_t)descr->pos > fmtObj->maxPos)\r
+ fmtObj->maxPos = descr->pos;\r
+ } else {\r
+ /* Number was not a XPG3, so it has to be a width */\r
+ descr->width = width;\r
+ }\r
+ }\r
+ /* If positioning mode was undetermined yet, fix this */\r
+ if (lastPos == -1)\r
+ lastPos = descr->pos;\r
+ /* Handle CHARSET conversion type ... */\r
+ if (*fmt == '[') {\r
+ int swapped = 1, beg = i, end, j;\r
+ descr->type = '[';\r
+ descr->arg = &buffer[i];\r
+ ++fmt;\r
+ if (*fmt == '^') buffer[i++] = *fmt++;\r
+ if (*fmt == ']') buffer[i++] = *fmt++;\r
+ while (*fmt && *fmt != ']') buffer[i++] = *fmt++;\r
+ if (*fmt != ']') {\r
+ fmtObj->error = "unmatched [ in format string";\r
+ return JIM_ERR;\r
+ } \r
+ end = i;\r
+ buffer[i++] = 0;\r
+ /* In case a range fence was given "backwards", swap it */\r
+ while (swapped) {\r
+ swapped = 0;\r
+ for (j=beg+1; j < end-1; ++j) {\r
+ if (buffer[j] == '-' && buffer[j-1] > buffer[j+1]) {\r
+ char tmp = buffer[j-1];\r
+ buffer[j-1] = buffer[j+1];\r
+ buffer[j+1] = tmp;\r
+ swapped = 1;\r
+ }\r
+ }\r
+ }\r
+ } else {\r
+ /* Remember any valid modifier if given */\r
+ if (strchr("hlL", *fmt) != 0)\r
+ descr->modifier = tolower((int)*fmt++);\r
+ \r
+ descr->type = *fmt;\r
+ if (strchr("efgcsndoxui", *fmt) == 0) {\r
+ fmtObj->error = "bad scan conversion character";\r
+ return JIM_ERR;\r
+ } else if (*fmt == 'c' && descr->width != 0) {\r
+ fmtObj->error = "field width may not be specified in %c "\r
+ "conversion";\r
+ return JIM_ERR;\r
+ } else if (*fmt == 'u' && descr->modifier == 'l') {\r
+ fmtObj->error = "unsigned wide not supported";\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ curr++;\r
+ }\r
+done:\r
+ if (fmtObj->convCount == 0) {\r
+ fmtObj->error = "no any conversion specifier given";\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* Some accessor macros to allow lowlevel access to fields of internal repr */\r
+\r
+#define FormatGetCnvCount(_fo_) \\r
+ ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount\r
+#define FormatGetMaxPos(_fo_) \\r
+ ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos\r
+#define FormatGetError(_fo_) \\r
+ ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error\r
+\r
+/* Some Bit testing/setting/cleaning routines. For now only used in handling\r
+ * charsets ([a-z123]) within scanning. Later on perhaps a base for a \r
+ * bitvector implementation in Jim? */ \r
+\r
+static int JimTestBit(const char *bitvec, char ch)\r
+{\r
+ div_t pos = div(ch-1, 8);\r
+ return bitvec[pos.quot] & (1 << pos.rem);\r
+}\r
+\r
+static void JimSetBit(char *bitvec, char ch)\r
+{\r
+ div_t pos = div(ch-1, 8);\r
+ bitvec[pos.quot] |= (1 << pos.rem);\r
+}\r
+\r
+#if 0 /* currently not used */\r
+static void JimClearBit(char *bitvec, char ch)\r
+{\r
+ div_t pos = div(ch-1, 8);\r
+ bitvec[pos.quot] &= ~(1 << pos.rem);\r
+}\r
+#endif\r
+\r
+/* JimScanAString is used to scan an unspecified string that ends with\r
+ * next WS, or a string that is specified via a charset. The charset\r
+ * is currently implemented in a way to only allow for usage with\r
+ * ASCII. Whenever we will switch to UNICODE, another idea has to\r
+ * be born :-/\r
+ *\r
+ * FIXME: Works only with ASCII */\r
+\r
+static Jim_Obj *\r
+JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)\r
+{\r
+ size_t i;\r
+ Jim_Obj *result;\r
+ char charset[256/8+1]; /* A Charset may contain max 256 chars */\r
+ char *buffer = Jim_Alloc(strlen(str)+1), *anchor = buffer;\r
+\r
+ /* First init charset to nothing or all, depending if a specified\r
+ * or an unspecified string has to be parsed */\r
+ memset(charset, (sdescr ? 0 : 255), sizeof(charset));\r
+ if (sdescr) {\r
+ /* There was a set description given, that means we are parsing\r
+ * a specified string. So we have to build a corresponding \r
+ * charset reflecting the description */\r
+ int notFlag = 0;\r
+ /* Should the set be negated at the end? */\r
+ if (*sdescr == '^') {\r
+ notFlag = 1;\r
+ ++sdescr;\r
+ }\r
+ /* Here '-' is meant literally and not to define a range */\r
+ if (*sdescr == '-') {\r
+ JimSetBit(charset, '-');\r
+ ++sdescr;\r
+ }\r
+ while (*sdescr) {\r
+ if (sdescr[1] == '-' && sdescr[2] != 0) {\r
+ /* Handle range definitions */\r
+ int i;\r
+ for (i=sdescr[0]; i <= sdescr[2]; ++i)\r
+ JimSetBit(charset, (char)i);\r
+ sdescr += 3;\r
+ } else {\r
+ /* Handle verbatim character definitions */\r
+ JimSetBit(charset, *sdescr++);\r
+ }\r
+ }\r
+ /* Negate the charset if there was a NOT given */\r
+ for (i=0; notFlag && i < sizeof(charset); ++i)\r
+ charset[i] = ~charset[i];\r
+ } \r
+ /* And after all the mess above, the real work begin ... */\r
+ while (str && *str) {\r
+ if (!sdescr && isspace((int)*str))\r
+ break; /* EOS via WS if unspecified */\r
+ if (JimTestBit(charset, *str)) *buffer++ = *str++;\r
+ else break; /* EOS via mismatch if specified scanning */\r
+ }\r
+ *buffer = 0; /* Close the string properly ... */\r
+ result = Jim_NewStringObj(interp, anchor, -1);\r
+ Jim_Free(anchor); /* ... and free it afer usage */\r
+ return result;\r
+}\r
+\r
+/* ScanOneEntry will scan one entry out of the string passed as argument.\r
+ * It use the sscanf() function for this task. After extracting and\r
+ * converting of the value, the count of scanned characters will be\r
+ * returned of -1 in case of no conversion tool place and string was\r
+ * already scanned thru */\r
+\r
+static int ScanOneEntry(Jim_Interp *interp, const char *str, long pos,\r
+ ScanFmtStringObj *fmtObj, long index, Jim_Obj **valObjPtr)\r
+{\r
+# define MAX_SIZE (sizeof(jim_wide) > sizeof(double) \\r
+ ? sizeof(jim_wide) \\r
+ : sizeof(double))\r
+ char buffer[MAX_SIZE];\r
+ char *value = buffer;\r
+ const char *tok;\r
+ const ScanFmtPartDescr *descr = &fmtObj->descr[index];\r
+ size_t sLen = strlen(&str[pos]), scanned = 0;\r
+ size_t anchor = pos;\r
+ int i;\r
+\r
+ /* First pessimiticly assume, we will not scan anything :-) */\r
+ *valObjPtr = 0;\r
+ if (descr->prefix) {\r
+ /* There was a prefix given before the conversion, skip it and adjust\r
+ * the string-to-be-parsed accordingly */\r
+ for (i=0; str[pos] && descr->prefix[i]; ++i) {\r
+ /* If prefix require, skip WS */\r
+ if (isspace((int)descr->prefix[i]))\r
+ while (str[pos] && isspace((int)str[pos])) ++pos;\r
+ else if (descr->prefix[i] != str[pos]) \r
+ break; /* Prefix do not match here, leave the loop */\r
+ else\r
+ ++pos; /* Prefix matched so far, next round */\r
+ }\r
+ if (str[pos] == 0)\r
+ return -1; /* All of str consumed: EOF condition */\r
+ else if (descr->prefix[i] != 0)\r
+ return 0; /* Not whole prefix consumed, no conversion possible */\r
+ }\r
+ /* For all but following conversion, skip leading WS */\r
+ if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')\r
+ while (isspace((int)str[pos])) ++pos;\r
+ /* Determine how much skipped/scanned so far */\r
+ scanned = pos - anchor;\r
+ if (descr->type == 'n') {\r
+ /* Return pseudo conversion means: how much scanned so far? */\r
+ *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);\r
+ } else if (str[pos] == 0) {\r
+ /* Cannot scan anything, as str is totally consumed */\r
+ return -1;\r
+ } else {\r
+ /* Processing of conversions follows ... */\r
+ if (descr->width > 0) {\r
+ /* Do not try to scan as fas as possible but only the given width.\r
+ * To ensure this, we copy the part that should be scanned. */\r
+ size_t tLen = descr->width > sLen ? sLen : descr->width;\r
+ tok = Jim_StrDupLen(&str[pos], tLen);\r
+ } else {\r
+ /* As no width was given, simply refer to the original string */\r
+ tok = &str[pos];\r
+ }\r
+ switch (descr->type) {\r
+ case 'c':\r
+ *valObjPtr = Jim_NewIntObj(interp, *tok);\r
+ scanned += 1;\r
+ break;\r
+ case 'd': case 'o': case 'x': case 'u': case 'i': {\r
+ char *endp; /* Position where the number finished */\r
+ int base = descr->type == 'o' ? 8\r
+ : descr->type == 'x' ? 16\r
+ : descr->type == 'i' ? 0\r
+ : 10;\r
+ \r
+ do {\r
+ /* Try to scan a number with the given base */\r
+ if (descr->modifier == 'l')\r
+#ifdef HAVE_LONG_LONG\r
+ *(jim_wide*)value = JimStrtoll(tok, &endp, base);\r
+#else\r
+ *(jim_wide*)value = strtol(tok, &endp, base);\r
+#endif\r
+ else\r
+ if (descr->type == 'u')\r
+ *(long*)value = strtoul(tok, &endp, base);\r
+ else\r
+ *(long*)value = strtol(tok, &endp, base);\r
+ /* If scanning failed, and base was undetermined, simply\r
+ * put it to 10 and try once more. This should catch the\r
+ * case where %i begin to parse a number prefix (e.g. \r
+ * '0x' but no further digits follows. This will be\r
+ * handled as a ZERO followed by a char 'x' by Tcl */\r
+ if (endp == tok && base == 0) base = 10;\r
+ else break;\r
+ } while (1);\r
+ if (endp != tok) {\r
+ /* There was some number sucessfully scanned! */\r
+ if (descr->modifier == 'l')\r
+ *valObjPtr = Jim_NewIntObj(interp, *(jim_wide*)value);\r
+ else\r
+ *valObjPtr = Jim_NewIntObj(interp, *(long*)value);\r
+ /* Adjust the number-of-chars scanned so far */\r
+ scanned += endp - tok;\r
+ } else {\r
+ /* Nothing was scanned. We have to determine if this\r
+ * happened due to e.g. prefix mismatch or input str\r
+ * exhausted */\r
+ scanned = *tok ? 0 : -1;\r
+ }\r
+ break;\r
+ }\r
+ case 's': case '[': {\r
+ *valObjPtr = JimScanAString(interp, descr->arg, tok);\r
+ scanned += Jim_Length(*valObjPtr);\r
+ break;\r
+ }\r
+ case 'e': case 'f': case 'g': {\r
+ char *endp;\r
+\r
+ *(double*)value = strtod(tok, &endp);\r
+ if (endp != tok) {\r
+ /* There was some number sucessfully scanned! */\r
+ *valObjPtr = Jim_NewDoubleObj(interp, *(double*)value);\r
+ /* Adjust the number-of-chars scanned so far */\r
+ scanned += endp - tok;\r
+ } else {\r
+ /* Nothing was scanned. We have to determine if this\r
+ * happened due to e.g. prefix mismatch or input str\r
+ * exhausted */\r
+ scanned = *tok ? 0 : -1;\r
+ }\r
+ break;\r
+ }\r
+ }\r
+ /* If a substring was allocated (due to pre-defined width) do not\r
+ * forget to free it */\r
+ if (tok != &str[pos])\r
+ Jim_Free((char*)tok);\r
+ }\r
+ return scanned;\r
+}\r
+\r
+/* Jim_ScanString is the workhorse of string scanning. It will scan a given\r
+ * string and returns all converted (and not ignored) values in a list back\r
+ * to the caller. If an error occured, a NULL pointer will be returned */\r
+\r
+Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr,\r
+ Jim_Obj *fmtObjPtr, int flags)\r
+{\r
+ size_t i, pos;\r
+ int scanned = 1;\r
+ const char *str = Jim_GetString(strObjPtr, 0);\r
+ Jim_Obj *resultList = 0;\r
+ Jim_Obj **resultVec;\r
+ int resultc;\r
+ Jim_Obj *emptyStr = 0;\r
+ ScanFmtStringObj *fmtObj;\r
+\r
+ /* If format specification is not an object, convert it! */\r
+ if (fmtObjPtr->typePtr != &scanFmtStringObjType)\r
+ SetScanFmtFromAny(interp, fmtObjPtr);\r
+ fmtObj = (ScanFmtStringObj*)fmtObjPtr->internalRep.ptr;\r
+ /* Check if format specification was valid */\r
+ if (fmtObj->error != 0) {\r
+ if (flags & JIM_ERRMSG)\r
+ Jim_SetResultString(interp, fmtObj->error, -1);\r
+ return 0;\r
+ }\r
+ /* Allocate a new "shared" empty string for all unassigned conversions */\r
+ emptyStr = Jim_NewEmptyStringObj(interp);\r
+ Jim_IncrRefCount(emptyStr);\r
+ /* Create a list and fill it with empty strings up to max specified XPG3 */\r
+ resultList = Jim_NewListObj(interp, 0, 0);\r
+ if (fmtObj->maxPos > 0) {\r
+ for (i=0; i < fmtObj->maxPos; ++i)\r
+ Jim_ListAppendElement(interp, resultList, emptyStr);\r
+ JimListGetElements(interp, resultList, &resultc, &resultVec);\r
+ }\r
+ /* Now handle every partial format description */\r
+ for (i=0, pos=0; i < fmtObj->count; ++i) {\r
+ ScanFmtPartDescr *descr = &(fmtObj->descr[i]);\r
+ Jim_Obj *value = 0;\r
+ /* Only last type may be "literal" w/o conversion - skip it! */\r
+ if (descr->type == 0) continue;\r
+ /* As long as any conversion could be done, we will proceed */\r
+ if (scanned > 0)\r
+ scanned = ScanOneEntry(interp, str, pos, fmtObj, i, &value);\r
+ /* In case our first try results in EOF, we will leave */\r
+ if (scanned == -1 && i == 0)\r
+ goto eof;\r
+ /* Advance next pos-to-be-scanned for the amount scanned already */\r
+ pos += scanned;\r
+ /* value == 0 means no conversion took place so take empty string */\r
+ if (value == 0)\r
+ value = Jim_NewEmptyStringObj(interp);\r
+ /* If value is a non-assignable one, skip it */\r
+ if (descr->pos == -1) {\r
+ Jim_FreeNewObj(interp, value);\r
+ } else if (descr->pos == 0)\r
+ /* Otherwise append it to the result list if no XPG3 was given */\r
+ Jim_ListAppendElement(interp, resultList, value);\r
+ else if (resultVec[descr->pos-1] == emptyStr) {\r
+ /* But due to given XPG3, put the value into the corr. slot */\r
+ Jim_DecrRefCount(interp, resultVec[descr->pos-1]);\r
+ Jim_IncrRefCount(value);\r
+ resultVec[descr->pos-1] = value;\r
+ } else {\r
+ /* Otherwise, the slot was already used - free obj and ERROR */\r
+ Jim_FreeNewObj(interp, value);\r
+ goto err;\r
+ }\r
+ }\r
+ Jim_DecrRefCount(interp, emptyStr);\r
+ return resultList;\r
+eof:\r
+ Jim_DecrRefCount(interp, emptyStr);\r
+ Jim_FreeNewObj(interp, resultList);\r
+ return (Jim_Obj*)EOF;\r
+err:\r
+ Jim_DecrRefCount(interp, emptyStr);\r
+ Jim_FreeNewObj(interp, resultList);\r
+ return 0;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Pseudo Random Number Generation\r
+ * ---------------------------------------------------------------------------*/\r
+static void JimPrngSeed(Jim_Interp *interp, const unsigned char *seed,\r
+ int seedLen);\r
+\r
+/* Initialize the sbox with the numbers from 0 to 255 */\r
+static void JimPrngInit(Jim_Interp *interp)\r
+{\r
+ int i;\r
+ unsigned int seed[256];\r
+\r
+ interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));\r
+ for (i = 0; i < 256; i++)\r
+ seed[i] = (rand() ^ time(NULL) ^ clock());\r
+ JimPrngSeed(interp, (unsigned char*) seed, sizeof(int)*256);\r
+}\r
+\r
+/* Generates N bytes of random data */\r
+static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)\r
+{\r
+ Jim_PrngState *prng;\r
+ unsigned char *destByte = (unsigned char*) dest;\r
+ unsigned int si, sj, x;\r
+\r
+ /* initialization, only needed the first time */\r
+ if (interp->prngState == NULL)\r
+ JimPrngInit(interp);\r
+ prng = interp->prngState;\r
+ /* generates 'len' bytes of pseudo-random numbers */\r
+ for (x = 0; x < len; x++) {\r
+ prng->i = (prng->i+1) & 0xff;\r
+ si = prng->sbox[prng->i];\r
+ prng->j = (prng->j + si) & 0xff;\r
+ sj = prng->sbox[prng->j];\r
+ prng->sbox[prng->i] = sj;\r
+ prng->sbox[prng->j] = si;\r
+ *destByte++ = prng->sbox[(si+sj)&0xff];\r
+ }\r
+}\r
+\r
+/* Re-seed the generator with user-provided bytes */\r
+static void JimPrngSeed(Jim_Interp *interp, const unsigned char *seed,\r
+ int seedLen)\r
+{\r
+ int i;\r
+ unsigned char buf[256];\r
+ Jim_PrngState *prng;\r
+\r
+ /* initialization, only needed the first time */\r
+ if (interp->prngState == NULL)\r
+ JimPrngInit(interp);\r
+ prng = interp->prngState;\r
+\r
+ /* Set the sbox[i] with i */\r
+ for (i = 0; i < 256; i++)\r
+ prng->sbox[i] = i;\r
+ /* Now use the seed to perform a random permutation of the sbox */\r
+ for (i = 0; i < seedLen; i++) {\r
+ unsigned char t;\r
+\r
+ t = prng->sbox[i&0xFF];\r
+ prng->sbox[i&0xFF] = prng->sbox[seed[i]];\r
+ prng->sbox[seed[i]] = t;\r
+ }\r
+ prng->i = prng->j = 0;\r
+ /* discard the first 256 bytes of stream. */\r
+ JimRandomBytes(interp, buf, 256);\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Dynamic libraries support (WIN32 not supported)\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+#ifdef JIM_DYNLIB\r
+#ifdef WIN32\r
+#define RTLD_LAZY 0\r
+void * dlopen(const char *path, int mode) \r
+{\r
+ JIM_NOTUSED(mode);\r
+\r
+ return (void *)LoadLibraryA(path);\r
+}\r
+int dlclose(void *handle)\r
+{\r
+ FreeLibrary((HANDLE)handle);\r
+ return 0;\r
+}\r
+void *dlsym(void *handle, const char *symbol)\r
+{\r
+ return GetProcAddress((HMODULE)handle, symbol);\r
+}\r
+static char win32_dlerror_string[121];\r
+const char *dlerror()\r
+{\r
+ FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),\r
+ LANG_NEUTRAL, win32_dlerror_string, 120, NULL);\r
+ return win32_dlerror_string;\r
+}\r
+#endif /* WIN32 */\r
+\r
+int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName)\r
+{\r
+ Jim_Obj *libPathObjPtr;\r
+ int prefixc, i;\r
+ void *handle;\r
+ int (*onload)(Jim_Interp *interp);\r
+\r
+ libPathObjPtr = Jim_GetGlobalVariableStr(interp, "jim_libpath", JIM_NONE);\r
+ if (libPathObjPtr == NULL) {\r
+ prefixc = 0;\r
+ libPathObjPtr = NULL;\r
+ } else {\r
+ Jim_IncrRefCount(libPathObjPtr);\r
+ Jim_ListLength(interp, libPathObjPtr, &prefixc);\r
+ }\r
+\r
+ for (i = -1; i < prefixc; i++) {\r
+ if (i < 0) {\r
+ handle = dlopen(pathName, RTLD_LAZY);\r
+ } else {\r
+ FILE *fp;\r
+ char buf[JIM_PATH_LEN];\r
+ const char *prefix;\r
+ int prefixlen;\r
+ Jim_Obj *prefixObjPtr;\r
+ \r
+ buf[0] = '\0';\r
+ if (Jim_ListIndex(interp, libPathObjPtr, i,\r
+ &prefixObjPtr, JIM_NONE) != JIM_OK)\r
+ continue;\r
+ prefix = Jim_GetString(prefixObjPtr, NULL);\r
+ prefixlen = strlen(prefix);\r
+ if (prefixlen+strlen(pathName)+1 >= JIM_PATH_LEN)\r
+ continue;\r
+ if (prefixlen && prefix[prefixlen-1] == '/')\r
+ sprintf(buf, "%s%s", prefix, pathName);\r
+ else\r
+ sprintf(buf, "%s/%s", prefix, pathName);\r
+ printf("opening '%s'\n", buf);\r
+ fp = fopen(buf, "r");\r
+ if (fp == NULL)\r
+ continue;\r
+ fclose(fp);\r
+ handle = dlopen(buf, RTLD_LAZY);\r
+ printf("got handle %p\n", handle);\r
+ }\r
+ if (handle == NULL) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "error loading extension \"", pathName,\r
+ "\": ", dlerror(), NULL);\r
+ if (i < 0)\r
+ continue;\r
+ goto err;\r
+ }\r
+ if ((onload = dlsym(handle, "Jim_OnLoad")) == NULL) {\r
+ Jim_SetResultString(interp,\r
+ "No Jim_OnLoad symbol found on extension", -1);\r
+ goto err;\r
+ }\r
+ if (onload(interp) == JIM_ERR) {\r
+ dlclose(handle);\r
+ goto err;\r
+ }\r
+ Jim_SetEmptyResult(interp);\r
+ if (libPathObjPtr != NULL)\r
+ Jim_DecrRefCount(interp, libPathObjPtr);\r
+ return JIM_OK;\r
+ }\r
+err:\r
+ if (libPathObjPtr != NULL)\r
+ Jim_DecrRefCount(interp, libPathObjPtr);\r
+ return JIM_ERR;\r
+}\r
+#else /* JIM_DYNLIB */\r
+int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName)\r
+{\r
+ JIM_NOTUSED(interp);\r
+ JIM_NOTUSED(pathName);\r
+\r
+ Jim_SetResultString(interp, "the Jim binary has no support for [load]", -1);\r
+ return JIM_ERR;\r
+}\r
+#endif/* JIM_DYNLIB */\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Packages handling\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+#define JIM_PKG_ANY_VERSION -1\r
+\r
+/* Convert a string of the type "1.2" into an integer.\r
+ * MAJOR.MINOR is converted as MAJOR*100+MINOR, so "1.2" is converted \r
+ * to the integer with value 102 */\r
+static int JimPackageVersionToInt(Jim_Interp *interp, const char *v,\r
+ int *intPtr, int flags)\r
+{\r
+ char *copy;\r
+ jim_wide major, minor;\r
+ char *majorStr, *minorStr, *p;\r
+\r
+ if (v[0] == '\0') {\r
+ *intPtr = JIM_PKG_ANY_VERSION;\r
+ return JIM_OK;\r
+ }\r
+\r
+ copy = Jim_StrDup(v);\r
+ p = strchr(copy, '.');\r
+ if (p == NULL) goto badfmt;\r
+ *p = '\0';\r
+ majorStr = copy;\r
+ minorStr = p+1;\r
+\r
+ if (Jim_StringToWide(majorStr, &major, 10) != JIM_OK ||\r
+ Jim_StringToWide(minorStr, &minor, 10) != JIM_OK)\r
+ goto badfmt;\r
+ *intPtr = (int)(major*100+minor);\r
+ Jim_Free(copy);\r
+ return JIM_OK;\r
+\r
+badfmt:\r
+ Jim_Free(copy);\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "invalid package version '", v, "'", NULL);\r
+ }\r
+ return JIM_ERR;\r
+}\r
+\r
+#define JIM_MATCHVER_EXACT (1<<JIM_PRIV_FLAG_SHIFT)\r
+static int JimPackageMatchVersion(int needed, int actual, int flags)\r
+{\r
+ if (needed == JIM_PKG_ANY_VERSION) return 1;\r
+ if (flags & JIM_MATCHVER_EXACT) {\r
+ return needed == actual;\r
+ } else {\r
+ return needed/100 == actual/100 && (needed <= actual);\r
+ }\r
+}\r
+\r
+int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver,\r
+ int flags)\r
+{\r
+ int intVersion;\r
+ /* Check if the version format is ok */\r
+ if (JimPackageVersionToInt(interp, ver, &intVersion, JIM_ERRMSG) != JIM_OK)\r
+ return JIM_ERR;\r
+ /* If the package was already provided returns an error. */\r
+ if (Jim_FindHashEntry(&interp->packages, name) != NULL) {\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "package '", name, "' was already provided", NULL);\r
+ }\r
+ return JIM_ERR;\r
+ }\r
+ Jim_AddHashEntry(&interp->packages, name, (char*) ver);\r
+ return JIM_OK;\r
+}\r
+\r
+#ifndef JIM_ANSIC\r
+\r
+#ifndef WIN32\r
+# include <sys/types.h>\r
+# include <dirent.h>\r
+#else\r
+# include <io.h>\r
+/* Posix dirent.h compatiblity layer for WIN32.\r
+ * Copyright Kevlin Henney, 1997, 2003. All rights reserved.\r
+ * Copyright Salvatore Sanfilippo ,2005.\r
+ *\r
+ * Permission to use, copy, modify, and distribute this software and its\r
+ * documentation for any purpose is hereby granted without fee, provided\r
+ * that this copyright and permissions notice appear in all copies and\r
+ * derivatives.\r
+ *\r
+ * This software is supplied "as is" without express or implied warranty.\r
+ * This software was modified by Salvatore Sanfilippo for the Jim Interpreter.\r
+ */\r
+\r
+struct dirent {\r
+ char *d_name;\r
+};\r
+\r
+typedef struct DIR {\r
+ long handle; /* -1 for failed rewind */\r
+ struct _finddata_t info;\r
+ struct dirent result; /* d_name null iff first time */\r
+ char *name; /* null-terminated char string */\r
+} DIR;\r
+\r
+DIR *opendir(const char *name)\r
+{\r
+ DIR *dir = 0;\r
+\r
+ if(name && name[0]) {\r
+ size_t base_length = strlen(name);\r
+ const char *all = /* search pattern must end with suitable wildcard */\r
+ strchr("/\\", name[base_length - 1]) ? "*" : "/*";\r
+\r
+ if((dir = (DIR *) Jim_Alloc(sizeof *dir)) != 0 &&\r
+ (dir->name = (char *) Jim_Alloc(base_length + strlen(all) + 1)) != 0)\r
+ {\r
+ strcat(strcpy(dir->name, name), all);\r
+\r
+ if((dir->handle = (long) _findfirst(dir->name, &dir->info)) != -1)\r
+ dir->result.d_name = 0;\r
+ else { /* rollback */\r
+ Jim_Free(dir->name);\r
+ Jim_Free(dir);\r
+ dir = 0;\r
+ }\r
+ } else { /* rollback */\r
+ Jim_Free(dir);\r
+ dir = 0;\r
+ errno = ENOMEM;\r
+ }\r
+ } else {\r
+ errno = EINVAL;\r
+ }\r
+ return dir;\r
+}\r
+\r
+int closedir(DIR *dir)\r
+{\r
+ int result = -1;\r
+\r
+ if(dir) {\r
+ if(dir->handle != -1)\r
+ result = _findclose(dir->handle);\r
+ Jim_Free(dir->name);\r
+ Jim_Free(dir);\r
+ }\r
+ if(result == -1) /* map all errors to EBADF */\r
+ errno = EBADF;\r
+ return result;\r
+}\r
+\r
+struct dirent *readdir(DIR *dir)\r
+{\r
+ struct dirent *result = 0;\r
+\r
+ if(dir && dir->handle != -1) {\r
+ if(!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1) {\r
+ result = &dir->result;\r
+ result->d_name = dir->info.name;\r
+ }\r
+ } else {\r
+ errno = EBADF;\r
+ }\r
+ return result;\r
+}\r
+\r
+#endif /* WIN32 */\r
+\r
+static char *JimFindBestPackage(Jim_Interp *interp, char **prefixes,\r
+ int prefixc, const char *pkgName, int pkgVer, int flags)\r
+{\r
+ int bestVer = -1, i;\r
+ int pkgNameLen = strlen(pkgName);\r
+ char *bestPackage = NULL;\r
+ struct dirent *de;\r
+\r
+ for (i = 0; i < prefixc; i++) {\r
+ DIR *dir;\r
+ char buf[JIM_PATH_LEN];\r
+ int prefixLen;\r
+\r
+ if (prefixes[i] == NULL) continue;\r
+ strncpy(buf, prefixes[i], JIM_PATH_LEN);\r
+ buf[JIM_PATH_LEN-1] = '\0';\r
+ prefixLen = strlen(buf);\r
+ if (prefixLen && buf[prefixLen-1] == '/')\r
+ buf[prefixLen-1] = '\0';\r
+\r
+ if ((dir = opendir(buf)) == NULL) continue;\r
+ while ((de = readdir(dir)) != NULL) {\r
+ char *fileName = de->d_name;\r
+ int fileNameLen = strlen(fileName);\r
+\r
+ if (strncmp(fileName, "jim-", 4) == 0 &&\r
+ strncmp(fileName+4, pkgName, pkgNameLen) == 0 &&\r
+ *(fileName+4+pkgNameLen) == '-' &&\r
+ fileNameLen > 4 && /* note that this is not really useful */\r
+ (strncmp(fileName+fileNameLen-4, ".tcl", 4) == 0 ||\r
+ strncmp(fileName+fileNameLen-4, ".dll", 4) == 0 ||\r
+ strncmp(fileName+fileNameLen-3, ".so", 3) == 0))\r
+ {\r
+ char ver[6]; /* xx.yy<nulterm> */\r
+ char *p = strrchr(fileName, '.');\r
+ int verLen, fileVer;\r
+\r
+ verLen = p - (fileName+4+pkgNameLen+1);\r
+ if (verLen < 3 || verLen > 5) continue;\r
+ memcpy(ver, fileName+4+pkgNameLen+1, verLen);\r
+ ver[verLen] = '\0';\r
+ if (JimPackageVersionToInt(interp, ver, &fileVer, JIM_NONE)\r
+ != JIM_OK) continue;\r
+ if (JimPackageMatchVersion(pkgVer, fileVer, flags) &&\r
+ (bestVer == -1 || bestVer < fileVer))\r
+ {\r
+ bestVer = fileVer;\r
+ Jim_Free(bestPackage);\r
+ bestPackage = Jim_Alloc(strlen(buf)+strlen(fileName)+2);\r
+ sprintf(bestPackage, "%s/%s", buf, fileName);\r
+ }\r
+ }\r
+ }\r
+ closedir(dir);\r
+ }\r
+ return bestPackage;\r
+}\r
+\r
+#else /* JIM_ANSIC */\r
+\r
+static char *JimFindBestPackage(Jim_Interp *interp, char **prefixes,\r
+ int prefixc, const char *pkgName, int pkgVer, int flags)\r
+{\r
+ JIM_NOTUSED(interp);\r
+ JIM_NOTUSED(prefixes);\r
+ JIM_NOTUSED(prefixc);\r
+ JIM_NOTUSED(pkgName);\r
+ JIM_NOTUSED(pkgVer);\r
+ JIM_NOTUSED(flags);\r
+ return NULL;\r
+}\r
+\r
+#endif /* JIM_ANSIC */\r
+\r
+/* Search for a suitable package under every dir specified by jim_libpath\r
+ * and load it if possible. If a suitable package was loaded with success\r
+ * JIM_OK is returned, otherwise JIM_ERR is returned. */\r
+static int JimLoadPackage(Jim_Interp *interp, const char *name, int ver,\r
+ int flags)\r
+{\r
+ Jim_Obj *libPathObjPtr;\r
+ char **prefixes, *best;\r
+ int prefixc, i, retCode = JIM_OK;\r
+\r
+ libPathObjPtr = Jim_GetGlobalVariableStr(interp, "jim_libpath", JIM_NONE);\r
+ if (libPathObjPtr == NULL) {\r
+ prefixc = 0;\r
+ libPathObjPtr = NULL;\r
+ } else {\r
+ Jim_IncrRefCount(libPathObjPtr);\r
+ Jim_ListLength(interp, libPathObjPtr, &prefixc);\r
+ }\r
+\r
+ prefixes = Jim_Alloc(sizeof(char*)*prefixc);\r
+ for (i = 0; i < prefixc; i++) {\r
+ Jim_Obj *prefixObjPtr;\r
+ if (Jim_ListIndex(interp, libPathObjPtr, i,\r
+ &prefixObjPtr, JIM_NONE) != JIM_OK)\r
+ {\r
+ prefixes[i] = NULL;\r
+ continue;\r
+ }\r
+ prefixes[i] = Jim_StrDup(Jim_GetString(prefixObjPtr, NULL));\r
+ }\r
+ /* Scan every directory to find the "best" package. */\r
+ best = JimFindBestPackage(interp, prefixes, prefixc, name, ver, flags);\r
+ if (best != NULL) {\r
+ char *p = strrchr(best, '.');\r
+ /* Try to load/source it */\r
+ if (p && strcmp(p, ".tcl") == 0) {\r
+ retCode = Jim_EvalFile(interp, best);\r
+ } else {\r
+ retCode = Jim_LoadLibrary(interp, best);\r
+ }\r
+ } else {\r
+ retCode = JIM_ERR;\r
+ }\r
+ Jim_Free(best);\r
+ for (i = 0; i < prefixc; i++)\r
+ Jim_Free(prefixes[i]);\r
+ Jim_Free(prefixes);\r
+ if (libPathObjPtr)\r
+ Jim_DecrRefCount(interp, libPathObjPtr);\r
+ return retCode;\r
+}\r
+\r
+const char *Jim_PackageRequire(Jim_Interp *interp, const char *name,\r
+ const char *ver, int flags)\r
+{\r
+ Jim_HashEntry *he;\r
+ int requiredVer;\r
+\r
+ if (JimPackageVersionToInt(interp, ver, &requiredVer, JIM_ERRMSG) != JIM_OK)\r
+ return NULL;\r
+ he = Jim_FindHashEntry(&interp->packages, name);\r
+ if (he == NULL) {\r
+ /* Try to load the package. */\r
+ if (JimLoadPackage(interp, name, requiredVer, flags) == JIM_OK) {\r
+ he = Jim_FindHashEntry(&interp->packages, name);\r
+ if (he == NULL) {\r
+ return "?";\r
+ }\r
+ return he->val;\r
+ }\r
+ /* No way... return an error. */\r
+ if (flags & JIM_ERRMSG) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "Can't find package '", name, "'", NULL);\r
+ }\r
+ return NULL;\r
+ } else {\r
+ int actualVer;\r
+ if (JimPackageVersionToInt(interp, he->val, &actualVer, JIM_ERRMSG)\r
+ != JIM_OK)\r
+ {\r
+ return NULL;\r
+ }\r
+ /* Check if version matches. */\r
+ if (JimPackageMatchVersion(requiredVer, actualVer, flags) == 0) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "Package '", name, "' already loaded, but with version ",\r
+ he->val, NULL);\r
+ return NULL;\r
+ }\r
+ return he->val;\r
+ }\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Eval\r
+ * ---------------------------------------------------------------------------*/\r
+#define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */\r
+#define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */\r
+\r
+static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc,\r
+ Jim_Obj *const *argv);\r
+\r
+/* Handle calls to the [unknown] command */\r
+static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj **v, *sv[JIM_EVAL_SARGV_LEN];\r
+ int retCode;\r
+\r
+ /* If the [unknown] command does not exists returns\r
+ * just now */\r
+ if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)\r
+ return JIM_ERR;\r
+\r
+ /* The object interp->unknown just contains\r
+ * the "unknown" string, it is used in order to\r
+ * avoid to lookup the unknown command every time\r
+ * but instread to cache the result. */\r
+ if (argc+1 <= JIM_EVAL_SARGV_LEN)\r
+ v = sv;\r
+ else\r
+ v = Jim_Alloc(sizeof(Jim_Obj*)*(argc+1));\r
+ /* Make a copy of the arguments vector, but shifted on\r
+ * the right of one position. The command name of the\r
+ * command will be instead the first argument of the\r
+ * [unknonw] call. */\r
+ memcpy(v+1, argv, sizeof(Jim_Obj*)*argc);\r
+ v[0] = interp->unknown;\r
+ /* Call it */\r
+ retCode = Jim_EvalObjVector(interp, argc+1, v);\r
+ /* Clean up */\r
+ if (v != sv)\r
+ Jim_Free(v);\r
+ return retCode;\r
+}\r
+\r
+/* Eval the object vector 'objv' composed of 'objc' elements.\r
+ * Every element is used as single argument.\r
+ * Jim_EvalObj() will call this function every time its object\r
+ * argument is of "list" type, with no string representation.\r
+ *\r
+ * This is possible because the string representation of a\r
+ * list object generated by the UpdateStringOfList is made\r
+ * in a way that ensures that every list element is a different\r
+ * command argument. */\r
+int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)\r
+{\r
+ int i, retcode;\r
+ Jim_Cmd *cmdPtr;\r
+\r
+ /* Incr refcount of arguments. */\r
+ for (i = 0; i < objc; i++)\r
+ Jim_IncrRefCount(objv[i]);\r
+ /* Command lookup */\r
+ cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);\r
+ if (cmdPtr == NULL) {\r
+ retcode = JimUnknown(interp, objc, objv);\r
+ } else {\r
+ /* Call it -- Make sure result is an empty object. */\r
+ Jim_SetEmptyResult(interp);\r
+ if (cmdPtr->cmdProc) {\r
+ interp->cmdPrivData = cmdPtr->privData;\r
+ retcode = cmdPtr->cmdProc(interp, objc, objv);\r
+ } else {\r
+ retcode = JimCallProcedure(interp, cmdPtr, objc, objv);\r
+ if (retcode == JIM_ERR) {\r
+ JimAppendStackTrace(interp,\r
+ Jim_GetString(objv[0], NULL), "?", 1);\r
+ }\r
+ }\r
+ }\r
+ /* Decr refcount of arguments and return the retcode */\r
+ for (i = 0; i < objc; i++)\r
+ Jim_DecrRefCount(interp, objv[i]);\r
+ return retcode;\r
+}\r
+\r
+/* Interpolate the given tokens into a unique Jim_Obj returned by reference\r
+ * via *objPtrPtr. This function is only called by Jim_EvalObj().\r
+ * The returned object has refcount = 0. */\r
+int Jim_InterpolateTokens(Jim_Interp *interp, ScriptToken *token,\r
+ int tokens, Jim_Obj **objPtrPtr)\r
+{\r
+ int totlen = 0, i, retcode;\r
+ Jim_Obj **intv;\r
+ Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];\r
+ Jim_Obj *objPtr;\r
+ char *s;\r
+\r
+ if (tokens <= JIM_EVAL_SINTV_LEN)\r
+ intv = sintv;\r
+ else\r
+ intv = Jim_Alloc(sizeof(Jim_Obj*)*\r
+ tokens);\r
+ /* Compute every token forming the argument\r
+ * in the intv objects vector. */\r
+ for (i = 0; i < tokens; i++) {\r
+ switch(token[i].type) {\r
+ case JIM_TT_ESC:\r
+ case JIM_TT_STR:\r
+ intv[i] = token[i].objPtr;\r
+ break;\r
+ case JIM_TT_VAR:\r
+ intv[i] = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);\r
+ if (!intv[i]) {\r
+ retcode = JIM_ERR;\r
+ goto err;\r
+ }\r
+ break;\r
+ case JIM_TT_DICTSUGAR:\r
+ intv[i] = Jim_ExpandDictSugar(interp, token[i].objPtr);\r
+ if (!intv[i]) {\r
+ retcode = JIM_ERR;\r
+ goto err;\r
+ }\r
+ break;\r
+ case JIM_TT_CMD:\r
+ retcode = Jim_EvalObj(interp, token[i].objPtr);\r
+ if (retcode != JIM_OK)\r
+ goto err;\r
+ intv[i] = Jim_GetResult(interp);\r
+ break;\r
+ default:\r
+ Jim_Panic(interp,\r
+ "default token type reached "\r
+ "in Jim_InterpolateTokens().");\r
+ break;\r
+ }\r
+ Jim_IncrRefCount(intv[i]);\r
+ /* Make sure there is a valid\r
+ * string rep, and add the string\r
+ * length to the total legnth. */\r
+ Jim_GetString(intv[i], NULL);\r
+ totlen += intv[i]->length;\r
+ }\r
+ /* Concatenate every token in an unique\r
+ * object. */\r
+ objPtr = Jim_NewStringObjNoAlloc(interp,\r
+ NULL, 0);\r
+ s = objPtr->bytes = Jim_Alloc(totlen+1);\r
+ objPtr->length = totlen;\r
+ for (i = 0; i < tokens; i++) {\r
+ memcpy(s, intv[i]->bytes, intv[i]->length);\r
+ s += intv[i]->length;\r
+ Jim_DecrRefCount(interp, intv[i]);\r
+ }\r
+ objPtr->bytes[totlen] = '\0';\r
+ /* Free the intv vector if not static. */\r
+ if (tokens > JIM_EVAL_SINTV_LEN)\r
+ Jim_Free(intv);\r
+ *objPtrPtr = objPtr;\r
+ return JIM_OK;\r
+err:\r
+ i--;\r
+ for (; i >= 0; i--)\r
+ Jim_DecrRefCount(interp, intv[i]);\r
+ if (tokens > JIM_EVAL_SINTV_LEN)\r
+ Jim_Free(intv);\r
+ return retcode;\r
+}\r
+\r
+/* Helper of Jim_EvalObj() to perform argument expansion.\r
+ * Basically this function append an argument to 'argv'\r
+ * (and increments argc by reference accordingly), performing\r
+ * expansion of the list object if 'expand' is non-zero, or\r
+ * just adding objPtr to argv if 'expand' is zero. */\r
+void Jim_ExpandArgument(Jim_Interp *interp, Jim_Obj ***argv,\r
+ int *argcPtr, int expand, Jim_Obj *objPtr)\r
+{\r
+ if (!expand) {\r
+ (*argv) = Jim_Realloc(*argv, sizeof(Jim_Obj*)*((*argcPtr)+1));\r
+ /* refcount of objPtr not incremented because\r
+ * we are actually transfering a reference from\r
+ * the old 'argv' to the expanded one. */\r
+ (*argv)[*argcPtr] = objPtr;\r
+ (*argcPtr)++;\r
+ } else {\r
+ int len, i;\r
+\r
+ Jim_ListLength(interp, objPtr, &len);\r
+ (*argv) = Jim_Realloc(*argv, sizeof(Jim_Obj*)*((*argcPtr)+len));\r
+ for (i = 0; i < len; i++) {\r
+ (*argv)[*argcPtr] = objPtr->internalRep.listValue.ele[i];\r
+ Jim_IncrRefCount(objPtr->internalRep.listValue.ele[i]);\r
+ (*argcPtr)++;\r
+ }\r
+ /* The original object reference is no longer needed,\r
+ * after the expansion it is no longer present on\r
+ * the argument vector, but the single elements are\r
+ * in its place. */\r
+ Jim_DecrRefCount(interp, objPtr);\r
+ }\r
+}\r
+\r
+int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)\r
+{\r
+ int i, j = 0, len;\r
+ ScriptObj *script;\r
+ ScriptToken *token;\r
+ int *cs; /* command structure array */\r
+ int retcode = JIM_OK;\r
+ Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL, *tmpObjPtr;\r
+\r
+ interp->errorFlag = 0;\r
+\r
+ /* If the object is of type "list" and there is no\r
+ * string representation for this object, we can call\r
+ * a specialized version of Jim_EvalObj() */\r
+ if (scriptObjPtr->typePtr == &listObjType &&\r
+ scriptObjPtr->internalRep.listValue.len &&\r
+ scriptObjPtr->bytes == NULL) {\r
+ Jim_IncrRefCount(scriptObjPtr);\r
+ retcode = Jim_EvalObjVector(interp,\r
+ scriptObjPtr->internalRep.listValue.len,\r
+ scriptObjPtr->internalRep.listValue.ele);\r
+ Jim_DecrRefCount(interp, scriptObjPtr);\r
+ return retcode;\r
+ }\r
+\r
+ Jim_IncrRefCount(scriptObjPtr); /* Make sure it's shared. */\r
+ script = Jim_GetScript(interp, scriptObjPtr);\r
+ /* Now we have to make sure the internal repr will not be\r
+ * freed on shimmering.\r
+ *\r
+ * Think for example to this:\r
+ *\r
+ * set x {llength $x; ... some more code ...}; eval $x\r
+ *\r
+ * In order to preserve the internal rep, we increment the\r
+ * inUse field of the script internal rep structure. */\r
+ script->inUse++;\r
+\r
+ token = script->token;\r
+ len = script->len;\r
+ cs = script->cmdStruct;\r
+ i = 0; /* 'i' is the current token index. */\r
+\r
+ /* Reset the interpreter result. This is useful to\r
+ * return the emtpy result in the case of empty program. */\r
+ Jim_SetEmptyResult(interp);\r
+\r
+ /* Execute every command sequentially, returns on\r
+ * error (i.e. if a command does not return JIM_OK) */\r
+ while (i < len) {\r
+ int expand = 0;\r
+ int argc = *cs++; /* Get the number of arguments */\r
+ Jim_Cmd *cmd;\r
+\r
+ /* Set the expand flag if needed. */\r
+ if (argc == -1) {\r
+ expand++;\r
+ argc = *cs++;\r
+ }\r
+ /* Allocate the arguments vector */\r
+ if (argc <= JIM_EVAL_SARGV_LEN)\r
+ argv = sargv;\r
+ else\r
+ argv = Jim_Alloc(sizeof(Jim_Obj*)*argc);\r
+ /* Populate the arguments objects. */\r
+ for (j = 0; j < argc; j++) {\r
+ int tokens = *cs++;\r
+\r
+ /* tokens is negative if expansion is needed.\r
+ * for this argument. */\r
+ if (tokens < 0) {\r
+ tokens = (-tokens)-1;\r
+ i++;\r
+ }\r
+ if (tokens == 1) {\r
+ /* Fast path if the token does not\r
+ * need interpolation */\r
+ switch(token[i].type) {\r
+ case JIM_TT_ESC:\r
+ case JIM_TT_STR:\r
+ argv[j] = token[i].objPtr;\r
+ break;\r
+ case JIM_TT_VAR:\r
+ tmpObjPtr = Jim_GetVariable(interp, token[i].objPtr,\r
+ JIM_ERRMSG);\r
+ if (!tmpObjPtr) {\r
+ retcode = JIM_ERR;\r
+ goto err;\r
+ }\r
+ argv[j] = tmpObjPtr;\r
+ break;\r
+ case JIM_TT_DICTSUGAR:\r
+ tmpObjPtr = Jim_ExpandDictSugar(interp, token[i].objPtr);\r
+ if (!tmpObjPtr) {\r
+ retcode = JIM_ERR;\r
+ goto err;\r
+ }\r
+ argv[j] = tmpObjPtr;\r
+ break;\r
+ case JIM_TT_CMD:\r
+ retcode = Jim_EvalObj(interp, token[i].objPtr);\r
+ if (retcode != JIM_OK)\r
+ goto err;\r
+ argv[j] = Jim_GetResult(interp);\r
+ break;\r
+ default:\r
+ Jim_Panic(interp,\r
+ "default token type reached "\r
+ "in Jim_EvalObj().");\r
+ break;\r
+ }\r
+ Jim_IncrRefCount(argv[j]);\r
+ i += 2;\r
+ } else {\r
+ /* For interpolation we call an helper\r
+ * function doing the work for us. */\r
+ if ((retcode = Jim_InterpolateTokens(interp,\r
+ token+i, tokens, &tmpObjPtr)) != JIM_OK)\r
+ {\r
+ goto err;\r
+ }\r
+ argv[j] = tmpObjPtr;\r
+ Jim_IncrRefCount(argv[j]);\r
+ i += tokens+1;\r
+ }\r
+ }\r
+ /* Handle {expand} expansion */\r
+ if (expand) {\r
+ int *ecs = cs - argc;\r
+ int eargc = 0;\r
+ Jim_Obj **eargv = NULL;\r
+\r
+ for (j = 0; j < argc; j++) {\r
+ Jim_ExpandArgument( interp, &eargv, &eargc,\r
+ ecs[j] < 0, argv[j]);\r
+ }\r
+ if (argv != sargv)\r
+ Jim_Free(argv);\r
+ argc = eargc;\r
+ argv = eargv;\r
+ j = argc;\r
+ if (argc == 0) {\r
+ /* Nothing to do with zero args. */\r
+ Jim_Free(eargv);\r
+ continue;\r
+ }\r
+ }\r
+ /* Lookup the command to call */\r
+ cmd = Jim_GetCommand(interp, argv[0], JIM_ERRMSG);\r
+ if (cmd != NULL) {\r
+ /* Call it -- Make sure result is an empty object. */\r
+ Jim_SetEmptyResult(interp);\r
+ if (cmd->cmdProc) {\r
+ interp->cmdPrivData = cmd->privData;\r
+ retcode = cmd->cmdProc(interp, argc, argv);\r
+ } else {\r
+ retcode = JimCallProcedure(interp, cmd, argc, argv);\r
+ if (retcode == JIM_ERR) {\r
+ JimAppendStackTrace(interp,\r
+ Jim_GetString(argv[0], NULL), script->fileName,\r
+ token[i-argc*2].linenr);\r
+ }\r
+ }\r
+ } else {\r
+ /* Call [unknown] */\r
+ retcode = JimUnknown(interp, argc, argv);\r
+ }\r
+ if (retcode != JIM_OK) {\r
+ i -= argc*2; /* point to the command name. */\r
+ goto err;\r
+ }\r
+ /* Decrement the arguments count */\r
+ for (j = 0; j < argc; j++) {\r
+ Jim_DecrRefCount(interp, argv[j]);\r
+ }\r
+\r
+ if (argv != sargv) {\r
+ Jim_Free(argv);\r
+ argv = NULL;\r
+ }\r
+ }\r
+ /* Note that we don't have to decrement inUse, because the\r
+ * following code transfers our use of the reference again to\r
+ * the script object. */\r
+ j = 0; /* on normal termination, the argv array is already\r
+ Jim_DecrRefCount-ed. */\r
+err:\r
+ /* Handle errors. */\r
+ if (retcode == JIM_ERR && !interp->errorFlag) {\r
+ interp->errorFlag = 1;\r
+ JimSetErrorFileName(interp, script->fileName);\r
+ JimSetErrorLineNumber(interp, token[i].linenr);\r
+ JimResetStackTrace(interp);\r
+ }\r
+ Jim_FreeIntRep(interp, scriptObjPtr);\r
+ scriptObjPtr->typePtr = &scriptObjType;\r
+ Jim_SetIntRepPtr(scriptObjPtr, script);\r
+ Jim_DecrRefCount(interp, scriptObjPtr);\r
+ for (i = 0; i < j; i++) {\r
+ Jim_DecrRefCount(interp, argv[i]);\r
+ }\r
+ if (argv != sargv)\r
+ Jim_Free(argv);\r
+ return retcode;\r
+}\r
+\r
+/* Call a procedure implemented in Tcl.\r
+ * It's possible to speed-up a lot this function, currently\r
+ * the callframes are not cached, but allocated and\r
+ * destroied every time. What is expecially costly is\r
+ * to create/destroy the local vars hash table every time.\r
+ *\r
+ * This can be fixed just implementing callframes caching\r
+ * in JimCreateCallFrame() and JimFreeCallFrame(). */\r
+int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ int i, retcode;\r
+ Jim_CallFrame *callFramePtr;\r
+\r
+ /* Check arity */\r
+ if (argc < cmd->arityMin || (cmd->arityMax != -1 &&\r
+ argc > cmd->arityMax)) {\r
+ Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);\r
+ Jim_AppendStrings(interp, objPtr,\r
+ "wrong # args: should be \"", Jim_GetString(argv[0], NULL),\r
+ (cmd->arityMin > 1) ? " " : "",\r
+ Jim_GetString(cmd->argListObjPtr, NULL), "\"", NULL);\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_ERR;\r
+ }\r
+ /* Check if there are too nested calls */\r
+ if (interp->numLevels == interp->maxNestingDepth) {\r
+ Jim_SetResultString(interp,\r
+ "Too many nested calls. Infinite recursion?", -1);\r
+ return JIM_ERR;\r
+ }\r
+ /* Create a new callframe */\r
+ callFramePtr = JimCreateCallFrame(interp);\r
+ callFramePtr->parentCallFrame = interp->framePtr;\r
+ callFramePtr->argv = argv;\r
+ callFramePtr->argc = argc;\r
+ callFramePtr->procArgsObjPtr = cmd->argListObjPtr;\r
+ callFramePtr->procBodyObjPtr = cmd->bodyObjPtr;\r
+ callFramePtr->staticVars = cmd->staticVars;\r
+ Jim_IncrRefCount(cmd->argListObjPtr);\r
+ Jim_IncrRefCount(cmd->bodyObjPtr);\r
+ interp->framePtr = callFramePtr;\r
+ interp->numLevels ++;\r
+ /* Set arguments */\r
+ for (i = 0; i < cmd->arityMin-1; i++) {\r
+ Jim_Obj *objPtr;\r
+\r
+ Jim_ListIndex(interp, cmd->argListObjPtr, i, &objPtr, JIM_NONE);\r
+ Jim_SetVariable(interp, objPtr, argv[i+1]);\r
+ }\r
+ if (cmd->arityMax == -1) {\r
+ Jim_Obj *listObjPtr, *objPtr;\r
+\r
+ listObjPtr = Jim_NewListObj(interp, argv+cmd->arityMin,\r
+ argc-cmd->arityMin);\r
+ Jim_ListIndex(interp, cmd->argListObjPtr, i, &objPtr, JIM_NONE);\r
+ Jim_SetVariable(interp, objPtr, listObjPtr);\r
+ }\r
+ /* Eval the body */\r
+ retcode = Jim_EvalObj(interp, cmd->bodyObjPtr);\r
+\r
+ /* Destroy the callframe */\r
+ interp->numLevels --;\r
+ interp->framePtr = interp->framePtr->parentCallFrame;\r
+ if (callFramePtr->vars.size != JIM_HT_INITIAL_SIZE) {\r
+ JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NONE);\r
+ } else {\r
+ JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NOHT);\r
+ }\r
+ /* Handle the JIM_EVAL return code */\r
+ if (retcode == JIM_EVAL && interp->evalRetcodeLevel != interp->numLevels) {\r
+ int savedLevel = interp->evalRetcodeLevel;\r
+\r
+ interp->evalRetcodeLevel = interp->numLevels;\r
+ while (retcode == JIM_EVAL) {\r
+ Jim_Obj *resultScriptObjPtr = Jim_GetResult(interp);\r
+ Jim_IncrRefCount(resultScriptObjPtr);\r
+ retcode = Jim_EvalObj(interp, resultScriptObjPtr);\r
+ Jim_DecrRefCount(interp, resultScriptObjPtr);\r
+ }\r
+ interp->evalRetcodeLevel = savedLevel;\r
+ }\r
+ /* Handle the JIM_RETURN return code */\r
+ if (retcode == JIM_RETURN) {\r
+ retcode = interp->returnCode;\r
+ interp->returnCode = JIM_OK;\r
+ }\r
+ return retcode;\r
+}\r
+\r
+int Jim_Eval(Jim_Interp *interp, const char *script)\r
+{\r
+ Jim_Obj *scriptObjPtr = Jim_NewStringObj(interp, script, -1);\r
+ int retval;\r
+\r
+ Jim_IncrRefCount(scriptObjPtr);\r
+ retval = Jim_EvalObj(interp, scriptObjPtr);\r
+ Jim_DecrRefCount(interp, scriptObjPtr);\r
+ return retval;\r
+}\r
+\r
+/* Execute script in the scope of the global level */\r
+int Jim_EvalGlobal(Jim_Interp *interp, const char *script)\r
+{\r
+ Jim_CallFrame *savedFramePtr;\r
+ int retval;\r
+\r
+ savedFramePtr = interp->framePtr;\r
+ interp->framePtr = interp->topFramePtr;\r
+ retval = Jim_Eval(interp, script);\r
+ interp->framePtr = savedFramePtr;\r
+ return retval;\r
+}\r
+\r
+int Jim_EvalObjBackground(Jim_Interp *interp, Jim_Obj *scriptObjPtr)\r
+{\r
+ Jim_CallFrame *savedFramePtr;\r
+ int retval;\r
+\r
+ savedFramePtr = interp->framePtr;\r
+ interp->framePtr = interp->topFramePtr;\r
+ retval = Jim_EvalObj(interp, scriptObjPtr);\r
+ interp->framePtr = savedFramePtr;\r
+ /* Try to report the error (if any) via the bgerror proc */\r
+ if (retval != JIM_OK) {\r
+ Jim_Obj *objv[2];\r
+\r
+ objv[0] = Jim_NewStringObj(interp, "bgerror", -1);\r
+ objv[1] = Jim_GetResult(interp);\r
+ Jim_IncrRefCount(objv[0]);\r
+ Jim_IncrRefCount(objv[1]);\r
+ if (Jim_EvalObjVector(interp, 2, objv) != JIM_OK) {\r
+ /* Report the error to stderr. */\r
+ fprintf(interp->stderr_, "Background error:" JIM_NL);\r
+ Jim_PrintErrorMessage(interp);\r
+ }\r
+ Jim_DecrRefCount(interp, objv[0]);\r
+ Jim_DecrRefCount(interp, objv[1]);\r
+ }\r
+ return retval;\r
+}\r
+\r
+int Jim_EvalFile(Jim_Interp *interp, const char *filename)\r
+{\r
+ char *prg = NULL;\r
+ FILE *fp;\r
+ int nread, totread, maxlen, buflen;\r
+ int retval;\r
+ Jim_Obj *scriptObjPtr;\r
+ \r
+ if ((fp = fopen(filename, "r")) == NULL) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "Error loading script \"", filename, "\": ",\r
+ strerror(errno), NULL);\r
+ return JIM_ERR;\r
+ }\r
+ buflen = 1024;\r
+ maxlen = totread = 0;\r
+ while (1) {\r
+ if (maxlen < totread+buflen+1) {\r
+ maxlen = totread+buflen+1;\r
+ prg = Jim_Realloc(prg, maxlen);\r
+ }\r
+ if ((nread = fread(prg+totread, 1, buflen, fp)) == 0) break;\r
+ totread += nread;\r
+ }\r
+ prg[totread] = '\0';\r
+ fclose(fp);\r
+\r
+ scriptObjPtr = Jim_NewStringObjNoAlloc(interp, prg, totread);\r
+ JimSetSourceInfo(interp, scriptObjPtr, filename, 1);\r
+ Jim_IncrRefCount(scriptObjPtr);\r
+ retval = Jim_EvalObj(interp, scriptObjPtr);\r
+ Jim_DecrRefCount(interp, scriptObjPtr);\r
+ return retval;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Subst\r
+ * ---------------------------------------------------------------------------*/\r
+static int JimParseSubstStr(struct JimParserCtx *pc)\r
+{\r
+ pc->tstart = pc->p;\r
+ pc->tline = pc->linenr;\r
+ while (*pc->p && *pc->p != '$' && *pc->p != '[') {\r
+ pc->p++; pc->len--;\r
+ }\r
+ pc->tend = pc->p-1;\r
+ pc->tt = JIM_TT_ESC;\r
+ return JIM_OK;\r
+}\r
+\r
+static int JimParseSubst(struct JimParserCtx *pc, int flags)\r
+{\r
+ int retval;\r
+\r
+ if (pc->len == 0) {\r
+ pc->tstart = pc->tend = pc->p;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_EOL;\r
+ pc->eof = 1;\r
+ return JIM_OK;\r
+ }\r
+ switch(*pc->p) {\r
+ case '[':\r
+ retval = JimParseCmd(pc);\r
+ if (flags & JIM_SUBST_NOCMD) {\r
+ pc->tstart--;\r
+ pc->tend++;\r
+ pc->tt = (flags & JIM_SUBST_NOESC) ?\r
+ JIM_TT_STR : JIM_TT_ESC;\r
+ }\r
+ return retval;\r
+ break;\r
+ case '$':\r
+ if (JimParseVar(pc) == JIM_ERR) {\r
+ pc->tstart = pc->tend = pc->p++; pc->len--;\r
+ pc->tline = pc->linenr;\r
+ pc->tt = JIM_TT_STR;\r
+ } else {\r
+ if (flags & JIM_SUBST_NOVAR) {\r
+ pc->tstart--;\r
+ if (flags & JIM_SUBST_NOESC)\r
+ pc->tt = JIM_TT_STR;\r
+ else\r
+ pc->tt = JIM_TT_ESC;\r
+ if (*pc->tstart == '{') {\r
+ pc->tstart--;\r
+ if (*(pc->tend+1))\r
+ pc->tend++;\r
+ }\r
+ }\r
+ }\r
+ break;\r
+ default:\r
+ retval = JimParseSubstStr(pc);\r
+ if (flags & JIM_SUBST_NOESC)\r
+ pc->tt = JIM_TT_STR;\r
+ return retval;\r
+ break;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* The subst object type reuses most of the data structures and functions\r
+ * of the script object. Script's data structures are a bit more complex\r
+ * for what is needed for [subst]itution tasks, but the reuse helps to\r
+ * deal with a single data structure at the cost of some more memory\r
+ * usage for substitutions. */\r
+static Jim_ObjType substObjType = {\r
+ "subst",\r
+ FreeScriptInternalRep,\r
+ DupScriptInternalRep,\r
+ NULL,\r
+ JIM_TYPE_REFERENCES,\r
+};\r
+\r
+/* This method takes the string representation of an object\r
+ * as a Tcl string where to perform [subst]itution, and generates\r
+ * the pre-parsed internal representation. */\r
+int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)\r
+{\r
+ int scriptTextLen;\r
+ const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);\r
+ struct JimParserCtx parser;\r
+ struct ScriptObj *script = Jim_Alloc(sizeof(*script));\r
+\r
+ script->len = 0;\r
+ script->csLen = 0;\r
+ script->commands = 0;\r
+ script->token = NULL;\r
+ script->cmdStruct = NULL;\r
+ script->inUse = 1;\r
+ script->substFlags = flags;\r
+ script->fileName = NULL;\r
+\r
+ JimParserInit(&parser, scriptText, scriptTextLen, 1);\r
+ while(1) {\r
+ char *token;\r
+ int len, type, linenr;\r
+\r
+ JimParseSubst(&parser, flags);\r
+ if (JimParserEof(&parser)) break;\r
+ token = JimParserGetToken(&parser, &len, &type, &linenr);\r
+ ScriptObjAddToken(interp, script, token, len, type,\r
+ NULL, linenr);\r
+ }\r
+ /* Free the old internal rep and set the new one. */\r
+ Jim_FreeIntRep(interp, objPtr);\r
+ Jim_SetIntRepPtr(objPtr, script);\r
+ objPtr->typePtr = &scriptObjType;\r
+ return JIM_OK;\r
+}\r
+\r
+ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)\r
+{\r
+ struct ScriptObj *script = Jim_GetIntRepPtr(objPtr);\r
+\r
+ if (objPtr->typePtr != &substObjType || script->substFlags != flags)\r
+ SetSubstFromAny(interp, objPtr, flags);\r
+ return (ScriptObj*) Jim_GetIntRepPtr(objPtr);\r
+}\r
+\r
+/* Performs commands,variables,blackslashes substitution,\r
+ * storing the result object (with refcount 0) into\r
+ * resObjPtrPtr. */\r
+int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr,\r
+ Jim_Obj **resObjPtrPtr, int flags)\r
+{\r
+ ScriptObj *script;\r
+ ScriptToken *token;\r
+ int i, len, retcode = JIM_OK;\r
+ Jim_Obj *resObjPtr, *savedResultObjPtr;\r
+\r
+ script = Jim_GetSubst(interp, substObjPtr, flags);\r
+#ifdef JIM_OPTIMIZATION\r
+ /* Fast path for a very common case with array-alike syntax,\r
+ * that's: $foo($bar) */\r
+ if (script->len == 1 && script->token[0].type == JIM_TT_VAR) {\r
+ Jim_Obj *varObjPtr = script->token[0].objPtr;\r
+ \r
+ Jim_IncrRefCount(varObjPtr);\r
+ resObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);\r
+ if (resObjPtr == NULL) {\r
+ Jim_DecrRefCount(interp, varObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ Jim_DecrRefCount(interp, varObjPtr);\r
+ *resObjPtrPtr = resObjPtr;\r
+ return JIM_OK;\r
+ }\r
+#endif\r
+\r
+ Jim_IncrRefCount(substObjPtr); /* Make sure it's shared. */\r
+ /* In order to preserve the internal rep, we increment the\r
+ * inUse field of the script internal rep structure. */\r
+ script->inUse++;\r
+\r
+ token = script->token;\r
+ len = script->len;\r
+\r
+ /* Save the interp old result, to set it again before\r
+ * to return. */\r
+ savedResultObjPtr = interp->result;\r
+ Jim_IncrRefCount(savedResultObjPtr);\r
+ \r
+ /* Perform the substitution. Starts with an empty object\r
+ * and adds every token (performing the appropriate\r
+ * var/command/escape substitution). */\r
+ resObjPtr = Jim_NewStringObj(interp, "", 0);\r
+ for (i = 0; i < len; i++) {\r
+ Jim_Obj *objPtr;\r
+\r
+ switch(token[i].type) {\r
+ case JIM_TT_STR:\r
+ case JIM_TT_ESC:\r
+ Jim_AppendObj(interp, resObjPtr, token[i].objPtr);\r
+ break;\r
+ case JIM_TT_VAR:\r
+ objPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);\r
+ if (objPtr == NULL) goto err;\r
+ Jim_IncrRefCount(objPtr);\r
+ Jim_AppendObj(interp, resObjPtr, objPtr);\r
+ Jim_DecrRefCount(interp, objPtr);\r
+ break;\r
+ case JIM_TT_CMD:\r
+ if (Jim_EvalObj(interp, token[i].objPtr) != JIM_OK)\r
+ goto err;\r
+ Jim_AppendObj(interp, resObjPtr, interp->result);\r
+ break;\r
+ default:\r
+ Jim_Panic(interp,\r
+ "default token type (%d) reached "\r
+ "in Jim_SubstObj().", token[i].type);\r
+ break;\r
+ }\r
+ }\r
+ok:\r
+ if (retcode == JIM_OK)\r
+ Jim_SetResult(interp, savedResultObjPtr);\r
+ Jim_DecrRefCount(interp, savedResultObjPtr);\r
+ /* Note that we don't have to decrement inUse, because the\r
+ * following code transfers our use of the reference again to\r
+ * the script object. */\r
+ Jim_FreeIntRep(interp, substObjPtr);\r
+ substObjPtr->typePtr = &scriptObjType;\r
+ Jim_SetIntRepPtr(substObjPtr, script);\r
+ Jim_DecrRefCount(interp, substObjPtr);\r
+ *resObjPtrPtr = resObjPtr;\r
+ return retcode;\r
+err:\r
+ Jim_FreeNewObj(interp, resObjPtr);\r
+ retcode = JIM_ERR;\r
+ goto ok;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * API Input/Export functions\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+int Jim_GetApi(Jim_Interp *interp, const char *funcname, void *targetPtrPtr)\r
+{\r
+ Jim_HashEntry *he;\r
+\r
+ he = Jim_FindHashEntry(&interp->stub, funcname);\r
+ if (!he)\r
+ return JIM_ERR;\r
+ memcpy(targetPtrPtr, &he->val, sizeof(void*));\r
+ return JIM_OK;\r
+}\r
+\r
+int Jim_RegisterApi(Jim_Interp *interp, const char *funcname, void *funcptr)\r
+{\r
+ return Jim_AddHashEntry(&interp->stub, funcname, funcptr);\r
+}\r
+\r
+#define JIM_REGISTER_API(name) \\r
+ Jim_RegisterApi(interp, "Jim_" #name, (void *)Jim_ ## name)\r
+\r
+void JimRegisterCoreApi(Jim_Interp *interp)\r
+{\r
+ interp->getApiFuncPtr = Jim_GetApi;\r
+ JIM_REGISTER_API(Alloc);\r
+ JIM_REGISTER_API(Free);\r
+ JIM_REGISTER_API(Eval);\r
+ JIM_REGISTER_API(EvalGlobal);\r
+ JIM_REGISTER_API(EvalFile);\r
+ JIM_REGISTER_API(EvalObj);\r
+ JIM_REGISTER_API(EvalObjBackground);\r
+ JIM_REGISTER_API(EvalObjVector);\r
+ JIM_REGISTER_API(InitHashTable);\r
+ JIM_REGISTER_API(ExpandHashTable);\r
+ JIM_REGISTER_API(AddHashEntry);\r
+ JIM_REGISTER_API(ReplaceHashEntry);\r
+ JIM_REGISTER_API(DeleteHashEntry);\r
+ JIM_REGISTER_API(FreeHashTable);\r
+ JIM_REGISTER_API(FindHashEntry);\r
+ JIM_REGISTER_API(ResizeHashTable);\r
+ JIM_REGISTER_API(GetHashTableIterator);\r
+ JIM_REGISTER_API(NextHashEntry);\r
+ JIM_REGISTER_API(NewObj);\r
+ JIM_REGISTER_API(FreeObj);\r
+ JIM_REGISTER_API(InvalidateStringRep);\r
+ JIM_REGISTER_API(InitStringRep);\r
+ JIM_REGISTER_API(DuplicateObj);\r
+ JIM_REGISTER_API(GetString);\r
+ JIM_REGISTER_API(Length);\r
+ JIM_REGISTER_API(InvalidateStringRep);\r
+ JIM_REGISTER_API(NewStringObj);\r
+ JIM_REGISTER_API(NewStringObjNoAlloc);\r
+ JIM_REGISTER_API(AppendString);\r
+ JIM_REGISTER_API(AppendObj);\r
+ JIM_REGISTER_API(AppendStrings);\r
+ JIM_REGISTER_API(StringEqObj);\r
+ JIM_REGISTER_API(StringMatchObj);\r
+ JIM_REGISTER_API(StringRangeObj);\r
+ JIM_REGISTER_API(FormatString);\r
+ JIM_REGISTER_API(CompareStringImmediate);\r
+ JIM_REGISTER_API(NewReference);\r
+ JIM_REGISTER_API(GetReference);\r
+ JIM_REGISTER_API(SetFinalizer);\r
+ JIM_REGISTER_API(GetFinalizer);\r
+ JIM_REGISTER_API(CreateInterp);\r
+ JIM_REGISTER_API(FreeInterp);\r
+ JIM_REGISTER_API(GetExitCode);\r
+ JIM_REGISTER_API(SetStdin);\r
+ JIM_REGISTER_API(SetStdout);\r
+ JIM_REGISTER_API(SetStderr);\r
+ JIM_REGISTER_API(CreateCommand);\r
+ JIM_REGISTER_API(CreateProcedure);\r
+ JIM_REGISTER_API(DeleteCommand);\r
+ JIM_REGISTER_API(RenameCommand);\r
+ JIM_REGISTER_API(GetCommand);\r
+ JIM_REGISTER_API(SetVariable);\r
+ JIM_REGISTER_API(SetVariableStr);\r
+ JIM_REGISTER_API(SetGlobalVariableStr);\r
+ JIM_REGISTER_API(SetVariableStrWithStr);\r
+ JIM_REGISTER_API(SetVariableLink);\r
+ JIM_REGISTER_API(GetVariable);\r
+ JIM_REGISTER_API(GetCallFrameByLevel);\r
+ JIM_REGISTER_API(Collect);\r
+ JIM_REGISTER_API(CollectIfNeeded);\r
+ JIM_REGISTER_API(GetIndex);\r
+ JIM_REGISTER_API(NewListObj);\r
+ JIM_REGISTER_API(ListAppendElement);\r
+ JIM_REGISTER_API(ListAppendList);\r
+ JIM_REGISTER_API(ListLength);\r
+ JIM_REGISTER_API(ListIndex);\r
+ JIM_REGISTER_API(SetListIndex);\r
+ JIM_REGISTER_API(ConcatObj);\r
+ JIM_REGISTER_API(NewDictObj);\r
+ JIM_REGISTER_API(DictKey);\r
+ JIM_REGISTER_API(DictKeysVector);\r
+ JIM_REGISTER_API(GetIndex);\r
+ JIM_REGISTER_API(GetReturnCode);\r
+ JIM_REGISTER_API(EvalExpression);\r
+ JIM_REGISTER_API(GetBoolFromExpr);\r
+ JIM_REGISTER_API(GetWide);\r
+ JIM_REGISTER_API(GetLong);\r
+ JIM_REGISTER_API(SetWide);\r
+ JIM_REGISTER_API(NewIntObj);\r
+ JIM_REGISTER_API(GetDouble);\r
+ JIM_REGISTER_API(SetDouble);\r
+ JIM_REGISTER_API(NewDoubleObj);\r
+ JIM_REGISTER_API(WrongNumArgs);\r
+ JIM_REGISTER_API(SetDictKeysVector);\r
+ JIM_REGISTER_API(SubstObj);\r
+ JIM_REGISTER_API(RegisterApi);\r
+ JIM_REGISTER_API(PrintErrorMessage);\r
+ JIM_REGISTER_API(InteractivePrompt);\r
+ JIM_REGISTER_API(RegisterCoreCommands);\r
+ JIM_REGISTER_API(GetSharedString);\r
+ JIM_REGISTER_API(ReleaseSharedString);\r
+ JIM_REGISTER_API(Panic);\r
+ JIM_REGISTER_API(StrDup);\r
+ JIM_REGISTER_API(UnsetVariable);\r
+ JIM_REGISTER_API(GetVariableStr);\r
+ JIM_REGISTER_API(GetGlobalVariable);\r
+ JIM_REGISTER_API(GetGlobalVariableStr);\r
+ JIM_REGISTER_API(GetAssocData);\r
+ JIM_REGISTER_API(SetAssocData);\r
+ JIM_REGISTER_API(DeleteAssocData);\r
+ JIM_REGISTER_API(GetEnum);\r
+ JIM_REGISTER_API(ScriptIsComplete);\r
+ JIM_REGISTER_API(PackageRequire);\r
+ JIM_REGISTER_API(PackageProvide);\r
+ JIM_REGISTER_API(InitStack);\r
+ JIM_REGISTER_API(FreeStack);\r
+ JIM_REGISTER_API(StackLen);\r
+ JIM_REGISTER_API(StackPush);\r
+ JIM_REGISTER_API(StackPop);\r
+ JIM_REGISTER_API(StackPeek);\r
+ JIM_REGISTER_API(FreeStackElements);\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Core commands utility functions\r
+ * ---------------------------------------------------------------------------*/\r
+void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, \r
+ const char *msg)\r
+{\r
+ int i;\r
+ Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);\r
+\r
+ Jim_AppendString(interp, objPtr, "wrong # args: should be \"", -1);\r
+ for (i = 0; i < argc; i++) {\r
+ Jim_AppendObj(interp, objPtr, argv[i]);\r
+ if (!(i+1 == argc && msg[0] == '\0'))\r
+ Jim_AppendString(interp, objPtr, " ", 1);\r
+ }\r
+ Jim_AppendString(interp, objPtr, msg, -1);\r
+ Jim_AppendString(interp, objPtr, "\"", 1);\r
+ Jim_SetResult(interp, objPtr);\r
+}\r
+\r
+static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr)\r
+{\r
+ Jim_HashTableIterator *htiter;\r
+ Jim_HashEntry *he;\r
+ Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);\r
+ const char *pattern;\r
+ int patternLen;\r
+ \r
+ pattern = patternObjPtr ? Jim_GetString(patternObjPtr, &patternLen) : NULL;\r
+ htiter = Jim_GetHashTableIterator(&interp->commands);\r
+ while ((he = Jim_NextHashEntry(htiter)) != NULL) {\r
+ if (pattern && !JimStringMatch(pattern, patternLen, he->key, \r
+ strlen((const char*)he->key), 0))\r
+ continue;\r
+ Jim_ListAppendElement(interp, listObjPtr,\r
+ Jim_NewStringObj(interp, he->key, -1));\r
+ }\r
+ Jim_FreeHashTableIterator(htiter);\r
+ return listObjPtr;\r
+}\r
+\r
+#define JIM_VARLIST_GLOBALS 0\r
+#define JIM_VARLIST_LOCALS 1\r
+#define JIM_VARLIST_VARS 2\r
+\r
+static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr,\r
+ int mode)\r
+{\r
+ Jim_HashTableIterator *htiter;\r
+ Jim_HashEntry *he;\r
+ Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);\r
+ const char *pattern;\r
+ int patternLen;\r
+ \r
+ pattern = patternObjPtr ? Jim_GetString(patternObjPtr, &patternLen) : NULL;\r
+ if (mode == JIM_VARLIST_GLOBALS) {\r
+ htiter = Jim_GetHashTableIterator(&interp->topFramePtr->vars);\r
+ } else {\r
+ /* For [info locals], if we are at top level an emtpy list\r
+ * is returned. I don't agree, but we aim at compatibility (SS) */\r
+ if (mode == JIM_VARLIST_LOCALS &&\r
+ interp->framePtr == interp->topFramePtr)\r
+ return listObjPtr;\r
+ htiter = Jim_GetHashTableIterator(&interp->framePtr->vars);\r
+ }\r
+ while ((he = Jim_NextHashEntry(htiter)) != NULL) {\r
+ Jim_Var *varPtr = (Jim_Var*) he->val;\r
+ if (mode == JIM_VARLIST_LOCALS) {\r
+ if (varPtr->linkFramePtr != NULL)\r
+ continue;\r
+ }\r
+ if (pattern && !JimStringMatch(pattern, patternLen, he->key, \r
+ strlen((const char*)he->key), 0))\r
+ continue;\r
+ Jim_ListAppendElement(interp, listObjPtr,\r
+ Jim_NewStringObj(interp, he->key, -1));\r
+ }\r
+ Jim_FreeHashTableIterator(htiter);\r
+ return listObjPtr;\r
+}\r
+\r
+static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,\r
+ Jim_Obj **objPtrPtr)\r
+{\r
+ Jim_CallFrame *targetCallFrame;\r
+\r
+ if (JimGetCallFrameByInteger(interp, levelObjPtr, &targetCallFrame)\r
+ != JIM_OK)\r
+ return JIM_ERR;\r
+ /* No proc call at toplevel callframe */\r
+ if (targetCallFrame == interp->topFramePtr) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad level \"",\r
+ Jim_GetString(levelObjPtr, NULL), "\"", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ *objPtrPtr = Jim_NewListObj(interp,\r
+ targetCallFrame->argv,\r
+ targetCallFrame->argc);\r
+ return JIM_OK;\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Core commands\r
+ * ---------------------------------------------------------------------------*/\r
+\r
+/* fake [puts] -- not the real puts, just for debugging. */\r
+static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ const char *str;\r
+ int len, nonewline = 0;\r
+ \r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "-nonewline string");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 3) {\r
+ if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline"))\r
+ {\r
+ Jim_SetResultString(interp, "The second argument must "\r
+ "be -nonewline", -1);\r
+ return JIM_OK;\r
+ } else {\r
+ nonewline = 1;\r
+ argv++;\r
+ }\r
+ }\r
+ str = Jim_GetString(argv[1], &len);\r
+ fwrite(str, 1, len, interp->stdout_);\r
+ if (!nonewline) fprintf(interp->stdout_, JIM_NL);\r
+ return JIM_OK;\r
+}\r
+\r
+/* Helper for [+] and [*] */\r
+static int Jim_AddMulHelper(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv, int op)\r
+{\r
+ jim_wide wideValue, res;\r
+ double doubleValue, doubleRes;\r
+ int i;\r
+\r
+ res = (op == JIM_EXPROP_ADD) ? 0 : 1;\r
+ \r
+ for (i = 1; i < argc; i++) {\r
+ if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)\r
+ goto trydouble;\r
+ if (op == JIM_EXPROP_ADD)\r
+ res += wideValue;\r
+ else\r
+ res *= wideValue;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, res));\r
+ return JIM_OK;\r
+trydouble:\r
+ doubleRes = (double) res;\r
+ for (;i < argc; i++) {\r
+ if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)\r
+ return JIM_ERR;\r
+ if (op == JIM_EXPROP_ADD)\r
+ doubleRes += doubleValue;\r
+ else\r
+ doubleRes *= doubleValue;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));\r
+ return JIM_OK;\r
+}\r
+\r
+/* Helper for [-] and [/] */\r
+static int Jim_SubDivHelper(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv, int op)\r
+{\r
+ jim_wide wideValue, res = 0;\r
+ double doubleValue, doubleRes = 0;\r
+ int i = 2;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");\r
+ return JIM_ERR;\r
+ } else if (argc == 2) {\r
+ /* The arity = 2 case is different. For [- x] returns -x,\r
+ * while [/ x] returns 1/x. */\r
+ if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {\r
+ if (Jim_GetDouble(interp, argv[1], &doubleValue) !=\r
+ JIM_OK)\r
+ {\r
+ return JIM_ERR;\r
+ } else {\r
+ if (op == JIM_EXPROP_SUB)\r
+ doubleRes = -doubleValue;\r
+ else\r
+ doubleRes = 1.0/doubleValue;\r
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp,\r
+ doubleRes));\r
+ return JIM_OK;\r
+ }\r
+ }\r
+ if (op == JIM_EXPROP_SUB) {\r
+ res = -wideValue;\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, res));\r
+ } else {\r
+ doubleRes = 1.0/wideValue;\r
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp,\r
+ doubleRes));\r
+ }\r
+ return JIM_OK;\r
+ } else {\r
+ if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {\r
+ if (Jim_GetDouble(interp, argv[1], &doubleRes)\r
+ != JIM_OK) {\r
+ return JIM_ERR;\r
+ } else {\r
+ goto trydouble;\r
+ }\r
+ }\r
+ }\r
+ for (i = 2; i < argc; i++) {\r
+ if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {\r
+ doubleRes = (double) res;\r
+ goto trydouble;\r
+ }\r
+ if (op == JIM_EXPROP_SUB)\r
+ res -= wideValue;\r
+ else\r
+ res /= wideValue;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, res));\r
+ return JIM_OK;\r
+trydouble:\r
+ for (;i < argc; i++) {\r
+ if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)\r
+ return JIM_ERR;\r
+ if (op == JIM_EXPROP_SUB)\r
+ doubleRes -= doubleValue;\r
+ else\r
+ doubleRes /= doubleValue;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));\r
+ return JIM_OK;\r
+}\r
+\r
+\r
+/* [+] */\r
+static int Jim_AddCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ return Jim_AddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);\r
+}\r
+\r
+/* [*] */\r
+static int Jim_MulCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ return Jim_AddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);\r
+}\r
+\r
+/* [-] */\r
+static int Jim_SubCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ return Jim_SubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);\r
+}\r
+\r
+/* [/] */\r
+static int Jim_DivCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ return Jim_SubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);\r
+}\r
+\r
+/* [set] */\r
+static int Jim_SetCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 2) {\r
+ Jim_Obj *objPtr;\r
+ objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);\r
+ if (!objPtr)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+ }\r
+ /* argc == 3 case. */\r
+ if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, argv[2]);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [unset] */\r
+static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int i;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");\r
+ return JIM_ERR;\r
+ }\r
+ for (i = 1; i < argc; i++) {\r
+ if (Jim_UnsetVariable(interp, argv[i], JIM_ERRMSG) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* [incr] */\r
+static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ jim_wide wideValue, increment = 1;\r
+ Jim_Obj *intObjPtr;\r
+\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 3) {\r
+ if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ intObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);\r
+ if (!intObjPtr) return JIM_ERR;\r
+ if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK)\r
+ return JIM_ERR;\r
+ if (Jim_IsShared(intObjPtr)) {\r
+ intObjPtr = Jim_NewIntObj(interp, wideValue+increment);\r
+ if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {\r
+ Jim_FreeNewObj(interp, intObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ } else {\r
+ Jim_SetWide(interp, intObjPtr, wideValue+increment);\r
+ /* The following step is required in order to invalidate the\r
+ * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */\r
+ if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ Jim_SetResult(interp, intObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [while] */\r
+static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "condition body");\r
+ return JIM_ERR;\r
+ }\r
+ /* Try to run a specialized version of while if the expression\r
+ * is in one of the following forms:\r
+ *\r
+ * $a < CONST, $a < $b\r
+ * $a <= CONST, $a <= $b\r
+ * $a > CONST, $a > $b\r
+ * $a >= CONST, $a >= $b\r
+ * $a != CONST, $a != $b\r
+ * $a == CONST, $a == $b\r
+ * $a\r
+ * !$a\r
+ * CONST\r
+ */\r
+\r
+#ifdef JIM_OPTIMIZATION\r
+ {\r
+ ExprByteCode *expr;\r
+ Jim_Obj *varAObjPtr = NULL, *varBObjPtr = NULL, *objPtr;\r
+ int exprLen, retval;\r
+\r
+ /* STEP 1 -- Check if there are the conditions to run the specialized\r
+ * version of while */\r
+ \r
+ if ((expr = Jim_GetExpression(interp, argv[1])) == NULL) goto noopt;\r
+ if (expr->len <= 0 || expr->len > 3) goto noopt;\r
+ switch(expr->len) {\r
+ case 1:\r
+ if (expr->opcode[0] != JIM_EXPROP_VARIABLE &&\r
+ expr->opcode[0] != JIM_EXPROP_NUMBER)\r
+ goto noopt;\r
+ break;\r
+ case 2:\r
+ if (expr->opcode[1] != JIM_EXPROP_NOT ||\r
+ expr->opcode[0] != JIM_EXPROP_VARIABLE)\r
+ goto noopt;\r
+ break;\r
+ case 3:\r
+ if (expr->opcode[0] != JIM_EXPROP_VARIABLE ||\r
+ (expr->opcode[1] != JIM_EXPROP_NUMBER &&\r
+ expr->opcode[1] != JIM_EXPROP_VARIABLE))\r
+ goto noopt;\r
+ switch(expr->opcode[2]) {\r
+ case JIM_EXPROP_LT:\r
+ case JIM_EXPROP_LTE:\r
+ case JIM_EXPROP_GT:\r
+ case JIM_EXPROP_GTE:\r
+ case JIM_EXPROP_NUMEQ:\r
+ case JIM_EXPROP_NUMNE:\r
+ /* nothing to do */\r
+ break;\r
+ default:\r
+ goto noopt;\r
+ }\r
+ break;\r
+ default:\r
+ Jim_Panic(interp,\r
+ "Unexpected default reached in Jim_WhileCoreCommand()");\r
+ break;\r
+ }\r
+\r
+ /* STEP 2 -- conditions meet. Initialization. Take different\r
+ * branches for different expression lengths. */\r
+ exprLen = expr->len;\r
+\r
+ if (exprLen == 1) {\r
+ jim_wide wideValue;\r
+\r
+ if (expr->opcode[0] == JIM_EXPROP_VARIABLE) {\r
+ varAObjPtr = expr->obj[0];\r
+ Jim_IncrRefCount(varAObjPtr);\r
+ } else {\r
+ if (Jim_GetWide(interp, expr->obj[0], &wideValue) != JIM_OK)\r
+ goto noopt;\r
+ }\r
+ while (1) {\r
+ if (varAObjPtr) {\r
+ if (!(objPtr =\r
+ Jim_GetVariable(interp, varAObjPtr, JIM_NONE)) ||\r
+ Jim_GetWide(interp, objPtr, &wideValue) != JIM_OK)\r
+ {\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ goto noopt;\r
+ }\r
+ }\r
+ if (!wideValue) break;\r
+ if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {\r
+ switch(retval) {\r
+ case JIM_BREAK:\r
+ if (varAObjPtr)\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ goto out;\r
+ break;\r
+ case JIM_CONTINUE:\r
+ continue;\r
+ break;\r
+ default:\r
+ if (varAObjPtr)\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ return retval;\r
+ }\r
+ }\r
+ }\r
+ if (varAObjPtr)\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ } else if (exprLen == 3) {\r
+ jim_wide wideValueA, wideValueB, cmpRes = 0;\r
+ int cmpType = expr->opcode[2];\r
+\r
+ varAObjPtr = expr->obj[0];\r
+ Jim_IncrRefCount(varAObjPtr);\r
+ if (expr->opcode[1] == JIM_EXPROP_VARIABLE) {\r
+ varBObjPtr = expr->obj[1];\r
+ Jim_IncrRefCount(varBObjPtr);\r
+ } else {\r
+ if (Jim_GetWide(interp, expr->obj[1], &wideValueB) != JIM_OK)\r
+ goto noopt;\r
+ }\r
+ while (1) {\r
+ if (!(objPtr = Jim_GetVariable(interp, varAObjPtr, JIM_NONE)) ||\r
+ Jim_GetWide(interp, objPtr, &wideValueA) != JIM_OK)\r
+ {\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ if (varBObjPtr)\r
+ Jim_DecrRefCount(interp, varBObjPtr);\r
+ goto noopt;\r
+ }\r
+ if (varBObjPtr) {\r
+ if (!(objPtr =\r
+ Jim_GetVariable(interp, varBObjPtr, JIM_NONE)) ||\r
+ Jim_GetWide(interp, objPtr, &wideValueB) != JIM_OK)\r
+ {\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ if (varBObjPtr)\r
+ Jim_DecrRefCount(interp, varBObjPtr);\r
+ goto noopt;\r
+ }\r
+ }\r
+ switch(cmpType) {\r
+ case JIM_EXPROP_LT:\r
+ cmpRes = wideValueA < wideValueB; break;\r
+ case JIM_EXPROP_LTE:\r
+ cmpRes = wideValueA <= wideValueB; break;\r
+ case JIM_EXPROP_GT:\r
+ cmpRes = wideValueA > wideValueB; break;\r
+ case JIM_EXPROP_GTE:\r
+ cmpRes = wideValueA >= wideValueB; break;\r
+ case JIM_EXPROP_NUMEQ:\r
+ cmpRes = wideValueA == wideValueB; break;\r
+ case JIM_EXPROP_NUMNE:\r
+ cmpRes = wideValueA != wideValueB; break;\r
+ }\r
+ if (!cmpRes) break;\r
+ if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {\r
+ switch(retval) {\r
+ case JIM_BREAK:\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ if (varBObjPtr)\r
+ Jim_DecrRefCount(interp, varBObjPtr);\r
+ goto out;\r
+ break;\r
+ case JIM_CONTINUE:\r
+ continue;\r
+ break;\r
+ default:\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ if (varBObjPtr)\r
+ Jim_DecrRefCount(interp, varBObjPtr);\r
+ return retval;\r
+ }\r
+ }\r
+ }\r
+ Jim_DecrRefCount(interp, varAObjPtr);\r
+ if (varBObjPtr)\r
+ Jim_DecrRefCount(interp, varBObjPtr);\r
+ } else {\r
+ /* TODO: case for len == 2 */\r
+ goto noopt;\r
+ }\r
+ Jim_SetEmptyResult(interp);\r
+ return JIM_OK;\r
+ }\r
+noopt:\r
+#endif\r
+\r
+ /* The general purpose implementation of while starts here */\r
+ while (1) {\r
+ int boolean, retval;\r
+\r
+ if ((retval = Jim_GetBoolFromExpr(interp, argv[1],\r
+ &boolean)) != JIM_OK)\r
+ return retval;\r
+ if (!boolean) break;\r
+ if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {\r
+ switch(retval) {\r
+ case JIM_BREAK:\r
+ goto out;\r
+ break;\r
+ case JIM_CONTINUE:\r
+ continue;\r
+ break;\r
+ default:\r
+ return retval;\r
+ }\r
+ }\r
+ }\r
+out:\r
+ Jim_SetEmptyResult(interp);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [for] */\r
+static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int retval;\r
+\r
+ if (argc != 5) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "start test next body");\r
+ return JIM_ERR;\r
+ }\r
+ /* Check if the for is on the form:\r
+ * for {set i CONST} {$i < CONST} {incr i}\r
+ * for {set i CONST} {$i < $j} {incr i}\r
+ * for {set i CONST} {$i <= CONST} {incr i}\r
+ * for {set i CONST} {$i <= $j} {incr i}\r
+ * XXX: NOTE: if variable traces are implemented, this optimization\r
+ * need to be modified to check for the proc epoch at every variable\r
+ * update. */\r
+#ifdef JIM_OPTIMIZATION\r
+ {\r
+ ScriptObj *initScript, *incrScript;\r
+ ExprByteCode *expr;\r
+ jim_wide start, stop, currentVal;\r
+ unsigned jim_wide procEpoch = interp->procEpoch;\r
+ Jim_Obj *varNamePtr, *stopVarNamePtr = NULL, *objPtr;\r
+ int cmpType;\r
+ struct Jim_Cmd *cmdPtr;\r
+\r
+ /* Do it only if there aren't shared arguments */\r
+ if (argv[1] == argv[2] || argv[2] == argv[3] || argv[1] == argv[3])\r
+ goto evalstart;\r
+ initScript = Jim_GetScript(interp, argv[1]);\r
+ expr = Jim_GetExpression(interp, argv[2]);\r
+ incrScript = Jim_GetScript(interp, argv[3]);\r
+\r
+ /* Ensure proper lengths to start */\r
+ if (initScript->len != 6) goto evalstart;\r
+ if (incrScript->len != 4) goto evalstart;\r
+ if (expr->len != 3) goto evalstart;\r
+ /* Ensure proper token types. */\r
+ if (initScript->token[2].type != JIM_TT_ESC ||\r
+ initScript->token[4].type != JIM_TT_ESC ||\r
+ incrScript->token[2].type != JIM_TT_ESC ||\r
+ expr->opcode[0] != JIM_EXPROP_VARIABLE ||\r
+ (expr->opcode[1] != JIM_EXPROP_NUMBER &&\r
+ expr->opcode[1] != JIM_EXPROP_VARIABLE) ||\r
+ (expr->opcode[2] != JIM_EXPROP_LT &&\r
+ expr->opcode[2] != JIM_EXPROP_LTE))\r
+ goto evalstart;\r
+ cmpType = expr->opcode[2];\r
+ /* Initialization command must be [set] */\r
+ cmdPtr = Jim_GetCommand(interp, initScript->token[0].objPtr, JIM_NONE);\r
+ if (cmdPtr == NULL || cmdPtr->cmdProc != Jim_SetCoreCommand)\r
+ goto evalstart;\r
+ /* Update command must be incr */\r
+ cmdPtr = Jim_GetCommand(interp, incrScript->token[0].objPtr, JIM_NONE);\r
+ if (cmdPtr == NULL || cmdPtr->cmdProc != Jim_IncrCoreCommand)\r
+ goto evalstart;\r
+ /* set, incr, expression must be about the same variable */\r
+ if (!Jim_StringEqObj(initScript->token[2].objPtr,\r
+ incrScript->token[2].objPtr, 0))\r
+ goto evalstart;\r
+ if (!Jim_StringEqObj(initScript->token[2].objPtr,\r
+ expr->obj[0], 0))\r
+ goto evalstart;\r
+ /* Check that the initialization and comparison are valid integers */\r
+ if (Jim_GetWide(interp, initScript->token[4].objPtr, &start) == JIM_ERR)\r
+ goto evalstart;\r
+ if (expr->opcode[1] == JIM_EXPROP_NUMBER &&\r
+ Jim_GetWide(interp, expr->obj[1], &stop) == JIM_ERR)\r
+ {\r
+ goto evalstart;\r
+ }\r
+\r
+ /* Initialization */\r
+ varNamePtr = expr->obj[0];\r
+ if (expr->opcode[1] == JIM_EXPROP_VARIABLE) {\r
+ stopVarNamePtr = expr->obj[1];\r
+ Jim_IncrRefCount(stopVarNamePtr);\r
+ }\r
+ Jim_IncrRefCount(varNamePtr);\r
+\r
+ /* --- OPTIMIZED FOR --- */\r
+ /* Start to loop */\r
+ objPtr = Jim_NewIntObj(interp, start);\r
+ if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ if (stopVarNamePtr) Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ Jim_FreeNewObj(interp, objPtr);\r
+ goto evalstart;\r
+ }\r
+ while (1) {\r
+ /* === Check condition === */\r
+ /* Common code: */\r
+ objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);\r
+ if (objPtr == NULL ||\r
+ Jim_GetWide(interp, objPtr, ¤tVal) != JIM_OK)\r
+ {\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ if (stopVarNamePtr) Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ goto testcond;\r
+ }\r
+ /* Immediate or Variable? get the 'stop' value if the latter. */\r
+ if (stopVarNamePtr) {\r
+ objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);\r
+ if (objPtr == NULL ||\r
+ Jim_GetWide(interp, objPtr, &stop) != JIM_OK)\r
+ {\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ goto testcond;\r
+ }\r
+ }\r
+ if (cmpType == JIM_EXPROP_LT) {\r
+ if (currentVal >= stop) break;\r
+ } else {\r
+ if (currentVal > stop) break;\r
+ }\r
+ /* Eval body */\r
+ if ((retval = Jim_EvalObj(interp, argv[4])) != JIM_OK) {\r
+ switch(retval) {\r
+ case JIM_BREAK:\r
+ if (stopVarNamePtr)\r
+ Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ goto out;\r
+ case JIM_CONTINUE:\r
+ /* nothing to do */\r
+ break;\r
+ default:\r
+ if (stopVarNamePtr)\r
+ Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ return retval;\r
+ }\r
+ }\r
+ /* If there was a change in procedures/command continue\r
+ * with the usual [for] command implementation */\r
+ if (procEpoch != interp->procEpoch) {\r
+ if (stopVarNamePtr)\r
+ Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ goto evalnext;\r
+ }\r
+ /* Increment */\r
+ objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);\r
+ if (objPtr->refCount == 1 && objPtr->typePtr == &intObjType) {\r
+ objPtr->internalRep.wideValue ++;\r
+ Jim_InvalidateStringRep(objPtr);\r
+ } else {\r
+ Jim_Obj *auxObjPtr;\r
+\r
+ if (Jim_GetWide(interp, objPtr, ¤tVal) == JIM_ERR) {\r
+ if (stopVarNamePtr)\r
+ Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ goto evalnext;\r
+ }\r
+ auxObjPtr = Jim_NewIntObj(interp, currentVal+1);\r
+ if (Jim_SetVariable(interp, varNamePtr, auxObjPtr) == JIM_ERR) {\r
+ if (stopVarNamePtr)\r
+ Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ Jim_FreeNewObj(interp, auxObjPtr);\r
+ goto evalnext;\r
+ }\r
+ }\r
+ }\r
+ if (stopVarNamePtr)\r
+ Jim_DecrRefCount(interp, stopVarNamePtr);\r
+ Jim_DecrRefCount(interp, varNamePtr);\r
+ Jim_SetEmptyResult(interp);\r
+ return JIM_OK;\r
+ }\r
+#endif\r
+evalstart:\r
+ /* Eval start */\r
+ if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK)\r
+ return retval;\r
+ while (1) {\r
+ int boolean;\r
+testcond:\r
+ /* Test the condition */\r
+ if ((retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean))\r
+ != JIM_OK)\r
+ return retval;\r
+ if (!boolean) break;\r
+ /* Eval body */\r
+ if ((retval = Jim_EvalObj(interp, argv[4])) != JIM_OK) {\r
+ switch(retval) {\r
+ case JIM_BREAK:\r
+ goto out;\r
+ break;\r
+ case JIM_CONTINUE:\r
+ /* Nothing to do */\r
+ break;\r
+ default:\r
+ return retval;\r
+ }\r
+ }\r
+evalnext:\r
+ /* Eval next */\r
+ if ((retval = Jim_EvalObj(interp, argv[3])) != JIM_OK) {\r
+ switch(retval) {\r
+ case JIM_BREAK:\r
+ goto out;\r
+ break;\r
+ case JIM_CONTINUE:\r
+ continue;\r
+ break;\r
+ default:\r
+ return retval;\r
+ }\r
+ }\r
+ }\r
+out:\r
+ Jim_SetEmptyResult(interp);\r
+ return JIM_OK;\r
+}\r
+\r
+/* foreach + lmap implementation. */\r
+static int JimForeachMapHelper(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv, int doMap)\r
+{\r
+ int result = JIM_ERR, i, nbrOfLists, *listsIdx, *listsEnd;\r
+ int nbrOfLoops = 0;\r
+ Jim_Obj *emptyStr, *script, *mapRes = NULL;\r
+\r
+ if (argc < 4 || argc % 2 != 0) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");\r
+ return JIM_ERR;\r
+ }\r
+ if (doMap) {\r
+ mapRes = Jim_NewListObj(interp, NULL, 0);\r
+ Jim_IncrRefCount(mapRes);\r
+ }\r
+ emptyStr = Jim_NewEmptyStringObj(interp);\r
+ Jim_IncrRefCount(emptyStr);\r
+ script = argv[argc-1]; /* Last argument is a script */\r
+ nbrOfLists = (argc - 1 - 1) / 2; /* argc - 'foreach' - script */\r
+ listsIdx = (int*)Jim_Alloc(nbrOfLists * sizeof(int));\r
+ listsEnd = (int*)Jim_Alloc(nbrOfLists*2 * sizeof(int));\r
+ /* Initialize iterators and remember max nbr elements each list */\r
+ memset(listsIdx, 0, nbrOfLists * sizeof(int));\r
+ /* Remember lengths of all lists and calculate how much rounds to loop */\r
+ for (i=0; i < nbrOfLists*2; i += 2) {\r
+ div_t cnt;\r
+ int count;\r
+ Jim_ListLength(interp, argv[i+1], &listsEnd[i]);\r
+ Jim_ListLength(interp, argv[i+2], &listsEnd[i+1]);\r
+ if (listsEnd[i] == 0) {\r
+ Jim_SetResultString(interp, "foreach varlist is empty", -1);\r
+ goto err;\r
+ }\r
+ cnt = div(listsEnd[i+1], listsEnd[i]);\r
+ count = cnt.quot + (cnt.rem ? 1 : 0);\r
+ if (count > nbrOfLoops)\r
+ nbrOfLoops = count;\r
+ }\r
+ for (; nbrOfLoops-- > 0; ) {\r
+ for (i=0; i < nbrOfLists; ++i) {\r
+ int varIdx = 0, var = i * 2;\r
+ while (varIdx < listsEnd[var]) {\r
+ Jim_Obj *varName, *ele;\r
+ int lst = i * 2 + 1;\r
+ if (Jim_ListIndex(interp, argv[var+1], varIdx, &varName, JIM_ERRMSG)\r
+ != JIM_OK)\r
+ goto err;\r
+ if (listsIdx[i] < listsEnd[lst]) {\r
+ if (Jim_ListIndex(interp, argv[lst+1], listsIdx[i], &ele, JIM_ERRMSG)\r
+ != JIM_OK)\r
+ goto err;\r
+ if (Jim_SetVariable(interp, varName, ele) != JIM_OK) {\r
+ Jim_SetResultString(interp, "couldn't set loop variable: ", -1);\r
+ goto err;\r
+ }\r
+ ++listsIdx[i]; /* Remember next iterator of current list */ \r
+ } else if (Jim_SetVariable(interp, varName, emptyStr) != JIM_OK) {\r
+ Jim_SetResultString(interp, "couldn't set loop variable: ", -1);\r
+ goto err;\r
+ }\r
+ ++varIdx; /* Next variable */\r
+ }\r
+ }\r
+ switch (result = Jim_EvalObj(interp, script)) {\r
+ case JIM_OK:\r
+ if (doMap)\r
+ Jim_ListAppendElement(interp, mapRes, interp->result);\r
+ break;\r
+ case JIM_CONTINUE:\r
+ break;\r
+ case JIM_BREAK:\r
+ goto out;\r
+ break;\r
+ default:\r
+ goto err;\r
+ }\r
+ }\r
+out:\r
+ result = JIM_OK;\r
+ if (doMap)\r
+ Jim_SetResult(interp, mapRes);\r
+ else\r
+ Jim_SetEmptyResult(interp);\r
+err:\r
+ if (doMap)\r
+ Jim_DecrRefCount(interp, mapRes);\r
+ Jim_DecrRefCount(interp, emptyStr);\r
+ Jim_Free(listsIdx);\r
+ Jim_Free(listsEnd);\r
+ return result;\r
+}\r
+\r
+/* [foreach] */\r
+static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ return JimForeachMapHelper(interp, argc, argv, 0);\r
+}\r
+\r
+/* [lmap] */\r
+static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ return JimForeachMapHelper(interp, argc, argv, 1);\r
+}\r
+\r
+/* [if] */\r
+static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int boolean, retval, current = 1, falsebody = 0;\r
+ if (argc >= 3) {\r
+ while (1) {\r
+ /* Far not enough arguments given! */\r
+ if (current >= argc) goto err;\r
+ if ((retval = Jim_GetBoolFromExpr(interp,\r
+ argv[current++], &boolean))\r
+ != JIM_OK)\r
+ return retval;\r
+ /* There lacks something, isn't it? */\r
+ if (current >= argc) goto err;\r
+ if (Jim_CompareStringImmediate(interp, argv[current],\r
+ "then")) current++;\r
+ /* Tsk tsk, no then-clause? */\r
+ if (current >= argc) goto err;\r
+ if (boolean)\r
+ return Jim_EvalObj(interp, argv[current]);\r
+ /* Ok: no else-clause follows */\r
+ if (++current >= argc) return JIM_OK;\r
+ falsebody = current++;\r
+ if (Jim_CompareStringImmediate(interp, argv[falsebody],\r
+ "else")) {\r
+ /* IIICKS - else-clause isn't last cmd? */\r
+ if (current != argc-1) goto err;\r
+ return Jim_EvalObj(interp, argv[current]);\r
+ } else if (Jim_CompareStringImmediate(interp,\r
+ argv[falsebody], "elseif"))\r
+ /* Ok: elseif follows meaning all the stuff\r
+ * again (how boring...) */\r
+ continue;\r
+ /* OOPS - else-clause is not last cmd?*/\r
+ else if (falsebody != argc-1)\r
+ goto err;\r
+ return Jim_EvalObj(interp, argv[falsebody]);\r
+ }\r
+ return JIM_OK;\r
+ }\r
+err:\r
+ Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");\r
+ return JIM_ERR;\r
+}\r
+\r
+enum {SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD, SWITCH_UNKNOWN};\r
+\r
+/* [switch] */\r
+static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int retcode = JIM_ERR, matchOpt = SWITCH_EXACT, opt=1, patCount, i;\r
+ Jim_Obj *command = 0, *const *caseList = 0, *strObj;\r
+ Jim_Obj *script = 0;\r
+ if (argc < 3) goto wrongnumargs;\r
+ for (opt=1; opt < argc; ++opt) {\r
+ const char *option = Jim_GetString(argv[opt], 0);\r
+ if (*option != '-') break;\r
+ else if (strncmp(option, "--", 2) == 0) { ++opt; break; }\r
+ else if (strncmp(option, "-exact", 2) == 0) matchOpt = SWITCH_EXACT;\r
+ else if (strncmp(option, "-glob", 2) == 0) matchOpt = SWITCH_GLOB;\r
+ else if (strncmp(option, "-regexp", 2) == 0) matchOpt = SWITCH_RE;\r
+ else if (strncmp(option, "-command", 2) == 0) { matchOpt = SWITCH_CMD;\r
+ if ((argc - opt) < 2) goto wrongnumargs;\r
+ command = argv[++opt]; \r
+ } else {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad option \"", option, "\": must be -exact, -glob, "\r
+ "-regexp, -command procname or --", 0);\r
+ goto err; \r
+ }\r
+ if ((argc - opt) < 2) goto wrongnumargs;\r
+ }\r
+ strObj = argv[opt++];\r
+ patCount = argc - opt;\r
+ if (patCount == 1) {\r
+ Jim_Obj **vector;\r
+ JimListGetElements(interp, argv[opt], &patCount, &vector);\r
+ caseList = vector;\r
+ } else\r
+ caseList = &argv[opt];\r
+ if (patCount == 0 || patCount % 2 != 0) goto wrongnumargs;\r
+ for (i=0; script == 0 && i < patCount; i += 2) {\r
+ Jim_Obj *patObj = caseList[i];\r
+ if (!Jim_CompareStringImmediate(interp, patObj, "default")\r
+ || i < (patCount-2)) {\r
+ switch (matchOpt) {\r
+ case SWITCH_EXACT:\r
+ if (Jim_StringEqObj(strObj, patObj, 0))\r
+ script = caseList[i+1];\r
+ break;\r
+ case SWITCH_GLOB:\r
+ if (Jim_StringMatchObj(patObj, strObj, 0))\r
+ script = caseList[i+1];\r
+ break;\r
+ case SWITCH_RE:\r
+ command = Jim_NewStringObj(interp, "regexp", -1);\r
+ /* Fall thru intentionally */\r
+ case SWITCH_CMD: {\r
+ Jim_Obj *parms[] = {command, patObj, strObj};\r
+ int rc = Jim_EvalObjVector(interp, 3, parms);\r
+ long matching;\r
+ /* After the execution of a command we need to\r
+ * make sure to reconvert the object into a list\r
+ * again. Only for the single-list style [switch]. */\r
+ if (argc-opt == 1) {\r
+ Jim_Obj **vector;\r
+ JimListGetElements(interp, argv[opt], &patCount,\r
+ &vector);\r
+ caseList = vector;\r
+ }\r
+ /* command is here already decref'd */\r
+ if (rc != JIM_OK) {\r
+ retcode = rc;\r
+ goto err;\r
+ }\r
+ rc = Jim_GetLong(interp, Jim_GetResult(interp), &matching);\r
+ if (rc != JIM_OK) {\r
+ retcode = rc;\r
+ goto err;\r
+ }\r
+ if (matching)\r
+ script = caseList[i+1];\r
+ break;\r
+ }\r
+ default:\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "internal error: no such option implemented", 0);\r
+ goto err;\r
+ }\r
+ } else {\r
+ script = caseList[i+1];\r
+ }\r
+ }\r
+ for(; i < patCount && Jim_CompareStringImmediate(interp, script, "-");\r
+ i += 2)\r
+ script = caseList[i+1];\r
+ if (script && Jim_CompareStringImmediate(interp, script, "-")) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "no body specified for pattern \"",\r
+ Jim_GetString(caseList[i-2], 0), "\"", 0);\r
+ goto err;\r
+ }\r
+ retcode = JIM_OK;\r
+ Jim_SetEmptyResult(interp);\r
+ if (script != 0)\r
+ retcode = Jim_EvalObj(interp, script);\r
+ return retcode;\r
+wrongnumargs:\r
+ Jim_WrongNumArgs(interp, 1, argv, "?options? string "\r
+ "pattern body ... ?default body? or "\r
+ "{pattern body ?pattern body ...?}");\r
+err:\r
+ return retcode; \r
+}\r
+\r
+/* [list] */\r
+static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *listObjPtr;\r
+\r
+ listObjPtr = Jim_NewListObj(interp, argv+1, argc-1);\r
+ Jim_SetResult(interp, listObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [lindex] */\r
+static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *objPtr, *listObjPtr;\r
+ int i;\r
+ int index;\r
+\r
+ if (argc < 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "list index ?...?");\r
+ return JIM_ERR;\r
+ }\r
+ objPtr = argv[1];\r
+ Jim_IncrRefCount(objPtr);\r
+ for (i = 2; i < argc; i++) {\r
+ listObjPtr = objPtr;\r
+ if (Jim_GetIndex(interp, argv[i], &index) != JIM_OK) {\r
+ Jim_DecrRefCount(interp, listObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ if (Jim_ListIndex(interp, listObjPtr, index, &objPtr,\r
+ JIM_NONE) != JIM_OK) {\r
+ /* Returns an empty object if the index\r
+ * is out of range. */\r
+ Jim_DecrRefCount(interp, listObjPtr);\r
+ Jim_SetEmptyResult(interp);\r
+ return JIM_OK;\r
+ }\r
+ Jim_IncrRefCount(objPtr);\r
+ Jim_DecrRefCount(interp, listObjPtr);\r
+ }\r
+ Jim_SetResult(interp, objPtr);\r
+ Jim_DecrRefCount(interp, objPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [llength] */\r
+static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int len;\r
+\r
+ if (argc != 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "list");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_ListLength(interp, argv[1], &len);\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, len));\r
+ return JIM_OK;\r
+}\r
+\r
+/* [lappend] */\r
+static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *listObjPtr;\r
+ int shared, i;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");\r
+ return JIM_ERR;\r
+ }\r
+ listObjPtr = Jim_GetVariable(interp, argv[1], JIM_NONE);\r
+ if (!listObjPtr) {\r
+ /* Create the list if it does not exists */\r
+ listObjPtr = Jim_NewListObj(interp, NULL, 0);\r
+ if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {\r
+ Jim_FreeNewObj(interp, listObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ shared = Jim_IsShared(listObjPtr);\r
+ if (shared)\r
+ listObjPtr = Jim_DuplicateObj(interp, listObjPtr);\r
+ for (i = 2; i < argc; i++)\r
+ Jim_ListAppendElement(interp, listObjPtr, argv[i]);\r
+ if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {\r
+ if (shared)\r
+ Jim_FreeNewObj(interp, listObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, listObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [linsert] */\r
+static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int index, len;\r
+ Jim_Obj *listPtr;\r
+\r
+ if (argc < 4) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "list index element "\r
+ "?element ...?");\r
+ return JIM_ERR;\r
+ }\r
+ listPtr = argv[1];\r
+ if (Jim_IsShared(listPtr))\r
+ listPtr = Jim_DuplicateObj(interp, listPtr);\r
+ if (Jim_GetIndex(interp, argv[2], &index) != JIM_OK)\r
+ goto err;\r
+ Jim_ListLength(interp, listPtr, &len);\r
+ if (index >= len)\r
+ index = len;\r
+ else if (index < 0)\r
+ index = len + index + 1;\r
+ Jim_ListInsertElements(interp, listPtr, index, argc-3, &argv[3]);\r
+ Jim_SetResult(interp, listPtr);\r
+ return JIM_OK;\r
+err:\r
+ if (listPtr != argv[1]) {\r
+ Jim_FreeNewObj(interp, listPtr);\r
+ }\r
+ return JIM_ERR;\r
+}\r
+\r
+/* [lset] */\r
+static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc < 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");\r
+ return JIM_ERR;\r
+ } else if (argc == 3) {\r
+ if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, argv[2]);\r
+ return JIM_OK;\r
+ }\r
+ if (Jim_SetListIndex(interp, argv[1], argv+2, argc-3, argv[argc-1])\r
+ == JIM_ERR) return JIM_ERR;\r
+ return JIM_OK;\r
+}\r
+\r
+/* [lsort] */\r
+static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])\r
+{\r
+ const char *options[] = {\r
+ "-ascii", "-nocase", "-increasing", "-decreasing", NULL\r
+ };\r
+ enum {OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING};\r
+ Jim_Obj *resObj;\r
+ int i, lsortType = JIM_LSORT_ASCII; /* default sort type */\r
+ int decreasing = 0;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "?options? list");\r
+ return JIM_ERR;\r
+ }\r
+ for (i = 1; i < (argc-1); i++) {\r
+ int option;\r
+\r
+ if (Jim_GetEnum(interp, argv[i], options, &option, "option", JIM_ERRMSG)\r
+ != JIM_OK)\r
+ return JIM_ERR;\r
+ switch(option) {\r
+ case OPT_ASCII: lsortType = JIM_LSORT_ASCII; break;\r
+ case OPT_NOCASE: lsortType = JIM_LSORT_NOCASE; break;\r
+ case OPT_INCREASING: decreasing = 0; break;\r
+ case OPT_DECREASING: decreasing = 1; break;\r
+ }\r
+ }\r
+ if (decreasing) {\r
+ switch(lsortType) {\r
+ case JIM_LSORT_ASCII: lsortType = JIM_LSORT_ASCII_DECR; break;\r
+ case JIM_LSORT_NOCASE: lsortType = JIM_LSORT_NOCASE_DECR; break;\r
+ }\r
+ }\r
+ resObj = Jim_DuplicateObj(interp, argv[argc-1]);\r
+ ListSortElements(interp, resObj, lsortType);\r
+ Jim_SetResult(interp, resObj);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [append] */\r
+static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *stringObjPtr;\r
+ int shared, i;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 2) {\r
+ stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);\r
+ if (!stringObjPtr) return JIM_ERR;\r
+ } else {\r
+ stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_NONE);\r
+ if (!stringObjPtr) {\r
+ /* Create the string if it does not exists */\r
+ stringObjPtr = Jim_NewEmptyStringObj(interp);\r
+ if (Jim_SetVariable(interp, argv[1], stringObjPtr)\r
+ != JIM_OK) {\r
+ Jim_FreeNewObj(interp, stringObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ }\r
+ shared = Jim_IsShared(stringObjPtr);\r
+ if (shared)\r
+ stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);\r
+ for (i = 2; i < argc; i++)\r
+ Jim_AppendObj(interp, stringObjPtr, argv[i]);\r
+ if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {\r
+ if (shared)\r
+ Jim_FreeNewObj(interp, stringObjPtr);\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, stringObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [debug] */\r
+static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ const char *options[] = {\r
+ "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",\r
+ "exprbc",\r
+ NULL\r
+ };\r
+ enum {\r
+ OPT_REFCOUNT, OPT_OBJCOUNT, OPT_OBJECTS, OPT_INVSTR, OPT_SCRIPTLEN,\r
+ OPT_EXPRLEN, OPT_EXPRBC\r
+ };\r
+ int option;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "option ?...?");\r
+ return JIM_ERR;\r
+ }\r
+ if (Jim_GetEnum(interp, argv[1], options, &option, "option",\r
+ JIM_ERRMSG) != JIM_OK)\r
+ return JIM_ERR;\r
+ if (option == OPT_REFCOUNT) {\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "object");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, argv[2]->refCount));\r
+ return JIM_OK;\r
+ } else if (option == OPT_OBJCOUNT) {\r
+ int freeobj = 0, liveobj = 0;\r
+ char buf[256];\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc != 2) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "");\r
+ return JIM_ERR;\r
+ }\r
+ /* Count the number of free objects. */\r
+ objPtr = interp->freeList;\r
+ while (objPtr) {\r
+ freeobj++;\r
+ objPtr = objPtr->nextObjPtr;\r
+ }\r
+ /* Count the number of live objects. */\r
+ objPtr = interp->liveList;\r
+ while (objPtr) {\r
+ liveobj++;\r
+ objPtr = objPtr->nextObjPtr;\r
+ }\r
+ /* Set the result string and return. */\r
+ sprintf(buf, "free %d used %d", freeobj, liveobj);\r
+ Jim_SetResultString(interp, buf, -1);\r
+ return JIM_OK;\r
+ } else if (option == OPT_OBJECTS) {\r
+ Jim_Obj *objPtr, *listObjPtr, *subListObjPtr;\r
+ /* Count the number of live objects. */\r
+ objPtr = interp->liveList;\r
+ listObjPtr = Jim_NewListObj(interp, NULL, 0);\r
+ while (objPtr) {\r
+ char buf[128];\r
+ const char *type = objPtr->typePtr ?\r
+ objPtr->typePtr->name : "";\r
+ subListObjPtr = Jim_NewListObj(interp, NULL, 0);\r
+ sprintf(buf, "%p", objPtr);\r
+ Jim_ListAppendElement(interp, subListObjPtr,\r
+ Jim_NewStringObj(interp, buf, -1));\r
+ Jim_ListAppendElement(interp, subListObjPtr,\r
+ Jim_NewStringObj(interp, type, -1));\r
+ Jim_ListAppendElement(interp, subListObjPtr,\r
+ Jim_NewIntObj(interp, objPtr->refCount));\r
+ Jim_ListAppendElement(interp, subListObjPtr, objPtr);\r
+ Jim_ListAppendElement(interp, listObjPtr, subListObjPtr);\r
+ objPtr = objPtr->nextObjPtr;\r
+ }\r
+ Jim_SetResult(interp, listObjPtr);\r
+ return JIM_OK;\r
+ } else if (option == OPT_INVSTR) {\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "object");\r
+ return JIM_ERR;\r
+ }\r
+ objPtr = argv[2];\r
+ if (objPtr->typePtr != NULL)\r
+ Jim_InvalidateStringRep(objPtr);\r
+ Jim_SetEmptyResult(interp);\r
+ return JIM_OK;\r
+ } else if (option == OPT_SCRIPTLEN) {\r
+ ScriptObj *script;\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "script");\r
+ return JIM_ERR;\r
+ }\r
+ script = Jim_GetScript(interp, argv[2]);\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, script->len));\r
+ return JIM_OK;\r
+ } else if (option == OPT_EXPRLEN) {\r
+ ExprByteCode *expr;\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "expression");\r
+ return JIM_ERR;\r
+ }\r
+ expr = Jim_GetExpression(interp, argv[2]);\r
+ if (expr == NULL)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, expr->len));\r
+ return JIM_OK;\r
+ } else if (option == OPT_EXPRBC) {\r
+ Jim_Obj *objPtr;\r
+ ExprByteCode *expr;\r
+ int i;\r
+\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "expression");\r
+ return JIM_ERR;\r
+ }\r
+ expr = Jim_GetExpression(interp, argv[2]);\r
+ if (expr == NULL)\r
+ return JIM_ERR;\r
+ objPtr = Jim_NewListObj(interp, NULL, 0);\r
+ for (i = 0; i < expr->len; i++) {\r
+ const char *type;\r
+ Jim_ExprOperator *op;\r
+\r
+ switch(expr->opcode[i]) {\r
+ case JIM_EXPROP_NUMBER: type = "number"; break;\r
+ case JIM_EXPROP_COMMAND: type = "command"; break;\r
+ case JIM_EXPROP_VARIABLE: type = "variable"; break;\r
+ case JIM_EXPROP_DICTSUGAR: type = "dictsugar"; break;\r
+ case JIM_EXPROP_SUBST: type = "subst"; break;\r
+ case JIM_EXPROP_STRING: type = "string"; break;\r
+ default:\r
+ op = JimExprOperatorInfo(Jim_GetString(expr->obj[i], NULL));\r
+ if (op == NULL) {\r
+ type = "private";\r
+ } else {\r
+ type = "operator";\r
+ }\r
+ break;\r
+ }\r
+ Jim_ListAppendElement(interp, objPtr,\r
+ Jim_NewStringObj(interp, type, -1));\r
+ Jim_ListAppendElement(interp, objPtr, expr->obj[i]);\r
+ }\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+ } else {\r
+ Jim_SetResultString(interp,\r
+ "bad option. Valid options are refcount, "\r
+ "objcount, objects, invstr", -1);\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_OK; /* unreached */\r
+}\r
+\r
+/* [eval] */\r
+static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc == 2) {\r
+ return Jim_EvalObj(interp, argv[1]);\r
+ } else if (argc > 2) {\r
+ Jim_Obj *objPtr;\r
+ int retcode;\r
+\r
+ objPtr = Jim_ConcatObj(interp, argc-1, argv+1);\r
+ Jim_IncrRefCount(objPtr);\r
+ retcode = Jim_EvalObj(interp, objPtr);\r
+ Jim_DecrRefCount(interp, objPtr);\r
+ return retcode;\r
+ } else {\r
+ Jim_WrongNumArgs(interp, 1, argv, "script ?...?");\r
+ return JIM_ERR;\r
+ }\r
+}\r
+\r
+/* [uplevel] */\r
+static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc >= 2) {\r
+ int retcode, newLevel, oldLevel;\r
+ Jim_CallFrame *savedCallFrame, *targetCallFrame;\r
+ Jim_Obj *objPtr;\r
+ const char *str;\r
+\r
+ /* Save the old callframe pointer */\r
+ savedCallFrame = interp->framePtr;\r
+\r
+ /* Lookup the target frame pointer */\r
+ str = Jim_GetString(argv[1], NULL);\r
+ if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#')\r
+ {\r
+ if (Jim_GetCallFrameByLevel(interp, argv[1],\r
+ &targetCallFrame,\r
+ &newLevel) != JIM_OK)\r
+ return JIM_ERR;\r
+ argc--;\r
+ argv++;\r
+ } else {\r
+ if (Jim_GetCallFrameByLevel(interp, NULL,\r
+ &targetCallFrame,\r
+ &newLevel) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ if (argc < 2) {\r
+ argc++;\r
+ argv--;\r
+ Jim_WrongNumArgs(interp, 1, argv,\r
+ "?level? command ?arg ...?");\r
+ return JIM_ERR;\r
+ }\r
+ /* Eval the code in the target callframe. */\r
+ interp->framePtr = targetCallFrame;\r
+ oldLevel = interp->numLevels;\r
+ interp->numLevels = newLevel;\r
+ if (argc == 2) {\r
+ retcode = Jim_EvalObj(interp, argv[1]);\r
+ } else {\r
+ objPtr = Jim_ConcatObj(interp, argc-1, argv+1);\r
+ Jim_IncrRefCount(objPtr);\r
+ retcode = Jim_EvalObj(interp, objPtr);\r
+ Jim_DecrRefCount(interp, objPtr);\r
+ }\r
+ interp->numLevels = oldLevel;\r
+ interp->framePtr = savedCallFrame;\r
+ return retcode;\r
+ } else {\r
+ Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");\r
+ return JIM_ERR;\r
+ }\r
+}\r
+\r
+/* [expr] */\r
+static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *exprResultPtr;\r
+ int retcode;\r
+\r
+ if (argc == 2) {\r
+ retcode = Jim_EvalExpression(interp, argv[1], &exprResultPtr);\r
+ } else if (argc > 2) {\r
+ Jim_Obj *objPtr;\r
+\r
+ objPtr = Jim_ConcatObj(interp, argc-1, argv+1);\r
+ Jim_IncrRefCount(objPtr);\r
+ retcode = Jim_EvalExpression(interp, objPtr, &exprResultPtr);\r
+ Jim_DecrRefCount(interp, objPtr);\r
+ } else {\r
+ Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");\r
+ return JIM_ERR;\r
+ }\r
+ if (retcode != JIM_OK) return retcode;\r
+ Jim_SetResult(interp, exprResultPtr);\r
+ Jim_DecrRefCount(interp, exprResultPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [break] */\r
+static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 1) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "");\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_BREAK;\r
+}\r
+\r
+/* [continue] */\r
+static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 1) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "");\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_CONTINUE;\r
+}\r
+\r
+/* [return] */\r
+static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc == 1) {\r
+ return JIM_RETURN;\r
+ } else if (argc == 2) {\r
+ Jim_SetResult(interp, argv[1]);\r
+ interp->returnCode = JIM_OK;\r
+ return JIM_RETURN;\r
+ } else if (argc == 3 || argc == 4) {\r
+ int returnCode;\r
+ if (Jim_GetReturnCode(interp, argv[2], &returnCode) == JIM_ERR)\r
+ return JIM_ERR;\r
+ interp->returnCode = returnCode;\r
+ if (argc == 4)\r
+ Jim_SetResult(interp, argv[3]);\r
+ return JIM_RETURN;\r
+ } else {\r
+ Jim_WrongNumArgs(interp, 1, argv, "?-code code? ?result?");\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_RETURN; /* unreached */\r
+}\r
+\r
+/* [tailcall] */\r
+static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *objPtr;\r
+\r
+ objPtr = Jim_NewListObj(interp, argv+1, argc-1);\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_EVAL;\r
+}\r
+\r
+/* [proc] */\r
+static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int argListLen;\r
+ int arityMin, arityMax;\r
+\r
+ if (argc != 4 && argc != 5) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_ListLength(interp, argv[2], &argListLen);\r
+ arityMin = arityMax = argListLen+1;\r
+ if (argListLen) {\r
+ const char *str;\r
+ int len;\r
+ Jim_Obj *lastArgPtr;\r
+ \r
+ Jim_ListIndex(interp, argv[2], argListLen-1, &lastArgPtr, JIM_NONE);\r
+ str = Jim_GetString(lastArgPtr, &len);\r
+ if (len == 4 && memcmp(str, "args", 4) == 0) {\r
+ arityMin--;\r
+ arityMax = -1;\r
+ }\r
+ }\r
+ if (argc == 4) {\r
+ return Jim_CreateProcedure(interp, Jim_GetString(argv[1], NULL),\r
+ argv[2], NULL, argv[3], arityMin, arityMax);\r
+ } else {\r
+ return Jim_CreateProcedure(interp, Jim_GetString(argv[1], NULL),\r
+ argv[2], argv[3], argv[4], arityMin, arityMax);\r
+ }\r
+}\r
+\r
+/* [concat] */\r
+static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_SetResult(interp, Jim_ConcatObj(interp, argc-1, argv+1));\r
+ return JIM_OK;\r
+}\r
+\r
+/* [upvar] */\r
+static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ const char *str;\r
+ int i;\r
+ Jim_CallFrame *targetCallFrame;\r
+\r
+ /* Lookup the target frame pointer */\r
+ str = Jim_GetString(argv[1], NULL);\r
+ if (argc > 3 && \r
+ ((str[0] >= '0' && str[0] <= '9') || str[0] == '#'))\r
+ {\r
+ if (Jim_GetCallFrameByLevel(interp, argv[1],\r
+ &targetCallFrame, NULL) != JIM_OK)\r
+ return JIM_ERR;\r
+ argc--;\r
+ argv++;\r
+ } else {\r
+ if (Jim_GetCallFrameByLevel(interp, NULL,\r
+ &targetCallFrame, NULL) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ /* Check for arity */\r
+ if (argc < 3 || ((argc-1)%2) != 0) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");\r
+ return JIM_ERR;\r
+ }\r
+ /* Now... for every other/local couple: */\r
+ for (i = 1; i < argc; i += 2) {\r
+ if (Jim_SetVariableLink(interp, argv[i+1], argv[i],\r
+ targetCallFrame) != JIM_OK) return JIM_ERR;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* [global] */\r
+static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int i;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");\r
+ return JIM_ERR;\r
+ }\r
+ /* Link every var to the toplevel having the same name */\r
+ if (interp->numLevels == 0) return JIM_OK; /* global at toplevel... */\r
+ for (i = 1; i < argc; i++) {\r
+ if (Jim_SetVariableLink(interp, argv[i], argv[i],\r
+ interp->topFramePtr) != JIM_OK) return JIM_ERR;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* does the [string map] operation. On error NULL is returned,\r
+ * otherwise a new string object with the result, having refcount = 0,\r
+ * is returned. */\r
+static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,\r
+ Jim_Obj *objPtr, int nocase)\r
+{\r
+ int numMaps;\r
+ const char **key, *str, *noMatchStart = NULL;\r
+ Jim_Obj **value;\r
+ int *keyLen, strLen, i;\r
+ Jim_Obj *resultObjPtr;\r
+ \r
+ Jim_ListLength(interp, mapListObjPtr, &numMaps);\r
+ if (numMaps % 2) {\r
+ Jim_SetResultString(interp,\r
+ "list must contain an even number of elements", -1);\r
+ return NULL;\r
+ }\r
+ /* Initialization */\r
+ numMaps /= 2;\r
+ key = Jim_Alloc(sizeof(char*)*numMaps);\r
+ keyLen = Jim_Alloc(sizeof(int)*numMaps);\r
+ value = Jim_Alloc(sizeof(Jim_Obj*)*numMaps);\r
+ resultObjPtr = Jim_NewStringObj(interp, "", 0);\r
+ for (i = 0; i < numMaps; i++) {\r
+ Jim_Obj *eleObjPtr;\r
+\r
+ Jim_ListIndex(interp, mapListObjPtr, i*2, &eleObjPtr, JIM_NONE);\r
+ key[i] = Jim_GetString(eleObjPtr, &keyLen[i]);\r
+ Jim_ListIndex(interp, mapListObjPtr, i*2+1, &eleObjPtr, JIM_NONE);\r
+ value[i] = eleObjPtr;\r
+ }\r
+ str = Jim_GetString(objPtr, &strLen);\r
+ /* Map it */\r
+ while(strLen) {\r
+ for (i = 0; i < numMaps; i++) {\r
+ if (strLen >= keyLen[i] && keyLen[i]) {\r
+ if (!JimStringCompare(str, keyLen[i], key[i], keyLen[i],\r
+ nocase))\r
+ {\r
+ if (noMatchStart) {\r
+ Jim_AppendString(interp, resultObjPtr,\r
+ noMatchStart, str-noMatchStart);\r
+ noMatchStart = NULL;\r
+ }\r
+ Jim_AppendObj(interp, resultObjPtr, value[i]);\r
+ str += keyLen[i];\r
+ strLen -= keyLen[i];\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ if (i == numMaps) { /* no match */\r
+ if (noMatchStart == NULL)\r
+ noMatchStart = str;\r
+ str ++;\r
+ strLen --;\r
+ }\r
+ }\r
+ if (noMatchStart) {\r
+ Jim_AppendString(interp, resultObjPtr,\r
+ noMatchStart, str-noMatchStart);\r
+ }\r
+ Jim_Free((void*)key);\r
+ Jim_Free(keyLen);\r
+ Jim_Free(value);\r
+ return resultObjPtr;\r
+}\r
+\r
+/* [string] */\r
+static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int option;\r
+ const char *options[] = {\r
+ "length", "compare", "match", "equal", "range", "map", "repeat",\r
+ "index", "first", "tolower", "toupper", NULL\r
+ };\r
+ enum {\r
+ OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_RANGE,\r
+ OPT_MAP, OPT_REPEAT, OPT_INDEX, OPT_FIRST, OPT_TOLOWER, OPT_TOUPPER\r
+ };\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");\r
+ return JIM_ERR;\r
+ }\r
+ if (Jim_GetEnum(interp, argv[1], options, &option, "option",\r
+ JIM_ERRMSG) != JIM_OK)\r
+ return JIM_ERR;\r
+\r
+ if (option == OPT_LENGTH) {\r
+ int len;\r
+\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_GetString(argv[2], &len);\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, len));\r
+ return JIM_OK;\r
+ } else if (option == OPT_COMPARE) {\r
+ int nocase = 0;\r
+ if ((argc != 4 && argc != 5) ||\r
+ (argc == 5 && Jim_CompareStringImmediate(interp,\r
+ argv[2], "-nocase") == 0)) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string1 string2");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 5) {\r
+ nocase = 1;\r
+ argv++;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp,\r
+ Jim_StringCompareObj(argv[2],\r
+ argv[3], nocase)));\r
+ return JIM_OK;\r
+ } else if (option == OPT_MATCH) {\r
+ int nocase = 0;\r
+ if ((argc != 4 && argc != 5) ||\r
+ (argc == 5 && Jim_CompareStringImmediate(interp,\r
+ argv[2], "-nocase") == 0)) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern "\r
+ "string");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 5) {\r
+ nocase = 1;\r
+ argv++;\r
+ }\r
+ Jim_SetResult(interp,\r
+ Jim_NewIntObj(interp, Jim_StringMatchObj(argv[2],\r
+ argv[3], nocase)));\r
+ return JIM_OK;\r
+ } else if (option == OPT_EQUAL) {\r
+ if (argc != 4) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string1 string2");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp,\r
+ Jim_NewIntObj(interp, Jim_StringEqObj(argv[2],\r
+ argv[3], 0)));\r
+ return JIM_OK;\r
+ } else if (option == OPT_RANGE) {\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc != 5) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string first last");\r
+ return JIM_ERR;\r
+ }\r
+ objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);\r
+ if (objPtr == NULL)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+ } else if (option == OPT_MAP) {\r
+ int nocase = 0;\r
+ Jim_Obj *objPtr;\r
+\r
+ if ((argc != 4 && argc != 5) ||\r
+ (argc == 5 && Jim_CompareStringImmediate(interp,\r
+ argv[2], "-nocase") == 0)) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList "\r
+ "string");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 5) {\r
+ nocase = 1;\r
+ argv++;\r
+ }\r
+ objPtr = JimStringMap(interp, argv[2], argv[3], nocase);\r
+ if (objPtr == NULL)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+ } else if (option == OPT_REPEAT) {\r
+ Jim_Obj *objPtr;\r
+ jim_wide count;\r
+\r
+ if (argc != 4) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string count");\r
+ return JIM_ERR;\r
+ }\r
+ if (Jim_GetWide(interp, argv[3], &count) != JIM_OK)\r
+ return JIM_ERR;\r
+ objPtr = Jim_NewStringObj(interp, "", 0);\r
+ while (count--) {\r
+ Jim_AppendObj(interp, objPtr, argv[2]);\r
+ }\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+ } else if (option == OPT_INDEX) {\r
+ int index, len;\r
+ const char *str;\r
+\r
+ if (argc != 4) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string index");\r
+ return JIM_ERR;\r
+ }\r
+ if (Jim_GetIndex(interp, argv[3], &index) != JIM_OK)\r
+ return JIM_ERR;\r
+ str = Jim_GetString(argv[2], &len);\r
+ if (index != INT_MIN && index != INT_MAX)\r
+ index = JimRelToAbsIndex(len, index);\r
+ if (index < 0 || index >= len) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ return JIM_OK;\r
+ } else {\r
+ Jim_SetResult(interp, Jim_NewStringObj(interp, str+index, 1));\r
+ return JIM_OK;\r
+ }\r
+ } else if (option == OPT_FIRST) {\r
+ int index = 0, l1, l2;\r
+ const char *s1, *s2;\r
+\r
+ if (argc != 4 && argc != 5) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "subString string ?startIndex?");\r
+ return JIM_ERR;\r
+ }\r
+ s1 = Jim_GetString(argv[2], &l1);\r
+ s2 = Jim_GetString(argv[3], &l2);\r
+ if (argc == 5) {\r
+ if (Jim_GetIndex(interp, argv[4], &index) != JIM_OK)\r
+ return JIM_ERR;\r
+ index = JimRelToAbsIndex(l2, index);\r
+ }\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp,\r
+ JimStringFirst(s1, l1, s2, l2, index)));\r
+ return JIM_OK;\r
+ } else if (option == OPT_TOLOWER) {\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, JimStringToLower(interp, argv[2]));\r
+ } else if (option == OPT_TOUPPER) {\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "string");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* [time] */\r
+static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ long i, count = 1;\r
+ jim_wide start, elapsed;\r
+ char buf [256];\r
+ const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "script ?count?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 3) {\r
+ if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ if (count < 0)\r
+ return JIM_OK;\r
+ i = count;\r
+ start = JimClock();\r
+ while (i-- > 0) {\r
+ int retval;\r
+\r
+ if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK)\r
+ return retval;\r
+ }\r
+ elapsed = JimClock() - start;\r
+ sprintf(buf, fmt, elapsed/count);\r
+ Jim_SetResultString(interp, buf, -1);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [exit] */\r
+static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ long exitCode = 0;\r
+\r
+ if (argc > 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 2) {\r
+ if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ interp->exitCode = exitCode;\r
+ return JIM_EXIT;\r
+}\r
+\r
+/* [catch] */\r
+static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int exitCode = 0;\r
+\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "script ?varName?");\r
+ return JIM_ERR;\r
+ }\r
+ exitCode = Jim_EvalObj(interp, argv[1]);\r
+ if (argc == 3) {\r
+ if (Jim_SetVariable(interp, argv[2], Jim_GetResult(interp))\r
+ != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, exitCode));\r
+ return JIM_OK;\r
+}\r
+\r
+/* [ref] */\r
+static int Jim_RefCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 3 && argc != 4) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "string tag ?finalizer?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 3) {\r
+ Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], NULL));\r
+ } else {\r
+ Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2],\r
+ argv[3]));\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* [getref] */\r
+static int Jim_GetrefCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Reference *refPtr;\r
+\r
+ if (argc != 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "reference");\r
+ return JIM_ERR;\r
+ }\r
+ if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, refPtr->objPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [setref] */\r
+static int Jim_SetrefCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Reference *refPtr;\r
+\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "reference newValue");\r
+ return JIM_ERR;\r
+ }\r
+ if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)\r
+ return JIM_ERR;\r
+ Jim_IncrRefCount(argv[2]);\r
+ Jim_DecrRefCount(interp, refPtr->objPtr);\r
+ refPtr->objPtr = argv[2];\r
+ Jim_SetResult(interp, argv[2]);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [collect] */\r
+static int Jim_CollectCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 1) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, Jim_Collect(interp)));\r
+ return JIM_OK;\r
+}\r
+\r
+/* [finalize] reference ?newValue? */\r
+static int Jim_FinalizeCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "reference ?finalizerProc?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 2) {\r
+ Jim_Obj *cmdNamePtr;\r
+\r
+ if (Jim_GetFinalizer(interp, argv[1], &cmdNamePtr) != JIM_OK)\r
+ return JIM_ERR;\r
+ if (cmdNamePtr != NULL) /* otherwise the null string is returned. */\r
+ Jim_SetResult(interp, cmdNamePtr);\r
+ } else {\r
+ if (Jim_SetFinalizer(interp, argv[1], argv[2]) != JIM_OK)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, argv[2]);\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* TODO */\r
+/* [info references] (list of all the references/finalizers) */\r
+\r
+/* [rename] */\r
+static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ const char *oldName, *newName;\r
+\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "oldName newName");\r
+ return JIM_ERR;\r
+ }\r
+ oldName = Jim_GetString(argv[1], NULL);\r
+ newName = Jim_GetString(argv[2], NULL);\r
+ if (Jim_RenameCommand(interp, oldName, newName) != JIM_OK) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "can't rename \"", oldName, "\": ",\r
+ "command doesn't exist", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* [dict] */\r
+static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int option;\r
+ const char *options[] = {\r
+ "create", "get", "set", "unset", "exists", NULL\r
+ };\r
+ enum {\r
+ OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXIST\r
+ };\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");\r
+ return JIM_ERR;\r
+ }\r
+\r
+ if (Jim_GetEnum(interp, argv[1], options, &option, "option",\r
+ JIM_ERRMSG) != JIM_OK)\r
+ return JIM_ERR;\r
+\r
+ if (option == OPT_CREATE) {\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc % 2) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");\r
+ return JIM_ERR;\r
+ }\r
+ objPtr = Jim_NewDictObj(interp, argv+2, argc-2);\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+ } else if (option == OPT_GET) {\r
+ Jim_Obj *objPtr;\r
+\r
+ if (Jim_DictKeysVector(interp, argv[2], argv+3, argc-3, &objPtr,\r
+ JIM_ERRMSG) != JIM_OK)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+ } else if (option == OPT_SET) {\r
+ if (argc < 5) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");\r
+ return JIM_ERR;\r
+ }\r
+ return Jim_SetDictKeysVector(interp, argv[2], argv+3, argc-4,\r
+ argv[argc-1]);\r
+ } else if (option == OPT_UNSET) {\r
+ if (argc < 4) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");\r
+ return JIM_ERR;\r
+ }\r
+ return Jim_SetDictKeysVector(interp, argv[2], argv+3, argc-3,\r
+ NULL);\r
+ } else if (option == OPT_EXIST) {\r
+ Jim_Obj *objPtr;\r
+ int exists;\r
+\r
+ if (Jim_DictKeysVector(interp, argv[2], argv+3, argc-3, &objPtr,\r
+ JIM_ERRMSG) == JIM_OK)\r
+ exists = 1;\r
+ else\r
+ exists = 0;\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, exists));\r
+ return JIM_OK;\r
+ } else {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad option \"", Jim_GetString(argv[1], NULL), "\":",\r
+ " must be create, get, set", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+/* [load] */\r
+static int Jim_LoadCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "libaryFile");\r
+ return JIM_ERR;\r
+ }\r
+ return Jim_LoadLibrary(interp, Jim_GetString(argv[1], NULL));\r
+}\r
+\r
+/* [subst] */\r
+static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int i, flags = 0;\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv,\r
+ "?-nobackslashes? ?-nocommands? ?-novariables? string");\r
+ return JIM_ERR;\r
+ }\r
+ i = argc-2;\r
+ while(i--) {\r
+ if (Jim_CompareStringImmediate(interp, argv[i+1],\r
+ "-nobackslashes"))\r
+ flags |= JIM_SUBST_NOESC;\r
+ else if (Jim_CompareStringImmediate(interp, argv[i+1],\r
+ "-novariables"))\r
+ flags |= JIM_SUBST_NOVAR;\r
+ else if (Jim_CompareStringImmediate(interp, argv[i+1],\r
+ "-nocommands"))\r
+ flags |= JIM_SUBST_NOCMD;\r
+ else {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "bad option \"", Jim_GetString(argv[i+1], NULL),\r
+ "\": must be -nobackslashes, -nocommands, or "\r
+ "-novariables", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ }\r
+ if (Jim_SubstObj(interp, argv[argc-1], &objPtr, flags) != JIM_OK)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [info] */\r
+static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int cmd, result = JIM_OK;\r
+ static const char *commands[] = {\r
+ "body", "commands", "exists", "globals", "level", "locals",\r
+ "vars", "version", "complete", "args", NULL\r
+ };\r
+ enum {INFO_BODY, INFO_COMMANDS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,\r
+ INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_COMPLETE, INFO_ARGS};\r
+ \r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "command ?args ...?");\r
+ return JIM_ERR;\r
+ }\r
+ if (Jim_GetEnum(interp, argv[1], commands, &cmd, "command", JIM_ERRMSG)\r
+ != JIM_OK) {\r
+ return JIM_ERR;\r
+ }\r
+ \r
+ if (cmd == INFO_COMMANDS) {\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "?pattern?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 3)\r
+ Jim_SetResult(interp,JimCommandsList(interp, argv[2]));\r
+ else\r
+ Jim_SetResult(interp, JimCommandsList(interp, NULL));\r
+ } else if (cmd == INFO_EXISTS) {\r
+ Jim_Obj *exists;\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "varName");\r
+ return JIM_ERR;\r
+ }\r
+ exists = Jim_GetVariable(interp, argv[2], 0);\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, exists != 0));\r
+ } else if (cmd == INFO_GLOBALS || cmd == INFO_LOCALS || cmd == INFO_VARS) {\r
+ int mode;\r
+ switch (cmd) {\r
+ case INFO_GLOBALS: mode = JIM_VARLIST_GLOBALS; break;\r
+ case INFO_LOCALS: mode = JIM_VARLIST_LOCALS; break;\r
+ case INFO_VARS: mode = JIM_VARLIST_VARS; break;\r
+ default: mode = 0; /* avoid warning */; break;\r
+ }\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "?pattern?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 3)\r
+ Jim_SetResult(interp,JimVariablesList(interp, argv[2], mode));\r
+ else\r
+ Jim_SetResult(interp, JimVariablesList(interp, NULL, mode));\r
+ } else if (cmd == INFO_LEVEL) {\r
+ Jim_Obj *objPtr;\r
+ switch (argc) {\r
+ case 2:\r
+ Jim_SetResult(interp,\r
+ Jim_NewIntObj(interp, interp->numLevels));\r
+ break;\r
+ case 3:\r
+ if (JimInfoLevel(interp, argv[2], &objPtr) != JIM_OK)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ break;\r
+ default:\r
+ Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");\r
+ return JIM_ERR;\r
+ }\r
+ } else if (cmd == INFO_BODY || cmd == INFO_ARGS) {\r
+ Jim_Cmd *cmdPtr;\r
+\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "procname");\r
+ return JIM_ERR;\r
+ }\r
+ if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL)\r
+ return JIM_ERR;\r
+ if (cmdPtr->cmdProc != NULL) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "command \"", Jim_GetString(argv[2], NULL),\r
+ "\" is not a procedure", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ if (cmd == INFO_BODY)\r
+ Jim_SetResult(interp, cmdPtr->bodyObjPtr);\r
+ else\r
+ Jim_SetResult(interp, cmdPtr->argListObjPtr);\r
+ } else if (cmd == INFO_VERSION) {\r
+ char buf[(JIM_INTEGER_SPACE * 2) + 1];\r
+ sprintf(buf, "%d.%d", \r
+ JIM_VERSION / 100, JIM_VERSION % 100);\r
+ Jim_SetResultString(interp, buf, -1);\r
+ } else if (cmd == INFO_COMPLETE) {\r
+ const char *s;\r
+ int len;\r
+\r
+ if (argc != 3) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "script");\r
+ return JIM_ERR;\r
+ }\r
+ s = Jim_GetString(argv[2], &len);\r
+ Jim_SetResult(interp,\r
+ Jim_NewIntObj(interp, Jim_ScriptIsComplete(s, len, NULL)));\r
+ }\r
+ return result;\r
+}\r
+\r
+/* [split] */\r
+static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ const char *str, *splitChars, *noMatchStart;\r
+ int splitLen, strLen, i;\r
+ Jim_Obj *resObjPtr;\r
+\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");\r
+ return JIM_ERR;\r
+ }\r
+ /* Init */\r
+ if (argc == 2) {\r
+ splitChars = " \n\t\r";\r
+ splitLen = 4;\r
+ } else {\r
+ splitChars = Jim_GetString(argv[2], &splitLen);\r
+ }\r
+ str = Jim_GetString(argv[1], &strLen);\r
+ if (!strLen) return JIM_OK;\r
+ noMatchStart = str;\r
+ resObjPtr = Jim_NewListObj(interp, NULL, 0);\r
+ /* Split */\r
+ if (splitLen) {\r
+ while (strLen) {\r
+ for (i = 0; i < splitLen; i++) {\r
+ if (*str == splitChars[i]) {\r
+ Jim_Obj *objPtr;\r
+\r
+ objPtr = Jim_NewStringObj(interp, noMatchStart,\r
+ (str-noMatchStart));\r
+ Jim_ListAppendElement(interp, resObjPtr, objPtr);\r
+ noMatchStart = str+1;\r
+ break;\r
+ }\r
+ }\r
+ str ++;\r
+ strLen --;\r
+ }\r
+ Jim_ListAppendElement(interp, resObjPtr,\r
+ Jim_NewStringObj(interp, noMatchStart, (str-noMatchStart)));\r
+ } else {\r
+ /* This handles the special case of splitchars eq {}. This\r
+ * is trivial but we want to perform object sharing as Tcl does. */\r
+ Jim_Obj *objCache[256];\r
+ const unsigned char *u = (unsigned char*) str;\r
+ memset(objCache, 0, sizeof(objCache));\r
+ for (i = 0; i < strLen; i++) {\r
+ int c = u[i];\r
+ \r
+ if (objCache[c] == NULL)\r
+ objCache[c] = Jim_NewStringObj(interp, (char*)u+i, 1);\r
+ Jim_ListAppendElement(interp, resObjPtr, objCache[c]);\r
+ }\r
+ }\r
+ Jim_SetResult(interp, resObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [join] */\r
+static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ const char *joinStr;\r
+ int joinStrLen, i, listLen;\r
+ Jim_Obj *resObjPtr;\r
+\r
+ if (argc != 2 && argc != 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");\r
+ return JIM_ERR;\r
+ }\r
+ /* Init */\r
+ if (argc == 2) {\r
+ joinStr = " ";\r
+ joinStrLen = 1;\r
+ } else {\r
+ joinStr = Jim_GetString(argv[2], &joinStrLen);\r
+ }\r
+ Jim_ListLength(interp, argv[1], &listLen);\r
+ resObjPtr = Jim_NewStringObj(interp, NULL, 0);\r
+ /* Split */\r
+ for (i = 0; i < listLen; i++) {\r
+ Jim_Obj *objPtr;\r
+\r
+ Jim_ListIndex(interp, argv[1], i, &objPtr, JIM_NONE);\r
+ Jim_AppendObj(interp, resObjPtr, objPtr);\r
+ if (i+1 != listLen) {\r
+ Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);\r
+ }\r
+ }\r
+ Jim_SetResult(interp, resObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [format] */\r
+static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");\r
+ return JIM_ERR;\r
+ }\r
+ objPtr = Jim_FormatString(interp, argv[1], argc-2, argv+2);\r
+ if (objPtr == NULL)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [scan] */\r
+static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *listPtr, **outVec;\r
+ int outc, i, count = 0;\r
+\r
+ if (argc < 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "string formatString ?varName ...?");\r
+ return JIM_ERR;\r
+ } \r
+ if (argv[2]->typePtr != &scanFmtStringObjType)\r
+ SetScanFmtFromAny(interp, argv[2]);\r
+ if (FormatGetError(argv[2]) != 0) {\r
+ Jim_SetResultString(interp, FormatGetError(argv[2]), -1);\r
+ return JIM_ERR;\r
+ }\r
+ if (argc > 3) {\r
+ int maxPos = FormatGetMaxPos(argv[2]);\r
+ int count = FormatGetCnvCount(argv[2]);\r
+ if (maxPos > argc-3) {\r
+ Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);\r
+ return JIM_ERR;\r
+ } else if (count != 0 && count < argc-3) {\r
+ Jim_SetResultString(interp, "variable is not assigned by any "\r
+ "conversion specifiers", -1);\r
+ return JIM_ERR;\r
+ } else if (count > argc-3) {\r
+ Jim_SetResultString(interp, "different numbers of variable names and "\r
+ "field specifiers", -1);\r
+ return JIM_ERR;\r
+ }\r
+ } \r
+ listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);\r
+ if (listPtr == 0)\r
+ return JIM_ERR;\r
+ if (argc > 3) {\r
+ int len = 0;\r
+ if (listPtr != 0 && listPtr != (Jim_Obj*)EOF)\r
+ Jim_ListLength(interp, listPtr, &len);\r
+ if (listPtr == (Jim_Obj*)EOF || len == 0) { // XXX\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, -1));\r
+ return JIM_OK;\r
+ }\r
+ JimListGetElements(interp, listPtr, &outc, &outVec);\r
+ for (i = 0; i < outc; ++i) {\r
+ if (Jim_Length(outVec[i]) > 0) {\r
+ ++count;\r
+ if (Jim_SetVariable(interp, argv[3+i], outVec[i]) != JIM_OK)\r
+ goto err;\r
+ }\r
+ }\r
+ Jim_FreeNewObj(interp, listPtr);\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, count));\r
+ } else {\r
+ if (listPtr == (Jim_Obj*)EOF) {\r
+ Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));\r
+ return JIM_OK;\r
+ }\r
+ Jim_SetResult(interp, listPtr);\r
+ }\r
+ return JIM_OK;\r
+err:\r
+ Jim_FreeNewObj(interp, listPtr);\r
+ return JIM_ERR;\r
+}\r
+\r
+/* [error] */\r
+static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ if (argc != 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "message");\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, argv[1]);\r
+ return JIM_ERR;\r
+}\r
+\r
+/* [lrange] */\r
+static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc != 4) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "list first last");\r
+ return JIM_ERR;\r
+ }\r
+ if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)\r
+ return JIM_ERR;\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [env] */\r
+static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ const char *key;\r
+ char *val;\r
+\r
+ if (argc != 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "varName");\r
+ return JIM_ERR;\r
+ }\r
+ key = Jim_GetString(argv[1], NULL);\r
+ val = getenv(key);\r
+ if (val == NULL) {\r
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));\r
+ Jim_AppendStrings(interp, Jim_GetResult(interp),\r
+ "environment variable \"",\r
+ key, "\" does not exist", NULL);\r
+ return JIM_ERR;\r
+ }\r
+ Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));\r
+ return JIM_OK;\r
+}\r
+\r
+/* [source] */\r
+static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ int retval;\r
+\r
+ if (argc != 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "fileName");\r
+ return JIM_ERR;\r
+ }\r
+ retval = Jim_EvalFile(interp, Jim_GetString(argv[1], NULL));\r
+ if (retval == JIM_RETURN)\r
+ return JIM_OK;\r
+ return retval;\r
+}\r
+\r
+/* [lreverse] */\r
+static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ Jim_Obj *revObjPtr, **ele;\r
+ int len;\r
+\r
+ if (argc != 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "list");\r
+ return JIM_ERR;\r
+ }\r
+ JimListGetElements(interp, argv[1], &len, &ele);\r
+ len--;\r
+ revObjPtr = Jim_NewListObj(interp, NULL, 0);\r
+ while (len >= 0)\r
+ ListAppendElement(revObjPtr, ele[len--]);\r
+ Jim_SetResult(interp, revObjPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)\r
+{\r
+ jim_wide len;\r
+\r
+ if (step == 0) return -1;\r
+ if (start == end) return 0;\r
+ else if (step > 0 && start > end) return -1;\r
+ else if (step < 0 && end > start) return -1;\r
+ len = end-start;\r
+ if (len < 0) len = -len; /* abs(len) */\r
+ if (step < 0) step = -step; /* abs(step) */\r
+ len = 1 + ((len-1)/step);\r
+ /* We can truncate safely to INT_MAX, the range command\r
+ * will always return an error for a such long range\r
+ * because Tcl lists can't be so long. */\r
+ if (len > INT_MAX) len = INT_MAX;\r
+ return (int)((len < 0) ? -1 : len);\r
+}\r
+\r
+/* [range] */\r
+static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ jim_wide start = 0, end, step = 1;\r
+ int len, i;\r
+ Jim_Obj *objPtr;\r
+\r
+ if (argc < 2 || argc > 4) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 2) {\r
+ if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)\r
+ return JIM_ERR;\r
+ } else {\r
+ if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||\r
+ Jim_GetWide(interp, argv[2], &end) != JIM_OK)\r
+ return JIM_ERR;\r
+ if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ if ((len = JimRangeLen(start, end, step)) == -1) {\r
+ Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);\r
+ return JIM_ERR;\r
+ }\r
+ objPtr = Jim_NewListObj(interp, NULL, 0);\r
+ for (i = 0; i < len; i++)\r
+ ListAppendElement(objPtr, Jim_NewIntObj(interp, start+i*step));\r
+ Jim_SetResult(interp, objPtr);\r
+ return JIM_OK;\r
+}\r
+\r
+/* [rand] */\r
+static int Jim_RandCoreCommand(Jim_Interp *interp, int argc,\r
+ Jim_Obj *const *argv)\r
+{\r
+ jim_wide min = 0, max, len, maxMul;\r
+\r
+ if (argc < 1 || argc > 3) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "?min? max");\r
+ return JIM_ERR;\r
+ }\r
+ if (argc == 1) {\r
+ max = JIM_WIDE_MAX;\r
+ } else if (argc == 2) {\r
+ if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)\r
+ return JIM_ERR;\r
+ } else if (argc == 3) {\r
+ if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||\r
+ Jim_GetWide(interp, argv[2], &max) != JIM_OK)\r
+ return JIM_ERR;\r
+ }\r
+ len = max-min;\r
+ if (len < 0) {\r
+ Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);\r
+ return JIM_ERR;\r
+ }\r
+ maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);\r
+ while (1) {\r
+ jim_wide r;\r
+\r
+ JimRandomBytes(interp, &r, sizeof(jim_wide));\r
+ if (r < 0 || r >= maxMul) continue;\r
+ r = (len == 0) ? 0 : r%len;\r
+ Jim_SetResult(interp, Jim_NewIntObj(interp, min+r));\r
+ return JIM_OK;\r
+ }\r
+}\r
+\r
+/* [package] */\r
+static int Jim_PackageCoreCommand(Jim_Interp *interp, int argc, \r
+ Jim_Obj *const *argv)\r
+{\r
+ int option;\r
+ const char *options[] = {\r
+ "require", "provide", NULL\r
+ };\r
+ enum {OPT_REQUIRE, OPT_PROVIDE};\r
+\r
+ if (argc < 2) {\r
+ Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");\r
+ return JIM_ERR;\r
+ }\r
+ if (Jim_GetEnum(interp, argv[1], options, &option, "option",\r
+ JIM_ERRMSG) != JIM_OK)\r
+ return JIM_ERR;\r
+\r
+ if (option == OPT_REQUIRE) {\r
+ int exact = 0;\r
+ const char *ver;\r
+\r
+ if (Jim_CompareStringImmediate(interp, argv[2], "-exact")) {\r
+ exact = 1;\r
+ argv++;\r
+ argc--;\r
+ }\r
+ if (argc != 3 && argc != 4) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "?-exact? package ?version?");\r
+ return JIM_ERR;\r
+ }\r
+ ver = Jim_PackageRequire(interp, Jim_GetString(argv[2], NULL),\r
+ argc == 4 ? Jim_GetString(argv[3], NULL) : "",\r
+ JIM_ERRMSG);\r
+ if (ver == NULL)\r
+ return JIM_ERR;\r
+ Jim_SetResultString(interp, ver, -1);\r
+ } else if (option == OPT_PROVIDE) {\r
+ if (argc != 4) {\r
+ Jim_WrongNumArgs(interp, 2, argv, "package version");\r
+ return JIM_ERR;\r
+ }\r
+ return Jim_PackageProvide(interp, Jim_GetString(argv[2], NULL),\r
+ Jim_GetString(argv[3], NULL), JIM_ERRMSG);\r
+ }\r
+ return JIM_OK;\r
+}\r
+\r
+static struct {\r
+ const char *name;\r
+ Jim_CmdProc cmdProc;\r
+} Jim_CoreCommandsTable[] = {\r
+ {"set", Jim_SetCoreCommand},\r
+ {"unset", Jim_UnsetCoreCommand},\r
+ {"puts", Jim_PutsCoreCommand},\r
+ {"+", Jim_AddCoreCommand},\r
+ {"*", Jim_MulCoreCommand},\r
+ {"-", Jim_SubCoreCommand},\r
+ {"/", Jim_DivCoreCommand},\r
+ {"incr", Jim_IncrCoreCommand},\r
+ {"while", Jim_WhileCoreCommand},\r
+ {"for", Jim_ForCoreCommand},\r
+ {"foreach", Jim_ForeachCoreCommand},\r
+ {"lmap", Jim_LmapCoreCommand},\r
+ {"if", Jim_IfCoreCommand},\r
+ {"switch", Jim_SwitchCoreCommand},\r
+ {"list", Jim_ListCoreCommand},\r
+ {"lindex", Jim_LindexCoreCommand},\r
+ {"lset", Jim_LsetCoreCommand},\r
+ {"llength", Jim_LlengthCoreCommand},\r
+ {"lappend", Jim_LappendCoreCommand},\r
+ {"linsert", Jim_LinsertCoreCommand},\r
+ {"lsort", Jim_LsortCoreCommand},\r
+ {"append", Jim_AppendCoreCommand},\r
+ {"debug", Jim_DebugCoreCommand},\r
+ {"eval", Jim_EvalCoreCommand},\r
+ {"uplevel", Jim_UplevelCoreCommand},\r
+ {"expr", Jim_ExprCoreCommand},\r
+ {"break", Jim_BreakCoreCommand},\r
+ {"continue", Jim_ContinueCoreCommand},\r
+ {"proc", Jim_ProcCoreCommand},\r
+ {"concat", Jim_ConcatCoreCommand},\r
+ {"return", Jim_ReturnCoreCommand},\r
+ {"upvar", Jim_UpvarCoreCommand},\r
+ {"global", Jim_GlobalCoreCommand},\r
+ {"string", Jim_StringCoreCommand},\r
+ {"time", Jim_TimeCoreCommand},\r
+ {"exit", Jim_ExitCoreCommand},\r
+ {"catch", Jim_CatchCoreCommand},\r
+ {"ref", Jim_RefCoreCommand},\r
+ {"getref", Jim_GetrefCoreCommand},\r
+ {"setref", Jim_SetrefCoreCommand},\r
+ {"finalize", Jim_FinalizeCoreCommand},\r
+ {"collect", Jim_CollectCoreCommand},\r
+ {"rename", Jim_RenameCoreCommand},\r
+ {"dict", Jim_DictCoreCommand},\r
+ {"load", Jim_LoadCoreCommand},\r
+ {"subst", Jim_SubstCoreCommand},\r
+ {"info", Jim_InfoCoreCommand},\r
+ {"split", Jim_SplitCoreCommand},\r
+ {"join", Jim_JoinCoreCommand},\r
+ {"format", Jim_FormatCoreCommand},\r
+ {"scan", Jim_ScanCoreCommand},\r
+ {"error", Jim_ErrorCoreCommand},\r
+ {"lrange", Jim_LrangeCoreCommand},\r
+ {"env", Jim_EnvCoreCommand},\r
+ {"source", Jim_SourceCoreCommand},\r
+ {"lreverse", Jim_LreverseCoreCommand},\r
+ {"range", Jim_RangeCoreCommand},\r
+ {"rand", Jim_RandCoreCommand},\r
+ {"package", Jim_PackageCoreCommand},\r
+ {"tailcall", Jim_TailcallCoreCommand},\r
+ {NULL, NULL},\r
+};\r
+\r
+/* Some Jim core command is actually a procedure written in Jim itself. */\r
+static void Jim_RegisterCoreProcedures(Jim_Interp *interp)\r
+{\r
+ Jim_Eval(interp, (char*)\r
+"proc lambda {arglist args} {\n"\r
+" set name [ref {} function lambdaFinalizer]\n"\r
+" uplevel 1 [list proc $name $arglist {expand}$args]\n"\r
+" return $name\n"\r
+"}\n"\r
+"proc lambdaFinalizer {name val} {\n"\r
+" rename $name {}\n"\r
+"}\n"\r
+ );\r
+}\r
+\r
+void Jim_RegisterCoreCommands(Jim_Interp *interp)\r
+{\r
+ int i = 0;\r
+\r
+ while(Jim_CoreCommandsTable[i].name != NULL) {\r
+ Jim_CreateCommand(interp, \r
+ Jim_CoreCommandsTable[i].name,\r
+ Jim_CoreCommandsTable[i].cmdProc,\r
+ NULL, NULL);\r
+ i++;\r
+ }\r
+ Jim_RegisterCoreProcedures(interp);\r
+}\r
+\r
+/* -----------------------------------------------------------------------------\r
+ * Interactive prompt\r
+ * ---------------------------------------------------------------------------*/\r
+void Jim_PrintErrorMessage(Jim_Interp *interp)\r
+{\r
+ int len, i;\r
+\r
+ fprintf(interp->stderr_, "Runtime error, file \"%s\", line %d:" JIM_NL,\r
+ interp->errorFileName, interp->errorLine);\r
+ fprintf(interp->stderr_, " %s" JIM_NL,\r
+ Jim_GetString(interp->result, NULL));\r
+ Jim_ListLength(interp, interp->stackTrace, &len);\r
+ for (i = 0; i < len; i+= 3) {\r
+ Jim_Obj *objPtr;\r
+ const char *proc, *file, *line;\r
+\r
+ Jim_ListIndex(interp, interp->stackTrace, i, &objPtr, JIM_NONE);\r
+ proc = Jim_GetString(objPtr, NULL);\r
+ Jim_ListIndex(interp, interp->stackTrace, i+1, &objPtr,\r
+ JIM_NONE);\r
+ file = Jim_GetString(objPtr, NULL);\r
+ Jim_ListIndex(interp, interp->stackTrace, i+2, &objPtr,\r
+ JIM_NONE);\r
+ line = Jim_GetString(objPtr, NULL);\r
+ fprintf(interp->stderr_,\r
+ "In procedure '%s' called at file \"%s\", line %s" JIM_NL,\r
+ proc, file, line);\r
+ }\r
+}\r
+\r
+int Jim_InteractivePrompt(Jim_Interp *interp)\r
+{\r
+ int retcode = JIM_OK;\r
+ Jim_Obj *scriptObjPtr;\r
+\r
+ fprintf(interp->stdout_, "Welcome to Jim version %d.%d, "\r
+ "Copyright (c) 2005-8 Salvatore Sanfilippo" JIM_NL,\r
+ JIM_VERSION / 100, JIM_VERSION % 100);\r
+ Jim_SetVariableStrWithStr(interp, "jim_interactive", "1");\r
+ while (1) {\r
+ char buf[1024];\r
+ const char *result;\r
+ const char *retcodestr[] = {\r
+ "ok", "error", "return", "break", "continue", "eval", "exit"\r
+ };\r
+ int reslen;\r
+\r
+ if (retcode != 0) {\r
+ if (retcode >= 2 && retcode <= 6)\r
+ fprintf(interp->stdout_, "[%s] . ", retcodestr[retcode]);\r
+ else\r
+ fprintf(interp->stdout_, "[%d] . ", retcode);\r
+ } else\r
+ fprintf(interp->stdout_, ". ");\r
+ fflush(interp->stdout_);\r
+ scriptObjPtr = Jim_NewStringObj(interp, "", 0);\r
+ Jim_IncrRefCount(scriptObjPtr);\r
+ while(1) {\r
+ const char *str;\r
+ char state;\r
+ int len;\r
+\r
+ if (fgets(buf, 1024, interp->stdin_) == NULL) {\r
+ Jim_DecrRefCount(interp, scriptObjPtr);\r
+ goto out;\r
+ }\r
+ Jim_AppendString(interp, scriptObjPtr, buf, -1);\r
+ str = Jim_GetString(scriptObjPtr, &len);\r
+ if (Jim_ScriptIsComplete(str, len, &state))\r
+ break;\r
+ fprintf(interp->stdout_, "%c> ", state);\r
+ fflush(stdout);\r
+ }\r
+ retcode = Jim_EvalObj(interp, scriptObjPtr);\r
+ Jim_DecrRefCount(interp, scriptObjPtr);\r
+ result = Jim_GetString(Jim_GetResult(interp), &reslen);\r
+ if (retcode == JIM_ERR) {\r
+ Jim_PrintErrorMessage(interp);\r
+ } else if (retcode == JIM_EXIT) {\r
+ exit(Jim_GetExitCode(interp));\r
+ } else {\r
+ if (reslen) {\r
+ fwrite(result, 1, reslen, interp->stdout_);\r
+ fprintf(interp->stdout_, JIM_NL);\r
+ }\r
+ }\r
+ }\r
+out:\r
+ return 0;\r
+}\r