Add a general purpose hashtable pattern matcher
[jimtcl.git] / jim.c
blobbb52915bb2eef2263f53bb470f3638977b7bb424
2 /* Jim - A small embeddable Tcl interpreter
4 * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
5 * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
6 * Copyright 2005 patthoyts - Pat Thoyts <patthoyts@users.sf.net>
7 * Copyright 2008,2009 oharboe - Øyvind Harboe - oyvind.harboe@zylin.com
8 * Copyright 2008 Andrew Lunn <andrew@lunn.ch>
9 * Copyright 2008 Duane Ellis <openocd@duaneellis.com>
10 * Copyright 2008 Uwe Klein <uklein@klein-messgeraete.de>
11 * Copyright 2008 Steve Bennett <steveb@workware.net.au>
12 * Copyright 2009 Nico Coesel <ncoesel@dealogic.nl>
13 * Copyright 2009 Zachary T Welch zw@superlucidity.net
14 * Copyright 2009 David Brownell
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above
23 * copyright notice, this list of conditions and the following
24 * disclaimer in the documentation and/or other materials
25 * provided with the distribution.
27 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
28 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
30 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
31 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
32 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
33 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
36 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
38 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 * The views and conclusions contained in the software and documentation
41 * are those of the authors and should not be interpreted as representing
42 * official policies, either expressed or implied, of the Jim Tcl Project.
43 **/
44 #define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
46 #include <stdio.h>
47 #include <stdlib.h>
49 #include <string.h>
50 #include <stdarg.h>
51 #include <ctype.h>
52 #include <limits.h>
53 #include <assert.h>
54 #include <errno.h>
55 #include <time.h>
56 #include <setjmp.h>
58 #include "jim.h"
59 #include "jimautoconf.h"
60 #include "utf8.h"
62 #ifdef HAVE_SYS_TIME_H
63 #include <sys/time.h>
64 #endif
65 #ifdef HAVE_BACKTRACE
66 #include <execinfo.h>
67 #endif
68 #ifdef HAVE_CRT_EXTERNS_H
69 #include <crt_externs.h>
70 #endif
72 /* For INFINITY, even if math functions are not enabled */
73 #include <math.h>
75 /* We may decide to switch to using $[...] after all, so leave it as an option */
76 /*#define EXPRSUGAR_BRACKET*/
78 /* For the no-autoconf case */
79 #ifndef TCL_LIBRARY
80 #define TCL_LIBRARY "."
81 #endif
82 #ifndef TCL_PLATFORM_OS
83 #define TCL_PLATFORM_OS "unknown"
84 #endif
85 #ifndef TCL_PLATFORM_PLATFORM
86 #define TCL_PLATFORM_PLATFORM "unknown"
87 #endif
88 #ifndef TCL_PLATFORM_PATH_SEPARATOR
89 #define TCL_PLATFORM_PATH_SEPARATOR ":"
90 #endif
92 /*#define DEBUG_SHOW_SCRIPT*/
93 /*#define DEBUG_SHOW_SCRIPT_TOKENS*/
94 /*#define DEBUG_SHOW_SUBST*/
95 /*#define DEBUG_SHOW_EXPR*/
96 /*#define DEBUG_SHOW_EXPR_TOKENS*/
97 /*#define JIM_DEBUG_GC*/
98 #ifdef JIM_MAINTAINER
99 #define JIM_DEBUG_COMMAND
100 #define JIM_DEBUG_PANIC
101 #endif
103 const char *jim_tt_name(int type);
105 #ifdef JIM_DEBUG_PANIC
106 static void JimPanicDump(int panic_condition, const char *fmt, ...);
107 #define JimPanic(X) JimPanicDump X
108 #else
109 #define JimPanic(X)
110 #endif
112 /* -----------------------------------------------------------------------------
113 * Global variables
114 * ---------------------------------------------------------------------------*/
116 /* A shared empty string for the objects string representation.
117 * Jim_InvalidateStringRep knows about it and doesn't try to free it. */
118 static char JimEmptyStringRep[] = "";
120 /* -----------------------------------------------------------------------------
121 * Required prototypes of not exported functions
122 * ---------------------------------------------------------------------------*/
123 static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf);
124 static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags);
125 static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int listindex, Jim_Obj *newObjPtr,
126 int flags);
127 static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr);
128 static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
129 static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
130 const char *prefix, const char *const *tablePtr, const char *name);
131 static void JimDeleteLocalProcs(Jim_Interp *interp);
132 static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, Jim_Obj *fileNameObj, int linenr,
133 int argc, Jim_Obj *const *argv);
134 static int JimEvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv,
135 Jim_Obj *fileNameObj, int linenr);
136 static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr);
137 static int JimSign(jim_wide w);
138 static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr);
139 static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen);
140 static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len);
143 /* Fast access to the int (wide) value of an object which is known to be of int type */
144 #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
146 #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
148 static int utf8_tounicode_case(const char *s, int *uc, int upper)
150 int l = utf8_tounicode(s, uc);
151 if (upper) {
152 *uc = utf8_upper(*uc);
154 return l;
157 /* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
158 #define JIM_CHARSET_SCAN 2
159 #define JIM_CHARSET_GLOB 0
162 * pattern points to a string like "[^a-z\ub5]"
164 * The pattern may contain trailing chars, which are ignored.
166 * The pattern is matched against unicode char 'c'.
168 * If (flags & JIM_NOCASE), case is ignored when matching.
169 * If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
170 * of the charset, per scan, rather than glob/string match.
172 * If the unicode char 'c' matches that set, returns a pointer to the ']' character,
173 * or the null character if the ']' is missing.
175 * Returns NULL on no match.
177 static const char *JimCharsetMatch(const char *pattern, int c, int flags)
179 int not = 0;
180 int pchar;
181 int match = 0;
182 int nocase = 0;
184 if (flags & JIM_NOCASE) {
185 nocase++;
186 c = utf8_upper(c);
189 if (flags & JIM_CHARSET_SCAN) {
190 if (*pattern == '^') {
191 not++;
192 pattern++;
195 /* Special case. If the first char is ']', it is part of the set */
196 if (*pattern == ']') {
197 goto first;
201 while (*pattern && *pattern != ']') {
202 /* Exact match */
203 if (pattern[0] == '\\') {
204 first:
205 pattern += utf8_tounicode_case(pattern, &pchar, nocase);
207 else {
208 /* Is this a range? a-z */
209 int start;
210 int end;
212 pattern += utf8_tounicode_case(pattern, &start, nocase);
213 if (pattern[0] == '-' && pattern[1]) {
214 /* skip '-' */
215 pattern += utf8_tounicode(pattern, &pchar);
216 pattern += utf8_tounicode_case(pattern, &end, nocase);
218 /* Handle reversed range too */
219 if ((c >= start && c <= end) || (c >= end && c <= start)) {
220 match = 1;
222 continue;
224 pchar = start;
227 if (pchar == c) {
228 match = 1;
231 if (not) {
232 match = !match;
235 return match ? pattern : NULL;
238 /* Glob-style pattern matching. */
240 /* Note: string *must* be valid UTF-8 sequences
241 * slen is a char length, not byte counts.
243 static int JimGlobMatch(const char *pattern, const char *string, int nocase)
245 int c;
246 int pchar;
247 while (*pattern) {
248 switch (pattern[0]) {
249 case '*':
250 while (pattern[1] == '*') {
251 pattern++;
253 pattern++;
254 if (!pattern[0]) {
255 return 1; /* match */
257 while (*string) {
258 /* Recursive call - Does the remaining pattern match anywhere? */
259 if (JimGlobMatch(pattern, string, nocase))
260 return 1; /* match */
261 string += utf8_tounicode(string, &c);
263 return 0; /* no match */
265 case '?':
266 string += utf8_tounicode(string, &c);
267 break;
269 case '[': {
270 string += utf8_tounicode(string, &c);
271 pattern = JimCharsetMatch(pattern + 1, c, nocase ? JIM_NOCASE : 0);
272 if (!pattern) {
273 return 0;
275 if (!*pattern) {
276 /* Ran out of pattern (no ']') */
277 continue;
279 break;
281 case '\\':
282 if (pattern[1]) {
283 pattern++;
285 /* fall through */
286 default:
287 string += utf8_tounicode_case(string, &c, nocase);
288 utf8_tounicode_case(pattern, &pchar, nocase);
289 if (pchar != c) {
290 return 0;
292 break;
294 pattern += utf8_tounicode_case(pattern, &pchar, nocase);
295 if (!*string) {
296 while (*pattern == '*') {
297 pattern++;
299 break;
302 if (!*pattern && !*string) {
303 return 1;
305 return 0;
308 static int JimStringMatch(Jim_Interp *interp, Jim_Obj *patternObj, const char *string, int nocase)
310 return JimGlobMatch(Jim_String(patternObj), string, nocase);
314 * string comparison works on binary data.
316 * Note that the lengths are byte lengths, not char lengths.
318 static int JimStringCompare(const char *s1, int l1, const char *s2, int l2)
320 if (l1 < l2) {
321 return memcmp(s1, s2, l1) <= 0 ? -1 : 1;
323 else if (l2 < l1) {
324 return memcmp(s1, s2, l2) >= 0 ? 1 : -1;
326 else {
327 return JimSign(memcmp(s1, s2, l1));
332 * No-case version.
334 * If maxchars is -1, compares to end of string.
335 * Otherwise compares at most 'maxchars' characters.
337 static int JimStringCompareNoCase(const char *s1, const char *s2, int maxchars)
339 while (*s1 && *s2 && maxchars) {
340 int c1, c2;
341 s1 += utf8_tounicode_case(s1, &c1, 1);
342 s2 += utf8_tounicode_case(s2, &c2, 1);
343 if (c1 != c2) {
344 return JimSign(c1 - c2);
346 maxchars--;
348 if (!maxchars) {
349 return 0;
351 /* One string or both terminated */
352 if (*s1) {
353 return 1;
355 if (*s2) {
356 return -1;
358 return 0;
361 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
362 * The index of the first occurrence of s1 in s2 is returned.
363 * If s1 is not found inside s2, -1 is returned. */
364 static int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int idx)
366 int i;
367 int l1bytelen;
369 if (!l1 || !l2 || l1 > l2) {
370 return -1;
372 if (idx < 0)
373 idx = 0;
374 s2 += utf8_index(s2, idx);
376 l1bytelen = utf8_index(s1, l1);
378 for (i = idx; i <= l2 - l1; i++) {
379 int c;
380 if (memcmp(s2, s1, l1bytelen) == 0) {
381 return i;
383 s2 += utf8_tounicode(s2, &c);
385 return -1;
389 * Note: Lengths and return value are in bytes, not chars.
391 static int JimStringLast(const char *s1, int l1, const char *s2, int l2)
393 const char *p;
395 if (!l1 || !l2 || l1 > l2)
396 return -1;
398 /* Now search for the needle */
399 for (p = s2 + l2 - 1; p != s2 - 1; p--) {
400 if (*p == *s1 && memcmp(s1, p, l1) == 0) {
401 return p - s2;
404 return -1;
407 #ifdef JIM_UTF8
409 * Note: Lengths and return value are in chars.
411 static int JimStringLastUtf8(const char *s1, int l1, const char *s2, int l2)
413 int n = JimStringLast(s1, utf8_index(s1, l1), s2, utf8_index(s2, l2));
414 if (n > 0) {
415 n = utf8_strlen(s2, n);
417 return n;
419 #endif
421 int Jim_WideToString(char *buf, jim_wide wideValue)
423 const char *fmt = "%" JIM_WIDE_MODIFIER;
425 return sprintf(buf, fmt, wideValue);
429 * After an strtol()/strtod()-like conversion,
430 * check whether something was converted and that
431 * the only thing left is white space.
433 * Returns JIM_OK or JIM_ERR.
435 static int JimCheckConversion(const char *str, const char *endptr)
437 if (str[0] == '\0' || str == endptr) {
438 return JIM_ERR;
441 if (endptr[0] != '\0') {
442 while (*endptr) {
443 if (!isspace(UCHAR(*endptr))) {
444 return JIM_ERR;
446 endptr++;
449 return JIM_OK;
452 int Jim_StringToWide(const char *str, jim_wide * widePtr, int base)
454 char *endptr;
456 *widePtr = strtoull(str, &endptr, base);
458 return JimCheckConversion(str, endptr);
461 int Jim_DoubleToString(char *buf, double doubleValue)
463 int len;
464 char *buf0 = buf;
466 len = sprintf(buf, "%.12g", doubleValue);
468 /* Add a final ".0" if it's a number. But not
469 * for NaN or InF */
470 while (*buf) {
471 if (*buf == '.' || isalpha(UCHAR(*buf))) {
472 /* inf -> Inf, nan -> Nan */
473 if (*buf == 'i' || *buf == 'n') {
474 *buf = toupper(UCHAR(*buf));
476 if (*buf == 'I') {
477 /* Infinity -> Inf */
478 buf[3] = '\0';
479 len = buf - buf0 + 3;
481 return len;
483 buf++;
486 *buf++ = '.';
487 *buf++ = '0';
488 *buf = '\0';
490 return len + 2;
493 int Jim_StringToDouble(const char *str, double *doublePtr)
495 char *endptr;
497 /* Callers can check for underflow via ERANGE */
498 errno = 0;
500 *doublePtr = strtod(str, &endptr);
502 return JimCheckConversion(str, endptr);
505 static jim_wide JimPowWide(jim_wide b, jim_wide e)
507 jim_wide i, res = 1;
509 if ((b == 0 && e != 0) || (e < 0))
510 return 0;
511 for (i = 0; i < e; i++) {
512 res *= b;
514 return res;
517 /* -----------------------------------------------------------------------------
518 * Special functions
519 * ---------------------------------------------------------------------------*/
520 #ifdef JIM_DEBUG_PANIC
521 void JimPanicDump(int condition, const char *fmt, ...)
523 va_list ap;
525 if (!condition) {
526 return;
529 va_start(ap, fmt);
531 fprintf(stderr, JIM_NL "JIM INTERPRETER PANIC: ");
532 vfprintf(stderr, fmt, ap);
533 fprintf(stderr, JIM_NL JIM_NL);
534 va_end(ap);
536 #ifdef HAVE_BACKTRACE
538 void *array[40];
539 int size, i;
540 char **strings;
542 size = backtrace(array, 40);
543 strings = backtrace_symbols(array, size);
544 for (i = 0; i < size; i++)
545 fprintf(stderr, "[backtrace] %s" JIM_NL, strings[i]);
546 fprintf(stderr, "[backtrace] Include the above lines and the output" JIM_NL);
547 fprintf(stderr, "[backtrace] of 'nm <executable>' in the bug report." JIM_NL);
549 #endif
551 abort();
553 #endif
555 /* -----------------------------------------------------------------------------
556 * Memory allocation
557 * ---------------------------------------------------------------------------*/
559 void *Jim_Alloc(int size)
561 return malloc(size);
564 void Jim_Free(void *ptr)
566 free(ptr);
569 void *Jim_Realloc(void *ptr, int size)
571 return realloc(ptr, size);
574 char *Jim_StrDup(const char *s)
576 return strdup(s);
579 char *Jim_StrDupLen(const char *s, int l)
581 char *copy = Jim_Alloc(l + 1);
583 memcpy(copy, s, l + 1);
584 copy[l] = 0; /* Just to be sure, original could be substring */
585 return copy;
588 /* -----------------------------------------------------------------------------
589 * Time related functions
590 * ---------------------------------------------------------------------------*/
592 /* Returns microseconds of CPU used since start. */
593 static jim_wide JimClock(void)
595 struct timeval tv;
597 gettimeofday(&tv, NULL);
598 return (jim_wide) tv.tv_sec * 1000000 + tv.tv_usec;
601 /* -----------------------------------------------------------------------------
602 * Hash Tables
603 * ---------------------------------------------------------------------------*/
605 /* -------------------------- private prototypes ---------------------------- */
606 static void JimExpandHashTableIfNeeded(Jim_HashTable *ht);
607 static unsigned int JimHashTableNextPower(unsigned int size);
608 static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace);
610 /* -------------------------- hash functions -------------------------------- */
612 /* Thomas Wang's 32 bit Mix Function */
613 unsigned int Jim_IntHashFunction(unsigned int key)
615 key += ~(key << 15);
616 key ^= (key >> 10);
617 key += (key << 3);
618 key ^= (key >> 6);
619 key += ~(key << 11);
620 key ^= (key >> 16);
621 return key;
624 /* Generic hash function (we are using to multiply by 9 and add the byte
625 * as Tcl) */
626 unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
628 unsigned int h = 0;
630 while (len--)
631 h += (h << 3) + *buf++;
632 return h;
635 /* ----------------------------- API implementation ------------------------- */
637 /* reset a hashtable already initialized with ht_init().
638 * NOTE: This function should only called by ht_destroy(). */
639 static void JimResetHashTable(Jim_HashTable *ht)
641 ht->table = NULL;
642 ht->size = 0;
643 ht->sizemask = 0;
644 ht->used = 0;
645 ht->collisions = 0;
648 /* Initialize the hash table */
649 int Jim_InitHashTable(Jim_HashTable *ht, const Jim_HashTableType *type, void *privDataPtr)
651 JimResetHashTable(ht);
652 ht->type = type;
653 ht->privdata = privDataPtr;
654 return JIM_OK;
657 /* Resize the table to the minimal size that contains all the elements,
658 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
659 void Jim_ResizeHashTable(Jim_HashTable *ht)
661 int minimal = ht->used;
663 if (minimal < JIM_HT_INITIAL_SIZE)
664 minimal = JIM_HT_INITIAL_SIZE;
665 Jim_ExpandHashTable(ht, minimal);
668 /* Expand or create the hashtable */
669 void Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
671 Jim_HashTable n; /* the new hashtable */
672 unsigned int realsize = JimHashTableNextPower(size), i;
674 /* the size is invalid if it is smaller than the number of
675 * elements already inside the hashtable */
676 if (size <= ht->used)
677 return;
679 Jim_InitHashTable(&n, ht->type, ht->privdata);
680 n.size = realsize;
681 n.sizemask = realsize - 1;
682 n.table = Jim_Alloc(realsize * sizeof(Jim_HashEntry *));
684 /* Initialize all the pointers to NULL */
685 memset(n.table, 0, realsize * sizeof(Jim_HashEntry *));
687 /* Copy all the elements from the old to the new table:
688 * note that if the old hash table is empty ht->used is zero,
689 * so Jim_ExpandHashTable just creates an empty hash table. */
690 n.used = ht->used;
691 for (i = 0; ht->used > 0; i++) {
692 Jim_HashEntry *he, *nextHe;
694 if (ht->table[i] == NULL)
695 continue;
697 /* For each hash entry on this slot... */
698 he = ht->table[i];
699 while (he) {
700 unsigned int h;
702 nextHe = he->next;
703 /* Get the new element index */
704 h = Jim_HashKey(ht, he->key) & n.sizemask;
705 he->next = n.table[h];
706 n.table[h] = he;
707 ht->used--;
708 /* Pass to the next element */
709 he = nextHe;
712 assert(ht->used == 0);
713 Jim_Free(ht->table);
715 /* Remap the new hashtable in the old */
716 *ht = n;
719 /* Add an element to the target hash table */
720 int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
722 Jim_HashEntry *entry;
724 /* Get the index of the new element, or -1 if
725 * the element already exists. */
726 entry = JimInsertHashEntry(ht, key, 0);
727 if (entry == NULL)
728 return JIM_ERR;
730 /* Set the hash entry fields. */
731 Jim_SetHashKey(ht, entry, key);
732 Jim_SetHashVal(ht, entry, val);
733 return JIM_OK;
736 /* Add an element, discarding the old if the key already exists */
737 int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
739 int existed;
740 Jim_HashEntry *entry;
742 /* Get the index of the new element, or -1 if
743 * the element already exists. */
744 entry = JimInsertHashEntry(ht, key, 1);
745 if (entry->key) {
746 /* It already exists, so replace the value */
747 Jim_FreeEntryVal(ht, entry);
748 existed = 1;
750 else {
751 /* Doesn't exist, so set the key */
752 Jim_SetHashKey(ht, entry, key);
753 existed = 0;
755 Jim_SetHashVal(ht, entry, val);
757 return existed;
760 /* Search and remove an element */
761 int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
763 unsigned int h;
764 Jim_HashEntry *he, *prevHe;
766 if (ht->used == 0)
767 return JIM_ERR;
768 h = Jim_HashKey(ht, key) & ht->sizemask;
769 he = ht->table[h];
771 prevHe = NULL;
772 while (he) {
773 if (Jim_CompareHashKeys(ht, key, he->key)) {
774 /* Unlink the element from the list */
775 if (prevHe)
776 prevHe->next = he->next;
777 else
778 ht->table[h] = he->next;
779 Jim_FreeEntryKey(ht, he);
780 Jim_FreeEntryVal(ht, he);
781 Jim_Free(he);
782 ht->used--;
783 return JIM_OK;
785 prevHe = he;
786 he = he->next;
788 return JIM_ERR; /* not found */
791 /* Destroy an entire hash table */
792 int Jim_FreeHashTable(Jim_HashTable *ht)
794 unsigned int i;
796 /* Free all the elements */
797 for (i = 0; ht->used > 0; i++) {
798 Jim_HashEntry *he, *nextHe;
800 if ((he = ht->table[i]) == NULL)
801 continue;
802 while (he) {
803 nextHe = he->next;
804 Jim_FreeEntryKey(ht, he);
805 Jim_FreeEntryVal(ht, he);
806 Jim_Free(he);
807 ht->used--;
808 he = nextHe;
811 /* Free the table and the allocated cache structure */
812 Jim_Free(ht->table);
813 /* Re-initialize the table */
814 JimResetHashTable(ht);
815 return JIM_OK; /* never fails */
818 Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
820 Jim_HashEntry *he;
821 unsigned int h;
823 if (ht->used == 0)
824 return NULL;
825 h = Jim_HashKey(ht, key) & ht->sizemask;
826 he = ht->table[h];
827 while (he) {
828 if (Jim_CompareHashKeys(ht, key, he->key))
829 return he;
830 he = he->next;
832 return NULL;
835 Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
837 Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
839 iter->ht = ht;
840 iter->index = -1;
841 iter->entry = NULL;
842 iter->nextEntry = NULL;
843 return iter;
846 Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
848 while (1) {
849 if (iter->entry == NULL) {
850 iter->index++;
851 if (iter->index >= (signed)iter->ht->size)
852 break;
853 iter->entry = iter->ht->table[iter->index];
855 else {
856 iter->entry = iter->nextEntry;
858 if (iter->entry) {
859 /* We need to save the 'next' here, the iterator user
860 * may delete the entry we are returning. */
861 iter->nextEntry = iter->entry->next;
862 return iter->entry;
865 return NULL;
868 /* ------------------------- private functions ------------------------------ */
870 /* Expand the hash table if needed */
871 static void JimExpandHashTableIfNeeded(Jim_HashTable *ht)
873 /* If the hash table is empty expand it to the intial size,
874 * if the table is "full" dobule its size. */
875 if (ht->size == 0)
876 Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
877 if (ht->size == ht->used)
878 Jim_ExpandHashTable(ht, ht->size * 2);
881 /* Our hash table capability is a power of two */
882 static unsigned int JimHashTableNextPower(unsigned int size)
884 unsigned int i = JIM_HT_INITIAL_SIZE;
886 if (size >= 2147483648U)
887 return 2147483648U;
888 while (1) {
889 if (i >= size)
890 return i;
891 i *= 2;
895 /* Returns the index of a free slot that can be populated with
896 * an hash entry for the given 'key'.
897 * If the key already exists, -1 is returned. */
898 static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace)
900 unsigned int h;
901 Jim_HashEntry *he;
903 /* Expand the hashtable if needed */
904 JimExpandHashTableIfNeeded(ht);
906 /* Compute the key hash value */
907 h = Jim_HashKey(ht, key) & ht->sizemask;
908 /* Search if this slot does not already contain the given key */
909 he = ht->table[h];
910 while (he) {
911 if (Jim_CompareHashKeys(ht, key, he->key))
912 return replace ? he : NULL;
913 he = he->next;
916 /* Allocates the memory and stores key */
917 he = Jim_Alloc(sizeof(*he));
918 he->next = ht->table[h];
919 ht->table[h] = he;
920 ht->used++;
921 he->key = NULL;
923 return he;
926 /* ----------------------- StringCopy Hash Table Type ------------------------*/
928 static unsigned int JimStringCopyHTHashFunction(const void *key)
930 return Jim_GenHashFunction(key, strlen(key));
933 static void *JimStringCopyHTDup(void *privdata, const void *key)
935 return strdup(key);
938 static int JimStringCopyHTKeyCompare(void *privdata, const void *key1, const void *key2)
940 return strcmp(key1, key2) == 0;
943 static void JimStringCopyHTKeyDestructor(void *privdata, void *key)
945 Jim_Free(key);
948 static const Jim_HashTableType JimPackageHashTableType = {
949 JimStringCopyHTHashFunction, /* hash function */
950 JimStringCopyHTDup, /* key dup */
951 NULL, /* val dup */
952 JimStringCopyHTKeyCompare, /* key compare */
953 JimStringCopyHTKeyDestructor, /* key destructor */
954 NULL /* val destructor */
957 typedef struct AssocDataValue
959 Jim_InterpDeleteProc *delProc;
960 void *data;
961 } AssocDataValue;
963 static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
965 AssocDataValue *assocPtr = (AssocDataValue *) data;
967 if (assocPtr->delProc != NULL)
968 assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
969 Jim_Free(data);
972 static const Jim_HashTableType JimAssocDataHashTableType = {
973 JimStringCopyHTHashFunction, /* hash function */
974 JimStringCopyHTDup, /* key dup */
975 NULL, /* val dup */
976 JimStringCopyHTKeyCompare, /* key compare */
977 JimStringCopyHTKeyDestructor, /* key destructor */
978 JimAssocDataHashTableValueDestructor /* val destructor */
981 /* -----------------------------------------------------------------------------
982 * Stack - This is a simple generic stack implementation. It is used for
983 * example in the 'expr' expression compiler.
984 * ---------------------------------------------------------------------------*/
985 void Jim_InitStack(Jim_Stack *stack)
987 stack->len = 0;
988 stack->maxlen = 0;
989 stack->vector = NULL;
992 void Jim_FreeStack(Jim_Stack *stack)
994 Jim_Free(stack->vector);
997 int Jim_StackLen(Jim_Stack *stack)
999 return stack->len;
1002 void Jim_StackPush(Jim_Stack *stack, void *element)
1004 int neededLen = stack->len + 1;
1006 if (neededLen > stack->maxlen) {
1007 stack->maxlen = neededLen < 20 ? 20 : neededLen * 2;
1008 stack->vector = Jim_Realloc(stack->vector, sizeof(void *) * stack->maxlen);
1010 stack->vector[stack->len] = element;
1011 stack->len++;
1014 void *Jim_StackPop(Jim_Stack *stack)
1016 if (stack->len == 0)
1017 return NULL;
1018 stack->len--;
1019 return stack->vector[stack->len];
1022 void *Jim_StackPeek(Jim_Stack *stack)
1024 if (stack->len == 0)
1025 return NULL;
1026 return stack->vector[stack->len - 1];
1029 void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc) (void *ptr))
1031 int i;
1033 for (i = 0; i < stack->len; i++)
1034 freeFunc(stack->vector[i]);
1037 /* -----------------------------------------------------------------------------
1038 * Parser
1039 * ---------------------------------------------------------------------------*/
1041 /* Token types */
1042 #define JIM_TT_NONE 0 /* No token returned */
1043 #define JIM_TT_STR 1 /* simple string */
1044 #define JIM_TT_ESC 2 /* string that needs escape chars conversion */
1045 #define JIM_TT_VAR 3 /* var substitution */
1046 #define JIM_TT_DICTSUGAR 4 /* Syntax sugar for [dict get], $foo(bar) */
1047 #define JIM_TT_CMD 5 /* command substitution */
1048 /* Note: Keep these three together for TOKEN_IS_SEP() */
1049 #define JIM_TT_SEP 6 /* word separator. arg is # of tokens. -ve if {*} */
1050 #define JIM_TT_EOL 7 /* line separator */
1051 #define JIM_TT_EOF 8 /* end of script */
1053 #define JIM_TT_LINE 9 /* special 'start-of-line' token. arg is # of arguments to the command. -ve if {*} */
1054 #define JIM_TT_WORD 10 /* special 'start-of-word' token. arg is # of tokens to combine. -ve if {*} */
1056 /* Additional token types needed for expressions */
1057 #define JIM_TT_SUBEXPR_START 11
1058 #define JIM_TT_SUBEXPR_END 12
1059 #define JIM_TT_SUBEXPR_COMMA 13
1060 #define JIM_TT_EXPR_INT 14
1061 #define JIM_TT_EXPR_DOUBLE 15
1063 #define JIM_TT_EXPRSUGAR 16 /* $(expression) */
1065 /* Operator token types start here */
1066 #define JIM_TT_EXPR_OP 20
1068 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1070 /* Parser states */
1071 #define JIM_PS_DEF 0 /* Default state */
1072 #define JIM_PS_QUOTE 1 /* Inside "" */
1073 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1075 /* Parser context structure. The same context is used both to parse
1076 * Tcl scripts and lists. */
1077 struct JimParserCtx
1079 const char *p; /* Pointer to the point of the program we are parsing */
1080 int len; /* Remaining length */
1081 int linenr; /* Current line number */
1082 const char *tstart;
1083 const char *tend; /* Returned token is at tstart-tend in 'prg'. */
1084 int tline; /* Line number of the returned token */
1085 int tt; /* Token type */
1086 int eof; /* Non zero if EOF condition is true. */
1087 int state; /* Parser state */
1088 int comment; /* Non zero if the next chars may be a comment. */
1089 char missing; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1090 int missingline; /* Line number starting the missing token */
1094 * Results of missing quotes, braces, etc. from parsing.
1096 struct JimParseResult {
1097 char missing; /* From JimParserCtx.missing */
1098 int line; /* From JimParserCtx.missingline */
1101 static int JimParseScript(struct JimParserCtx *pc);
1102 static int JimParseSep(struct JimParserCtx *pc);
1103 static int JimParseEol(struct JimParserCtx *pc);
1104 static int JimParseCmd(struct JimParserCtx *pc);
1105 static int JimParseQuote(struct JimParserCtx *pc);
1106 static int JimParseVar(struct JimParserCtx *pc);
1107 static int JimParseBrace(struct JimParserCtx *pc);
1108 static int JimParseStr(struct JimParserCtx *pc);
1109 static int JimParseComment(struct JimParserCtx *pc);
1110 static void JimParseSubCmd(struct JimParserCtx *pc);
1111 static int JimParseSubQuote(struct JimParserCtx *pc);
1112 static void JimParseSubCmd(struct JimParserCtx *pc);
1113 static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc);
1115 /* Initialize a parser context.
1116 * 'prg' is a pointer to the program text, linenr is the line
1117 * number of the first line contained in the program. */
1118 static void JimParserInit(struct JimParserCtx *pc, const char *prg, int len, int linenr)
1120 pc->p = prg;
1121 pc->len = len;
1122 pc->tstart = NULL;
1123 pc->tend = NULL;
1124 pc->tline = 0;
1125 pc->tt = JIM_TT_NONE;
1126 pc->eof = 0;
1127 pc->state = JIM_PS_DEF;
1128 pc->linenr = linenr;
1129 pc->comment = 1;
1130 pc->missing = ' ';
1131 pc->missingline = linenr;
1134 static int JimParseScript(struct JimParserCtx *pc)
1136 while (1) { /* the while is used to reiterate with continue if needed */
1137 if (!pc->len) {
1138 pc->tstart = pc->p;
1139 pc->tend = pc->p - 1;
1140 pc->tline = pc->linenr;
1141 pc->tt = JIM_TT_EOL;
1142 pc->eof = 1;
1143 return JIM_OK;
1145 switch (*(pc->p)) {
1146 case '\\':
1147 if (*(pc->p + 1) == '\n' && pc->state == JIM_PS_DEF) {
1148 return JimParseSep(pc);
1150 pc->comment = 0;
1151 return JimParseStr(pc);
1152 case ' ':
1153 case '\t':
1154 case '\r':
1155 case '\f':
1156 if (pc->state == JIM_PS_DEF)
1157 return JimParseSep(pc);
1158 pc->comment = 0;
1159 return JimParseStr(pc);
1160 case '\n':
1161 case ';':
1162 pc->comment = 1;
1163 if (pc->state == JIM_PS_DEF)
1164 return JimParseEol(pc);
1165 return JimParseStr(pc);
1166 case '[':
1167 pc->comment = 0;
1168 return JimParseCmd(pc);
1169 case '$':
1170 pc->comment = 0;
1171 if (JimParseVar(pc) == JIM_ERR) {
1172 /* An orphan $. Create as a separate token */
1173 pc->tstart = pc->tend = pc->p++;
1174 pc->len--;
1175 pc->tt = JIM_TT_ESC;
1177 return JIM_OK;
1178 case '#':
1179 if (pc->comment) {
1180 JimParseComment(pc);
1181 continue;
1183 return JimParseStr(pc);
1184 default:
1185 pc->comment = 0;
1186 return JimParseStr(pc);
1188 return JIM_OK;
1192 static int JimParseSep(struct JimParserCtx *pc)
1194 pc->tstart = pc->p;
1195 pc->tline = pc->linenr;
1196 while (isspace(UCHAR(*pc->p)) || (*pc->p == '\\' && *(pc->p + 1) == '\n')) {
1197 if (*pc->p == '\n') {
1198 break;
1200 if (*pc->p == '\\') {
1201 pc->p++;
1202 pc->len--;
1203 pc->linenr++;
1205 pc->p++;
1206 pc->len--;
1208 pc->tend = pc->p - 1;
1209 pc->tt = JIM_TT_SEP;
1210 return JIM_OK;
1213 static int JimParseEol(struct JimParserCtx *pc)
1215 pc->tstart = pc->p;
1216 pc->tline = pc->linenr;
1217 while (isspace(UCHAR(*pc->p)) || *pc->p == ';') {
1218 if (*pc->p == '\n')
1219 pc->linenr++;
1220 pc->p++;
1221 pc->len--;
1223 pc->tend = pc->p - 1;
1224 pc->tt = JIM_TT_EOL;
1225 return JIM_OK;
1229 ** Here are the rules for parsing:
1230 ** {braced expression}
1231 ** - Count open and closing braces
1232 ** - Backslash escapes meaning of braces
1234 ** "quoted expression"
1235 ** - First double quote at start of word terminates the expression
1236 ** - Backslash escapes quote and bracket
1237 ** - [commands brackets] are counted/nested
1238 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1240 ** [command expression]
1241 ** - Count open and closing brackets
1242 ** - Backslash escapes quote, bracket and brace
1243 ** - [commands brackets] are counted/nested
1244 ** - "quoted expressions" are parsed according to quoting rules
1245 ** - {braced expressions} are parsed according to brace rules
1247 ** For everything, backslash escapes the next char, newline increments current line
1251 * Parses a braced expression starting at pc->p.
1253 * Positions the parser at the end of the braced expression,
1254 * sets pc->tend and possibly pc->missing.
1256 static void JimParseSubBrace(struct JimParserCtx *pc)
1258 int level = 1;
1260 /* Skip the brace */
1261 pc->p++;
1262 pc->len--;
1263 while (pc->len) {
1264 switch (*pc->p) {
1265 case '\\':
1266 if (pc->len > 1) {
1267 if (*++pc->p == '\n') {
1268 pc->linenr++;
1270 pc->len--;
1272 break;
1274 case '{':
1275 level++;
1276 break;
1278 case '}':
1279 if (--level == 0) {
1280 pc->tend = pc->p - 1;
1281 pc->p++;
1282 pc->len--;
1283 return;
1285 break;
1287 case '\n':
1288 pc->linenr++;
1289 break;
1291 pc->p++;
1292 pc->len--;
1294 pc->missing = '{';
1295 pc->missingline = pc->tline;
1296 pc->tend = pc->p - 1;
1300 * Parses a quoted expression starting at pc->p.
1302 * Positions the parser at the end of the quoted expression,
1303 * sets pc->tend and possibly pc->missing.
1305 * Returns the type of the token of the string,
1306 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1307 * or JIM_TT_STR.
1309 static int JimParseSubQuote(struct JimParserCtx *pc)
1311 int tt = JIM_TT_STR;
1312 int line = pc->tline;
1314 /* Skip the quote */
1315 pc->p++;
1316 pc->len--;
1317 while (pc->len) {
1318 switch (*pc->p) {
1319 case '\\':
1320 if (pc->len > 1) {
1321 if (*++pc->p == '\n') {
1322 pc->linenr++;
1324 pc->len--;
1325 tt = JIM_TT_ESC;
1327 break;
1329 case '"':
1330 pc->tend = pc->p - 1;
1331 pc->p++;
1332 pc->len--;
1333 return tt;
1335 case '[':
1336 JimParseSubCmd(pc);
1337 tt = JIM_TT_ESC;
1338 continue;
1340 case '\n':
1341 pc->linenr++;
1342 break;
1344 case '$':
1345 tt = JIM_TT_ESC;
1346 break;
1348 pc->p++;
1349 pc->len--;
1351 pc->missing = '"';
1352 pc->missingline = line;
1353 pc->tend = pc->p - 1;
1354 return tt;
1358 * Parses a [command] expression starting at pc->p.
1360 * Positions the parser at the end of the command expression,
1361 * sets pc->tend and possibly pc->missing.
1363 static void JimParseSubCmd(struct JimParserCtx *pc)
1365 int level = 1;
1366 int startofword = 1;
1367 int line = pc->tline;
1369 /* Skip the bracket */
1370 pc->p++;
1371 pc->len--;
1372 while (pc->len) {
1373 switch (*pc->p) {
1374 case '\\':
1375 if (pc->len > 1) {
1376 if (*++pc->p == '\n') {
1377 pc->linenr++;
1379 pc->len--;
1381 break;
1383 case '[':
1384 level++;
1385 break;
1387 case ']':
1388 if (--level == 0) {
1389 pc->tend = pc->p - 1;
1390 pc->p++;
1391 pc->len--;
1392 return;
1394 break;
1396 case '"':
1397 if (startofword) {
1398 JimParseSubQuote(pc);
1399 continue;
1401 break;
1403 case '{':
1404 JimParseSubBrace(pc);
1405 startofword = 0;
1406 continue;
1408 case '\n':
1409 pc->linenr++;
1410 break;
1412 startofword = isspace(UCHAR(*pc->p));
1413 pc->p++;
1414 pc->len--;
1416 pc->missing = '[';
1417 pc->missingline = line;
1418 pc->tend = pc->p - 1;
1421 static int JimParseBrace(struct JimParserCtx *pc)
1423 pc->tstart = pc->p + 1;
1424 pc->tline = pc->linenr;
1425 pc->tt = JIM_TT_STR;
1426 JimParseSubBrace(pc);
1427 return JIM_OK;
1430 static int JimParseCmd(struct JimParserCtx *pc)
1432 pc->tstart = pc->p + 1;
1433 pc->tline = pc->linenr;
1434 pc->tt = JIM_TT_CMD;
1435 JimParseSubCmd(pc);
1436 return JIM_OK;
1439 static int JimParseQuote(struct JimParserCtx *pc)
1441 pc->tstart = pc->p + 1;
1442 pc->tline = pc->linenr;
1443 pc->tt = JimParseSubQuote(pc);
1444 return JIM_OK;
1447 static int JimParseVar(struct JimParserCtx *pc)
1449 /* skip the $ */
1450 pc->p++;
1451 pc->len--;
1453 #ifdef EXPRSUGAR_BRACKET
1454 if (*pc->p == '[') {
1455 /* Parse $[...] expr shorthand syntax */
1456 JimParseCmd(pc);
1457 pc->tt = JIM_TT_EXPRSUGAR;
1458 return JIM_OK;
1460 #endif
1462 pc->tstart = pc->p;
1463 pc->tt = JIM_TT_VAR;
1464 pc->tline = pc->linenr;
1466 if (*pc->p == '{') {
1467 pc->tstart = ++pc->p;
1468 pc->len--;
1470 while (pc->len && *pc->p != '}') {
1471 if (*pc->p == '\n') {
1472 pc->linenr++;
1474 pc->p++;
1475 pc->len--;
1477 pc->tend = pc->p - 1;
1478 if (pc->len) {
1479 pc->p++;
1480 pc->len--;
1483 else {
1484 while (1) {
1485 /* Skip double colon, but not single colon! */
1486 if (pc->p[0] == ':' && pc->p[1] == ':') {
1487 pc->p += 2;
1488 pc->len -= 2;
1489 continue;
1491 if (isalnum(UCHAR(*pc->p)) || *pc->p == '_') {
1492 pc->p++;
1493 pc->len--;
1494 continue;
1496 break;
1498 /* Parse [dict get] syntax sugar. */
1499 if (*pc->p == '(') {
1500 int count = 1;
1501 const char *paren = NULL;
1503 pc->tt = JIM_TT_DICTSUGAR;
1505 while (count && pc->len) {
1506 pc->p++;
1507 pc->len--;
1508 if (*pc->p == '\\' && pc->len >= 1) {
1509 pc->p++;
1510 pc->len--;
1512 else if (*pc->p == '(') {
1513 count++;
1515 else if (*pc->p == ')') {
1516 paren = pc->p;
1517 count--;
1520 if (count == 0) {
1521 pc->p++;
1522 pc->len--;
1524 else if (paren) {
1525 /* Did not find a matching paren. Back up */
1526 paren++;
1527 pc->len += (pc->p - paren);
1528 pc->p = paren;
1530 #ifndef EXPRSUGAR_BRACKET
1531 if (*pc->tstart == '(') {
1532 pc->tt = JIM_TT_EXPRSUGAR;
1534 #endif
1536 pc->tend = pc->p - 1;
1538 /* Check if we parsed just the '$' character.
1539 * That's not a variable so an error is returned
1540 * to tell the state machine to consider this '$' just
1541 * a string. */
1542 if (pc->tstart == pc->p) {
1543 pc->p--;
1544 pc->len++;
1545 return JIM_ERR;
1547 return JIM_OK;
1550 static int JimParseStr(struct JimParserCtx *pc)
1552 if (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
1553 pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR) {
1554 /* Starting a new word */
1555 if (*pc->p == '{') {
1556 return JimParseBrace(pc);
1558 if (*pc->p == '"') {
1559 pc->state = JIM_PS_QUOTE;
1560 pc->p++;
1561 pc->len--;
1562 /* In case the end quote is missing */
1563 pc->missingline = pc->tline;
1566 pc->tstart = pc->p;
1567 pc->tline = pc->linenr;
1568 while (1) {
1569 if (pc->len == 0) {
1570 if (pc->state == JIM_PS_QUOTE) {
1571 pc->missing = '"';
1573 pc->tend = pc->p - 1;
1574 pc->tt = JIM_TT_ESC;
1575 return JIM_OK;
1577 switch (*pc->p) {
1578 case '\\':
1579 if (pc->state == JIM_PS_DEF && *(pc->p + 1) == '\n') {
1580 pc->tend = pc->p - 1;
1581 pc->tt = JIM_TT_ESC;
1582 return JIM_OK;
1584 if (pc->len >= 2) {
1585 if (*(pc->p + 1) == '\n') {
1586 pc->linenr++;
1588 pc->p++;
1589 pc->len--;
1591 break;
1592 case '(':
1593 /* If the following token is not '$' just keep going */
1594 if (pc->len > 1 && pc->p[1] != '$') {
1595 break;
1597 case ')':
1598 /* Only need a separate ')' token if the previous was a var */
1599 if (*pc->p == '(' || pc->tt == JIM_TT_VAR) {
1600 if (pc->p == pc->tstart) {
1601 /* At the start of the token, so just return this char */
1602 pc->p++;
1603 pc->len--;
1605 pc->tend = pc->p - 1;
1606 pc->tt = JIM_TT_ESC;
1607 return JIM_OK;
1609 break;
1611 case '$':
1612 case '[':
1613 pc->tend = pc->p - 1;
1614 pc->tt = JIM_TT_ESC;
1615 return JIM_OK;
1616 case ' ':
1617 case '\t':
1618 case '\n':
1619 case '\r':
1620 case '\f':
1621 case ';':
1622 if (pc->state == JIM_PS_DEF) {
1623 pc->tend = pc->p - 1;
1624 pc->tt = JIM_TT_ESC;
1625 return JIM_OK;
1627 else if (*pc->p == '\n') {
1628 pc->linenr++;
1630 break;
1631 case '"':
1632 if (pc->state == JIM_PS_QUOTE) {
1633 pc->tend = pc->p - 1;
1634 pc->tt = JIM_TT_ESC;
1635 pc->p++;
1636 pc->len--;
1637 pc->state = JIM_PS_DEF;
1638 return JIM_OK;
1640 break;
1642 pc->p++;
1643 pc->len--;
1645 return JIM_OK; /* unreached */
1648 static int JimParseComment(struct JimParserCtx *pc)
1650 while (*pc->p) {
1651 if (*pc->p == '\n') {
1652 pc->linenr++;
1653 if (*(pc->p - 1) != '\\') {
1654 pc->p++;
1655 pc->len--;
1656 return JIM_OK;
1659 pc->p++;
1660 pc->len--;
1662 return JIM_OK;
1665 /* xdigitval and odigitval are helper functions for JimEscape() */
1666 static int xdigitval(int c)
1668 if (c >= '0' && c <= '9')
1669 return c - '0';
1670 if (c >= 'a' && c <= 'f')
1671 return c - 'a' + 10;
1672 if (c >= 'A' && c <= 'F')
1673 return c - 'A' + 10;
1674 return -1;
1677 static int odigitval(int c)
1679 if (c >= '0' && c <= '7')
1680 return c - '0';
1681 return -1;
1684 /* Perform Tcl escape substitution of 's', storing the result
1685 * string into 'dest'. The escaped string is guaranteed to
1686 * be the same length or shorted than the source string.
1687 * Slen is the length of the string at 's', if it's -1 the string
1688 * length will be calculated by the function.
1690 * The function returns the length of the resulting string. */
1691 static int JimEscape(char *dest, const char *s, int slen)
1693 char *p = dest;
1694 int i, len;
1696 if (slen == -1)
1697 slen = strlen(s);
1699 for (i = 0; i < slen; i++) {
1700 switch (s[i]) {
1701 case '\\':
1702 switch (s[i + 1]) {
1703 case 'a':
1704 *p++ = 0x7;
1705 i++;
1706 break;
1707 case 'b':
1708 *p++ = 0x8;
1709 i++;
1710 break;
1711 case 'f':
1712 *p++ = 0xc;
1713 i++;
1714 break;
1715 case 'n':
1716 *p++ = 0xa;
1717 i++;
1718 break;
1719 case 'r':
1720 *p++ = 0xd;
1721 i++;
1722 break;
1723 case 't':
1724 *p++ = 0x9;
1725 i++;
1726 break;
1727 case 'u':
1728 case 'x':
1729 /* A unicode or hex sequence.
1730 * \u Expect 1-4 hex chars and convert to utf-8.
1731 * \x Expect 1-2 hex chars and convert to hex.
1732 * An invalid sequence means simply the escaped char.
1735 int val = 0;
1736 int k;
1738 i++;
1740 for (k = 0; k < (s[i] == 'u' ? 4 : 2); k++) {
1741 int c = xdigitval(s[i + k + 1]);
1742 if (c == -1) {
1743 break;
1745 val = (val << 4) | c;
1747 if (k) {
1748 /* Got a valid sequence, so convert */
1749 if (s[i] == 'u') {
1750 p += utf8_fromunicode(p, val);
1752 else {
1753 *p++ = val;
1755 i += k;
1756 break;
1758 /* Not a valid codepoint, just an escaped char */
1759 *p++ = s[i];
1761 break;
1762 case 'v':
1763 *p++ = 0xb;
1764 i++;
1765 break;
1766 case '\0':
1767 *p++ = '\\';
1768 i++;
1769 break;
1770 case '\n':
1771 /* Replace all spaces and tabs after backslash newline with a single space*/
1772 *p++ = ' ';
1773 do {
1774 i++;
1775 } while (s[i + 1] == ' ' || s[i + 1] == '\t');
1776 break;
1777 case '0':
1778 case '1':
1779 case '2':
1780 case '3':
1781 case '4':
1782 case '5':
1783 case '6':
1784 case '7':
1785 /* octal escape */
1787 int val = 0;
1788 int c = odigitval(s[i + 1]);
1790 val = c;
1791 c = odigitval(s[i + 2]);
1792 if (c == -1) {
1793 *p++ = val;
1794 i++;
1795 break;
1797 val = (val * 8) + c;
1798 c = odigitval(s[i + 3]);
1799 if (c == -1) {
1800 *p++ = val;
1801 i += 2;
1802 break;
1804 val = (val * 8) + c;
1805 *p++ = val;
1806 i += 3;
1808 break;
1809 default:
1810 *p++ = s[i + 1];
1811 i++;
1812 break;
1814 break;
1815 default:
1816 *p++ = s[i];
1817 break;
1820 len = p - dest;
1821 *p = '\0';
1822 return len;
1825 /* Returns a dynamically allocated copy of the current token in the
1826 * parser context. The function performs conversion of escapes if
1827 * the token is of type JIM_TT_ESC.
1829 * Note that after the conversion, tokens that are grouped with
1830 * braces in the source code, are always recognizable from the
1831 * identical string obtained in a different way from the type.
1833 * For example the string:
1835 * {*}$a
1837 * will return as first token "*", of type JIM_TT_STR
1839 * While the string:
1841 * *$a
1843 * will return as first token "*", of type JIM_TT_ESC
1845 static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc)
1847 const char *start, *end;
1848 char *token;
1849 int len;
1851 start = pc->tstart;
1852 end = pc->tend;
1853 if (start > end) {
1854 len = 0;
1855 token = Jim_Alloc(1);
1856 token[0] = '\0';
1858 else {
1859 len = (end - start) + 1;
1860 token = Jim_Alloc(len + 1);
1861 if (pc->tt != JIM_TT_ESC) {
1862 /* No escape conversion needed? Just copy it. */
1863 memcpy(token, start, len);
1864 token[len] = '\0';
1866 else {
1867 /* Else convert the escape chars. */
1868 len = JimEscape(token, start, len);
1872 return Jim_NewStringObjNoAlloc(interp, token, len);
1875 /* Parses the given string to determine if it represents a complete script.
1877 * This is useful for interactive shells implementation, for [info complete].
1879 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1880 * '{' on scripts incomplete missing one or more '}' to be balanced.
1881 * '[' on scripts incomplete missing one or more ']' to be balanced.
1882 * '"' on scripts incomplete missing a '"' char.
1884 * If the script is complete, 1 is returned, otherwise 0.
1886 int Jim_ScriptIsComplete(const char *s, int len, char *stateCharPtr)
1888 struct JimParserCtx parser;
1890 JimParserInit(&parser, s, len, 1);
1891 while (!parser.eof) {
1892 JimParseScript(&parser);
1894 if (stateCharPtr) {
1895 *stateCharPtr = parser.missing;
1897 return parser.missing == ' ';
1900 /* -----------------------------------------------------------------------------
1901 * Tcl Lists parsing
1902 * ---------------------------------------------------------------------------*/
1903 static int JimParseListSep(struct JimParserCtx *pc);
1904 static int JimParseListStr(struct JimParserCtx *pc);
1905 static int JimParseListQuote(struct JimParserCtx *pc);
1907 static int JimParseList(struct JimParserCtx *pc)
1909 if (isspace(UCHAR(*pc->p))) {
1910 return JimParseListSep(pc);
1912 switch (*pc->p) {
1913 case '"':
1914 return JimParseListQuote(pc);
1916 case '{':
1917 return JimParseBrace(pc);
1919 default:
1920 if (pc->len) {
1921 return JimParseListStr(pc);
1923 break;
1926 pc->tstart = pc->tend = pc->p;
1927 pc->tline = pc->linenr;
1928 pc->tt = JIM_TT_EOL;
1929 pc->eof = 1;
1930 return JIM_OK;
1933 static int JimParseListSep(struct JimParserCtx *pc)
1935 pc->tstart = pc->p;
1936 pc->tline = pc->linenr;
1937 while (isspace(UCHAR(*pc->p))) {
1938 if (*pc->p == '\n') {
1939 pc->linenr++;
1941 pc->p++;
1942 pc->len--;
1944 pc->tend = pc->p - 1;
1945 pc->tt = JIM_TT_SEP;
1946 return JIM_OK;
1949 static int JimParseListQuote(struct JimParserCtx *pc)
1951 pc->p++;
1952 pc->len--;
1954 pc->tstart = pc->p;
1955 pc->tline = pc->linenr;
1956 pc->tt = JIM_TT_STR;
1958 while (pc->len) {
1959 switch (*pc->p) {
1960 case '\\':
1961 pc->tt = JIM_TT_ESC;
1962 if (--pc->len == 0) {
1963 /* Trailing backslash */
1964 pc->tend = pc->p;
1965 return JIM_OK;
1967 pc->p++;
1968 break;
1969 case '\n':
1970 pc->linenr++;
1971 break;
1972 case '"':
1973 pc->tend = pc->p - 1;
1974 pc->p++;
1975 pc->len--;
1976 return JIM_OK;
1978 pc->p++;
1979 pc->len--;
1982 pc->tend = pc->p - 1;
1983 return JIM_OK;
1986 static int JimParseListStr(struct JimParserCtx *pc)
1988 pc->tstart = pc->p;
1989 pc->tline = pc->linenr;
1990 pc->tt = JIM_TT_STR;
1992 while (pc->len) {
1993 if (isspace(UCHAR(*pc->p))) {
1994 pc->tend = pc->p - 1;
1995 return JIM_OK;
1997 if (*pc->p == '\\') {
1998 if (--pc->len == 0) {
1999 /* Trailing backslash */
2000 pc->tend = pc->p;
2001 return JIM_OK;
2003 pc->tt = JIM_TT_ESC;
2004 pc->p++;
2006 pc->p++;
2007 pc->len--;
2009 pc->tend = pc->p - 1;
2010 return JIM_OK;
2013 /* -----------------------------------------------------------------------------
2014 * Jim_Obj related functions
2015 * ---------------------------------------------------------------------------*/
2017 /* Return a new initialized object. */
2018 Jim_Obj *Jim_NewObj(Jim_Interp *interp)
2020 Jim_Obj *objPtr;
2022 /* -- Check if there are objects in the free list -- */
2023 if (interp->freeList != NULL) {
2024 /* -- Unlink the object from the free list -- */
2025 objPtr = interp->freeList;
2026 interp->freeList = objPtr->nextObjPtr;
2028 else {
2029 /* -- No ready to use objects: allocate a new one -- */
2030 objPtr = Jim_Alloc(sizeof(*objPtr));
2033 /* Object is returned with refCount of 0. Every
2034 * kind of GC implemented should take care to don't try
2035 * to scan objects with refCount == 0. */
2036 objPtr->refCount = 0;
2037 /* All the other fields are left not initialized to save time.
2038 * The caller will probably want to set them to the right
2039 * value anyway. */
2041 /* -- Put the object into the live list -- */
2042 objPtr->prevObjPtr = NULL;
2043 objPtr->nextObjPtr = interp->liveList;
2044 if (interp->liveList)
2045 interp->liveList->prevObjPtr = objPtr;
2046 interp->liveList = objPtr;
2048 return objPtr;
2051 /* Free an object. Actually objects are never freed, but
2052 * just moved to the free objects list, where they will be
2053 * reused by Jim_NewObj(). */
2054 void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
2056 /* Check if the object was already freed, panic. */
2057 JimPanic((objPtr->refCount != 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr,
2058 objPtr->refCount, objPtr->typePtr ? objPtr->typePtr->name : "<none>"));
2060 /* Free the internal representation */
2061 Jim_FreeIntRep(interp, objPtr);
2062 /* Free the string representation */
2063 if (objPtr->bytes != NULL) {
2064 if (objPtr->bytes != JimEmptyStringRep)
2065 Jim_Free(objPtr->bytes);
2067 /* Unlink the object from the live objects list */
2068 if (objPtr->prevObjPtr)
2069 objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
2070 if (objPtr->nextObjPtr)
2071 objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
2072 if (interp->liveList == objPtr)
2073 interp->liveList = objPtr->nextObjPtr;
2074 /* Link the object into the free objects list */
2075 objPtr->prevObjPtr = NULL;
2076 objPtr->nextObjPtr = interp->freeList;
2077 if (interp->freeList)
2078 interp->freeList->prevObjPtr = objPtr;
2079 interp->freeList = objPtr;
2080 objPtr->refCount = -1;
2083 /* Invalidate the string representation of an object. */
2084 void Jim_InvalidateStringRep(Jim_Obj *objPtr)
2086 if (objPtr->bytes != NULL) {
2087 if (objPtr->bytes != JimEmptyStringRep)
2088 Jim_Free(objPtr->bytes);
2090 objPtr->bytes = NULL;
2093 #define Jim_SetStringRep(o, b, l) \
2094 do { (o)->bytes = b; (o)->length = l; } while (0)
2096 /* Set the initial string representation for an object.
2097 * Does not try to free an old one. */
2098 void Jim_InitStringRep(Jim_Obj *objPtr, const char *bytes, int length)
2100 if (length == 0) {
2101 objPtr->bytes = JimEmptyStringRep;
2102 objPtr->length = 0;
2104 else {
2105 objPtr->bytes = Jim_Alloc(length + 1);
2106 objPtr->length = length;
2107 memcpy(objPtr->bytes, bytes, length);
2108 objPtr->bytes[length] = '\0';
2112 /* Duplicate an object. The returned object has refcount = 0. */
2113 Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
2115 Jim_Obj *dupPtr;
2117 dupPtr = Jim_NewObj(interp);
2118 if (objPtr->bytes == NULL) {
2119 /* Object does not have a valid string representation. */
2120 dupPtr->bytes = NULL;
2122 else {
2123 Jim_InitStringRep(dupPtr, objPtr->bytes, objPtr->length);
2126 /* By default, the new object has the same type as the old object */
2127 dupPtr->typePtr = objPtr->typePtr;
2128 if (objPtr->typePtr != NULL) {
2129 if (objPtr->typePtr->dupIntRepProc == NULL) {
2130 dupPtr->internalRep = objPtr->internalRep;
2132 else {
2133 /* The dup proc may set a different type, e.g. NULL */
2134 objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
2137 return dupPtr;
2140 /* Return the string representation for objPtr. If the object
2141 * string representation is invalid, calls the method to create
2142 * a new one starting from the internal representation of the object. */
2143 const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
2145 if (objPtr->bytes == NULL) {
2146 /* Invalid string repr. Generate it. */
2147 JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
2148 objPtr->typePtr->updateStringProc(objPtr);
2150 if (lenPtr)
2151 *lenPtr = objPtr->length;
2152 return objPtr->bytes;
2155 /* Just returns the length of the object's string rep */
2156 int Jim_Length(Jim_Obj *objPtr)
2158 int len;
2160 Jim_GetString(objPtr, &len);
2161 return len;
2164 static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2165 static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2167 static const Jim_ObjType dictSubstObjType = {
2168 "dict-substitution",
2169 FreeDictSubstInternalRep,
2170 DupDictSubstInternalRep,
2171 NULL,
2172 JIM_TYPE_NONE,
2175 static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2177 Jim_DecrRefCount(interp, (Jim_Obj *)objPtr->internalRep.twoPtrValue.ptr2);
2180 static const Jim_ObjType interpolatedObjType = {
2181 "interpolated",
2182 FreeInterpolatedInternalRep,
2183 NULL,
2184 NULL,
2185 JIM_TYPE_NONE,
2188 /* -----------------------------------------------------------------------------
2189 * String Object
2190 * ---------------------------------------------------------------------------*/
2191 static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2192 static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
2194 static const Jim_ObjType stringObjType = {
2195 "string",
2196 NULL,
2197 DupStringInternalRep,
2198 NULL,
2199 JIM_TYPE_REFERENCES,
2202 static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2204 JIM_NOTUSED(interp);
2206 /* This is a bit subtle: the only caller of this function
2207 * should be Jim_DuplicateObj(), that will copy the
2208 * string representaion. After the copy, the duplicated
2209 * object will not have more room in teh buffer than
2210 * srcPtr->length bytes. So we just set it to length. */
2211 dupPtr->internalRep.strValue.maxLength = srcPtr->length;
2213 dupPtr->internalRep.strValue.charLength = srcPtr->internalRep.strValue.charLength;
2216 static int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
2218 /* Get a fresh string representation. */
2219 (void)Jim_String(objPtr);
2220 /* Free any other internal representation. */
2221 Jim_FreeIntRep(interp, objPtr);
2222 /* Set it as string, i.e. just set the maxLength field. */
2223 objPtr->typePtr = &stringObjType;
2224 objPtr->internalRep.strValue.maxLength = objPtr->length;
2225 /* Don't know the utf-8 length yet */
2226 objPtr->internalRep.strValue.charLength = -1;
2227 return JIM_OK;
2231 * Returns the length of the object string in chars, not bytes.
2233 * These may be different for a utf-8 string.
2235 int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr)
2237 #ifdef JIM_UTF8
2238 if (objPtr->typePtr != &stringObjType)
2239 SetStringFromAny(interp, objPtr);
2241 if (objPtr->internalRep.strValue.charLength < 0) {
2242 objPtr->internalRep.strValue.charLength = utf8_strlen(objPtr->bytes, objPtr->length);
2244 return objPtr->internalRep.strValue.charLength;
2245 #else
2246 return Jim_Length(objPtr);
2247 #endif
2250 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2251 Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
2253 Jim_Obj *objPtr = Jim_NewObj(interp);
2255 /* Need to find out how many bytes the string requires */
2256 if (len == -1)
2257 len = strlen(s);
2258 /* Alloc/Set the string rep. */
2259 if (len == 0) {
2260 objPtr->bytes = JimEmptyStringRep;
2261 objPtr->length = 0;
2263 else {
2264 objPtr->bytes = Jim_Alloc(len + 1);
2265 objPtr->length = len;
2266 memcpy(objPtr->bytes, s, len);
2267 objPtr->bytes[len] = '\0';
2270 /* No typePtr field for the vanilla string object. */
2271 objPtr->typePtr = NULL;
2272 return objPtr;
2275 /* charlen is in characters -- see also Jim_NewStringObj() */
2276 Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp, const char *s, int charlen)
2278 #ifdef JIM_UTF8
2279 /* Need to find out how many bytes the string requires */
2280 int bytelen = utf8_index(s, charlen);
2282 Jim_Obj *objPtr = Jim_NewStringObj(interp, s, bytelen);
2284 /* Remember the utf8 length, so set the type */
2285 objPtr->typePtr = &stringObjType;
2286 objPtr->internalRep.strValue.maxLength = bytelen;
2287 objPtr->internalRep.strValue.charLength = charlen;
2289 return objPtr;
2290 #else
2291 return Jim_NewStringObj(interp, s, charlen);
2292 #endif
2295 /* This version does not try to duplicate the 's' pointer, but
2296 * use it directly. */
2297 Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
2299 Jim_Obj *objPtr = Jim_NewObj(interp);
2301 if (len == -1)
2302 len = strlen(s);
2303 Jim_SetStringRep(objPtr, s, len);
2304 objPtr->typePtr = NULL;
2305 return objPtr;
2308 /* Low-level string append. Use it only against objects
2309 * of type "string". */
2310 static void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
2312 int needlen;
2314 if (len == -1)
2315 len = strlen(str);
2316 needlen = objPtr->length + len;
2317 if (objPtr->internalRep.strValue.maxLength < needlen ||
2318 objPtr->internalRep.strValue.maxLength == 0) {
2319 needlen *= 2;
2320 /* Inefficient to malloc() for less than 8 bytes */
2321 if (needlen < 7) {
2322 needlen = 7;
2324 if (objPtr->bytes == JimEmptyStringRep) {
2325 objPtr->bytes = Jim_Alloc(needlen + 1);
2327 else {
2328 objPtr->bytes = Jim_Realloc(objPtr->bytes, needlen + 1);
2330 objPtr->internalRep.strValue.maxLength = needlen;
2332 memcpy(objPtr->bytes + objPtr->length, str, len);
2333 objPtr->bytes[objPtr->length + len] = '\0';
2334 if (objPtr->internalRep.strValue.charLength >= 0) {
2335 /* Update the utf-8 char length */
2336 objPtr->internalRep.strValue.charLength += utf8_strlen(objPtr->bytes + objPtr->length, len);
2338 objPtr->length += len;
2341 /* Higher level API to append strings to objects. */
2342 void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str, int len)
2344 JimPanic((Jim_IsShared(objPtr), "Jim_AppendString called with shared object"));
2345 if (objPtr->typePtr != &stringObjType)
2346 SetStringFromAny(interp, objPtr);
2347 StringAppendString(objPtr, str, len);
2350 void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
2352 int len;
2353 const char *str;
2355 str = Jim_GetString(appendObjPtr, &len);
2356 Jim_AppendString(interp, objPtr, str, len);
2359 void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
2361 va_list ap;
2363 if (objPtr->typePtr != &stringObjType)
2364 SetStringFromAny(interp, objPtr);
2365 va_start(ap, objPtr);
2366 while (1) {
2367 char *s = va_arg(ap, char *);
2369 if (s == NULL)
2370 break;
2371 Jim_AppendString(interp, objPtr, s, -1);
2373 va_end(ap);
2376 int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr)
2378 const char *aStr, *bStr;
2379 int aLen, bLen;
2381 if (aObjPtr == bObjPtr)
2382 return 1;
2383 aStr = Jim_GetString(aObjPtr, &aLen);
2384 bStr = Jim_GetString(bObjPtr, &bLen);
2385 if (aLen != bLen)
2386 return 0;
2387 return JimStringCompare(aStr, aLen, bStr, bLen) == 0;
2390 int Jim_StringMatchObj(Jim_Interp *interp, Jim_Obj *patternObjPtr, Jim_Obj *objPtr, int nocase)
2392 return JimStringMatch(interp, patternObjPtr, Jim_String(objPtr), nocase);
2395 int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
2397 const char *s1, *s2;
2398 int l1, l2;
2400 s1 = Jim_GetString(firstObjPtr, &l1);
2401 s2 = Jim_GetString(secondObjPtr, &l2);
2403 if (nocase) {
2404 return JimStringCompareNoCase(s1, s2, -1);
2406 return JimStringCompare(s1, l1, s2, l2);
2409 /* Convert a range, as returned by Jim_GetRange(), into
2410 * an absolute index into an object of the specified length.
2411 * This function may return negative values, or values
2412 * bigger or equal to the length of the list if the index
2413 * is out of range. */
2414 static int JimRelToAbsIndex(int len, int idx)
2416 if (idx < 0)
2417 return len + idx;
2418 return idx;
2421 /* Convert a pair of index (*firstPtr, *lastPtr) as normalized by JimRelToAbsIndex(),
2422 * into form suitable for implementation of commands like [string range] and [lrange].
2424 * The resulting range is guaranteed to address valid elements of
2425 * the structure.
2428 static void JimRelToAbsRange(int len, int *firstPtr, int *lastPtr, int *rangeLenPtr)
2430 int rangeLen;
2432 if (*firstPtr > *lastPtr) {
2433 rangeLen = 0;
2435 else {
2436 rangeLen = *lastPtr - *firstPtr + 1;
2437 if (rangeLen) {
2438 if (*firstPtr < 0) {
2439 rangeLen += *firstPtr;
2440 *firstPtr = 0;
2442 if (*lastPtr >= len) {
2443 rangeLen -= (*lastPtr - (len - 1));
2444 *lastPtr = len - 1;
2448 if (rangeLen < 0)
2449 rangeLen = 0;
2451 *rangeLenPtr = rangeLen;
2454 static int JimStringGetRange(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr,
2455 int len, int *first, int *last, int *range)
2457 if (Jim_GetIndex(interp, firstObjPtr, first) != JIM_OK) {
2458 return JIM_ERR;
2460 if (Jim_GetIndex(interp, lastObjPtr, last) != JIM_OK) {
2461 return JIM_ERR;
2463 *first = JimRelToAbsIndex(len, *first);
2464 *last = JimRelToAbsIndex(len, *last);
2465 JimRelToAbsRange(len, first, last, range);
2466 return JIM_OK;
2469 Jim_Obj *Jim_StringByteRangeObj(Jim_Interp *interp,
2470 Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
2472 int first, last;
2473 const char *str;
2474 int rangeLen;
2475 int bytelen;
2477 str = Jim_GetString(strObjPtr, &bytelen);
2479 if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, bytelen, &first, &last, &rangeLen) != JIM_OK) {
2480 return NULL;
2483 if (first == 0 && rangeLen == bytelen) {
2484 return strObjPtr;
2486 return Jim_NewStringObj(interp, str + first, rangeLen);
2489 Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
2490 Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
2492 #ifdef JIM_UTF8
2493 int first, last;
2494 const char *str;
2495 int len, rangeLen;
2496 int bytelen;
2498 str = Jim_GetString(strObjPtr, &bytelen);
2499 len = Jim_Utf8Length(interp, strObjPtr);
2501 if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
2502 return NULL;
2505 if (first == 0 && rangeLen == len) {
2506 return strObjPtr;
2508 if (len == bytelen) {
2509 /* ASCII optimisation */
2510 return Jim_NewStringObj(interp, str + first, rangeLen);
2512 return Jim_NewStringObjUtf8(interp, str + utf8_index(str, first), rangeLen);
2513 #else
2514 return Jim_StringByteRangeObj(interp, strObjPtr, firstObjPtr, lastObjPtr);
2515 #endif
2518 static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
2520 char *buf, *p;
2521 int len;
2522 const char *str;
2524 if (strObjPtr->typePtr != &stringObjType) {
2525 SetStringFromAny(interp, strObjPtr);
2528 str = Jim_GetString(strObjPtr, &len);
2530 buf = p = Jim_Alloc(len + 1);
2531 while (*str) {
2532 int c;
2533 str += utf8_tounicode(str, &c);
2534 p += utf8_fromunicode(p, utf8_lower(c));
2536 *p = 0;
2537 return Jim_NewStringObjNoAlloc(interp, buf, len);
2540 static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
2542 char *buf, *p;
2543 int len;
2544 const char *str;
2546 if (strObjPtr->typePtr != &stringObjType) {
2547 SetStringFromAny(interp, strObjPtr);
2550 str = Jim_GetString(strObjPtr, &len);
2552 buf = p = Jim_Alloc(len + 1);
2553 while (*str) {
2554 int c;
2555 str += utf8_tounicode(str, &c);
2556 p += utf8_fromunicode(p, utf8_upper(c));
2558 *p = 0;
2559 return Jim_NewStringObjNoAlloc(interp, buf, len);
2562 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2563 * for unicode character 'c'.
2564 * Returns the position if found or NULL if not
2566 static const char *utf8_memchr(const char *str, int len, int c)
2568 #ifdef JIM_UTF8
2569 while (len) {
2570 int sc;
2571 int n = utf8_tounicode(str, &sc);
2572 if (sc == c) {
2573 return str;
2575 str += n;
2576 len -= n;
2578 return NULL;
2579 #else
2580 return memchr(str, c, len);
2581 #endif
2585 * Searches for the first non-trim char in string (str, len)
2587 * If none is found, returns just past the last char.
2589 * Lengths are in bytes.
2591 static const char *JimFindTrimLeft(const char *str, int len, const char *trimchars, int trimlen)
2593 while (len) {
2594 int c;
2595 int n = utf8_tounicode(str, &c);
2597 if (utf8_memchr(trimchars, trimlen, c) == NULL) {
2598 /* Not a trim char, so stop */
2599 break;
2601 str += n;
2602 len -= n;
2604 return str;
2608 * Searches backwards for a non-trim char in string (str, len).
2610 * Returns a pointer to just after the non-trim char, or NULL if not found.
2612 * Lengths are in bytes.
2614 static const char *JimFindTrimRight(const char *str, int len, const char *trimchars, int trimlen)
2616 str += len;
2618 while (len) {
2619 int c;
2620 int n = utf8_prev_len(str, len);
2622 len -= n;
2623 str -= n;
2625 n = utf8_tounicode(str, &c);
2627 if (utf8_memchr(trimchars, trimlen, c) == NULL) {
2628 return str + n;
2632 return NULL;
2635 static const char default_trim_chars[] = " \t\n\r";
2636 /* sizeof() here includes the null byte */
2637 static int default_trim_chars_len = sizeof(default_trim_chars);
2639 static Jim_Obj *JimStringTrimLeft(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2641 int len;
2642 const char *str = Jim_GetString(strObjPtr, &len);
2643 const char *trimchars = default_trim_chars;
2644 int trimcharslen = default_trim_chars_len;
2645 const char *newstr;
2647 if (trimcharsObjPtr) {
2648 trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
2651 newstr = JimFindTrimLeft(str, len, trimchars, trimcharslen);
2652 if (newstr == str) {
2653 return strObjPtr;
2656 return Jim_NewStringObj(interp, newstr, len - (newstr - str));
2659 static Jim_Obj *JimStringTrimRight(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2661 int len;
2662 const char *trimchars = default_trim_chars;
2663 int trimcharslen = default_trim_chars_len;
2664 const char *nontrim;
2666 if (trimcharsObjPtr) {
2667 trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
2670 if (strObjPtr->typePtr != &stringObjType) {
2671 SetStringFromAny(interp, strObjPtr);
2673 len = Jim_Length(strObjPtr);
2674 nontrim = JimFindTrimRight(strObjPtr->bytes, len, trimchars, trimcharslen);
2676 if (nontrim == NULL) {
2677 /* All trim, so return a zero-length string */
2678 return Jim_NewEmptyStringObj(interp);
2680 if (nontrim == strObjPtr->bytes + len) {
2681 return strObjPtr;
2684 if (Jim_IsShared(strObjPtr)) {
2685 strObjPtr = Jim_NewStringObj(interp, strObjPtr->bytes, (nontrim - strObjPtr->bytes));
2687 else {
2688 /* Can modify this string in place */
2689 strObjPtr->bytes[nontrim - strObjPtr->bytes] = 0;
2690 strObjPtr->length = (nontrim - strObjPtr->bytes);
2693 return strObjPtr;
2696 static Jim_Obj *JimStringTrim(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2698 /* First trim left. */
2699 Jim_Obj *objPtr = JimStringTrimLeft(interp, strObjPtr, trimcharsObjPtr);
2701 /* Now trim right */
2702 strObjPtr = JimStringTrimRight(interp, objPtr, trimcharsObjPtr);
2704 if (objPtr != strObjPtr) {
2705 /* Note that we don't want this object to be leaked */
2706 Jim_IncrRefCount(objPtr);
2707 Jim_DecrRefCount(interp, objPtr);
2710 return strObjPtr;
2714 static int JimStringIs(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *strClass, int strict)
2716 static const char * const strclassnames[] = {
2717 "integer", "alpha", "alnum", "ascii", "digit",
2718 "double", "lower", "upper", "space", "xdigit",
2719 "control", "print", "graph", "punct",
2720 NULL
2722 enum {
2723 STR_IS_INTEGER, STR_IS_ALPHA, STR_IS_ALNUM, STR_IS_ASCII, STR_IS_DIGIT,
2724 STR_IS_DOUBLE, STR_IS_LOWER, STR_IS_UPPER, STR_IS_SPACE, STR_IS_XDIGIT,
2725 STR_IS_CONTROL, STR_IS_PRINT, STR_IS_GRAPH, STR_IS_PUNCT
2727 int strclass;
2728 int len;
2729 int i;
2730 const char *str;
2731 int (*isclassfunc)(int c) = NULL;
2733 if (Jim_GetEnum(interp, strClass, strclassnames, &strclass, "class", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
2734 return JIM_ERR;
2737 str = Jim_GetString(strObjPtr, &len);
2738 if (len == 0) {
2739 Jim_SetResultInt(interp, !strict);
2740 return JIM_OK;
2743 switch (strclass) {
2744 case STR_IS_INTEGER:
2746 jim_wide w;
2747 Jim_SetResultInt(interp, JimGetWideNoErr(interp, strObjPtr, &w) == JIM_OK);
2748 return JIM_OK;
2751 case STR_IS_DOUBLE:
2753 double d;
2754 Jim_SetResultInt(interp, Jim_GetDouble(interp, strObjPtr, &d) == JIM_OK && errno != ERANGE);
2755 return JIM_OK;
2758 case STR_IS_ALPHA: isclassfunc = isalpha; break;
2759 case STR_IS_ALNUM: isclassfunc = isalnum; break;
2760 case STR_IS_ASCII: isclassfunc = isascii; break;
2761 case STR_IS_DIGIT: isclassfunc = isdigit; break;
2762 case STR_IS_LOWER: isclassfunc = islower; break;
2763 case STR_IS_UPPER: isclassfunc = isupper; break;
2764 case STR_IS_SPACE: isclassfunc = isspace; break;
2765 case STR_IS_XDIGIT: isclassfunc = isxdigit; break;
2766 case STR_IS_CONTROL: isclassfunc = iscntrl; break;
2767 case STR_IS_PRINT: isclassfunc = isprint; break;
2768 case STR_IS_GRAPH: isclassfunc = isgraph; break;
2769 case STR_IS_PUNCT: isclassfunc = ispunct; break;
2770 default:
2771 return JIM_ERR;
2774 for (i = 0; i < len; i++) {
2775 if (!isclassfunc(str[i])) {
2776 Jim_SetResultInt(interp, 0);
2777 return JIM_OK;
2780 Jim_SetResultInt(interp, 1);
2781 return JIM_OK;
2784 /* -----------------------------------------------------------------------------
2785 * Compared String Object
2786 * ---------------------------------------------------------------------------*/
2788 /* This is strange object that allows to compare a C literal string
2789 * with a Jim object in very short time if the same comparison is done
2790 * multiple times. For example every time the [if] command is executed,
2791 * Jim has to check if a given argument is "else". This comparions if
2792 * the code has no errors are true most of the times, so we can cache
2793 * inside the object the pointer of the string of the last matching
2794 * comparison. Because most C compilers perform literal sharing,
2795 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2796 * this works pretty well even if comparisons are at different places
2797 * inside the C code. */
2799 static const Jim_ObjType comparedStringObjType = {
2800 "compared-string",
2801 NULL,
2802 NULL,
2803 NULL,
2804 JIM_TYPE_REFERENCES,
2807 /* The only way this object is exposed to the API is via the following
2808 * function. Returns true if the string and the object string repr.
2809 * are the same, otherwise zero is returned.
2811 * Note: this isn't binary safe, but it hardly needs to be.*/
2812 int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr, const char *str)
2814 if (objPtr->typePtr == &comparedStringObjType && objPtr->internalRep.ptr == str)
2815 return 1;
2816 else {
2817 const char *objStr = Jim_String(objPtr);
2819 if (strcmp(str, objStr) != 0)
2820 return 0;
2821 if (objPtr->typePtr != &comparedStringObjType) {
2822 Jim_FreeIntRep(interp, objPtr);
2823 objPtr->typePtr = &comparedStringObjType;
2825 objPtr->internalRep.ptr = (char *)str; /*ATTENTION: const cast */
2826 return 1;
2830 static int qsortCompareStringPointers(const void *a, const void *b)
2832 char *const *sa = (char *const *)a;
2833 char *const *sb = (char *const *)b;
2835 return strcmp(*sa, *sb);
2839 /* -----------------------------------------------------------------------------
2840 * Source Object
2842 * This object is just a string from the language point of view, but
2843 * in the internal representation it contains the filename and line number
2844 * where this given token was read. This information is used by
2845 * Jim_EvalObj() if the object passed happens to be of type "source".
2847 * This allows to propagate the information about line numbers and file
2848 * names and give error messages with absolute line numbers.
2850 * Note that this object uses shared strings for filenames, and the
2851 * pointer to the filename together with the line number is taken into
2852 * the space for the "inline" internal representation of the Jim_Object,
2853 * so there is almost memory zero-overhead.
2855 * Also the object will be converted to something else if the given
2856 * token it represents in the source file is not something to be
2857 * evaluated (not a script), and will be specialized in some other way,
2858 * so the time overhead is also null.
2859 * ---------------------------------------------------------------------------*/
2861 static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2862 static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2864 static const Jim_ObjType sourceObjType = {
2865 "source",
2866 FreeSourceInternalRep,
2867 DupSourceInternalRep,
2868 NULL,
2869 JIM_TYPE_REFERENCES,
2872 void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2874 Jim_DecrRefCount(interp, objPtr->internalRep.sourceValue.fileNameObj);
2877 void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2879 dupPtr->internalRep = srcPtr->internalRep;
2880 Jim_IncrRefCount(dupPtr->internalRep.sourceValue.fileNameObj);
2883 static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
2884 Jim_Obj *fileNameObj, int lineNumber)
2886 JimPanic((Jim_IsShared(objPtr), "JimSetSourceInfo called with shared object"));
2887 JimPanic((objPtr->typePtr != NULL, "JimSetSourceInfo called with typePtr != NULL"));
2888 Jim_IncrRefCount(fileNameObj);
2889 objPtr->internalRep.sourceValue.fileNameObj = fileNameObj;
2890 objPtr->internalRep.sourceValue.lineNumber = lineNumber;
2891 objPtr->typePtr = &sourceObjType;
2894 /* -----------------------------------------------------------------------------
2895 * Script Object
2896 * ---------------------------------------------------------------------------*/
2898 static const Jim_ObjType scriptLineObjType = {
2899 "scriptline",
2900 NULL,
2901 NULL,
2902 NULL,
2906 static Jim_Obj *JimNewScriptLineObj(Jim_Interp *interp, int argc, int line)
2908 Jim_Obj *objPtr;
2910 #ifdef DEBUG_SHOW_SCRIPT
2911 char buf[100];
2912 snprintf(buf, sizeof(buf), "line=%d, argc=%d", line, argc);
2913 objPtr = Jim_NewStringObj(interp, buf, -1);
2914 #else
2915 objPtr = Jim_NewEmptyStringObj(interp);
2916 #endif
2917 objPtr->typePtr = &scriptLineObjType;
2918 objPtr->internalRep.scriptLineValue.argc = argc;
2919 objPtr->internalRep.scriptLineValue.line = line;
2921 return objPtr;
2924 #define JIM_CMDSTRUCT_EXPAND -1
2926 static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2927 static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2928 static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, struct JimParseResult *result);
2930 static const Jim_ObjType scriptObjType = {
2931 "script",
2932 FreeScriptInternalRep,
2933 DupScriptInternalRep,
2934 NULL,
2935 JIM_TYPE_REFERENCES,
2938 /* The ScriptToken structure represents every token into a scriptObj.
2939 * Every token contains an associated Jim_Obj that can be specialized
2940 * by commands operating on it. */
2941 typedef struct ScriptToken
2943 int type;
2944 Jim_Obj *objPtr;
2945 } ScriptToken;
2947 /* This is the script object internal representation. An array of
2948 * ScriptToken structures, including a pre-computed representation of the
2949 * command length and arguments.
2951 * For example the script:
2953 * puts hello
2954 * set $i $x$y [foo]BAR
2956 * will produce a ScriptObj with the following Tokens:
2958 * LIN 2
2959 * ESC puts
2960 * ESC hello
2961 * LIN 4
2962 * ESC set
2963 * VAR i
2964 * WRD 2
2965 * VAR x
2966 * VAR y
2967 * WRD 2
2968 * CMD foo
2969 * ESC BAR
2971 * "puts hello" has two args (LIN 2), composed of single tokens.
2972 * (Note that the WRD token is omitted for the common case of a single token.)
2974 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
2975 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
2977 * The precomputation of the command structure makes Jim_Eval() faster,
2978 * and simpler because there aren't dynamic lengths / allocations.
2980 * -- {expand}/{*} handling --
2982 * Expand is handled in a special way.
2984 * If a "word" begins with {*}, the word token count is -ve.
2986 * For example the command:
2988 * list {*}{a b}
2990 * Will produce the following cmdstruct array:
2992 * LIN 2
2993 * ESC list
2994 * WRD -1
2995 * STR a b
2997 * Note that the 'LIN' token also contains the source information for the
2998 * first word of the line for error reporting purposes
3000 * -- the substFlags field of the structure --
3002 * The scriptObj structure is used to represent both "script" objects
3003 * and "subst" objects. In the second case, the there are no LIN and WRD
3004 * tokens. Instead SEP and EOL tokens are added as-is.
3005 * In addition, the field 'substFlags' is used to represent the flags used to turn
3006 * the string into the internal representation used to perform the
3007 * substitution. If this flags are not what the application requires
3008 * the scriptObj is created again. For example the script:
3010 * subst -nocommands $string
3011 * subst -novariables $string
3013 * Will recreate the internal representation of the $string object
3014 * two times.
3016 typedef struct ScriptObj
3018 int len; /* Length as number of tokens. */
3019 ScriptToken *token; /* Tokens array. */
3020 int substFlags; /* flags used for the compilation of "subst" objects */
3021 int inUse; /* Used to share a ScriptObj. Currently
3022 only used by Jim_EvalObj() as protection against
3023 shimmering of the currently evaluated object. */
3024 Jim_Obj *fileNameObj;
3025 int line; /* Line number of the first line */
3026 } ScriptObj;
3028 void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
3030 int i;
3031 struct ScriptObj *script = (void *)objPtr->internalRep.ptr;
3033 script->inUse--;
3034 if (script->inUse != 0)
3035 return;
3036 for (i = 0; i < script->len; i++) {
3037 Jim_DecrRefCount(interp, script->token[i].objPtr);
3039 Jim_Free(script->token);
3040 Jim_DecrRefCount(interp, script->fileNameObj);
3041 Jim_Free(script);
3044 void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
3046 JIM_NOTUSED(interp);
3047 JIM_NOTUSED(srcPtr);
3049 /* Just returns an simple string. */
3050 dupPtr->typePtr = NULL;
3053 /* A simple parser token.
3054 * All the simple tokens for the script point into the same script string rep.
3056 typedef struct
3058 const char *token; /* Pointer to the start of the token */
3059 int len; /* Length of this token */
3060 int type; /* Token type */
3061 int line; /* Line number */
3062 } ParseToken;
3064 /* A list of parsed tokens representing a script.
3065 * Tokens are added to this list as the script is parsed.
3066 * It grows as needed.
3068 typedef struct
3070 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3071 ParseToken *list; /* Array of tokens */
3072 int size; /* Current size of the list */
3073 int count; /* Number of entries used */
3074 ParseToken static_list[20]; /* Small initial token space to avoid allocation */
3075 } ParseTokenList;
3077 static void ScriptTokenListInit(ParseTokenList *tokenlist)
3079 tokenlist->list = tokenlist->static_list;
3080 tokenlist->size = sizeof(tokenlist->static_list) / sizeof(ParseToken);
3081 tokenlist->count = 0;
3084 static void ScriptTokenListFree(ParseTokenList *tokenlist)
3086 if (tokenlist->list != tokenlist->static_list) {
3087 Jim_Free(tokenlist->list);
3092 * Adds the new token to the tokenlist.
3093 * The token has the given length, type and line number.
3094 * The token list is resized as necessary.
3096 static void ScriptAddToken(ParseTokenList *tokenlist, const char *token, int len, int type,
3097 int line)
3099 ParseToken *t;
3101 if (tokenlist->count == tokenlist->size) {
3102 /* Resize the list */
3103 tokenlist->size *= 2;
3104 if (tokenlist->list != tokenlist->static_list) {
3105 tokenlist->list =
3106 Jim_Realloc(tokenlist->list, tokenlist->size * sizeof(*tokenlist->list));
3108 else {
3109 /* The list needs to become allocated */
3110 tokenlist->list = Jim_Alloc(tokenlist->size * sizeof(*tokenlist->list));
3111 memcpy(tokenlist->list, tokenlist->static_list,
3112 tokenlist->count * sizeof(*tokenlist->list));
3115 t = &tokenlist->list[tokenlist->count++];
3116 t->token = token;
3117 t->len = len;
3118 t->type = type;
3119 t->line = line;
3122 /* Counts the number of adjoining non-separator.
3124 * Returns -ve if the first token is the expansion
3125 * operator (in which case the count doesn't include
3126 * that token).
3128 static int JimCountWordTokens(ParseToken *t)
3130 int expand = 1;
3131 int count = 0;
3133 /* Is the first word {*} or {expand}? */
3134 if (t->type == JIM_TT_STR && !TOKEN_IS_SEP(t[1].type)) {
3135 if ((t->len == 1 && *t->token == '*') || (t->len == 6 && strncmp(t->token, "expand", 6) == 0)) {
3136 /* Create an expand token */
3137 expand = -1;
3138 t++;
3142 /* Now count non-separator words */
3143 while (!TOKEN_IS_SEP(t->type)) {
3144 t++;
3145 count++;
3148 return count * expand;
3152 * Create a script/subst object from the given token.
3154 static Jim_Obj *JimMakeScriptObj(Jim_Interp *interp, const ParseToken *t)
3156 Jim_Obj *objPtr;
3158 if (t->type == JIM_TT_ESC && memchr(t->token, '\\', t->len) != NULL) {
3159 /* Convert the backlash escapes . */
3160 int len = t->len;
3161 char *str = Jim_Alloc(len + 1);
3162 len = JimEscape(str, t->token, len);
3163 objPtr = Jim_NewStringObjNoAlloc(interp, str, len);
3165 else {
3166 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3167 * with a single space. This is currently not done.
3169 objPtr = Jim_NewStringObj(interp, t->token, t->len);
3171 return objPtr;
3175 * Takes a tokenlist and creates the allocated list of script tokens
3176 * in script->token, of length script->len.
3178 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3179 * as required.
3181 * Also sets script->line to the line number of the first token
3183 static void ScriptObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
3184 ParseTokenList *tokenlist)
3186 int i;
3187 struct ScriptToken *token;
3188 /* Number of tokens so far for the current command */
3189 int lineargs = 0;
3190 /* This is the first token for the current command */
3191 ScriptToken *linefirst;
3192 int count;
3193 int linenr;
3195 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3196 printf("==== Tokens ====\n");
3197 for (i = 0; i < tokenlist->count; i++) {
3198 printf("[%2d]@%d %s '%.*s'\n", i, tokenlist->list[i].line, jim_tt_name(tokenlist->list[i].type),
3199 tokenlist->list[i].len, tokenlist->list[i].token);
3201 #endif
3203 /* May need up to one extra script token for each EOL in the worst case */
3204 count = tokenlist->count;
3205 for (i = 0; i < tokenlist->count; i++) {
3206 if (tokenlist->list[i].type == JIM_TT_EOL) {
3207 count++;
3210 linenr = script->line = tokenlist->list[0].line;
3212 token = script->token = Jim_Alloc(sizeof(ScriptToken) * count);
3214 /* This is the first token for the current command */
3215 linefirst = token++;
3217 for (i = 0; i < tokenlist->count; ) {
3218 /* Look ahead to find out how many tokens make up the next word */
3219 int wordtokens;
3221 /* Skip any leading separators */
3222 while (tokenlist->list[i].type == JIM_TT_SEP) {
3223 i++;
3226 wordtokens = JimCountWordTokens(tokenlist->list + i);
3228 if (wordtokens == 0) {
3229 /* None, so at end of line */
3230 if (lineargs) {
3231 linefirst->type = JIM_TT_LINE;
3232 linefirst->objPtr = JimNewScriptLineObj(interp, lineargs, linenr);
3233 Jim_IncrRefCount(linefirst->objPtr);
3235 /* Reset for new line */
3236 lineargs = 0;
3237 linefirst = token++;
3239 i++;
3240 continue;
3242 else if (wordtokens != 1) {
3243 /* More than 1, or {expand}, so insert a WORD token */
3244 token->type = JIM_TT_WORD;
3245 token->objPtr = Jim_NewIntObj(interp, wordtokens);
3246 Jim_IncrRefCount(token->objPtr);
3247 token++;
3248 if (wordtokens < 0) {
3249 /* Skip the expand token */
3250 i++;
3251 wordtokens = -wordtokens - 1;
3252 lineargs--;
3256 if (lineargs == 0) {
3257 /* First real token on the line, so record the line number */
3258 linenr = tokenlist->list[i].line;
3260 lineargs++;
3262 /* Add each non-separator word token to the line */
3263 while (wordtokens--) {
3264 const ParseToken *t = &tokenlist->list[i++];
3266 token->type = t->type;
3267 token->objPtr = JimMakeScriptObj(interp, t);
3268 Jim_IncrRefCount(token->objPtr);
3270 /* Every object is initially a string, but the
3271 * internal type may be specialized during execution of the
3272 * script. */
3273 JimSetSourceInfo(interp, token->objPtr, script->fileNameObj, t->line);
3274 token++;
3278 if (lineargs == 0) {
3279 token--;
3282 script->len = token - script->token;
3284 assert(script->len < count);
3286 #ifdef DEBUG_SHOW_SCRIPT
3287 printf("==== Script (%s) ====\n", Jim_String(script->fileNameObj));
3288 for (i = 0; i < script->len; i++) {
3289 const ScriptToken *t = &script->token[i];
3290 printf("[%2d] %s %s\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
3292 #endif
3297 * Similar to ScriptObjAddTokens(), but for subst objects.
3299 static void SubstObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
3300 ParseTokenList *tokenlist)
3302 int i;
3303 struct ScriptToken *token;
3305 token = script->token = Jim_Alloc(sizeof(ScriptToken) * tokenlist->count);
3307 for (i = 0; i < tokenlist->count; i++) {
3308 const ParseToken *t = &tokenlist->list[i];
3310 /* Create a token for 't' */
3311 token->type = t->type;
3312 token->objPtr = JimMakeScriptObj(interp, t);
3313 Jim_IncrRefCount(token->objPtr);
3314 token++;
3317 script->len = i;
3320 /* This method takes the string representation of an object
3321 * as a Tcl script, and generates the pre-parsed internal representation
3322 * of the script. */
3323 static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, struct JimParseResult *result)
3325 int scriptTextLen;
3326 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
3327 struct JimParserCtx parser;
3328 struct ScriptObj *script;
3329 ParseTokenList tokenlist;
3330 int line = 1;
3332 /* Try to get information about filename / line number */
3333 if (objPtr->typePtr == &sourceObjType) {
3334 line = objPtr->internalRep.sourceValue.lineNumber;
3337 /* Initially parse the script into tokens (in tokenlist) */
3338 ScriptTokenListInit(&tokenlist);
3340 JimParserInit(&parser, scriptText, scriptTextLen, line);
3341 while (!parser.eof) {
3342 JimParseScript(&parser);
3343 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
3344 parser.tline);
3346 if (result && parser.missing != ' ') {
3347 ScriptTokenListFree(&tokenlist);
3348 result->missing = parser.missing;
3349 result->line = parser.missingline;
3350 return JIM_ERR;
3353 /* Add a final EOF token */
3354 ScriptAddToken(&tokenlist, scriptText + scriptTextLen, 0, JIM_TT_EOF, 0);
3356 /* Create the "real" script tokens from the initial token list */
3357 script = Jim_Alloc(sizeof(*script));
3358 memset(script, 0, sizeof(*script));
3359 script->inUse = 1;
3360 script->line = line;
3361 if (objPtr->typePtr == &sourceObjType) {
3362 script->fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
3364 else {
3365 script->fileNameObj = interp->emptyObj;
3367 Jim_IncrRefCount(script->fileNameObj);
3369 ScriptObjAddTokens(interp, script, &tokenlist);
3371 /* No longer need the token list */
3372 ScriptTokenListFree(&tokenlist);
3374 /* Free the old internal rep and set the new one. */
3375 Jim_FreeIntRep(interp, objPtr);
3376 Jim_SetIntRepPtr(objPtr, script);
3377 objPtr->typePtr = &scriptObjType;
3379 return JIM_OK;
3382 ScriptObj *Jim_GetScript(Jim_Interp *interp, Jim_Obj *objPtr)
3384 struct ScriptObj *script = Jim_GetIntRepPtr(objPtr);
3386 if (objPtr->typePtr != &scriptObjType || script->substFlags) {
3387 SetScriptFromAny(interp, objPtr, NULL);
3389 return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
3392 /* -----------------------------------------------------------------------------
3393 * Commands
3394 * ---------------------------------------------------------------------------*/
3395 static void JimIncrCmdRefCount(Jim_Cmd *cmdPtr)
3397 cmdPtr->inUse++;
3400 static void JimDecrCmdRefCount(Jim_Interp *interp, Jim_Cmd *cmdPtr)
3402 if (--cmdPtr->inUse == 0) {
3403 if (cmdPtr->isproc) {
3404 Jim_DecrRefCount(interp, cmdPtr->u.proc.argListObjPtr);
3405 Jim_DecrRefCount(interp, cmdPtr->u.proc.bodyObjPtr);
3406 if (cmdPtr->u.proc.staticVars) {
3407 Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
3408 Jim_Free(cmdPtr->u.proc.staticVars);
3410 if (cmdPtr->u.proc.prevCmd) {
3411 /* Delete any pushed command too */
3412 JimDecrCmdRefCount(interp, cmdPtr->u.proc.prevCmd);
3415 else {
3416 /* native (C) */
3417 if (cmdPtr->u.native.delProc) {
3418 cmdPtr->u.native.delProc(interp, cmdPtr->u.native.privData);
3421 Jim_Free(cmdPtr);
3425 /* Variables HashTable Type.
3427 * Keys are dynamic allocated strings, Values are Jim_Var structures.
3430 /* Variables HashTable Type.
3432 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3433 static void JimVariablesHTValDestructor(void *interp, void *val)
3435 Jim_DecrRefCount(interp, ((Jim_Var *)val)->objPtr);
3436 Jim_Free(val);
3439 static const Jim_HashTableType JimVariablesHashTableType = {
3440 JimStringCopyHTHashFunction, /* hash function */
3441 JimStringCopyHTDup, /* key dup */
3442 NULL, /* val dup */
3443 JimStringCopyHTKeyCompare, /* key compare */
3444 JimStringCopyHTKeyDestructor, /* key destructor */
3445 JimVariablesHTValDestructor /* val destructor */
3448 /* Commands HashTable Type.
3450 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3451 static void JimCommandsHT_ValDestructor(void *interp, void *val)
3453 JimDecrCmdRefCount(interp, val);
3456 static const Jim_HashTableType JimCommandsHashTableType = {
3457 JimStringCopyHTHashFunction, /* hash function */
3458 JimStringCopyHTDup, /* key dup */
3459 NULL, /* val dup */
3460 JimStringCopyHTKeyCompare, /* key compare */
3461 JimStringCopyHTKeyDestructor, /* key destructor */
3462 JimCommandsHT_ValDestructor /* val destructor */
3465 /* ------------------------- Commands related functions --------------------- */
3467 int Jim_CreateCommand(Jim_Interp *interp, const char *cmdName,
3468 Jim_CmdProc cmdProc, void *privData, Jim_DelCmdProc delProc)
3470 Jim_Cmd *cmdPtr;
3472 if (Jim_DeleteHashEntry(&interp->commands, cmdName) != JIM_ERR) {
3473 /* Command existed so incr proc epoch */
3474 Jim_InterpIncrProcEpoch(interp);
3477 cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
3479 /* Store the new details for this proc */
3480 memset(cmdPtr, 0, sizeof(*cmdPtr));
3481 cmdPtr->inUse = 1;
3482 cmdPtr->u.native.delProc = delProc;
3483 cmdPtr->u.native.cmdProc = cmdProc;
3484 cmdPtr->u.native.privData = privData;
3486 Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);
3488 /* There is no need to increment the 'proc epoch' because
3489 * creation of a new procedure can never affect existing
3490 * cached commands. We don't do negative caching. */
3491 return JIM_OK;
3494 static int JimCreateProcedureStatics(Jim_Interp *interp, Jim_Cmd *cmdPtr, Jim_Obj *staticsListObjPtr)
3496 int len, i;
3498 len = Jim_ListLength(interp, staticsListObjPtr);
3499 if (len == 0) {
3500 return JIM_OK;
3503 cmdPtr->u.proc.staticVars = Jim_Alloc(sizeof(Jim_HashTable));
3504 Jim_InitHashTable(cmdPtr->u.proc.staticVars, &JimVariablesHashTableType, interp);
3505 for (i = 0; i < len; i++) {
3506 Jim_Obj *objPtr = NULL, *initObjPtr = NULL, *nameObjPtr = NULL;
3507 Jim_Var *varPtr;
3508 int subLen;
3510 Jim_ListIndex(interp, staticsListObjPtr, i, &objPtr, JIM_NONE);
3511 /* Check if it's composed of two elements. */
3512 subLen = Jim_ListLength(interp, objPtr);
3513 if (subLen == 1 || subLen == 2) {
3514 /* Try to get the variable value from the current
3515 * environment. */
3516 Jim_ListIndex(interp, objPtr, 0, &nameObjPtr, JIM_NONE);
3517 if (subLen == 1) {
3518 initObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_NONE);
3519 if (initObjPtr == NULL) {
3520 Jim_SetResultFormatted(interp,
3521 "variable for initialization of static \"%#s\" not found in the local context",
3522 nameObjPtr);
3523 return JIM_ERR;
3526 else {
3527 Jim_ListIndex(interp, objPtr, 1, &initObjPtr, JIM_NONE);
3529 if (JimValidName(interp, "static variable", nameObjPtr) != JIM_OK) {
3530 return JIM_ERR;
3533 varPtr = Jim_Alloc(sizeof(*varPtr));
3534 varPtr->objPtr = initObjPtr;
3535 Jim_IncrRefCount(initObjPtr);
3536 varPtr->linkFramePtr = NULL;
3537 if (Jim_AddHashEntry(cmdPtr->u.proc.staticVars,
3538 Jim_String(nameObjPtr), varPtr) != JIM_OK) {
3539 Jim_SetResultFormatted(interp,
3540 "static variable name \"%#s\" duplicated in statics list", nameObjPtr);
3541 Jim_DecrRefCount(interp, initObjPtr);
3542 Jim_Free(varPtr);
3543 return JIM_ERR;
3546 else {
3547 Jim_SetResultFormatted(interp, "too many fields in static specifier \"%#s\"",
3548 objPtr);
3549 return JIM_ERR;
3552 return JIM_OK;
3555 static int JimCreateProcedure(Jim_Interp *interp, Jim_Obj *cmdName,
3556 Jim_Obj *argListObjPtr, Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr)
3558 Jim_Cmd *cmdPtr;
3559 Jim_HashEntry *he;
3560 int argListLen;
3561 int i;
3563 if (JimValidName(interp, "procedure", cmdName) != JIM_OK) {
3564 return JIM_ERR;
3567 argListLen = Jim_ListLength(interp, argListObjPtr);
3569 /* Allocate space for both the command pointer and the arg list */
3570 cmdPtr = Jim_Alloc(sizeof(*cmdPtr) + sizeof(struct Jim_ProcArg) * argListLen);
3571 memset(cmdPtr, 0, sizeof(*cmdPtr));
3572 cmdPtr->inUse = 1;
3573 cmdPtr->isproc = 1;
3574 cmdPtr->u.proc.argListObjPtr = argListObjPtr;
3575 cmdPtr->u.proc.argListLen = argListLen;
3576 cmdPtr->u.proc.bodyObjPtr = bodyObjPtr;
3577 cmdPtr->u.proc.argsPos = -1;
3578 cmdPtr->u.proc.arglist = (struct Jim_ProcArg *)(cmdPtr + 1);
3579 Jim_IncrRefCount(argListObjPtr);
3580 Jim_IncrRefCount(bodyObjPtr);
3582 /* Create the statics hash table. */
3583 if (staticsListObjPtr && JimCreateProcedureStatics(interp, cmdPtr, staticsListObjPtr) != JIM_OK) {
3584 goto err;
3587 /* Parse the args out into arglist, validating as we go */
3588 /* Examine the argument list for default parameters and 'args' */
3589 for (i = 0; i < argListLen; i++) {
3590 Jim_Obj *argPtr;
3591 Jim_Obj *nameObjPtr;
3592 Jim_Obj *defaultObjPtr;
3593 int len;
3594 int n = 1;
3596 /* Examine a parameter */
3597 Jim_ListIndex(interp, argListObjPtr, i, &argPtr, JIM_NONE);
3598 len = Jim_ListLength(interp, argPtr);
3599 if (len == 0) {
3600 Jim_SetResultString(interp, "procedure has argument with no name", -1);
3601 goto err;
3603 if (len > 2) {
3604 Jim_SetResultString(interp, "procedure has argument with too many fields", -1);
3605 goto err;
3608 if (len == 2) {
3609 /* Optional parameter */
3610 Jim_ListIndex(interp, argPtr, 0, &nameObjPtr, JIM_NONE);
3611 Jim_ListIndex(interp, argPtr, 1, &defaultObjPtr, JIM_NONE);
3613 else {
3614 /* Required parameter */
3615 nameObjPtr = argPtr;
3616 defaultObjPtr = NULL;
3620 if (Jim_CompareStringImmediate(interp, nameObjPtr, "args")) {
3621 if (cmdPtr->u.proc.argsPos >= 0) {
3622 Jim_SetResultString(interp, "procedure has 'args' specified more than once", -1);
3623 goto err;
3625 cmdPtr->u.proc.argsPos = i;
3627 else {
3628 if (len == 2) {
3629 cmdPtr->u.proc.optArity += n;
3631 else {
3632 cmdPtr->u.proc.reqArity += n;
3636 cmdPtr->u.proc.arglist[i].nameObjPtr = nameObjPtr;
3637 cmdPtr->u.proc.arglist[i].defaultObjPtr = defaultObjPtr;
3640 /* Add the new command */
3642 /* It may already exist, so we try to delete the old one.
3643 * Note that reference count means that it won't be deleted yet if
3644 * it exists in the call stack.
3646 * BUT, if 'local' is in force, instead of deleting the existing
3647 * proc, we stash a reference to the old proc here.
3649 he = Jim_FindHashEntry(&interp->commands, Jim_String(cmdName));
3650 if (he) {
3651 /* There was an old procedure with the same name, this requires
3652 * a 'proc epoch' update. */
3654 /* If a procedure with the same name didn't existed there is no need
3655 * to increment the 'proc epoch' because creation of a new procedure
3656 * can never affect existing cached commands. We don't do
3657 * negative caching. */
3658 Jim_InterpIncrProcEpoch(interp);
3661 if (he && interp->local) {
3662 /* Just push this proc over the top of the previous one */
3663 cmdPtr->u.proc.prevCmd = he->u.val;
3664 he->u.val = cmdPtr;
3666 else {
3667 if (he) {
3668 /* Replace the existing proc */
3669 Jim_DeleteHashEntry(&interp->commands, Jim_String(cmdName));
3672 Jim_AddHashEntry(&interp->commands, Jim_String(cmdName), cmdPtr);
3675 /* Unlike Tcl, set the name of the proc as the result */
3676 Jim_SetResult(interp, cmdName);
3677 return JIM_OK;
3679 err:
3680 if (cmdPtr->u.proc.staticVars) {
3681 Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
3683 Jim_Free(cmdPtr->u.proc.staticVars);
3684 Jim_DecrRefCount(interp, argListObjPtr);
3685 Jim_DecrRefCount(interp, bodyObjPtr);
3686 Jim_Free(cmdPtr);
3687 return JIM_ERR;
3690 int Jim_DeleteCommand(Jim_Interp *interp, const char *cmdName)
3692 if (Jim_DeleteHashEntry(&interp->commands, cmdName) == JIM_ERR)
3693 return JIM_ERR;
3694 Jim_InterpIncrProcEpoch(interp);
3695 return JIM_OK;
3698 int Jim_RenameCommand(Jim_Interp *interp, const char *oldName, const char *newName)
3700 Jim_HashEntry *he;
3702 /* Does it exist? */
3703 he = Jim_FindHashEntry(&interp->commands, oldName);
3704 if (he == NULL) {
3705 Jim_SetResultFormatted(interp, "can't %s \"%s\": command doesn't exist",
3706 newName[0] ? "rename" : "delete", oldName);
3707 return JIM_ERR;
3710 if (newName[0] == '\0') /* Delete! */
3711 return Jim_DeleteCommand(interp, oldName);
3713 /* rename */
3714 if (Jim_FindHashEntry(&interp->commands, newName)) {
3715 Jim_SetResultFormatted(interp, "can't rename to \"%s\": command already exists", newName);
3716 return JIM_ERR;
3719 /* Add the new name first */
3720 JimIncrCmdRefCount(he->u.val);
3721 Jim_AddHashEntry(&interp->commands, newName, he->u.val);
3723 /* Now remove the old name */
3724 Jim_DeleteHashEntry(&interp->commands, oldName);
3726 /* Increment the epoch */
3727 Jim_InterpIncrProcEpoch(interp);
3728 return JIM_OK;
3731 /* -----------------------------------------------------------------------------
3732 * Command object
3733 * ---------------------------------------------------------------------------*/
3735 static int SetCommandFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3737 static const Jim_ObjType commandObjType = {
3738 "command",
3739 NULL,
3740 NULL,
3741 NULL,
3742 JIM_TYPE_REFERENCES,
3745 int SetCommandFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
3747 Jim_HashEntry *he;
3748 const char *cmdName;
3750 /* Get the string representation */
3751 cmdName = Jim_String(objPtr);
3752 /* Lookup this name into the commands hash table */
3753 he = Jim_FindHashEntry(&interp->commands, cmdName);
3754 if (he == NULL)
3755 return JIM_ERR;
3757 /* Free the old internal repr and set the new one. */
3758 Jim_FreeIntRep(interp, objPtr);
3759 objPtr->typePtr = &commandObjType;
3760 objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
3761 objPtr->internalRep.cmdValue.cmdPtr = (void *)he->u.val;
3762 return JIM_OK;
3765 /* This function returns the command structure for the command name
3766 * stored in objPtr. It tries to specialize the objPtr to contain
3767 * a cached info instead to perform the lookup into the hash table
3768 * every time. The information cached may not be uptodate, in such
3769 * a case the lookup is performed and the cache updated.
3771 * Respects the 'upcall' setting
3773 Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
3775 Jim_Cmd *cmd;
3777 if ((objPtr->typePtr != &commandObjType ||
3778 objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch) &&
3779 SetCommandFromAny(interp, objPtr) == JIM_ERR) {
3780 if (flags & JIM_ERRMSG) {
3781 Jim_SetResultFormatted(interp, "invalid command name \"%#s\"", objPtr);
3783 return NULL;
3785 cmd = objPtr->internalRep.cmdValue.cmdPtr;
3786 while (cmd->isproc && cmd->u.proc.upcall) {
3787 cmd = cmd->u.proc.prevCmd;
3789 return cmd;
3792 /* -----------------------------------------------------------------------------
3793 * Variables
3794 * ---------------------------------------------------------------------------*/
3796 /* -----------------------------------------------------------------------------
3797 * Variable object
3798 * ---------------------------------------------------------------------------*/
3800 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3802 static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3804 static const Jim_ObjType variableObjType = {
3805 "variable",
3806 NULL,
3807 NULL,
3808 NULL,
3809 JIM_TYPE_REFERENCES,
3813 * Check that the name does not contain embedded nulls.
3815 * Variable and procedure names are maniplated as null terminated strings, so
3816 * don't allow names with embedded nulls.
3818 static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr)
3820 /* Variable names and proc names can't contain embedded nulls */
3821 if (nameObjPtr->typePtr != &variableObjType) {
3822 int len;
3823 const char *str = Jim_GetString(nameObjPtr, &len);
3824 if (memchr(str, '\0', len)) {
3825 Jim_SetResultFormatted(interp, "%s name contains embedded null", type);
3826 return JIM_ERR;
3829 return JIM_OK;
3832 static const char *JimUnscopedName(Jim_Interp *interp, const char *varName, Jim_CallFrame **framePtr)
3834 if (varName[0] == ':' && varName[1] == ':') {
3835 *framePtr = interp->topFramePtr;
3836 return varName + 2;
3838 *framePtr = interp->framePtr;
3839 return varName;
3842 /* This method should be called only by the variable API.
3843 * It returns JIM_OK on success (variable already exists),
3844 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3845 * a variable name, but syntax glue for [dict] i.e. the last
3846 * character is ')' */
3847 static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
3849 const char *varName;
3850 Jim_CallFrame *framePtr;
3851 Jim_HashEntry *he;
3853 /* Check if the object is already an uptodate variable */
3854 if (objPtr->typePtr == &variableObjType) {
3855 varName = objPtr->bytes;
3856 if (varName[0] == ':' && varName[1] == ':') {
3857 framePtr = interp->topFramePtr;
3858 varName += 2;
3860 else {
3861 framePtr = interp->framePtr;
3864 if (objPtr->internalRep.varValue.callFrameId == framePtr->id) {
3865 /* nothing to do */
3866 return JIM_OK;
3868 /* Need to re-resolve the variable in the updated callframe */
3870 else if (objPtr->typePtr == &dictSubstObjType) {
3871 return JIM_DICT_SUGAR;
3873 else if (JimValidName(interp, "variable", objPtr) != JIM_OK) {
3874 return JIM_ERR;
3876 else {
3877 int len;
3879 varName = Jim_GetString(objPtr, &len);
3881 /* Make sure it's not syntax glue to get/set dict. */
3882 if (len && varName[len - 1] == ')' && strchr(varName, '(') != NULL) {
3883 return JIM_DICT_SUGAR;
3886 varName = JimUnscopedName(interp, varName, &framePtr);
3889 /* Resolve this name in the variables hash table */
3890 he = Jim_FindHashEntry(&framePtr->vars, varName);
3891 if (he == NULL) {
3892 if (framePtr->staticVars) {
3893 /* Try with static vars. */
3894 he = Jim_FindHashEntry(framePtr->staticVars, varName);
3896 if (he == NULL) {
3897 return JIM_ERR;
3901 /* Free the old internal repr and set the new one. */
3902 Jim_FreeIntRep(interp, objPtr);
3903 objPtr->typePtr = &variableObjType;
3904 objPtr->internalRep.varValue.callFrameId = framePtr->id;
3905 objPtr->internalRep.varValue.varPtr = he->u.val;
3906 return JIM_OK;
3909 /* -------------------- Variables related functions ------------------------- */
3910 static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr, Jim_Obj *valObjPtr);
3911 static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr, int flags);
3913 static Jim_Var *JimCreateVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
3915 const char *name;
3916 Jim_CallFrame *framePtr;
3918 /* New variable to create */
3919 Jim_Var *var = Jim_Alloc(sizeof(*var));
3921 var->objPtr = valObjPtr;
3922 Jim_IncrRefCount(valObjPtr);
3923 var->linkFramePtr = NULL;
3925 name = JimUnscopedName(interp, Jim_String(nameObjPtr), &framePtr);
3927 /* Insert the new variable */
3928 Jim_AddHashEntry(&framePtr->vars, name, var);
3930 /* Make the object int rep a variable */
3931 Jim_FreeIntRep(interp, nameObjPtr);
3932 nameObjPtr->typePtr = &variableObjType;
3933 nameObjPtr->internalRep.varValue.callFrameId = framePtr->id;
3934 nameObjPtr->internalRep.varValue.varPtr = var;
3936 return var;
3939 /* For now that's dummy. Variables lookup should be optimized
3940 * in many ways, with caching of lookups, and possibly with
3941 * a table of pre-allocated vars in every CallFrame for local vars.
3942 * All the caching should also have an 'epoch' mechanism similar
3943 * to the one used by Tcl for procedures lookup caching. */
3945 int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
3947 int err;
3948 Jim_Var *var;
3950 switch (SetVariableFromAny(interp, nameObjPtr)) {
3951 case JIM_DICT_SUGAR:
3952 return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
3954 case JIM_ERR:
3955 if (JimValidName(interp, "variable", nameObjPtr) != JIM_OK) {
3956 return JIM_ERR;
3958 JimCreateVariable(interp, nameObjPtr, valObjPtr);
3959 break;
3961 case JIM_OK:
3962 var = nameObjPtr->internalRep.varValue.varPtr;
3963 if (var->linkFramePtr == NULL) {
3964 Jim_IncrRefCount(valObjPtr);
3965 Jim_DecrRefCount(interp, var->objPtr);
3966 var->objPtr = valObjPtr;
3968 else { /* Else handle the link */
3969 Jim_CallFrame *savedCallFrame;
3971 savedCallFrame = interp->framePtr;
3972 interp->framePtr = var->linkFramePtr;
3973 err = Jim_SetVariable(interp, var->objPtr, valObjPtr);
3974 interp->framePtr = savedCallFrame;
3975 if (err != JIM_OK)
3976 return err;
3979 return JIM_OK;
3982 int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
3984 Jim_Obj *nameObjPtr;
3985 int result;
3987 nameObjPtr = Jim_NewStringObj(interp, name, -1);
3988 Jim_IncrRefCount(nameObjPtr);
3989 result = Jim_SetVariable(interp, nameObjPtr, objPtr);
3990 Jim_DecrRefCount(interp, nameObjPtr);
3991 return result;
3994 int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
3996 Jim_CallFrame *savedFramePtr;
3997 int result;
3999 savedFramePtr = interp->framePtr;
4000 interp->framePtr = interp->topFramePtr;
4001 result = Jim_SetVariableStr(interp, name, objPtr);
4002 interp->framePtr = savedFramePtr;
4003 return result;
4006 int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
4008 Jim_Obj *nameObjPtr, *valObjPtr;
4009 int result;
4011 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4012 valObjPtr = Jim_NewStringObj(interp, val, -1);
4013 Jim_IncrRefCount(nameObjPtr);
4014 Jim_IncrRefCount(valObjPtr);
4015 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4016 Jim_DecrRefCount(interp, nameObjPtr);
4017 Jim_DecrRefCount(interp, valObjPtr);
4018 return result;
4021 int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
4022 Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
4024 const char *varName;
4025 const char *targetName;
4026 Jim_CallFrame *framePtr;
4027 Jim_Var *varPtr;
4029 /* Check for an existing variable or link */
4030 switch (SetVariableFromAny(interp, nameObjPtr)) {
4031 case JIM_DICT_SUGAR:
4032 /* XXX: This message seem unnecessarily verbose, but it matches Tcl */
4033 Jim_SetResultFormatted(interp, "bad variable name \"%#s\": upvar won't create a scalar variable that looks like an array element", nameObjPtr);
4034 return JIM_ERR;
4036 case JIM_OK:
4037 varPtr = nameObjPtr->internalRep.varValue.varPtr;
4039 if (varPtr->linkFramePtr == NULL) {
4040 Jim_SetResultFormatted(interp, "variable \"%#s\" already exists", nameObjPtr);
4041 return JIM_ERR;
4044 /* It exists, but is a link, so first delete the link */
4045 varPtr->linkFramePtr = NULL;
4046 break;
4049 /* Resolve the call frames for both variables */
4050 /* XXX: SetVariableFromAny() already did this! */
4051 varName = Jim_String(nameObjPtr);
4053 if (varName[0] == ':' && varName[1] == ':') {
4054 /* Linking a global var does nothing */
4055 varName += 2;
4056 framePtr = interp->topFramePtr;
4058 else {
4059 framePtr = interp->framePtr;
4062 targetName = Jim_String(targetNameObjPtr);
4063 if (targetName[0] == ':' && targetName[1] == ':') {
4064 targetNameObjPtr = Jim_NewStringObj(interp, targetName + 2, -1);
4065 targetCallFrame = interp->topFramePtr;
4067 Jim_IncrRefCount(targetNameObjPtr);
4069 if (framePtr->level < targetCallFrame->level) {
4070 Jim_SetResultFormatted(interp,
4071 "bad variable name \"%#s\": upvar won't create namespace variable that refers to procedure variable",
4072 nameObjPtr);
4073 Jim_DecrRefCount(interp, targetNameObjPtr);
4074 return JIM_ERR;
4077 /* Check for cycles. */
4078 if (framePtr == targetCallFrame) {
4079 Jim_Obj *objPtr = targetNameObjPtr;
4081 /* Cycles are only possible with 'uplevel 0' */
4082 while (1) {
4083 if (strcmp(Jim_String(objPtr), varName) == 0) {
4084 Jim_SetResultString(interp, "can't upvar from variable to itself", -1);
4085 Jim_DecrRefCount(interp, targetNameObjPtr);
4086 return JIM_ERR;
4088 if (SetVariableFromAny(interp, objPtr) != JIM_OK)
4089 break;
4090 varPtr = objPtr->internalRep.varValue.varPtr;
4091 if (varPtr->linkFramePtr != targetCallFrame)
4092 break;
4093 objPtr = varPtr->objPtr;
4097 /* Perform the binding */
4098 Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
4099 /* We are now sure 'nameObjPtr' type is variableObjType */
4100 nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;
4101 Jim_DecrRefCount(interp, targetNameObjPtr);
4102 return JIM_OK;
4105 /* Return the Jim_Obj pointer associated with a variable name,
4106 * or NULL if the variable was not found in the current context.
4107 * The same optimization discussed in the comment to the
4108 * 'SetVariable' function should apply here.
4110 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4111 * in a dictionary which is shared, the array variable value is duplicated first.
4112 * This allows the array element to be updated (e.g. append, lappend) without
4113 * affecting other references to the dictionary.
4115 Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4117 switch (SetVariableFromAny(interp, nameObjPtr)) {
4118 case JIM_OK:{
4119 Jim_Var *varPtr = nameObjPtr->internalRep.varValue.varPtr;
4121 if (varPtr->linkFramePtr == NULL) {
4122 return varPtr->objPtr;
4124 else {
4125 Jim_Obj *objPtr;
4127 /* The variable is a link? Resolve it. */
4128 Jim_CallFrame *savedCallFrame = interp->framePtr;
4130 interp->framePtr = varPtr->linkFramePtr;
4131 objPtr = Jim_GetVariable(interp, varPtr->objPtr, flags);
4132 interp->framePtr = savedCallFrame;
4133 if (objPtr) {
4134 return objPtr;
4136 /* Error, so fall through to the error message */
4139 break;
4141 case JIM_DICT_SUGAR:
4142 /* [dict] syntax sugar. */
4143 return JimDictSugarGet(interp, nameObjPtr, flags);
4145 if (flags & JIM_ERRMSG) {
4146 Jim_SetResultFormatted(interp, "can't read \"%#s\": no such variable", nameObjPtr);
4148 return NULL;
4151 Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4153 Jim_CallFrame *savedFramePtr;
4154 Jim_Obj *objPtr;
4156 savedFramePtr = interp->framePtr;
4157 interp->framePtr = interp->topFramePtr;
4158 objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
4159 interp->framePtr = savedFramePtr;
4161 return objPtr;
4164 Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
4166 Jim_Obj *nameObjPtr, *varObjPtr;
4168 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4169 Jim_IncrRefCount(nameObjPtr);
4170 varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
4171 Jim_DecrRefCount(interp, nameObjPtr);
4172 return varObjPtr;
4175 Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name, int flags)
4177 Jim_CallFrame *savedFramePtr;
4178 Jim_Obj *objPtr;
4180 savedFramePtr = interp->framePtr;
4181 interp->framePtr = interp->topFramePtr;
4182 objPtr = Jim_GetVariableStr(interp, name, flags);
4183 interp->framePtr = savedFramePtr;
4185 return objPtr;
4188 /* Unset a variable.
4189 * Note: On success unset invalidates all the variable objects created
4190 * in the current call frame incrementing. */
4191 int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4193 const char *name;
4194 Jim_Var *varPtr;
4195 int retval;
4197 retval = SetVariableFromAny(interp, nameObjPtr);
4198 if (retval == JIM_DICT_SUGAR) {
4199 /* [dict] syntax sugar. */
4200 return JimDictSugarSet(interp, nameObjPtr, NULL);
4202 else if (retval == JIM_OK) {
4203 varPtr = nameObjPtr->internalRep.varValue.varPtr;
4205 /* If it's a link call UnsetVariable recursively */
4206 if (varPtr->linkFramePtr) {
4207 Jim_CallFrame *savedCallFrame;
4209 savedCallFrame = interp->framePtr;
4210 interp->framePtr = varPtr->linkFramePtr;
4211 retval = Jim_UnsetVariable(interp, varPtr->objPtr, JIM_NONE);
4212 interp->framePtr = savedCallFrame;
4214 else {
4215 Jim_CallFrame *framePtr;
4217 name = JimUnscopedName(interp, Jim_String(nameObjPtr), &framePtr);
4219 retval = Jim_DeleteHashEntry(&framePtr->vars, name);
4220 if (retval == JIM_OK) {
4221 /* Change the callframe id, invalidating var lookup caching */
4222 JimChangeCallFrameId(interp, framePtr);
4226 if (retval != JIM_OK && (flags & JIM_ERRMSG)) {
4227 Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such variable", nameObjPtr);
4229 return retval;
4232 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4234 /* Given a variable name for [dict] operation syntax sugar,
4235 * this function returns two objects, the first with the name
4236 * of the variable to set, and the second with the rispective key.
4237 * For example "foo(bar)" will return objects with string repr. of
4238 * "foo" and "bar".
4240 * The returned objects have refcount = 1. The function can't fail. */
4241 static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
4242 Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
4244 const char *str, *p;
4245 int len, keyLen;
4246 Jim_Obj *varObjPtr, *keyObjPtr;
4248 str = Jim_GetString(objPtr, &len);
4250 p = strchr(str, '(');
4251 JimPanic((p == NULL, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str));
4253 varObjPtr = Jim_NewStringObj(interp, str, p - str);
4255 p++;
4256 keyLen = (str + len) - p;
4257 if (str[len - 1] == ')') {
4258 keyLen--;
4261 /* Create the objects with the variable name and key. */
4262 keyObjPtr = Jim_NewStringObj(interp, p, keyLen);
4264 Jim_IncrRefCount(varObjPtr);
4265 Jim_IncrRefCount(keyObjPtr);
4266 *varPtrPtr = varObjPtr;
4267 *keyPtrPtr = keyObjPtr;
4270 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4271 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4272 static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *valObjPtr)
4274 int err;
4276 SetDictSubstFromAny(interp, objPtr);
4278 err = Jim_SetDictKeysVector(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
4279 &objPtr->internalRep.dictSubstValue.indexObjPtr, 1, valObjPtr, JIM_ERRMSG);
4281 if (err == JIM_OK) {
4282 /* Don't keep an extra ref to the result */
4283 Jim_SetEmptyResult(interp);
4285 else {
4286 if (!valObjPtr) {
4287 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4288 if (Jim_GetVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_NONE)) {
4289 Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such element in array",
4290 objPtr);
4291 return err;
4294 /* Make the error more informative and Tcl-compatible */
4295 Jim_SetResultFormatted(interp, "can't %s \"%#s\": variable isn't array",
4296 (valObjPtr ? "set" : "unset"), objPtr);
4298 return err;
4302 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4304 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4305 * and stored back to the variable before expansion.
4307 static Jim_Obj *JimDictExpandArrayVariable(Jim_Interp *interp, Jim_Obj *varObjPtr,
4308 Jim_Obj *keyObjPtr, int flags)
4310 Jim_Obj *dictObjPtr;
4311 Jim_Obj *resObjPtr = NULL;
4312 int ret;
4314 dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
4315 if (!dictObjPtr) {
4316 return NULL;
4319 ret = Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
4320 if (ret != JIM_OK) {
4321 resObjPtr = NULL;
4322 if (ret < 0) {
4323 Jim_SetResultFormatted(interp,
4324 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr, keyObjPtr);
4326 else {
4327 Jim_SetResultFormatted(interp,
4328 "can't read \"%#s(%#s)\": no such element in array", varObjPtr, keyObjPtr);
4331 else if ((flags & JIM_UNSHARED) && Jim_IsShared(dictObjPtr)) {
4332 dictObjPtr = Jim_DuplicateObj(interp, dictObjPtr);
4333 if (Jim_SetVariable(interp, varObjPtr, dictObjPtr) != JIM_OK) {
4334 /* This can probably never happen */
4335 JimPanic((1, "SetVariable failed for JIM_UNSHARED"));
4337 /* We know that the key exists. Get the result in the now-unshared dictionary */
4338 Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
4341 return resObjPtr;
4344 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4345 static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
4347 SetDictSubstFromAny(interp, objPtr);
4349 return JimDictExpandArrayVariable(interp,
4350 objPtr->internalRep.dictSubstValue.varNameObjPtr,
4351 objPtr->internalRep.dictSubstValue.indexObjPtr, flags);
4354 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4356 void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
4358 Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
4359 Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
4362 void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
4364 JIM_NOTUSED(interp);
4366 dupPtr->internalRep.dictSubstValue.varNameObjPtr =
4367 srcPtr->internalRep.dictSubstValue.varNameObjPtr;
4368 dupPtr->internalRep.dictSubstValue.indexObjPtr = srcPtr->internalRep.dictSubstValue.indexObjPtr;
4369 dupPtr->typePtr = &dictSubstObjType;
4372 /* Note: The object *must* be in dict-sugar format */
4373 static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
4375 if (objPtr->typePtr != &dictSubstObjType) {
4376 Jim_Obj *varObjPtr, *keyObjPtr;
4378 if (objPtr->typePtr == &interpolatedObjType) {
4379 /* An interpolated object in dict-sugar form */
4381 const ScriptToken *token = objPtr->internalRep.twoPtrValue.ptr1;
4383 varObjPtr = token[0].objPtr;
4384 keyObjPtr = objPtr->internalRep.twoPtrValue.ptr2;
4386 Jim_IncrRefCount(varObjPtr);
4387 Jim_IncrRefCount(keyObjPtr);
4389 else {
4390 JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
4393 Jim_FreeIntRep(interp, objPtr);
4394 objPtr->typePtr = &dictSubstObjType;
4395 objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
4396 objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
4400 /* This function is used to expand [dict get] sugar in the form
4401 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4402 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4403 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4404 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4405 * the [dict]ionary contained in variable VARNAME. */
4406 static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
4408 Jim_Obj *resObjPtr = NULL;
4409 Jim_Obj *substKeyObjPtr = NULL;
4411 SetDictSubstFromAny(interp, objPtr);
4413 if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
4414 &substKeyObjPtr, JIM_NONE)
4415 != JIM_OK) {
4416 return NULL;
4418 Jim_IncrRefCount(substKeyObjPtr);
4419 resObjPtr =
4420 JimDictExpandArrayVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
4421 substKeyObjPtr, 0);
4422 Jim_DecrRefCount(interp, substKeyObjPtr);
4424 return resObjPtr;
4427 static Jim_Obj *JimExpandExprSugar(Jim_Interp *interp, Jim_Obj *objPtr)
4429 Jim_Obj *resultObjPtr;
4431 if (Jim_EvalExpression(interp, objPtr, &resultObjPtr) == JIM_OK) {
4432 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4433 resultObjPtr->refCount--;
4434 return resultObjPtr;
4436 return NULL;
4439 /* -----------------------------------------------------------------------------
4440 * CallFrame
4441 * ---------------------------------------------------------------------------*/
4443 static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp, Jim_CallFrame *parent)
4445 Jim_CallFrame *cf;
4447 if (interp->freeFramesList) {
4448 cf = interp->freeFramesList;
4449 interp->freeFramesList = cf->nextFramePtr;
4451 else {
4452 cf = Jim_Alloc(sizeof(*cf));
4453 cf->vars.table = NULL;
4456 cf->id = interp->callFrameEpoch++;
4457 cf->parentCallFrame = parent;
4458 cf->level = parent ? parent->level + 1 : 0;
4459 cf->argv = NULL;
4460 cf->argc = 0;
4461 cf->procArgsObjPtr = NULL;
4462 cf->procBodyObjPtr = NULL;
4463 cf->nextFramePtr = NULL;
4464 cf->staticVars = NULL;
4465 if (cf->vars.table == NULL)
4466 Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
4467 return cf;
4470 /* Used to invalidate every caching related to callframe stability. */
4471 static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf)
4473 cf->id = interp->callFrameEpoch++;
4476 #define JIM_FCF_NONE 0 /* no flags */
4477 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4478 static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags)
4480 if (cf->procArgsObjPtr)
4481 Jim_DecrRefCount(interp, cf->procArgsObjPtr);
4482 if (cf->procBodyObjPtr)
4483 Jim_DecrRefCount(interp, cf->procBodyObjPtr);
4484 if (!(flags & JIM_FCF_NOHT))
4485 Jim_FreeHashTable(&cf->vars);
4486 else {
4487 int i;
4488 Jim_HashEntry **table = cf->vars.table, *he;
4490 for (i = 0; i < JIM_HT_INITIAL_SIZE; i++) {
4491 he = table[i];
4492 while (he != NULL) {
4493 Jim_HashEntry *nextEntry = he->next;
4494 Jim_Var *varPtr = (void *)he->u.val;
4496 Jim_DecrRefCount(interp, varPtr->objPtr);
4497 Jim_Free(he->u.val);
4498 Jim_Free((void *)he->key); /* ATTENTION: const cast */
4499 Jim_Free(he);
4500 table[i] = NULL;
4501 he = nextEntry;
4504 cf->vars.used = 0;
4506 cf->nextFramePtr = interp->freeFramesList;
4507 interp->freeFramesList = cf;
4510 /* -----------------------------------------------------------------------------
4511 * References
4512 * ---------------------------------------------------------------------------*/
4513 #ifdef JIM_REFERENCES
4515 /* References HashTable Type.
4517 * Keys are jim_wide integers, dynamically allocated for now but in the
4518 * future it's worth to cache this 8 bytes objects. Values are poitners
4519 * to Jim_References. */
4520 static void JimReferencesHTValDestructor(void *interp, void *val)
4522 Jim_Reference *refPtr = (void *)val;
4524 Jim_DecrRefCount(interp, refPtr->objPtr);
4525 if (refPtr->finalizerCmdNamePtr != NULL) {
4526 Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
4528 Jim_Free(val);
4531 static unsigned int JimReferencesHTHashFunction(const void *key)
4533 /* Only the least significant bits are used. */
4534 const jim_wide *widePtr = key;
4535 unsigned int intValue = (unsigned int)*widePtr;
4537 return Jim_IntHashFunction(intValue);
4540 static void *JimReferencesHTKeyDup(void *privdata, const void *key)
4542 void *copy = Jim_Alloc(sizeof(jim_wide));
4544 JIM_NOTUSED(privdata);
4546 memcpy(copy, key, sizeof(jim_wide));
4547 return copy;
4550 static int JimReferencesHTKeyCompare(void *privdata, const void *key1, const void *key2)
4552 JIM_NOTUSED(privdata);
4554 return memcmp(key1, key2, sizeof(jim_wide)) == 0;
4557 static void JimReferencesHTKeyDestructor(void *privdata, void *key)
4559 JIM_NOTUSED(privdata);
4561 Jim_Free(key);
4564 static const Jim_HashTableType JimReferencesHashTableType = {
4565 JimReferencesHTHashFunction, /* hash function */
4566 JimReferencesHTKeyDup, /* key dup */
4567 NULL, /* val dup */
4568 JimReferencesHTKeyCompare, /* key compare */
4569 JimReferencesHTKeyDestructor, /* key destructor */
4570 JimReferencesHTValDestructor /* val destructor */
4573 /* -----------------------------------------------------------------------------
4574 * Reference object type and References API
4575 * ---------------------------------------------------------------------------*/
4577 /* The string representation of references has two features in order
4578 * to make the GC faster. The first is that every reference starts
4579 * with a non common character '<', in order to make the string matching
4580 * faster. The second is that the reference string rep is 42 characters
4581 * in length, this allows to avoid to check every object with a string
4582 * repr < 42, and usually there aren't many of these objects. */
4584 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4586 static int JimFormatReference(char *buf, Jim_Reference *refPtr, jim_wide id)
4588 const char *fmt = "<reference.<%s>.%020" JIM_WIDE_MODIFIER ">";
4590 sprintf(buf, fmt, refPtr->tag, id);
4591 return JIM_REFERENCE_SPACE;
4594 static void UpdateStringOfReference(struct Jim_Obj *objPtr);
4596 static const Jim_ObjType referenceObjType = {
4597 "reference",
4598 NULL,
4599 NULL,
4600 UpdateStringOfReference,
4601 JIM_TYPE_REFERENCES,
4604 void UpdateStringOfReference(struct Jim_Obj *objPtr)
4606 int len;
4607 char buf[JIM_REFERENCE_SPACE + 1];
4608 Jim_Reference *refPtr;
4610 refPtr = objPtr->internalRep.refValue.refPtr;
4611 len = JimFormatReference(buf, refPtr, objPtr->internalRep.refValue.id);
4612 objPtr->bytes = Jim_Alloc(len + 1);
4613 memcpy(objPtr->bytes, buf, len + 1);
4614 objPtr->length = len;
4617 /* returns true if 'c' is a valid reference tag character.
4618 * i.e. inside the range [_a-zA-Z0-9] */
4619 static int isrefchar(int c)
4621 return (c == '_' || isalnum(c));
4624 static int SetReferenceFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
4626 jim_wide wideValue;
4627 int i, len;
4628 const char *str, *start, *end;
4629 char refId[21];
4630 Jim_Reference *refPtr;
4631 Jim_HashEntry *he;
4633 /* Get the string representation */
4634 str = Jim_GetString(objPtr, &len);
4635 /* Check if it looks like a reference */
4636 if (len < JIM_REFERENCE_SPACE)
4637 goto badformat;
4638 /* Trim spaces */
4639 start = str;
4640 end = str + len - 1;
4641 while (*start == ' ')
4642 start++;
4643 while (*end == ' ' && end > start)
4644 end--;
4645 if (end - start + 1 != JIM_REFERENCE_SPACE)
4646 goto badformat;
4647 /* <reference.<1234567>.%020> */
4648 if (memcmp(start, "<reference.<", 12) != 0)
4649 goto badformat;
4650 if (start[12 + JIM_REFERENCE_TAGLEN] != '>' || end[0] != '>')
4651 goto badformat;
4652 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4653 for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
4654 if (!isrefchar(start[12 + i]))
4655 goto badformat;
4657 /* Extract info from the reference. */
4658 memcpy(refId, start + 14 + JIM_REFERENCE_TAGLEN, 20);
4659 refId[20] = '\0';
4660 /* Try to convert the ID into a jim_wide */
4661 if (Jim_StringToWide(refId, &wideValue, 10) != JIM_OK)
4662 goto badformat;
4663 /* Check if the reference really exists! */
4664 he = Jim_FindHashEntry(&interp->references, &wideValue);
4665 if (he == NULL) {
4666 Jim_SetResultFormatted(interp, "invalid reference id \"%#s\"", objPtr);
4667 return JIM_ERR;
4669 refPtr = he->u.val;
4670 /* Free the old internal repr and set the new one. */
4671 Jim_FreeIntRep(interp, objPtr);
4672 objPtr->typePtr = &referenceObjType;
4673 objPtr->internalRep.refValue.id = wideValue;
4674 objPtr->internalRep.refValue.refPtr = refPtr;
4675 return JIM_OK;
4677 badformat:
4678 Jim_SetResultFormatted(interp, "expected reference but got \"%#s\"", objPtr);
4679 return JIM_ERR;
4682 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4683 * as finalizer command (or NULL if there is no finalizer).
4684 * The returned reference object has refcount = 0. */
4685 Jim_Obj *Jim_NewReference(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr)
4687 struct Jim_Reference *refPtr;
4688 jim_wide wideValue = interp->referenceNextId;
4689 Jim_Obj *refObjPtr;
4690 const char *tag;
4691 int tagLen, i;
4693 /* Perform the Garbage Collection if needed. */
4694 Jim_CollectIfNeeded(interp);
4696 refPtr = Jim_Alloc(sizeof(*refPtr));
4697 refPtr->objPtr = objPtr;
4698 Jim_IncrRefCount(objPtr);
4699 refPtr->finalizerCmdNamePtr = cmdNamePtr;
4700 if (cmdNamePtr)
4701 Jim_IncrRefCount(cmdNamePtr);
4702 Jim_AddHashEntry(&interp->references, &wideValue, refPtr);
4703 refObjPtr = Jim_NewObj(interp);
4704 refObjPtr->typePtr = &referenceObjType;
4705 refObjPtr->bytes = NULL;
4706 refObjPtr->internalRep.refValue.id = interp->referenceNextId;
4707 refObjPtr->internalRep.refValue.refPtr = refPtr;
4708 interp->referenceNextId++;
4709 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4710 * that does not pass the 'isrefchar' test is replaced with '_' */
4711 tag = Jim_GetString(tagPtr, &tagLen);
4712 if (tagLen > JIM_REFERENCE_TAGLEN)
4713 tagLen = JIM_REFERENCE_TAGLEN;
4714 for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
4715 if (i < tagLen && isrefchar(tag[i]))
4716 refPtr->tag[i] = tag[i];
4717 else
4718 refPtr->tag[i] = '_';
4720 refPtr->tag[JIM_REFERENCE_TAGLEN] = '\0';
4721 return refObjPtr;
4724 Jim_Reference *Jim_GetReference(Jim_Interp *interp, Jim_Obj *objPtr)
4726 if (objPtr->typePtr != &referenceObjType && SetReferenceFromAny(interp, objPtr) == JIM_ERR)
4727 return NULL;
4728 return objPtr->internalRep.refValue.refPtr;
4731 int Jim_SetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr)
4733 Jim_Reference *refPtr;
4735 if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
4736 return JIM_ERR;
4737 Jim_IncrRefCount(cmdNamePtr);
4738 if (refPtr->finalizerCmdNamePtr)
4739 Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
4740 refPtr->finalizerCmdNamePtr = cmdNamePtr;
4741 return JIM_OK;
4744 int Jim_GetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr)
4746 Jim_Reference *refPtr;
4748 if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
4749 return JIM_ERR;
4750 *cmdNamePtrPtr = refPtr->finalizerCmdNamePtr;
4751 return JIM_OK;
4754 /* -----------------------------------------------------------------------------
4755 * References Garbage Collection
4756 * ---------------------------------------------------------------------------*/
4758 /* This the hash table type for the "MARK" phase of the GC */
4759 static const Jim_HashTableType JimRefMarkHashTableType = {
4760 JimReferencesHTHashFunction, /* hash function */
4761 JimReferencesHTKeyDup, /* key dup */
4762 NULL, /* val dup */
4763 JimReferencesHTKeyCompare, /* key compare */
4764 JimReferencesHTKeyDestructor, /* key destructor */
4765 NULL /* val destructor */
4768 /* Performs the garbage collection. */
4769 int Jim_Collect(Jim_Interp *interp)
4771 int collected = 0;
4772 #ifndef JIM_BOOTSTRAP
4773 Jim_HashTable marks;
4774 Jim_HashTableIterator *htiter;
4775 Jim_HashEntry *he;
4776 Jim_Obj *objPtr;
4778 /* Avoid recursive calls */
4779 if (interp->lastCollectId == -1) {
4780 /* Jim_Collect() already running. Return just now. */
4781 return 0;
4783 interp->lastCollectId = -1;
4785 /* Mark all the references found into the 'mark' hash table.
4786 * The references are searched in every live object that
4787 * is of a type that can contain references. */
4788 Jim_InitHashTable(&marks, &JimRefMarkHashTableType, NULL);
4789 objPtr = interp->liveList;
4790 while (objPtr) {
4791 if (objPtr->typePtr == NULL || objPtr->typePtr->flags & JIM_TYPE_REFERENCES) {
4792 const char *str, *p;
4793 int len;
4795 /* If the object is of type reference, to get the
4796 * Id is simple... */
4797 if (objPtr->typePtr == &referenceObjType) {
4798 Jim_AddHashEntry(&marks, &objPtr->internalRep.refValue.id, NULL);
4799 #ifdef JIM_DEBUG_GC
4800 printf("MARK (reference): %d refcount: %d" JIM_NL,
4801 (int)objPtr->internalRep.refValue.id, objPtr->refCount);
4802 #endif
4803 objPtr = objPtr->nextObjPtr;
4804 continue;
4806 /* Get the string repr of the object we want
4807 * to scan for references. */
4808 p = str = Jim_GetString(objPtr, &len);
4809 /* Skip objects too little to contain references. */
4810 if (len < JIM_REFERENCE_SPACE) {
4811 objPtr = objPtr->nextObjPtr;
4812 continue;
4814 /* Extract references from the object string repr. */
4815 while (1) {
4816 int i;
4817 jim_wide id;
4818 char buf[21];
4820 if ((p = strstr(p, "<reference.<")) == NULL)
4821 break;
4822 /* Check if it's a valid reference. */
4823 if (len - (p - str) < JIM_REFERENCE_SPACE)
4824 break;
4825 if (p[41] != '>' || p[19] != '>' || p[20] != '.')
4826 break;
4827 for (i = 21; i <= 40; i++)
4828 if (!isdigit(UCHAR(p[i])))
4829 break;
4830 /* Get the ID */
4831 memcpy(buf, p + 21, 20);
4832 buf[20] = '\0';
4833 Jim_StringToWide(buf, &id, 10);
4835 /* Ok, a reference for the given ID
4836 * was found. Mark it. */
4837 Jim_AddHashEntry(&marks, &id, NULL);
4838 #ifdef JIM_DEBUG_GC
4839 printf("MARK: %d" JIM_NL, (int)id);
4840 #endif
4841 p += JIM_REFERENCE_SPACE;
4844 objPtr = objPtr->nextObjPtr;
4847 /* Run the references hash table to destroy every reference that
4848 * is not referenced outside (not present in the mark HT). */
4849 htiter = Jim_GetHashTableIterator(&interp->references);
4850 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
4851 const jim_wide *refId;
4852 Jim_Reference *refPtr;
4854 refId = he->key;
4855 /* Check if in the mark phase we encountered
4856 * this reference. */
4857 if (Jim_FindHashEntry(&marks, refId) == NULL) {
4858 #ifdef JIM_DEBUG_GC
4859 printf("COLLECTING %d" JIM_NL, (int)*refId);
4860 #endif
4861 collected++;
4862 /* Drop the reference, but call the
4863 * finalizer first if registered. */
4864 refPtr = he->u.val;
4865 if (refPtr->finalizerCmdNamePtr) {
4866 char *refstr = Jim_Alloc(JIM_REFERENCE_SPACE + 1);
4867 Jim_Obj *objv[3], *oldResult;
4869 JimFormatReference(refstr, refPtr, *refId);
4871 objv[0] = refPtr->finalizerCmdNamePtr;
4872 objv[1] = Jim_NewStringObjNoAlloc(interp, refstr, 32);
4873 objv[2] = refPtr->objPtr;
4874 Jim_IncrRefCount(objv[0]);
4875 Jim_IncrRefCount(objv[1]);
4876 Jim_IncrRefCount(objv[2]);
4878 /* Drop the reference itself */
4879 Jim_DeleteHashEntry(&interp->references, refId);
4881 /* Call the finalizer. Errors ignored. */
4882 oldResult = interp->result;
4883 Jim_IncrRefCount(oldResult);
4884 Jim_EvalObjVector(interp, 3, objv);
4885 Jim_SetResult(interp, oldResult);
4886 Jim_DecrRefCount(interp, oldResult);
4888 Jim_DecrRefCount(interp, objv[0]);
4889 Jim_DecrRefCount(interp, objv[1]);
4890 Jim_DecrRefCount(interp, objv[2]);
4892 else {
4893 Jim_DeleteHashEntry(&interp->references, refId);
4897 Jim_FreeHashTableIterator(htiter);
4898 Jim_FreeHashTable(&marks);
4899 interp->lastCollectId = interp->referenceNextId;
4900 interp->lastCollectTime = time(NULL);
4901 #endif /* JIM_BOOTSTRAP */
4902 return collected;
4905 #define JIM_COLLECT_ID_PERIOD 5000
4906 #define JIM_COLLECT_TIME_PERIOD 300
4908 void Jim_CollectIfNeeded(Jim_Interp *interp)
4910 jim_wide elapsedId;
4911 int elapsedTime;
4913 elapsedId = interp->referenceNextId - interp->lastCollectId;
4914 elapsedTime = time(NULL) - interp->lastCollectTime;
4917 if (elapsedId > JIM_COLLECT_ID_PERIOD || elapsedTime > JIM_COLLECT_TIME_PERIOD) {
4918 Jim_Collect(interp);
4921 #endif
4923 static int JimIsBigEndian(void)
4925 union {
4926 unsigned short s;
4927 unsigned char c[2];
4928 } uval = {0x0102};
4930 return uval.c[0] == 1;
4933 /* -----------------------------------------------------------------------------
4934 * Interpreter related functions
4935 * ---------------------------------------------------------------------------*/
4937 Jim_Interp *Jim_CreateInterp(void)
4939 Jim_Interp *i = Jim_Alloc(sizeof(*i));
4941 memset(i, 0, sizeof(*i));
4943 i->maxNestingDepth = JIM_MAX_NESTING_DEPTH;
4944 i->lastCollectTime = time(NULL);
4946 /* Note that we can create objects only after the
4947 * interpreter liveList and freeList pointers are
4948 * initialized to NULL. */
4949 Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
4950 #ifdef JIM_REFERENCES
4951 Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
4952 #endif
4953 Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
4954 Jim_InitHashTable(&i->packages, &JimPackageHashTableType, NULL);
4955 i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL);
4956 i->emptyObj = Jim_NewEmptyStringObj(i);
4957 i->trueObj = Jim_NewIntObj(i, 1);
4958 i->falseObj = Jim_NewIntObj(i, 0);
4959 i->errorFileNameObj = i->emptyObj;
4960 i->result = i->emptyObj;
4961 i->stackTrace = Jim_NewListObj(i, NULL, 0);
4962 i->unknown = Jim_NewStringObj(i, "unknown", -1);
4963 i->errorProc = i->emptyObj;
4964 i->currentScriptObj = Jim_NewEmptyStringObj(i);
4965 Jim_IncrRefCount(i->emptyObj);
4966 Jim_IncrRefCount(i->errorFileNameObj);
4967 Jim_IncrRefCount(i->result);
4968 Jim_IncrRefCount(i->stackTrace);
4969 Jim_IncrRefCount(i->unknown);
4970 Jim_IncrRefCount(i->currentScriptObj);
4971 Jim_IncrRefCount(i->errorProc);
4972 Jim_IncrRefCount(i->trueObj);
4973 Jim_IncrRefCount(i->falseObj);
4975 /* Initialize key variables every interpreter should contain */
4976 Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
4977 Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
4979 Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
4980 Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
4981 Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
4982 Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4983 Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
4984 Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
4985 Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
4987 return i;
4990 void Jim_FreeInterp(Jim_Interp *i)
4992 Jim_CallFrame *cf = i->framePtr, *prevcf, *nextcf;
4993 Jim_Obj *objPtr, *nextObjPtr;
4995 Jim_DecrRefCount(i, i->emptyObj);
4996 Jim_DecrRefCount(i, i->trueObj);
4997 Jim_DecrRefCount(i, i->falseObj);
4998 Jim_DecrRefCount(i, i->result);
4999 Jim_DecrRefCount(i, i->stackTrace);
5000 Jim_DecrRefCount(i, i->errorProc);
5001 Jim_DecrRefCount(i, i->unknown);
5002 Jim_DecrRefCount(i, i->errorFileNameObj);
5003 Jim_DecrRefCount(i, i->currentScriptObj);
5004 Jim_FreeHashTable(&i->commands);
5005 #ifdef JIM_REFERENCES
5006 Jim_FreeHashTable(&i->references);
5007 #endif
5008 Jim_FreeHashTable(&i->packages);
5009 Jim_Free(i->prngState);
5010 Jim_FreeHashTable(&i->assocData);
5011 JimDeleteLocalProcs(i);
5013 /* Free the call frames list */
5014 while (cf) {
5015 prevcf = cf->parentCallFrame;
5016 JimFreeCallFrame(i, cf, JIM_FCF_NONE);
5017 cf = prevcf;
5019 /* Check that the live object list is empty, otherwise
5020 * there is a memory leak. */
5021 if (i->liveList != NULL) {
5022 objPtr = i->liveList;
5024 printf(JIM_NL "-------------------------------------" JIM_NL);
5025 printf("Objects still in the free list:" JIM_NL);
5026 while (objPtr) {
5027 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
5029 printf("%p (%d) %-10s: '%.20s'" JIM_NL,
5030 (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
5031 if (objPtr->typePtr == &sourceObjType) {
5032 printf("FILE %s LINE %d" JIM_NL,
5033 Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
5034 objPtr->internalRep.sourceValue.lineNumber);
5036 objPtr = objPtr->nextObjPtr;
5038 printf("-------------------------------------" JIM_NL JIM_NL);
5039 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5041 /* Free all the freed objects. */
5042 objPtr = i->freeList;
5043 while (objPtr) {
5044 nextObjPtr = objPtr->nextObjPtr;
5045 Jim_Free(objPtr);
5046 objPtr = nextObjPtr;
5048 /* Free cached CallFrame structures */
5049 cf = i->freeFramesList;
5050 while (cf) {
5051 nextcf = cf->nextFramePtr;
5052 if (cf->vars.table != NULL)
5053 Jim_Free(cf->vars.table);
5054 Jim_Free(cf);
5055 cf = nextcf;
5057 #ifdef jim_ext_load
5058 Jim_FreeLoadHandles(i);
5059 #endif
5061 /* Free the interpreter structure. */
5062 Jim_Free(i);
5065 /* Returns the call frame relative to the level represented by
5066 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5068 * This function accepts the 'level' argument in the form
5069 * of the commands [uplevel] and [upvar].
5071 * For a function accepting a relative integer as level suitable
5072 * for implementation of [info level ?level?] check the
5073 * JimGetCallFrameByInteger() function.
5075 * Returns NULL on error.
5077 Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5079 long level;
5080 const char *str;
5081 Jim_CallFrame *framePtr;
5083 if (levelObjPtr) {
5084 str = Jim_String(levelObjPtr);
5085 if (str[0] == '#') {
5086 char *endptr;
5088 level = strtol(str + 1, &endptr, 0);
5089 if (str[1] == '\0' || endptr[0] != '\0') {
5090 level = -1;
5093 else {
5094 if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
5095 level = -1;
5097 else {
5098 /* Convert from a relative to an absolute level */
5099 level = interp->framePtr->level - level;
5103 else {
5104 str = "1"; /* Needed to format the error message. */
5105 level = interp->framePtr->level - 1;
5108 if (level == 0) {
5109 return interp->topFramePtr;
5111 if (level > 0) {
5112 /* Lookup */
5113 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5114 if (framePtr->level == level) {
5115 return framePtr;
5120 Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
5121 return NULL;
5124 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5125 * as a relative integer like in the [info level ?level?] command.
5127 static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5129 long level;
5130 Jim_CallFrame *framePtr;
5132 if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
5133 if (level <= 0) {
5134 /* Convert from a relative to an absolute level */
5135 level = interp->framePtr->level + level;
5138 if (level == 0) {
5139 return interp->topFramePtr;
5142 /* Lookup */
5143 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5144 if (framePtr->level == level) {
5145 return framePtr;
5150 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
5151 return NULL;
5154 static void JimResetStackTrace(Jim_Interp *interp)
5156 Jim_DecrRefCount(interp, interp->stackTrace);
5157 interp->stackTrace = Jim_NewListObj(interp, NULL, 0);
5158 Jim_IncrRefCount(interp->stackTrace);
5161 static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
5163 int len;
5165 /* Increment reference first in case these are the same object */
5166 Jim_IncrRefCount(stackTraceObj);
5167 Jim_DecrRefCount(interp, interp->stackTrace);
5168 interp->stackTrace = stackTraceObj;
5169 interp->errorFlag = 1;
5171 /* This is a bit ugly.
5172 * If the filename of the last entry of the stack trace is empty,
5173 * the next stack level should be added.
5175 len = Jim_ListLength(interp, interp->stackTrace);
5176 if (len >= 3) {
5177 Jim_Obj *filenameObj;
5179 Jim_ListIndex(interp, interp->stackTrace, len - 2, &filenameObj, JIM_NONE);
5181 Jim_GetString(filenameObj, &len);
5183 if (!Jim_Length(filenameObj)) {
5184 interp->addStackTrace = 1;
5189 /* Returns 1 if the stack trace information was used or 0 if not */
5190 static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,
5191 Jim_Obj *fileNameObj, int linenr)
5193 if (strcmp(procname, "unknown") == 0) {
5194 procname = "";
5196 if (!*procname && !Jim_Length(fileNameObj)) {
5197 /* No useful info here */
5198 return;
5201 if (Jim_IsShared(interp->stackTrace)) {
5202 Jim_DecrRefCount(interp, interp->stackTrace);
5203 interp->stackTrace = Jim_DuplicateObj(interp, interp->stackTrace);
5204 Jim_IncrRefCount(interp->stackTrace);
5207 /* If we have no procname but the previous element did, merge with that frame */
5208 if (!*procname && Jim_Length(fileNameObj)) {
5209 /* Just a filename. Check the previous entry */
5210 int len = Jim_ListLength(interp, interp->stackTrace);
5212 if (len >= 3) {
5213 Jim_Obj *objPtr;
5214 if (Jim_ListIndex(interp, interp->stackTrace, len - 3, &objPtr, JIM_NONE) == JIM_OK && Jim_Length(objPtr)) {
5215 /* Yes, the previous level had procname */
5216 if (Jim_ListIndex(interp, interp->stackTrace, len - 2, &objPtr, JIM_NONE) == JIM_OK && !Jim_Length(objPtr)) {
5217 /* But no filename, so merge the new info with that frame */
5218 ListSetIndex(interp, interp->stackTrace, len - 2, fileNameObj, 0);
5219 ListSetIndex(interp, interp->stackTrace, len - 1, Jim_NewIntObj(interp, linenr), 0);
5220 return;
5226 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewStringObj(interp, procname, -1));
5227 Jim_ListAppendElement(interp, interp->stackTrace, fileNameObj);
5228 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewIntObj(interp, linenr));
5231 int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
5232 void *data)
5234 AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
5236 assocEntryPtr->delProc = delProc;
5237 assocEntryPtr->data = data;
5238 return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
5241 void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
5243 Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
5245 if (entryPtr != NULL) {
5246 AssocDataValue *assocEntryPtr = (AssocDataValue *) entryPtr->u.val;
5248 return assocEntryPtr->data;
5250 return NULL;
5253 int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
5255 return Jim_DeleteHashEntry(&interp->assocData, key);
5258 int Jim_GetExitCode(Jim_Interp *interp)
5260 return interp->exitCode;
5263 /* -----------------------------------------------------------------------------
5264 * Integer object
5265 * ---------------------------------------------------------------------------*/
5266 #define JIM_INTEGER_SPACE 24
5268 static void UpdateStringOfInt(struct Jim_Obj *objPtr);
5269 static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
5271 static const Jim_ObjType intObjType = {
5272 "int",
5273 NULL,
5274 NULL,
5275 UpdateStringOfInt,
5276 JIM_TYPE_NONE,
5279 /* A coerced double is closer to an int than a double.
5280 * It is an int value temporarily masquerading as a double value.
5281 * i.e. it has the same string value as an int and Jim_GetWide()
5282 * succeeds, but also Jim_GetDouble() returns the value directly.
5284 static const Jim_ObjType coercedDoubleObjType = {
5285 "coerced-double",
5286 NULL,
5287 NULL,
5288 UpdateStringOfInt,
5289 JIM_TYPE_NONE,
5293 void UpdateStringOfInt(struct Jim_Obj *objPtr)
5295 int len;
5296 char buf[JIM_INTEGER_SPACE + 1];
5298 len = Jim_WideToString(buf, JimWideValue(objPtr));
5299 objPtr->bytes = Jim_Alloc(len + 1);
5300 memcpy(objPtr->bytes, buf, len + 1);
5301 objPtr->length = len;
5304 int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
5306 jim_wide wideValue;
5307 const char *str;
5309 if (objPtr->typePtr == &coercedDoubleObjType) {
5310 /* Simple switcheroo */
5311 objPtr->typePtr = &intObjType;
5312 return JIM_OK;
5315 /* Get the string representation */
5316 str = Jim_String(objPtr);
5317 /* Try to convert into a jim_wide */
5318 if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
5319 if (flags & JIM_ERRMSG) {
5320 Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
5322 return JIM_ERR;
5324 if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
5325 Jim_SetResultString(interp, "Integer value too big to be represented", -1);
5326 return JIM_ERR;
5328 /* Free the old internal repr and set the new one. */
5329 Jim_FreeIntRep(interp, objPtr);
5330 objPtr->typePtr = &intObjType;
5331 objPtr->internalRep.wideValue = wideValue;
5332 return JIM_OK;
5335 #ifdef JIM_OPTIMIZATION
5336 static int JimIsWide(Jim_Obj *objPtr)
5338 return objPtr->typePtr == &intObjType;
5340 #endif
5342 int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5344 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
5345 return JIM_ERR;
5346 *widePtr = JimWideValue(objPtr);
5347 return JIM_OK;
5350 /* Get a wide but does not set an error if the format is bad. */
5351 static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5353 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
5354 return JIM_ERR;
5355 *widePtr = JimWideValue(objPtr);
5356 return JIM_OK;
5359 int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
5361 jim_wide wideValue;
5362 int retval;
5364 retval = Jim_GetWide(interp, objPtr, &wideValue);
5365 if (retval == JIM_OK) {
5366 *longPtr = (long)wideValue;
5367 return JIM_OK;
5369 return JIM_ERR;
5372 Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
5374 Jim_Obj *objPtr;
5376 objPtr = Jim_NewObj(interp);
5377 objPtr->typePtr = &intObjType;
5378 objPtr->bytes = NULL;
5379 objPtr->internalRep.wideValue = wideValue;
5380 return objPtr;
5383 /* -----------------------------------------------------------------------------
5384 * Double object
5385 * ---------------------------------------------------------------------------*/
5386 #define JIM_DOUBLE_SPACE 30
5388 static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
5389 static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
5391 static const Jim_ObjType doubleObjType = {
5392 "double",
5393 NULL,
5394 NULL,
5395 UpdateStringOfDouble,
5396 JIM_TYPE_NONE,
5399 void UpdateStringOfDouble(struct Jim_Obj *objPtr)
5401 int len;
5402 char buf[JIM_DOUBLE_SPACE + 1];
5404 len = Jim_DoubleToString(buf, objPtr->internalRep.doubleValue);
5405 objPtr->bytes = Jim_Alloc(len + 1);
5406 memcpy(objPtr->bytes, buf, len + 1);
5407 objPtr->length = len;
5410 int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
5412 double doubleValue;
5413 jim_wide wideValue;
5414 const char *str;
5416 /* Preserve the string representation.
5417 * Needed so we can convert back to int without loss
5419 str = Jim_String(objPtr);
5421 #ifdef HAVE_LONG_LONG
5422 /* Assume a 53 bit mantissa */
5423 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5424 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5426 if (objPtr->typePtr == &intObjType
5427 && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
5428 && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
5430 /* Direct conversion to coerced double */
5431 objPtr->typePtr = &coercedDoubleObjType;
5432 return JIM_OK;
5434 else
5435 #endif
5436 if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
5437 /* Managed to convert to an int, so we can use this as a cooerced double */
5438 Jim_FreeIntRep(interp, objPtr);
5439 objPtr->typePtr = &coercedDoubleObjType;
5440 objPtr->internalRep.wideValue = wideValue;
5441 return JIM_OK;
5443 else {
5444 /* Try to convert into a double */
5445 if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
5446 Jim_SetResultFormatted(interp, "expected number but got \"%#s\"", objPtr);
5447 return JIM_ERR;
5449 /* Free the old internal repr and set the new one. */
5450 Jim_FreeIntRep(interp, objPtr);
5452 objPtr->typePtr = &doubleObjType;
5453 objPtr->internalRep.doubleValue = doubleValue;
5454 return JIM_OK;
5457 int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
5459 if (objPtr->typePtr == &coercedDoubleObjType) {
5460 *doublePtr = JimWideValue(objPtr);
5461 return JIM_OK;
5463 if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
5464 return JIM_ERR;
5466 if (objPtr->typePtr == &coercedDoubleObjType) {
5467 *doublePtr = JimWideValue(objPtr);
5469 else {
5470 *doublePtr = objPtr->internalRep.doubleValue;
5472 return JIM_OK;
5475 Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
5477 Jim_Obj *objPtr;
5479 objPtr = Jim_NewObj(interp);
5480 objPtr->typePtr = &doubleObjType;
5481 objPtr->bytes = NULL;
5482 objPtr->internalRep.doubleValue = doubleValue;
5483 return objPtr;
5486 /* -----------------------------------------------------------------------------
5487 * List object
5488 * ---------------------------------------------------------------------------*/
5489 static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec);
5490 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
5491 static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
5492 static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
5493 static void UpdateStringOfList(struct Jim_Obj *objPtr);
5494 static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
5496 /* Note that while the elements of the list may contain references,
5497 * the list object itself can't. This basically means that the
5498 * list object string representation as a whole can't contain references
5499 * that are not presents in the single elements. */
5500 static const Jim_ObjType listObjType = {
5501 "list",
5502 FreeListInternalRep,
5503 DupListInternalRep,
5504 UpdateStringOfList,
5505 JIM_TYPE_NONE,
5508 void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
5510 int i;
5512 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5513 Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
5515 Jim_Free(objPtr->internalRep.listValue.ele);
5518 void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
5520 int i;
5522 JIM_NOTUSED(interp);
5524 dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
5525 dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
5526 dupPtr->internalRep.listValue.ele =
5527 Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
5528 memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
5529 sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
5530 for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
5531 Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
5533 dupPtr->typePtr = &listObjType;
5536 /* The following function checks if a given string can be encoded
5537 * into a list element without any kind of quoting, surrounded by braces,
5538 * or using escapes to quote. */
5539 #define JIM_ELESTR_SIMPLE 0
5540 #define JIM_ELESTR_BRACE 1
5541 #define JIM_ELESTR_QUOTE 2
5542 static int ListElementQuotingType(const char *s, int len)
5544 int i, level, blevel, trySimple = 1;
5546 /* Try with the SIMPLE case */
5547 if (len == 0)
5548 return JIM_ELESTR_BRACE;
5549 if (s[0] == '"' || s[0] == '{') {
5550 trySimple = 0;
5551 goto testbrace;
5553 for (i = 0; i < len; i++) {
5554 switch (s[i]) {
5555 case ' ':
5556 case '$':
5557 case '"':
5558 case '[':
5559 case ']':
5560 case ';':
5561 case '\\':
5562 case '\r':
5563 case '\n':
5564 case '\t':
5565 case '\f':
5566 case '\v':
5567 trySimple = 0;
5568 case '{':
5569 case '}':
5570 goto testbrace;
5573 return JIM_ELESTR_SIMPLE;
5575 testbrace:
5576 /* Test if it's possible to do with braces */
5577 if (s[len - 1] == '\\')
5578 return JIM_ELESTR_QUOTE;
5579 level = 0;
5580 blevel = 0;
5581 for (i = 0; i < len; i++) {
5582 switch (s[i]) {
5583 case '{':
5584 level++;
5585 break;
5586 case '}':
5587 level--;
5588 if (level < 0)
5589 return JIM_ELESTR_QUOTE;
5590 break;
5591 case '[':
5592 blevel++;
5593 break;
5594 case ']':
5595 blevel--;
5596 break;
5597 case '\\':
5598 if (s[i + 1] == '\n')
5599 return JIM_ELESTR_QUOTE;
5600 else if (s[i + 1] != '\0')
5601 i++;
5602 break;
5605 if (blevel < 0) {
5606 return JIM_ELESTR_QUOTE;
5609 if (level == 0) {
5610 if (!trySimple)
5611 return JIM_ELESTR_BRACE;
5612 for (i = 0; i < len; i++) {
5613 switch (s[i]) {
5614 case ' ':
5615 case '$':
5616 case '"':
5617 case '[':
5618 case ']':
5619 case ';':
5620 case '\\':
5621 case '\r':
5622 case '\n':
5623 case '\t':
5624 case '\f':
5625 case '\v':
5626 return JIM_ELESTR_BRACE;
5627 break;
5630 return JIM_ELESTR_SIMPLE;
5632 return JIM_ELESTR_QUOTE;
5635 /* Returns the malloc-ed representation of a string
5636 * using backslash to quote special chars. */
5637 static char *BackslashQuoteString(const char *s, int len, int *qlenPtr)
5639 char *q = Jim_Alloc(len * 2 + 1), *p;
5641 p = q;
5642 while (*s) {
5643 switch (*s) {
5644 case ' ':
5645 case '$':
5646 case '"':
5647 case '[':
5648 case ']':
5649 case '{':
5650 case '}':
5651 case ';':
5652 case '\\':
5653 *p++ = '\\';
5654 *p++ = *s++;
5655 break;
5656 case '\n':
5657 *p++ = '\\';
5658 *p++ = 'n';
5659 s++;
5660 break;
5661 case '\r':
5662 *p++ = '\\';
5663 *p++ = 'r';
5664 s++;
5665 break;
5666 case '\t':
5667 *p++ = '\\';
5668 *p++ = 't';
5669 s++;
5670 break;
5671 case '\f':
5672 *p++ = '\\';
5673 *p++ = 'f';
5674 s++;
5675 break;
5676 case '\v':
5677 *p++ = '\\';
5678 *p++ = 'v';
5679 s++;
5680 break;
5681 default:
5682 *p++ = *s++;
5683 break;
5686 *p = '\0';
5687 *qlenPtr = p - q;
5688 return q;
5691 static void UpdateStringOfList(struct Jim_Obj *objPtr)
5693 int i, bufLen, realLength;
5694 const char *strRep;
5695 char *p;
5696 int *quotingType;
5697 Jim_Obj **ele = objPtr->internalRep.listValue.ele;
5699 /* (Over) Estimate the space needed. */
5700 quotingType = Jim_Alloc(sizeof(int) * objPtr->internalRep.listValue.len + 1);
5701 bufLen = 0;
5702 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5703 int len;
5705 strRep = Jim_GetString(ele[i], &len);
5706 quotingType[i] = ListElementQuotingType(strRep, len);
5707 switch (quotingType[i]) {
5708 case JIM_ELESTR_SIMPLE:
5709 if (i != 0 || strRep[0] != '#') {
5710 bufLen += len;
5711 break;
5713 /* Special case '#' on first element needs braces */
5714 quotingType[i] = JIM_ELESTR_BRACE;
5715 /* fall through */
5716 case JIM_ELESTR_BRACE:
5717 bufLen += len + 2;
5718 break;
5719 case JIM_ELESTR_QUOTE:
5720 bufLen += len * 2;
5721 break;
5723 bufLen++; /* elements separator. */
5725 bufLen++;
5727 /* Generate the string rep. */
5728 p = objPtr->bytes = Jim_Alloc(bufLen + 1);
5729 realLength = 0;
5730 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5731 int len, qlen;
5732 char *q;
5734 strRep = Jim_GetString(ele[i], &len);
5736 switch (quotingType[i]) {
5737 case JIM_ELESTR_SIMPLE:
5738 memcpy(p, strRep, len);
5739 p += len;
5740 realLength += len;
5741 break;
5742 case JIM_ELESTR_BRACE:
5743 *p++ = '{';
5744 memcpy(p, strRep, len);
5745 p += len;
5746 *p++ = '}';
5747 realLength += len + 2;
5748 break;
5749 case JIM_ELESTR_QUOTE:
5750 q = BackslashQuoteString(strRep, len, &qlen);
5751 memcpy(p, q, qlen);
5752 Jim_Free(q);
5753 p += qlen;
5754 realLength += qlen;
5755 break;
5757 /* Add a separating space */
5758 if (i + 1 != objPtr->internalRep.listValue.len) {
5759 *p++ = ' ';
5760 realLength++;
5763 *p = '\0'; /* nul term. */
5764 objPtr->length = realLength;
5765 Jim_Free(quotingType);
5768 static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
5770 struct JimParserCtx parser;
5771 const char *str;
5772 int strLen;
5773 Jim_Obj *fileNameObj;
5774 int linenr;
5776 #if 0
5777 /* Optimise dict -> list. XXX: Is it worth it? */
5778 if (Jim_IsDict(objPtr)) {
5779 Jim_Obj **listObjPtrPtr;
5780 int len;
5781 int i;
5783 Jim_DictPairs(interp, objPtr, &listObjPtrPtr, &len);
5784 for (i = 0; i < len; i++) {
5785 Jim_IncrRefCount(listObjPtrPtr[i]);
5788 /* Now just switch the internal rep */
5789 Jim_FreeIntRep(interp, objPtr);
5790 objPtr->typePtr = &listObjType;
5791 objPtr->internalRep.listValue.len = len;
5792 objPtr->internalRep.listValue.maxLen = len;
5793 objPtr->internalRep.listValue.ele = listObjPtrPtr;
5795 return JIM_OK;
5797 #endif
5799 /* Try to preserve information about filename / line number */
5800 if (objPtr->typePtr == &sourceObjType) {
5801 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
5802 linenr = objPtr->internalRep.sourceValue.lineNumber;
5804 else {
5805 fileNameObj = interp->emptyObj;
5806 linenr = 1;
5808 Jim_IncrRefCount(fileNameObj);
5810 /* Get the string representation */
5811 str = Jim_GetString(objPtr, &strLen);
5813 /* Free the old internal repr just now and initialize the
5814 * new one just now. The string->list conversion can't fail. */
5815 Jim_FreeIntRep(interp, objPtr);
5816 objPtr->typePtr = &listObjType;
5817 objPtr->internalRep.listValue.len = 0;
5818 objPtr->internalRep.listValue.maxLen = 0;
5819 objPtr->internalRep.listValue.ele = NULL;
5821 /* Convert into a list */
5822 JimParserInit(&parser, str, strLen, linenr);
5823 while (!parser.eof) {
5824 Jim_Obj *elementPtr;
5826 JimParseList(&parser);
5827 if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
5828 continue;
5829 elementPtr = JimParserGetTokenObj(interp, &parser);
5830 JimSetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
5831 ListAppendElement(objPtr, elementPtr);
5833 Jim_DecrRefCount(interp, fileNameObj);
5834 return JIM_OK;
5837 Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
5839 Jim_Obj *objPtr;
5841 objPtr = Jim_NewObj(interp);
5842 objPtr->typePtr = &listObjType;
5843 objPtr->bytes = NULL;
5844 objPtr->internalRep.listValue.ele = NULL;
5845 objPtr->internalRep.listValue.len = 0;
5846 objPtr->internalRep.listValue.maxLen = 0;
5848 if (len) {
5849 ListInsertElements(objPtr, 0, len, elements);
5852 return objPtr;
5855 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5856 * length of the vector. Note that the user of this function should make
5857 * sure that the list object can't shimmer while the vector returned
5858 * is in use, this vector is the one stored inside the internal representation
5859 * of the list object. This function is not exported, extensions should
5860 * always access to the List object elements using Jim_ListIndex(). */
5861 static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
5862 Jim_Obj ***listVec)
5864 *listLen = Jim_ListLength(interp, listObj);
5865 *listVec = listObj->internalRep.listValue.ele;
5868 /* Sorting uses ints, but commands may return wide */
5869 static int JimSign(jim_wide w)
5871 if (w == 0) {
5872 return 0;
5874 else if (w < 0) {
5875 return -1;
5877 return 1;
5880 /* ListSortElements type values */
5881 struct lsort_info {
5882 jmp_buf jmpbuf;
5883 Jim_Obj *command;
5884 Jim_Interp *interp;
5885 enum {
5886 JIM_LSORT_ASCII,
5887 JIM_LSORT_NOCASE,
5888 JIM_LSORT_INTEGER,
5889 JIM_LSORT_COMMAND
5890 } type;
5891 int order;
5892 int index;
5893 int indexed;
5894 int (*subfn)(Jim_Obj **, Jim_Obj **);
5897 static struct lsort_info *sort_info;
5899 static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5901 Jim_Obj *lObj, *rObj;
5903 if (Jim_ListIndex(sort_info->interp, *lhsObj, sort_info->index, &lObj, JIM_ERRMSG) != JIM_OK ||
5904 Jim_ListIndex(sort_info->interp, *rhsObj, sort_info->index, &rObj, JIM_ERRMSG) != JIM_OK) {
5905 longjmp(sort_info->jmpbuf, JIM_ERR);
5907 return sort_info->subfn(&lObj, &rObj);
5910 /* Sort the internal rep of a list. */
5911 static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5913 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
5916 static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5918 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
5921 static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5923 jim_wide lhs = 0, rhs = 0;
5925 if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
5926 Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
5927 longjmp(sort_info->jmpbuf, JIM_ERR);
5930 return JimSign(lhs - rhs) * sort_info->order;
5933 static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5935 Jim_Obj *compare_script;
5936 int rc;
5938 jim_wide ret = 0;
5940 /* This must be a valid list */
5941 compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
5942 Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
5943 Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
5945 rc = Jim_EvalObj(sort_info->interp, compare_script);
5947 if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
5948 longjmp(sort_info->jmpbuf, rc);
5951 return JimSign(ret) * sort_info->order;
5954 /* Sort a list *in place*. MUST be called with non-shared objects. */
5955 static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
5957 struct lsort_info *prev_info;
5959 typedef int (qsort_comparator) (const void *, const void *);
5960 int (*fn) (Jim_Obj **, Jim_Obj **);
5961 Jim_Obj **vector;
5962 int len;
5963 int rc;
5965 JimPanic((Jim_IsShared(listObjPtr), "Jim_ListSortElements called with shared object"));
5966 if (!Jim_IsList(listObjPtr))
5967 SetListFromAny(interp, listObjPtr);
5969 /* Allow lsort to be called reentrantly */
5970 prev_info = sort_info;
5971 sort_info = info;
5973 vector = listObjPtr->internalRep.listValue.ele;
5974 len = listObjPtr->internalRep.listValue.len;
5975 switch (info->type) {
5976 case JIM_LSORT_ASCII:
5977 fn = ListSortString;
5978 break;
5979 case JIM_LSORT_NOCASE:
5980 fn = ListSortStringNoCase;
5981 break;
5982 case JIM_LSORT_INTEGER:
5983 fn = ListSortInteger;
5984 break;
5985 case JIM_LSORT_COMMAND:
5986 fn = ListSortCommand;
5987 break;
5988 default:
5989 fn = NULL; /* avoid warning */
5990 JimPanic((1, "ListSort called with invalid sort type"));
5993 if (info->indexed) {
5994 /* Need to interpose a "list index" function */
5995 info->subfn = fn;
5996 fn = ListSortIndexHelper;
5999 if ((rc = setjmp(info->jmpbuf)) == 0) {
6000 qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
6002 Jim_InvalidateStringRep(listObjPtr);
6003 sort_info = prev_info;
6005 return rc;
6008 /* This is the low-level function to insert elements into a list.
6009 * The higher-level Jim_ListInsertElements() performs shared object
6010 * check and invalidate the string repr. This version is used
6011 * in the internals of the List Object and is not exported.
6013 * NOTE: this function can be called only against objects
6014 * with internal type of List.
6016 * An insertion point (idx) of -1 means end-of-list.
6018 static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
6020 int currentLen = listPtr->internalRep.listValue.len;
6021 int requiredLen = currentLen + elemc;
6022 int i;
6023 Jim_Obj **point;
6025 if (requiredLen > listPtr->internalRep.listValue.maxLen) {
6026 listPtr->internalRep.listValue.maxLen = requiredLen * 2;
6028 listPtr->internalRep.listValue.ele = Jim_Realloc(listPtr->internalRep.listValue.ele,
6029 sizeof(Jim_Obj *) * listPtr->internalRep.listValue.maxLen);
6031 if (idx < 0) {
6032 idx = currentLen;
6034 point = listPtr->internalRep.listValue.ele + idx;
6035 memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
6036 for (i = 0; i < elemc; ++i) {
6037 point[i] = elemVec[i];
6038 Jim_IncrRefCount(point[i]);
6040 listPtr->internalRep.listValue.len += elemc;
6043 /* Convenience call to ListInsertElements() to append a single element.
6045 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
6047 ListInsertElements(listPtr, -1, 1, &objPtr);
6050 /* Appends every element of appendListPtr into listPtr.
6051 * Both have to be of the list type.
6052 * Convenience call to ListInsertElements()
6054 static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6056 ListInsertElements(listPtr, -1,
6057 appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
6060 void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
6062 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
6063 if (!Jim_IsList(listPtr))
6064 SetListFromAny(interp, listPtr);
6065 Jim_InvalidateStringRep(listPtr);
6066 ListAppendElement(listPtr, objPtr);
6069 void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6071 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
6072 if (!Jim_IsList(listPtr))
6073 SetListFromAny(interp, listPtr);
6074 Jim_InvalidateStringRep(listPtr);
6075 ListAppendList(listPtr, appendListPtr);
6078 int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
6080 if (!Jim_IsList(objPtr))
6081 SetListFromAny(interp, objPtr);
6082 return objPtr->internalRep.listValue.len;
6085 void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6086 int objc, Jim_Obj *const *objVec)
6088 JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
6089 if (!Jim_IsList(listPtr))
6090 SetListFromAny(interp, listPtr);
6091 if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
6092 idx = listPtr->internalRep.listValue.len;
6093 else if (idx < 0)
6094 idx = 0;
6095 Jim_InvalidateStringRep(listPtr);
6096 ListInsertElements(listPtr, idx, objc, objVec);
6099 int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
6101 if (!Jim_IsList(listPtr))
6102 SetListFromAny(interp, listPtr);
6103 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6104 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6105 if (flags & JIM_ERRMSG) {
6106 Jim_SetResultString(interp, "list index out of range", -1);
6108 *objPtrPtr = NULL;
6109 return JIM_ERR;
6111 if (idx < 0)
6112 idx = listPtr->internalRep.listValue.len + idx;
6113 *objPtrPtr = listPtr->internalRep.listValue.ele[idx];
6114 return JIM_OK;
6117 static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6118 Jim_Obj *newObjPtr, int flags)
6120 if (!Jim_IsList(listPtr))
6121 SetListFromAny(interp, listPtr);
6122 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6123 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6124 if (flags & JIM_ERRMSG) {
6125 Jim_SetResultString(interp, "list index out of range", -1);
6127 return JIM_ERR;
6129 if (idx < 0)
6130 idx = listPtr->internalRep.listValue.len + idx;
6131 Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
6132 listPtr->internalRep.listValue.ele[idx] = newObjPtr;
6133 Jim_IncrRefCount(newObjPtr);
6134 return JIM_OK;
6137 /* Modify the list stored into the variable named 'varNamePtr'
6138 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6139 * with the new element 'newObjptr'. */
6140 int Jim_SetListIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
6141 Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
6143 Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
6144 int shared, i, idx;
6146 varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
6147 if (objPtr == NULL)
6148 return JIM_ERR;
6149 if ((shared = Jim_IsShared(objPtr)))
6150 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6151 for (i = 0; i < indexc - 1; i++) {
6152 listObjPtr = objPtr;
6153 if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
6154 goto err;
6155 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_ERRMSG) != JIM_OK) {
6156 goto err;
6158 if (Jim_IsShared(objPtr)) {
6159 objPtr = Jim_DuplicateObj(interp, objPtr);
6160 ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
6162 Jim_InvalidateStringRep(listObjPtr);
6164 if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
6165 goto err;
6166 if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
6167 goto err;
6168 Jim_InvalidateStringRep(objPtr);
6169 Jim_InvalidateStringRep(varObjPtr);
6170 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
6171 goto err;
6172 Jim_SetResult(interp, varObjPtr);
6173 return JIM_OK;
6174 err:
6175 if (shared) {
6176 Jim_FreeNewObj(interp, varObjPtr);
6178 return JIM_ERR;
6181 Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
6183 int i;
6185 /* If all the objects in objv are lists,
6186 * it's possible to return a list as result, that's the
6187 * concatenation of all the lists. */
6188 for (i = 0; i < objc; i++) {
6189 if (!Jim_IsList(objv[i]))
6190 break;
6192 if (i == objc) {
6193 Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
6195 for (i = 0; i < objc; i++)
6196 ListAppendList(objPtr, objv[i]);
6197 return objPtr;
6199 else {
6200 /* Else... we have to glue strings together */
6201 int len = 0, objLen;
6202 char *bytes, *p;
6204 /* Compute the length */
6205 for (i = 0; i < objc; i++) {
6206 Jim_GetString(objv[i], &objLen);
6207 len += objLen;
6209 if (objc)
6210 len += objc - 1;
6211 /* Create the string rep, and a string object holding it. */
6212 p = bytes = Jim_Alloc(len + 1);
6213 for (i = 0; i < objc; i++) {
6214 const char *s = Jim_GetString(objv[i], &objLen);
6216 /* Remove leading space */
6217 while (objLen && (*s == ' ' || *s == '\t' || *s == '\n')) {
6218 s++;
6219 objLen--;
6220 len--;
6222 /* And trailing space */
6223 while (objLen && (s[objLen - 1] == ' ' ||
6224 s[objLen - 1] == '\n' || s[objLen - 1] == '\t')) {
6225 /* Handle trailing backslash-space case */
6226 if (objLen > 1 && s[objLen - 2] == '\\') {
6227 break;
6229 objLen--;
6230 len--;
6232 memcpy(p, s, objLen);
6233 p += objLen;
6234 if (objLen && i + 1 != objc) {
6235 *p++ = ' ';
6237 else if (i + 1 != objc) {
6238 /* Drop the space calcuated for this
6239 * element that is instead null. */
6240 len--;
6243 *p = '\0';
6244 return Jim_NewStringObjNoAlloc(interp, bytes, len);
6248 /* Returns a list composed of the elements in the specified range.
6249 * first and start are directly accepted as Jim_Objects and
6250 * processed for the end?-index? case. */
6251 Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
6252 Jim_Obj *lastObjPtr)
6254 int first, last;
6255 int len, rangeLen;
6257 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
6258 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
6259 return NULL;
6260 len = Jim_ListLength(interp, listObjPtr); /* will convert into list */
6261 first = JimRelToAbsIndex(len, first);
6262 last = JimRelToAbsIndex(len, last);
6263 JimRelToAbsRange(len, &first, &last, &rangeLen);
6264 if (first == 0 && last == len) {
6265 return listObjPtr;
6267 return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
6270 /* -----------------------------------------------------------------------------
6271 * Dict object
6272 * ---------------------------------------------------------------------------*/
6273 static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
6274 static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
6275 static void UpdateStringOfDict(struct Jim_Obj *objPtr);
6276 static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6278 /* Dict HashTable Type.
6280 * Keys and Values are Jim objects. */
6282 static unsigned int JimObjectHTHashFunction(const void *key)
6284 int len;
6285 const char *str = Jim_GetString((Jim_Obj *)key, &len);
6286 return Jim_GenHashFunction((const unsigned char *)str, len);
6289 static int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
6291 return Jim_StringEqObj((Jim_Obj *)key1, (Jim_Obj *)key2);
6294 static void JimObjectHTKeyValDestructor(void *interp, void *val)
6296 Jim_DecrRefCount(interp, (Jim_Obj *)val);
6299 static const Jim_HashTableType JimDictHashTableType = {
6300 JimObjectHTHashFunction, /* hash function */
6301 NULL, /* key dup */
6302 NULL, /* val dup */
6303 JimObjectHTKeyCompare, /* key compare */
6304 JimObjectHTKeyValDestructor, /* key destructor */
6305 JimObjectHTKeyValDestructor /* val destructor */
6308 /* Note that while the elements of the dict may contain references,
6309 * the list object itself can't. This basically means that the
6310 * dict object string representation as a whole can't contain references
6311 * that are not presents in the single elements. */
6312 static const Jim_ObjType dictObjType = {
6313 "dict",
6314 FreeDictInternalRep,
6315 DupDictInternalRep,
6316 UpdateStringOfDict,
6317 JIM_TYPE_NONE,
6320 void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
6322 JIM_NOTUSED(interp);
6324 Jim_FreeHashTable(objPtr->internalRep.ptr);
6325 Jim_Free(objPtr->internalRep.ptr);
6328 void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
6330 Jim_HashTable *ht, *dupHt;
6331 Jim_HashTableIterator *htiter;
6332 Jim_HashEntry *he;
6334 /* Create a new hash table */
6335 ht = srcPtr->internalRep.ptr;
6336 dupHt = Jim_Alloc(sizeof(*dupHt));
6337 Jim_InitHashTable(dupHt, &JimDictHashTableType, interp);
6338 if (ht->size != 0)
6339 Jim_ExpandHashTable(dupHt, ht->size);
6340 /* Copy every element from the source to the dup hash table */
6341 htiter = Jim_GetHashTableIterator(ht);
6342 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6343 const Jim_Obj *keyObjPtr = he->key;
6344 Jim_Obj *valObjPtr = he->u.val;
6346 Jim_IncrRefCount((Jim_Obj *)keyObjPtr); /* ATTENTION: const cast */
6347 Jim_IncrRefCount(valObjPtr);
6348 Jim_AddHashEntry(dupHt, keyObjPtr, valObjPtr);
6350 Jim_FreeHashTableIterator(htiter);
6352 dupPtr->internalRep.ptr = dupHt;
6353 dupPtr->typePtr = &dictObjType;
6356 void UpdateStringOfDict(struct Jim_Obj *objPtr)
6358 int i, bufLen, realLength;
6359 const char *strRep;
6360 char *p;
6361 int *quotingType, objc;
6362 Jim_HashTable *ht;
6363 Jim_HashTableIterator *htiter;
6364 Jim_HashEntry *he;
6365 Jim_Obj **objv;
6367 /* Trun the hash table into a flat vector of Jim_Objects. */
6368 ht = objPtr->internalRep.ptr;
6369 objc = ht->used * 2;
6370 objv = Jim_Alloc(objc * sizeof(Jim_Obj *));
6371 htiter = Jim_GetHashTableIterator(ht);
6372 i = 0;
6373 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6374 objv[i++] = (Jim_Obj *)he->key; /* ATTENTION: const cast */
6375 objv[i++] = he->u.val;
6377 Jim_FreeHashTableIterator(htiter);
6378 /* (Over) Estimate the space needed. */
6379 quotingType = Jim_Alloc(sizeof(int) * objc);
6380 bufLen = 0;
6381 for (i = 0; i < objc; i++) {
6382 int len;
6384 strRep = Jim_GetString(objv[i], &len);
6385 quotingType[i] = ListElementQuotingType(strRep, len);
6386 switch (quotingType[i]) {
6387 case JIM_ELESTR_SIMPLE:
6388 if (i != 0 || strRep[0] != '#') {
6389 bufLen += len;
6390 break;
6392 /* Special case '#' on first element needs braces */
6393 quotingType[i] = JIM_ELESTR_BRACE;
6394 /* fall through */
6395 case JIM_ELESTR_BRACE:
6396 bufLen += len + 2;
6397 break;
6398 case JIM_ELESTR_QUOTE:
6399 bufLen += len * 2;
6400 break;
6402 bufLen++; /* elements separator. */
6404 bufLen++;
6406 /* Generate the string rep. */
6407 p = objPtr->bytes = Jim_Alloc(bufLen + 1);
6408 realLength = 0;
6409 for (i = 0; i < objc; i++) {
6410 int len, qlen;
6411 char *q;
6413 strRep = Jim_GetString(objv[i], &len);
6415 switch (quotingType[i]) {
6416 case JIM_ELESTR_SIMPLE:
6417 memcpy(p, strRep, len);
6418 p += len;
6419 realLength += len;
6420 break;
6421 case JIM_ELESTR_BRACE:
6422 *p++ = '{';
6423 memcpy(p, strRep, len);
6424 p += len;
6425 *p++ = '}';
6426 realLength += len + 2;
6427 break;
6428 case JIM_ELESTR_QUOTE:
6429 q = BackslashQuoteString(strRep, len, &qlen);
6430 memcpy(p, q, qlen);
6431 Jim_Free(q);
6432 p += qlen;
6433 realLength += qlen;
6434 break;
6436 /* Add a separating space */
6437 if (i + 1 != objc) {
6438 *p++ = ' ';
6439 realLength++;
6442 *p = '\0'; /* nul term. */
6443 objPtr->length = realLength;
6444 Jim_Free(quotingType);
6445 Jim_Free(objv);
6448 static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
6450 int listlen;
6452 if (objPtr->typePtr == &dictObjType) {
6453 return JIM_OK;
6456 /* Get the string representation. Do this first so we don't
6457 * change order in case of fast conversion to dict.
6459 Jim_String(objPtr);
6461 /* For simplicity, convert a non-list object to a list and then to a dict */
6462 listlen = Jim_ListLength(interp, objPtr);
6463 if (listlen % 2) {
6464 Jim_SetResultString(interp,
6465 "invalid dictionary value: must be a list with an even number of elements", -1);
6466 return JIM_ERR;
6468 else {
6469 /* Now it is easy to convert to a dict from a list, and it can't fail */
6470 Jim_HashTable *ht;
6471 int i;
6473 ht = Jim_Alloc(sizeof(*ht));
6474 Jim_InitHashTable(ht, &JimDictHashTableType, interp);
6476 for (i = 0; i < listlen; i += 2) {
6477 Jim_Obj *keyObjPtr;
6478 Jim_Obj *valObjPtr;
6480 Jim_ListIndex(interp, objPtr, i, &keyObjPtr, JIM_NONE);
6481 Jim_ListIndex(interp, objPtr, i + 1, &valObjPtr, JIM_NONE);
6483 Jim_IncrRefCount(keyObjPtr);
6484 Jim_IncrRefCount(valObjPtr);
6486 if (Jim_AddHashEntry(ht, keyObjPtr, valObjPtr) != JIM_OK) {
6487 Jim_HashEntry *he;
6489 he = Jim_FindHashEntry(ht, keyObjPtr);
6490 Jim_DecrRefCount(interp, keyObjPtr);
6491 /* ATTENTION: const cast */
6492 Jim_DecrRefCount(interp, (Jim_Obj *)he->u.val);
6493 he->u.val = valObjPtr;
6497 Jim_FreeIntRep(interp, objPtr);
6498 objPtr->typePtr = &dictObjType;
6499 objPtr->internalRep.ptr = ht;
6501 return JIM_OK;
6505 /* Dict object API */
6507 /* Add an element to a dict. objPtr must be of the "dict" type.
6508 * The higer-level exported function is Jim_DictAddElement().
6509 * If an element with the specified key already exists, the value
6510 * associated is replaced with the new one.
6512 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6513 static int DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
6514 Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
6516 Jim_HashTable *ht = objPtr->internalRep.ptr;
6518 if (valueObjPtr == NULL) { /* unset */
6519 return Jim_DeleteHashEntry(ht, keyObjPtr);
6521 Jim_IncrRefCount(keyObjPtr);
6522 Jim_IncrRefCount(valueObjPtr);
6523 if (Jim_ReplaceHashEntry(ht, keyObjPtr, valueObjPtr)) {
6524 /* Value existed, so need to decrement key ref count */
6525 Jim_DecrRefCount(interp, keyObjPtr);
6527 return JIM_OK;
6530 /* Add an element, higher-level interface for DictAddElement().
6531 * If valueObjPtr == NULL, the key is removed if it exists. */
6532 int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
6533 Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
6535 int retcode;
6537 JimPanic((Jim_IsShared(objPtr), "Jim_DictAddElement called with shared object"));
6538 if (SetDictFromAny(interp, objPtr) != JIM_OK) {
6539 return JIM_ERR;
6541 retcode = DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
6542 Jim_InvalidateStringRep(objPtr);
6543 return retcode;
6546 Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
6548 Jim_Obj *objPtr;
6549 int i;
6551 JimPanic((len % 2, "Jim_NewDictObj() 'len' argument must be even"));
6553 objPtr = Jim_NewObj(interp);
6554 objPtr->typePtr = &dictObjType;
6555 objPtr->bytes = NULL;
6556 objPtr->internalRep.ptr = Jim_Alloc(sizeof(Jim_HashTable));
6557 Jim_InitHashTable(objPtr->internalRep.ptr, &JimDictHashTableType, interp);
6558 for (i = 0; i < len; i += 2)
6559 DictAddElement(interp, objPtr, elements[i], elements[i + 1]);
6560 return objPtr;
6563 /* Return the value associated to the specified dict key
6564 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6566 int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
6567 Jim_Obj **objPtrPtr, int flags)
6569 Jim_HashEntry *he;
6570 Jim_HashTable *ht;
6572 if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
6573 return -1;
6575 ht = dictPtr->internalRep.ptr;
6576 if ((he = Jim_FindHashEntry(ht, keyPtr)) == NULL) {
6577 if (flags & JIM_ERRMSG) {
6578 Jim_SetResultFormatted(interp, "key \"%#s\" not found in dictionary", keyPtr);
6580 return JIM_ERR;
6582 *objPtrPtr = he->u.val;
6583 return JIM_OK;
6586 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6587 int Jim_DictPairs(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj ***objPtrPtr, int *len)
6589 Jim_HashTable *ht;
6590 Jim_HashTableIterator *htiter;
6591 Jim_HashEntry *he;
6592 Jim_Obj **objv;
6593 int i;
6595 if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
6596 return JIM_ERR;
6598 ht = dictPtr->internalRep.ptr;
6600 /* Turn the hash table into a flat vector of Jim_Objects. */
6601 objv = Jim_Alloc((ht->used * 2) * sizeof(Jim_Obj *));
6602 htiter = Jim_GetHashTableIterator(ht);
6603 i = 0;
6604 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6605 objv[i++] = (Jim_Obj *)he->key; /* ATTENTION: const cast */
6606 objv[i++] = he->u.val;
6608 *len = i;
6609 Jim_FreeHashTableIterator(htiter);
6610 *objPtrPtr = objv;
6611 return JIM_OK;
6615 /* Return the value associated to the specified dict keys */
6616 int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
6617 Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
6619 int i;
6621 if (keyc == 0) {
6622 *objPtrPtr = dictPtr;
6623 return JIM_OK;
6626 for (i = 0; i < keyc; i++) {
6627 Jim_Obj *objPtr;
6629 int rc = Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags);
6630 if (rc != JIM_OK) {
6631 return rc;
6633 dictPtr = objPtr;
6635 *objPtrPtr = dictPtr;
6636 return JIM_OK;
6639 /* Modify the dict stored into the variable named 'varNamePtr'
6640 * setting the element specified by the 'keyc' keys objects in 'keyv',
6641 * with the new value of the element 'newObjPtr'.
6643 * If newObjPtr == NULL the operation is to remove the given key
6644 * from the dictionary.
6646 * If flags & JIM_ERRMSG, then failure to remove the key is considered an error
6647 * and JIM_ERR is returned. Otherwise it is ignored and JIM_OK is returned.
6649 int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
6650 Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr, int flags)
6652 Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
6653 int shared, i;
6655 varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, flags);
6656 if (objPtr == NULL) {
6657 if (newObjPtr == NULL && (flags & JIM_ERRMSG)) {
6658 /* Cannot remove a key from non existing var */
6659 return JIM_ERR;
6661 varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
6662 if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
6663 Jim_FreeNewObj(interp, varObjPtr);
6664 return JIM_ERR;
6667 if ((shared = Jim_IsShared(objPtr)))
6668 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6669 for (i = 0; i < keyc; i++) {
6670 dictObjPtr = objPtr;
6672 /* Check if it's a valid dictionary */
6673 if (SetDictFromAny(interp, dictObjPtr) != JIM_OK) {
6674 goto err;
6677 if (i == keyc - 1) {
6678 /* Last key: Note that error on unset with missing last key is OK */
6679 if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
6680 if (newObjPtr || (flags & JIM_ERRMSG)) {
6681 goto err;
6684 break;
6687 /* Check if the given key exists. */
6688 Jim_InvalidateStringRep(dictObjPtr);
6689 if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
6690 newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
6691 /* This key exists at the current level.
6692 * Make sure it's not shared!. */
6693 if (Jim_IsShared(objPtr)) {
6694 objPtr = Jim_DuplicateObj(interp, objPtr);
6695 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6698 else {
6699 /* Key not found. If it's an [unset] operation
6700 * this is an error. Only the last key may not
6701 * exist. */
6702 if (newObjPtr == NULL) {
6703 goto err;
6705 /* Otherwise set an empty dictionary
6706 * as key's value. */
6707 objPtr = Jim_NewDictObj(interp, NULL, 0);
6708 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6711 Jim_InvalidateStringRep(objPtr);
6712 Jim_InvalidateStringRep(varObjPtr);
6713 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK) {
6714 goto err;
6716 Jim_SetResult(interp, varObjPtr);
6717 return JIM_OK;
6718 err:
6719 if (shared) {
6720 Jim_FreeNewObj(interp, varObjPtr);
6722 return JIM_ERR;
6725 /* -----------------------------------------------------------------------------
6726 * Index object
6727 * ---------------------------------------------------------------------------*/
6728 static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
6729 static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6731 static const Jim_ObjType indexObjType = {
6732 "index",
6733 NULL,
6734 NULL,
6735 UpdateStringOfIndex,
6736 JIM_TYPE_NONE,
6739 void UpdateStringOfIndex(struct Jim_Obj *objPtr)
6741 int len;
6742 char buf[JIM_INTEGER_SPACE + 1];
6744 if (objPtr->internalRep.indexValue >= 0)
6745 len = sprintf(buf, "%d", objPtr->internalRep.indexValue);
6746 else if (objPtr->internalRep.indexValue == -1)
6747 len = sprintf(buf, "end");
6748 else {
6749 len = sprintf(buf, "end%d", objPtr->internalRep.indexValue + 1);
6751 objPtr->bytes = Jim_Alloc(len + 1);
6752 memcpy(objPtr->bytes, buf, len + 1);
6753 objPtr->length = len;
6756 int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6758 int idx, end = 0;
6759 const char *str;
6760 char *endptr;
6762 /* Get the string representation */
6763 str = Jim_String(objPtr);
6765 /* Try to convert into an index */
6766 if (strncmp(str, "end", 3) == 0) {
6767 end = 1;
6768 str += 3;
6769 idx = 0;
6771 else {
6772 idx = strtol(str, &endptr, 10);
6774 if (endptr == str) {
6775 goto badindex;
6777 str = endptr;
6780 /* Now str may include or +<num> or -<num> */
6781 if (*str == '+' || *str == '-') {
6782 int sign = (*str == '+' ? 1 : -1);
6784 idx += sign * strtol(++str, &endptr, 10);
6785 if (str == endptr || *endptr) {
6786 goto badindex;
6788 str = endptr;
6790 /* The only thing left should be spaces */
6791 while (isspace(UCHAR(*str))) {
6792 str++;
6794 if (*str) {
6795 goto badindex;
6797 if (end) {
6798 if (idx > 0) {
6799 idx = INT_MAX;
6801 else {
6802 /* end-1 is repesented as -2 */
6803 idx--;
6806 else if (idx < 0) {
6807 idx = -INT_MAX;
6810 /* Free the old internal repr and set the new one. */
6811 Jim_FreeIntRep(interp, objPtr);
6812 objPtr->typePtr = &indexObjType;
6813 objPtr->internalRep.indexValue = idx;
6814 return JIM_OK;
6816 badindex:
6817 Jim_SetResultFormatted(interp,
6818 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr);
6819 return JIM_ERR;
6822 int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
6824 /* Avoid shimmering if the object is an integer. */
6825 if (objPtr->typePtr == &intObjType) {
6826 jim_wide val = JimWideValue(objPtr);
6828 if (!(val < LONG_MIN) && !(val > LONG_MAX)) {
6829 *indexPtr = (val < 0) ? -INT_MAX : (long)val;;
6830 return JIM_OK;
6833 if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
6834 return JIM_ERR;
6835 *indexPtr = objPtr->internalRep.indexValue;
6836 return JIM_OK;
6839 /* -----------------------------------------------------------------------------
6840 * Return Code Object.
6841 * ---------------------------------------------------------------------------*/
6843 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6844 static const char * const jimReturnCodes[] = {
6845 "ok",
6846 "error",
6847 "return",
6848 "break",
6849 "continue",
6850 "signal",
6851 "exit",
6852 "eval",
6853 NULL
6856 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6858 static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
6860 static const Jim_ObjType returnCodeObjType = {
6861 "return-code",
6862 NULL,
6863 NULL,
6864 NULL,
6865 JIM_TYPE_NONE,
6868 /* Converts a (standard) return code to a string. Returns "?" for
6869 * non-standard return codes.
6871 const char *Jim_ReturnCode(int code)
6873 if (code < 0 || code >= (int)jimReturnCodesSize) {
6874 return "?";
6876 else {
6877 return jimReturnCodes[code];
6881 int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6883 int returnCode;
6884 jim_wide wideValue;
6886 /* Try to convert into an integer */
6887 if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
6888 returnCode = (int)wideValue;
6889 else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
6890 Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
6891 return JIM_ERR;
6893 /* Free the old internal repr and set the new one. */
6894 Jim_FreeIntRep(interp, objPtr);
6895 objPtr->typePtr = &returnCodeObjType;
6896 objPtr->internalRep.returnCode = returnCode;
6897 return JIM_OK;
6900 int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
6902 if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
6903 return JIM_ERR;
6904 *intPtr = objPtr->internalRep.returnCode;
6905 return JIM_OK;
6908 /* -----------------------------------------------------------------------------
6909 * Expression Parsing
6910 * ---------------------------------------------------------------------------*/
6911 static int JimParseExprOperator(struct JimParserCtx *pc);
6912 static int JimParseExprNumber(struct JimParserCtx *pc);
6913 static int JimParseExprIrrational(struct JimParserCtx *pc);
6915 /* Exrp's Stack machine operators opcodes. */
6917 /* Binary operators (numbers) */
6918 enum
6920 /* Continues on from the JIM_TT_ space */
6921 /* Operations */
6922 JIM_EXPROP_MUL = JIM_TT_EXPR_OP, /* 20 */
6923 JIM_EXPROP_DIV,
6924 JIM_EXPROP_MOD,
6925 JIM_EXPROP_SUB,
6926 JIM_EXPROP_ADD,
6927 JIM_EXPROP_LSHIFT,
6928 JIM_EXPROP_RSHIFT,
6929 JIM_EXPROP_ROTL,
6930 JIM_EXPROP_ROTR,
6931 JIM_EXPROP_LT,
6932 JIM_EXPROP_GT,
6933 JIM_EXPROP_LTE,
6934 JIM_EXPROP_GTE,
6935 JIM_EXPROP_NUMEQ,
6936 JIM_EXPROP_NUMNE,
6937 JIM_EXPROP_BITAND, /* 35 */
6938 JIM_EXPROP_BITXOR,
6939 JIM_EXPROP_BITOR,
6941 /* Note must keep these together */
6942 JIM_EXPROP_LOGICAND, /* 38 */
6943 JIM_EXPROP_LOGICAND_LEFT,
6944 JIM_EXPROP_LOGICAND_RIGHT,
6946 /* and these */
6947 JIM_EXPROP_LOGICOR, /* 41 */
6948 JIM_EXPROP_LOGICOR_LEFT,
6949 JIM_EXPROP_LOGICOR_RIGHT,
6951 /* and these */
6952 /* Ternary operators */
6953 JIM_EXPROP_TERNARY, /* 44 */
6954 JIM_EXPROP_TERNARY_LEFT,
6955 JIM_EXPROP_TERNARY_RIGHT,
6957 /* and these */
6958 JIM_EXPROP_COLON, /* 47 */
6959 JIM_EXPROP_COLON_LEFT,
6960 JIM_EXPROP_COLON_RIGHT,
6962 JIM_EXPROP_POW, /* 50 */
6964 /* Binary operators (strings) */
6965 JIM_EXPROP_STREQ, /* 51 */
6966 JIM_EXPROP_STRNE,
6967 JIM_EXPROP_STRIN,
6968 JIM_EXPROP_STRNI,
6970 /* Unary operators (numbers) */
6971 JIM_EXPROP_NOT, /* 55 */
6972 JIM_EXPROP_BITNOT,
6973 JIM_EXPROP_UNARYMINUS,
6974 JIM_EXPROP_UNARYPLUS,
6976 /* Functions */
6977 JIM_EXPROP_FUNC_FIRST, /* 59 */
6978 JIM_EXPROP_FUNC_INT = JIM_EXPROP_FUNC_FIRST,
6979 JIM_EXPROP_FUNC_ABS,
6980 JIM_EXPROP_FUNC_DOUBLE,
6981 JIM_EXPROP_FUNC_ROUND,
6982 JIM_EXPROP_FUNC_RAND,
6983 JIM_EXPROP_FUNC_SRAND,
6985 /* math functions from libm */
6986 JIM_EXPROP_FUNC_SIN, /* 64 */
6987 JIM_EXPROP_FUNC_COS,
6988 JIM_EXPROP_FUNC_TAN,
6989 JIM_EXPROP_FUNC_ASIN,
6990 JIM_EXPROP_FUNC_ACOS,
6991 JIM_EXPROP_FUNC_ATAN,
6992 JIM_EXPROP_FUNC_SINH,
6993 JIM_EXPROP_FUNC_COSH,
6994 JIM_EXPROP_FUNC_TANH,
6995 JIM_EXPROP_FUNC_CEIL,
6996 JIM_EXPROP_FUNC_FLOOR,
6997 JIM_EXPROP_FUNC_EXP,
6998 JIM_EXPROP_FUNC_LOG,
6999 JIM_EXPROP_FUNC_LOG10,
7000 JIM_EXPROP_FUNC_SQRT,
7001 JIM_EXPROP_FUNC_POW,
7004 struct JimExprState
7006 Jim_Obj **stack;
7007 int stacklen;
7008 int opcode;
7009 int skip;
7012 /* Operators table */
7013 typedef struct Jim_ExprOperator
7015 const char *name;
7016 int precedence;
7017 int arity;
7018 int (*funcop) (Jim_Interp *interp, struct JimExprState * e);
7019 int lazy;
7020 } Jim_ExprOperator;
7022 static void ExprPush(struct JimExprState *e, Jim_Obj *obj)
7024 Jim_IncrRefCount(obj);
7025 e->stack[e->stacklen++] = obj;
7028 static Jim_Obj *ExprPop(struct JimExprState *e)
7030 return e->stack[--e->stacklen];
7033 static int JimExprOpNumUnary(Jim_Interp *interp, struct JimExprState *e)
7035 int intresult = 0;
7036 int rc = JIM_OK;
7037 Jim_Obj *A = ExprPop(e);
7038 double dA, dC = 0;
7039 jim_wide wA, wC = 0;
7041 if ((A->typePtr != &doubleObjType || A->bytes) && JimGetWideNoErr(interp, A, &wA) == JIM_OK) {
7042 intresult = 1;
7044 switch (e->opcode) {
7045 case JIM_EXPROP_FUNC_INT:
7046 wC = wA;
7047 break;
7048 case JIM_EXPROP_FUNC_ROUND:
7049 wC = wA;
7050 break;
7051 case JIM_EXPROP_FUNC_DOUBLE:
7052 dC = wA;
7053 intresult = 0;
7054 break;
7055 case JIM_EXPROP_FUNC_ABS:
7056 wC = wA >= 0 ? wA : -wA;
7057 break;
7058 case JIM_EXPROP_UNARYMINUS:
7059 wC = -wA;
7060 break;
7061 case JIM_EXPROP_UNARYPLUS:
7062 wC = wA;
7063 break;
7064 case JIM_EXPROP_NOT:
7065 wC = !wA;
7066 break;
7067 default:
7068 abort();
7071 else if ((rc = Jim_GetDouble(interp, A, &dA)) == JIM_OK) {
7072 switch (e->opcode) {
7073 case JIM_EXPROP_FUNC_INT:
7074 wC = dA;
7075 intresult = 1;
7076 break;
7077 case JIM_EXPROP_FUNC_ROUND:
7078 wC = dA < 0 ? (dA - 0.5) : (dA + 0.5);
7079 intresult = 1;
7080 break;
7081 case JIM_EXPROP_FUNC_DOUBLE:
7082 dC = dA;
7083 break;
7084 case JIM_EXPROP_FUNC_ABS:
7085 dC = dA >= 0 ? dA : -dA;
7086 break;
7087 case JIM_EXPROP_UNARYMINUS:
7088 dC = -dA;
7089 break;
7090 case JIM_EXPROP_UNARYPLUS:
7091 dC = dA;
7092 break;
7093 case JIM_EXPROP_NOT:
7094 wC = !dA;
7095 intresult = 1;
7096 break;
7097 default:
7098 abort();
7102 if (rc == JIM_OK) {
7103 if (intresult) {
7104 ExprPush(e, Jim_NewIntObj(interp, wC));
7106 else {
7107 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7111 Jim_DecrRefCount(interp, A);
7113 return rc;
7116 static double JimRandDouble(Jim_Interp *interp)
7118 unsigned long x;
7119 JimRandomBytes(interp, &x, sizeof(x));
7121 return (double)x / (unsigned long)~0;
7124 static int JimExprOpIntUnary(Jim_Interp *interp, struct JimExprState *e)
7126 Jim_Obj *A = ExprPop(e);
7127 jim_wide wA;
7129 int rc = Jim_GetWide(interp, A, &wA);
7130 if (rc == JIM_OK) {
7131 switch (e->opcode) {
7132 case JIM_EXPROP_BITNOT:
7133 ExprPush(e, Jim_NewIntObj(interp, ~wA));
7134 break;
7135 case JIM_EXPROP_FUNC_SRAND:
7136 JimPrngSeed(interp, (unsigned char *)&wA, sizeof(wA));
7137 ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
7138 break;
7139 default:
7140 abort();
7144 Jim_DecrRefCount(interp, A);
7146 return rc;
7149 static int JimExprOpNone(Jim_Interp *interp, struct JimExprState *e)
7151 JimPanic((e->opcode != JIM_EXPROP_FUNC_RAND, "JimExprOpNone only support rand()"));
7153 ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
7155 return JIM_OK;
7158 #ifdef JIM_MATH_FUNCTIONS
7159 static int JimExprOpDoubleUnary(Jim_Interp *interp, struct JimExprState *e)
7161 int rc;
7162 Jim_Obj *A = ExprPop(e);
7163 double dA, dC;
7165 rc = Jim_GetDouble(interp, A, &dA);
7166 if (rc == JIM_OK) {
7167 switch (e->opcode) {
7168 case JIM_EXPROP_FUNC_SIN:
7169 dC = sin(dA);
7170 break;
7171 case JIM_EXPROP_FUNC_COS:
7172 dC = cos(dA);
7173 break;
7174 case JIM_EXPROP_FUNC_TAN:
7175 dC = tan(dA);
7176 break;
7177 case JIM_EXPROP_FUNC_ASIN:
7178 dC = asin(dA);
7179 break;
7180 case JIM_EXPROP_FUNC_ACOS:
7181 dC = acos(dA);
7182 break;
7183 case JIM_EXPROP_FUNC_ATAN:
7184 dC = atan(dA);
7185 break;
7186 case JIM_EXPROP_FUNC_SINH:
7187 dC = sinh(dA);
7188 break;
7189 case JIM_EXPROP_FUNC_COSH:
7190 dC = cosh(dA);
7191 break;
7192 case JIM_EXPROP_FUNC_TANH:
7193 dC = tanh(dA);
7194 break;
7195 case JIM_EXPROP_FUNC_CEIL:
7196 dC = ceil(dA);
7197 break;
7198 case JIM_EXPROP_FUNC_FLOOR:
7199 dC = floor(dA);
7200 break;
7201 case JIM_EXPROP_FUNC_EXP:
7202 dC = exp(dA);
7203 break;
7204 case JIM_EXPROP_FUNC_LOG:
7205 dC = log(dA);
7206 break;
7207 case JIM_EXPROP_FUNC_LOG10:
7208 dC = log10(dA);
7209 break;
7210 case JIM_EXPROP_FUNC_SQRT:
7211 dC = sqrt(dA);
7212 break;
7213 default:
7214 abort();
7216 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7219 Jim_DecrRefCount(interp, A);
7221 return rc;
7223 #endif
7225 /* A binary operation on two ints */
7226 static int JimExprOpIntBin(Jim_Interp *interp, struct JimExprState *e)
7228 Jim_Obj *B = ExprPop(e);
7229 Jim_Obj *A = ExprPop(e);
7230 jim_wide wA, wB;
7231 int rc = JIM_ERR;
7233 if (Jim_GetWide(interp, A, &wA) == JIM_OK && Jim_GetWide(interp, B, &wB) == JIM_OK) {
7234 jim_wide wC;
7236 rc = JIM_OK;
7238 switch (e->opcode) {
7239 case JIM_EXPROP_LSHIFT:
7240 wC = wA << wB;
7241 break;
7242 case JIM_EXPROP_RSHIFT:
7243 wC = wA >> wB;
7244 break;
7245 case JIM_EXPROP_BITAND:
7246 wC = wA & wB;
7247 break;
7248 case JIM_EXPROP_BITXOR:
7249 wC = wA ^ wB;
7250 break;
7251 case JIM_EXPROP_BITOR:
7252 wC = wA | wB;
7253 break;
7254 case JIM_EXPROP_MOD:
7255 if (wB == 0) {
7256 wC = 0;
7257 Jim_SetResultString(interp, "Division by zero", -1);
7258 rc = JIM_ERR;
7260 else {
7262 * From Tcl 8.x
7264 * This code is tricky: C doesn't guarantee much
7265 * about the quotient or remainder, but Tcl does.
7266 * The remainder always has the same sign as the
7267 * divisor and a smaller absolute value.
7269 int negative = 0;
7271 if (wB < 0) {
7272 wB = -wB;
7273 wA = -wA;
7274 negative = 1;
7276 wC = wA % wB;
7277 if (wC < 0) {
7278 wC += wB;
7280 if (negative) {
7281 wC = -wC;
7284 break;
7285 case JIM_EXPROP_ROTL:
7286 case JIM_EXPROP_ROTR:{
7287 /* uint32_t would be better. But not everyone has inttypes.h? */
7288 unsigned long uA = (unsigned long)wA;
7289 unsigned long uB = (unsigned long)wB;
7290 const unsigned int S = sizeof(unsigned long) * 8;
7292 /* Shift left by the word size or more is undefined. */
7293 uB %= S;
7295 if (e->opcode == JIM_EXPROP_ROTR) {
7296 uB = S - uB;
7298 wC = (unsigned long)(uA << uB) | (uA >> (S - uB));
7299 break;
7301 default:
7302 abort();
7304 ExprPush(e, Jim_NewIntObj(interp, wC));
7308 Jim_DecrRefCount(interp, A);
7309 Jim_DecrRefCount(interp, B);
7311 return rc;
7315 /* A binary operation on two ints or two doubles (or two strings for some ops) */
7316 static int JimExprOpBin(Jim_Interp *interp, struct JimExprState *e)
7318 int intresult = 0;
7319 int rc = JIM_OK;
7320 double dA, dB, dC = 0;
7321 jim_wide wA, wB, wC = 0;
7323 Jim_Obj *B = ExprPop(e);
7324 Jim_Obj *A = ExprPop(e);
7326 if ((A->typePtr != &doubleObjType || A->bytes) &&
7327 (B->typePtr != &doubleObjType || B->bytes) &&
7328 JimGetWideNoErr(interp, A, &wA) == JIM_OK && JimGetWideNoErr(interp, B, &wB) == JIM_OK) {
7330 /* Both are ints */
7332 intresult = 1;
7334 switch (e->opcode) {
7335 case JIM_EXPROP_POW:
7336 case JIM_EXPROP_FUNC_POW:
7337 wC = JimPowWide(wA, wB);
7338 break;
7339 case JIM_EXPROP_ADD:
7340 wC = wA + wB;
7341 break;
7342 case JIM_EXPROP_SUB:
7343 wC = wA - wB;
7344 break;
7345 case JIM_EXPROP_MUL:
7346 wC = wA * wB;
7347 break;
7348 case JIM_EXPROP_DIV:
7349 if (wB == 0) {
7350 Jim_SetResultString(interp, "Division by zero", -1);
7351 rc = JIM_ERR;
7353 else {
7355 * From Tcl 8.x
7357 * This code is tricky: C doesn't guarantee much
7358 * about the quotient or remainder, but Tcl does.
7359 * The remainder always has the same sign as the
7360 * divisor and a smaller absolute value.
7362 if (wB < 0) {
7363 wB = -wB;
7364 wA = -wA;
7366 wC = wA / wB;
7367 if (wA % wB < 0) {
7368 wC--;
7371 break;
7372 case JIM_EXPROP_LT:
7373 wC = wA < wB;
7374 break;
7375 case JIM_EXPROP_GT:
7376 wC = wA > wB;
7377 break;
7378 case JIM_EXPROP_LTE:
7379 wC = wA <= wB;
7380 break;
7381 case JIM_EXPROP_GTE:
7382 wC = wA >= wB;
7383 break;
7384 case JIM_EXPROP_NUMEQ:
7385 wC = wA == wB;
7386 break;
7387 case JIM_EXPROP_NUMNE:
7388 wC = wA != wB;
7389 break;
7390 default:
7391 abort();
7394 else if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
7395 switch (e->opcode) {
7396 case JIM_EXPROP_POW:
7397 case JIM_EXPROP_FUNC_POW:
7398 #ifdef JIM_MATH_FUNCTIONS
7399 dC = pow(dA, dB);
7400 #else
7401 Jim_SetResultString(interp, "unsupported", -1);
7402 rc = JIM_ERR;
7403 #endif
7404 break;
7405 case JIM_EXPROP_ADD:
7406 dC = dA + dB;
7407 break;
7408 case JIM_EXPROP_SUB:
7409 dC = dA - dB;
7410 break;
7411 case JIM_EXPROP_MUL:
7412 dC = dA * dB;
7413 break;
7414 case JIM_EXPROP_DIV:
7415 if (dB == 0) {
7416 #ifdef INFINITY
7417 dC = dA < 0 ? -INFINITY : INFINITY;
7418 #else
7419 dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
7420 #endif
7422 else {
7423 dC = dA / dB;
7425 break;
7426 case JIM_EXPROP_LT:
7427 wC = dA < dB;
7428 intresult = 1;
7429 break;
7430 case JIM_EXPROP_GT:
7431 wC = dA > dB;
7432 intresult = 1;
7433 break;
7434 case JIM_EXPROP_LTE:
7435 wC = dA <= dB;
7436 intresult = 1;
7437 break;
7438 case JIM_EXPROP_GTE:
7439 wC = dA >= dB;
7440 intresult = 1;
7441 break;
7442 case JIM_EXPROP_NUMEQ:
7443 wC = dA == dB;
7444 intresult = 1;
7445 break;
7446 case JIM_EXPROP_NUMNE:
7447 wC = dA != dB;
7448 intresult = 1;
7449 break;
7450 default:
7451 abort();
7454 else {
7455 /* Handle the string case */
7457 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7458 int i = Jim_StringCompareObj(interp, A, B, 0);
7460 intresult = 1;
7462 switch (e->opcode) {
7463 case JIM_EXPROP_LT:
7464 wC = i < 0;
7465 break;
7466 case JIM_EXPROP_GT:
7467 wC = i > 0;
7468 break;
7469 case JIM_EXPROP_LTE:
7470 wC = i <= 0;
7471 break;
7472 case JIM_EXPROP_GTE:
7473 wC = i >= 0;
7474 break;
7475 case JIM_EXPROP_NUMEQ:
7476 wC = i == 0;
7477 break;
7478 case JIM_EXPROP_NUMNE:
7479 wC = i != 0;
7480 break;
7481 default:
7482 rc = JIM_ERR;
7483 break;
7487 if (rc == JIM_OK) {
7488 if (intresult) {
7489 ExprPush(e, Jim_NewIntObj(interp, wC));
7491 else {
7492 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7496 Jim_DecrRefCount(interp, A);
7497 Jim_DecrRefCount(interp, B);
7499 return rc;
7502 static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
7504 int listlen;
7505 int i;
7507 listlen = Jim_ListLength(interp, listObjPtr);
7508 for (i = 0; i < listlen; i++) {
7509 Jim_Obj *objPtr;
7511 Jim_ListIndex(interp, listObjPtr, i, &objPtr, JIM_NONE);
7513 if (Jim_StringEqObj(objPtr, valObj)) {
7514 return 1;
7517 return 0;
7520 static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprState *e)
7522 Jim_Obj *B = ExprPop(e);
7523 Jim_Obj *A = ExprPop(e);
7525 jim_wide wC;
7527 switch (e->opcode) {
7528 case JIM_EXPROP_STREQ:
7529 case JIM_EXPROP_STRNE: {
7530 int Alen, Blen;
7531 const char *sA = Jim_GetString(A, &Alen);
7532 const char *sB = Jim_GetString(B, &Blen);
7534 if (e->opcode == JIM_EXPROP_STREQ) {
7535 wC = (Alen == Blen && memcmp(sA, sB, Alen) == 0);
7537 else {
7538 wC = (Alen != Blen || memcmp(sA, sB, Alen) != 0);
7540 break;
7542 case JIM_EXPROP_STRIN:
7543 wC = JimSearchList(interp, B, A);
7544 break;
7545 case JIM_EXPROP_STRNI:
7546 wC = !JimSearchList(interp, B, A);
7547 break;
7548 default:
7549 abort();
7551 ExprPush(e, Jim_NewIntObj(interp, wC));
7553 Jim_DecrRefCount(interp, A);
7554 Jim_DecrRefCount(interp, B);
7556 return JIM_OK;
7559 static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
7561 long l;
7562 double d;
7564 if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
7565 return l != 0;
7567 if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
7568 return d != 0;
7570 return -1;
7573 static int JimExprOpAndLeft(Jim_Interp *interp, struct JimExprState *e)
7575 Jim_Obj *skip = ExprPop(e);
7576 Jim_Obj *A = ExprPop(e);
7577 int rc = JIM_OK;
7579 switch (ExprBool(interp, A)) {
7580 case 0:
7581 /* false, so skip RHS opcodes with a 0 result */
7582 e->skip = JimWideValue(skip);
7583 ExprPush(e, Jim_NewIntObj(interp, 0));
7584 break;
7586 case 1:
7587 /* true so continue */
7588 break;
7590 case -1:
7591 /* Invalid */
7592 rc = JIM_ERR;
7594 Jim_DecrRefCount(interp, A);
7595 Jim_DecrRefCount(interp, skip);
7597 return rc;
7600 static int JimExprOpOrLeft(Jim_Interp *interp, struct JimExprState *e)
7602 Jim_Obj *skip = ExprPop(e);
7603 Jim_Obj *A = ExprPop(e);
7604 int rc = JIM_OK;
7606 switch (ExprBool(interp, A)) {
7607 case 0:
7608 /* false, so do nothing */
7609 break;
7611 case 1:
7612 /* true so skip RHS opcodes with a 1 result */
7613 e->skip = JimWideValue(skip);
7614 ExprPush(e, Jim_NewIntObj(interp, 1));
7615 break;
7617 case -1:
7618 /* Invalid */
7619 rc = JIM_ERR;
7620 break;
7622 Jim_DecrRefCount(interp, A);
7623 Jim_DecrRefCount(interp, skip);
7625 return rc;
7628 static int JimExprOpAndOrRight(Jim_Interp *interp, struct JimExprState *e)
7630 Jim_Obj *A = ExprPop(e);
7631 int rc = JIM_OK;
7633 switch (ExprBool(interp, A)) {
7634 case 0:
7635 ExprPush(e, Jim_NewIntObj(interp, 0));
7636 break;
7638 case 1:
7639 ExprPush(e, Jim_NewIntObj(interp, 1));
7640 break;
7642 case -1:
7643 /* Invalid */
7644 rc = JIM_ERR;
7645 break;
7647 Jim_DecrRefCount(interp, A);
7649 return rc;
7652 static int JimExprOpTernaryLeft(Jim_Interp *interp, struct JimExprState *e)
7654 Jim_Obj *skip = ExprPop(e);
7655 Jim_Obj *A = ExprPop(e);
7656 int rc = JIM_OK;
7658 /* Repush A */
7659 ExprPush(e, A);
7661 switch (ExprBool(interp, A)) {
7662 case 0:
7663 /* false, skip RHS opcodes */
7664 e->skip = JimWideValue(skip);
7665 /* Push a dummy value */
7666 ExprPush(e, Jim_NewIntObj(interp, 0));
7667 break;
7669 case 1:
7670 /* true so do nothing */
7671 break;
7673 case -1:
7674 /* Invalid */
7675 rc = JIM_ERR;
7676 break;
7678 Jim_DecrRefCount(interp, A);
7679 Jim_DecrRefCount(interp, skip);
7681 return rc;
7684 static int JimExprOpColonLeft(Jim_Interp *interp, struct JimExprState *e)
7686 Jim_Obj *skip = ExprPop(e);
7687 Jim_Obj *B = ExprPop(e);
7688 Jim_Obj *A = ExprPop(e);
7690 /* No need to check for A as non-boolean */
7691 if (ExprBool(interp, A)) {
7692 /* true, so skip RHS opcodes */
7693 e->skip = JimWideValue(skip);
7694 /* Repush B as the answer */
7695 ExprPush(e, B);
7698 Jim_DecrRefCount(interp, skip);
7699 Jim_DecrRefCount(interp, A);
7700 Jim_DecrRefCount(interp, B);
7701 return JIM_OK;
7704 static int JimExprOpNull(Jim_Interp *interp, struct JimExprState *e)
7706 return JIM_OK;
7709 enum
7711 LAZY_NONE,
7712 LAZY_OP,
7713 LAZY_LEFT,
7714 LAZY_RIGHT
7717 /* name - precedence - arity - opcode
7719 * This array *must* be kept in sync with the JIM_EXPROP enum
7721 static const struct Jim_ExprOperator Jim_ExprOperators[] = {
7722 {"*", 200, 2, JimExprOpBin, LAZY_NONE},
7723 {"/", 200, 2, JimExprOpBin, LAZY_NONE},
7724 {"%", 200, 2, JimExprOpIntBin, LAZY_NONE},
7726 {"-", 100, 2, JimExprOpBin, LAZY_NONE},
7727 {"+", 100, 2, JimExprOpBin, LAZY_NONE},
7729 {"<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7730 {">>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7732 {"<<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7733 {">>>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7735 {"<", 80, 2, JimExprOpBin, LAZY_NONE},
7736 {">", 80, 2, JimExprOpBin, LAZY_NONE},
7737 {"<=", 80, 2, JimExprOpBin, LAZY_NONE},
7738 {">=", 80, 2, JimExprOpBin, LAZY_NONE},
7740 {"==", 70, 2, JimExprOpBin, LAZY_NONE},
7741 {"!=", 70, 2, JimExprOpBin, LAZY_NONE},
7743 {"&", 50, 2, JimExprOpIntBin, LAZY_NONE},
7744 {"^", 49, 2, JimExprOpIntBin, LAZY_NONE},
7745 {"|", 48, 2, JimExprOpIntBin, LAZY_NONE},
7747 {"&&", 10, 2, NULL, LAZY_OP},
7748 {NULL, 10, 2, JimExprOpAndLeft, LAZY_LEFT},
7749 {NULL, 10, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7751 {"||", 9, 2, NULL, LAZY_OP},
7752 {NULL, 9, 2, JimExprOpOrLeft, LAZY_LEFT},
7753 {NULL, 9, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7755 {"?", 5, 2, JimExprOpNull, LAZY_OP},
7756 {NULL, 5, 2, JimExprOpTernaryLeft, LAZY_LEFT},
7757 {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7759 {":", 5, 2, JimExprOpNull, LAZY_OP},
7760 {NULL, 5, 2, JimExprOpColonLeft, LAZY_LEFT},
7761 {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7763 {"**", 250, 2, JimExprOpBin, LAZY_NONE},
7765 {"eq", 60, 2, JimExprOpStrBin, LAZY_NONE},
7766 {"ne", 60, 2, JimExprOpStrBin, LAZY_NONE},
7768 {"in", 55, 2, JimExprOpStrBin, LAZY_NONE},
7769 {"ni", 55, 2, JimExprOpStrBin, LAZY_NONE},
7771 {"!", 300, 1, JimExprOpNumUnary, LAZY_NONE},
7772 {"~", 300, 1, JimExprOpIntUnary, LAZY_NONE},
7773 {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7774 {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7778 {"int", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7779 {"abs", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7780 {"double", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7781 {"round", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7782 {"rand", 400, 0, JimExprOpNone, LAZY_NONE},
7783 {"srand", 400, 1, JimExprOpIntUnary, LAZY_NONE},
7785 #ifdef JIM_MATH_FUNCTIONS
7786 {"sin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7787 {"cos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7788 {"tan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7789 {"asin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7790 {"acos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7791 {"atan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7792 {"sinh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7793 {"cosh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7794 {"tanh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7795 {"ceil", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7796 {"floor", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7797 {"exp", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7798 {"log", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7799 {"log10", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7800 {"sqrt", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7801 {"pow", 400, 2, JimExprOpBin, LAZY_NONE},
7802 #endif
7805 #define JIM_EXPR_OPERATORS_NUM \
7806 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7808 static int JimParseExpression(struct JimParserCtx *pc)
7810 /* Discard spaces and quoted newline */
7811 while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
7812 if (*pc->p == '\n') {
7813 pc->linenr++;
7815 pc->p++;
7816 pc->len--;
7819 if (pc->len == 0) {
7820 pc->tstart = pc->tend = pc->p;
7821 pc->tline = pc->linenr;
7822 pc->tt = JIM_TT_EOL;
7823 pc->eof = 1;
7824 return JIM_OK;
7826 switch (*(pc->p)) {
7827 case '(':
7828 pc->tt = JIM_TT_SUBEXPR_START;
7829 goto singlechar;
7830 case ')':
7831 pc->tt = JIM_TT_SUBEXPR_END;
7832 goto singlechar;
7833 case ',':
7834 pc->tt = JIM_TT_SUBEXPR_COMMA;
7835 singlechar:
7836 pc->tstart = pc->tend = pc->p;
7837 pc->tline = pc->linenr;
7838 pc->p++;
7839 pc->len--;
7840 break;
7841 case '[':
7842 return JimParseCmd(pc);
7843 case '$':
7844 if (JimParseVar(pc) == JIM_ERR)
7845 return JimParseExprOperator(pc);
7846 else {
7847 /* Don't allow expr sugar in expressions */
7848 if (pc->tt == JIM_TT_EXPRSUGAR) {
7849 return JIM_ERR;
7851 return JIM_OK;
7853 break;
7854 case '0':
7855 case '1':
7856 case '2':
7857 case '3':
7858 case '4':
7859 case '5':
7860 case '6':
7861 case '7':
7862 case '8':
7863 case '9':
7864 case '.':
7865 return JimParseExprNumber(pc);
7866 case '"':
7867 return JimParseQuote(pc);
7868 case '{':
7869 return JimParseBrace(pc);
7871 case 'N':
7872 case 'I':
7873 case 'n':
7874 case 'i':
7875 if (JimParseExprIrrational(pc) == JIM_ERR)
7876 return JimParseExprOperator(pc);
7877 break;
7878 default:
7879 return JimParseExprOperator(pc);
7880 break;
7882 return JIM_OK;
7885 static int JimParseExprNumber(struct JimParserCtx *pc)
7887 int allowdot = 1;
7888 int allowhex = 0;
7890 /* Assume an integer for now */
7891 pc->tt = JIM_TT_EXPR_INT;
7892 pc->tstart = pc->p;
7893 pc->tline = pc->linenr;
7894 while (isdigit(UCHAR(*pc->p))
7895 || (allowhex && isxdigit(UCHAR(*pc->p)))
7896 || (allowdot && *pc->p == '.')
7897 || (pc->p - pc->tstart == 1 && *pc->tstart == '0' && (*pc->p == 'x' || *pc->p == 'X'))
7899 if ((*pc->p == 'x') || (*pc->p == 'X')) {
7900 allowhex = 1;
7901 allowdot = 0;
7903 if (*pc->p == '.') {
7904 allowdot = 0;
7905 pc->tt = JIM_TT_EXPR_DOUBLE;
7907 pc->p++;
7908 pc->len--;
7909 if (!allowhex && (*pc->p == 'e' || *pc->p == 'E') && (pc->p[1] == '-' || pc->p[1] == '+'
7910 || isdigit(UCHAR(pc->p[1])))) {
7911 pc->p += 2;
7912 pc->len -= 2;
7913 pc->tt = JIM_TT_EXPR_DOUBLE;
7916 pc->tend = pc->p - 1;
7917 return JIM_OK;
7920 static int JimParseExprIrrational(struct JimParserCtx *pc)
7922 const char *Tokens[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
7923 const char **token;
7925 for (token = Tokens; *token != NULL; token++) {
7926 int len = strlen(*token);
7928 if (strncmp(*token, pc->p, len) == 0) {
7929 pc->tstart = pc->p;
7930 pc->tend = pc->p + len - 1;
7931 pc->p += len;
7932 pc->len -= len;
7933 pc->tline = pc->linenr;
7934 pc->tt = JIM_TT_EXPR_DOUBLE;
7935 return JIM_OK;
7938 return JIM_ERR;
7941 static int JimParseExprOperator(struct JimParserCtx *pc)
7943 int i;
7944 int bestIdx = -1, bestLen = 0;
7946 /* Try to get the longest match. */
7947 for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
7948 const char *opname;
7949 int oplen;
7951 opname = Jim_ExprOperators[i].name;
7952 if (opname == NULL) {
7953 continue;
7955 oplen = strlen(opname);
7957 if (strncmp(opname, pc->p, oplen) == 0 && oplen > bestLen) {
7958 bestIdx = i + JIM_TT_EXPR_OP;
7959 bestLen = oplen;
7962 if (bestIdx == -1) {
7963 return JIM_ERR;
7966 /* Validate paretheses around function arguments */
7967 if (bestIdx >= JIM_EXPROP_FUNC_FIRST) {
7968 const char *p = pc->p + bestLen;
7969 int len = pc->len - bestLen;
7971 while (len && isspace(UCHAR(*p))) {
7972 len--;
7973 p++;
7975 if (*p != '(') {
7976 return JIM_ERR;
7979 pc->tstart = pc->p;
7980 pc->tend = pc->p + bestLen - 1;
7981 pc->p += bestLen;
7982 pc->len -= bestLen;
7983 pc->tline = pc->linenr;
7985 pc->tt = bestIdx;
7986 return JIM_OK;
7989 static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
7991 static Jim_ExprOperator dummy_op;
7992 if (opcode < JIM_TT_EXPR_OP) {
7993 return &dummy_op;
7995 return &Jim_ExprOperators[opcode - JIM_TT_EXPR_OP];
7998 const char *jim_tt_name(int type)
8000 static const char * const tt_names[JIM_TT_EXPR_OP] =
8001 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", ",,,", "INT",
8002 "DBL", "$()" };
8003 if (type < JIM_TT_EXPR_OP) {
8004 return tt_names[type];
8006 else {
8007 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(type);
8008 static char buf[20];
8010 if (op->name) {
8011 return op->name;
8013 sprintf(buf, "(%d)", type);
8014 return buf;
8018 /* -----------------------------------------------------------------------------
8019 * Expression Object
8020 * ---------------------------------------------------------------------------*/
8021 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
8022 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
8023 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
8025 static const Jim_ObjType exprObjType = {
8026 "expression",
8027 FreeExprInternalRep,
8028 DupExprInternalRep,
8029 NULL,
8030 JIM_TYPE_REFERENCES,
8033 /* Expr bytecode structure */
8034 typedef struct ExprByteCode
8036 int len; /* Length as number of tokens. */
8037 ScriptToken *token; /* Tokens array. */
8038 int inUse; /* Used for sharing. */
8039 } ExprByteCode;
8041 static void ExprFreeByteCode(Jim_Interp *interp, ExprByteCode * expr)
8043 int i;
8045 for (i = 0; i < expr->len; i++) {
8046 Jim_DecrRefCount(interp, expr->token[i].objPtr);
8048 Jim_Free(expr->token);
8049 Jim_Free(expr);
8052 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8054 ExprByteCode *expr = (void *)objPtr->internalRep.ptr;
8056 if (expr) {
8057 if (--expr->inUse != 0) {
8058 return;
8061 ExprFreeByteCode(interp, expr);
8065 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8067 JIM_NOTUSED(interp);
8068 JIM_NOTUSED(srcPtr);
8070 /* Just returns an simple string. */
8071 dupPtr->typePtr = NULL;
8074 /* Check if an expr program looks correct. */
8075 static int ExprCheckCorrectness(ExprByteCode * expr)
8077 int i;
8078 int stacklen = 0;
8079 int ternary = 0;
8081 /* Try to check if there are stack underflows,
8082 * and make sure at the end of the program there is
8083 * a single result on the stack. */
8084 for (i = 0; i < expr->len; i++) {
8085 ScriptToken *t = &expr->token[i];
8086 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8088 stacklen -= op->arity;
8089 if (stacklen < 0) {
8090 break;
8092 if (t->type == JIM_EXPROP_TERNARY || t->type == JIM_EXPROP_TERNARY_LEFT) {
8093 ternary++;
8095 else if (t->type == JIM_EXPROP_COLON || t->type == JIM_EXPROP_COLON_LEFT) {
8096 ternary--;
8099 /* All operations and operands add one to the stack */
8100 stacklen++;
8102 if (stacklen != 1 || ternary != 0) {
8103 return JIM_ERR;
8105 return JIM_OK;
8108 /* This procedure converts every occurrence of || and && opereators
8109 * in lazy unary versions.
8111 * a b || is converted into:
8113 * a <offset> |L b |R
8115 * a b && is converted into:
8117 * a <offset> &L b &R
8119 * "|L" checks if 'a' is true:
8120 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8121 * the opcode just after |R.
8122 * 2) if it is false does nothing.
8123 * "|R" checks if 'b' is true:
8124 * 1) if it is true pushes 1, otherwise pushes 0.
8126 * "&L" checks if 'a' is true:
8127 * 1) if it is true does nothing.
8128 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8129 * the opcode just after &R
8130 * "&R" checks if 'a' is true:
8131 * if it is true pushes 1, otherwise pushes 0.
8133 static int ExprAddLazyOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8135 int i;
8137 int leftindex, arity, offset;
8139 /* Search for the end of the first operator */
8140 leftindex = expr->len - 1;
8142 arity = 1;
8143 while (arity) {
8144 ScriptToken *tt = &expr->token[leftindex];
8146 if (tt->type >= JIM_TT_EXPR_OP) {
8147 arity += JimExprOperatorInfoByOpcode(tt->type)->arity;
8149 arity--;
8150 if (--leftindex < 0) {
8151 return JIM_ERR;
8154 leftindex++;
8156 /* Move them up */
8157 memmove(&expr->token[leftindex + 2], &expr->token[leftindex],
8158 sizeof(*expr->token) * (expr->len - leftindex));
8159 expr->len += 2;
8160 offset = (expr->len - leftindex) - 1;
8162 /* Now we rely on the fact the the left and right version have opcodes
8163 * 1 and 2 after the main opcode respectively
8165 expr->token[leftindex + 1].type = t->type + 1;
8166 expr->token[leftindex + 1].objPtr = interp->emptyObj;
8168 expr->token[leftindex].type = JIM_TT_EXPR_INT;
8169 expr->token[leftindex].objPtr = Jim_NewIntObj(interp, offset);
8171 /* Now add the 'R' operator */
8172 expr->token[expr->len].objPtr = interp->emptyObj;
8173 expr->token[expr->len].type = t->type + 2;
8174 expr->len++;
8176 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8177 for (i = leftindex - 1; i > 0; i--) {
8178 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(expr->token[i].type);
8179 if (op->lazy == LAZY_LEFT) {
8180 if (JimWideValue(expr->token[i - 1].objPtr) + i - 1 >= leftindex) {
8181 JimWideValue(expr->token[i - 1].objPtr) += 2;
8185 return JIM_OK;
8188 static int ExprAddOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8190 struct ScriptToken *token = &expr->token[expr->len];
8191 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8193 if (op->lazy == LAZY_OP) {
8194 if (ExprAddLazyOperator(interp, expr, t) != JIM_OK) {
8195 Jim_SetResultFormatted(interp, "Expression has bad operands to %s", op->name);
8196 return JIM_ERR;
8199 else {
8200 token->objPtr = interp->emptyObj;
8201 token->type = t->type;
8202 expr->len++;
8204 return JIM_OK;
8208 * Returns the index of the COLON_LEFT to the left of 'right_index'
8209 * taking into account nesting.
8211 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8213 static int ExprTernaryGetColonLeftIndex(ExprByteCode *expr, int right_index)
8215 int ternary_count = 1;
8217 right_index--;
8219 while (right_index > 1) {
8220 if (expr->token[right_index].type == JIM_EXPROP_TERNARY_LEFT) {
8221 ternary_count--;
8223 else if (expr->token[right_index].type == JIM_EXPROP_COLON_RIGHT) {
8224 ternary_count++;
8226 else if (expr->token[right_index].type == JIM_EXPROP_COLON_LEFT && ternary_count == 1) {
8227 return right_index;
8229 right_index--;
8232 /*notreached*/
8233 return -1;
8237 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8239 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8240 * Otherwise returns 0.
8242 static int ExprTernaryGetMoveIndices(ExprByteCode *expr, int right_index, int *prev_right_index, int *prev_left_index)
8244 int i = right_index - 1;
8245 int ternary_count = 1;
8247 while (i > 1) {
8248 if (expr->token[i].type == JIM_EXPROP_TERNARY_LEFT) {
8249 if (--ternary_count == 0 && expr->token[i - 2].type == JIM_EXPROP_COLON_RIGHT) {
8250 *prev_right_index = i - 2;
8251 *prev_left_index = ExprTernaryGetColonLeftIndex(expr, *prev_right_index);
8252 return 1;
8255 else if (expr->token[i].type == JIM_EXPROP_COLON_RIGHT) {
8256 if (ternary_count == 0) {
8257 return 0;
8259 ternary_count++;
8261 i--;
8263 return 0;
8267 * ExprTernaryReorderExpression description
8268 * ========================================
8270 * ?: is right-to-left associative which doesn't work with the stack-based
8271 * expression engine. The fix is to reorder the bytecode.
8273 * The expression:
8275 * expr 1?2:0?3:4
8277 * Has initial bytecode:
8279 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8280 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8282 * The fix involves simulating this expression instead:
8284 * expr 1?2:(0?3:4)
8286 * With the following bytecode:
8288 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8289 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8291 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8292 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8293 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8294 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8296 * ExprTernaryReorderExpression works thus as follows :
8297 * - start from the end of the stack
8298 * - while walking towards the beginning of the stack
8299 * if token=JIM_EXPROP_COLON_RIGHT then
8300 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8301 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8302 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8303 * if all found then
8304 * perform the rotation
8305 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8306 * end if
8307 * end if
8309 * Note: care has to be taken for nested ternary constructs!!!
8311 static void ExprTernaryReorderExpression(Jim_Interp *interp, ExprByteCode *expr)
8313 int i;
8315 for (i = expr->len - 1; i > 1; i--) {
8316 int prev_right_index;
8317 int prev_left_index;
8318 int j;
8319 ScriptToken tmp;
8321 if (expr->token[i].type != JIM_EXPROP_COLON_RIGHT) {
8322 continue;
8325 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8326 if (ExprTernaryGetMoveIndices(expr, i, &prev_right_index, &prev_left_index) == 0) {
8327 continue;
8331 ** rotate tokens down
8333 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8334 ** | | |
8335 ** | V V
8336 ** | [...] : ...
8337 ** | | |
8338 ** | V V
8339 ** | [...] : ...
8340 ** | | |
8341 ** | V V
8342 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8344 tmp = expr->token[prev_right_index];
8345 for (j = prev_right_index; j < i; j++) {
8346 expr->token[j] = expr->token[j + 1];
8348 expr->token[i] = tmp;
8350 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8352 * This is 'colon left increment' = i - prev_right_index
8354 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8355 * [prev_left_index-1] : skip_count
8358 JimWideValue(expr->token[prev_left_index-1].objPtr) += (i - prev_right_index);
8360 /* Adjust for i-- in the loop */
8361 i++;
8365 static ExprByteCode *ExprCreateByteCode(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *fileNameObj)
8367 Jim_Stack stack;
8368 ExprByteCode *expr;
8369 int ok = 1;
8370 int i;
8371 int prevtt = JIM_TT_NONE;
8372 int have_ternary = 0;
8374 /* -1 for EOL */
8375 int count = tokenlist->count - 1;
8377 expr = Jim_Alloc(sizeof(*expr));
8378 expr->inUse = 1;
8379 expr->len = 0;
8381 Jim_InitStack(&stack);
8383 /* Need extra bytecodes for lazy operators.
8384 * Also check for the ternary operator
8386 for (i = 0; i < tokenlist->count; i++) {
8387 ParseToken *t = &tokenlist->list[i];
8388 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8390 if (op->lazy == LAZY_OP) {
8391 count += 2;
8392 /* Ternary is a lazy op but also needs reordering */
8393 if (t->type == JIM_EXPROP_TERNARY) {
8394 have_ternary = 1;
8399 expr->token = Jim_Alloc(sizeof(ScriptToken) * count);
8401 for (i = 0; i < tokenlist->count && ok; i++) {
8402 ParseToken *t = &tokenlist->list[i];
8404 /* Next token will be stored here */
8405 struct ScriptToken *token = &expr->token[expr->len];
8407 if (t->type == JIM_TT_EOL) {
8408 break;
8411 switch (t->type) {
8412 case JIM_TT_STR:
8413 case JIM_TT_ESC:
8414 case JIM_TT_VAR:
8415 case JIM_TT_DICTSUGAR:
8416 case JIM_TT_EXPRSUGAR:
8417 case JIM_TT_CMD:
8418 token->objPtr = Jim_NewStringObj(interp, t->token, t->len);
8419 token->type = t->type;
8420 if (t->type == JIM_TT_CMD) {
8421 /* Only commands need source info */
8422 JimSetSourceInfo(interp, token->objPtr, fileNameObj, t->line);
8424 expr->len++;
8425 break;
8427 case JIM_TT_EXPR_INT:
8428 token->objPtr = Jim_NewIntObj(interp, strtoull(t->token, NULL, 0));
8429 token->type = t->type;
8430 expr->len++;
8431 break;
8433 case JIM_TT_EXPR_DOUBLE:
8434 token->objPtr = Jim_NewDoubleObj(interp, strtod(t->token, NULL));
8435 token->type = t->type;
8436 expr->len++;
8437 break;
8439 case JIM_TT_SUBEXPR_START:
8440 Jim_StackPush(&stack, t);
8441 prevtt = JIM_TT_NONE;
8442 continue;
8444 case JIM_TT_SUBEXPR_COMMA:
8445 /* Simple approach. Comma is simply ignored */
8446 continue;
8448 case JIM_TT_SUBEXPR_END:
8449 ok = 0;
8450 while (Jim_StackLen(&stack)) {
8451 ParseToken *tt = Jim_StackPop(&stack);
8453 if (tt->type == JIM_TT_SUBEXPR_START) {
8454 ok = 1;
8455 break;
8458 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8459 goto err;
8462 if (!ok) {
8463 Jim_SetResultString(interp, "Unexpected close parenthesis", -1);
8464 goto err;
8466 break;
8469 default:{
8470 /* Must be an operator */
8471 const struct Jim_ExprOperator *op;
8472 ParseToken *tt;
8474 /* Convert -/+ to unary minus or unary plus if necessary */
8475 if (prevtt == JIM_TT_NONE || prevtt >= JIM_TT_EXPR_OP) {
8476 if (t->type == JIM_EXPROP_SUB) {
8477 t->type = JIM_EXPROP_UNARYMINUS;
8479 else if (t->type == JIM_EXPROP_ADD) {
8480 t->type = JIM_EXPROP_UNARYPLUS;
8484 op = JimExprOperatorInfoByOpcode(t->type);
8486 /* Now handle precedence */
8487 while ((tt = Jim_StackPeek(&stack)) != NULL) {
8488 const struct Jim_ExprOperator *tt_op =
8489 JimExprOperatorInfoByOpcode(tt->type);
8491 /* Note that right-to-left associativity of ?: operator is handled later */
8493 if (op->arity != 1 && tt_op->precedence >= op->precedence) {
8494 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8495 ok = 0;
8496 goto err;
8498 Jim_StackPop(&stack);
8500 else {
8501 break;
8504 Jim_StackPush(&stack, t);
8505 break;
8508 prevtt = t->type;
8511 /* Reduce any remaining subexpr */
8512 while (Jim_StackLen(&stack)) {
8513 ParseToken *tt = Jim_StackPop(&stack);
8515 if (tt->type == JIM_TT_SUBEXPR_START) {
8516 ok = 0;
8517 Jim_SetResultString(interp, "Missing close parenthesis", -1);
8518 goto err;
8520 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8521 ok = 0;
8522 goto err;
8526 if (have_ternary) {
8527 ExprTernaryReorderExpression(interp, expr);
8530 err:
8531 /* Free the stack used for the compilation. */
8532 Jim_FreeStack(&stack);
8534 for (i = 0; i < expr->len; i++) {
8535 Jim_IncrRefCount(expr->token[i].objPtr);
8538 if (!ok) {
8539 ExprFreeByteCode(interp, expr);
8540 return NULL;
8543 return expr;
8547 /* This method takes the string representation of an expression
8548 * and generates a program for the Expr's stack-based VM. */
8549 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
8551 int exprTextLen;
8552 const char *exprText;
8553 struct JimParserCtx parser;
8554 struct ExprByteCode *expr;
8555 ParseTokenList tokenlist;
8556 int line;
8557 Jim_Obj *fileNameObj;
8558 int rc = JIM_ERR;
8560 /* Try to get information about filename / line number */
8561 if (objPtr->typePtr == &sourceObjType) {
8562 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
8563 line = objPtr->internalRep.sourceValue.lineNumber;
8565 else {
8566 fileNameObj = interp->emptyObj;
8567 line = 1;
8569 Jim_IncrRefCount(fileNameObj);
8571 exprText = Jim_GetString(objPtr, &exprTextLen);
8573 /* Initially tokenise the expression into tokenlist */
8574 ScriptTokenListInit(&tokenlist);
8576 JimParserInit(&parser, exprText, exprTextLen, line);
8577 while (!parser.eof) {
8578 if (JimParseExpression(&parser) != JIM_OK) {
8579 ScriptTokenListFree(&tokenlist);
8580 invalidexpr:
8581 Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
8582 expr = NULL;
8583 goto err;
8586 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
8587 parser.tline);
8590 #ifdef DEBUG_SHOW_EXPR_TOKENS
8592 int i;
8593 printf("==== Expr Tokens ====\n");
8594 for (i = 0; i < tokenlist.count; i++) {
8595 printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
8596 tokenlist.list[i].len, tokenlist.list[i].token);
8599 #endif
8601 /* Now create the expression bytecode from the tokenlist */
8602 expr = ExprCreateByteCode(interp, &tokenlist, fileNameObj);
8604 /* No longer need the token list */
8605 ScriptTokenListFree(&tokenlist);
8607 if (!expr) {
8608 goto err;
8611 #ifdef DEBUG_SHOW_EXPR
8613 int i;
8615 printf("==== Expr ====\n");
8616 for (i = 0; i < expr->len; i++) {
8617 ScriptToken *t = &expr->token[i];
8619 printf("[%2d] %s '%s'\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
8622 #endif
8624 /* Check program correctness. */
8625 if (ExprCheckCorrectness(expr) != JIM_OK) {
8626 ExprFreeByteCode(interp, expr);
8627 goto invalidexpr;
8630 rc = JIM_OK;
8632 err:
8633 /* Free the old internal rep and set the new one. */
8634 Jim_DecrRefCount(interp, fileNameObj);
8635 Jim_FreeIntRep(interp, objPtr);
8636 Jim_SetIntRepPtr(objPtr, expr);
8637 objPtr->typePtr = &exprObjType;
8638 return rc;
8641 static ExprByteCode *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
8643 if (objPtr->typePtr != &exprObjType) {
8644 if (SetExprFromAny(interp, objPtr) != JIM_OK) {
8645 return NULL;
8648 return (ExprByteCode *) Jim_GetIntRepPtr(objPtr);
8651 /* -----------------------------------------------------------------------------
8652 * Expressions evaluation.
8653 * Jim uses a specialized stack-based virtual machine for expressions,
8654 * that takes advantage of the fact that expr's operators
8655 * can't be redefined.
8657 * Jim_EvalExpression() uses the bytecode compiled by
8658 * SetExprFromAny() method of the "expression" object.
8660 * On success a Tcl Object containing the result of the evaluation
8661 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8662 * returned.
8663 * On error the function returns a retcode != to JIM_OK and set a suitable
8664 * error on the interp.
8665 * ---------------------------------------------------------------------------*/
8666 #define JIM_EE_STATICSTACK_LEN 10
8668 int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr, Jim_Obj **exprResultPtrPtr)
8670 ExprByteCode *expr;
8671 Jim_Obj *staticStack[JIM_EE_STATICSTACK_LEN];
8672 int i;
8673 int retcode = JIM_OK;
8674 struct JimExprState e;
8676 expr = JimGetExpression(interp, exprObjPtr);
8677 if (!expr) {
8678 return JIM_ERR; /* error in expression. */
8681 #ifdef JIM_OPTIMIZATION
8682 /* Check for one of the following common expressions used by while/for
8684 * CONST
8685 * $a
8686 * !$a
8687 * $a < CONST, $a < $b
8688 * $a <= CONST, $a <= $b
8689 * $a > CONST, $a > $b
8690 * $a >= CONST, $a >= $b
8691 * $a != CONST, $a != $b
8692 * $a == CONST, $a == $b
8695 Jim_Obj *objPtr;
8697 /* STEP 1 -- Check if there are the conditions to run the specialized
8698 * version of while */
8700 switch (expr->len) {
8701 case 1:
8702 if (expr->token[0].type == JIM_TT_EXPR_INT) {
8703 *exprResultPtrPtr = expr->token[0].objPtr;
8704 Jim_IncrRefCount(*exprResultPtrPtr);
8705 return JIM_OK;
8707 if (expr->token[0].type == JIM_TT_VAR) {
8708 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_ERRMSG);
8709 if (objPtr) {
8710 *exprResultPtrPtr = objPtr;
8711 Jim_IncrRefCount(*exprResultPtrPtr);
8712 return JIM_OK;
8715 break;
8717 case 2:
8718 if (expr->token[1].type == JIM_EXPROP_NOT && expr->token[0].type == JIM_TT_VAR) {
8719 jim_wide wideValue;
8721 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8722 if (objPtr && JimIsWide(objPtr)
8723 && Jim_GetWide(interp, objPtr, &wideValue) == JIM_OK) {
8724 *exprResultPtrPtr = wideValue ? interp->falseObj : interp->trueObj;
8725 Jim_IncrRefCount(*exprResultPtrPtr);
8726 return JIM_OK;
8729 break;
8731 case 3:
8732 if (expr->token[0].type == JIM_TT_VAR && (expr->token[1].type == JIM_TT_EXPR_INT
8733 || expr->token[1].type == JIM_TT_VAR)) {
8734 switch (expr->token[2].type) {
8735 case JIM_EXPROP_LT:
8736 case JIM_EXPROP_LTE:
8737 case JIM_EXPROP_GT:
8738 case JIM_EXPROP_GTE:
8739 case JIM_EXPROP_NUMEQ:
8740 case JIM_EXPROP_NUMNE:{
8741 /* optimise ok */
8742 jim_wide wideValueA;
8743 jim_wide wideValueB;
8745 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8746 if (objPtr && JimIsWide(objPtr)
8747 && Jim_GetWide(interp, objPtr, &wideValueA) == JIM_OK) {
8748 if (expr->token[1].type == JIM_TT_VAR) {
8749 objPtr =
8750 Jim_GetVariable(interp, expr->token[1].objPtr,
8751 JIM_NONE);
8753 else {
8754 objPtr = expr->token[1].objPtr;
8756 if (objPtr && JimIsWide(objPtr)
8757 && Jim_GetWide(interp, objPtr, &wideValueB) == JIM_OK) {
8758 int cmpRes;
8760 switch (expr->token[2].type) {
8761 case JIM_EXPROP_LT:
8762 cmpRes = wideValueA < wideValueB;
8763 break;
8764 case JIM_EXPROP_LTE:
8765 cmpRes = wideValueA <= wideValueB;
8766 break;
8767 case JIM_EXPROP_GT:
8768 cmpRes = wideValueA > wideValueB;
8769 break;
8770 case JIM_EXPROP_GTE:
8771 cmpRes = wideValueA >= wideValueB;
8772 break;
8773 case JIM_EXPROP_NUMEQ:
8774 cmpRes = wideValueA == wideValueB;
8775 break;
8776 case JIM_EXPROP_NUMNE:
8777 cmpRes = wideValueA != wideValueB;
8778 break;
8779 default: /*notreached */
8780 cmpRes = 0;
8782 *exprResultPtrPtr =
8783 cmpRes ? interp->trueObj : interp->falseObj;
8784 Jim_IncrRefCount(*exprResultPtrPtr);
8785 return JIM_OK;
8791 break;
8794 #endif
8796 /* In order to avoid that the internal repr gets freed due to
8797 * shimmering of the exprObjPtr's object, we make the internal rep
8798 * shared. */
8799 expr->inUse++;
8801 /* The stack-based expr VM itself */
8803 /* Stack allocation. Expr programs have the feature that
8804 * a program of length N can't require a stack longer than
8805 * N. */
8806 if (expr->len > JIM_EE_STATICSTACK_LEN)
8807 e.stack = Jim_Alloc(sizeof(Jim_Obj *) * expr->len);
8808 else
8809 e.stack = staticStack;
8811 e.stacklen = 0;
8813 /* Execute every instruction */
8814 for (i = 0; i < expr->len && retcode == JIM_OK; i++) {
8815 Jim_Obj *objPtr;
8817 switch (expr->token[i].type) {
8818 case JIM_TT_EXPR_INT:
8819 case JIM_TT_EXPR_DOUBLE:
8820 case JIM_TT_STR:
8821 ExprPush(&e, expr->token[i].objPtr);
8822 break;
8824 case JIM_TT_VAR:
8825 objPtr = Jim_GetVariable(interp, expr->token[i].objPtr, JIM_ERRMSG);
8826 if (objPtr) {
8827 ExprPush(&e, objPtr);
8829 else {
8830 retcode = JIM_ERR;
8832 break;
8834 case JIM_TT_DICTSUGAR:
8835 objPtr = JimExpandDictSugar(interp, expr->token[i].objPtr);
8836 if (objPtr) {
8837 ExprPush(&e, objPtr);
8839 else {
8840 retcode = JIM_ERR;
8842 break;
8844 case JIM_TT_ESC:
8845 retcode = Jim_SubstObj(interp, expr->token[i].objPtr, &objPtr, JIM_NONE);
8846 if (retcode == JIM_OK) {
8847 ExprPush(&e, objPtr);
8849 break;
8851 case JIM_TT_CMD:
8852 retcode = Jim_EvalObj(interp, expr->token[i].objPtr);
8853 if (retcode == JIM_OK) {
8854 ExprPush(&e, Jim_GetResult(interp));
8856 break;
8858 default:{
8859 /* Find and execute the operation */
8860 e.skip = 0;
8861 e.opcode = expr->token[i].type;
8863 retcode = JimExprOperatorInfoByOpcode(e.opcode)->funcop(interp, &e);
8864 /* Skip some opcodes if necessary */
8865 i += e.skip;
8866 continue;
8871 expr->inUse--;
8873 if (retcode == JIM_OK) {
8874 *exprResultPtrPtr = ExprPop(&e);
8876 else {
8877 for (i = 0; i < e.stacklen; i++) {
8878 Jim_DecrRefCount(interp, e.stack[i]);
8881 if (e.stack != staticStack) {
8882 Jim_Free(e.stack);
8884 return retcode;
8887 int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
8889 int retcode;
8890 jim_wide wideValue;
8891 double doubleValue;
8892 Jim_Obj *exprResultPtr;
8894 retcode = Jim_EvalExpression(interp, exprObjPtr, &exprResultPtr);
8895 if (retcode != JIM_OK)
8896 return retcode;
8898 if (JimGetWideNoErr(interp, exprResultPtr, &wideValue) != JIM_OK) {
8899 if (Jim_GetDouble(interp, exprResultPtr, &doubleValue) != JIM_OK) {
8900 Jim_DecrRefCount(interp, exprResultPtr);
8901 return JIM_ERR;
8903 else {
8904 Jim_DecrRefCount(interp, exprResultPtr);
8905 *boolPtr = doubleValue != 0;
8906 return JIM_OK;
8909 *boolPtr = wideValue != 0;
8911 Jim_DecrRefCount(interp, exprResultPtr);
8912 return JIM_OK;
8915 /* -----------------------------------------------------------------------------
8916 * ScanFormat String Object
8917 * ---------------------------------------------------------------------------*/
8919 /* This Jim_Obj will held a parsed representation of a format string passed to
8920 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8921 * to be parsed in its entirely first and then, if correct, can be used for
8922 * scanning. To avoid endless re-parsing, the parsed representation will be
8923 * stored in an internal representation and re-used for performance reason. */
8925 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8926 * scanformat string. This part will later be used to extract information
8927 * out from the string to be parsed by Jim_ScanString */
8929 typedef struct ScanFmtPartDescr
8931 char type; /* Type of conversion (e.g. c, d, f) */
8932 char modifier; /* Modify type (e.g. l - long, h - short */
8933 size_t width; /* Maximal width of input to be converted */
8934 int pos; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8935 char *arg; /* Specification of a CHARSET conversion */
8936 char *prefix; /* Prefix to be scanned literally before conversion */
8937 } ScanFmtPartDescr;
8939 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8940 * string parsed and separated in part descriptions. Furthermore it contains
8941 * the original string representation of the scanformat string to allow for
8942 * fast update of the Jim_Obj's string representation part.
8944 * As an add-on the internal object representation adds some scratch pad area
8945 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8946 * memory for purpose of string scanning.
8948 * The error member points to a static allocated string in case of a mal-
8949 * formed scanformat string or it contains '0' (NULL) in case of a valid
8950 * parse representation.
8952 * The whole memory of the internal representation is allocated as a single
8953 * area of memory that will be internally separated. So freeing and duplicating
8954 * of such an object is cheap */
8956 typedef struct ScanFmtStringObj
8958 jim_wide size; /* Size of internal repr in bytes */
8959 char *stringRep; /* Original string representation */
8960 size_t count; /* Number of ScanFmtPartDescr contained */
8961 size_t convCount; /* Number of conversions that will assign */
8962 size_t maxPos; /* Max position index if XPG3 is used */
8963 const char *error; /* Ptr to error text (NULL if no error */
8964 char *scratch; /* Some scratch pad used by Jim_ScanString */
8965 ScanFmtPartDescr descr[1]; /* The vector of partial descriptions */
8966 } ScanFmtStringObj;
8969 static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
8970 static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
8971 static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
8973 static const Jim_ObjType scanFmtStringObjType = {
8974 "scanformatstring",
8975 FreeScanFmtInternalRep,
8976 DupScanFmtInternalRep,
8977 UpdateStringOfScanFmt,
8978 JIM_TYPE_NONE,
8981 void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8983 JIM_NOTUSED(interp);
8984 Jim_Free((char *)objPtr->internalRep.ptr);
8985 objPtr->internalRep.ptr = 0;
8988 void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8990 size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
8991 ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
8993 JIM_NOTUSED(interp);
8994 memcpy(newVec, srcPtr->internalRep.ptr, size);
8995 dupPtr->internalRep.ptr = newVec;
8996 dupPtr->typePtr = &scanFmtStringObjType;
8999 void UpdateStringOfScanFmt(Jim_Obj *objPtr)
9001 char *bytes = ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep;
9003 objPtr->bytes = Jim_StrDup(bytes);
9004 objPtr->length = strlen(bytes);
9007 /* SetScanFmtFromAny will parse a given string and create the internal
9008 * representation of the format specification. In case of an error
9009 * the error data member of the internal representation will be set
9010 * to an descriptive error text and the function will be left with
9011 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
9012 * specification */
9014 static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
9016 ScanFmtStringObj *fmtObj;
9017 char *buffer;
9018 int maxCount, i, approxSize, lastPos = -1;
9019 const char *fmt = objPtr->bytes;
9020 int maxFmtLen = objPtr->length;
9021 const char *fmtEnd = fmt + maxFmtLen;
9022 int curr;
9024 Jim_FreeIntRep(interp, objPtr);
9025 /* Count how many conversions could take place maximally */
9026 for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
9027 if (fmt[i] == '%')
9028 ++maxCount;
9029 /* Calculate an approximation of the memory necessary */
9030 approxSize = sizeof(ScanFmtStringObj) /* Size of the container */
9031 +(maxCount + 1) * sizeof(ScanFmtPartDescr) /* Size of all partials */
9032 +maxFmtLen * sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
9033 + maxFmtLen * sizeof(char) + 1 /* Original stringrep */
9034 + maxFmtLen * sizeof(char) /* Arg for CHARSETs */
9035 +(maxCount + 1) * sizeof(char) /* '\0' for every partial */
9036 +1; /* safety byte */
9037 fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
9038 memset(fmtObj, 0, approxSize);
9039 fmtObj->size = approxSize;
9040 fmtObj->maxPos = 0;
9041 fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
9042 fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
9043 memcpy(fmtObj->stringRep, fmt, maxFmtLen);
9044 buffer = fmtObj->stringRep + maxFmtLen + 1;
9045 objPtr->internalRep.ptr = fmtObj;
9046 objPtr->typePtr = &scanFmtStringObjType;
9047 for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
9048 int width = 0, skip;
9049 ScanFmtPartDescr *descr = &fmtObj->descr[curr];
9051 fmtObj->count++;
9052 descr->width = 0; /* Assume width unspecified */
9053 /* Overread and store any "literal" prefix */
9054 if (*fmt != '%' || fmt[1] == '%') {
9055 descr->type = 0;
9056 descr->prefix = &buffer[i];
9057 for (; fmt < fmtEnd; ++fmt) {
9058 if (*fmt == '%') {
9059 if (fmt[1] != '%')
9060 break;
9061 ++fmt;
9063 buffer[i++] = *fmt;
9065 buffer[i++] = 0;
9067 /* Skip the conversion introducing '%' sign */
9068 ++fmt;
9069 /* End reached due to non-conversion literal only? */
9070 if (fmt >= fmtEnd)
9071 goto done;
9072 descr->pos = 0; /* Assume "natural" positioning */
9073 if (*fmt == '*') {
9074 descr->pos = -1; /* Okay, conversion will not be assigned */
9075 ++fmt;
9077 else
9078 fmtObj->convCount++; /* Otherwise count as assign-conversion */
9079 /* Check if next token is a number (could be width or pos */
9080 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9081 fmt += skip;
9082 /* Was the number a XPG3 position specifier? */
9083 if (descr->pos != -1 && *fmt == '$') {
9084 int prev;
9086 ++fmt;
9087 descr->pos = width;
9088 width = 0;
9089 /* Look if "natural" postioning and XPG3 one was mixed */
9090 if ((lastPos == 0 && descr->pos > 0)
9091 || (lastPos > 0 && descr->pos == 0)) {
9092 fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
9093 return JIM_ERR;
9095 /* Look if this position was already used */
9096 for (prev = 0; prev < curr; ++prev) {
9097 if (fmtObj->descr[prev].pos == -1)
9098 continue;
9099 if (fmtObj->descr[prev].pos == descr->pos) {
9100 fmtObj->error =
9101 "variable is assigned by multiple \"%n$\" conversion specifiers";
9102 return JIM_ERR;
9105 /* Try to find a width after the XPG3 specifier */
9106 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9107 descr->width = width;
9108 fmt += skip;
9110 if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
9111 fmtObj->maxPos = descr->pos;
9113 else {
9114 /* Number was not a XPG3, so it has to be a width */
9115 descr->width = width;
9118 /* If positioning mode was undetermined yet, fix this */
9119 if (lastPos == -1)
9120 lastPos = descr->pos;
9121 /* Handle CHARSET conversion type ... */
9122 if (*fmt == '[') {
9123 int swapped = 1, beg = i, end, j;
9125 descr->type = '[';
9126 descr->arg = &buffer[i];
9127 ++fmt;
9128 if (*fmt == '^')
9129 buffer[i++] = *fmt++;
9130 if (*fmt == ']')
9131 buffer[i++] = *fmt++;
9132 while (*fmt && *fmt != ']')
9133 buffer[i++] = *fmt++;
9134 if (*fmt != ']') {
9135 fmtObj->error = "unmatched [ in format string";
9136 return JIM_ERR;
9138 end = i;
9139 buffer[i++] = 0;
9140 /* In case a range fence was given "backwards", swap it */
9141 while (swapped) {
9142 swapped = 0;
9143 for (j = beg + 1; j < end - 1; ++j) {
9144 if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
9145 char tmp = buffer[j - 1];
9147 buffer[j - 1] = buffer[j + 1];
9148 buffer[j + 1] = tmp;
9149 swapped = 1;
9154 else {
9155 /* Remember any valid modifier if given */
9156 if (strchr("hlL", *fmt) != 0)
9157 descr->modifier = tolower((int)*fmt++);
9159 descr->type = *fmt;
9160 if (strchr("efgcsndoxui", *fmt) == 0) {
9161 fmtObj->error = "bad scan conversion character";
9162 return JIM_ERR;
9164 else if (*fmt == 'c' && descr->width != 0) {
9165 fmtObj->error = "field width may not be specified in %c " "conversion";
9166 return JIM_ERR;
9168 else if (*fmt == 'u' && descr->modifier == 'l') {
9169 fmtObj->error = "unsigned wide not supported";
9170 return JIM_ERR;
9173 curr++;
9175 done:
9176 return JIM_OK;
9179 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9181 #define FormatGetCnvCount(_fo_) \
9182 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9183 #define FormatGetMaxPos(_fo_) \
9184 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9185 #define FormatGetError(_fo_) \
9186 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9188 /* JimScanAString is used to scan an unspecified string that ends with
9189 * next WS, or a string that is specified via a charset.
9192 static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
9194 char *buffer = Jim_StrDup(str);
9195 char *p = buffer;
9197 while (*str) {
9198 int c;
9199 int n;
9201 if (!sdescr && isspace(UCHAR(*str)))
9202 break; /* EOS via WS if unspecified */
9204 n = utf8_tounicode(str, &c);
9205 if (sdescr && !JimCharsetMatch(sdescr, c, JIM_CHARSET_SCAN))
9206 break;
9207 while (n--)
9208 *p++ = *str++;
9210 *p = 0;
9211 return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
9214 /* ScanOneEntry will scan one entry out of the string passed as argument.
9215 * It use the sscanf() function for this task. After extracting and
9216 * converting of the value, the count of scanned characters will be
9217 * returned of -1 in case of no conversion tool place and string was
9218 * already scanned thru */
9220 static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int strLen,
9221 ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
9223 const char *tok;
9224 const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
9225 size_t scanned = 0;
9226 size_t anchor = pos;
9227 int i;
9228 Jim_Obj *tmpObj = NULL;
9230 /* First pessimistically assume, we will not scan anything :-) */
9231 *valObjPtr = 0;
9232 if (descr->prefix) {
9233 /* There was a prefix given before the conversion, skip it and adjust
9234 * the string-to-be-parsed accordingly */
9235 /* XXX: Should be checking strLen, not str[pos] */
9236 for (i = 0; pos < strLen && descr->prefix[i]; ++i) {
9237 /* If prefix require, skip WS */
9238 if (isspace(UCHAR(descr->prefix[i])))
9239 while (pos < strLen && isspace(UCHAR(str[pos])))
9240 ++pos;
9241 else if (descr->prefix[i] != str[pos])
9242 break; /* Prefix do not match here, leave the loop */
9243 else
9244 ++pos; /* Prefix matched so far, next round */
9246 if (pos >= strLen) {
9247 return -1; /* All of str consumed: EOF condition */
9249 else if (descr->prefix[i] != 0)
9250 return 0; /* Not whole prefix consumed, no conversion possible */
9252 /* For all but following conversion, skip leading WS */
9253 if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
9254 while (isspace(UCHAR(str[pos])))
9255 ++pos;
9256 /* Determine how much skipped/scanned so far */
9257 scanned = pos - anchor;
9259 /* %c is a special, simple case. no width */
9260 if (descr->type == 'n') {
9261 /* Return pseudo conversion means: how much scanned so far? */
9262 *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
9264 else if (pos >= strLen) {
9265 /* Cannot scan anything, as str is totally consumed */
9266 return -1;
9268 else if (descr->type == 'c') {
9269 int c;
9270 scanned += utf8_tounicode(&str[pos], &c);
9271 *valObjPtr = Jim_NewIntObj(interp, c);
9272 return scanned;
9274 else {
9275 /* Processing of conversions follows ... */
9276 if (descr->width > 0) {
9277 /* Do not try to scan as fas as possible but only the given width.
9278 * To ensure this, we copy the part that should be scanned. */
9279 size_t sLen = utf8_strlen(&str[pos], strLen - pos);
9280 size_t tLen = descr->width > sLen ? sLen : descr->width;
9282 tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
9283 tok = tmpObj->bytes;
9285 else {
9286 /* As no width was given, simply refer to the original string */
9287 tok = &str[pos];
9289 switch (descr->type) {
9290 case 'd':
9291 case 'o':
9292 case 'x':
9293 case 'u':
9294 case 'i':{
9295 char *endp; /* Position where the number finished */
9296 jim_wide w;
9298 int base = descr->type == 'o' ? 8
9299 : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
9301 /* Try to scan a number with the given base */
9302 w = strtoull(tok, &endp, base);
9303 if (endp == tok && base == 0) {
9304 /* If scanning failed, and base was undetermined, simply
9305 * put it to 10 and try once more. This should catch the
9306 * case where %i begin to parse a number prefix (e.g.
9307 * '0x' but no further digits follows. This will be
9308 * handled as a ZERO followed by a char 'x' by Tcl */
9309 w = strtoull(tok, &endp, 10);
9312 if (endp != tok) {
9313 /* There was some number sucessfully scanned! */
9314 *valObjPtr = Jim_NewIntObj(interp, w);
9316 /* Adjust the number-of-chars scanned so far */
9317 scanned += endp - tok;
9319 else {
9320 /* Nothing was scanned. We have to determine if this
9321 * happened due to e.g. prefix mismatch or input str
9322 * exhausted */
9323 scanned = *tok ? 0 : -1;
9325 break;
9327 case 's':
9328 case '[':{
9329 *valObjPtr = JimScanAString(interp, descr->arg, tok);
9330 scanned += Jim_Length(*valObjPtr);
9331 break;
9333 case 'e':
9334 case 'f':
9335 case 'g':{
9336 char *endp;
9337 double value = strtod(tok, &endp);
9339 if (endp != tok) {
9340 /* There was some number sucessfully scanned! */
9341 *valObjPtr = Jim_NewDoubleObj(interp, value);
9342 /* Adjust the number-of-chars scanned so far */
9343 scanned += endp - tok;
9345 else {
9346 /* Nothing was scanned. We have to determine if this
9347 * happened due to e.g. prefix mismatch or input str
9348 * exhausted */
9349 scanned = *tok ? 0 : -1;
9351 break;
9354 /* If a substring was allocated (due to pre-defined width) do not
9355 * forget to free it */
9356 if (tmpObj) {
9357 Jim_FreeNewObj(interp, tmpObj);
9360 return scanned;
9363 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9364 * string and returns all converted (and not ignored) values in a list back
9365 * to the caller. If an error occured, a NULL pointer will be returned */
9367 Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
9369 size_t i, pos;
9370 int scanned = 1;
9371 const char *str = Jim_String(strObjPtr);
9372 int strLen = Jim_Utf8Length(interp, strObjPtr);
9373 Jim_Obj *resultList = 0;
9374 Jim_Obj **resultVec = 0;
9375 int resultc;
9376 Jim_Obj *emptyStr = 0;
9377 ScanFmtStringObj *fmtObj;
9379 /* This should never happen. The format object should already be of the correct type */
9380 JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
9382 fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
9383 /* Check if format specification was valid */
9384 if (fmtObj->error != 0) {
9385 if (flags & JIM_ERRMSG)
9386 Jim_SetResultString(interp, fmtObj->error, -1);
9387 return 0;
9389 /* Allocate a new "shared" empty string for all unassigned conversions */
9390 emptyStr = Jim_NewEmptyStringObj(interp);
9391 Jim_IncrRefCount(emptyStr);
9392 /* Create a list and fill it with empty strings up to max specified XPG3 */
9393 resultList = Jim_NewListObj(interp, NULL, 0);
9394 if (fmtObj->maxPos > 0) {
9395 for (i = 0; i < fmtObj->maxPos; ++i)
9396 Jim_ListAppendElement(interp, resultList, emptyStr);
9397 JimListGetElements(interp, resultList, &resultc, &resultVec);
9399 /* Now handle every partial format description */
9400 for (i = 0, pos = 0; i < fmtObj->count; ++i) {
9401 ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
9402 Jim_Obj *value = 0;
9404 /* Only last type may be "literal" w/o conversion - skip it! */
9405 if (descr->type == 0)
9406 continue;
9407 /* As long as any conversion could be done, we will proceed */
9408 if (scanned > 0)
9409 scanned = ScanOneEntry(interp, str, pos, strLen, fmtObj, i, &value);
9410 /* In case our first try results in EOF, we will leave */
9411 if (scanned == -1 && i == 0)
9412 goto eof;
9413 /* Advance next pos-to-be-scanned for the amount scanned already */
9414 pos += scanned;
9416 /* value == 0 means no conversion took place so take empty string */
9417 if (value == 0)
9418 value = Jim_NewEmptyStringObj(interp);
9419 /* If value is a non-assignable one, skip it */
9420 if (descr->pos == -1) {
9421 Jim_FreeNewObj(interp, value);
9423 else if (descr->pos == 0)
9424 /* Otherwise append it to the result list if no XPG3 was given */
9425 Jim_ListAppendElement(interp, resultList, value);
9426 else if (resultVec[descr->pos - 1] == emptyStr) {
9427 /* But due to given XPG3, put the value into the corr. slot */
9428 Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
9429 Jim_IncrRefCount(value);
9430 resultVec[descr->pos - 1] = value;
9432 else {
9433 /* Otherwise, the slot was already used - free obj and ERROR */
9434 Jim_FreeNewObj(interp, value);
9435 goto err;
9438 Jim_DecrRefCount(interp, emptyStr);
9439 return resultList;
9440 eof:
9441 Jim_DecrRefCount(interp, emptyStr);
9442 Jim_FreeNewObj(interp, resultList);
9443 return (Jim_Obj *)EOF;
9444 err:
9445 Jim_DecrRefCount(interp, emptyStr);
9446 Jim_FreeNewObj(interp, resultList);
9447 return 0;
9450 /* -----------------------------------------------------------------------------
9451 * Pseudo Random Number Generation
9452 * ---------------------------------------------------------------------------*/
9453 /* Initialize the sbox with the numbers from 0 to 255 */
9454 static void JimPrngInit(Jim_Interp *interp)
9456 #define PRNG_SEED_SIZE 256
9457 int i;
9458 unsigned int *seed;
9459 time_t t = time(NULL);
9461 interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
9463 seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
9464 for (i = 0; i < PRNG_SEED_SIZE; i++) {
9465 seed[i] = (rand() ^ t ^ clock());
9467 JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
9468 Jim_Free(seed);
9471 /* Generates N bytes of random data */
9472 static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
9474 Jim_PrngState *prng;
9475 unsigned char *destByte = (unsigned char *)dest;
9476 unsigned int si, sj, x;
9478 /* initialization, only needed the first time */
9479 if (interp->prngState == NULL)
9480 JimPrngInit(interp);
9481 prng = interp->prngState;
9482 /* generates 'len' bytes of pseudo-random numbers */
9483 for (x = 0; x < len; x++) {
9484 prng->i = (prng->i + 1) & 0xff;
9485 si = prng->sbox[prng->i];
9486 prng->j = (prng->j + si) & 0xff;
9487 sj = prng->sbox[prng->j];
9488 prng->sbox[prng->i] = sj;
9489 prng->sbox[prng->j] = si;
9490 *destByte++ = prng->sbox[(si + sj) & 0xff];
9494 /* Re-seed the generator with user-provided bytes */
9495 static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
9497 int i;
9498 Jim_PrngState *prng;
9500 /* initialization, only needed the first time */
9501 if (interp->prngState == NULL)
9502 JimPrngInit(interp);
9503 prng = interp->prngState;
9505 /* Set the sbox[i] with i */
9506 for (i = 0; i < 256; i++)
9507 prng->sbox[i] = i;
9508 /* Now use the seed to perform a random permutation of the sbox */
9509 for (i = 0; i < seedLen; i++) {
9510 unsigned char t;
9512 t = prng->sbox[i & 0xFF];
9513 prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
9514 prng->sbox[seed[i]] = t;
9516 prng->i = prng->j = 0;
9518 /* discard at least the first 256 bytes of stream.
9519 * borrow the seed buffer for this
9521 for (i = 0; i < 256; i += seedLen) {
9522 JimRandomBytes(interp, seed, seedLen);
9526 /* [incr] */
9527 static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
9529 jim_wide wideValue, increment = 1;
9530 Jim_Obj *intObjPtr;
9532 if (argc != 2 && argc != 3) {
9533 Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
9534 return JIM_ERR;
9536 if (argc == 3) {
9537 if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)
9538 return JIM_ERR;
9540 intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
9541 if (!intObjPtr) {
9542 /* Set missing variable to 0 */
9543 wideValue = 0;
9545 else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
9546 return JIM_ERR;
9548 if (!intObjPtr || Jim_IsShared(intObjPtr)) {
9549 intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
9550 if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
9551 Jim_FreeNewObj(interp, intObjPtr);
9552 return JIM_ERR;
9555 else {
9556 /* Can do it the quick way */
9557 Jim_InvalidateStringRep(intObjPtr);
9558 JimWideValue(intObjPtr) = wideValue + increment;
9560 /* The following step is required in order to invalidate the
9561 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9562 if (argv[1]->typePtr != &variableObjType) {
9563 /* Note that this can't fail since GetVariable already succeeded */
9564 Jim_SetVariable(interp, argv[1], intObjPtr);
9567 Jim_SetResult(interp, intObjPtr);
9568 return JIM_OK;
9572 /* -----------------------------------------------------------------------------
9573 * Eval
9574 * ---------------------------------------------------------------------------*/
9575 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9576 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9578 /* Handle calls to the [unknown] command */
9579 static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv, Jim_Obj *fileNameObj,
9580 int linenr)
9582 Jim_Obj **v, *sv[JIM_EVAL_SARGV_LEN];
9583 int retCode;
9585 /* If JimUnknown() is recursively called too many times...
9586 * done here
9588 if (interp->unknown_called > 50) {
9589 return JIM_ERR;
9592 /* If the [unknown] command does not exists returns
9593 * just now */
9594 if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
9595 return JIM_ERR;
9597 /* The object interp->unknown just contains
9598 * the "unknown" string, it is used in order to
9599 * avoid to lookup the unknown command every time
9600 * but instread to cache the result. */
9601 if (argc + 1 <= JIM_EVAL_SARGV_LEN)
9602 v = sv;
9603 else
9604 v = Jim_Alloc(sizeof(Jim_Obj *) * (argc + 1));
9605 /* Make a copy of the arguments vector, but shifted on
9606 * the right of one position. The command name of the
9607 * command will be instead the first argument of the
9608 * [unknown] call. */
9609 memcpy(v + 1, argv, sizeof(Jim_Obj *) * argc);
9610 v[0] = interp->unknown;
9611 /* Call it */
9612 interp->unknown_called++;
9613 retCode = JimEvalObjVector(interp, argc + 1, v, fileNameObj, linenr);
9614 interp->unknown_called--;
9616 /* Clean up */
9617 if (v != sv)
9618 Jim_Free(v);
9619 return retCode;
9622 /* Eval the object vector 'objv' composed of 'objc' elements.
9623 * Every element is used as single argument.
9624 * Jim_EvalObj() will call this function every time its object
9625 * argument is of "list" type, with no string representation.
9627 * This is possible because the string representation of a
9628 * list object generated by the UpdateStringOfList is made
9629 * in a way that ensures that every list element is a different
9630 * command argument. */
9631 static int JimEvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv,
9632 Jim_Obj *fileNameObj, int linenr)
9634 int i, retcode;
9635 Jim_Cmd *cmdPtr;
9637 /* Incr refcount of arguments. */
9638 for (i = 0; i < objc; i++)
9639 Jim_IncrRefCount(objv[i]);
9640 /* Command lookup */
9641 cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
9642 if (cmdPtr == NULL) {
9643 retcode = JimUnknown(interp, objc, objv, fileNameObj, linenr);
9645 else {
9646 /* Call it -- Make sure result is an empty object. */
9647 JimIncrCmdRefCount(cmdPtr);
9648 Jim_SetEmptyResult(interp);
9649 if (cmdPtr->isproc) {
9650 retcode = JimCallProcedure(interp, cmdPtr, fileNameObj, linenr, objc, objv);
9652 else {
9653 interp->cmdPrivData = cmdPtr->u.native.privData;
9654 retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
9656 JimDecrCmdRefCount(interp, cmdPtr);
9658 /* Decr refcount of arguments and return the retcode */
9659 for (i = 0; i < objc; i++)
9660 Jim_DecrRefCount(interp, objv[i]);
9662 return retcode;
9665 int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
9667 return JimEvalObjVector(interp, objc, objv, interp->emptyObj, 1);
9671 * Invokes 'prefix' as a command with the objv array as arguments.
9673 int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix, int objc, Jim_Obj *const *objv)
9675 int i;
9676 int ret;
9677 Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
9679 nargv[0] = prefix;
9680 for (i = 0; i < objc; i++) {
9681 nargv[i + 1] = objv[i];
9683 ret = Jim_EvalObjVector(interp, objc + 1, nargv);
9684 Jim_Free(nargv);
9685 return ret;
9688 static void JimAddErrorToStack(Jim_Interp *interp, int retcode, Jim_Obj *fileNameObj, int line)
9690 int rc = retcode;
9692 if (rc == JIM_ERR && !interp->errorFlag) {
9693 /* This is the first error, so save the file/line information and reset the stack */
9694 interp->errorFlag = 1;
9695 Jim_IncrRefCount(fileNameObj);
9696 Jim_DecrRefCount(interp, interp->errorFileNameObj);
9697 interp->errorFileNameObj = fileNameObj;
9698 interp->errorLine = line;
9700 JimResetStackTrace(interp);
9701 /* Always add a level where the error first occurs */
9702 interp->addStackTrace++;
9705 /* Now if this is an "interesting" level, add it to the stack trace */
9706 if (rc == JIM_ERR && interp->addStackTrace > 0) {
9707 /* Add the stack info for the current level */
9709 JimAppendStackTrace(interp, Jim_String(interp->errorProc), fileNameObj, line);
9711 /* Note: if we didn't have a filename for this level,
9712 * don't clear the addStackTrace flag
9713 * so we can pick it up at the next level
9715 if (Jim_Length(fileNameObj)) {
9716 interp->addStackTrace = 0;
9719 Jim_DecrRefCount(interp, interp->errorProc);
9720 interp->errorProc = interp->emptyObj;
9721 Jim_IncrRefCount(interp->errorProc);
9723 else if (rc == JIM_RETURN && interp->returnCode == JIM_ERR) {
9724 /* Propagate the addStackTrace value through 'return -code error' */
9726 else {
9727 interp->addStackTrace = 0;
9731 /* And delete any local procs */
9732 static void JimDeleteLocalProcs(Jim_Interp *interp)
9734 if (interp->localProcs) {
9735 char *procname;
9737 while ((procname = Jim_StackPop(interp->localProcs)) != NULL) {
9738 /* If there is a pushed command, find it */
9739 Jim_Cmd *prevCmd = NULL;
9740 Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, procname);
9741 if (he) {
9742 Jim_Cmd *cmd = (Jim_Cmd *)he->u.val;
9743 if (cmd->isproc && cmd->u.proc.prevCmd) {
9744 prevCmd = cmd->u.proc.prevCmd;
9745 cmd->u.proc.prevCmd = NULL;
9749 /* Delete the local proc */
9750 Jim_DeleteCommand(interp, procname);
9752 if (prevCmd) {
9753 /* And restore the pushed command */
9754 Jim_AddHashEntry(&interp->commands, procname, prevCmd);
9756 Jim_Free(procname);
9758 Jim_FreeStack(interp->localProcs);
9759 Jim_Free(interp->localProcs);
9760 interp->localProcs = NULL;
9764 static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
9766 Jim_Obj *objPtr;
9768 switch (token->type) {
9769 case JIM_TT_STR:
9770 case JIM_TT_ESC:
9771 objPtr = token->objPtr;
9772 break;
9773 case JIM_TT_VAR:
9774 objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
9775 break;
9776 case JIM_TT_DICTSUGAR:
9777 objPtr = JimExpandDictSugar(interp, token->objPtr);
9778 break;
9779 case JIM_TT_EXPRSUGAR:
9780 objPtr = JimExpandExprSugar(interp, token->objPtr);
9781 break;
9782 case JIM_TT_CMD:
9783 switch (Jim_EvalObj(interp, token->objPtr)) {
9784 case JIM_OK:
9785 case JIM_RETURN:
9786 objPtr = interp->result;
9787 break;
9788 case JIM_BREAK:
9789 /* Stop substituting */
9790 return JIM_BREAK;
9791 case JIM_CONTINUE:
9792 /* just skip this one */
9793 return JIM_CONTINUE;
9794 default:
9795 return JIM_ERR;
9797 break;
9798 default:
9799 JimPanic((1,
9800 "default token type (%d) reached " "in Jim_SubstObj().", token->type));
9801 objPtr = NULL;
9802 break;
9804 if (objPtr) {
9805 *objPtrPtr = objPtr;
9806 return JIM_OK;
9808 return JIM_ERR;
9811 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9812 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9813 * The returned object has refcount = 0.
9815 static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
9817 int totlen = 0, i;
9818 Jim_Obj **intv;
9819 Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
9820 Jim_Obj *objPtr;
9821 char *s;
9823 if (tokens <= JIM_EVAL_SINTV_LEN)
9824 intv = sintv;
9825 else
9826 intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
9828 /* Compute every token forming the argument
9829 * in the intv objects vector. */
9830 for (i = 0; i < tokens; i++) {
9831 switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
9832 case JIM_OK:
9833 case JIM_RETURN:
9834 break;
9835 case JIM_BREAK:
9836 if (flags & JIM_SUBST_FLAG) {
9837 /* Stop here */
9838 tokens = i;
9839 continue;
9841 /* XXX: Should probably set an error about break outside loop */
9842 /* fall through to error */
9843 case JIM_CONTINUE:
9844 if (flags & JIM_SUBST_FLAG) {
9845 intv[i] = NULL;
9846 continue;
9848 /* XXX: Ditto continue outside loop */
9849 /* fall through to error */
9850 default:
9851 while (i--) {
9852 Jim_DecrRefCount(interp, intv[i]);
9854 if (intv != sintv) {
9855 Jim_Free(intv);
9857 return NULL;
9859 Jim_IncrRefCount(intv[i]);
9860 Jim_String(intv[i]);
9861 totlen += intv[i]->length;
9864 /* Fast path return for a single token */
9865 if (tokens == 1 && intv[0] && intv == sintv) {
9866 Jim_DecrRefCount(interp, intv[0]);
9867 return intv[0];
9870 /* Concatenate every token in an unique
9871 * object. */
9872 objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
9874 if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
9875 && token[2].type == JIM_TT_VAR) {
9876 /* May be able to do fast interpolated object -> dictSubst */
9877 objPtr->typePtr = &interpolatedObjType;
9878 objPtr->internalRep.twoPtrValue.ptr1 = (void *)token;
9879 objPtr->internalRep.twoPtrValue.ptr2 = intv[2];
9880 Jim_IncrRefCount(intv[2]);
9883 s = objPtr->bytes = Jim_Alloc(totlen + 1);
9884 objPtr->length = totlen;
9885 for (i = 0; i < tokens; i++) {
9886 if (intv[i]) {
9887 memcpy(s, intv[i]->bytes, intv[i]->length);
9888 s += intv[i]->length;
9889 Jim_DecrRefCount(interp, intv[i]);
9892 objPtr->bytes[totlen] = '\0';
9893 /* Free the intv vector if not static. */
9894 if (intv != sintv) {
9895 Jim_Free(intv);
9898 return objPtr;
9902 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9903 * Otherwise eval with Jim_EvalObj()
9905 static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *fileNameObj, int linenr)
9907 int retcode = JIM_OK;
9909 JimPanic((!Jim_IsList(listPtr), "JimEvalObjList() called without list arg"));
9911 if (listPtr->internalRep.listValue.len) {
9912 Jim_IncrRefCount(listPtr);
9913 retcode = JimEvalObjVector(interp,
9914 listPtr->internalRep.listValue.len,
9915 listPtr->internalRep.listValue.ele, fileNameObj, linenr);
9916 Jim_DecrRefCount(interp, listPtr);
9918 return retcode;
9921 int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
9923 int i;
9924 ScriptObj *script;
9925 ScriptToken *token;
9926 int retcode = JIM_OK;
9927 Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
9928 int linenr = 0;
9930 interp->errorFlag = 0;
9932 /* If the object is of type "list", with no string rep we can call
9933 * a specialized version of Jim_EvalObj() */
9934 if (Jim_IsList(scriptObjPtr) && scriptObjPtr->bytes == NULL) {
9935 return JimEvalObjList(interp, scriptObjPtr, interp->emptyObj, 1);
9938 Jim_IncrRefCount(scriptObjPtr); /* Make sure it's shared. */
9939 script = Jim_GetScript(interp, scriptObjPtr);
9941 /* Reset the interpreter result. This is useful to
9942 * return the empty result in the case of empty program. */
9943 Jim_SetEmptyResult(interp);
9945 #ifdef JIM_OPTIMIZATION
9946 /* Check for one of the following common scripts used by for, while
9948 * {}
9949 * incr a
9951 if (script->len == 0) {
9952 Jim_DecrRefCount(interp, scriptObjPtr);
9953 return JIM_OK;
9955 if (script->len == 3
9956 && script->token[1].objPtr->typePtr == &commandObjType
9957 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
9958 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
9959 && script->token[2].objPtr->typePtr == &variableObjType) {
9961 Jim_Obj *objPtr = Jim_GetVariable(interp, script->token[2].objPtr, JIM_NONE);
9963 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
9964 JimWideValue(objPtr)++;
9965 Jim_InvalidateStringRep(objPtr);
9966 Jim_DecrRefCount(interp, scriptObjPtr);
9967 Jim_SetResult(interp, objPtr);
9968 return JIM_OK;
9971 #endif
9973 /* Now we have to make sure the internal repr will not be
9974 * freed on shimmering.
9976 * Think for example to this:
9978 * set x {llength $x; ... some more code ...}; eval $x
9980 * In order to preserve the internal rep, we increment the
9981 * inUse field of the script internal rep structure. */
9982 script->inUse++;
9984 token = script->token;
9985 argv = sargv;
9987 /* Execute every command sequentially until the end of the script
9988 * or an error occurs.
9990 for (i = 0; i < script->len && retcode == JIM_OK; ) {
9991 int argc;
9992 int j;
9993 Jim_Cmd *cmd;
9995 /* First token of the line is always JIM_TT_LINE */
9996 argc = token[i].objPtr->internalRep.scriptLineValue.argc;
9997 linenr = token[i].objPtr->internalRep.scriptLineValue.line;
9999 /* Allocate the arguments vector if required */
10000 if (argc > JIM_EVAL_SARGV_LEN)
10001 argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
10003 /* Skip the JIM_TT_LINE token */
10004 i++;
10006 /* Populate the arguments objects.
10007 * If an error occurs, retcode will be set and
10008 * 'j' will be set to the number of args expanded
10010 for (j = 0; j < argc; j++) {
10011 long wordtokens = 1;
10012 int expand = 0;
10013 Jim_Obj *wordObjPtr = NULL;
10015 if (token[i].type == JIM_TT_WORD) {
10016 wordtokens = JimWideValue(token[i++].objPtr);
10017 if (wordtokens < 0) {
10018 expand = 1;
10019 wordtokens = -wordtokens;
10023 if (wordtokens == 1) {
10024 /* Fast path if the token does not
10025 * need interpolation */
10027 switch (token[i].type) {
10028 case JIM_TT_ESC:
10029 case JIM_TT_STR:
10030 wordObjPtr = token[i].objPtr;
10031 break;
10032 case JIM_TT_VAR:
10033 wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
10034 break;
10035 case JIM_TT_EXPRSUGAR:
10036 wordObjPtr = JimExpandExprSugar(interp, token[i].objPtr);
10037 break;
10038 case JIM_TT_DICTSUGAR:
10039 wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
10040 break;
10041 case JIM_TT_CMD:
10042 retcode = Jim_EvalObj(interp, token[i].objPtr);
10043 if (retcode == JIM_OK) {
10044 wordObjPtr = Jim_GetResult(interp);
10046 break;
10047 default:
10048 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10051 else {
10052 /* For interpolation we call a helper
10053 * function to do the work for us. */
10054 wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
10057 if (!wordObjPtr) {
10058 if (retcode == JIM_OK) {
10059 retcode = JIM_ERR;
10061 break;
10064 Jim_IncrRefCount(wordObjPtr);
10065 i += wordtokens;
10067 if (!expand) {
10068 argv[j] = wordObjPtr;
10070 else {
10071 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10072 int len = Jim_ListLength(interp, wordObjPtr);
10073 int newargc = argc + len - 1;
10074 int k;
10076 if (len > 1) {
10077 if (argv == sargv) {
10078 if (newargc > JIM_EVAL_SARGV_LEN) {
10079 argv = Jim_Alloc(sizeof(*argv) * newargc);
10080 memcpy(argv, sargv, sizeof(*argv) * j);
10083 else {
10084 /* Need to realloc to make room for (len - 1) more entries */
10085 argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
10089 /* Now copy in the expanded version */
10090 for (k = 0; k < len; k++) {
10091 argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
10092 Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
10095 /* The original object reference is no longer needed,
10096 * after the expansion it is no longer present on
10097 * the argument vector, but the single elements are
10098 * in its place. */
10099 Jim_DecrRefCount(interp, wordObjPtr);
10101 /* And update the indexes */
10102 j--;
10103 argc += len - 1;
10107 if (retcode == JIM_OK && argc) {
10108 /* Lookup the command to call */
10109 cmd = Jim_GetCommand(interp, argv[0], JIM_ERRMSG);
10110 if (cmd != NULL) {
10111 /* Call it -- Make sure result is an empty object. */
10112 JimIncrCmdRefCount(cmd);
10113 Jim_SetEmptyResult(interp);
10114 if (cmd->isproc) {
10115 retcode =
10116 JimCallProcedure(interp, cmd, script->fileNameObj, linenr, argc, argv);
10117 } else {
10118 interp->cmdPrivData = cmd->u.native.privData;
10119 retcode = cmd->u.native.cmdProc(interp, argc, argv);
10121 JimDecrCmdRefCount(interp, cmd);
10123 else {
10124 /* Call [unknown] */
10125 retcode = JimUnknown(interp, argc, argv, script->fileNameObj, linenr);
10127 if (interp->signal_level && interp->sigmask) {
10128 /* Check for a signal after each command */
10129 retcode = JIM_SIGNAL;
10133 /* Finished with the command, so decrement ref counts of each argument */
10134 while (j-- > 0) {
10135 Jim_DecrRefCount(interp, argv[j]);
10138 if (argv != sargv) {
10139 Jim_Free(argv);
10140 argv = sargv;
10144 /* Possibly add to the error stack trace */
10145 JimAddErrorToStack(interp, retcode, script->fileNameObj, linenr);
10147 /* Note that we don't have to decrement inUse, because the
10148 * following code transfers our use of the reference again to
10149 * the script object. */
10150 Jim_FreeIntRep(interp, scriptObjPtr);
10151 scriptObjPtr->typePtr = &scriptObjType;
10152 Jim_SetIntRepPtr(scriptObjPtr, script);
10153 Jim_DecrRefCount(interp, scriptObjPtr);
10155 return retcode;
10158 static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
10160 int retcode;
10161 /* If argObjPtr begins with '&', do an automatic upvar */
10162 const char *varname = Jim_String(argNameObj);
10163 if (*varname == '&') {
10164 /* First check that the target variable exists */
10165 Jim_Obj *objPtr;
10166 Jim_CallFrame *savedCallFrame = interp->framePtr;
10168 interp->framePtr = interp->framePtr->parentCallFrame;
10169 objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
10170 interp->framePtr = savedCallFrame;
10171 if (!objPtr) {
10172 return JIM_ERR;
10175 /* It exists, so perform the binding. */
10176 objPtr = Jim_NewStringObj(interp, varname + 1, -1);
10177 Jim_IncrRefCount(objPtr);
10178 retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parentCallFrame);
10179 Jim_DecrRefCount(interp, objPtr);
10181 else {
10182 retcode = Jim_SetVariable(interp, argNameObj, argValObj);
10184 return retcode;
10188 * Sets the interp result to be an error message indicating the required proc args.
10190 static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
10192 /* Create a nice error message, consistent with Tcl 8.5 */
10193 Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
10194 int i;
10196 for (i = 0; i < cmd->u.proc.argListLen; i++) {
10197 Jim_AppendString(interp, argmsg, " ", 1);
10199 if (i == cmd->u.proc.argsPos) {
10200 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10201 /* Renamed args */
10202 Jim_AppendString(interp, argmsg, "?", 1);
10203 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
10204 Jim_AppendString(interp, argmsg, " ...?", -1);
10206 else {
10207 /* We have plain args */
10208 Jim_AppendString(interp, argmsg, "?argument ...?", -1);
10211 else {
10212 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10213 Jim_AppendString(interp, argmsg, "?", 1);
10214 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10215 Jim_AppendString(interp, argmsg, "?", 1);
10217 else {
10218 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10222 Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
10223 Jim_FreeNewObj(interp, argmsg);
10226 /* Call a procedure implemented in Tcl.
10227 * It's possible to speed-up a lot this function, currently
10228 * the callframes are not cached, but allocated and
10229 * destroied every time. What is expecially costly is
10230 * to create/destroy the local vars hash table every time.
10232 * This can be fixed just implementing callframes caching
10233 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10234 static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, Jim_Obj *fileNameObj, int linenr, int argc,
10235 Jim_Obj *const *argv)
10237 Jim_CallFrame *callFramePtr;
10238 Jim_Stack *prevLocalProcs;
10239 int i, d, retcode, optargs;
10241 /* Check arity */
10242 if (argc - 1 < cmd->u.proc.reqArity ||
10243 (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
10244 JimSetProcWrongArgs(interp, argv[0], cmd);
10245 return JIM_ERR;
10248 /* Check if there are too nested calls */
10249 if (interp->framePtr->level == interp->maxNestingDepth) {
10250 Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
10251 return JIM_ERR;
10254 /* Create a new callframe */
10255 callFramePtr = JimCreateCallFrame(interp, interp->framePtr);
10256 callFramePtr->argv = argv;
10257 callFramePtr->argc = argc;
10258 callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
10259 callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
10260 callFramePtr->staticVars = cmd->u.proc.staticVars;
10261 callFramePtr->fileNameObj = fileNameObj;
10262 callFramePtr->line = linenr;
10263 Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
10264 Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
10265 interp->framePtr = callFramePtr;
10267 /* Install a new stack for local procs */
10268 prevLocalProcs = interp->localProcs;
10269 interp->localProcs = NULL;
10271 /* How many optional args are available */
10272 optargs = (argc - 1 - cmd->u.proc.reqArity);
10274 /* Step 'i' along the actual args, and step 'd' along the formal args */
10275 i = 1;
10276 for (d = 0; d < cmd->u.proc.argListLen; d++) {
10277 Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
10278 if (d == cmd->u.proc.argsPos) {
10279 /* assign $args */
10280 Jim_Obj *listObjPtr;
10281 int argsLen = 0;
10282 if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
10283 argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
10285 listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
10287 /* It is possible to rename args. */
10288 if (cmd->u.proc.arglist[d].defaultObjPtr) {
10289 nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
10291 retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
10292 if (retcode != JIM_OK) {
10293 goto badargset;
10296 i += argsLen;
10297 continue;
10300 /* Optional or required? */
10301 if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
10302 retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
10304 else {
10305 /* Ran out, so use the default */
10306 retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
10308 if (retcode != JIM_OK) {
10309 goto badargset;
10313 /* Eval the body */
10314 retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
10316 badargset:
10317 /* Destroy the callframe */
10318 interp->framePtr = interp->framePtr->parentCallFrame;
10319 if (callFramePtr->vars.size != JIM_HT_INITIAL_SIZE) {
10320 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NONE);
10322 else {
10323 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NOHT);
10325 /* Handle the JIM_EVAL return code */
10326 while (retcode == JIM_EVAL) {
10327 Jim_Obj *resultScriptObjPtr = Jim_GetResult(interp);
10329 Jim_IncrRefCount(resultScriptObjPtr);
10330 /* Result must be a list */
10331 retcode = JimEvalObjList(interp, resultScriptObjPtr, fileNameObj, linenr);
10332 if (retcode == JIM_RETURN) {
10333 /* If the result of the tailcall invokes 'return', push
10334 * it up to the caller
10336 interp->returnLevel++;
10338 Jim_DecrRefCount(interp, resultScriptObjPtr);
10340 /* Handle the JIM_RETURN return code */
10341 if (retcode == JIM_RETURN) {
10342 if (--interp->returnLevel <= 0) {
10343 retcode = interp->returnCode;
10344 interp->returnCode = JIM_OK;
10345 interp->returnLevel = 0;
10348 else if (retcode == JIM_ERR) {
10349 interp->addStackTrace++;
10350 Jim_DecrRefCount(interp, interp->errorProc);
10351 interp->errorProc = argv[0];
10352 Jim_IncrRefCount(interp->errorProc);
10355 /* Delete any local procs */
10356 JimDeleteLocalProcs(interp);
10357 interp->localProcs = prevLocalProcs;
10359 return retcode;
10362 int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script)
10364 int retval;
10365 Jim_Obj *scriptObjPtr;
10367 scriptObjPtr = Jim_NewStringObj(interp, script, -1);
10368 Jim_IncrRefCount(scriptObjPtr);
10370 if (filename) {
10371 Jim_Obj *prevScriptObj;
10373 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
10375 prevScriptObj = interp->currentScriptObj;
10376 interp->currentScriptObj = scriptObjPtr;
10378 retval = Jim_EvalObj(interp, scriptObjPtr);
10380 interp->currentScriptObj = prevScriptObj;
10382 else {
10383 retval = Jim_EvalObj(interp, scriptObjPtr);
10385 Jim_DecrRefCount(interp, scriptObjPtr);
10386 return retval;
10389 int Jim_Eval(Jim_Interp *interp, const char *script)
10391 return Jim_EvalObj(interp, Jim_NewStringObj(interp, script, -1));
10394 /* Execute script in the scope of the global level */
10395 int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
10397 int retval;
10398 Jim_CallFrame *savedFramePtr = interp->framePtr;
10400 interp->framePtr = interp->topFramePtr;
10401 retval = Jim_Eval(interp, script);
10402 interp->framePtr = savedFramePtr;
10404 return retval;
10407 int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
10409 int retval;
10410 Jim_CallFrame *savedFramePtr = interp->framePtr;
10412 interp->framePtr = interp->topFramePtr;
10413 retval = Jim_EvalFile(interp, filename);
10414 interp->framePtr = savedFramePtr;
10416 return retval;
10419 #include <sys/stat.h>
10421 int Jim_EvalFile(Jim_Interp *interp, const char *filename)
10423 FILE *fp;
10424 char *buf;
10425 Jim_Obj *scriptObjPtr;
10426 Jim_Obj *prevScriptObj;
10427 struct stat sb;
10428 int retcode;
10429 int readlen;
10430 struct JimParseResult result;
10432 if (stat(filename, &sb) != 0 || (fp = fopen(filename, "rt")) == NULL) {
10433 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
10434 return JIM_ERR;
10436 if (sb.st_size == 0) {
10437 fclose(fp);
10438 return JIM_OK;
10441 buf = Jim_Alloc(sb.st_size + 1);
10442 readlen = fread(buf, 1, sb.st_size, fp);
10443 if (ferror(fp)) {
10444 fclose(fp);
10445 Jim_Free(buf);
10446 Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
10447 return JIM_ERR;
10449 fclose(fp);
10450 buf[readlen] = 0;
10452 scriptObjPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
10453 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), 1);
10454 Jim_IncrRefCount(scriptObjPtr);
10456 /* Now check the script for unmatched braces, etc. */
10457 if (SetScriptFromAny(interp, scriptObjPtr, &result) == JIM_ERR) {
10458 const char *msg;
10459 char linebuf[20];
10461 switch (result.missing) {
10462 case '[':
10463 msg = "unmatched \"[\"";
10464 break;
10465 case '{':
10466 msg = "missing close-brace";
10467 break;
10468 case '"':
10469 default:
10470 msg = "missing quote";
10471 break;
10474 snprintf(linebuf, sizeof(linebuf), "%d", result.line);
10476 Jim_SetResultFormatted(interp, "%s in \"%s\" at line %s",
10477 msg, filename, linebuf);
10478 Jim_DecrRefCount(interp, scriptObjPtr);
10479 return JIM_ERR;
10482 prevScriptObj = interp->currentScriptObj;
10483 interp->currentScriptObj = scriptObjPtr;
10485 retcode = Jim_EvalObj(interp, scriptObjPtr);
10487 /* Handle the JIM_RETURN return code */
10488 if (retcode == JIM_RETURN) {
10489 if (--interp->returnLevel <= 0) {
10490 retcode = interp->returnCode;
10491 interp->returnCode = JIM_OK;
10492 interp->returnLevel = 0;
10495 if (retcode == JIM_ERR) {
10496 /* EvalFile changes context, so add a stack frame here */
10497 interp->addStackTrace++;
10500 interp->currentScriptObj = prevScriptObj;
10502 Jim_DecrRefCount(interp, scriptObjPtr);
10504 return retcode;
10507 /* -----------------------------------------------------------------------------
10508 * Subst
10509 * ---------------------------------------------------------------------------*/
10510 static int JimParseSubstStr(struct JimParserCtx *pc)
10512 pc->tstart = pc->p;
10513 pc->tline = pc->linenr;
10514 while (pc->len && *pc->p != '$' && *pc->p != '[') {
10515 if (*pc->p == '\\' && pc->len > 1) {
10516 pc->p++;
10517 pc->len--;
10519 pc->p++;
10520 pc->len--;
10522 pc->tend = pc->p - 1;
10523 pc->tt = JIM_TT_ESC;
10524 return JIM_OK;
10527 static int JimParseSubst(struct JimParserCtx *pc, int flags)
10529 int retval;
10531 if (pc->len == 0) {
10532 pc->tstart = pc->tend = pc->p;
10533 pc->tline = pc->linenr;
10534 pc->tt = JIM_TT_EOL;
10535 pc->eof = 1;
10536 return JIM_OK;
10538 switch (*pc->p) {
10539 case '[':
10540 retval = JimParseCmd(pc);
10541 if (flags & JIM_SUBST_NOCMD) {
10542 pc->tstart--;
10543 pc->tend++;
10544 pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
10546 return retval;
10547 break;
10548 case '$':
10549 if (JimParseVar(pc) == JIM_ERR) {
10550 pc->tstart = pc->tend = pc->p++;
10551 pc->len--;
10552 pc->tline = pc->linenr;
10553 pc->tt = JIM_TT_STR;
10555 else {
10556 if (flags & JIM_SUBST_NOVAR) {
10557 pc->tstart--;
10558 if (flags & JIM_SUBST_NOESC)
10559 pc->tt = JIM_TT_STR;
10560 else
10561 pc->tt = JIM_TT_ESC;
10562 if (*pc->tstart == '{') {
10563 pc->tstart--;
10564 if (*(pc->tend + 1))
10565 pc->tend++;
10569 break;
10570 default:
10571 retval = JimParseSubstStr(pc);
10572 if (flags & JIM_SUBST_NOESC)
10573 pc->tt = JIM_TT_STR;
10574 return retval;
10575 break;
10577 return JIM_OK;
10580 /* The subst object type reuses most of the data structures and functions
10581 * of the script object. Script's data structures are a bit more complex
10582 * for what is needed for [subst]itution tasks, but the reuse helps to
10583 * deal with a single data structure at the cost of some more memory
10584 * usage for substitutions. */
10586 /* This method takes the string representation of an object
10587 * as a Tcl string where to perform [subst]itution, and generates
10588 * the pre-parsed internal representation. */
10589 static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
10591 int scriptTextLen;
10592 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
10593 struct JimParserCtx parser;
10594 struct ScriptObj *script = Jim_Alloc(sizeof(*script));
10595 ParseTokenList tokenlist;
10597 /* Initially parse the subst into tokens (in tokenlist) */
10598 ScriptTokenListInit(&tokenlist);
10600 JimParserInit(&parser, scriptText, scriptTextLen, 1);
10601 while (1) {
10602 JimParseSubst(&parser, flags);
10603 if (parser.eof) {
10604 /* Note that subst doesn't need the EOL token */
10605 break;
10607 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
10608 parser.tline);
10611 /* Create the "real" subst/script tokens from the initial token list */
10612 script->inUse = 1;
10613 script->substFlags = flags;
10614 script->fileNameObj = interp->emptyObj;
10615 Jim_IncrRefCount(script->fileNameObj);
10616 SubstObjAddTokens(interp, script, &tokenlist);
10618 /* No longer need the token list */
10619 ScriptTokenListFree(&tokenlist);
10621 #ifdef DEBUG_SHOW_SUBST
10623 int i;
10625 printf("==== Subst ====\n");
10626 for (i = 0; i < script->len; i++) {
10627 printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
10628 Jim_String(script->token[i].objPtr));
10631 #endif
10633 /* Free the old internal rep and set the new one. */
10634 Jim_FreeIntRep(interp, objPtr);
10635 Jim_SetIntRepPtr(objPtr, script);
10636 objPtr->typePtr = &scriptObjType;
10637 return JIM_OK;
10640 static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
10642 if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
10643 SetSubstFromAny(interp, objPtr, flags);
10644 return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
10647 /* Performs commands,variables,blackslashes substitution,
10648 * storing the result object (with refcount 0) into
10649 * resObjPtrPtr. */
10650 int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
10652 ScriptObj *script = Jim_GetSubst(interp, substObjPtr, flags);
10654 Jim_IncrRefCount(substObjPtr); /* Make sure it's shared. */
10655 /* In order to preserve the internal rep, we increment the
10656 * inUse field of the script internal rep structure. */
10657 script->inUse++;
10659 *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
10661 script->inUse--;
10662 Jim_DecrRefCount(interp, substObjPtr);
10663 if (*resObjPtrPtr == NULL) {
10664 return JIM_ERR;
10666 return JIM_OK;
10669 /* -----------------------------------------------------------------------------
10670 * Core commands utility functions
10671 * ---------------------------------------------------------------------------*/
10672 void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
10674 int i;
10675 Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);
10677 Jim_AppendString(interp, objPtr, "wrong # args: should be \"", -1);
10678 for (i = 0; i < argc; i++) {
10679 Jim_AppendObj(interp, objPtr, argv[i]);
10680 if (!(i + 1 == argc && msg[0] == '\0'))
10681 Jim_AppendString(interp, objPtr, " ", 1);
10683 Jim_AppendString(interp, objPtr, msg, -1);
10684 Jim_AppendString(interp, objPtr, "\"", 1);
10685 Jim_SetResult(interp, objPtr);
10689 * May add the key and/or value to the list.
10691 typedef void JimHashtableIteratorCallbackType(Jim_Interp *interp, Jim_Obj *listObjPtr,
10692 Jim_HashEntry *he, void *privdata);
10694 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10697 * For each key of the hash table 'ht' which matches the glob pattern (all if NULL),
10698 * invoke the callback to add entries to a list.
10699 * Returns the list.
10701 * If 'string_keys' is set, the hash table keys are plain strings instead of objects.
10703 static Jim_Obj *JimHashtablePatternMatch(Jim_Interp *interp, Jim_HashTable *ht, Jim_Obj *patternObjPtr,
10704 JimHashtableIteratorCallbackType *callback, void *privdata, int string_keys)
10706 Jim_HashEntry *he;
10707 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
10709 /* Check for the non-pattern case. We can do this much more efficiently. */
10710 if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
10711 he = Jim_FindHashEntry(ht, string_keys ? (void *)Jim_String(patternObjPtr) : (void *)patternObjPtr);
10712 if (he) {
10713 callback(interp, listObjPtr, he, privdata);
10716 else {
10717 Jim_HashTableIterator *htiter;
10719 htiter = Jim_GetHashTableIterator(ht);
10720 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
10721 if (patternObjPtr == NULL || JimStringMatch(interp, patternObjPtr, string_keys ? he->key : Jim_String((Jim_Obj *)he->key), 0)) {
10722 callback(interp, listObjPtr, he, privdata);
10725 Jim_FreeHashTableIterator(htiter);
10727 return listObjPtr;
10730 /* Keep these in order */
10731 #define JIM_CMDLIST_COMMANDS 0
10732 #define JIM_CMDLIST_PROCS 1
10733 #define JIM_CMDLIST_CHANNELS 2
10736 * Adds matching command names (procs, channels) to the list.
10738 static void JimCommandMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
10739 Jim_HashEntry *he, void *privdata)
10741 Jim_Cmd *cmdPtr = (Jim_Cmd *)he->u.val;
10742 int type = *(int *)privdata;
10743 Jim_Obj *objPtr;
10745 if (type == JIM_CMDLIST_PROCS && !cmdPtr->isproc) {
10746 /* not a proc */
10747 return;
10750 objPtr = Jim_NewStringObj(interp, he->key, -1);
10752 if (type == JIM_CMDLIST_CHANNELS && !Jim_AioFilehandle(interp, objPtr)) {
10753 /* not a channel */
10754 Jim_FreeNewObj(interp, objPtr);
10755 return;
10758 Jim_ListAppendElement(interp, listObjPtr, objPtr);
10761 /* type is JIM_CMDLIST_xxx */
10762 static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
10764 return JimHashtablePatternMatch(interp, &interp->commands, patternObjPtr, JimCommandMatch, &type, 1);
10767 /* Keep these in order */
10768 #define JIM_VARLIST_GLOBALS 0
10769 #define JIM_VARLIST_LOCALS 1
10770 #define JIM_VARLIST_VARS 2
10773 * Adds matching variable names to the list.
10775 static void JimVariablesMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
10776 Jim_HashEntry *he, void *privdata)
10778 Jim_Var *varPtr = (Jim_Var *)he->u.val;
10779 int mode = *(int *)privdata;
10781 if (mode != JIM_VARLIST_LOCALS || varPtr->linkFramePtr == NULL) {
10782 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, he->key, -1));
10786 /* mode is JIM_VARLIST_xxx */
10787 static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
10789 if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr) {
10790 /* For [info locals], if we are at top level an emtpy list
10791 * is returned. I don't agree, but we aim at compatibility (SS) */
10792 return interp->emptyObj;
10794 else {
10795 Jim_CallFrame *framePtr = (mode == JIM_VARLIST_GLOBALS) ? interp->topFramePtr : interp->framePtr;
10796 return JimHashtablePatternMatch(interp, &framePtr->vars, patternObjPtr, JimVariablesMatch, &mode, 1);
10800 static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
10801 Jim_Obj **objPtrPtr, int info_level_cmd)
10803 Jim_CallFrame *targetCallFrame;
10805 targetCallFrame = JimGetCallFrameByInteger(interp, levelObjPtr);
10806 if (targetCallFrame == NULL) {
10807 return JIM_ERR;
10809 /* No proc call at toplevel callframe */
10810 if (targetCallFrame == interp->topFramePtr) {
10811 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
10812 return JIM_ERR;
10814 if (info_level_cmd) {
10815 *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
10817 else {
10818 Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
10820 Jim_ListAppendElement(interp, listObj, targetCallFrame->argv[0]);
10821 Jim_ListAppendElement(interp, listObj, targetCallFrame->fileNameObj);
10822 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, targetCallFrame->line));
10823 *objPtrPtr = listObj;
10825 return JIM_OK;
10828 /* -----------------------------------------------------------------------------
10829 * Core commands
10830 * ---------------------------------------------------------------------------*/
10832 /* fake [puts] -- not the real puts, just for debugging. */
10833 static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10835 if (argc != 2 && argc != 3) {
10836 Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
10837 return JIM_ERR;
10839 if (argc == 3) {
10840 if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
10841 Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
10842 return JIM_ERR;
10844 else {
10845 fputs(Jim_String(argv[2]), stdout);
10848 else {
10849 puts(Jim_String(argv[1]));
10851 return JIM_OK;
10854 /* Helper for [+] and [*] */
10855 static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10857 jim_wide wideValue, res;
10858 double doubleValue, doubleRes;
10859 int i;
10861 res = (op == JIM_EXPROP_ADD) ? 0 : 1;
10863 for (i = 1; i < argc; i++) {
10864 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
10865 goto trydouble;
10866 if (op == JIM_EXPROP_ADD)
10867 res += wideValue;
10868 else
10869 res *= wideValue;
10871 Jim_SetResultInt(interp, res);
10872 return JIM_OK;
10873 trydouble:
10874 doubleRes = (double)res;
10875 for (; i < argc; i++) {
10876 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10877 return JIM_ERR;
10878 if (op == JIM_EXPROP_ADD)
10879 doubleRes += doubleValue;
10880 else
10881 doubleRes *= doubleValue;
10883 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10884 return JIM_OK;
10887 /* Helper for [-] and [/] */
10888 static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10890 jim_wide wideValue, res = 0;
10891 double doubleValue, doubleRes = 0;
10892 int i = 2;
10894 if (argc < 2) {
10895 Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
10896 return JIM_ERR;
10898 else if (argc == 2) {
10899 /* The arity = 2 case is different. For [- x] returns -x,
10900 * while [/ x] returns 1/x. */
10901 if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
10902 if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
10903 return JIM_ERR;
10905 else {
10906 if (op == JIM_EXPROP_SUB)
10907 doubleRes = -doubleValue;
10908 else
10909 doubleRes = 1.0 / doubleValue;
10910 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10911 return JIM_OK;
10914 if (op == JIM_EXPROP_SUB) {
10915 res = -wideValue;
10916 Jim_SetResultInt(interp, res);
10918 else {
10919 doubleRes = 1.0 / wideValue;
10920 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10922 return JIM_OK;
10924 else {
10925 if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
10926 if (Jim_GetDouble(interp, argv[1], &doubleRes)
10927 != JIM_OK) {
10928 return JIM_ERR;
10930 else {
10931 goto trydouble;
10935 for (i = 2; i < argc; i++) {
10936 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
10937 doubleRes = (double)res;
10938 goto trydouble;
10940 if (op == JIM_EXPROP_SUB)
10941 res -= wideValue;
10942 else
10943 res /= wideValue;
10945 Jim_SetResultInt(interp, res);
10946 return JIM_OK;
10947 trydouble:
10948 for (; i < argc; i++) {
10949 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10950 return JIM_ERR;
10951 if (op == JIM_EXPROP_SUB)
10952 doubleRes -= doubleValue;
10953 else
10954 doubleRes /= doubleValue;
10956 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10957 return JIM_OK;
10961 /* [+] */
10962 static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10964 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
10967 /* [*] */
10968 static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10970 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
10973 /* [-] */
10974 static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10976 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
10979 /* [/] */
10980 static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10982 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
10985 /* [set] */
10986 static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10988 if (argc != 2 && argc != 3) {
10989 Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
10990 return JIM_ERR;
10992 if (argc == 2) {
10993 Jim_Obj *objPtr;
10995 objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
10996 if (!objPtr)
10997 return JIM_ERR;
10998 Jim_SetResult(interp, objPtr);
10999 return JIM_OK;
11001 /* argc == 3 case. */
11002 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
11003 return JIM_ERR;
11004 Jim_SetResult(interp, argv[2]);
11005 return JIM_OK;
11008 /* [unset]
11010 * unset ?-nocomplain? ?--? ?varName ...?
11012 static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11014 int i = 1;
11015 int complain = 1;
11017 while (i < argc) {
11018 if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
11019 i++;
11020 break;
11022 if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
11023 complain = 0;
11024 i++;
11025 continue;
11027 break;
11030 while (i < argc) {
11031 if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
11032 && complain) {
11033 return JIM_ERR;
11035 i++;
11037 return JIM_OK;
11040 /* [while] */
11041 static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11043 if (argc != 3) {
11044 Jim_WrongNumArgs(interp, 1, argv, "condition body");
11045 return JIM_ERR;
11048 /* The general purpose implementation of while starts here */
11049 while (1) {
11050 int boolean, retval;
11052 if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
11053 return retval;
11054 if (!boolean)
11055 break;
11057 if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
11058 switch (retval) {
11059 case JIM_BREAK:
11060 goto out;
11061 break;
11062 case JIM_CONTINUE:
11063 continue;
11064 break;
11065 default:
11066 return retval;
11070 out:
11071 Jim_SetEmptyResult(interp);
11072 return JIM_OK;
11075 /* [for] */
11076 static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11078 int retval;
11079 int boolean = 1;
11080 Jim_Obj *varNamePtr = NULL;
11081 Jim_Obj *stopVarNamePtr = NULL;
11083 if (argc != 5) {
11084 Jim_WrongNumArgs(interp, 1, argv, "start test next body");
11085 return JIM_ERR;
11088 /* Do the initialisation */
11089 if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
11090 return retval;
11093 /* And do the first test now. Better for optimisation
11094 * if we can do next/test at the bottom of the loop
11096 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11098 /* Ready to do the body as follows:
11099 * while (1) {
11100 * body // check retcode
11101 * next // check retcode
11102 * test // check retcode/test bool
11106 #ifdef JIM_OPTIMIZATION
11107 /* Check if the for is on the form:
11108 * for ... {$i < CONST} {incr i}
11109 * for ... {$i < $j} {incr i}
11111 if (retval == JIM_OK && boolean) {
11112 ScriptObj *incrScript;
11113 ExprByteCode *expr;
11114 jim_wide stop, currentVal;
11115 unsigned jim_wide procEpoch;
11116 Jim_Obj *objPtr;
11117 int cmpOffset;
11119 /* Do it only if there aren't shared arguments */
11120 expr = JimGetExpression(interp, argv[2]);
11121 incrScript = Jim_GetScript(interp, argv[3]);
11123 /* Ensure proper lengths to start */
11124 if (incrScript->len != 3 || !expr || expr->len != 3) {
11125 goto evalstart;
11127 /* Ensure proper token types. */
11128 if (incrScript->token[1].type != JIM_TT_ESC ||
11129 expr->token[0].type != JIM_TT_VAR ||
11130 (expr->token[1].type != JIM_TT_EXPR_INT && expr->token[1].type != JIM_TT_VAR)) {
11131 goto evalstart;
11134 if (expr->token[2].type == JIM_EXPROP_LT) {
11135 cmpOffset = 0;
11137 else if (expr->token[2].type == JIM_EXPROP_LTE) {
11138 cmpOffset = 1;
11140 else {
11141 goto evalstart;
11144 /* Update command must be incr */
11145 if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
11146 goto evalstart;
11149 /* incr, expression must be about the same variable */
11150 if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->token[0].objPtr)) {
11151 goto evalstart;
11154 /* Get the stop condition (must be a variable or integer) */
11155 if (expr->token[1].type == JIM_TT_EXPR_INT) {
11156 if (Jim_GetWide(interp, expr->token[1].objPtr, &stop) == JIM_ERR) {
11157 goto evalstart;
11160 else {
11161 stopVarNamePtr = expr->token[1].objPtr;
11162 Jim_IncrRefCount(stopVarNamePtr);
11163 /* Keep the compiler happy */
11164 stop = 0;
11167 /* Initialization */
11168 procEpoch = interp->procEpoch;
11169 varNamePtr = expr->token[0].objPtr;
11170 Jim_IncrRefCount(varNamePtr);
11172 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
11173 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK) {
11174 goto testcond;
11177 /* --- OPTIMIZED FOR --- */
11178 while (retval == JIM_OK) {
11179 /* === Check condition === */
11180 /* Note that currentVal is already set here */
11182 /* Immediate or Variable? get the 'stop' value if the latter. */
11183 if (stopVarNamePtr) {
11184 objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
11185 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
11186 goto testcond;
11190 if (currentVal >= stop + cmpOffset) {
11191 break;
11194 /* Eval body */
11195 retval = Jim_EvalObj(interp, argv[4]);
11196 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11197 retval = JIM_OK;
11198 /* If there was a change in procedures/command continue
11199 * with the usual [for] command implementation */
11200 if (procEpoch != interp->procEpoch) {
11201 goto evalnext;
11204 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
11206 /* Increment */
11207 if (objPtr == NULL) {
11208 retval = JIM_ERR;
11209 goto out;
11211 if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11212 currentVal = ++JimWideValue(objPtr);
11213 Jim_InvalidateStringRep(objPtr);
11215 else {
11216 if (Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK ||
11217 Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
11218 ++currentVal)) != JIM_OK) {
11219 goto evalnext;
11224 goto out;
11226 evalstart:
11227 #endif
11229 while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
11230 /* Body */
11231 retval = Jim_EvalObj(interp, argv[4]);
11233 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11234 /* increment */
11235 evalnext:
11236 retval = Jim_EvalObj(interp, argv[3]);
11237 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11238 /* test */
11239 testcond:
11240 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11244 out:
11245 if (stopVarNamePtr) {
11246 Jim_DecrRefCount(interp, stopVarNamePtr);
11248 if (varNamePtr) {
11249 Jim_DecrRefCount(interp, varNamePtr);
11252 if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
11253 Jim_SetEmptyResult(interp);
11254 return JIM_OK;
11257 return retval;
11260 /* [loop] */
11261 static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11263 int retval;
11264 jim_wide i;
11265 jim_wide limit;
11266 jim_wide incr = 1;
11267 Jim_Obj *bodyObjPtr;
11269 if (argc != 5 && argc != 6) {
11270 Jim_WrongNumArgs(interp, 1, argv, "var first limit ?incr? body");
11271 return JIM_ERR;
11274 if (Jim_GetWide(interp, argv[2], &i) != JIM_OK ||
11275 Jim_GetWide(interp, argv[3], &limit) != JIM_OK ||
11276 (argc == 6 && Jim_GetWide(interp, argv[4], &incr) != JIM_OK)) {
11277 return JIM_ERR;
11279 bodyObjPtr = (argc == 5) ? argv[4] : argv[5];
11281 retval = Jim_SetVariable(interp, argv[1], argv[2]);
11283 while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
11284 retval = Jim_EvalObj(interp, bodyObjPtr);
11285 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11286 Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
11288 retval = JIM_OK;
11290 /* Increment */
11291 i += incr;
11293 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11294 if (argv[1]->typePtr != &variableObjType) {
11295 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11296 return JIM_ERR;
11299 JimWideValue(objPtr) = i;
11300 Jim_InvalidateStringRep(objPtr);
11302 /* The following step is required in order to invalidate the
11303 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11304 if (argv[1]->typePtr != &variableObjType) {
11305 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11306 retval = JIM_ERR;
11307 break;
11311 else {
11312 objPtr = Jim_NewIntObj(interp, i);
11313 retval = Jim_SetVariable(interp, argv[1], objPtr);
11314 if (retval != JIM_OK) {
11315 Jim_FreeNewObj(interp, objPtr);
11321 if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
11322 Jim_SetEmptyResult(interp);
11323 return JIM_OK;
11325 return retval;
11328 /* foreach + lmap implementation. */
11329 static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
11331 int result = JIM_ERR, i, nbrOfLists, *listsIdx, *listsEnd;
11332 int nbrOfLoops = 0;
11333 Jim_Obj *emptyStr, *script, *mapRes = NULL;
11335 if (argc < 4 || argc % 2 != 0) {
11336 Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
11337 return JIM_ERR;
11339 if (doMap) {
11340 mapRes = Jim_NewListObj(interp, NULL, 0);
11341 Jim_IncrRefCount(mapRes);
11343 emptyStr = Jim_NewEmptyStringObj(interp);
11344 Jim_IncrRefCount(emptyStr);
11345 script = argv[argc - 1]; /* Last argument is a script */
11346 nbrOfLists = (argc - 1 - 1) / 2; /* argc - 'foreach' - script */
11347 listsIdx = (int *)Jim_Alloc(nbrOfLists * sizeof(int));
11348 listsEnd = (int *)Jim_Alloc(nbrOfLists * 2 * sizeof(int));
11349 /* Initialize iterators and remember max nbr elements each list */
11350 memset(listsIdx, 0, nbrOfLists * sizeof(int));
11351 /* Remember lengths of all lists and calculate how much rounds to loop */
11352 for (i = 0; i < nbrOfLists * 2; i += 2) {
11353 div_t cnt;
11354 int count;
11356 listsEnd[i] = Jim_ListLength(interp, argv[i + 1]);
11357 listsEnd[i + 1] = Jim_ListLength(interp, argv[i + 2]);
11358 if (listsEnd[i] == 0) {
11359 Jim_SetResultString(interp, "foreach varlist is empty", -1);
11360 goto err;
11362 cnt = div(listsEnd[i + 1], listsEnd[i]);
11363 count = cnt.quot + (cnt.rem ? 1 : 0);
11364 if (count > nbrOfLoops)
11365 nbrOfLoops = count;
11367 for (; nbrOfLoops-- > 0;) {
11368 for (i = 0; i < nbrOfLists; ++i) {
11369 int varIdx = 0, var = i * 2;
11371 while (varIdx < listsEnd[var]) {
11372 Jim_Obj *varName, *ele;
11373 int lst = i * 2 + 1;
11375 /* List index operations below can't fail */
11376 Jim_ListIndex(interp, argv[var + 1], varIdx, &varName, JIM_NONE);
11377 if (listsIdx[i] < listsEnd[lst]) {
11378 Jim_ListIndex(interp, argv[lst + 1], listsIdx[i], &ele, JIM_NONE);
11379 /* Avoid shimmering */
11380 Jim_IncrRefCount(ele);
11381 result = Jim_SetVariable(interp, varName, ele);
11382 Jim_DecrRefCount(interp, ele);
11383 if (result == JIM_OK) {
11384 ++listsIdx[i]; /* Remember next iterator of current list */
11385 ++varIdx; /* Next variable */
11386 continue;
11389 else if (Jim_SetVariable(interp, varName, emptyStr) == JIM_OK) {
11390 ++varIdx; /* Next variable */
11391 continue;
11393 goto err;
11396 switch (result = Jim_EvalObj(interp, script)) {
11397 case JIM_OK:
11398 if (doMap)
11399 Jim_ListAppendElement(interp, mapRes, interp->result);
11400 break;
11401 case JIM_CONTINUE:
11402 break;
11403 case JIM_BREAK:
11404 goto out;
11405 break;
11406 default:
11407 goto err;
11410 out:
11411 result = JIM_OK;
11412 if (doMap)
11413 Jim_SetResult(interp, mapRes);
11414 else
11415 Jim_SetEmptyResult(interp);
11416 err:
11417 if (doMap)
11418 Jim_DecrRefCount(interp, mapRes);
11419 Jim_DecrRefCount(interp, emptyStr);
11420 Jim_Free(listsIdx);
11421 Jim_Free(listsEnd);
11422 return result;
11425 /* [foreach] */
11426 static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11428 return JimForeachMapHelper(interp, argc, argv, 0);
11431 /* [lmap] */
11432 static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11434 return JimForeachMapHelper(interp, argc, argv, 1);
11437 /* [if] */
11438 static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11440 int boolean, retval, current = 1, falsebody = 0;
11442 if (argc >= 3) {
11443 while (1) {
11444 /* Far not enough arguments given! */
11445 if (current >= argc)
11446 goto err;
11447 if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
11448 != JIM_OK)
11449 return retval;
11450 /* There lacks something, isn't it? */
11451 if (current >= argc)
11452 goto err;
11453 if (Jim_CompareStringImmediate(interp, argv[current], "then"))
11454 current++;
11455 /* Tsk tsk, no then-clause? */
11456 if (current >= argc)
11457 goto err;
11458 if (boolean)
11459 return Jim_EvalObj(interp, argv[current]);
11460 /* Ok: no else-clause follows */
11461 if (++current >= argc) {
11462 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
11463 return JIM_OK;
11465 falsebody = current++;
11466 if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
11467 /* IIICKS - else-clause isn't last cmd? */
11468 if (current != argc - 1)
11469 goto err;
11470 return Jim_EvalObj(interp, argv[current]);
11472 else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
11473 /* Ok: elseif follows meaning all the stuff
11474 * again (how boring...) */
11475 continue;
11476 /* OOPS - else-clause is not last cmd? */
11477 else if (falsebody != argc - 1)
11478 goto err;
11479 return Jim_EvalObj(interp, argv[falsebody]);
11481 return JIM_OK;
11483 err:
11484 Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11485 return JIM_ERR;
11489 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11490 int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
11491 Jim_Obj *stringObj, int nocase)
11493 Jim_Obj *parms[4];
11494 int argc = 0;
11495 long eq;
11496 int rc;
11498 parms[argc++] = commandObj;
11499 if (nocase) {
11500 parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
11502 parms[argc++] = patternObj;
11503 parms[argc++] = stringObj;
11505 rc = Jim_EvalObjVector(interp, argc, parms);
11507 if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
11508 eq = -rc;
11511 return eq;
11514 enum
11515 { SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
11517 /* [switch] */
11518 static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11520 int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
11521 Jim_Obj *command = 0, *const *caseList = 0, *strObj;
11522 Jim_Obj *script = 0;
11524 if (argc < 3) {
11525 wrongnumargs:
11526 Jim_WrongNumArgs(interp, 1, argv, "?options? string "
11527 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11528 return JIM_ERR;
11530 for (opt = 1; opt < argc; ++opt) {
11531 const char *option = Jim_String(argv[opt]);
11533 if (*option != '-')
11534 break;
11535 else if (strncmp(option, "--", 2) == 0) {
11536 ++opt;
11537 break;
11539 else if (strncmp(option, "-exact", 2) == 0)
11540 matchOpt = SWITCH_EXACT;
11541 else if (strncmp(option, "-glob", 2) == 0)
11542 matchOpt = SWITCH_GLOB;
11543 else if (strncmp(option, "-regexp", 2) == 0)
11544 matchOpt = SWITCH_RE;
11545 else if (strncmp(option, "-command", 2) == 0) {
11546 matchOpt = SWITCH_CMD;
11547 if ((argc - opt) < 2)
11548 goto wrongnumargs;
11549 command = argv[++opt];
11551 else {
11552 Jim_SetResultFormatted(interp,
11553 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11554 argv[opt]);
11555 return JIM_ERR;
11557 if ((argc - opt) < 2)
11558 goto wrongnumargs;
11560 strObj = argv[opt++];
11561 patCount = argc - opt;
11562 if (patCount == 1) {
11563 Jim_Obj **vector;
11565 JimListGetElements(interp, argv[opt], &patCount, &vector);
11566 caseList = vector;
11568 else
11569 caseList = &argv[opt];
11570 if (patCount == 0 || patCount % 2 != 0)
11571 goto wrongnumargs;
11572 for (i = 0; script == 0 && i < patCount; i += 2) {
11573 Jim_Obj *patObj = caseList[i];
11575 if (!Jim_CompareStringImmediate(interp, patObj, "default")
11576 || i < (patCount - 2)) {
11577 switch (matchOpt) {
11578 case SWITCH_EXACT:
11579 if (Jim_StringEqObj(strObj, patObj))
11580 script = caseList[i + 1];
11581 break;
11582 case SWITCH_GLOB:
11583 if (Jim_StringMatchObj(interp, patObj, strObj, 0))
11584 script = caseList[i + 1];
11585 break;
11586 case SWITCH_RE:
11587 command = Jim_NewStringObj(interp, "regexp", -1);
11588 /* Fall thru intentionally */
11589 case SWITCH_CMD:{
11590 int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, 0);
11592 /* After the execution of a command we need to
11593 * make sure to reconvert the object into a list
11594 * again. Only for the single-list style [switch]. */
11595 if (argc - opt == 1) {
11596 Jim_Obj **vector;
11598 JimListGetElements(interp, argv[opt], &patCount, &vector);
11599 caseList = vector;
11601 /* command is here already decref'd */
11602 if (rc < 0) {
11603 return -rc;
11605 if (rc)
11606 script = caseList[i + 1];
11607 break;
11611 else {
11612 script = caseList[i + 1];
11615 for (; i < patCount && Jim_CompareStringImmediate(interp, script, "-"); i += 2)
11616 script = caseList[i + 1];
11617 if (script && Jim_CompareStringImmediate(interp, script, "-")) {
11618 Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
11619 return JIM_ERR;
11621 Jim_SetEmptyResult(interp);
11622 if (script) {
11623 return Jim_EvalObj(interp, script);
11625 return JIM_OK;
11628 /* [list] */
11629 static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11631 Jim_Obj *listObjPtr;
11633 listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
11634 Jim_SetResult(interp, listObjPtr);
11635 return JIM_OK;
11638 /* [lindex] */
11639 static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11641 Jim_Obj *objPtr, *listObjPtr;
11642 int i;
11643 int idx;
11645 if (argc < 3) {
11646 Jim_WrongNumArgs(interp, 1, argv, "list index ?...?");
11647 return JIM_ERR;
11649 objPtr = argv[1];
11650 Jim_IncrRefCount(objPtr);
11651 for (i = 2; i < argc; i++) {
11652 listObjPtr = objPtr;
11653 if (Jim_GetIndex(interp, argv[i], &idx) != JIM_OK) {
11654 Jim_DecrRefCount(interp, listObjPtr);
11655 return JIM_ERR;
11657 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_NONE) != JIM_OK) {
11658 /* Returns an empty object if the index
11659 * is out of range. */
11660 Jim_DecrRefCount(interp, listObjPtr);
11661 Jim_SetEmptyResult(interp);
11662 return JIM_OK;
11664 Jim_IncrRefCount(objPtr);
11665 Jim_DecrRefCount(interp, listObjPtr);
11667 Jim_SetResult(interp, objPtr);
11668 Jim_DecrRefCount(interp, objPtr);
11669 return JIM_OK;
11672 /* [llength] */
11673 static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11675 if (argc != 2) {
11676 Jim_WrongNumArgs(interp, 1, argv, "list");
11677 return JIM_ERR;
11679 Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
11680 return JIM_OK;
11683 /* [lsearch] */
11684 static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11686 static const char * const options[] = {
11687 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11688 NULL
11690 enum
11691 { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
11692 OPT_COMMAND };
11693 int i;
11694 int opt_bool = 0;
11695 int opt_not = 0;
11696 int opt_nocase = 0;
11697 int opt_all = 0;
11698 int opt_inline = 0;
11699 int opt_match = OPT_EXACT;
11700 int listlen;
11701 int rc = JIM_OK;
11702 Jim_Obj *listObjPtr = NULL;
11703 Jim_Obj *commandObj = NULL;
11705 if (argc < 3) {
11706 wrongargs:
11707 Jim_WrongNumArgs(interp, 1, argv,
11708 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11709 return JIM_ERR;
11712 for (i = 1; i < argc - 2; i++) {
11713 int option;
11715 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
11716 return JIM_ERR;
11718 switch (option) {
11719 case OPT_BOOL:
11720 opt_bool = 1;
11721 opt_inline = 0;
11722 break;
11723 case OPT_NOT:
11724 opt_not = 1;
11725 break;
11726 case OPT_NOCASE:
11727 opt_nocase = 1;
11728 break;
11729 case OPT_INLINE:
11730 opt_inline = 1;
11731 opt_bool = 0;
11732 break;
11733 case OPT_ALL:
11734 opt_all = 1;
11735 break;
11736 case OPT_COMMAND:
11737 if (i >= argc - 2) {
11738 goto wrongargs;
11740 commandObj = argv[++i];
11741 /* fallthru */
11742 case OPT_EXACT:
11743 case OPT_GLOB:
11744 case OPT_REGEXP:
11745 opt_match = option;
11746 break;
11750 argv += i;
11752 if (opt_all) {
11753 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11755 if (opt_match == OPT_REGEXP) {
11756 commandObj = Jim_NewStringObj(interp, "regexp", -1);
11758 if (commandObj) {
11759 Jim_IncrRefCount(commandObj);
11762 listlen = Jim_ListLength(interp, argv[0]);
11763 for (i = 0; i < listlen; i++) {
11764 Jim_Obj *objPtr;
11765 int eq = 0;
11767 Jim_ListIndex(interp, argv[0], i, &objPtr, JIM_NONE);
11768 switch (opt_match) {
11769 case OPT_EXACT:
11770 eq = Jim_StringCompareObj(interp, objPtr, argv[1], opt_nocase) == 0;
11771 break;
11773 case OPT_GLOB:
11774 eq = Jim_StringMatchObj(interp, argv[1], objPtr, opt_nocase);
11775 break;
11777 case OPT_REGEXP:
11778 case OPT_COMMAND:
11779 eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, opt_nocase);
11780 if (eq < 0) {
11781 if (listObjPtr) {
11782 Jim_FreeNewObj(interp, listObjPtr);
11784 rc = JIM_ERR;
11785 goto done;
11787 break;
11790 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11791 if (!eq && opt_bool && opt_not && !opt_all) {
11792 continue;
11795 if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
11796 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11797 Jim_Obj *resultObj;
11799 if (opt_bool) {
11800 resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
11802 else if (!opt_inline) {
11803 resultObj = Jim_NewIntObj(interp, i);
11805 else {
11806 resultObj = objPtr;
11809 if (opt_all) {
11810 Jim_ListAppendElement(interp, listObjPtr, resultObj);
11812 else {
11813 Jim_SetResult(interp, resultObj);
11814 goto done;
11819 if (opt_all) {
11820 Jim_SetResult(interp, listObjPtr);
11822 else {
11823 /* No match */
11824 if (opt_bool) {
11825 Jim_SetResultBool(interp, opt_not);
11827 else if (!opt_inline) {
11828 Jim_SetResultInt(interp, -1);
11832 done:
11833 if (commandObj) {
11834 Jim_DecrRefCount(interp, commandObj);
11836 return rc;
11839 /* [lappend] */
11840 static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11842 Jim_Obj *listObjPtr;
11843 int shared, i;
11845 if (argc < 2) {
11846 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
11847 return JIM_ERR;
11849 listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
11850 if (!listObjPtr) {
11851 /* Create the list if it does not exists */
11852 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11853 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11854 Jim_FreeNewObj(interp, listObjPtr);
11855 return JIM_ERR;
11858 shared = Jim_IsShared(listObjPtr);
11859 if (shared)
11860 listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
11861 for (i = 2; i < argc; i++)
11862 Jim_ListAppendElement(interp, listObjPtr, argv[i]);
11863 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11864 if (shared)
11865 Jim_FreeNewObj(interp, listObjPtr);
11866 return JIM_ERR;
11868 Jim_SetResult(interp, listObjPtr);
11869 return JIM_OK;
11872 /* [linsert] */
11873 static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11875 int idx, len;
11876 Jim_Obj *listPtr;
11878 if (argc < 4) {
11879 Jim_WrongNumArgs(interp, 1, argv, "list index element " "?element ...?");
11880 return JIM_ERR;
11882 listPtr = argv[1];
11883 if (Jim_IsShared(listPtr))
11884 listPtr = Jim_DuplicateObj(interp, listPtr);
11885 if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
11886 goto err;
11887 len = Jim_ListLength(interp, listPtr);
11888 if (idx >= len)
11889 idx = len;
11890 else if (idx < 0)
11891 idx = len + idx + 1;
11892 Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
11893 Jim_SetResult(interp, listPtr);
11894 return JIM_OK;
11895 err:
11896 if (listPtr != argv[1]) {
11897 Jim_FreeNewObj(interp, listPtr);
11899 return JIM_ERR;
11902 /* [lreplace] */
11903 static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11905 int first, last, len, rangeLen;
11906 Jim_Obj *listObj;
11907 Jim_Obj *newListObj;
11909 if (argc < 4) {
11910 Jim_WrongNumArgs(interp, 1, argv, "list first last ?element element ...?");
11911 return JIM_ERR;
11913 if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
11914 Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
11915 return JIM_ERR;
11918 listObj = argv[1];
11919 len = Jim_ListLength(interp, listObj);
11921 first = JimRelToAbsIndex(len, first);
11922 last = JimRelToAbsIndex(len, last);
11923 JimRelToAbsRange(len, &first, &last, &rangeLen);
11925 /* Now construct a new list which consists of:
11926 * <elements before first> <supplied elements> <elements after last>
11929 /* Check to see if trying to replace past the end of the list */
11930 if (first < len) {
11931 /* OK. Not past the end */
11933 else if (len == 0) {
11934 /* Special for empty list, adjust first to 0 */
11935 first = 0;
11937 else {
11938 Jim_SetResultString(interp, "list doesn't contain element ", -1);
11939 Jim_AppendObj(interp, Jim_GetResult(interp), argv[2]);
11940 return JIM_ERR;
11943 /* Add the first set of elements */
11944 newListObj = Jim_NewListObj(interp, listObj->internalRep.listValue.ele, first);
11946 /* Add supplied elements */
11947 ListInsertElements(newListObj, -1, argc - 4, argv + 4);
11949 /* Add the remaining elements */
11950 ListInsertElements(newListObj, -1, len - first - rangeLen, listObj->internalRep.listValue.ele + first + rangeLen);
11952 Jim_SetResult(interp, newListObj);
11953 return JIM_OK;
11956 /* [lset] */
11957 static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11959 if (argc < 3) {
11960 Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");
11961 return JIM_ERR;
11963 else if (argc == 3) {
11964 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
11965 return JIM_ERR;
11966 Jim_SetResult(interp, argv[2]);
11967 return JIM_OK;
11969 if (Jim_SetListIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1])
11970 == JIM_ERR)
11971 return JIM_ERR;
11972 return JIM_OK;
11975 /* [lsort] */
11976 static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
11978 static const char * const options[] = {
11979 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11981 enum
11982 { OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_INDEX };
11983 Jim_Obj *resObj;
11984 int i;
11985 int retCode;
11987 struct lsort_info info;
11989 if (argc < 2) {
11990 Jim_WrongNumArgs(interp, 1, argv, "?options? list");
11991 return JIM_ERR;
11994 info.type = JIM_LSORT_ASCII;
11995 info.order = 1;
11996 info.indexed = 0;
11997 info.command = NULL;
11998 info.interp = interp;
12000 for (i = 1; i < (argc - 1); i++) {
12001 int option;
12003 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG)
12004 != JIM_OK)
12005 return JIM_ERR;
12006 switch (option) {
12007 case OPT_ASCII:
12008 info.type = JIM_LSORT_ASCII;
12009 break;
12010 case OPT_NOCASE:
12011 info.type = JIM_LSORT_NOCASE;
12012 break;
12013 case OPT_INTEGER:
12014 info.type = JIM_LSORT_INTEGER;
12015 break;
12016 case OPT_INCREASING:
12017 info.order = 1;
12018 break;
12019 case OPT_DECREASING:
12020 info.order = -1;
12021 break;
12022 case OPT_COMMAND:
12023 if (i >= (argc - 2)) {
12024 Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
12025 return JIM_ERR;
12027 info.type = JIM_LSORT_COMMAND;
12028 info.command = argv[i + 1];
12029 i++;
12030 break;
12031 case OPT_INDEX:
12032 if (i >= (argc - 2)) {
12033 Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
12034 return JIM_ERR;
12036 if (Jim_GetIndex(interp, argv[i + 1], &info.index) != JIM_OK) {
12037 return JIM_ERR;
12039 info.indexed = 1;
12040 i++;
12041 break;
12044 resObj = Jim_DuplicateObj(interp, argv[argc - 1]);
12045 retCode = ListSortElements(interp, resObj, &info);
12046 if (retCode == JIM_OK) {
12047 Jim_SetResult(interp, resObj);
12049 else {
12050 Jim_FreeNewObj(interp, resObj);
12052 return retCode;
12055 /* [append] */
12056 static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12058 Jim_Obj *stringObjPtr;
12059 int i;
12061 if (argc < 2) {
12062 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
12063 return JIM_ERR;
12065 if (argc == 2) {
12066 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
12067 if (!stringObjPtr)
12068 return JIM_ERR;
12070 else {
12071 int freeobj = 0;
12072 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
12073 if (!stringObjPtr) {
12074 /* Create the string if it doesn't exist */
12075 stringObjPtr = Jim_NewEmptyStringObj(interp);
12076 freeobj = 1;
12078 else if (Jim_IsShared(stringObjPtr)) {
12079 freeobj = 1;
12080 stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
12082 for (i = 2; i < argc; i++) {
12083 Jim_AppendObj(interp, stringObjPtr, argv[i]);
12085 if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
12086 if (freeobj) {
12087 Jim_FreeNewObj(interp, stringObjPtr);
12089 return JIM_ERR;
12092 Jim_SetResult(interp, stringObjPtr);
12093 return JIM_OK;
12096 /* [debug] */
12097 static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12099 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12100 static const char * const options[] = {
12101 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12102 "exprbc", "show",
12103 NULL
12105 enum
12107 OPT_REFCOUNT, OPT_OBJCOUNT, OPT_OBJECTS, OPT_INVSTR, OPT_SCRIPTLEN,
12108 OPT_EXPRLEN, OPT_EXPRBC, OPT_SHOW,
12110 int option;
12112 if (argc < 2) {
12113 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?...?");
12114 return JIM_ERR;
12116 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK)
12117 return JIM_ERR;
12118 if (option == OPT_REFCOUNT) {
12119 if (argc != 3) {
12120 Jim_WrongNumArgs(interp, 2, argv, "object");
12121 return JIM_ERR;
12123 Jim_SetResultInt(interp, argv[2]->refCount);
12124 return JIM_OK;
12126 else if (option == OPT_OBJCOUNT) {
12127 int freeobj = 0, liveobj = 0;
12128 char buf[256];
12129 Jim_Obj *objPtr;
12131 if (argc != 2) {
12132 Jim_WrongNumArgs(interp, 2, argv, "");
12133 return JIM_ERR;
12135 /* Count the number of free objects. */
12136 objPtr = interp->freeList;
12137 while (objPtr) {
12138 freeobj++;
12139 objPtr = objPtr->nextObjPtr;
12141 /* Count the number of live objects. */
12142 objPtr = interp->liveList;
12143 while (objPtr) {
12144 liveobj++;
12145 objPtr = objPtr->nextObjPtr;
12147 /* Set the result string and return. */
12148 sprintf(buf, "free %d used %d", freeobj, liveobj);
12149 Jim_SetResultString(interp, buf, -1);
12150 return JIM_OK;
12152 else if (option == OPT_OBJECTS) {
12153 Jim_Obj *objPtr, *listObjPtr, *subListObjPtr;
12155 /* Count the number of live objects. */
12156 objPtr = interp->liveList;
12157 listObjPtr = Jim_NewListObj(interp, NULL, 0);
12158 while (objPtr) {
12159 char buf[128];
12160 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "";
12162 subListObjPtr = Jim_NewListObj(interp, NULL, 0);
12163 sprintf(buf, "%p", objPtr);
12164 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, buf, -1));
12165 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, type, -1));
12166 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewIntObj(interp, objPtr->refCount));
12167 Jim_ListAppendElement(interp, subListObjPtr, objPtr);
12168 Jim_ListAppendElement(interp, listObjPtr, subListObjPtr);
12169 objPtr = objPtr->nextObjPtr;
12171 Jim_SetResult(interp, listObjPtr);
12172 return JIM_OK;
12174 else if (option == OPT_INVSTR) {
12175 Jim_Obj *objPtr;
12177 if (argc != 3) {
12178 Jim_WrongNumArgs(interp, 2, argv, "object");
12179 return JIM_ERR;
12181 objPtr = argv[2];
12182 if (objPtr->typePtr != NULL)
12183 Jim_InvalidateStringRep(objPtr);
12184 Jim_SetEmptyResult(interp);
12185 return JIM_OK;
12187 else if (option == OPT_SHOW) {
12188 const char *s;
12189 int len, charlen;
12191 if (argc != 3) {
12192 Jim_WrongNumArgs(interp, 2, argv, "object");
12193 return JIM_ERR;
12195 s = Jim_GetString(argv[2], &len);
12196 #ifdef JIM_UTF8
12197 charlen = utf8_strlen(s, len);
12198 #else
12199 charlen = len;
12200 #endif
12201 printf("refcount: %d, type: %s\n", argv[2]->refCount, JimObjTypeName(argv[2]));
12202 printf("chars (%d): <<%s>>\n", charlen, s);
12203 printf("bytes (%d):", len);
12204 while (len--) {
12205 printf(" %02x", (unsigned char)*s++);
12207 printf("\n");
12208 return JIM_OK;
12210 else if (option == OPT_SCRIPTLEN) {
12211 ScriptObj *script;
12213 if (argc != 3) {
12214 Jim_WrongNumArgs(interp, 2, argv, "script");
12215 return JIM_ERR;
12217 script = Jim_GetScript(interp, argv[2]);
12218 Jim_SetResultInt(interp, script->len);
12219 return JIM_OK;
12221 else if (option == OPT_EXPRLEN) {
12222 ExprByteCode *expr;
12224 if (argc != 3) {
12225 Jim_WrongNumArgs(interp, 2, argv, "expression");
12226 return JIM_ERR;
12228 expr = JimGetExpression(interp, argv[2]);
12229 if (expr == NULL)
12230 return JIM_ERR;
12231 Jim_SetResultInt(interp, expr->len);
12232 return JIM_OK;
12234 else if (option == OPT_EXPRBC) {
12235 Jim_Obj *objPtr;
12236 ExprByteCode *expr;
12237 int i;
12239 if (argc != 3) {
12240 Jim_WrongNumArgs(interp, 2, argv, "expression");
12241 return JIM_ERR;
12243 expr = JimGetExpression(interp, argv[2]);
12244 if (expr == NULL)
12245 return JIM_ERR;
12246 objPtr = Jim_NewListObj(interp, NULL, 0);
12247 for (i = 0; i < expr->len; i++) {
12248 const char *type;
12249 const Jim_ExprOperator *op;
12250 Jim_Obj *obj = expr->token[i].objPtr;
12252 switch (expr->token[i].type) {
12253 case JIM_TT_EXPR_INT:
12254 type = "int";
12255 break;
12256 case JIM_TT_EXPR_DOUBLE:
12257 type = "double";
12258 break;
12259 case JIM_TT_CMD:
12260 type = "command";
12261 break;
12262 case JIM_TT_VAR:
12263 type = "variable";
12264 break;
12265 case JIM_TT_DICTSUGAR:
12266 type = "dictsugar";
12267 break;
12268 case JIM_TT_EXPRSUGAR:
12269 type = "exprsugar";
12270 break;
12271 case JIM_TT_ESC:
12272 type = "subst";
12273 break;
12274 case JIM_TT_STR:
12275 type = "string";
12276 break;
12277 default:
12278 op = JimExprOperatorInfoByOpcode(expr->token[i].type);
12279 if (op == NULL) {
12280 type = "private";
12282 else {
12283 type = "operator";
12285 obj = Jim_NewStringObj(interp, op ? op->name : "", -1);
12286 break;
12288 Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, type, -1));
12289 Jim_ListAppendElement(interp, objPtr, obj);
12291 Jim_SetResult(interp, objPtr);
12292 return JIM_OK;
12294 else {
12295 Jim_SetResultString(interp,
12296 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12297 return JIM_ERR;
12299 /* unreached */
12300 #endif /* JIM_BOOTSTRAP */
12301 #if !defined(JIM_DEBUG_COMMAND)
12302 Jim_SetResultString(interp, "unsupported", -1);
12303 return JIM_ERR;
12304 #endif
12307 /* [eval] */
12308 static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12310 int rc;
12312 if (argc < 2) {
12313 Jim_WrongNumArgs(interp, 1, argv, "script ?...?");
12314 return JIM_ERR;
12317 if (argc == 2) {
12318 rc = Jim_EvalObj(interp, argv[1]);
12320 else {
12321 rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12324 if (rc == JIM_ERR) {
12325 /* eval is "interesting", so add a stack frame here */
12326 interp->addStackTrace++;
12328 return rc;
12331 /* [uplevel] */
12332 static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12334 if (argc >= 2) {
12335 int retcode;
12336 Jim_CallFrame *savedCallFrame, *targetCallFrame;
12337 Jim_Obj *objPtr;
12338 const char *str;
12340 /* Save the old callframe pointer */
12341 savedCallFrame = interp->framePtr;
12343 /* Lookup the target frame pointer */
12344 str = Jim_String(argv[1]);
12345 if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
12346 targetCallFrame =Jim_GetCallFrameByLevel(interp, argv[1]);
12347 argc--;
12348 argv++;
12350 else {
12351 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12353 if (targetCallFrame == NULL) {
12354 return JIM_ERR;
12356 if (argc < 2) {
12357 argv--;
12358 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12359 return JIM_ERR;
12361 /* Eval the code in the target callframe. */
12362 interp->framePtr = targetCallFrame;
12363 if (argc == 2) {
12364 retcode = Jim_EvalObj(interp, argv[1]);
12366 else {
12367 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12368 Jim_IncrRefCount(objPtr);
12369 retcode = Jim_EvalObj(interp, objPtr);
12370 Jim_DecrRefCount(interp, objPtr);
12372 interp->framePtr = savedCallFrame;
12373 return retcode;
12375 else {
12376 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12377 return JIM_ERR;
12381 /* [expr] */
12382 static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12384 Jim_Obj *exprResultPtr;
12385 int retcode;
12387 if (argc == 2) {
12388 retcode = Jim_EvalExpression(interp, argv[1], &exprResultPtr);
12390 else if (argc > 2) {
12391 Jim_Obj *objPtr;
12393 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12394 Jim_IncrRefCount(objPtr);
12395 retcode = Jim_EvalExpression(interp, objPtr, &exprResultPtr);
12396 Jim_DecrRefCount(interp, objPtr);
12398 else {
12399 Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
12400 return JIM_ERR;
12402 if (retcode != JIM_OK)
12403 return retcode;
12404 Jim_SetResult(interp, exprResultPtr);
12405 Jim_DecrRefCount(interp, exprResultPtr);
12406 return JIM_OK;
12409 /* [break] */
12410 static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12412 if (argc != 1) {
12413 Jim_WrongNumArgs(interp, 1, argv, "");
12414 return JIM_ERR;
12416 return JIM_BREAK;
12419 /* [continue] */
12420 static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12422 if (argc != 1) {
12423 Jim_WrongNumArgs(interp, 1, argv, "");
12424 return JIM_ERR;
12426 return JIM_CONTINUE;
12429 /* [return] */
12430 static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12432 int i;
12433 Jim_Obj *stackTraceObj = NULL;
12434 Jim_Obj *errorCodeObj = NULL;
12435 int returnCode = JIM_OK;
12436 long level = 1;
12438 for (i = 1; i < argc - 1; i += 2) {
12439 if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
12440 if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
12441 return JIM_ERR;
12444 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
12445 stackTraceObj = argv[i + 1];
12447 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
12448 errorCodeObj = argv[i + 1];
12450 else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
12451 if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
12452 Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
12453 return JIM_ERR;
12456 else {
12457 break;
12461 if (i != argc - 1 && i != argc) {
12462 Jim_WrongNumArgs(interp, 1, argv,
12463 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12466 /* If a stack trace is supplied and code is error, set the stack trace */
12467 if (stackTraceObj && returnCode == JIM_ERR) {
12468 JimSetStackTrace(interp, stackTraceObj);
12470 /* If an error code list is supplied, set the global $errorCode */
12471 if (errorCodeObj && returnCode == JIM_ERR) {
12472 Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
12474 interp->returnCode = returnCode;
12475 interp->returnLevel = level;
12477 if (i == argc - 1) {
12478 Jim_SetResult(interp, argv[i]);
12480 return JIM_RETURN;
12483 /* [tailcall] */
12484 static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12486 Jim_Obj *objPtr;
12488 objPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
12489 Jim_SetResult(interp, objPtr);
12490 return JIM_EVAL;
12493 /* [proc] */
12494 static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12496 if (argc != 4 && argc != 5) {
12497 Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
12498 return JIM_ERR;
12501 if (argc == 4) {
12502 return JimCreateProcedure(interp, argv[1], argv[2], NULL, argv[3]);
12504 else {
12505 return JimCreateProcedure(interp, argv[1], argv[2], argv[3], argv[4]);
12509 /* [local] */
12510 static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12512 int retcode;
12514 /* Evaluate the arguments with 'local' in force */
12515 interp->local++;
12516 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12517 interp->local--;
12520 /* If OK, and the result is a proc, add it to the list of local procs */
12521 if (retcode == 0) {
12522 const char *procname = Jim_String(Jim_GetResult(interp));
12524 if (Jim_FindHashEntry(&interp->commands, procname) == NULL) {
12525 Jim_SetResultFormatted(interp, "not a proc: \"%s\"", procname);
12526 return JIM_ERR;
12528 if (interp->localProcs == NULL) {
12529 interp->localProcs = Jim_Alloc(sizeof(*interp->localProcs));
12530 Jim_InitStack(interp->localProcs);
12532 Jim_StackPush(interp->localProcs, Jim_StrDup(procname));
12535 return retcode;
12538 /* [upcall] */
12539 static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12541 if (argc < 2) {
12542 Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
12543 return JIM_ERR;
12545 else {
12546 int retcode;
12548 Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
12549 if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->u.proc.prevCmd) {
12550 Jim_SetResultFormatted(interp, "no previous proc: \"%#s\"", argv[1]);
12551 return JIM_ERR;
12553 /* OK. Mark this command as being in an upcall */
12554 cmdPtr->u.proc.upcall++;
12555 JimIncrCmdRefCount(cmdPtr);
12557 /* Invoke the command as normal */
12558 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12560 /* No longer in an upcall */
12561 cmdPtr->u.proc.upcall--;
12562 JimDecrCmdRefCount(interp, cmdPtr);
12564 return retcode;
12568 /* [concat] */
12569 static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12571 Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12572 return JIM_OK;
12575 /* [upvar] */
12576 static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12578 int i;
12579 Jim_CallFrame *targetCallFrame;
12581 /* Lookup the target frame pointer */
12582 if (argc > 3 && (argc % 2 == 0)) {
12583 targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
12584 argc--;
12585 argv++;
12587 else {
12588 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12590 if (targetCallFrame == NULL) {
12591 return JIM_ERR;
12594 /* Check for arity */
12595 if (argc < 3) {
12596 Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
12597 return JIM_ERR;
12600 /* Now... for every other/local couple: */
12601 for (i = 1; i < argc; i += 2) {
12602 if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
12603 return JIM_ERR;
12605 return JIM_OK;
12608 /* [global] */
12609 static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12611 int i;
12613 if (argc < 2) {
12614 Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
12615 return JIM_ERR;
12617 /* Link every var to the toplevel having the same name */
12618 if (interp->framePtr->level == 0)
12619 return JIM_OK; /* global at toplevel... */
12620 for (i = 1; i < argc; i++) {
12621 /* global ::blah does nothing */
12622 const char *name = Jim_String(argv[i]);
12623 if (name[0] != ':' || name[1] != ':') {
12624 if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
12625 return JIM_ERR;
12628 return JIM_OK;
12631 /* does the [string map] operation. On error NULL is returned,
12632 * otherwise a new string object with the result, having refcount = 0,
12633 * is returned. */
12634 static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
12635 Jim_Obj *objPtr, int nocase)
12637 int numMaps;
12638 const char *str, *noMatchStart = NULL;
12639 int strLen, i;
12640 Jim_Obj *resultObjPtr;
12642 numMaps = Jim_ListLength(interp, mapListObjPtr);
12643 if (numMaps % 2) {
12644 Jim_SetResultString(interp, "list must contain an even number of elements", -1);
12645 return NULL;
12648 str = Jim_String(objPtr);
12649 strLen = Jim_Utf8Length(interp, objPtr);
12651 /* Map it */
12652 resultObjPtr = Jim_NewStringObj(interp, "", 0);
12653 while (strLen) {
12654 for (i = 0; i < numMaps; i += 2) {
12655 Jim_Obj *objPtr;
12656 const char *k;
12657 int kl;
12659 Jim_ListIndex(interp, mapListObjPtr, i, &objPtr, JIM_NONE);
12660 k = Jim_String(objPtr);
12661 kl = Jim_Utf8Length(interp, objPtr);
12663 if (strLen >= kl && kl) {
12664 int rc;
12665 if (nocase) {
12666 rc = JimStringCompareNoCase(str, k, kl);
12668 else {
12669 rc = JimStringCompare(str, kl, k, kl);
12671 if (rc == 0) {
12672 if (noMatchStart) {
12673 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12674 noMatchStart = NULL;
12676 Jim_ListIndex(interp, mapListObjPtr, i + 1, &objPtr, JIM_NONE);
12677 Jim_AppendObj(interp, resultObjPtr, objPtr);
12678 str += utf8_index(str, kl);
12679 strLen -= kl;
12680 break;
12684 if (i == numMaps) { /* no match */
12685 int c;
12686 if (noMatchStart == NULL)
12687 noMatchStart = str;
12688 str += utf8_tounicode(str, &c);
12689 strLen--;
12692 if (noMatchStart) {
12693 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12695 return resultObjPtr;
12698 /* [string] */
12699 static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12701 int len;
12702 int opt_case = 1;
12703 int option;
12704 static const char * const options[] = {
12705 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12706 "repeat", "reverse", "index", "first", "last",
12707 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12709 enum
12711 OPT_BYTELENGTH, OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_IS, OPT_BYTERANGE, OPT_RANGE, OPT_MAP,
12712 OPT_REPEAT, OPT_REVERSE, OPT_INDEX, OPT_FIRST, OPT_LAST,
12713 OPT_TRIM, OPT_TRIMLEFT, OPT_TRIMRIGHT, OPT_TOLOWER, OPT_TOUPPER
12715 static const char * const nocase_options[] = {
12716 "-nocase", NULL
12719 if (argc < 2) {
12720 Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
12721 return JIM_ERR;
12723 if (Jim_GetEnum(interp, argv[1], options, &option, NULL,
12724 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK)
12725 return JIM_ERR;
12727 switch (option) {
12728 case OPT_LENGTH:
12729 case OPT_BYTELENGTH:
12730 if (argc != 3) {
12731 Jim_WrongNumArgs(interp, 2, argv, "string");
12732 return JIM_ERR;
12734 if (option == OPT_LENGTH) {
12735 len = Jim_Utf8Length(interp, argv[2]);
12737 else {
12738 len = Jim_Length(argv[2]);
12740 Jim_SetResultInt(interp, len);
12741 return JIM_OK;
12743 case OPT_COMPARE:
12744 case OPT_EQUAL:
12745 if (argc != 4 &&
12746 (argc != 5 ||
12747 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12748 JIM_ENUM_ABBREV) != JIM_OK)) {
12749 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? string1 string2");
12750 return JIM_ERR;
12752 if (opt_case == 0) {
12753 argv++;
12755 if (option == OPT_COMPARE || !opt_case) {
12756 Jim_SetResultInt(interp, Jim_StringCompareObj(interp, argv[2], argv[3], !opt_case));
12758 else {
12759 Jim_SetResultBool(interp, Jim_StringEqObj(argv[2], argv[3]));
12761 return JIM_OK;
12763 case OPT_MATCH:
12764 if (argc != 4 &&
12765 (argc != 5 ||
12766 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12767 JIM_ENUM_ABBREV) != JIM_OK)) {
12768 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
12769 return JIM_ERR;
12771 if (opt_case == 0) {
12772 argv++;
12774 Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
12775 return JIM_OK;
12777 case OPT_MAP:{
12778 Jim_Obj *objPtr;
12780 if (argc != 4 &&
12781 (argc != 5 ||
12782 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12783 JIM_ENUM_ABBREV) != JIM_OK)) {
12784 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
12785 return JIM_ERR;
12788 if (opt_case == 0) {
12789 argv++;
12791 objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
12792 if (objPtr == NULL) {
12793 return JIM_ERR;
12795 Jim_SetResult(interp, objPtr);
12796 return JIM_OK;
12799 case OPT_RANGE:
12800 case OPT_BYTERANGE:{
12801 Jim_Obj *objPtr;
12803 if (argc != 5) {
12804 Jim_WrongNumArgs(interp, 2, argv, "string first last");
12805 return JIM_ERR;
12807 if (option == OPT_RANGE) {
12808 objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
12810 else
12812 objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
12815 if (objPtr == NULL) {
12816 return JIM_ERR;
12818 Jim_SetResult(interp, objPtr);
12819 return JIM_OK;
12822 case OPT_REPEAT:{
12823 Jim_Obj *objPtr;
12824 jim_wide count;
12826 if (argc != 4) {
12827 Jim_WrongNumArgs(interp, 2, argv, "string count");
12828 return JIM_ERR;
12830 if (Jim_GetWide(interp, argv[3], &count) != JIM_OK) {
12831 return JIM_ERR;
12833 objPtr = Jim_NewStringObj(interp, "", 0);
12834 if (count > 0) {
12835 while (count--) {
12836 Jim_AppendObj(interp, objPtr, argv[2]);
12839 Jim_SetResult(interp, objPtr);
12840 return JIM_OK;
12843 case OPT_REVERSE:{
12844 char *buf, *p;
12845 const char *str;
12846 int len;
12847 int i;
12849 if (argc != 3) {
12850 Jim_WrongNumArgs(interp, 2, argv, "string");
12851 return JIM_ERR;
12854 str = Jim_GetString(argv[2], &len);
12855 buf = Jim_Alloc(len + 1);
12856 p = buf + len;
12857 *p = 0;
12858 for (i = 0; i < len; ) {
12859 int c;
12860 int l = utf8_tounicode(str, &c);
12861 memcpy(p - l, str, l);
12862 p -= l;
12863 i += l;
12864 str += l;
12866 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
12867 return JIM_OK;
12870 case OPT_INDEX:{
12871 int idx;
12872 const char *str;
12874 if (argc != 4) {
12875 Jim_WrongNumArgs(interp, 2, argv, "string index");
12876 return JIM_ERR;
12878 if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
12879 return JIM_ERR;
12881 str = Jim_String(argv[2]);
12882 len = Jim_Utf8Length(interp, argv[2]);
12883 if (idx != INT_MIN && idx != INT_MAX) {
12884 idx = JimRelToAbsIndex(len, idx);
12886 if (idx < 0 || idx >= len || str == NULL) {
12887 Jim_SetResultString(interp, "", 0);
12889 else if (len == Jim_Length(argv[2])) {
12890 /* ASCII optimisation */
12891 Jim_SetResultString(interp, str + idx, 1);
12893 else {
12894 int c;
12895 int i = utf8_index(str, idx);
12896 Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
12898 return JIM_OK;
12901 case OPT_FIRST:
12902 case OPT_LAST:{
12903 int idx = 0, l1, l2;
12904 const char *s1, *s2;
12906 if (argc != 4 && argc != 5) {
12907 Jim_WrongNumArgs(interp, 2, argv, "subString string ?index?");
12908 return JIM_ERR;
12910 s1 = Jim_String(argv[2]);
12911 s2 = Jim_String(argv[3]);
12912 l1 = Jim_Utf8Length(interp, argv[2]);
12913 l2 = Jim_Utf8Length(interp, argv[3]);
12914 if (argc == 5) {
12915 if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
12916 return JIM_ERR;
12918 idx = JimRelToAbsIndex(l2, idx);
12920 else if (option == OPT_LAST) {
12921 idx = l2;
12923 if (option == OPT_FIRST) {
12924 Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
12926 else {
12927 #ifdef JIM_UTF8
12928 Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
12929 #else
12930 Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
12931 #endif
12933 return JIM_OK;
12936 case OPT_TRIM:
12937 case OPT_TRIMLEFT:
12938 case OPT_TRIMRIGHT:{
12939 Jim_Obj *trimchars;
12941 if (argc != 3 && argc != 4) {
12942 Jim_WrongNumArgs(interp, 2, argv, "string ?trimchars?");
12943 return JIM_ERR;
12945 trimchars = (argc == 4 ? argv[3] : NULL);
12946 if (option == OPT_TRIM) {
12947 Jim_SetResult(interp, JimStringTrim(interp, argv[2], trimchars));
12949 else if (option == OPT_TRIMLEFT) {
12950 Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], trimchars));
12952 else if (option == OPT_TRIMRIGHT) {
12953 Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], trimchars));
12955 return JIM_OK;
12958 case OPT_TOLOWER:
12959 case OPT_TOUPPER:
12960 if (argc != 3) {
12961 Jim_WrongNumArgs(interp, 2, argv, "string");
12962 return JIM_ERR;
12964 if (option == OPT_TOLOWER) {
12965 Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
12967 else {
12968 Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
12970 return JIM_OK;
12972 case OPT_IS:
12973 if (argc == 4 || (argc == 5 && Jim_CompareStringImmediate(interp, argv[3], "-strict"))) {
12974 return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
12976 Jim_WrongNumArgs(interp, 2, argv, "class ?-strict? str");
12977 return JIM_ERR;
12979 return JIM_OK;
12982 /* [time] */
12983 static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12985 long i, count = 1;
12986 jim_wide start, elapsed;
12987 char buf[60];
12988 const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";
12990 if (argc < 2) {
12991 Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
12992 return JIM_ERR;
12994 if (argc == 3) {
12995 if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
12996 return JIM_ERR;
12998 if (count < 0)
12999 return JIM_OK;
13000 i = count;
13001 start = JimClock();
13002 while (i-- > 0) {
13003 int retval;
13005 retval = Jim_EvalObj(interp, argv[1]);
13006 if (retval != JIM_OK) {
13007 return retval;
13010 elapsed = JimClock() - start;
13011 sprintf(buf, fmt, count == 0 ? 0 : elapsed / count);
13012 Jim_SetResultString(interp, buf, -1);
13013 return JIM_OK;
13016 /* [exit] */
13017 static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13019 long exitCode = 0;
13021 if (argc > 2) {
13022 Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
13023 return JIM_ERR;
13025 if (argc == 2) {
13026 if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
13027 return JIM_ERR;
13029 interp->exitCode = exitCode;
13030 return JIM_EXIT;
13033 /* [catch] */
13034 static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13036 int exitCode = 0;
13037 int i;
13038 int sig = 0;
13040 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
13041 jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
13042 static const int max_ignore_code = sizeof(ignore_mask) * 8;
13044 /* Reset the error code before catch.
13045 * Note that this is not strictly correct.
13047 Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
13049 for (i = 1; i < argc - 1; i++) {
13050 const char *arg = Jim_String(argv[i]);
13051 jim_wide option;
13052 int ignore;
13054 /* It's a pity we can't use Jim_GetEnum here :-( */
13055 if (strcmp(arg, "--") == 0) {
13056 i++;
13057 break;
13059 if (*arg != '-') {
13060 break;
13063 if (strncmp(arg, "-no", 3) == 0) {
13064 arg += 3;
13065 ignore = 1;
13067 else {
13068 arg++;
13069 ignore = 0;
13072 if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
13073 option = -1;
13075 if (option < 0) {
13076 option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
13078 if (option < 0) {
13079 goto wrongargs;
13082 if (ignore) {
13083 ignore_mask |= (1 << option);
13085 else {
13086 ignore_mask &= ~(1 << option);
13090 argc -= i;
13091 if (argc < 1 || argc > 3) {
13092 wrongargs:
13093 Jim_WrongNumArgs(interp, 1, argv,
13094 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13095 return JIM_ERR;
13097 argv += i;
13099 if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
13100 sig++;
13103 interp->signal_level += sig;
13104 if (interp->signal_level && interp->sigmask) {
13105 /* If a signal is set, don't even try to execute the body */
13106 exitCode = JIM_SIGNAL;
13108 else {
13109 exitCode = Jim_EvalObj(interp, argv[0]);
13111 interp->signal_level -= sig;
13113 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13114 if (exitCode >= 0 && exitCode < max_ignore_code && ((1 << exitCode) & ignore_mask)) {
13115 /* Not caught, pass it up */
13116 return exitCode;
13119 if (sig && exitCode == JIM_SIGNAL) {
13120 /* Catch the signal at this level */
13121 if (interp->signal_set_result) {
13122 interp->signal_set_result(interp, interp->sigmask);
13124 else {
13125 Jim_SetResultInt(interp, interp->sigmask);
13127 interp->sigmask = 0;
13130 if (argc >= 2) {
13131 if (Jim_SetVariable(interp, argv[1], Jim_GetResult(interp)) != JIM_OK) {
13132 return JIM_ERR;
13134 if (argc == 3) {
13135 Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
13137 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
13138 Jim_ListAppendElement(interp, optListObj,
13139 Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
13140 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
13141 Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
13142 if (exitCode == JIM_ERR) {
13143 Jim_Obj *errorCode;
13144 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
13145 -1));
13146 Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
13148 errorCode = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
13149 if (errorCode) {
13150 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
13151 Jim_ListAppendElement(interp, optListObj, errorCode);
13154 if (Jim_SetVariable(interp, argv[2], optListObj) != JIM_OK) {
13155 return JIM_ERR;
13159 Jim_SetResultInt(interp, exitCode);
13160 return JIM_OK;
13163 #ifdef JIM_REFERENCES
13165 /* [ref] */
13166 static int Jim_RefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13168 if (argc != 3 && argc != 4) {
13169 Jim_WrongNumArgs(interp, 1, argv, "string tag ?finalizer?");
13170 return JIM_ERR;
13172 if (argc == 3) {
13173 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], NULL));
13175 else {
13176 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], argv[3]));
13178 return JIM_OK;
13181 /* [getref] */
13182 static int Jim_GetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13184 Jim_Reference *refPtr;
13186 if (argc != 2) {
13187 Jim_WrongNumArgs(interp, 1, argv, "reference");
13188 return JIM_ERR;
13190 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13191 return JIM_ERR;
13192 Jim_SetResult(interp, refPtr->objPtr);
13193 return JIM_OK;
13196 /* [setref] */
13197 static int Jim_SetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13199 Jim_Reference *refPtr;
13201 if (argc != 3) {
13202 Jim_WrongNumArgs(interp, 1, argv, "reference newValue");
13203 return JIM_ERR;
13205 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13206 return JIM_ERR;
13207 Jim_IncrRefCount(argv[2]);
13208 Jim_DecrRefCount(interp, refPtr->objPtr);
13209 refPtr->objPtr = argv[2];
13210 Jim_SetResult(interp, argv[2]);
13211 return JIM_OK;
13214 /* [collect] */
13215 static int Jim_CollectCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13217 if (argc != 1) {
13218 Jim_WrongNumArgs(interp, 1, argv, "");
13219 return JIM_ERR;
13221 Jim_SetResultInt(interp, Jim_Collect(interp));
13223 /* Free all the freed objects. */
13224 while (interp->freeList) {
13225 Jim_Obj *nextObjPtr = interp->freeList->nextObjPtr;
13226 Jim_Free(interp->freeList);
13227 interp->freeList = nextObjPtr;
13230 return JIM_OK;
13233 /* [finalize] reference ?newValue? */
13234 static int Jim_FinalizeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13236 if (argc != 2 && argc != 3) {
13237 Jim_WrongNumArgs(interp, 1, argv, "reference ?finalizerProc?");
13238 return JIM_ERR;
13240 if (argc == 2) {
13241 Jim_Obj *cmdNamePtr;
13243 if (Jim_GetFinalizer(interp, argv[1], &cmdNamePtr) != JIM_OK)
13244 return JIM_ERR;
13245 if (cmdNamePtr != NULL) /* otherwise the null string is returned. */
13246 Jim_SetResult(interp, cmdNamePtr);
13248 else {
13249 if (Jim_SetFinalizer(interp, argv[1], argv[2]) != JIM_OK)
13250 return JIM_ERR;
13251 Jim_SetResult(interp, argv[2]);
13253 return JIM_OK;
13256 /* [info references] */
13257 static int JimInfoReferences(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13259 Jim_Obj *listObjPtr;
13260 Jim_HashTableIterator *htiter;
13261 Jim_HashEntry *he;
13263 listObjPtr = Jim_NewListObj(interp, NULL, 0);
13265 htiter = Jim_GetHashTableIterator(&interp->references);
13266 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
13267 char buf[JIM_REFERENCE_SPACE];
13268 Jim_Reference *refPtr = he->u.val;
13269 const jim_wide *refId = he->key;
13271 JimFormatReference(buf, refPtr, *refId);
13272 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, buf, -1));
13274 Jim_FreeHashTableIterator(htiter);
13275 Jim_SetResult(interp, listObjPtr);
13276 return JIM_OK;
13278 #endif
13280 /* [rename] */
13281 static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13283 const char *oldName, *newName;
13285 if (argc != 3) {
13286 Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
13287 return JIM_ERR;
13290 if (JimValidName(interp, "new procedure", argv[2])) {
13291 return JIM_ERR;
13294 oldName = Jim_String(argv[1]);
13295 newName = Jim_String(argv[2]);
13296 return Jim_RenameCommand(interp, oldName, newName);
13299 static void JimDictMatchKeys(Jim_Interp *interp, Jim_Obj *listObjPtr,
13300 Jim_HashEntry *he, void *privdata)
13302 Jim_ListAppendElement(interp, listObjPtr, (Jim_Obj *)he->key);
13305 int Jim_DictKeys(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObjPtr)
13307 if (SetDictFromAny(interp, objPtr) != JIM_OK) {
13308 return JIM_ERR;
13310 Jim_SetResult(interp, JimHashtablePatternMatch(interp, objPtr->internalRep.ptr, patternObjPtr, JimDictMatchKeys, NULL, 0));
13311 return JIM_OK;
13314 static void JimDictMatchValues(Jim_Interp *interp, Jim_Obj *listObjPtr,
13315 Jim_HashEntry *he, void *privdata)
13317 Jim_ListAppendElement(interp, listObjPtr, (Jim_Obj *)he->key);
13318 Jim_ListAppendElement(interp, listObjPtr, (Jim_Obj *)he->u.val);
13321 int Jim_DictValues(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObjPtr)
13323 if (SetDictFromAny(interp, objPtr) != JIM_OK) {
13324 return JIM_ERR;
13326 Jim_SetResult(interp, JimHashtablePatternMatch(interp, objPtr->internalRep.ptr, patternObjPtr, JimDictMatchValues, NULL, 0));
13327 return JIM_OK;
13330 int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
13332 if (SetDictFromAny(interp, objPtr) != JIM_OK) {
13333 return -1;
13335 return ((Jim_HashTable *)objPtr->internalRep.ptr)->used;
13338 /* [dict] */
13339 static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13341 Jim_Obj *objPtr;
13342 int option;
13343 static const char * const options[] = {
13344 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13346 enum
13348 OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXIST, OPT_KEYS, OPT_MERGE, OPT_SIZE, OPT_WITH,
13351 if (argc < 2) {
13352 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?arguments ...?");
13353 return JIM_ERR;
13356 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK) {
13357 return JIM_ERR;
13360 switch (option) {
13361 case OPT_GET:
13362 if (argc < 3) {
13363 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13364 return JIM_ERR;
13366 if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
13367 JIM_ERRMSG) != JIM_OK) {
13368 return JIM_ERR;
13370 Jim_SetResult(interp, objPtr);
13371 return JIM_OK;
13373 case OPT_SET:
13374 if (argc < 5) {
13375 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");
13376 return JIM_ERR;
13378 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1], JIM_ERRMSG);
13380 case OPT_EXIST:
13381 if (argc < 3) {
13382 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13383 return JIM_ERR;
13385 Jim_SetResultBool(interp, Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3,
13386 &objPtr, JIM_ERRMSG) == JIM_OK);
13387 return JIM_OK;
13389 case OPT_UNSET:
13390 if (argc < 4) {
13391 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");
13392 return JIM_ERR;
13394 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL, JIM_NONE);
13396 case OPT_KEYS:
13397 if (argc != 3 && argc != 4) {
13398 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?pattern?");
13399 return JIM_ERR;
13401 return Jim_DictKeys(interp, argv[2], argc == 4 ? argv[3] : NULL);
13403 case OPT_SIZE: {
13404 int size;
13406 if (argc != 3) {
13407 Jim_WrongNumArgs(interp, 2, argv, "dictVar");
13408 return JIM_ERR;
13411 size = Jim_DictSize(interp, argv[2]);
13412 if (size < 0) {
13413 return JIM_ERR;
13415 Jim_SetResultInt(interp, size);
13416 return JIM_OK;
13419 case OPT_MERGE:
13420 if (argc == 2) {
13421 return JIM_OK;
13423 else if (SetDictFromAny(interp, argv[2]) != JIM_OK) {
13424 return JIM_ERR;
13426 else {
13427 return Jim_EvalPrefix(interp, "dict merge", argc - 2, argv + 2);
13430 case OPT_WITH:
13431 if (argc < 4) {
13432 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?key ...? script");
13433 return JIM_ERR;
13435 else if (Jim_GetVariable(interp, argv[2], JIM_ERRMSG) == NULL) {
13436 return JIM_ERR;
13438 else {
13439 return Jim_EvalPrefix(interp, "dict with", argc - 2, argv + 2);
13442 case OPT_CREATE:
13443 if (argc % 2) {
13444 Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");
13445 return JIM_ERR;
13447 objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
13448 Jim_SetResult(interp, objPtr);
13449 return JIM_OK;
13451 return JIM_ERR;
13454 /* [subst] */
13455 static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13457 static const char * const options[] = {
13458 "-nobackslashes", "-nocommands", "-novariables", NULL
13460 enum
13461 { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
13462 int i;
13463 int flags = JIM_SUBST_FLAG;
13464 Jim_Obj *objPtr;
13466 if (argc < 2) {
13467 Jim_WrongNumArgs(interp, 1, argv, "?options? string");
13468 return JIM_ERR;
13470 for (i = 1; i < (argc - 1); i++) {
13471 int option;
13473 if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
13474 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13475 return JIM_ERR;
13477 switch (option) {
13478 case OPT_NOBACKSLASHES:
13479 flags |= JIM_SUBST_NOESC;
13480 break;
13481 case OPT_NOCOMMANDS:
13482 flags |= JIM_SUBST_NOCMD;
13483 break;
13484 case OPT_NOVARIABLES:
13485 flags |= JIM_SUBST_NOVAR;
13486 break;
13489 if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
13490 return JIM_ERR;
13492 Jim_SetResult(interp, objPtr);
13493 return JIM_OK;
13496 /* [info] */
13497 static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13499 int cmd;
13500 Jim_Obj *objPtr;
13501 int mode = 0;
13503 static const char * const commands[] = {
13504 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13505 "vars", "version", "patchlevel", "complete", "args", "hostname",
13506 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13507 "references", NULL
13509 enum
13510 { INFO_BODY, INFO_COMMANDS, INFO_PROCS, INFO_CHANNELS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,
13511 INFO_FRAME, INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_PATCHLEVEL, INFO_COMPLETE, INFO_ARGS,
13512 INFO_HOSTNAME, INFO_SCRIPT, INFO_SOURCE, INFO_STACKTRACE, INFO_NAMEOFEXECUTABLE,
13513 INFO_RETURNCODES, INFO_REFERENCES,
13516 if (argc < 2) {
13517 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?args ...?");
13518 return JIM_ERR;
13520 if (Jim_GetEnum(interp, argv[1], commands, &cmd, "subcommand", JIM_ERRMSG | JIM_ENUM_ABBREV)
13521 != JIM_OK) {
13522 return JIM_ERR;
13525 /* Test for the the most common commands first, just in case it makes a difference */
13526 switch (cmd) {
13527 case INFO_EXISTS:{
13528 if (argc != 3) {
13529 Jim_WrongNumArgs(interp, 2, argv, "varName");
13530 return JIM_ERR;
13532 Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
13533 break;
13536 case INFO_CHANNELS:
13537 mode++; /* JIM_CMDLIST_CHANNELS */
13538 #ifndef jim_ext_aio
13539 Jim_SetResultString(interp, "aio not enabled", -1);
13540 return JIM_ERR;
13541 #endif
13542 case INFO_PROCS:
13543 mode++; /* JIM_CMDLIST_PROCS */
13544 case INFO_COMMANDS:
13545 /* mode 0 => JIM_CMDLIST_COMMANDS */
13546 if (argc != 2 && argc != 3) {
13547 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13548 return JIM_ERR;
13550 Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL, mode));
13551 break;
13553 case INFO_VARS:
13554 mode++; /* JIM_VARLIST_VARS */
13555 case INFO_LOCALS:
13556 mode++; /* JIM_VARLIST_LOCALS */
13557 case INFO_GLOBALS:
13558 /* mode 0 => JIM_VARLIST_GLOBALS */
13559 if (argc != 2 && argc != 3) {
13560 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13561 return JIM_ERR;
13563 Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
13564 break;
13566 case INFO_SCRIPT:
13567 if (argc != 2) {
13568 Jim_WrongNumArgs(interp, 2, argv, "");
13569 return JIM_ERR;
13571 Jim_SetResult(interp, Jim_GetScript(interp, interp->currentScriptObj)->fileNameObj);
13572 break;
13574 case INFO_SOURCE:{
13575 int line;
13576 Jim_Obj *resObjPtr;
13577 Jim_Obj *fileNameObj;
13579 if (argc != 3) {
13580 Jim_WrongNumArgs(interp, 2, argv, "source");
13581 return JIM_ERR;
13583 if (argv[2]->typePtr == &sourceObjType) {
13584 fileNameObj = argv[2]->internalRep.sourceValue.fileNameObj;
13585 line = argv[2]->internalRep.sourceValue.lineNumber;
13587 else if (argv[2]->typePtr == &scriptObjType) {
13588 ScriptObj *script = Jim_GetScript(interp, argv[2]);
13589 fileNameObj = script->fileNameObj;
13590 line = script->line;
13592 else {
13593 fileNameObj = interp->emptyObj;
13594 line = 1;
13596 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13597 Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
13598 Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
13599 Jim_SetResult(interp, resObjPtr);
13600 break;
13603 case INFO_STACKTRACE:
13604 Jim_SetResult(interp, interp->stackTrace);
13605 break;
13607 case INFO_LEVEL:
13608 case INFO_FRAME:
13609 switch (argc) {
13610 case 2:
13611 Jim_SetResultInt(interp, interp->framePtr->level);
13612 break;
13614 case 3:
13615 if (JimInfoLevel(interp, argv[2], &objPtr, cmd == INFO_LEVEL) != JIM_OK) {
13616 return JIM_ERR;
13618 Jim_SetResult(interp, objPtr);
13619 break;
13621 default:
13622 Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");
13623 return JIM_ERR;
13625 break;
13627 case INFO_BODY:
13628 case INFO_ARGS:{
13629 Jim_Cmd *cmdPtr;
13631 if (argc != 3) {
13632 Jim_WrongNumArgs(interp, 2, argv, "procname");
13633 return JIM_ERR;
13635 if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
13636 return JIM_ERR;
13638 if (!cmdPtr->isproc) {
13639 Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
13640 return JIM_ERR;
13642 Jim_SetResult(interp,
13643 cmd == INFO_BODY ? cmdPtr->u.proc.bodyObjPtr : cmdPtr->u.proc.argListObjPtr);
13644 break;
13647 case INFO_VERSION:
13648 case INFO_PATCHLEVEL:{
13649 char buf[(JIM_INTEGER_SPACE * 2) + 1];
13651 sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
13652 Jim_SetResultString(interp, buf, -1);
13653 break;
13656 case INFO_COMPLETE:
13657 if (argc != 3 && argc != 4) {
13658 Jim_WrongNumArgs(interp, 2, argv, "script ?missing?");
13659 return JIM_ERR;
13661 else {
13662 int len;
13663 const char *s = Jim_GetString(argv[2], &len);
13664 char missing;
13666 Jim_SetResultBool(interp, Jim_ScriptIsComplete(s, len, &missing));
13667 if (missing != ' ' && argc == 4) {
13668 Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
13671 break;
13673 case INFO_HOSTNAME:
13674 /* Redirect to os.gethostname if it exists */
13675 return Jim_Eval(interp, "os.gethostname");
13677 case INFO_NAMEOFEXECUTABLE:
13678 /* Redirect to Tcl proc */
13679 return Jim_Eval(interp, "{info nameofexecutable}");
13681 case INFO_RETURNCODES:
13682 if (argc == 2) {
13683 int i;
13684 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
13686 for (i = 0; jimReturnCodes[i]; i++) {
13687 Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
13688 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
13689 jimReturnCodes[i], -1));
13692 Jim_SetResult(interp, listObjPtr);
13694 else if (argc == 3) {
13695 long code;
13696 const char *name;
13698 if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
13699 return JIM_ERR;
13701 name = Jim_ReturnCode(code);
13702 if (*name == '?') {
13703 Jim_SetResultInt(interp, code);
13705 else {
13706 Jim_SetResultString(interp, name, -1);
13709 else {
13710 Jim_WrongNumArgs(interp, 2, argv, "?code?");
13711 return JIM_ERR;
13713 break;
13714 case INFO_REFERENCES:
13715 #ifdef JIM_REFERENCES
13716 return JimInfoReferences(interp, argc, argv);
13717 #else
13718 Jim_SetResultString(interp, "not supported", -1);
13719 return JIM_ERR;
13720 #endif
13722 return JIM_OK;
13725 /* [exists] */
13726 static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13728 Jim_Obj *objPtr;
13730 static const char * const options[] = {
13731 "-command", "-proc", "-var", NULL
13733 enum
13735 OPT_COMMAND, OPT_PROC, OPT_VAR
13737 int option;
13739 if (argc == 2) {
13740 option = OPT_VAR;
13741 objPtr = argv[1];
13743 else if (argc == 3) {
13744 if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13745 return JIM_ERR;
13747 objPtr = argv[2];
13749 else {
13750 Jim_WrongNumArgs(interp, 1, argv, "?option? name");
13751 return JIM_ERR;
13754 /* Test for the the most common commands first, just in case it makes a difference */
13755 switch (option) {
13756 case OPT_VAR:
13757 Jim_SetResultBool(interp, Jim_GetVariable(interp, objPtr, 0) != NULL);
13758 break;
13760 case OPT_COMMAND:
13761 case OPT_PROC: {
13762 Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
13763 Jim_SetResultBool(interp, cmd != NULL && (option == OPT_COMMAND || cmd->isproc));
13764 break;
13767 return JIM_OK;
13770 /* [split] */
13771 static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13773 const char *str, *splitChars, *noMatchStart;
13774 int splitLen, strLen;
13775 Jim_Obj *resObjPtr;
13776 int c;
13777 int len;
13779 if (argc != 2 && argc != 3) {
13780 Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
13781 return JIM_ERR;
13784 str = Jim_GetString(argv[1], &len);
13785 if (len == 0) {
13786 return JIM_OK;
13788 strLen = Jim_Utf8Length(interp, argv[1]);
13790 /* Init */
13791 if (argc == 2) {
13792 splitChars = " \n\t\r";
13793 splitLen = 4;
13795 else {
13796 splitChars = Jim_String(argv[2]);
13797 splitLen = Jim_Utf8Length(interp, argv[2]);
13800 noMatchStart = str;
13801 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13803 /* Split */
13804 if (splitLen) {
13805 Jim_Obj *objPtr;
13806 while (strLen--) {
13807 const char *sc = splitChars;
13808 int scLen = splitLen;
13809 int sl = utf8_tounicode(str, &c);
13810 while (scLen--) {
13811 int pc;
13812 sc += utf8_tounicode(sc, &pc);
13813 if (c == pc) {
13814 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13815 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13816 noMatchStart = str + sl;
13817 break;
13820 str += sl;
13822 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13823 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13825 else {
13826 /* This handles the special case of splitchars eq {}
13827 * Optimise by sharing common (ASCII) characters
13829 Jim_Obj **commonObj = NULL;
13830 #define NUM_COMMON (128 - 9)
13831 while (strLen--) {
13832 int n = utf8_tounicode(str, &c);
13833 #ifdef JIM_OPTIMIZATION
13834 if (c >= 9 && c < 128) {
13835 /* Common ASCII char. Note that 9 is the tab character */
13836 c -= 9;
13837 if (!commonObj) {
13838 commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
13839 memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
13841 if (!commonObj[c]) {
13842 commonObj[c] = Jim_NewStringObj(interp, str, 1);
13844 Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
13845 str++;
13846 continue;
13848 #endif
13849 Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
13850 str += n;
13852 Jim_Free(commonObj);
13855 Jim_SetResult(interp, resObjPtr);
13856 return JIM_OK;
13859 /* [join] */
13860 static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13862 const char *joinStr;
13863 int joinStrLen, i, listLen;
13864 Jim_Obj *resObjPtr;
13866 if (argc != 2 && argc != 3) {
13867 Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
13868 return JIM_ERR;
13870 /* Init */
13871 if (argc == 2) {
13872 joinStr = " ";
13873 joinStrLen = 1;
13875 else {
13876 joinStr = Jim_GetString(argv[2], &joinStrLen);
13878 listLen = Jim_ListLength(interp, argv[1]);
13879 resObjPtr = Jim_NewStringObj(interp, NULL, 0);
13880 /* Split */
13881 for (i = 0; i < listLen; i++) {
13882 Jim_Obj *objPtr = 0;
13884 Jim_ListIndex(interp, argv[1], i, &objPtr, JIM_NONE);
13885 Jim_AppendObj(interp, resObjPtr, objPtr);
13886 if (i + 1 != listLen) {
13887 Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
13890 Jim_SetResult(interp, resObjPtr);
13891 return JIM_OK;
13894 /* [format] */
13895 static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13897 Jim_Obj *objPtr;
13899 if (argc < 2) {
13900 Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
13901 return JIM_ERR;
13903 objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
13904 if (objPtr == NULL)
13905 return JIM_ERR;
13906 Jim_SetResult(interp, objPtr);
13907 return JIM_OK;
13910 /* [scan] */
13911 static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13913 Jim_Obj *listPtr, **outVec;
13914 int outc, i;
13916 if (argc < 3) {
13917 Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
13918 return JIM_ERR;
13920 if (argv[2]->typePtr != &scanFmtStringObjType)
13921 SetScanFmtFromAny(interp, argv[2]);
13922 if (FormatGetError(argv[2]) != 0) {
13923 Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
13924 return JIM_ERR;
13926 if (argc > 3) {
13927 int maxPos = FormatGetMaxPos(argv[2]);
13928 int count = FormatGetCnvCount(argv[2]);
13930 if (maxPos > argc - 3) {
13931 Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
13932 return JIM_ERR;
13934 else if (count > argc - 3) {
13935 Jim_SetResultString(interp, "different numbers of variable names and "
13936 "field specifiers", -1);
13937 return JIM_ERR;
13939 else if (count < argc - 3) {
13940 Jim_SetResultString(interp, "variable is not assigned by any "
13941 "conversion specifiers", -1);
13942 return JIM_ERR;
13945 listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
13946 if (listPtr == 0)
13947 return JIM_ERR;
13948 if (argc > 3) {
13949 int rc = JIM_OK;
13950 int count = 0;
13952 if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
13953 int len = Jim_ListLength(interp, listPtr);
13955 if (len != 0) {
13956 JimListGetElements(interp, listPtr, &outc, &outVec);
13957 for (i = 0; i < outc; ++i) {
13958 if (Jim_Length(outVec[i]) > 0) {
13959 ++count;
13960 if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
13961 rc = JIM_ERR;
13966 Jim_FreeNewObj(interp, listPtr);
13968 else {
13969 count = -1;
13971 if (rc == JIM_OK) {
13972 Jim_SetResultInt(interp, count);
13974 return rc;
13976 else {
13977 if (listPtr == (Jim_Obj *)EOF) {
13978 Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
13979 return JIM_OK;
13981 Jim_SetResult(interp, listPtr);
13983 return JIM_OK;
13986 /* [error] */
13987 static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13989 if (argc != 2 && argc != 3) {
13990 Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
13991 return JIM_ERR;
13993 Jim_SetResult(interp, argv[1]);
13994 if (argc == 3) {
13995 JimSetStackTrace(interp, argv[2]);
13996 return JIM_ERR;
13998 interp->addStackTrace++;
13999 return JIM_ERR;
14002 /* [lrange] */
14003 static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14005 Jim_Obj *objPtr;
14007 if (argc != 4) {
14008 Jim_WrongNumArgs(interp, 1, argv, "list first last");
14009 return JIM_ERR;
14011 if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
14012 return JIM_ERR;
14013 Jim_SetResult(interp, objPtr);
14014 return JIM_OK;
14017 /* [lrepeat] */
14018 static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14020 Jim_Obj *objPtr;
14021 long count;
14023 if (argc < 2 || Jim_GetLong(interp, argv[1], &count) != JIM_OK || count < 0) {
14024 Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
14025 return JIM_ERR;
14028 if (count == 0 || argc == 2) {
14029 return JIM_OK;
14032 argc -= 2;
14033 argv += 2;
14035 objPtr = Jim_NewListObj(interp, argv, argc);
14036 while (--count) {
14037 ListInsertElements(objPtr, -1, argc, argv);
14040 Jim_SetResult(interp, objPtr);
14041 return JIM_OK;
14044 char **Jim_GetEnviron(void)
14046 #if defined(HAVE__NSGETENVIRON)
14047 return *_NSGetEnviron();
14048 #else
14049 #if !defined(NO_ENVIRON_EXTERN)
14050 extern char **environ;
14051 #endif
14053 return environ;
14054 #endif
14057 void Jim_SetEnviron(char **env)
14059 #if defined(HAVE__NSGETENVIRON)
14060 *_NSGetEnviron() = env;
14061 #else
14062 #if !defined(NO_ENVIRON_EXTERN)
14063 extern char **environ;
14064 #endif
14066 environ = env;
14067 #endif
14070 /* [env] */
14071 static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14073 const char *key;
14074 const char *val;
14076 if (argc == 1) {
14077 char **e = Jim_GetEnviron();
14079 int i;
14080 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
14082 for (i = 0; e[i]; i++) {
14083 const char *equals = strchr(e[i], '=');
14085 if (equals) {
14086 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
14087 equals - e[i]));
14088 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
14092 Jim_SetResult(interp, listObjPtr);
14093 return JIM_OK;
14096 if (argc < 2) {
14097 Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
14098 return JIM_ERR;
14100 key = Jim_String(argv[1]);
14101 val = getenv(key);
14102 if (val == NULL) {
14103 if (argc < 3) {
14104 Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
14105 return JIM_ERR;
14107 val = Jim_String(argv[2]);
14109 Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
14110 return JIM_OK;
14113 /* [source] */
14114 static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14116 int retval;
14118 if (argc != 2) {
14119 Jim_WrongNumArgs(interp, 1, argv, "fileName");
14120 return JIM_ERR;
14122 retval = Jim_EvalFile(interp, Jim_String(argv[1]));
14123 if (retval == JIM_RETURN)
14124 return JIM_OK;
14125 return retval;
14128 /* [lreverse] */
14129 static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14131 Jim_Obj *revObjPtr, **ele;
14132 int len;
14134 if (argc != 2) {
14135 Jim_WrongNumArgs(interp, 1, argv, "list");
14136 return JIM_ERR;
14138 JimListGetElements(interp, argv[1], &len, &ele);
14139 len--;
14140 revObjPtr = Jim_NewListObj(interp, NULL, 0);
14141 while (len >= 0)
14142 ListAppendElement(revObjPtr, ele[len--]);
14143 Jim_SetResult(interp, revObjPtr);
14144 return JIM_OK;
14147 static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
14149 jim_wide len;
14151 if (step == 0)
14152 return -1;
14153 if (start == end)
14154 return 0;
14155 else if (step > 0 && start > end)
14156 return -1;
14157 else if (step < 0 && end > start)
14158 return -1;
14159 len = end - start;
14160 if (len < 0)
14161 len = -len; /* abs(len) */
14162 if (step < 0)
14163 step = -step; /* abs(step) */
14164 len = 1 + ((len - 1) / step);
14165 /* We can truncate safely to INT_MAX, the range command
14166 * will always return an error for a such long range
14167 * because Tcl lists can't be so long. */
14168 if (len > INT_MAX)
14169 len = INT_MAX;
14170 return (int)((len < 0) ? -1 : len);
14173 /* [range] */
14174 static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14176 jim_wide start = 0, end, step = 1;
14177 int len, i;
14178 Jim_Obj *objPtr;
14180 if (argc < 2 || argc > 4) {
14181 Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
14182 return JIM_ERR;
14184 if (argc == 2) {
14185 if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)
14186 return JIM_ERR;
14188 else {
14189 if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||
14190 Jim_GetWide(interp, argv[2], &end) != JIM_OK)
14191 return JIM_ERR;
14192 if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)
14193 return JIM_ERR;
14195 if ((len = JimRangeLen(start, end, step)) == -1) {
14196 Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
14197 return JIM_ERR;
14199 objPtr = Jim_NewListObj(interp, NULL, 0);
14200 for (i = 0; i < len; i++)
14201 ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
14202 Jim_SetResult(interp, objPtr);
14203 return JIM_OK;
14206 /* [rand] */
14207 static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14209 jim_wide min = 0, max = 0, len, maxMul;
14211 if (argc < 1 || argc > 3) {
14212 Jim_WrongNumArgs(interp, 1, argv, "?min? max");
14213 return JIM_ERR;
14215 if (argc == 1) {
14216 max = JIM_WIDE_MAX;
14217 } else if (argc == 2) {
14218 if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)
14219 return JIM_ERR;
14220 } else if (argc == 3) {
14221 if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||
14222 Jim_GetWide(interp, argv[2], &max) != JIM_OK)
14223 return JIM_ERR;
14225 len = max-min;
14226 if (len < 0) {
14227 Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
14228 return JIM_ERR;
14230 maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
14231 while (1) {
14232 jim_wide r;
14234 JimRandomBytes(interp, &r, sizeof(jim_wide));
14235 if (r < 0 || r >= maxMul) continue;
14236 r = (len == 0) ? 0 : r%len;
14237 Jim_SetResultInt(interp, min+r);
14238 return JIM_OK;
14242 static const struct {
14243 const char *name;
14244 Jim_CmdProc cmdProc;
14245 } Jim_CoreCommandsTable[] = {
14246 {"set", Jim_SetCoreCommand},
14247 {"unset", Jim_UnsetCoreCommand},
14248 {"puts", Jim_PutsCoreCommand},
14249 {"+", Jim_AddCoreCommand},
14250 {"*", Jim_MulCoreCommand},
14251 {"-", Jim_SubCoreCommand},
14252 {"/", Jim_DivCoreCommand},
14253 {"incr", Jim_IncrCoreCommand},
14254 {"while", Jim_WhileCoreCommand},
14255 {"loop", Jim_LoopCoreCommand},
14256 {"for", Jim_ForCoreCommand},
14257 {"foreach", Jim_ForeachCoreCommand},
14258 {"lmap", Jim_LmapCoreCommand},
14259 {"if", Jim_IfCoreCommand},
14260 {"switch", Jim_SwitchCoreCommand},
14261 {"list", Jim_ListCoreCommand},
14262 {"lindex", Jim_LindexCoreCommand},
14263 {"lset", Jim_LsetCoreCommand},
14264 {"lsearch", Jim_LsearchCoreCommand},
14265 {"llength", Jim_LlengthCoreCommand},
14266 {"lappend", Jim_LappendCoreCommand},
14267 {"linsert", Jim_LinsertCoreCommand},
14268 {"lreplace", Jim_LreplaceCoreCommand},
14269 {"lsort", Jim_LsortCoreCommand},
14270 {"append", Jim_AppendCoreCommand},
14271 {"debug", Jim_DebugCoreCommand},
14272 {"eval", Jim_EvalCoreCommand},
14273 {"uplevel", Jim_UplevelCoreCommand},
14274 {"expr", Jim_ExprCoreCommand},
14275 {"break", Jim_BreakCoreCommand},
14276 {"continue", Jim_ContinueCoreCommand},
14277 {"proc", Jim_ProcCoreCommand},
14278 {"concat", Jim_ConcatCoreCommand},
14279 {"return", Jim_ReturnCoreCommand},
14280 {"upvar", Jim_UpvarCoreCommand},
14281 {"global", Jim_GlobalCoreCommand},
14282 {"string", Jim_StringCoreCommand},
14283 {"time", Jim_TimeCoreCommand},
14284 {"exit", Jim_ExitCoreCommand},
14285 {"catch", Jim_CatchCoreCommand},
14286 #ifdef JIM_REFERENCES
14287 {"ref", Jim_RefCoreCommand},
14288 {"getref", Jim_GetrefCoreCommand},
14289 {"setref", Jim_SetrefCoreCommand},
14290 {"finalize", Jim_FinalizeCoreCommand},
14291 {"collect", Jim_CollectCoreCommand},
14292 #endif
14293 {"rename", Jim_RenameCoreCommand},
14294 {"dict", Jim_DictCoreCommand},
14295 {"subst", Jim_SubstCoreCommand},
14296 {"info", Jim_InfoCoreCommand},
14297 {"exists", Jim_ExistsCoreCommand},
14298 {"split", Jim_SplitCoreCommand},
14299 {"join", Jim_JoinCoreCommand},
14300 {"format", Jim_FormatCoreCommand},
14301 {"scan", Jim_ScanCoreCommand},
14302 {"error", Jim_ErrorCoreCommand},
14303 {"lrange", Jim_LrangeCoreCommand},
14304 {"lrepeat", Jim_LrepeatCoreCommand},
14305 {"env", Jim_EnvCoreCommand},
14306 {"source", Jim_SourceCoreCommand},
14307 {"lreverse", Jim_LreverseCoreCommand},
14308 {"range", Jim_RangeCoreCommand},
14309 {"rand", Jim_RandCoreCommand},
14310 {"tailcall", Jim_TailcallCoreCommand},
14311 {"local", Jim_LocalCoreCommand},
14312 {"upcall", Jim_UpcallCoreCommand},
14313 {NULL, NULL},
14316 void Jim_RegisterCoreCommands(Jim_Interp *interp)
14318 int i = 0;
14320 while (Jim_CoreCommandsTable[i].name != NULL) {
14321 Jim_CreateCommand(interp,
14322 Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
14323 i++;
14327 /* -----------------------------------------------------------------------------
14328 * Interactive prompt
14329 * ---------------------------------------------------------------------------*/
14330 void Jim_MakeErrorMessage(Jim_Interp *interp)
14332 Jim_Obj *argv[2];
14334 argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
14335 argv[1] = interp->result;
14337 Jim_EvalObjVector(interp, 2, argv);
14340 static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
14341 const char *prefix, const char *const *tablePtr, const char *name)
14343 int count;
14344 char **tablePtrSorted;
14345 int i;
14347 for (count = 0; tablePtr[count]; count++) {
14350 if (name == NULL) {
14351 name = "option";
14354 Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
14355 tablePtrSorted = Jim_Alloc(sizeof(char *) * count);
14356 memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
14357 qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
14358 for (i = 0; i < count; i++) {
14359 if (i + 1 == count && count > 1) {
14360 Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
14362 Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
14363 if (i + 1 != count) {
14364 Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
14367 Jim_Free(tablePtrSorted);
14370 int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
14371 const char *const *tablePtr, int *indexPtr, const char *name, int flags)
14373 const char *bad = "bad ";
14374 const char *const *entryPtr = NULL;
14375 int i;
14376 int match = -1;
14377 int arglen;
14378 const char *arg = Jim_GetString(objPtr, &arglen);
14380 *indexPtr = -1;
14382 for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
14383 if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
14384 /* Found an exact match */
14385 *indexPtr = i;
14386 return JIM_OK;
14388 if (flags & JIM_ENUM_ABBREV) {
14389 /* Accept an unambiguous abbreviation.
14390 * Note that '-' doesnt' consitute a valid abbreviation
14392 if (strncmp(arg, *entryPtr, arglen) == 0) {
14393 if (*arg == '-' && arglen == 1) {
14394 break;
14396 if (match >= 0) {
14397 bad = "ambiguous ";
14398 goto ambiguous;
14400 match = i;
14405 /* If we had an unambiguous partial match */
14406 if (match >= 0) {
14407 *indexPtr = match;
14408 return JIM_OK;
14411 ambiguous:
14412 if (flags & JIM_ERRMSG) {
14413 JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
14415 return JIM_ERR;
14418 int Jim_FindByName(const char *name, const char * const array[], size_t len)
14420 int i;
14422 for (i = 0; i < (int)len; i++) {
14423 if (array[i] && strcmp(array[i], name) == 0) {
14424 return i;
14427 return -1;
14430 int Jim_IsDict(Jim_Obj *objPtr)
14432 return objPtr->typePtr == &dictObjType;
14435 int Jim_IsList(Jim_Obj *objPtr)
14437 return objPtr->typePtr == &listObjType;
14441 * Very simple printf-like formatting, designed for error messages.
14443 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14444 * The resulting string is created and set as the result.
14446 * Each '%s' should correspond to a regular string parameter.
14447 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14448 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14450 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14452 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14454 void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
14456 /* Initial space needed */
14457 int len = strlen(format);
14458 int extra = 0;
14459 int n = 0;
14460 const char *params[5];
14461 char *buf;
14462 va_list args;
14463 int i;
14465 va_start(args, format);
14467 for (i = 0; i < len && n < 5; i++) {
14468 int l;
14470 if (strncmp(format + i, "%s", 2) == 0) {
14471 params[n] = va_arg(args, char *);
14473 l = strlen(params[n]);
14475 else if (strncmp(format + i, "%#s", 3) == 0) {
14476 Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
14478 params[n] = Jim_GetString(objPtr, &l);
14480 else {
14481 if (format[i] == '%') {
14482 i++;
14484 continue;
14486 n++;
14487 extra += l;
14490 len += extra;
14491 buf = Jim_Alloc(len + 1);
14492 len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
14494 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
14497 /* stubs */
14498 #ifndef jim_ext_package
14499 int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
14501 return JIM_OK;
14503 #endif
14504 #ifndef jim_ext_aio
14505 FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
14507 Jim_SetResultString(interp, "aio not enabled", -1);
14508 return NULL;
14510 #endif
14514 * Local Variables: ***
14515 * c-basic-offset: 4 ***
14516 * tab-width: 4 ***
14517 * End: ***