Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / usbmodeswitch / jim / jim.c
blob8543de4675c4a9d8a243fac55025f30c2bbc5796
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 <unistd.h>
59 #include <sys/time.h>
61 #include "jim.h"
62 #include "jimautoconf.h"
63 #include "utf8.h"
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 static const Jim_HashTableType JimVariablesHashTableType;
145 /* Fast access to the int (wide) value of an object which is known to be of int type */
146 #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
148 #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
150 static int utf8_tounicode_case(const char *s, int *uc, int upper)
152 int l = utf8_tounicode(s, uc);
153 if (upper) {
154 *uc = utf8_upper(*uc);
156 return l;
159 /* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
160 #define JIM_CHARSET_SCAN 2
161 #define JIM_CHARSET_GLOB 0
164 * pattern points to a string like "[^a-z\ub5]"
166 * The pattern may contain trailing chars, which are ignored.
168 * The pattern is matched against unicode char 'c'.
170 * If (flags & JIM_NOCASE), case is ignored when matching.
171 * If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
172 * of the charset, per scan, rather than glob/string match.
174 * If the unicode char 'c' matches that set, returns a pointer to the ']' character,
175 * or the null character if the ']' is missing.
177 * Returns NULL on no match.
179 static const char *JimCharsetMatch(const char *pattern, int c, int flags)
181 int not = 0;
182 int pchar;
183 int match = 0;
184 int nocase = 0;
186 if (flags & JIM_NOCASE) {
187 nocase++;
188 c = utf8_upper(c);
191 if (flags & JIM_CHARSET_SCAN) {
192 if (*pattern == '^') {
193 not++;
194 pattern++;
197 /* Special case. If the first char is ']', it is part of the set */
198 if (*pattern == ']') {
199 goto first;
203 while (*pattern && *pattern != ']') {
204 /* Exact match */
205 if (pattern[0] == '\\') {
206 first:
207 pattern += utf8_tounicode_case(pattern, &pchar, nocase);
209 else {
210 /* Is this a range? a-z */
211 int start;
212 int end;
214 pattern += utf8_tounicode_case(pattern, &start, nocase);
215 if (pattern[0] == '-' && pattern[1]) {
216 /* skip '-' */
217 pattern += utf8_tounicode(pattern, &pchar);
218 pattern += utf8_tounicode_case(pattern, &end, nocase);
220 /* Handle reversed range too */
221 if ((c >= start && c <= end) || (c >= end && c <= start)) {
222 match = 1;
224 continue;
226 pchar = start;
229 if (pchar == c) {
230 match = 1;
233 if (not) {
234 match = !match;
237 return match ? pattern : NULL;
240 /* Glob-style pattern matching. */
242 /* Note: string *must* be valid UTF-8 sequences
243 * slen is a char length, not byte counts.
245 static int GlobMatch(const char *pattern, const char *string, int nocase)
247 int c;
248 int pchar;
249 while (*pattern) {
250 switch (pattern[0]) {
251 case '*':
252 while (pattern[1] == '*') {
253 pattern++;
255 pattern++;
256 if (!pattern[0]) {
257 return 1; /* match */
259 while (*string) {
260 /* Recursive call - Does the remaining pattern match anywhere? */
261 if (GlobMatch(pattern, string, nocase))
262 return 1; /* match */
263 string += utf8_tounicode(string, &c);
265 return 0; /* no match */
267 case '?':
268 string += utf8_tounicode(string, &c);
269 break;
271 case '[': {
272 string += utf8_tounicode(string, &c);
273 pattern = JimCharsetMatch(pattern + 1, c, nocase ? JIM_NOCASE : 0);
274 if (!pattern) {
275 return 0;
277 if (!*pattern) {
278 /* Ran out of pattern (no ']') */
279 continue;
281 break;
283 case '\\':
284 if (pattern[1]) {
285 pattern++;
287 /* fall through */
288 default:
289 string += utf8_tounicode_case(string, &c, nocase);
290 utf8_tounicode_case(pattern, &pchar, nocase);
291 if (pchar != c) {
292 return 0;
294 break;
296 pattern += utf8_tounicode_case(pattern, &pchar, nocase);
297 if (!*string) {
298 while (*pattern == '*') {
299 pattern++;
301 break;
304 if (!*pattern && !*string) {
305 return 1;
307 return 0;
310 static int JimStringMatch(Jim_Interp *interp, Jim_Obj *patternObj, const char *string, int nocase)
312 return GlobMatch(Jim_String(patternObj), string, nocase);
316 * string comparison works on binary data.
318 * Note that the lengths are byte lengths, not char lengths.
320 static int JimStringCompare(const char *s1, int l1, const char *s2, int l2)
322 if (l1 < l2) {
323 return memcmp(s1, s2, l1) <= 0 ? -1 : 1;
325 else if (l2 < l1) {
326 return memcmp(s1, s2, l2) >= 0 ? 1 : -1;
328 else {
329 return JimSign(memcmp(s1, s2, l1));
334 * No-case version.
336 * If maxchars is -1, compares to end of string.
337 * Otherwise compares at most 'maxchars' characters.
339 static int JimStringCompareNoCase(const char *s1, const char *s2, int maxchars)
341 while (*s1 && *s2 && maxchars) {
342 int c1, c2;
343 s1 += utf8_tounicode_case(s1, &c1, 1);
344 s2 += utf8_tounicode_case(s2, &c2, 1);
345 if (c1 != c2) {
346 return JimSign(c1 - c2);
348 maxchars--;
350 if (!maxchars) {
351 return 0;
353 /* One string or both terminated */
354 if (*s1) {
355 return 1;
357 if (*s2) {
358 return -1;
360 return 0;
363 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
364 * The index of the first occurrence of s1 in s2 is returned.
365 * If s1 is not found inside s2, -1 is returned. */
366 static int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int idx)
368 int i;
369 int l1bytelen;
371 if (!l1 || !l2 || l1 > l2) {
372 return -1;
374 if (idx < 0)
375 idx = 0;
376 s2 += utf8_index(s2, idx);
378 l1bytelen = utf8_index(s1, l1);
380 for (i = idx; i <= l2 - l1; i++) {
381 int c;
382 if (memcmp(s2, s1, l1bytelen) == 0) {
383 return i;
385 s2 += utf8_tounicode(s2, &c);
387 return -1;
391 * Note: Lengths and return value are in bytes, not chars.
393 static int JimStringLast(const char *s1, int l1, const char *s2, int l2)
395 const char *p;
397 if (!l1 || !l2 || l1 > l2)
398 return -1;
400 /* Now search for the needle */
401 for (p = s2 + l2 - 1; p != s2 - 1; p--) {
402 if (*p == *s1 && memcmp(s1, p, l1) == 0) {
403 return p - s2;
406 return -1;
409 #ifdef JIM_UTF8
411 * Note: Lengths and return value are in chars.
413 static int JimStringLastUtf8(const char *s1, int l1, const char *s2, int l2)
415 int n = JimStringLast(s1, utf8_index(s1, l1), s2, utf8_index(s2, l2));
416 if (n > 0) {
417 n = utf8_strlen(s2, n);
419 return n;
421 #endif
423 int Jim_WideToString(char *buf, jim_wide wideValue)
425 const char *fmt = "%" JIM_WIDE_MODIFIER;
427 return sprintf(buf, fmt, wideValue);
431 * After an strtol()/strtod()-like conversion,
432 * check whether something was converted and that
433 * the only thing left is white space.
435 * Returns JIM_OK or JIM_ERR.
437 static int JimCheckConversion(const char *str, const char *endptr)
439 if (str[0] == '\0' || str == endptr) {
440 return JIM_ERR;
443 if (endptr[0] != '\0') {
444 while (*endptr) {
445 if (!isspace(UCHAR(*endptr))) {
446 return JIM_ERR;
448 endptr++;
451 return JIM_OK;
454 int Jim_StringToWide(const char *str, jim_wide * widePtr, int base)
456 char *endptr;
458 *widePtr = strtoull(str, &endptr, base);
460 return JimCheckConversion(str, endptr);
463 int Jim_DoubleToString(char *buf, double doubleValue)
465 int len;
466 char *buf0 = buf;
468 len = sprintf(buf, "%.12g", doubleValue);
470 /* Add a final ".0" if it's a number. But not
471 * for NaN or InF */
472 while (*buf) {
473 if (*buf == '.' || isalpha(UCHAR(*buf))) {
474 /* inf -> Inf, nan -> Nan */
475 if (*buf == 'i' || *buf == 'n') {
476 *buf = toupper(UCHAR(*buf));
478 if (*buf == 'I') {
479 /* Infinity -> Inf */
480 buf[3] = '\0';
481 len = buf - buf0 + 3;
483 return len;
485 buf++;
488 *buf++ = '.';
489 *buf++ = '0';
490 *buf = '\0';
492 return len + 2;
495 int Jim_StringToDouble(const char *str, double *doublePtr)
497 char *endptr;
499 /* Callers can check for underflow via ERANGE */
500 errno = 0;
502 *doublePtr = strtod(str, &endptr);
504 return JimCheckConversion(str, endptr);
507 static jim_wide JimPowWide(jim_wide b, jim_wide e)
509 jim_wide i, res = 1;
511 if ((b == 0 && e != 0) || (e < 0))
512 return 0;
513 for (i = 0; i < e; i++) {
514 res *= b;
516 return res;
519 /* -----------------------------------------------------------------------------
520 * Special functions
521 * ---------------------------------------------------------------------------*/
522 #ifdef JIM_DEBUG_PANIC
523 void JimPanicDump(int condition, const char *fmt, ...)
525 va_list ap;
527 if (!condition) {
528 return;
531 va_start(ap, fmt);
533 fprintf(stderr, JIM_NL "JIM INTERPRETER PANIC: ");
534 vfprintf(stderr, fmt, ap);
535 fprintf(stderr, JIM_NL JIM_NL);
536 va_end(ap);
538 #ifdef HAVE_BACKTRACE
540 void *array[40];
541 int size, i;
542 char **strings;
544 size = backtrace(array, 40);
545 strings = backtrace_symbols(array, size);
546 for (i = 0; i < size; i++)
547 fprintf(stderr, "[backtrace] %s" JIM_NL, strings[i]);
548 fprintf(stderr, "[backtrace] Include the above lines and the output" JIM_NL);
549 fprintf(stderr, "[backtrace] of 'nm <executable>' in the bug report." JIM_NL);
551 #endif
553 abort();
555 #endif
557 /* -----------------------------------------------------------------------------
558 * Memory allocation
559 * ---------------------------------------------------------------------------*/
561 void *Jim_Alloc(int size)
563 return malloc(size);
566 void Jim_Free(void *ptr)
568 free(ptr);
571 void *Jim_Realloc(void *ptr, int size)
573 return realloc(ptr, size);
576 char *Jim_StrDup(const char *s)
578 return strdup(s);
581 char *Jim_StrDupLen(const char *s, int l)
583 char *copy = Jim_Alloc(l + 1);
585 memcpy(copy, s, l + 1);
586 copy[l] = 0; /* Just to be sure, original could be substring */
587 return copy;
590 /* -----------------------------------------------------------------------------
591 * Time related functions
592 * ---------------------------------------------------------------------------*/
594 /* Returns microseconds of CPU used since start. */
595 static jim_wide JimClock(void)
597 struct timeval tv;
599 gettimeofday(&tv, NULL);
600 return (jim_wide) tv.tv_sec * 1000000 + tv.tv_usec;
603 /* -----------------------------------------------------------------------------
604 * Hash Tables
605 * ---------------------------------------------------------------------------*/
607 /* -------------------------- private prototypes ---------------------------- */
608 static int JimExpandHashTableIfNeeded(Jim_HashTable *ht);
609 static unsigned int JimHashTableNextPower(unsigned int size);
610 static int JimInsertHashEntry(Jim_HashTable *ht, const void *key);
612 /* -------------------------- hash functions -------------------------------- */
614 /* Thomas Wang's 32 bit Mix Function */
615 unsigned int Jim_IntHashFunction(unsigned int key)
617 key += ~(key << 15);
618 key ^= (key >> 10);
619 key += (key << 3);
620 key ^= (key >> 6);
621 key += ~(key << 11);
622 key ^= (key >> 16);
623 return key;
626 /* Generic hash function (we are using to multiply by 9 and add the byte
627 * as Tcl) */
628 unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
630 unsigned int h = 0;
632 while (len--)
633 h += (h << 3) + *buf++;
634 return h;
637 /* ----------------------------- API implementation ------------------------- */
639 /* reset a hashtable already initialized with ht_init().
640 * NOTE: This function should only called by ht_destroy(). */
641 static void JimResetHashTable(Jim_HashTable *ht)
643 ht->table = NULL;
644 ht->size = 0;
645 ht->sizemask = 0;
646 ht->used = 0;
647 ht->collisions = 0;
650 /* Initialize the hash table */
651 int Jim_InitHashTable(Jim_HashTable *ht, const Jim_HashTableType *type, void *privDataPtr)
653 JimResetHashTable(ht);
654 ht->type = type;
655 ht->privdata = privDataPtr;
656 return JIM_OK;
659 /* Resize the table to the minimal size that contains all the elements,
660 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
661 int Jim_ResizeHashTable(Jim_HashTable *ht)
663 int minimal = ht->used;
665 if (minimal < JIM_HT_INITIAL_SIZE)
666 minimal = JIM_HT_INITIAL_SIZE;
667 return Jim_ExpandHashTable(ht, minimal);
670 /* Expand or create the hashtable */
671 int Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
673 Jim_HashTable n; /* the new hashtable */
674 unsigned int realsize = JimHashTableNextPower(size), i;
676 /* the size is invalid if it is smaller than the number of
677 * elements already inside the hashtable */
678 if (ht->used >= size)
679 return JIM_ERR;
681 Jim_InitHashTable(&n, ht->type, ht->privdata);
682 n.size = realsize;
683 n.sizemask = realsize - 1;
684 n.table = Jim_Alloc(realsize * sizeof(Jim_HashEntry *));
686 /* Initialize all the pointers to NULL */
687 memset(n.table, 0, realsize * sizeof(Jim_HashEntry *));
689 /* Copy all the elements from the old to the new table:
690 * note that if the old hash table is empty ht->used is zero,
691 * so Jim_ExpandHashTable just creates an empty hash table. */
692 n.used = ht->used;
693 for (i = 0; ht->used > 0; i++) {
694 Jim_HashEntry *he, *nextHe;
696 if (ht->table[i] == NULL)
697 continue;
699 /* For each hash entry on this slot... */
700 he = ht->table[i];
701 while (he) {
702 unsigned int h;
704 nextHe = he->next;
705 /* Get the new element index */
706 h = Jim_HashKey(ht, he->key) & n.sizemask;
707 he->next = n.table[h];
708 n.table[h] = he;
709 ht->used--;
710 /* Pass to the next element */
711 he = nextHe;
714 assert(ht->used == 0);
715 Jim_Free(ht->table);
717 /* Remap the new hashtable in the old */
718 *ht = n;
719 return JIM_OK;
722 /* Add an element to the target hash table */
723 int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
725 int idx;
726 Jim_HashEntry *entry;
728 /* Get the index of the new element, or -1 if
729 * the element already exists. */
730 if ((idx = JimInsertHashEntry(ht, key)) == -1)
731 return JIM_ERR;
733 /* Allocates the memory and stores key */
734 entry = Jim_Alloc(sizeof(*entry));
735 entry->next = ht->table[idx];
736 ht->table[idx] = entry;
738 /* Set the hash entry fields. */
739 Jim_SetHashKey(ht, entry, key);
740 Jim_SetHashVal(ht, entry, val);
741 ht->used++;
742 return JIM_OK;
745 /* Add an element, discarding the old if the key already exists */
746 int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
748 Jim_HashEntry *entry;
750 /* Try to add the element. If the key
751 * does not exists Jim_AddHashEntry will suceed. */
752 if (Jim_AddHashEntry(ht, key, val) == JIM_OK)
753 return JIM_OK;
754 /* It already exists, get the entry */
755 entry = Jim_FindHashEntry(ht, key);
756 /* Free the old value and set the new one */
757 Jim_FreeEntryVal(ht, entry);
758 Jim_SetHashVal(ht, entry, val);
759 return JIM_OK;
762 /* Search and remove an element */
763 int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
765 unsigned int h;
766 Jim_HashEntry *he, *prevHe;
768 if (ht->used == 0)
769 return JIM_ERR;
770 h = Jim_HashKey(ht, key) & ht->sizemask;
771 he = ht->table[h];
773 prevHe = NULL;
774 while (he) {
775 if (Jim_CompareHashKeys(ht, key, he->key)) {
776 /* Unlink the element from the list */
777 if (prevHe)
778 prevHe->next = he->next;
779 else
780 ht->table[h] = he->next;
781 Jim_FreeEntryKey(ht, he);
782 Jim_FreeEntryVal(ht, he);
783 Jim_Free(he);
784 ht->used--;
785 return JIM_OK;
787 prevHe = he;
788 he = he->next;
790 return JIM_ERR; /* not found */
793 /* Destroy an entire hash table */
794 int Jim_FreeHashTable(Jim_HashTable *ht)
796 unsigned int i;
798 /* Free all the elements */
799 for (i = 0; ht->used > 0; i++) {
800 Jim_HashEntry *he, *nextHe;
802 if ((he = ht->table[i]) == NULL)
803 continue;
804 while (he) {
805 nextHe = he->next;
806 Jim_FreeEntryKey(ht, he);
807 Jim_FreeEntryVal(ht, he);
808 Jim_Free(he);
809 ht->used--;
810 he = nextHe;
813 /* Free the table and the allocated cache structure */
814 Jim_Free(ht->table);
815 /* Re-initialize the table */
816 JimResetHashTable(ht);
817 return JIM_OK; /* never fails */
820 Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
822 Jim_HashEntry *he;
823 unsigned int h;
825 if (ht->used == 0)
826 return NULL;
827 h = Jim_HashKey(ht, key) & ht->sizemask;
828 he = ht->table[h];
829 while (he) {
830 if (Jim_CompareHashKeys(ht, key, he->key))
831 return he;
832 he = he->next;
834 return NULL;
837 Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
839 Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
841 iter->ht = ht;
842 iter->index = -1;
843 iter->entry = NULL;
844 iter->nextEntry = NULL;
845 return iter;
848 Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
850 while (1) {
851 if (iter->entry == NULL) {
852 iter->index++;
853 if (iter->index >= (signed)iter->ht->size)
854 break;
855 iter->entry = iter->ht->table[iter->index];
857 else {
858 iter->entry = iter->nextEntry;
860 if (iter->entry) {
861 /* We need to save the 'next' here, the iterator user
862 * may delete the entry we are returning. */
863 iter->nextEntry = iter->entry->next;
864 return iter->entry;
867 return NULL;
870 /* ------------------------- private functions ------------------------------ */
872 /* Expand the hash table if needed */
873 static int JimExpandHashTableIfNeeded(Jim_HashTable *ht)
875 /* If the hash table is empty expand it to the intial size,
876 * if the table is "full" dobule its size. */
877 if (ht->size == 0)
878 return Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
879 if (ht->size == ht->used)
880 return Jim_ExpandHashTable(ht, ht->size * 2);
881 return JIM_OK;
884 /* Our hash table capability is a power of two */
885 static unsigned int JimHashTableNextPower(unsigned int size)
887 unsigned int i = JIM_HT_INITIAL_SIZE;
889 if (size >= 2147483648U)
890 return 2147483648U;
891 while (1) {
892 if (i >= size)
893 return i;
894 i *= 2;
898 /* Returns the index of a free slot that can be populated with
899 * an hash entry for the given 'key'.
900 * If the key already exists, -1 is returned. */
901 static int JimInsertHashEntry(Jim_HashTable *ht, const void *key)
903 unsigned int h;
904 Jim_HashEntry *he;
906 /* Expand the hashtable if needed */
907 if (JimExpandHashTableIfNeeded(ht) == JIM_ERR)
908 return -1;
909 /* Compute the key hash value */
910 h = Jim_HashKey(ht, key) & ht->sizemask;
911 /* Search if this slot does not already contain the given key */
912 he = ht->table[h];
913 while (he) {
914 if (Jim_CompareHashKeys(ht, key, he->key))
915 return -1;
916 he = he->next;
918 return h;
921 /* ----------------------- StringCopy Hash Table Type ------------------------*/
923 static unsigned int JimStringCopyHTHashFunction(const void *key)
925 return Jim_GenHashFunction(key, strlen(key));
928 static const void *JimStringCopyHTKeyDup(void *privdata, const void *key)
930 int len = strlen(key);
931 char *copy = Jim_Alloc(len + 1);
933 JIM_NOTUSED(privdata);
935 memcpy(copy, key, len);
936 copy[len] = '\0';
937 return copy;
940 static void *JimStringKeyValCopyHTValDup(void *privdata, const void *val)
942 int len = strlen(val);
943 char *copy = Jim_Alloc(len + 1);
945 JIM_NOTUSED(privdata);
947 memcpy(copy, val, len);
948 copy[len] = '\0';
949 return copy;
952 static int JimStringCopyHTKeyCompare(void *privdata, const void *key1, const void *key2)
954 JIM_NOTUSED(privdata);
956 return strcmp(key1, key2) == 0;
959 static void JimStringCopyHTKeyDestructor(void *privdata, const void *key)
961 JIM_NOTUSED(privdata);
963 Jim_Free((void *)key); /* ATTENTION: const cast */
966 static void JimStringKeyValCopyHTValDestructor(void *privdata, void *val)
968 JIM_NOTUSED(privdata);
970 Jim_Free((void *)val); /* ATTENTION: const cast */
973 #if 0
974 static Jim_HashTableType JimStringCopyHashTableType = {
975 JimStringCopyHTHashFunction, /* hash function */
976 JimStringCopyHTKeyDup, /* key dup */
977 NULL, /* val dup */
978 JimStringCopyHTKeyCompare, /* key compare */
979 JimStringCopyHTKeyDestructor, /* key destructor */
980 NULL /* val destructor */
982 #endif
984 /* This is like StringCopy but does not auto-duplicate the key.
985 * It's used for intepreter's shared strings. */
986 static const Jim_HashTableType JimSharedStringsHashTableType = {
987 JimStringCopyHTHashFunction, /* hash function */
988 NULL, /* key dup */
989 NULL, /* val dup */
990 JimStringCopyHTKeyCompare, /* key compare */
991 JimStringCopyHTKeyDestructor, /* key destructor */
992 NULL /* val destructor */
995 /* This is like StringCopy but also automatically handle dynamic
996 * allocated C strings as values. */
997 static const Jim_HashTableType JimStringKeyValCopyHashTableType = {
998 JimStringCopyHTHashFunction, /* hash function */
999 JimStringCopyHTKeyDup, /* key dup */
1000 JimStringKeyValCopyHTValDup, /* val dup */
1001 JimStringCopyHTKeyCompare, /* key compare */
1002 JimStringCopyHTKeyDestructor, /* key destructor */
1003 JimStringKeyValCopyHTValDestructor, /* val destructor */
1006 typedef struct AssocDataValue
1008 Jim_InterpDeleteProc *delProc;
1009 void *data;
1010 } AssocDataValue;
1012 static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
1014 AssocDataValue *assocPtr = (AssocDataValue *) data;
1016 if (assocPtr->delProc != NULL)
1017 assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
1018 Jim_Free(data);
1021 static const Jim_HashTableType JimAssocDataHashTableType = {
1022 JimStringCopyHTHashFunction, /* hash function */
1023 JimStringCopyHTKeyDup, /* key dup */
1024 NULL, /* val dup */
1025 JimStringCopyHTKeyCompare, /* key compare */
1026 JimStringCopyHTKeyDestructor, /* key destructor */
1027 JimAssocDataHashTableValueDestructor /* val destructor */
1030 /* -----------------------------------------------------------------------------
1031 * Stack - This is a simple generic stack implementation. It is used for
1032 * example in the 'expr' expression compiler.
1033 * ---------------------------------------------------------------------------*/
1034 void Jim_InitStack(Jim_Stack *stack)
1036 stack->len = 0;
1037 stack->maxlen = 0;
1038 stack->vector = NULL;
1041 void Jim_FreeStack(Jim_Stack *stack)
1043 Jim_Free(stack->vector);
1046 int Jim_StackLen(Jim_Stack *stack)
1048 return stack->len;
1051 void Jim_StackPush(Jim_Stack *stack, void *element)
1053 int neededLen = stack->len + 1;
1055 if (neededLen > stack->maxlen) {
1056 stack->maxlen = neededLen < 20 ? 20 : neededLen * 2;
1057 stack->vector = Jim_Realloc(stack->vector, sizeof(void *) * stack->maxlen);
1059 stack->vector[stack->len] = element;
1060 stack->len++;
1063 void *Jim_StackPop(Jim_Stack *stack)
1065 if (stack->len == 0)
1066 return NULL;
1067 stack->len--;
1068 return stack->vector[stack->len];
1071 void *Jim_StackPeek(Jim_Stack *stack)
1073 if (stack->len == 0)
1074 return NULL;
1075 return stack->vector[stack->len - 1];
1078 void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc) (void *ptr))
1080 int i;
1082 for (i = 0; i < stack->len; i++)
1083 freeFunc(stack->vector[i]);
1086 /* -----------------------------------------------------------------------------
1087 * Parser
1088 * ---------------------------------------------------------------------------*/
1090 /* Token types */
1091 #define JIM_TT_NONE 0 /* No token returned */
1092 #define JIM_TT_STR 1 /* simple string */
1093 #define JIM_TT_ESC 2 /* string that needs escape chars conversion */
1094 #define JIM_TT_VAR 3 /* var substitution */
1095 #define JIM_TT_DICTSUGAR 4 /* Syntax sugar for [dict get], $foo(bar) */
1096 #define JIM_TT_CMD 5 /* command substitution */
1097 /* Note: Keep these three together for TOKEN_IS_SEP() */
1098 #define JIM_TT_SEP 6 /* word separator. arg is # of tokens. -ve if {*} */
1099 #define JIM_TT_EOL 7 /* line separator */
1100 #define JIM_TT_EOF 8 /* end of script */
1102 #define JIM_TT_LINE 9 /* special 'start-of-line' token. arg is # of arguments to the command. -ve if {*} */
1103 #define JIM_TT_WORD 10 /* special 'start-of-word' token. arg is # of tokens to combine. -ve if {*} */
1105 /* Additional token types needed for expressions */
1106 #define JIM_TT_SUBEXPR_START 11
1107 #define JIM_TT_SUBEXPR_END 12
1108 #define JIM_TT_SUBEXPR_COMMA 13
1109 #define JIM_TT_EXPR_INT 14
1110 #define JIM_TT_EXPR_DOUBLE 15
1112 #define JIM_TT_EXPRSUGAR 16 /* $(expression) */
1114 /* Operator token types start here */
1115 #define JIM_TT_EXPR_OP 20
1117 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1119 /* Parser states */
1120 #define JIM_PS_DEF 0 /* Default state */
1121 #define JIM_PS_QUOTE 1 /* Inside "" */
1122 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1124 /* Parser context structure. The same context is used both to parse
1125 * Tcl scripts and lists. */
1126 struct JimParserCtx
1128 const char *p; /* Pointer to the point of the program we are parsing */
1129 int len; /* Remaining length */
1130 int linenr; /* Current line number */
1131 const char *tstart;
1132 const char *tend; /* Returned token is at tstart-tend in 'prg'. */
1133 int tline; /* Line number of the returned token */
1134 int tt; /* Token type */
1135 int eof; /* Non zero if EOF condition is true. */
1136 int state; /* Parser state */
1137 int comment; /* Non zero if the next chars may be a comment. */
1138 char missing; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1139 int missingline; /* Line number starting the missing token */
1143 * Results of missing quotes, braces, etc. from parsing.
1145 struct JimParseResult {
1146 char missing; /* From JimParserCtx.missing */
1147 int line; /* From JimParserCtx.missingline */
1150 static int JimParseScript(struct JimParserCtx *pc);
1151 static int JimParseSep(struct JimParserCtx *pc);
1152 static int JimParseEol(struct JimParserCtx *pc);
1153 static int JimParseCmd(struct JimParserCtx *pc);
1154 static int JimParseQuote(struct JimParserCtx *pc);
1155 static int JimParseVar(struct JimParserCtx *pc);
1156 static int JimParseBrace(struct JimParserCtx *pc);
1157 static int JimParseStr(struct JimParserCtx *pc);
1158 static int JimParseComment(struct JimParserCtx *pc);
1159 static void JimParseSubCmd(struct JimParserCtx *pc);
1160 static int JimParseSubQuote(struct JimParserCtx *pc);
1161 static void JimParseSubCmd(struct JimParserCtx *pc);
1162 static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc);
1164 /* Initialize a parser context.
1165 * 'prg' is a pointer to the program text, linenr is the line
1166 * number of the first line contained in the program. */
1167 static void JimParserInit(struct JimParserCtx *pc, const char *prg, int len, int linenr)
1169 pc->p = prg;
1170 pc->len = len;
1171 pc->tstart = NULL;
1172 pc->tend = NULL;
1173 pc->tline = 0;
1174 pc->tt = JIM_TT_NONE;
1175 pc->eof = 0;
1176 pc->state = JIM_PS_DEF;
1177 pc->linenr = linenr;
1178 pc->comment = 1;
1179 pc->missing = ' ';
1180 pc->missingline = linenr;
1183 static int JimParseScript(struct JimParserCtx *pc)
1185 while (1) { /* the while is used to reiterate with continue if needed */
1186 if (!pc->len) {
1187 pc->tstart = pc->p;
1188 pc->tend = pc->p - 1;
1189 pc->tline = pc->linenr;
1190 pc->tt = JIM_TT_EOL;
1191 pc->eof = 1;
1192 return JIM_OK;
1194 switch (*(pc->p)) {
1195 case '\\':
1196 if (*(pc->p + 1) == '\n' && pc->state == JIM_PS_DEF) {
1197 return JimParseSep(pc);
1199 else {
1200 pc->comment = 0;
1201 return JimParseStr(pc);
1203 break;
1204 case ' ':
1205 case '\t':
1206 case '\r':
1207 if (pc->state == JIM_PS_DEF)
1208 return JimParseSep(pc);
1209 else {
1210 pc->comment = 0;
1211 return JimParseStr(pc);
1213 break;
1214 case '\n':
1215 case ';':
1216 pc->comment = 1;
1217 if (pc->state == JIM_PS_DEF)
1218 return JimParseEol(pc);
1219 else
1220 return JimParseStr(pc);
1221 break;
1222 case '[':
1223 pc->comment = 0;
1224 return JimParseCmd(pc);
1225 break;
1226 case '$':
1227 pc->comment = 0;
1228 if (JimParseVar(pc) == JIM_ERR) {
1229 pc->tstart = pc->tend = pc->p++;
1230 pc->len--;
1231 pc->tline = pc->linenr;
1232 pc->tt = JIM_TT_STR;
1233 return JIM_OK;
1235 else
1236 return JIM_OK;
1237 break;
1238 case '#':
1239 if (pc->comment) {
1240 JimParseComment(pc);
1241 continue;
1243 else {
1244 return JimParseStr(pc);
1246 default:
1247 pc->comment = 0;
1248 return JimParseStr(pc);
1249 break;
1251 return JIM_OK;
1255 static int JimParseSep(struct JimParserCtx *pc)
1257 pc->tstart = pc->p;
1258 pc->tline = pc->linenr;
1259 while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' ||
1260 (*pc->p == '\\' && *(pc->p + 1) == '\n')) {
1261 if (*pc->p == '\\') {
1262 pc->p++;
1263 pc->len--;
1264 pc->linenr++;
1266 pc->p++;
1267 pc->len--;
1269 pc->tend = pc->p - 1;
1270 pc->tt = JIM_TT_SEP;
1271 return JIM_OK;
1274 static int JimParseEol(struct JimParserCtx *pc)
1276 pc->tstart = pc->p;
1277 pc->tline = pc->linenr;
1278 while (*pc->p == ' ' || *pc->p == '\n' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == ';') {
1279 if (*pc->p == '\n')
1280 pc->linenr++;
1281 pc->p++;
1282 pc->len--;
1284 pc->tend = pc->p - 1;
1285 pc->tt = JIM_TT_EOL;
1286 return JIM_OK;
1290 ** Here are the rules for parsing:
1291 ** {braced expression}
1292 ** - Count open and closing braces
1293 ** - Backslash escapes meaning of braces
1295 ** "quoted expression"
1296 ** - First double quote at start of word terminates the expression
1297 ** - Backslash escapes quote and bracket
1298 ** - [commands brackets] are counted/nested
1299 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1301 ** [command expression]
1302 ** - Count open and closing brackets
1303 ** - Backslash escapes quote, bracket and brace
1304 ** - [commands brackets] are counted/nested
1305 ** - "quoted expressions" are parsed according to quoting rules
1306 ** - {braced expressions} are parsed according to brace rules
1308 ** For everything, backslash escapes the next char, newline increments current line
1312 * Parses a braced expression starting at pc->p.
1314 * Positions the parser at the end of the braced expression,
1315 * sets pc->tend and possibly pc->missing.
1317 static void JimParseSubBrace(struct JimParserCtx *pc)
1319 int level = 1;
1321 /* Skip the brace */
1322 pc->p++;
1323 pc->len--;
1324 while (pc->len) {
1325 switch (*pc->p) {
1326 case '\\':
1327 if (pc->len > 1) {
1328 if (*++pc->p == '\n') {
1329 pc->linenr++;
1331 pc->len--;
1333 break;
1335 case '{':
1336 level++;
1337 break;
1339 case '}':
1340 if (--level == 0) {
1341 pc->tend = pc->p - 1;
1342 pc->p++;
1343 pc->len--;
1344 return;
1346 break;
1348 case '\n':
1349 pc->linenr++;
1350 break;
1352 pc->p++;
1353 pc->len--;
1355 pc->missing = '{';
1356 pc->missingline = pc->tline;
1357 pc->tend = pc->p - 1;
1361 * Parses a quoted expression starting at pc->p.
1363 * Positions the parser at the end of the quoted expression,
1364 * sets pc->tend and possibly pc->missing.
1366 * Returns the type of the token of the string,
1367 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1368 * or JIM_TT_STR.
1370 static int JimParseSubQuote(struct JimParserCtx *pc)
1372 int tt = JIM_TT_STR;
1373 int line = pc->tline;
1375 /* Skip the quote */
1376 pc->p++;
1377 pc->len--;
1378 while (pc->len) {
1379 switch (*pc->p) {
1380 case '\\':
1381 if (pc->len > 1) {
1382 if (*++pc->p == '\n') {
1383 pc->linenr++;
1385 pc->len--;
1386 tt = JIM_TT_ESC;
1388 break;
1390 case '"':
1391 pc->tend = pc->p - 1;
1392 pc->p++;
1393 pc->len--;
1394 return tt;
1396 case '[':
1397 JimParseSubCmd(pc);
1398 tt = JIM_TT_ESC;
1399 continue;
1401 case '\n':
1402 pc->linenr++;
1403 break;
1405 case '$':
1406 tt = JIM_TT_ESC;
1407 break;
1409 pc->p++;
1410 pc->len--;
1412 pc->missing = '"';
1413 pc->missingline = line;
1414 pc->tend = pc->p - 1;
1415 return tt;
1419 * Parses a [command] expression starting at pc->p.
1421 * Positions the parser at the end of the command expression,
1422 * sets pc->tend and possibly pc->missing.
1424 static void JimParseSubCmd(struct JimParserCtx *pc)
1426 int level = 1;
1427 int startofword = 1;
1428 int line = pc->tline;
1430 /* Skip the bracket */
1431 pc->p++;
1432 pc->len--;
1433 while (pc->len) {
1434 switch (*pc->p) {
1435 case '\\':
1436 if (pc->len > 1) {
1437 if (*++pc->p == '\n') {
1438 pc->linenr++;
1440 pc->len--;
1442 break;
1444 case '[':
1445 level++;
1446 break;
1448 case ']':
1449 if (--level == 0) {
1450 pc->tend = pc->p - 1;
1451 pc->p++;
1452 pc->len--;
1453 return;
1455 break;
1457 case '"':
1458 if (startofword) {
1459 JimParseSubQuote(pc);
1460 continue;
1462 break;
1464 case '{':
1465 JimParseSubBrace(pc);
1466 startofword = 0;
1467 continue;
1469 case '\n':
1470 pc->linenr++;
1471 break;
1473 startofword = isspace(UCHAR(*pc->p));
1474 pc->p++;
1475 pc->len--;
1477 pc->missing = '[';
1478 pc->missingline = line;
1479 pc->tend = pc->p - 1;
1482 static int JimParseBrace(struct JimParserCtx *pc)
1484 pc->tstart = pc->p + 1;
1485 pc->tline = pc->linenr;
1486 pc->tt = JIM_TT_STR;
1487 JimParseSubBrace(pc);
1488 return JIM_OK;
1491 static int JimParseCmd(struct JimParserCtx *pc)
1493 pc->tstart = pc->p + 1;
1494 pc->tline = pc->linenr;
1495 pc->tt = JIM_TT_CMD;
1496 JimParseSubCmd(pc);
1497 return JIM_OK;
1500 static int JimParseQuote(struct JimParserCtx *pc)
1502 pc->tstart = pc->p + 1;
1503 pc->tline = pc->linenr;
1504 pc->tt = JimParseSubQuote(pc);
1505 return JIM_OK;
1508 static int JimParseVar(struct JimParserCtx *pc)
1510 /* skip the $ */
1511 pc->p++;
1512 pc->len--;
1514 #ifdef EXPRSUGAR_BRACKET
1515 if (*pc->p == '[') {
1516 /* Parse $[...] expr shorthand syntax */
1517 JimParseCmd(pc);
1518 pc->tt = JIM_TT_EXPRSUGAR;
1519 return JIM_OK;
1521 #endif
1523 pc->tstart = pc->p;
1524 pc->tt = JIM_TT_VAR;
1525 pc->tline = pc->linenr;
1527 if (*pc->p == '{') {
1528 pc->tstart = ++pc->p;
1529 pc->len--;
1531 while (pc->len && *pc->p != '}') {
1532 if (*pc->p == '\n') {
1533 pc->linenr++;
1535 pc->p++;
1536 pc->len--;
1538 pc->tend = pc->p - 1;
1539 if (pc->len) {
1540 pc->p++;
1541 pc->len--;
1544 else {
1545 while (1) {
1546 /* Skip double colon, but not single colon! */
1547 if (pc->p[0] == ':' && pc->p[1] == ':') {
1548 pc->p += 2;
1549 pc->len -= 2;
1550 continue;
1552 if (isalnum(UCHAR(*pc->p)) || *pc->p == '_') {
1553 pc->p++;
1554 pc->len--;
1555 continue;
1557 break;
1559 /* Parse [dict get] syntax sugar. */
1560 if (*pc->p == '(') {
1561 int count = 1;
1562 const char *paren = NULL;
1564 pc->tt = JIM_TT_DICTSUGAR;
1566 while (count && pc->len) {
1567 pc->p++;
1568 pc->len--;
1569 if (*pc->p == '\\' && pc->len >= 1) {
1570 pc->p++;
1571 pc->len--;
1573 else if (*pc->p == '(') {
1574 count++;
1576 else if (*pc->p == ')') {
1577 paren = pc->p;
1578 count--;
1581 if (count == 0) {
1582 pc->p++;
1583 pc->len--;
1585 else if (paren) {
1586 /* Did not find a matching paren. Back up */
1587 paren++;
1588 pc->len += (pc->p - paren);
1589 pc->p = paren;
1591 #ifndef EXPRSUGAR_BRACKET
1592 if (*pc->tstart == '(') {
1593 pc->tt = JIM_TT_EXPRSUGAR;
1595 #endif
1597 pc->tend = pc->p - 1;
1599 /* Check if we parsed just the '$' character.
1600 * That's not a variable so an error is returned
1601 * to tell the state machine to consider this '$' just
1602 * a string. */
1603 if (pc->tstart == pc->p) {
1604 pc->p--;
1605 pc->len++;
1606 return JIM_ERR;
1608 return JIM_OK;
1611 static int JimParseStr(struct JimParserCtx *pc)
1613 int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
1614 pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR);
1615 if (newword && *pc->p == '{') {
1616 return JimParseBrace(pc);
1618 else if (newword && *pc->p == '"') {
1619 pc->state = JIM_PS_QUOTE;
1620 pc->p++;
1621 pc->len--;
1622 /* In case the end quote is missing */
1623 pc->missingline = pc->tline;
1625 pc->tstart = pc->p;
1626 pc->tline = pc->linenr;
1627 while (1) {
1628 if (pc->len == 0) {
1629 if (pc->state == JIM_PS_QUOTE) {
1630 pc->missing = '"';
1632 pc->tend = pc->p - 1;
1633 pc->tt = JIM_TT_ESC;
1634 return JIM_OK;
1636 switch (*pc->p) {
1637 case '\\':
1638 if (pc->state == JIM_PS_DEF && *(pc->p + 1) == '\n') {
1639 pc->tend = pc->p - 1;
1640 pc->tt = JIM_TT_ESC;
1641 return JIM_OK;
1643 if (pc->len >= 2) {
1644 if (*(pc->p + 1) == '\n') {
1645 pc->linenr++;
1647 pc->p++;
1648 pc->len--;
1650 break;
1651 case '(':
1652 /* If the following token is not '$' just keep going */
1653 if (pc->len > 1 && pc->p[1] != '$') {
1654 break;
1656 case ')':
1657 /* Only need a separate ')' token if the previous was a var */
1658 if (*pc->p == '(' || pc->tt == JIM_TT_VAR) {
1659 if (pc->p == pc->tstart) {
1660 /* At the start of the token, so just return this char */
1661 pc->p++;
1662 pc->len--;
1664 pc->tend = pc->p - 1;
1665 pc->tt = JIM_TT_ESC;
1666 return JIM_OK;
1668 break;
1670 case '$':
1671 case '[':
1672 pc->tend = pc->p - 1;
1673 pc->tt = JIM_TT_ESC;
1674 return JIM_OK;
1675 case ' ':
1676 case '\t':
1677 case '\n':
1678 case '\r':
1679 case ';':
1680 if (pc->state == JIM_PS_DEF) {
1681 pc->tend = pc->p - 1;
1682 pc->tt = JIM_TT_ESC;
1683 return JIM_OK;
1685 else if (*pc->p == '\n') {
1686 pc->linenr++;
1688 break;
1689 case '"':
1690 if (pc->state == JIM_PS_QUOTE) {
1691 pc->tend = pc->p - 1;
1692 pc->tt = JIM_TT_ESC;
1693 pc->p++;
1694 pc->len--;
1695 pc->state = JIM_PS_DEF;
1696 return JIM_OK;
1698 break;
1700 pc->p++;
1701 pc->len--;
1703 return JIM_OK; /* unreached */
1706 static int JimParseComment(struct JimParserCtx *pc)
1708 while (*pc->p) {
1709 if (*pc->p == '\n') {
1710 pc->linenr++;
1711 if (*(pc->p - 1) != '\\') {
1712 pc->p++;
1713 pc->len--;
1714 return JIM_OK;
1717 pc->p++;
1718 pc->len--;
1720 return JIM_OK;
1723 /* xdigitval and odigitval are helper functions for JimEscape() */
1724 static int xdigitval(int c)
1726 if (c >= '0' && c <= '9')
1727 return c - '0';
1728 if (c >= 'a' && c <= 'f')
1729 return c - 'a' + 10;
1730 if (c >= 'A' && c <= 'F')
1731 return c - 'A' + 10;
1732 return -1;
1735 static int odigitval(int c)
1737 if (c >= '0' && c <= '7')
1738 return c - '0';
1739 return -1;
1742 /* Perform Tcl escape substitution of 's', storing the result
1743 * string into 'dest'. The escaped string is guaranteed to
1744 * be the same length or shorted than the source string.
1745 * Slen is the length of the string at 's', if it's -1 the string
1746 * length will be calculated by the function.
1748 * The function returns the length of the resulting string. */
1749 static int JimEscape(char *dest, const char *s, int slen)
1751 char *p = dest;
1752 int i, len;
1754 if (slen == -1)
1755 slen = strlen(s);
1757 for (i = 0; i < slen; i++) {
1758 switch (s[i]) {
1759 case '\\':
1760 switch (s[i + 1]) {
1761 case 'a':
1762 *p++ = 0x7;
1763 i++;
1764 break;
1765 case 'b':
1766 *p++ = 0x8;
1767 i++;
1768 break;
1769 case 'f':
1770 *p++ = 0xc;
1771 i++;
1772 break;
1773 case 'n':
1774 *p++ = 0xa;
1775 i++;
1776 break;
1777 case 'r':
1778 *p++ = 0xd;
1779 i++;
1780 break;
1781 case 't':
1782 *p++ = 0x9;
1783 i++;
1784 break;
1785 case 'u':
1786 case 'x':
1787 /* A unicode or hex sequence.
1788 * \u Expect 1-4 hex chars and convert to utf-8.
1789 * \x Expect 1-2 hex chars and convert to hex.
1790 * An invalid sequence means simply the escaped char.
1793 int val = 0;
1794 int k;
1796 i++;
1798 for (k = 0; k < (s[i] == 'u' ? 4 : 2); k++) {
1799 int c = xdigitval(s[i + k + 1]);
1800 if (c == -1) {
1801 break;
1803 val = (val << 4) | c;
1805 if (k) {
1806 /* Got a valid sequence, so convert */
1807 if (s[i] == 'u') {
1808 p += utf8_fromunicode(p, val);
1810 else {
1811 *p++ = val;
1813 i += k;
1814 break;
1816 /* Not a valid codepoint, just an escaped char */
1817 *p++ = s[i];
1819 break;
1820 case 'v':
1821 *p++ = 0xb;
1822 i++;
1823 break;
1824 case '\0':
1825 *p++ = '\\';
1826 i++;
1827 break;
1828 case '\n':
1829 /* Replace all spaces and tabs after backslash newline with a single space*/
1830 *p++ = ' ';
1831 do {
1832 i++;
1833 } while (s[i + 1] == ' ' || s[i + 1] == '\t');
1834 break;
1835 case '0':
1836 case '1':
1837 case '2':
1838 case '3':
1839 case '4':
1840 case '5':
1841 case '6':
1842 case '7':
1843 /* octal escape */
1845 int val = 0;
1846 int c = odigitval(s[i + 1]);
1848 val = c;
1849 c = odigitval(s[i + 2]);
1850 if (c == -1) {
1851 *p++ = val;
1852 i++;
1853 break;
1855 val = (val * 8) + c;
1856 c = odigitval(s[i + 3]);
1857 if (c == -1) {
1858 *p++ = val;
1859 i += 2;
1860 break;
1862 val = (val * 8) + c;
1863 *p++ = val;
1864 i += 3;
1866 break;
1867 default:
1868 *p++ = s[i + 1];
1869 i++;
1870 break;
1872 break;
1873 default:
1874 *p++ = s[i];
1875 break;
1878 len = p - dest;
1879 *p = '\0';
1880 return len;
1883 /* Returns a dynamically allocated copy of the current token in the
1884 * parser context. The function performs conversion of escapes if
1885 * the token is of type JIM_TT_ESC.
1887 * Note that after the conversion, tokens that are grouped with
1888 * braces in the source code, are always recognizable from the
1889 * identical string obtained in a different way from the type.
1891 * For example the string:
1893 * {*}$a
1895 * will return as first token "*", of type JIM_TT_STR
1897 * While the string:
1899 * *$a
1901 * will return as first token "*", of type JIM_TT_ESC
1903 static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc)
1905 const char *start, *end;
1906 char *token;
1907 int len;
1909 start = pc->tstart;
1910 end = pc->tend;
1911 if (start > end) {
1912 len = 0;
1913 token = Jim_Alloc(1);
1914 token[0] = '\0';
1916 else {
1917 len = (end - start) + 1;
1918 token = Jim_Alloc(len + 1);
1919 if (pc->tt != JIM_TT_ESC) {
1920 /* No escape conversion needed? Just copy it. */
1921 memcpy(token, start, len);
1922 token[len] = '\0';
1924 else {
1925 /* Else convert the escape chars. */
1926 len = JimEscape(token, start, len);
1930 return Jim_NewStringObjNoAlloc(interp, token, len);
1933 /* Parses the given string to determine if it represents a complete script.
1935 * This is useful for interactive shells implementation, for [info complete].
1937 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1938 * '{' on scripts incomplete missing one or more '}' to be balanced.
1939 * '[' on scripts incomplete missing one or more ']' to be balanced.
1940 * '"' on scripts incomplete missing a '"' char.
1942 * If the script is complete, 1 is returned, otherwise 0.
1944 int Jim_ScriptIsComplete(const char *s, int len, char *stateCharPtr)
1946 struct JimParserCtx parser;
1948 JimParserInit(&parser, s, len, 1);
1949 while (!parser.eof) {
1950 JimParseScript(&parser);
1952 if (stateCharPtr) {
1953 *stateCharPtr = parser.missing;
1955 return parser.missing == ' ';
1958 /* -----------------------------------------------------------------------------
1959 * Tcl Lists parsing
1960 * ---------------------------------------------------------------------------*/
1961 static int JimParseListSep(struct JimParserCtx *pc);
1962 static int JimParseListStr(struct JimParserCtx *pc);
1963 static int JimParseListQuote(struct JimParserCtx *pc);
1965 static int JimParseList(struct JimParserCtx *pc)
1967 switch (*pc->p) {
1968 case ' ':
1969 case '\n':
1970 case '\t':
1971 case '\r':
1972 return JimParseListSep(pc);
1974 case '"':
1975 return JimParseListQuote(pc);
1977 case '{':
1978 return JimParseBrace(pc);
1980 default:
1981 if (pc->len) {
1982 return JimParseListStr(pc);
1984 break;
1987 pc->tstart = pc->tend = pc->p;
1988 pc->tline = pc->linenr;
1989 pc->tt = JIM_TT_EOL;
1990 pc->eof = 1;
1991 return JIM_OK;
1994 static int JimParseListSep(struct JimParserCtx *pc)
1996 pc->tstart = pc->p;
1997 pc->tline = pc->linenr;
1998 while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == '\n') {
1999 if (*pc->p == '\n') {
2000 pc->linenr++;
2002 pc->p++;
2003 pc->len--;
2005 pc->tend = pc->p - 1;
2006 pc->tt = JIM_TT_SEP;
2007 return JIM_OK;
2010 static int JimParseListQuote(struct JimParserCtx *pc)
2012 pc->p++;
2013 pc->len--;
2015 pc->tstart = pc->p;
2016 pc->tline = pc->linenr;
2017 pc->tt = JIM_TT_STR;
2019 while (pc->len) {
2020 switch (*pc->p) {
2021 case '\\':
2022 pc->tt = JIM_TT_ESC;
2023 if (--pc->len == 0) {
2024 /* Trailing backslash */
2025 pc->tend = pc->p;
2026 return JIM_OK;
2028 pc->p++;
2029 break;
2030 case '\n':
2031 pc->linenr++;
2032 break;
2033 case '"':
2034 pc->tend = pc->p - 1;
2035 pc->p++;
2036 pc->len--;
2037 return JIM_OK;
2039 pc->p++;
2040 pc->len--;
2043 pc->tend = pc->p - 1;
2044 return JIM_OK;
2047 static int JimParseListStr(struct JimParserCtx *pc)
2049 pc->tstart = pc->p;
2050 pc->tline = pc->linenr;
2051 pc->tt = JIM_TT_STR;
2053 while (pc->len) {
2054 switch (*pc->p) {
2055 case '\\':
2056 if (--pc->len == 0) {
2057 /* Trailing backslash */
2058 pc->tend = pc->p;
2059 return JIM_OK;
2061 pc->tt = JIM_TT_ESC;
2062 pc->p++;
2063 break;
2064 case ' ':
2065 case '\t':
2066 case '\n':
2067 case '\r':
2068 pc->tend = pc->p - 1;
2069 return JIM_OK;
2071 pc->p++;
2072 pc->len--;
2074 pc->tend = pc->p - 1;
2075 return JIM_OK;
2078 /* -----------------------------------------------------------------------------
2079 * Jim_Obj related functions
2080 * ---------------------------------------------------------------------------*/
2082 /* Return a new initialized object. */
2083 Jim_Obj *Jim_NewObj(Jim_Interp *interp)
2085 Jim_Obj *objPtr;
2087 /* -- Check if there are objects in the free list -- */
2088 if (interp->freeList != NULL) {
2089 /* -- Unlink the object from the free list -- */
2090 objPtr = interp->freeList;
2091 interp->freeList = objPtr->nextObjPtr;
2093 else {
2094 /* -- No ready to use objects: allocate a new one -- */
2095 objPtr = Jim_Alloc(sizeof(*objPtr));
2098 /* Object is returned with refCount of 0. Every
2099 * kind of GC implemented should take care to don't try
2100 * to scan objects with refCount == 0. */
2101 objPtr->refCount = 0;
2102 /* All the other fields are left not initialized to save time.
2103 * The caller will probably want to set them to the right
2104 * value anyway. */
2106 /* -- Put the object into the live list -- */
2107 objPtr->prevObjPtr = NULL;
2108 objPtr->nextObjPtr = interp->liveList;
2109 if (interp->liveList)
2110 interp->liveList->prevObjPtr = objPtr;
2111 interp->liveList = objPtr;
2113 return objPtr;
2116 /* Free an object. Actually objects are never freed, but
2117 * just moved to the free objects list, where they will be
2118 * reused by Jim_NewObj(). */
2119 void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
2121 /* Check if the object was already freed, panic. */
2122 JimPanic((objPtr->refCount != 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr,
2123 objPtr->refCount, objPtr->typePtr ? objPtr->typePtr->name : "<none>"));
2125 /* Free the internal representation */
2126 Jim_FreeIntRep(interp, objPtr);
2127 /* Free the string representation */
2128 if (objPtr->bytes != NULL) {
2129 if (objPtr->bytes != JimEmptyStringRep)
2130 Jim_Free(objPtr->bytes);
2132 /* Unlink the object from the live objects list */
2133 if (objPtr->prevObjPtr)
2134 objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
2135 if (objPtr->nextObjPtr)
2136 objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
2137 if (interp->liveList == objPtr)
2138 interp->liveList = objPtr->nextObjPtr;
2139 /* Link the object into the free objects list */
2140 objPtr->prevObjPtr = NULL;
2141 objPtr->nextObjPtr = interp->freeList;
2142 if (interp->freeList)
2143 interp->freeList->prevObjPtr = objPtr;
2144 interp->freeList = objPtr;
2145 objPtr->refCount = -1;
2148 /* Invalidate the string representation of an object. */
2149 void Jim_InvalidateStringRep(Jim_Obj *objPtr)
2151 if (objPtr->bytes != NULL) {
2152 if (objPtr->bytes != JimEmptyStringRep)
2153 Jim_Free(objPtr->bytes);
2155 objPtr->bytes = NULL;
2158 #define Jim_SetStringRep(o, b, l) \
2159 do { (o)->bytes = b; (o)->length = l; } while (0)
2161 /* Set the initial string representation for an object.
2162 * Does not try to free an old one. */
2163 void Jim_InitStringRep(Jim_Obj *objPtr, const char *bytes, int length)
2165 if (length == 0) {
2166 objPtr->bytes = JimEmptyStringRep;
2167 objPtr->length = 0;
2169 else {
2170 objPtr->bytes = Jim_Alloc(length + 1);
2171 objPtr->length = length;
2172 memcpy(objPtr->bytes, bytes, length);
2173 objPtr->bytes[length] = '\0';
2177 /* Duplicate an object. The returned object has refcount = 0. */
2178 Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
2180 Jim_Obj *dupPtr;
2182 dupPtr = Jim_NewObj(interp);
2183 if (objPtr->bytes == NULL) {
2184 /* Object does not have a valid string representation. */
2185 dupPtr->bytes = NULL;
2187 else {
2188 Jim_InitStringRep(dupPtr, objPtr->bytes, objPtr->length);
2191 /* By default, the new object has the same type as the old object */
2192 dupPtr->typePtr = objPtr->typePtr;
2193 if (objPtr->typePtr != NULL) {
2194 if (objPtr->typePtr->dupIntRepProc == NULL) {
2195 dupPtr->internalRep = objPtr->internalRep;
2197 else {
2198 /* The dup proc may set a different type, e.g. NULL */
2199 objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
2202 return dupPtr;
2205 /* Return the string representation for objPtr. If the object
2206 * string representation is invalid, calls the method to create
2207 * a new one starting from the internal representation of the object. */
2208 const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
2210 if (objPtr->bytes == NULL) {
2211 /* Invalid string repr. Generate it. */
2212 JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
2213 objPtr->typePtr->updateStringProc(objPtr);
2215 if (lenPtr)
2216 *lenPtr = objPtr->length;
2217 return objPtr->bytes;
2220 /* Just returns the length of the object's string rep */
2221 int Jim_Length(Jim_Obj *objPtr)
2223 int len;
2225 Jim_GetString(objPtr, &len);
2226 return len;
2229 static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2230 static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2232 static const Jim_ObjType dictSubstObjType = {
2233 "dict-substitution",
2234 FreeDictSubstInternalRep,
2235 DupDictSubstInternalRep,
2236 NULL,
2237 JIM_TYPE_NONE,
2240 static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2242 Jim_DecrRefCount(interp, (Jim_Obj *)objPtr->internalRep.twoPtrValue.ptr2);
2245 static const Jim_ObjType interpolatedObjType = {
2246 "interpolated",
2247 FreeInterpolatedInternalRep,
2248 NULL,
2249 NULL,
2250 JIM_TYPE_NONE,
2253 /* -----------------------------------------------------------------------------
2254 * String Object
2255 * ---------------------------------------------------------------------------*/
2256 static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2257 static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
2259 static const Jim_ObjType stringObjType = {
2260 "string",
2261 NULL,
2262 DupStringInternalRep,
2263 NULL,
2264 JIM_TYPE_REFERENCES,
2267 static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2269 JIM_NOTUSED(interp);
2271 /* This is a bit subtle: the only caller of this function
2272 * should be Jim_DuplicateObj(), that will copy the
2273 * string representaion. After the copy, the duplicated
2274 * object will not have more room in teh buffer than
2275 * srcPtr->length bytes. So we just set it to length. */
2276 dupPtr->internalRep.strValue.maxLength = srcPtr->length;
2278 dupPtr->internalRep.strValue.charLength = srcPtr->internalRep.strValue.charLength;
2281 static int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
2283 /* Get a fresh string representation. */
2284 (void)Jim_String(objPtr);
2285 /* Free any other internal representation. */
2286 Jim_FreeIntRep(interp, objPtr);
2287 /* Set it as string, i.e. just set the maxLength field. */
2288 objPtr->typePtr = &stringObjType;
2289 objPtr->internalRep.strValue.maxLength = objPtr->length;
2290 /* Don't know the utf-8 length yet */
2291 objPtr->internalRep.strValue.charLength = -1;
2292 return JIM_OK;
2296 * Returns the length of the object string in chars, not bytes.
2298 * These may be different for a utf-8 string.
2300 int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr)
2302 #ifdef JIM_UTF8
2303 if (objPtr->typePtr != &stringObjType)
2304 SetStringFromAny(interp, objPtr);
2306 if (objPtr->internalRep.strValue.charLength < 0) {
2307 objPtr->internalRep.strValue.charLength = utf8_strlen(objPtr->bytes, objPtr->length);
2309 return objPtr->internalRep.strValue.charLength;
2310 #else
2311 return Jim_Length(objPtr);
2312 #endif
2315 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2316 Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
2318 Jim_Obj *objPtr = Jim_NewObj(interp);
2320 /* Need to find out how many bytes the string requires */
2321 if (len == -1)
2322 len = strlen(s);
2323 /* Alloc/Set the string rep. */
2324 if (len == 0) {
2325 objPtr->bytes = JimEmptyStringRep;
2326 objPtr->length = 0;
2328 else {
2329 objPtr->bytes = Jim_Alloc(len + 1);
2330 objPtr->length = len;
2331 memcpy(objPtr->bytes, s, len);
2332 objPtr->bytes[len] = '\0';
2335 /* No typePtr field for the vanilla string object. */
2336 objPtr->typePtr = NULL;
2337 return objPtr;
2340 /* charlen is in characters -- see also Jim_NewStringObj() */
2341 Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp, const char *s, int charlen)
2343 #ifdef JIM_UTF8
2344 /* Need to find out how many bytes the string requires */
2345 int bytelen = utf8_index(s, charlen);
2347 Jim_Obj *objPtr = Jim_NewStringObj(interp, s, bytelen);
2349 /* Remember the utf8 length, so set the type */
2350 objPtr->typePtr = &stringObjType;
2351 objPtr->internalRep.strValue.maxLength = bytelen;
2352 objPtr->internalRep.strValue.charLength = charlen;
2354 return objPtr;
2355 #else
2356 return Jim_NewStringObj(interp, s, charlen);
2357 #endif
2360 /* This version does not try to duplicate the 's' pointer, but
2361 * use it directly. */
2362 Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
2364 Jim_Obj *objPtr = Jim_NewObj(interp);
2366 if (len == -1)
2367 len = strlen(s);
2368 Jim_SetStringRep(objPtr, s, len);
2369 objPtr->typePtr = NULL;
2370 return objPtr;
2373 /* Low-level string append. Use it only against objects
2374 * of type "string". */
2375 static void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
2377 int needlen;
2379 if (len == -1)
2380 len = strlen(str);
2381 needlen = objPtr->length + len;
2382 if (objPtr->internalRep.strValue.maxLength < needlen ||
2383 objPtr->internalRep.strValue.maxLength == 0) {
2384 needlen *= 2;
2385 /* Inefficient to malloc() for less than 8 bytes */
2386 if (needlen < 7) {
2387 needlen = 7;
2389 if (objPtr->bytes == JimEmptyStringRep) {
2390 objPtr->bytes = Jim_Alloc(needlen + 1);
2392 else {
2393 objPtr->bytes = Jim_Realloc(objPtr->bytes, needlen + 1);
2395 objPtr->internalRep.strValue.maxLength = needlen;
2397 memcpy(objPtr->bytes + objPtr->length, str, len);
2398 objPtr->bytes[objPtr->length + len] = '\0';
2399 if (objPtr->internalRep.strValue.charLength >= 0) {
2400 /* Update the utf-8 char length */
2401 objPtr->internalRep.strValue.charLength += utf8_strlen(objPtr->bytes + objPtr->length, len);
2403 objPtr->length += len;
2406 /* Higher level API to append strings to objects. */
2407 void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str, int len)
2409 JimPanic((Jim_IsShared(objPtr), "Jim_AppendString called with shared object"));
2410 if (objPtr->typePtr != &stringObjType)
2411 SetStringFromAny(interp, objPtr);
2412 StringAppendString(objPtr, str, len);
2415 void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
2417 int len;
2418 const char *str;
2420 str = Jim_GetString(appendObjPtr, &len);
2421 Jim_AppendString(interp, objPtr, str, len);
2424 void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
2426 va_list ap;
2428 if (objPtr->typePtr != &stringObjType)
2429 SetStringFromAny(interp, objPtr);
2430 va_start(ap, objPtr);
2431 while (1) {
2432 char *s = va_arg(ap, char *);
2434 if (s == NULL)
2435 break;
2436 Jim_AppendString(interp, objPtr, s, -1);
2438 va_end(ap);
2441 int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr)
2443 const char *aStr, *bStr;
2444 int aLen, bLen;
2446 if (aObjPtr == bObjPtr)
2447 return 1;
2448 aStr = Jim_GetString(aObjPtr, &aLen);
2449 bStr = Jim_GetString(bObjPtr, &bLen);
2450 if (aLen != bLen)
2451 return 0;
2452 return JimStringCompare(aStr, aLen, bStr, bLen) == 0;
2455 int Jim_StringMatchObj(Jim_Interp *interp, Jim_Obj *patternObjPtr, Jim_Obj *objPtr, int nocase)
2457 return JimStringMatch(interp, patternObjPtr, Jim_String(objPtr), nocase);
2460 int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
2462 const char *s1, *s2;
2463 int l1, l2;
2465 s1 = Jim_GetString(firstObjPtr, &l1);
2466 s2 = Jim_GetString(secondObjPtr, &l2);
2468 if (nocase) {
2469 return JimStringCompareNoCase(s1, s2, -1);
2471 return JimStringCompare(s1, l1, s2, l2);
2474 /* Convert a range, as returned by Jim_GetRange(), into
2475 * an absolute index into an object of the specified length.
2476 * This function may return negative values, or values
2477 * bigger or equal to the length of the list if the index
2478 * is out of range. */
2479 static int JimRelToAbsIndex(int len, int idx)
2481 if (idx < 0)
2482 return len + idx;
2483 return idx;
2486 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2487 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2488 * for implementation of commands like [string range] and [lrange].
2490 * The resulting range is guaranteed to address valid elements of
2491 * the structure. */
2492 static void JimRelToAbsRange(int len, int first, int last,
2493 int *firstPtr, int *lastPtr, int *rangeLenPtr)
2495 int rangeLen;
2497 if (first > last) {
2498 rangeLen = 0;
2500 else {
2501 rangeLen = last - first + 1;
2502 if (rangeLen) {
2503 if (first < 0) {
2504 rangeLen += first;
2505 first = 0;
2507 if (last >= len) {
2508 rangeLen -= (last - (len - 1));
2509 last = len - 1;
2513 if (rangeLen < 0)
2514 rangeLen = 0;
2516 *firstPtr = first;
2517 *lastPtr = last;
2518 *rangeLenPtr = rangeLen;
2521 Jim_Obj *Jim_StringByteRangeObj(Jim_Interp *interp,
2522 Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
2524 int first, last;
2525 const char *str;
2526 int rangeLen;
2527 int bytelen;
2529 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
2530 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
2531 return NULL;
2532 str = Jim_GetString(strObjPtr, &bytelen);
2533 first = JimRelToAbsIndex(bytelen, first);
2534 last = JimRelToAbsIndex(bytelen, last);
2535 JimRelToAbsRange(bytelen, first, last, &first, &last, &rangeLen);
2536 if (first == 0 && rangeLen == bytelen) {
2537 return strObjPtr;
2539 return Jim_NewStringObj(interp, str + first, rangeLen);
2542 Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
2543 Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
2545 #ifdef JIM_UTF8
2546 int first, last;
2547 const char *str;
2548 int len, rangeLen;
2549 int bytelen;
2551 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
2552 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
2553 return NULL;
2554 str = Jim_GetString(strObjPtr, &bytelen);
2555 len = Jim_Utf8Length(interp, strObjPtr);
2556 first = JimRelToAbsIndex(len, first);
2557 last = JimRelToAbsIndex(len, last);
2558 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
2559 if (first == 0 && rangeLen == len) {
2560 return strObjPtr;
2562 if (len == bytelen) {
2563 /* ASCII optimisation */
2564 return Jim_NewStringObj(interp, str + first, rangeLen);
2566 return Jim_NewStringObjUtf8(interp, str + utf8_index(str, first), rangeLen);
2567 #else
2568 return Jim_StringByteRangeObj(interp, strObjPtr, firstObjPtr, lastObjPtr);
2569 #endif
2572 static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
2574 char *buf, *p;
2575 int len;
2576 const char *str;
2578 if (strObjPtr->typePtr != &stringObjType) {
2579 SetStringFromAny(interp, strObjPtr);
2582 str = Jim_GetString(strObjPtr, &len);
2584 buf = p = Jim_Alloc(len + 1);
2585 while (*str) {
2586 int c;
2587 str += utf8_tounicode(str, &c);
2588 p += utf8_fromunicode(p, utf8_lower(c));
2590 *p = 0;
2591 return Jim_NewStringObjNoAlloc(interp, buf, len);
2594 static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
2596 char *buf, *p;
2597 int len;
2598 const char *str;
2600 if (strObjPtr->typePtr != &stringObjType) {
2601 SetStringFromAny(interp, strObjPtr);
2604 str = Jim_GetString(strObjPtr, &len);
2606 buf = p = Jim_Alloc(len + 1);
2607 while (*str) {
2608 int c;
2609 str += utf8_tounicode(str, &c);
2610 p += utf8_fromunicode(p, utf8_upper(c));
2612 *p = 0;
2613 return Jim_NewStringObjNoAlloc(interp, buf, len);
2616 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2617 * for unicode character 'c'.
2618 * Returns the position if found or NULL if not
2620 static const char *utf8_memchr(const char *str, int len, int c)
2622 #ifdef JIM_UTF8
2623 while (len) {
2624 int sc;
2625 int n = utf8_tounicode(str, &sc);
2626 if (sc == c) {
2627 return str;
2629 str += n;
2630 len -= n;
2632 return NULL;
2633 #else
2634 return memchr(str, c, len);
2635 #endif
2639 * Searches for the first non-trim char in string (str, len)
2641 * If none is found, returns just past the last char.
2643 * Lengths are in bytes.
2645 static const char *JimFindTrimLeft(const char *str, int len, const char *trimchars, int trimlen)
2647 while (len) {
2648 int c;
2649 int n = utf8_tounicode(str, &c);
2651 if (utf8_memchr(trimchars, trimlen, c) == NULL) {
2652 /* Not a trim char, so stop */
2653 break;
2655 str += n;
2656 len -= n;
2658 return str;
2662 * Searches backwards for a non-trim char in string (str, len).
2664 * Returns a pointer to just after the non-trim char, or NULL if not found.
2666 * Lengths are in bytes.
2668 static const char *JimFindTrimRight(const char *str, int len, const char *trimchars, int trimlen)
2670 str += len;
2672 while (len) {
2673 int c;
2674 int n = utf8_prev_len(str, len);
2676 len -= n;
2677 str -= n;
2679 n = utf8_tounicode(str, &c);
2681 if (utf8_memchr(trimchars, trimlen, c) == NULL) {
2682 return str + n;
2686 return NULL;
2689 static const char default_trim_chars[] = " \t\n\r";
2690 /* sizeof() here includes the null byte */
2691 static int default_trim_chars_len = sizeof(default_trim_chars);
2693 static Jim_Obj *JimStringTrimLeft(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2695 int len;
2696 const char *str = Jim_GetString(strObjPtr, &len);
2697 const char *trimchars = default_trim_chars;
2698 int trimcharslen = default_trim_chars_len;
2699 const char *newstr;
2701 if (trimcharsObjPtr) {
2702 trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
2705 newstr = JimFindTrimLeft(str, len, trimchars, trimcharslen);
2706 if (newstr == str) {
2707 return strObjPtr;
2710 return Jim_NewStringObj(interp, newstr, len - (newstr - str));
2713 static Jim_Obj *JimStringTrimRight(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2715 int len;
2716 const char *trimchars = default_trim_chars;
2717 int trimcharslen = default_trim_chars_len;
2718 const char *nontrim;
2720 if (trimcharsObjPtr) {
2721 trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
2724 if (strObjPtr->typePtr != &stringObjType) {
2725 SetStringFromAny(interp, strObjPtr);
2727 len = Jim_Length(strObjPtr);
2728 nontrim = JimFindTrimRight(strObjPtr->bytes, len, trimchars, trimcharslen);
2730 if (nontrim == NULL) {
2731 /* All trim, so return a zero-length string */
2732 return Jim_NewEmptyStringObj(interp);
2734 if (nontrim == strObjPtr->bytes + len) {
2735 return strObjPtr;
2738 if (Jim_IsShared(strObjPtr)) {
2739 strObjPtr = Jim_NewStringObj(interp, strObjPtr->bytes, (nontrim - strObjPtr->bytes));
2741 else {
2742 /* Can modify this string in place */
2743 strObjPtr->bytes[nontrim - strObjPtr->bytes] = 0;
2744 strObjPtr->length = (nontrim - strObjPtr->bytes);
2747 return strObjPtr;
2750 static Jim_Obj *JimStringTrim(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2752 /* First trim left. */
2753 Jim_Obj *objPtr = JimStringTrimLeft(interp, strObjPtr, trimcharsObjPtr);
2755 /* Now trim right */
2756 strObjPtr = JimStringTrimRight(interp, objPtr, trimcharsObjPtr);
2758 if (objPtr != strObjPtr) {
2759 /* Note that we don't want this object to be leaked */
2760 Jim_IncrRefCount(objPtr);
2761 Jim_DecrRefCount(interp, objPtr);
2764 return strObjPtr;
2768 static int JimStringIs(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *strClass, int strict)
2770 static const char * const strclassnames[] = {
2771 "integer", "alpha", "alnum", "ascii", "digit",
2772 "double", "lower", "upper", "space", "xdigit",
2773 "control", "print", "graph", "punct",
2774 NULL
2776 enum {
2777 STR_IS_INTEGER, STR_IS_ALPHA, STR_IS_ALNUM, STR_IS_ASCII, STR_IS_DIGIT,
2778 STR_IS_DOUBLE, STR_IS_LOWER, STR_IS_UPPER, STR_IS_SPACE, STR_IS_XDIGIT,
2779 STR_IS_CONTROL, STR_IS_PRINT, STR_IS_GRAPH, STR_IS_PUNCT
2781 int strclass;
2782 int len;
2783 int i;
2784 const char *str;
2785 int (*isclassfunc)(int c) = NULL;
2787 if (Jim_GetEnum(interp, strClass, strclassnames, &strclass, "class", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
2788 return JIM_ERR;
2791 str = Jim_GetString(strObjPtr, &len);
2792 if (len == 0) {
2793 Jim_SetResultInt(interp, !strict);
2794 return JIM_OK;
2797 switch (strclass) {
2798 case STR_IS_INTEGER:
2800 jim_wide w;
2801 Jim_SetResultInt(interp, JimGetWideNoErr(interp, strObjPtr, &w) == JIM_OK);
2802 return JIM_OK;
2805 case STR_IS_DOUBLE:
2807 double d;
2808 Jim_SetResultInt(interp, Jim_GetDouble(interp, strObjPtr, &d) == JIM_OK && errno != ERANGE);
2809 return JIM_OK;
2812 case STR_IS_ALPHA: isclassfunc = isalpha; break;
2813 case STR_IS_ALNUM: isclassfunc = isalnum; break;
2814 case STR_IS_ASCII: isclassfunc = isascii; break;
2815 case STR_IS_DIGIT: isclassfunc = isdigit; break;
2816 case STR_IS_LOWER: isclassfunc = islower; break;
2817 case STR_IS_UPPER: isclassfunc = isupper; break;
2818 case STR_IS_SPACE: isclassfunc = isspace; break;
2819 case STR_IS_XDIGIT: isclassfunc = isxdigit; break;
2820 case STR_IS_CONTROL: isclassfunc = iscntrl; break;
2821 case STR_IS_PRINT: isclassfunc = isprint; break;
2822 case STR_IS_GRAPH: isclassfunc = isgraph; break;
2823 case STR_IS_PUNCT: isclassfunc = ispunct; break;
2824 default:
2825 return JIM_ERR;
2828 for (i = 0; i < len; i++) {
2829 if (!isclassfunc(str[i])) {
2830 Jim_SetResultInt(interp, 0);
2831 return JIM_OK;
2834 Jim_SetResultInt(interp, 1);
2835 return JIM_OK;
2838 /* -----------------------------------------------------------------------------
2839 * Compared String Object
2840 * ---------------------------------------------------------------------------*/
2842 /* This is strange object that allows to compare a C literal string
2843 * with a Jim object in very short time if the same comparison is done
2844 * multiple times. For example every time the [if] command is executed,
2845 * Jim has to check if a given argument is "else". This comparions if
2846 * the code has no errors are true most of the times, so we can cache
2847 * inside the object the pointer of the string of the last matching
2848 * comparison. Because most C compilers perform literal sharing,
2849 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2850 * this works pretty well even if comparisons are at different places
2851 * inside the C code. */
2853 static const Jim_ObjType comparedStringObjType = {
2854 "compared-string",
2855 NULL,
2856 NULL,
2857 NULL,
2858 JIM_TYPE_REFERENCES,
2861 /* The only way this object is exposed to the API is via the following
2862 * function. Returns true if the string and the object string repr.
2863 * are the same, otherwise zero is returned.
2865 * Note: this isn't binary safe, but it hardly needs to be.*/
2866 int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr, const char *str)
2868 if (objPtr->typePtr == &comparedStringObjType && objPtr->internalRep.ptr == str)
2869 return 1;
2870 else {
2871 const char *objStr = Jim_String(objPtr);
2873 if (strcmp(str, objStr) != 0)
2874 return 0;
2875 if (objPtr->typePtr != &comparedStringObjType) {
2876 Jim_FreeIntRep(interp, objPtr);
2877 objPtr->typePtr = &comparedStringObjType;
2879 objPtr->internalRep.ptr = (char *)str; /*ATTENTION: const cast */
2880 return 1;
2884 static int qsortCompareStringPointers(const void *a, const void *b)
2886 char *const *sa = (char *const *)a;
2887 char *const *sb = (char *const *)b;
2889 return strcmp(*sa, *sb);
2893 /* -----------------------------------------------------------------------------
2894 * Source Object
2896 * This object is just a string from the language point of view, but
2897 * in the internal representation it contains the filename and line number
2898 * where this given token was read. This information is used by
2899 * Jim_EvalObj() if the object passed happens to be of type "source".
2901 * This allows to propagate the information about line numbers and file
2902 * names and give error messages with absolute line numbers.
2904 * Note that this object uses shared strings for filenames, and the
2905 * pointer to the filename together with the line number is taken into
2906 * the space for the "inline" internal representation of the Jim_Object,
2907 * so there is almost memory zero-overhead.
2909 * Also the object will be converted to something else if the given
2910 * token it represents in the source file is not something to be
2911 * evaluated (not a script), and will be specialized in some other way,
2912 * so the time overhead is also null.
2913 * ---------------------------------------------------------------------------*/
2915 static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2916 static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2918 static const Jim_ObjType sourceObjType = {
2919 "source",
2920 FreeSourceInternalRep,
2921 DupSourceInternalRep,
2922 NULL,
2923 JIM_TYPE_REFERENCES,
2926 void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2928 Jim_DecrRefCount(interp, objPtr->internalRep.sourceValue.fileNameObj);
2931 void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2933 dupPtr->internalRep = srcPtr->internalRep;
2934 Jim_IncrRefCount(dupPtr->internalRep.sourceValue.fileNameObj);
2937 static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
2938 Jim_Obj *fileNameObj, int lineNumber)
2940 JimPanic((Jim_IsShared(objPtr), "JimSetSourceInfo called with shared object"));
2941 JimPanic((objPtr->typePtr != NULL, "JimSetSourceInfo called with typePtr != NULL"));
2942 Jim_IncrRefCount(fileNameObj);
2943 objPtr->internalRep.sourceValue.fileNameObj = fileNameObj;
2944 objPtr->internalRep.sourceValue.lineNumber = lineNumber;
2945 objPtr->typePtr = &sourceObjType;
2948 /* -----------------------------------------------------------------------------
2949 * Script Object
2950 * ---------------------------------------------------------------------------*/
2952 static const Jim_ObjType scriptLineObjType = {
2953 "scriptline",
2954 NULL,
2955 NULL,
2956 NULL,
2960 static Jim_Obj *JimNewScriptLineObj(Jim_Interp *interp, int argc, int line)
2962 Jim_Obj *objPtr;
2964 #ifdef DEBUG_SHOW_SCRIPT
2965 char buf[100];
2966 snprintf(buf, sizeof(buf), "line=%d, argc=%d", line, argc);
2967 objPtr = Jim_NewStringObj(interp, buf, -1);
2968 #else
2969 objPtr = Jim_NewEmptyStringObj(interp);
2970 #endif
2971 objPtr->typePtr = &scriptLineObjType;
2972 objPtr->internalRep.scriptLineValue.argc = argc;
2973 objPtr->internalRep.scriptLineValue.line = line;
2975 return objPtr;
2978 #define JIM_CMDSTRUCT_EXPAND -1
2980 static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2981 static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2982 static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, struct JimParseResult *result);
2984 static const Jim_ObjType scriptObjType = {
2985 "script",
2986 FreeScriptInternalRep,
2987 DupScriptInternalRep,
2988 NULL,
2989 JIM_TYPE_REFERENCES,
2992 /* The ScriptToken structure represents every token into a scriptObj.
2993 * Every token contains an associated Jim_Obj that can be specialized
2994 * by commands operating on it. */
2995 typedef struct ScriptToken
2997 int type;
2998 Jim_Obj *objPtr;
2999 } ScriptToken;
3001 /* This is the script object internal representation. An array of
3002 * ScriptToken structures, including a pre-computed representation of the
3003 * command length and arguments.
3005 * For example the script:
3007 * puts hello
3008 * set $i $x$y [foo]BAR
3010 * will produce a ScriptObj with the following Tokens:
3012 * LIN 2
3013 * ESC puts
3014 * ESC hello
3015 * LIN 4
3016 * ESC set
3017 * VAR i
3018 * WRD 2
3019 * VAR x
3020 * VAR y
3021 * WRD 2
3022 * CMD foo
3023 * ESC BAR
3025 * "puts hello" has two args (LIN 2), composed of single tokens.
3026 * (Note that the WRD token is omitted for the common case of a single token.)
3028 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
3029 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
3031 * The precomputation of the command structure makes Jim_Eval() faster,
3032 * and simpler because there aren't dynamic lengths / allocations.
3034 * -- {expand}/{*} handling --
3036 * Expand is handled in a special way.
3038 * If a "word" begins with {*}, the word token count is -ve.
3040 * For example the command:
3042 * list {*}{a b}
3044 * Will produce the following cmdstruct array:
3046 * LIN 2
3047 * ESC list
3048 * WRD -1
3049 * STR a b
3051 * Note that the 'LIN' token also contains the source information for the
3052 * first word of the line for error reporting purposes
3054 * -- the substFlags field of the structure --
3056 * The scriptObj structure is used to represent both "script" objects
3057 * and "subst" objects. In the second case, the there are no LIN and WRD
3058 * tokens. Instead SEP and EOL tokens are added as-is.
3059 * In addition, the field 'substFlags' is used to represent the flags used to turn
3060 * the string into the internal representation used to perform the
3061 * substitution. If this flags are not what the application requires
3062 * the scriptObj is created again. For example the script:
3064 * subst -nocommands $string
3065 * subst -novariables $string
3067 * Will recreate the internal representation of the $string object
3068 * two times.
3070 typedef struct ScriptObj
3072 int len; /* Length as number of tokens. */
3073 ScriptToken *token; /* Tokens array. */
3074 int substFlags; /* flags used for the compilation of "subst" objects */
3075 int inUse; /* Used to share a ScriptObj. Currently
3076 only used by Jim_EvalObj() as protection against
3077 shimmering of the currently evaluated object. */
3078 Jim_Obj *fileNameObj;
3079 int line; /* Line number of the first line */
3080 } ScriptObj;
3082 void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
3084 int i;
3085 struct ScriptObj *script = (void *)objPtr->internalRep.ptr;
3087 script->inUse--;
3088 if (script->inUse != 0)
3089 return;
3090 for (i = 0; i < script->len; i++) {
3091 Jim_DecrRefCount(interp, script->token[i].objPtr);
3093 Jim_Free(script->token);
3094 Jim_DecrRefCount(interp, script->fileNameObj);
3095 Jim_Free(script);
3098 void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
3100 JIM_NOTUSED(interp);
3101 JIM_NOTUSED(srcPtr);
3103 /* Just returns an simple string. */
3104 dupPtr->typePtr = NULL;
3107 /* A simple parser token.
3108 * All the simple tokens for the script point into the same script string rep.
3110 typedef struct
3112 const char *token; /* Pointer to the start of the token */
3113 int len; /* Length of this token */
3114 int type; /* Token type */
3115 int line; /* Line number */
3116 } ParseToken;
3118 /* A list of parsed tokens representing a script.
3119 * Tokens are added to this list as the script is parsed.
3120 * It grows as needed.
3122 typedef struct
3124 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3125 ParseToken *list; /* Array of tokens */
3126 int size; /* Current size of the list */
3127 int count; /* Number of entries used */
3128 ParseToken static_list[20]; /* Small initial token space to avoid allocation */
3129 } ParseTokenList;
3131 static void ScriptTokenListInit(ParseTokenList *tokenlist)
3133 tokenlist->list = tokenlist->static_list;
3134 tokenlist->size = sizeof(tokenlist->static_list) / sizeof(ParseToken);
3135 tokenlist->count = 0;
3138 static void ScriptTokenListFree(ParseTokenList *tokenlist)
3140 if (tokenlist->list != tokenlist->static_list) {
3141 Jim_Free(tokenlist->list);
3146 * Adds the new token to the tokenlist.
3147 * The token has the given length, type and line number.
3148 * The token list is resized as necessary.
3150 static void ScriptAddToken(ParseTokenList *tokenlist, const char *token, int len, int type,
3151 int line)
3153 ParseToken *t;
3155 if (tokenlist->count == tokenlist->size) {
3156 /* Resize the list */
3157 tokenlist->size *= 2;
3158 if (tokenlist->list != tokenlist->static_list) {
3159 tokenlist->list =
3160 Jim_Realloc(tokenlist->list, tokenlist->size * sizeof(*tokenlist->list));
3162 else {
3163 /* The list needs to become allocated */
3164 tokenlist->list = Jim_Alloc(tokenlist->size * sizeof(*tokenlist->list));
3165 memcpy(tokenlist->list, tokenlist->static_list,
3166 tokenlist->count * sizeof(*tokenlist->list));
3169 t = &tokenlist->list[tokenlist->count++];
3170 t->token = token;
3171 t->len = len;
3172 t->type = type;
3173 t->line = line;
3176 /* Counts the number of adjoining non-separator.
3178 * Returns -ve if the first token is the expansion
3179 * operator (in which case the count doesn't include
3180 * that token).
3182 static int JimCountWordTokens(ParseToken *t)
3184 int expand = 1;
3185 int count = 0;
3187 /* Is the first word {*} or {expand}? */
3188 if (t->type == JIM_TT_STR && !TOKEN_IS_SEP(t[1].type)) {
3189 if ((t->len == 1 && *t->token == '*') || (t->len == 6 && strncmp(t->token, "expand", 6) == 0)) {
3190 /* Create an expand token */
3191 expand = -1;
3192 t++;
3196 /* Now count non-separator words */
3197 while (!TOKEN_IS_SEP(t->type)) {
3198 t++;
3199 count++;
3202 return count * expand;
3206 * Create a script/subst object from the given token.
3208 static Jim_Obj *JimMakeScriptObj(Jim_Interp *interp, const ParseToken *t)
3210 Jim_Obj *objPtr;
3212 if (t->type == JIM_TT_ESC && memchr(t->token, '\\', t->len) != NULL) {
3213 /* Convert the backlash escapes . */
3214 int len = t->len;
3215 char *str = Jim_Alloc(len + 1);
3216 len = JimEscape(str, t->token, len);
3217 objPtr = Jim_NewStringObjNoAlloc(interp, str, len);
3219 else {
3220 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3221 * with a single space. This is currently not done.
3223 objPtr = Jim_NewStringObj(interp, t->token, t->len);
3225 return objPtr;
3229 * Takes a tokenlist and creates the allocated list of script tokens
3230 * in script->token, of length script->len.
3232 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3233 * as required.
3235 * Also sets script->line to the line number of the first token
3237 static void ScriptObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
3238 ParseTokenList *tokenlist)
3240 int i;
3241 struct ScriptToken *token;
3242 /* Number of tokens so far for the current command */
3243 int lineargs = 0;
3244 /* This is the first token for the current command */
3245 ScriptToken *linefirst;
3246 int count;
3247 int linenr;
3249 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3250 printf("==== Tokens ====\n");
3251 for (i = 0; i < tokenlist->count; i++) {
3252 printf("[%2d]@%d %s '%.*s'\n", i, tokenlist->list[i].line, jim_tt_name(tokenlist->list[i].type),
3253 tokenlist->list[i].len, tokenlist->list[i].token);
3255 #endif
3257 /* May need up to one extra script token for each EOL in the worst case */
3258 count = tokenlist->count;
3259 for (i = 0; i < tokenlist->count; i++) {
3260 if (tokenlist->list[i].type == JIM_TT_EOL) {
3261 count++;
3264 linenr = script->line = tokenlist->list[0].line;
3266 token = script->token = Jim_Alloc(sizeof(ScriptToken) * count);
3268 /* This is the first token for the current command */
3269 linefirst = token++;
3271 for (i = 0; i < tokenlist->count; ) {
3272 /* Look ahead to find out how many tokens make up the next word */
3273 int wordtokens;
3275 /* Skip any leading separators */
3276 while (tokenlist->list[i].type == JIM_TT_SEP) {
3277 i++;
3280 wordtokens = JimCountWordTokens(tokenlist->list + i);
3282 if (wordtokens == 0) {
3283 /* None, so at end of line */
3284 if (lineargs) {
3285 linefirst->type = JIM_TT_LINE;
3286 linefirst->objPtr = JimNewScriptLineObj(interp, lineargs, linenr);
3287 Jim_IncrRefCount(linefirst->objPtr);
3289 /* Reset for new line */
3290 lineargs = 0;
3291 linefirst = token++;
3293 i++;
3294 continue;
3296 else if (wordtokens != 1) {
3297 /* More than 1, or {expand}, so insert a WORD token */
3298 token->type = JIM_TT_WORD;
3299 token->objPtr = Jim_NewIntObj(interp, wordtokens);
3300 Jim_IncrRefCount(token->objPtr);
3301 token++;
3302 if (wordtokens < 0) {
3303 /* Skip the expand token */
3304 i++;
3305 wordtokens = -wordtokens - 1;
3306 lineargs--;
3310 if (lineargs == 0) {
3311 /* First real token on the line, so record the line number */
3312 linenr = tokenlist->list[i].line;
3314 lineargs++;
3316 /* Add each non-separator word token to the line */
3317 while (wordtokens--) {
3318 const ParseToken *t = &tokenlist->list[i++];
3320 token->type = t->type;
3321 token->objPtr = JimMakeScriptObj(interp, t);
3322 Jim_IncrRefCount(token->objPtr);
3324 /* Every object is initially a string, but the
3325 * internal type may be specialized during execution of the
3326 * script. */
3327 JimSetSourceInfo(interp, token->objPtr, script->fileNameObj, t->line);
3328 token++;
3332 if (lineargs == 0) {
3333 token--;
3336 script->len = token - script->token;
3338 assert(script->len < count);
3340 #ifdef DEBUG_SHOW_SCRIPT
3341 printf("==== Script (%s) ====\n", Jim_String(script->fileNameObj));
3342 for (i = 0; i < script->len; i++) {
3343 const ScriptToken *t = &script->token[i];
3344 printf("[%2d] %s %s\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
3346 #endif
3351 * Similar to ScriptObjAddTokens(), but for subst objects.
3353 static void SubstObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
3354 ParseTokenList *tokenlist)
3356 int i;
3357 struct ScriptToken *token;
3359 token = script->token = Jim_Alloc(sizeof(ScriptToken) * tokenlist->count);
3361 for (i = 0; i < tokenlist->count; i++) {
3362 const ParseToken *t = &tokenlist->list[i];
3364 /* Create a token for 't' */
3365 token->type = t->type;
3366 token->objPtr = JimMakeScriptObj(interp, t);
3367 Jim_IncrRefCount(token->objPtr);
3368 token++;
3371 script->len = i;
3374 /* This method takes the string representation of an object
3375 * as a Tcl script, and generates the pre-parsed internal representation
3376 * of the script. */
3377 static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, struct JimParseResult *result)
3379 int scriptTextLen;
3380 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
3381 struct JimParserCtx parser;
3382 struct ScriptObj *script;
3383 ParseTokenList tokenlist;
3384 int line = 1;
3386 /* Try to get information about filename / line number */
3387 if (objPtr->typePtr == &sourceObjType) {
3388 line = objPtr->internalRep.sourceValue.lineNumber;
3391 /* Initially parse the script into tokens (in tokenlist) */
3392 ScriptTokenListInit(&tokenlist);
3394 JimParserInit(&parser, scriptText, scriptTextLen, line);
3395 while (!parser.eof) {
3396 JimParseScript(&parser);
3397 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
3398 parser.tline);
3400 if (result && parser.missing != ' ') {
3401 ScriptTokenListFree(&tokenlist);
3402 result->missing = parser.missing;
3403 result->line = parser.missingline;
3404 return JIM_ERR;
3407 /* Add a final EOF token */
3408 ScriptAddToken(&tokenlist, scriptText + scriptTextLen, 0, JIM_TT_EOF, 0);
3410 /* Create the "real" script tokens from the initial token list */
3411 script = Jim_Alloc(sizeof(*script));
3412 memset(script, 0, sizeof(*script));
3413 script->inUse = 1;
3414 script->line = line;
3415 if (objPtr->typePtr == &sourceObjType) {
3416 script->fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
3418 else {
3419 script->fileNameObj = interp->emptyObj;
3421 Jim_IncrRefCount(script->fileNameObj);
3423 ScriptObjAddTokens(interp, script, &tokenlist);
3425 /* No longer need the token list */
3426 ScriptTokenListFree(&tokenlist);
3428 /* Free the old internal rep and set the new one. */
3429 Jim_FreeIntRep(interp, objPtr);
3430 Jim_SetIntRepPtr(objPtr, script);
3431 objPtr->typePtr = &scriptObjType;
3433 return JIM_OK;
3436 ScriptObj *Jim_GetScript(Jim_Interp *interp, Jim_Obj *objPtr)
3438 struct ScriptObj *script = Jim_GetIntRepPtr(objPtr);
3440 if (objPtr->typePtr != &scriptObjType || script->substFlags) {
3441 SetScriptFromAny(interp, objPtr, NULL);
3443 return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
3446 /* -----------------------------------------------------------------------------
3447 * Commands
3448 * ---------------------------------------------------------------------------*/
3449 static void JimIncrCmdRefCount(Jim_Cmd *cmdPtr)
3451 cmdPtr->inUse++;
3454 static void JimDecrCmdRefCount(Jim_Interp *interp, Jim_Cmd *cmdPtr)
3456 if (--cmdPtr->inUse == 0) {
3457 if (cmdPtr->isproc) {
3458 Jim_DecrRefCount(interp, cmdPtr->u.proc.argListObjPtr);
3459 Jim_DecrRefCount(interp, cmdPtr->u.proc.bodyObjPtr);
3460 if (cmdPtr->u.proc.staticVars) {
3461 Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
3462 Jim_Free(cmdPtr->u.proc.staticVars);
3464 if (cmdPtr->u.proc.prevCmd) {
3465 /* Delete any pushed command too */
3466 JimDecrCmdRefCount(interp, cmdPtr->u.proc.prevCmd);
3469 else {
3470 /* native (C) */
3471 if (cmdPtr->u.native.delProc) {
3472 cmdPtr->u.native.delProc(interp, cmdPtr->u.native.privData);
3475 Jim_Free(cmdPtr);
3479 /* Commands HashTable Type.
3481 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3482 static void JimCommandsHT_ValDestructor(void *interp, void *val)
3484 JimDecrCmdRefCount(interp, val);
3487 static const Jim_HashTableType JimCommandsHashTableType = {
3488 JimStringCopyHTHashFunction, /* hash function */
3489 JimStringCopyHTKeyDup, /* key dup */
3490 NULL, /* val dup */
3491 JimStringCopyHTKeyCompare, /* key compare */
3492 JimStringCopyHTKeyDestructor, /* key destructor */
3493 JimCommandsHT_ValDestructor /* val destructor */
3496 /* ------------------------- Commands related functions --------------------- */
3498 int Jim_CreateCommand(Jim_Interp *interp, const char *cmdName,
3499 Jim_CmdProc cmdProc, void *privData, Jim_DelCmdProc delProc)
3501 Jim_Cmd *cmdPtr;
3503 if (Jim_DeleteHashEntry(&interp->commands, cmdName) != JIM_ERR) {
3504 /* Command existed so incr proc epoch */
3505 Jim_InterpIncrProcEpoch(interp);
3508 cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
3510 /* Store the new details for this proc */
3511 memset(cmdPtr, 0, sizeof(*cmdPtr));
3512 cmdPtr->inUse = 1;
3513 cmdPtr->u.native.delProc = delProc;
3514 cmdPtr->u.native.cmdProc = cmdProc;
3515 cmdPtr->u.native.privData = privData;
3517 Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);
3519 /* There is no need to increment the 'proc epoch' because
3520 * creation of a new procedure can never affect existing
3521 * cached commands. We don't do negative caching. */
3522 return JIM_OK;
3525 static int JimCreateProcedure(Jim_Interp *interp, Jim_Obj *cmdName,
3526 Jim_Obj *argListObjPtr, Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr)
3528 Jim_Cmd *cmdPtr;
3529 Jim_HashEntry *he;
3530 int argListLen;
3531 int i;
3533 if (JimValidName(interp, "procedure", cmdName) != JIM_OK) {
3534 return JIM_ERR;
3537 argListLen = Jim_ListLength(interp, argListObjPtr);
3539 /* Allocate space for both the command pointer and the arg list */
3540 cmdPtr = Jim_Alloc(sizeof(*cmdPtr) + sizeof(struct Jim_ProcArg) * argListLen);
3541 memset(cmdPtr, 0, sizeof(*cmdPtr));
3542 cmdPtr->inUse = 1;
3543 cmdPtr->isproc = 1;
3544 cmdPtr->u.proc.argListObjPtr = argListObjPtr;
3545 cmdPtr->u.proc.argListLen = argListLen;
3546 cmdPtr->u.proc.bodyObjPtr = bodyObjPtr;
3547 cmdPtr->u.proc.argsPos = -1;
3548 cmdPtr->u.proc.arglist = (struct Jim_ProcArg *)(cmdPtr + 1);
3549 Jim_IncrRefCount(argListObjPtr);
3550 Jim_IncrRefCount(bodyObjPtr);
3552 /* Create the statics hash table. */
3553 if (staticsListObjPtr) {
3554 int len, i;
3556 len = Jim_ListLength(interp, staticsListObjPtr);
3557 if (len != 0) {
3558 cmdPtr->u.proc.staticVars = Jim_Alloc(sizeof(Jim_HashTable));
3559 Jim_InitHashTable(cmdPtr->u.proc.staticVars, &JimVariablesHashTableType, interp);
3560 for (i = 0; i < len; i++) {
3561 Jim_Obj *objPtr = 0, *initObjPtr = 0, *nameObjPtr = 0;
3562 Jim_Var *varPtr;
3563 int subLen;
3565 Jim_ListIndex(interp, staticsListObjPtr, i, &objPtr, JIM_NONE);
3566 /* Check if it's composed of two elements. */
3567 subLen = Jim_ListLength(interp, objPtr);
3568 if (subLen == 1 || subLen == 2) {
3569 /* Try to get the variable value from the current
3570 * environment. */
3571 Jim_ListIndex(interp, objPtr, 0, &nameObjPtr, JIM_NONE);
3572 if (subLen == 1) {
3573 initObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_NONE);
3574 if (initObjPtr == NULL) {
3575 Jim_SetResultFormatted(interp,
3576 "variable for initialization of static \"%#s\" not found in the local context",
3577 nameObjPtr);
3578 goto err;
3581 else {
3582 Jim_ListIndex(interp, objPtr, 1, &initObjPtr, JIM_NONE);
3584 if (JimValidName(interp, "static variable", nameObjPtr) != JIM_OK) {
3585 goto err;
3588 varPtr = Jim_Alloc(sizeof(*varPtr));
3589 varPtr->objPtr = initObjPtr;
3590 Jim_IncrRefCount(initObjPtr);
3591 varPtr->linkFramePtr = NULL;
3592 if (Jim_AddHashEntry(cmdPtr->u.proc.staticVars,
3593 Jim_String(nameObjPtr), varPtr) != JIM_OK) {
3594 Jim_SetResultFormatted(interp,
3595 "static variable name \"%#s\" duplicated in statics list", nameObjPtr);
3596 Jim_DecrRefCount(interp, initObjPtr);
3597 Jim_Free(varPtr);
3598 goto err;
3601 else {
3602 Jim_SetResultFormatted(interp, "too many fields in static specifier \"%#s\"",
3603 objPtr);
3604 goto err;
3610 /* Parse the args out into arglist, validating as we go */
3611 /* Examine the argument list for default parameters and 'args' */
3612 for (i = 0; i < argListLen; i++) {
3613 Jim_Obj *argPtr;
3614 Jim_Obj *nameObjPtr;
3615 Jim_Obj *defaultObjPtr;
3616 int len;
3617 int n = 1;
3619 /* Examine a parameter */
3620 Jim_ListIndex(interp, argListObjPtr, i, &argPtr, JIM_NONE);
3621 len = Jim_ListLength(interp, argPtr);
3622 if (len == 0) {
3623 Jim_SetResultString(interp, "procedure has argument with no name", -1);
3624 goto err;
3626 if (len > 2) {
3627 Jim_SetResultString(interp, "procedure has argument with too many fields", -1);
3628 goto err;
3631 if (len == 2) {
3632 /* Optional parameter */
3633 Jim_ListIndex(interp, argPtr, 0, &nameObjPtr, JIM_NONE);
3634 Jim_ListIndex(interp, argPtr, 1, &defaultObjPtr, JIM_NONE);
3636 else {
3637 /* Required parameter */
3638 nameObjPtr = argPtr;
3639 defaultObjPtr = NULL;
3643 if (Jim_CompareStringImmediate(interp, nameObjPtr, "args")) {
3644 if (cmdPtr->u.proc.argsPos >= 0) {
3645 Jim_SetResultString(interp, "procedure has 'args' specified more than once", -1);
3646 goto err;
3648 cmdPtr->u.proc.argsPos = i;
3650 else {
3651 if (len == 2) {
3652 cmdPtr->u.proc.optArity += n;
3654 else {
3655 cmdPtr->u.proc.reqArity += n;
3659 cmdPtr->u.proc.arglist[i].nameObjPtr = nameObjPtr;
3660 cmdPtr->u.proc.arglist[i].defaultObjPtr = defaultObjPtr;
3663 /* Add the new command */
3665 /* It may already exist, so we try to delete the old one.
3666 * Note that reference count means that it won't be deleted yet if
3667 * it exists in the call stack.
3669 * BUT, if 'local' is in force, instead of deleting the existing
3670 * proc, we stash a reference to the old proc here.
3672 he = Jim_FindHashEntry(&interp->commands, Jim_String(cmdName));
3673 if (he) {
3674 /* There was an old procedure with the same name, this requires
3675 * a 'proc epoch' update. */
3677 /* If a procedure with the same name didn't existed there is no need
3678 * to increment the 'proc epoch' because creation of a new procedure
3679 * can never affect existing cached commands. We don't do
3680 * negative caching. */
3681 Jim_InterpIncrProcEpoch(interp);
3684 if (he && interp->local) {
3685 /* Just push this proc over the top of the previous one */
3686 cmdPtr->u.proc.prevCmd = he->u.val;
3687 he->u.val = cmdPtr;
3689 else {
3690 if (he) {
3691 /* Replace the existing proc */
3692 Jim_DeleteHashEntry(&interp->commands, Jim_String(cmdName));
3695 Jim_AddHashEntry(&interp->commands, Jim_String(cmdName), cmdPtr);
3698 /* Unlike Tcl, set the name of the proc as the result */
3699 Jim_SetResult(interp, cmdName);
3700 return JIM_OK;
3702 err:
3703 if (cmdPtr->u.proc.staticVars) {
3704 Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
3706 Jim_Free(cmdPtr->u.proc.staticVars);
3707 Jim_DecrRefCount(interp, argListObjPtr);
3708 Jim_DecrRefCount(interp, bodyObjPtr);
3709 Jim_Free(cmdPtr);
3710 return JIM_ERR;
3713 int Jim_DeleteCommand(Jim_Interp *interp, const char *cmdName)
3715 if (Jim_DeleteHashEntry(&interp->commands, cmdName) == JIM_ERR)
3716 return JIM_ERR;
3717 Jim_InterpIncrProcEpoch(interp);
3718 return JIM_OK;
3721 int Jim_RenameCommand(Jim_Interp *interp, const char *oldName, const char *newName)
3723 Jim_HashEntry *he;
3725 /* Does it exist? */
3726 he = Jim_FindHashEntry(&interp->commands, oldName);
3727 if (he == NULL) {
3728 Jim_SetResultFormatted(interp, "can't %s \"%s\": command doesn't exist",
3729 newName[0] ? "rename" : "delete", oldName);
3730 return JIM_ERR;
3733 if (newName[0] == '\0') /* Delete! */
3734 return Jim_DeleteCommand(interp, oldName);
3736 /* rename */
3737 if (Jim_FindHashEntry(&interp->commands, newName)) {
3738 Jim_SetResultFormatted(interp, "can't rename to \"%s\": command already exists", newName);
3739 return JIM_ERR;
3742 /* Add the new name first */
3743 JimIncrCmdRefCount(he->u.val);
3744 Jim_AddHashEntry(&interp->commands, newName, he->u.val);
3746 /* Now remove the old name */
3747 Jim_DeleteHashEntry(&interp->commands, oldName);
3749 /* Increment the epoch */
3750 Jim_InterpIncrProcEpoch(interp);
3751 return JIM_OK;
3754 /* -----------------------------------------------------------------------------
3755 * Command object
3756 * ---------------------------------------------------------------------------*/
3758 static int SetCommandFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3760 static const Jim_ObjType commandObjType = {
3761 "command",
3762 NULL,
3763 NULL,
3764 NULL,
3765 JIM_TYPE_REFERENCES,
3768 int SetCommandFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
3770 Jim_HashEntry *he;
3771 const char *cmdName;
3773 /* Get the string representation */
3774 cmdName = Jim_String(objPtr);
3775 /* Lookup this name into the commands hash table */
3776 he = Jim_FindHashEntry(&interp->commands, cmdName);
3777 if (he == NULL)
3778 return JIM_ERR;
3780 /* Free the old internal repr and set the new one. */
3781 Jim_FreeIntRep(interp, objPtr);
3782 objPtr->typePtr = &commandObjType;
3783 objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
3784 objPtr->internalRep.cmdValue.cmdPtr = (void *)he->u.val;
3785 return JIM_OK;
3788 /* This function returns the command structure for the command name
3789 * stored in objPtr. It tries to specialize the objPtr to contain
3790 * a cached info instead to perform the lookup into the hash table
3791 * every time. The information cached may not be uptodate, in such
3792 * a case the lookup is performed and the cache updated.
3794 * Respects the 'upcall' setting
3796 Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
3798 Jim_Cmd *cmd;
3800 if ((objPtr->typePtr != &commandObjType ||
3801 objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch) &&
3802 SetCommandFromAny(interp, objPtr) == JIM_ERR) {
3803 if (flags & JIM_ERRMSG) {
3804 Jim_SetResultFormatted(interp, "invalid command name \"%#s\"", objPtr);
3806 return NULL;
3808 cmd = objPtr->internalRep.cmdValue.cmdPtr;
3809 while (cmd->isproc && cmd->u.proc.upcall) {
3810 cmd = cmd->u.proc.prevCmd;
3812 return cmd;
3815 /* -----------------------------------------------------------------------------
3816 * Variables
3817 * ---------------------------------------------------------------------------*/
3819 /* Variables HashTable Type.
3821 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3822 static void JimVariablesHTValDestructor(void *interp, void *val)
3824 Jim_Var *varPtr = (void *)val;
3826 Jim_DecrRefCount(interp, varPtr->objPtr);
3827 Jim_Free(val);
3830 static const Jim_HashTableType JimVariablesHashTableType = {
3831 JimStringCopyHTHashFunction, /* hash function */
3832 JimStringCopyHTKeyDup, /* key dup */
3833 NULL, /* val dup */
3834 JimStringCopyHTKeyCompare, /* key compare */
3835 JimStringCopyHTKeyDestructor, /* key destructor */
3836 JimVariablesHTValDestructor /* val destructor */
3839 /* -----------------------------------------------------------------------------
3840 * Variable object
3841 * ---------------------------------------------------------------------------*/
3843 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3845 static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3847 static const Jim_ObjType variableObjType = {
3848 "variable",
3849 NULL,
3850 NULL,
3851 NULL,
3852 JIM_TYPE_REFERENCES,
3855 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3856 * is in the form "varname(key)". */
3857 static int JimNameIsDictSugar(const char *str, int len)
3859 if (len && str[len - 1] == ')' && strchr(str, '(') != NULL)
3860 return 1;
3861 return 0;
3865 * Check that the name does not contain embedded nulls.
3867 * Variable and procedure names are maniplated as null terminated strings, so
3868 * don't allow names with embedded nulls.
3870 static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr)
3872 /* Variable names and proc names can't contain embedded nulls */
3873 if (nameObjPtr->typePtr != &variableObjType) {
3874 int len;
3875 const char *str = Jim_GetString(nameObjPtr, &len);
3876 if (memchr(str, '\0', len)) {
3877 Jim_SetResultFormatted(interp, "%s name contains embedded null", type);
3878 return JIM_ERR;
3881 return JIM_OK;
3884 /* This method should be called only by the variable API.
3885 * It returns JIM_OK on success (variable already exists),
3886 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3887 * a variable name, but syntax glue for [dict] i.e. the last
3888 * character is ')' */
3889 static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
3891 Jim_HashEntry *he;
3892 const char *varName;
3893 int len;
3894 Jim_CallFrame *framePtr = interp->framePtr;
3896 /* Check if the object is already an uptodate variable */
3897 if (objPtr->typePtr == &variableObjType &&
3898 objPtr->internalRep.varValue.callFrameId == framePtr->id) {
3899 return JIM_OK; /* nothing to do */
3902 if (objPtr->typePtr == &dictSubstObjType) {
3903 return JIM_DICT_SUGAR;
3906 if (JimValidName(interp, "variable", objPtr) != JIM_OK) {
3907 return JIM_ERR;
3910 /* Get the string representation */
3911 varName = Jim_GetString(objPtr, &len);
3913 /* Make sure it's not syntax glue to get/set dict. */
3914 if (JimNameIsDictSugar(varName, len)) {
3915 return JIM_DICT_SUGAR;
3918 if (varName[0] == ':' && varName[1] == ':') {
3919 framePtr = interp->topFramePtr;
3920 he = Jim_FindHashEntry(&framePtr->vars, varName + 2);
3921 if (he == NULL) {
3922 return JIM_ERR;
3925 else {
3926 /* Lookup this name into the variables hash table */
3927 he = Jim_FindHashEntry(&framePtr->vars, varName);
3928 if (he == NULL) {
3929 /* Try with static vars. */
3930 if (framePtr->staticVars == NULL)
3931 return JIM_ERR;
3932 if (!(he = Jim_FindHashEntry(framePtr->staticVars, varName)))
3933 return JIM_ERR;
3936 /* Free the old internal repr and set the new one. */
3937 Jim_FreeIntRep(interp, objPtr);
3938 objPtr->typePtr = &variableObjType;
3939 objPtr->internalRep.varValue.callFrameId = framePtr->id;
3940 objPtr->internalRep.varValue.varPtr = (void *)he->u.val;
3941 return JIM_OK;
3944 /* -------------------- Variables related functions ------------------------- */
3945 static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr, Jim_Obj *valObjPtr);
3946 static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr, int flags);
3948 /* For now that's dummy. Variables lookup should be optimized
3949 * in many ways, with caching of lookups, and possibly with
3950 * a table of pre-allocated vars in every CallFrame for local vars.
3951 * All the caching should also have an 'epoch' mechanism similar
3952 * to the one used by Tcl for procedures lookup caching. */
3954 int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
3956 const char *name;
3957 Jim_Var *var;
3958 int err;
3960 if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {
3961 Jim_CallFrame *framePtr = interp->framePtr;
3963 /* Check for [dict] syntax sugar. */
3964 if (err == JIM_DICT_SUGAR)
3965 return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
3967 if (JimValidName(interp, "variable", nameObjPtr) != JIM_OK) {
3968 return JIM_ERR;
3971 /* New variable to create */
3972 name = Jim_String(nameObjPtr);
3974 var = Jim_Alloc(sizeof(*var));
3975 var->objPtr = valObjPtr;
3976 Jim_IncrRefCount(valObjPtr);
3977 var->linkFramePtr = NULL;
3978 /* Insert the new variable */
3979 if (name[0] == ':' && name[1] == ':') {
3980 /* Into the top level frame */
3981 framePtr = interp->topFramePtr;
3982 Jim_AddHashEntry(&framePtr->vars, name + 2, var);
3984 else {
3985 Jim_AddHashEntry(&framePtr->vars, name, var);
3987 /* Make the object int rep a variable */
3988 Jim_FreeIntRep(interp, nameObjPtr);
3989 nameObjPtr->typePtr = &variableObjType;
3990 nameObjPtr->internalRep.varValue.callFrameId = framePtr->id;
3991 nameObjPtr->internalRep.varValue.varPtr = var;
3993 else {
3994 var = nameObjPtr->internalRep.varValue.varPtr;
3995 if (var->linkFramePtr == NULL) {
3996 Jim_IncrRefCount(valObjPtr);
3997 Jim_DecrRefCount(interp, var->objPtr);
3998 var->objPtr = valObjPtr;
4000 else { /* Else handle the link */
4001 Jim_CallFrame *savedCallFrame;
4003 savedCallFrame = interp->framePtr;
4004 interp->framePtr = var->linkFramePtr;
4005 err = Jim_SetVariable(interp, var->objPtr, valObjPtr);
4006 interp->framePtr = savedCallFrame;
4007 if (err != JIM_OK)
4008 return err;
4011 return JIM_OK;
4014 int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
4016 Jim_Obj *nameObjPtr;
4017 int result;
4019 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4020 Jim_IncrRefCount(nameObjPtr);
4021 result = Jim_SetVariable(interp, nameObjPtr, objPtr);
4022 Jim_DecrRefCount(interp, nameObjPtr);
4023 return result;
4026 int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
4028 Jim_CallFrame *savedFramePtr;
4029 int result;
4031 savedFramePtr = interp->framePtr;
4032 interp->framePtr = interp->topFramePtr;
4033 result = Jim_SetVariableStr(interp, name, objPtr);
4034 interp->framePtr = savedFramePtr;
4035 return result;
4038 int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
4040 Jim_Obj *nameObjPtr, *valObjPtr;
4041 int result;
4043 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4044 valObjPtr = Jim_NewStringObj(interp, val, -1);
4045 Jim_IncrRefCount(nameObjPtr);
4046 Jim_IncrRefCount(valObjPtr);
4047 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4048 Jim_DecrRefCount(interp, nameObjPtr);
4049 Jim_DecrRefCount(interp, valObjPtr);
4050 return result;
4053 int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
4054 Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
4056 const char *varName;
4057 int len;
4059 varName = Jim_GetString(nameObjPtr, &len);
4061 if (varName[0] == ':' && varName[1] == ':') {
4062 /* Linking a global var does nothing */
4063 return JIM_OK;
4066 if (JimNameIsDictSugar(varName, len)) {
4067 Jim_SetResultString(interp, "Dict key syntax invalid as link source", -1);
4068 return JIM_ERR;
4071 /* Check for an existing variable or link */
4072 if (SetVariableFromAny(interp, nameObjPtr) == JIM_OK) {
4073 Jim_Var *varPtr = nameObjPtr->internalRep.varValue.varPtr;
4075 if (varPtr->linkFramePtr == NULL) {
4076 Jim_SetResultFormatted(interp, "variable \"%#s\" already exists", nameObjPtr);
4077 return JIM_ERR;
4080 /* It exists, but is a link, so delete the link */
4081 varPtr->linkFramePtr = NULL;
4084 /* Check for cycles. */
4085 if (interp->framePtr == targetCallFrame) {
4086 Jim_Obj *objPtr = targetNameObjPtr;
4087 Jim_Var *varPtr;
4089 /* Cycles are only possible with 'uplevel 0' */
4090 while (1) {
4091 if (Jim_StringEqObj(objPtr, nameObjPtr)) {
4092 Jim_SetResultString(interp, "can't upvar from variable to itself", -1);
4093 return JIM_ERR;
4095 if (SetVariableFromAny(interp, objPtr) != JIM_OK)
4096 break;
4097 varPtr = objPtr->internalRep.varValue.varPtr;
4098 if (varPtr->linkFramePtr != targetCallFrame)
4099 break;
4100 objPtr = varPtr->objPtr;
4104 /* Perform the binding */
4105 Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
4106 /* We are now sure 'nameObjPtr' type is variableObjType */
4107 nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;
4108 return JIM_OK;
4111 /* Return the Jim_Obj pointer associated with a variable name,
4112 * or NULL if the variable was not found in the current context.
4113 * The same optimization discussed in the comment to the
4114 * 'SetVariable' function should apply here.
4116 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4117 * in a dictionary which is shared, the array variable value is duplicated first.
4118 * This allows the array element to be updated (e.g. append, lappend) without
4119 * affecting other references to the dictionary.
4121 Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4123 switch (SetVariableFromAny(interp, nameObjPtr)) {
4124 case JIM_OK:{
4125 Jim_Var *varPtr = nameObjPtr->internalRep.varValue.varPtr;
4127 if (varPtr->linkFramePtr == NULL) {
4128 return varPtr->objPtr;
4130 else {
4131 Jim_Obj *objPtr;
4133 /* The variable is a link? Resolve it. */
4134 Jim_CallFrame *savedCallFrame = interp->framePtr;
4136 interp->framePtr = varPtr->linkFramePtr;
4137 objPtr = Jim_GetVariable(interp, varPtr->objPtr, flags);
4138 interp->framePtr = savedCallFrame;
4139 if (objPtr) {
4140 return objPtr;
4142 /* Error, so fall through to the error message */
4145 break;
4147 case JIM_DICT_SUGAR:
4148 /* [dict] syntax sugar. */
4149 return JimDictSugarGet(interp, nameObjPtr, flags);
4151 if (flags & JIM_ERRMSG) {
4152 Jim_SetResultFormatted(interp, "can't read \"%#s\": no such variable", nameObjPtr);
4154 return NULL;
4157 Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4159 Jim_CallFrame *savedFramePtr;
4160 Jim_Obj *objPtr;
4162 savedFramePtr = interp->framePtr;
4163 interp->framePtr = interp->topFramePtr;
4164 objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
4165 interp->framePtr = savedFramePtr;
4167 return objPtr;
4170 Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
4172 Jim_Obj *nameObjPtr, *varObjPtr;
4174 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4175 Jim_IncrRefCount(nameObjPtr);
4176 varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
4177 Jim_DecrRefCount(interp, nameObjPtr);
4178 return varObjPtr;
4181 Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name, int flags)
4183 Jim_CallFrame *savedFramePtr;
4184 Jim_Obj *objPtr;
4186 savedFramePtr = interp->framePtr;
4187 interp->framePtr = interp->topFramePtr;
4188 objPtr = Jim_GetVariableStr(interp, name, flags);
4189 interp->framePtr = savedFramePtr;
4191 return objPtr;
4194 /* Unset a variable.
4195 * Note: On success unset invalidates all the variable objects created
4196 * in the current call frame incrementing. */
4197 int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4199 const char *name;
4200 Jim_Var *varPtr;
4201 int retval;
4203 retval = SetVariableFromAny(interp, nameObjPtr);
4204 if (retval == JIM_DICT_SUGAR) {
4205 /* [dict] syntax sugar. */
4206 return JimDictSugarSet(interp, nameObjPtr, NULL);
4208 else if (retval == JIM_OK) {
4209 varPtr = nameObjPtr->internalRep.varValue.varPtr;
4211 /* If it's a link call UnsetVariable recursively */
4212 if (varPtr->linkFramePtr) {
4213 Jim_CallFrame *savedCallFrame;
4215 savedCallFrame = interp->framePtr;
4216 interp->framePtr = varPtr->linkFramePtr;
4217 retval = Jim_UnsetVariable(interp, varPtr->objPtr, JIM_NONE);
4218 interp->framePtr = savedCallFrame;
4220 else {
4221 Jim_CallFrame *framePtr = interp->framePtr;
4223 name = Jim_String(nameObjPtr);
4224 if (name[0] == ':' && name[1] == ':') {
4225 framePtr = interp->topFramePtr;
4226 name += 2;
4228 retval = Jim_DeleteHashEntry(&framePtr->vars, name);
4229 if (retval == JIM_OK) {
4230 /* Change the callframe id, invalidating var lookup caching */
4231 JimChangeCallFrameId(interp, framePtr);
4235 if (retval != JIM_OK && (flags & JIM_ERRMSG)) {
4236 Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such variable", nameObjPtr);
4238 return retval;
4241 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4243 /* Given a variable name for [dict] operation syntax sugar,
4244 * this function returns two objects, the first with the name
4245 * of the variable to set, and the second with the rispective key.
4246 * For example "foo(bar)" will return objects with string repr. of
4247 * "foo" and "bar".
4249 * The returned objects have refcount = 1. The function can't fail. */
4250 static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
4251 Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
4253 const char *str, *p;
4254 int len, keyLen;
4255 Jim_Obj *varObjPtr, *keyObjPtr;
4257 str = Jim_GetString(objPtr, &len);
4259 p = strchr(str, '(');
4260 JimPanic((p == NULL, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str));
4262 varObjPtr = Jim_NewStringObj(interp, str, p - str);
4264 p++;
4265 keyLen = (str + len) - p;
4266 if (str[len - 1] == ')') {
4267 keyLen--;
4270 /* Create the objects with the variable name and key. */
4271 keyObjPtr = Jim_NewStringObj(interp, p, keyLen);
4273 Jim_IncrRefCount(varObjPtr);
4274 Jim_IncrRefCount(keyObjPtr);
4275 *varPtrPtr = varObjPtr;
4276 *keyPtrPtr = keyObjPtr;
4279 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4280 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4281 static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *valObjPtr)
4283 int err;
4285 SetDictSubstFromAny(interp, objPtr);
4287 err = Jim_SetDictKeysVector(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
4288 &objPtr->internalRep.dictSubstValue.indexObjPtr, 1, valObjPtr, JIM_ERRMSG);
4290 if (err == JIM_OK) {
4291 /* Don't keep an extra ref to the result */
4292 Jim_SetEmptyResult(interp);
4294 else {
4295 if (!valObjPtr) {
4296 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4297 if (Jim_GetVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_NONE)) {
4298 Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such element in array",
4299 objPtr);
4300 return err;
4303 /* Make the error more informative and Tcl-compatible */
4304 Jim_SetResultFormatted(interp, "can't %s \"%#s\": variable isn't array",
4305 (valObjPtr ? "set" : "unset"), objPtr);
4307 return err;
4311 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4313 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4314 * and stored back to the variable before expansion.
4316 static Jim_Obj *JimDictExpandArrayVariable(Jim_Interp *interp, Jim_Obj *varObjPtr,
4317 Jim_Obj *keyObjPtr, int flags)
4319 Jim_Obj *dictObjPtr;
4320 Jim_Obj *resObjPtr = NULL;
4321 int ret;
4323 dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
4324 if (!dictObjPtr) {
4325 return NULL;
4328 ret = Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
4329 if (ret != JIM_OK) {
4330 resObjPtr = NULL;
4331 if (ret < 0) {
4332 Jim_SetResultFormatted(interp,
4333 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr, keyObjPtr);
4335 else {
4336 Jim_SetResultFormatted(interp,
4337 "can't read \"%#s(%#s)\": no such element in array", varObjPtr, keyObjPtr);
4340 else if ((flags & JIM_UNSHARED) && Jim_IsShared(dictObjPtr)) {
4341 dictObjPtr = Jim_DuplicateObj(interp, dictObjPtr);
4342 if (Jim_SetVariable(interp, varObjPtr, dictObjPtr) != JIM_OK) {
4343 /* This can probably never happen */
4344 JimPanic((1, "SetVariable failed for JIM_UNSHARED"));
4346 /* We know that the key exists. Get the result in the now-unshared dictionary */
4347 Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
4350 return resObjPtr;
4353 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4354 static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
4356 SetDictSubstFromAny(interp, objPtr);
4358 return JimDictExpandArrayVariable(interp,
4359 objPtr->internalRep.dictSubstValue.varNameObjPtr,
4360 objPtr->internalRep.dictSubstValue.indexObjPtr, flags);
4363 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4365 void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
4367 Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
4368 Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
4371 void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
4373 JIM_NOTUSED(interp);
4375 dupPtr->internalRep.dictSubstValue.varNameObjPtr =
4376 srcPtr->internalRep.dictSubstValue.varNameObjPtr;
4377 dupPtr->internalRep.dictSubstValue.indexObjPtr = srcPtr->internalRep.dictSubstValue.indexObjPtr;
4378 dupPtr->typePtr = &dictSubstObjType;
4381 /* Note: The object *must* be in dict-sugar format */
4382 static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
4384 if (objPtr->typePtr != &dictSubstObjType) {
4385 Jim_Obj *varObjPtr, *keyObjPtr;
4387 if (objPtr->typePtr == &interpolatedObjType) {
4388 /* An interpolated object in dict-sugar form */
4390 const ScriptToken *token = objPtr->internalRep.twoPtrValue.ptr1;
4392 varObjPtr = token[0].objPtr;
4393 keyObjPtr = objPtr->internalRep.twoPtrValue.ptr2;
4395 Jim_IncrRefCount(varObjPtr);
4396 Jim_IncrRefCount(keyObjPtr);
4398 else {
4399 JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
4402 Jim_FreeIntRep(interp, objPtr);
4403 objPtr->typePtr = &dictSubstObjType;
4404 objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
4405 objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
4409 /* This function is used to expand [dict get] sugar in the form
4410 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4411 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4412 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4413 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4414 * the [dict]ionary contained in variable VARNAME. */
4415 static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
4417 Jim_Obj *resObjPtr = NULL;
4418 Jim_Obj *substKeyObjPtr = NULL;
4420 SetDictSubstFromAny(interp, objPtr);
4422 if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
4423 &substKeyObjPtr, JIM_NONE)
4424 != JIM_OK) {
4425 return NULL;
4427 Jim_IncrRefCount(substKeyObjPtr);
4428 resObjPtr =
4429 JimDictExpandArrayVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
4430 substKeyObjPtr, 0);
4431 Jim_DecrRefCount(interp, substKeyObjPtr);
4433 return resObjPtr;
4436 static Jim_Obj *JimExpandExprSugar(Jim_Interp *interp, Jim_Obj *objPtr)
4438 Jim_Obj *resultObjPtr;
4440 if (Jim_EvalExpression(interp, objPtr, &resultObjPtr) == JIM_OK) {
4441 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4442 resultObjPtr->refCount--;
4443 return resultObjPtr;
4445 return NULL;
4448 /* -----------------------------------------------------------------------------
4449 * CallFrame
4450 * ---------------------------------------------------------------------------*/
4452 static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp, Jim_CallFrame *parent)
4454 Jim_CallFrame *cf;
4456 if (interp->freeFramesList) {
4457 cf = interp->freeFramesList;
4458 interp->freeFramesList = cf->nextFramePtr;
4460 else {
4461 cf = Jim_Alloc(sizeof(*cf));
4462 cf->vars.table = NULL;
4465 cf->id = interp->callFrameEpoch++;
4466 cf->parentCallFrame = parent;
4467 cf->level = parent ? parent->level + 1 : 0;
4468 cf->argv = NULL;
4469 cf->argc = 0;
4470 cf->procArgsObjPtr = NULL;
4471 cf->procBodyObjPtr = NULL;
4472 cf->nextFramePtr = NULL;
4473 cf->staticVars = NULL;
4474 if (cf->vars.table == NULL)
4475 Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
4476 return cf;
4479 /* Used to invalidate every caching related to callframe stability. */
4480 static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf)
4482 cf->id = interp->callFrameEpoch++;
4485 #define JIM_FCF_NONE 0 /* no flags */
4486 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4487 static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags)
4489 if (cf->procArgsObjPtr)
4490 Jim_DecrRefCount(interp, cf->procArgsObjPtr);
4491 if (cf->procBodyObjPtr)
4492 Jim_DecrRefCount(interp, cf->procBodyObjPtr);
4493 if (!(flags & JIM_FCF_NOHT))
4494 Jim_FreeHashTable(&cf->vars);
4495 else {
4496 int i;
4497 Jim_HashEntry **table = cf->vars.table, *he;
4499 for (i = 0; i < JIM_HT_INITIAL_SIZE; i++) {
4500 he = table[i];
4501 while (he != NULL) {
4502 Jim_HashEntry *nextEntry = he->next;
4503 Jim_Var *varPtr = (void *)he->u.val;
4505 Jim_DecrRefCount(interp, varPtr->objPtr);
4506 Jim_Free(he->u.val);
4507 Jim_Free((void *)he->key); /* ATTENTION: const cast */
4508 Jim_Free(he);
4509 table[i] = NULL;
4510 he = nextEntry;
4513 cf->vars.used = 0;
4515 cf->nextFramePtr = interp->freeFramesList;
4516 interp->freeFramesList = cf;
4519 /* -----------------------------------------------------------------------------
4520 * References
4521 * ---------------------------------------------------------------------------*/
4522 #ifdef JIM_REFERENCES
4524 /* References HashTable Type.
4526 * Keys are jim_wide integers, dynamically allocated for now but in the
4527 * future it's worth to cache this 8 bytes objects. Values are poitners
4528 * to Jim_References. */
4529 static void JimReferencesHTValDestructor(void *interp, void *val)
4531 Jim_Reference *refPtr = (void *)val;
4533 Jim_DecrRefCount(interp, refPtr->objPtr);
4534 if (refPtr->finalizerCmdNamePtr != NULL) {
4535 Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
4537 Jim_Free(val);
4540 static unsigned int JimReferencesHTHashFunction(const void *key)
4542 /* Only the least significant bits are used. */
4543 const jim_wide *widePtr = key;
4544 unsigned int intValue = (unsigned int)*widePtr;
4546 return Jim_IntHashFunction(intValue);
4549 static const void *JimReferencesHTKeyDup(void *privdata, const void *key)
4551 void *copy = Jim_Alloc(sizeof(jim_wide));
4553 JIM_NOTUSED(privdata);
4555 memcpy(copy, key, sizeof(jim_wide));
4556 return copy;
4559 static int JimReferencesHTKeyCompare(void *privdata, const void *key1, const void *key2)
4561 JIM_NOTUSED(privdata);
4563 return memcmp(key1, key2, sizeof(jim_wide)) == 0;
4566 static void JimReferencesHTKeyDestructor(void *privdata, const void *key)
4568 JIM_NOTUSED(privdata);
4570 Jim_Free((void *)key);
4573 static const Jim_HashTableType JimReferencesHashTableType = {
4574 JimReferencesHTHashFunction, /* hash function */
4575 JimReferencesHTKeyDup, /* key dup */
4576 NULL, /* val dup */
4577 JimReferencesHTKeyCompare, /* key compare */
4578 JimReferencesHTKeyDestructor, /* key destructor */
4579 JimReferencesHTValDestructor /* val destructor */
4582 /* -----------------------------------------------------------------------------
4583 * Reference object type and References API
4584 * ---------------------------------------------------------------------------*/
4586 /* The string representation of references has two features in order
4587 * to make the GC faster. The first is that every reference starts
4588 * with a non common character '<', in order to make the string matching
4589 * faster. The second is that the reference string rep is 42 characters
4590 * in length, this allows to avoid to check every object with a string
4591 * repr < 42, and usually there aren't many of these objects. */
4593 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4595 static int JimFormatReference(char *buf, Jim_Reference *refPtr, jim_wide id)
4597 const char *fmt = "<reference.<%s>.%020" JIM_WIDE_MODIFIER ">";
4599 sprintf(buf, fmt, refPtr->tag, id);
4600 return JIM_REFERENCE_SPACE;
4603 static void UpdateStringOfReference(struct Jim_Obj *objPtr);
4605 static const Jim_ObjType referenceObjType = {
4606 "reference",
4607 NULL,
4608 NULL,
4609 UpdateStringOfReference,
4610 JIM_TYPE_REFERENCES,
4613 void UpdateStringOfReference(struct Jim_Obj *objPtr)
4615 int len;
4616 char buf[JIM_REFERENCE_SPACE + 1];
4617 Jim_Reference *refPtr;
4619 refPtr = objPtr->internalRep.refValue.refPtr;
4620 len = JimFormatReference(buf, refPtr, objPtr->internalRep.refValue.id);
4621 objPtr->bytes = Jim_Alloc(len + 1);
4622 memcpy(objPtr->bytes, buf, len + 1);
4623 objPtr->length = len;
4626 /* returns true if 'c' is a valid reference tag character.
4627 * i.e. inside the range [_a-zA-Z0-9] */
4628 static int isrefchar(int c)
4630 return (c == '_' || isalnum(c));
4633 static int SetReferenceFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
4635 jim_wide wideValue;
4636 int i, len;
4637 const char *str, *start, *end;
4638 char refId[21];
4639 Jim_Reference *refPtr;
4640 Jim_HashEntry *he;
4642 /* Get the string representation */
4643 str = Jim_GetString(objPtr, &len);
4644 /* Check if it looks like a reference */
4645 if (len < JIM_REFERENCE_SPACE)
4646 goto badformat;
4647 /* Trim spaces */
4648 start = str;
4649 end = str + len - 1;
4650 while (*start == ' ')
4651 start++;
4652 while (*end == ' ' && end > start)
4653 end--;
4654 if (end - start + 1 != JIM_REFERENCE_SPACE)
4655 goto badformat;
4656 /* <reference.<1234567>.%020> */
4657 if (memcmp(start, "<reference.<", 12) != 0)
4658 goto badformat;
4659 if (start[12 + JIM_REFERENCE_TAGLEN] != '>' || end[0] != '>')
4660 goto badformat;
4661 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4662 for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
4663 if (!isrefchar(start[12 + i]))
4664 goto badformat;
4666 /* Extract info from the reference. */
4667 memcpy(refId, start + 14 + JIM_REFERENCE_TAGLEN, 20);
4668 refId[20] = '\0';
4669 /* Try to convert the ID into a jim_wide */
4670 if (Jim_StringToWide(refId, &wideValue, 10) != JIM_OK)
4671 goto badformat;
4672 /* Check if the reference really exists! */
4673 he = Jim_FindHashEntry(&interp->references, &wideValue);
4674 if (he == NULL) {
4675 Jim_SetResultFormatted(interp, "invalid reference id \"%#s\"", objPtr);
4676 return JIM_ERR;
4678 refPtr = he->u.val;
4679 /* Free the old internal repr and set the new one. */
4680 Jim_FreeIntRep(interp, objPtr);
4681 objPtr->typePtr = &referenceObjType;
4682 objPtr->internalRep.refValue.id = wideValue;
4683 objPtr->internalRep.refValue.refPtr = refPtr;
4684 return JIM_OK;
4686 badformat:
4687 Jim_SetResultFormatted(interp, "expected reference but got \"%#s\"", objPtr);
4688 return JIM_ERR;
4691 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4692 * as finalizer command (or NULL if there is no finalizer).
4693 * The returned reference object has refcount = 0. */
4694 Jim_Obj *Jim_NewReference(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr)
4696 struct Jim_Reference *refPtr;
4697 jim_wide wideValue = interp->referenceNextId;
4698 Jim_Obj *refObjPtr;
4699 const char *tag;
4700 int tagLen, i;
4702 /* Perform the Garbage Collection if needed. */
4703 Jim_CollectIfNeeded(interp);
4705 refPtr = Jim_Alloc(sizeof(*refPtr));
4706 refPtr->objPtr = objPtr;
4707 Jim_IncrRefCount(objPtr);
4708 refPtr->finalizerCmdNamePtr = cmdNamePtr;
4709 if (cmdNamePtr)
4710 Jim_IncrRefCount(cmdNamePtr);
4711 Jim_AddHashEntry(&interp->references, &wideValue, refPtr);
4712 refObjPtr = Jim_NewObj(interp);
4713 refObjPtr->typePtr = &referenceObjType;
4714 refObjPtr->bytes = NULL;
4715 refObjPtr->internalRep.refValue.id = interp->referenceNextId;
4716 refObjPtr->internalRep.refValue.refPtr = refPtr;
4717 interp->referenceNextId++;
4718 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4719 * that does not pass the 'isrefchar' test is replaced with '_' */
4720 tag = Jim_GetString(tagPtr, &tagLen);
4721 if (tagLen > JIM_REFERENCE_TAGLEN)
4722 tagLen = JIM_REFERENCE_TAGLEN;
4723 for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
4724 if (i < tagLen && isrefchar(tag[i]))
4725 refPtr->tag[i] = tag[i];
4726 else
4727 refPtr->tag[i] = '_';
4729 refPtr->tag[JIM_REFERENCE_TAGLEN] = '\0';
4730 return refObjPtr;
4733 Jim_Reference *Jim_GetReference(Jim_Interp *interp, Jim_Obj *objPtr)
4735 if (objPtr->typePtr != &referenceObjType && SetReferenceFromAny(interp, objPtr) == JIM_ERR)
4736 return NULL;
4737 return objPtr->internalRep.refValue.refPtr;
4740 int Jim_SetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr)
4742 Jim_Reference *refPtr;
4744 if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
4745 return JIM_ERR;
4746 Jim_IncrRefCount(cmdNamePtr);
4747 if (refPtr->finalizerCmdNamePtr)
4748 Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
4749 refPtr->finalizerCmdNamePtr = cmdNamePtr;
4750 return JIM_OK;
4753 int Jim_GetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr)
4755 Jim_Reference *refPtr;
4757 if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
4758 return JIM_ERR;
4759 *cmdNamePtrPtr = refPtr->finalizerCmdNamePtr;
4760 return JIM_OK;
4763 /* -----------------------------------------------------------------------------
4764 * References Garbage Collection
4765 * ---------------------------------------------------------------------------*/
4767 /* This the hash table type for the "MARK" phase of the GC */
4768 static const Jim_HashTableType JimRefMarkHashTableType = {
4769 JimReferencesHTHashFunction, /* hash function */
4770 JimReferencesHTKeyDup, /* key dup */
4771 NULL, /* val dup */
4772 JimReferencesHTKeyCompare, /* key compare */
4773 JimReferencesHTKeyDestructor, /* key destructor */
4774 NULL /* val destructor */
4777 /* Performs the garbage collection. */
4778 int Jim_Collect(Jim_Interp *interp)
4780 int collected = 0;
4781 #ifndef JIM_BOOTSTRAP
4782 Jim_HashTable marks;
4783 Jim_HashTableIterator *htiter;
4784 Jim_HashEntry *he;
4785 Jim_Obj *objPtr;
4787 /* Avoid recursive calls */
4788 if (interp->lastCollectId == -1) {
4789 /* Jim_Collect() already running. Return just now. */
4790 return 0;
4792 interp->lastCollectId = -1;
4794 /* Mark all the references found into the 'mark' hash table.
4795 * The references are searched in every live object that
4796 * is of a type that can contain references. */
4797 Jim_InitHashTable(&marks, &JimRefMarkHashTableType, NULL);
4798 objPtr = interp->liveList;
4799 while (objPtr) {
4800 if (objPtr->typePtr == NULL || objPtr->typePtr->flags & JIM_TYPE_REFERENCES) {
4801 const char *str, *p;
4802 int len;
4804 /* If the object is of type reference, to get the
4805 * Id is simple... */
4806 if (objPtr->typePtr == &referenceObjType) {
4807 Jim_AddHashEntry(&marks, &objPtr->internalRep.refValue.id, NULL);
4808 #ifdef JIM_DEBUG_GC
4809 printf("MARK (reference): %d refcount: %d" JIM_NL,
4810 (int)objPtr->internalRep.refValue.id, objPtr->refCount);
4811 #endif
4812 objPtr = objPtr->nextObjPtr;
4813 continue;
4815 /* Get the string repr of the object we want
4816 * to scan for references. */
4817 p = str = Jim_GetString(objPtr, &len);
4818 /* Skip objects too little to contain references. */
4819 if (len < JIM_REFERENCE_SPACE) {
4820 objPtr = objPtr->nextObjPtr;
4821 continue;
4823 /* Extract references from the object string repr. */
4824 while (1) {
4825 int i;
4826 jim_wide id;
4827 char buf[21];
4829 if ((p = strstr(p, "<reference.<")) == NULL)
4830 break;
4831 /* Check if it's a valid reference. */
4832 if (len - (p - str) < JIM_REFERENCE_SPACE)
4833 break;
4834 if (p[41] != '>' || p[19] != '>' || p[20] != '.')
4835 break;
4836 for (i = 21; i <= 40; i++)
4837 if (!isdigit(UCHAR(p[i])))
4838 break;
4839 /* Get the ID */
4840 memcpy(buf, p + 21, 20);
4841 buf[20] = '\0';
4842 Jim_StringToWide(buf, &id, 10);
4844 /* Ok, a reference for the given ID
4845 * was found. Mark it. */
4846 Jim_AddHashEntry(&marks, &id, NULL);
4847 #ifdef JIM_DEBUG_GC
4848 printf("MARK: %d" JIM_NL, (int)id);
4849 #endif
4850 p += JIM_REFERENCE_SPACE;
4853 objPtr = objPtr->nextObjPtr;
4856 /* Run the references hash table to destroy every reference that
4857 * is not referenced outside (not present in the mark HT). */
4858 htiter = Jim_GetHashTableIterator(&interp->references);
4859 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
4860 const jim_wide *refId;
4861 Jim_Reference *refPtr;
4863 refId = he->key;
4864 /* Check if in the mark phase we encountered
4865 * this reference. */
4866 if (Jim_FindHashEntry(&marks, refId) == NULL) {
4867 #ifdef JIM_DEBUG_GC
4868 printf("COLLECTING %d" JIM_NL, (int)*refId);
4869 #endif
4870 collected++;
4871 /* Drop the reference, but call the
4872 * finalizer first if registered. */
4873 refPtr = he->u.val;
4874 if (refPtr->finalizerCmdNamePtr) {
4875 char *refstr = Jim_Alloc(JIM_REFERENCE_SPACE + 1);
4876 Jim_Obj *objv[3], *oldResult;
4878 JimFormatReference(refstr, refPtr, *refId);
4880 objv[0] = refPtr->finalizerCmdNamePtr;
4881 objv[1] = Jim_NewStringObjNoAlloc(interp, refstr, 32);
4882 objv[2] = refPtr->objPtr;
4883 Jim_IncrRefCount(objv[0]);
4884 Jim_IncrRefCount(objv[1]);
4885 Jim_IncrRefCount(objv[2]);
4887 /* Drop the reference itself */
4888 Jim_DeleteHashEntry(&interp->references, refId);
4890 /* Call the finalizer. Errors ignored. */
4891 oldResult = interp->result;
4892 Jim_IncrRefCount(oldResult);
4893 Jim_EvalObjVector(interp, 3, objv);
4894 Jim_SetResult(interp, oldResult);
4895 Jim_DecrRefCount(interp, oldResult);
4897 Jim_DecrRefCount(interp, objv[0]);
4898 Jim_DecrRefCount(interp, objv[1]);
4899 Jim_DecrRefCount(interp, objv[2]);
4901 else {
4902 Jim_DeleteHashEntry(&interp->references, refId);
4906 Jim_FreeHashTableIterator(htiter);
4907 Jim_FreeHashTable(&marks);
4908 interp->lastCollectId = interp->referenceNextId;
4909 interp->lastCollectTime = time(NULL);
4910 #endif /* JIM_BOOTSTRAP */
4911 return collected;
4914 #define JIM_COLLECT_ID_PERIOD 5000
4915 #define JIM_COLLECT_TIME_PERIOD 300
4917 void Jim_CollectIfNeeded(Jim_Interp *interp)
4919 jim_wide elapsedId;
4920 int elapsedTime;
4922 elapsedId = interp->referenceNextId - interp->lastCollectId;
4923 elapsedTime = time(NULL) - interp->lastCollectTime;
4926 if (elapsedId > JIM_COLLECT_ID_PERIOD || elapsedTime > JIM_COLLECT_TIME_PERIOD) {
4927 Jim_Collect(interp);
4930 #endif
4932 static int JimIsBigEndian(void)
4934 union {
4935 unsigned short s;
4936 unsigned char c[2];
4937 } uval = {0x0102};
4939 return uval.c[0] == 1;
4942 /* -----------------------------------------------------------------------------
4943 * Interpreter related functions
4944 * ---------------------------------------------------------------------------*/
4946 Jim_Interp *Jim_CreateInterp(void)
4948 Jim_Interp *i = Jim_Alloc(sizeof(*i));
4950 memset(i, 0, sizeof(*i));
4952 i->maxNestingDepth = JIM_MAX_NESTING_DEPTH;
4953 i->lastCollectTime = time(NULL);
4955 /* Note that we can create objects only after the
4956 * interpreter liveList and freeList pointers are
4957 * initialized to NULL. */
4958 Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
4959 #ifdef JIM_REFERENCES
4960 Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
4961 #endif
4962 Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
4963 Jim_InitHashTable(&i->packages, &JimStringKeyValCopyHashTableType, NULL);
4964 i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL);
4965 i->emptyObj = Jim_NewEmptyStringObj(i);
4966 i->trueObj = Jim_NewIntObj(i, 1);
4967 i->falseObj = Jim_NewIntObj(i, 0);
4968 i->errorFileNameObj = i->emptyObj;
4969 i->result = i->emptyObj;
4970 i->stackTrace = Jim_NewListObj(i, NULL, 0);
4971 i->unknown = Jim_NewStringObj(i, "unknown", -1);
4972 i->errorProc = i->emptyObj;
4973 i->currentScriptObj = Jim_NewEmptyStringObj(i);
4974 Jim_IncrRefCount(i->emptyObj);
4975 Jim_IncrRefCount(i->errorFileNameObj);
4976 Jim_IncrRefCount(i->result);
4977 Jim_IncrRefCount(i->stackTrace);
4978 Jim_IncrRefCount(i->unknown);
4979 Jim_IncrRefCount(i->currentScriptObj);
4980 Jim_IncrRefCount(i->errorProc);
4981 Jim_IncrRefCount(i->trueObj);
4982 Jim_IncrRefCount(i->falseObj);
4984 /* Initialize key variables every interpreter should contain */
4985 Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
4986 Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
4988 Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
4989 Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
4990 Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
4991 Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4992 Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
4993 Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
4994 Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
4996 return i;
4999 void Jim_FreeInterp(Jim_Interp *i)
5001 Jim_CallFrame *cf = i->framePtr, *prevcf, *nextcf;
5002 Jim_Obj *objPtr, *nextObjPtr;
5004 Jim_DecrRefCount(i, i->emptyObj);
5005 Jim_DecrRefCount(i, i->trueObj);
5006 Jim_DecrRefCount(i, i->falseObj);
5007 Jim_DecrRefCount(i, i->result);
5008 Jim_DecrRefCount(i, i->stackTrace);
5009 Jim_DecrRefCount(i, i->errorProc);
5010 Jim_DecrRefCount(i, i->unknown);
5011 Jim_DecrRefCount(i, i->errorFileNameObj);
5012 Jim_DecrRefCount(i, i->currentScriptObj);
5013 Jim_FreeHashTable(&i->commands);
5014 #ifdef JIM_REFERENCES
5015 Jim_FreeHashTable(&i->references);
5016 #endif
5017 Jim_FreeHashTable(&i->packages);
5018 Jim_Free(i->prngState);
5019 Jim_FreeHashTable(&i->assocData);
5020 JimDeleteLocalProcs(i);
5022 /* Free the call frames list */
5023 while (cf) {
5024 prevcf = cf->parentCallFrame;
5025 JimFreeCallFrame(i, cf, JIM_FCF_NONE);
5026 cf = prevcf;
5028 /* Check that the live object list is empty, otherwise
5029 * there is a memory leak. */
5030 if (i->liveList != NULL) {
5031 objPtr = i->liveList;
5033 printf(JIM_NL "-------------------------------------" JIM_NL);
5034 printf("Objects still in the free list:" JIM_NL);
5035 while (objPtr) {
5036 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
5038 printf("%p (%d) %-10s: '%.20s'" JIM_NL,
5039 (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
5040 if (objPtr->typePtr == &sourceObjType) {
5041 printf("FILE %s LINE %d" JIM_NL,
5042 Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
5043 objPtr->internalRep.sourceValue.lineNumber);
5045 objPtr = objPtr->nextObjPtr;
5047 printf("-------------------------------------" JIM_NL JIM_NL);
5048 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5050 /* Free all the freed objects. */
5051 objPtr = i->freeList;
5052 while (objPtr) {
5053 nextObjPtr = objPtr->nextObjPtr;
5054 Jim_Free(objPtr);
5055 objPtr = nextObjPtr;
5057 /* Free cached CallFrame structures */
5058 cf = i->freeFramesList;
5059 while (cf) {
5060 nextcf = cf->nextFramePtr;
5061 if (cf->vars.table != NULL)
5062 Jim_Free(cf->vars.table);
5063 Jim_Free(cf);
5064 cf = nextcf;
5066 #ifdef jim_ext_load
5067 Jim_FreeLoadHandles(i);
5068 #endif
5070 /* Free the interpreter structure. */
5071 Jim_Free(i);
5074 /* Returns the call frame relative to the level represented by
5075 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5077 * This function accepts the 'level' argument in the form
5078 * of the commands [uplevel] and [upvar].
5080 * For a function accepting a relative integer as level suitable
5081 * for implementation of [info level ?level?] check the
5082 * JimGetCallFrameByInteger() function.
5084 * Returns NULL on error.
5086 Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5088 long level;
5089 const char *str;
5090 Jim_CallFrame *framePtr;
5092 if (levelObjPtr) {
5093 str = Jim_String(levelObjPtr);
5094 if (str[0] == '#') {
5095 char *endptr;
5097 level = strtol(str + 1, &endptr, 0);
5098 if (str[1] == '\0' || endptr[0] != '\0') {
5099 level = -1;
5102 else {
5103 if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
5104 level = -1;
5106 else {
5107 /* Convert from a relative to an absolute level */
5108 level = interp->framePtr->level - level;
5112 else {
5113 str = "1"; /* Needed to format the error message. */
5114 level = interp->framePtr->level - 1;
5117 if (level == 0) {
5118 return interp->topFramePtr;
5120 if (level > 0) {
5121 /* Lookup */
5122 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5123 if (framePtr->level == level) {
5124 return framePtr;
5129 Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
5130 return NULL;
5133 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5134 * as a relative integer like in the [info level ?level?] command.
5136 static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5138 long level;
5139 Jim_CallFrame *framePtr;
5141 if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
5142 if (level <= 0) {
5143 /* Convert from a relative to an absolute level */
5144 level = interp->framePtr->level + level;
5147 if (level == 0) {
5148 return interp->topFramePtr;
5151 /* Lookup */
5152 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5153 if (framePtr->level == level) {
5154 return framePtr;
5159 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
5160 return NULL;
5163 static void JimResetStackTrace(Jim_Interp *interp)
5165 Jim_DecrRefCount(interp, interp->stackTrace);
5166 interp->stackTrace = Jim_NewListObj(interp, NULL, 0);
5167 Jim_IncrRefCount(interp->stackTrace);
5170 static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
5172 int len;
5174 /* Increment reference first in case these are the same object */
5175 Jim_IncrRefCount(stackTraceObj);
5176 Jim_DecrRefCount(interp, interp->stackTrace);
5177 interp->stackTrace = stackTraceObj;
5178 interp->errorFlag = 1;
5180 /* This is a bit ugly.
5181 * If the filename of the last entry of the stack trace is empty,
5182 * the next stack level should be added.
5184 len = Jim_ListLength(interp, interp->stackTrace);
5185 if (len >= 3) {
5186 Jim_Obj *filenameObj;
5188 Jim_ListIndex(interp, interp->stackTrace, len - 2, &filenameObj, JIM_NONE);
5190 Jim_GetString(filenameObj, &len);
5192 if (!Jim_Length(filenameObj)) {
5193 interp->addStackTrace = 1;
5198 /* Returns 1 if the stack trace information was used or 0 if not */
5199 static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,
5200 Jim_Obj *fileNameObj, int linenr)
5202 if (strcmp(procname, "unknown") == 0) {
5203 procname = "";
5205 if (!*procname && !Jim_Length(fileNameObj)) {
5206 /* No useful info here */
5207 return;
5210 if (Jim_IsShared(interp->stackTrace)) {
5211 Jim_DecrRefCount(interp, interp->stackTrace);
5212 interp->stackTrace = Jim_DuplicateObj(interp, interp->stackTrace);
5213 Jim_IncrRefCount(interp->stackTrace);
5216 /* If we have no procname but the previous element did, merge with that frame */
5217 if (!*procname && Jim_Length(fileNameObj)) {
5218 /* Just a filename. Check the previous entry */
5219 int len = Jim_ListLength(interp, interp->stackTrace);
5221 if (len >= 3) {
5222 Jim_Obj *objPtr;
5223 if (Jim_ListIndex(interp, interp->stackTrace, len - 3, &objPtr, JIM_NONE) == JIM_OK && Jim_Length(objPtr)) {
5224 /* Yes, the previous level had procname */
5225 if (Jim_ListIndex(interp, interp->stackTrace, len - 2, &objPtr, JIM_NONE) == JIM_OK && !Jim_Length(objPtr)) {
5226 /* But no filename, so merge the new info with that frame */
5227 ListSetIndex(interp, interp->stackTrace, len - 2, fileNameObj, 0);
5228 ListSetIndex(interp, interp->stackTrace, len - 1, Jim_NewIntObj(interp, linenr), 0);
5229 return;
5235 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewStringObj(interp, procname, -1));
5236 Jim_ListAppendElement(interp, interp->stackTrace, fileNameObj);
5237 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewIntObj(interp, linenr));
5240 int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
5241 void *data)
5243 AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
5245 assocEntryPtr->delProc = delProc;
5246 assocEntryPtr->data = data;
5247 return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
5250 void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
5252 Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
5254 if (entryPtr != NULL) {
5255 AssocDataValue *assocEntryPtr = (AssocDataValue *) entryPtr->u.val;
5257 return assocEntryPtr->data;
5259 return NULL;
5262 int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
5264 return Jim_DeleteHashEntry(&interp->assocData, key);
5267 int Jim_GetExitCode(Jim_Interp *interp)
5269 return interp->exitCode;
5272 /* -----------------------------------------------------------------------------
5273 * Integer object
5274 * ---------------------------------------------------------------------------*/
5275 #define JIM_INTEGER_SPACE 24
5277 static void UpdateStringOfInt(struct Jim_Obj *objPtr);
5278 static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
5280 static const Jim_ObjType intObjType = {
5281 "int",
5282 NULL,
5283 NULL,
5284 UpdateStringOfInt,
5285 JIM_TYPE_NONE,
5288 /* A coerced double is closer to an int than a double.
5289 * It is an int value temporarily masquerading as a double value.
5290 * i.e. it has the same string value as an int and Jim_GetWide()
5291 * succeeds, but also Jim_GetDouble() returns the value directly.
5293 static const Jim_ObjType coercedDoubleObjType = {
5294 "coerced-double",
5295 NULL,
5296 NULL,
5297 UpdateStringOfInt,
5298 JIM_TYPE_NONE,
5302 void UpdateStringOfInt(struct Jim_Obj *objPtr)
5304 int len;
5305 char buf[JIM_INTEGER_SPACE + 1];
5307 len = Jim_WideToString(buf, JimWideValue(objPtr));
5308 objPtr->bytes = Jim_Alloc(len + 1);
5309 memcpy(objPtr->bytes, buf, len + 1);
5310 objPtr->length = len;
5313 int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
5315 jim_wide wideValue;
5316 const char *str;
5318 if (objPtr->typePtr == &coercedDoubleObjType) {
5319 /* Simple switcheroo */
5320 objPtr->typePtr = &intObjType;
5321 return JIM_OK;
5324 /* Get the string representation */
5325 str = Jim_String(objPtr);
5326 /* Try to convert into a jim_wide */
5327 if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
5328 if (flags & JIM_ERRMSG) {
5329 Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
5331 return JIM_ERR;
5333 if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
5334 Jim_SetResultString(interp, "Integer value too big to be represented", -1);
5335 return JIM_ERR;
5337 /* Free the old internal repr and set the new one. */
5338 Jim_FreeIntRep(interp, objPtr);
5339 objPtr->typePtr = &intObjType;
5340 objPtr->internalRep.wideValue = wideValue;
5341 return JIM_OK;
5344 #ifdef JIM_OPTIMIZATION
5345 static int JimIsWide(Jim_Obj *objPtr)
5347 return objPtr->typePtr == &intObjType;
5349 #endif
5351 int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5353 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
5354 return JIM_ERR;
5355 *widePtr = JimWideValue(objPtr);
5356 return JIM_OK;
5359 /* Get a wide but does not set an error if the format is bad. */
5360 static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5362 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
5363 return JIM_ERR;
5364 *widePtr = JimWideValue(objPtr);
5365 return JIM_OK;
5368 int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
5370 jim_wide wideValue;
5371 int retval;
5373 retval = Jim_GetWide(interp, objPtr, &wideValue);
5374 if (retval == JIM_OK) {
5375 *longPtr = (long)wideValue;
5376 return JIM_OK;
5378 return JIM_ERR;
5381 Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
5383 Jim_Obj *objPtr;
5385 objPtr = Jim_NewObj(interp);
5386 objPtr->typePtr = &intObjType;
5387 objPtr->bytes = NULL;
5388 objPtr->internalRep.wideValue = wideValue;
5389 return objPtr;
5392 /* -----------------------------------------------------------------------------
5393 * Double object
5394 * ---------------------------------------------------------------------------*/
5395 #define JIM_DOUBLE_SPACE 30
5397 static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
5398 static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
5400 static const Jim_ObjType doubleObjType = {
5401 "double",
5402 NULL,
5403 NULL,
5404 UpdateStringOfDouble,
5405 JIM_TYPE_NONE,
5408 void UpdateStringOfDouble(struct Jim_Obj *objPtr)
5410 int len;
5411 char buf[JIM_DOUBLE_SPACE + 1];
5413 len = Jim_DoubleToString(buf, objPtr->internalRep.doubleValue);
5414 objPtr->bytes = Jim_Alloc(len + 1);
5415 memcpy(objPtr->bytes, buf, len + 1);
5416 objPtr->length = len;
5419 int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
5421 double doubleValue;
5422 jim_wide wideValue;
5423 const char *str;
5425 /* Preserve the string representation.
5426 * Needed so we can convert back to int without loss
5428 str = Jim_String(objPtr);
5430 #ifdef HAVE_LONG_LONG
5431 /* Assume a 53 bit mantissa */
5432 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5433 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5435 if (objPtr->typePtr == &intObjType
5436 && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
5437 && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
5439 /* Direct conversion to coerced double */
5440 objPtr->typePtr = &coercedDoubleObjType;
5441 return JIM_OK;
5443 else
5444 #endif
5445 if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
5446 /* Managed to convert to an int, so we can use this as a cooerced double */
5447 Jim_FreeIntRep(interp, objPtr);
5448 objPtr->typePtr = &coercedDoubleObjType;
5449 objPtr->internalRep.wideValue = wideValue;
5450 return JIM_OK;
5452 else {
5453 /* Try to convert into a double */
5454 if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
5455 Jim_SetResultFormatted(interp, "expected number but got \"%#s\"", objPtr);
5456 return JIM_ERR;
5458 /* Free the old internal repr and set the new one. */
5459 Jim_FreeIntRep(interp, objPtr);
5461 objPtr->typePtr = &doubleObjType;
5462 objPtr->internalRep.doubleValue = doubleValue;
5463 return JIM_OK;
5466 int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
5468 if (objPtr->typePtr == &coercedDoubleObjType) {
5469 *doublePtr = JimWideValue(objPtr);
5470 return JIM_OK;
5472 if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
5473 return JIM_ERR;
5475 if (objPtr->typePtr == &coercedDoubleObjType) {
5476 *doublePtr = JimWideValue(objPtr);
5478 else {
5479 *doublePtr = objPtr->internalRep.doubleValue;
5481 return JIM_OK;
5484 Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
5486 Jim_Obj *objPtr;
5488 objPtr = Jim_NewObj(interp);
5489 objPtr->typePtr = &doubleObjType;
5490 objPtr->bytes = NULL;
5491 objPtr->internalRep.doubleValue = doubleValue;
5492 return objPtr;
5495 /* -----------------------------------------------------------------------------
5496 * List object
5497 * ---------------------------------------------------------------------------*/
5498 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
5499 static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
5500 static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
5501 static void UpdateStringOfList(struct Jim_Obj *objPtr);
5502 static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
5504 /* Note that while the elements of the list may contain references,
5505 * the list object itself can't. This basically means that the
5506 * list object string representation as a whole can't contain references
5507 * that are not presents in the single elements. */
5508 static const Jim_ObjType listObjType = {
5509 "list",
5510 FreeListInternalRep,
5511 DupListInternalRep,
5512 UpdateStringOfList,
5513 JIM_TYPE_NONE,
5516 void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
5518 int i;
5520 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5521 Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
5523 Jim_Free(objPtr->internalRep.listValue.ele);
5526 void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
5528 int i;
5530 JIM_NOTUSED(interp);
5532 dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
5533 dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
5534 dupPtr->internalRep.listValue.ele =
5535 Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
5536 memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
5537 sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
5538 for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
5539 Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
5541 dupPtr->typePtr = &listObjType;
5544 /* The following function checks if a given string can be encoded
5545 * into a list element without any kind of quoting, surrounded by braces,
5546 * or using escapes to quote. */
5547 #define JIM_ELESTR_SIMPLE 0
5548 #define JIM_ELESTR_BRACE 1
5549 #define JIM_ELESTR_QUOTE 2
5550 static int ListElementQuotingType(const char *s, int len)
5552 int i, level, blevel, trySimple = 1;
5554 /* Try with the SIMPLE case */
5555 if (len == 0)
5556 return JIM_ELESTR_BRACE;
5557 if (s[0] == '#')
5558 return JIM_ELESTR_BRACE;
5559 if (s[0] == '"' || s[0] == '{') {
5560 trySimple = 0;
5561 goto testbrace;
5563 for (i = 0; i < len; i++) {
5564 switch (s[i]) {
5565 case ' ':
5566 case '$':
5567 case '"':
5568 case '[':
5569 case ']':
5570 case ';':
5571 case '\\':
5572 case '\r':
5573 case '\n':
5574 case '\t':
5575 case '\f':
5576 case '\v':
5577 trySimple = 0;
5578 case '{':
5579 case '}':
5580 goto testbrace;
5583 return JIM_ELESTR_SIMPLE;
5585 testbrace:
5586 /* Test if it's possible to do with braces */
5587 if (s[len - 1] == '\\')
5588 return JIM_ELESTR_QUOTE;
5589 level = 0;
5590 blevel = 0;
5591 for (i = 0; i < len; i++) {
5592 switch (s[i]) {
5593 case '{':
5594 level++;
5595 break;
5596 case '}':
5597 level--;
5598 if (level < 0)
5599 return JIM_ELESTR_QUOTE;
5600 break;
5601 case '[':
5602 blevel++;
5603 break;
5604 case ']':
5605 blevel--;
5606 break;
5607 case '\\':
5608 if (s[i + 1] == '\n')
5609 return JIM_ELESTR_QUOTE;
5610 else if (s[i + 1] != '\0')
5611 i++;
5612 break;
5615 if (blevel < 0) {
5616 return JIM_ELESTR_QUOTE;
5619 if (level == 0) {
5620 if (!trySimple)
5621 return JIM_ELESTR_BRACE;
5622 for (i = 0; i < len; i++) {
5623 switch (s[i]) {
5624 case ' ':
5625 case '$':
5626 case '"':
5627 case '[':
5628 case ']':
5629 case ';':
5630 case '\\':
5631 case '\r':
5632 case '\n':
5633 case '\t':
5634 case '\f':
5635 case '\v':
5636 return JIM_ELESTR_BRACE;
5637 break;
5640 return JIM_ELESTR_SIMPLE;
5642 return JIM_ELESTR_QUOTE;
5645 /* Returns the malloc-ed representation of a string
5646 * using backslash to quote special chars. */
5647 static char *BackslashQuoteString(const char *s, int len, int *qlenPtr)
5649 char *q = Jim_Alloc(len * 2 + 1), *p;
5651 p = q;
5652 while (*s) {
5653 switch (*s) {
5654 case ' ':
5655 case '$':
5656 case '"':
5657 case '[':
5658 case ']':
5659 case '{':
5660 case '}':
5661 case ';':
5662 case '\\':
5663 *p++ = '\\';
5664 *p++ = *s++;
5665 break;
5666 case '\n':
5667 *p++ = '\\';
5668 *p++ = 'n';
5669 s++;
5670 break;
5671 case '\r':
5672 *p++ = '\\';
5673 *p++ = 'r';
5674 s++;
5675 break;
5676 case '\t':
5677 *p++ = '\\';
5678 *p++ = 't';
5679 s++;
5680 break;
5681 case '\f':
5682 *p++ = '\\';
5683 *p++ = 'f';
5684 s++;
5685 break;
5686 case '\v':
5687 *p++ = '\\';
5688 *p++ = 'v';
5689 s++;
5690 break;
5691 default:
5692 *p++ = *s++;
5693 break;
5696 *p = '\0';
5697 *qlenPtr = p - q;
5698 return q;
5701 static void UpdateStringOfList(struct Jim_Obj *objPtr)
5703 int i, bufLen, realLength;
5704 const char *strRep;
5705 char *p;
5706 int *quotingType;
5707 Jim_Obj **ele = objPtr->internalRep.listValue.ele;
5709 /* (Over) Estimate the space needed. */
5710 quotingType = Jim_Alloc(sizeof(int) * objPtr->internalRep.listValue.len + 1);
5711 bufLen = 0;
5712 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5713 int len;
5715 strRep = Jim_GetString(ele[i], &len);
5716 quotingType[i] = ListElementQuotingType(strRep, len);
5717 switch (quotingType[i]) {
5718 case JIM_ELESTR_SIMPLE:
5719 bufLen += len;
5720 break;
5721 case JIM_ELESTR_BRACE:
5722 bufLen += len + 2;
5723 break;
5724 case JIM_ELESTR_QUOTE:
5725 bufLen += len * 2;
5726 break;
5728 bufLen++; /* elements separator. */
5730 bufLen++;
5732 /* Generate the string rep. */
5733 p = objPtr->bytes = Jim_Alloc(bufLen + 1);
5734 realLength = 0;
5735 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5736 int len, qlen;
5737 char *q;
5739 strRep = Jim_GetString(ele[i], &len);
5741 switch (quotingType[i]) {
5742 case JIM_ELESTR_SIMPLE:
5743 memcpy(p, strRep, len);
5744 p += len;
5745 realLength += len;
5746 break;
5747 case JIM_ELESTR_BRACE:
5748 *p++ = '{';
5749 memcpy(p, strRep, len);
5750 p += len;
5751 *p++ = '}';
5752 realLength += len + 2;
5753 break;
5754 case JIM_ELESTR_QUOTE:
5755 q = BackslashQuoteString(strRep, len, &qlen);
5756 memcpy(p, q, qlen);
5757 Jim_Free(q);
5758 p += qlen;
5759 realLength += qlen;
5760 break;
5762 /* Add a separating space */
5763 if (i + 1 != objPtr->internalRep.listValue.len) {
5764 *p++ = ' ';
5765 realLength++;
5768 *p = '\0'; /* nul term. */
5769 objPtr->length = realLength;
5770 Jim_Free(quotingType);
5773 int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
5775 struct JimParserCtx parser;
5776 const char *str;
5777 int strLen;
5778 Jim_Obj *fileNameObj;
5779 int linenr;
5781 /* Try to preserve information about filename / line number */
5782 if (objPtr->typePtr == &sourceObjType) {
5783 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
5784 linenr = objPtr->internalRep.sourceValue.lineNumber;
5786 else {
5787 fileNameObj = interp->emptyObj;
5788 linenr = 1;
5790 Jim_IncrRefCount(fileNameObj);
5792 /* Get the string representation */
5793 str = Jim_GetString(objPtr, &strLen);
5795 /* Free the old internal repr just now and initialize the
5796 * new one just now. The string->list conversion can't fail. */
5797 Jim_FreeIntRep(interp, objPtr);
5798 objPtr->typePtr = &listObjType;
5799 objPtr->internalRep.listValue.len = 0;
5800 objPtr->internalRep.listValue.maxLen = 0;
5801 objPtr->internalRep.listValue.ele = NULL;
5803 /* Convert into a list */
5804 JimParserInit(&parser, str, strLen, linenr);
5805 while (!parser.eof) {
5806 Jim_Obj *elementPtr;
5808 JimParseList(&parser);
5809 if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
5810 continue;
5811 elementPtr = JimParserGetTokenObj(interp, &parser);
5812 JimSetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
5813 ListAppendElement(objPtr, elementPtr);
5815 Jim_DecrRefCount(interp, fileNameObj);
5816 return JIM_OK;
5819 Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
5821 Jim_Obj *objPtr;
5822 int i;
5824 objPtr = Jim_NewObj(interp);
5825 objPtr->typePtr = &listObjType;
5826 objPtr->bytes = NULL;
5827 objPtr->internalRep.listValue.ele = NULL;
5828 objPtr->internalRep.listValue.len = 0;
5829 objPtr->internalRep.listValue.maxLen = 0;
5830 for (i = 0; i < len; i++) {
5831 ListAppendElement(objPtr, elements[i]);
5833 return objPtr;
5836 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5837 * length of the vector. Note that the user of this function should make
5838 * sure that the list object can't shimmer while the vector returned
5839 * is in use, this vector is the one stored inside the internal representation
5840 * of the list object. This function is not exported, extensions should
5841 * always access to the List object elements using Jim_ListIndex(). */
5842 static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
5843 Jim_Obj ***listVec)
5845 *listLen = Jim_ListLength(interp, listObj);
5846 *listVec = listObj->internalRep.listValue.ele;
5849 /* Sorting uses ints, but commands may return wide */
5850 static int JimSign(jim_wide w)
5852 if (w == 0) {
5853 return 0;
5855 else if (w < 0) {
5856 return -1;
5858 return 1;
5861 /* ListSortElements type values */
5862 struct lsort_info {
5863 jmp_buf jmpbuf;
5864 Jim_Obj *command;
5865 Jim_Interp *interp;
5866 enum {
5867 JIM_LSORT_ASCII,
5868 JIM_LSORT_NOCASE,
5869 JIM_LSORT_INTEGER,
5870 JIM_LSORT_COMMAND
5871 } type;
5872 int order;
5873 int index;
5874 int indexed;
5875 int (*subfn)(Jim_Obj **, Jim_Obj **);
5878 static struct lsort_info *sort_info;
5880 static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5882 Jim_Obj *lObj, *rObj;
5884 if (Jim_ListIndex(sort_info->interp, *lhsObj, sort_info->index, &lObj, JIM_ERRMSG) != JIM_OK ||
5885 Jim_ListIndex(sort_info->interp, *rhsObj, sort_info->index, &rObj, JIM_ERRMSG) != JIM_OK) {
5886 longjmp(sort_info->jmpbuf, JIM_ERR);
5888 return sort_info->subfn(&lObj, &rObj);
5891 /* Sort the internal rep of a list. */
5892 static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5894 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
5897 static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5899 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
5902 static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5904 jim_wide lhs = 0, rhs = 0;
5906 if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
5907 Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
5908 longjmp(sort_info->jmpbuf, JIM_ERR);
5911 return JimSign(lhs - rhs) * sort_info->order;
5914 static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5916 Jim_Obj *compare_script;
5917 int rc;
5919 jim_wide ret = 0;
5921 /* This must be a valid list */
5922 compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
5923 Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
5924 Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
5926 rc = Jim_EvalObj(sort_info->interp, compare_script);
5928 if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
5929 longjmp(sort_info->jmpbuf, rc);
5932 return JimSign(ret) * sort_info->order;
5935 /* Sort a list *in place*. MUST be called with non-shared objects. */
5936 static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
5938 struct lsort_info *prev_info;
5940 typedef int (qsort_comparator) (const void *, const void *);
5941 int (*fn) (Jim_Obj **, Jim_Obj **);
5942 Jim_Obj **vector;
5943 int len;
5944 int rc;
5946 JimPanic((Jim_IsShared(listObjPtr), "Jim_ListSortElements called with shared object"));
5947 if (!Jim_IsList(listObjPtr))
5948 SetListFromAny(interp, listObjPtr);
5950 /* Allow lsort to be called reentrantly */
5951 prev_info = sort_info;
5952 sort_info = info;
5954 vector = listObjPtr->internalRep.listValue.ele;
5955 len = listObjPtr->internalRep.listValue.len;
5956 switch (info->type) {
5957 case JIM_LSORT_ASCII:
5958 fn = ListSortString;
5959 break;
5960 case JIM_LSORT_NOCASE:
5961 fn = ListSortStringNoCase;
5962 break;
5963 case JIM_LSORT_INTEGER:
5964 fn = ListSortInteger;
5965 break;
5966 case JIM_LSORT_COMMAND:
5967 fn = ListSortCommand;
5968 break;
5969 default:
5970 fn = NULL; /* avoid warning */
5971 JimPanic((1, "ListSort called with invalid sort type"));
5974 if (info->indexed) {
5975 /* Need to interpose a "list index" function */
5976 info->subfn = fn;
5977 fn = ListSortIndexHelper;
5980 if ((rc = setjmp(info->jmpbuf)) == 0) {
5981 qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
5983 Jim_InvalidateStringRep(listObjPtr);
5984 sort_info = prev_info;
5986 return rc;
5989 /* This is the low-level function to insert elements into a list.
5990 * The higher-level Jim_ListInsertElements() performs shared object
5991 * check and invalidate the string repr. This version is used
5992 * in the internals of the List Object and is not exported.
5994 * NOTE: this function can be called only against objects
5995 * with internal type of List. */
5996 static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
5998 int currentLen = listPtr->internalRep.listValue.len;
5999 int requiredLen = currentLen + elemc;
6000 int i;
6001 Jim_Obj **point;
6003 if (requiredLen > listPtr->internalRep.listValue.maxLen) {
6004 int maxLen = requiredLen * 2;
6006 listPtr->internalRep.listValue.ele =
6007 Jim_Realloc(listPtr->internalRep.listValue.ele, sizeof(Jim_Obj *) * maxLen);
6008 listPtr->internalRep.listValue.maxLen = maxLen;
6010 point = listPtr->internalRep.listValue.ele + idx;
6011 memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
6012 for (i = 0; i < elemc; ++i) {
6013 point[i] = elemVec[i];
6014 Jim_IncrRefCount(point[i]);
6016 listPtr->internalRep.listValue.len += elemc;
6019 /* Convenience call to ListInsertElements() to append a single element.
6021 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
6023 ListInsertElements(listPtr, listPtr->internalRep.listValue.len, 1, &objPtr);
6027 /* Appends every element of appendListPtr into listPtr.
6028 * Both have to be of the list type.
6029 * Convenience call to ListInsertElements()
6031 static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6033 ListInsertElements(listPtr, listPtr->internalRep.listValue.len,
6034 appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
6037 void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
6039 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
6040 if (!Jim_IsList(listPtr))
6041 SetListFromAny(interp, listPtr);
6042 Jim_InvalidateStringRep(listPtr);
6043 ListAppendElement(listPtr, objPtr);
6046 void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6048 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
6049 if (!Jim_IsList(listPtr))
6050 SetListFromAny(interp, listPtr);
6051 Jim_InvalidateStringRep(listPtr);
6052 ListAppendList(listPtr, appendListPtr);
6055 int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
6057 if (!Jim_IsList(objPtr))
6058 SetListFromAny(interp, objPtr);
6059 return objPtr->internalRep.listValue.len;
6062 void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6063 int objc, Jim_Obj *const *objVec)
6065 JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
6066 if (!Jim_IsList(listPtr))
6067 SetListFromAny(interp, listPtr);
6068 if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
6069 idx = listPtr->internalRep.listValue.len;
6070 else if (idx < 0)
6071 idx = 0;
6072 Jim_InvalidateStringRep(listPtr);
6073 ListInsertElements(listPtr, idx, objc, objVec);
6076 int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
6078 if (!Jim_IsList(listPtr))
6079 SetListFromAny(interp, listPtr);
6080 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6081 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6082 if (flags & JIM_ERRMSG) {
6083 Jim_SetResultString(interp, "list index out of range", -1);
6085 *objPtrPtr = NULL;
6086 return JIM_ERR;
6088 if (idx < 0)
6089 idx = listPtr->internalRep.listValue.len + idx;
6090 *objPtrPtr = listPtr->internalRep.listValue.ele[idx];
6091 return JIM_OK;
6094 static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6095 Jim_Obj *newObjPtr, int flags)
6097 if (!Jim_IsList(listPtr))
6098 SetListFromAny(interp, listPtr);
6099 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6100 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6101 if (flags & JIM_ERRMSG) {
6102 Jim_SetResultString(interp, "list index out of range", -1);
6104 return JIM_ERR;
6106 if (idx < 0)
6107 idx = listPtr->internalRep.listValue.len + idx;
6108 Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
6109 listPtr->internalRep.listValue.ele[idx] = newObjPtr;
6110 Jim_IncrRefCount(newObjPtr);
6111 return JIM_OK;
6114 /* Modify the list stored into the variable named 'varNamePtr'
6115 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6116 * with the new element 'newObjptr'. */
6117 int Jim_SetListIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
6118 Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
6120 Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
6121 int shared, i, idx;
6123 varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
6124 if (objPtr == NULL)
6125 return JIM_ERR;
6126 if ((shared = Jim_IsShared(objPtr)))
6127 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6128 for (i = 0; i < indexc - 1; i++) {
6129 listObjPtr = objPtr;
6130 if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
6131 goto err;
6132 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_ERRMSG) != JIM_OK) {
6133 goto err;
6135 if (Jim_IsShared(objPtr)) {
6136 objPtr = Jim_DuplicateObj(interp, objPtr);
6137 ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
6139 Jim_InvalidateStringRep(listObjPtr);
6141 if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
6142 goto err;
6143 if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
6144 goto err;
6145 Jim_InvalidateStringRep(objPtr);
6146 Jim_InvalidateStringRep(varObjPtr);
6147 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
6148 goto err;
6149 Jim_SetResult(interp, varObjPtr);
6150 return JIM_OK;
6151 err:
6152 if (shared) {
6153 Jim_FreeNewObj(interp, varObjPtr);
6155 return JIM_ERR;
6158 Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
6160 int i;
6162 /* If all the objects in objv are lists,
6163 * it's possible to return a list as result, that's the
6164 * concatenation of all the lists. */
6165 for (i = 0; i < objc; i++) {
6166 if (!Jim_IsList(objv[i]))
6167 break;
6169 if (i == objc) {
6170 Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
6172 for (i = 0; i < objc; i++)
6173 Jim_ListAppendList(interp, objPtr, objv[i]);
6174 return objPtr;
6176 else {
6177 /* Else... we have to glue strings together */
6178 int len = 0, objLen;
6179 char *bytes, *p;
6181 /* Compute the length */
6182 for (i = 0; i < objc; i++) {
6183 Jim_GetString(objv[i], &objLen);
6184 len += objLen;
6186 if (objc)
6187 len += objc - 1;
6188 /* Create the string rep, and a string object holding it. */
6189 p = bytes = Jim_Alloc(len + 1);
6190 for (i = 0; i < objc; i++) {
6191 const char *s = Jim_GetString(objv[i], &objLen);
6193 /* Remove leading space */
6194 while (objLen && (*s == ' ' || *s == '\t' || *s == '\n')) {
6195 s++;
6196 objLen--;
6197 len--;
6199 /* And trailing space */
6200 while (objLen && (s[objLen - 1] == ' ' ||
6201 s[objLen - 1] == '\n' || s[objLen - 1] == '\t')) {
6202 /* Handle trailing backslash-space case */
6203 if (objLen > 1 && s[objLen - 2] == '\\') {
6204 break;
6206 objLen--;
6207 len--;
6209 memcpy(p, s, objLen);
6210 p += objLen;
6211 if (objLen && i + 1 != objc) {
6212 *p++ = ' ';
6214 else if (i + 1 != objc) {
6215 /* Drop the space calcuated for this
6216 * element that is instead null. */
6217 len--;
6220 *p = '\0';
6221 return Jim_NewStringObjNoAlloc(interp, bytes, len);
6225 /* Returns a list composed of the elements in the specified range.
6226 * first and start are directly accepted as Jim_Objects and
6227 * processed for the end?-index? case. */
6228 Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
6229 Jim_Obj *lastObjPtr)
6231 int first, last;
6232 int len, rangeLen;
6234 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
6235 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
6236 return NULL;
6237 len = Jim_ListLength(interp, listObjPtr); /* will convert into list */
6238 first = JimRelToAbsIndex(len, first);
6239 last = JimRelToAbsIndex(len, last);
6240 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
6241 if (first == 0 && last == len) {
6242 return listObjPtr;
6244 return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
6247 /* -----------------------------------------------------------------------------
6248 * Dict object
6249 * ---------------------------------------------------------------------------*/
6250 static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
6251 static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
6252 static void UpdateStringOfDict(struct Jim_Obj *objPtr);
6253 static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6255 /* Dict HashTable Type.
6257 * Keys and Values are Jim objects. */
6259 static unsigned int JimObjectHTHashFunction(const void *key)
6261 const char *str;
6262 Jim_Obj *objPtr = (Jim_Obj *)key;
6263 int len;
6265 str = Jim_GetString(objPtr, &len);
6266 return Jim_GenHashFunction((unsigned char *)str, len);
6269 static int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
6271 JIM_NOTUSED(privdata);
6273 return Jim_StringEqObj((Jim_Obj *)key1, (Jim_Obj *)key2);
6276 static void JimObjectHTKeyValDestructor(void *interp, void *val)
6278 Jim_Obj *objPtr = val;
6280 Jim_DecrRefCount(interp, objPtr);
6283 static const Jim_HashTableType JimDictHashTableType = {
6284 JimObjectHTHashFunction, /* hash function */
6285 NULL, /* key dup */
6286 NULL, /* val dup */
6287 JimObjectHTKeyCompare, /* key compare */
6288 (void (*)(void *, const void *)) /* ATTENTION: const cast */
6289 JimObjectHTKeyValDestructor, /* key destructor */
6290 JimObjectHTKeyValDestructor /* val destructor */
6293 /* Note that while the elements of the dict may contain references,
6294 * the list object itself can't. This basically means that the
6295 * dict object string representation as a whole can't contain references
6296 * that are not presents in the single elements. */
6297 static const Jim_ObjType dictObjType = {
6298 "dict",
6299 FreeDictInternalRep,
6300 DupDictInternalRep,
6301 UpdateStringOfDict,
6302 JIM_TYPE_NONE,
6305 void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
6307 JIM_NOTUSED(interp);
6309 Jim_FreeHashTable(objPtr->internalRep.ptr);
6310 Jim_Free(objPtr->internalRep.ptr);
6313 void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
6315 Jim_HashTable *ht, *dupHt;
6316 Jim_HashTableIterator *htiter;
6317 Jim_HashEntry *he;
6319 /* Create a new hash table */
6320 ht = srcPtr->internalRep.ptr;
6321 dupHt = Jim_Alloc(sizeof(*dupHt));
6322 Jim_InitHashTable(dupHt, &JimDictHashTableType, interp);
6323 if (ht->size != 0)
6324 Jim_ExpandHashTable(dupHt, ht->size);
6325 /* Copy every element from the source to the dup hash table */
6326 htiter = Jim_GetHashTableIterator(ht);
6327 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6328 const Jim_Obj *keyObjPtr = he->key;
6329 Jim_Obj *valObjPtr = he->u.val;
6331 Jim_IncrRefCount((Jim_Obj *)keyObjPtr); /* ATTENTION: const cast */
6332 Jim_IncrRefCount(valObjPtr);
6333 Jim_AddHashEntry(dupHt, keyObjPtr, valObjPtr);
6335 Jim_FreeHashTableIterator(htiter);
6337 dupPtr->internalRep.ptr = dupHt;
6338 dupPtr->typePtr = &dictObjType;
6341 void UpdateStringOfDict(struct Jim_Obj *objPtr)
6343 int i, bufLen, realLength;
6344 const char *strRep;
6345 char *p;
6346 int *quotingType, objc;
6347 Jim_HashTable *ht;
6348 Jim_HashTableIterator *htiter;
6349 Jim_HashEntry *he;
6350 Jim_Obj **objv;
6352 /* Trun the hash table into a flat vector of Jim_Objects. */
6353 ht = objPtr->internalRep.ptr;
6354 objc = ht->used * 2;
6355 objv = Jim_Alloc(objc * sizeof(Jim_Obj *));
6356 htiter = Jim_GetHashTableIterator(ht);
6357 i = 0;
6358 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6359 objv[i++] = (Jim_Obj *)he->key; /* ATTENTION: const cast */
6360 objv[i++] = he->u.val;
6362 Jim_FreeHashTableIterator(htiter);
6363 /* (Over) Estimate the space needed. */
6364 quotingType = Jim_Alloc(sizeof(int) * objc);
6365 bufLen = 0;
6366 for (i = 0; i < objc; i++) {
6367 int len;
6369 strRep = Jim_GetString(objv[i], &len);
6370 quotingType[i] = ListElementQuotingType(strRep, len);
6371 switch (quotingType[i]) {
6372 case JIM_ELESTR_SIMPLE:
6373 bufLen += len;
6374 break;
6375 case JIM_ELESTR_BRACE:
6376 bufLen += len + 2;
6377 break;
6378 case JIM_ELESTR_QUOTE:
6379 bufLen += len * 2;
6380 break;
6382 bufLen++; /* elements separator. */
6384 bufLen++;
6386 /* Generate the string rep. */
6387 p = objPtr->bytes = Jim_Alloc(bufLen + 1);
6388 realLength = 0;
6389 for (i = 0; i < objc; i++) {
6390 int len, qlen;
6391 char *q;
6393 strRep = Jim_GetString(objv[i], &len);
6395 switch (quotingType[i]) {
6396 case JIM_ELESTR_SIMPLE:
6397 memcpy(p, strRep, len);
6398 p += len;
6399 realLength += len;
6400 break;
6401 case JIM_ELESTR_BRACE:
6402 *p++ = '{';
6403 memcpy(p, strRep, len);
6404 p += len;
6405 *p++ = '}';
6406 realLength += len + 2;
6407 break;
6408 case JIM_ELESTR_QUOTE:
6409 q = BackslashQuoteString(strRep, len, &qlen);
6410 memcpy(p, q, qlen);
6411 Jim_Free(q);
6412 p += qlen;
6413 realLength += qlen;
6414 break;
6416 /* Add a separating space */
6417 if (i + 1 != objc) {
6418 *p++ = ' ';
6419 realLength++;
6422 *p = '\0'; /* nul term. */
6423 objPtr->length = realLength;
6424 Jim_Free(quotingType);
6425 Jim_Free(objv);
6428 static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
6430 int listlen;
6432 /* Get the string representation. Do this first so we don't
6433 * change order in case of fast conversion to dict.
6435 Jim_String(objPtr);
6437 /* For simplicity, convert a non-list object to a list and then to a dict */
6438 listlen = Jim_ListLength(interp, objPtr);
6439 if (listlen % 2) {
6440 Jim_SetResultString(interp,
6441 "invalid dictionary value: must be a list with an even number of elements", -1);
6442 return JIM_ERR;
6444 else {
6445 /* Now it is easy to convert to a dict from a list, and it can't fail */
6446 Jim_HashTable *ht;
6447 int i;
6449 ht = Jim_Alloc(sizeof(*ht));
6450 Jim_InitHashTable(ht, &JimDictHashTableType, interp);
6452 for (i = 0; i < listlen; i += 2) {
6453 Jim_Obj *keyObjPtr;
6454 Jim_Obj *valObjPtr;
6456 Jim_ListIndex(interp, objPtr, i, &keyObjPtr, JIM_NONE);
6457 Jim_ListIndex(interp, objPtr, i + 1, &valObjPtr, JIM_NONE);
6459 Jim_IncrRefCount(keyObjPtr);
6460 Jim_IncrRefCount(valObjPtr);
6462 if (Jim_AddHashEntry(ht, keyObjPtr, valObjPtr) != JIM_OK) {
6463 Jim_HashEntry *he;
6465 he = Jim_FindHashEntry(ht, keyObjPtr);
6466 Jim_DecrRefCount(interp, keyObjPtr);
6467 /* ATTENTION: const cast */
6468 Jim_DecrRefCount(interp, (Jim_Obj *)he->u.val);
6469 he->u.val = valObjPtr;
6473 Jim_FreeIntRep(interp, objPtr);
6474 objPtr->typePtr = &dictObjType;
6475 objPtr->internalRep.ptr = ht;
6477 return JIM_OK;
6481 /* Dict object API */
6483 /* Add an element to a dict. objPtr must be of the "dict" type.
6484 * The higer-level exported function is Jim_DictAddElement().
6485 * If an element with the specified key already exists, the value
6486 * associated is replaced with the new one.
6488 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6489 static int DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
6490 Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
6492 Jim_HashTable *ht = objPtr->internalRep.ptr;
6494 if (valueObjPtr == NULL) { /* unset */
6495 return Jim_DeleteHashEntry(ht, keyObjPtr);
6497 Jim_IncrRefCount(keyObjPtr);
6498 Jim_IncrRefCount(valueObjPtr);
6499 if (Jim_AddHashEntry(ht, keyObjPtr, valueObjPtr) != JIM_OK) {
6500 Jim_HashEntry *he = Jim_FindHashEntry(ht, keyObjPtr);
6502 Jim_DecrRefCount(interp, keyObjPtr);
6503 /* ATTENTION: const cast */
6504 Jim_DecrRefCount(interp, (Jim_Obj *)he->u.val);
6505 he->u.val = valueObjPtr;
6507 return JIM_OK;
6510 /* Add an element, higher-level interface for DictAddElement().
6511 * If valueObjPtr == NULL, the key is removed if it exists. */
6512 int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
6513 Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
6515 int retcode;
6517 JimPanic((Jim_IsShared(objPtr), "Jim_DictAddElement called with shared object"));
6518 if (objPtr->typePtr != &dictObjType) {
6519 if (SetDictFromAny(interp, objPtr) != JIM_OK)
6520 return JIM_ERR;
6522 retcode = DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
6523 Jim_InvalidateStringRep(objPtr);
6524 return retcode;
6527 Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
6529 Jim_Obj *objPtr;
6530 int i;
6532 JimPanic((len % 2, "Jim_NewDictObj() 'len' argument must be even"));
6534 objPtr = Jim_NewObj(interp);
6535 objPtr->typePtr = &dictObjType;
6536 objPtr->bytes = NULL;
6537 objPtr->internalRep.ptr = Jim_Alloc(sizeof(Jim_HashTable));
6538 Jim_InitHashTable(objPtr->internalRep.ptr, &JimDictHashTableType, interp);
6539 for (i = 0; i < len; i += 2)
6540 DictAddElement(interp, objPtr, elements[i], elements[i + 1]);
6541 return objPtr;
6544 /* Return the value associated to the specified dict key
6545 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6547 int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
6548 Jim_Obj **objPtrPtr, int flags)
6550 Jim_HashEntry *he;
6551 Jim_HashTable *ht;
6553 if (dictPtr->typePtr != &dictObjType) {
6554 if (SetDictFromAny(interp, dictPtr) != JIM_OK)
6555 return -1;
6557 ht = dictPtr->internalRep.ptr;
6558 if ((he = Jim_FindHashEntry(ht, keyPtr)) == NULL) {
6559 if (flags & JIM_ERRMSG) {
6560 Jim_SetResultFormatted(interp, "key \"%#s\" not found in dictionary", keyPtr);
6562 return JIM_ERR;
6564 *objPtrPtr = he->u.val;
6565 return JIM_OK;
6568 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6569 int Jim_DictPairs(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj ***objPtrPtr, int *len)
6571 Jim_HashTable *ht;
6572 Jim_HashTableIterator *htiter;
6573 Jim_HashEntry *he;
6574 Jim_Obj **objv;
6575 int i;
6577 if (dictPtr->typePtr != &dictObjType) {
6578 if (SetDictFromAny(interp, dictPtr) != JIM_OK)
6579 return JIM_ERR;
6581 ht = dictPtr->internalRep.ptr;
6583 /* Turn the hash table into a flat vector of Jim_Objects. */
6584 objv = Jim_Alloc((ht->used * 2) * sizeof(Jim_Obj *));
6585 htiter = Jim_GetHashTableIterator(ht);
6586 i = 0;
6587 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6588 objv[i++] = (Jim_Obj *)he->key; /* ATTENTION: const cast */
6589 objv[i++] = he->u.val;
6591 *len = i;
6592 Jim_FreeHashTableIterator(htiter);
6593 *objPtrPtr = objv;
6594 return JIM_OK;
6598 /* Return the value associated to the specified dict keys */
6599 int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
6600 Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
6602 int i;
6604 if (keyc == 0) {
6605 *objPtrPtr = dictPtr;
6606 return JIM_OK;
6609 for (i = 0; i < keyc; i++) {
6610 Jim_Obj *objPtr;
6612 if (Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags)
6613 != JIM_OK)
6614 return JIM_ERR;
6615 dictPtr = objPtr;
6617 *objPtrPtr = dictPtr;
6618 return JIM_OK;
6621 /* Modify the dict stored into the variable named 'varNamePtr'
6622 * setting the element specified by the 'keyc' keys objects in 'keyv',
6623 * with the new value of the element 'newObjPtr'.
6625 * If newObjPtr == NULL the operation is to remove the given key
6626 * from the dictionary.
6628 * If flags & JIM_ERRMSG, then failure to remove the key is considered an error
6629 * and JIM_ERR is returned. Otherwise it is ignored and JIM_OK is returned.
6631 int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
6632 Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr, int flags)
6634 Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
6635 int shared, i;
6637 varObjPtr = objPtr =
6638 Jim_GetVariable(interp, varNamePtr, newObjPtr == NULL ? JIM_ERRMSG : JIM_NONE);
6639 if (objPtr == NULL) {
6640 if (newObjPtr == NULL) /* Cannot remove a key from non existing var */ {
6641 return JIM_ERR;
6643 varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
6644 if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
6645 Jim_FreeNewObj(interp, varObjPtr);
6646 return JIM_ERR;
6649 if ((shared = Jim_IsShared(objPtr)))
6650 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6651 for (i = 0; i < keyc - 1; i++) {
6652 dictObjPtr = objPtr;
6654 /* Check if it's a valid dictionary */
6655 if (dictObjPtr->typePtr != &dictObjType) {
6656 if (SetDictFromAny(interp, dictObjPtr) != JIM_OK) {
6657 goto err;
6660 /* Check if the given key exists. */
6661 Jim_InvalidateStringRep(dictObjPtr);
6662 if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
6663 newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
6664 /* This key exists at the current level.
6665 * Make sure it's not shared!. */
6666 if (Jim_IsShared(objPtr)) {
6667 objPtr = Jim_DuplicateObj(interp, objPtr);
6668 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6671 else {
6672 /* Key not found. If it's an [unset] operation
6673 * this is an error. Only the last key may not
6674 * exist. */
6675 if (newObjPtr == NULL) {
6676 goto err;
6678 /* Otherwise set an empty dictionary
6679 * as key's value. */
6680 objPtr = Jim_NewDictObj(interp, NULL, 0);
6681 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6684 /* Note error on unset with missing last key is OK */
6685 if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
6686 if (newObjPtr || (flags & JIM_ERRMSG)) {
6687 goto err;
6690 Jim_InvalidateStringRep(objPtr);
6691 Jim_InvalidateStringRep(varObjPtr);
6692 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK) {
6693 goto err;
6695 Jim_SetResult(interp, varObjPtr);
6696 return JIM_OK;
6697 err:
6698 if (shared) {
6699 Jim_FreeNewObj(interp, varObjPtr);
6701 return JIM_ERR;
6704 /* -----------------------------------------------------------------------------
6705 * Index object
6706 * ---------------------------------------------------------------------------*/
6707 static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
6708 static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6710 static const Jim_ObjType indexObjType = {
6711 "index",
6712 NULL,
6713 NULL,
6714 UpdateStringOfIndex,
6715 JIM_TYPE_NONE,
6718 void UpdateStringOfIndex(struct Jim_Obj *objPtr)
6720 int len;
6721 char buf[JIM_INTEGER_SPACE + 1];
6723 if (objPtr->internalRep.indexValue >= 0)
6724 len = sprintf(buf, "%d", objPtr->internalRep.indexValue);
6725 else if (objPtr->internalRep.indexValue == -1)
6726 len = sprintf(buf, "end");
6727 else {
6728 len = sprintf(buf, "end%d", objPtr->internalRep.indexValue + 1);
6730 objPtr->bytes = Jim_Alloc(len + 1);
6731 memcpy(objPtr->bytes, buf, len + 1);
6732 objPtr->length = len;
6735 int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6737 int idx, end = 0;
6738 const char *str;
6739 char *endptr;
6741 /* Get the string representation */
6742 str = Jim_String(objPtr);
6744 /* Try to convert into an index */
6745 if (strncmp(str, "end", 3) == 0) {
6746 end = 1;
6747 str += 3;
6748 idx = 0;
6750 else {
6751 idx = strtol(str, &endptr, 10);
6753 if (endptr == str) {
6754 goto badindex;
6756 str = endptr;
6759 /* Now str may include or +<num> or -<num> */
6760 if (*str == '+' || *str == '-') {
6761 int sign = (*str == '+' ? 1 : -1);
6763 idx += sign * strtol(++str, &endptr, 10);
6764 if (str == endptr || *endptr) {
6765 goto badindex;
6767 str = endptr;
6769 /* The only thing left should be spaces */
6770 while (isspace(UCHAR(*str))) {
6771 str++;
6773 if (*str) {
6774 goto badindex;
6776 if (end) {
6777 if (idx > 0) {
6778 idx = INT_MAX;
6780 else {
6781 /* end-1 is repesented as -2 */
6782 idx--;
6785 else if (idx < 0) {
6786 idx = -INT_MAX;
6789 /* Free the old internal repr and set the new one. */
6790 Jim_FreeIntRep(interp, objPtr);
6791 objPtr->typePtr = &indexObjType;
6792 objPtr->internalRep.indexValue = idx;
6793 return JIM_OK;
6795 badindex:
6796 Jim_SetResultFormatted(interp,
6797 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr);
6798 return JIM_ERR;
6801 int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
6803 /* Avoid shimmering if the object is an integer. */
6804 if (objPtr->typePtr == &intObjType) {
6805 jim_wide val = JimWideValue(objPtr);
6807 if (!(val < LONG_MIN) && !(val > LONG_MAX)) {
6808 *indexPtr = (val < 0) ? -INT_MAX : (long)val;;
6809 return JIM_OK;
6812 if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
6813 return JIM_ERR;
6814 *indexPtr = objPtr->internalRep.indexValue;
6815 return JIM_OK;
6818 /* -----------------------------------------------------------------------------
6819 * Return Code Object.
6820 * ---------------------------------------------------------------------------*/
6822 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6823 static const char * const jimReturnCodes[] = {
6824 [JIM_OK] = "ok",
6825 [JIM_ERR] = "error",
6826 [JIM_RETURN] = "return",
6827 [JIM_BREAK] = "break",
6828 [JIM_CONTINUE] = "continue",
6829 [JIM_SIGNAL] = "signal",
6830 [JIM_EXIT] = "exit",
6831 [JIM_EVAL] = "eval",
6832 NULL
6835 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6837 static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
6839 static const Jim_ObjType returnCodeObjType = {
6840 "return-code",
6841 NULL,
6842 NULL,
6843 NULL,
6844 JIM_TYPE_NONE,
6847 /* Converts a (standard) return code to a string. Returns "?" for
6848 * non-standard return codes.
6850 const char *Jim_ReturnCode(int code)
6852 if (code < 0 || code >= (int)jimReturnCodesSize) {
6853 return "?";
6855 else {
6856 return jimReturnCodes[code];
6860 int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6862 int returnCode;
6863 jim_wide wideValue;
6865 /* Try to convert into an integer */
6866 if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
6867 returnCode = (int)wideValue;
6868 else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
6869 Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
6870 return JIM_ERR;
6872 /* Free the old internal repr and set the new one. */
6873 Jim_FreeIntRep(interp, objPtr);
6874 objPtr->typePtr = &returnCodeObjType;
6875 objPtr->internalRep.returnCode = returnCode;
6876 return JIM_OK;
6879 int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
6881 if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
6882 return JIM_ERR;
6883 *intPtr = objPtr->internalRep.returnCode;
6884 return JIM_OK;
6887 /* -----------------------------------------------------------------------------
6888 * Expression Parsing
6889 * ---------------------------------------------------------------------------*/
6890 static int JimParseExprOperator(struct JimParserCtx *pc);
6891 static int JimParseExprNumber(struct JimParserCtx *pc);
6892 static int JimParseExprIrrational(struct JimParserCtx *pc);
6894 /* Exrp's Stack machine operators opcodes. */
6896 /* Binary operators (numbers) */
6897 enum
6899 /* Continues on from the JIM_TT_ space */
6900 /* Operations */
6901 JIM_EXPROP_MUL = JIM_TT_EXPR_OP, /* 15 */
6902 JIM_EXPROP_DIV,
6903 JIM_EXPROP_MOD,
6904 JIM_EXPROP_SUB,
6905 JIM_EXPROP_ADD,
6906 JIM_EXPROP_LSHIFT,
6907 JIM_EXPROP_RSHIFT,
6908 JIM_EXPROP_ROTL,
6909 JIM_EXPROP_ROTR,
6910 JIM_EXPROP_LT,
6911 JIM_EXPROP_GT,
6912 JIM_EXPROP_LTE,
6913 JIM_EXPROP_GTE,
6914 JIM_EXPROP_NUMEQ,
6915 JIM_EXPROP_NUMNE,
6916 JIM_EXPROP_BITAND, /* 30 */
6917 JIM_EXPROP_BITXOR,
6918 JIM_EXPROP_BITOR,
6920 /* Note must keep these together */
6921 JIM_EXPROP_LOGICAND, /* 33 */
6922 JIM_EXPROP_LOGICAND_LEFT,
6923 JIM_EXPROP_LOGICAND_RIGHT,
6925 /* and these */
6926 JIM_EXPROP_LOGICOR, /* 36 */
6927 JIM_EXPROP_LOGICOR_LEFT,
6928 JIM_EXPROP_LOGICOR_RIGHT,
6930 /* and these */
6931 /* Ternary operators */
6932 JIM_EXPROP_TERNARY, /* 39 */
6933 JIM_EXPROP_TERNARY_LEFT,
6934 JIM_EXPROP_TERNARY_RIGHT,
6936 /* and these */
6937 JIM_EXPROP_COLON, /* 42 */
6938 JIM_EXPROP_COLON_LEFT,
6939 JIM_EXPROP_COLON_RIGHT,
6941 JIM_EXPROP_POW, /* 45 */
6943 /* Binary operators (strings) */
6944 JIM_EXPROP_STREQ,
6945 JIM_EXPROP_STRNE,
6946 JIM_EXPROP_STRIN,
6947 JIM_EXPROP_STRNI,
6949 /* Unary operators (numbers) */
6950 JIM_EXPROP_NOT,
6951 JIM_EXPROP_BITNOT,
6952 JIM_EXPROP_UNARYMINUS,
6953 JIM_EXPROP_UNARYPLUS,
6955 /* Functions */
6956 JIM_EXPROP_FUNC_FIRST,
6957 JIM_EXPROP_FUNC_INT = JIM_EXPROP_FUNC_FIRST,
6958 JIM_EXPROP_FUNC_ABS,
6959 JIM_EXPROP_FUNC_DOUBLE,
6960 JIM_EXPROP_FUNC_ROUND,
6961 JIM_EXPROP_FUNC_RAND,
6962 JIM_EXPROP_FUNC_SRAND,
6964 /* math functions from libm */
6965 JIM_EXPROP_FUNC_SIN,
6966 JIM_EXPROP_FUNC_COS,
6967 JIM_EXPROP_FUNC_TAN,
6968 JIM_EXPROP_FUNC_ASIN,
6969 JIM_EXPROP_FUNC_ACOS,
6970 JIM_EXPROP_FUNC_ATAN,
6971 JIM_EXPROP_FUNC_SINH,
6972 JIM_EXPROP_FUNC_COSH,
6973 JIM_EXPROP_FUNC_TANH,
6974 JIM_EXPROP_FUNC_CEIL,
6975 JIM_EXPROP_FUNC_FLOOR,
6976 JIM_EXPROP_FUNC_EXP,
6977 JIM_EXPROP_FUNC_LOG,
6978 JIM_EXPROP_FUNC_LOG10,
6979 JIM_EXPROP_FUNC_SQRT,
6980 JIM_EXPROP_FUNC_POW,
6983 struct JimExprState
6985 Jim_Obj **stack;
6986 int stacklen;
6987 int opcode;
6988 int skip;
6991 /* Operators table */
6992 typedef struct Jim_ExprOperator
6994 const char *name;
6995 int precedence;
6996 int arity;
6997 int (*funcop) (Jim_Interp *interp, struct JimExprState * e);
6998 int lazy;
6999 } Jim_ExprOperator;
7001 static void ExprPush(struct JimExprState *e, Jim_Obj *obj)
7003 Jim_IncrRefCount(obj);
7004 e->stack[e->stacklen++] = obj;
7007 static Jim_Obj *ExprPop(struct JimExprState *e)
7009 return e->stack[--e->stacklen];
7012 static int JimExprOpNumUnary(Jim_Interp *interp, struct JimExprState *e)
7014 int intresult = 0;
7015 int rc = JIM_OK;
7016 Jim_Obj *A = ExprPop(e);
7017 double dA, dC = 0;
7018 jim_wide wA, wC = 0;
7020 if ((A->typePtr != &doubleObjType || A->bytes) && JimGetWideNoErr(interp, A, &wA) == JIM_OK) {
7021 intresult = 1;
7023 switch (e->opcode) {
7024 case JIM_EXPROP_FUNC_INT:
7025 wC = wA;
7026 break;
7027 case JIM_EXPROP_FUNC_ROUND:
7028 wC = wA;
7029 break;
7030 case JIM_EXPROP_FUNC_DOUBLE:
7031 dC = wA;
7032 intresult = 0;
7033 break;
7034 case JIM_EXPROP_FUNC_ABS:
7035 wC = wA >= 0 ? wA : -wA;
7036 break;
7037 case JIM_EXPROP_UNARYMINUS:
7038 wC = -wA;
7039 break;
7040 case JIM_EXPROP_UNARYPLUS:
7041 wC = wA;
7042 break;
7043 case JIM_EXPROP_NOT:
7044 wC = !wA;
7045 break;
7046 default:
7047 abort();
7050 else if ((rc = Jim_GetDouble(interp, A, &dA)) == JIM_OK) {
7051 switch (e->opcode) {
7052 case JIM_EXPROP_FUNC_INT:
7053 wC = dA;
7054 intresult = 1;
7055 break;
7056 case JIM_EXPROP_FUNC_ROUND:
7057 wC = dA < 0 ? (dA - 0.5) : (dA + 0.5);
7058 intresult = 1;
7059 break;
7060 case JIM_EXPROP_FUNC_DOUBLE:
7061 dC = dA;
7062 break;
7063 case JIM_EXPROP_FUNC_ABS:
7064 dC = dA >= 0 ? dA : -dA;
7065 break;
7066 case JIM_EXPROP_UNARYMINUS:
7067 dC = -dA;
7068 break;
7069 case JIM_EXPROP_UNARYPLUS:
7070 dC = dA;
7071 break;
7072 case JIM_EXPROP_NOT:
7073 wC = !dA;
7074 intresult = 1;
7075 break;
7076 default:
7077 abort();
7081 if (rc == JIM_OK) {
7082 if (intresult) {
7083 ExprPush(e, Jim_NewIntObj(interp, wC));
7085 else {
7086 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7090 Jim_DecrRefCount(interp, A);
7092 return rc;
7095 static double JimRandDouble(Jim_Interp *interp)
7097 unsigned long x;
7098 JimRandomBytes(interp, &x, sizeof(x));
7100 return (double)x / (unsigned long)~0;
7103 static int JimExprOpIntUnary(Jim_Interp *interp, struct JimExprState *e)
7105 Jim_Obj *A = ExprPop(e);
7106 jim_wide wA;
7108 int rc = Jim_GetWide(interp, A, &wA);
7109 if (rc == JIM_OK) {
7110 switch (e->opcode) {
7111 case JIM_EXPROP_BITNOT:
7112 ExprPush(e, Jim_NewIntObj(interp, ~wA));
7113 break;
7114 case JIM_EXPROP_FUNC_SRAND:
7115 JimPrngSeed(interp, (unsigned char *)&wA, sizeof(wA));
7116 ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
7117 break;
7118 default:
7119 abort();
7123 Jim_DecrRefCount(interp, A);
7125 return rc;
7128 static int JimExprOpNone(Jim_Interp *interp, struct JimExprState *e)
7130 JimPanic((e->opcode != JIM_EXPROP_FUNC_RAND, "JimExprOpNone only support rand()"));
7132 ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
7134 return JIM_OK;
7137 #ifdef JIM_MATH_FUNCTIONS
7138 static int JimExprOpDoubleUnary(Jim_Interp *interp, struct JimExprState *e)
7140 int rc;
7141 Jim_Obj *A = ExprPop(e);
7142 double dA, dC;
7144 rc = Jim_GetDouble(interp, A, &dA);
7145 if (rc == JIM_OK) {
7146 switch (e->opcode) {
7147 case JIM_EXPROP_FUNC_SIN:
7148 dC = sin(dA);
7149 break;
7150 case JIM_EXPROP_FUNC_COS:
7151 dC = cos(dA);
7152 break;
7153 case JIM_EXPROP_FUNC_TAN:
7154 dC = tan(dA);
7155 break;
7156 case JIM_EXPROP_FUNC_ASIN:
7157 dC = asin(dA);
7158 break;
7159 case JIM_EXPROP_FUNC_ACOS:
7160 dC = acos(dA);
7161 break;
7162 case JIM_EXPROP_FUNC_ATAN:
7163 dC = atan(dA);
7164 break;
7165 case JIM_EXPROP_FUNC_SINH:
7166 dC = sinh(dA);
7167 break;
7168 case JIM_EXPROP_FUNC_COSH:
7169 dC = cosh(dA);
7170 break;
7171 case JIM_EXPROP_FUNC_TANH:
7172 dC = tanh(dA);
7173 break;
7174 case JIM_EXPROP_FUNC_CEIL:
7175 dC = ceil(dA);
7176 break;
7177 case JIM_EXPROP_FUNC_FLOOR:
7178 dC = floor(dA);
7179 break;
7180 case JIM_EXPROP_FUNC_EXP:
7181 dC = exp(dA);
7182 break;
7183 case JIM_EXPROP_FUNC_LOG:
7184 dC = log(dA);
7185 break;
7186 case JIM_EXPROP_FUNC_LOG10:
7187 dC = log10(dA);
7188 break;
7189 case JIM_EXPROP_FUNC_SQRT:
7190 dC = sqrt(dA);
7191 break;
7192 default:
7193 abort();
7195 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7198 Jim_DecrRefCount(interp, A);
7200 return rc;
7202 #endif
7204 /* A binary operation on two ints */
7205 static int JimExprOpIntBin(Jim_Interp *interp, struct JimExprState *e)
7207 Jim_Obj *B = ExprPop(e);
7208 Jim_Obj *A = ExprPop(e);
7209 jim_wide wA, wB;
7210 int rc = JIM_ERR;
7212 if (Jim_GetWide(interp, A, &wA) == JIM_OK && Jim_GetWide(interp, B, &wB) == JIM_OK) {
7213 jim_wide wC;
7215 rc = JIM_OK;
7217 switch (e->opcode) {
7218 case JIM_EXPROP_LSHIFT:
7219 wC = wA << wB;
7220 break;
7221 case JIM_EXPROP_RSHIFT:
7222 wC = wA >> wB;
7223 break;
7224 case JIM_EXPROP_BITAND:
7225 wC = wA & wB;
7226 break;
7227 case JIM_EXPROP_BITXOR:
7228 wC = wA ^ wB;
7229 break;
7230 case JIM_EXPROP_BITOR:
7231 wC = wA | wB;
7232 break;
7233 case JIM_EXPROP_MOD:
7234 if (wB == 0) {
7235 wC = 0;
7236 Jim_SetResultString(interp, "Division by zero", -1);
7237 rc = JIM_ERR;
7239 else {
7241 * From Tcl 8.x
7243 * This code is tricky: C doesn't guarantee much
7244 * about the quotient or remainder, but Tcl does.
7245 * The remainder always has the same sign as the
7246 * divisor and a smaller absolute value.
7248 int negative = 0;
7250 if (wB < 0) {
7251 wB = -wB;
7252 wA = -wA;
7253 negative = 1;
7255 wC = wA % wB;
7256 if (wC < 0) {
7257 wC += wB;
7259 if (negative) {
7260 wC = -wC;
7263 break;
7264 case JIM_EXPROP_ROTL:
7265 case JIM_EXPROP_ROTR:{
7266 /* uint32_t would be better. But not everyone has inttypes.h? */
7267 unsigned long uA = (unsigned long)wA;
7268 unsigned long uB = (unsigned long)wB;
7269 const unsigned int S = sizeof(unsigned long) * 8;
7271 /* Shift left by the word size or more is undefined. */
7272 uB %= S;
7274 if (e->opcode == JIM_EXPROP_ROTR) {
7275 uB = S - uB;
7277 wC = (unsigned long)(uA << uB) | (uA >> (S - uB));
7278 break;
7280 default:
7281 abort();
7283 ExprPush(e, Jim_NewIntObj(interp, wC));
7287 Jim_DecrRefCount(interp, A);
7288 Jim_DecrRefCount(interp, B);
7290 return rc;
7294 /* A binary operation on two ints or two doubles (or two strings for some ops) */
7295 static int JimExprOpBin(Jim_Interp *interp, struct JimExprState *e)
7297 int intresult = 0;
7298 int rc = JIM_OK;
7299 double dA, dB, dC = 0;
7300 jim_wide wA, wB, wC = 0;
7302 Jim_Obj *B = ExprPop(e);
7303 Jim_Obj *A = ExprPop(e);
7305 if ((A->typePtr != &doubleObjType || A->bytes) &&
7306 (B->typePtr != &doubleObjType || B->bytes) &&
7307 JimGetWideNoErr(interp, A, &wA) == JIM_OK && JimGetWideNoErr(interp, B, &wB) == JIM_OK) {
7309 /* Both are ints */
7311 intresult = 1;
7313 switch (e->opcode) {
7314 case JIM_EXPROP_POW:
7315 case JIM_EXPROP_FUNC_POW:
7316 wC = JimPowWide(wA, wB);
7317 break;
7318 case JIM_EXPROP_ADD:
7319 wC = wA + wB;
7320 break;
7321 case JIM_EXPROP_SUB:
7322 wC = wA - wB;
7323 break;
7324 case JIM_EXPROP_MUL:
7325 wC = wA * wB;
7326 break;
7327 case JIM_EXPROP_DIV:
7328 if (wB == 0) {
7329 Jim_SetResultString(interp, "Division by zero", -1);
7330 rc = JIM_ERR;
7332 else {
7334 * From Tcl 8.x
7336 * This code is tricky: C doesn't guarantee much
7337 * about the quotient or remainder, but Tcl does.
7338 * The remainder always has the same sign as the
7339 * divisor and a smaller absolute value.
7341 if (wB < 0) {
7342 wB = -wB;
7343 wA = -wA;
7345 wC = wA / wB;
7346 if (wA % wB < 0) {
7347 wC--;
7350 break;
7351 case JIM_EXPROP_LT:
7352 wC = wA < wB;
7353 break;
7354 case JIM_EXPROP_GT:
7355 wC = wA > wB;
7356 break;
7357 case JIM_EXPROP_LTE:
7358 wC = wA <= wB;
7359 break;
7360 case JIM_EXPROP_GTE:
7361 wC = wA >= wB;
7362 break;
7363 case JIM_EXPROP_NUMEQ:
7364 wC = wA == wB;
7365 break;
7366 case JIM_EXPROP_NUMNE:
7367 wC = wA != wB;
7368 break;
7369 default:
7370 abort();
7373 else if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
7374 switch (e->opcode) {
7375 case JIM_EXPROP_POW:
7376 case JIM_EXPROP_FUNC_POW:
7377 #ifdef JIM_MATH_FUNCTIONS
7378 dC = pow(dA, dB);
7379 #else
7380 Jim_SetResultString(interp, "unsupported", -1);
7381 rc = JIM_ERR;
7382 #endif
7383 break;
7384 case JIM_EXPROP_ADD:
7385 dC = dA + dB;
7386 break;
7387 case JIM_EXPROP_SUB:
7388 dC = dA - dB;
7389 break;
7390 case JIM_EXPROP_MUL:
7391 dC = dA * dB;
7392 break;
7393 case JIM_EXPROP_DIV:
7394 if (dB == 0) {
7395 #ifdef INFINITY
7396 dC = dA < 0 ? -INFINITY : INFINITY;
7397 #else
7398 dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
7399 #endif
7401 else {
7402 dC = dA / dB;
7404 break;
7405 case JIM_EXPROP_LT:
7406 wC = dA < dB;
7407 intresult = 1;
7408 break;
7409 case JIM_EXPROP_GT:
7410 wC = dA > dB;
7411 intresult = 1;
7412 break;
7413 case JIM_EXPROP_LTE:
7414 wC = dA <= dB;
7415 intresult = 1;
7416 break;
7417 case JIM_EXPROP_GTE:
7418 wC = dA >= dB;
7419 intresult = 1;
7420 break;
7421 case JIM_EXPROP_NUMEQ:
7422 wC = dA == dB;
7423 intresult = 1;
7424 break;
7425 case JIM_EXPROP_NUMNE:
7426 wC = dA != dB;
7427 intresult = 1;
7428 break;
7429 default:
7430 abort();
7433 else {
7434 /* Handle the string case */
7436 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7437 int i = Jim_StringCompareObj(interp, A, B, 0);
7439 intresult = 1;
7441 switch (e->opcode) {
7442 case JIM_EXPROP_LT:
7443 wC = i < 0;
7444 break;
7445 case JIM_EXPROP_GT:
7446 wC = i > 0;
7447 break;
7448 case JIM_EXPROP_LTE:
7449 wC = i <= 0;
7450 break;
7451 case JIM_EXPROP_GTE:
7452 wC = i >= 0;
7453 break;
7454 case JIM_EXPROP_NUMEQ:
7455 wC = i == 0;
7456 break;
7457 case JIM_EXPROP_NUMNE:
7458 wC = i != 0;
7459 break;
7460 default:
7461 rc = JIM_ERR;
7462 break;
7466 if (rc == JIM_OK) {
7467 if (intresult) {
7468 ExprPush(e, Jim_NewIntObj(interp, wC));
7470 else {
7471 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7475 Jim_DecrRefCount(interp, A);
7476 Jim_DecrRefCount(interp, B);
7478 return rc;
7481 static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
7483 int listlen;
7484 int i;
7486 listlen = Jim_ListLength(interp, listObjPtr);
7487 for (i = 0; i < listlen; i++) {
7488 Jim_Obj *objPtr;
7490 Jim_ListIndex(interp, listObjPtr, i, &objPtr, JIM_NONE);
7492 if (Jim_StringEqObj(objPtr, valObj)) {
7493 return 1;
7496 return 0;
7499 static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprState *e)
7501 Jim_Obj *B = ExprPop(e);
7502 Jim_Obj *A = ExprPop(e);
7504 jim_wide wC;
7506 switch (e->opcode) {
7507 case JIM_EXPROP_STREQ:
7508 case JIM_EXPROP_STRNE: {
7509 int Alen, Blen;
7510 const char *sA = Jim_GetString(A, &Alen);
7511 const char *sB = Jim_GetString(B, &Blen);
7513 if (e->opcode == JIM_EXPROP_STREQ) {
7514 wC = (Alen == Blen && memcmp(sA, sB, Alen) == 0);
7516 else {
7517 wC = (Alen != Blen || memcmp(sA, sB, Alen) != 0);
7519 break;
7521 case JIM_EXPROP_STRIN:
7522 wC = JimSearchList(interp, B, A);
7523 break;
7524 case JIM_EXPROP_STRNI:
7525 wC = !JimSearchList(interp, B, A);
7526 break;
7527 default:
7528 abort();
7530 ExprPush(e, Jim_NewIntObj(interp, wC));
7532 Jim_DecrRefCount(interp, A);
7533 Jim_DecrRefCount(interp, B);
7535 return JIM_OK;
7538 static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
7540 long l;
7541 double d;
7543 if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
7544 return l != 0;
7546 if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
7547 return d != 0;
7549 return -1;
7552 static int JimExprOpAndLeft(Jim_Interp *interp, struct JimExprState *e)
7554 Jim_Obj *skip = ExprPop(e);
7555 Jim_Obj *A = ExprPop(e);
7556 int rc = JIM_OK;
7558 switch (ExprBool(interp, A)) {
7559 case 0:
7560 /* false, so skip RHS opcodes with a 0 result */
7561 e->skip = JimWideValue(skip);
7562 ExprPush(e, Jim_NewIntObj(interp, 0));
7563 break;
7565 case 1:
7566 /* true so continue */
7567 break;
7569 case -1:
7570 /* Invalid */
7571 rc = JIM_ERR;
7573 Jim_DecrRefCount(interp, A);
7574 Jim_DecrRefCount(interp, skip);
7576 return rc;
7579 static int JimExprOpOrLeft(Jim_Interp *interp, struct JimExprState *e)
7581 Jim_Obj *skip = ExprPop(e);
7582 Jim_Obj *A = ExprPop(e);
7583 int rc = JIM_OK;
7585 switch (ExprBool(interp, A)) {
7586 case 0:
7587 /* false, so do nothing */
7588 break;
7590 case 1:
7591 /* true so skip RHS opcodes with a 1 result */
7592 e->skip = JimWideValue(skip);
7593 ExprPush(e, Jim_NewIntObj(interp, 1));
7594 break;
7596 case -1:
7597 /* Invalid */
7598 rc = JIM_ERR;
7599 break;
7601 Jim_DecrRefCount(interp, A);
7602 Jim_DecrRefCount(interp, skip);
7604 return rc;
7607 static int JimExprOpAndOrRight(Jim_Interp *interp, struct JimExprState *e)
7609 Jim_Obj *A = ExprPop(e);
7610 int rc = JIM_OK;
7612 switch (ExprBool(interp, A)) {
7613 case 0:
7614 ExprPush(e, Jim_NewIntObj(interp, 0));
7615 break;
7617 case 1:
7618 ExprPush(e, Jim_NewIntObj(interp, 1));
7619 break;
7621 case -1:
7622 /* Invalid */
7623 rc = JIM_ERR;
7624 break;
7626 Jim_DecrRefCount(interp, A);
7628 return rc;
7631 static int JimExprOpTernaryLeft(Jim_Interp *interp, struct JimExprState *e)
7633 Jim_Obj *skip = ExprPop(e);
7634 Jim_Obj *A = ExprPop(e);
7635 int rc = JIM_OK;
7637 /* Repush A */
7638 ExprPush(e, A);
7640 switch (ExprBool(interp, A)) {
7641 case 0:
7642 /* false, skip RHS opcodes */
7643 e->skip = JimWideValue(skip);
7644 /* Push a dummy value */
7645 ExprPush(e, Jim_NewIntObj(interp, 0));
7646 break;
7648 case 1:
7649 /* true so do nothing */
7650 break;
7652 case -1:
7653 /* Invalid */
7654 rc = JIM_ERR;
7655 break;
7657 Jim_DecrRefCount(interp, A);
7658 Jim_DecrRefCount(interp, skip);
7660 return rc;
7663 static int JimExprOpColonLeft(Jim_Interp *interp, struct JimExprState *e)
7665 Jim_Obj *skip = ExprPop(e);
7666 Jim_Obj *B = ExprPop(e);
7667 Jim_Obj *A = ExprPop(e);
7669 /* No need to check for A as non-boolean */
7670 if (ExprBool(interp, A)) {
7671 /* true, so skip RHS opcodes */
7672 e->skip = JimWideValue(skip);
7673 /* Repush B as the answer */
7674 ExprPush(e, B);
7677 Jim_DecrRefCount(interp, skip);
7678 Jim_DecrRefCount(interp, A);
7679 Jim_DecrRefCount(interp, B);
7680 return JIM_OK;
7683 static int JimExprOpNull(Jim_Interp *interp, struct JimExprState *e)
7685 return JIM_OK;
7688 enum
7690 LAZY_NONE,
7691 LAZY_OP,
7692 LAZY_LEFT,
7693 LAZY_RIGHT
7696 /* name - precedence - arity - opcode */
7697 static const struct Jim_ExprOperator Jim_ExprOperators[] = {
7698 [JIM_EXPROP_FUNC_INT] = {"int", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7699 [JIM_EXPROP_FUNC_DOUBLE] = {"double", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7700 [JIM_EXPROP_FUNC_ABS] = {"abs", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7701 [JIM_EXPROP_FUNC_ROUND] = {"round", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7702 [JIM_EXPROP_FUNC_RAND] = {"rand", 400, 0, JimExprOpNone, LAZY_NONE},
7703 [JIM_EXPROP_FUNC_SRAND] = {"srand", 400, 1, JimExprOpIntUnary, LAZY_NONE},
7705 #ifdef JIM_MATH_FUNCTIONS
7706 [JIM_EXPROP_FUNC_SIN] = {"sin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7707 [JIM_EXPROP_FUNC_COS] = {"cos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7708 [JIM_EXPROP_FUNC_TAN] = {"tan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7709 [JIM_EXPROP_FUNC_ASIN] = {"asin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7710 [JIM_EXPROP_FUNC_ACOS] = {"acos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7711 [JIM_EXPROP_FUNC_ATAN] = {"atan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7712 [JIM_EXPROP_FUNC_SINH] = {"sinh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7713 [JIM_EXPROP_FUNC_COSH] = {"cosh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7714 [JIM_EXPROP_FUNC_TANH] = {"tanh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7715 [JIM_EXPROP_FUNC_CEIL] = {"ceil", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7716 [JIM_EXPROP_FUNC_FLOOR] = {"floor", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7717 [JIM_EXPROP_FUNC_EXP] = {"exp", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7718 [JIM_EXPROP_FUNC_LOG] = {"log", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7719 [JIM_EXPROP_FUNC_LOG10] = {"log10", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7720 [JIM_EXPROP_FUNC_SQRT] = {"sqrt", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7721 [JIM_EXPROP_FUNC_POW] = {"pow", 400, 2, JimExprOpBin, LAZY_NONE},
7722 #endif
7724 [JIM_EXPROP_NOT] = {"!", 300, 1, JimExprOpNumUnary, LAZY_NONE},
7725 [JIM_EXPROP_BITNOT] = {"~", 300, 1, JimExprOpIntUnary, LAZY_NONE},
7726 [JIM_EXPROP_UNARYMINUS] = {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7727 [JIM_EXPROP_UNARYPLUS] = {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7729 [JIM_EXPROP_POW] = {"**", 250, 2, JimExprOpBin, LAZY_NONE},
7731 [JIM_EXPROP_MUL] = {"*", 200, 2, JimExprOpBin, LAZY_NONE},
7732 [JIM_EXPROP_DIV] = {"/", 200, 2, JimExprOpBin, LAZY_NONE},
7733 [JIM_EXPROP_MOD] = {"%", 200, 2, JimExprOpIntBin, LAZY_NONE},
7735 [JIM_EXPROP_SUB] = {"-", 100, 2, JimExprOpBin, LAZY_NONE},
7736 [JIM_EXPROP_ADD] = {"+", 100, 2, JimExprOpBin, LAZY_NONE},
7738 [JIM_EXPROP_ROTL] = {"<<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7739 [JIM_EXPROP_ROTR] = {">>>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7740 [JIM_EXPROP_LSHIFT] = {"<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7741 [JIM_EXPROP_RSHIFT] = {">>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7743 [JIM_EXPROP_LT] = {"<", 80, 2, JimExprOpBin, LAZY_NONE},
7744 [JIM_EXPROP_GT] = {">", 80, 2, JimExprOpBin, LAZY_NONE},
7745 [JIM_EXPROP_LTE] = {"<=", 80, 2, JimExprOpBin, LAZY_NONE},
7746 [JIM_EXPROP_GTE] = {">=", 80, 2, JimExprOpBin, LAZY_NONE},
7748 [JIM_EXPROP_NUMEQ] = {"==", 70, 2, JimExprOpBin, LAZY_NONE},
7749 [JIM_EXPROP_NUMNE] = {"!=", 70, 2, JimExprOpBin, LAZY_NONE},
7751 [JIM_EXPROP_STREQ] = {"eq", 60, 2, JimExprOpStrBin, LAZY_NONE},
7752 [JIM_EXPROP_STRNE] = {"ne", 60, 2, JimExprOpStrBin, LAZY_NONE},
7754 [JIM_EXPROP_STRIN] = {"in", 55, 2, JimExprOpStrBin, LAZY_NONE},
7755 [JIM_EXPROP_STRNI] = {"ni", 55, 2, JimExprOpStrBin, LAZY_NONE},
7757 [JIM_EXPROP_BITAND] = {"&", 50, 2, JimExprOpIntBin, LAZY_NONE},
7758 [JIM_EXPROP_BITXOR] = {"^", 49, 2, JimExprOpIntBin, LAZY_NONE},
7759 [JIM_EXPROP_BITOR] = {"|", 48, 2, JimExprOpIntBin, LAZY_NONE},
7761 [JIM_EXPROP_LOGICAND] = {"&&", 10, 2, NULL, LAZY_OP},
7762 [JIM_EXPROP_LOGICOR] = {"||", 9, 2, NULL, LAZY_OP},
7764 [JIM_EXPROP_TERNARY] = {"?", 5, 2, JimExprOpNull, LAZY_OP},
7765 [JIM_EXPROP_COLON] = {":", 5, 2, JimExprOpNull, LAZY_OP},
7767 /* private operators */
7768 [JIM_EXPROP_TERNARY_LEFT] = {NULL, 5, 2, JimExprOpTernaryLeft, LAZY_LEFT},
7769 [JIM_EXPROP_TERNARY_RIGHT] = {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7770 [JIM_EXPROP_COLON_LEFT] = {NULL, 5, 2, JimExprOpColonLeft, LAZY_LEFT},
7771 [JIM_EXPROP_COLON_RIGHT] = {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7772 [JIM_EXPROP_LOGICAND_LEFT] = {NULL, 10, 2, JimExprOpAndLeft, LAZY_LEFT},
7773 [JIM_EXPROP_LOGICAND_RIGHT] = {NULL, 10, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7774 [JIM_EXPROP_LOGICOR_LEFT] = {NULL, 9, 2, JimExprOpOrLeft, LAZY_LEFT},
7775 [JIM_EXPROP_LOGICOR_RIGHT] = {NULL, 9, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7778 #define JIM_EXPR_OPERATORS_NUM \
7779 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7781 static int JimParseExpression(struct JimParserCtx *pc)
7783 /* Discard spaces and quoted newline */
7784 while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
7785 if (*pc->p == '\n') {
7786 pc->linenr++;
7788 pc->p++;
7789 pc->len--;
7792 if (pc->len == 0) {
7793 pc->tstart = pc->tend = pc->p;
7794 pc->tline = pc->linenr;
7795 pc->tt = JIM_TT_EOL;
7796 pc->eof = 1;
7797 return JIM_OK;
7799 switch (*(pc->p)) {
7800 case '(':
7801 pc->tt = JIM_TT_SUBEXPR_START;
7802 goto singlechar;
7803 case ')':
7804 pc->tt = JIM_TT_SUBEXPR_END;
7805 goto singlechar;
7806 case ',':
7807 pc->tt = JIM_TT_SUBEXPR_COMMA;
7808 singlechar:
7809 pc->tstart = pc->tend = pc->p;
7810 pc->tline = pc->linenr;
7811 pc->p++;
7812 pc->len--;
7813 break;
7814 case '[':
7815 return JimParseCmd(pc);
7816 case '$':
7817 if (JimParseVar(pc) == JIM_ERR)
7818 return JimParseExprOperator(pc);
7819 else {
7820 /* Don't allow expr sugar in expressions */
7821 if (pc->tt == JIM_TT_EXPRSUGAR) {
7822 return JIM_ERR;
7824 return JIM_OK;
7826 break;
7827 case '0':
7828 case '1':
7829 case '2':
7830 case '3':
7831 case '4':
7832 case '5':
7833 case '6':
7834 case '7':
7835 case '8':
7836 case '9':
7837 case '.':
7838 return JimParseExprNumber(pc);
7839 case '"':
7840 return JimParseQuote(pc);
7841 case '{':
7842 return JimParseBrace(pc);
7844 case 'N':
7845 case 'I':
7846 case 'n':
7847 case 'i':
7848 if (JimParseExprIrrational(pc) == JIM_ERR)
7849 return JimParseExprOperator(pc);
7850 break;
7851 default:
7852 return JimParseExprOperator(pc);
7853 break;
7855 return JIM_OK;
7858 static int JimParseExprNumber(struct JimParserCtx *pc)
7860 int allowdot = 1;
7861 int allowhex = 0;
7863 /* Assume an integer for now */
7864 pc->tt = JIM_TT_EXPR_INT;
7865 pc->tstart = pc->p;
7866 pc->tline = pc->linenr;
7867 while (isdigit(UCHAR(*pc->p))
7868 || (allowhex && isxdigit(UCHAR(*pc->p)))
7869 || (allowdot && *pc->p == '.')
7870 || (pc->p - pc->tstart == 1 && *pc->tstart == '0' && (*pc->p == 'x' || *pc->p == 'X'))
7872 if ((*pc->p == 'x') || (*pc->p == 'X')) {
7873 allowhex = 1;
7874 allowdot = 0;
7876 if (*pc->p == '.') {
7877 allowdot = 0;
7878 pc->tt = JIM_TT_EXPR_DOUBLE;
7880 pc->p++;
7881 pc->len--;
7882 if (!allowhex && (*pc->p == 'e' || *pc->p == 'E') && (pc->p[1] == '-' || pc->p[1] == '+'
7883 || isdigit(UCHAR(pc->p[1])))) {
7884 pc->p += 2;
7885 pc->len -= 2;
7886 pc->tt = JIM_TT_EXPR_DOUBLE;
7889 pc->tend = pc->p - 1;
7890 return JIM_OK;
7893 static int JimParseExprIrrational(struct JimParserCtx *pc)
7895 const char *Tokens[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
7896 const char **token;
7898 for (token = Tokens; *token != NULL; token++) {
7899 int len = strlen(*token);
7901 if (strncmp(*token, pc->p, len) == 0) {
7902 pc->tstart = pc->p;
7903 pc->tend = pc->p + len - 1;
7904 pc->p += len;
7905 pc->len -= len;
7906 pc->tline = pc->linenr;
7907 pc->tt = JIM_TT_EXPR_DOUBLE;
7908 return JIM_OK;
7911 return JIM_ERR;
7914 static int JimParseExprOperator(struct JimParserCtx *pc)
7916 int i;
7917 int bestIdx = -1, bestLen = 0;
7919 /* Try to get the longest match. */
7920 for (i = JIM_TT_EXPR_OP; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
7921 const char *opname;
7922 int oplen;
7924 opname = Jim_ExprOperators[i].name;
7925 if (opname == NULL) {
7926 continue;
7928 oplen = strlen(opname);
7930 if (strncmp(opname, pc->p, oplen) == 0 && oplen > bestLen) {
7931 bestIdx = i;
7932 bestLen = oplen;
7935 if (bestIdx == -1) {
7936 return JIM_ERR;
7939 /* Validate paretheses around function arguments */
7940 if (bestIdx >= JIM_EXPROP_FUNC_FIRST) {
7941 const char *p = pc->p + bestLen;
7942 int len = pc->len - bestLen;
7944 while (len && isspace(UCHAR(*p))) {
7945 len--;
7946 p++;
7948 if (*p != '(') {
7949 return JIM_ERR;
7952 pc->tstart = pc->p;
7953 pc->tend = pc->p + bestLen - 1;
7954 pc->p += bestLen;
7955 pc->len -= bestLen;
7956 pc->tline = pc->linenr;
7958 pc->tt = bestIdx;
7959 return JIM_OK;
7962 static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
7964 return &Jim_ExprOperators[opcode];
7967 const char *jim_tt_name(int type)
7969 static const char * const tt_names[JIM_TT_EXPR_OP] =
7970 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", ",,,", "INT",
7971 "DBL", "$()" };
7972 if (type < JIM_TT_EXPR_OP) {
7973 return tt_names[type];
7975 else {
7976 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(type);
7977 static char buf[20];
7979 if (op && op->name) {
7980 return op->name;
7982 sprintf(buf, "(%d)", type);
7983 return buf;
7987 /* -----------------------------------------------------------------------------
7988 * Expression Object
7989 * ---------------------------------------------------------------------------*/
7990 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
7991 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
7992 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
7994 static const Jim_ObjType exprObjType = {
7995 "expression",
7996 FreeExprInternalRep,
7997 DupExprInternalRep,
7998 NULL,
7999 JIM_TYPE_REFERENCES,
8002 /* Expr bytecode structure */
8003 typedef struct ExprByteCode
8005 int len; /* Length as number of tokens. */
8006 ScriptToken *token; /* Tokens array. */
8007 int inUse; /* Used for sharing. */
8008 } ExprByteCode;
8010 static void ExprFreeByteCode(Jim_Interp *interp, ExprByteCode * expr)
8012 int i;
8014 for (i = 0; i < expr->len; i++) {
8015 Jim_DecrRefCount(interp, expr->token[i].objPtr);
8017 Jim_Free(expr->token);
8018 Jim_Free(expr);
8021 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8023 ExprByteCode *expr = (void *)objPtr->internalRep.ptr;
8025 if (expr) {
8026 if (--expr->inUse != 0) {
8027 return;
8030 ExprFreeByteCode(interp, expr);
8034 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8036 JIM_NOTUSED(interp);
8037 JIM_NOTUSED(srcPtr);
8039 /* Just returns an simple string. */
8040 dupPtr->typePtr = NULL;
8043 /* Check if an expr program looks correct. */
8044 static int ExprCheckCorrectness(ExprByteCode * expr)
8046 int i;
8047 int stacklen = 0;
8048 int ternary = 0;
8050 /* Try to check if there are stack underflows,
8051 * and make sure at the end of the program there is
8052 * a single result on the stack. */
8053 for (i = 0; i < expr->len; i++) {
8054 ScriptToken *t = &expr->token[i];
8055 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8057 if (op) {
8058 stacklen -= op->arity;
8059 if (stacklen < 0) {
8060 break;
8062 if (t->type == JIM_EXPROP_TERNARY || t->type == JIM_EXPROP_TERNARY_LEFT) {
8063 ternary++;
8065 else if (t->type == JIM_EXPROP_COLON || t->type == JIM_EXPROP_COLON_LEFT) {
8066 ternary--;
8070 /* All operations and operands add one to the stack */
8071 stacklen++;
8073 if (stacklen != 1 || ternary != 0) {
8074 return JIM_ERR;
8076 return JIM_OK;
8079 /* This procedure converts every occurrence of || and && opereators
8080 * in lazy unary versions.
8082 * a b || is converted into:
8084 * a <offset> |L b |R
8086 * a b && is converted into:
8088 * a <offset> &L b &R
8090 * "|L" checks if 'a' is true:
8091 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8092 * the opcode just after |R.
8093 * 2) if it is false does nothing.
8094 * "|R" checks if 'b' is true:
8095 * 1) if it is true pushes 1, otherwise pushes 0.
8097 * "&L" checks if 'a' is true:
8098 * 1) if it is true does nothing.
8099 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8100 * the opcode just after &R
8101 * "&R" checks if 'a' is true:
8102 * if it is true pushes 1, otherwise pushes 0.
8104 static int ExprAddLazyOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8106 int i;
8108 int leftindex, arity, offset;
8110 /* Search for the end of the first operator */
8111 leftindex = expr->len - 1;
8113 arity = 1;
8114 while (arity) {
8115 ScriptToken *tt = &expr->token[leftindex];
8117 if (tt->type >= JIM_TT_EXPR_OP) {
8118 arity += JimExprOperatorInfoByOpcode(tt->type)->arity;
8120 arity--;
8121 if (--leftindex < 0) {
8122 return JIM_ERR;
8125 leftindex++;
8127 /* Move them up */
8128 memmove(&expr->token[leftindex + 2], &expr->token[leftindex],
8129 sizeof(*expr->token) * (expr->len - leftindex));
8130 expr->len += 2;
8131 offset = (expr->len - leftindex) - 1;
8133 /* Now we rely on the fact the the left and right version have opcodes
8134 * 1 and 2 after the main opcode respectively
8136 expr->token[leftindex + 1].type = t->type + 1;
8137 expr->token[leftindex + 1].objPtr = interp->emptyObj;
8139 expr->token[leftindex].type = JIM_TT_EXPR_INT;
8140 expr->token[leftindex].objPtr = Jim_NewIntObj(interp, offset);
8142 /* Now add the 'R' operator */
8143 expr->token[expr->len].objPtr = interp->emptyObj;
8144 expr->token[expr->len].type = t->type + 2;
8145 expr->len++;
8147 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8148 for (i = leftindex - 1; i > 0; i--) {
8149 if (JimExprOperatorInfoByOpcode(expr->token[i].type)->lazy == LAZY_LEFT) {
8150 if (JimWideValue(expr->token[i - 1].objPtr) + i - 1 >= leftindex) {
8151 JimWideValue(expr->token[i - 1].objPtr) += 2;
8155 return JIM_OK;
8158 static int ExprAddOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8160 struct ScriptToken *token = &expr->token[expr->len];
8161 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8163 if (op->lazy == LAZY_OP) {
8164 if (ExprAddLazyOperator(interp, expr, t) != JIM_OK) {
8165 Jim_SetResultFormatted(interp, "Expression has bad operands to %s", op->name);
8166 return JIM_ERR;
8169 else {
8170 token->objPtr = interp->emptyObj;
8171 token->type = t->type;
8172 expr->len++;
8174 return JIM_OK;
8178 * Returns the index of the COLON_LEFT to the left of 'right_index'
8179 * taking into account nesting.
8181 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8183 static int ExprTernaryGetColonLeftIndex(ExprByteCode *expr, int right_index)
8185 int ternary_count = 1;
8187 right_index--;
8189 while (right_index > 1) {
8190 if (expr->token[right_index].type == JIM_EXPROP_TERNARY_LEFT) {
8191 ternary_count--;
8193 else if (expr->token[right_index].type == JIM_EXPROP_COLON_RIGHT) {
8194 ternary_count++;
8196 else if (expr->token[right_index].type == JIM_EXPROP_COLON_LEFT && ternary_count == 1) {
8197 return right_index;
8199 right_index--;
8202 /*notreached*/
8203 return -1;
8207 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8209 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8210 * Otherwise returns 0.
8212 static int ExprTernaryGetMoveIndices(ExprByteCode *expr, int right_index, int *prev_right_index, int *prev_left_index)
8214 int i = right_index - 1;
8215 int ternary_count = 1;
8217 while (i > 1) {
8218 if (expr->token[i].type == JIM_EXPROP_TERNARY_LEFT) {
8219 if (--ternary_count == 0 && expr->token[i - 2].type == JIM_EXPROP_COLON_RIGHT) {
8220 *prev_right_index = i - 2;
8221 *prev_left_index = ExprTernaryGetColonLeftIndex(expr, *prev_right_index);
8222 return 1;
8225 else if (expr->token[i].type == JIM_EXPROP_COLON_RIGHT) {
8226 if (ternary_count == 0) {
8227 return 0;
8229 ternary_count++;
8231 i--;
8233 return 0;
8237 * ExprTernaryReorderExpression description
8238 * ========================================
8240 * ?: is right-to-left associative which doesn't work with the stack-based
8241 * expression engine. The fix is to reorder the bytecode.
8243 * The expression:
8245 * expr 1?2:0?3:4
8247 * Has initial bytecode:
8249 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8250 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8252 * The fix involves simulating this expression instead:
8254 * expr 1?2:(0?3:4)
8256 * With the following bytecode:
8258 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8259 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8261 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8262 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8263 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8264 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8266 * ExprTernaryReorderExpression works thus as follows :
8267 * - start from the end of the stack
8268 * - while walking towards the beginning of the stack
8269 * if token=JIM_EXPROP_COLON_RIGHT then
8270 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8271 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8272 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8273 * if all found then
8274 * perform the rotation
8275 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8276 * end if
8277 * end if
8279 * Note: care has to be taken for nested ternary constructs!!!
8281 static void ExprTernaryReorderExpression(Jim_Interp *interp, ExprByteCode *expr)
8283 int i;
8285 for (i = expr->len - 1; i > 1; i--) {
8286 int prev_right_index;
8287 int prev_left_index;
8288 int j;
8289 ScriptToken tmp;
8291 if (expr->token[i].type != JIM_EXPROP_COLON_RIGHT) {
8292 continue;
8295 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8296 if (ExprTernaryGetMoveIndices(expr, i, &prev_right_index, &prev_left_index) == 0) {
8297 continue;
8301 ** rotate tokens down
8303 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8304 ** | | |
8305 ** | V V
8306 ** | [...] : ...
8307 ** | | |
8308 ** | V V
8309 ** | [...] : ...
8310 ** | | |
8311 ** | V V
8312 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8314 tmp = expr->token[prev_right_index];
8315 for (j = prev_right_index; j < i; j++) {
8316 expr->token[j] = expr->token[j + 1];
8318 expr->token[i] = tmp;
8320 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8322 * This is 'colon left increment' = i - prev_right_index
8324 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8325 * [prev_left_index-1] : skip_count
8328 JimWideValue(expr->token[prev_left_index-1].objPtr) += (i - prev_right_index);
8330 /* Adjust for i-- in the loop */
8331 i++;
8335 static ExprByteCode *ExprCreateByteCode(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *fileNameObj)
8337 Jim_Stack stack;
8338 ExprByteCode *expr;
8339 int ok = 1;
8340 int i;
8341 int prevtt = JIM_TT_NONE;
8342 int have_ternary = 0;
8344 /* -1 for EOL */
8345 int count = tokenlist->count - 1;
8347 expr = Jim_Alloc(sizeof(*expr));
8348 expr->inUse = 1;
8349 expr->len = 0;
8351 Jim_InitStack(&stack);
8353 /* Need extra bytecodes for lazy operators.
8354 * Also check for the ternary operator
8356 for (i = 0; i < tokenlist->count; i++) {
8357 ParseToken *t = &tokenlist->list[i];
8359 if (JimExprOperatorInfoByOpcode(t->type)->lazy == LAZY_OP) {
8360 count += 2;
8361 /* Ternary is a lazy op but also needs reordering */
8362 if (t->type == JIM_EXPROP_TERNARY) {
8363 have_ternary = 1;
8368 expr->token = Jim_Alloc(sizeof(ScriptToken) * count);
8370 for (i = 0; i < tokenlist->count && ok; i++) {
8371 ParseToken *t = &tokenlist->list[i];
8373 /* Next token will be stored here */
8374 struct ScriptToken *token = &expr->token[expr->len];
8376 if (t->type == JIM_TT_EOL) {
8377 break;
8380 switch (t->type) {
8381 case JIM_TT_STR:
8382 case JIM_TT_ESC:
8383 case JIM_TT_VAR:
8384 case JIM_TT_DICTSUGAR:
8385 case JIM_TT_EXPRSUGAR:
8386 case JIM_TT_CMD:
8387 token->objPtr = Jim_NewStringObj(interp, t->token, t->len);
8388 token->type = t->type;
8389 if (t->type == JIM_TT_CMD) {
8390 /* Only commands need source info */
8391 JimSetSourceInfo(interp, token->objPtr, fileNameObj, t->line);
8393 expr->len++;
8394 break;
8396 case JIM_TT_EXPR_INT:
8397 token->objPtr = Jim_NewIntObj(interp, strtoull(t->token, NULL, 0));
8398 token->type = t->type;
8399 expr->len++;
8400 break;
8402 case JIM_TT_EXPR_DOUBLE:
8403 token->objPtr = Jim_NewDoubleObj(interp, strtod(t->token, NULL));
8404 token->type = t->type;
8405 expr->len++;
8406 break;
8408 case JIM_TT_SUBEXPR_START:
8409 Jim_StackPush(&stack, t);
8410 prevtt = JIM_TT_NONE;
8411 continue;
8413 case JIM_TT_SUBEXPR_COMMA:
8414 /* Simple approach. Comma is simply ignored */
8415 continue;
8417 case JIM_TT_SUBEXPR_END:
8418 ok = 0;
8419 while (Jim_StackLen(&stack)) {
8420 ParseToken *tt = Jim_StackPop(&stack);
8422 if (tt->type == JIM_TT_SUBEXPR_START) {
8423 ok = 1;
8424 break;
8427 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8428 goto err;
8431 if (!ok) {
8432 Jim_SetResultString(interp, "Unexpected close parenthesis", -1);
8433 goto err;
8435 break;
8438 default:{
8439 /* Must be an operator */
8440 const struct Jim_ExprOperator *op;
8441 ParseToken *tt;
8443 /* Convert -/+ to unary minus or unary plus if necessary */
8444 if (prevtt == JIM_TT_NONE || prevtt >= JIM_TT_EXPR_OP) {
8445 if (t->type == JIM_EXPROP_SUB) {
8446 t->type = JIM_EXPROP_UNARYMINUS;
8448 else if (t->type == JIM_EXPROP_ADD) {
8449 t->type = JIM_EXPROP_UNARYPLUS;
8453 op = JimExprOperatorInfoByOpcode(t->type);
8455 /* Now handle precedence */
8456 while ((tt = Jim_StackPeek(&stack)) != NULL) {
8457 const struct Jim_ExprOperator *tt_op =
8458 JimExprOperatorInfoByOpcode(tt->type);
8460 /* Note that right-to-left associativity of ?: operator is handled later */
8462 if (op->arity != 1 && tt_op->precedence >= op->precedence) {
8463 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8464 ok = 0;
8465 goto err;
8467 Jim_StackPop(&stack);
8469 else {
8470 break;
8473 Jim_StackPush(&stack, t);
8474 break;
8477 prevtt = t->type;
8480 /* Reduce any remaining subexpr */
8481 while (Jim_StackLen(&stack)) {
8482 ParseToken *tt = Jim_StackPop(&stack);
8484 if (tt->type == JIM_TT_SUBEXPR_START) {
8485 ok = 0;
8486 Jim_SetResultString(interp, "Missing close parenthesis", -1);
8487 goto err;
8489 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8490 ok = 0;
8491 goto err;
8495 if (have_ternary) {
8496 ExprTernaryReorderExpression(interp, expr);
8499 err:
8500 /* Free the stack used for the compilation. */
8501 Jim_FreeStack(&stack);
8503 for (i = 0; i < expr->len; i++) {
8504 Jim_IncrRefCount(expr->token[i].objPtr);
8507 if (!ok) {
8508 ExprFreeByteCode(interp, expr);
8509 return NULL;
8512 return expr;
8516 /* This method takes the string representation of an expression
8517 * and generates a program for the Expr's stack-based VM. */
8518 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
8520 int exprTextLen;
8521 const char *exprText;
8522 struct JimParserCtx parser;
8523 struct ExprByteCode *expr;
8524 ParseTokenList tokenlist;
8525 int line;
8526 Jim_Obj *fileNameObj;
8527 int rc = JIM_ERR;
8529 /* Try to get information about filename / line number */
8530 if (objPtr->typePtr == &sourceObjType) {
8531 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
8532 line = objPtr->internalRep.sourceValue.lineNumber;
8534 else {
8535 fileNameObj = interp->emptyObj;
8536 line = 1;
8538 Jim_IncrRefCount(fileNameObj);
8540 exprText = Jim_GetString(objPtr, &exprTextLen);
8542 /* Initially tokenise the expression into tokenlist */
8543 ScriptTokenListInit(&tokenlist);
8545 JimParserInit(&parser, exprText, exprTextLen, line);
8546 while (!parser.eof) {
8547 if (JimParseExpression(&parser) != JIM_OK) {
8548 ScriptTokenListFree(&tokenlist);
8549 invalidexpr:
8550 Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
8551 expr = NULL;
8552 goto err;
8555 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
8556 parser.tline);
8559 #ifdef DEBUG_SHOW_EXPR_TOKENS
8561 int i;
8562 printf("==== Expr Tokens ====\n");
8563 for (i = 0; i < tokenlist.count; i++) {
8564 printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
8565 tokenlist.list[i].len, tokenlist.list[i].token);
8568 #endif
8570 /* Now create the expression bytecode from the tokenlist */
8571 expr = ExprCreateByteCode(interp, &tokenlist, fileNameObj);
8573 /* No longer need the token list */
8574 ScriptTokenListFree(&tokenlist);
8576 if (!expr) {
8577 goto err;
8580 #ifdef DEBUG_SHOW_EXPR
8582 int i;
8584 printf("==== Expr ====\n");
8585 for (i = 0; i < expr->len; i++) {
8586 ScriptToken *t = &expr->token[i];
8588 printf("[%2d] %s '%s'\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
8591 #endif
8593 /* Check program correctness. */
8594 if (ExprCheckCorrectness(expr) != JIM_OK) {
8595 ExprFreeByteCode(interp, expr);
8596 goto invalidexpr;
8599 rc = JIM_OK;
8601 err:
8602 /* Free the old internal rep and set the new one. */
8603 Jim_DecrRefCount(interp, fileNameObj);
8604 Jim_FreeIntRep(interp, objPtr);
8605 Jim_SetIntRepPtr(objPtr, expr);
8606 objPtr->typePtr = &exprObjType;
8607 return rc;
8610 static ExprByteCode *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
8612 if (objPtr->typePtr != &exprObjType) {
8613 if (SetExprFromAny(interp, objPtr) != JIM_OK) {
8614 return NULL;
8617 return (ExprByteCode *) Jim_GetIntRepPtr(objPtr);
8620 /* -----------------------------------------------------------------------------
8621 * Expressions evaluation.
8622 * Jim uses a specialized stack-based virtual machine for expressions,
8623 * that takes advantage of the fact that expr's operators
8624 * can't be redefined.
8626 * Jim_EvalExpression() uses the bytecode compiled by
8627 * SetExprFromAny() method of the "expression" object.
8629 * On success a Tcl Object containing the result of the evaluation
8630 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8631 * returned.
8632 * On error the function returns a retcode != to JIM_OK and set a suitable
8633 * error on the interp.
8634 * ---------------------------------------------------------------------------*/
8635 #define JIM_EE_STATICSTACK_LEN 10
8637 int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr, Jim_Obj **exprResultPtrPtr)
8639 ExprByteCode *expr;
8640 Jim_Obj *staticStack[JIM_EE_STATICSTACK_LEN];
8641 int i;
8642 int retcode = JIM_OK;
8643 struct JimExprState e;
8645 expr = JimGetExpression(interp, exprObjPtr);
8646 if (!expr) {
8647 return JIM_ERR; /* error in expression. */
8650 #ifdef JIM_OPTIMIZATION
8651 /* Check for one of the following common expressions used by while/for
8653 * CONST
8654 * $a
8655 * !$a
8656 * $a < CONST, $a < $b
8657 * $a <= CONST, $a <= $b
8658 * $a > CONST, $a > $b
8659 * $a >= CONST, $a >= $b
8660 * $a != CONST, $a != $b
8661 * $a == CONST, $a == $b
8664 Jim_Obj *objPtr;
8666 /* STEP 1 -- Check if there are the conditions to run the specialized
8667 * version of while */
8669 switch (expr->len) {
8670 case 1:
8671 if (expr->token[0].type == JIM_TT_EXPR_INT) {
8672 *exprResultPtrPtr = expr->token[0].objPtr;
8673 Jim_IncrRefCount(*exprResultPtrPtr);
8674 return JIM_OK;
8676 if (expr->token[0].type == JIM_TT_VAR) {
8677 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_ERRMSG);
8678 if (objPtr) {
8679 *exprResultPtrPtr = objPtr;
8680 Jim_IncrRefCount(*exprResultPtrPtr);
8681 return JIM_OK;
8684 break;
8686 case 2:
8687 if (expr->token[1].type == JIM_EXPROP_NOT && expr->token[0].type == JIM_TT_VAR) {
8688 jim_wide wideValue;
8690 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8691 if (objPtr && JimIsWide(objPtr)
8692 && Jim_GetWide(interp, objPtr, &wideValue) == JIM_OK) {
8693 *exprResultPtrPtr = wideValue ? interp->falseObj : interp->trueObj;
8694 Jim_IncrRefCount(*exprResultPtrPtr);
8695 return JIM_OK;
8698 break;
8700 case 3:
8701 if (expr->token[0].type == JIM_TT_VAR && (expr->token[1].type == JIM_TT_EXPR_INT
8702 || expr->token[1].type == JIM_TT_VAR)) {
8703 switch (expr->token[2].type) {
8704 case JIM_EXPROP_LT:
8705 case JIM_EXPROP_LTE:
8706 case JIM_EXPROP_GT:
8707 case JIM_EXPROP_GTE:
8708 case JIM_EXPROP_NUMEQ:
8709 case JIM_EXPROP_NUMNE:{
8710 /* optimise ok */
8711 jim_wide wideValueA;
8712 jim_wide wideValueB;
8714 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8715 if (objPtr && JimIsWide(objPtr)
8716 && Jim_GetWide(interp, objPtr, &wideValueA) == JIM_OK) {
8717 if (expr->token[1].type == JIM_TT_VAR) {
8718 objPtr =
8719 Jim_GetVariable(interp, expr->token[1].objPtr,
8720 JIM_NONE);
8722 else {
8723 objPtr = expr->token[1].objPtr;
8725 if (objPtr && JimIsWide(objPtr)
8726 && Jim_GetWide(interp, objPtr, &wideValueB) == JIM_OK) {
8727 int cmpRes;
8729 switch (expr->token[2].type) {
8730 case JIM_EXPROP_LT:
8731 cmpRes = wideValueA < wideValueB;
8732 break;
8733 case JIM_EXPROP_LTE:
8734 cmpRes = wideValueA <= wideValueB;
8735 break;
8736 case JIM_EXPROP_GT:
8737 cmpRes = wideValueA > wideValueB;
8738 break;
8739 case JIM_EXPROP_GTE:
8740 cmpRes = wideValueA >= wideValueB;
8741 break;
8742 case JIM_EXPROP_NUMEQ:
8743 cmpRes = wideValueA == wideValueB;
8744 break;
8745 case JIM_EXPROP_NUMNE:
8746 cmpRes = wideValueA != wideValueB;
8747 break;
8748 default: /*notreached */
8749 cmpRes = 0;
8751 *exprResultPtrPtr =
8752 cmpRes ? interp->trueObj : interp->falseObj;
8753 Jim_IncrRefCount(*exprResultPtrPtr);
8754 return JIM_OK;
8760 break;
8763 #endif
8765 /* In order to avoid that the internal repr gets freed due to
8766 * shimmering of the exprObjPtr's object, we make the internal rep
8767 * shared. */
8768 expr->inUse++;
8770 /* The stack-based expr VM itself */
8772 /* Stack allocation. Expr programs have the feature that
8773 * a program of length N can't require a stack longer than
8774 * N. */
8775 if (expr->len > JIM_EE_STATICSTACK_LEN)
8776 e.stack = Jim_Alloc(sizeof(Jim_Obj *) * expr->len);
8777 else
8778 e.stack = staticStack;
8780 e.stacklen = 0;
8782 /* Execute every instruction */
8783 for (i = 0; i < expr->len && retcode == JIM_OK; i++) {
8784 Jim_Obj *objPtr;
8786 switch (expr->token[i].type) {
8787 case JIM_TT_EXPR_INT:
8788 case JIM_TT_EXPR_DOUBLE:
8789 case JIM_TT_STR:
8790 ExprPush(&e, expr->token[i].objPtr);
8791 break;
8793 case JIM_TT_VAR:
8794 objPtr = Jim_GetVariable(interp, expr->token[i].objPtr, JIM_ERRMSG);
8795 if (objPtr) {
8796 ExprPush(&e, objPtr);
8798 else {
8799 retcode = JIM_ERR;
8801 break;
8803 case JIM_TT_DICTSUGAR:
8804 objPtr = JimExpandDictSugar(interp, expr->token[i].objPtr);
8805 if (objPtr) {
8806 ExprPush(&e, objPtr);
8808 else {
8809 retcode = JIM_ERR;
8811 break;
8813 case JIM_TT_ESC:
8814 retcode = Jim_SubstObj(interp, expr->token[i].objPtr, &objPtr, JIM_NONE);
8815 if (retcode == JIM_OK) {
8816 ExprPush(&e, objPtr);
8818 break;
8820 case JIM_TT_CMD:
8821 retcode = Jim_EvalObj(interp, expr->token[i].objPtr);
8822 if (retcode == JIM_OK) {
8823 ExprPush(&e, Jim_GetResult(interp));
8825 break;
8827 default:{
8828 /* Find and execute the operation */
8829 e.skip = 0;
8830 e.opcode = expr->token[i].type;
8832 retcode = JimExprOperatorInfoByOpcode(e.opcode)->funcop(interp, &e);
8833 /* Skip some opcodes if necessary */
8834 i += e.skip;
8835 continue;
8840 expr->inUse--;
8842 if (retcode == JIM_OK) {
8843 *exprResultPtrPtr = ExprPop(&e);
8845 else {
8846 for (i = 0; i < e.stacklen; i++) {
8847 Jim_DecrRefCount(interp, e.stack[i]);
8850 if (e.stack != staticStack) {
8851 Jim_Free(e.stack);
8853 return retcode;
8856 int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
8858 int retcode;
8859 jim_wide wideValue;
8860 double doubleValue;
8861 Jim_Obj *exprResultPtr;
8863 retcode = Jim_EvalExpression(interp, exprObjPtr, &exprResultPtr);
8864 if (retcode != JIM_OK)
8865 return retcode;
8867 if (JimGetWideNoErr(interp, exprResultPtr, &wideValue) != JIM_OK) {
8868 if (Jim_GetDouble(interp, exprResultPtr, &doubleValue) != JIM_OK) {
8869 Jim_DecrRefCount(interp, exprResultPtr);
8870 return JIM_ERR;
8872 else {
8873 Jim_DecrRefCount(interp, exprResultPtr);
8874 *boolPtr = doubleValue != 0;
8875 return JIM_OK;
8878 *boolPtr = wideValue != 0;
8880 Jim_DecrRefCount(interp, exprResultPtr);
8881 return JIM_OK;
8884 /* -----------------------------------------------------------------------------
8885 * ScanFormat String Object
8886 * ---------------------------------------------------------------------------*/
8888 /* This Jim_Obj will held a parsed representation of a format string passed to
8889 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8890 * to be parsed in its entirely first and then, if correct, can be used for
8891 * scanning. To avoid endless re-parsing, the parsed representation will be
8892 * stored in an internal representation and re-used for performance reason. */
8894 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8895 * scanformat string. This part will later be used to extract information
8896 * out from the string to be parsed by Jim_ScanString */
8898 typedef struct ScanFmtPartDescr
8900 char type; /* Type of conversion (e.g. c, d, f) */
8901 char modifier; /* Modify type (e.g. l - long, h - short */
8902 size_t width; /* Maximal width of input to be converted */
8903 int pos; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8904 char *arg; /* Specification of a CHARSET conversion */
8905 char *prefix; /* Prefix to be scanned literally before conversion */
8906 } ScanFmtPartDescr;
8908 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8909 * string parsed and separated in part descriptions. Furthermore it contains
8910 * the original string representation of the scanformat string to allow for
8911 * fast update of the Jim_Obj's string representation part.
8913 * As an add-on the internal object representation adds some scratch pad area
8914 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8915 * memory for purpose of string scanning.
8917 * The error member points to a static allocated string in case of a mal-
8918 * formed scanformat string or it contains '0' (NULL) in case of a valid
8919 * parse representation.
8921 * The whole memory of the internal representation is allocated as a single
8922 * area of memory that will be internally separated. So freeing and duplicating
8923 * of such an object is cheap */
8925 typedef struct ScanFmtStringObj
8927 jim_wide size; /* Size of internal repr in bytes */
8928 char *stringRep; /* Original string representation */
8929 size_t count; /* Number of ScanFmtPartDescr contained */
8930 size_t convCount; /* Number of conversions that will assign */
8931 size_t maxPos; /* Max position index if XPG3 is used */
8932 const char *error; /* Ptr to error text (NULL if no error */
8933 char *scratch; /* Some scratch pad used by Jim_ScanString */
8934 ScanFmtPartDescr descr[1]; /* The vector of partial descriptions */
8935 } ScanFmtStringObj;
8938 static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
8939 static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
8940 static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
8942 static const Jim_ObjType scanFmtStringObjType = {
8943 "scanformatstring",
8944 FreeScanFmtInternalRep,
8945 DupScanFmtInternalRep,
8946 UpdateStringOfScanFmt,
8947 JIM_TYPE_NONE,
8950 void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8952 JIM_NOTUSED(interp);
8953 Jim_Free((char *)objPtr->internalRep.ptr);
8954 objPtr->internalRep.ptr = 0;
8957 void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8959 size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
8960 ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
8962 JIM_NOTUSED(interp);
8963 memcpy(newVec, srcPtr->internalRep.ptr, size);
8964 dupPtr->internalRep.ptr = newVec;
8965 dupPtr->typePtr = &scanFmtStringObjType;
8968 void UpdateStringOfScanFmt(Jim_Obj *objPtr)
8970 char *bytes = ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep;
8972 objPtr->bytes = Jim_StrDup(bytes);
8973 objPtr->length = strlen(bytes);
8976 /* SetScanFmtFromAny will parse a given string and create the internal
8977 * representation of the format specification. In case of an error
8978 * the error data member of the internal representation will be set
8979 * to an descriptive error text and the function will be left with
8980 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
8981 * specification */
8983 static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
8985 ScanFmtStringObj *fmtObj;
8986 char *buffer;
8987 int maxCount, i, approxSize, lastPos = -1;
8988 const char *fmt = objPtr->bytes;
8989 int maxFmtLen = objPtr->length;
8990 const char *fmtEnd = fmt + maxFmtLen;
8991 int curr;
8993 Jim_FreeIntRep(interp, objPtr);
8994 /* Count how many conversions could take place maximally */
8995 for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
8996 if (fmt[i] == '%')
8997 ++maxCount;
8998 /* Calculate an approximation of the memory necessary */
8999 approxSize = sizeof(ScanFmtStringObj) /* Size of the container */
9000 +(maxCount + 1) * sizeof(ScanFmtPartDescr) /* Size of all partials */
9001 +maxFmtLen * sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
9002 + maxFmtLen * sizeof(char) + 1 /* Original stringrep */
9003 + maxFmtLen * sizeof(char) /* Arg for CHARSETs */
9004 +(maxCount + 1) * sizeof(char) /* '\0' for every partial */
9005 +1; /* safety byte */
9006 fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
9007 memset(fmtObj, 0, approxSize);
9008 fmtObj->size = approxSize;
9009 fmtObj->maxPos = 0;
9010 fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
9011 fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
9012 memcpy(fmtObj->stringRep, fmt, maxFmtLen);
9013 buffer = fmtObj->stringRep + maxFmtLen + 1;
9014 objPtr->internalRep.ptr = fmtObj;
9015 objPtr->typePtr = &scanFmtStringObjType;
9016 for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
9017 int width = 0, skip;
9018 ScanFmtPartDescr *descr = &fmtObj->descr[curr];
9020 fmtObj->count++;
9021 descr->width = 0; /* Assume width unspecified */
9022 /* Overread and store any "literal" prefix */
9023 if (*fmt != '%' || fmt[1] == '%') {
9024 descr->type = 0;
9025 descr->prefix = &buffer[i];
9026 for (; fmt < fmtEnd; ++fmt) {
9027 if (*fmt == '%') {
9028 if (fmt[1] != '%')
9029 break;
9030 ++fmt;
9032 buffer[i++] = *fmt;
9034 buffer[i++] = 0;
9036 /* Skip the conversion introducing '%' sign */
9037 ++fmt;
9038 /* End reached due to non-conversion literal only? */
9039 if (fmt >= fmtEnd)
9040 goto done;
9041 descr->pos = 0; /* Assume "natural" positioning */
9042 if (*fmt == '*') {
9043 descr->pos = -1; /* Okay, conversion will not be assigned */
9044 ++fmt;
9046 else
9047 fmtObj->convCount++; /* Otherwise count as assign-conversion */
9048 /* Check if next token is a number (could be width or pos */
9049 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9050 fmt += skip;
9051 /* Was the number a XPG3 position specifier? */
9052 if (descr->pos != -1 && *fmt == '$') {
9053 int prev;
9055 ++fmt;
9056 descr->pos = width;
9057 width = 0;
9058 /* Look if "natural" postioning and XPG3 one was mixed */
9059 if ((lastPos == 0 && descr->pos > 0)
9060 || (lastPos > 0 && descr->pos == 0)) {
9061 fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
9062 return JIM_ERR;
9064 /* Look if this position was already used */
9065 for (prev = 0; prev < curr; ++prev) {
9066 if (fmtObj->descr[prev].pos == -1)
9067 continue;
9068 if (fmtObj->descr[prev].pos == descr->pos) {
9069 fmtObj->error =
9070 "variable is assigned by multiple \"%n$\" conversion specifiers";
9071 return JIM_ERR;
9074 /* Try to find a width after the XPG3 specifier */
9075 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9076 descr->width = width;
9077 fmt += skip;
9079 if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
9080 fmtObj->maxPos = descr->pos;
9082 else {
9083 /* Number was not a XPG3, so it has to be a width */
9084 descr->width = width;
9087 /* If positioning mode was undetermined yet, fix this */
9088 if (lastPos == -1)
9089 lastPos = descr->pos;
9090 /* Handle CHARSET conversion type ... */
9091 if (*fmt == '[') {
9092 int swapped = 1, beg = i, end, j;
9094 descr->type = '[';
9095 descr->arg = &buffer[i];
9096 ++fmt;
9097 if (*fmt == '^')
9098 buffer[i++] = *fmt++;
9099 if (*fmt == ']')
9100 buffer[i++] = *fmt++;
9101 while (*fmt && *fmt != ']')
9102 buffer[i++] = *fmt++;
9103 if (*fmt != ']') {
9104 fmtObj->error = "unmatched [ in format string";
9105 return JIM_ERR;
9107 end = i;
9108 buffer[i++] = 0;
9109 /* In case a range fence was given "backwards", swap it */
9110 while (swapped) {
9111 swapped = 0;
9112 for (j = beg + 1; j < end - 1; ++j) {
9113 if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
9114 char tmp = buffer[j - 1];
9116 buffer[j - 1] = buffer[j + 1];
9117 buffer[j + 1] = tmp;
9118 swapped = 1;
9123 else {
9124 /* Remember any valid modifier if given */
9125 if (strchr("hlL", *fmt) != 0)
9126 descr->modifier = tolower((int)*fmt++);
9128 descr->type = *fmt;
9129 if (strchr("efgcsndoxui", *fmt) == 0) {
9130 fmtObj->error = "bad scan conversion character";
9131 return JIM_ERR;
9133 else if (*fmt == 'c' && descr->width != 0) {
9134 fmtObj->error = "field width may not be specified in %c " "conversion";
9135 return JIM_ERR;
9137 else if (*fmt == 'u' && descr->modifier == 'l') {
9138 fmtObj->error = "unsigned wide not supported";
9139 return JIM_ERR;
9142 curr++;
9144 done:
9145 return JIM_OK;
9148 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9150 #define FormatGetCnvCount(_fo_) \
9151 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9152 #define FormatGetMaxPos(_fo_) \
9153 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9154 #define FormatGetError(_fo_) \
9155 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9157 /* JimScanAString is used to scan an unspecified string that ends with
9158 * next WS, or a string that is specified via a charset.
9161 static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
9163 char *buffer = Jim_StrDup(str);
9164 char *p = buffer;
9166 while (*str) {
9167 int c;
9168 int n;
9170 if (!sdescr && isspace(UCHAR(*str)))
9171 break; /* EOS via WS if unspecified */
9173 n = utf8_tounicode(str, &c);
9174 if (sdescr && !JimCharsetMatch(sdescr, c, JIM_CHARSET_SCAN))
9175 break;
9176 while (n--)
9177 *p++ = *str++;
9179 *p = 0;
9180 return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
9183 /* ScanOneEntry will scan one entry out of the string passed as argument.
9184 * It use the sscanf() function for this task. After extracting and
9185 * converting of the value, the count of scanned characters will be
9186 * returned of -1 in case of no conversion tool place and string was
9187 * already scanned thru */
9189 static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int strLen,
9190 ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
9192 const char *tok;
9193 const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
9194 size_t scanned = 0;
9195 size_t anchor = pos;
9196 int i;
9197 Jim_Obj *tmpObj = NULL;
9199 /* First pessimistically assume, we will not scan anything :-) */
9200 *valObjPtr = 0;
9201 if (descr->prefix) {
9202 /* There was a prefix given before the conversion, skip it and adjust
9203 * the string-to-be-parsed accordingly */
9204 /* XXX: Should be checking strLen, not str[pos] */
9205 for (i = 0; pos < strLen && descr->prefix[i]; ++i) {
9206 /* If prefix require, skip WS */
9207 if (isspace(UCHAR(descr->prefix[i])))
9208 while (pos < strLen && isspace(UCHAR(str[pos])))
9209 ++pos;
9210 else if (descr->prefix[i] != str[pos])
9211 break; /* Prefix do not match here, leave the loop */
9212 else
9213 ++pos; /* Prefix matched so far, next round */
9215 if (pos >= strLen) {
9216 return -1; /* All of str consumed: EOF condition */
9218 else if (descr->prefix[i] != 0)
9219 return 0; /* Not whole prefix consumed, no conversion possible */
9221 /* For all but following conversion, skip leading WS */
9222 if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
9223 while (isspace(UCHAR(str[pos])))
9224 ++pos;
9225 /* Determine how much skipped/scanned so far */
9226 scanned = pos - anchor;
9228 /* %c is a special, simple case. no width */
9229 if (descr->type == 'n') {
9230 /* Return pseudo conversion means: how much scanned so far? */
9231 *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
9233 else if (pos >= strLen) {
9234 /* Cannot scan anything, as str is totally consumed */
9235 return -1;
9237 else if (descr->type == 'c') {
9238 int c;
9239 scanned += utf8_tounicode(&str[pos], &c);
9240 *valObjPtr = Jim_NewIntObj(interp, c);
9241 return scanned;
9243 else {
9244 /* Processing of conversions follows ... */
9245 if (descr->width > 0) {
9246 /* Do not try to scan as fas as possible but only the given width.
9247 * To ensure this, we copy the part that should be scanned. */
9248 size_t sLen = utf8_strlen(&str[pos], strLen - pos);
9249 size_t tLen = descr->width > sLen ? sLen : descr->width;
9251 tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
9252 tok = tmpObj->bytes;
9254 else {
9255 /* As no width was given, simply refer to the original string */
9256 tok = &str[pos];
9258 switch (descr->type) {
9259 case 'd':
9260 case 'o':
9261 case 'x':
9262 case 'u':
9263 case 'i':{
9264 char *endp; /* Position where the number finished */
9265 jim_wide w;
9267 int base = descr->type == 'o' ? 8
9268 : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
9270 /* Try to scan a number with the given base */
9271 w = strtoull(tok, &endp, base);
9272 if (endp == tok && base == 0) {
9273 /* If scanning failed, and base was undetermined, simply
9274 * put it to 10 and try once more. This should catch the
9275 * case where %i begin to parse a number prefix (e.g.
9276 * '0x' but no further digits follows. This will be
9277 * handled as a ZERO followed by a char 'x' by Tcl */
9278 w = strtoull(tok, &endp, 10);
9281 if (endp != tok) {
9282 /* There was some number sucessfully scanned! */
9283 *valObjPtr = Jim_NewIntObj(interp, w);
9285 /* Adjust the number-of-chars scanned so far */
9286 scanned += endp - tok;
9288 else {
9289 /* Nothing was scanned. We have to determine if this
9290 * happened due to e.g. prefix mismatch or input str
9291 * exhausted */
9292 scanned = *tok ? 0 : -1;
9294 break;
9296 case 's':
9297 case '[':{
9298 *valObjPtr = JimScanAString(interp, descr->arg, tok);
9299 scanned += Jim_Length(*valObjPtr);
9300 break;
9302 case 'e':
9303 case 'f':
9304 case 'g':{
9305 char *endp;
9306 double value = strtod(tok, &endp);
9308 if (endp != tok) {
9309 /* There was some number sucessfully scanned! */
9310 *valObjPtr = Jim_NewDoubleObj(interp, value);
9311 /* Adjust the number-of-chars scanned so far */
9312 scanned += endp - tok;
9314 else {
9315 /* Nothing was scanned. We have to determine if this
9316 * happened due to e.g. prefix mismatch or input str
9317 * exhausted */
9318 scanned = *tok ? 0 : -1;
9320 break;
9323 /* If a substring was allocated (due to pre-defined width) do not
9324 * forget to free it */
9325 if (tmpObj) {
9326 Jim_FreeNewObj(interp, tmpObj);
9329 return scanned;
9332 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9333 * string and returns all converted (and not ignored) values in a list back
9334 * to the caller. If an error occured, a NULL pointer will be returned */
9336 Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
9338 size_t i, pos;
9339 int scanned = 1;
9340 const char *str = Jim_String(strObjPtr);
9341 int strLen = Jim_Utf8Length(interp, strObjPtr);
9342 Jim_Obj *resultList = 0;
9343 Jim_Obj **resultVec = 0;
9344 int resultc;
9345 Jim_Obj *emptyStr = 0;
9346 ScanFmtStringObj *fmtObj;
9348 /* This should never happen. The format object should already be of the correct type */
9349 JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
9351 fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
9352 /* Check if format specification was valid */
9353 if (fmtObj->error != 0) {
9354 if (flags & JIM_ERRMSG)
9355 Jim_SetResultString(interp, fmtObj->error, -1);
9356 return 0;
9358 /* Allocate a new "shared" empty string for all unassigned conversions */
9359 emptyStr = Jim_NewEmptyStringObj(interp);
9360 Jim_IncrRefCount(emptyStr);
9361 /* Create a list and fill it with empty strings up to max specified XPG3 */
9362 resultList = Jim_NewListObj(interp, 0, 0);
9363 if (fmtObj->maxPos > 0) {
9364 for (i = 0; i < fmtObj->maxPos; ++i)
9365 Jim_ListAppendElement(interp, resultList, emptyStr);
9366 JimListGetElements(interp, resultList, &resultc, &resultVec);
9368 /* Now handle every partial format description */
9369 for (i = 0, pos = 0; i < fmtObj->count; ++i) {
9370 ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
9371 Jim_Obj *value = 0;
9373 /* Only last type may be "literal" w/o conversion - skip it! */
9374 if (descr->type == 0)
9375 continue;
9376 /* As long as any conversion could be done, we will proceed */
9377 if (scanned > 0)
9378 scanned = ScanOneEntry(interp, str, pos, strLen, fmtObj, i, &value);
9379 /* In case our first try results in EOF, we will leave */
9380 if (scanned == -1 && i == 0)
9381 goto eof;
9382 /* Advance next pos-to-be-scanned for the amount scanned already */
9383 pos += scanned;
9385 /* value == 0 means no conversion took place so take empty string */
9386 if (value == 0)
9387 value = Jim_NewEmptyStringObj(interp);
9388 /* If value is a non-assignable one, skip it */
9389 if (descr->pos == -1) {
9390 Jim_FreeNewObj(interp, value);
9392 else if (descr->pos == 0)
9393 /* Otherwise append it to the result list if no XPG3 was given */
9394 Jim_ListAppendElement(interp, resultList, value);
9395 else if (resultVec[descr->pos - 1] == emptyStr) {
9396 /* But due to given XPG3, put the value into the corr. slot */
9397 Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
9398 Jim_IncrRefCount(value);
9399 resultVec[descr->pos - 1] = value;
9401 else {
9402 /* Otherwise, the slot was already used - free obj and ERROR */
9403 Jim_FreeNewObj(interp, value);
9404 goto err;
9407 Jim_DecrRefCount(interp, emptyStr);
9408 return resultList;
9409 eof:
9410 Jim_DecrRefCount(interp, emptyStr);
9411 Jim_FreeNewObj(interp, resultList);
9412 return (Jim_Obj *)EOF;
9413 err:
9414 Jim_DecrRefCount(interp, emptyStr);
9415 Jim_FreeNewObj(interp, resultList);
9416 return 0;
9419 /* -----------------------------------------------------------------------------
9420 * Pseudo Random Number Generation
9421 * ---------------------------------------------------------------------------*/
9422 /* Initialize the sbox with the numbers from 0 to 255 */
9423 static void JimPrngInit(Jim_Interp *interp)
9425 #define PRNG_SEED_SIZE 256
9426 int i;
9427 unsigned int *seed;
9428 time_t t = time(NULL);
9430 interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
9432 seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
9433 for (i = 0; i < PRNG_SEED_SIZE; i++) {
9434 seed[i] = (rand() ^ t ^ clock());
9436 JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
9437 Jim_Free(seed);
9440 /* Generates N bytes of random data */
9441 static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
9443 Jim_PrngState *prng;
9444 unsigned char *destByte = (unsigned char *)dest;
9445 unsigned int si, sj, x;
9447 /* initialization, only needed the first time */
9448 if (interp->prngState == NULL)
9449 JimPrngInit(interp);
9450 prng = interp->prngState;
9451 /* generates 'len' bytes of pseudo-random numbers */
9452 for (x = 0; x < len; x++) {
9453 prng->i = (prng->i + 1) & 0xff;
9454 si = prng->sbox[prng->i];
9455 prng->j = (prng->j + si) & 0xff;
9456 sj = prng->sbox[prng->j];
9457 prng->sbox[prng->i] = sj;
9458 prng->sbox[prng->j] = si;
9459 *destByte++ = prng->sbox[(si + sj) & 0xff];
9463 /* Re-seed the generator with user-provided bytes */
9464 static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
9466 int i;
9467 Jim_PrngState *prng;
9469 /* initialization, only needed the first time */
9470 if (interp->prngState == NULL)
9471 JimPrngInit(interp);
9472 prng = interp->prngState;
9474 /* Set the sbox[i] with i */
9475 for (i = 0; i < 256; i++)
9476 prng->sbox[i] = i;
9477 /* Now use the seed to perform a random permutation of the sbox */
9478 for (i = 0; i < seedLen; i++) {
9479 unsigned char t;
9481 t = prng->sbox[i & 0xFF];
9482 prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
9483 prng->sbox[seed[i]] = t;
9485 prng->i = prng->j = 0;
9487 /* discard at least the first 256 bytes of stream.
9488 * borrow the seed buffer for this
9490 for (i = 0; i < 256; i += seedLen) {
9491 JimRandomBytes(interp, seed, seedLen);
9495 /* [incr] */
9496 static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
9498 jim_wide wideValue, increment = 1;
9499 Jim_Obj *intObjPtr;
9501 if (argc != 2 && argc != 3) {
9502 Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
9503 return JIM_ERR;
9505 if (argc == 3) {
9506 if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)
9507 return JIM_ERR;
9509 intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
9510 if (!intObjPtr) {
9511 /* Set missing variable to 0 */
9512 wideValue = 0;
9514 else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
9515 return JIM_ERR;
9517 if (!intObjPtr || Jim_IsShared(intObjPtr)) {
9518 intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
9519 if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
9520 Jim_FreeNewObj(interp, intObjPtr);
9521 return JIM_ERR;
9524 else {
9525 /* Can do it the quick way */
9526 Jim_InvalidateStringRep(intObjPtr);
9527 JimWideValue(intObjPtr) = wideValue + increment;
9529 /* The following step is required in order to invalidate the
9530 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9531 if (argv[1]->typePtr != &variableObjType) {
9532 /* Note that this can't fail since GetVariable already succeeded */
9533 Jim_SetVariable(interp, argv[1], intObjPtr);
9536 Jim_SetResult(interp, intObjPtr);
9537 return JIM_OK;
9541 /* -----------------------------------------------------------------------------
9542 * Eval
9543 * ---------------------------------------------------------------------------*/
9544 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9545 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9547 /* Handle calls to the [unknown] command */
9548 static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv, Jim_Obj *fileNameObj,
9549 int linenr)
9551 Jim_Obj **v, *sv[JIM_EVAL_SARGV_LEN];
9552 int retCode;
9554 /* If JimUnknown() is recursively called too many times...
9555 * done here
9557 if (interp->unknown_called > 50) {
9558 return JIM_ERR;
9561 /* If the [unknown] command does not exists returns
9562 * just now */
9563 if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
9564 return JIM_ERR;
9566 /* The object interp->unknown just contains
9567 * the "unknown" string, it is used in order to
9568 * avoid to lookup the unknown command every time
9569 * but instread to cache the result. */
9570 if (argc + 1 <= JIM_EVAL_SARGV_LEN)
9571 v = sv;
9572 else
9573 v = Jim_Alloc(sizeof(Jim_Obj *) * (argc + 1));
9574 /* Make a copy of the arguments vector, but shifted on
9575 * the right of one position. The command name of the
9576 * command will be instead the first argument of the
9577 * [unknown] call. */
9578 memcpy(v + 1, argv, sizeof(Jim_Obj *) * argc);
9579 v[0] = interp->unknown;
9580 /* Call it */
9581 interp->unknown_called++;
9582 retCode = JimEvalObjVector(interp, argc + 1, v, fileNameObj, linenr);
9583 interp->unknown_called--;
9585 /* Clean up */
9586 if (v != sv)
9587 Jim_Free(v);
9588 return retCode;
9591 /* Eval the object vector 'objv' composed of 'objc' elements.
9592 * Every element is used as single argument.
9593 * Jim_EvalObj() will call this function every time its object
9594 * argument is of "list" type, with no string representation.
9596 * This is possible because the string representation of a
9597 * list object generated by the UpdateStringOfList is made
9598 * in a way that ensures that every list element is a different
9599 * command argument. */
9600 static int JimEvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv,
9601 Jim_Obj *fileNameObj, int linenr)
9603 int i, retcode;
9604 Jim_Cmd *cmdPtr;
9606 /* Incr refcount of arguments. */
9607 for (i = 0; i < objc; i++)
9608 Jim_IncrRefCount(objv[i]);
9609 /* Command lookup */
9610 cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
9611 if (cmdPtr == NULL) {
9612 retcode = JimUnknown(interp, objc, objv, fileNameObj, linenr);
9614 else {
9615 /* Call it -- Make sure result is an empty object. */
9616 JimIncrCmdRefCount(cmdPtr);
9617 Jim_SetEmptyResult(interp);
9618 if (cmdPtr->isproc) {
9619 retcode = JimCallProcedure(interp, cmdPtr, fileNameObj, linenr, objc, objv);
9621 else {
9622 interp->cmdPrivData = cmdPtr->u.native.privData;
9623 retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
9625 JimDecrCmdRefCount(interp, cmdPtr);
9627 /* Decr refcount of arguments and return the retcode */
9628 for (i = 0; i < objc; i++)
9629 Jim_DecrRefCount(interp, objv[i]);
9631 return retcode;
9634 int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
9636 return JimEvalObjVector(interp, objc, objv, interp->emptyObj, 1);
9640 * Invokes 'prefix' as a command with the objv array as arguments.
9642 int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix, int objc, Jim_Obj *const *objv)
9644 int i;
9645 int ret;
9646 Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
9648 nargv[0] = prefix;
9649 for (i = 0; i < objc; i++) {
9650 nargv[i + 1] = objv[i];
9652 ret = Jim_EvalObjVector(interp, objc + 1, nargv);
9653 Jim_Free(nargv);
9654 return ret;
9657 static void JimAddErrorToStack(Jim_Interp *interp, int retcode, Jim_Obj *fileNameObj, int line)
9659 int rc = retcode;
9661 if (rc == JIM_ERR && !interp->errorFlag) {
9662 /* This is the first error, so save the file/line information and reset the stack */
9663 interp->errorFlag = 1;
9664 Jim_IncrRefCount(fileNameObj);
9665 Jim_DecrRefCount(interp, interp->errorFileNameObj);
9666 interp->errorFileNameObj = fileNameObj;
9667 interp->errorLine = line;
9669 JimResetStackTrace(interp);
9670 /* Always add a level where the error first occurs */
9671 interp->addStackTrace++;
9674 /* Now if this is an "interesting" level, add it to the stack trace */
9675 if (rc == JIM_ERR && interp->addStackTrace > 0) {
9676 /* Add the stack info for the current level */
9678 JimAppendStackTrace(interp, Jim_String(interp->errorProc), fileNameObj, line);
9680 /* Note: if we didn't have a filename for this level,
9681 * don't clear the addStackTrace flag
9682 * so we can pick it up at the next level
9684 if (Jim_Length(fileNameObj)) {
9685 interp->addStackTrace = 0;
9688 Jim_DecrRefCount(interp, interp->errorProc);
9689 interp->errorProc = interp->emptyObj;
9690 Jim_IncrRefCount(interp->errorProc);
9692 else if (rc == JIM_RETURN && interp->returnCode == JIM_ERR) {
9693 /* Propagate the addStackTrace value through 'return -code error' */
9695 else {
9696 interp->addStackTrace = 0;
9700 /* And delete any local procs */
9701 static void JimDeleteLocalProcs(Jim_Interp *interp)
9703 if (interp->localProcs) {
9704 char *procname;
9706 while ((procname = Jim_StackPop(interp->localProcs)) != NULL) {
9707 /* If there is a pushed command, find it */
9708 Jim_Cmd *prevCmd = NULL;
9709 Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, procname);
9710 if (he) {
9711 Jim_Cmd *cmd = (Jim_Cmd *)he->u.val;
9712 if (cmd->isproc && cmd->u.proc.prevCmd) {
9713 prevCmd = cmd->u.proc.prevCmd;
9714 cmd->u.proc.prevCmd = NULL;
9718 /* Delete the local proc */
9719 Jim_DeleteCommand(interp, procname);
9721 if (prevCmd) {
9722 /* And restore the pushed command */
9723 Jim_AddHashEntry(&interp->commands, procname, prevCmd);
9725 Jim_Free(procname);
9727 Jim_FreeStack(interp->localProcs);
9728 Jim_Free(interp->localProcs);
9729 interp->localProcs = NULL;
9733 static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
9735 Jim_Obj *objPtr;
9737 switch (token->type) {
9738 case JIM_TT_STR:
9739 case JIM_TT_ESC:
9740 objPtr = token->objPtr;
9741 break;
9742 case JIM_TT_VAR:
9743 objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
9744 break;
9745 case JIM_TT_DICTSUGAR:
9746 objPtr = JimExpandDictSugar(interp, token->objPtr);
9747 break;
9748 case JIM_TT_EXPRSUGAR:
9749 objPtr = JimExpandExprSugar(interp, token->objPtr);
9750 break;
9751 case JIM_TT_CMD:
9752 switch (Jim_EvalObj(interp, token->objPtr)) {
9753 case JIM_OK:
9754 case JIM_RETURN:
9755 objPtr = interp->result;
9756 break;
9757 case JIM_BREAK:
9758 /* Stop substituting */
9759 return JIM_BREAK;
9760 case JIM_CONTINUE:
9761 /* just skip this one */
9762 return JIM_CONTINUE;
9763 default:
9764 return JIM_ERR;
9766 break;
9767 default:
9768 JimPanic((1,
9769 "default token type (%d) reached " "in Jim_SubstObj().", token->type));
9770 objPtr = NULL;
9771 break;
9773 if (objPtr) {
9774 *objPtrPtr = objPtr;
9775 return JIM_OK;
9777 return JIM_ERR;
9780 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9781 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9782 * The returned object has refcount = 0.
9784 static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
9786 int totlen = 0, i;
9787 Jim_Obj **intv;
9788 Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
9789 Jim_Obj *objPtr;
9790 char *s;
9792 if (tokens <= JIM_EVAL_SINTV_LEN)
9793 intv = sintv;
9794 else
9795 intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
9797 /* Compute every token forming the argument
9798 * in the intv objects vector. */
9799 for (i = 0; i < tokens; i++) {
9800 switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
9801 case JIM_OK:
9802 case JIM_RETURN:
9803 break;
9804 case JIM_BREAK:
9805 if (flags & JIM_SUBST_FLAG) {
9806 /* Stop here */
9807 tokens = i;
9808 continue;
9810 /* XXX: Should probably set an error about break outside loop */
9811 /* fall through to error */
9812 case JIM_CONTINUE:
9813 if (flags & JIM_SUBST_FLAG) {
9814 intv[i] = NULL;
9815 continue;
9817 /* XXX: Ditto continue outside loop */
9818 /* fall through to error */
9819 default:
9820 while (i--) {
9821 Jim_DecrRefCount(interp, intv[i]);
9823 if (intv != sintv) {
9824 Jim_Free(intv);
9826 return NULL;
9828 Jim_IncrRefCount(intv[i]);
9829 Jim_String(intv[i]);
9830 totlen += intv[i]->length;
9833 /* Fast path return for a single token */
9834 if (tokens == 1 && intv[0] && intv == sintv) {
9835 Jim_DecrRefCount(interp, intv[0]);
9836 return intv[0];
9839 /* Concatenate every token in an unique
9840 * object. */
9841 objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
9843 if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
9844 && token[2].type == JIM_TT_VAR) {
9845 /* May be able to do fast interpolated object -> dictSubst */
9846 objPtr->typePtr = &interpolatedObjType;
9847 objPtr->internalRep.twoPtrValue.ptr1 = (void *)token;
9848 objPtr->internalRep.twoPtrValue.ptr2 = intv[2];
9849 Jim_IncrRefCount(intv[2]);
9852 s = objPtr->bytes = Jim_Alloc(totlen + 1);
9853 objPtr->length = totlen;
9854 for (i = 0; i < tokens; i++) {
9855 if (intv[i]) {
9856 memcpy(s, intv[i]->bytes, intv[i]->length);
9857 s += intv[i]->length;
9858 Jim_DecrRefCount(interp, intv[i]);
9861 objPtr->bytes[totlen] = '\0';
9862 /* Free the intv vector if not static. */
9863 if (intv != sintv) {
9864 Jim_Free(intv);
9867 return objPtr;
9871 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9872 * Otherwise eval with Jim_EvalObj()
9874 static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *fileNameObj, int linenr)
9876 if (!Jim_IsList(listPtr)) {
9877 return Jim_EvalObj(interp, listPtr);
9879 else {
9880 int retcode = JIM_OK;
9882 if (listPtr->internalRep.listValue.len) {
9883 Jim_IncrRefCount(listPtr);
9884 retcode = JimEvalObjVector(interp,
9885 listPtr->internalRep.listValue.len,
9886 listPtr->internalRep.listValue.ele, fileNameObj, linenr);
9887 Jim_DecrRefCount(interp, listPtr);
9889 return retcode;
9893 int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
9895 int i;
9896 ScriptObj *script;
9897 ScriptToken *token;
9898 int retcode = JIM_OK;
9899 Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
9900 int linenr = 0;
9902 interp->errorFlag = 0;
9904 /* If the object is of type "list", with no string rep we can call
9905 * a specialized version of Jim_EvalObj() */
9906 if (Jim_IsList(scriptObjPtr) && scriptObjPtr->bytes == NULL) {
9907 return JimEvalObjList(interp, scriptObjPtr, interp->emptyObj, 1);
9910 Jim_IncrRefCount(scriptObjPtr); /* Make sure it's shared. */
9911 script = Jim_GetScript(interp, scriptObjPtr);
9913 /* Reset the interpreter result. This is useful to
9914 * return the empty result in the case of empty program. */
9915 Jim_SetEmptyResult(interp);
9917 #ifdef JIM_OPTIMIZATION
9918 /* Check for one of the following common scripts used by for, while
9920 * {}
9921 * incr a
9923 if (script->len == 0) {
9924 Jim_DecrRefCount(interp, scriptObjPtr);
9925 return JIM_OK;
9927 if (script->len == 3
9928 && script->token[1].objPtr->typePtr == &commandObjType
9929 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
9930 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
9931 && script->token[2].objPtr->typePtr == &variableObjType) {
9933 Jim_Obj *objPtr = Jim_GetVariable(interp, script->token[2].objPtr, JIM_NONE);
9935 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
9936 JimWideValue(objPtr)++;
9937 Jim_InvalidateStringRep(objPtr);
9938 Jim_DecrRefCount(interp, scriptObjPtr);
9939 Jim_SetResult(interp, objPtr);
9940 return JIM_OK;
9943 #endif
9945 /* Now we have to make sure the internal repr will not be
9946 * freed on shimmering.
9948 * Think for example to this:
9950 * set x {llength $x; ... some more code ...}; eval $x
9952 * In order to preserve the internal rep, we increment the
9953 * inUse field of the script internal rep structure. */
9954 script->inUse++;
9956 token = script->token;
9957 argv = sargv;
9959 /* Execute every command sequentially until the end of the script
9960 * or an error occurs.
9962 for (i = 0; i < script->len && retcode == JIM_OK; ) {
9963 int argc;
9964 int j;
9965 Jim_Cmd *cmd;
9967 /* First token of the line is always JIM_TT_LINE */
9968 argc = token[i].objPtr->internalRep.scriptLineValue.argc;
9969 linenr = token[i].objPtr->internalRep.scriptLineValue.line;
9971 /* Allocate the arguments vector if required */
9972 if (argc > JIM_EVAL_SARGV_LEN)
9973 argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
9975 /* Skip the JIM_TT_LINE token */
9976 i++;
9978 /* Populate the arguments objects.
9979 * If an error occurs, retcode will be set and
9980 * 'j' will be set to the number of args expanded
9982 for (j = 0; j < argc; j++) {
9983 long wordtokens = 1;
9984 int expand = 0;
9985 Jim_Obj *wordObjPtr = NULL;
9987 if (token[i].type == JIM_TT_WORD) {
9988 wordtokens = JimWideValue(token[i++].objPtr);
9989 if (wordtokens < 0) {
9990 expand = 1;
9991 wordtokens = -wordtokens;
9995 if (wordtokens == 1) {
9996 /* Fast path if the token does not
9997 * need interpolation */
9999 switch (token[i].type) {
10000 case JIM_TT_ESC:
10001 case JIM_TT_STR:
10002 wordObjPtr = token[i].objPtr;
10003 break;
10004 case JIM_TT_VAR:
10005 wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
10006 break;
10007 case JIM_TT_EXPRSUGAR:
10008 wordObjPtr = JimExpandExprSugar(interp, token[i].objPtr);
10009 break;
10010 case JIM_TT_DICTSUGAR:
10011 wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
10012 break;
10013 case JIM_TT_CMD:
10014 retcode = Jim_EvalObj(interp, token[i].objPtr);
10015 if (retcode == JIM_OK) {
10016 wordObjPtr = Jim_GetResult(interp);
10018 break;
10019 default:
10020 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10023 else {
10024 /* For interpolation we call a helper
10025 * function to do the work for us. */
10026 wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
10029 if (!wordObjPtr) {
10030 if (retcode == JIM_OK) {
10031 retcode = JIM_ERR;
10033 break;
10036 Jim_IncrRefCount(wordObjPtr);
10037 i += wordtokens;
10039 if (!expand) {
10040 argv[j] = wordObjPtr;
10042 else {
10043 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10044 int len = Jim_ListLength(interp, wordObjPtr);
10045 int newargc = argc + len - 1;
10046 int k;
10048 if (len > 1) {
10049 if (argv == sargv) {
10050 if (newargc > JIM_EVAL_SARGV_LEN) {
10051 argv = Jim_Alloc(sizeof(*argv) * newargc);
10052 memcpy(argv, sargv, sizeof(*argv) * j);
10055 else {
10056 /* Need to realloc to make room for (len - 1) more entries */
10057 argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
10061 /* Now copy in the expanded version */
10062 for (k = 0; k < len; k++) {
10063 argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
10064 Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
10067 /* The original object reference is no longer needed,
10068 * after the expansion it is no longer present on
10069 * the argument vector, but the single elements are
10070 * in its place. */
10071 Jim_DecrRefCount(interp, wordObjPtr);
10073 /* And update the indexes */
10074 j--;
10075 argc += len - 1;
10079 if (retcode == JIM_OK && argc) {
10080 /* Lookup the command to call */
10081 cmd = Jim_GetCommand(interp, argv[0], JIM_ERRMSG);
10082 if (cmd != NULL) {
10083 /* Call it -- Make sure result is an empty object. */
10084 JimIncrCmdRefCount(cmd);
10085 Jim_SetEmptyResult(interp);
10086 if (cmd->isproc) {
10087 retcode =
10088 JimCallProcedure(interp, cmd, script->fileNameObj, linenr, argc, argv);
10089 } else {
10090 interp->cmdPrivData = cmd->u.native.privData;
10091 retcode = cmd->u.native.cmdProc(interp, argc, argv);
10093 JimDecrCmdRefCount(interp, cmd);
10095 else {
10096 /* Call [unknown] */
10097 retcode = JimUnknown(interp, argc, argv, script->fileNameObj, linenr);
10099 if (interp->signal_level && interp->sigmask) {
10100 /* Check for a signal after each command */
10101 retcode = JIM_SIGNAL;
10105 /* Finished with the command, so decrement ref counts of each argument */
10106 while (j-- > 0) {
10107 Jim_DecrRefCount(interp, argv[j]);
10110 if (argv != sargv) {
10111 Jim_Free(argv);
10112 argv = sargv;
10116 /* Possibly add to the error stack trace */
10117 JimAddErrorToStack(interp, retcode, script->fileNameObj, linenr);
10119 /* Note that we don't have to decrement inUse, because the
10120 * following code transfers our use of the reference again to
10121 * the script object. */
10122 Jim_FreeIntRep(interp, scriptObjPtr);
10123 scriptObjPtr->typePtr = &scriptObjType;
10124 Jim_SetIntRepPtr(scriptObjPtr, script);
10125 Jim_DecrRefCount(interp, scriptObjPtr);
10127 return retcode;
10130 static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
10132 int retcode;
10133 /* If argObjPtr begins with '&', do an automatic upvar */
10134 const char *varname = Jim_String(argNameObj);
10135 if (*varname == '&') {
10136 /* First check that the target variable exists */
10137 Jim_Obj *objPtr;
10138 Jim_CallFrame *savedCallFrame = interp->framePtr;
10140 interp->framePtr = interp->framePtr->parentCallFrame;
10141 objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
10142 interp->framePtr = savedCallFrame;
10143 if (!objPtr) {
10144 return JIM_ERR;
10147 /* It exists, so perform the binding. */
10148 objPtr = Jim_NewStringObj(interp, varname + 1, -1);
10149 Jim_IncrRefCount(objPtr);
10150 retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parentCallFrame);
10151 Jim_DecrRefCount(interp, objPtr);
10153 else {
10154 retcode = Jim_SetVariable(interp, argNameObj, argValObj);
10156 return retcode;
10160 * Sets the interp result to be an error message indicating the required proc args.
10162 static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
10164 /* Create a nice error message, consistent with Tcl 8.5 */
10165 Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
10166 int i;
10168 for (i = 0; i < cmd->u.proc.argListLen; i++) {
10169 Jim_AppendString(interp, argmsg, " ", 1);
10171 if (i == cmd->u.proc.argsPos) {
10172 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10173 /* Renamed args */
10174 Jim_AppendString(interp, argmsg, "?", 1);
10175 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
10176 Jim_AppendString(interp, argmsg, " ...?", -1);
10178 else {
10179 /* We have plain args */
10180 Jim_AppendString(interp, argmsg, "?argument ...?", -1);
10183 else {
10184 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10185 Jim_AppendString(interp, argmsg, "?", 1);
10186 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10187 Jim_AppendString(interp, argmsg, "?", 1);
10189 else {
10190 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10194 Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
10195 Jim_FreeNewObj(interp, argmsg);
10198 /* Call a procedure implemented in Tcl.
10199 * It's possible to speed-up a lot this function, currently
10200 * the callframes are not cached, but allocated and
10201 * destroied every time. What is expecially costly is
10202 * to create/destroy the local vars hash table every time.
10204 * This can be fixed just implementing callframes caching
10205 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10206 static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, Jim_Obj *fileNameObj, int linenr, int argc,
10207 Jim_Obj *const *argv)
10209 Jim_CallFrame *callFramePtr;
10210 Jim_Stack *prevLocalProcs;
10211 int i, d, retcode, optargs;
10213 /* Check arity */
10214 if (argc - 1 < cmd->u.proc.reqArity ||
10215 (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
10216 JimSetProcWrongArgs(interp, argv[0], cmd);
10217 return JIM_ERR;
10220 /* Check if there are too nested calls */
10221 if (interp->framePtr->level == interp->maxNestingDepth) {
10222 Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
10223 return JIM_ERR;
10226 /* Create a new callframe */
10227 callFramePtr = JimCreateCallFrame(interp, interp->framePtr);
10228 callFramePtr->argv = argv;
10229 callFramePtr->argc = argc;
10230 callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
10231 callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
10232 callFramePtr->staticVars = cmd->u.proc.staticVars;
10233 callFramePtr->fileNameObj = fileNameObj;
10234 callFramePtr->line = linenr;
10235 Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
10236 Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
10237 interp->framePtr = callFramePtr;
10239 /* How many optional args are available */
10240 optargs = (argc - 1 - cmd->u.proc.reqArity);
10242 /* Step 'i' along the actual args, and step 'd' along the formal args */
10243 i = 1;
10244 for (d = 0; d < cmd->u.proc.argListLen; d++) {
10245 Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
10246 if (d == cmd->u.proc.argsPos) {
10247 /* assign $args */
10248 Jim_Obj *listObjPtr;
10249 int argsLen = 0;
10250 if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
10251 argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
10253 listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
10255 /* It is possible to rename args. */
10256 if (cmd->u.proc.arglist[d].defaultObjPtr) {
10257 nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
10259 retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
10260 if (retcode != JIM_OK) {
10261 goto badargset;
10264 i += argsLen;
10265 continue;
10268 /* Optional or required? */
10269 if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
10270 retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
10272 else {
10273 /* Ran out, so use the default */
10274 retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
10276 if (retcode != JIM_OK) {
10277 goto badargset;
10281 /* Install a new stack for local procs */
10282 prevLocalProcs = interp->localProcs;
10283 interp->localProcs = NULL;
10285 /* Eval the body */
10286 retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
10288 /* Delete any local procs */
10289 JimDeleteLocalProcs(interp);
10290 interp->localProcs = prevLocalProcs;
10292 badargset:
10293 /* Destroy the callframe */
10294 interp->framePtr = interp->framePtr->parentCallFrame;
10295 if (callFramePtr->vars.size != JIM_HT_INITIAL_SIZE) {
10296 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NONE);
10298 else {
10299 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NOHT);
10301 /* Handle the JIM_EVAL return code */
10302 while (retcode == JIM_EVAL) {
10303 Jim_Obj *resultScriptObjPtr = Jim_GetResult(interp);
10305 Jim_IncrRefCount(resultScriptObjPtr);
10306 /* Should be a list! */
10307 retcode = JimEvalObjList(interp, resultScriptObjPtr, fileNameObj, linenr);
10308 Jim_DecrRefCount(interp, resultScriptObjPtr);
10310 /* Handle the JIM_RETURN return code */
10311 if (retcode == JIM_RETURN) {
10312 if (--interp->returnLevel <= 0) {
10313 retcode = interp->returnCode;
10314 interp->returnCode = JIM_OK;
10315 interp->returnLevel = 0;
10318 else if (retcode == JIM_ERR) {
10319 interp->addStackTrace++;
10320 Jim_DecrRefCount(interp, interp->errorProc);
10321 interp->errorProc = argv[0];
10322 Jim_IncrRefCount(interp->errorProc);
10324 return retcode;
10327 int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script)
10329 int retval;
10330 Jim_Obj *scriptObjPtr;
10332 scriptObjPtr = Jim_NewStringObj(interp, script, -1);
10333 Jim_IncrRefCount(scriptObjPtr);
10335 if (filename) {
10336 Jim_Obj *prevScriptObj;
10338 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
10340 prevScriptObj = interp->currentScriptObj;
10341 interp->currentScriptObj = scriptObjPtr;
10343 retval = Jim_EvalObj(interp, scriptObjPtr);
10345 interp->currentScriptObj = prevScriptObj;
10347 else {
10348 retval = Jim_EvalObj(interp, scriptObjPtr);
10350 Jim_DecrRefCount(interp, scriptObjPtr);
10351 return retval;
10354 int Jim_Eval(Jim_Interp *interp, const char *script)
10356 return Jim_EvalObj(interp, Jim_NewStringObj(interp, script, -1));
10359 /* Execute script in the scope of the global level */
10360 int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
10362 int retval;
10363 Jim_CallFrame *savedFramePtr = interp->framePtr;
10365 interp->framePtr = interp->topFramePtr;
10366 retval = Jim_Eval(interp, script);
10367 interp->framePtr = savedFramePtr;
10369 return retval;
10372 int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
10374 int retval;
10375 Jim_CallFrame *savedFramePtr = interp->framePtr;
10377 interp->framePtr = interp->topFramePtr;
10378 retval = Jim_EvalFile(interp, filename);
10379 interp->framePtr = savedFramePtr;
10381 return retval;
10384 #include <sys/stat.h>
10386 int Jim_EvalFile(Jim_Interp *interp, const char *filename)
10388 FILE *fp;
10389 char *buf;
10390 Jim_Obj *scriptObjPtr;
10391 Jim_Obj *prevScriptObj;
10392 struct stat sb;
10393 int retcode;
10394 int readlen;
10395 struct JimParseResult result;
10397 if (stat(filename, &sb) != 0 || (fp = fopen(filename, "rt")) == NULL) {
10398 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
10399 return JIM_ERR;
10401 if (sb.st_size == 0) {
10402 fclose(fp);
10403 return JIM_OK;
10406 buf = Jim_Alloc(sb.st_size + 1);
10407 readlen = fread(buf, 1, sb.st_size, fp);
10408 if (ferror(fp)) {
10409 fclose(fp);
10410 Jim_Free(buf);
10411 Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
10412 return JIM_ERR;
10414 fclose(fp);
10415 buf[readlen] = 0;
10417 scriptObjPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
10418 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), 1);
10419 Jim_IncrRefCount(scriptObjPtr);
10421 /* Now check the script for unmatched braces, etc. */
10422 if (SetScriptFromAny(interp, scriptObjPtr, &result) == JIM_ERR) {
10423 const char *msg;
10424 char linebuf[20];
10426 switch (result.missing) {
10427 case '[':
10428 msg = "unmatched \"[\"";
10429 break;
10430 case '{':
10431 msg = "missing close-brace";
10432 break;
10433 case '"':
10434 default:
10435 msg = "missing quote";
10436 break;
10439 snprintf(linebuf, sizeof(linebuf), "%d", result.line);
10441 Jim_SetResultFormatted(interp, "%s in \"%s\" at line %s",
10442 msg, filename, linebuf);
10443 Jim_DecrRefCount(interp, scriptObjPtr);
10444 return JIM_ERR;
10447 prevScriptObj = interp->currentScriptObj;
10448 interp->currentScriptObj = scriptObjPtr;
10450 retcode = Jim_EvalObj(interp, scriptObjPtr);
10452 /* Handle the JIM_RETURN return code */
10453 if (retcode == JIM_RETURN) {
10454 if (--interp->returnLevel <= 0) {
10455 retcode = interp->returnCode;
10456 interp->returnCode = JIM_OK;
10457 interp->returnLevel = 0;
10460 if (retcode == JIM_ERR) {
10461 /* EvalFile changes context, so add a stack frame here */
10462 interp->addStackTrace++;
10465 interp->currentScriptObj = prevScriptObj;
10467 Jim_DecrRefCount(interp, scriptObjPtr);
10469 return retcode;
10472 /* -----------------------------------------------------------------------------
10473 * Subst
10474 * ---------------------------------------------------------------------------*/
10475 static int JimParseSubstStr(struct JimParserCtx *pc)
10477 pc->tstart = pc->p;
10478 pc->tline = pc->linenr;
10479 while (pc->len && *pc->p != '$' && *pc->p != '[') {
10480 if (*pc->p == '\\' && pc->len > 1) {
10481 pc->p++;
10482 pc->len--;
10484 pc->p++;
10485 pc->len--;
10487 pc->tend = pc->p - 1;
10488 pc->tt = JIM_TT_ESC;
10489 return JIM_OK;
10492 static int JimParseSubst(struct JimParserCtx *pc, int flags)
10494 int retval;
10496 if (pc->len == 0) {
10497 pc->tstart = pc->tend = pc->p;
10498 pc->tline = pc->linenr;
10499 pc->tt = JIM_TT_EOL;
10500 pc->eof = 1;
10501 return JIM_OK;
10503 switch (*pc->p) {
10504 case '[':
10505 retval = JimParseCmd(pc);
10506 if (flags & JIM_SUBST_NOCMD) {
10507 pc->tstart--;
10508 pc->tend++;
10509 pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
10511 return retval;
10512 break;
10513 case '$':
10514 if (JimParseVar(pc) == JIM_ERR) {
10515 pc->tstart = pc->tend = pc->p++;
10516 pc->len--;
10517 pc->tline = pc->linenr;
10518 pc->tt = JIM_TT_STR;
10520 else {
10521 if (flags & JIM_SUBST_NOVAR) {
10522 pc->tstart--;
10523 if (flags & JIM_SUBST_NOESC)
10524 pc->tt = JIM_TT_STR;
10525 else
10526 pc->tt = JIM_TT_ESC;
10527 if (*pc->tstart == '{') {
10528 pc->tstart--;
10529 if (*(pc->tend + 1))
10530 pc->tend++;
10534 break;
10535 default:
10536 retval = JimParseSubstStr(pc);
10537 if (flags & JIM_SUBST_NOESC)
10538 pc->tt = JIM_TT_STR;
10539 return retval;
10540 break;
10542 return JIM_OK;
10545 /* The subst object type reuses most of the data structures and functions
10546 * of the script object. Script's data structures are a bit more complex
10547 * for what is needed for [subst]itution tasks, but the reuse helps to
10548 * deal with a single data structure at the cost of some more memory
10549 * usage for substitutions. */
10551 /* This method takes the string representation of an object
10552 * as a Tcl string where to perform [subst]itution, and generates
10553 * the pre-parsed internal representation. */
10554 static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
10556 int scriptTextLen;
10557 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
10558 struct JimParserCtx parser;
10559 struct ScriptObj *script = Jim_Alloc(sizeof(*script));
10560 ParseTokenList tokenlist;
10562 /* Initially parse the subst into tokens (in tokenlist) */
10563 ScriptTokenListInit(&tokenlist);
10565 JimParserInit(&parser, scriptText, scriptTextLen, 1);
10566 while (1) {
10567 JimParseSubst(&parser, flags);
10568 if (parser.eof) {
10569 /* Note that subst doesn't need the EOL token */
10570 break;
10572 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
10573 parser.tline);
10576 /* Create the "real" subst/script tokens from the initial token list */
10577 script->inUse = 1;
10578 script->substFlags = flags;
10579 script->fileNameObj = interp->emptyObj;
10580 Jim_IncrRefCount(script->fileNameObj);
10581 SubstObjAddTokens(interp, script, &tokenlist);
10583 /* No longer need the token list */
10584 ScriptTokenListFree(&tokenlist);
10586 #ifdef DEBUG_SHOW_SUBST
10588 int i;
10590 printf("==== Subst ====\n");
10591 for (i = 0; i < script->len; i++) {
10592 printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
10593 Jim_String(script->token[i].objPtr));
10596 #endif
10598 /* Free the old internal rep and set the new one. */
10599 Jim_FreeIntRep(interp, objPtr);
10600 Jim_SetIntRepPtr(objPtr, script);
10601 objPtr->typePtr = &scriptObjType;
10602 return JIM_OK;
10605 static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
10607 if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
10608 SetSubstFromAny(interp, objPtr, flags);
10609 return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
10612 /* Performs commands,variables,blackslashes substitution,
10613 * storing the result object (with refcount 0) into
10614 * resObjPtrPtr. */
10615 int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
10617 ScriptObj *script = Jim_GetSubst(interp, substObjPtr, flags);
10619 Jim_IncrRefCount(substObjPtr); /* Make sure it's shared. */
10620 /* In order to preserve the internal rep, we increment the
10621 * inUse field of the script internal rep structure. */
10622 script->inUse++;
10624 *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
10626 script->inUse--;
10627 Jim_DecrRefCount(interp, substObjPtr);
10628 if (*resObjPtrPtr == NULL) {
10629 return JIM_ERR;
10631 return JIM_OK;
10634 /* -----------------------------------------------------------------------------
10635 * Core commands utility functions
10636 * ---------------------------------------------------------------------------*/
10637 void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
10639 int i;
10640 Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);
10642 Jim_AppendString(interp, objPtr, "wrong # args: should be \"", -1);
10643 for (i = 0; i < argc; i++) {
10644 Jim_AppendObj(interp, objPtr, argv[i]);
10645 if (!(i + 1 == argc && msg[0] == '\0'))
10646 Jim_AppendString(interp, objPtr, " ", 1);
10648 Jim_AppendString(interp, objPtr, msg, -1);
10649 Jim_AppendString(interp, objPtr, "\"", 1);
10650 Jim_SetResult(interp, objPtr);
10653 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10655 /* type is: 0=commands, 1=procs, 2=channels */
10656 static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
10658 Jim_HashTableIterator *htiter;
10659 Jim_HashEntry *he;
10660 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
10662 /* Check for the non-pattern case. We can do this much more efficiently. */
10663 if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
10664 Jim_Cmd *cmdPtr = Jim_GetCommand(interp, patternObjPtr, JIM_NONE);
10665 if (cmdPtr) {
10666 if (type == 1 && !cmdPtr->isproc) {
10667 /* not a proc */
10669 else if (type == 2 && !Jim_AioFilehandle(interp, patternObjPtr)) {
10670 /* not a channel */
10672 else {
10673 Jim_ListAppendElement(interp, listObjPtr, patternObjPtr);
10676 return listObjPtr;
10679 htiter = Jim_GetHashTableIterator(&interp->commands);
10680 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
10681 Jim_Cmd *cmdPtr = he->u.val;
10682 Jim_Obj *cmdNameObj;
10684 if (type == 1 && !cmdPtr->isproc) {
10685 /* not a proc */
10686 continue;
10688 if (patternObjPtr && !JimStringMatch(interp, patternObjPtr, he->key, 0))
10689 continue;
10691 cmdNameObj = Jim_NewStringObj(interp, he->key, -1);
10693 /* Is it a channel? */
10694 if (type == 2 && !Jim_AioFilehandle(interp, cmdNameObj)) {
10695 Jim_FreeNewObj(interp, cmdNameObj);
10696 continue;
10699 Jim_ListAppendElement(interp, listObjPtr, cmdNameObj);
10701 Jim_FreeHashTableIterator(htiter);
10702 return listObjPtr;
10705 /* Keep this in order */
10706 #define JIM_VARLIST_GLOBALS 0
10707 #define JIM_VARLIST_LOCALS 1
10708 #define JIM_VARLIST_VARS 2
10710 static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
10712 Jim_HashTableIterator *htiter;
10713 Jim_HashEntry *he;
10714 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
10716 if (mode == JIM_VARLIST_GLOBALS) {
10717 htiter = Jim_GetHashTableIterator(&interp->topFramePtr->vars);
10719 else {
10720 /* For [info locals], if we are at top level an emtpy list
10721 * is returned. I don't agree, but we aim at compatibility (SS) */
10722 if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr)
10723 return listObjPtr;
10724 htiter = Jim_GetHashTableIterator(&interp->framePtr->vars);
10726 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
10727 Jim_Var *varPtr = (Jim_Var *)he->u.val;
10729 if (mode == JIM_VARLIST_LOCALS) {
10730 if (varPtr->linkFramePtr != NULL)
10731 continue;
10733 if (patternObjPtr && !JimStringMatch(interp, patternObjPtr, he->key, 0))
10734 continue;
10735 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, he->key, -1));
10737 Jim_FreeHashTableIterator(htiter);
10738 return listObjPtr;
10741 static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
10742 Jim_Obj **objPtrPtr, int info_level_cmd)
10744 Jim_CallFrame *targetCallFrame;
10746 targetCallFrame = JimGetCallFrameByInteger(interp, levelObjPtr);
10747 if (targetCallFrame == NULL) {
10748 return JIM_ERR;
10750 /* No proc call at toplevel callframe */
10751 if (targetCallFrame == interp->topFramePtr) {
10752 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
10753 return JIM_ERR;
10755 if (info_level_cmd) {
10756 *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
10758 else {
10759 Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
10761 Jim_ListAppendElement(interp, listObj, targetCallFrame->argv[0]);
10762 Jim_ListAppendElement(interp, listObj, targetCallFrame->fileNameObj);
10763 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, targetCallFrame->line));
10764 *objPtrPtr = listObj;
10766 return JIM_OK;
10769 /* -----------------------------------------------------------------------------
10770 * Core commands
10771 * ---------------------------------------------------------------------------*/
10773 /* fake [puts] -- not the real puts, just for debugging. */
10774 static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10776 if (argc != 2 && argc != 3) {
10777 Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
10778 return JIM_ERR;
10780 if (argc == 3) {
10781 if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
10782 Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
10783 return JIM_ERR;
10785 else {
10786 fputs(Jim_String(argv[2]), stdout);
10789 else {
10790 puts(Jim_String(argv[1]));
10792 return JIM_OK;
10795 /* Helper for [+] and [*] */
10796 static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10798 jim_wide wideValue, res;
10799 double doubleValue, doubleRes;
10800 int i;
10802 res = (op == JIM_EXPROP_ADD) ? 0 : 1;
10804 for (i = 1; i < argc; i++) {
10805 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
10806 goto trydouble;
10807 if (op == JIM_EXPROP_ADD)
10808 res += wideValue;
10809 else
10810 res *= wideValue;
10812 Jim_SetResultInt(interp, res);
10813 return JIM_OK;
10814 trydouble:
10815 doubleRes = (double)res;
10816 for (; i < argc; i++) {
10817 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10818 return JIM_ERR;
10819 if (op == JIM_EXPROP_ADD)
10820 doubleRes += doubleValue;
10821 else
10822 doubleRes *= doubleValue;
10824 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10825 return JIM_OK;
10828 /* Helper for [-] and [/] */
10829 static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10831 jim_wide wideValue, res = 0;
10832 double doubleValue, doubleRes = 0;
10833 int i = 2;
10835 if (argc < 2) {
10836 Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
10837 return JIM_ERR;
10839 else if (argc == 2) {
10840 /* The arity = 2 case is different. For [- x] returns -x,
10841 * while [/ x] returns 1/x. */
10842 if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
10843 if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
10844 return JIM_ERR;
10846 else {
10847 if (op == JIM_EXPROP_SUB)
10848 doubleRes = -doubleValue;
10849 else
10850 doubleRes = 1.0 / doubleValue;
10851 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10852 return JIM_OK;
10855 if (op == JIM_EXPROP_SUB) {
10856 res = -wideValue;
10857 Jim_SetResultInt(interp, res);
10859 else {
10860 doubleRes = 1.0 / wideValue;
10861 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10863 return JIM_OK;
10865 else {
10866 if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
10867 if (Jim_GetDouble(interp, argv[1], &doubleRes)
10868 != JIM_OK) {
10869 return JIM_ERR;
10871 else {
10872 goto trydouble;
10876 for (i = 2; i < argc; i++) {
10877 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
10878 doubleRes = (double)res;
10879 goto trydouble;
10881 if (op == JIM_EXPROP_SUB)
10882 res -= wideValue;
10883 else
10884 res /= wideValue;
10886 Jim_SetResultInt(interp, res);
10887 return JIM_OK;
10888 trydouble:
10889 for (; i < argc; i++) {
10890 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10891 return JIM_ERR;
10892 if (op == JIM_EXPROP_SUB)
10893 doubleRes -= doubleValue;
10894 else
10895 doubleRes /= doubleValue;
10897 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10898 return JIM_OK;
10902 /* [+] */
10903 static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10905 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
10908 /* [*] */
10909 static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10911 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
10914 /* [-] */
10915 static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10917 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
10920 /* [/] */
10921 static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10923 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
10926 /* [set] */
10927 static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10929 if (argc != 2 && argc != 3) {
10930 Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
10931 return JIM_ERR;
10933 if (argc == 2) {
10934 Jim_Obj *objPtr;
10936 objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
10937 if (!objPtr)
10938 return JIM_ERR;
10939 Jim_SetResult(interp, objPtr);
10940 return JIM_OK;
10942 /* argc == 3 case. */
10943 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
10944 return JIM_ERR;
10945 Jim_SetResult(interp, argv[2]);
10946 return JIM_OK;
10949 /* [unset]
10951 * unset ?-nocomplain? ?--? ?varName ...?
10953 static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10955 int i = 1;
10956 int complain = 1;
10958 while (i < argc) {
10959 if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
10960 i++;
10961 break;
10963 if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
10964 complain = 0;
10965 i++;
10966 continue;
10968 break;
10971 while (i < argc) {
10972 if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
10973 && complain) {
10974 return JIM_ERR;
10976 i++;
10978 return JIM_OK;
10981 /* [while] */
10982 static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10984 if (argc != 3) {
10985 Jim_WrongNumArgs(interp, 1, argv, "condition body");
10986 return JIM_ERR;
10989 /* The general purpose implementation of while starts here */
10990 while (1) {
10991 int boolean, retval;
10993 if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
10994 return retval;
10995 if (!boolean)
10996 break;
10998 if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
10999 switch (retval) {
11000 case JIM_BREAK:
11001 goto out;
11002 break;
11003 case JIM_CONTINUE:
11004 continue;
11005 break;
11006 default:
11007 return retval;
11011 out:
11012 Jim_SetEmptyResult(interp);
11013 return JIM_OK;
11016 /* [for] */
11017 static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11019 int retval;
11020 int boolean = 1;
11021 Jim_Obj *varNamePtr = NULL;
11022 Jim_Obj *stopVarNamePtr = NULL;
11024 if (argc != 5) {
11025 Jim_WrongNumArgs(interp, 1, argv, "start test next body");
11026 return JIM_ERR;
11029 /* Do the initialisation */
11030 if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
11031 return retval;
11034 /* And do the first test now. Better for optimisation
11035 * if we can do next/test at the bottom of the loop
11037 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11039 /* Ready to do the body as follows:
11040 * while (1) {
11041 * body // check retcode
11042 * next // check retcode
11043 * test // check retcode/test bool
11047 #ifdef JIM_OPTIMIZATION
11048 /* Check if the for is on the form:
11049 * for ... {$i < CONST} {incr i}
11050 * for ... {$i < $j} {incr i}
11052 if (retval == JIM_OK && boolean) {
11053 ScriptObj *incrScript;
11054 ExprByteCode *expr;
11055 jim_wide stop, currentVal;
11056 unsigned jim_wide procEpoch;
11057 Jim_Obj *objPtr;
11058 int cmpOffset;
11060 /* Do it only if there aren't shared arguments */
11061 expr = JimGetExpression(interp, argv[2]);
11062 incrScript = Jim_GetScript(interp, argv[3]);
11064 /* Ensure proper lengths to start */
11065 if (incrScript->len != 3 || !expr || expr->len != 3) {
11066 goto evalstart;
11068 /* Ensure proper token types. */
11069 if (incrScript->token[1].type != JIM_TT_ESC ||
11070 expr->token[0].type != JIM_TT_VAR ||
11071 (expr->token[1].type != JIM_TT_EXPR_INT && expr->token[1].type != JIM_TT_VAR)) {
11072 goto evalstart;
11075 if (expr->token[2].type == JIM_EXPROP_LT) {
11076 cmpOffset = 0;
11078 else if (expr->token[2].type == JIM_EXPROP_LTE) {
11079 cmpOffset = 1;
11081 else {
11082 goto evalstart;
11085 /* Update command must be incr */
11086 if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
11087 goto evalstart;
11090 /* incr, expression must be about the same variable */
11091 if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->token[0].objPtr)) {
11092 goto evalstart;
11095 /* Get the stop condition (must be a variable or integer) */
11096 if (expr->token[1].type == JIM_TT_EXPR_INT) {
11097 if (Jim_GetWide(interp, expr->token[1].objPtr, &stop) == JIM_ERR) {
11098 goto evalstart;
11101 else {
11102 stopVarNamePtr = expr->token[1].objPtr;
11103 Jim_IncrRefCount(stopVarNamePtr);
11104 /* Keep the compiler happy */
11105 stop = 0;
11108 /* Initialization */
11109 procEpoch = interp->procEpoch;
11110 varNamePtr = expr->token[0].objPtr;
11111 Jim_IncrRefCount(varNamePtr);
11113 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
11114 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK) {
11115 goto testcond;
11118 /* --- OPTIMIZED FOR --- */
11119 while (retval == JIM_OK) {
11120 /* === Check condition === */
11121 /* Note that currentVal is already set here */
11123 /* Immediate or Variable? get the 'stop' value if the latter. */
11124 if (stopVarNamePtr) {
11125 objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
11126 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
11127 goto testcond;
11131 if (currentVal >= stop + cmpOffset) {
11132 break;
11135 /* Eval body */
11136 retval = Jim_EvalObj(interp, argv[4]);
11137 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11138 retval = JIM_OK;
11139 /* If there was a change in procedures/command continue
11140 * with the usual [for] command implementation */
11141 if (procEpoch != interp->procEpoch) {
11142 goto evalnext;
11145 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
11147 /* Increment */
11148 if (objPtr == NULL) {
11149 retval = JIM_ERR;
11150 goto out;
11152 if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11153 currentVal = ++JimWideValue(objPtr);
11154 Jim_InvalidateStringRep(objPtr);
11156 else {
11157 if (Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK ||
11158 Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
11159 ++currentVal)) != JIM_OK) {
11160 goto evalnext;
11165 goto out;
11167 evalstart:
11168 #endif
11170 while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
11171 /* Body */
11172 retval = Jim_EvalObj(interp, argv[4]);
11174 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11175 /* increment */
11176 evalnext:
11177 retval = Jim_EvalObj(interp, argv[3]);
11178 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11179 /* test */
11180 testcond:
11181 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11185 out:
11186 if (stopVarNamePtr) {
11187 Jim_DecrRefCount(interp, stopVarNamePtr);
11189 if (varNamePtr) {
11190 Jim_DecrRefCount(interp, varNamePtr);
11193 if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
11194 Jim_SetEmptyResult(interp);
11195 return JIM_OK;
11198 return retval;
11201 /* [loop] */
11202 static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11204 int retval;
11205 jim_wide i;
11206 jim_wide limit;
11207 jim_wide incr = 1;
11208 Jim_Obj *bodyObjPtr;
11210 if (argc != 5 && argc != 6) {
11211 Jim_WrongNumArgs(interp, 1, argv, "var first limit ?incr? body");
11212 return JIM_ERR;
11215 if (Jim_GetWide(interp, argv[2], &i) != JIM_OK ||
11216 Jim_GetWide(interp, argv[3], &limit) != JIM_OK ||
11217 (argc == 6 && Jim_GetWide(interp, argv[4], &incr) != JIM_OK)) {
11218 return JIM_ERR;
11220 bodyObjPtr = (argc == 5) ? argv[4] : argv[5];
11222 retval = Jim_SetVariable(interp, argv[1], argv[2]);
11224 while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
11225 retval = Jim_EvalObj(interp, bodyObjPtr);
11226 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11227 Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
11229 retval = JIM_OK;
11231 /* Increment */
11232 i += incr;
11234 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11235 if (argv[1]->typePtr != &variableObjType) {
11236 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11237 return JIM_ERR;
11240 JimWideValue(objPtr) = i;
11241 Jim_InvalidateStringRep(objPtr);
11243 /* The following step is required in order to invalidate the
11244 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11245 if (argv[1]->typePtr != &variableObjType) {
11246 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11247 retval = JIM_ERR;
11248 break;
11252 else {
11253 objPtr = Jim_NewIntObj(interp, i);
11254 retval = Jim_SetVariable(interp, argv[1], objPtr);
11255 if (retval != JIM_OK) {
11256 Jim_FreeNewObj(interp, objPtr);
11262 if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
11263 Jim_SetEmptyResult(interp);
11264 return JIM_OK;
11266 return retval;
11269 /* foreach + lmap implementation. */
11270 static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
11272 int result = JIM_ERR, i, nbrOfLists, *listsIdx, *listsEnd;
11273 int nbrOfLoops = 0;
11274 Jim_Obj *emptyStr, *script, *mapRes = NULL;
11276 if (argc < 4 || argc % 2 != 0) {
11277 Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
11278 return JIM_ERR;
11280 if (doMap) {
11281 mapRes = Jim_NewListObj(interp, NULL, 0);
11282 Jim_IncrRefCount(mapRes);
11284 emptyStr = Jim_NewEmptyStringObj(interp);
11285 Jim_IncrRefCount(emptyStr);
11286 script = argv[argc - 1]; /* Last argument is a script */
11287 nbrOfLists = (argc - 1 - 1) / 2; /* argc - 'foreach' - script */
11288 listsIdx = (int *)Jim_Alloc(nbrOfLists * sizeof(int));
11289 listsEnd = (int *)Jim_Alloc(nbrOfLists * 2 * sizeof(int));
11290 /* Initialize iterators and remember max nbr elements each list */
11291 memset(listsIdx, 0, nbrOfLists * sizeof(int));
11292 /* Remember lengths of all lists and calculate how much rounds to loop */
11293 for (i = 0; i < nbrOfLists * 2; i += 2) {
11294 div_t cnt;
11295 int count;
11297 listsEnd[i] = Jim_ListLength(interp, argv[i + 1]);
11298 listsEnd[i + 1] = Jim_ListLength(interp, argv[i + 2]);
11299 if (listsEnd[i] == 0) {
11300 Jim_SetResultString(interp, "foreach varlist is empty", -1);
11301 goto err;
11303 cnt = div(listsEnd[i + 1], listsEnd[i]);
11304 count = cnt.quot + (cnt.rem ? 1 : 0);
11305 if (count > nbrOfLoops)
11306 nbrOfLoops = count;
11308 for (; nbrOfLoops-- > 0;) {
11309 for (i = 0; i < nbrOfLists; ++i) {
11310 int varIdx = 0, var = i * 2;
11312 while (varIdx < listsEnd[var]) {
11313 Jim_Obj *varName, *ele;
11314 int lst = i * 2 + 1;
11316 /* List index operations below can't fail */
11317 Jim_ListIndex(interp, argv[var + 1], varIdx, &varName, JIM_NONE);
11318 if (listsIdx[i] < listsEnd[lst]) {
11319 Jim_ListIndex(interp, argv[lst + 1], listsIdx[i], &ele, JIM_NONE);
11320 /* Avoid shimmering */
11321 Jim_IncrRefCount(ele);
11322 result = Jim_SetVariable(interp, varName, ele);
11323 Jim_DecrRefCount(interp, ele);
11324 if (result == JIM_OK) {
11325 ++listsIdx[i]; /* Remember next iterator of current list */
11326 ++varIdx; /* Next variable */
11327 continue;
11330 else if (Jim_SetVariable(interp, varName, emptyStr) == JIM_OK) {
11331 ++varIdx; /* Next variable */
11332 continue;
11334 goto err;
11337 switch (result = Jim_EvalObj(interp, script)) {
11338 case JIM_OK:
11339 if (doMap)
11340 Jim_ListAppendElement(interp, mapRes, interp->result);
11341 break;
11342 case JIM_CONTINUE:
11343 break;
11344 case JIM_BREAK:
11345 goto out;
11346 break;
11347 default:
11348 goto err;
11351 out:
11352 result = JIM_OK;
11353 if (doMap)
11354 Jim_SetResult(interp, mapRes);
11355 else
11356 Jim_SetEmptyResult(interp);
11357 err:
11358 if (doMap)
11359 Jim_DecrRefCount(interp, mapRes);
11360 Jim_DecrRefCount(interp, emptyStr);
11361 Jim_Free(listsIdx);
11362 Jim_Free(listsEnd);
11363 return result;
11366 /* [foreach] */
11367 static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11369 return JimForeachMapHelper(interp, argc, argv, 0);
11372 /* [lmap] */
11373 static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11375 return JimForeachMapHelper(interp, argc, argv, 1);
11378 /* [if] */
11379 static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11381 int boolean, retval, current = 1, falsebody = 0;
11383 if (argc >= 3) {
11384 while (1) {
11385 /* Far not enough arguments given! */
11386 if (current >= argc)
11387 goto err;
11388 if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
11389 != JIM_OK)
11390 return retval;
11391 /* There lacks something, isn't it? */
11392 if (current >= argc)
11393 goto err;
11394 if (Jim_CompareStringImmediate(interp, argv[current], "then"))
11395 current++;
11396 /* Tsk tsk, no then-clause? */
11397 if (current >= argc)
11398 goto err;
11399 if (boolean)
11400 return Jim_EvalObj(interp, argv[current]);
11401 /* Ok: no else-clause follows */
11402 if (++current >= argc) {
11403 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
11404 return JIM_OK;
11406 falsebody = current++;
11407 if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
11408 /* IIICKS - else-clause isn't last cmd? */
11409 if (current != argc - 1)
11410 goto err;
11411 return Jim_EvalObj(interp, argv[current]);
11413 else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
11414 /* Ok: elseif follows meaning all the stuff
11415 * again (how boring...) */
11416 continue;
11417 /* OOPS - else-clause is not last cmd? */
11418 else if (falsebody != argc - 1)
11419 goto err;
11420 return Jim_EvalObj(interp, argv[falsebody]);
11422 return JIM_OK;
11424 err:
11425 Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11426 return JIM_ERR;
11430 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11431 int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
11432 Jim_Obj *stringObj, int nocase)
11434 Jim_Obj *parms[4];
11435 int argc = 0;
11436 long eq;
11437 int rc;
11439 parms[argc++] = commandObj;
11440 if (nocase) {
11441 parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
11443 parms[argc++] = patternObj;
11444 parms[argc++] = stringObj;
11446 rc = Jim_EvalObjVector(interp, argc, parms);
11448 if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
11449 eq = -rc;
11452 return eq;
11455 enum
11456 { SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
11458 /* [switch] */
11459 static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11461 int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
11462 Jim_Obj *command = 0, *const *caseList = 0, *strObj;
11463 Jim_Obj *script = 0;
11465 if (argc < 3) {
11466 wrongnumargs:
11467 Jim_WrongNumArgs(interp, 1, argv, "?options? string "
11468 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11469 return JIM_ERR;
11471 for (opt = 1; opt < argc; ++opt) {
11472 const char *option = Jim_String(argv[opt]);
11474 if (*option != '-')
11475 break;
11476 else if (strncmp(option, "--", 2) == 0) {
11477 ++opt;
11478 break;
11480 else if (strncmp(option, "-exact", 2) == 0)
11481 matchOpt = SWITCH_EXACT;
11482 else if (strncmp(option, "-glob", 2) == 0)
11483 matchOpt = SWITCH_GLOB;
11484 else if (strncmp(option, "-regexp", 2) == 0)
11485 matchOpt = SWITCH_RE;
11486 else if (strncmp(option, "-command", 2) == 0) {
11487 matchOpt = SWITCH_CMD;
11488 if ((argc - opt) < 2)
11489 goto wrongnumargs;
11490 command = argv[++opt];
11492 else {
11493 Jim_SetResultFormatted(interp,
11494 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11495 argv[opt]);
11496 return JIM_ERR;
11498 if ((argc - opt) < 2)
11499 goto wrongnumargs;
11501 strObj = argv[opt++];
11502 patCount = argc - opt;
11503 if (patCount == 1) {
11504 Jim_Obj **vector;
11506 JimListGetElements(interp, argv[opt], &patCount, &vector);
11507 caseList = vector;
11509 else
11510 caseList = &argv[opt];
11511 if (patCount == 0 || patCount % 2 != 0)
11512 goto wrongnumargs;
11513 for (i = 0; script == 0 && i < patCount; i += 2) {
11514 Jim_Obj *patObj = caseList[i];
11516 if (!Jim_CompareStringImmediate(interp, patObj, "default")
11517 || i < (patCount - 2)) {
11518 switch (matchOpt) {
11519 case SWITCH_EXACT:
11520 if (Jim_StringEqObj(strObj, patObj))
11521 script = caseList[i + 1];
11522 break;
11523 case SWITCH_GLOB:
11524 if (Jim_StringMatchObj(interp, patObj, strObj, 0))
11525 script = caseList[i + 1];
11526 break;
11527 case SWITCH_RE:
11528 command = Jim_NewStringObj(interp, "regexp", -1);
11529 /* Fall thru intentionally */
11530 case SWITCH_CMD:{
11531 int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, 0);
11533 /* After the execution of a command we need to
11534 * make sure to reconvert the object into a list
11535 * again. Only for the single-list style [switch]. */
11536 if (argc - opt == 1) {
11537 Jim_Obj **vector;
11539 JimListGetElements(interp, argv[opt], &patCount, &vector);
11540 caseList = vector;
11542 /* command is here already decref'd */
11543 if (rc < 0) {
11544 return -rc;
11546 if (rc)
11547 script = caseList[i + 1];
11548 break;
11552 else {
11553 script = caseList[i + 1];
11556 for (; i < patCount && Jim_CompareStringImmediate(interp, script, "-"); i += 2)
11557 script = caseList[i + 1];
11558 if (script && Jim_CompareStringImmediate(interp, script, "-")) {
11559 Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
11560 return JIM_ERR;
11562 Jim_SetEmptyResult(interp);
11563 if (script) {
11564 return Jim_EvalObj(interp, script);
11566 return JIM_OK;
11569 /* [list] */
11570 static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11572 Jim_Obj *listObjPtr;
11574 listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
11575 Jim_SetResult(interp, listObjPtr);
11576 return JIM_OK;
11579 /* [lindex] */
11580 static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11582 Jim_Obj *objPtr, *listObjPtr;
11583 int i;
11584 int idx;
11586 if (argc < 3) {
11587 Jim_WrongNumArgs(interp, 1, argv, "list index ?...?");
11588 return JIM_ERR;
11590 objPtr = argv[1];
11591 Jim_IncrRefCount(objPtr);
11592 for (i = 2; i < argc; i++) {
11593 listObjPtr = objPtr;
11594 if (Jim_GetIndex(interp, argv[i], &idx) != JIM_OK) {
11595 Jim_DecrRefCount(interp, listObjPtr);
11596 return JIM_ERR;
11598 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_NONE) != JIM_OK) {
11599 /* Returns an empty object if the index
11600 * is out of range. */
11601 Jim_DecrRefCount(interp, listObjPtr);
11602 Jim_SetEmptyResult(interp);
11603 return JIM_OK;
11605 Jim_IncrRefCount(objPtr);
11606 Jim_DecrRefCount(interp, listObjPtr);
11608 Jim_SetResult(interp, objPtr);
11609 Jim_DecrRefCount(interp, objPtr);
11610 return JIM_OK;
11613 /* [llength] */
11614 static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11616 if (argc != 2) {
11617 Jim_WrongNumArgs(interp, 1, argv, "list");
11618 return JIM_ERR;
11620 Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
11621 return JIM_OK;
11624 /* [lsearch] */
11625 static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11627 static const char * const options[] = {
11628 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11629 NULL
11631 enum
11632 { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
11633 OPT_COMMAND };
11634 int i;
11635 int opt_bool = 0;
11636 int opt_not = 0;
11637 int opt_nocase = 0;
11638 int opt_all = 0;
11639 int opt_inline = 0;
11640 int opt_match = OPT_EXACT;
11641 int listlen;
11642 int rc = JIM_OK;
11643 Jim_Obj *listObjPtr = NULL;
11644 Jim_Obj *commandObj = NULL;
11646 if (argc < 3) {
11647 wrongargs:
11648 Jim_WrongNumArgs(interp, 1, argv,
11649 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11650 return JIM_ERR;
11653 for (i = 1; i < argc - 2; i++) {
11654 int option;
11656 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
11657 return JIM_ERR;
11659 switch (option) {
11660 case OPT_BOOL:
11661 opt_bool = 1;
11662 opt_inline = 0;
11663 break;
11664 case OPT_NOT:
11665 opt_not = 1;
11666 break;
11667 case OPT_NOCASE:
11668 opt_nocase = 1;
11669 break;
11670 case OPT_INLINE:
11671 opt_inline = 1;
11672 opt_bool = 0;
11673 break;
11674 case OPT_ALL:
11675 opt_all = 1;
11676 break;
11677 case OPT_COMMAND:
11678 if (i >= argc - 2) {
11679 goto wrongargs;
11681 commandObj = argv[++i];
11682 /* fallthru */
11683 case OPT_EXACT:
11684 case OPT_GLOB:
11685 case OPT_REGEXP:
11686 opt_match = option;
11687 break;
11691 argv += i;
11693 if (opt_all) {
11694 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11696 if (opt_match == OPT_REGEXP) {
11697 commandObj = Jim_NewStringObj(interp, "regexp", -1);
11699 if (commandObj) {
11700 Jim_IncrRefCount(commandObj);
11703 listlen = Jim_ListLength(interp, argv[0]);
11704 for (i = 0; i < listlen; i++) {
11705 Jim_Obj *objPtr;
11706 int eq = 0;
11708 Jim_ListIndex(interp, argv[0], i, &objPtr, JIM_NONE);
11709 switch (opt_match) {
11710 case OPT_EXACT:
11711 eq = Jim_StringCompareObj(interp, objPtr, argv[1], opt_nocase) == 0;
11712 break;
11714 case OPT_GLOB:
11715 eq = Jim_StringMatchObj(interp, argv[1], objPtr, opt_nocase);
11716 break;
11718 case OPT_REGEXP:
11719 case OPT_COMMAND:
11720 eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, opt_nocase);
11721 if (eq < 0) {
11722 if (listObjPtr) {
11723 Jim_FreeNewObj(interp, listObjPtr);
11725 rc = JIM_ERR;
11726 goto done;
11728 break;
11731 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11732 if (!eq && opt_bool && opt_not && !opt_all) {
11733 continue;
11736 if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
11737 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11738 Jim_Obj *resultObj;
11740 if (opt_bool) {
11741 resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
11743 else if (!opt_inline) {
11744 resultObj = Jim_NewIntObj(interp, i);
11746 else {
11747 resultObj = objPtr;
11750 if (opt_all) {
11751 Jim_ListAppendElement(interp, listObjPtr, resultObj);
11753 else {
11754 Jim_SetResult(interp, resultObj);
11755 goto done;
11760 if (opt_all) {
11761 Jim_SetResult(interp, listObjPtr);
11763 else {
11764 /* No match */
11765 if (opt_bool) {
11766 Jim_SetResultBool(interp, opt_not);
11768 else if (!opt_inline) {
11769 Jim_SetResultInt(interp, -1);
11773 done:
11774 if (commandObj) {
11775 Jim_DecrRefCount(interp, commandObj);
11777 return rc;
11780 /* [lappend] */
11781 static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11783 Jim_Obj *listObjPtr;
11784 int shared, i;
11786 if (argc < 2) {
11787 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
11788 return JIM_ERR;
11790 listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
11791 if (!listObjPtr) {
11792 /* Create the list if it does not exists */
11793 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11794 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11795 Jim_FreeNewObj(interp, listObjPtr);
11796 return JIM_ERR;
11799 shared = Jim_IsShared(listObjPtr);
11800 if (shared)
11801 listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
11802 for (i = 2; i < argc; i++)
11803 Jim_ListAppendElement(interp, listObjPtr, argv[i]);
11804 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11805 if (shared)
11806 Jim_FreeNewObj(interp, listObjPtr);
11807 return JIM_ERR;
11809 Jim_SetResult(interp, listObjPtr);
11810 return JIM_OK;
11813 /* [linsert] */
11814 static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11816 int idx, len;
11817 Jim_Obj *listPtr;
11819 if (argc < 4) {
11820 Jim_WrongNumArgs(interp, 1, argv, "list index element " "?element ...?");
11821 return JIM_ERR;
11823 listPtr = argv[1];
11824 if (Jim_IsShared(listPtr))
11825 listPtr = Jim_DuplicateObj(interp, listPtr);
11826 if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
11827 goto err;
11828 len = Jim_ListLength(interp, listPtr);
11829 if (idx >= len)
11830 idx = len;
11831 else if (idx < 0)
11832 idx = len + idx + 1;
11833 Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
11834 Jim_SetResult(interp, listPtr);
11835 return JIM_OK;
11836 err:
11837 if (listPtr != argv[1]) {
11838 Jim_FreeNewObj(interp, listPtr);
11840 return JIM_ERR;
11843 /* [lreplace] */
11844 static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11846 int first, last, len, rangeLen;
11847 Jim_Obj *listObj;
11848 Jim_Obj *newListObj;
11849 int i;
11850 int shared;
11852 if (argc < 4) {
11853 Jim_WrongNumArgs(interp, 1, argv, "list first last ?element element ...?");
11854 return JIM_ERR;
11856 if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
11857 Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
11858 return JIM_ERR;
11861 listObj = argv[1];
11862 len = Jim_ListLength(interp, listObj);
11864 first = JimRelToAbsIndex(len, first);
11865 last = JimRelToAbsIndex(len, last);
11866 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
11868 /* Now construct a new list which consists of:
11869 * <elements before first> <supplied elements> <elements after last>
11872 /* Check to see if trying to replace past the end of the list */
11873 if (first < len) {
11874 /* OK. Not past the end */
11876 else if (len == 0) {
11877 /* Special for empty list, adjust first to 0 */
11878 first = 0;
11880 else {
11881 Jim_SetResultString(interp, "list doesn't contain element ", -1);
11882 Jim_AppendObj(interp, Jim_GetResult(interp), argv[2]);
11883 return JIM_ERR;
11886 newListObj = Jim_NewListObj(interp, NULL, 0);
11888 shared = Jim_IsShared(listObj);
11889 if (shared) {
11890 listObj = Jim_DuplicateObj(interp, listObj);
11893 /* Add the first set of elements */
11894 for (i = 0; i < first; i++) {
11895 Jim_ListAppendElement(interp, newListObj, listObj->internalRep.listValue.ele[i]);
11898 /* Add supplied elements */
11899 for (i = 4; i < argc; i++) {
11900 Jim_ListAppendElement(interp, newListObj, argv[i]);
11903 /* Add the remaining elements */
11904 for (i = first + rangeLen; i < len; i++) {
11905 Jim_ListAppendElement(interp, newListObj, listObj->internalRep.listValue.ele[i]);
11907 Jim_SetResult(interp, newListObj);
11908 if (shared) {
11909 Jim_FreeNewObj(interp, listObj);
11911 return JIM_OK;
11914 /* [lset] */
11915 static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11917 if (argc < 3) {
11918 Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");
11919 return JIM_ERR;
11921 else if (argc == 3) {
11922 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
11923 return JIM_ERR;
11924 Jim_SetResult(interp, argv[2]);
11925 return JIM_OK;
11927 if (Jim_SetListIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1])
11928 == JIM_ERR)
11929 return JIM_ERR;
11930 return JIM_OK;
11933 /* [lsort] */
11934 static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
11936 static const char * const options[] = {
11937 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11939 enum
11940 { OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_INDEX };
11941 Jim_Obj *resObj;
11942 int i;
11943 int retCode;
11945 struct lsort_info info;
11947 if (argc < 2) {
11948 Jim_WrongNumArgs(interp, 1, argv, "?options? list");
11949 return JIM_ERR;
11952 info.type = JIM_LSORT_ASCII;
11953 info.order = 1;
11954 info.indexed = 0;
11955 info.command = NULL;
11956 info.interp = interp;
11958 for (i = 1; i < (argc - 1); i++) {
11959 int option;
11961 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG)
11962 != JIM_OK)
11963 return JIM_ERR;
11964 switch (option) {
11965 case OPT_ASCII:
11966 info.type = JIM_LSORT_ASCII;
11967 break;
11968 case OPT_NOCASE:
11969 info.type = JIM_LSORT_NOCASE;
11970 break;
11971 case OPT_INTEGER:
11972 info.type = JIM_LSORT_INTEGER;
11973 break;
11974 case OPT_INCREASING:
11975 info.order = 1;
11976 break;
11977 case OPT_DECREASING:
11978 info.order = -1;
11979 break;
11980 case OPT_COMMAND:
11981 if (i >= (argc - 2)) {
11982 Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
11983 return JIM_ERR;
11985 info.type = JIM_LSORT_COMMAND;
11986 info.command = argv[i + 1];
11987 i++;
11988 break;
11989 case OPT_INDEX:
11990 if (i >= (argc - 2)) {
11991 Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
11992 return JIM_ERR;
11994 if (Jim_GetIndex(interp, argv[i + 1], &info.index) != JIM_OK) {
11995 return JIM_ERR;
11997 info.indexed = 1;
11998 i++;
11999 break;
12002 resObj = Jim_DuplicateObj(interp, argv[argc - 1]);
12003 retCode = ListSortElements(interp, resObj, &info);
12004 if (retCode == JIM_OK) {
12005 Jim_SetResult(interp, resObj);
12007 else {
12008 Jim_FreeNewObj(interp, resObj);
12010 return retCode;
12013 /* [append] */
12014 static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12016 Jim_Obj *stringObjPtr;
12017 int i;
12019 if (argc < 2) {
12020 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
12021 return JIM_ERR;
12023 if (argc == 2) {
12024 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
12025 if (!stringObjPtr)
12026 return JIM_ERR;
12028 else {
12029 int freeobj = 0;
12030 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
12031 if (!stringObjPtr) {
12032 /* Create the string if it doesn't exist */
12033 stringObjPtr = Jim_NewEmptyStringObj(interp);
12034 freeobj = 1;
12036 else if (Jim_IsShared(stringObjPtr)) {
12037 freeobj = 1;
12038 stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
12040 for (i = 2; i < argc; i++) {
12041 Jim_AppendObj(interp, stringObjPtr, argv[i]);
12043 if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
12044 if (freeobj) {
12045 Jim_FreeNewObj(interp, stringObjPtr);
12047 return JIM_ERR;
12050 Jim_SetResult(interp, stringObjPtr);
12051 return JIM_OK;
12054 /* [debug] */
12055 static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12057 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12058 static const char * const options[] = {
12059 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12060 "exprbc", "show",
12061 NULL
12063 enum
12065 OPT_REFCOUNT, OPT_OBJCOUNT, OPT_OBJECTS, OPT_INVSTR, OPT_SCRIPTLEN,
12066 OPT_EXPRLEN, OPT_EXPRBC, OPT_SHOW,
12068 int option;
12070 if (argc < 2) {
12071 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?...?");
12072 return JIM_ERR;
12074 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK)
12075 return JIM_ERR;
12076 if (option == OPT_REFCOUNT) {
12077 if (argc != 3) {
12078 Jim_WrongNumArgs(interp, 2, argv, "object");
12079 return JIM_ERR;
12081 Jim_SetResultInt(interp, argv[2]->refCount);
12082 return JIM_OK;
12084 else if (option == OPT_OBJCOUNT) {
12085 int freeobj = 0, liveobj = 0;
12086 char buf[256];
12087 Jim_Obj *objPtr;
12089 if (argc != 2) {
12090 Jim_WrongNumArgs(interp, 2, argv, "");
12091 return JIM_ERR;
12093 /* Count the number of free objects. */
12094 objPtr = interp->freeList;
12095 while (objPtr) {
12096 freeobj++;
12097 objPtr = objPtr->nextObjPtr;
12099 /* Count the number of live objects. */
12100 objPtr = interp->liveList;
12101 while (objPtr) {
12102 liveobj++;
12103 objPtr = objPtr->nextObjPtr;
12105 /* Set the result string and return. */
12106 sprintf(buf, "free %d used %d", freeobj, liveobj);
12107 Jim_SetResultString(interp, buf, -1);
12108 return JIM_OK;
12110 else if (option == OPT_OBJECTS) {
12111 Jim_Obj *objPtr, *listObjPtr, *subListObjPtr;
12113 /* Count the number of live objects. */
12114 objPtr = interp->liveList;
12115 listObjPtr = Jim_NewListObj(interp, NULL, 0);
12116 while (objPtr) {
12117 char buf[128];
12118 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "";
12120 subListObjPtr = Jim_NewListObj(interp, NULL, 0);
12121 sprintf(buf, "%p", objPtr);
12122 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, buf, -1));
12123 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, type, -1));
12124 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewIntObj(interp, objPtr->refCount));
12125 Jim_ListAppendElement(interp, subListObjPtr, objPtr);
12126 Jim_ListAppendElement(interp, listObjPtr, subListObjPtr);
12127 objPtr = objPtr->nextObjPtr;
12129 Jim_SetResult(interp, listObjPtr);
12130 return JIM_OK;
12132 else if (option == OPT_INVSTR) {
12133 Jim_Obj *objPtr;
12135 if (argc != 3) {
12136 Jim_WrongNumArgs(interp, 2, argv, "object");
12137 return JIM_ERR;
12139 objPtr = argv[2];
12140 if (objPtr->typePtr != NULL)
12141 Jim_InvalidateStringRep(objPtr);
12142 Jim_SetEmptyResult(interp);
12143 return JIM_OK;
12145 else if (option == OPT_SHOW) {
12146 const char *s;
12147 int len, charlen;
12149 if (argc != 3) {
12150 Jim_WrongNumArgs(interp, 2, argv, "object");
12151 return JIM_ERR;
12153 s = Jim_GetString(argv[2], &len);
12154 #ifdef JIM_UTF8
12155 charlen = utf8_strlen(s, len);
12156 #else
12157 charlen = len;
12158 #endif
12159 printf("refcount: %d, type: %s\n", argv[2]->refCount, JimObjTypeName(argv[2]));
12160 printf("chars (%d): <<%s>>\n", charlen, s);
12161 printf("bytes (%d):", len);
12162 while (len--) {
12163 printf(" %02x", (unsigned char)*s++);
12165 printf("\n");
12166 return JIM_OK;
12168 else if (option == OPT_SCRIPTLEN) {
12169 ScriptObj *script;
12171 if (argc != 3) {
12172 Jim_WrongNumArgs(interp, 2, argv, "script");
12173 return JIM_ERR;
12175 script = Jim_GetScript(interp, argv[2]);
12176 Jim_SetResultInt(interp, script->len);
12177 return JIM_OK;
12179 else if (option == OPT_EXPRLEN) {
12180 ExprByteCode *expr;
12182 if (argc != 3) {
12183 Jim_WrongNumArgs(interp, 2, argv, "expression");
12184 return JIM_ERR;
12186 expr = JimGetExpression(interp, argv[2]);
12187 if (expr == NULL)
12188 return JIM_ERR;
12189 Jim_SetResultInt(interp, expr->len);
12190 return JIM_OK;
12192 else if (option == OPT_EXPRBC) {
12193 Jim_Obj *objPtr;
12194 ExprByteCode *expr;
12195 int i;
12197 if (argc != 3) {
12198 Jim_WrongNumArgs(interp, 2, argv, "expression");
12199 return JIM_ERR;
12201 expr = JimGetExpression(interp, argv[2]);
12202 if (expr == NULL)
12203 return JIM_ERR;
12204 objPtr = Jim_NewListObj(interp, NULL, 0);
12205 for (i = 0; i < expr->len; i++) {
12206 const char *type;
12207 const Jim_ExprOperator *op;
12208 Jim_Obj *obj = expr->token[i].objPtr;
12210 switch (expr->token[i].type) {
12211 case JIM_TT_EXPR_INT:
12212 type = "int";
12213 break;
12214 case JIM_TT_EXPR_DOUBLE:
12215 type = "double";
12216 break;
12217 case JIM_TT_CMD:
12218 type = "command";
12219 break;
12220 case JIM_TT_VAR:
12221 type = "variable";
12222 break;
12223 case JIM_TT_DICTSUGAR:
12224 type = "dictsugar";
12225 break;
12226 case JIM_TT_EXPRSUGAR:
12227 type = "exprsugar";
12228 break;
12229 case JIM_TT_ESC:
12230 type = "subst";
12231 break;
12232 case JIM_TT_STR:
12233 type = "string";
12234 break;
12235 default:
12236 op = JimExprOperatorInfoByOpcode(expr->token[i].type);
12237 if (op == NULL) {
12238 type = "private";
12240 else {
12241 type = "operator";
12243 obj = Jim_NewStringObj(interp, op ? op->name : "", -1);
12244 break;
12246 Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, type, -1));
12247 Jim_ListAppendElement(interp, objPtr, obj);
12249 Jim_SetResult(interp, objPtr);
12250 return JIM_OK;
12252 else {
12253 Jim_SetResultString(interp,
12254 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12255 return JIM_ERR;
12257 /* unreached */
12258 #endif /* JIM_BOOTSTRAP */
12259 #if !defined(JIM_DEBUG_COMMAND)
12260 Jim_SetResultString(interp, "unsupported", -1);
12261 return JIM_ERR;
12262 #endif
12265 /* [eval] */
12266 static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12268 int rc;
12270 if (argc < 2) {
12271 Jim_WrongNumArgs(interp, 1, argv, "script ?...?");
12272 return JIM_ERR;
12275 if (argc == 2) {
12276 rc = Jim_EvalObj(interp, argv[1]);
12278 else {
12279 rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12282 if (rc == JIM_ERR) {
12283 /* eval is "interesting", so add a stack frame here */
12284 interp->addStackTrace++;
12286 return rc;
12289 /* [uplevel] */
12290 static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12292 if (argc >= 2) {
12293 int retcode;
12294 Jim_CallFrame *savedCallFrame, *targetCallFrame;
12295 Jim_Obj *objPtr;
12296 const char *str;
12298 /* Save the old callframe pointer */
12299 savedCallFrame = interp->framePtr;
12301 /* Lookup the target frame pointer */
12302 str = Jim_String(argv[1]);
12303 if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
12304 targetCallFrame =Jim_GetCallFrameByLevel(interp, argv[1]);
12305 argc--;
12306 argv++;
12308 else {
12309 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12311 if (targetCallFrame == NULL) {
12312 return JIM_ERR;
12314 if (argc < 2) {
12315 argv--;
12316 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12317 return JIM_ERR;
12319 /* Eval the code in the target callframe. */
12320 interp->framePtr = targetCallFrame;
12321 if (argc == 2) {
12322 retcode = Jim_EvalObj(interp, argv[1]);
12324 else {
12325 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12326 Jim_IncrRefCount(objPtr);
12327 retcode = Jim_EvalObj(interp, objPtr);
12328 Jim_DecrRefCount(interp, objPtr);
12330 interp->framePtr = savedCallFrame;
12331 return retcode;
12333 else {
12334 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12335 return JIM_ERR;
12339 /* [expr] */
12340 static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12342 Jim_Obj *exprResultPtr;
12343 int retcode;
12345 if (argc == 2) {
12346 retcode = Jim_EvalExpression(interp, argv[1], &exprResultPtr);
12348 else if (argc > 2) {
12349 Jim_Obj *objPtr;
12351 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12352 Jim_IncrRefCount(objPtr);
12353 retcode = Jim_EvalExpression(interp, objPtr, &exprResultPtr);
12354 Jim_DecrRefCount(interp, objPtr);
12356 else {
12357 Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
12358 return JIM_ERR;
12360 if (retcode != JIM_OK)
12361 return retcode;
12362 Jim_SetResult(interp, exprResultPtr);
12363 Jim_DecrRefCount(interp, exprResultPtr);
12364 return JIM_OK;
12367 /* [break] */
12368 static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12370 if (argc != 1) {
12371 Jim_WrongNumArgs(interp, 1, argv, "");
12372 return JIM_ERR;
12374 return JIM_BREAK;
12377 /* [continue] */
12378 static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12380 if (argc != 1) {
12381 Jim_WrongNumArgs(interp, 1, argv, "");
12382 return JIM_ERR;
12384 return JIM_CONTINUE;
12387 /* [return] */
12388 static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12390 int i;
12391 Jim_Obj *stackTraceObj = NULL;
12392 Jim_Obj *errorCodeObj = NULL;
12393 int returnCode = JIM_OK;
12394 long level = 1;
12396 for (i = 1; i < argc - 1; i += 2) {
12397 if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
12398 if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
12399 return JIM_ERR;
12402 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
12403 stackTraceObj = argv[i + 1];
12405 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
12406 errorCodeObj = argv[i + 1];
12408 else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
12409 if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
12410 Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
12411 return JIM_ERR;
12414 else {
12415 break;
12419 if (i != argc - 1 && i != argc) {
12420 Jim_WrongNumArgs(interp, 1, argv,
12421 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12424 /* If a stack trace is supplied and code is error, set the stack trace */
12425 if (stackTraceObj && returnCode == JIM_ERR) {
12426 JimSetStackTrace(interp, stackTraceObj);
12428 /* If an error code list is supplied, set the global $errorCode */
12429 if (errorCodeObj && returnCode == JIM_ERR) {
12430 Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
12432 interp->returnCode = returnCode;
12433 interp->returnLevel = level;
12435 if (i == argc - 1) {
12436 Jim_SetResult(interp, argv[i]);
12438 return JIM_RETURN;
12441 /* [tailcall] */
12442 static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12444 Jim_Obj *objPtr;
12446 objPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
12447 Jim_SetResult(interp, objPtr);
12448 return JIM_EVAL;
12451 /* [proc] */
12452 static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12454 if (argc != 4 && argc != 5) {
12455 Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
12456 return JIM_ERR;
12459 if (argc == 4) {
12460 return JimCreateProcedure(interp, argv[1], argv[2], NULL, argv[3]);
12462 else {
12463 return JimCreateProcedure(interp, argv[1], argv[2], argv[3], argv[4]);
12467 /* [local] */
12468 static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12470 int retcode;
12472 /* Evaluate the arguments with 'local' in force */
12473 interp->local++;
12474 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12475 interp->local--;
12478 /* If OK, and the result is a proc, add it to the list of local procs */
12479 if (retcode == 0) {
12480 const char *procname = Jim_String(Jim_GetResult(interp));
12482 if (Jim_FindHashEntry(&interp->commands, procname) == NULL) {
12483 Jim_SetResultFormatted(interp, "not a proc: \"%s\"", procname);
12484 return JIM_ERR;
12486 if (interp->localProcs == NULL) {
12487 interp->localProcs = Jim_Alloc(sizeof(*interp->localProcs));
12488 Jim_InitStack(interp->localProcs);
12490 Jim_StackPush(interp->localProcs, Jim_StrDup(procname));
12493 return retcode;
12496 /* [upcall] */
12497 static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12499 if (argc < 2) {
12500 Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
12501 return JIM_ERR;
12503 else {
12504 int retcode;
12506 Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
12507 if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->u.proc.prevCmd) {
12508 Jim_SetResultFormatted(interp, "no previous proc: \"%#s\"", argv[1]);
12509 return JIM_ERR;
12511 /* OK. Mark this command as being in an upcall */
12512 cmdPtr->u.proc.upcall++;
12513 JimIncrCmdRefCount(cmdPtr);
12515 /* Invoke the command as normal */
12516 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12518 /* No longer in an upcall */
12519 cmdPtr->u.proc.upcall--;
12520 JimDecrCmdRefCount(interp, cmdPtr);
12522 return retcode;
12526 /* [concat] */
12527 static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12529 Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12530 return JIM_OK;
12533 /* [upvar] */
12534 static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12536 int i;
12537 Jim_CallFrame *targetCallFrame;
12539 /* Lookup the target frame pointer */
12540 if (argc > 3 && (argc % 2 == 0)) {
12541 targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
12542 argc--;
12543 argv++;
12545 else {
12546 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12548 if (targetCallFrame == NULL) {
12549 return JIM_ERR;
12552 /* Check for arity */
12553 if (argc < 3) {
12554 Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
12555 return JIM_ERR;
12558 /* Now... for every other/local couple: */
12559 for (i = 1; i < argc; i += 2) {
12560 if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
12561 return JIM_ERR;
12563 return JIM_OK;
12566 /* [global] */
12567 static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12569 int i;
12571 if (argc < 2) {
12572 Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
12573 return JIM_ERR;
12575 /* Link every var to the toplevel having the same name */
12576 if (interp->framePtr->level == 0)
12577 return JIM_OK; /* global at toplevel... */
12578 for (i = 1; i < argc; i++) {
12579 if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
12580 return JIM_ERR;
12582 return JIM_OK;
12585 /* does the [string map] operation. On error NULL is returned,
12586 * otherwise a new string object with the result, having refcount = 0,
12587 * is returned. */
12588 static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
12589 Jim_Obj *objPtr, int nocase)
12591 int numMaps;
12592 const char *str, *noMatchStart = NULL;
12593 int strLen, i;
12594 Jim_Obj *resultObjPtr;
12596 numMaps = Jim_ListLength(interp, mapListObjPtr);
12597 if (numMaps % 2) {
12598 Jim_SetResultString(interp, "list must contain an even number of elements", -1);
12599 return NULL;
12602 str = Jim_String(objPtr);
12603 strLen = Jim_Utf8Length(interp, objPtr);
12605 /* Map it */
12606 resultObjPtr = Jim_NewStringObj(interp, "", 0);
12607 while (strLen) {
12608 for (i = 0; i < numMaps; i += 2) {
12609 Jim_Obj *objPtr;
12610 const char *k;
12611 int kl;
12613 Jim_ListIndex(interp, mapListObjPtr, i, &objPtr, JIM_NONE);
12614 k = Jim_String(objPtr);
12615 kl = Jim_Utf8Length(interp, objPtr);
12617 if (strLen >= kl && kl) {
12618 int rc;
12619 if (nocase) {
12620 rc = JimStringCompareNoCase(str, k, kl);
12622 else {
12623 rc = JimStringCompare(str, kl, k, kl);
12625 if (rc == 0) {
12626 if (noMatchStart) {
12627 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12628 noMatchStart = NULL;
12630 Jim_ListIndex(interp, mapListObjPtr, i + 1, &objPtr, JIM_NONE);
12631 Jim_AppendObj(interp, resultObjPtr, objPtr);
12632 str += utf8_index(str, kl);
12633 strLen -= kl;
12634 break;
12638 if (i == numMaps) { /* no match */
12639 int c;
12640 if (noMatchStart == NULL)
12641 noMatchStart = str;
12642 str += utf8_tounicode(str, &c);
12643 strLen--;
12646 if (noMatchStart) {
12647 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12649 return resultObjPtr;
12652 /* [string] */
12653 static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12655 int len;
12656 int opt_case = 1;
12657 int option;
12658 static const char * const options[] = {
12659 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12660 "repeat", "reverse", "index", "first", "last",
12661 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12663 enum
12665 OPT_BYTELENGTH, OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_IS, OPT_BYTERANGE, OPT_RANGE, OPT_MAP,
12666 OPT_REPEAT, OPT_REVERSE, OPT_INDEX, OPT_FIRST, OPT_LAST,
12667 OPT_TRIM, OPT_TRIMLEFT, OPT_TRIMRIGHT, OPT_TOLOWER, OPT_TOUPPER
12669 static const char * const nocase_options[] = {
12670 "-nocase", NULL
12673 if (argc < 2) {
12674 Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
12675 return JIM_ERR;
12677 if (Jim_GetEnum(interp, argv[1], options, &option, NULL,
12678 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK)
12679 return JIM_ERR;
12681 switch (option) {
12682 case OPT_LENGTH:
12683 case OPT_BYTELENGTH:
12684 if (argc != 3) {
12685 Jim_WrongNumArgs(interp, 2, argv, "string");
12686 return JIM_ERR;
12688 if (option == OPT_LENGTH) {
12689 len = Jim_Utf8Length(interp, argv[2]);
12691 else {
12692 len = Jim_Length(argv[2]);
12694 Jim_SetResultInt(interp, len);
12695 return JIM_OK;
12697 case OPT_COMPARE:
12698 case OPT_EQUAL:
12699 if (argc != 4 &&
12700 (argc != 5 ||
12701 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12702 JIM_ENUM_ABBREV) != JIM_OK)) {
12703 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? string1 string2");
12704 return JIM_ERR;
12706 if (opt_case == 0) {
12707 argv++;
12709 if (option == OPT_COMPARE || !opt_case) {
12710 Jim_SetResultInt(interp, Jim_StringCompareObj(interp, argv[2], argv[3], !opt_case));
12712 else {
12713 Jim_SetResultBool(interp, Jim_StringEqObj(argv[2], argv[3]));
12715 return JIM_OK;
12717 case OPT_MATCH:
12718 if (argc != 4 &&
12719 (argc != 5 ||
12720 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12721 JIM_ENUM_ABBREV) != JIM_OK)) {
12722 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
12723 return JIM_ERR;
12725 if (opt_case == 0) {
12726 argv++;
12728 Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
12729 return JIM_OK;
12731 case OPT_MAP:{
12732 Jim_Obj *objPtr;
12734 if (argc != 4 &&
12735 (argc != 5 ||
12736 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12737 JIM_ENUM_ABBREV) != JIM_OK)) {
12738 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
12739 return JIM_ERR;
12742 if (opt_case == 0) {
12743 argv++;
12745 objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
12746 if (objPtr == NULL) {
12747 return JIM_ERR;
12749 Jim_SetResult(interp, objPtr);
12750 return JIM_OK;
12753 case OPT_RANGE:
12754 case OPT_BYTERANGE:{
12755 Jim_Obj *objPtr;
12757 if (argc != 5) {
12758 Jim_WrongNumArgs(interp, 2, argv, "string first last");
12759 return JIM_ERR;
12761 if (option == OPT_RANGE) {
12762 objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
12764 else
12766 objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
12769 if (objPtr == NULL) {
12770 return JIM_ERR;
12772 Jim_SetResult(interp, objPtr);
12773 return JIM_OK;
12776 case OPT_REPEAT:{
12777 Jim_Obj *objPtr;
12778 jim_wide count;
12780 if (argc != 4) {
12781 Jim_WrongNumArgs(interp, 2, argv, "string count");
12782 return JIM_ERR;
12784 if (Jim_GetWide(interp, argv[3], &count) != JIM_OK) {
12785 return JIM_ERR;
12787 objPtr = Jim_NewStringObj(interp, "", 0);
12788 if (count > 0) {
12789 while (count--) {
12790 Jim_AppendObj(interp, objPtr, argv[2]);
12793 Jim_SetResult(interp, objPtr);
12794 return JIM_OK;
12797 case OPT_REVERSE:{
12798 char *buf, *p;
12799 const char *str;
12800 int len;
12801 int i;
12803 if (argc != 3) {
12804 Jim_WrongNumArgs(interp, 2, argv, "string");
12805 return JIM_ERR;
12808 str = Jim_GetString(argv[2], &len);
12809 buf = Jim_Alloc(len + 1);
12810 p = buf + len;
12811 *p = 0;
12812 for (i = 0; i < len; ) {
12813 int c;
12814 int l = utf8_tounicode(str, &c);
12815 memcpy(p - l, str, l);
12816 p -= l;
12817 i += l;
12818 str += l;
12820 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
12821 return JIM_OK;
12824 case OPT_INDEX:{
12825 int idx;
12826 const char *str;
12828 if (argc != 4) {
12829 Jim_WrongNumArgs(interp, 2, argv, "string index");
12830 return JIM_ERR;
12832 if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
12833 return JIM_ERR;
12835 str = Jim_String(argv[2]);
12836 len = Jim_Utf8Length(interp, argv[2]);
12837 if (idx != INT_MIN && idx != INT_MAX) {
12838 idx = JimRelToAbsIndex(len, idx);
12840 if (idx < 0 || idx >= len || str == NULL) {
12841 Jim_SetResultString(interp, "", 0);
12843 else if (len == Jim_Length(argv[2])) {
12844 /* ASCII optimisation */
12845 Jim_SetResultString(interp, str + idx, 1);
12847 else {
12848 int c;
12849 int i = utf8_index(str, idx);
12850 Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
12852 return JIM_OK;
12855 case OPT_FIRST:
12856 case OPT_LAST:{
12857 int idx = 0, l1, l2;
12858 const char *s1, *s2;
12860 if (argc != 4 && argc != 5) {
12861 Jim_WrongNumArgs(interp, 2, argv, "subString string ?index?");
12862 return JIM_ERR;
12864 s1 = Jim_String(argv[2]);
12865 s2 = Jim_String(argv[3]);
12866 l1 = Jim_Utf8Length(interp, argv[2]);
12867 l2 = Jim_Utf8Length(interp, argv[3]);
12868 if (argc == 5) {
12869 if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
12870 return JIM_ERR;
12872 idx = JimRelToAbsIndex(l2, idx);
12874 else if (option == OPT_LAST) {
12875 idx = l2;
12877 if (option == OPT_FIRST) {
12878 Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
12880 else {
12881 #ifdef JIM_UTF8
12882 Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
12883 #else
12884 Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
12885 #endif
12887 return JIM_OK;
12890 case OPT_TRIM:
12891 case OPT_TRIMLEFT:
12892 case OPT_TRIMRIGHT:{
12893 Jim_Obj *trimchars;
12895 if (argc != 3 && argc != 4) {
12896 Jim_WrongNumArgs(interp, 2, argv, "string ?trimchars?");
12897 return JIM_ERR;
12899 trimchars = (argc == 4 ? argv[3] : NULL);
12900 if (option == OPT_TRIM) {
12901 Jim_SetResult(interp, JimStringTrim(interp, argv[2], trimchars));
12903 else if (option == OPT_TRIMLEFT) {
12904 Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], trimchars));
12906 else if (option == OPT_TRIMRIGHT) {
12907 Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], trimchars));
12909 return JIM_OK;
12912 case OPT_TOLOWER:
12913 case OPT_TOUPPER:
12914 if (argc != 3) {
12915 Jim_WrongNumArgs(interp, 2, argv, "string");
12916 return JIM_ERR;
12918 if (option == OPT_TOLOWER) {
12919 Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
12921 else {
12922 Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
12924 return JIM_OK;
12926 case OPT_IS:
12927 if (argc == 4 || (argc == 5 && Jim_CompareStringImmediate(interp, argv[3], "-strict"))) {
12928 return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
12930 Jim_WrongNumArgs(interp, 2, argv, "class ?-strict? str");
12931 return JIM_ERR;
12933 return JIM_OK;
12936 /* [time] */
12937 static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12939 long i, count = 1;
12940 jim_wide start, elapsed;
12941 char buf[60];
12942 const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";
12944 if (argc < 2) {
12945 Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
12946 return JIM_ERR;
12948 if (argc == 3) {
12949 if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
12950 return JIM_ERR;
12952 if (count < 0)
12953 return JIM_OK;
12954 i = count;
12955 start = JimClock();
12956 while (i-- > 0) {
12957 int retval;
12959 retval = Jim_EvalObj(interp, argv[1]);
12960 if (retval != JIM_OK) {
12961 return retval;
12964 elapsed = JimClock() - start;
12965 sprintf(buf, fmt, count == 0 ? 0 : elapsed / count);
12966 Jim_SetResultString(interp, buf, -1);
12967 return JIM_OK;
12970 /* [exit] */
12971 static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12973 long exitCode = 0;
12975 if (argc > 2) {
12976 Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
12977 return JIM_ERR;
12979 if (argc == 2) {
12980 if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
12981 return JIM_ERR;
12983 interp->exitCode = exitCode;
12984 return JIM_EXIT;
12987 /* [catch] */
12988 static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12990 int exitCode = 0;
12991 int i;
12992 int sig = 0;
12994 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
12995 jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
12996 static const int max_ignore_code = sizeof(ignore_mask) * 8;
12998 /* Reset the error code before catch.
12999 * Note that this is not strictly correct.
13001 Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
13003 for (i = 1; i < argc - 1; i++) {
13004 const char *arg = Jim_String(argv[i]);
13005 jim_wide option;
13006 int ignore;
13008 /* It's a pity we can't use Jim_GetEnum here :-( */
13009 if (strcmp(arg, "--") == 0) {
13010 i++;
13011 break;
13013 if (*arg != '-') {
13014 break;
13017 if (strncmp(arg, "-no", 3) == 0) {
13018 arg += 3;
13019 ignore = 1;
13021 else {
13022 arg++;
13023 ignore = 0;
13026 if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
13027 option = -1;
13029 if (option < 0) {
13030 option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
13032 if (option < 0) {
13033 goto wrongargs;
13036 if (ignore) {
13037 ignore_mask |= (1 << option);
13039 else {
13040 ignore_mask &= ~(1 << option);
13044 argc -= i;
13045 if (argc < 1 || argc > 3) {
13046 wrongargs:
13047 Jim_WrongNumArgs(interp, 1, argv,
13048 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13049 return JIM_ERR;
13051 argv += i;
13053 if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
13054 sig++;
13057 interp->signal_level += sig;
13058 if (interp->signal_level && interp->sigmask) {
13059 /* If a signal is set, don't even try to execute the body */
13060 exitCode = JIM_SIGNAL;
13062 else {
13063 exitCode = Jim_EvalObj(interp, argv[0]);
13065 interp->signal_level -= sig;
13067 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13068 if (exitCode >= 0 && exitCode < max_ignore_code && ((1 << exitCode) & ignore_mask)) {
13069 /* Not caught, pass it up */
13070 return exitCode;
13073 if (sig && exitCode == JIM_SIGNAL) {
13074 /* Catch the signal at this level */
13075 if (interp->signal_set_result) {
13076 interp->signal_set_result(interp, interp->sigmask);
13078 else {
13079 Jim_SetResultInt(interp, interp->sigmask);
13081 interp->sigmask = 0;
13084 if (argc >= 2) {
13085 if (Jim_SetVariable(interp, argv[1], Jim_GetResult(interp)) != JIM_OK) {
13086 return JIM_ERR;
13088 if (argc == 3) {
13089 Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
13091 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
13092 Jim_ListAppendElement(interp, optListObj,
13093 Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
13094 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
13095 Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
13096 if (exitCode == JIM_ERR) {
13097 Jim_Obj *errorCode;
13098 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
13099 -1));
13100 Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
13102 errorCode = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
13103 if (errorCode) {
13104 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
13105 Jim_ListAppendElement(interp, optListObj, errorCode);
13108 if (Jim_SetVariable(interp, argv[2], optListObj) != JIM_OK) {
13109 return JIM_ERR;
13113 Jim_SetResultInt(interp, exitCode);
13114 return JIM_OK;
13117 #ifdef JIM_REFERENCES
13119 /* [ref] */
13120 static int Jim_RefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13122 if (argc != 3 && argc != 4) {
13123 Jim_WrongNumArgs(interp, 1, argv, "string tag ?finalizer?");
13124 return JIM_ERR;
13126 if (argc == 3) {
13127 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], NULL));
13129 else {
13130 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], argv[3]));
13132 return JIM_OK;
13135 /* [getref] */
13136 static int Jim_GetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13138 Jim_Reference *refPtr;
13140 if (argc != 2) {
13141 Jim_WrongNumArgs(interp, 1, argv, "reference");
13142 return JIM_ERR;
13144 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13145 return JIM_ERR;
13146 Jim_SetResult(interp, refPtr->objPtr);
13147 return JIM_OK;
13150 /* [setref] */
13151 static int Jim_SetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13153 Jim_Reference *refPtr;
13155 if (argc != 3) {
13156 Jim_WrongNumArgs(interp, 1, argv, "reference newValue");
13157 return JIM_ERR;
13159 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13160 return JIM_ERR;
13161 Jim_IncrRefCount(argv[2]);
13162 Jim_DecrRefCount(interp, refPtr->objPtr);
13163 refPtr->objPtr = argv[2];
13164 Jim_SetResult(interp, argv[2]);
13165 return JIM_OK;
13168 /* [collect] */
13169 static int Jim_CollectCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13171 if (argc != 1) {
13172 Jim_WrongNumArgs(interp, 1, argv, "");
13173 return JIM_ERR;
13175 Jim_SetResultInt(interp, Jim_Collect(interp));
13177 /* Free all the freed objects. */
13178 while (interp->freeList) {
13179 Jim_Obj *nextObjPtr = interp->freeList->nextObjPtr;
13180 Jim_Free(interp->freeList);
13181 interp->freeList = nextObjPtr;
13184 return JIM_OK;
13187 /* [finalize] reference ?newValue? */
13188 static int Jim_FinalizeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13190 if (argc != 2 && argc != 3) {
13191 Jim_WrongNumArgs(interp, 1, argv, "reference ?finalizerProc?");
13192 return JIM_ERR;
13194 if (argc == 2) {
13195 Jim_Obj *cmdNamePtr;
13197 if (Jim_GetFinalizer(interp, argv[1], &cmdNamePtr) != JIM_OK)
13198 return JIM_ERR;
13199 if (cmdNamePtr != NULL) /* otherwise the null string is returned. */
13200 Jim_SetResult(interp, cmdNamePtr);
13202 else {
13203 if (Jim_SetFinalizer(interp, argv[1], argv[2]) != JIM_OK)
13204 return JIM_ERR;
13205 Jim_SetResult(interp, argv[2]);
13207 return JIM_OK;
13210 /* [info references] */
13211 static int JimInfoReferences(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13213 Jim_Obj *listObjPtr;
13214 Jim_HashTableIterator *htiter;
13215 Jim_HashEntry *he;
13217 listObjPtr = Jim_NewListObj(interp, NULL, 0);
13219 htiter = Jim_GetHashTableIterator(&interp->references);
13220 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
13221 char buf[JIM_REFERENCE_SPACE];
13222 Jim_Reference *refPtr = he->u.val;
13223 const jim_wide *refId = he->key;
13225 JimFormatReference(buf, refPtr, *refId);
13226 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, buf, -1));
13228 Jim_FreeHashTableIterator(htiter);
13229 Jim_SetResult(interp, listObjPtr);
13230 return JIM_OK;
13232 #endif
13234 /* [rename] */
13235 static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13237 const char *oldName, *newName;
13239 if (argc != 3) {
13240 Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
13241 return JIM_ERR;
13244 if (JimValidName(interp, "new procedure", argv[2])) {
13245 return JIM_ERR;
13248 oldName = Jim_String(argv[1]);
13249 newName = Jim_String(argv[2]);
13250 return Jim_RenameCommand(interp, oldName, newName);
13253 int Jim_DictKeys(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj)
13255 int i;
13256 int len;
13257 Jim_Obj *resultObj;
13258 Jim_Obj *dictObj;
13259 Jim_Obj **dictValuesObj;
13261 if (Jim_DictKeysVector(interp, objPtr, NULL, 0, &dictObj, JIM_ERRMSG) != JIM_OK) {
13262 return JIM_ERR;
13265 /* XXX: Could make the exact-match case much more efficient here.
13266 * See JimCommandsList()
13268 if (Jim_DictPairs(interp, dictObj, &dictValuesObj, &len) != JIM_OK) {
13269 return JIM_ERR;
13272 /* Only return the matching values */
13273 resultObj = Jim_NewListObj(interp, NULL, 0);
13275 for (i = 0; i < len; i += 2) {
13276 if (patternObj == NULL || Jim_StringMatchObj(interp, patternObj, dictValuesObj[i], 0)) {
13277 Jim_ListAppendElement(interp, resultObj, dictValuesObj[i]);
13280 Jim_Free(dictValuesObj);
13282 Jim_SetResult(interp, resultObj);
13283 return JIM_OK;
13286 int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
13288 if (SetDictFromAny(interp, objPtr) != JIM_OK) {
13289 return -1;
13291 return ((Jim_HashTable *)objPtr->internalRep.ptr)->used;
13294 /* [dict] */
13295 static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13297 Jim_Obj *objPtr;
13298 int option;
13299 static const char * const options[] = {
13300 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13302 enum
13304 OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXIST, OPT_KEYS, OPT_MERGE, OPT_SIZE, OPT_WITH,
13307 if (argc < 2) {
13308 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?arguments ...?");
13309 return JIM_ERR;
13312 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK) {
13313 return JIM_ERR;
13316 switch (option) {
13317 case OPT_GET:
13318 if (argc < 3) {
13319 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13320 return JIM_ERR;
13322 if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
13323 JIM_ERRMSG) != JIM_OK) {
13324 return JIM_ERR;
13326 Jim_SetResult(interp, objPtr);
13327 return JIM_OK;
13329 case OPT_SET:
13330 if (argc < 5) {
13331 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");
13332 return JIM_ERR;
13334 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1], JIM_ERRMSG);
13336 case OPT_EXIST:
13337 if (argc < 3) {
13338 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13339 return JIM_ERR;
13341 Jim_SetResultBool(interp, Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3,
13342 &objPtr, JIM_ERRMSG) == JIM_OK);
13343 return JIM_OK;
13345 case OPT_UNSET:
13346 if (argc < 4) {
13347 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");
13348 return JIM_ERR;
13350 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL, JIM_NONE);
13352 case OPT_KEYS:
13353 if (argc != 3 && argc != 4) {
13354 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?pattern?");
13355 return JIM_ERR;
13357 return Jim_DictKeys(interp, argv[2], argc == 4 ? argv[3] : NULL);
13359 case OPT_SIZE: {
13360 int size;
13362 if (argc != 3) {
13363 Jim_WrongNumArgs(interp, 2, argv, "dictVar");
13364 return JIM_ERR;
13367 size = Jim_DictSize(interp, argv[2]);
13368 if (size < 0) {
13369 return JIM_ERR;
13371 Jim_SetResultInt(interp, size);
13372 return JIM_OK;
13375 case OPT_MERGE:
13376 if (argc == 2) {
13377 return JIM_OK;
13379 else if (argv[2]->typePtr != &dictObjType && SetDictFromAny(interp, argv[2]) != JIM_OK) {
13380 return JIM_ERR;
13382 else {
13383 return Jim_EvalPrefix(interp, "dict merge", argc - 2, argv + 2);
13386 case OPT_WITH:
13387 if (argc < 4) {
13388 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?key ...? script");
13389 return JIM_ERR;
13391 else if (Jim_GetVariable(interp, argv[2], JIM_ERRMSG) == NULL) {
13392 return JIM_ERR;
13394 else {
13395 return Jim_EvalPrefix(interp, "dict with", argc - 2, argv + 2);
13398 case OPT_CREATE:
13399 if (argc % 2) {
13400 Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");
13401 return JIM_ERR;
13403 objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
13404 Jim_SetResult(interp, objPtr);
13405 return JIM_OK;
13407 default:
13408 abort();
13412 /* [subst] */
13413 static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13415 static const char * const options[] = {
13416 "-nobackslashes", "-nocommands", "-novariables", NULL
13418 enum
13419 { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
13420 int i;
13421 int flags = JIM_SUBST_FLAG;
13422 Jim_Obj *objPtr;
13424 if (argc < 2) {
13425 Jim_WrongNumArgs(interp, 1, argv, "?options? string");
13426 return JIM_ERR;
13428 for (i = 1; i < (argc - 1); i++) {
13429 int option;
13431 if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
13432 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13433 return JIM_ERR;
13435 switch (option) {
13436 case OPT_NOBACKSLASHES:
13437 flags |= JIM_SUBST_NOESC;
13438 break;
13439 case OPT_NOCOMMANDS:
13440 flags |= JIM_SUBST_NOCMD;
13441 break;
13442 case OPT_NOVARIABLES:
13443 flags |= JIM_SUBST_NOVAR;
13444 break;
13447 if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
13448 return JIM_ERR;
13450 Jim_SetResult(interp, objPtr);
13451 return JIM_OK;
13454 /* [info] */
13455 static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13457 int cmd;
13458 Jim_Obj *objPtr;
13459 int mode = 0;
13461 static const char * const commands[] = {
13462 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13463 "vars", "version", "patchlevel", "complete", "args", "hostname",
13464 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13465 "references", NULL
13467 enum
13468 { INFO_BODY, INFO_COMMANDS, INFO_PROCS, INFO_CHANNELS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,
13469 INFO_FRAME, INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_PATCHLEVEL, INFO_COMPLETE, INFO_ARGS,
13470 INFO_HOSTNAME, INFO_SCRIPT, INFO_SOURCE, INFO_STACKTRACE, INFO_NAMEOFEXECUTABLE,
13471 INFO_RETURNCODES, INFO_REFERENCES,
13474 if (argc < 2) {
13475 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?args ...?");
13476 return JIM_ERR;
13478 if (Jim_GetEnum(interp, argv[1], commands, &cmd, "subcommand", JIM_ERRMSG | JIM_ENUM_ABBREV)
13479 != JIM_OK) {
13480 return JIM_ERR;
13483 /* Test for the the most common commands first, just in case it makes a difference */
13484 switch (cmd) {
13485 case INFO_EXISTS:{
13486 if (argc != 3) {
13487 Jim_WrongNumArgs(interp, 2, argv, "varName");
13488 return JIM_ERR;
13490 Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
13491 break;
13494 case INFO_CHANNELS:
13495 #ifndef jim_ext_aio
13496 Jim_SetResultString(interp, "aio not enabled", -1);
13497 return JIM_ERR;
13498 #endif
13499 case INFO_COMMANDS:
13500 case INFO_PROCS:
13501 if (argc != 2 && argc != 3) {
13502 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13503 return JIM_ERR;
13505 Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL,
13506 (cmd - INFO_COMMANDS)));
13507 break;
13509 case INFO_VARS:
13510 mode++; /* JIM_VARLIST_VARS */
13511 case INFO_LOCALS:
13512 mode++; /* JIM_VARLIST_LOCALS */
13513 case INFO_GLOBALS:
13514 /* mode 0 => JIM_VARLIST_GLOBALS */
13515 if (argc != 2 && argc != 3) {
13516 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13517 return JIM_ERR;
13519 Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
13520 break;
13522 case INFO_SCRIPT:
13523 if (argc != 2) {
13524 Jim_WrongNumArgs(interp, 2, argv, "");
13525 return JIM_ERR;
13527 Jim_SetResult(interp, Jim_GetScript(interp, interp->currentScriptObj)->fileNameObj);
13528 break;
13530 case INFO_SOURCE:{
13531 int line;
13532 Jim_Obj *resObjPtr;
13533 Jim_Obj *fileNameObj;
13535 if (argc != 3) {
13536 Jim_WrongNumArgs(interp, 2, argv, "source");
13537 return JIM_ERR;
13539 if (argv[2]->typePtr == &sourceObjType) {
13540 fileNameObj = argv[2]->internalRep.sourceValue.fileNameObj;
13541 line = argv[2]->internalRep.sourceValue.lineNumber;
13543 else if (argv[2]->typePtr == &scriptObjType) {
13544 ScriptObj *script = Jim_GetScript(interp, argv[2]);
13545 fileNameObj = script->fileNameObj;
13546 line = script->line;
13548 else {
13549 fileNameObj = interp->emptyObj;
13550 line = 1;
13552 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13553 Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
13554 Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
13555 Jim_SetResult(interp, resObjPtr);
13556 break;
13559 case INFO_STACKTRACE:
13560 Jim_SetResult(interp, interp->stackTrace);
13561 break;
13563 case INFO_LEVEL:
13564 case INFO_FRAME:
13565 switch (argc) {
13566 case 2:
13567 Jim_SetResultInt(interp, interp->framePtr->level);
13568 break;
13570 case 3:
13571 if (JimInfoLevel(interp, argv[2], &objPtr, cmd == INFO_LEVEL) != JIM_OK) {
13572 return JIM_ERR;
13574 Jim_SetResult(interp, objPtr);
13575 break;
13577 default:
13578 Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");
13579 return JIM_ERR;
13581 break;
13583 case INFO_BODY:
13584 case INFO_ARGS:{
13585 Jim_Cmd *cmdPtr;
13587 if (argc != 3) {
13588 Jim_WrongNumArgs(interp, 2, argv, "procname");
13589 return JIM_ERR;
13591 if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
13592 return JIM_ERR;
13594 if (!cmdPtr->isproc) {
13595 Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
13596 return JIM_ERR;
13598 Jim_SetResult(interp,
13599 cmd == INFO_BODY ? cmdPtr->u.proc.bodyObjPtr : cmdPtr->u.proc.argListObjPtr);
13600 break;
13603 case INFO_VERSION:
13604 case INFO_PATCHLEVEL:{
13605 char buf[(JIM_INTEGER_SPACE * 2) + 1];
13607 sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
13608 Jim_SetResultString(interp, buf, -1);
13609 break;
13612 case INFO_COMPLETE:
13613 if (argc != 3 && argc != 4) {
13614 Jim_WrongNumArgs(interp, 2, argv, "script ?missing?");
13615 return JIM_ERR;
13617 else {
13618 int len;
13619 const char *s = Jim_GetString(argv[2], &len);
13620 char missing;
13622 Jim_SetResultBool(interp, Jim_ScriptIsComplete(s, len, &missing));
13623 if (missing != ' ' && argc == 4) {
13624 Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
13627 break;
13629 case INFO_HOSTNAME:
13630 /* Redirect to os.gethostname if it exists */
13631 return Jim_Eval(interp, "os.gethostname");
13633 case INFO_NAMEOFEXECUTABLE:
13634 /* Redirect to Tcl proc */
13635 return Jim_Eval(interp, "{info nameofexecutable}");
13637 case INFO_RETURNCODES:
13638 if (argc == 2) {
13639 int i;
13640 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
13642 for (i = 0; jimReturnCodes[i]; i++) {
13643 Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
13644 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
13645 jimReturnCodes[i], -1));
13648 Jim_SetResult(interp, listObjPtr);
13650 else if (argc == 3) {
13651 long code;
13652 const char *name;
13654 if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
13655 return JIM_ERR;
13657 name = Jim_ReturnCode(code);
13658 if (*name == '?') {
13659 Jim_SetResultInt(interp, code);
13661 else {
13662 Jim_SetResultString(interp, name, -1);
13665 else {
13666 Jim_WrongNumArgs(interp, 2, argv, "?code?");
13667 return JIM_ERR;
13669 break;
13670 case INFO_REFERENCES:
13671 #ifdef JIM_REFERENCES
13672 return JimInfoReferences(interp, argc, argv);
13673 #else
13674 Jim_SetResultString(interp, "not supported", -1);
13675 return JIM_ERR;
13676 #endif
13678 return JIM_OK;
13681 /* [exists] */
13682 static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13684 Jim_Obj *objPtr;
13686 static const char * const options[] = {
13687 "-command", "-proc", "-var", NULL
13689 enum
13691 OPT_COMMAND, OPT_PROC, OPT_VAR
13693 int option;
13695 if (argc == 2) {
13696 option = OPT_VAR;
13697 objPtr = argv[1];
13699 else if (argc == 3) {
13700 if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13701 return JIM_ERR;
13703 objPtr = argv[2];
13705 else {
13706 Jim_WrongNumArgs(interp, 1, argv, "?option? name");
13707 return JIM_ERR;
13710 /* Test for the the most common commands first, just in case it makes a difference */
13711 switch (option) {
13712 case OPT_VAR:
13713 Jim_SetResultBool(interp, Jim_GetVariable(interp, objPtr, 0) != NULL);
13714 break;
13716 case OPT_COMMAND:
13717 case OPT_PROC: {
13718 Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
13719 Jim_SetResultBool(interp, cmd != NULL && (option == OPT_COMMAND || cmd->isproc));
13720 break;
13723 return JIM_OK;
13726 /* [split] */
13727 static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13729 const char *str, *splitChars, *noMatchStart;
13730 int splitLen, strLen;
13731 Jim_Obj *resObjPtr;
13732 int c;
13733 int len;
13735 if (argc != 2 && argc != 3) {
13736 Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
13737 return JIM_ERR;
13740 str = Jim_GetString(argv[1], &len);
13741 if (len == 0) {
13742 return JIM_OK;
13744 strLen = Jim_Utf8Length(interp, argv[1]);
13746 /* Init */
13747 if (argc == 2) {
13748 splitChars = " \n\t\r";
13749 splitLen = 4;
13751 else {
13752 splitChars = Jim_String(argv[2]);
13753 splitLen = Jim_Utf8Length(interp, argv[2]);
13756 noMatchStart = str;
13757 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13759 /* Split */
13760 if (splitLen) {
13761 Jim_Obj *objPtr;
13762 while (strLen--) {
13763 const char *sc = splitChars;
13764 int scLen = splitLen;
13765 int sl = utf8_tounicode(str, &c);
13766 while (scLen--) {
13767 int pc;
13768 sc += utf8_tounicode(sc, &pc);
13769 if (c == pc) {
13770 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13771 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13772 noMatchStart = str + sl;
13773 break;
13776 str += sl;
13778 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13779 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13781 else {
13782 /* This handles the special case of splitchars eq {}
13783 * Optimise by sharing common (ASCII) characters
13785 Jim_Obj **commonObj = NULL;
13786 #define NUM_COMMON (128 - 9)
13787 while (strLen--) {
13788 int n = utf8_tounicode(str, &c);
13789 #ifdef JIM_OPTIMIZATION
13790 if (c >= 9 && c < 128) {
13791 /* Common ASCII char. Note that 9 is the tab character */
13792 c -= 9;
13793 if (!commonObj) {
13794 commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
13795 memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
13797 if (!commonObj[c]) {
13798 commonObj[c] = Jim_NewStringObj(interp, str, 1);
13800 Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
13801 str++;
13802 continue;
13804 #endif
13805 Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
13806 str += n;
13808 Jim_Free(commonObj);
13811 Jim_SetResult(interp, resObjPtr);
13812 return JIM_OK;
13815 /* [join] */
13816 static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13818 const char *joinStr;
13819 int joinStrLen, i, listLen;
13820 Jim_Obj *resObjPtr;
13822 if (argc != 2 && argc != 3) {
13823 Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
13824 return JIM_ERR;
13826 /* Init */
13827 if (argc == 2) {
13828 joinStr = " ";
13829 joinStrLen = 1;
13831 else {
13832 joinStr = Jim_GetString(argv[2], &joinStrLen);
13834 listLen = Jim_ListLength(interp, argv[1]);
13835 resObjPtr = Jim_NewStringObj(interp, NULL, 0);
13836 /* Split */
13837 for (i = 0; i < listLen; i++) {
13838 Jim_Obj *objPtr = 0;
13840 Jim_ListIndex(interp, argv[1], i, &objPtr, JIM_NONE);
13841 Jim_AppendObj(interp, resObjPtr, objPtr);
13842 if (i + 1 != listLen) {
13843 Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
13846 Jim_SetResult(interp, resObjPtr);
13847 return JIM_OK;
13850 /* [format] */
13851 static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13853 Jim_Obj *objPtr;
13855 if (argc < 2) {
13856 Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
13857 return JIM_ERR;
13859 objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
13860 if (objPtr == NULL)
13861 return JIM_ERR;
13862 Jim_SetResult(interp, objPtr);
13863 return JIM_OK;
13866 /* [scan] */
13867 static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13869 Jim_Obj *listPtr, **outVec;
13870 int outc, i;
13872 if (argc < 3) {
13873 Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
13874 return JIM_ERR;
13876 if (argv[2]->typePtr != &scanFmtStringObjType)
13877 SetScanFmtFromAny(interp, argv[2]);
13878 if (FormatGetError(argv[2]) != 0) {
13879 Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
13880 return JIM_ERR;
13882 if (argc > 3) {
13883 int maxPos = FormatGetMaxPos(argv[2]);
13884 int count = FormatGetCnvCount(argv[2]);
13886 if (maxPos > argc - 3) {
13887 Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
13888 return JIM_ERR;
13890 else if (count > argc - 3) {
13891 Jim_SetResultString(interp, "different numbers of variable names and "
13892 "field specifiers", -1);
13893 return JIM_ERR;
13895 else if (count < argc - 3) {
13896 Jim_SetResultString(interp, "variable is not assigned by any "
13897 "conversion specifiers", -1);
13898 return JIM_ERR;
13901 listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
13902 if (listPtr == 0)
13903 return JIM_ERR;
13904 if (argc > 3) {
13905 int rc = JIM_OK;
13906 int count = 0;
13908 if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
13909 int len = Jim_ListLength(interp, listPtr);
13911 if (len != 0) {
13912 JimListGetElements(interp, listPtr, &outc, &outVec);
13913 for (i = 0; i < outc; ++i) {
13914 if (Jim_Length(outVec[i]) > 0) {
13915 ++count;
13916 if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
13917 rc = JIM_ERR;
13922 Jim_FreeNewObj(interp, listPtr);
13924 else {
13925 count = -1;
13927 if (rc == JIM_OK) {
13928 Jim_SetResultInt(interp, count);
13930 return rc;
13932 else {
13933 if (listPtr == (Jim_Obj *)EOF) {
13934 Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
13935 return JIM_OK;
13937 Jim_SetResult(interp, listPtr);
13939 return JIM_OK;
13942 /* [error] */
13943 static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13945 if (argc != 2 && argc != 3) {
13946 Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
13947 return JIM_ERR;
13949 Jim_SetResult(interp, argv[1]);
13950 if (argc == 3) {
13951 JimSetStackTrace(interp, argv[2]);
13952 return JIM_ERR;
13954 interp->addStackTrace++;
13955 return JIM_ERR;
13958 /* [lrange] */
13959 static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13961 Jim_Obj *objPtr;
13963 if (argc != 4) {
13964 Jim_WrongNumArgs(interp, 1, argv, "list first last");
13965 return JIM_ERR;
13967 if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
13968 return JIM_ERR;
13969 Jim_SetResult(interp, objPtr);
13970 return JIM_OK;
13973 /* [lrepeat] */
13974 static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13976 Jim_Obj *objPtr;
13977 long count;
13979 if (argc < 2 || Jim_GetLong(interp, argv[1], &count) != JIM_OK || count < 0) {
13980 Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
13981 return JIM_ERR;
13984 if (count == 0 || argc == 2) {
13985 return JIM_OK;
13988 argc -= 2;
13989 argv += 2;
13991 objPtr = Jim_NewListObj(interp, argv, argc);
13992 while (--count) {
13993 int i;
13995 for (i = 0; i < argc; i++) {
13996 ListAppendElement(objPtr, argv[i]);
14000 Jim_SetResult(interp, objPtr);
14001 return JIM_OK;
14004 char **Jim_GetEnviron(void)
14006 #if defined(HAVE__NSGETENVIRON)
14007 return *_NSGetEnviron();
14008 #else
14009 #if !defined(NO_ENVIRON_EXTERN)
14010 extern char **environ;
14011 #endif
14013 return environ;
14014 #endif
14017 void Jim_SetEnviron(char **env)
14019 #if defined(HAVE__NSGETENVIRON)
14020 *_NSGetEnviron() = env;
14021 #else
14022 #if !defined(NO_ENVIRON_EXTERN)
14023 extern char **environ;
14024 #endif
14026 environ = env;
14027 #endif
14030 /* [env] */
14031 static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14033 const char *key;
14034 const char *val;
14036 if (argc == 1) {
14037 char **e = Jim_GetEnviron();
14039 int i;
14040 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
14042 for (i = 0; e[i]; i++) {
14043 const char *equals = strchr(e[i], '=');
14045 if (equals) {
14046 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
14047 equals - e[i]));
14048 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
14052 Jim_SetResult(interp, listObjPtr);
14053 return JIM_OK;
14056 if (argc < 2) {
14057 Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
14058 return JIM_ERR;
14060 key = Jim_String(argv[1]);
14061 val = getenv(key);
14062 if (val == NULL) {
14063 if (argc < 3) {
14064 Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
14065 return JIM_ERR;
14067 val = Jim_String(argv[2]);
14069 Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
14070 return JIM_OK;
14073 /* [source] */
14074 static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14076 int retval;
14078 if (argc != 2) {
14079 Jim_WrongNumArgs(interp, 1, argv, "fileName");
14080 return JIM_ERR;
14082 retval = Jim_EvalFile(interp, Jim_String(argv[1]));
14083 if (retval == JIM_RETURN)
14084 return JIM_OK;
14085 return retval;
14088 /* [lreverse] */
14089 static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14091 Jim_Obj *revObjPtr, **ele;
14092 int len;
14094 if (argc != 2) {
14095 Jim_WrongNumArgs(interp, 1, argv, "list");
14096 return JIM_ERR;
14098 JimListGetElements(interp, argv[1], &len, &ele);
14099 len--;
14100 revObjPtr = Jim_NewListObj(interp, NULL, 0);
14101 while (len >= 0)
14102 ListAppendElement(revObjPtr, ele[len--]);
14103 Jim_SetResult(interp, revObjPtr);
14104 return JIM_OK;
14107 static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
14109 jim_wide len;
14111 if (step == 0)
14112 return -1;
14113 if (start == end)
14114 return 0;
14115 else if (step > 0 && start > end)
14116 return -1;
14117 else if (step < 0 && end > start)
14118 return -1;
14119 len = end - start;
14120 if (len < 0)
14121 len = -len; /* abs(len) */
14122 if (step < 0)
14123 step = -step; /* abs(step) */
14124 len = 1 + ((len - 1) / step);
14125 /* We can truncate safely to INT_MAX, the range command
14126 * will always return an error for a such long range
14127 * because Tcl lists can't be so long. */
14128 if (len > INT_MAX)
14129 len = INT_MAX;
14130 return (int)((len < 0) ? -1 : len);
14133 /* [range] */
14134 static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14136 jim_wide start = 0, end, step = 1;
14137 int len, i;
14138 Jim_Obj *objPtr;
14140 if (argc < 2 || argc > 4) {
14141 Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
14142 return JIM_ERR;
14144 if (argc == 2) {
14145 if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)
14146 return JIM_ERR;
14148 else {
14149 if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||
14150 Jim_GetWide(interp, argv[2], &end) != JIM_OK)
14151 return JIM_ERR;
14152 if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)
14153 return JIM_ERR;
14155 if ((len = JimRangeLen(start, end, step)) == -1) {
14156 Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
14157 return JIM_ERR;
14159 objPtr = Jim_NewListObj(interp, NULL, 0);
14160 for (i = 0; i < len; i++)
14161 ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
14162 Jim_SetResult(interp, objPtr);
14163 return JIM_OK;
14166 /* [rand] */
14167 static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14169 jim_wide min = 0, max = 0, len, maxMul;
14171 if (argc < 1 || argc > 3) {
14172 Jim_WrongNumArgs(interp, 1, argv, "?min? max");
14173 return JIM_ERR;
14175 if (argc == 1) {
14176 max = JIM_WIDE_MAX;
14177 } else if (argc == 2) {
14178 if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)
14179 return JIM_ERR;
14180 } else if (argc == 3) {
14181 if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||
14182 Jim_GetWide(interp, argv[2], &max) != JIM_OK)
14183 return JIM_ERR;
14185 len = max-min;
14186 if (len < 0) {
14187 Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
14188 return JIM_ERR;
14190 maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
14191 while (1) {
14192 jim_wide r;
14194 JimRandomBytes(interp, &r, sizeof(jim_wide));
14195 if (r < 0 || r >= maxMul) continue;
14196 r = (len == 0) ? 0 : r%len;
14197 Jim_SetResultInt(interp, min+r);
14198 return JIM_OK;
14202 static const struct {
14203 const char *name;
14204 Jim_CmdProc cmdProc;
14205 } Jim_CoreCommandsTable[] = {
14206 {"set", Jim_SetCoreCommand},
14207 {"unset", Jim_UnsetCoreCommand},
14208 {"puts", Jim_PutsCoreCommand},
14209 {"+", Jim_AddCoreCommand},
14210 {"*", Jim_MulCoreCommand},
14211 {"-", Jim_SubCoreCommand},
14212 {"/", Jim_DivCoreCommand},
14213 {"incr", Jim_IncrCoreCommand},
14214 {"while", Jim_WhileCoreCommand},
14215 {"loop", Jim_LoopCoreCommand},
14216 {"for", Jim_ForCoreCommand},
14217 {"foreach", Jim_ForeachCoreCommand},
14218 {"lmap", Jim_LmapCoreCommand},
14219 {"if", Jim_IfCoreCommand},
14220 {"switch", Jim_SwitchCoreCommand},
14221 {"list", Jim_ListCoreCommand},
14222 {"lindex", Jim_LindexCoreCommand},
14223 {"lset", Jim_LsetCoreCommand},
14224 {"lsearch", Jim_LsearchCoreCommand},
14225 {"llength", Jim_LlengthCoreCommand},
14226 {"lappend", Jim_LappendCoreCommand},
14227 {"linsert", Jim_LinsertCoreCommand},
14228 {"lreplace", Jim_LreplaceCoreCommand},
14229 {"lsort", Jim_LsortCoreCommand},
14230 {"append", Jim_AppendCoreCommand},
14231 {"debug", Jim_DebugCoreCommand},
14232 {"eval", Jim_EvalCoreCommand},
14233 {"uplevel", Jim_UplevelCoreCommand},
14234 {"expr", Jim_ExprCoreCommand},
14235 {"break", Jim_BreakCoreCommand},
14236 {"continue", Jim_ContinueCoreCommand},
14237 {"proc", Jim_ProcCoreCommand},
14238 {"concat", Jim_ConcatCoreCommand},
14239 {"return", Jim_ReturnCoreCommand},
14240 {"upvar", Jim_UpvarCoreCommand},
14241 {"global", Jim_GlobalCoreCommand},
14242 {"string", Jim_StringCoreCommand},
14243 {"time", Jim_TimeCoreCommand},
14244 {"exit", Jim_ExitCoreCommand},
14245 {"catch", Jim_CatchCoreCommand},
14246 #ifdef JIM_REFERENCES
14247 {"ref", Jim_RefCoreCommand},
14248 {"getref", Jim_GetrefCoreCommand},
14249 {"setref", Jim_SetrefCoreCommand},
14250 {"finalize", Jim_FinalizeCoreCommand},
14251 {"collect", Jim_CollectCoreCommand},
14252 #endif
14253 {"rename", Jim_RenameCoreCommand},
14254 {"dict", Jim_DictCoreCommand},
14255 {"subst", Jim_SubstCoreCommand},
14256 {"info", Jim_InfoCoreCommand},
14257 {"exists", Jim_ExistsCoreCommand},
14258 {"split", Jim_SplitCoreCommand},
14259 {"join", Jim_JoinCoreCommand},
14260 {"format", Jim_FormatCoreCommand},
14261 {"scan", Jim_ScanCoreCommand},
14262 {"error", Jim_ErrorCoreCommand},
14263 {"lrange", Jim_LrangeCoreCommand},
14264 {"lrepeat", Jim_LrepeatCoreCommand},
14265 {"env", Jim_EnvCoreCommand},
14266 {"source", Jim_SourceCoreCommand},
14267 {"lreverse", Jim_LreverseCoreCommand},
14268 {"range", Jim_RangeCoreCommand},
14269 {"rand", Jim_RandCoreCommand},
14270 {"tailcall", Jim_TailcallCoreCommand},
14271 {"local", Jim_LocalCoreCommand},
14272 {"upcall", Jim_UpcallCoreCommand},
14273 {NULL, NULL},
14276 void Jim_RegisterCoreCommands(Jim_Interp *interp)
14278 int i = 0;
14280 while (Jim_CoreCommandsTable[i].name != NULL) {
14281 Jim_CreateCommand(interp,
14282 Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
14283 i++;
14287 /* -----------------------------------------------------------------------------
14288 * Interactive prompt
14289 * ---------------------------------------------------------------------------*/
14290 void Jim_MakeErrorMessage(Jim_Interp *interp)
14292 Jim_Obj *argv[2];
14294 argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
14295 argv[1] = interp->result;
14297 Jim_EvalObjVector(interp, 2, argv);
14300 static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
14301 const char *prefix, const char *const *tablePtr, const char *name)
14303 int count;
14304 char **tablePtrSorted;
14305 int i;
14307 for (count = 0; tablePtr[count]; count++) {
14310 if (name == NULL) {
14311 name = "option";
14314 Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
14315 tablePtrSorted = Jim_Alloc(sizeof(char *) * count);
14316 memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
14317 qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
14318 for (i = 0; i < count; i++) {
14319 if (i + 1 == count && count > 1) {
14320 Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
14322 Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
14323 if (i + 1 != count) {
14324 Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
14327 Jim_Free(tablePtrSorted);
14330 int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
14331 const char *const *tablePtr, int *indexPtr, const char *name, int flags)
14333 const char *bad = "bad ";
14334 const char *const *entryPtr = NULL;
14335 int i;
14336 int match = -1;
14337 int arglen;
14338 const char *arg = Jim_GetString(objPtr, &arglen);
14340 *indexPtr = -1;
14342 for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
14343 if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
14344 /* Found an exact match */
14345 *indexPtr = i;
14346 return JIM_OK;
14348 if (flags & JIM_ENUM_ABBREV) {
14349 /* Accept an unambiguous abbreviation.
14350 * Note that '-' doesnt' consitute a valid abbreviation
14352 if (strncmp(arg, *entryPtr, arglen) == 0) {
14353 if (*arg == '-' && arglen == 1) {
14354 break;
14356 if (match >= 0) {
14357 bad = "ambiguous ";
14358 goto ambiguous;
14360 match = i;
14365 /* If we had an unambiguous partial match */
14366 if (match >= 0) {
14367 *indexPtr = match;
14368 return JIM_OK;
14371 ambiguous:
14372 if (flags & JIM_ERRMSG) {
14373 JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
14375 return JIM_ERR;
14378 int Jim_FindByName(const char *name, const char * const array[], size_t len)
14380 int i;
14382 for (i = 0; i < (int)len; i++) {
14383 if (array[i] && strcmp(array[i], name) == 0) {
14384 return i;
14387 return -1;
14390 int Jim_IsDict(Jim_Obj *objPtr)
14392 return objPtr->typePtr == &dictObjType;
14395 int Jim_IsList(Jim_Obj *objPtr)
14397 return objPtr->typePtr == &listObjType;
14401 * Very simple printf-like formatting, designed for error messages.
14403 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14404 * The resulting string is created and set as the result.
14406 * Each '%s' should correspond to a regular string parameter.
14407 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14408 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14410 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14412 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14414 void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
14416 /* Initial space needed */
14417 int len = strlen(format);
14418 int extra = 0;
14419 int n = 0;
14420 const char *params[5];
14421 char *buf;
14422 va_list args;
14423 int i;
14425 va_start(args, format);
14427 for (i = 0; i < len && n < 5; i++) {
14428 int l;
14430 if (strncmp(format + i, "%s", 2) == 0) {
14431 params[n] = va_arg(args, char *);
14433 l = strlen(params[n]);
14435 else if (strncmp(format + i, "%#s", 3) == 0) {
14436 Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
14438 params[n] = Jim_GetString(objPtr, &l);
14440 else {
14441 if (format[i] == '%') {
14442 i++;
14444 continue;
14446 n++;
14447 extra += l;
14450 len += extra;
14451 buf = Jim_Alloc(len + 1);
14452 len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
14454 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
14457 /* stubs */
14458 #ifndef jim_ext_package
14459 int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
14461 return JIM_OK;
14463 #endif
14464 #ifndef jim_ext_aio
14465 FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
14467 Jim_SetResultString(interp, "aio not enabled", -1);
14468 return NULL;
14470 #endif
14474 * Local Variables: ***
14475 * c-basic-offset: 4 ***
14476 * tab-width: 4 ***
14477 * End: ***