Missing parens in non-utf8 version of utf8_strlen
[jimtcl.git] / jim.c
blobca29cb2b2cceeac2b602022c42bce4d4fe56ccb9
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_EXPR_INT 13
1109 #define JIM_TT_EXPR_DOUBLE 14
1111 #define JIM_TT_EXPRSUGAR 15 /* $(expression) */
1113 /* Operator token types start here */
1114 #define JIM_TT_EXPR_OP 20
1116 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1118 /* Parser states */
1119 #define JIM_PS_DEF 0 /* Default state */
1120 #define JIM_PS_QUOTE 1 /* Inside "" */
1121 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1123 /* Parser context structure. The same context is used both to parse
1124 * Tcl scripts and lists. */
1125 struct JimParserCtx
1127 const char *p; /* Pointer to the point of the program we are parsing */
1128 int len; /* Remaining length */
1129 int linenr; /* Current line number */
1130 const char *tstart;
1131 const char *tend; /* Returned token is at tstart-tend in 'prg'. */
1132 int tline; /* Line number of the returned token */
1133 int tt; /* Token type */
1134 int eof; /* Non zero if EOF condition is true. */
1135 int state; /* Parser state */
1136 int comment; /* Non zero if the next chars may be a comment. */
1137 char missing; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1138 int missingline; /* Line number starting the missing token */
1142 * Results of missing quotes, braces, etc. from parsing.
1144 struct JimParseResult {
1145 char missing; /* From JimParserCtx.missing */
1146 int line; /* From JimParserCtx.missingline */
1149 static int JimParseScript(struct JimParserCtx *pc);
1150 static int JimParseSep(struct JimParserCtx *pc);
1151 static int JimParseEol(struct JimParserCtx *pc);
1152 static int JimParseCmd(struct JimParserCtx *pc);
1153 static int JimParseQuote(struct JimParserCtx *pc);
1154 static int JimParseVar(struct JimParserCtx *pc);
1155 static int JimParseBrace(struct JimParserCtx *pc);
1156 static int JimParseStr(struct JimParserCtx *pc);
1157 static int JimParseComment(struct JimParserCtx *pc);
1158 static void JimParseSubCmd(struct JimParserCtx *pc);
1159 static int JimParseSubQuote(struct JimParserCtx *pc);
1160 static void JimParseSubCmd(struct JimParserCtx *pc);
1161 static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc);
1163 /* Initialize a parser context.
1164 * 'prg' is a pointer to the program text, linenr is the line
1165 * number of the first line contained in the program. */
1166 static void JimParserInit(struct JimParserCtx *pc, const char *prg, int len, int linenr)
1168 pc->p = prg;
1169 pc->len = len;
1170 pc->tstart = NULL;
1171 pc->tend = NULL;
1172 pc->tline = 0;
1173 pc->tt = JIM_TT_NONE;
1174 pc->eof = 0;
1175 pc->state = JIM_PS_DEF;
1176 pc->linenr = linenr;
1177 pc->comment = 1;
1178 pc->missing = ' ';
1179 pc->missingline = linenr;
1182 static int JimParseScript(struct JimParserCtx *pc)
1184 while (1) { /* the while is used to reiterate with continue if needed */
1185 if (!pc->len) {
1186 pc->tstart = pc->p;
1187 pc->tend = pc->p - 1;
1188 pc->tline = pc->linenr;
1189 pc->tt = JIM_TT_EOL;
1190 pc->eof = 1;
1191 return JIM_OK;
1193 switch (*(pc->p)) {
1194 case '\\':
1195 if (*(pc->p + 1) == '\n' && pc->state == JIM_PS_DEF) {
1196 return JimParseSep(pc);
1198 else {
1199 pc->comment = 0;
1200 return JimParseStr(pc);
1202 break;
1203 case ' ':
1204 case '\t':
1205 case '\r':
1206 if (pc->state == JIM_PS_DEF)
1207 return JimParseSep(pc);
1208 else {
1209 pc->comment = 0;
1210 return JimParseStr(pc);
1212 break;
1213 case '\n':
1214 case ';':
1215 pc->comment = 1;
1216 if (pc->state == JIM_PS_DEF)
1217 return JimParseEol(pc);
1218 else
1219 return JimParseStr(pc);
1220 break;
1221 case '[':
1222 pc->comment = 0;
1223 return JimParseCmd(pc);
1224 break;
1225 case '$':
1226 pc->comment = 0;
1227 if (JimParseVar(pc) == JIM_ERR) {
1228 pc->tstart = pc->tend = pc->p++;
1229 pc->len--;
1230 pc->tline = pc->linenr;
1231 pc->tt = JIM_TT_STR;
1232 return JIM_OK;
1234 else
1235 return JIM_OK;
1236 break;
1237 case '#':
1238 if (pc->comment) {
1239 JimParseComment(pc);
1240 continue;
1242 else {
1243 return JimParseStr(pc);
1245 default:
1246 pc->comment = 0;
1247 return JimParseStr(pc);
1248 break;
1250 return JIM_OK;
1254 static int JimParseSep(struct JimParserCtx *pc)
1256 pc->tstart = pc->p;
1257 pc->tline = pc->linenr;
1258 while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' ||
1259 (*pc->p == '\\' && *(pc->p + 1) == '\n')) {
1260 if (*pc->p == '\\') {
1261 pc->p++;
1262 pc->len--;
1263 pc->linenr++;
1265 pc->p++;
1266 pc->len--;
1268 pc->tend = pc->p - 1;
1269 pc->tt = JIM_TT_SEP;
1270 return JIM_OK;
1273 static int JimParseEol(struct JimParserCtx *pc)
1275 pc->tstart = pc->p;
1276 pc->tline = pc->linenr;
1277 while (*pc->p == ' ' || *pc->p == '\n' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == ';') {
1278 if (*pc->p == '\n')
1279 pc->linenr++;
1280 pc->p++;
1281 pc->len--;
1283 pc->tend = pc->p - 1;
1284 pc->tt = JIM_TT_EOL;
1285 return JIM_OK;
1289 ** Here are the rules for parsing:
1290 ** {braced expression}
1291 ** - Count open and closing braces
1292 ** - Backslash escapes meaning of braces
1294 ** "quoted expression"
1295 ** - First double quote at start of word terminates the expression
1296 ** - Backslash escapes quote and bracket
1297 ** - [commands brackets] are counted/nested
1298 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1300 ** [command expression]
1301 ** - Count open and closing brackets
1302 ** - Backslash escapes quote, bracket and brace
1303 ** - [commands brackets] are counted/nested
1304 ** - "quoted expressions" are parsed according to quoting rules
1305 ** - {braced expressions} are parsed according to brace rules
1307 ** For everything, backslash escapes the next char, newline increments current line
1311 * Parses a braced expression starting at pc->p.
1313 * Positions the parser at the end of the braced expression,
1314 * sets pc->tend and possibly pc->missing.
1316 static void JimParseSubBrace(struct JimParserCtx *pc)
1318 int level = 1;
1320 /* Skip the brace */
1321 pc->p++;
1322 pc->len--;
1323 while (pc->len) {
1324 switch (*pc->p) {
1325 case '\\':
1326 if (pc->len > 1) {
1327 if (*++pc->p == '\n') {
1328 pc->linenr++;
1330 pc->len--;
1332 break;
1334 case '{':
1335 level++;
1336 break;
1338 case '}':
1339 if (--level == 0) {
1340 pc->tend = pc->p - 1;
1341 pc->p++;
1342 pc->len--;
1343 return;
1345 break;
1347 case '\n':
1348 pc->linenr++;
1349 break;
1351 pc->p++;
1352 pc->len--;
1354 pc->missing = '{';
1355 pc->missingline = pc->tline;
1356 pc->tend = pc->p - 1;
1360 * Parses a quoted expression starting at pc->p.
1362 * Positions the parser at the end of the quoted expression,
1363 * sets pc->tend and possibly pc->missing.
1365 * Returns the type of the token of the string,
1366 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1367 * or JIM_TT_STR.
1369 static int JimParseSubQuote(struct JimParserCtx *pc)
1371 int tt = JIM_TT_STR;
1372 int line = pc->tline;
1374 /* Skip the quote */
1375 pc->p++;
1376 pc->len--;
1377 while (pc->len) {
1378 switch (*pc->p) {
1379 case '\\':
1380 if (pc->len > 1) {
1381 if (*++pc->p == '\n') {
1382 pc->linenr++;
1384 pc->len--;
1385 tt = JIM_TT_ESC;
1387 break;
1389 case '"':
1390 pc->tend = pc->p - 1;
1391 pc->p++;
1392 pc->len--;
1393 return tt;
1395 case '[':
1396 JimParseSubCmd(pc);
1397 tt = JIM_TT_ESC;
1398 continue;
1400 case '\n':
1401 pc->linenr++;
1402 break;
1404 case '$':
1405 tt = JIM_TT_ESC;
1406 break;
1408 pc->p++;
1409 pc->len--;
1411 pc->missing = '"';
1412 pc->missingline = line;
1413 pc->tend = pc->p - 1;
1414 return tt;
1418 * Parses a [command] expression starting at pc->p.
1420 * Positions the parser at the end of the command expression,
1421 * sets pc->tend and possibly pc->missing.
1423 static void JimParseSubCmd(struct JimParserCtx *pc)
1425 int level = 1;
1426 int startofword = 1;
1427 int line = pc->tline;
1429 /* Skip the bracket */
1430 pc->p++;
1431 pc->len--;
1432 while (pc->len) {
1433 switch (*pc->p) {
1434 case '\\':
1435 if (pc->len > 1) {
1436 if (*++pc->p == '\n') {
1437 pc->linenr++;
1439 pc->len--;
1441 break;
1443 case '[':
1444 level++;
1445 break;
1447 case ']':
1448 if (--level == 0) {
1449 pc->tend = pc->p - 1;
1450 pc->p++;
1451 pc->len--;
1452 return;
1454 break;
1456 case '"':
1457 if (startofword) {
1458 JimParseSubQuote(pc);
1459 continue;
1461 break;
1463 case '{':
1464 JimParseSubBrace(pc);
1465 startofword = 0;
1466 continue;
1468 case '\n':
1469 pc->linenr++;
1470 break;
1472 startofword = isspace(UCHAR(*pc->p));
1473 pc->p++;
1474 pc->len--;
1476 pc->missing = '[';
1477 pc->missingline = line;
1478 pc->tend = pc->p - 1;
1481 static int JimParseBrace(struct JimParserCtx *pc)
1483 pc->tstart = pc->p + 1;
1484 pc->tline = pc->linenr;
1485 pc->tt = JIM_TT_STR;
1486 JimParseSubBrace(pc);
1487 return JIM_OK;
1490 static int JimParseCmd(struct JimParserCtx *pc)
1492 pc->tstart = pc->p + 1;
1493 pc->tline = pc->linenr;
1494 pc->tt = JIM_TT_CMD;
1495 JimParseSubCmd(pc);
1496 return JIM_OK;
1499 static int JimParseQuote(struct JimParserCtx *pc)
1501 pc->tstart = pc->p + 1;
1502 pc->tline = pc->linenr;
1503 pc->tt = JimParseSubQuote(pc);
1504 return JIM_OK;
1507 static int JimParseVar(struct JimParserCtx *pc)
1509 /* skip the $ */
1510 pc->p++;
1511 pc->len--;
1513 #ifdef EXPRSUGAR_BRACKET
1514 if (*pc->p == '[') {
1515 /* Parse $[...] expr shorthand syntax */
1516 JimParseCmd(pc);
1517 pc->tt = JIM_TT_EXPRSUGAR;
1518 return JIM_OK;
1520 #endif
1522 pc->tstart = pc->p;
1523 pc->tt = JIM_TT_VAR;
1524 pc->tline = pc->linenr;
1526 if (*pc->p == '{') {
1527 pc->tstart = ++pc->p;
1528 pc->len--;
1530 while (pc->len && *pc->p != '}') {
1531 if (*pc->p == '\n') {
1532 pc->linenr++;
1534 pc->p++;
1535 pc->len--;
1537 pc->tend = pc->p - 1;
1538 if (pc->len) {
1539 pc->p++;
1540 pc->len--;
1543 else {
1544 while (1) {
1545 /* Skip double colon, but not single colon! */
1546 if (pc->p[0] == ':' && pc->p[1] == ':') {
1547 pc->p += 2;
1548 pc->len -= 2;
1549 continue;
1551 if (isalnum(UCHAR(*pc->p)) || *pc->p == '_') {
1552 pc->p++;
1553 pc->len--;
1554 continue;
1556 break;
1558 /* Parse [dict get] syntax sugar. */
1559 if (*pc->p == '(') {
1560 int count = 1;
1561 const char *paren = NULL;
1563 pc->tt = JIM_TT_DICTSUGAR;
1565 while (count && pc->len) {
1566 pc->p++;
1567 pc->len--;
1568 if (*pc->p == '\\' && pc->len >= 1) {
1569 pc->p++;
1570 pc->len--;
1572 else if (*pc->p == '(') {
1573 count++;
1575 else if (*pc->p == ')') {
1576 paren = pc->p;
1577 count--;
1580 if (count == 0) {
1581 pc->p++;
1582 pc->len--;
1584 else if (paren) {
1585 /* Did not find a matching paren. Back up */
1586 paren++;
1587 pc->len += (pc->p - paren);
1588 pc->p = paren;
1590 #ifndef EXPRSUGAR_BRACKET
1591 if (*pc->tstart == '(') {
1592 pc->tt = JIM_TT_EXPRSUGAR;
1594 #endif
1596 pc->tend = pc->p - 1;
1598 /* Check if we parsed just the '$' character.
1599 * That's not a variable so an error is returned
1600 * to tell the state machine to consider this '$' just
1601 * a string. */
1602 if (pc->tstart == pc->p) {
1603 pc->p--;
1604 pc->len++;
1605 return JIM_ERR;
1607 return JIM_OK;
1610 static int JimParseStr(struct JimParserCtx *pc)
1612 int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
1613 pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR);
1614 if (newword && *pc->p == '{') {
1615 return JimParseBrace(pc);
1617 else if (newword && *pc->p == '"') {
1618 pc->state = JIM_PS_QUOTE;
1619 pc->p++;
1620 pc->len--;
1621 /* In case the end quote is missing */
1622 pc->missingline = pc->tline;
1624 pc->tstart = pc->p;
1625 pc->tline = pc->linenr;
1626 while (1) {
1627 if (pc->len == 0) {
1628 if (pc->state == JIM_PS_QUOTE) {
1629 pc->missing = '"';
1631 pc->tend = pc->p - 1;
1632 pc->tt = JIM_TT_ESC;
1633 return JIM_OK;
1635 switch (*pc->p) {
1636 case '\\':
1637 if (pc->state == JIM_PS_DEF && *(pc->p + 1) == '\n') {
1638 pc->tend = pc->p - 1;
1639 pc->tt = JIM_TT_ESC;
1640 return JIM_OK;
1642 if (pc->len >= 2) {
1643 if (*(pc->p + 1) == '\n') {
1644 pc->linenr++;
1646 pc->p++;
1647 pc->len--;
1649 break;
1650 case '(':
1651 /* If the following token is not '$' just keep going */
1652 if (pc->len > 1 && pc->p[1] != '$') {
1653 break;
1655 case ')':
1656 /* Only need a separate ')' token if the previous was a var */
1657 if (*pc->p == '(' || pc->tt == JIM_TT_VAR) {
1658 if (pc->p == pc->tstart) {
1659 /* At the start of the token, so just return this char */
1660 pc->p++;
1661 pc->len--;
1663 pc->tend = pc->p - 1;
1664 pc->tt = JIM_TT_ESC;
1665 return JIM_OK;
1667 break;
1669 case '$':
1670 case '[':
1671 pc->tend = pc->p - 1;
1672 pc->tt = JIM_TT_ESC;
1673 return JIM_OK;
1674 case ' ':
1675 case '\t':
1676 case '\n':
1677 case '\r':
1678 case ';':
1679 if (pc->state == JIM_PS_DEF) {
1680 pc->tend = pc->p - 1;
1681 pc->tt = JIM_TT_ESC;
1682 return JIM_OK;
1684 else if (*pc->p == '\n') {
1685 pc->linenr++;
1687 break;
1688 case '"':
1689 if (pc->state == JIM_PS_QUOTE) {
1690 pc->tend = pc->p - 1;
1691 pc->tt = JIM_TT_ESC;
1692 pc->p++;
1693 pc->len--;
1694 pc->state = JIM_PS_DEF;
1695 return JIM_OK;
1697 break;
1699 pc->p++;
1700 pc->len--;
1702 return JIM_OK; /* unreached */
1705 static int JimParseComment(struct JimParserCtx *pc)
1707 while (*pc->p) {
1708 if (*pc->p == '\n') {
1709 pc->linenr++;
1710 if (*(pc->p - 1) != '\\') {
1711 pc->p++;
1712 pc->len--;
1713 return JIM_OK;
1716 pc->p++;
1717 pc->len--;
1719 return JIM_OK;
1722 /* xdigitval and odigitval are helper functions for JimEscape() */
1723 static int xdigitval(int c)
1725 if (c >= '0' && c <= '9')
1726 return c - '0';
1727 if (c >= 'a' && c <= 'f')
1728 return c - 'a' + 10;
1729 if (c >= 'A' && c <= 'F')
1730 return c - 'A' + 10;
1731 return -1;
1734 static int odigitval(int c)
1736 if (c >= '0' && c <= '7')
1737 return c - '0';
1738 return -1;
1741 /* Perform Tcl escape substitution of 's', storing the result
1742 * string into 'dest'. The escaped string is guaranteed to
1743 * be the same length or shorted than the source string.
1744 * Slen is the length of the string at 's', if it's -1 the string
1745 * length will be calculated by the function.
1747 * The function returns the length of the resulting string. */
1748 static int JimEscape(char *dest, const char *s, int slen)
1750 char *p = dest;
1751 int i, len;
1753 if (slen == -1)
1754 slen = strlen(s);
1756 for (i = 0; i < slen; i++) {
1757 switch (s[i]) {
1758 case '\\':
1759 switch (s[i + 1]) {
1760 case 'a':
1761 *p++ = 0x7;
1762 i++;
1763 break;
1764 case 'b':
1765 *p++ = 0x8;
1766 i++;
1767 break;
1768 case 'f':
1769 *p++ = 0xc;
1770 i++;
1771 break;
1772 case 'n':
1773 *p++ = 0xa;
1774 i++;
1775 break;
1776 case 'r':
1777 *p++ = 0xd;
1778 i++;
1779 break;
1780 case 't':
1781 *p++ = 0x9;
1782 i++;
1783 break;
1784 case 'u':
1785 case 'x':
1786 /* A unicode or hex sequence.
1787 * \u Expect 1-4 hex chars and convert to utf-8.
1788 * \x Expect 1-2 hex chars and convert to hex.
1789 * An invalid sequence means simply the escaped char.
1792 int val = 0;
1793 int k;
1795 i++;
1797 for (k = 0; k < (s[i] == 'u' ? 4 : 2); k++) {
1798 int c = xdigitval(s[i + k + 1]);
1799 if (c == -1) {
1800 break;
1802 val = (val << 4) | c;
1804 if (k) {
1805 /* Got a valid sequence, so convert */
1806 if (s[i] == 'u') {
1807 p += utf8_fromunicode(p, val);
1809 else {
1810 *p++ = val;
1812 i += k;
1813 break;
1815 /* Not a valid codepoint, just an escaped char */
1816 *p++ = s[i];
1818 break;
1819 case 'v':
1820 *p++ = 0xb;
1821 i++;
1822 break;
1823 case '\0':
1824 *p++ = '\\';
1825 i++;
1826 break;
1827 case '\n':
1828 /* Replace all spaces and tabs after backslash newline with a single space*/
1829 *p++ = ' ';
1830 do {
1831 i++;
1832 } while (s[i + 1] == ' ' || s[i + 1] == '\t');
1833 break;
1834 case '0':
1835 case '1':
1836 case '2':
1837 case '3':
1838 case '4':
1839 case '5':
1840 case '6':
1841 case '7':
1842 /* octal escape */
1844 int val = 0;
1845 int c = odigitval(s[i + 1]);
1847 val = c;
1848 c = odigitval(s[i + 2]);
1849 if (c == -1) {
1850 *p++ = val;
1851 i++;
1852 break;
1854 val = (val * 8) + c;
1855 c = odigitval(s[i + 3]);
1856 if (c == -1) {
1857 *p++ = val;
1858 i += 2;
1859 break;
1861 val = (val * 8) + c;
1862 *p++ = val;
1863 i += 3;
1865 break;
1866 default:
1867 *p++ = s[i + 1];
1868 i++;
1869 break;
1871 break;
1872 default:
1873 *p++ = s[i];
1874 break;
1877 len = p - dest;
1878 *p = '\0';
1879 return len;
1882 /* Returns a dynamically allocated copy of the current token in the
1883 * parser context. The function performs conversion of escapes if
1884 * the token is of type JIM_TT_ESC.
1886 * Note that after the conversion, tokens that are grouped with
1887 * braces in the source code, are always recognizable from the
1888 * identical string obtained in a different way from the type.
1890 * For example the string:
1892 * {*}$a
1894 * will return as first token "*", of type JIM_TT_STR
1896 * While the string:
1898 * *$a
1900 * will return as first token "*", of type JIM_TT_ESC
1902 static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc)
1904 const char *start, *end;
1905 char *token;
1906 int len;
1908 start = pc->tstart;
1909 end = pc->tend;
1910 if (start > end) {
1911 len = 0;
1912 token = Jim_Alloc(1);
1913 token[0] = '\0';
1915 else {
1916 len = (end - start) + 1;
1917 token = Jim_Alloc(len + 1);
1918 if (pc->tt != JIM_TT_ESC) {
1919 /* No escape conversion needed? Just copy it. */
1920 memcpy(token, start, len);
1921 token[len] = '\0';
1923 else {
1924 /* Else convert the escape chars. */
1925 len = JimEscape(token, start, len);
1929 return Jim_NewStringObjNoAlloc(interp, token, len);
1932 /* Parses the given string to determine if it represents a complete script.
1934 * This is useful for interactive shells implementation, for [info complete].
1936 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1937 * '{' on scripts incomplete missing one or more '}' to be balanced.
1938 * '[' on scripts incomplete missing one or more ']' to be balanced.
1939 * '"' on scripts incomplete missing a '"' char.
1941 * If the script is complete, 1 is returned, otherwise 0.
1943 int Jim_ScriptIsComplete(const char *s, int len, char *stateCharPtr)
1945 struct JimParserCtx parser;
1947 JimParserInit(&parser, s, len, 1);
1948 while (!parser.eof) {
1949 JimParseScript(&parser);
1951 if (stateCharPtr) {
1952 *stateCharPtr = parser.missing;
1954 return parser.missing == ' ';
1957 /* -----------------------------------------------------------------------------
1958 * Tcl Lists parsing
1959 * ---------------------------------------------------------------------------*/
1960 static int JimParseListSep(struct JimParserCtx *pc);
1961 static int JimParseListStr(struct JimParserCtx *pc);
1962 static int JimParseListQuote(struct JimParserCtx *pc);
1964 static int JimParseList(struct JimParserCtx *pc)
1966 switch (*pc->p) {
1967 case ' ':
1968 case '\n':
1969 case '\t':
1970 case '\r':
1971 return JimParseListSep(pc);
1973 case '"':
1974 return JimParseListQuote(pc);
1976 case '{':
1977 return JimParseBrace(pc);
1979 default:
1980 if (pc->len) {
1981 return JimParseListStr(pc);
1983 break;
1986 pc->tstart = pc->tend = pc->p;
1987 pc->tline = pc->linenr;
1988 pc->tt = JIM_TT_EOL;
1989 pc->eof = 1;
1990 return JIM_OK;
1993 static int JimParseListSep(struct JimParserCtx *pc)
1995 pc->tstart = pc->p;
1996 pc->tline = pc->linenr;
1997 while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == '\n') {
1998 if (*pc->p == '\n') {
1999 pc->linenr++;
2001 pc->p++;
2002 pc->len--;
2004 pc->tend = pc->p - 1;
2005 pc->tt = JIM_TT_SEP;
2006 return JIM_OK;
2009 static int JimParseListQuote(struct JimParserCtx *pc)
2011 pc->p++;
2012 pc->len--;
2014 pc->tstart = pc->p;
2015 pc->tline = pc->linenr;
2016 pc->tt = JIM_TT_STR;
2018 while (pc->len) {
2019 switch (*pc->p) {
2020 case '\\':
2021 pc->tt = JIM_TT_ESC;
2022 if (--pc->len == 0) {
2023 /* Trailing backslash */
2024 pc->tend = pc->p;
2025 return JIM_OK;
2027 pc->p++;
2028 break;
2029 case '\n':
2030 pc->linenr++;
2031 break;
2032 case '"':
2033 pc->tend = pc->p - 1;
2034 pc->p++;
2035 pc->len--;
2036 return JIM_OK;
2038 pc->p++;
2039 pc->len--;
2042 pc->tend = pc->p - 1;
2043 return JIM_OK;
2046 static int JimParseListStr(struct JimParserCtx *pc)
2048 pc->tstart = pc->p;
2049 pc->tline = pc->linenr;
2050 pc->tt = JIM_TT_STR;
2052 while (pc->len) {
2053 switch (*pc->p) {
2054 case '\\':
2055 if (--pc->len == 0) {
2056 /* Trailing backslash */
2057 pc->tend = pc->p;
2058 return JIM_OK;
2060 pc->tt = JIM_TT_ESC;
2061 pc->p++;
2062 break;
2063 case ' ':
2064 case '\t':
2065 case '\n':
2066 case '\r':
2067 pc->tend = pc->p - 1;
2068 return JIM_OK;
2070 pc->p++;
2071 pc->len--;
2073 pc->tend = pc->p - 1;
2074 return JIM_OK;
2077 /* -----------------------------------------------------------------------------
2078 * Jim_Obj related functions
2079 * ---------------------------------------------------------------------------*/
2081 /* Return a new initialized object. */
2082 Jim_Obj *Jim_NewObj(Jim_Interp *interp)
2084 Jim_Obj *objPtr;
2086 /* -- Check if there are objects in the free list -- */
2087 if (interp->freeList != NULL) {
2088 /* -- Unlink the object from the free list -- */
2089 objPtr = interp->freeList;
2090 interp->freeList = objPtr->nextObjPtr;
2092 else {
2093 /* -- No ready to use objects: allocate a new one -- */
2094 objPtr = Jim_Alloc(sizeof(*objPtr));
2097 /* Object is returned with refCount of 0. Every
2098 * kind of GC implemented should take care to don't try
2099 * to scan objects with refCount == 0. */
2100 objPtr->refCount = 0;
2101 /* All the other fields are left not initialized to save time.
2102 * The caller will probably want to set them to the right
2103 * value anyway. */
2105 /* -- Put the object into the live list -- */
2106 objPtr->prevObjPtr = NULL;
2107 objPtr->nextObjPtr = interp->liveList;
2108 if (interp->liveList)
2109 interp->liveList->prevObjPtr = objPtr;
2110 interp->liveList = objPtr;
2112 return objPtr;
2115 /* Free an object. Actually objects are never freed, but
2116 * just moved to the free objects list, where they will be
2117 * reused by Jim_NewObj(). */
2118 void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
2120 /* Check if the object was already freed, panic. */
2121 JimPanic((objPtr->refCount != 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr,
2122 objPtr->refCount, objPtr->typePtr ? objPtr->typePtr->name : "<none>"));
2124 /* Free the internal representation */
2125 Jim_FreeIntRep(interp, objPtr);
2126 /* Free the string representation */
2127 if (objPtr->bytes != NULL) {
2128 if (objPtr->bytes != JimEmptyStringRep)
2129 Jim_Free(objPtr->bytes);
2131 /* Unlink the object from the live objects list */
2132 if (objPtr->prevObjPtr)
2133 objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
2134 if (objPtr->nextObjPtr)
2135 objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
2136 if (interp->liveList == objPtr)
2137 interp->liveList = objPtr->nextObjPtr;
2138 /* Link the object into the free objects list */
2139 objPtr->prevObjPtr = NULL;
2140 objPtr->nextObjPtr = interp->freeList;
2141 if (interp->freeList)
2142 interp->freeList->prevObjPtr = objPtr;
2143 interp->freeList = objPtr;
2144 objPtr->refCount = -1;
2147 /* Invalidate the string representation of an object. */
2148 void Jim_InvalidateStringRep(Jim_Obj *objPtr)
2150 if (objPtr->bytes != NULL) {
2151 if (objPtr->bytes != JimEmptyStringRep)
2152 Jim_Free(objPtr->bytes);
2154 objPtr->bytes = NULL;
2157 #define Jim_SetStringRep(o, b, l) \
2158 do { (o)->bytes = b; (o)->length = l; } while (0)
2160 /* Set the initial string representation for an object.
2161 * Does not try to free an old one. */
2162 void Jim_InitStringRep(Jim_Obj *objPtr, const char *bytes, int length)
2164 if (length == 0) {
2165 objPtr->bytes = JimEmptyStringRep;
2166 objPtr->length = 0;
2168 else {
2169 objPtr->bytes = Jim_Alloc(length + 1);
2170 objPtr->length = length;
2171 memcpy(objPtr->bytes, bytes, length);
2172 objPtr->bytes[length] = '\0';
2176 /* Duplicate an object. The returned object has refcount = 0. */
2177 Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
2179 Jim_Obj *dupPtr;
2181 dupPtr = Jim_NewObj(interp);
2182 if (objPtr->bytes == NULL) {
2183 /* Object does not have a valid string representation. */
2184 dupPtr->bytes = NULL;
2186 else {
2187 Jim_InitStringRep(dupPtr, objPtr->bytes, objPtr->length);
2190 /* By default, the new object has the same type as the old object */
2191 dupPtr->typePtr = objPtr->typePtr;
2192 if (objPtr->typePtr != NULL) {
2193 if (objPtr->typePtr->dupIntRepProc == NULL) {
2194 dupPtr->internalRep = objPtr->internalRep;
2196 else {
2197 /* The dup proc may set a different type, e.g. NULL */
2198 objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
2201 return dupPtr;
2204 /* Return the string representation for objPtr. If the object
2205 * string representation is invalid, calls the method to create
2206 * a new one starting from the internal representation of the object. */
2207 const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
2209 if (objPtr->bytes == NULL) {
2210 /* Invalid string repr. Generate it. */
2211 JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
2212 objPtr->typePtr->updateStringProc(objPtr);
2214 if (lenPtr)
2215 *lenPtr = objPtr->length;
2216 return objPtr->bytes;
2219 /* Just returns the length of the object's string rep */
2220 int Jim_Length(Jim_Obj *objPtr)
2222 int len;
2224 Jim_GetString(objPtr, &len);
2225 return len;
2228 static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2229 static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2231 static const Jim_ObjType dictSubstObjType = {
2232 "dict-substitution",
2233 FreeDictSubstInternalRep,
2234 DupDictSubstInternalRep,
2235 NULL,
2236 JIM_TYPE_NONE,
2239 static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2241 Jim_DecrRefCount(interp, (Jim_Obj *)objPtr->internalRep.twoPtrValue.ptr2);
2244 static const Jim_ObjType interpolatedObjType = {
2245 "interpolated",
2246 FreeInterpolatedInternalRep,
2247 NULL,
2248 NULL,
2249 JIM_TYPE_NONE,
2252 /* -----------------------------------------------------------------------------
2253 * String Object
2254 * ---------------------------------------------------------------------------*/
2255 static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2256 static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
2258 static const Jim_ObjType stringObjType = {
2259 "string",
2260 NULL,
2261 DupStringInternalRep,
2262 NULL,
2263 JIM_TYPE_REFERENCES,
2266 static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2268 JIM_NOTUSED(interp);
2270 /* This is a bit subtle: the only caller of this function
2271 * should be Jim_DuplicateObj(), that will copy the
2272 * string representaion. After the copy, the duplicated
2273 * object will not have more room in teh buffer than
2274 * srcPtr->length bytes. So we just set it to length. */
2275 dupPtr->internalRep.strValue.maxLength = srcPtr->length;
2277 dupPtr->internalRep.strValue.charLength = srcPtr->internalRep.strValue.charLength;
2280 static int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
2282 /* Get a fresh string representation. */
2283 (void)Jim_String(objPtr);
2284 /* Free any other internal representation. */
2285 Jim_FreeIntRep(interp, objPtr);
2286 /* Set it as string, i.e. just set the maxLength field. */
2287 objPtr->typePtr = &stringObjType;
2288 objPtr->internalRep.strValue.maxLength = objPtr->length;
2289 /* Don't know the utf-8 length yet */
2290 objPtr->internalRep.strValue.charLength = -1;
2291 return JIM_OK;
2295 * Returns the length of the object string in chars, not bytes.
2297 * These may be different for a utf-8 string.
2299 int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr)
2301 #ifdef JIM_UTF8
2302 if (objPtr->typePtr != &stringObjType)
2303 SetStringFromAny(interp, objPtr);
2305 if (objPtr->internalRep.strValue.charLength < 0) {
2306 objPtr->internalRep.strValue.charLength = utf8_strlen(objPtr->bytes, objPtr->length);
2308 return objPtr->internalRep.strValue.charLength;
2309 #else
2310 return Jim_Length(objPtr);
2311 #endif
2314 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2315 Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
2317 Jim_Obj *objPtr = Jim_NewObj(interp);
2319 /* Need to find out how many bytes the string requires */
2320 if (len == -1)
2321 len = strlen(s);
2322 /* Alloc/Set the string rep. */
2323 if (len == 0) {
2324 objPtr->bytes = JimEmptyStringRep;
2325 objPtr->length = 0;
2327 else {
2328 objPtr->bytes = Jim_Alloc(len + 1);
2329 objPtr->length = len;
2330 memcpy(objPtr->bytes, s, len);
2331 objPtr->bytes[len] = '\0';
2334 /* No typePtr field for the vanilla string object. */
2335 objPtr->typePtr = NULL;
2336 return objPtr;
2339 /* charlen is in characters -- see also Jim_NewStringObj() */
2340 Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp, const char *s, int charlen)
2342 #ifdef JIM_UTF8
2343 /* Need to find out how many bytes the string requires */
2344 int bytelen = utf8_index(s, charlen);
2346 Jim_Obj *objPtr = Jim_NewStringObj(interp, s, bytelen);
2348 /* Remember the utf8 length, so set the type */
2349 objPtr->typePtr = &stringObjType;
2350 objPtr->internalRep.strValue.maxLength = bytelen;
2351 objPtr->internalRep.strValue.charLength = charlen;
2353 return objPtr;
2354 #else
2355 return Jim_NewStringObj(interp, s, charlen);
2356 #endif
2359 /* This version does not try to duplicate the 's' pointer, but
2360 * use it directly. */
2361 Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
2363 Jim_Obj *objPtr = Jim_NewObj(interp);
2365 if (len == -1)
2366 len = strlen(s);
2367 Jim_SetStringRep(objPtr, s, len);
2368 objPtr->typePtr = NULL;
2369 return objPtr;
2372 /* Low-level string append. Use it only against objects
2373 * of type "string". */
2374 static void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
2376 int needlen;
2378 if (len == -1)
2379 len = strlen(str);
2380 needlen = objPtr->length + len;
2381 if (objPtr->internalRep.strValue.maxLength < needlen ||
2382 objPtr->internalRep.strValue.maxLength == 0) {
2383 needlen *= 2;
2384 /* Inefficient to malloc() for less than 8 bytes */
2385 if (needlen < 7) {
2386 needlen = 7;
2388 if (objPtr->bytes == JimEmptyStringRep) {
2389 objPtr->bytes = Jim_Alloc(needlen + 1);
2391 else {
2392 objPtr->bytes = Jim_Realloc(objPtr->bytes, needlen + 1);
2394 objPtr->internalRep.strValue.maxLength = needlen;
2396 memcpy(objPtr->bytes + objPtr->length, str, len);
2397 objPtr->bytes[objPtr->length + len] = '\0';
2398 if (objPtr->internalRep.strValue.charLength >= 0) {
2399 /* Update the utf-8 char length */
2400 objPtr->internalRep.strValue.charLength += utf8_strlen(objPtr->bytes + objPtr->length, len);
2402 objPtr->length += len;
2405 /* Higher level API to append strings to objects. */
2406 void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str, int len)
2408 JimPanic((Jim_IsShared(objPtr), "Jim_AppendString called with shared object"));
2409 if (objPtr->typePtr != &stringObjType)
2410 SetStringFromAny(interp, objPtr);
2411 StringAppendString(objPtr, str, len);
2414 void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
2416 int len;
2417 const char *str;
2419 str = Jim_GetString(appendObjPtr, &len);
2420 Jim_AppendString(interp, objPtr, str, len);
2423 void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
2425 va_list ap;
2427 if (objPtr->typePtr != &stringObjType)
2428 SetStringFromAny(interp, objPtr);
2429 va_start(ap, objPtr);
2430 while (1) {
2431 char *s = va_arg(ap, char *);
2433 if (s == NULL)
2434 break;
2435 Jim_AppendString(interp, objPtr, s, -1);
2437 va_end(ap);
2440 int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr)
2442 const char *aStr, *bStr;
2443 int aLen, bLen;
2445 if (aObjPtr == bObjPtr)
2446 return 1;
2447 aStr = Jim_GetString(aObjPtr, &aLen);
2448 bStr = Jim_GetString(bObjPtr, &bLen);
2449 if (aLen != bLen)
2450 return 0;
2451 return JimStringCompare(aStr, aLen, bStr, bLen) == 0;
2454 int Jim_StringMatchObj(Jim_Interp *interp, Jim_Obj *patternObjPtr, Jim_Obj *objPtr, int nocase)
2456 return JimStringMatch(interp, patternObjPtr, Jim_String(objPtr), nocase);
2459 int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
2461 const char *s1, *s2;
2462 int l1, l2;
2464 s1 = Jim_GetString(firstObjPtr, &l1);
2465 s2 = Jim_GetString(secondObjPtr, &l2);
2467 if (nocase) {
2468 return JimStringCompareNoCase(s1, s2, -1);
2470 return JimStringCompare(s1, l1, s2, l2);
2473 /* Convert a range, as returned by Jim_GetRange(), into
2474 * an absolute index into an object of the specified length.
2475 * This function may return negative values, or values
2476 * bigger or equal to the length of the list if the index
2477 * is out of range. */
2478 static int JimRelToAbsIndex(int len, int idx)
2480 if (idx < 0)
2481 return len + idx;
2482 return idx;
2485 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2486 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2487 * for implementation of commands like [string range] and [lrange].
2489 * The resulting range is guaranteed to address valid elements of
2490 * the structure. */
2491 static void JimRelToAbsRange(int len, int first, int last,
2492 int *firstPtr, int *lastPtr, int *rangeLenPtr)
2494 int rangeLen;
2496 if (first > last) {
2497 rangeLen = 0;
2499 else {
2500 rangeLen = last - first + 1;
2501 if (rangeLen) {
2502 if (first < 0) {
2503 rangeLen += first;
2504 first = 0;
2506 if (last >= len) {
2507 rangeLen -= (last - (len - 1));
2508 last = len - 1;
2512 if (rangeLen < 0)
2513 rangeLen = 0;
2515 *firstPtr = first;
2516 *lastPtr = last;
2517 *rangeLenPtr = rangeLen;
2520 Jim_Obj *Jim_StringByteRangeObj(Jim_Interp *interp,
2521 Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
2523 int first, last;
2524 const char *str;
2525 int rangeLen;
2526 int bytelen;
2528 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
2529 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
2530 return NULL;
2531 str = Jim_GetString(strObjPtr, &bytelen);
2532 first = JimRelToAbsIndex(bytelen, first);
2533 last = JimRelToAbsIndex(bytelen, last);
2534 JimRelToAbsRange(bytelen, first, last, &first, &last, &rangeLen);
2535 if (first == 0 && rangeLen == bytelen) {
2536 return strObjPtr;
2538 return Jim_NewStringObj(interp, str + first, rangeLen);
2541 Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
2542 Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
2544 #ifdef JIM_UTF8
2545 int first, last;
2546 const char *str;
2547 int len, rangeLen;
2548 int bytelen;
2550 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
2551 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
2552 return NULL;
2553 str = Jim_GetString(strObjPtr, &bytelen);
2554 len = Jim_Utf8Length(interp, strObjPtr);
2555 first = JimRelToAbsIndex(len, first);
2556 last = JimRelToAbsIndex(len, last);
2557 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
2558 if (first == 0 && rangeLen == len) {
2559 return strObjPtr;
2561 if (len == bytelen) {
2562 /* ASCII optimisation */
2563 return Jim_NewStringObj(interp, str + first, rangeLen);
2565 return Jim_NewStringObjUtf8(interp, str + utf8_index(str, first), rangeLen);
2566 #else
2567 return Jim_StringByteRangeObj(interp, strObjPtr, firstObjPtr, lastObjPtr);
2568 #endif
2571 static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
2573 char *buf, *p;
2574 int len;
2575 const char *str;
2577 if (strObjPtr->typePtr != &stringObjType) {
2578 SetStringFromAny(interp, strObjPtr);
2581 str = Jim_GetString(strObjPtr, &len);
2583 buf = p = Jim_Alloc(len + 1);
2584 while (*str) {
2585 int c;
2586 str += utf8_tounicode(str, &c);
2587 p += utf8_fromunicode(p, utf8_lower(c));
2589 *p = 0;
2590 return Jim_NewStringObjNoAlloc(interp, buf, len);
2593 static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
2595 char *buf, *p;
2596 int len;
2597 const char *str;
2599 if (strObjPtr->typePtr != &stringObjType) {
2600 SetStringFromAny(interp, strObjPtr);
2603 str = Jim_GetString(strObjPtr, &len);
2605 buf = p = Jim_Alloc(len + 1);
2606 while (*str) {
2607 int c;
2608 str += utf8_tounicode(str, &c);
2609 p += utf8_fromunicode(p, utf8_upper(c));
2611 *p = 0;
2612 return Jim_NewStringObjNoAlloc(interp, buf, len);
2615 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2616 * for unicode character 'c'.
2617 * Returns the position if found or NULL if not
2619 static const char *utf8_memchr(const char *str, int len, int c)
2621 #ifdef JIM_UTF8
2622 while (len) {
2623 int sc;
2624 int n = utf8_tounicode(str, &sc);
2625 if (sc == c) {
2626 return str;
2628 str += n;
2629 len -= n;
2631 return NULL;
2632 #else
2633 return memchr(str, c, len);
2634 #endif
2638 * Searches for the first non-trim char in string (str, len)
2640 * If none is found, returns just past the last char.
2642 * Lengths are in bytes.
2644 static const char *JimFindTrimLeft(const char *str, int len, const char *trimchars, int trimlen)
2646 while (len) {
2647 int c;
2648 int n = utf8_tounicode(str, &c);
2650 if (utf8_memchr(trimchars, trimlen, c) == NULL) {
2651 /* Not a trim char, so stop */
2652 break;
2654 str += n;
2655 len -= n;
2657 return str;
2661 * Searches backwards for a non-trim char in string (str, len).
2663 * Returns a pointer to just after the non-trim char, or NULL if not found.
2665 * Lengths are in bytes.
2667 static const char *JimFindTrimRight(const char *str, int len, const char *trimchars, int trimlen)
2669 str += len;
2671 while (len) {
2672 int c;
2673 int n = utf8_prev_len(str, len);
2675 len -= n;
2676 str -= n;
2678 n = utf8_tounicode(str, &c);
2680 if (utf8_memchr(trimchars, trimlen, c) == NULL) {
2681 return str + n;
2685 return NULL;
2688 static const char default_trim_chars[] = " \t\n\r";
2689 /* sizeof() here includes the null byte */
2690 static int default_trim_chars_len = sizeof(default_trim_chars);
2692 static Jim_Obj *JimStringTrimLeft(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2694 int len;
2695 const char *str = Jim_GetString(strObjPtr, &len);
2696 const char *trimchars = default_trim_chars;
2697 int trimcharslen = default_trim_chars_len;
2698 const char *newstr;
2700 if (trimcharsObjPtr) {
2701 trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
2704 newstr = JimFindTrimLeft(str, len, trimchars, trimcharslen);
2705 if (newstr == str) {
2706 return strObjPtr;
2709 return Jim_NewStringObj(interp, newstr, len - (newstr - str));
2712 static Jim_Obj *JimStringTrimRight(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2714 int len;
2715 const char *trimchars = default_trim_chars;
2716 int trimcharslen = default_trim_chars_len;
2717 const char *nontrim;
2719 if (trimcharsObjPtr) {
2720 trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
2723 if (strObjPtr->typePtr != &stringObjType) {
2724 SetStringFromAny(interp, strObjPtr);
2726 len = Jim_Length(strObjPtr);
2727 nontrim = JimFindTrimRight(strObjPtr->bytes, len, trimchars, trimcharslen);
2729 if (nontrim == NULL) {
2730 /* All trim, so return a zero-length string */
2731 return Jim_NewEmptyStringObj(interp);
2733 if (nontrim == strObjPtr->bytes + len) {
2734 return strObjPtr;
2737 if (Jim_IsShared(strObjPtr)) {
2738 strObjPtr = Jim_NewStringObj(interp, strObjPtr->bytes, (nontrim - strObjPtr->bytes));
2740 else {
2741 /* Can modify this string in place */
2742 strObjPtr->bytes[nontrim - strObjPtr->bytes] = 0;
2743 strObjPtr->length = (nontrim - strObjPtr->bytes);
2746 return strObjPtr;
2749 static Jim_Obj *JimStringTrim(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
2751 /* First trim left. */
2752 Jim_Obj *objPtr = JimStringTrimLeft(interp, strObjPtr, trimcharsObjPtr);
2754 /* Now trim right */
2755 strObjPtr = JimStringTrimRight(interp, objPtr, trimcharsObjPtr);
2757 if (objPtr != strObjPtr) {
2758 /* Note that we don't want this object to be leaked */
2759 Jim_IncrRefCount(objPtr);
2760 Jim_DecrRefCount(interp, objPtr);
2763 return strObjPtr;
2767 static int JimStringIs(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *strClass, int strict)
2769 static const char * const strclassnames[] = {
2770 "integer", "alpha", "alnum", "ascii", "digit",
2771 "double", "lower", "upper", "space", "xdigit",
2772 "control", "print", "graph", "punct",
2773 NULL
2775 enum {
2776 STR_IS_INTEGER, STR_IS_ALPHA, STR_IS_ALNUM, STR_IS_ASCII, STR_IS_DIGIT,
2777 STR_IS_DOUBLE, STR_IS_LOWER, STR_IS_UPPER, STR_IS_SPACE, STR_IS_XDIGIT,
2778 STR_IS_CONTROL, STR_IS_PRINT, STR_IS_GRAPH, STR_IS_PUNCT
2780 int strclass;
2781 int len;
2782 int i;
2783 const char *str;
2784 int (*isclassfunc)(int c) = NULL;
2786 if (Jim_GetEnum(interp, strClass, strclassnames, &strclass, "class", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
2787 return JIM_ERR;
2790 str = Jim_GetString(strObjPtr, &len);
2791 if (len == 0) {
2792 Jim_SetResultInt(interp, !strict);
2793 return JIM_OK;
2796 switch (strclass) {
2797 case STR_IS_INTEGER:
2799 jim_wide w;
2800 Jim_SetResultInt(interp, JimGetWideNoErr(interp, strObjPtr, &w) == JIM_OK);
2801 return JIM_OK;
2804 case STR_IS_DOUBLE:
2806 double d;
2807 Jim_SetResultInt(interp, Jim_GetDouble(interp, strObjPtr, &d) == JIM_OK && errno != ERANGE);
2808 return JIM_OK;
2811 case STR_IS_ALPHA: isclassfunc = isalpha; break;
2812 case STR_IS_ALNUM: isclassfunc = isalnum; break;
2813 case STR_IS_ASCII: isclassfunc = isascii; break;
2814 case STR_IS_DIGIT: isclassfunc = isdigit; break;
2815 case STR_IS_LOWER: isclassfunc = islower; break;
2816 case STR_IS_UPPER: isclassfunc = isupper; break;
2817 case STR_IS_SPACE: isclassfunc = isspace; break;
2818 case STR_IS_XDIGIT: isclassfunc = isxdigit; break;
2819 case STR_IS_CONTROL: isclassfunc = iscntrl; break;
2820 case STR_IS_PRINT: isclassfunc = isprint; break;
2821 case STR_IS_GRAPH: isclassfunc = isgraph; break;
2822 case STR_IS_PUNCT: isclassfunc = ispunct; break;
2823 default:
2824 return JIM_ERR;
2827 for (i = 0; i < len; i++) {
2828 if (!isclassfunc(str[i])) {
2829 Jim_SetResultInt(interp, 0);
2830 return JIM_OK;
2833 Jim_SetResultInt(interp, 1);
2834 return JIM_OK;
2837 /* -----------------------------------------------------------------------------
2838 * Compared String Object
2839 * ---------------------------------------------------------------------------*/
2841 /* This is strange object that allows to compare a C literal string
2842 * with a Jim object in very short time if the same comparison is done
2843 * multiple times. For example every time the [if] command is executed,
2844 * Jim has to check if a given argument is "else". This comparions if
2845 * the code has no errors are true most of the times, so we can cache
2846 * inside the object the pointer of the string of the last matching
2847 * comparison. Because most C compilers perform literal sharing,
2848 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2849 * this works pretty well even if comparisons are at different places
2850 * inside the C code. */
2852 static const Jim_ObjType comparedStringObjType = {
2853 "compared-string",
2854 NULL,
2855 NULL,
2856 NULL,
2857 JIM_TYPE_REFERENCES,
2860 /* The only way this object is exposed to the API is via the following
2861 * function. Returns true if the string and the object string repr.
2862 * are the same, otherwise zero is returned.
2864 * Note: this isn't binary safe, but it hardly needs to be.*/
2865 int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr, const char *str)
2867 if (objPtr->typePtr == &comparedStringObjType && objPtr->internalRep.ptr == str)
2868 return 1;
2869 else {
2870 const char *objStr = Jim_String(objPtr);
2872 if (strcmp(str, objStr) != 0)
2873 return 0;
2874 if (objPtr->typePtr != &comparedStringObjType) {
2875 Jim_FreeIntRep(interp, objPtr);
2876 objPtr->typePtr = &comparedStringObjType;
2878 objPtr->internalRep.ptr = (char *)str; /*ATTENTION: const cast */
2879 return 1;
2883 static int qsortCompareStringPointers(const void *a, const void *b)
2885 char *const *sa = (char *const *)a;
2886 char *const *sb = (char *const *)b;
2888 return strcmp(*sa, *sb);
2892 /* -----------------------------------------------------------------------------
2893 * Source Object
2895 * This object is just a string from the language point of view, but
2896 * in the internal representation it contains the filename and line number
2897 * where this given token was read. This information is used by
2898 * Jim_EvalObj() if the object passed happens to be of type "source".
2900 * This allows to propagate the information about line numbers and file
2901 * names and give error messages with absolute line numbers.
2903 * Note that this object uses shared strings for filenames, and the
2904 * pointer to the filename together with the line number is taken into
2905 * the space for the "inline" internal representation of the Jim_Object,
2906 * so there is almost memory zero-overhead.
2908 * Also the object will be converted to something else if the given
2909 * token it represents in the source file is not something to be
2910 * evaluated (not a script), and will be specialized in some other way,
2911 * so the time overhead is also null.
2912 * ---------------------------------------------------------------------------*/
2914 static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2915 static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2917 static const Jim_ObjType sourceObjType = {
2918 "source",
2919 FreeSourceInternalRep,
2920 DupSourceInternalRep,
2921 NULL,
2922 JIM_TYPE_REFERENCES,
2925 void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
2927 Jim_DecrRefCount(interp, objPtr->internalRep.sourceValue.fileNameObj);
2930 void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
2932 dupPtr->internalRep = srcPtr->internalRep;
2933 Jim_IncrRefCount(dupPtr->internalRep.sourceValue.fileNameObj);
2936 static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
2937 Jim_Obj *fileNameObj, int lineNumber)
2939 JimPanic((Jim_IsShared(objPtr), "JimSetSourceInfo called with shared object"));
2940 JimPanic((objPtr->typePtr != NULL, "JimSetSourceInfo called with typePtr != NULL"));
2941 Jim_IncrRefCount(fileNameObj);
2942 objPtr->internalRep.sourceValue.fileNameObj = fileNameObj;
2943 objPtr->internalRep.sourceValue.lineNumber = lineNumber;
2944 objPtr->typePtr = &sourceObjType;
2947 /* -----------------------------------------------------------------------------
2948 * Script Object
2949 * ---------------------------------------------------------------------------*/
2951 static const Jim_ObjType scriptLineObjType = {
2952 "scriptline",
2953 NULL,
2954 NULL,
2955 NULL,
2959 static Jim_Obj *JimNewScriptLineObj(Jim_Interp *interp, int argc, int line)
2961 Jim_Obj *objPtr;
2963 #ifdef DEBUG_SHOW_SCRIPT
2964 char buf[100];
2965 snprintf(buf, sizeof(buf), "line=%d, argc=%d", line, argc);
2966 objPtr = Jim_NewStringObj(interp, buf, -1);
2967 #else
2968 objPtr = Jim_NewEmptyStringObj(interp);
2969 #endif
2970 objPtr->typePtr = &scriptLineObjType;
2971 objPtr->internalRep.scriptLineValue.argc = argc;
2972 objPtr->internalRep.scriptLineValue.line = line;
2974 return objPtr;
2977 #define JIM_CMDSTRUCT_EXPAND -1
2979 static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
2980 static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
2981 static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, struct JimParseResult *result);
2983 static const Jim_ObjType scriptObjType = {
2984 "script",
2985 FreeScriptInternalRep,
2986 DupScriptInternalRep,
2987 NULL,
2988 JIM_TYPE_REFERENCES,
2991 /* The ScriptToken structure represents every token into a scriptObj.
2992 * Every token contains an associated Jim_Obj that can be specialized
2993 * by commands operating on it. */
2994 typedef struct ScriptToken
2996 int type;
2997 Jim_Obj *objPtr;
2998 } ScriptToken;
3000 /* This is the script object internal representation. An array of
3001 * ScriptToken structures, including a pre-computed representation of the
3002 * command length and arguments.
3004 * For example the script:
3006 * puts hello
3007 * set $i $x$y [foo]BAR
3009 * will produce a ScriptObj with the following Tokens:
3011 * LIN 2
3012 * ESC puts
3013 * ESC hello
3014 * LIN 4
3015 * ESC set
3016 * VAR i
3017 * WRD 2
3018 * VAR x
3019 * VAR y
3020 * WRD 2
3021 * CMD foo
3022 * ESC BAR
3024 * "puts hello" has two args (LIN 2), composed of single tokens.
3025 * (Note that the WRD token is omitted for the common case of a single token.)
3027 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
3028 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
3030 * The precomputation of the command structure makes Jim_Eval() faster,
3031 * and simpler because there aren't dynamic lengths / allocations.
3033 * -- {expand}/{*} handling --
3035 * Expand is handled in a special way.
3037 * If a "word" begins with {*}, the word token count is -ve.
3039 * For example the command:
3041 * list {*}{a b}
3043 * Will produce the following cmdstruct array:
3045 * LIN 2
3046 * ESC list
3047 * WRD -1
3048 * STR a b
3050 * Note that the 'LIN' token also contains the source information for the
3051 * first word of the line for error reporting purposes
3053 * -- the substFlags field of the structure --
3055 * The scriptObj structure is used to represent both "script" objects
3056 * and "subst" objects. In the second case, the there are no LIN and WRD
3057 * tokens. Instead SEP and EOL tokens are added as-is.
3058 * In addition, the field 'substFlags' is used to represent the flags used to turn
3059 * the string into the internal representation used to perform the
3060 * substitution. If this flags are not what the application requires
3061 * the scriptObj is created again. For example the script:
3063 * subst -nocommands $string
3064 * subst -novariables $string
3066 * Will recreate the internal representation of the $string object
3067 * two times.
3069 typedef struct ScriptObj
3071 int len; /* Length as number of tokens. */
3072 ScriptToken *token; /* Tokens array. */
3073 int substFlags; /* flags used for the compilation of "subst" objects */
3074 int inUse; /* Used to share a ScriptObj. Currently
3075 only used by Jim_EvalObj() as protection against
3076 shimmering of the currently evaluated object. */
3077 Jim_Obj *fileNameObj;
3078 int line; /* Line number of the first line */
3079 } ScriptObj;
3081 void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
3083 int i;
3084 struct ScriptObj *script = (void *)objPtr->internalRep.ptr;
3086 script->inUse--;
3087 if (script->inUse != 0)
3088 return;
3089 for (i = 0; i < script->len; i++) {
3090 Jim_DecrRefCount(interp, script->token[i].objPtr);
3092 Jim_Free(script->token);
3093 Jim_DecrRefCount(interp, script->fileNameObj);
3094 Jim_Free(script);
3097 void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
3099 JIM_NOTUSED(interp);
3100 JIM_NOTUSED(srcPtr);
3102 /* Just returns an simple string. */
3103 dupPtr->typePtr = NULL;
3106 /* A simple parser token.
3107 * All the simple tokens for the script point into the same script string rep.
3109 typedef struct
3111 const char *token; /* Pointer to the start of the token */
3112 int len; /* Length of this token */
3113 int type; /* Token type */
3114 int line; /* Line number */
3115 } ParseToken;
3117 /* A list of parsed tokens representing a script.
3118 * Tokens are added to this list as the script is parsed.
3119 * It grows as needed.
3121 typedef struct
3123 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3124 ParseToken *list; /* Array of tokens */
3125 int size; /* Current size of the list */
3126 int count; /* Number of entries used */
3127 ParseToken static_list[20]; /* Small initial token space to avoid allocation */
3128 } ParseTokenList;
3130 static void ScriptTokenListInit(ParseTokenList *tokenlist)
3132 tokenlist->list = tokenlist->static_list;
3133 tokenlist->size = sizeof(tokenlist->static_list) / sizeof(ParseToken);
3134 tokenlist->count = 0;
3137 static void ScriptTokenListFree(ParseTokenList *tokenlist)
3139 if (tokenlist->list != tokenlist->static_list) {
3140 Jim_Free(tokenlist->list);
3145 * Adds the new token to the tokenlist.
3146 * The token has the given length, type and line number.
3147 * The token list is resized as necessary.
3149 static void ScriptAddToken(ParseTokenList *tokenlist, const char *token, int len, int type,
3150 int line)
3152 ParseToken *t;
3154 if (tokenlist->count == tokenlist->size) {
3155 /* Resize the list */
3156 tokenlist->size *= 2;
3157 if (tokenlist->list != tokenlist->static_list) {
3158 tokenlist->list =
3159 Jim_Realloc(tokenlist->list, tokenlist->size * sizeof(*tokenlist->list));
3161 else {
3162 /* The list needs to become allocated */
3163 tokenlist->list = Jim_Alloc(tokenlist->size * sizeof(*tokenlist->list));
3164 memcpy(tokenlist->list, tokenlist->static_list,
3165 tokenlist->count * sizeof(*tokenlist->list));
3168 t = &tokenlist->list[tokenlist->count++];
3169 t->token = token;
3170 t->len = len;
3171 t->type = type;
3172 t->line = line;
3175 /* Counts the number of adjoining non-separator.
3177 * Returns -ve if the first token is the expansion
3178 * operator (in which case the count doesn't include
3179 * that token).
3181 static int JimCountWordTokens(ParseToken *t)
3183 int expand = 1;
3184 int count = 0;
3186 /* Is the first word {*} or {expand}? */
3187 if (t->type == JIM_TT_STR && !TOKEN_IS_SEP(t[1].type)) {
3188 if ((t->len == 1 && *t->token == '*') || (t->len == 6 && strncmp(t->token, "expand", 6) == 0)) {
3189 /* Create an expand token */
3190 expand = -1;
3191 t++;
3195 /* Now count non-separator words */
3196 while (!TOKEN_IS_SEP(t->type)) {
3197 t++;
3198 count++;
3201 return count * expand;
3205 * Create a script/subst object from the given token.
3207 static Jim_Obj *JimMakeScriptObj(Jim_Interp *interp, const ParseToken *t)
3209 Jim_Obj *objPtr;
3211 if (t->type == JIM_TT_ESC && memchr(t->token, '\\', t->len) != NULL) {
3212 /* Convert the backlash escapes . */
3213 int len = t->len;
3214 char *str = Jim_Alloc(len + 1);
3215 len = JimEscape(str, t->token, len);
3216 objPtr = Jim_NewStringObjNoAlloc(interp, str, len);
3218 else {
3219 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3220 * with a single space. This is currently not done.
3222 objPtr = Jim_NewStringObj(interp, t->token, t->len);
3224 return objPtr;
3228 * Takes a tokenlist and creates the allocated list of script tokens
3229 * in script->token, of length script->len.
3231 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3232 * as required.
3234 * Also sets script->line to the line number of the first token
3236 static void ScriptObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
3237 ParseTokenList *tokenlist)
3239 int i;
3240 struct ScriptToken *token;
3241 /* Number of tokens so far for the current command */
3242 int lineargs = 0;
3243 /* This is the first token for the current command */
3244 ScriptToken *linefirst;
3245 int count;
3246 int linenr;
3248 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3249 printf("==== Tokens ====\n");
3250 for (i = 0; i < tokenlist->count; i++) {
3251 printf("[%2d]@%d %s '%.*s'\n", i, tokenlist->list[i].line, jim_tt_name(tokenlist->list[i].type),
3252 tokenlist->list[i].len, tokenlist->list[i].token);
3254 #endif
3256 /* May need up to one extra script token for each EOL in the worst case */
3257 count = tokenlist->count;
3258 for (i = 0; i < tokenlist->count; i++) {
3259 if (tokenlist->list[i].type == JIM_TT_EOL) {
3260 count++;
3263 linenr = script->line = tokenlist->list[0].line;
3265 token = script->token = Jim_Alloc(sizeof(ScriptToken) * count);
3267 /* This is the first token for the current command */
3268 linefirst = token++;
3270 for (i = 0; i < tokenlist->count; ) {
3271 /* Look ahead to find out how many tokens make up the next word */
3272 int wordtokens;
3274 /* Skip any leading separators */
3275 while (tokenlist->list[i].type == JIM_TT_SEP) {
3276 i++;
3279 wordtokens = JimCountWordTokens(tokenlist->list + i);
3281 if (wordtokens == 0) {
3282 /* None, so at end of line */
3283 if (lineargs) {
3284 linefirst->type = JIM_TT_LINE;
3285 linefirst->objPtr = JimNewScriptLineObj(interp, lineargs, linenr);
3286 Jim_IncrRefCount(linefirst->objPtr);
3288 /* Reset for new line */
3289 lineargs = 0;
3290 linefirst = token++;
3292 i++;
3293 continue;
3295 else if (wordtokens != 1) {
3296 /* More than 1, or {expand}, so insert a WORD token */
3297 token->type = JIM_TT_WORD;
3298 token->objPtr = Jim_NewIntObj(interp, wordtokens);
3299 Jim_IncrRefCount(token->objPtr);
3300 token++;
3301 if (wordtokens < 0) {
3302 /* Skip the expand token */
3303 i++;
3304 wordtokens = -wordtokens - 1;
3305 lineargs--;
3309 if (lineargs == 0) {
3310 /* First real token on the line, so record the line number */
3311 linenr = tokenlist->list[i].line;
3313 lineargs++;
3315 /* Add each non-separator word token to the line */
3316 while (wordtokens--) {
3317 const ParseToken *t = &tokenlist->list[i++];
3319 token->type = t->type;
3320 token->objPtr = JimMakeScriptObj(interp, t);
3321 Jim_IncrRefCount(token->objPtr);
3323 /* Every object is initially a string, but the
3324 * internal type may be specialized during execution of the
3325 * script. */
3326 JimSetSourceInfo(interp, token->objPtr, script->fileNameObj, t->line);
3327 token++;
3331 if (lineargs == 0) {
3332 token--;
3335 script->len = token - script->token;
3337 assert(script->len < count);
3339 #ifdef DEBUG_SHOW_SCRIPT
3340 printf("==== Script (%s) ====\n", Jim_String(script->fileNameObj));
3341 for (i = 0; i < script->len; i++) {
3342 const ScriptToken *t = &script->token[i];
3343 printf("[%2d] %s %s\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
3345 #endif
3350 * Similar to ScriptObjAddTokens(), but for subst objects.
3352 static void SubstObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
3353 ParseTokenList *tokenlist)
3355 int i;
3356 struct ScriptToken *token;
3358 token = script->token = Jim_Alloc(sizeof(ScriptToken) * tokenlist->count);
3360 for (i = 0; i < tokenlist->count; i++) {
3361 const ParseToken *t = &tokenlist->list[i];
3363 /* Create a token for 't' */
3364 token->type = t->type;
3365 token->objPtr = JimMakeScriptObj(interp, t);
3366 Jim_IncrRefCount(token->objPtr);
3367 token++;
3370 script->len = i;
3373 /* This method takes the string representation of an object
3374 * as a Tcl script, and generates the pre-parsed internal representation
3375 * of the script. */
3376 static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, struct JimParseResult *result)
3378 int scriptTextLen;
3379 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
3380 struct JimParserCtx parser;
3381 struct ScriptObj *script;
3382 ParseTokenList tokenlist;
3383 int line = 1;
3385 /* Try to get information about filename / line number */
3386 if (objPtr->typePtr == &sourceObjType) {
3387 line = objPtr->internalRep.sourceValue.lineNumber;
3390 /* Initially parse the script into tokens (in tokenlist) */
3391 ScriptTokenListInit(&tokenlist);
3393 JimParserInit(&parser, scriptText, scriptTextLen, line);
3394 while (!parser.eof) {
3395 JimParseScript(&parser);
3396 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
3397 parser.tline);
3399 if (result && parser.missing != ' ') {
3400 ScriptTokenListFree(&tokenlist);
3401 result->missing = parser.missing;
3402 result->line = parser.missingline;
3403 return JIM_ERR;
3406 /* Add a final EOF token */
3407 ScriptAddToken(&tokenlist, scriptText + scriptTextLen, 0, JIM_TT_EOF, 0);
3409 /* Create the "real" script tokens from the initial token list */
3410 script = Jim_Alloc(sizeof(*script));
3411 memset(script, 0, sizeof(*script));
3412 script->inUse = 1;
3413 script->line = line;
3414 if (objPtr->typePtr == &sourceObjType) {
3415 script->fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
3417 else {
3418 script->fileNameObj = interp->emptyObj;
3420 Jim_IncrRefCount(script->fileNameObj);
3422 ScriptObjAddTokens(interp, script, &tokenlist);
3424 /* No longer need the token list */
3425 ScriptTokenListFree(&tokenlist);
3427 /* Free the old internal rep and set the new one. */
3428 Jim_FreeIntRep(interp, objPtr);
3429 Jim_SetIntRepPtr(objPtr, script);
3430 objPtr->typePtr = &scriptObjType;
3432 return JIM_OK;
3435 ScriptObj *Jim_GetScript(Jim_Interp *interp, Jim_Obj *objPtr)
3437 struct ScriptObj *script = Jim_GetIntRepPtr(objPtr);
3439 if (objPtr->typePtr != &scriptObjType || script->substFlags) {
3440 SetScriptFromAny(interp, objPtr, NULL);
3442 return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
3445 /* -----------------------------------------------------------------------------
3446 * Commands
3447 * ---------------------------------------------------------------------------*/
3448 static void JimIncrCmdRefCount(Jim_Cmd *cmdPtr)
3450 cmdPtr->inUse++;
3453 static void JimDecrCmdRefCount(Jim_Interp *interp, Jim_Cmd *cmdPtr)
3455 if (--cmdPtr->inUse == 0) {
3456 if (cmdPtr->isproc) {
3457 Jim_DecrRefCount(interp, cmdPtr->u.proc.argListObjPtr);
3458 Jim_DecrRefCount(interp, cmdPtr->u.proc.bodyObjPtr);
3459 if (cmdPtr->u.proc.staticVars) {
3460 Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
3461 Jim_Free(cmdPtr->u.proc.staticVars);
3463 if (cmdPtr->u.proc.prevCmd) {
3464 /* Delete any pushed command too */
3465 JimDecrCmdRefCount(interp, cmdPtr->u.proc.prevCmd);
3468 else {
3469 /* native (C) */
3470 if (cmdPtr->u.native.delProc) {
3471 cmdPtr->u.native.delProc(interp, cmdPtr->u.native.privData);
3474 Jim_Free(cmdPtr);
3478 /* Commands HashTable Type.
3480 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3481 static void JimCommandsHT_ValDestructor(void *interp, void *val)
3483 JimDecrCmdRefCount(interp, val);
3486 static const Jim_HashTableType JimCommandsHashTableType = {
3487 JimStringCopyHTHashFunction, /* hash function */
3488 JimStringCopyHTKeyDup, /* key dup */
3489 NULL, /* val dup */
3490 JimStringCopyHTKeyCompare, /* key compare */
3491 JimStringCopyHTKeyDestructor, /* key destructor */
3492 JimCommandsHT_ValDestructor /* val destructor */
3495 /* ------------------------- Commands related functions --------------------- */
3497 int Jim_CreateCommand(Jim_Interp *interp, const char *cmdName,
3498 Jim_CmdProc cmdProc, void *privData, Jim_DelCmdProc delProc)
3500 Jim_Cmd *cmdPtr;
3502 if (Jim_DeleteHashEntry(&interp->commands, cmdName) != JIM_ERR) {
3503 /* Command existed so incr proc epoch */
3504 Jim_InterpIncrProcEpoch(interp);
3507 cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
3509 /* Store the new details for this proc */
3510 memset(cmdPtr, 0, sizeof(*cmdPtr));
3511 cmdPtr->inUse = 1;
3512 cmdPtr->u.native.delProc = delProc;
3513 cmdPtr->u.native.cmdProc = cmdProc;
3514 cmdPtr->u.native.privData = privData;
3516 Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);
3518 /* There is no need to increment the 'proc epoch' because
3519 * creation of a new procedure can never affect existing
3520 * cached commands. We don't do negative caching. */
3521 return JIM_OK;
3524 static int JimCreateProcedure(Jim_Interp *interp, Jim_Obj *cmdName,
3525 Jim_Obj *argListObjPtr, Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr)
3527 Jim_Cmd *cmdPtr;
3528 Jim_HashEntry *he;
3529 int argListLen;
3530 int i;
3532 if (JimValidName(interp, "procedure", cmdName) != JIM_OK) {
3533 return JIM_ERR;
3536 argListLen = Jim_ListLength(interp, argListObjPtr);
3538 /* Allocate space for both the command pointer and the arg list */
3539 cmdPtr = Jim_Alloc(sizeof(*cmdPtr) + sizeof(struct Jim_ProcArg) * argListLen);
3540 memset(cmdPtr, 0, sizeof(*cmdPtr));
3541 cmdPtr->inUse = 1;
3542 cmdPtr->isproc = 1;
3543 cmdPtr->u.proc.argListObjPtr = argListObjPtr;
3544 cmdPtr->u.proc.argListLen = argListLen;
3545 cmdPtr->u.proc.bodyObjPtr = bodyObjPtr;
3546 cmdPtr->u.proc.argsPos = -1;
3547 cmdPtr->u.proc.arglist = (struct Jim_ProcArg *)(cmdPtr + 1);
3548 Jim_IncrRefCount(argListObjPtr);
3549 Jim_IncrRefCount(bodyObjPtr);
3551 /* Create the statics hash table. */
3552 if (staticsListObjPtr) {
3553 int len, i;
3555 len = Jim_ListLength(interp, staticsListObjPtr);
3556 if (len != 0) {
3557 cmdPtr->u.proc.staticVars = Jim_Alloc(sizeof(Jim_HashTable));
3558 Jim_InitHashTable(cmdPtr->u.proc.staticVars, &JimVariablesHashTableType, interp);
3559 for (i = 0; i < len; i++) {
3560 Jim_Obj *objPtr = 0, *initObjPtr = 0, *nameObjPtr = 0;
3561 Jim_Var *varPtr;
3562 int subLen;
3564 Jim_ListIndex(interp, staticsListObjPtr, i, &objPtr, JIM_NONE);
3565 /* Check if it's composed of two elements. */
3566 subLen = Jim_ListLength(interp, objPtr);
3567 if (subLen == 1 || subLen == 2) {
3568 /* Try to get the variable value from the current
3569 * environment. */
3570 Jim_ListIndex(interp, objPtr, 0, &nameObjPtr, JIM_NONE);
3571 if (subLen == 1) {
3572 initObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_NONE);
3573 if (initObjPtr == NULL) {
3574 Jim_SetResultFormatted(interp,
3575 "variable for initialization of static \"%#s\" not found in the local context",
3576 nameObjPtr);
3577 goto err;
3580 else {
3581 Jim_ListIndex(interp, objPtr, 1, &initObjPtr, JIM_NONE);
3583 if (JimValidName(interp, "static variable", nameObjPtr) != JIM_OK) {
3584 goto err;
3587 varPtr = Jim_Alloc(sizeof(*varPtr));
3588 varPtr->objPtr = initObjPtr;
3589 Jim_IncrRefCount(initObjPtr);
3590 varPtr->linkFramePtr = NULL;
3591 if (Jim_AddHashEntry(cmdPtr->u.proc.staticVars,
3592 Jim_String(nameObjPtr), varPtr) != JIM_OK) {
3593 Jim_SetResultFormatted(interp,
3594 "static variable name \"%#s\" duplicated in statics list", nameObjPtr);
3595 Jim_DecrRefCount(interp, initObjPtr);
3596 Jim_Free(varPtr);
3597 goto err;
3600 else {
3601 Jim_SetResultFormatted(interp, "too many fields in static specifier \"%#s\"",
3602 objPtr);
3603 goto err;
3609 /* Parse the args out into arglist, validating as we go */
3610 /* Examine the argument list for default parameters and 'args' */
3611 for (i = 0; i < argListLen; i++) {
3612 Jim_Obj *argPtr;
3613 Jim_Obj *nameObjPtr;
3614 Jim_Obj *defaultObjPtr;
3615 int len;
3616 int n = 1;
3618 /* Examine a parameter */
3619 Jim_ListIndex(interp, argListObjPtr, i, &argPtr, JIM_NONE);
3620 len = Jim_ListLength(interp, argPtr);
3621 if (len == 0) {
3622 Jim_SetResultString(interp, "procedure has argument with no name", -1);
3623 goto err;
3625 if (len > 2) {
3626 Jim_SetResultString(interp, "procedure has argument with too many fields", -1);
3627 goto err;
3630 if (len == 2) {
3631 /* Optional parameter */
3632 Jim_ListIndex(interp, argPtr, 0, &nameObjPtr, JIM_NONE);
3633 Jim_ListIndex(interp, argPtr, 1, &defaultObjPtr, JIM_NONE);
3635 else {
3636 /* Required parameter */
3637 nameObjPtr = argPtr;
3638 defaultObjPtr = NULL;
3642 if (Jim_CompareStringImmediate(interp, nameObjPtr, "args")) {
3643 if (cmdPtr->u.proc.argsPos >= 0) {
3644 Jim_SetResultString(interp, "procedure has 'args' specified more than once", -1);
3645 goto err;
3647 cmdPtr->u.proc.argsPos = i;
3649 else {
3650 if (len == 2) {
3651 cmdPtr->u.proc.optArity += n;
3653 else {
3654 cmdPtr->u.proc.reqArity += n;
3658 cmdPtr->u.proc.arglist[i].nameObjPtr = nameObjPtr;
3659 cmdPtr->u.proc.arglist[i].defaultObjPtr = defaultObjPtr;
3662 /* Add the new command */
3664 /* It may already exist, so we try to delete the old one.
3665 * Note that reference count means that it won't be deleted yet if
3666 * it exists in the call stack.
3668 * BUT, if 'local' is in force, instead of deleting the existing
3669 * proc, we stash a reference to the old proc here.
3671 he = Jim_FindHashEntry(&interp->commands, Jim_String(cmdName));
3672 if (he) {
3673 /* There was an old procedure with the same name, this requires
3674 * a 'proc epoch' update. */
3676 /* If a procedure with the same name didn't existed there is no need
3677 * to increment the 'proc epoch' because creation of a new procedure
3678 * can never affect existing cached commands. We don't do
3679 * negative caching. */
3680 Jim_InterpIncrProcEpoch(interp);
3683 if (he && interp->local) {
3684 /* Just push this proc over the top of the previous one */
3685 cmdPtr->u.proc.prevCmd = he->u.val;
3686 he->u.val = cmdPtr;
3688 else {
3689 if (he) {
3690 /* Replace the existing proc */
3691 Jim_DeleteHashEntry(&interp->commands, Jim_String(cmdName));
3694 Jim_AddHashEntry(&interp->commands, Jim_String(cmdName), cmdPtr);
3697 /* Unlike Tcl, set the name of the proc as the result */
3698 Jim_SetResult(interp, cmdName);
3699 return JIM_OK;
3701 err:
3702 if (cmdPtr->u.proc.staticVars) {
3703 Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
3705 Jim_Free(cmdPtr->u.proc.staticVars);
3706 Jim_DecrRefCount(interp, argListObjPtr);
3707 Jim_DecrRefCount(interp, bodyObjPtr);
3708 Jim_Free(cmdPtr);
3709 return JIM_ERR;
3712 int Jim_DeleteCommand(Jim_Interp *interp, const char *cmdName)
3714 if (Jim_DeleteHashEntry(&interp->commands, cmdName) == JIM_ERR)
3715 return JIM_ERR;
3716 Jim_InterpIncrProcEpoch(interp);
3717 return JIM_OK;
3720 int Jim_RenameCommand(Jim_Interp *interp, const char *oldName, const char *newName)
3722 Jim_HashEntry *he;
3724 /* Does it exist? */
3725 he = Jim_FindHashEntry(&interp->commands, oldName);
3726 if (he == NULL) {
3727 Jim_SetResultFormatted(interp, "can't %s \"%s\": command doesn't exist",
3728 newName[0] ? "rename" : "delete", oldName);
3729 return JIM_ERR;
3732 if (newName[0] == '\0') /* Delete! */
3733 return Jim_DeleteCommand(interp, oldName);
3735 /* rename */
3736 if (Jim_FindHashEntry(&interp->commands, newName)) {
3737 Jim_SetResultFormatted(interp, "can't rename to \"%s\": command already exists", newName);
3738 return JIM_ERR;
3741 /* Add the new name first */
3742 JimIncrCmdRefCount(he->u.val);
3743 Jim_AddHashEntry(&interp->commands, newName, he->u.val);
3745 /* Now remove the old name */
3746 Jim_DeleteHashEntry(&interp->commands, oldName);
3748 /* Increment the epoch */
3749 Jim_InterpIncrProcEpoch(interp);
3750 return JIM_OK;
3753 /* -----------------------------------------------------------------------------
3754 * Command object
3755 * ---------------------------------------------------------------------------*/
3757 static int SetCommandFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3759 static const Jim_ObjType commandObjType = {
3760 "command",
3761 NULL,
3762 NULL,
3763 NULL,
3764 JIM_TYPE_REFERENCES,
3767 int SetCommandFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
3769 Jim_HashEntry *he;
3770 const char *cmdName;
3772 /* Get the string representation */
3773 cmdName = Jim_String(objPtr);
3774 /* Lookup this name into the commands hash table */
3775 he = Jim_FindHashEntry(&interp->commands, cmdName);
3776 if (he == NULL)
3777 return JIM_ERR;
3779 /* Free the old internal repr and set the new one. */
3780 Jim_FreeIntRep(interp, objPtr);
3781 objPtr->typePtr = &commandObjType;
3782 objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
3783 objPtr->internalRep.cmdValue.cmdPtr = (void *)he->u.val;
3784 return JIM_OK;
3787 /* This function returns the command structure for the command name
3788 * stored in objPtr. It tries to specialize the objPtr to contain
3789 * a cached info instead to perform the lookup into the hash table
3790 * every time. The information cached may not be uptodate, in such
3791 * a case the lookup is performed and the cache updated.
3793 * Respects the 'upcall' setting
3795 Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
3797 Jim_Cmd *cmd;
3799 if ((objPtr->typePtr != &commandObjType ||
3800 objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch) &&
3801 SetCommandFromAny(interp, objPtr) == JIM_ERR) {
3802 if (flags & JIM_ERRMSG) {
3803 Jim_SetResultFormatted(interp, "invalid command name \"%#s\"", objPtr);
3805 return NULL;
3807 cmd = objPtr->internalRep.cmdValue.cmdPtr;
3808 while (cmd->isproc && cmd->u.proc.upcall) {
3809 cmd = cmd->u.proc.prevCmd;
3811 return cmd;
3814 /* -----------------------------------------------------------------------------
3815 * Variables
3816 * ---------------------------------------------------------------------------*/
3818 /* Variables HashTable Type.
3820 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3821 static void JimVariablesHTValDestructor(void *interp, void *val)
3823 Jim_Var *varPtr = (void *)val;
3825 Jim_DecrRefCount(interp, varPtr->objPtr);
3826 Jim_Free(val);
3829 static const Jim_HashTableType JimVariablesHashTableType = {
3830 JimStringCopyHTHashFunction, /* hash function */
3831 JimStringCopyHTKeyDup, /* key dup */
3832 NULL, /* val dup */
3833 JimStringCopyHTKeyCompare, /* key compare */
3834 JimStringCopyHTKeyDestructor, /* key destructor */
3835 JimVariablesHTValDestructor /* val destructor */
3838 /* -----------------------------------------------------------------------------
3839 * Variable object
3840 * ---------------------------------------------------------------------------*/
3842 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3844 static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
3846 static const Jim_ObjType variableObjType = {
3847 "variable",
3848 NULL,
3849 NULL,
3850 NULL,
3851 JIM_TYPE_REFERENCES,
3854 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3855 * is in the form "varname(key)". */
3856 static int JimNameIsDictSugar(const char *str, int len)
3858 if (len && str[len - 1] == ')' && strchr(str, '(') != NULL)
3859 return 1;
3860 return 0;
3864 * Check that the name does not contain embedded nulls.
3866 * Variable and procedure names are maniplated as null terminated strings, so
3867 * don't allow names with embedded nulls.
3869 static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr)
3871 /* Variable names and proc names can't contain embedded nulls */
3872 if (nameObjPtr->typePtr != &variableObjType) {
3873 int len;
3874 const char *str = Jim_GetString(nameObjPtr, &len);
3875 if (memchr(str, '\0', len)) {
3876 Jim_SetResultFormatted(interp, "%s name contains embedded null", type);
3877 return JIM_ERR;
3880 return JIM_OK;
3883 /* This method should be called only by the variable API.
3884 * It returns JIM_OK on success (variable already exists),
3885 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3886 * a variable name, but syntax glue for [dict] i.e. the last
3887 * character is ')' */
3888 static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
3890 Jim_HashEntry *he;
3891 const char *varName;
3892 int len;
3893 Jim_CallFrame *framePtr = interp->framePtr;
3895 /* Check if the object is already an uptodate variable */
3896 if (objPtr->typePtr == &variableObjType &&
3897 objPtr->internalRep.varValue.callFrameId == framePtr->id) {
3898 return JIM_OK; /* nothing to do */
3901 if (objPtr->typePtr == &dictSubstObjType) {
3902 return JIM_DICT_SUGAR;
3905 if (JimValidName(interp, "variable", objPtr) != JIM_OK) {
3906 return JIM_ERR;
3909 /* Get the string representation */
3910 varName = Jim_GetString(objPtr, &len);
3912 /* Make sure it's not syntax glue to get/set dict. */
3913 if (JimNameIsDictSugar(varName, len)) {
3914 return JIM_DICT_SUGAR;
3917 if (varName[0] == ':' && varName[1] == ':') {
3918 framePtr = interp->topFramePtr;
3919 he = Jim_FindHashEntry(&framePtr->vars, varName + 2);
3920 if (he == NULL) {
3921 return JIM_ERR;
3924 else {
3925 /* Lookup this name into the variables hash table */
3926 he = Jim_FindHashEntry(&framePtr->vars, varName);
3927 if (he == NULL) {
3928 /* Try with static vars. */
3929 if (framePtr->staticVars == NULL)
3930 return JIM_ERR;
3931 if (!(he = Jim_FindHashEntry(framePtr->staticVars, varName)))
3932 return JIM_ERR;
3935 /* Free the old internal repr and set the new one. */
3936 Jim_FreeIntRep(interp, objPtr);
3937 objPtr->typePtr = &variableObjType;
3938 objPtr->internalRep.varValue.callFrameId = framePtr->id;
3939 objPtr->internalRep.varValue.varPtr = (void *)he->u.val;
3940 return JIM_OK;
3943 /* -------------------- Variables related functions ------------------------- */
3944 static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr, Jim_Obj *valObjPtr);
3945 static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr, int flags);
3947 /* For now that's dummy. Variables lookup should be optimized
3948 * in many ways, with caching of lookups, and possibly with
3949 * a table of pre-allocated vars in every CallFrame for local vars.
3950 * All the caching should also have an 'epoch' mechanism similar
3951 * to the one used by Tcl for procedures lookup caching. */
3953 int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
3955 const char *name;
3956 Jim_Var *var;
3957 int err;
3959 if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {
3960 Jim_CallFrame *framePtr = interp->framePtr;
3962 /* Check for [dict] syntax sugar. */
3963 if (err == JIM_DICT_SUGAR)
3964 return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
3966 if (JimValidName(interp, "variable", nameObjPtr) != JIM_OK) {
3967 return JIM_ERR;
3970 /* New variable to create */
3971 name = Jim_String(nameObjPtr);
3973 var = Jim_Alloc(sizeof(*var));
3974 var->objPtr = valObjPtr;
3975 Jim_IncrRefCount(valObjPtr);
3976 var->linkFramePtr = NULL;
3977 /* Insert the new variable */
3978 if (name[0] == ':' && name[1] == ':') {
3979 /* Into the top level frame */
3980 framePtr = interp->topFramePtr;
3981 Jim_AddHashEntry(&framePtr->vars, name + 2, var);
3983 else {
3984 Jim_AddHashEntry(&framePtr->vars, name, var);
3986 /* Make the object int rep a variable */
3987 Jim_FreeIntRep(interp, nameObjPtr);
3988 nameObjPtr->typePtr = &variableObjType;
3989 nameObjPtr->internalRep.varValue.callFrameId = framePtr->id;
3990 nameObjPtr->internalRep.varValue.varPtr = var;
3992 else {
3993 var = nameObjPtr->internalRep.varValue.varPtr;
3994 if (var->linkFramePtr == NULL) {
3995 Jim_IncrRefCount(valObjPtr);
3996 Jim_DecrRefCount(interp, var->objPtr);
3997 var->objPtr = valObjPtr;
3999 else { /* Else handle the link */
4000 Jim_CallFrame *savedCallFrame;
4002 savedCallFrame = interp->framePtr;
4003 interp->framePtr = var->linkFramePtr;
4004 err = Jim_SetVariable(interp, var->objPtr, valObjPtr);
4005 interp->framePtr = savedCallFrame;
4006 if (err != JIM_OK)
4007 return err;
4010 return JIM_OK;
4013 int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
4015 Jim_Obj *nameObjPtr;
4016 int result;
4018 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4019 Jim_IncrRefCount(nameObjPtr);
4020 result = Jim_SetVariable(interp, nameObjPtr, objPtr);
4021 Jim_DecrRefCount(interp, nameObjPtr);
4022 return result;
4025 int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
4027 Jim_CallFrame *savedFramePtr;
4028 int result;
4030 savedFramePtr = interp->framePtr;
4031 interp->framePtr = interp->topFramePtr;
4032 result = Jim_SetVariableStr(interp, name, objPtr);
4033 interp->framePtr = savedFramePtr;
4034 return result;
4037 int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
4039 Jim_Obj *nameObjPtr, *valObjPtr;
4040 int result;
4042 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4043 valObjPtr = Jim_NewStringObj(interp, val, -1);
4044 Jim_IncrRefCount(nameObjPtr);
4045 Jim_IncrRefCount(valObjPtr);
4046 result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
4047 Jim_DecrRefCount(interp, nameObjPtr);
4048 Jim_DecrRefCount(interp, valObjPtr);
4049 return result;
4052 int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
4053 Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
4055 const char *varName;
4056 int len;
4058 varName = Jim_GetString(nameObjPtr, &len);
4060 if (varName[0] == ':' && varName[1] == ':') {
4061 /* Linking a global var does nothing */
4062 return JIM_OK;
4065 if (JimNameIsDictSugar(varName, len)) {
4066 Jim_SetResultString(interp, "Dict key syntax invalid as link source", -1);
4067 return JIM_ERR;
4070 /* Check for an existing variable or link */
4071 if (SetVariableFromAny(interp, nameObjPtr) == JIM_OK) {
4072 Jim_Var *varPtr = nameObjPtr->internalRep.varValue.varPtr;
4074 if (varPtr->linkFramePtr == NULL) {
4075 Jim_SetResultFormatted(interp, "variable \"%#s\" already exists", nameObjPtr);
4076 return JIM_ERR;
4079 /* It exists, but is a link, so delete the link */
4080 varPtr->linkFramePtr = NULL;
4083 /* Check for cycles. */
4084 if (interp->framePtr == targetCallFrame) {
4085 Jim_Obj *objPtr = targetNameObjPtr;
4086 Jim_Var *varPtr;
4088 /* Cycles are only possible with 'uplevel 0' */
4089 while (1) {
4090 if (Jim_StringEqObj(objPtr, nameObjPtr)) {
4091 Jim_SetResultString(interp, "can't upvar from variable to itself", -1);
4092 return JIM_ERR;
4094 if (SetVariableFromAny(interp, objPtr) != JIM_OK)
4095 break;
4096 varPtr = objPtr->internalRep.varValue.varPtr;
4097 if (varPtr->linkFramePtr != targetCallFrame)
4098 break;
4099 objPtr = varPtr->objPtr;
4103 /* Perform the binding */
4104 Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
4105 /* We are now sure 'nameObjPtr' type is variableObjType */
4106 nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;
4107 return JIM_OK;
4110 /* Return the Jim_Obj pointer associated with a variable name,
4111 * or NULL if the variable was not found in the current context.
4112 * The same optimization discussed in the comment to the
4113 * 'SetVariable' function should apply here.
4115 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4116 * in a dictionary which is shared, the array variable value is duplicated first.
4117 * This allows the array element to be updated (e.g. append, lappend) without
4118 * affecting other references to the dictionary.
4120 Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4122 switch (SetVariableFromAny(interp, nameObjPtr)) {
4123 case JIM_OK:{
4124 Jim_Var *varPtr = nameObjPtr->internalRep.varValue.varPtr;
4126 if (varPtr->linkFramePtr == NULL) {
4127 return varPtr->objPtr;
4129 else {
4130 Jim_Obj *objPtr;
4132 /* The variable is a link? Resolve it. */
4133 Jim_CallFrame *savedCallFrame = interp->framePtr;
4135 interp->framePtr = varPtr->linkFramePtr;
4136 objPtr = Jim_GetVariable(interp, varPtr->objPtr, flags);
4137 interp->framePtr = savedCallFrame;
4138 if (objPtr) {
4139 return objPtr;
4141 /* Error, so fall through to the error message */
4144 break;
4146 case JIM_DICT_SUGAR:
4147 /* [dict] syntax sugar. */
4148 return JimDictSugarGet(interp, nameObjPtr, flags);
4150 if (flags & JIM_ERRMSG) {
4151 Jim_SetResultFormatted(interp, "can't read \"%#s\": no such variable", nameObjPtr);
4153 return NULL;
4156 Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4158 Jim_CallFrame *savedFramePtr;
4159 Jim_Obj *objPtr;
4161 savedFramePtr = interp->framePtr;
4162 interp->framePtr = interp->topFramePtr;
4163 objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
4164 interp->framePtr = savedFramePtr;
4166 return objPtr;
4169 Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
4171 Jim_Obj *nameObjPtr, *varObjPtr;
4173 nameObjPtr = Jim_NewStringObj(interp, name, -1);
4174 Jim_IncrRefCount(nameObjPtr);
4175 varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
4176 Jim_DecrRefCount(interp, nameObjPtr);
4177 return varObjPtr;
4180 Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name, int flags)
4182 Jim_CallFrame *savedFramePtr;
4183 Jim_Obj *objPtr;
4185 savedFramePtr = interp->framePtr;
4186 interp->framePtr = interp->topFramePtr;
4187 objPtr = Jim_GetVariableStr(interp, name, flags);
4188 interp->framePtr = savedFramePtr;
4190 return objPtr;
4193 /* Unset a variable.
4194 * Note: On success unset invalidates all the variable objects created
4195 * in the current call frame incrementing. */
4196 int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
4198 const char *name;
4199 Jim_Var *varPtr;
4200 int retval;
4202 retval = SetVariableFromAny(interp, nameObjPtr);
4203 if (retval == JIM_DICT_SUGAR) {
4204 /* [dict] syntax sugar. */
4205 return JimDictSugarSet(interp, nameObjPtr, NULL);
4207 else if (retval == JIM_OK) {
4208 varPtr = nameObjPtr->internalRep.varValue.varPtr;
4210 /* If it's a link call UnsetVariable recursively */
4211 if (varPtr->linkFramePtr) {
4212 Jim_CallFrame *savedCallFrame;
4214 savedCallFrame = interp->framePtr;
4215 interp->framePtr = varPtr->linkFramePtr;
4216 retval = Jim_UnsetVariable(interp, varPtr->objPtr, JIM_NONE);
4217 interp->framePtr = savedCallFrame;
4219 else {
4220 Jim_CallFrame *framePtr = interp->framePtr;
4222 name = Jim_String(nameObjPtr);
4223 if (name[0] == ':' && name[1] == ':') {
4224 framePtr = interp->topFramePtr;
4225 name += 2;
4227 retval = Jim_DeleteHashEntry(&framePtr->vars, name);
4228 if (retval == JIM_OK) {
4229 /* Change the callframe id, invalidating var lookup caching */
4230 JimChangeCallFrameId(interp, framePtr);
4234 if (retval != JIM_OK && (flags & JIM_ERRMSG)) {
4235 Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such variable", nameObjPtr);
4237 return retval;
4240 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4242 /* Given a variable name for [dict] operation syntax sugar,
4243 * this function returns two objects, the first with the name
4244 * of the variable to set, and the second with the rispective key.
4245 * For example "foo(bar)" will return objects with string repr. of
4246 * "foo" and "bar".
4248 * The returned objects have refcount = 1. The function can't fail. */
4249 static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
4250 Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
4252 const char *str, *p;
4253 int len, keyLen;
4254 Jim_Obj *varObjPtr, *keyObjPtr;
4256 str = Jim_GetString(objPtr, &len);
4258 p = strchr(str, '(');
4259 JimPanic((p == NULL, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str));
4261 varObjPtr = Jim_NewStringObj(interp, str, p - str);
4263 p++;
4264 keyLen = (str + len) - p;
4265 if (str[len - 1] == ')') {
4266 keyLen--;
4269 /* Create the objects with the variable name and key. */
4270 keyObjPtr = Jim_NewStringObj(interp, p, keyLen);
4272 Jim_IncrRefCount(varObjPtr);
4273 Jim_IncrRefCount(keyObjPtr);
4274 *varPtrPtr = varObjPtr;
4275 *keyPtrPtr = keyObjPtr;
4278 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4279 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4280 static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *valObjPtr)
4282 int err;
4284 SetDictSubstFromAny(interp, objPtr);
4286 err = Jim_SetDictKeysVector(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
4287 &objPtr->internalRep.dictSubstValue.indexObjPtr, 1, valObjPtr, JIM_ERRMSG);
4289 if (err == JIM_OK) {
4290 /* Don't keep an extra ref to the result */
4291 Jim_SetEmptyResult(interp);
4293 else {
4294 if (!valObjPtr) {
4295 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4296 if (Jim_GetVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_NONE)) {
4297 Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such element in array",
4298 objPtr);
4299 return err;
4302 /* Make the error more informative and Tcl-compatible */
4303 Jim_SetResultFormatted(interp, "can't %s \"%#s\": variable isn't array",
4304 (valObjPtr ? "set" : "unset"), objPtr);
4306 return err;
4310 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4312 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4313 * and stored back to the variable before expansion.
4315 static Jim_Obj *JimDictExpandArrayVariable(Jim_Interp *interp, Jim_Obj *varObjPtr,
4316 Jim_Obj *keyObjPtr, int flags)
4318 Jim_Obj *dictObjPtr;
4319 Jim_Obj *resObjPtr = NULL;
4320 int ret;
4322 dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
4323 if (!dictObjPtr) {
4324 return NULL;
4327 ret = Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
4328 if (ret != JIM_OK) {
4329 resObjPtr = NULL;
4330 if (ret < 0) {
4331 Jim_SetResultFormatted(interp,
4332 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr, keyObjPtr);
4334 else {
4335 Jim_SetResultFormatted(interp,
4336 "can't read \"%#s(%#s)\": no such element in array", varObjPtr, keyObjPtr);
4339 else if ((flags & JIM_UNSHARED) && Jim_IsShared(dictObjPtr)) {
4340 dictObjPtr = Jim_DuplicateObj(interp, dictObjPtr);
4341 if (Jim_SetVariable(interp, varObjPtr, dictObjPtr) != JIM_OK) {
4342 /* This can probably never happen */
4343 JimPanic((1, "SetVariable failed for JIM_UNSHARED"));
4345 /* We know that the key exists. Get the result in the now-unshared dictionary */
4346 Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
4349 return resObjPtr;
4352 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4353 static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
4355 SetDictSubstFromAny(interp, objPtr);
4357 return JimDictExpandArrayVariable(interp,
4358 objPtr->internalRep.dictSubstValue.varNameObjPtr,
4359 objPtr->internalRep.dictSubstValue.indexObjPtr, flags);
4362 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4364 void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
4366 Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
4367 Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
4370 void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
4372 JIM_NOTUSED(interp);
4374 dupPtr->internalRep.dictSubstValue.varNameObjPtr =
4375 srcPtr->internalRep.dictSubstValue.varNameObjPtr;
4376 dupPtr->internalRep.dictSubstValue.indexObjPtr = srcPtr->internalRep.dictSubstValue.indexObjPtr;
4377 dupPtr->typePtr = &dictSubstObjType;
4380 /* Note: The object *must* be in dict-sugar format */
4381 static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
4383 if (objPtr->typePtr != &dictSubstObjType) {
4384 Jim_Obj *varObjPtr, *keyObjPtr;
4386 if (objPtr->typePtr == &interpolatedObjType) {
4387 /* An interpolated object in dict-sugar form */
4389 const ScriptToken *token = objPtr->internalRep.twoPtrValue.ptr1;
4391 varObjPtr = token[0].objPtr;
4392 keyObjPtr = objPtr->internalRep.twoPtrValue.ptr2;
4394 Jim_IncrRefCount(varObjPtr);
4395 Jim_IncrRefCount(keyObjPtr);
4397 else {
4398 JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
4401 Jim_FreeIntRep(interp, objPtr);
4402 objPtr->typePtr = &dictSubstObjType;
4403 objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
4404 objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
4408 /* This function is used to expand [dict get] sugar in the form
4409 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4410 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4411 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4412 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4413 * the [dict]ionary contained in variable VARNAME. */
4414 static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
4416 Jim_Obj *resObjPtr = NULL;
4417 Jim_Obj *substKeyObjPtr = NULL;
4419 SetDictSubstFromAny(interp, objPtr);
4421 if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
4422 &substKeyObjPtr, JIM_NONE)
4423 != JIM_OK) {
4424 return NULL;
4426 Jim_IncrRefCount(substKeyObjPtr);
4427 resObjPtr =
4428 JimDictExpandArrayVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
4429 substKeyObjPtr, 0);
4430 Jim_DecrRefCount(interp, substKeyObjPtr);
4432 return resObjPtr;
4435 static Jim_Obj *JimExpandExprSugar(Jim_Interp *interp, Jim_Obj *objPtr)
4437 Jim_Obj *resultObjPtr;
4439 if (Jim_EvalExpression(interp, objPtr, &resultObjPtr) == JIM_OK) {
4440 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4441 resultObjPtr->refCount--;
4442 return resultObjPtr;
4444 return NULL;
4447 /* -----------------------------------------------------------------------------
4448 * CallFrame
4449 * ---------------------------------------------------------------------------*/
4451 static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp, Jim_CallFrame *parent)
4453 Jim_CallFrame *cf;
4455 if (interp->freeFramesList) {
4456 cf = interp->freeFramesList;
4457 interp->freeFramesList = cf->nextFramePtr;
4459 else {
4460 cf = Jim_Alloc(sizeof(*cf));
4461 cf->vars.table = NULL;
4464 cf->id = interp->callFrameEpoch++;
4465 cf->parentCallFrame = parent;
4466 cf->level = parent ? parent->level + 1 : 0;
4467 cf->argv = NULL;
4468 cf->argc = 0;
4469 cf->procArgsObjPtr = NULL;
4470 cf->procBodyObjPtr = NULL;
4471 cf->nextFramePtr = NULL;
4472 cf->staticVars = NULL;
4473 if (cf->vars.table == NULL)
4474 Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
4475 return cf;
4478 /* Used to invalidate every caching related to callframe stability. */
4479 static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf)
4481 cf->id = interp->callFrameEpoch++;
4484 #define JIM_FCF_NONE 0 /* no flags */
4485 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4486 static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags)
4488 if (cf->procArgsObjPtr)
4489 Jim_DecrRefCount(interp, cf->procArgsObjPtr);
4490 if (cf->procBodyObjPtr)
4491 Jim_DecrRefCount(interp, cf->procBodyObjPtr);
4492 if (!(flags & JIM_FCF_NOHT))
4493 Jim_FreeHashTable(&cf->vars);
4494 else {
4495 int i;
4496 Jim_HashEntry **table = cf->vars.table, *he;
4498 for (i = 0; i < JIM_HT_INITIAL_SIZE; i++) {
4499 he = table[i];
4500 while (he != NULL) {
4501 Jim_HashEntry *nextEntry = he->next;
4502 Jim_Var *varPtr = (void *)he->u.val;
4504 Jim_DecrRefCount(interp, varPtr->objPtr);
4505 Jim_Free(he->u.val);
4506 Jim_Free((void *)he->key); /* ATTENTION: const cast */
4507 Jim_Free(he);
4508 table[i] = NULL;
4509 he = nextEntry;
4512 cf->vars.used = 0;
4514 cf->nextFramePtr = interp->freeFramesList;
4515 interp->freeFramesList = cf;
4518 /* -----------------------------------------------------------------------------
4519 * References
4520 * ---------------------------------------------------------------------------*/
4521 #ifdef JIM_REFERENCES
4523 /* References HashTable Type.
4525 * Keys are jim_wide integers, dynamically allocated for now but in the
4526 * future it's worth to cache this 8 bytes objects. Values are poitners
4527 * to Jim_References. */
4528 static void JimReferencesHTValDestructor(void *interp, void *val)
4530 Jim_Reference *refPtr = (void *)val;
4532 Jim_DecrRefCount(interp, refPtr->objPtr);
4533 if (refPtr->finalizerCmdNamePtr != NULL) {
4534 Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
4536 Jim_Free(val);
4539 static unsigned int JimReferencesHTHashFunction(const void *key)
4541 /* Only the least significant bits are used. */
4542 const jim_wide *widePtr = key;
4543 unsigned int intValue = (unsigned int)*widePtr;
4545 return Jim_IntHashFunction(intValue);
4548 static const void *JimReferencesHTKeyDup(void *privdata, const void *key)
4550 void *copy = Jim_Alloc(sizeof(jim_wide));
4552 JIM_NOTUSED(privdata);
4554 memcpy(copy, key, sizeof(jim_wide));
4555 return copy;
4558 static int JimReferencesHTKeyCompare(void *privdata, const void *key1, const void *key2)
4560 JIM_NOTUSED(privdata);
4562 return memcmp(key1, key2, sizeof(jim_wide)) == 0;
4565 static void JimReferencesHTKeyDestructor(void *privdata, const void *key)
4567 JIM_NOTUSED(privdata);
4569 Jim_Free((void *)key);
4572 static const Jim_HashTableType JimReferencesHashTableType = {
4573 JimReferencesHTHashFunction, /* hash function */
4574 JimReferencesHTKeyDup, /* key dup */
4575 NULL, /* val dup */
4576 JimReferencesHTKeyCompare, /* key compare */
4577 JimReferencesHTKeyDestructor, /* key destructor */
4578 JimReferencesHTValDestructor /* val destructor */
4581 /* -----------------------------------------------------------------------------
4582 * Reference object type and References API
4583 * ---------------------------------------------------------------------------*/
4585 /* The string representation of references has two features in order
4586 * to make the GC faster. The first is that every reference starts
4587 * with a non common character '<', in order to make the string matching
4588 * faster. The second is that the reference string rep is 42 characters
4589 * in length, this allows to avoid to check every object with a string
4590 * repr < 42, and usually there aren't many of these objects. */
4592 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4594 static int JimFormatReference(char *buf, Jim_Reference *refPtr, jim_wide id)
4596 const char *fmt = "<reference.<%s>.%020" JIM_WIDE_MODIFIER ">";
4598 sprintf(buf, fmt, refPtr->tag, id);
4599 return JIM_REFERENCE_SPACE;
4602 static void UpdateStringOfReference(struct Jim_Obj *objPtr);
4604 static const Jim_ObjType referenceObjType = {
4605 "reference",
4606 NULL,
4607 NULL,
4608 UpdateStringOfReference,
4609 JIM_TYPE_REFERENCES,
4612 void UpdateStringOfReference(struct Jim_Obj *objPtr)
4614 int len;
4615 char buf[JIM_REFERENCE_SPACE + 1];
4616 Jim_Reference *refPtr;
4618 refPtr = objPtr->internalRep.refValue.refPtr;
4619 len = JimFormatReference(buf, refPtr, objPtr->internalRep.refValue.id);
4620 objPtr->bytes = Jim_Alloc(len + 1);
4621 memcpy(objPtr->bytes, buf, len + 1);
4622 objPtr->length = len;
4625 /* returns true if 'c' is a valid reference tag character.
4626 * i.e. inside the range [_a-zA-Z0-9] */
4627 static int isrefchar(int c)
4629 return (c == '_' || isalnum(c));
4632 static int SetReferenceFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
4634 jim_wide wideValue;
4635 int i, len;
4636 const char *str, *start, *end;
4637 char refId[21];
4638 Jim_Reference *refPtr;
4639 Jim_HashEntry *he;
4641 /* Get the string representation */
4642 str = Jim_GetString(objPtr, &len);
4643 /* Check if it looks like a reference */
4644 if (len < JIM_REFERENCE_SPACE)
4645 goto badformat;
4646 /* Trim spaces */
4647 start = str;
4648 end = str + len - 1;
4649 while (*start == ' ')
4650 start++;
4651 while (*end == ' ' && end > start)
4652 end--;
4653 if (end - start + 1 != JIM_REFERENCE_SPACE)
4654 goto badformat;
4655 /* <reference.<1234567>.%020> */
4656 if (memcmp(start, "<reference.<", 12) != 0)
4657 goto badformat;
4658 if (start[12 + JIM_REFERENCE_TAGLEN] != '>' || end[0] != '>')
4659 goto badformat;
4660 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4661 for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
4662 if (!isrefchar(start[12 + i]))
4663 goto badformat;
4665 /* Extract info from the reference. */
4666 memcpy(refId, start + 14 + JIM_REFERENCE_TAGLEN, 20);
4667 refId[20] = '\0';
4668 /* Try to convert the ID into a jim_wide */
4669 if (Jim_StringToWide(refId, &wideValue, 10) != JIM_OK)
4670 goto badformat;
4671 /* Check if the reference really exists! */
4672 he = Jim_FindHashEntry(&interp->references, &wideValue);
4673 if (he == NULL) {
4674 Jim_SetResultFormatted(interp, "invalid reference id \"%#s\"", objPtr);
4675 return JIM_ERR;
4677 refPtr = he->u.val;
4678 /* Free the old internal repr and set the new one. */
4679 Jim_FreeIntRep(interp, objPtr);
4680 objPtr->typePtr = &referenceObjType;
4681 objPtr->internalRep.refValue.id = wideValue;
4682 objPtr->internalRep.refValue.refPtr = refPtr;
4683 return JIM_OK;
4685 badformat:
4686 Jim_SetResultFormatted(interp, "expected reference but got \"%#s\"", objPtr);
4687 return JIM_ERR;
4690 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4691 * as finalizer command (or NULL if there is no finalizer).
4692 * The returned reference object has refcount = 0. */
4693 Jim_Obj *Jim_NewReference(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr)
4695 struct Jim_Reference *refPtr;
4696 jim_wide wideValue = interp->referenceNextId;
4697 Jim_Obj *refObjPtr;
4698 const char *tag;
4699 int tagLen, i;
4701 /* Perform the Garbage Collection if needed. */
4702 Jim_CollectIfNeeded(interp);
4704 refPtr = Jim_Alloc(sizeof(*refPtr));
4705 refPtr->objPtr = objPtr;
4706 Jim_IncrRefCount(objPtr);
4707 refPtr->finalizerCmdNamePtr = cmdNamePtr;
4708 if (cmdNamePtr)
4709 Jim_IncrRefCount(cmdNamePtr);
4710 Jim_AddHashEntry(&interp->references, &wideValue, refPtr);
4711 refObjPtr = Jim_NewObj(interp);
4712 refObjPtr->typePtr = &referenceObjType;
4713 refObjPtr->bytes = NULL;
4714 refObjPtr->internalRep.refValue.id = interp->referenceNextId;
4715 refObjPtr->internalRep.refValue.refPtr = refPtr;
4716 interp->referenceNextId++;
4717 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4718 * that does not pass the 'isrefchar' test is replaced with '_' */
4719 tag = Jim_GetString(tagPtr, &tagLen);
4720 if (tagLen > JIM_REFERENCE_TAGLEN)
4721 tagLen = JIM_REFERENCE_TAGLEN;
4722 for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
4723 if (i < tagLen && isrefchar(tag[i]))
4724 refPtr->tag[i] = tag[i];
4725 else
4726 refPtr->tag[i] = '_';
4728 refPtr->tag[JIM_REFERENCE_TAGLEN] = '\0';
4729 return refObjPtr;
4732 Jim_Reference *Jim_GetReference(Jim_Interp *interp, Jim_Obj *objPtr)
4734 if (objPtr->typePtr != &referenceObjType && SetReferenceFromAny(interp, objPtr) == JIM_ERR)
4735 return NULL;
4736 return objPtr->internalRep.refValue.refPtr;
4739 int Jim_SetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr)
4741 Jim_Reference *refPtr;
4743 if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
4744 return JIM_ERR;
4745 Jim_IncrRefCount(cmdNamePtr);
4746 if (refPtr->finalizerCmdNamePtr)
4747 Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
4748 refPtr->finalizerCmdNamePtr = cmdNamePtr;
4749 return JIM_OK;
4752 int Jim_GetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr)
4754 Jim_Reference *refPtr;
4756 if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
4757 return JIM_ERR;
4758 *cmdNamePtrPtr = refPtr->finalizerCmdNamePtr;
4759 return JIM_OK;
4762 /* -----------------------------------------------------------------------------
4763 * References Garbage Collection
4764 * ---------------------------------------------------------------------------*/
4766 /* This the hash table type for the "MARK" phase of the GC */
4767 static const Jim_HashTableType JimRefMarkHashTableType = {
4768 JimReferencesHTHashFunction, /* hash function */
4769 JimReferencesHTKeyDup, /* key dup */
4770 NULL, /* val dup */
4771 JimReferencesHTKeyCompare, /* key compare */
4772 JimReferencesHTKeyDestructor, /* key destructor */
4773 NULL /* val destructor */
4776 /* Performs the garbage collection. */
4777 int Jim_Collect(Jim_Interp *interp)
4779 int collected = 0;
4780 #ifndef JIM_BOOTSTRAP
4781 Jim_HashTable marks;
4782 Jim_HashTableIterator *htiter;
4783 Jim_HashEntry *he;
4784 Jim_Obj *objPtr;
4786 /* Avoid recursive calls */
4787 if (interp->lastCollectId == -1) {
4788 /* Jim_Collect() already running. Return just now. */
4789 return 0;
4791 interp->lastCollectId = -1;
4793 /* Mark all the references found into the 'mark' hash table.
4794 * The references are searched in every live object that
4795 * is of a type that can contain references. */
4796 Jim_InitHashTable(&marks, &JimRefMarkHashTableType, NULL);
4797 objPtr = interp->liveList;
4798 while (objPtr) {
4799 if (objPtr->typePtr == NULL || objPtr->typePtr->flags & JIM_TYPE_REFERENCES) {
4800 const char *str, *p;
4801 int len;
4803 /* If the object is of type reference, to get the
4804 * Id is simple... */
4805 if (objPtr->typePtr == &referenceObjType) {
4806 Jim_AddHashEntry(&marks, &objPtr->internalRep.refValue.id, NULL);
4807 #ifdef JIM_DEBUG_GC
4808 printf("MARK (reference): %d refcount: %d" JIM_NL,
4809 (int)objPtr->internalRep.refValue.id, objPtr->refCount);
4810 #endif
4811 objPtr = objPtr->nextObjPtr;
4812 continue;
4814 /* Get the string repr of the object we want
4815 * to scan for references. */
4816 p = str = Jim_GetString(objPtr, &len);
4817 /* Skip objects too little to contain references. */
4818 if (len < JIM_REFERENCE_SPACE) {
4819 objPtr = objPtr->nextObjPtr;
4820 continue;
4822 /* Extract references from the object string repr. */
4823 while (1) {
4824 int i;
4825 jim_wide id;
4826 char buf[21];
4828 if ((p = strstr(p, "<reference.<")) == NULL)
4829 break;
4830 /* Check if it's a valid reference. */
4831 if (len - (p - str) < JIM_REFERENCE_SPACE)
4832 break;
4833 if (p[41] != '>' || p[19] != '>' || p[20] != '.')
4834 break;
4835 for (i = 21; i <= 40; i++)
4836 if (!isdigit(UCHAR(p[i])))
4837 break;
4838 /* Get the ID */
4839 memcpy(buf, p + 21, 20);
4840 buf[20] = '\0';
4841 Jim_StringToWide(buf, &id, 10);
4843 /* Ok, a reference for the given ID
4844 * was found. Mark it. */
4845 Jim_AddHashEntry(&marks, &id, NULL);
4846 #ifdef JIM_DEBUG_GC
4847 printf("MARK: %d" JIM_NL, (int)id);
4848 #endif
4849 p += JIM_REFERENCE_SPACE;
4852 objPtr = objPtr->nextObjPtr;
4855 /* Run the references hash table to destroy every reference that
4856 * is not referenced outside (not present in the mark HT). */
4857 htiter = Jim_GetHashTableIterator(&interp->references);
4858 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
4859 const jim_wide *refId;
4860 Jim_Reference *refPtr;
4862 refId = he->key;
4863 /* Check if in the mark phase we encountered
4864 * this reference. */
4865 if (Jim_FindHashEntry(&marks, refId) == NULL) {
4866 #ifdef JIM_DEBUG_GC
4867 printf("COLLECTING %d" JIM_NL, (int)*refId);
4868 #endif
4869 collected++;
4870 /* Drop the reference, but call the
4871 * finalizer first if registered. */
4872 refPtr = he->u.val;
4873 if (refPtr->finalizerCmdNamePtr) {
4874 char *refstr = Jim_Alloc(JIM_REFERENCE_SPACE + 1);
4875 Jim_Obj *objv[3], *oldResult;
4877 JimFormatReference(refstr, refPtr, *refId);
4879 objv[0] = refPtr->finalizerCmdNamePtr;
4880 objv[1] = Jim_NewStringObjNoAlloc(interp, refstr, 32);
4881 objv[2] = refPtr->objPtr;
4882 Jim_IncrRefCount(objv[0]);
4883 Jim_IncrRefCount(objv[1]);
4884 Jim_IncrRefCount(objv[2]);
4886 /* Drop the reference itself */
4887 Jim_DeleteHashEntry(&interp->references, refId);
4889 /* Call the finalizer. Errors ignored. */
4890 oldResult = interp->result;
4891 Jim_IncrRefCount(oldResult);
4892 Jim_EvalObjVector(interp, 3, objv);
4893 Jim_SetResult(interp, oldResult);
4894 Jim_DecrRefCount(interp, oldResult);
4896 Jim_DecrRefCount(interp, objv[0]);
4897 Jim_DecrRefCount(interp, objv[1]);
4898 Jim_DecrRefCount(interp, objv[2]);
4900 else {
4901 Jim_DeleteHashEntry(&interp->references, refId);
4905 Jim_FreeHashTableIterator(htiter);
4906 Jim_FreeHashTable(&marks);
4907 interp->lastCollectId = interp->referenceNextId;
4908 interp->lastCollectTime = time(NULL);
4909 #endif /* JIM_BOOTSTRAP */
4910 return collected;
4913 #define JIM_COLLECT_ID_PERIOD 5000
4914 #define JIM_COLLECT_TIME_PERIOD 300
4916 void Jim_CollectIfNeeded(Jim_Interp *interp)
4918 jim_wide elapsedId;
4919 int elapsedTime;
4921 elapsedId = interp->referenceNextId - interp->lastCollectId;
4922 elapsedTime = time(NULL) - interp->lastCollectTime;
4925 if (elapsedId > JIM_COLLECT_ID_PERIOD || elapsedTime > JIM_COLLECT_TIME_PERIOD) {
4926 Jim_Collect(interp);
4929 #endif
4931 static int JimIsBigEndian(void)
4933 union {
4934 unsigned short s;
4935 unsigned char c[2];
4936 } uval = {0x0102};
4938 return uval.c[0] == 1;
4941 /* -----------------------------------------------------------------------------
4942 * Interpreter related functions
4943 * ---------------------------------------------------------------------------*/
4945 Jim_Interp *Jim_CreateInterp(void)
4947 Jim_Interp *i = Jim_Alloc(sizeof(*i));
4949 memset(i, 0, sizeof(*i));
4951 i->maxNestingDepth = JIM_MAX_NESTING_DEPTH;
4952 i->lastCollectTime = time(NULL);
4954 /* Note that we can create objects only after the
4955 * interpreter liveList and freeList pointers are
4956 * initialized to NULL. */
4957 Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
4958 #ifdef JIM_REFERENCES
4959 Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
4960 #endif
4961 Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
4962 Jim_InitHashTable(&i->packages, &JimStringKeyValCopyHashTableType, NULL);
4963 i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL);
4964 i->emptyObj = Jim_NewEmptyStringObj(i);
4965 i->trueObj = Jim_NewIntObj(i, 1);
4966 i->falseObj = Jim_NewIntObj(i, 0);
4967 i->errorFileNameObj = i->emptyObj;
4968 i->result = i->emptyObj;
4969 i->stackTrace = Jim_NewListObj(i, NULL, 0);
4970 i->unknown = Jim_NewStringObj(i, "unknown", -1);
4971 i->errorProc = i->emptyObj;
4972 i->currentScriptObj = Jim_NewEmptyStringObj(i);
4973 Jim_IncrRefCount(i->emptyObj);
4974 Jim_IncrRefCount(i->errorFileNameObj);
4975 Jim_IncrRefCount(i->result);
4976 Jim_IncrRefCount(i->stackTrace);
4977 Jim_IncrRefCount(i->unknown);
4978 Jim_IncrRefCount(i->currentScriptObj);
4979 Jim_IncrRefCount(i->errorProc);
4980 Jim_IncrRefCount(i->trueObj);
4981 Jim_IncrRefCount(i->falseObj);
4983 /* Initialize key variables every interpreter should contain */
4984 Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
4985 Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
4987 Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
4988 Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
4989 Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
4990 Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4991 Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
4992 Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
4993 Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
4995 return i;
4998 void Jim_FreeInterp(Jim_Interp *i)
5000 Jim_CallFrame *cf = i->framePtr, *prevcf, *nextcf;
5001 Jim_Obj *objPtr, *nextObjPtr;
5003 Jim_DecrRefCount(i, i->emptyObj);
5004 Jim_DecrRefCount(i, i->trueObj);
5005 Jim_DecrRefCount(i, i->falseObj);
5006 Jim_DecrRefCount(i, i->result);
5007 Jim_DecrRefCount(i, i->stackTrace);
5008 Jim_DecrRefCount(i, i->errorProc);
5009 Jim_DecrRefCount(i, i->unknown);
5010 Jim_DecrRefCount(i, i->errorFileNameObj);
5011 Jim_DecrRefCount(i, i->currentScriptObj);
5012 Jim_FreeHashTable(&i->commands);
5013 #ifdef JIM_REFERENCES
5014 Jim_FreeHashTable(&i->references);
5015 #endif
5016 Jim_FreeHashTable(&i->packages);
5017 Jim_Free(i->prngState);
5018 Jim_FreeHashTable(&i->assocData);
5019 JimDeleteLocalProcs(i);
5021 /* Free the call frames list */
5022 while (cf) {
5023 prevcf = cf->parentCallFrame;
5024 JimFreeCallFrame(i, cf, JIM_FCF_NONE);
5025 cf = prevcf;
5027 /* Check that the live object list is empty, otherwise
5028 * there is a memory leak. */
5029 if (i->liveList != NULL) {
5030 objPtr = i->liveList;
5032 printf(JIM_NL "-------------------------------------" JIM_NL);
5033 printf("Objects still in the free list:" JIM_NL);
5034 while (objPtr) {
5035 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
5037 printf("%p (%d) %-10s: '%.20s'" JIM_NL,
5038 (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
5039 if (objPtr->typePtr == &sourceObjType) {
5040 printf("FILE %s LINE %d" JIM_NL,
5041 Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
5042 objPtr->internalRep.sourceValue.lineNumber);
5044 objPtr = objPtr->nextObjPtr;
5046 printf("-------------------------------------" JIM_NL JIM_NL);
5047 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5049 /* Free all the freed objects. */
5050 objPtr = i->freeList;
5051 while (objPtr) {
5052 nextObjPtr = objPtr->nextObjPtr;
5053 Jim_Free(objPtr);
5054 objPtr = nextObjPtr;
5056 /* Free cached CallFrame structures */
5057 cf = i->freeFramesList;
5058 while (cf) {
5059 nextcf = cf->nextFramePtr;
5060 if (cf->vars.table != NULL)
5061 Jim_Free(cf->vars.table);
5062 Jim_Free(cf);
5063 cf = nextcf;
5065 #ifdef jim_ext_load
5066 Jim_FreeLoadHandles(i);
5067 #endif
5069 /* Free the interpreter structure. */
5070 Jim_Free(i);
5073 /* Returns the call frame relative to the level represented by
5074 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5076 * This function accepts the 'level' argument in the form
5077 * of the commands [uplevel] and [upvar].
5079 * For a function accepting a relative integer as level suitable
5080 * for implementation of [info level ?level?] check the
5081 * JimGetCallFrameByInteger() function.
5083 * Returns NULL on error.
5085 Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5087 long level;
5088 const char *str;
5089 Jim_CallFrame *framePtr;
5091 if (levelObjPtr) {
5092 str = Jim_String(levelObjPtr);
5093 if (str[0] == '#') {
5094 char *endptr;
5096 level = strtol(str + 1, &endptr, 0);
5097 if (str[1] == '\0' || endptr[0] != '\0') {
5098 level = -1;
5101 else {
5102 if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
5103 level = -1;
5105 else {
5106 /* Convert from a relative to an absolute level */
5107 level = interp->framePtr->level - level;
5111 else {
5112 str = "1"; /* Needed to format the error message. */
5113 level = interp->framePtr->level - 1;
5116 if (level == 0) {
5117 return interp->topFramePtr;
5119 if (level > 0) {
5120 /* Lookup */
5121 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5122 if (framePtr->level == level) {
5123 return framePtr;
5128 Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
5129 return NULL;
5132 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5133 * as a relative integer like in the [info level ?level?] command.
5135 static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5137 long level;
5138 Jim_CallFrame *framePtr;
5140 if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
5141 if (level <= 0) {
5142 /* Convert from a relative to an absolute level */
5143 level = interp->framePtr->level + level;
5146 if (level == 0) {
5147 return interp->topFramePtr;
5150 /* Lookup */
5151 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5152 if (framePtr->level == level) {
5153 return framePtr;
5158 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
5159 return NULL;
5162 static void JimResetStackTrace(Jim_Interp *interp)
5164 Jim_DecrRefCount(interp, interp->stackTrace);
5165 interp->stackTrace = Jim_NewListObj(interp, NULL, 0);
5166 Jim_IncrRefCount(interp->stackTrace);
5169 static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
5171 int len;
5173 /* Increment reference first in case these are the same object */
5174 Jim_IncrRefCount(stackTraceObj);
5175 Jim_DecrRefCount(interp, interp->stackTrace);
5176 interp->stackTrace = stackTraceObj;
5177 interp->errorFlag = 1;
5179 /* This is a bit ugly.
5180 * If the filename of the last entry of the stack trace is empty,
5181 * the next stack level should be added.
5183 len = Jim_ListLength(interp, interp->stackTrace);
5184 if (len >= 3) {
5185 Jim_Obj *filenameObj;
5187 Jim_ListIndex(interp, interp->stackTrace, len - 2, &filenameObj, JIM_NONE);
5189 Jim_GetString(filenameObj, &len);
5191 if (!Jim_Length(filenameObj)) {
5192 interp->addStackTrace = 1;
5197 /* Returns 1 if the stack trace information was used or 0 if not */
5198 static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,
5199 Jim_Obj *fileNameObj, int linenr)
5201 if (strcmp(procname, "unknown") == 0) {
5202 procname = "";
5204 if (!*procname && !Jim_Length(fileNameObj)) {
5205 /* No useful info here */
5206 return;
5209 if (Jim_IsShared(interp->stackTrace)) {
5210 Jim_DecrRefCount(interp, interp->stackTrace);
5211 interp->stackTrace = Jim_DuplicateObj(interp, interp->stackTrace);
5212 Jim_IncrRefCount(interp->stackTrace);
5215 /* If we have no procname but the previous element did, merge with that frame */
5216 if (!*procname && Jim_Length(fileNameObj)) {
5217 /* Just a filename. Check the previous entry */
5218 int len = Jim_ListLength(interp, interp->stackTrace);
5220 if (len >= 3) {
5221 Jim_Obj *objPtr;
5222 if (Jim_ListIndex(interp, interp->stackTrace, len - 3, &objPtr, JIM_NONE) == JIM_OK && Jim_Length(objPtr)) {
5223 /* Yes, the previous level had procname */
5224 if (Jim_ListIndex(interp, interp->stackTrace, len - 2, &objPtr, JIM_NONE) == JIM_OK && !Jim_Length(objPtr)) {
5225 /* But no filename, so merge the new info with that frame */
5226 ListSetIndex(interp, interp->stackTrace, len - 2, fileNameObj, 0);
5227 ListSetIndex(interp, interp->stackTrace, len - 1, Jim_NewIntObj(interp, linenr), 0);
5228 return;
5234 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewStringObj(interp, procname, -1));
5235 Jim_ListAppendElement(interp, interp->stackTrace, fileNameObj);
5236 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewIntObj(interp, linenr));
5239 int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
5240 void *data)
5242 AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
5244 assocEntryPtr->delProc = delProc;
5245 assocEntryPtr->data = data;
5246 return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
5249 void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
5251 Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
5253 if (entryPtr != NULL) {
5254 AssocDataValue *assocEntryPtr = (AssocDataValue *) entryPtr->u.val;
5256 return assocEntryPtr->data;
5258 return NULL;
5261 int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
5263 return Jim_DeleteHashEntry(&interp->assocData, key);
5266 int Jim_GetExitCode(Jim_Interp *interp)
5268 return interp->exitCode;
5271 /* -----------------------------------------------------------------------------
5272 * Integer object
5273 * ---------------------------------------------------------------------------*/
5274 #define JIM_INTEGER_SPACE 24
5276 static void UpdateStringOfInt(struct Jim_Obj *objPtr);
5277 static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
5279 static const Jim_ObjType intObjType = {
5280 "int",
5281 NULL,
5282 NULL,
5283 UpdateStringOfInt,
5284 JIM_TYPE_NONE,
5287 /* A coerced double is closer to an int than a double.
5288 * It is an int value temporarily masquerading as a double value.
5289 * i.e. it has the same string value as an int and Jim_GetWide()
5290 * succeeds, but also Jim_GetDouble() returns the value directly.
5292 static const Jim_ObjType coercedDoubleObjType = {
5293 "coerced-double",
5294 NULL,
5295 NULL,
5296 UpdateStringOfInt,
5297 JIM_TYPE_NONE,
5301 void UpdateStringOfInt(struct Jim_Obj *objPtr)
5303 int len;
5304 char buf[JIM_INTEGER_SPACE + 1];
5306 len = Jim_WideToString(buf, JimWideValue(objPtr));
5307 objPtr->bytes = Jim_Alloc(len + 1);
5308 memcpy(objPtr->bytes, buf, len + 1);
5309 objPtr->length = len;
5312 int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
5314 jim_wide wideValue;
5315 const char *str;
5317 if (objPtr->typePtr == &coercedDoubleObjType) {
5318 /* Simple switcheroo */
5319 objPtr->typePtr = &intObjType;
5320 return JIM_OK;
5323 /* Get the string representation */
5324 str = Jim_String(objPtr);
5325 /* Try to convert into a jim_wide */
5326 if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
5327 if (flags & JIM_ERRMSG) {
5328 Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
5330 return JIM_ERR;
5332 if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
5333 Jim_SetResultString(interp, "Integer value too big to be represented", -1);
5334 return JIM_ERR;
5336 /* Free the old internal repr and set the new one. */
5337 Jim_FreeIntRep(interp, objPtr);
5338 objPtr->typePtr = &intObjType;
5339 objPtr->internalRep.wideValue = wideValue;
5340 return JIM_OK;
5343 #ifdef JIM_OPTIMIZATION
5344 static int JimIsWide(Jim_Obj *objPtr)
5346 return objPtr->typePtr == &intObjType;
5348 #endif
5350 int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5352 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
5353 return JIM_ERR;
5354 *widePtr = JimWideValue(objPtr);
5355 return JIM_OK;
5358 /* Get a wide but does not set an error if the format is bad. */
5359 static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5361 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
5362 return JIM_ERR;
5363 *widePtr = JimWideValue(objPtr);
5364 return JIM_OK;
5367 int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
5369 jim_wide wideValue;
5370 int retval;
5372 retval = Jim_GetWide(interp, objPtr, &wideValue);
5373 if (retval == JIM_OK) {
5374 *longPtr = (long)wideValue;
5375 return JIM_OK;
5377 return JIM_ERR;
5380 Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
5382 Jim_Obj *objPtr;
5384 objPtr = Jim_NewObj(interp);
5385 objPtr->typePtr = &intObjType;
5386 objPtr->bytes = NULL;
5387 objPtr->internalRep.wideValue = wideValue;
5388 return objPtr;
5391 /* -----------------------------------------------------------------------------
5392 * Double object
5393 * ---------------------------------------------------------------------------*/
5394 #define JIM_DOUBLE_SPACE 30
5396 static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
5397 static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
5399 static const Jim_ObjType doubleObjType = {
5400 "double",
5401 NULL,
5402 NULL,
5403 UpdateStringOfDouble,
5404 JIM_TYPE_NONE,
5407 void UpdateStringOfDouble(struct Jim_Obj *objPtr)
5409 int len;
5410 char buf[JIM_DOUBLE_SPACE + 1];
5412 len = Jim_DoubleToString(buf, objPtr->internalRep.doubleValue);
5413 objPtr->bytes = Jim_Alloc(len + 1);
5414 memcpy(objPtr->bytes, buf, len + 1);
5415 objPtr->length = len;
5418 int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
5420 double doubleValue;
5421 jim_wide wideValue;
5422 const char *str;
5424 /* Preserve the string representation.
5425 * Needed so we can convert back to int without loss
5427 str = Jim_String(objPtr);
5429 #ifdef HAVE_LONG_LONG
5430 /* Assume a 53 bit mantissa */
5431 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5432 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5434 if (objPtr->typePtr == &intObjType
5435 && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
5436 && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
5438 /* Direct conversion to coerced double */
5439 objPtr->typePtr = &coercedDoubleObjType;
5440 return JIM_OK;
5442 else
5443 #endif
5444 if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
5445 /* Managed to convert to an int, so we can use this as a cooerced double */
5446 Jim_FreeIntRep(interp, objPtr);
5447 objPtr->typePtr = &coercedDoubleObjType;
5448 objPtr->internalRep.wideValue = wideValue;
5449 return JIM_OK;
5451 else {
5452 /* Try to convert into a double */
5453 if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
5454 Jim_SetResultFormatted(interp, "expected number but got \"%#s\"", objPtr);
5455 return JIM_ERR;
5457 /* Free the old internal repr and set the new one. */
5458 Jim_FreeIntRep(interp, objPtr);
5460 objPtr->typePtr = &doubleObjType;
5461 objPtr->internalRep.doubleValue = doubleValue;
5462 return JIM_OK;
5465 int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
5467 if (objPtr->typePtr == &coercedDoubleObjType) {
5468 *doublePtr = JimWideValue(objPtr);
5469 return JIM_OK;
5471 if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
5472 return JIM_ERR;
5474 if (objPtr->typePtr == &coercedDoubleObjType) {
5475 *doublePtr = JimWideValue(objPtr);
5477 else {
5478 *doublePtr = objPtr->internalRep.doubleValue;
5480 return JIM_OK;
5483 Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
5485 Jim_Obj *objPtr;
5487 objPtr = Jim_NewObj(interp);
5488 objPtr->typePtr = &doubleObjType;
5489 objPtr->bytes = NULL;
5490 objPtr->internalRep.doubleValue = doubleValue;
5491 return objPtr;
5494 /* -----------------------------------------------------------------------------
5495 * List object
5496 * ---------------------------------------------------------------------------*/
5497 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
5498 static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
5499 static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
5500 static void UpdateStringOfList(struct Jim_Obj *objPtr);
5501 static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
5503 /* Note that while the elements of the list may contain references,
5504 * the list object itself can't. This basically means that the
5505 * list object string representation as a whole can't contain references
5506 * that are not presents in the single elements. */
5507 static const Jim_ObjType listObjType = {
5508 "list",
5509 FreeListInternalRep,
5510 DupListInternalRep,
5511 UpdateStringOfList,
5512 JIM_TYPE_NONE,
5515 void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
5517 int i;
5519 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5520 Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
5522 Jim_Free(objPtr->internalRep.listValue.ele);
5525 void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
5527 int i;
5529 JIM_NOTUSED(interp);
5531 dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
5532 dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
5533 dupPtr->internalRep.listValue.ele =
5534 Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
5535 memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
5536 sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
5537 for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
5538 Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
5540 dupPtr->typePtr = &listObjType;
5543 /* The following function checks if a given string can be encoded
5544 * into a list element without any kind of quoting, surrounded by braces,
5545 * or using escapes to quote. */
5546 #define JIM_ELESTR_SIMPLE 0
5547 #define JIM_ELESTR_BRACE 1
5548 #define JIM_ELESTR_QUOTE 2
5549 static int ListElementQuotingType(const char *s, int len)
5551 int i, level, blevel, trySimple = 1;
5553 /* Try with the SIMPLE case */
5554 if (len == 0)
5555 return JIM_ELESTR_BRACE;
5556 if (s[0] == '#')
5557 return JIM_ELESTR_BRACE;
5558 if (s[0] == '"' || s[0] == '{') {
5559 trySimple = 0;
5560 goto testbrace;
5562 for (i = 0; i < len; i++) {
5563 switch (s[i]) {
5564 case ' ':
5565 case '$':
5566 case '"':
5567 case '[':
5568 case ']':
5569 case ';':
5570 case '\\':
5571 case '\r':
5572 case '\n':
5573 case '\t':
5574 case '\f':
5575 case '\v':
5576 trySimple = 0;
5577 case '{':
5578 case '}':
5579 goto testbrace;
5582 return JIM_ELESTR_SIMPLE;
5584 testbrace:
5585 /* Test if it's possible to do with braces */
5586 if (s[len - 1] == '\\')
5587 return JIM_ELESTR_QUOTE;
5588 level = 0;
5589 blevel = 0;
5590 for (i = 0; i < len; i++) {
5591 switch (s[i]) {
5592 case '{':
5593 level++;
5594 break;
5595 case '}':
5596 level--;
5597 if (level < 0)
5598 return JIM_ELESTR_QUOTE;
5599 break;
5600 case '[':
5601 blevel++;
5602 break;
5603 case ']':
5604 blevel--;
5605 break;
5606 case '\\':
5607 if (s[i + 1] == '\n')
5608 return JIM_ELESTR_QUOTE;
5609 else if (s[i + 1] != '\0')
5610 i++;
5611 break;
5614 if (blevel < 0) {
5615 return JIM_ELESTR_QUOTE;
5618 if (level == 0) {
5619 if (!trySimple)
5620 return JIM_ELESTR_BRACE;
5621 for (i = 0; i < len; i++) {
5622 switch (s[i]) {
5623 case ' ':
5624 case '$':
5625 case '"':
5626 case '[':
5627 case ']':
5628 case ';':
5629 case '\\':
5630 case '\r':
5631 case '\n':
5632 case '\t':
5633 case '\f':
5634 case '\v':
5635 return JIM_ELESTR_BRACE;
5636 break;
5639 return JIM_ELESTR_SIMPLE;
5641 return JIM_ELESTR_QUOTE;
5644 /* Returns the malloc-ed representation of a string
5645 * using backslash to quote special chars. */
5646 static char *BackslashQuoteString(const char *s, int len, int *qlenPtr)
5648 char *q = Jim_Alloc(len * 2 + 1), *p;
5650 p = q;
5651 while (*s) {
5652 switch (*s) {
5653 case ' ':
5654 case '$':
5655 case '"':
5656 case '[':
5657 case ']':
5658 case '{':
5659 case '}':
5660 case ';':
5661 case '\\':
5662 *p++ = '\\';
5663 *p++ = *s++;
5664 break;
5665 case '\n':
5666 *p++ = '\\';
5667 *p++ = 'n';
5668 s++;
5669 break;
5670 case '\r':
5671 *p++ = '\\';
5672 *p++ = 'r';
5673 s++;
5674 break;
5675 case '\t':
5676 *p++ = '\\';
5677 *p++ = 't';
5678 s++;
5679 break;
5680 case '\f':
5681 *p++ = '\\';
5682 *p++ = 'f';
5683 s++;
5684 break;
5685 case '\v':
5686 *p++ = '\\';
5687 *p++ = 'v';
5688 s++;
5689 break;
5690 default:
5691 *p++ = *s++;
5692 break;
5695 *p = '\0';
5696 *qlenPtr = p - q;
5697 return q;
5700 static void UpdateStringOfList(struct Jim_Obj *objPtr)
5702 int i, bufLen, realLength;
5703 const char *strRep;
5704 char *p;
5705 int *quotingType;
5706 Jim_Obj **ele = objPtr->internalRep.listValue.ele;
5708 /* (Over) Estimate the space needed. */
5709 quotingType = Jim_Alloc(sizeof(int) * objPtr->internalRep.listValue.len + 1);
5710 bufLen = 0;
5711 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5712 int len;
5714 strRep = Jim_GetString(ele[i], &len);
5715 quotingType[i] = ListElementQuotingType(strRep, len);
5716 switch (quotingType[i]) {
5717 case JIM_ELESTR_SIMPLE:
5718 bufLen += len;
5719 break;
5720 case JIM_ELESTR_BRACE:
5721 bufLen += len + 2;
5722 break;
5723 case JIM_ELESTR_QUOTE:
5724 bufLen += len * 2;
5725 break;
5727 bufLen++; /* elements separator. */
5729 bufLen++;
5731 /* Generate the string rep. */
5732 p = objPtr->bytes = Jim_Alloc(bufLen + 1);
5733 realLength = 0;
5734 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5735 int len, qlen;
5736 char *q;
5738 strRep = Jim_GetString(ele[i], &len);
5740 switch (quotingType[i]) {
5741 case JIM_ELESTR_SIMPLE:
5742 memcpy(p, strRep, len);
5743 p += len;
5744 realLength += len;
5745 break;
5746 case JIM_ELESTR_BRACE:
5747 *p++ = '{';
5748 memcpy(p, strRep, len);
5749 p += len;
5750 *p++ = '}';
5751 realLength += len + 2;
5752 break;
5753 case JIM_ELESTR_QUOTE:
5754 q = BackslashQuoteString(strRep, len, &qlen);
5755 memcpy(p, q, qlen);
5756 Jim_Free(q);
5757 p += qlen;
5758 realLength += qlen;
5759 break;
5761 /* Add a separating space */
5762 if (i + 1 != objPtr->internalRep.listValue.len) {
5763 *p++ = ' ';
5764 realLength++;
5767 *p = '\0'; /* nul term. */
5768 objPtr->length = realLength;
5769 Jim_Free(quotingType);
5772 int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
5774 struct JimParserCtx parser;
5775 const char *str;
5776 int strLen;
5777 Jim_Obj *fileNameObj;
5778 int linenr;
5780 /* Try to preserve information about filename / line number */
5781 if (objPtr->typePtr == &sourceObjType) {
5782 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
5783 linenr = objPtr->internalRep.sourceValue.lineNumber;
5785 else {
5786 fileNameObj = interp->emptyObj;
5787 linenr = 1;
5789 Jim_IncrRefCount(fileNameObj);
5791 /* Get the string representation */
5792 str = Jim_GetString(objPtr, &strLen);
5794 /* Free the old internal repr just now and initialize the
5795 * new one just now. The string->list conversion can't fail. */
5796 Jim_FreeIntRep(interp, objPtr);
5797 objPtr->typePtr = &listObjType;
5798 objPtr->internalRep.listValue.len = 0;
5799 objPtr->internalRep.listValue.maxLen = 0;
5800 objPtr->internalRep.listValue.ele = NULL;
5802 /* Convert into a list */
5803 JimParserInit(&parser, str, strLen, linenr);
5804 while (!parser.eof) {
5805 Jim_Obj *elementPtr;
5807 JimParseList(&parser);
5808 if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
5809 continue;
5810 elementPtr = JimParserGetTokenObj(interp, &parser);
5811 JimSetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
5812 ListAppendElement(objPtr, elementPtr);
5814 Jim_DecrRefCount(interp, fileNameObj);
5815 return JIM_OK;
5818 Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
5820 Jim_Obj *objPtr;
5821 int i;
5823 objPtr = Jim_NewObj(interp);
5824 objPtr->typePtr = &listObjType;
5825 objPtr->bytes = NULL;
5826 objPtr->internalRep.listValue.ele = NULL;
5827 objPtr->internalRep.listValue.len = 0;
5828 objPtr->internalRep.listValue.maxLen = 0;
5829 for (i = 0; i < len; i++) {
5830 ListAppendElement(objPtr, elements[i]);
5832 return objPtr;
5835 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5836 * length of the vector. Note that the user of this function should make
5837 * sure that the list object can't shimmer while the vector returned
5838 * is in use, this vector is the one stored inside the internal representation
5839 * of the list object. This function is not exported, extensions should
5840 * always access to the List object elements using Jim_ListIndex(). */
5841 static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
5842 Jim_Obj ***listVec)
5844 *listLen = Jim_ListLength(interp, listObj);
5845 *listVec = listObj->internalRep.listValue.ele;
5848 /* Sorting uses ints, but commands may return wide */
5849 static int JimSign(jim_wide w)
5851 if (w == 0) {
5852 return 0;
5854 else if (w < 0) {
5855 return -1;
5857 return 1;
5860 /* ListSortElements type values */
5861 struct lsort_info {
5862 jmp_buf jmpbuf;
5863 Jim_Obj *command;
5864 Jim_Interp *interp;
5865 enum {
5866 JIM_LSORT_ASCII,
5867 JIM_LSORT_NOCASE,
5868 JIM_LSORT_INTEGER,
5869 JIM_LSORT_COMMAND
5870 } type;
5871 int order;
5872 int index;
5873 int indexed;
5874 int (*subfn)(Jim_Obj **, Jim_Obj **);
5877 static struct lsort_info *sort_info;
5879 static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5881 Jim_Obj *lObj, *rObj;
5883 if (Jim_ListIndex(sort_info->interp, *lhsObj, sort_info->index, &lObj, JIM_ERRMSG) != JIM_OK ||
5884 Jim_ListIndex(sort_info->interp, *rhsObj, sort_info->index, &rObj, JIM_ERRMSG) != JIM_OK) {
5885 longjmp(sort_info->jmpbuf, JIM_ERR);
5887 return sort_info->subfn(&lObj, &rObj);
5890 /* Sort the internal rep of a list. */
5891 static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5893 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
5896 static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5898 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
5901 static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5903 jim_wide lhs = 0, rhs = 0;
5905 if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
5906 Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
5907 longjmp(sort_info->jmpbuf, JIM_ERR);
5910 return JimSign(lhs - rhs) * sort_info->order;
5913 static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5915 Jim_Obj *compare_script;
5916 int rc;
5918 jim_wide ret = 0;
5920 /* This must be a valid list */
5921 compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
5922 Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
5923 Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
5925 rc = Jim_EvalObj(sort_info->interp, compare_script);
5927 if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
5928 longjmp(sort_info->jmpbuf, rc);
5931 return JimSign(ret) * sort_info->order;
5934 /* Sort a list *in place*. MUST be called with non-shared objects. */
5935 static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
5937 struct lsort_info *prev_info;
5939 typedef int (qsort_comparator) (const void *, const void *);
5940 int (*fn) (Jim_Obj **, Jim_Obj **);
5941 Jim_Obj **vector;
5942 int len;
5943 int rc;
5945 JimPanic((Jim_IsShared(listObjPtr), "Jim_ListSortElements called with shared object"));
5946 if (!Jim_IsList(listObjPtr))
5947 SetListFromAny(interp, listObjPtr);
5949 /* Allow lsort to be called reentrantly */
5950 prev_info = sort_info;
5951 sort_info = info;
5953 vector = listObjPtr->internalRep.listValue.ele;
5954 len = listObjPtr->internalRep.listValue.len;
5955 switch (info->type) {
5956 case JIM_LSORT_ASCII:
5957 fn = ListSortString;
5958 break;
5959 case JIM_LSORT_NOCASE:
5960 fn = ListSortStringNoCase;
5961 break;
5962 case JIM_LSORT_INTEGER:
5963 fn = ListSortInteger;
5964 break;
5965 case JIM_LSORT_COMMAND:
5966 fn = ListSortCommand;
5967 break;
5968 default:
5969 fn = NULL; /* avoid warning */
5970 JimPanic((1, "ListSort called with invalid sort type"));
5973 if (info->indexed) {
5974 /* Need to interpose a "list index" function */
5975 info->subfn = fn;
5976 fn = ListSortIndexHelper;
5979 if ((rc = setjmp(info->jmpbuf)) == 0) {
5980 qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
5982 Jim_InvalidateStringRep(listObjPtr);
5983 sort_info = prev_info;
5985 return rc;
5988 /* This is the low-level function to insert elements into a list.
5989 * The higher-level Jim_ListInsertElements() performs shared object
5990 * check and invalidate the string repr. This version is used
5991 * in the internals of the List Object and is not exported.
5993 * NOTE: this function can be called only against objects
5994 * with internal type of List. */
5995 static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
5997 int currentLen = listPtr->internalRep.listValue.len;
5998 int requiredLen = currentLen + elemc;
5999 int i;
6000 Jim_Obj **point;
6002 if (requiredLen > listPtr->internalRep.listValue.maxLen) {
6003 int maxLen = requiredLen * 2;
6005 listPtr->internalRep.listValue.ele =
6006 Jim_Realloc(listPtr->internalRep.listValue.ele, sizeof(Jim_Obj *) * maxLen);
6007 listPtr->internalRep.listValue.maxLen = maxLen;
6009 point = listPtr->internalRep.listValue.ele + idx;
6010 memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
6011 for (i = 0; i < elemc; ++i) {
6012 point[i] = elemVec[i];
6013 Jim_IncrRefCount(point[i]);
6015 listPtr->internalRep.listValue.len += elemc;
6018 /* Convenience call to ListInsertElements() to append a single element.
6020 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
6022 ListInsertElements(listPtr, listPtr->internalRep.listValue.len, 1, &objPtr);
6026 /* Appends every element of appendListPtr into listPtr.
6027 * Both have to be of the list type.
6028 * Convenience call to ListInsertElements()
6030 static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6032 ListInsertElements(listPtr, listPtr->internalRep.listValue.len,
6033 appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
6036 void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
6038 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
6039 if (!Jim_IsList(listPtr))
6040 SetListFromAny(interp, listPtr);
6041 Jim_InvalidateStringRep(listPtr);
6042 ListAppendElement(listPtr, objPtr);
6045 void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6047 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
6048 if (!Jim_IsList(listPtr))
6049 SetListFromAny(interp, listPtr);
6050 Jim_InvalidateStringRep(listPtr);
6051 ListAppendList(listPtr, appendListPtr);
6054 int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
6056 if (!Jim_IsList(objPtr))
6057 SetListFromAny(interp, objPtr);
6058 return objPtr->internalRep.listValue.len;
6061 void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6062 int objc, Jim_Obj *const *objVec)
6064 JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
6065 if (!Jim_IsList(listPtr))
6066 SetListFromAny(interp, listPtr);
6067 if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
6068 idx = listPtr->internalRep.listValue.len;
6069 else if (idx < 0)
6070 idx = 0;
6071 Jim_InvalidateStringRep(listPtr);
6072 ListInsertElements(listPtr, idx, objc, objVec);
6075 int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
6077 if (!Jim_IsList(listPtr))
6078 SetListFromAny(interp, listPtr);
6079 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6080 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6081 if (flags & JIM_ERRMSG) {
6082 Jim_SetResultString(interp, "list index out of range", -1);
6084 *objPtrPtr = NULL;
6085 return JIM_ERR;
6087 if (idx < 0)
6088 idx = listPtr->internalRep.listValue.len + idx;
6089 *objPtrPtr = listPtr->internalRep.listValue.ele[idx];
6090 return JIM_OK;
6093 static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6094 Jim_Obj *newObjPtr, int flags)
6096 if (!Jim_IsList(listPtr))
6097 SetListFromAny(interp, listPtr);
6098 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6099 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6100 if (flags & JIM_ERRMSG) {
6101 Jim_SetResultString(interp, "list index out of range", -1);
6103 return JIM_ERR;
6105 if (idx < 0)
6106 idx = listPtr->internalRep.listValue.len + idx;
6107 Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
6108 listPtr->internalRep.listValue.ele[idx] = newObjPtr;
6109 Jim_IncrRefCount(newObjPtr);
6110 return JIM_OK;
6113 /* Modify the list stored into the variable named 'varNamePtr'
6114 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6115 * with the new element 'newObjptr'. */
6116 int Jim_SetListIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
6117 Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
6119 Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
6120 int shared, i, idx;
6122 varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
6123 if (objPtr == NULL)
6124 return JIM_ERR;
6125 if ((shared = Jim_IsShared(objPtr)))
6126 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6127 for (i = 0; i < indexc - 1; i++) {
6128 listObjPtr = objPtr;
6129 if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
6130 goto err;
6131 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_ERRMSG) != JIM_OK) {
6132 goto err;
6134 if (Jim_IsShared(objPtr)) {
6135 objPtr = Jim_DuplicateObj(interp, objPtr);
6136 ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
6138 Jim_InvalidateStringRep(listObjPtr);
6140 if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
6141 goto err;
6142 if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
6143 goto err;
6144 Jim_InvalidateStringRep(objPtr);
6145 Jim_InvalidateStringRep(varObjPtr);
6146 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
6147 goto err;
6148 Jim_SetResult(interp, varObjPtr);
6149 return JIM_OK;
6150 err:
6151 if (shared) {
6152 Jim_FreeNewObj(interp, varObjPtr);
6154 return JIM_ERR;
6157 Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
6159 int i;
6161 /* If all the objects in objv are lists,
6162 * it's possible to return a list as result, that's the
6163 * concatenation of all the lists. */
6164 for (i = 0; i < objc; i++) {
6165 if (!Jim_IsList(objv[i]))
6166 break;
6168 if (i == objc) {
6169 Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
6171 for (i = 0; i < objc; i++)
6172 Jim_ListAppendList(interp, objPtr, objv[i]);
6173 return objPtr;
6175 else {
6176 /* Else... we have to glue strings together */
6177 int len = 0, objLen;
6178 char *bytes, *p;
6180 /* Compute the length */
6181 for (i = 0; i < objc; i++) {
6182 Jim_GetString(objv[i], &objLen);
6183 len += objLen;
6185 if (objc)
6186 len += objc - 1;
6187 /* Create the string rep, and a string object holding it. */
6188 p = bytes = Jim_Alloc(len + 1);
6189 for (i = 0; i < objc; i++) {
6190 const char *s = Jim_GetString(objv[i], &objLen);
6192 /* Remove leading space */
6193 while (objLen && (*s == ' ' || *s == '\t' || *s == '\n')) {
6194 s++;
6195 objLen--;
6196 len--;
6198 /* And trailing space */
6199 while (objLen && (s[objLen - 1] == ' ' ||
6200 s[objLen - 1] == '\n' || s[objLen - 1] == '\t')) {
6201 /* Handle trailing backslash-space case */
6202 if (objLen > 1 && s[objLen - 2] == '\\') {
6203 break;
6205 objLen--;
6206 len--;
6208 memcpy(p, s, objLen);
6209 p += objLen;
6210 if (objLen && i + 1 != objc) {
6211 *p++ = ' ';
6213 else if (i + 1 != objc) {
6214 /* Drop the space calcuated for this
6215 * element that is instead null. */
6216 len--;
6219 *p = '\0';
6220 return Jim_NewStringObjNoAlloc(interp, bytes, len);
6224 /* Returns a list composed of the elements in the specified range.
6225 * first and start are directly accepted as Jim_Objects and
6226 * processed for the end?-index? case. */
6227 Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
6228 Jim_Obj *lastObjPtr)
6230 int first, last;
6231 int len, rangeLen;
6233 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
6234 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
6235 return NULL;
6236 len = Jim_ListLength(interp, listObjPtr); /* will convert into list */
6237 first = JimRelToAbsIndex(len, first);
6238 last = JimRelToAbsIndex(len, last);
6239 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
6240 if (first == 0 && last == len) {
6241 return listObjPtr;
6243 return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
6246 /* -----------------------------------------------------------------------------
6247 * Dict object
6248 * ---------------------------------------------------------------------------*/
6249 static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
6250 static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
6251 static void UpdateStringOfDict(struct Jim_Obj *objPtr);
6252 static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6254 /* Dict HashTable Type.
6256 * Keys and Values are Jim objects. */
6258 static unsigned int JimObjectHTHashFunction(const void *key)
6260 const char *str;
6261 Jim_Obj *objPtr = (Jim_Obj *)key;
6262 int len;
6264 str = Jim_GetString(objPtr, &len);
6265 return Jim_GenHashFunction((unsigned char *)str, len);
6268 static int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
6270 JIM_NOTUSED(privdata);
6272 return Jim_StringEqObj((Jim_Obj *)key1, (Jim_Obj *)key2);
6275 static void JimObjectHTKeyValDestructor(void *interp, void *val)
6277 Jim_Obj *objPtr = val;
6279 Jim_DecrRefCount(interp, objPtr);
6282 static const Jim_HashTableType JimDictHashTableType = {
6283 JimObjectHTHashFunction, /* hash function */
6284 NULL, /* key dup */
6285 NULL, /* val dup */
6286 JimObjectHTKeyCompare, /* key compare */
6287 (void (*)(void *, const void *)) /* ATTENTION: const cast */
6288 JimObjectHTKeyValDestructor, /* key destructor */
6289 JimObjectHTKeyValDestructor /* val destructor */
6292 /* Note that while the elements of the dict may contain references,
6293 * the list object itself can't. This basically means that the
6294 * dict object string representation as a whole can't contain references
6295 * that are not presents in the single elements. */
6296 static const Jim_ObjType dictObjType = {
6297 "dict",
6298 FreeDictInternalRep,
6299 DupDictInternalRep,
6300 UpdateStringOfDict,
6301 JIM_TYPE_NONE,
6304 void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
6306 JIM_NOTUSED(interp);
6308 Jim_FreeHashTable(objPtr->internalRep.ptr);
6309 Jim_Free(objPtr->internalRep.ptr);
6312 void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
6314 Jim_HashTable *ht, *dupHt;
6315 Jim_HashTableIterator *htiter;
6316 Jim_HashEntry *he;
6318 /* Create a new hash table */
6319 ht = srcPtr->internalRep.ptr;
6320 dupHt = Jim_Alloc(sizeof(*dupHt));
6321 Jim_InitHashTable(dupHt, &JimDictHashTableType, interp);
6322 if (ht->size != 0)
6323 Jim_ExpandHashTable(dupHt, ht->size);
6324 /* Copy every element from the source to the dup hash table */
6325 htiter = Jim_GetHashTableIterator(ht);
6326 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6327 const Jim_Obj *keyObjPtr = he->key;
6328 Jim_Obj *valObjPtr = he->u.val;
6330 Jim_IncrRefCount((Jim_Obj *)keyObjPtr); /* ATTENTION: const cast */
6331 Jim_IncrRefCount(valObjPtr);
6332 Jim_AddHashEntry(dupHt, keyObjPtr, valObjPtr);
6334 Jim_FreeHashTableIterator(htiter);
6336 dupPtr->internalRep.ptr = dupHt;
6337 dupPtr->typePtr = &dictObjType;
6340 void UpdateStringOfDict(struct Jim_Obj *objPtr)
6342 int i, bufLen, realLength;
6343 const char *strRep;
6344 char *p;
6345 int *quotingType, objc;
6346 Jim_HashTable *ht;
6347 Jim_HashTableIterator *htiter;
6348 Jim_HashEntry *he;
6349 Jim_Obj **objv;
6351 /* Trun the hash table into a flat vector of Jim_Objects. */
6352 ht = objPtr->internalRep.ptr;
6353 objc = ht->used * 2;
6354 objv = Jim_Alloc(objc * sizeof(Jim_Obj *));
6355 htiter = Jim_GetHashTableIterator(ht);
6356 i = 0;
6357 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6358 objv[i++] = (Jim_Obj *)he->key; /* ATTENTION: const cast */
6359 objv[i++] = he->u.val;
6361 Jim_FreeHashTableIterator(htiter);
6362 /* (Over) Estimate the space needed. */
6363 quotingType = Jim_Alloc(sizeof(int) * objc);
6364 bufLen = 0;
6365 for (i = 0; i < objc; i++) {
6366 int len;
6368 strRep = Jim_GetString(objv[i], &len);
6369 quotingType[i] = ListElementQuotingType(strRep, len);
6370 switch (quotingType[i]) {
6371 case JIM_ELESTR_SIMPLE:
6372 bufLen += len;
6373 break;
6374 case JIM_ELESTR_BRACE:
6375 bufLen += len + 2;
6376 break;
6377 case JIM_ELESTR_QUOTE:
6378 bufLen += len * 2;
6379 break;
6381 bufLen++; /* elements separator. */
6383 bufLen++;
6385 /* Generate the string rep. */
6386 p = objPtr->bytes = Jim_Alloc(bufLen + 1);
6387 realLength = 0;
6388 for (i = 0; i < objc; i++) {
6389 int len, qlen;
6390 char *q;
6392 strRep = Jim_GetString(objv[i], &len);
6394 switch (quotingType[i]) {
6395 case JIM_ELESTR_SIMPLE:
6396 memcpy(p, strRep, len);
6397 p += len;
6398 realLength += len;
6399 break;
6400 case JIM_ELESTR_BRACE:
6401 *p++ = '{';
6402 memcpy(p, strRep, len);
6403 p += len;
6404 *p++ = '}';
6405 realLength += len + 2;
6406 break;
6407 case JIM_ELESTR_QUOTE:
6408 q = BackslashQuoteString(strRep, len, &qlen);
6409 memcpy(p, q, qlen);
6410 Jim_Free(q);
6411 p += qlen;
6412 realLength += qlen;
6413 break;
6415 /* Add a separating space */
6416 if (i + 1 != objc) {
6417 *p++ = ' ';
6418 realLength++;
6421 *p = '\0'; /* nul term. */
6422 objPtr->length = realLength;
6423 Jim_Free(quotingType);
6424 Jim_Free(objv);
6427 static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
6429 int listlen;
6431 /* Get the string representation. Do this first so we don't
6432 * change order in case of fast conversion to dict.
6434 Jim_String(objPtr);
6436 /* For simplicity, convert a non-list object to a list and then to a dict */
6437 listlen = Jim_ListLength(interp, objPtr);
6438 if (listlen % 2) {
6439 Jim_SetResultString(interp,
6440 "invalid dictionary value: must be a list with an even number of elements", -1);
6441 return JIM_ERR;
6443 else {
6444 /* Now it is easy to convert to a dict from a list, and it can't fail */
6445 Jim_HashTable *ht;
6446 int i;
6448 ht = Jim_Alloc(sizeof(*ht));
6449 Jim_InitHashTable(ht, &JimDictHashTableType, interp);
6451 for (i = 0; i < listlen; i += 2) {
6452 Jim_Obj *keyObjPtr;
6453 Jim_Obj *valObjPtr;
6455 Jim_ListIndex(interp, objPtr, i, &keyObjPtr, JIM_NONE);
6456 Jim_ListIndex(interp, objPtr, i + 1, &valObjPtr, JIM_NONE);
6458 Jim_IncrRefCount(keyObjPtr);
6459 Jim_IncrRefCount(valObjPtr);
6461 if (Jim_AddHashEntry(ht, keyObjPtr, valObjPtr) != JIM_OK) {
6462 Jim_HashEntry *he;
6464 he = Jim_FindHashEntry(ht, keyObjPtr);
6465 Jim_DecrRefCount(interp, keyObjPtr);
6466 /* ATTENTION: const cast */
6467 Jim_DecrRefCount(interp, (Jim_Obj *)he->u.val);
6468 he->u.val = valObjPtr;
6472 Jim_FreeIntRep(interp, objPtr);
6473 objPtr->typePtr = &dictObjType;
6474 objPtr->internalRep.ptr = ht;
6476 return JIM_OK;
6480 /* Dict object API */
6482 /* Add an element to a dict. objPtr must be of the "dict" type.
6483 * The higer-level exported function is Jim_DictAddElement().
6484 * If an element with the specified key already exists, the value
6485 * associated is replaced with the new one.
6487 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6488 static int DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
6489 Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
6491 Jim_HashTable *ht = objPtr->internalRep.ptr;
6493 if (valueObjPtr == NULL) { /* unset */
6494 return Jim_DeleteHashEntry(ht, keyObjPtr);
6496 Jim_IncrRefCount(keyObjPtr);
6497 Jim_IncrRefCount(valueObjPtr);
6498 if (Jim_AddHashEntry(ht, keyObjPtr, valueObjPtr) != JIM_OK) {
6499 Jim_HashEntry *he = Jim_FindHashEntry(ht, keyObjPtr);
6501 Jim_DecrRefCount(interp, keyObjPtr);
6502 /* ATTENTION: const cast */
6503 Jim_DecrRefCount(interp, (Jim_Obj *)he->u.val);
6504 he->u.val = valueObjPtr;
6506 return JIM_OK;
6509 /* Add an element, higher-level interface for DictAddElement().
6510 * If valueObjPtr == NULL, the key is removed if it exists. */
6511 int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
6512 Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
6514 int retcode;
6516 JimPanic((Jim_IsShared(objPtr), "Jim_DictAddElement called with shared object"));
6517 if (objPtr->typePtr != &dictObjType) {
6518 if (SetDictFromAny(interp, objPtr) != JIM_OK)
6519 return JIM_ERR;
6521 retcode = DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
6522 Jim_InvalidateStringRep(objPtr);
6523 return retcode;
6526 Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
6528 Jim_Obj *objPtr;
6529 int i;
6531 JimPanic((len % 2, "Jim_NewDictObj() 'len' argument must be even"));
6533 objPtr = Jim_NewObj(interp);
6534 objPtr->typePtr = &dictObjType;
6535 objPtr->bytes = NULL;
6536 objPtr->internalRep.ptr = Jim_Alloc(sizeof(Jim_HashTable));
6537 Jim_InitHashTable(objPtr->internalRep.ptr, &JimDictHashTableType, interp);
6538 for (i = 0; i < len; i += 2)
6539 DictAddElement(interp, objPtr, elements[i], elements[i + 1]);
6540 return objPtr;
6543 /* Return the value associated to the specified dict key
6544 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6546 int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
6547 Jim_Obj **objPtrPtr, int flags)
6549 Jim_HashEntry *he;
6550 Jim_HashTable *ht;
6552 if (dictPtr->typePtr != &dictObjType) {
6553 if (SetDictFromAny(interp, dictPtr) != JIM_OK)
6554 return -1;
6556 ht = dictPtr->internalRep.ptr;
6557 if ((he = Jim_FindHashEntry(ht, keyPtr)) == NULL) {
6558 if (flags & JIM_ERRMSG) {
6559 Jim_SetResultFormatted(interp, "key \"%#s\" not found in dictionary", keyPtr);
6561 return JIM_ERR;
6563 *objPtrPtr = he->u.val;
6564 return JIM_OK;
6567 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6568 int Jim_DictPairs(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj ***objPtrPtr, int *len)
6570 Jim_HashTable *ht;
6571 Jim_HashTableIterator *htiter;
6572 Jim_HashEntry *he;
6573 Jim_Obj **objv;
6574 int i;
6576 if (dictPtr->typePtr != &dictObjType) {
6577 if (SetDictFromAny(interp, dictPtr) != JIM_OK)
6578 return JIM_ERR;
6580 ht = dictPtr->internalRep.ptr;
6582 /* Turn the hash table into a flat vector of Jim_Objects. */
6583 objv = Jim_Alloc((ht->used * 2) * sizeof(Jim_Obj *));
6584 htiter = Jim_GetHashTableIterator(ht);
6585 i = 0;
6586 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
6587 objv[i++] = (Jim_Obj *)he->key; /* ATTENTION: const cast */
6588 objv[i++] = he->u.val;
6590 *len = i;
6591 Jim_FreeHashTableIterator(htiter);
6592 *objPtrPtr = objv;
6593 return JIM_OK;
6597 /* Return the value associated to the specified dict keys */
6598 int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
6599 Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
6601 int i;
6603 if (keyc == 0) {
6604 *objPtrPtr = dictPtr;
6605 return JIM_OK;
6608 for (i = 0; i < keyc; i++) {
6609 Jim_Obj *objPtr;
6611 if (Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags)
6612 != JIM_OK)
6613 return JIM_ERR;
6614 dictPtr = objPtr;
6616 *objPtrPtr = dictPtr;
6617 return JIM_OK;
6620 /* Modify the dict stored into the variable named 'varNamePtr'
6621 * setting the element specified by the 'keyc' keys objects in 'keyv',
6622 * with the new value of the element 'newObjPtr'.
6624 * If newObjPtr == NULL the operation is to remove the given key
6625 * from the dictionary.
6627 * If flags & JIM_ERRMSG, then failure to remove the key is considered an error
6628 * and JIM_ERR is returned. Otherwise it is ignored and JIM_OK is returned.
6630 int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
6631 Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr, int flags)
6633 Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
6634 int shared, i;
6636 varObjPtr = objPtr =
6637 Jim_GetVariable(interp, varNamePtr, newObjPtr == NULL ? JIM_ERRMSG : JIM_NONE);
6638 if (objPtr == NULL) {
6639 if (newObjPtr == NULL) /* Cannot remove a key from non existing var */ {
6640 return JIM_ERR;
6642 varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
6643 if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
6644 Jim_FreeNewObj(interp, varObjPtr);
6645 return JIM_ERR;
6648 if ((shared = Jim_IsShared(objPtr)))
6649 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6650 for (i = 0; i < keyc - 1; i++) {
6651 dictObjPtr = objPtr;
6653 /* Check if it's a valid dictionary */
6654 if (dictObjPtr->typePtr != &dictObjType) {
6655 if (SetDictFromAny(interp, dictObjPtr) != JIM_OK) {
6656 goto err;
6659 /* Check if the given key exists. */
6660 Jim_InvalidateStringRep(dictObjPtr);
6661 if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
6662 newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
6663 /* This key exists at the current level.
6664 * Make sure it's not shared!. */
6665 if (Jim_IsShared(objPtr)) {
6666 objPtr = Jim_DuplicateObj(interp, objPtr);
6667 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6670 else {
6671 /* Key not found. If it's an [unset] operation
6672 * this is an error. Only the last key may not
6673 * exist. */
6674 if (newObjPtr == NULL) {
6675 goto err;
6677 /* Otherwise set an empty dictionary
6678 * as key's value. */
6679 objPtr = Jim_NewDictObj(interp, NULL, 0);
6680 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6683 /* Note error on unset with missing last key is OK */
6684 if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
6685 if (newObjPtr || (flags & JIM_ERRMSG)) {
6686 goto err;
6689 Jim_InvalidateStringRep(objPtr);
6690 Jim_InvalidateStringRep(varObjPtr);
6691 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK) {
6692 goto err;
6694 Jim_SetResult(interp, varObjPtr);
6695 return JIM_OK;
6696 err:
6697 if (shared) {
6698 Jim_FreeNewObj(interp, varObjPtr);
6700 return JIM_ERR;
6703 /* -----------------------------------------------------------------------------
6704 * Index object
6705 * ---------------------------------------------------------------------------*/
6706 static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
6707 static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6709 static const Jim_ObjType indexObjType = {
6710 "index",
6711 NULL,
6712 NULL,
6713 UpdateStringOfIndex,
6714 JIM_TYPE_NONE,
6717 void UpdateStringOfIndex(struct Jim_Obj *objPtr)
6719 int len;
6720 char buf[JIM_INTEGER_SPACE + 1];
6722 if (objPtr->internalRep.indexValue >= 0)
6723 len = sprintf(buf, "%d", objPtr->internalRep.indexValue);
6724 else if (objPtr->internalRep.indexValue == -1)
6725 len = sprintf(buf, "end");
6726 else {
6727 len = sprintf(buf, "end%d", objPtr->internalRep.indexValue + 1);
6729 objPtr->bytes = Jim_Alloc(len + 1);
6730 memcpy(objPtr->bytes, buf, len + 1);
6731 objPtr->length = len;
6734 int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6736 int idx, end = 0;
6737 const char *str;
6738 char *endptr;
6740 /* Get the string representation */
6741 str = Jim_String(objPtr);
6743 /* Try to convert into an index */
6744 if (strncmp(str, "end", 3) == 0) {
6745 end = 1;
6746 str += 3;
6747 idx = 0;
6749 else {
6750 idx = strtol(str, &endptr, 10);
6752 if (endptr == str) {
6753 goto badindex;
6755 str = endptr;
6758 /* Now str may include or +<num> or -<num> */
6759 if (*str == '+' || *str == '-') {
6760 int sign = (*str == '+' ? 1 : -1);
6762 idx += sign * strtol(++str, &endptr, 10);
6763 if (str == endptr || *endptr) {
6764 goto badindex;
6766 str = endptr;
6768 /* The only thing left should be spaces */
6769 while (isspace(UCHAR(*str))) {
6770 str++;
6772 if (*str) {
6773 goto badindex;
6775 if (end) {
6776 if (idx > 0) {
6777 idx = INT_MAX;
6779 else {
6780 /* end-1 is repesented as -2 */
6781 idx--;
6784 else if (idx < 0) {
6785 idx = -INT_MAX;
6788 /* Free the old internal repr and set the new one. */
6789 Jim_FreeIntRep(interp, objPtr);
6790 objPtr->typePtr = &indexObjType;
6791 objPtr->internalRep.indexValue = idx;
6792 return JIM_OK;
6794 badindex:
6795 Jim_SetResultFormatted(interp,
6796 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr);
6797 return JIM_ERR;
6800 int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
6802 /* Avoid shimmering if the object is an integer. */
6803 if (objPtr->typePtr == &intObjType) {
6804 jim_wide val = JimWideValue(objPtr);
6806 if (!(val < LONG_MIN) && !(val > LONG_MAX)) {
6807 *indexPtr = (val < 0) ? -INT_MAX : (long)val;;
6808 return JIM_OK;
6811 if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
6812 return JIM_ERR;
6813 *indexPtr = objPtr->internalRep.indexValue;
6814 return JIM_OK;
6817 /* -----------------------------------------------------------------------------
6818 * Return Code Object.
6819 * ---------------------------------------------------------------------------*/
6821 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6822 static const char * const jimReturnCodes[] = {
6823 [JIM_OK] = "ok",
6824 [JIM_ERR] = "error",
6825 [JIM_RETURN] = "return",
6826 [JIM_BREAK] = "break",
6827 [JIM_CONTINUE] = "continue",
6828 [JIM_SIGNAL] = "signal",
6829 [JIM_EXIT] = "exit",
6830 [JIM_EVAL] = "eval",
6831 NULL
6834 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6836 static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
6838 static const Jim_ObjType returnCodeObjType = {
6839 "return-code",
6840 NULL,
6841 NULL,
6842 NULL,
6843 JIM_TYPE_NONE,
6846 /* Converts a (standard) return code to a string. Returns "?" for
6847 * non-standard return codes.
6849 const char *Jim_ReturnCode(int code)
6851 if (code < 0 || code >= (int)jimReturnCodesSize) {
6852 return "?";
6854 else {
6855 return jimReturnCodes[code];
6859 int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6861 int returnCode;
6862 jim_wide wideValue;
6864 /* Try to convert into an integer */
6865 if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
6866 returnCode = (int)wideValue;
6867 else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
6868 Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
6869 return JIM_ERR;
6871 /* Free the old internal repr and set the new one. */
6872 Jim_FreeIntRep(interp, objPtr);
6873 objPtr->typePtr = &returnCodeObjType;
6874 objPtr->internalRep.returnCode = returnCode;
6875 return JIM_OK;
6878 int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
6880 if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
6881 return JIM_ERR;
6882 *intPtr = objPtr->internalRep.returnCode;
6883 return JIM_OK;
6886 /* -----------------------------------------------------------------------------
6887 * Expression Parsing
6888 * ---------------------------------------------------------------------------*/
6889 static int JimParseExprOperator(struct JimParserCtx *pc);
6890 static int JimParseExprNumber(struct JimParserCtx *pc);
6891 static int JimParseExprIrrational(struct JimParserCtx *pc);
6893 /* Exrp's Stack machine operators opcodes. */
6895 /* Binary operators (numbers) */
6896 enum
6898 /* Continues on from the JIM_TT_ space */
6899 /* Operations */
6900 JIM_EXPROP_MUL = JIM_TT_EXPR_OP, /* 15 */
6901 JIM_EXPROP_DIV,
6902 JIM_EXPROP_MOD,
6903 JIM_EXPROP_SUB,
6904 JIM_EXPROP_ADD,
6905 JIM_EXPROP_LSHIFT,
6906 JIM_EXPROP_RSHIFT,
6907 JIM_EXPROP_ROTL,
6908 JIM_EXPROP_ROTR,
6909 JIM_EXPROP_LT,
6910 JIM_EXPROP_GT,
6911 JIM_EXPROP_LTE,
6912 JIM_EXPROP_GTE,
6913 JIM_EXPROP_NUMEQ,
6914 JIM_EXPROP_NUMNE,
6915 JIM_EXPROP_BITAND, /* 30 */
6916 JIM_EXPROP_BITXOR,
6917 JIM_EXPROP_BITOR,
6919 /* Note must keep these together */
6920 JIM_EXPROP_LOGICAND, /* 33 */
6921 JIM_EXPROP_LOGICAND_LEFT,
6922 JIM_EXPROP_LOGICAND_RIGHT,
6924 /* and these */
6925 JIM_EXPROP_LOGICOR, /* 36 */
6926 JIM_EXPROP_LOGICOR_LEFT,
6927 JIM_EXPROP_LOGICOR_RIGHT,
6929 /* and these */
6930 /* Ternary operators */
6931 JIM_EXPROP_TERNARY, /* 39 */
6932 JIM_EXPROP_TERNARY_LEFT,
6933 JIM_EXPROP_TERNARY_RIGHT,
6935 /* and these */
6936 JIM_EXPROP_COLON, /* 42 */
6937 JIM_EXPROP_COLON_LEFT,
6938 JIM_EXPROP_COLON_RIGHT,
6940 JIM_EXPROP_POW, /* 45 */
6942 /* Binary operators (strings) */
6943 JIM_EXPROP_STREQ,
6944 JIM_EXPROP_STRNE,
6945 JIM_EXPROP_STRIN,
6946 JIM_EXPROP_STRNI,
6948 /* Unary operators (numbers) */
6949 JIM_EXPROP_NOT,
6950 JIM_EXPROP_BITNOT,
6951 JIM_EXPROP_UNARYMINUS,
6952 JIM_EXPROP_UNARYPLUS,
6954 /* Functions */
6955 JIM_EXPROP_FUNC_FIRST,
6956 JIM_EXPROP_FUNC_INT = JIM_EXPROP_FUNC_FIRST,
6957 JIM_EXPROP_FUNC_ABS,
6958 JIM_EXPROP_FUNC_DOUBLE,
6959 JIM_EXPROP_FUNC_ROUND,
6960 JIM_EXPROP_FUNC_RAND,
6961 JIM_EXPROP_FUNC_SRAND,
6963 #ifdef JIM_MATH_FUNCTIONS
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 #endif
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 wC = JimPowWide(wA, wB);
7316 break;
7317 case JIM_EXPROP_ADD:
7318 wC = wA + wB;
7319 break;
7320 case JIM_EXPROP_SUB:
7321 wC = wA - wB;
7322 break;
7323 case JIM_EXPROP_MUL:
7324 wC = wA * wB;
7325 break;
7326 case JIM_EXPROP_DIV:
7327 if (wB == 0) {
7328 Jim_SetResultString(interp, "Division by zero", -1);
7329 rc = JIM_ERR;
7331 else {
7333 * From Tcl 8.x
7335 * This code is tricky: C doesn't guarantee much
7336 * about the quotient or remainder, but Tcl does.
7337 * The remainder always has the same sign as the
7338 * divisor and a smaller absolute value.
7340 if (wB < 0) {
7341 wB = -wB;
7342 wA = -wA;
7344 wC = wA / wB;
7345 if (wA % wB < 0) {
7346 wC--;
7349 break;
7350 case JIM_EXPROP_LT:
7351 wC = wA < wB;
7352 break;
7353 case JIM_EXPROP_GT:
7354 wC = wA > wB;
7355 break;
7356 case JIM_EXPROP_LTE:
7357 wC = wA <= wB;
7358 break;
7359 case JIM_EXPROP_GTE:
7360 wC = wA >= wB;
7361 break;
7362 case JIM_EXPROP_NUMEQ:
7363 wC = wA == wB;
7364 break;
7365 case JIM_EXPROP_NUMNE:
7366 wC = wA != wB;
7367 break;
7368 default:
7369 abort();
7372 else if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
7373 switch (e->opcode) {
7374 case JIM_EXPROP_POW:
7375 #ifdef JIM_MATH_FUNCTIONS
7376 dC = pow(dA, dB);
7377 #else
7378 Jim_SetResultString(interp, "unsupported", -1);
7379 rc = JIM_ERR;
7380 #endif
7381 break;
7382 case JIM_EXPROP_ADD:
7383 dC = dA + dB;
7384 break;
7385 case JIM_EXPROP_SUB:
7386 dC = dA - dB;
7387 break;
7388 case JIM_EXPROP_MUL:
7389 dC = dA * dB;
7390 break;
7391 case JIM_EXPROP_DIV:
7392 if (dB == 0) {
7393 #ifdef INFINITY
7394 dC = dA < 0 ? -INFINITY : INFINITY;
7395 #else
7396 dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
7397 #endif
7399 else {
7400 dC = dA / dB;
7402 break;
7403 case JIM_EXPROP_LT:
7404 wC = dA < dB;
7405 intresult = 1;
7406 break;
7407 case JIM_EXPROP_GT:
7408 wC = dA > dB;
7409 intresult = 1;
7410 break;
7411 case JIM_EXPROP_LTE:
7412 wC = dA <= dB;
7413 intresult = 1;
7414 break;
7415 case JIM_EXPROP_GTE:
7416 wC = dA >= dB;
7417 intresult = 1;
7418 break;
7419 case JIM_EXPROP_NUMEQ:
7420 wC = dA == dB;
7421 intresult = 1;
7422 break;
7423 case JIM_EXPROP_NUMNE:
7424 wC = dA != dB;
7425 intresult = 1;
7426 break;
7427 default:
7428 abort();
7431 else {
7432 /* Handle the string case */
7434 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7435 int i = Jim_StringCompareObj(interp, A, B, 0);
7437 intresult = 1;
7439 switch (e->opcode) {
7440 case JIM_EXPROP_LT:
7441 wC = i < 0;
7442 break;
7443 case JIM_EXPROP_GT:
7444 wC = i > 0;
7445 break;
7446 case JIM_EXPROP_LTE:
7447 wC = i <= 0;
7448 break;
7449 case JIM_EXPROP_GTE:
7450 wC = i >= 0;
7451 break;
7452 case JIM_EXPROP_NUMEQ:
7453 wC = i == 0;
7454 break;
7455 case JIM_EXPROP_NUMNE:
7456 wC = i != 0;
7457 break;
7458 default:
7459 rc = JIM_ERR;
7460 break;
7464 if (rc == JIM_OK) {
7465 if (intresult) {
7466 ExprPush(e, Jim_NewIntObj(interp, wC));
7468 else {
7469 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7473 Jim_DecrRefCount(interp, A);
7474 Jim_DecrRefCount(interp, B);
7476 return rc;
7479 static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
7481 int listlen;
7482 int i;
7484 listlen = Jim_ListLength(interp, listObjPtr);
7485 for (i = 0; i < listlen; i++) {
7486 Jim_Obj *objPtr;
7488 Jim_ListIndex(interp, listObjPtr, i, &objPtr, JIM_NONE);
7490 if (Jim_StringEqObj(objPtr, valObj)) {
7491 return 1;
7494 return 0;
7497 static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprState *e)
7499 Jim_Obj *B = ExprPop(e);
7500 Jim_Obj *A = ExprPop(e);
7502 jim_wide wC;
7504 switch (e->opcode) {
7505 case JIM_EXPROP_STREQ:
7506 case JIM_EXPROP_STRNE: {
7507 int Alen, Blen;
7508 const char *sA = Jim_GetString(A, &Alen);
7509 const char *sB = Jim_GetString(B, &Blen);
7511 if (e->opcode == JIM_EXPROP_STREQ) {
7512 wC = (Alen == Blen && memcmp(sA, sB, Alen) == 0);
7514 else {
7515 wC = (Alen != Blen || memcmp(sA, sB, Alen) != 0);
7517 break;
7519 case JIM_EXPROP_STRIN:
7520 wC = JimSearchList(interp, B, A);
7521 break;
7522 case JIM_EXPROP_STRNI:
7523 wC = !JimSearchList(interp, B, A);
7524 break;
7525 default:
7526 abort();
7528 ExprPush(e, Jim_NewIntObj(interp, wC));
7530 Jim_DecrRefCount(interp, A);
7531 Jim_DecrRefCount(interp, B);
7533 return JIM_OK;
7536 static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
7538 long l;
7539 double d;
7541 if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
7542 return l != 0;
7544 if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
7545 return d != 0;
7547 return -1;
7550 static int JimExprOpAndLeft(Jim_Interp *interp, struct JimExprState *e)
7552 Jim_Obj *skip = ExprPop(e);
7553 Jim_Obj *A = ExprPop(e);
7554 int rc = JIM_OK;
7556 switch (ExprBool(interp, A)) {
7557 case 0:
7558 /* false, so skip RHS opcodes with a 0 result */
7559 e->skip = JimWideValue(skip);
7560 ExprPush(e, Jim_NewIntObj(interp, 0));
7561 break;
7563 case 1:
7564 /* true so continue */
7565 break;
7567 case -1:
7568 /* Invalid */
7569 rc = JIM_ERR;
7571 Jim_DecrRefCount(interp, A);
7572 Jim_DecrRefCount(interp, skip);
7574 return rc;
7577 static int JimExprOpOrLeft(Jim_Interp *interp, struct JimExprState *e)
7579 Jim_Obj *skip = ExprPop(e);
7580 Jim_Obj *A = ExprPop(e);
7581 int rc = JIM_OK;
7583 switch (ExprBool(interp, A)) {
7584 case 0:
7585 /* false, so do nothing */
7586 break;
7588 case 1:
7589 /* true so skip RHS opcodes with a 1 result */
7590 e->skip = JimWideValue(skip);
7591 ExprPush(e, Jim_NewIntObj(interp, 1));
7592 break;
7594 case -1:
7595 /* Invalid */
7596 rc = JIM_ERR;
7597 break;
7599 Jim_DecrRefCount(interp, A);
7600 Jim_DecrRefCount(interp, skip);
7602 return rc;
7605 static int JimExprOpAndOrRight(Jim_Interp *interp, struct JimExprState *e)
7607 Jim_Obj *A = ExprPop(e);
7608 int rc = JIM_OK;
7610 switch (ExprBool(interp, A)) {
7611 case 0:
7612 ExprPush(e, Jim_NewIntObj(interp, 0));
7613 break;
7615 case 1:
7616 ExprPush(e, Jim_NewIntObj(interp, 1));
7617 break;
7619 case -1:
7620 /* Invalid */
7621 rc = JIM_ERR;
7622 break;
7624 Jim_DecrRefCount(interp, A);
7626 return rc;
7629 static int JimExprOpTernaryLeft(Jim_Interp *interp, struct JimExprState *e)
7631 Jim_Obj *skip = ExprPop(e);
7632 Jim_Obj *A = ExprPop(e);
7633 int rc = JIM_OK;
7635 /* Repush A */
7636 ExprPush(e, A);
7638 switch (ExprBool(interp, A)) {
7639 case 0:
7640 /* false, skip RHS opcodes */
7641 e->skip = JimWideValue(skip);
7642 /* Push a dummy value */
7643 ExprPush(e, Jim_NewIntObj(interp, 0));
7644 break;
7646 case 1:
7647 /* true so do nothing */
7648 break;
7650 case -1:
7651 /* Invalid */
7652 rc = JIM_ERR;
7653 break;
7655 Jim_DecrRefCount(interp, A);
7656 Jim_DecrRefCount(interp, skip);
7658 return rc;
7661 static int JimExprOpColonLeft(Jim_Interp *interp, struct JimExprState *e)
7663 Jim_Obj *skip = ExprPop(e);
7664 Jim_Obj *B = ExprPop(e);
7665 Jim_Obj *A = ExprPop(e);
7667 /* No need to check for A as non-boolean */
7668 if (ExprBool(interp, A)) {
7669 /* true, so skip RHS opcodes */
7670 e->skip = JimWideValue(skip);
7671 /* Repush B as the answer */
7672 ExprPush(e, B);
7675 Jim_DecrRefCount(interp, skip);
7676 Jim_DecrRefCount(interp, A);
7677 Jim_DecrRefCount(interp, B);
7678 return JIM_OK;
7681 static int JimExprOpNull(Jim_Interp *interp, struct JimExprState *e)
7683 return JIM_OK;
7686 enum
7688 LAZY_NONE,
7689 LAZY_OP,
7690 LAZY_LEFT,
7691 LAZY_RIGHT
7694 /* name - precedence - arity - opcode */
7695 static const struct Jim_ExprOperator Jim_ExprOperators[] = {
7696 [JIM_EXPROP_FUNC_INT] = {"int", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7697 [JIM_EXPROP_FUNC_DOUBLE] = {"double", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7698 [JIM_EXPROP_FUNC_ABS] = {"abs", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7699 [JIM_EXPROP_FUNC_ROUND] = {"round", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7700 [JIM_EXPROP_FUNC_RAND] = {"rand", 400, 0, JimExprOpNone, LAZY_NONE},
7701 [JIM_EXPROP_FUNC_SRAND] = {"srand", 400, 1, JimExprOpIntUnary, LAZY_NONE},
7703 #ifdef JIM_MATH_FUNCTIONS
7704 [JIM_EXPROP_FUNC_SIN] = {"sin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7705 [JIM_EXPROP_FUNC_COS] = {"cos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7706 [JIM_EXPROP_FUNC_TAN] = {"tan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7707 [JIM_EXPROP_FUNC_ASIN] = {"asin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7708 [JIM_EXPROP_FUNC_ACOS] = {"acos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7709 [JIM_EXPROP_FUNC_ATAN] = {"atan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7710 [JIM_EXPROP_FUNC_SINH] = {"sinh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7711 [JIM_EXPROP_FUNC_COSH] = {"cosh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7712 [JIM_EXPROP_FUNC_TANH] = {"tanh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7713 [JIM_EXPROP_FUNC_CEIL] = {"ceil", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7714 [JIM_EXPROP_FUNC_FLOOR] = {"floor", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7715 [JIM_EXPROP_FUNC_EXP] = {"exp", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7716 [JIM_EXPROP_FUNC_LOG] = {"log", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7717 [JIM_EXPROP_FUNC_LOG10] = {"log10", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7718 [JIM_EXPROP_FUNC_SQRT] = {"sqrt", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7719 #endif
7721 [JIM_EXPROP_NOT] = {"!", 300, 1, JimExprOpNumUnary, LAZY_NONE},
7722 [JIM_EXPROP_BITNOT] = {"~", 300, 1, JimExprOpIntUnary, LAZY_NONE},
7723 [JIM_EXPROP_UNARYMINUS] = {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7724 [JIM_EXPROP_UNARYPLUS] = {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7726 [JIM_EXPROP_POW] = {"**", 250, 2, JimExprOpBin, LAZY_NONE},
7728 [JIM_EXPROP_MUL] = {"*", 200, 2, JimExprOpBin, LAZY_NONE},
7729 [JIM_EXPROP_DIV] = {"/", 200, 2, JimExprOpBin, LAZY_NONE},
7730 [JIM_EXPROP_MOD] = {"%", 200, 2, JimExprOpIntBin, LAZY_NONE},
7732 [JIM_EXPROP_SUB] = {"-", 100, 2, JimExprOpBin, LAZY_NONE},
7733 [JIM_EXPROP_ADD] = {"+", 100, 2, JimExprOpBin, LAZY_NONE},
7735 [JIM_EXPROP_ROTL] = {"<<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7736 [JIM_EXPROP_ROTR] = {">>>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7737 [JIM_EXPROP_LSHIFT] = {"<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7738 [JIM_EXPROP_RSHIFT] = {">>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7740 [JIM_EXPROP_LT] = {"<", 80, 2, JimExprOpBin, LAZY_NONE},
7741 [JIM_EXPROP_GT] = {">", 80, 2, JimExprOpBin, LAZY_NONE},
7742 [JIM_EXPROP_LTE] = {"<=", 80, 2, JimExprOpBin, LAZY_NONE},
7743 [JIM_EXPROP_GTE] = {">=", 80, 2, JimExprOpBin, LAZY_NONE},
7745 [JIM_EXPROP_NUMEQ] = {"==", 70, 2, JimExprOpBin, LAZY_NONE},
7746 [JIM_EXPROP_NUMNE] = {"!=", 70, 2, JimExprOpBin, LAZY_NONE},
7748 [JIM_EXPROP_STREQ] = {"eq", 60, 2, JimExprOpStrBin, LAZY_NONE},
7749 [JIM_EXPROP_STRNE] = {"ne", 60, 2, JimExprOpStrBin, LAZY_NONE},
7751 [JIM_EXPROP_STRIN] = {"in", 55, 2, JimExprOpStrBin, LAZY_NONE},
7752 [JIM_EXPROP_STRNI] = {"ni", 55, 2, JimExprOpStrBin, LAZY_NONE},
7754 [JIM_EXPROP_BITAND] = {"&", 50, 2, JimExprOpIntBin, LAZY_NONE},
7755 [JIM_EXPROP_BITXOR] = {"^", 49, 2, JimExprOpIntBin, LAZY_NONE},
7756 [JIM_EXPROP_BITOR] = {"|", 48, 2, JimExprOpIntBin, LAZY_NONE},
7758 [JIM_EXPROP_LOGICAND] = {"&&", 10, 2, NULL, LAZY_OP},
7759 [JIM_EXPROP_LOGICOR] = {"||", 9, 2, NULL, LAZY_OP},
7761 [JIM_EXPROP_TERNARY] = {"?", 5, 2, JimExprOpNull, LAZY_OP},
7762 [JIM_EXPROP_COLON] = {":", 5, 2, JimExprOpNull, LAZY_OP},
7764 /* private operators */
7765 [JIM_EXPROP_TERNARY_LEFT] = {NULL, 5, 2, JimExprOpTernaryLeft, LAZY_LEFT},
7766 [JIM_EXPROP_TERNARY_RIGHT] = {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7767 [JIM_EXPROP_COLON_LEFT] = {NULL, 5, 2, JimExprOpColonLeft, LAZY_LEFT},
7768 [JIM_EXPROP_COLON_RIGHT] = {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7769 [JIM_EXPROP_LOGICAND_LEFT] = {NULL, 10, 2, JimExprOpAndLeft, LAZY_LEFT},
7770 [JIM_EXPROP_LOGICAND_RIGHT] = {NULL, 10, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7771 [JIM_EXPROP_LOGICOR_LEFT] = {NULL, 9, 2, JimExprOpOrLeft, LAZY_LEFT},
7772 [JIM_EXPROP_LOGICOR_RIGHT] = {NULL, 9, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7775 #define JIM_EXPR_OPERATORS_NUM \
7776 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7778 static int JimParseExpression(struct JimParserCtx *pc)
7780 /* Discard spaces and quoted newline */
7781 while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
7782 if (*pc->p == '\n') {
7783 pc->linenr++;
7785 pc->p++;
7786 pc->len--;
7789 if (pc->len == 0) {
7790 pc->tstart = pc->tend = pc->p;
7791 pc->tline = pc->linenr;
7792 pc->tt = JIM_TT_EOL;
7793 pc->eof = 1;
7794 return JIM_OK;
7796 switch (*(pc->p)) {
7797 case '(':
7798 pc->tstart = pc->tend = pc->p;
7799 pc->tline = pc->linenr;
7800 pc->tt = JIM_TT_SUBEXPR_START;
7801 pc->p++;
7802 pc->len--;
7803 break;
7804 case ')':
7805 pc->tstart = pc->tend = pc->p;
7806 pc->tline = pc->linenr;
7807 pc->tt = JIM_TT_SUBEXPR_END;
7808 pc->p++;
7809 pc->len--;
7810 break;
7811 case '[':
7812 return JimParseCmd(pc);
7813 case '$':
7814 if (JimParseVar(pc) == JIM_ERR)
7815 return JimParseExprOperator(pc);
7816 else {
7817 /* Don't allow expr sugar in expressions */
7818 if (pc->tt == JIM_TT_EXPRSUGAR) {
7819 return JIM_ERR;
7821 return JIM_OK;
7823 break;
7824 case '0':
7825 case '1':
7826 case '2':
7827 case '3':
7828 case '4':
7829 case '5':
7830 case '6':
7831 case '7':
7832 case '8':
7833 case '9':
7834 case '.':
7835 return JimParseExprNumber(pc);
7836 case '"':
7837 return JimParseQuote(pc);
7838 case '{':
7839 return JimParseBrace(pc);
7841 case 'N':
7842 case 'I':
7843 case 'n':
7844 case 'i':
7845 if (JimParseExprIrrational(pc) == JIM_ERR)
7846 return JimParseExprOperator(pc);
7847 break;
7848 default:
7849 return JimParseExprOperator(pc);
7850 break;
7852 return JIM_OK;
7855 static int JimParseExprNumber(struct JimParserCtx *pc)
7857 int allowdot = 1;
7858 int allowhex = 0;
7860 /* Assume an integer for now */
7861 pc->tt = JIM_TT_EXPR_INT;
7862 pc->tstart = pc->p;
7863 pc->tline = pc->linenr;
7864 while (isdigit(UCHAR(*pc->p))
7865 || (allowhex && isxdigit(UCHAR(*pc->p)))
7866 || (allowdot && *pc->p == '.')
7867 || (pc->p - pc->tstart == 1 && *pc->tstart == '0' && (*pc->p == 'x' || *pc->p == 'X'))
7869 if ((*pc->p == 'x') || (*pc->p == 'X')) {
7870 allowhex = 1;
7871 allowdot = 0;
7873 if (*pc->p == '.') {
7874 allowdot = 0;
7875 pc->tt = JIM_TT_EXPR_DOUBLE;
7877 pc->p++;
7878 pc->len--;
7879 if (!allowhex && (*pc->p == 'e' || *pc->p == 'E') && (pc->p[1] == '-' || pc->p[1] == '+'
7880 || isdigit(UCHAR(pc->p[1])))) {
7881 pc->p += 2;
7882 pc->len -= 2;
7883 pc->tt = JIM_TT_EXPR_DOUBLE;
7886 pc->tend = pc->p - 1;
7887 return JIM_OK;
7890 static int JimParseExprIrrational(struct JimParserCtx *pc)
7892 const char *Tokens[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
7893 const char **token;
7895 for (token = Tokens; *token != NULL; token++) {
7896 int len = strlen(*token);
7898 if (strncmp(*token, pc->p, len) == 0) {
7899 pc->tstart = pc->p;
7900 pc->tend = pc->p + len - 1;
7901 pc->p += len;
7902 pc->len -= len;
7903 pc->tline = pc->linenr;
7904 pc->tt = JIM_TT_EXPR_DOUBLE;
7905 return JIM_OK;
7908 return JIM_ERR;
7911 static int JimParseExprOperator(struct JimParserCtx *pc)
7913 int i;
7914 int bestIdx = -1, bestLen = 0;
7916 /* Try to get the longest match. */
7917 for (i = JIM_TT_EXPR_OP; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
7918 const char *opname;
7919 int oplen;
7921 opname = Jim_ExprOperators[i].name;
7922 if (opname == NULL) {
7923 continue;
7925 oplen = strlen(opname);
7927 if (strncmp(opname, pc->p, oplen) == 0 && oplen > bestLen) {
7928 bestIdx = i;
7929 bestLen = oplen;
7932 if (bestIdx == -1) {
7933 return JIM_ERR;
7936 /* Validate paretheses around function arguments */
7937 if (bestIdx >= JIM_EXPROP_FUNC_FIRST) {
7938 const char *p = pc->p + bestLen;
7939 int len = pc->len - bestLen;
7941 while (len && isspace(UCHAR(*p))) {
7942 len--;
7943 p++;
7945 if (*p != '(') {
7946 return JIM_ERR;
7949 pc->tstart = pc->p;
7950 pc->tend = pc->p + bestLen - 1;
7951 pc->p += bestLen;
7952 pc->len -= bestLen;
7953 pc->tline = pc->linenr;
7955 pc->tt = bestIdx;
7956 return JIM_OK;
7959 static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
7961 return &Jim_ExprOperators[opcode];
7964 const char *jim_tt_name(int type)
7966 static const char * const tt_names[JIM_TT_EXPR_OP] =
7967 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", "INT",
7968 "DBL", "$()" };
7969 if (type < JIM_TT_EXPR_OP) {
7970 return tt_names[type];
7972 else {
7973 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(type);
7974 static char buf[20];
7976 if (op && op->name) {
7977 return op->name;
7979 sprintf(buf, "(%d)", type);
7980 return buf;
7984 /* -----------------------------------------------------------------------------
7985 * Expression Object
7986 * ---------------------------------------------------------------------------*/
7987 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
7988 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
7989 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
7991 static const Jim_ObjType exprObjType = {
7992 "expression",
7993 FreeExprInternalRep,
7994 DupExprInternalRep,
7995 NULL,
7996 JIM_TYPE_REFERENCES,
7999 /* Expr bytecode structure */
8000 typedef struct ExprByteCode
8002 int len; /* Length as number of tokens. */
8003 ScriptToken *token; /* Tokens array. */
8004 int inUse; /* Used for sharing. */
8005 } ExprByteCode;
8007 static void ExprFreeByteCode(Jim_Interp *interp, ExprByteCode * expr)
8009 int i;
8011 for (i = 0; i < expr->len; i++) {
8012 Jim_DecrRefCount(interp, expr->token[i].objPtr);
8014 Jim_Free(expr->token);
8015 Jim_Free(expr);
8018 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8020 ExprByteCode *expr = (void *)objPtr->internalRep.ptr;
8022 if (expr) {
8023 if (--expr->inUse != 0) {
8024 return;
8027 ExprFreeByteCode(interp, expr);
8031 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8033 JIM_NOTUSED(interp);
8034 JIM_NOTUSED(srcPtr);
8036 /* Just returns an simple string. */
8037 dupPtr->typePtr = NULL;
8040 /* Check if an expr program looks correct. */
8041 static int ExprCheckCorrectness(ExprByteCode * expr)
8043 int i;
8044 int stacklen = 0;
8045 int ternary = 0;
8047 /* Try to check if there are stack underflows,
8048 * and make sure at the end of the program there is
8049 * a single result on the stack. */
8050 for (i = 0; i < expr->len; i++) {
8051 ScriptToken *t = &expr->token[i];
8052 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8054 if (op) {
8055 stacklen -= op->arity;
8056 if (stacklen < 0) {
8057 break;
8059 if (t->type == JIM_EXPROP_TERNARY || t->type == JIM_EXPROP_TERNARY_LEFT) {
8060 ternary++;
8062 else if (t->type == JIM_EXPROP_COLON || t->type == JIM_EXPROP_COLON_LEFT) {
8063 ternary--;
8067 /* All operations and operands add one to the stack */
8068 stacklen++;
8070 if (stacklen != 1 || ternary != 0) {
8071 return JIM_ERR;
8073 return JIM_OK;
8076 /* This procedure converts every occurrence of || and && opereators
8077 * in lazy unary versions.
8079 * a b || is converted into:
8081 * a <offset> |L b |R
8083 * a b && is converted into:
8085 * a <offset> &L b &R
8087 * "|L" checks if 'a' is true:
8088 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8089 * the opcode just after |R.
8090 * 2) if it is false does nothing.
8091 * "|R" checks if 'b' is true:
8092 * 1) if it is true pushes 1, otherwise pushes 0.
8094 * "&L" checks if 'a' is true:
8095 * 1) if it is true does nothing.
8096 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8097 * the opcode just after &R
8098 * "&R" checks if 'a' is true:
8099 * if it is true pushes 1, otherwise pushes 0.
8101 static int ExprAddLazyOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8103 int i;
8105 int leftindex, arity, offset;
8107 /* Search for the end of the first operator */
8108 leftindex = expr->len - 1;
8110 arity = 1;
8111 while (arity) {
8112 ScriptToken *tt = &expr->token[leftindex];
8114 if (tt->type >= JIM_TT_EXPR_OP) {
8115 arity += JimExprOperatorInfoByOpcode(tt->type)->arity;
8117 arity--;
8118 if (--leftindex < 0) {
8119 return JIM_ERR;
8122 leftindex++;
8124 /* Move them up */
8125 memmove(&expr->token[leftindex + 2], &expr->token[leftindex],
8126 sizeof(*expr->token) * (expr->len - leftindex));
8127 expr->len += 2;
8128 offset = (expr->len - leftindex) - 1;
8130 /* Now we rely on the fact the the left and right version have opcodes
8131 * 1 and 2 after the main opcode respectively
8133 expr->token[leftindex + 1].type = t->type + 1;
8134 expr->token[leftindex + 1].objPtr = interp->emptyObj;
8136 expr->token[leftindex].type = JIM_TT_EXPR_INT;
8137 expr->token[leftindex].objPtr = Jim_NewIntObj(interp, offset);
8139 /* Now add the 'R' operator */
8140 expr->token[expr->len].objPtr = interp->emptyObj;
8141 expr->token[expr->len].type = t->type + 2;
8142 expr->len++;
8144 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8145 for (i = leftindex - 1; i > 0; i--) {
8146 if (JimExprOperatorInfoByOpcode(expr->token[i].type)->lazy == LAZY_LEFT) {
8147 if (JimWideValue(expr->token[i - 1].objPtr) + i - 1 >= leftindex) {
8148 JimWideValue(expr->token[i - 1].objPtr) += 2;
8152 return JIM_OK;
8155 static int ExprAddOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8157 struct ScriptToken *token = &expr->token[expr->len];
8158 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8160 if (op->lazy == LAZY_OP) {
8161 if (ExprAddLazyOperator(interp, expr, t) != JIM_OK) {
8162 Jim_SetResultFormatted(interp, "Expression has bad operands to %s", op->name);
8163 return JIM_ERR;
8166 else {
8167 token->objPtr = interp->emptyObj;
8168 token->type = t->type;
8169 expr->len++;
8171 return JIM_OK;
8175 * Returns the index of the COLON_LEFT to the left of 'right_index'
8176 * taking into account nesting.
8178 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8180 static int ExprTernaryGetColonLeftIndex(ExprByteCode *expr, int right_index)
8182 int ternary_count = 1;
8184 right_index--;
8186 while (right_index > 1) {
8187 if (expr->token[right_index].type == JIM_EXPROP_TERNARY_LEFT) {
8188 ternary_count--;
8190 else if (expr->token[right_index].type == JIM_EXPROP_COLON_RIGHT) {
8191 ternary_count++;
8193 else if (expr->token[right_index].type == JIM_EXPROP_COLON_LEFT && ternary_count == 1) {
8194 return right_index;
8196 right_index--;
8199 /*notreached*/
8200 return -1;
8204 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8206 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8207 * Otherwise returns 0.
8209 static int ExprTernaryGetMoveIndices(ExprByteCode *expr, int right_index, int *prev_right_index, int *prev_left_index)
8211 int i = right_index - 1;
8212 int ternary_count = 1;
8214 while (i > 1) {
8215 if (expr->token[i].type == JIM_EXPROP_TERNARY_LEFT) {
8216 if (--ternary_count == 0 && expr->token[i - 2].type == JIM_EXPROP_COLON_RIGHT) {
8217 *prev_right_index = i - 2;
8218 *prev_left_index = ExprTernaryGetColonLeftIndex(expr, *prev_right_index);
8219 return 1;
8222 else if (expr->token[i].type == JIM_EXPROP_COLON_RIGHT) {
8223 if (ternary_count == 0) {
8224 return 0;
8226 ternary_count++;
8228 i--;
8230 return 0;
8234 * ExprTernaryReorderExpression description
8235 * ========================================
8237 * ?: is right-to-left associative which doesn't work with the stack-based
8238 * expression engine. The fix is to reorder the bytecode.
8240 * The expression:
8242 * expr 1?2:0?3:4
8244 * Has initial bytecode:
8246 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8247 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8249 * The fix involves simulating this expression instead:
8251 * expr 1?2:(0?3:4)
8253 * With the following bytecode:
8255 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8256 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8258 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8259 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8260 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8261 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8263 * ExprTernaryReorderExpression works thus as follows :
8264 * - start from the end of the stack
8265 * - while walking towards the beginning of the stack
8266 * if token=JIM_EXPROP_COLON_RIGHT then
8267 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8268 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8269 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8270 * if all found then
8271 * perform the rotation
8272 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8273 * end if
8274 * end if
8276 * Note: care has to be taken for nested ternary constructs!!!
8278 static void ExprTernaryReorderExpression(Jim_Interp *interp, ExprByteCode *expr)
8280 int i;
8282 for (i = expr->len - 1; i > 1; i--) {
8283 int prev_right_index;
8284 int prev_left_index;
8285 int j;
8286 ScriptToken tmp;
8288 if (expr->token[i].type != JIM_EXPROP_COLON_RIGHT) {
8289 continue;
8292 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8293 if (ExprTernaryGetMoveIndices(expr, i, &prev_right_index, &prev_left_index) == 0) {
8294 continue;
8298 ** rotate tokens down
8300 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8301 ** | | |
8302 ** | V V
8303 ** | [...] : ...
8304 ** | | |
8305 ** | V V
8306 ** | [...] : ...
8307 ** | | |
8308 ** | V V
8309 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8311 tmp = expr->token[prev_right_index];
8312 for (j = prev_right_index; j < i; j++) {
8313 expr->token[j] = expr->token[j + 1];
8315 expr->token[i] = tmp;
8317 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8319 * This is 'colon left increment' = i - prev_right_index
8321 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8322 * [prev_left_index-1] : skip_count
8325 JimWideValue(expr->token[prev_left_index-1].objPtr) += (i - prev_right_index);
8327 /* Adjust for i-- in the loop */
8328 i++;
8332 static ExprByteCode *ExprCreateByteCode(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *fileNameObj)
8334 Jim_Stack stack;
8335 ExprByteCode *expr;
8336 int ok = 1;
8337 int i;
8338 int prevtt = JIM_TT_NONE;
8339 int have_ternary = 0;
8341 /* -1 for EOL */
8342 int count = tokenlist->count - 1;
8344 expr = Jim_Alloc(sizeof(*expr));
8345 expr->inUse = 1;
8346 expr->len = 0;
8348 Jim_InitStack(&stack);
8350 /* Need extra bytecodes for lazy operators.
8351 * Also check for the ternary operator
8353 for (i = 0; i < tokenlist->count; i++) {
8354 ParseToken *t = &tokenlist->list[i];
8356 if (JimExprOperatorInfoByOpcode(t->type)->lazy == LAZY_OP) {
8357 count += 2;
8358 /* Ternary is a lazy op but also needs reordering */
8359 if (t->type == JIM_EXPROP_TERNARY) {
8360 have_ternary = 1;
8365 expr->token = Jim_Alloc(sizeof(ScriptToken) * count);
8367 for (i = 0; i < tokenlist->count && ok; i++) {
8368 ParseToken *t = &tokenlist->list[i];
8370 /* Next token will be stored here */
8371 struct ScriptToken *token = &expr->token[expr->len];
8373 if (t->type == JIM_TT_EOL) {
8374 break;
8377 switch (t->type) {
8378 case JIM_TT_STR:
8379 case JIM_TT_ESC:
8380 case JIM_TT_VAR:
8381 case JIM_TT_DICTSUGAR:
8382 case JIM_TT_EXPRSUGAR:
8383 case JIM_TT_CMD:
8384 token->objPtr = Jim_NewStringObj(interp, t->token, t->len);
8385 token->type = t->type;
8386 if (t->type == JIM_TT_CMD) {
8387 /* Only commands need source info */
8388 JimSetSourceInfo(interp, token->objPtr, fileNameObj, t->line);
8390 expr->len++;
8391 break;
8393 case JIM_TT_EXPR_INT:
8394 token->objPtr = Jim_NewIntObj(interp, strtoull(t->token, NULL, 0));
8395 token->type = t->type;
8396 expr->len++;
8397 break;
8399 case JIM_TT_EXPR_DOUBLE:
8400 token->objPtr = Jim_NewDoubleObj(interp, strtod(t->token, NULL));
8401 token->type = t->type;
8402 expr->len++;
8403 break;
8405 case JIM_TT_SUBEXPR_START:
8406 Jim_StackPush(&stack, t);
8407 prevtt = JIM_TT_NONE;
8408 continue;
8410 case JIM_TT_SUBEXPR_END:
8411 ok = 0;
8412 while (Jim_StackLen(&stack)) {
8413 ParseToken *tt = Jim_StackPop(&stack);
8415 if (tt->type == JIM_TT_SUBEXPR_START) {
8416 ok = 1;
8417 break;
8420 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8421 goto err;
8424 if (!ok) {
8425 Jim_SetResultString(interp, "Unexpected close parenthesis", -1);
8426 goto err;
8428 break;
8431 default:{
8432 /* Must be an operator */
8433 const struct Jim_ExprOperator *op;
8434 ParseToken *tt;
8436 /* Convert -/+ to unary minus or unary plus if necessary */
8437 if (prevtt == JIM_TT_NONE || prevtt >= JIM_TT_EXPR_OP) {
8438 if (t->type == JIM_EXPROP_SUB) {
8439 t->type = JIM_EXPROP_UNARYMINUS;
8441 else if (t->type == JIM_EXPROP_ADD) {
8442 t->type = JIM_EXPROP_UNARYPLUS;
8446 op = JimExprOperatorInfoByOpcode(t->type);
8448 /* Now handle precedence */
8449 while ((tt = Jim_StackPeek(&stack)) != NULL) {
8450 const struct Jim_ExprOperator *tt_op =
8451 JimExprOperatorInfoByOpcode(tt->type);
8453 /* Note that right-to-left associativity of ?: operator is handled later */
8455 if (op->arity != 1 && tt_op->precedence >= op->precedence) {
8456 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8457 ok = 0;
8458 goto err;
8460 Jim_StackPop(&stack);
8462 else {
8463 break;
8466 Jim_StackPush(&stack, t);
8467 break;
8470 prevtt = t->type;
8473 /* Reduce any remaining subexpr */
8474 while (Jim_StackLen(&stack)) {
8475 ParseToken *tt = Jim_StackPop(&stack);
8477 if (tt->type == JIM_TT_SUBEXPR_START) {
8478 ok = 0;
8479 Jim_SetResultString(interp, "Missing close parenthesis", -1);
8480 goto err;
8482 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8483 ok = 0;
8484 goto err;
8488 if (have_ternary) {
8489 ExprTernaryReorderExpression(interp, expr);
8492 err:
8493 /* Free the stack used for the compilation. */
8494 Jim_FreeStack(&stack);
8496 for (i = 0; i < expr->len; i++) {
8497 Jim_IncrRefCount(expr->token[i].objPtr);
8500 if (!ok) {
8501 ExprFreeByteCode(interp, expr);
8502 return NULL;
8505 return expr;
8509 /* This method takes the string representation of an expression
8510 * and generates a program for the Expr's stack-based VM. */
8511 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
8513 int exprTextLen;
8514 const char *exprText;
8515 struct JimParserCtx parser;
8516 struct ExprByteCode *expr;
8517 ParseTokenList tokenlist;
8518 int line;
8519 Jim_Obj *fileNameObj;
8520 int rc = JIM_ERR;
8522 /* Try to get information about filename / line number */
8523 if (objPtr->typePtr == &sourceObjType) {
8524 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
8525 line = objPtr->internalRep.sourceValue.lineNumber;
8527 else {
8528 fileNameObj = interp->emptyObj;
8529 line = 1;
8531 Jim_IncrRefCount(fileNameObj);
8533 exprText = Jim_GetString(objPtr, &exprTextLen);
8535 /* Initially tokenise the expression into tokenlist */
8536 ScriptTokenListInit(&tokenlist);
8538 JimParserInit(&parser, exprText, exprTextLen, line);
8539 while (!parser.eof) {
8540 if (JimParseExpression(&parser) != JIM_OK) {
8541 ScriptTokenListFree(&tokenlist);
8542 invalidexpr:
8543 Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
8544 expr = NULL;
8545 goto err;
8548 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
8549 parser.tline);
8552 #ifdef DEBUG_SHOW_EXPR_TOKENS
8554 int i;
8555 printf("==== Expr Tokens ====\n");
8556 for (i = 0; i < tokenlist.count; i++) {
8557 printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
8558 tokenlist.list[i].len, tokenlist.list[i].token);
8561 #endif
8563 /* Now create the expression bytecode from the tokenlist */
8564 expr = ExprCreateByteCode(interp, &tokenlist, fileNameObj);
8566 /* No longer need the token list */
8567 ScriptTokenListFree(&tokenlist);
8569 if (!expr) {
8570 goto err;
8573 #ifdef DEBUG_SHOW_EXPR
8575 int i;
8577 printf("==== Expr ====\n");
8578 for (i = 0; i < expr->len; i++) {
8579 ScriptToken *t = &expr->token[i];
8581 printf("[%2d] %s '%s'\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
8584 #endif
8586 /* Check program correctness. */
8587 if (ExprCheckCorrectness(expr) != JIM_OK) {
8588 ExprFreeByteCode(interp, expr);
8589 goto invalidexpr;
8592 rc = JIM_OK;
8594 err:
8595 /* Free the old internal rep and set the new one. */
8596 Jim_DecrRefCount(interp, fileNameObj);
8597 Jim_FreeIntRep(interp, objPtr);
8598 Jim_SetIntRepPtr(objPtr, expr);
8599 objPtr->typePtr = &exprObjType;
8600 return rc;
8603 static ExprByteCode *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
8605 if (objPtr->typePtr != &exprObjType) {
8606 if (SetExprFromAny(interp, objPtr) != JIM_OK) {
8607 return NULL;
8610 return (ExprByteCode *) Jim_GetIntRepPtr(objPtr);
8613 /* -----------------------------------------------------------------------------
8614 * Expressions evaluation.
8615 * Jim uses a specialized stack-based virtual machine for expressions,
8616 * that takes advantage of the fact that expr's operators
8617 * can't be redefined.
8619 * Jim_EvalExpression() uses the bytecode compiled by
8620 * SetExprFromAny() method of the "expression" object.
8622 * On success a Tcl Object containing the result of the evaluation
8623 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8624 * returned.
8625 * On error the function returns a retcode != to JIM_OK and set a suitable
8626 * error on the interp.
8627 * ---------------------------------------------------------------------------*/
8628 #define JIM_EE_STATICSTACK_LEN 10
8630 int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr, Jim_Obj **exprResultPtrPtr)
8632 ExprByteCode *expr;
8633 Jim_Obj *staticStack[JIM_EE_STATICSTACK_LEN];
8634 int i;
8635 int retcode = JIM_OK;
8636 struct JimExprState e;
8638 expr = JimGetExpression(interp, exprObjPtr);
8639 if (!expr) {
8640 return JIM_ERR; /* error in expression. */
8643 #ifdef JIM_OPTIMIZATION
8644 /* Check for one of the following common expressions used by while/for
8646 * CONST
8647 * $a
8648 * !$a
8649 * $a < CONST, $a < $b
8650 * $a <= CONST, $a <= $b
8651 * $a > CONST, $a > $b
8652 * $a >= CONST, $a >= $b
8653 * $a != CONST, $a != $b
8654 * $a == CONST, $a == $b
8657 Jim_Obj *objPtr;
8659 /* STEP 1 -- Check if there are the conditions to run the specialized
8660 * version of while */
8662 switch (expr->len) {
8663 case 1:
8664 if (expr->token[0].type == JIM_TT_EXPR_INT) {
8665 *exprResultPtrPtr = expr->token[0].objPtr;
8666 Jim_IncrRefCount(*exprResultPtrPtr);
8667 return JIM_OK;
8669 if (expr->token[0].type == JIM_TT_VAR) {
8670 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_ERRMSG);
8671 if (objPtr) {
8672 *exprResultPtrPtr = objPtr;
8673 Jim_IncrRefCount(*exprResultPtrPtr);
8674 return JIM_OK;
8677 break;
8679 case 2:
8680 if (expr->token[1].type == JIM_EXPROP_NOT && expr->token[0].type == JIM_TT_VAR) {
8681 jim_wide wideValue;
8683 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8684 if (objPtr && JimIsWide(objPtr)
8685 && Jim_GetWide(interp, objPtr, &wideValue) == JIM_OK) {
8686 *exprResultPtrPtr = wideValue ? interp->falseObj : interp->trueObj;
8687 Jim_IncrRefCount(*exprResultPtrPtr);
8688 return JIM_OK;
8691 break;
8693 case 3:
8694 if (expr->token[0].type == JIM_TT_VAR && (expr->token[1].type == JIM_TT_EXPR_INT
8695 || expr->token[1].type == JIM_TT_VAR)) {
8696 switch (expr->token[2].type) {
8697 case JIM_EXPROP_LT:
8698 case JIM_EXPROP_LTE:
8699 case JIM_EXPROP_GT:
8700 case JIM_EXPROP_GTE:
8701 case JIM_EXPROP_NUMEQ:
8702 case JIM_EXPROP_NUMNE:{
8703 /* optimise ok */
8704 jim_wide wideValueA;
8705 jim_wide wideValueB;
8707 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8708 if (objPtr && JimIsWide(objPtr)
8709 && Jim_GetWide(interp, objPtr, &wideValueA) == JIM_OK) {
8710 if (expr->token[1].type == JIM_TT_VAR) {
8711 objPtr =
8712 Jim_GetVariable(interp, expr->token[1].objPtr,
8713 JIM_NONE);
8715 else {
8716 objPtr = expr->token[1].objPtr;
8718 if (objPtr && JimIsWide(objPtr)
8719 && Jim_GetWide(interp, objPtr, &wideValueB) == JIM_OK) {
8720 int cmpRes;
8722 switch (expr->token[2].type) {
8723 case JIM_EXPROP_LT:
8724 cmpRes = wideValueA < wideValueB;
8725 break;
8726 case JIM_EXPROP_LTE:
8727 cmpRes = wideValueA <= wideValueB;
8728 break;
8729 case JIM_EXPROP_GT:
8730 cmpRes = wideValueA > wideValueB;
8731 break;
8732 case JIM_EXPROP_GTE:
8733 cmpRes = wideValueA >= wideValueB;
8734 break;
8735 case JIM_EXPROP_NUMEQ:
8736 cmpRes = wideValueA == wideValueB;
8737 break;
8738 case JIM_EXPROP_NUMNE:
8739 cmpRes = wideValueA != wideValueB;
8740 break;
8741 default: /*notreached */
8742 cmpRes = 0;
8744 *exprResultPtrPtr =
8745 cmpRes ? interp->trueObj : interp->falseObj;
8746 Jim_IncrRefCount(*exprResultPtrPtr);
8747 return JIM_OK;
8753 break;
8756 #endif
8758 /* In order to avoid that the internal repr gets freed due to
8759 * shimmering of the exprObjPtr's object, we make the internal rep
8760 * shared. */
8761 expr->inUse++;
8763 /* The stack-based expr VM itself */
8765 /* Stack allocation. Expr programs have the feature that
8766 * a program of length N can't require a stack longer than
8767 * N. */
8768 if (expr->len > JIM_EE_STATICSTACK_LEN)
8769 e.stack = Jim_Alloc(sizeof(Jim_Obj *) * expr->len);
8770 else
8771 e.stack = staticStack;
8773 e.stacklen = 0;
8775 /* Execute every instruction */
8776 for (i = 0; i < expr->len && retcode == JIM_OK; i++) {
8777 Jim_Obj *objPtr;
8779 switch (expr->token[i].type) {
8780 case JIM_TT_EXPR_INT:
8781 case JIM_TT_EXPR_DOUBLE:
8782 case JIM_TT_STR:
8783 ExprPush(&e, expr->token[i].objPtr);
8784 break;
8786 case JIM_TT_VAR:
8787 objPtr = Jim_GetVariable(interp, expr->token[i].objPtr, JIM_ERRMSG);
8788 if (objPtr) {
8789 ExprPush(&e, objPtr);
8791 else {
8792 retcode = JIM_ERR;
8794 break;
8796 case JIM_TT_DICTSUGAR:
8797 objPtr = JimExpandDictSugar(interp, expr->token[i].objPtr);
8798 if (objPtr) {
8799 ExprPush(&e, objPtr);
8801 else {
8802 retcode = JIM_ERR;
8804 break;
8806 case JIM_TT_ESC:
8807 retcode = Jim_SubstObj(interp, expr->token[i].objPtr, &objPtr, JIM_NONE);
8808 if (retcode == JIM_OK) {
8809 ExprPush(&e, objPtr);
8811 break;
8813 case JIM_TT_CMD:
8814 retcode = Jim_EvalObj(interp, expr->token[i].objPtr);
8815 if (retcode == JIM_OK) {
8816 ExprPush(&e, Jim_GetResult(interp));
8818 break;
8820 default:{
8821 /* Find and execute the operation */
8822 e.skip = 0;
8823 e.opcode = expr->token[i].type;
8825 retcode = JimExprOperatorInfoByOpcode(e.opcode)->funcop(interp, &e);
8826 /* Skip some opcodes if necessary */
8827 i += e.skip;
8828 continue;
8833 expr->inUse--;
8835 if (retcode == JIM_OK) {
8836 *exprResultPtrPtr = ExprPop(&e);
8838 else {
8839 for (i = 0; i < e.stacklen; i++) {
8840 Jim_DecrRefCount(interp, e.stack[i]);
8843 if (e.stack != staticStack) {
8844 Jim_Free(e.stack);
8846 return retcode;
8849 int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
8851 int retcode;
8852 jim_wide wideValue;
8853 double doubleValue;
8854 Jim_Obj *exprResultPtr;
8856 retcode = Jim_EvalExpression(interp, exprObjPtr, &exprResultPtr);
8857 if (retcode != JIM_OK)
8858 return retcode;
8860 if (JimGetWideNoErr(interp, exprResultPtr, &wideValue) != JIM_OK) {
8861 if (Jim_GetDouble(interp, exprResultPtr, &doubleValue) != JIM_OK) {
8862 Jim_DecrRefCount(interp, exprResultPtr);
8863 return JIM_ERR;
8865 else {
8866 Jim_DecrRefCount(interp, exprResultPtr);
8867 *boolPtr = doubleValue != 0;
8868 return JIM_OK;
8871 *boolPtr = wideValue != 0;
8873 Jim_DecrRefCount(interp, exprResultPtr);
8874 return JIM_OK;
8877 /* -----------------------------------------------------------------------------
8878 * ScanFormat String Object
8879 * ---------------------------------------------------------------------------*/
8881 /* This Jim_Obj will held a parsed representation of a format string passed to
8882 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8883 * to be parsed in its entirely first and then, if correct, can be used for
8884 * scanning. To avoid endless re-parsing, the parsed representation will be
8885 * stored in an internal representation and re-used for performance reason. */
8887 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8888 * scanformat string. This part will later be used to extract information
8889 * out from the string to be parsed by Jim_ScanString */
8891 typedef struct ScanFmtPartDescr
8893 char type; /* Type of conversion (e.g. c, d, f) */
8894 char modifier; /* Modify type (e.g. l - long, h - short */
8895 size_t width; /* Maximal width of input to be converted */
8896 int pos; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8897 char *arg; /* Specification of a CHARSET conversion */
8898 char *prefix; /* Prefix to be scanned literally before conversion */
8899 } ScanFmtPartDescr;
8901 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8902 * string parsed and separated in part descriptions. Furthermore it contains
8903 * the original string representation of the scanformat string to allow for
8904 * fast update of the Jim_Obj's string representation part.
8906 * As an add-on the internal object representation adds some scratch pad area
8907 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8908 * memory for purpose of string scanning.
8910 * The error member points to a static allocated string in case of a mal-
8911 * formed scanformat string or it contains '0' (NULL) in case of a valid
8912 * parse representation.
8914 * The whole memory of the internal representation is allocated as a single
8915 * area of memory that will be internally separated. So freeing and duplicating
8916 * of such an object is cheap */
8918 typedef struct ScanFmtStringObj
8920 jim_wide size; /* Size of internal repr in bytes */
8921 char *stringRep; /* Original string representation */
8922 size_t count; /* Number of ScanFmtPartDescr contained */
8923 size_t convCount; /* Number of conversions that will assign */
8924 size_t maxPos; /* Max position index if XPG3 is used */
8925 const char *error; /* Ptr to error text (NULL if no error */
8926 char *scratch; /* Some scratch pad used by Jim_ScanString */
8927 ScanFmtPartDescr descr[1]; /* The vector of partial descriptions */
8928 } ScanFmtStringObj;
8931 static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
8932 static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
8933 static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
8935 static const Jim_ObjType scanFmtStringObjType = {
8936 "scanformatstring",
8937 FreeScanFmtInternalRep,
8938 DupScanFmtInternalRep,
8939 UpdateStringOfScanFmt,
8940 JIM_TYPE_NONE,
8943 void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8945 JIM_NOTUSED(interp);
8946 Jim_Free((char *)objPtr->internalRep.ptr);
8947 objPtr->internalRep.ptr = 0;
8950 void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8952 size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
8953 ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
8955 JIM_NOTUSED(interp);
8956 memcpy(newVec, srcPtr->internalRep.ptr, size);
8957 dupPtr->internalRep.ptr = newVec;
8958 dupPtr->typePtr = &scanFmtStringObjType;
8961 void UpdateStringOfScanFmt(Jim_Obj *objPtr)
8963 char *bytes = ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep;
8965 objPtr->bytes = Jim_StrDup(bytes);
8966 objPtr->length = strlen(bytes);
8969 /* SetScanFmtFromAny will parse a given string and create the internal
8970 * representation of the format specification. In case of an error
8971 * the error data member of the internal representation will be set
8972 * to an descriptive error text and the function will be left with
8973 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
8974 * specification */
8976 static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
8978 ScanFmtStringObj *fmtObj;
8979 char *buffer;
8980 int maxCount, i, approxSize, lastPos = -1;
8981 const char *fmt = objPtr->bytes;
8982 int maxFmtLen = objPtr->length;
8983 const char *fmtEnd = fmt + maxFmtLen;
8984 int curr;
8986 Jim_FreeIntRep(interp, objPtr);
8987 /* Count how many conversions could take place maximally */
8988 for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
8989 if (fmt[i] == '%')
8990 ++maxCount;
8991 /* Calculate an approximation of the memory necessary */
8992 approxSize = sizeof(ScanFmtStringObj) /* Size of the container */
8993 +(maxCount + 1) * sizeof(ScanFmtPartDescr) /* Size of all partials */
8994 +maxFmtLen * sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
8995 + maxFmtLen * sizeof(char) + 1 /* Original stringrep */
8996 + maxFmtLen * sizeof(char) /* Arg for CHARSETs */
8997 +(maxCount + 1) * sizeof(char) /* '\0' for every partial */
8998 +1; /* safety byte */
8999 fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
9000 memset(fmtObj, 0, approxSize);
9001 fmtObj->size = approxSize;
9002 fmtObj->maxPos = 0;
9003 fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
9004 fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
9005 memcpy(fmtObj->stringRep, fmt, maxFmtLen);
9006 buffer = fmtObj->stringRep + maxFmtLen + 1;
9007 objPtr->internalRep.ptr = fmtObj;
9008 objPtr->typePtr = &scanFmtStringObjType;
9009 for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
9010 int width = 0, skip;
9011 ScanFmtPartDescr *descr = &fmtObj->descr[curr];
9013 fmtObj->count++;
9014 descr->width = 0; /* Assume width unspecified */
9015 /* Overread and store any "literal" prefix */
9016 if (*fmt != '%' || fmt[1] == '%') {
9017 descr->type = 0;
9018 descr->prefix = &buffer[i];
9019 for (; fmt < fmtEnd; ++fmt) {
9020 if (*fmt == '%') {
9021 if (fmt[1] != '%')
9022 break;
9023 ++fmt;
9025 buffer[i++] = *fmt;
9027 buffer[i++] = 0;
9029 /* Skip the conversion introducing '%' sign */
9030 ++fmt;
9031 /* End reached due to non-conversion literal only? */
9032 if (fmt >= fmtEnd)
9033 goto done;
9034 descr->pos = 0; /* Assume "natural" positioning */
9035 if (*fmt == '*') {
9036 descr->pos = -1; /* Okay, conversion will not be assigned */
9037 ++fmt;
9039 else
9040 fmtObj->convCount++; /* Otherwise count as assign-conversion */
9041 /* Check if next token is a number (could be width or pos */
9042 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9043 fmt += skip;
9044 /* Was the number a XPG3 position specifier? */
9045 if (descr->pos != -1 && *fmt == '$') {
9046 int prev;
9048 ++fmt;
9049 descr->pos = width;
9050 width = 0;
9051 /* Look if "natural" postioning and XPG3 one was mixed */
9052 if ((lastPos == 0 && descr->pos > 0)
9053 || (lastPos > 0 && descr->pos == 0)) {
9054 fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
9055 return JIM_ERR;
9057 /* Look if this position was already used */
9058 for (prev = 0; prev < curr; ++prev) {
9059 if (fmtObj->descr[prev].pos == -1)
9060 continue;
9061 if (fmtObj->descr[prev].pos == descr->pos) {
9062 fmtObj->error =
9063 "variable is assigned by multiple \"%n$\" conversion specifiers";
9064 return JIM_ERR;
9067 /* Try to find a width after the XPG3 specifier */
9068 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9069 descr->width = width;
9070 fmt += skip;
9072 if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
9073 fmtObj->maxPos = descr->pos;
9075 else {
9076 /* Number was not a XPG3, so it has to be a width */
9077 descr->width = width;
9080 /* If positioning mode was undetermined yet, fix this */
9081 if (lastPos == -1)
9082 lastPos = descr->pos;
9083 /* Handle CHARSET conversion type ... */
9084 if (*fmt == '[') {
9085 int swapped = 1, beg = i, end, j;
9087 descr->type = '[';
9088 descr->arg = &buffer[i];
9089 ++fmt;
9090 if (*fmt == '^')
9091 buffer[i++] = *fmt++;
9092 if (*fmt == ']')
9093 buffer[i++] = *fmt++;
9094 while (*fmt && *fmt != ']')
9095 buffer[i++] = *fmt++;
9096 if (*fmt != ']') {
9097 fmtObj->error = "unmatched [ in format string";
9098 return JIM_ERR;
9100 end = i;
9101 buffer[i++] = 0;
9102 /* In case a range fence was given "backwards", swap it */
9103 while (swapped) {
9104 swapped = 0;
9105 for (j = beg + 1; j < end - 1; ++j) {
9106 if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
9107 char tmp = buffer[j - 1];
9109 buffer[j - 1] = buffer[j + 1];
9110 buffer[j + 1] = tmp;
9111 swapped = 1;
9116 else {
9117 /* Remember any valid modifier if given */
9118 if (strchr("hlL", *fmt) != 0)
9119 descr->modifier = tolower((int)*fmt++);
9121 descr->type = *fmt;
9122 if (strchr("efgcsndoxui", *fmt) == 0) {
9123 fmtObj->error = "bad scan conversion character";
9124 return JIM_ERR;
9126 else if (*fmt == 'c' && descr->width != 0) {
9127 fmtObj->error = "field width may not be specified in %c " "conversion";
9128 return JIM_ERR;
9130 else if (*fmt == 'u' && descr->modifier == 'l') {
9131 fmtObj->error = "unsigned wide not supported";
9132 return JIM_ERR;
9135 curr++;
9137 done:
9138 return JIM_OK;
9141 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9143 #define FormatGetCnvCount(_fo_) \
9144 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9145 #define FormatGetMaxPos(_fo_) \
9146 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9147 #define FormatGetError(_fo_) \
9148 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9150 /* JimScanAString is used to scan an unspecified string that ends with
9151 * next WS, or a string that is specified via a charset.
9154 static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
9156 char *buffer = Jim_StrDup(str);
9157 char *p = buffer;
9159 while (*str) {
9160 int c;
9161 int n;
9163 if (!sdescr && isspace(UCHAR(*str)))
9164 break; /* EOS via WS if unspecified */
9166 n = utf8_tounicode(str, &c);
9167 if (sdescr && !JimCharsetMatch(sdescr, c, JIM_CHARSET_SCAN))
9168 break;
9169 while (n--)
9170 *p++ = *str++;
9172 *p = 0;
9173 return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
9176 /* ScanOneEntry will scan one entry out of the string passed as argument.
9177 * It use the sscanf() function for this task. After extracting and
9178 * converting of the value, the count of scanned characters will be
9179 * returned of -1 in case of no conversion tool place and string was
9180 * already scanned thru */
9182 static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int strLen,
9183 ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
9185 const char *tok;
9186 const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
9187 size_t scanned = 0;
9188 size_t anchor = pos;
9189 int i;
9190 Jim_Obj *tmpObj = NULL;
9192 /* First pessimistically assume, we will not scan anything :-) */
9193 *valObjPtr = 0;
9194 if (descr->prefix) {
9195 /* There was a prefix given before the conversion, skip it and adjust
9196 * the string-to-be-parsed accordingly */
9197 /* XXX: Should be checking strLen, not str[pos] */
9198 for (i = 0; pos < strLen && descr->prefix[i]; ++i) {
9199 /* If prefix require, skip WS */
9200 if (isspace(UCHAR(descr->prefix[i])))
9201 while (pos < strLen && isspace(UCHAR(str[pos])))
9202 ++pos;
9203 else if (descr->prefix[i] != str[pos])
9204 break; /* Prefix do not match here, leave the loop */
9205 else
9206 ++pos; /* Prefix matched so far, next round */
9208 if (pos >= strLen) {
9209 return -1; /* All of str consumed: EOF condition */
9211 else if (descr->prefix[i] != 0)
9212 return 0; /* Not whole prefix consumed, no conversion possible */
9214 /* For all but following conversion, skip leading WS */
9215 if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
9216 while (isspace(UCHAR(str[pos])))
9217 ++pos;
9218 /* Determine how much skipped/scanned so far */
9219 scanned = pos - anchor;
9221 /* %c is a special, simple case. no width */
9222 if (descr->type == 'n') {
9223 /* Return pseudo conversion means: how much scanned so far? */
9224 *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
9226 else if (pos >= strLen) {
9227 /* Cannot scan anything, as str is totally consumed */
9228 return -1;
9230 else if (descr->type == 'c') {
9231 int c;
9232 scanned += utf8_tounicode(&str[pos], &c);
9233 *valObjPtr = Jim_NewIntObj(interp, c);
9234 return scanned;
9236 else {
9237 /* Processing of conversions follows ... */
9238 if (descr->width > 0) {
9239 /* Do not try to scan as fas as possible but only the given width.
9240 * To ensure this, we copy the part that should be scanned. */
9241 size_t sLen = utf8_strlen(&str[pos], strLen - pos);
9242 size_t tLen = descr->width > sLen ? sLen : descr->width;
9244 tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
9245 tok = tmpObj->bytes;
9247 else {
9248 /* As no width was given, simply refer to the original string */
9249 tok = &str[pos];
9251 switch (descr->type) {
9252 case 'd':
9253 case 'o':
9254 case 'x':
9255 case 'u':
9256 case 'i':{
9257 char *endp; /* Position where the number finished */
9258 jim_wide w;
9260 int base = descr->type == 'o' ? 8
9261 : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
9263 /* Try to scan a number with the given base */
9264 w = strtoull(tok, &endp, base);
9265 if (endp == tok && base == 0) {
9266 /* If scanning failed, and base was undetermined, simply
9267 * put it to 10 and try once more. This should catch the
9268 * case where %i begin to parse a number prefix (e.g.
9269 * '0x' but no further digits follows. This will be
9270 * handled as a ZERO followed by a char 'x' by Tcl */
9271 w = strtoull(tok, &endp, 10);
9274 if (endp != tok) {
9275 /* There was some number sucessfully scanned! */
9276 *valObjPtr = Jim_NewIntObj(interp, w);
9278 /* Adjust the number-of-chars scanned so far */
9279 scanned += endp - tok;
9281 else {
9282 /* Nothing was scanned. We have to determine if this
9283 * happened due to e.g. prefix mismatch or input str
9284 * exhausted */
9285 scanned = *tok ? 0 : -1;
9287 break;
9289 case 's':
9290 case '[':{
9291 *valObjPtr = JimScanAString(interp, descr->arg, tok);
9292 scanned += Jim_Length(*valObjPtr);
9293 break;
9295 case 'e':
9296 case 'f':
9297 case 'g':{
9298 char *endp;
9299 double value = strtod(tok, &endp);
9301 if (endp != tok) {
9302 /* There was some number sucessfully scanned! */
9303 *valObjPtr = Jim_NewDoubleObj(interp, value);
9304 /* Adjust the number-of-chars scanned so far */
9305 scanned += endp - tok;
9307 else {
9308 /* Nothing was scanned. We have to determine if this
9309 * happened due to e.g. prefix mismatch or input str
9310 * exhausted */
9311 scanned = *tok ? 0 : -1;
9313 break;
9316 /* If a substring was allocated (due to pre-defined width) do not
9317 * forget to free it */
9318 if (tmpObj) {
9319 Jim_FreeNewObj(interp, tmpObj);
9322 return scanned;
9325 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9326 * string and returns all converted (and not ignored) values in a list back
9327 * to the caller. If an error occured, a NULL pointer will be returned */
9329 Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
9331 size_t i, pos;
9332 int scanned = 1;
9333 const char *str = Jim_String(strObjPtr);
9334 int strLen = Jim_Utf8Length(interp, strObjPtr);
9335 Jim_Obj *resultList = 0;
9336 Jim_Obj **resultVec = 0;
9337 int resultc;
9338 Jim_Obj *emptyStr = 0;
9339 ScanFmtStringObj *fmtObj;
9341 /* This should never happen. The format object should already be of the correct type */
9342 JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
9344 fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
9345 /* Check if format specification was valid */
9346 if (fmtObj->error != 0) {
9347 if (flags & JIM_ERRMSG)
9348 Jim_SetResultString(interp, fmtObj->error, -1);
9349 return 0;
9351 /* Allocate a new "shared" empty string for all unassigned conversions */
9352 emptyStr = Jim_NewEmptyStringObj(interp);
9353 Jim_IncrRefCount(emptyStr);
9354 /* Create a list and fill it with empty strings up to max specified XPG3 */
9355 resultList = Jim_NewListObj(interp, 0, 0);
9356 if (fmtObj->maxPos > 0) {
9357 for (i = 0; i < fmtObj->maxPos; ++i)
9358 Jim_ListAppendElement(interp, resultList, emptyStr);
9359 JimListGetElements(interp, resultList, &resultc, &resultVec);
9361 /* Now handle every partial format description */
9362 for (i = 0, pos = 0; i < fmtObj->count; ++i) {
9363 ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
9364 Jim_Obj *value = 0;
9366 /* Only last type may be "literal" w/o conversion - skip it! */
9367 if (descr->type == 0)
9368 continue;
9369 /* As long as any conversion could be done, we will proceed */
9370 if (scanned > 0)
9371 scanned = ScanOneEntry(interp, str, pos, strLen, fmtObj, i, &value);
9372 /* In case our first try results in EOF, we will leave */
9373 if (scanned == -1 && i == 0)
9374 goto eof;
9375 /* Advance next pos-to-be-scanned for the amount scanned already */
9376 pos += scanned;
9378 /* value == 0 means no conversion took place so take empty string */
9379 if (value == 0)
9380 value = Jim_NewEmptyStringObj(interp);
9381 /* If value is a non-assignable one, skip it */
9382 if (descr->pos == -1) {
9383 Jim_FreeNewObj(interp, value);
9385 else if (descr->pos == 0)
9386 /* Otherwise append it to the result list if no XPG3 was given */
9387 Jim_ListAppendElement(interp, resultList, value);
9388 else if (resultVec[descr->pos - 1] == emptyStr) {
9389 /* But due to given XPG3, put the value into the corr. slot */
9390 Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
9391 Jim_IncrRefCount(value);
9392 resultVec[descr->pos - 1] = value;
9394 else {
9395 /* Otherwise, the slot was already used - free obj and ERROR */
9396 Jim_FreeNewObj(interp, value);
9397 goto err;
9400 Jim_DecrRefCount(interp, emptyStr);
9401 return resultList;
9402 eof:
9403 Jim_DecrRefCount(interp, emptyStr);
9404 Jim_FreeNewObj(interp, resultList);
9405 return (Jim_Obj *)EOF;
9406 err:
9407 Jim_DecrRefCount(interp, emptyStr);
9408 Jim_FreeNewObj(interp, resultList);
9409 return 0;
9412 /* -----------------------------------------------------------------------------
9413 * Pseudo Random Number Generation
9414 * ---------------------------------------------------------------------------*/
9415 /* Initialize the sbox with the numbers from 0 to 255 */
9416 static void JimPrngInit(Jim_Interp *interp)
9418 #define PRNG_SEED_SIZE 256
9419 int i;
9420 unsigned int *seed;
9421 time_t t = time(NULL);
9423 interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
9425 seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
9426 for (i = 0; i < PRNG_SEED_SIZE; i++) {
9427 seed[i] = (rand() ^ t ^ clock());
9429 JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
9430 Jim_Free(seed);
9433 /* Generates N bytes of random data */
9434 static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
9436 Jim_PrngState *prng;
9437 unsigned char *destByte = (unsigned char *)dest;
9438 unsigned int si, sj, x;
9440 /* initialization, only needed the first time */
9441 if (interp->prngState == NULL)
9442 JimPrngInit(interp);
9443 prng = interp->prngState;
9444 /* generates 'len' bytes of pseudo-random numbers */
9445 for (x = 0; x < len; x++) {
9446 prng->i = (prng->i + 1) & 0xff;
9447 si = prng->sbox[prng->i];
9448 prng->j = (prng->j + si) & 0xff;
9449 sj = prng->sbox[prng->j];
9450 prng->sbox[prng->i] = sj;
9451 prng->sbox[prng->j] = si;
9452 *destByte++ = prng->sbox[(si + sj) & 0xff];
9456 /* Re-seed the generator with user-provided bytes */
9457 static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
9459 int i;
9460 Jim_PrngState *prng;
9462 /* initialization, only needed the first time */
9463 if (interp->prngState == NULL)
9464 JimPrngInit(interp);
9465 prng = interp->prngState;
9467 /* Set the sbox[i] with i */
9468 for (i = 0; i < 256; i++)
9469 prng->sbox[i] = i;
9470 /* Now use the seed to perform a random permutation of the sbox */
9471 for (i = 0; i < seedLen; i++) {
9472 unsigned char t;
9474 t = prng->sbox[i & 0xFF];
9475 prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
9476 prng->sbox[seed[i]] = t;
9478 prng->i = prng->j = 0;
9480 /* discard at least the first 256 bytes of stream.
9481 * borrow the seed buffer for this
9483 for (i = 0; i < 256; i += seedLen) {
9484 JimRandomBytes(interp, seed, seedLen);
9488 /* [incr] */
9489 static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
9491 jim_wide wideValue, increment = 1;
9492 Jim_Obj *intObjPtr;
9494 if (argc != 2 && argc != 3) {
9495 Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
9496 return JIM_ERR;
9498 if (argc == 3) {
9499 if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)
9500 return JIM_ERR;
9502 intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
9503 if (!intObjPtr) {
9504 /* Set missing variable to 0 */
9505 wideValue = 0;
9507 else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
9508 return JIM_ERR;
9510 if (!intObjPtr || Jim_IsShared(intObjPtr)) {
9511 intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
9512 if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
9513 Jim_FreeNewObj(interp, intObjPtr);
9514 return JIM_ERR;
9517 else {
9518 /* Can do it the quick way */
9519 Jim_InvalidateStringRep(intObjPtr);
9520 JimWideValue(intObjPtr) = wideValue + increment;
9522 /* The following step is required in order to invalidate the
9523 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9524 if (argv[1]->typePtr != &variableObjType) {
9525 /* Note that this can't fail since GetVariable already succeeded */
9526 Jim_SetVariable(interp, argv[1], intObjPtr);
9529 Jim_SetResult(interp, intObjPtr);
9530 return JIM_OK;
9534 /* -----------------------------------------------------------------------------
9535 * Eval
9536 * ---------------------------------------------------------------------------*/
9537 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9538 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9540 /* Handle calls to the [unknown] command */
9541 static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv, Jim_Obj *fileNameObj,
9542 int linenr)
9544 Jim_Obj **v, *sv[JIM_EVAL_SARGV_LEN];
9545 int retCode;
9547 /* If JimUnknown() is recursively called too many times...
9548 * done here
9550 if (interp->unknown_called > 50) {
9551 return JIM_ERR;
9554 /* If the [unknown] command does not exists returns
9555 * just now */
9556 if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
9557 return JIM_ERR;
9559 /* The object interp->unknown just contains
9560 * the "unknown" string, it is used in order to
9561 * avoid to lookup the unknown command every time
9562 * but instread to cache the result. */
9563 if (argc + 1 <= JIM_EVAL_SARGV_LEN)
9564 v = sv;
9565 else
9566 v = Jim_Alloc(sizeof(Jim_Obj *) * (argc + 1));
9567 /* Make a copy of the arguments vector, but shifted on
9568 * the right of one position. The command name of the
9569 * command will be instead the first argument of the
9570 * [unknown] call. */
9571 memcpy(v + 1, argv, sizeof(Jim_Obj *) * argc);
9572 v[0] = interp->unknown;
9573 /* Call it */
9574 interp->unknown_called++;
9575 retCode = JimEvalObjVector(interp, argc + 1, v, fileNameObj, linenr);
9576 interp->unknown_called--;
9578 /* Clean up */
9579 if (v != sv)
9580 Jim_Free(v);
9581 return retCode;
9584 /* Eval the object vector 'objv' composed of 'objc' elements.
9585 * Every element is used as single argument.
9586 * Jim_EvalObj() will call this function every time its object
9587 * argument is of "list" type, with no string representation.
9589 * This is possible because the string representation of a
9590 * list object generated by the UpdateStringOfList is made
9591 * in a way that ensures that every list element is a different
9592 * command argument. */
9593 static int JimEvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv,
9594 Jim_Obj *fileNameObj, int linenr)
9596 int i, retcode;
9597 Jim_Cmd *cmdPtr;
9599 /* Incr refcount of arguments. */
9600 for (i = 0; i < objc; i++)
9601 Jim_IncrRefCount(objv[i]);
9602 /* Command lookup */
9603 cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
9604 if (cmdPtr == NULL) {
9605 retcode = JimUnknown(interp, objc, objv, fileNameObj, linenr);
9607 else {
9608 /* Call it -- Make sure result is an empty object. */
9609 JimIncrCmdRefCount(cmdPtr);
9610 Jim_SetEmptyResult(interp);
9611 if (cmdPtr->isproc) {
9612 retcode = JimCallProcedure(interp, cmdPtr, fileNameObj, linenr, objc, objv);
9614 else {
9615 interp->cmdPrivData = cmdPtr->u.native.privData;
9616 retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
9618 JimDecrCmdRefCount(interp, cmdPtr);
9620 /* Decr refcount of arguments and return the retcode */
9621 for (i = 0; i < objc; i++)
9622 Jim_DecrRefCount(interp, objv[i]);
9624 return retcode;
9627 int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
9629 return JimEvalObjVector(interp, objc, objv, interp->emptyObj, 1);
9633 * Invokes 'prefix' as a command with the objv array as arguments.
9635 int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix, int objc, Jim_Obj *const *objv)
9637 int i;
9638 int ret;
9639 Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
9641 nargv[0] = prefix;
9642 for (i = 0; i < objc; i++) {
9643 nargv[i + 1] = objv[i];
9645 ret = Jim_EvalObjVector(interp, objc + 1, nargv);
9646 Jim_Free(nargv);
9647 return ret;
9650 static void JimAddErrorToStack(Jim_Interp *interp, int retcode, Jim_Obj *fileNameObj, int line)
9652 int rc = retcode;
9654 if (rc == JIM_ERR && !interp->errorFlag) {
9655 /* This is the first error, so save the file/line information and reset the stack */
9656 interp->errorFlag = 1;
9657 Jim_IncrRefCount(fileNameObj);
9658 Jim_DecrRefCount(interp, interp->errorFileNameObj);
9659 interp->errorFileNameObj = fileNameObj;
9660 interp->errorLine = line;
9662 JimResetStackTrace(interp);
9663 /* Always add a level where the error first occurs */
9664 interp->addStackTrace++;
9667 /* Now if this is an "interesting" level, add it to the stack trace */
9668 if (rc == JIM_ERR && interp->addStackTrace > 0) {
9669 /* Add the stack info for the current level */
9671 JimAppendStackTrace(interp, Jim_String(interp->errorProc), fileNameObj, line);
9673 /* Note: if we didn't have a filename for this level,
9674 * don't clear the addStackTrace flag
9675 * so we can pick it up at the next level
9677 if (Jim_Length(fileNameObj)) {
9678 interp->addStackTrace = 0;
9681 Jim_DecrRefCount(interp, interp->errorProc);
9682 interp->errorProc = interp->emptyObj;
9683 Jim_IncrRefCount(interp->errorProc);
9685 else if (rc == JIM_RETURN && interp->returnCode == JIM_ERR) {
9686 /* Propagate the addStackTrace value through 'return -code error' */
9688 else {
9689 interp->addStackTrace = 0;
9693 /* And delete any local procs */
9694 static void JimDeleteLocalProcs(Jim_Interp *interp)
9696 if (interp->localProcs) {
9697 char *procname;
9699 while ((procname = Jim_StackPop(interp->localProcs)) != NULL) {
9700 /* If there is a pushed command, find it */
9701 Jim_Cmd *prevCmd = NULL;
9702 Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, procname);
9703 if (he) {
9704 Jim_Cmd *cmd = (Jim_Cmd *)he->u.val;
9705 if (cmd->isproc && cmd->u.proc.prevCmd) {
9706 prevCmd = cmd->u.proc.prevCmd;
9707 cmd->u.proc.prevCmd = NULL;
9711 /* Delete the local proc */
9712 Jim_DeleteCommand(interp, procname);
9714 if (prevCmd) {
9715 /* And restore the pushed command */
9716 Jim_AddHashEntry(&interp->commands, procname, prevCmd);
9718 Jim_Free(procname);
9720 Jim_FreeStack(interp->localProcs);
9721 Jim_Free(interp->localProcs);
9722 interp->localProcs = NULL;
9726 static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
9728 Jim_Obj *objPtr;
9730 switch (token->type) {
9731 case JIM_TT_STR:
9732 case JIM_TT_ESC:
9733 objPtr = token->objPtr;
9734 break;
9735 case JIM_TT_VAR:
9736 objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
9737 break;
9738 case JIM_TT_DICTSUGAR:
9739 objPtr = JimExpandDictSugar(interp, token->objPtr);
9740 break;
9741 case JIM_TT_EXPRSUGAR:
9742 objPtr = JimExpandExprSugar(interp, token->objPtr);
9743 break;
9744 case JIM_TT_CMD:
9745 switch (Jim_EvalObj(interp, token->objPtr)) {
9746 case JIM_OK:
9747 case JIM_RETURN:
9748 objPtr = interp->result;
9749 break;
9750 case JIM_BREAK:
9751 /* Stop substituting */
9752 return JIM_BREAK;
9753 case JIM_CONTINUE:
9754 /* just skip this one */
9755 return JIM_CONTINUE;
9756 default:
9757 return JIM_ERR;
9759 break;
9760 default:
9761 JimPanic((1,
9762 "default token type (%d) reached " "in Jim_SubstObj().", token->type));
9763 objPtr = NULL;
9764 break;
9766 if (objPtr) {
9767 *objPtrPtr = objPtr;
9768 return JIM_OK;
9770 return JIM_ERR;
9773 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9774 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9775 * The returned object has refcount = 0.
9777 static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
9779 int totlen = 0, i;
9780 Jim_Obj **intv;
9781 Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
9782 Jim_Obj *objPtr;
9783 char *s;
9785 if (tokens <= JIM_EVAL_SINTV_LEN)
9786 intv = sintv;
9787 else
9788 intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
9790 /* Compute every token forming the argument
9791 * in the intv objects vector. */
9792 for (i = 0; i < tokens; i++) {
9793 switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
9794 case JIM_OK:
9795 case JIM_RETURN:
9796 break;
9797 case JIM_BREAK:
9798 if (flags & JIM_SUBST_FLAG) {
9799 /* Stop here */
9800 tokens = i;
9801 continue;
9803 /* XXX: Should probably set an error about break outside loop */
9804 /* fall through to error */
9805 case JIM_CONTINUE:
9806 if (flags & JIM_SUBST_FLAG) {
9807 intv[i] = NULL;
9808 continue;
9810 /* XXX: Ditto continue outside loop */
9811 /* fall through to error */
9812 default:
9813 while (i--) {
9814 Jim_DecrRefCount(interp, intv[i]);
9816 if (intv != sintv) {
9817 Jim_Free(intv);
9819 return NULL;
9821 Jim_IncrRefCount(intv[i]);
9822 Jim_String(intv[i]);
9823 totlen += intv[i]->length;
9826 /* Fast path return for a single token */
9827 if (tokens == 1 && intv[0] && intv == sintv) {
9828 Jim_DecrRefCount(interp, intv[0]);
9829 return intv[0];
9832 /* Concatenate every token in an unique
9833 * object. */
9834 objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
9836 if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
9837 && token[2].type == JIM_TT_VAR) {
9838 /* May be able to do fast interpolated object -> dictSubst */
9839 objPtr->typePtr = &interpolatedObjType;
9840 objPtr->internalRep.twoPtrValue.ptr1 = (void *)token;
9841 objPtr->internalRep.twoPtrValue.ptr2 = intv[2];
9842 Jim_IncrRefCount(intv[2]);
9845 s = objPtr->bytes = Jim_Alloc(totlen + 1);
9846 objPtr->length = totlen;
9847 for (i = 0; i < tokens; i++) {
9848 if (intv[i]) {
9849 memcpy(s, intv[i]->bytes, intv[i]->length);
9850 s += intv[i]->length;
9851 Jim_DecrRefCount(interp, intv[i]);
9854 objPtr->bytes[totlen] = '\0';
9855 /* Free the intv vector if not static. */
9856 if (intv != sintv) {
9857 Jim_Free(intv);
9860 return objPtr;
9864 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9865 * Otherwise eval with Jim_EvalObj()
9867 static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *fileNameObj, int linenr)
9869 if (!Jim_IsList(listPtr)) {
9870 return Jim_EvalObj(interp, listPtr);
9872 else {
9873 int retcode = JIM_OK;
9875 if (listPtr->internalRep.listValue.len) {
9876 Jim_IncrRefCount(listPtr);
9877 retcode = JimEvalObjVector(interp,
9878 listPtr->internalRep.listValue.len,
9879 listPtr->internalRep.listValue.ele, fileNameObj, linenr);
9880 Jim_DecrRefCount(interp, listPtr);
9882 return retcode;
9886 int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
9888 int i;
9889 ScriptObj *script;
9890 ScriptToken *token;
9891 int retcode = JIM_OK;
9892 Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
9893 int linenr = 0;
9895 interp->errorFlag = 0;
9897 /* If the object is of type "list", with no string rep we can call
9898 * a specialized version of Jim_EvalObj() */
9899 if (Jim_IsList(scriptObjPtr) && scriptObjPtr->bytes == NULL) {
9900 return JimEvalObjList(interp, scriptObjPtr, interp->emptyObj, 1);
9903 Jim_IncrRefCount(scriptObjPtr); /* Make sure it's shared. */
9904 script = Jim_GetScript(interp, scriptObjPtr);
9906 /* Reset the interpreter result. This is useful to
9907 * return the empty result in the case of empty program. */
9908 Jim_SetEmptyResult(interp);
9910 #ifdef JIM_OPTIMIZATION
9911 /* Check for one of the following common scripts used by for, while
9913 * {}
9914 * incr a
9916 if (script->len == 0) {
9917 Jim_DecrRefCount(interp, scriptObjPtr);
9918 return JIM_OK;
9920 if (script->len == 3
9921 && script->token[1].objPtr->typePtr == &commandObjType
9922 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
9923 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
9924 && script->token[2].objPtr->typePtr == &variableObjType) {
9926 Jim_Obj *objPtr = Jim_GetVariable(interp, script->token[2].objPtr, JIM_NONE);
9928 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
9929 JimWideValue(objPtr)++;
9930 Jim_InvalidateStringRep(objPtr);
9931 Jim_DecrRefCount(interp, scriptObjPtr);
9932 Jim_SetResult(interp, objPtr);
9933 return JIM_OK;
9936 #endif
9938 /* Now we have to make sure the internal repr will not be
9939 * freed on shimmering.
9941 * Think for example to this:
9943 * set x {llength $x; ... some more code ...}; eval $x
9945 * In order to preserve the internal rep, we increment the
9946 * inUse field of the script internal rep structure. */
9947 script->inUse++;
9949 token = script->token;
9950 argv = sargv;
9952 /* Execute every command sequentially until the end of the script
9953 * or an error occurs.
9955 for (i = 0; i < script->len && retcode == JIM_OK; ) {
9956 int argc;
9957 int j;
9958 Jim_Cmd *cmd;
9960 /* First token of the line is always JIM_TT_LINE */
9961 argc = token[i].objPtr->internalRep.scriptLineValue.argc;
9962 linenr = token[i].objPtr->internalRep.scriptLineValue.line;
9964 /* Allocate the arguments vector if required */
9965 if (argc > JIM_EVAL_SARGV_LEN)
9966 argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
9968 /* Skip the JIM_TT_LINE token */
9969 i++;
9971 /* Populate the arguments objects.
9972 * If an error occurs, retcode will be set and
9973 * 'j' will be set to the number of args expanded
9975 for (j = 0; j < argc; j++) {
9976 long wordtokens = 1;
9977 int expand = 0;
9978 Jim_Obj *wordObjPtr = NULL;
9980 if (token[i].type == JIM_TT_WORD) {
9981 wordtokens = JimWideValue(token[i++].objPtr);
9982 if (wordtokens < 0) {
9983 expand = 1;
9984 wordtokens = -wordtokens;
9988 if (wordtokens == 1) {
9989 /* Fast path if the token does not
9990 * need interpolation */
9992 switch (token[i].type) {
9993 case JIM_TT_ESC:
9994 case JIM_TT_STR:
9995 wordObjPtr = token[i].objPtr;
9996 break;
9997 case JIM_TT_VAR:
9998 wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
9999 break;
10000 case JIM_TT_EXPRSUGAR:
10001 wordObjPtr = JimExpandExprSugar(interp, token[i].objPtr);
10002 break;
10003 case JIM_TT_DICTSUGAR:
10004 wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
10005 break;
10006 case JIM_TT_CMD:
10007 retcode = Jim_EvalObj(interp, token[i].objPtr);
10008 if (retcode == JIM_OK) {
10009 wordObjPtr = Jim_GetResult(interp);
10011 break;
10012 default:
10013 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10016 else {
10017 /* For interpolation we call a helper
10018 * function to do the work for us. */
10019 wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
10022 if (!wordObjPtr) {
10023 if (retcode == JIM_OK) {
10024 retcode = JIM_ERR;
10026 break;
10029 Jim_IncrRefCount(wordObjPtr);
10030 i += wordtokens;
10032 if (!expand) {
10033 argv[j] = wordObjPtr;
10035 else {
10036 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10037 int len = Jim_ListLength(interp, wordObjPtr);
10038 int newargc = argc + len - 1;
10039 int k;
10041 if (len > 1) {
10042 if (argv == sargv) {
10043 if (newargc > JIM_EVAL_SARGV_LEN) {
10044 argv = Jim_Alloc(sizeof(*argv) * newargc);
10045 memcpy(argv, sargv, sizeof(*argv) * j);
10048 else {
10049 /* Need to realloc to make room for (len - 1) more entries */
10050 argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
10054 /* Now copy in the expanded version */
10055 for (k = 0; k < len; k++) {
10056 argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
10057 Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
10060 /* The original object reference is no longer needed,
10061 * after the expansion it is no longer present on
10062 * the argument vector, but the single elements are
10063 * in its place. */
10064 Jim_DecrRefCount(interp, wordObjPtr);
10066 /* And update the indexes */
10067 j--;
10068 argc += len - 1;
10072 if (retcode == JIM_OK && argc) {
10073 /* Lookup the command to call */
10074 cmd = Jim_GetCommand(interp, argv[0], JIM_ERRMSG);
10075 if (cmd != NULL) {
10076 /* Call it -- Make sure result is an empty object. */
10077 JimIncrCmdRefCount(cmd);
10078 Jim_SetEmptyResult(interp);
10079 if (cmd->isproc) {
10080 retcode =
10081 JimCallProcedure(interp, cmd, script->fileNameObj, linenr, argc, argv);
10082 } else {
10083 interp->cmdPrivData = cmd->u.native.privData;
10084 retcode = cmd->u.native.cmdProc(interp, argc, argv);
10086 JimDecrCmdRefCount(interp, cmd);
10088 else {
10089 /* Call [unknown] */
10090 retcode = JimUnknown(interp, argc, argv, script->fileNameObj, linenr);
10092 if (interp->signal_level && interp->sigmask) {
10093 /* Check for a signal after each command */
10094 retcode = JIM_SIGNAL;
10098 /* Finished with the command, so decrement ref counts of each argument */
10099 while (j-- > 0) {
10100 Jim_DecrRefCount(interp, argv[j]);
10103 if (argv != sargv) {
10104 Jim_Free(argv);
10105 argv = sargv;
10109 /* Possibly add to the error stack trace */
10110 JimAddErrorToStack(interp, retcode, script->fileNameObj, linenr);
10112 /* Note that we don't have to decrement inUse, because the
10113 * following code transfers our use of the reference again to
10114 * the script object. */
10115 Jim_FreeIntRep(interp, scriptObjPtr);
10116 scriptObjPtr->typePtr = &scriptObjType;
10117 Jim_SetIntRepPtr(scriptObjPtr, script);
10118 Jim_DecrRefCount(interp, scriptObjPtr);
10120 return retcode;
10123 static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
10125 int retcode;
10126 /* If argObjPtr begins with '&', do an automatic upvar */
10127 const char *varname = Jim_String(argNameObj);
10128 if (*varname == '&') {
10129 /* First check that the target variable exists */
10130 Jim_Obj *objPtr;
10131 Jim_CallFrame *savedCallFrame = interp->framePtr;
10133 interp->framePtr = interp->framePtr->parentCallFrame;
10134 objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
10135 interp->framePtr = savedCallFrame;
10136 if (!objPtr) {
10137 return JIM_ERR;
10140 /* It exists, so perform the binding. */
10141 objPtr = Jim_NewStringObj(interp, varname + 1, -1);
10142 Jim_IncrRefCount(objPtr);
10143 retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parentCallFrame);
10144 Jim_DecrRefCount(interp, objPtr);
10146 else {
10147 retcode = Jim_SetVariable(interp, argNameObj, argValObj);
10149 return retcode;
10153 * Sets the interp result to be an error message indicating the required proc args.
10155 static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
10157 /* Create a nice error message, consistent with Tcl 8.5 */
10158 Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
10159 int i;
10161 for (i = 0; i < cmd->u.proc.argListLen; i++) {
10162 Jim_AppendString(interp, argmsg, " ", 1);
10164 if (i == cmd->u.proc.argsPos) {
10165 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10166 /* Renamed args */
10167 Jim_AppendString(interp, argmsg, "?", 1);
10168 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
10169 Jim_AppendString(interp, argmsg, " ...?", -1);
10171 else {
10172 /* We have plain args */
10173 Jim_AppendString(interp, argmsg, "?argument ...?", -1);
10176 else {
10177 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10178 Jim_AppendString(interp, argmsg, "?", 1);
10179 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10180 Jim_AppendString(interp, argmsg, "?", 1);
10182 else {
10183 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10187 Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
10188 Jim_FreeNewObj(interp, argmsg);
10191 /* Call a procedure implemented in Tcl.
10192 * It's possible to speed-up a lot this function, currently
10193 * the callframes are not cached, but allocated and
10194 * destroied every time. What is expecially costly is
10195 * to create/destroy the local vars hash table every time.
10197 * This can be fixed just implementing callframes caching
10198 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10199 static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, Jim_Obj *fileNameObj, int linenr, int argc,
10200 Jim_Obj *const *argv)
10202 Jim_CallFrame *callFramePtr;
10203 Jim_Stack *prevLocalProcs;
10204 int i, d, retcode, optargs;
10206 /* Check arity */
10207 if (argc - 1 < cmd->u.proc.reqArity ||
10208 (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
10209 JimSetProcWrongArgs(interp, argv[0], cmd);
10210 return JIM_ERR;
10213 /* Check if there are too nested calls */
10214 if (interp->framePtr->level == interp->maxNestingDepth) {
10215 Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
10216 return JIM_ERR;
10219 /* Create a new callframe */
10220 callFramePtr = JimCreateCallFrame(interp, interp->framePtr);
10221 callFramePtr->argv = argv;
10222 callFramePtr->argc = argc;
10223 callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
10224 callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
10225 callFramePtr->staticVars = cmd->u.proc.staticVars;
10226 callFramePtr->fileNameObj = fileNameObj;
10227 callFramePtr->line = linenr;
10228 Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
10229 Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
10230 interp->framePtr = callFramePtr;
10232 /* How many optional args are available */
10233 optargs = (argc - 1 - cmd->u.proc.reqArity);
10235 /* Step 'i' along the actual args, and step 'd' along the formal args */
10236 i = 1;
10237 for (d = 0; d < cmd->u.proc.argListLen; d++) {
10238 Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
10239 if (d == cmd->u.proc.argsPos) {
10240 /* assign $args */
10241 Jim_Obj *listObjPtr;
10242 int argsLen = 0;
10243 if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
10244 argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
10246 listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
10248 /* It is possible to rename args. */
10249 if (cmd->u.proc.arglist[d].defaultObjPtr) {
10250 nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
10252 retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
10253 if (retcode != JIM_OK) {
10254 goto badargset;
10257 i += argsLen;
10258 continue;
10261 /* Optional or required? */
10262 if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
10263 retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
10265 else {
10266 /* Ran out, so use the default */
10267 retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
10269 if (retcode != JIM_OK) {
10270 goto badargset;
10274 /* Install a new stack for local procs */
10275 prevLocalProcs = interp->localProcs;
10276 interp->localProcs = NULL;
10278 /* Eval the body */
10279 retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
10281 /* Delete any local procs */
10282 JimDeleteLocalProcs(interp);
10283 interp->localProcs = prevLocalProcs;
10285 badargset:
10286 /* Destroy the callframe */
10287 interp->framePtr = interp->framePtr->parentCallFrame;
10288 if (callFramePtr->vars.size != JIM_HT_INITIAL_SIZE) {
10289 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NONE);
10291 else {
10292 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NOHT);
10294 /* Handle the JIM_EVAL return code */
10295 while (retcode == JIM_EVAL) {
10296 Jim_Obj *resultScriptObjPtr = Jim_GetResult(interp);
10298 Jim_IncrRefCount(resultScriptObjPtr);
10299 /* Should be a list! */
10300 retcode = JimEvalObjList(interp, resultScriptObjPtr, fileNameObj, linenr);
10301 Jim_DecrRefCount(interp, resultScriptObjPtr);
10303 /* Handle the JIM_RETURN return code */
10304 if (retcode == JIM_RETURN) {
10305 if (--interp->returnLevel <= 0) {
10306 retcode = interp->returnCode;
10307 interp->returnCode = JIM_OK;
10308 interp->returnLevel = 0;
10311 else if (retcode == JIM_ERR) {
10312 interp->addStackTrace++;
10313 Jim_DecrRefCount(interp, interp->errorProc);
10314 interp->errorProc = argv[0];
10315 Jim_IncrRefCount(interp->errorProc);
10317 return retcode;
10320 int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script)
10322 int retval;
10323 Jim_Obj *scriptObjPtr;
10325 scriptObjPtr = Jim_NewStringObj(interp, script, -1);
10326 Jim_IncrRefCount(scriptObjPtr);
10328 if (filename) {
10329 Jim_Obj *prevScriptObj;
10331 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
10333 prevScriptObj = interp->currentScriptObj;
10334 interp->currentScriptObj = scriptObjPtr;
10336 retval = Jim_EvalObj(interp, scriptObjPtr);
10338 interp->currentScriptObj = prevScriptObj;
10340 else {
10341 retval = Jim_EvalObj(interp, scriptObjPtr);
10343 Jim_DecrRefCount(interp, scriptObjPtr);
10344 return retval;
10347 int Jim_Eval(Jim_Interp *interp, const char *script)
10349 return Jim_EvalObj(interp, Jim_NewStringObj(interp, script, -1));
10352 /* Execute script in the scope of the global level */
10353 int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
10355 int retval;
10356 Jim_CallFrame *savedFramePtr = interp->framePtr;
10358 interp->framePtr = interp->topFramePtr;
10359 retval = Jim_Eval(interp, script);
10360 interp->framePtr = savedFramePtr;
10362 return retval;
10365 int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
10367 int retval;
10368 Jim_CallFrame *savedFramePtr = interp->framePtr;
10370 interp->framePtr = interp->topFramePtr;
10371 retval = Jim_EvalFile(interp, filename);
10372 interp->framePtr = savedFramePtr;
10374 return retval;
10377 #include <sys/stat.h>
10379 int Jim_EvalFile(Jim_Interp *interp, const char *filename)
10381 FILE *fp;
10382 char *buf;
10383 Jim_Obj *scriptObjPtr;
10384 Jim_Obj *prevScriptObj;
10385 struct stat sb;
10386 int retcode;
10387 int readlen;
10388 struct JimParseResult result;
10390 if (stat(filename, &sb) != 0 || (fp = fopen(filename, "rt")) == NULL) {
10391 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
10392 return JIM_ERR;
10394 if (sb.st_size == 0) {
10395 fclose(fp);
10396 return JIM_OK;
10399 buf = Jim_Alloc(sb.st_size + 1);
10400 readlen = fread(buf, 1, sb.st_size, fp);
10401 if (ferror(fp)) {
10402 fclose(fp);
10403 Jim_Free(buf);
10404 Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
10405 return JIM_ERR;
10407 fclose(fp);
10408 buf[readlen] = 0;
10410 scriptObjPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
10411 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), 1);
10412 Jim_IncrRefCount(scriptObjPtr);
10414 /* Now check the script for unmatched braces, etc. */
10415 if (SetScriptFromAny(interp, scriptObjPtr, &result) == JIM_ERR) {
10416 const char *msg;
10417 char linebuf[20];
10419 switch (result.missing) {
10420 case '[':
10421 msg = "unmatched \"[\"";
10422 break;
10423 case '{':
10424 msg = "missing close-brace";
10425 break;
10426 case '"':
10427 default:
10428 msg = "missing quote";
10429 break;
10432 snprintf(linebuf, sizeof(linebuf), "%d", result.line);
10434 Jim_SetResultFormatted(interp, "%s in \"%s\" at line %s",
10435 msg, filename, linebuf);
10436 Jim_DecrRefCount(interp, scriptObjPtr);
10437 return JIM_ERR;
10440 prevScriptObj = interp->currentScriptObj;
10441 interp->currentScriptObj = scriptObjPtr;
10443 retcode = Jim_EvalObj(interp, scriptObjPtr);
10445 /* Handle the JIM_RETURN return code */
10446 if (retcode == JIM_RETURN) {
10447 if (--interp->returnLevel <= 0) {
10448 retcode = interp->returnCode;
10449 interp->returnCode = JIM_OK;
10450 interp->returnLevel = 0;
10453 if (retcode == JIM_ERR) {
10454 /* EvalFile changes context, so add a stack frame here */
10455 interp->addStackTrace++;
10458 interp->currentScriptObj = prevScriptObj;
10460 Jim_DecrRefCount(interp, scriptObjPtr);
10462 return retcode;
10465 /* -----------------------------------------------------------------------------
10466 * Subst
10467 * ---------------------------------------------------------------------------*/
10468 static int JimParseSubstStr(struct JimParserCtx *pc)
10470 pc->tstart = pc->p;
10471 pc->tline = pc->linenr;
10472 while (pc->len && *pc->p != '$' && *pc->p != '[') {
10473 if (*pc->p == '\\' && pc->len > 1) {
10474 pc->p++;
10475 pc->len--;
10477 pc->p++;
10478 pc->len--;
10480 pc->tend = pc->p - 1;
10481 pc->tt = JIM_TT_ESC;
10482 return JIM_OK;
10485 static int JimParseSubst(struct JimParserCtx *pc, int flags)
10487 int retval;
10489 if (pc->len == 0) {
10490 pc->tstart = pc->tend = pc->p;
10491 pc->tline = pc->linenr;
10492 pc->tt = JIM_TT_EOL;
10493 pc->eof = 1;
10494 return JIM_OK;
10496 switch (*pc->p) {
10497 case '[':
10498 retval = JimParseCmd(pc);
10499 if (flags & JIM_SUBST_NOCMD) {
10500 pc->tstart--;
10501 pc->tend++;
10502 pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
10504 return retval;
10505 break;
10506 case '$':
10507 if (JimParseVar(pc) == JIM_ERR) {
10508 pc->tstart = pc->tend = pc->p++;
10509 pc->len--;
10510 pc->tline = pc->linenr;
10511 pc->tt = JIM_TT_STR;
10513 else {
10514 if (flags & JIM_SUBST_NOVAR) {
10515 pc->tstart--;
10516 if (flags & JIM_SUBST_NOESC)
10517 pc->tt = JIM_TT_STR;
10518 else
10519 pc->tt = JIM_TT_ESC;
10520 if (*pc->tstart == '{') {
10521 pc->tstart--;
10522 if (*(pc->tend + 1))
10523 pc->tend++;
10527 break;
10528 default:
10529 retval = JimParseSubstStr(pc);
10530 if (flags & JIM_SUBST_NOESC)
10531 pc->tt = JIM_TT_STR;
10532 return retval;
10533 break;
10535 return JIM_OK;
10538 /* The subst object type reuses most of the data structures and functions
10539 * of the script object. Script's data structures are a bit more complex
10540 * for what is needed for [subst]itution tasks, but the reuse helps to
10541 * deal with a single data structure at the cost of some more memory
10542 * usage for substitutions. */
10544 /* This method takes the string representation of an object
10545 * as a Tcl string where to perform [subst]itution, and generates
10546 * the pre-parsed internal representation. */
10547 static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
10549 int scriptTextLen;
10550 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
10551 struct JimParserCtx parser;
10552 struct ScriptObj *script = Jim_Alloc(sizeof(*script));
10553 ParseTokenList tokenlist;
10555 /* Initially parse the subst into tokens (in tokenlist) */
10556 ScriptTokenListInit(&tokenlist);
10558 JimParserInit(&parser, scriptText, scriptTextLen, 1);
10559 while (1) {
10560 JimParseSubst(&parser, flags);
10561 if (parser.eof) {
10562 /* Note that subst doesn't need the EOL token */
10563 break;
10565 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
10566 parser.tline);
10569 /* Create the "real" subst/script tokens from the initial token list */
10570 script->inUse = 1;
10571 script->substFlags = flags;
10572 script->fileNameObj = interp->emptyObj;
10573 Jim_IncrRefCount(script->fileNameObj);
10574 SubstObjAddTokens(interp, script, &tokenlist);
10576 /* No longer need the token list */
10577 ScriptTokenListFree(&tokenlist);
10579 #ifdef DEBUG_SHOW_SUBST
10581 int i;
10583 printf("==== Subst ====\n");
10584 for (i = 0; i < script->len; i++) {
10585 printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
10586 Jim_String(script->token[i].objPtr));
10589 #endif
10591 /* Free the old internal rep and set the new one. */
10592 Jim_FreeIntRep(interp, objPtr);
10593 Jim_SetIntRepPtr(objPtr, script);
10594 objPtr->typePtr = &scriptObjType;
10595 return JIM_OK;
10598 static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
10600 if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
10601 SetSubstFromAny(interp, objPtr, flags);
10602 return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
10605 /* Performs commands,variables,blackslashes substitution,
10606 * storing the result object (with refcount 0) into
10607 * resObjPtrPtr. */
10608 int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
10610 ScriptObj *script = Jim_GetSubst(interp, substObjPtr, flags);
10612 Jim_IncrRefCount(substObjPtr); /* Make sure it's shared. */
10613 /* In order to preserve the internal rep, we increment the
10614 * inUse field of the script internal rep structure. */
10615 script->inUse++;
10617 *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
10619 script->inUse--;
10620 Jim_DecrRefCount(interp, substObjPtr);
10621 if (*resObjPtrPtr == NULL) {
10622 return JIM_ERR;
10624 return JIM_OK;
10627 /* -----------------------------------------------------------------------------
10628 * Core commands utility functions
10629 * ---------------------------------------------------------------------------*/
10630 void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
10632 int i;
10633 Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);
10635 Jim_AppendString(interp, objPtr, "wrong # args: should be \"", -1);
10636 for (i = 0; i < argc; i++) {
10637 Jim_AppendObj(interp, objPtr, argv[i]);
10638 if (!(i + 1 == argc && msg[0] == '\0'))
10639 Jim_AppendString(interp, objPtr, " ", 1);
10641 Jim_AppendString(interp, objPtr, msg, -1);
10642 Jim_AppendString(interp, objPtr, "\"", 1);
10643 Jim_SetResult(interp, objPtr);
10646 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10648 /* type is: 0=commands, 1=procs, 2=channels */
10649 static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
10651 Jim_HashTableIterator *htiter;
10652 Jim_HashEntry *he;
10653 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
10655 /* Check for the non-pattern case. We can do this much more efficiently. */
10656 if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
10657 Jim_Cmd *cmdPtr = Jim_GetCommand(interp, patternObjPtr, JIM_NONE);
10658 if (cmdPtr) {
10659 if (type == 1 && !cmdPtr->isproc) {
10660 /* not a proc */
10662 else if (type == 2 && !Jim_AioFilehandle(interp, patternObjPtr)) {
10663 /* not a channel */
10665 else {
10666 Jim_ListAppendElement(interp, listObjPtr, patternObjPtr);
10669 return listObjPtr;
10672 htiter = Jim_GetHashTableIterator(&interp->commands);
10673 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
10674 Jim_Cmd *cmdPtr = he->u.val;
10675 Jim_Obj *cmdNameObj;
10677 if (type == 1 && !cmdPtr->isproc) {
10678 /* not a proc */
10679 continue;
10681 if (patternObjPtr && !JimStringMatch(interp, patternObjPtr, he->key, 0))
10682 continue;
10684 cmdNameObj = Jim_NewStringObj(interp, he->key, -1);
10686 /* Is it a channel? */
10687 if (type == 2 && !Jim_AioFilehandle(interp, cmdNameObj)) {
10688 Jim_FreeNewObj(interp, cmdNameObj);
10689 continue;
10692 Jim_ListAppendElement(interp, listObjPtr, cmdNameObj);
10694 Jim_FreeHashTableIterator(htiter);
10695 return listObjPtr;
10698 /* Keep this in order */
10699 #define JIM_VARLIST_GLOBALS 0
10700 #define JIM_VARLIST_LOCALS 1
10701 #define JIM_VARLIST_VARS 2
10703 static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
10705 Jim_HashTableIterator *htiter;
10706 Jim_HashEntry *he;
10707 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
10709 if (mode == JIM_VARLIST_GLOBALS) {
10710 htiter = Jim_GetHashTableIterator(&interp->topFramePtr->vars);
10712 else {
10713 /* For [info locals], if we are at top level an emtpy list
10714 * is returned. I don't agree, but we aim at compatibility (SS) */
10715 if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr)
10716 return listObjPtr;
10717 htiter = Jim_GetHashTableIterator(&interp->framePtr->vars);
10719 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
10720 Jim_Var *varPtr = (Jim_Var *)he->u.val;
10722 if (mode == JIM_VARLIST_LOCALS) {
10723 if (varPtr->linkFramePtr != NULL)
10724 continue;
10726 if (patternObjPtr && !JimStringMatch(interp, patternObjPtr, he->key, 0))
10727 continue;
10728 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, he->key, -1));
10730 Jim_FreeHashTableIterator(htiter);
10731 return listObjPtr;
10734 static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
10735 Jim_Obj **objPtrPtr, int info_level_cmd)
10737 Jim_CallFrame *targetCallFrame;
10739 targetCallFrame = JimGetCallFrameByInteger(interp, levelObjPtr);
10740 if (targetCallFrame == NULL) {
10741 return JIM_ERR;
10743 /* No proc call at toplevel callframe */
10744 if (targetCallFrame == interp->topFramePtr) {
10745 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
10746 return JIM_ERR;
10748 if (info_level_cmd) {
10749 *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
10751 else {
10752 Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
10754 Jim_ListAppendElement(interp, listObj, targetCallFrame->argv[0]);
10755 Jim_ListAppendElement(interp, listObj, targetCallFrame->fileNameObj);
10756 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, targetCallFrame->line));
10757 *objPtrPtr = listObj;
10759 return JIM_OK;
10762 /* -----------------------------------------------------------------------------
10763 * Core commands
10764 * ---------------------------------------------------------------------------*/
10766 /* fake [puts] -- not the real puts, just for debugging. */
10767 static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10769 if (argc != 2 && argc != 3) {
10770 Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
10771 return JIM_ERR;
10773 if (argc == 3) {
10774 if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
10775 Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
10776 return JIM_ERR;
10778 else {
10779 fputs(Jim_String(argv[2]), stdout);
10782 else {
10783 puts(Jim_String(argv[1]));
10785 return JIM_OK;
10788 /* Helper for [+] and [*] */
10789 static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10791 jim_wide wideValue, res;
10792 double doubleValue, doubleRes;
10793 int i;
10795 res = (op == JIM_EXPROP_ADD) ? 0 : 1;
10797 for (i = 1; i < argc; i++) {
10798 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
10799 goto trydouble;
10800 if (op == JIM_EXPROP_ADD)
10801 res += wideValue;
10802 else
10803 res *= wideValue;
10805 Jim_SetResultInt(interp, res);
10806 return JIM_OK;
10807 trydouble:
10808 doubleRes = (double)res;
10809 for (; i < argc; i++) {
10810 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10811 return JIM_ERR;
10812 if (op == JIM_EXPROP_ADD)
10813 doubleRes += doubleValue;
10814 else
10815 doubleRes *= doubleValue;
10817 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10818 return JIM_OK;
10821 /* Helper for [-] and [/] */
10822 static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10824 jim_wide wideValue, res = 0;
10825 double doubleValue, doubleRes = 0;
10826 int i = 2;
10828 if (argc < 2) {
10829 Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
10830 return JIM_ERR;
10832 else if (argc == 2) {
10833 /* The arity = 2 case is different. For [- x] returns -x,
10834 * while [/ x] returns 1/x. */
10835 if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
10836 if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
10837 return JIM_ERR;
10839 else {
10840 if (op == JIM_EXPROP_SUB)
10841 doubleRes = -doubleValue;
10842 else
10843 doubleRes = 1.0 / doubleValue;
10844 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10845 return JIM_OK;
10848 if (op == JIM_EXPROP_SUB) {
10849 res = -wideValue;
10850 Jim_SetResultInt(interp, res);
10852 else {
10853 doubleRes = 1.0 / wideValue;
10854 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10856 return JIM_OK;
10858 else {
10859 if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
10860 if (Jim_GetDouble(interp, argv[1], &doubleRes)
10861 != JIM_OK) {
10862 return JIM_ERR;
10864 else {
10865 goto trydouble;
10869 for (i = 2; i < argc; i++) {
10870 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
10871 doubleRes = (double)res;
10872 goto trydouble;
10874 if (op == JIM_EXPROP_SUB)
10875 res -= wideValue;
10876 else
10877 res /= wideValue;
10879 Jim_SetResultInt(interp, res);
10880 return JIM_OK;
10881 trydouble:
10882 for (; i < argc; i++) {
10883 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10884 return JIM_ERR;
10885 if (op == JIM_EXPROP_SUB)
10886 doubleRes -= doubleValue;
10887 else
10888 doubleRes /= doubleValue;
10890 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10891 return JIM_OK;
10895 /* [+] */
10896 static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10898 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
10901 /* [*] */
10902 static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10904 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
10907 /* [-] */
10908 static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10910 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
10913 /* [/] */
10914 static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10916 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
10919 /* [set] */
10920 static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10922 if (argc != 2 && argc != 3) {
10923 Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
10924 return JIM_ERR;
10926 if (argc == 2) {
10927 Jim_Obj *objPtr;
10929 objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
10930 if (!objPtr)
10931 return JIM_ERR;
10932 Jim_SetResult(interp, objPtr);
10933 return JIM_OK;
10935 /* argc == 3 case. */
10936 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
10937 return JIM_ERR;
10938 Jim_SetResult(interp, argv[2]);
10939 return JIM_OK;
10942 /* [unset]
10944 * unset ?-nocomplain? ?--? ?varName ...?
10946 static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10948 int i = 1;
10949 int complain = 1;
10951 while (i < argc) {
10952 if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
10953 i++;
10954 break;
10956 if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
10957 complain = 0;
10958 i++;
10959 continue;
10961 break;
10964 while (i < argc) {
10965 if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
10966 && complain) {
10967 return JIM_ERR;
10969 i++;
10971 return JIM_OK;
10974 /* [while] */
10975 static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10977 if (argc != 3) {
10978 Jim_WrongNumArgs(interp, 1, argv, "condition body");
10979 return JIM_ERR;
10982 /* The general purpose implementation of while starts here */
10983 while (1) {
10984 int boolean, retval;
10986 if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
10987 return retval;
10988 if (!boolean)
10989 break;
10991 if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
10992 switch (retval) {
10993 case JIM_BREAK:
10994 goto out;
10995 break;
10996 case JIM_CONTINUE:
10997 continue;
10998 break;
10999 default:
11000 return retval;
11004 out:
11005 Jim_SetEmptyResult(interp);
11006 return JIM_OK;
11009 /* [for] */
11010 static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11012 int retval;
11013 int boolean = 1;
11014 Jim_Obj *varNamePtr = NULL;
11015 Jim_Obj *stopVarNamePtr = NULL;
11017 if (argc != 5) {
11018 Jim_WrongNumArgs(interp, 1, argv, "start test next body");
11019 return JIM_ERR;
11022 /* Do the initialisation */
11023 if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
11024 return retval;
11027 /* And do the first test now. Better for optimisation
11028 * if we can do next/test at the bottom of the loop
11030 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11032 /* Ready to do the body as follows:
11033 * while (1) {
11034 * body // check retcode
11035 * next // check retcode
11036 * test // check retcode/test bool
11040 #ifdef JIM_OPTIMIZATION
11041 /* Check if the for is on the form:
11042 * for ... {$i < CONST} {incr i}
11043 * for ... {$i < $j} {incr i}
11045 if (retval == JIM_OK && boolean) {
11046 ScriptObj *incrScript;
11047 ExprByteCode *expr;
11048 jim_wide stop, currentVal;
11049 unsigned jim_wide procEpoch;
11050 Jim_Obj *objPtr;
11051 int cmpOffset;
11053 /* Do it only if there aren't shared arguments */
11054 expr = JimGetExpression(interp, argv[2]);
11055 incrScript = Jim_GetScript(interp, argv[3]);
11057 /* Ensure proper lengths to start */
11058 if (incrScript->len != 3 || !expr || expr->len != 3) {
11059 goto evalstart;
11061 /* Ensure proper token types. */
11062 if (incrScript->token[1].type != JIM_TT_ESC ||
11063 expr->token[0].type != JIM_TT_VAR ||
11064 (expr->token[1].type != JIM_TT_EXPR_INT && expr->token[1].type != JIM_TT_VAR)) {
11065 goto evalstart;
11068 if (expr->token[2].type == JIM_EXPROP_LT) {
11069 cmpOffset = 0;
11071 else if (expr->token[2].type == JIM_EXPROP_LTE) {
11072 cmpOffset = 1;
11074 else {
11075 goto evalstart;
11078 /* Update command must be incr */
11079 if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
11080 goto evalstart;
11083 /* incr, expression must be about the same variable */
11084 if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->token[0].objPtr)) {
11085 goto evalstart;
11088 /* Get the stop condition (must be a variable or integer) */
11089 if (expr->token[1].type == JIM_TT_EXPR_INT) {
11090 if (Jim_GetWide(interp, expr->token[1].objPtr, &stop) == JIM_ERR) {
11091 goto evalstart;
11094 else {
11095 stopVarNamePtr = expr->token[1].objPtr;
11096 Jim_IncrRefCount(stopVarNamePtr);
11097 /* Keep the compiler happy */
11098 stop = 0;
11101 /* Initialization */
11102 procEpoch = interp->procEpoch;
11103 varNamePtr = expr->token[0].objPtr;
11104 Jim_IncrRefCount(varNamePtr);
11106 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
11107 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK) {
11108 goto testcond;
11111 /* --- OPTIMIZED FOR --- */
11112 while (retval == JIM_OK) {
11113 /* === Check condition === */
11114 /* Note that currentVal is already set here */
11116 /* Immediate or Variable? get the 'stop' value if the latter. */
11117 if (stopVarNamePtr) {
11118 objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
11119 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
11120 goto testcond;
11124 if (currentVal >= stop + cmpOffset) {
11125 break;
11128 /* Eval body */
11129 retval = Jim_EvalObj(interp, argv[4]);
11130 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11131 retval = JIM_OK;
11132 /* If there was a change in procedures/command continue
11133 * with the usual [for] command implementation */
11134 if (procEpoch != interp->procEpoch) {
11135 goto evalnext;
11138 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
11140 /* Increment */
11141 if (objPtr == NULL) {
11142 retval = JIM_ERR;
11143 goto out;
11145 if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11146 currentVal = ++JimWideValue(objPtr);
11147 Jim_InvalidateStringRep(objPtr);
11149 else {
11150 if (Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK ||
11151 Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
11152 ++currentVal)) != JIM_OK) {
11153 goto evalnext;
11158 goto out;
11160 evalstart:
11161 #endif
11163 while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
11164 /* Body */
11165 retval = Jim_EvalObj(interp, argv[4]);
11167 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11168 /* increment */
11169 evalnext:
11170 retval = Jim_EvalObj(interp, argv[3]);
11171 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11172 /* test */
11173 testcond:
11174 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11178 out:
11179 if (stopVarNamePtr) {
11180 Jim_DecrRefCount(interp, stopVarNamePtr);
11182 if (varNamePtr) {
11183 Jim_DecrRefCount(interp, varNamePtr);
11186 if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
11187 Jim_SetEmptyResult(interp);
11188 return JIM_OK;
11191 return retval;
11194 /* [loop] */
11195 static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11197 int retval;
11198 jim_wide i;
11199 jim_wide limit;
11200 jim_wide incr = 1;
11201 Jim_Obj *bodyObjPtr;
11203 if (argc != 5 && argc != 6) {
11204 Jim_WrongNumArgs(interp, 1, argv, "var first limit ?incr? body");
11205 return JIM_ERR;
11208 if (Jim_GetWide(interp, argv[2], &i) != JIM_OK ||
11209 Jim_GetWide(interp, argv[3], &limit) != JIM_OK ||
11210 (argc == 6 && Jim_GetWide(interp, argv[4], &incr) != JIM_OK)) {
11211 return JIM_ERR;
11213 bodyObjPtr = (argc == 5) ? argv[4] : argv[5];
11215 retval = Jim_SetVariable(interp, argv[1], argv[2]);
11217 while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
11218 retval = Jim_EvalObj(interp, bodyObjPtr);
11219 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11220 Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
11222 retval = JIM_OK;
11224 /* Increment */
11225 i += incr;
11227 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11228 if (argv[1]->typePtr != &variableObjType) {
11229 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11230 return JIM_ERR;
11233 JimWideValue(objPtr) = i;
11234 Jim_InvalidateStringRep(objPtr);
11236 /* The following step is required in order to invalidate the
11237 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11238 if (argv[1]->typePtr != &variableObjType) {
11239 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11240 retval = JIM_ERR;
11241 break;
11245 else {
11246 objPtr = Jim_NewIntObj(interp, i);
11247 retval = Jim_SetVariable(interp, argv[1], objPtr);
11248 if (retval != JIM_OK) {
11249 Jim_FreeNewObj(interp, objPtr);
11255 if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
11256 Jim_SetEmptyResult(interp);
11257 return JIM_OK;
11259 return retval;
11262 /* foreach + lmap implementation. */
11263 static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
11265 int result = JIM_ERR, i, nbrOfLists, *listsIdx, *listsEnd;
11266 int nbrOfLoops = 0;
11267 Jim_Obj *emptyStr, *script, *mapRes = NULL;
11269 if (argc < 4 || argc % 2 != 0) {
11270 Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
11271 return JIM_ERR;
11273 if (doMap) {
11274 mapRes = Jim_NewListObj(interp, NULL, 0);
11275 Jim_IncrRefCount(mapRes);
11277 emptyStr = Jim_NewEmptyStringObj(interp);
11278 Jim_IncrRefCount(emptyStr);
11279 script = argv[argc - 1]; /* Last argument is a script */
11280 nbrOfLists = (argc - 1 - 1) / 2; /* argc - 'foreach' - script */
11281 listsIdx = (int *)Jim_Alloc(nbrOfLists * sizeof(int));
11282 listsEnd = (int *)Jim_Alloc(nbrOfLists * 2 * sizeof(int));
11283 /* Initialize iterators and remember max nbr elements each list */
11284 memset(listsIdx, 0, nbrOfLists * sizeof(int));
11285 /* Remember lengths of all lists and calculate how much rounds to loop */
11286 for (i = 0; i < nbrOfLists * 2; i += 2) {
11287 div_t cnt;
11288 int count;
11290 listsEnd[i] = Jim_ListLength(interp, argv[i + 1]);
11291 listsEnd[i + 1] = Jim_ListLength(interp, argv[i + 2]);
11292 if (listsEnd[i] == 0) {
11293 Jim_SetResultString(interp, "foreach varlist is empty", -1);
11294 goto err;
11296 cnt = div(listsEnd[i + 1], listsEnd[i]);
11297 count = cnt.quot + (cnt.rem ? 1 : 0);
11298 if (count > nbrOfLoops)
11299 nbrOfLoops = count;
11301 for (; nbrOfLoops-- > 0;) {
11302 for (i = 0; i < nbrOfLists; ++i) {
11303 int varIdx = 0, var = i * 2;
11305 while (varIdx < listsEnd[var]) {
11306 Jim_Obj *varName, *ele;
11307 int lst = i * 2 + 1;
11309 /* List index operations below can't fail */
11310 Jim_ListIndex(interp, argv[var + 1], varIdx, &varName, JIM_NONE);
11311 if (listsIdx[i] < listsEnd[lst]) {
11312 Jim_ListIndex(interp, argv[lst + 1], listsIdx[i], &ele, JIM_NONE);
11313 /* Avoid shimmering */
11314 Jim_IncrRefCount(ele);
11315 result = Jim_SetVariable(interp, varName, ele);
11316 Jim_DecrRefCount(interp, ele);
11317 if (result == JIM_OK) {
11318 ++listsIdx[i]; /* Remember next iterator of current list */
11319 ++varIdx; /* Next variable */
11320 continue;
11323 else if (Jim_SetVariable(interp, varName, emptyStr) == JIM_OK) {
11324 ++varIdx; /* Next variable */
11325 continue;
11327 goto err;
11330 switch (result = Jim_EvalObj(interp, script)) {
11331 case JIM_OK:
11332 if (doMap)
11333 Jim_ListAppendElement(interp, mapRes, interp->result);
11334 break;
11335 case JIM_CONTINUE:
11336 break;
11337 case JIM_BREAK:
11338 goto out;
11339 break;
11340 default:
11341 goto err;
11344 out:
11345 result = JIM_OK;
11346 if (doMap)
11347 Jim_SetResult(interp, mapRes);
11348 else
11349 Jim_SetEmptyResult(interp);
11350 err:
11351 if (doMap)
11352 Jim_DecrRefCount(interp, mapRes);
11353 Jim_DecrRefCount(interp, emptyStr);
11354 Jim_Free(listsIdx);
11355 Jim_Free(listsEnd);
11356 return result;
11359 /* [foreach] */
11360 static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11362 return JimForeachMapHelper(interp, argc, argv, 0);
11365 /* [lmap] */
11366 static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11368 return JimForeachMapHelper(interp, argc, argv, 1);
11371 /* [if] */
11372 static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11374 int boolean, retval, current = 1, falsebody = 0;
11376 if (argc >= 3) {
11377 while (1) {
11378 /* Far not enough arguments given! */
11379 if (current >= argc)
11380 goto err;
11381 if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
11382 != JIM_OK)
11383 return retval;
11384 /* There lacks something, isn't it? */
11385 if (current >= argc)
11386 goto err;
11387 if (Jim_CompareStringImmediate(interp, argv[current], "then"))
11388 current++;
11389 /* Tsk tsk, no then-clause? */
11390 if (current >= argc)
11391 goto err;
11392 if (boolean)
11393 return Jim_EvalObj(interp, argv[current]);
11394 /* Ok: no else-clause follows */
11395 if (++current >= argc) {
11396 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
11397 return JIM_OK;
11399 falsebody = current++;
11400 if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
11401 /* IIICKS - else-clause isn't last cmd? */
11402 if (current != argc - 1)
11403 goto err;
11404 return Jim_EvalObj(interp, argv[current]);
11406 else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
11407 /* Ok: elseif follows meaning all the stuff
11408 * again (how boring...) */
11409 continue;
11410 /* OOPS - else-clause is not last cmd? */
11411 else if (falsebody != argc - 1)
11412 goto err;
11413 return Jim_EvalObj(interp, argv[falsebody]);
11415 return JIM_OK;
11417 err:
11418 Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11419 return JIM_ERR;
11423 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11424 int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
11425 Jim_Obj *stringObj, int nocase)
11427 Jim_Obj *parms[4];
11428 int argc = 0;
11429 long eq;
11430 int rc;
11432 parms[argc++] = commandObj;
11433 if (nocase) {
11434 parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
11436 parms[argc++] = patternObj;
11437 parms[argc++] = stringObj;
11439 rc = Jim_EvalObjVector(interp, argc, parms);
11441 if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
11442 eq = -rc;
11445 return eq;
11448 enum
11449 { SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
11451 /* [switch] */
11452 static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11454 int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
11455 Jim_Obj *command = 0, *const *caseList = 0, *strObj;
11456 Jim_Obj *script = 0;
11458 if (argc < 3) {
11459 wrongnumargs:
11460 Jim_WrongNumArgs(interp, 1, argv, "?options? string "
11461 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11462 return JIM_ERR;
11464 for (opt = 1; opt < argc; ++opt) {
11465 const char *option = Jim_String(argv[opt]);
11467 if (*option != '-')
11468 break;
11469 else if (strncmp(option, "--", 2) == 0) {
11470 ++opt;
11471 break;
11473 else if (strncmp(option, "-exact", 2) == 0)
11474 matchOpt = SWITCH_EXACT;
11475 else if (strncmp(option, "-glob", 2) == 0)
11476 matchOpt = SWITCH_GLOB;
11477 else if (strncmp(option, "-regexp", 2) == 0)
11478 matchOpt = SWITCH_RE;
11479 else if (strncmp(option, "-command", 2) == 0) {
11480 matchOpt = SWITCH_CMD;
11481 if ((argc - opt) < 2)
11482 goto wrongnumargs;
11483 command = argv[++opt];
11485 else {
11486 Jim_SetResultFormatted(interp,
11487 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11488 argv[opt]);
11489 return JIM_ERR;
11491 if ((argc - opt) < 2)
11492 goto wrongnumargs;
11494 strObj = argv[opt++];
11495 patCount = argc - opt;
11496 if (patCount == 1) {
11497 Jim_Obj **vector;
11499 JimListGetElements(interp, argv[opt], &patCount, &vector);
11500 caseList = vector;
11502 else
11503 caseList = &argv[opt];
11504 if (patCount == 0 || patCount % 2 != 0)
11505 goto wrongnumargs;
11506 for (i = 0; script == 0 && i < patCount; i += 2) {
11507 Jim_Obj *patObj = caseList[i];
11509 if (!Jim_CompareStringImmediate(interp, patObj, "default")
11510 || i < (patCount - 2)) {
11511 switch (matchOpt) {
11512 case SWITCH_EXACT:
11513 if (Jim_StringEqObj(strObj, patObj))
11514 script = caseList[i + 1];
11515 break;
11516 case SWITCH_GLOB:
11517 if (Jim_StringMatchObj(interp, patObj, strObj, 0))
11518 script = caseList[i + 1];
11519 break;
11520 case SWITCH_RE:
11521 command = Jim_NewStringObj(interp, "regexp", -1);
11522 /* Fall thru intentionally */
11523 case SWITCH_CMD:{
11524 int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, 0);
11526 /* After the execution of a command we need to
11527 * make sure to reconvert the object into a list
11528 * again. Only for the single-list style [switch]. */
11529 if (argc - opt == 1) {
11530 Jim_Obj **vector;
11532 JimListGetElements(interp, argv[opt], &patCount, &vector);
11533 caseList = vector;
11535 /* command is here already decref'd */
11536 if (rc < 0) {
11537 return -rc;
11539 if (rc)
11540 script = caseList[i + 1];
11541 break;
11545 else {
11546 script = caseList[i + 1];
11549 for (; i < patCount && Jim_CompareStringImmediate(interp, script, "-"); i += 2)
11550 script = caseList[i + 1];
11551 if (script && Jim_CompareStringImmediate(interp, script, "-")) {
11552 Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
11553 return JIM_ERR;
11555 Jim_SetEmptyResult(interp);
11556 if (script) {
11557 return Jim_EvalObj(interp, script);
11559 return JIM_OK;
11562 /* [list] */
11563 static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11565 Jim_Obj *listObjPtr;
11567 listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
11568 Jim_SetResult(interp, listObjPtr);
11569 return JIM_OK;
11572 /* [lindex] */
11573 static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11575 Jim_Obj *objPtr, *listObjPtr;
11576 int i;
11577 int idx;
11579 if (argc < 3) {
11580 Jim_WrongNumArgs(interp, 1, argv, "list index ?...?");
11581 return JIM_ERR;
11583 objPtr = argv[1];
11584 Jim_IncrRefCount(objPtr);
11585 for (i = 2; i < argc; i++) {
11586 listObjPtr = objPtr;
11587 if (Jim_GetIndex(interp, argv[i], &idx) != JIM_OK) {
11588 Jim_DecrRefCount(interp, listObjPtr);
11589 return JIM_ERR;
11591 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_NONE) != JIM_OK) {
11592 /* Returns an empty object if the index
11593 * is out of range. */
11594 Jim_DecrRefCount(interp, listObjPtr);
11595 Jim_SetEmptyResult(interp);
11596 return JIM_OK;
11598 Jim_IncrRefCount(objPtr);
11599 Jim_DecrRefCount(interp, listObjPtr);
11601 Jim_SetResult(interp, objPtr);
11602 Jim_DecrRefCount(interp, objPtr);
11603 return JIM_OK;
11606 /* [llength] */
11607 static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11609 if (argc != 2) {
11610 Jim_WrongNumArgs(interp, 1, argv, "list");
11611 return JIM_ERR;
11613 Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
11614 return JIM_OK;
11617 /* [lsearch] */
11618 static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11620 static const char * const options[] = {
11621 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11622 NULL
11624 enum
11625 { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
11626 OPT_COMMAND };
11627 int i;
11628 int opt_bool = 0;
11629 int opt_not = 0;
11630 int opt_nocase = 0;
11631 int opt_all = 0;
11632 int opt_inline = 0;
11633 int opt_match = OPT_EXACT;
11634 int listlen;
11635 int rc = JIM_OK;
11636 Jim_Obj *listObjPtr = NULL;
11637 Jim_Obj *commandObj = NULL;
11639 if (argc < 3) {
11640 wrongargs:
11641 Jim_WrongNumArgs(interp, 1, argv,
11642 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11643 return JIM_ERR;
11646 for (i = 1; i < argc - 2; i++) {
11647 int option;
11649 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
11650 return JIM_ERR;
11652 switch (option) {
11653 case OPT_BOOL:
11654 opt_bool = 1;
11655 opt_inline = 0;
11656 break;
11657 case OPT_NOT:
11658 opt_not = 1;
11659 break;
11660 case OPT_NOCASE:
11661 opt_nocase = 1;
11662 break;
11663 case OPT_INLINE:
11664 opt_inline = 1;
11665 opt_bool = 0;
11666 break;
11667 case OPT_ALL:
11668 opt_all = 1;
11669 break;
11670 case OPT_COMMAND:
11671 if (i >= argc - 2) {
11672 goto wrongargs;
11674 commandObj = argv[++i];
11675 /* fallthru */
11676 case OPT_EXACT:
11677 case OPT_GLOB:
11678 case OPT_REGEXP:
11679 opt_match = option;
11680 break;
11684 argv += i;
11686 if (opt_all) {
11687 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11689 if (opt_match == OPT_REGEXP) {
11690 commandObj = Jim_NewStringObj(interp, "regexp", -1);
11692 if (commandObj) {
11693 Jim_IncrRefCount(commandObj);
11696 listlen = Jim_ListLength(interp, argv[0]);
11697 for (i = 0; i < listlen; i++) {
11698 Jim_Obj *objPtr;
11699 int eq = 0;
11701 Jim_ListIndex(interp, argv[0], i, &objPtr, JIM_NONE);
11702 switch (opt_match) {
11703 case OPT_EXACT:
11704 eq = Jim_StringCompareObj(interp, objPtr, argv[1], opt_nocase) == 0;
11705 break;
11707 case OPT_GLOB:
11708 eq = Jim_StringMatchObj(interp, argv[1], objPtr, opt_nocase);
11709 break;
11711 case OPT_REGEXP:
11712 case OPT_COMMAND:
11713 eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, opt_nocase);
11714 if (eq < 0) {
11715 if (listObjPtr) {
11716 Jim_FreeNewObj(interp, listObjPtr);
11718 rc = JIM_ERR;
11719 goto done;
11721 break;
11724 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11725 if (!eq && opt_bool && opt_not && !opt_all) {
11726 continue;
11729 if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
11730 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11731 Jim_Obj *resultObj;
11733 if (opt_bool) {
11734 resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
11736 else if (!opt_inline) {
11737 resultObj = Jim_NewIntObj(interp, i);
11739 else {
11740 resultObj = objPtr;
11743 if (opt_all) {
11744 Jim_ListAppendElement(interp, listObjPtr, resultObj);
11746 else {
11747 Jim_SetResult(interp, resultObj);
11748 goto done;
11753 if (opt_all) {
11754 Jim_SetResult(interp, listObjPtr);
11756 else {
11757 /* No match */
11758 if (opt_bool) {
11759 Jim_SetResultBool(interp, opt_not);
11761 else if (!opt_inline) {
11762 Jim_SetResultInt(interp, -1);
11766 done:
11767 if (commandObj) {
11768 Jim_DecrRefCount(interp, commandObj);
11770 return rc;
11773 /* [lappend] */
11774 static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11776 Jim_Obj *listObjPtr;
11777 int shared, i;
11779 if (argc < 2) {
11780 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
11781 return JIM_ERR;
11783 listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
11784 if (!listObjPtr) {
11785 /* Create the list if it does not exists */
11786 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11787 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11788 Jim_FreeNewObj(interp, listObjPtr);
11789 return JIM_ERR;
11792 shared = Jim_IsShared(listObjPtr);
11793 if (shared)
11794 listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
11795 for (i = 2; i < argc; i++)
11796 Jim_ListAppendElement(interp, listObjPtr, argv[i]);
11797 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11798 if (shared)
11799 Jim_FreeNewObj(interp, listObjPtr);
11800 return JIM_ERR;
11802 Jim_SetResult(interp, listObjPtr);
11803 return JIM_OK;
11806 /* [linsert] */
11807 static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11809 int idx, len;
11810 Jim_Obj *listPtr;
11812 if (argc < 4) {
11813 Jim_WrongNumArgs(interp, 1, argv, "list index element " "?element ...?");
11814 return JIM_ERR;
11816 listPtr = argv[1];
11817 if (Jim_IsShared(listPtr))
11818 listPtr = Jim_DuplicateObj(interp, listPtr);
11819 if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
11820 goto err;
11821 len = Jim_ListLength(interp, listPtr);
11822 if (idx >= len)
11823 idx = len;
11824 else if (idx < 0)
11825 idx = len + idx + 1;
11826 Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
11827 Jim_SetResult(interp, listPtr);
11828 return JIM_OK;
11829 err:
11830 if (listPtr != argv[1]) {
11831 Jim_FreeNewObj(interp, listPtr);
11833 return JIM_ERR;
11836 /* [lreplace] */
11837 static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11839 int first, last, len, rangeLen;
11840 Jim_Obj *listObj;
11841 Jim_Obj *newListObj;
11842 int i;
11843 int shared;
11845 if (argc < 4) {
11846 Jim_WrongNumArgs(interp, 1, argv, "list first last ?element element ...?");
11847 return JIM_ERR;
11849 if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
11850 Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
11851 return JIM_ERR;
11854 listObj = argv[1];
11855 len = Jim_ListLength(interp, listObj);
11857 first = JimRelToAbsIndex(len, first);
11858 last = JimRelToAbsIndex(len, last);
11859 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
11861 /* Now construct a new list which consists of:
11862 * <elements before first> <supplied elements> <elements after last>
11865 /* Check to see if trying to replace past the end of the list */
11866 if (first < len) {
11867 /* OK. Not past the end */
11869 else if (len == 0) {
11870 /* Special for empty list, adjust first to 0 */
11871 first = 0;
11873 else {
11874 Jim_SetResultString(interp, "list doesn't contain element ", -1);
11875 Jim_AppendObj(interp, Jim_GetResult(interp), argv[2]);
11876 return JIM_ERR;
11879 newListObj = Jim_NewListObj(interp, NULL, 0);
11881 shared = Jim_IsShared(listObj);
11882 if (shared) {
11883 listObj = Jim_DuplicateObj(interp, listObj);
11886 /* Add the first set of elements */
11887 for (i = 0; i < first; i++) {
11888 Jim_ListAppendElement(interp, newListObj, listObj->internalRep.listValue.ele[i]);
11891 /* Add supplied elements */
11892 for (i = 4; i < argc; i++) {
11893 Jim_ListAppendElement(interp, newListObj, argv[i]);
11896 /* Add the remaining elements */
11897 for (i = first + rangeLen; i < len; i++) {
11898 Jim_ListAppendElement(interp, newListObj, listObj->internalRep.listValue.ele[i]);
11900 Jim_SetResult(interp, newListObj);
11901 if (shared) {
11902 Jim_FreeNewObj(interp, listObj);
11904 return JIM_OK;
11907 /* [lset] */
11908 static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11910 if (argc < 3) {
11911 Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");
11912 return JIM_ERR;
11914 else if (argc == 3) {
11915 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
11916 return JIM_ERR;
11917 Jim_SetResult(interp, argv[2]);
11918 return JIM_OK;
11920 if (Jim_SetListIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1])
11921 == JIM_ERR)
11922 return JIM_ERR;
11923 return JIM_OK;
11926 /* [lsort] */
11927 static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
11929 static const char * const options[] = {
11930 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11932 enum
11933 { OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_INDEX };
11934 Jim_Obj *resObj;
11935 int i;
11936 int retCode;
11938 struct lsort_info info;
11940 if (argc < 2) {
11941 Jim_WrongNumArgs(interp, 1, argv, "?options? list");
11942 return JIM_ERR;
11945 info.type = JIM_LSORT_ASCII;
11946 info.order = 1;
11947 info.indexed = 0;
11948 info.command = NULL;
11949 info.interp = interp;
11951 for (i = 1; i < (argc - 1); i++) {
11952 int option;
11954 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG)
11955 != JIM_OK)
11956 return JIM_ERR;
11957 switch (option) {
11958 case OPT_ASCII:
11959 info.type = JIM_LSORT_ASCII;
11960 break;
11961 case OPT_NOCASE:
11962 info.type = JIM_LSORT_NOCASE;
11963 break;
11964 case OPT_INTEGER:
11965 info.type = JIM_LSORT_INTEGER;
11966 break;
11967 case OPT_INCREASING:
11968 info.order = 1;
11969 break;
11970 case OPT_DECREASING:
11971 info.order = -1;
11972 break;
11973 case OPT_COMMAND:
11974 if (i >= (argc - 2)) {
11975 Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
11976 return JIM_ERR;
11978 info.type = JIM_LSORT_COMMAND;
11979 info.command = argv[i + 1];
11980 i++;
11981 break;
11982 case OPT_INDEX:
11983 if (i >= (argc - 2)) {
11984 Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
11985 return JIM_ERR;
11987 if (Jim_GetIndex(interp, argv[i + 1], &info.index) != JIM_OK) {
11988 return JIM_ERR;
11990 info.indexed = 1;
11991 i++;
11992 break;
11995 resObj = Jim_DuplicateObj(interp, argv[argc - 1]);
11996 retCode = ListSortElements(interp, resObj, &info);
11997 if (retCode == JIM_OK) {
11998 Jim_SetResult(interp, resObj);
12000 else {
12001 Jim_FreeNewObj(interp, resObj);
12003 return retCode;
12006 /* [append] */
12007 static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12009 Jim_Obj *stringObjPtr;
12010 int i;
12012 if (argc < 2) {
12013 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
12014 return JIM_ERR;
12016 if (argc == 2) {
12017 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
12018 if (!stringObjPtr)
12019 return JIM_ERR;
12021 else {
12022 int freeobj = 0;
12023 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
12024 if (!stringObjPtr) {
12025 /* Create the string if it doesn't exist */
12026 stringObjPtr = Jim_NewEmptyStringObj(interp);
12027 freeobj = 1;
12029 else if (Jim_IsShared(stringObjPtr)) {
12030 freeobj = 1;
12031 stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
12033 for (i = 2; i < argc; i++) {
12034 Jim_AppendObj(interp, stringObjPtr, argv[i]);
12036 if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
12037 if (freeobj) {
12038 Jim_FreeNewObj(interp, stringObjPtr);
12040 return JIM_ERR;
12043 Jim_SetResult(interp, stringObjPtr);
12044 return JIM_OK;
12047 /* [debug] */
12048 static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12050 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12051 static const char * const options[] = {
12052 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12053 "exprbc", "show",
12054 NULL
12056 enum
12058 OPT_REFCOUNT, OPT_OBJCOUNT, OPT_OBJECTS, OPT_INVSTR, OPT_SCRIPTLEN,
12059 OPT_EXPRLEN, OPT_EXPRBC, OPT_SHOW,
12061 int option;
12063 if (argc < 2) {
12064 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?...?");
12065 return JIM_ERR;
12067 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK)
12068 return JIM_ERR;
12069 if (option == OPT_REFCOUNT) {
12070 if (argc != 3) {
12071 Jim_WrongNumArgs(interp, 2, argv, "object");
12072 return JIM_ERR;
12074 Jim_SetResultInt(interp, argv[2]->refCount);
12075 return JIM_OK;
12077 else if (option == OPT_OBJCOUNT) {
12078 int freeobj = 0, liveobj = 0;
12079 char buf[256];
12080 Jim_Obj *objPtr;
12082 if (argc != 2) {
12083 Jim_WrongNumArgs(interp, 2, argv, "");
12084 return JIM_ERR;
12086 /* Count the number of free objects. */
12087 objPtr = interp->freeList;
12088 while (objPtr) {
12089 freeobj++;
12090 objPtr = objPtr->nextObjPtr;
12092 /* Count the number of live objects. */
12093 objPtr = interp->liveList;
12094 while (objPtr) {
12095 liveobj++;
12096 objPtr = objPtr->nextObjPtr;
12098 /* Set the result string and return. */
12099 sprintf(buf, "free %d used %d", freeobj, liveobj);
12100 Jim_SetResultString(interp, buf, -1);
12101 return JIM_OK;
12103 else if (option == OPT_OBJECTS) {
12104 Jim_Obj *objPtr, *listObjPtr, *subListObjPtr;
12106 /* Count the number of live objects. */
12107 objPtr = interp->liveList;
12108 listObjPtr = Jim_NewListObj(interp, NULL, 0);
12109 while (objPtr) {
12110 char buf[128];
12111 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "";
12113 subListObjPtr = Jim_NewListObj(interp, NULL, 0);
12114 sprintf(buf, "%p", objPtr);
12115 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, buf, -1));
12116 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, type, -1));
12117 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewIntObj(interp, objPtr->refCount));
12118 Jim_ListAppendElement(interp, subListObjPtr, objPtr);
12119 Jim_ListAppendElement(interp, listObjPtr, subListObjPtr);
12120 objPtr = objPtr->nextObjPtr;
12122 Jim_SetResult(interp, listObjPtr);
12123 return JIM_OK;
12125 else if (option == OPT_INVSTR) {
12126 Jim_Obj *objPtr;
12128 if (argc != 3) {
12129 Jim_WrongNumArgs(interp, 2, argv, "object");
12130 return JIM_ERR;
12132 objPtr = argv[2];
12133 if (objPtr->typePtr != NULL)
12134 Jim_InvalidateStringRep(objPtr);
12135 Jim_SetEmptyResult(interp);
12136 return JIM_OK;
12138 else if (option == OPT_SHOW) {
12139 const char *s;
12140 int len, charlen;
12142 if (argc != 3) {
12143 Jim_WrongNumArgs(interp, 2, argv, "object");
12144 return JIM_ERR;
12146 s = Jim_GetString(argv[2], &len);
12147 #ifdef JIM_UTF8
12148 charlen = utf8_strlen(s, len);
12149 #else
12150 charlen = len;
12151 #endif
12152 printf("refcount: %d, type: %s\n", argv[2]->refCount, JimObjTypeName(argv[2]));
12153 printf("chars (%d): <<%s>>\n", charlen, s);
12154 printf("bytes (%d):", len);
12155 while (len--) {
12156 printf(" %02x", (unsigned char)*s++);
12158 printf("\n");
12159 return JIM_OK;
12161 else if (option == OPT_SCRIPTLEN) {
12162 ScriptObj *script;
12164 if (argc != 3) {
12165 Jim_WrongNumArgs(interp, 2, argv, "script");
12166 return JIM_ERR;
12168 script = Jim_GetScript(interp, argv[2]);
12169 Jim_SetResultInt(interp, script->len);
12170 return JIM_OK;
12172 else if (option == OPT_EXPRLEN) {
12173 ExprByteCode *expr;
12175 if (argc != 3) {
12176 Jim_WrongNumArgs(interp, 2, argv, "expression");
12177 return JIM_ERR;
12179 expr = JimGetExpression(interp, argv[2]);
12180 if (expr == NULL)
12181 return JIM_ERR;
12182 Jim_SetResultInt(interp, expr->len);
12183 return JIM_OK;
12185 else if (option == OPT_EXPRBC) {
12186 Jim_Obj *objPtr;
12187 ExprByteCode *expr;
12188 int i;
12190 if (argc != 3) {
12191 Jim_WrongNumArgs(interp, 2, argv, "expression");
12192 return JIM_ERR;
12194 expr = JimGetExpression(interp, argv[2]);
12195 if (expr == NULL)
12196 return JIM_ERR;
12197 objPtr = Jim_NewListObj(interp, NULL, 0);
12198 for (i = 0; i < expr->len; i++) {
12199 const char *type;
12200 const Jim_ExprOperator *op;
12201 Jim_Obj *obj = expr->token[i].objPtr;
12203 switch (expr->token[i].type) {
12204 case JIM_TT_EXPR_INT:
12205 type = "int";
12206 break;
12207 case JIM_TT_EXPR_DOUBLE:
12208 type = "double";
12209 break;
12210 case JIM_TT_CMD:
12211 type = "command";
12212 break;
12213 case JIM_TT_VAR:
12214 type = "variable";
12215 break;
12216 case JIM_TT_DICTSUGAR:
12217 type = "dictsugar";
12218 break;
12219 case JIM_TT_EXPRSUGAR:
12220 type = "exprsugar";
12221 break;
12222 case JIM_TT_ESC:
12223 type = "subst";
12224 break;
12225 case JIM_TT_STR:
12226 type = "string";
12227 break;
12228 default:
12229 op = JimExprOperatorInfoByOpcode(expr->token[i].type);
12230 if (op == NULL) {
12231 type = "private";
12233 else {
12234 type = "operator";
12236 obj = Jim_NewStringObj(interp, op ? op->name : "", -1);
12237 break;
12239 Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, type, -1));
12240 Jim_ListAppendElement(interp, objPtr, obj);
12242 Jim_SetResult(interp, objPtr);
12243 return JIM_OK;
12245 else {
12246 Jim_SetResultString(interp,
12247 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12248 return JIM_ERR;
12250 /* unreached */
12251 #endif /* JIM_BOOTSTRAP */
12252 #if !defined(JIM_DEBUG_COMMAND)
12253 Jim_SetResultString(interp, "unsupported", -1);
12254 return JIM_ERR;
12255 #endif
12258 /* [eval] */
12259 static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12261 int rc;
12263 if (argc < 2) {
12264 Jim_WrongNumArgs(interp, 1, argv, "script ?...?");
12265 return JIM_ERR;
12268 if (argc == 2) {
12269 rc = Jim_EvalObj(interp, argv[1]);
12271 else {
12272 rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12275 if (rc == JIM_ERR) {
12276 /* eval is "interesting", so add a stack frame here */
12277 interp->addStackTrace++;
12279 return rc;
12282 /* [uplevel] */
12283 static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12285 if (argc >= 2) {
12286 int retcode;
12287 Jim_CallFrame *savedCallFrame, *targetCallFrame;
12288 Jim_Obj *objPtr;
12289 const char *str;
12291 /* Save the old callframe pointer */
12292 savedCallFrame = interp->framePtr;
12294 /* Lookup the target frame pointer */
12295 str = Jim_String(argv[1]);
12296 if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
12297 targetCallFrame =Jim_GetCallFrameByLevel(interp, argv[1]);
12298 argc--;
12299 argv++;
12301 else {
12302 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12304 if (targetCallFrame == NULL) {
12305 return JIM_ERR;
12307 if (argc < 2) {
12308 argv--;
12309 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12310 return JIM_ERR;
12312 /* Eval the code in the target callframe. */
12313 interp->framePtr = targetCallFrame;
12314 if (argc == 2) {
12315 retcode = Jim_EvalObj(interp, argv[1]);
12317 else {
12318 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12319 Jim_IncrRefCount(objPtr);
12320 retcode = Jim_EvalObj(interp, objPtr);
12321 Jim_DecrRefCount(interp, objPtr);
12323 interp->framePtr = savedCallFrame;
12324 return retcode;
12326 else {
12327 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12328 return JIM_ERR;
12332 /* [expr] */
12333 static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12335 Jim_Obj *exprResultPtr;
12336 int retcode;
12338 if (argc == 2) {
12339 retcode = Jim_EvalExpression(interp, argv[1], &exprResultPtr);
12341 else if (argc > 2) {
12342 Jim_Obj *objPtr;
12344 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12345 Jim_IncrRefCount(objPtr);
12346 retcode = Jim_EvalExpression(interp, objPtr, &exprResultPtr);
12347 Jim_DecrRefCount(interp, objPtr);
12349 else {
12350 Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
12351 return JIM_ERR;
12353 if (retcode != JIM_OK)
12354 return retcode;
12355 Jim_SetResult(interp, exprResultPtr);
12356 Jim_DecrRefCount(interp, exprResultPtr);
12357 return JIM_OK;
12360 /* [break] */
12361 static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12363 if (argc != 1) {
12364 Jim_WrongNumArgs(interp, 1, argv, "");
12365 return JIM_ERR;
12367 return JIM_BREAK;
12370 /* [continue] */
12371 static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12373 if (argc != 1) {
12374 Jim_WrongNumArgs(interp, 1, argv, "");
12375 return JIM_ERR;
12377 return JIM_CONTINUE;
12380 /* [return] */
12381 static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12383 int i;
12384 Jim_Obj *stackTraceObj = NULL;
12385 Jim_Obj *errorCodeObj = NULL;
12386 int returnCode = JIM_OK;
12387 long level = 1;
12389 for (i = 1; i < argc - 1; i += 2) {
12390 if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
12391 if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
12392 return JIM_ERR;
12395 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
12396 stackTraceObj = argv[i + 1];
12398 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
12399 errorCodeObj = argv[i + 1];
12401 else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
12402 if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
12403 Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
12404 return JIM_ERR;
12407 else {
12408 break;
12412 if (i != argc - 1 && i != argc) {
12413 Jim_WrongNumArgs(interp, 1, argv,
12414 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12417 /* If a stack trace is supplied and code is error, set the stack trace */
12418 if (stackTraceObj && returnCode == JIM_ERR) {
12419 JimSetStackTrace(interp, stackTraceObj);
12421 /* If an error code list is supplied, set the global $errorCode */
12422 if (errorCodeObj && returnCode == JIM_ERR) {
12423 Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
12425 interp->returnCode = returnCode;
12426 interp->returnLevel = level;
12428 if (i == argc - 1) {
12429 Jim_SetResult(interp, argv[i]);
12431 return JIM_RETURN;
12434 /* [tailcall] */
12435 static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12437 Jim_Obj *objPtr;
12439 objPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
12440 Jim_SetResult(interp, objPtr);
12441 return JIM_EVAL;
12444 /* [proc] */
12445 static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12447 if (argc != 4 && argc != 5) {
12448 Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
12449 return JIM_ERR;
12452 if (argc == 4) {
12453 return JimCreateProcedure(interp, argv[1], argv[2], NULL, argv[3]);
12455 else {
12456 return JimCreateProcedure(interp, argv[1], argv[2], argv[3], argv[4]);
12460 /* [local] */
12461 static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12463 int retcode;
12465 /* Evaluate the arguments with 'local' in force */
12466 interp->local++;
12467 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12468 interp->local--;
12471 /* If OK, and the result is a proc, add it to the list of local procs */
12472 if (retcode == 0) {
12473 const char *procname = Jim_String(Jim_GetResult(interp));
12475 if (Jim_FindHashEntry(&interp->commands, procname) == NULL) {
12476 Jim_SetResultFormatted(interp, "not a proc: \"%s\"", procname);
12477 return JIM_ERR;
12479 if (interp->localProcs == NULL) {
12480 interp->localProcs = Jim_Alloc(sizeof(*interp->localProcs));
12481 Jim_InitStack(interp->localProcs);
12483 Jim_StackPush(interp->localProcs, Jim_StrDup(procname));
12486 return retcode;
12489 /* [upcall] */
12490 static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12492 if (argc < 2) {
12493 Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
12494 return JIM_ERR;
12496 else {
12497 int retcode;
12499 Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
12500 if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->u.proc.prevCmd) {
12501 Jim_SetResultFormatted(interp, "no previous proc: \"%#s\"", argv[1]);
12502 return JIM_ERR;
12504 /* OK. Mark this command as being in an upcall */
12505 cmdPtr->u.proc.upcall++;
12506 JimIncrCmdRefCount(cmdPtr);
12508 /* Invoke the command as normal */
12509 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12511 /* No longer in an upcall */
12512 cmdPtr->u.proc.upcall--;
12513 JimDecrCmdRefCount(interp, cmdPtr);
12515 return retcode;
12519 /* [concat] */
12520 static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12522 Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12523 return JIM_OK;
12526 /* [upvar] */
12527 static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12529 int i;
12530 Jim_CallFrame *targetCallFrame;
12532 /* Lookup the target frame pointer */
12533 if (argc > 3 && (argc % 2 == 0)) {
12534 targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
12535 argc--;
12536 argv++;
12538 else {
12539 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12541 if (targetCallFrame == NULL) {
12542 return JIM_ERR;
12545 /* Check for arity */
12546 if (argc < 3) {
12547 Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
12548 return JIM_ERR;
12551 /* Now... for every other/local couple: */
12552 for (i = 1; i < argc; i += 2) {
12553 if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
12554 return JIM_ERR;
12556 return JIM_OK;
12559 /* [global] */
12560 static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12562 int i;
12564 if (argc < 2) {
12565 Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
12566 return JIM_ERR;
12568 /* Link every var to the toplevel having the same name */
12569 if (interp->framePtr->level == 0)
12570 return JIM_OK; /* global at toplevel... */
12571 for (i = 1; i < argc; i++) {
12572 if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
12573 return JIM_ERR;
12575 return JIM_OK;
12578 /* does the [string map] operation. On error NULL is returned,
12579 * otherwise a new string object with the result, having refcount = 0,
12580 * is returned. */
12581 static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
12582 Jim_Obj *objPtr, int nocase)
12584 int numMaps;
12585 const char *str, *noMatchStart = NULL;
12586 int strLen, i;
12587 Jim_Obj *resultObjPtr;
12589 numMaps = Jim_ListLength(interp, mapListObjPtr);
12590 if (numMaps % 2) {
12591 Jim_SetResultString(interp, "list must contain an even number of elements", -1);
12592 return NULL;
12595 str = Jim_String(objPtr);
12596 strLen = Jim_Utf8Length(interp, objPtr);
12598 /* Map it */
12599 resultObjPtr = Jim_NewStringObj(interp, "", 0);
12600 while (strLen) {
12601 for (i = 0; i < numMaps; i += 2) {
12602 Jim_Obj *objPtr;
12603 const char *k;
12604 int kl;
12606 Jim_ListIndex(interp, mapListObjPtr, i, &objPtr, JIM_NONE);
12607 k = Jim_String(objPtr);
12608 kl = Jim_Utf8Length(interp, objPtr);
12610 if (strLen >= kl && kl) {
12611 int rc;
12612 if (nocase) {
12613 rc = JimStringCompareNoCase(str, k, kl);
12615 else {
12616 rc = JimStringCompare(str, kl, k, kl);
12618 if (rc == 0) {
12619 if (noMatchStart) {
12620 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12621 noMatchStart = NULL;
12623 Jim_ListIndex(interp, mapListObjPtr, i + 1, &objPtr, JIM_NONE);
12624 Jim_AppendObj(interp, resultObjPtr, objPtr);
12625 str += utf8_index(str, kl);
12626 strLen -= kl;
12627 break;
12631 if (i == numMaps) { /* no match */
12632 int c;
12633 if (noMatchStart == NULL)
12634 noMatchStart = str;
12635 str += utf8_tounicode(str, &c);
12636 strLen--;
12639 if (noMatchStart) {
12640 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12642 return resultObjPtr;
12645 /* [string] */
12646 static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12648 int len;
12649 int opt_case = 1;
12650 int option;
12651 static const char * const options[] = {
12652 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12653 "repeat", "reverse", "index", "first", "last",
12654 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12656 enum
12658 OPT_BYTELENGTH, OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_IS, OPT_BYTERANGE, OPT_RANGE, OPT_MAP,
12659 OPT_REPEAT, OPT_REVERSE, OPT_INDEX, OPT_FIRST, OPT_LAST,
12660 OPT_TRIM, OPT_TRIMLEFT, OPT_TRIMRIGHT, OPT_TOLOWER, OPT_TOUPPER
12662 static const char * const nocase_options[] = {
12663 "-nocase", NULL
12666 if (argc < 2) {
12667 Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
12668 return JIM_ERR;
12670 if (Jim_GetEnum(interp, argv[1], options, &option, NULL,
12671 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK)
12672 return JIM_ERR;
12674 switch (option) {
12675 case OPT_LENGTH:
12676 case OPT_BYTELENGTH:
12677 if (argc != 3) {
12678 Jim_WrongNumArgs(interp, 2, argv, "string");
12679 return JIM_ERR;
12681 if (option == OPT_LENGTH) {
12682 len = Jim_Utf8Length(interp, argv[2]);
12684 else {
12685 len = Jim_Length(argv[2]);
12687 Jim_SetResultInt(interp, len);
12688 return JIM_OK;
12690 case OPT_COMPARE:
12691 case OPT_EQUAL:
12692 if (argc != 4 &&
12693 (argc != 5 ||
12694 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12695 JIM_ENUM_ABBREV) != JIM_OK)) {
12696 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? string1 string2");
12697 return JIM_ERR;
12699 if (opt_case == 0) {
12700 argv++;
12702 if (option == OPT_COMPARE || !opt_case) {
12703 Jim_SetResultInt(interp, Jim_StringCompareObj(interp, argv[2], argv[3], !opt_case));
12705 else {
12706 Jim_SetResultBool(interp, Jim_StringEqObj(argv[2], argv[3]));
12708 return JIM_OK;
12710 case OPT_MATCH:
12711 if (argc != 4 &&
12712 (argc != 5 ||
12713 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12714 JIM_ENUM_ABBREV) != JIM_OK)) {
12715 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
12716 return JIM_ERR;
12718 if (opt_case == 0) {
12719 argv++;
12721 Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
12722 return JIM_OK;
12724 case OPT_MAP:{
12725 Jim_Obj *objPtr;
12727 if (argc != 4 &&
12728 (argc != 5 ||
12729 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12730 JIM_ENUM_ABBREV) != JIM_OK)) {
12731 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
12732 return JIM_ERR;
12735 if (opt_case == 0) {
12736 argv++;
12738 objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
12739 if (objPtr == NULL) {
12740 return JIM_ERR;
12742 Jim_SetResult(interp, objPtr);
12743 return JIM_OK;
12746 case OPT_RANGE:
12747 case OPT_BYTERANGE:{
12748 Jim_Obj *objPtr;
12750 if (argc != 5) {
12751 Jim_WrongNumArgs(interp, 2, argv, "string first last");
12752 return JIM_ERR;
12754 if (option == OPT_RANGE) {
12755 objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
12757 else
12759 objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
12762 if (objPtr == NULL) {
12763 return JIM_ERR;
12765 Jim_SetResult(interp, objPtr);
12766 return JIM_OK;
12769 case OPT_REPEAT:{
12770 Jim_Obj *objPtr;
12771 jim_wide count;
12773 if (argc != 4) {
12774 Jim_WrongNumArgs(interp, 2, argv, "string count");
12775 return JIM_ERR;
12777 if (Jim_GetWide(interp, argv[3], &count) != JIM_OK) {
12778 return JIM_ERR;
12780 objPtr = Jim_NewStringObj(interp, "", 0);
12781 if (count > 0) {
12782 while (count--) {
12783 Jim_AppendObj(interp, objPtr, argv[2]);
12786 Jim_SetResult(interp, objPtr);
12787 return JIM_OK;
12790 case OPT_REVERSE:{
12791 char *buf, *p;
12792 const char *str;
12793 int len;
12794 int i;
12796 if (argc != 3) {
12797 Jim_WrongNumArgs(interp, 2, argv, "string");
12798 return JIM_ERR;
12801 str = Jim_GetString(argv[2], &len);
12802 buf = Jim_Alloc(len + 1);
12803 p = buf + len;
12804 *p = 0;
12805 for (i = 0; i < len; ) {
12806 int c;
12807 int l = utf8_tounicode(str, &c);
12808 memcpy(p - l, str, l);
12809 p -= l;
12810 i += l;
12811 str += l;
12813 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
12814 return JIM_OK;
12817 case OPT_INDEX:{
12818 int idx;
12819 const char *str;
12821 if (argc != 4) {
12822 Jim_WrongNumArgs(interp, 2, argv, "string index");
12823 return JIM_ERR;
12825 if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
12826 return JIM_ERR;
12828 str = Jim_String(argv[2]);
12829 len = Jim_Utf8Length(interp, argv[2]);
12830 if (idx != INT_MIN && idx != INT_MAX) {
12831 idx = JimRelToAbsIndex(len, idx);
12833 if (idx < 0 || idx >= len || str == NULL) {
12834 Jim_SetResultString(interp, "", 0);
12836 else if (len == Jim_Length(argv[2])) {
12837 /* ASCII optimisation */
12838 Jim_SetResultString(interp, str + idx, 1);
12840 else {
12841 int c;
12842 int i = utf8_index(str, idx);
12843 Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
12845 return JIM_OK;
12848 case OPT_FIRST:
12849 case OPT_LAST:{
12850 int idx = 0, l1, l2;
12851 const char *s1, *s2;
12853 if (argc != 4 && argc != 5) {
12854 Jim_WrongNumArgs(interp, 2, argv, "subString string ?index?");
12855 return JIM_ERR;
12857 s1 = Jim_String(argv[2]);
12858 s2 = Jim_String(argv[3]);
12859 l1 = Jim_Utf8Length(interp, argv[2]);
12860 l2 = Jim_Utf8Length(interp, argv[3]);
12861 if (argc == 5) {
12862 if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
12863 return JIM_ERR;
12865 idx = JimRelToAbsIndex(l2, idx);
12867 else if (option == OPT_LAST) {
12868 idx = l2;
12870 if (option == OPT_FIRST) {
12871 Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
12873 else {
12874 #ifdef JIM_UTF8
12875 Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
12876 #else
12877 Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
12878 #endif
12880 return JIM_OK;
12883 case OPT_TRIM:
12884 case OPT_TRIMLEFT:
12885 case OPT_TRIMRIGHT:{
12886 Jim_Obj *trimchars;
12888 if (argc != 3 && argc != 4) {
12889 Jim_WrongNumArgs(interp, 2, argv, "string ?trimchars?");
12890 return JIM_ERR;
12892 trimchars = (argc == 4 ? argv[3] : NULL);
12893 if (option == OPT_TRIM) {
12894 Jim_SetResult(interp, JimStringTrim(interp, argv[2], trimchars));
12896 else if (option == OPT_TRIMLEFT) {
12897 Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], trimchars));
12899 else if (option == OPT_TRIMRIGHT) {
12900 Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], trimchars));
12902 return JIM_OK;
12905 case OPT_TOLOWER:
12906 case OPT_TOUPPER:
12907 if (argc != 3) {
12908 Jim_WrongNumArgs(interp, 2, argv, "string");
12909 return JIM_ERR;
12911 if (option == OPT_TOLOWER) {
12912 Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
12914 else {
12915 Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
12917 return JIM_OK;
12919 case OPT_IS:
12920 if (argc == 4 || (argc == 5 && Jim_CompareStringImmediate(interp, argv[3], "-strict"))) {
12921 return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
12923 Jim_WrongNumArgs(interp, 2, argv, "class ?-strict? str");
12924 return JIM_ERR;
12926 return JIM_OK;
12929 /* [time] */
12930 static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12932 long i, count = 1;
12933 jim_wide start, elapsed;
12934 char buf[60];
12935 const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";
12937 if (argc < 2) {
12938 Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
12939 return JIM_ERR;
12941 if (argc == 3) {
12942 if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
12943 return JIM_ERR;
12945 if (count < 0)
12946 return JIM_OK;
12947 i = count;
12948 start = JimClock();
12949 while (i-- > 0) {
12950 int retval;
12952 retval = Jim_EvalObj(interp, argv[1]);
12953 if (retval != JIM_OK) {
12954 return retval;
12957 elapsed = JimClock() - start;
12958 sprintf(buf, fmt, count == 0 ? 0 : elapsed / count);
12959 Jim_SetResultString(interp, buf, -1);
12960 return JIM_OK;
12963 /* [exit] */
12964 static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12966 long exitCode = 0;
12968 if (argc > 2) {
12969 Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
12970 return JIM_ERR;
12972 if (argc == 2) {
12973 if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
12974 return JIM_ERR;
12976 interp->exitCode = exitCode;
12977 return JIM_EXIT;
12980 /* [catch] */
12981 static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12983 int exitCode = 0;
12984 int i;
12985 int sig = 0;
12987 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
12988 jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
12989 static const int max_ignore_code = sizeof(ignore_mask) * 8;
12991 /* Reset the error code before catch.
12992 * Note that this is not strictly correct.
12994 Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
12996 for (i = 1; i < argc - 1; i++) {
12997 const char *arg = Jim_String(argv[i]);
12998 jim_wide option;
12999 int ignore;
13001 /* It's a pity we can't use Jim_GetEnum here :-( */
13002 if (strcmp(arg, "--") == 0) {
13003 i++;
13004 break;
13006 if (*arg != '-') {
13007 break;
13010 if (strncmp(arg, "-no", 3) == 0) {
13011 arg += 3;
13012 ignore = 1;
13014 else {
13015 arg++;
13016 ignore = 0;
13019 if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
13020 option = -1;
13022 if (option < 0) {
13023 option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
13025 if (option < 0) {
13026 goto wrongargs;
13029 if (ignore) {
13030 ignore_mask |= (1 << option);
13032 else {
13033 ignore_mask &= ~(1 << option);
13037 argc -= i;
13038 if (argc < 1 || argc > 3) {
13039 wrongargs:
13040 Jim_WrongNumArgs(interp, 1, argv,
13041 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13042 return JIM_ERR;
13044 argv += i;
13046 if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
13047 sig++;
13050 interp->signal_level += sig;
13051 if (interp->signal_level && interp->sigmask) {
13052 /* If a signal is set, don't even try to execute the body */
13053 exitCode = JIM_SIGNAL;
13055 else {
13056 exitCode = Jim_EvalObj(interp, argv[0]);
13058 interp->signal_level -= sig;
13060 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13061 if (exitCode >= 0 && exitCode < max_ignore_code && ((1 << exitCode) & ignore_mask)) {
13062 /* Not caught, pass it up */
13063 return exitCode;
13066 if (sig && exitCode == JIM_SIGNAL) {
13067 /* Catch the signal at this level */
13068 if (interp->signal_set_result) {
13069 interp->signal_set_result(interp, interp->sigmask);
13071 else {
13072 Jim_SetResultInt(interp, interp->sigmask);
13074 interp->sigmask = 0;
13077 if (argc >= 2) {
13078 if (Jim_SetVariable(interp, argv[1], Jim_GetResult(interp)) != JIM_OK) {
13079 return JIM_ERR;
13081 if (argc == 3) {
13082 Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
13084 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
13085 Jim_ListAppendElement(interp, optListObj,
13086 Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
13087 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
13088 Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
13089 if (exitCode == JIM_ERR) {
13090 Jim_Obj *errorCode;
13091 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
13092 -1));
13093 Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
13095 errorCode = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
13096 if (errorCode) {
13097 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
13098 Jim_ListAppendElement(interp, optListObj, errorCode);
13101 if (Jim_SetVariable(interp, argv[2], optListObj) != JIM_OK) {
13102 return JIM_ERR;
13106 Jim_SetResultInt(interp, exitCode);
13107 return JIM_OK;
13110 #ifdef JIM_REFERENCES
13112 /* [ref] */
13113 static int Jim_RefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13115 if (argc != 3 && argc != 4) {
13116 Jim_WrongNumArgs(interp, 1, argv, "string tag ?finalizer?");
13117 return JIM_ERR;
13119 if (argc == 3) {
13120 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], NULL));
13122 else {
13123 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], argv[3]));
13125 return JIM_OK;
13128 /* [getref] */
13129 static int Jim_GetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13131 Jim_Reference *refPtr;
13133 if (argc != 2) {
13134 Jim_WrongNumArgs(interp, 1, argv, "reference");
13135 return JIM_ERR;
13137 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13138 return JIM_ERR;
13139 Jim_SetResult(interp, refPtr->objPtr);
13140 return JIM_OK;
13143 /* [setref] */
13144 static int Jim_SetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13146 Jim_Reference *refPtr;
13148 if (argc != 3) {
13149 Jim_WrongNumArgs(interp, 1, argv, "reference newValue");
13150 return JIM_ERR;
13152 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13153 return JIM_ERR;
13154 Jim_IncrRefCount(argv[2]);
13155 Jim_DecrRefCount(interp, refPtr->objPtr);
13156 refPtr->objPtr = argv[2];
13157 Jim_SetResult(interp, argv[2]);
13158 return JIM_OK;
13161 /* [collect] */
13162 static int Jim_CollectCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13164 if (argc != 1) {
13165 Jim_WrongNumArgs(interp, 1, argv, "");
13166 return JIM_ERR;
13168 Jim_SetResultInt(interp, Jim_Collect(interp));
13170 /* Free all the freed objects. */
13171 while (interp->freeList) {
13172 Jim_Obj *nextObjPtr = interp->freeList->nextObjPtr;
13173 Jim_Free(interp->freeList);
13174 interp->freeList = nextObjPtr;
13177 return JIM_OK;
13180 /* [finalize] reference ?newValue? */
13181 static int Jim_FinalizeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13183 if (argc != 2 && argc != 3) {
13184 Jim_WrongNumArgs(interp, 1, argv, "reference ?finalizerProc?");
13185 return JIM_ERR;
13187 if (argc == 2) {
13188 Jim_Obj *cmdNamePtr;
13190 if (Jim_GetFinalizer(interp, argv[1], &cmdNamePtr) != JIM_OK)
13191 return JIM_ERR;
13192 if (cmdNamePtr != NULL) /* otherwise the null string is returned. */
13193 Jim_SetResult(interp, cmdNamePtr);
13195 else {
13196 if (Jim_SetFinalizer(interp, argv[1], argv[2]) != JIM_OK)
13197 return JIM_ERR;
13198 Jim_SetResult(interp, argv[2]);
13200 return JIM_OK;
13203 /* [info references] */
13204 static int JimInfoReferences(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13206 Jim_Obj *listObjPtr;
13207 Jim_HashTableIterator *htiter;
13208 Jim_HashEntry *he;
13210 listObjPtr = Jim_NewListObj(interp, NULL, 0);
13212 htiter = Jim_GetHashTableIterator(&interp->references);
13213 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
13214 char buf[JIM_REFERENCE_SPACE];
13215 Jim_Reference *refPtr = he->u.val;
13216 const jim_wide *refId = he->key;
13218 JimFormatReference(buf, refPtr, *refId);
13219 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, buf, -1));
13221 Jim_FreeHashTableIterator(htiter);
13222 Jim_SetResult(interp, listObjPtr);
13223 return JIM_OK;
13225 #endif
13227 /* [rename] */
13228 static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13230 const char *oldName, *newName;
13232 if (argc != 3) {
13233 Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
13234 return JIM_ERR;
13237 if (JimValidName(interp, "new procedure", argv[2])) {
13238 return JIM_ERR;
13241 oldName = Jim_String(argv[1]);
13242 newName = Jim_String(argv[2]);
13243 return Jim_RenameCommand(interp, oldName, newName);
13246 int Jim_DictKeys(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj)
13248 int i;
13249 int len;
13250 Jim_Obj *resultObj;
13251 Jim_Obj *dictObj;
13252 Jim_Obj **dictValuesObj;
13254 if (Jim_DictKeysVector(interp, objPtr, NULL, 0, &dictObj, JIM_ERRMSG) != JIM_OK) {
13255 return JIM_ERR;
13258 /* XXX: Could make the exact-match case much more efficient here.
13259 * See JimCommandsList()
13261 if (Jim_DictPairs(interp, dictObj, &dictValuesObj, &len) != JIM_OK) {
13262 return JIM_ERR;
13265 /* Only return the matching values */
13266 resultObj = Jim_NewListObj(interp, NULL, 0);
13268 for (i = 0; i < len; i += 2) {
13269 if (patternObj == NULL || Jim_StringMatchObj(interp, patternObj, dictValuesObj[i], 0)) {
13270 Jim_ListAppendElement(interp, resultObj, dictValuesObj[i]);
13273 Jim_Free(dictValuesObj);
13275 Jim_SetResult(interp, resultObj);
13276 return JIM_OK;
13279 int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
13281 if (SetDictFromAny(interp, objPtr) != JIM_OK) {
13282 return -1;
13284 return ((Jim_HashTable *)objPtr->internalRep.ptr)->used;
13287 /* [dict] */
13288 static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13290 Jim_Obj *objPtr;
13291 int option;
13292 static const char * const options[] = {
13293 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13295 enum
13297 OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXIST, OPT_KEYS, OPT_MERGE, OPT_SIZE, OPT_WITH,
13300 if (argc < 2) {
13301 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?arguments ...?");
13302 return JIM_ERR;
13305 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK) {
13306 return JIM_ERR;
13309 switch (option) {
13310 case OPT_GET:
13311 if (argc < 3) {
13312 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13313 return JIM_ERR;
13315 if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
13316 JIM_ERRMSG) != JIM_OK) {
13317 return JIM_ERR;
13319 Jim_SetResult(interp, objPtr);
13320 return JIM_OK;
13322 case OPT_SET:
13323 if (argc < 5) {
13324 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");
13325 return JIM_ERR;
13327 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1], JIM_ERRMSG);
13329 case OPT_EXIST:
13330 if (argc < 3) {
13331 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13332 return JIM_ERR;
13334 Jim_SetResultBool(interp, Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3,
13335 &objPtr, JIM_ERRMSG) == JIM_OK);
13336 return JIM_OK;
13338 case OPT_UNSET:
13339 if (argc < 4) {
13340 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");
13341 return JIM_ERR;
13343 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL, JIM_NONE);
13345 case OPT_KEYS:
13346 if (argc != 3 && argc != 4) {
13347 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?pattern?");
13348 return JIM_ERR;
13350 return Jim_DictKeys(interp, argv[2], argc == 4 ? argv[3] : NULL);
13352 case OPT_SIZE: {
13353 int size;
13355 if (argc != 3) {
13356 Jim_WrongNumArgs(interp, 2, argv, "dictVar");
13357 return JIM_ERR;
13360 size = Jim_DictSize(interp, argv[2]);
13361 if (size < 0) {
13362 return JIM_ERR;
13364 Jim_SetResultInt(interp, size);
13365 return JIM_OK;
13368 case OPT_MERGE:
13369 if (argc == 2) {
13370 return JIM_OK;
13372 else if (argv[2]->typePtr != &dictObjType && SetDictFromAny(interp, argv[2]) != JIM_OK) {
13373 return JIM_ERR;
13375 else {
13376 return Jim_EvalPrefix(interp, "dict merge", argc - 2, argv + 2);
13379 case OPT_WITH:
13380 if (argc < 4) {
13381 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?key ...? script");
13382 return JIM_ERR;
13384 else if (Jim_GetVariable(interp, argv[2], JIM_ERRMSG) == NULL) {
13385 return JIM_ERR;
13387 else {
13388 return Jim_EvalPrefix(interp, "dict with", argc - 2, argv + 2);
13391 case OPT_CREATE:
13392 if (argc % 2) {
13393 Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");
13394 return JIM_ERR;
13396 objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
13397 Jim_SetResult(interp, objPtr);
13398 return JIM_OK;
13400 default:
13401 abort();
13405 /* [subst] */
13406 static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13408 static const char * const options[] = {
13409 "-nobackslashes", "-nocommands", "-novariables", NULL
13411 enum
13412 { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
13413 int i;
13414 int flags = JIM_SUBST_FLAG;
13415 Jim_Obj *objPtr;
13417 if (argc < 2) {
13418 Jim_WrongNumArgs(interp, 1, argv, "?options? string");
13419 return JIM_ERR;
13421 for (i = 1; i < (argc - 1); i++) {
13422 int option;
13424 if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
13425 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13426 return JIM_ERR;
13428 switch (option) {
13429 case OPT_NOBACKSLASHES:
13430 flags |= JIM_SUBST_NOESC;
13431 break;
13432 case OPT_NOCOMMANDS:
13433 flags |= JIM_SUBST_NOCMD;
13434 break;
13435 case OPT_NOVARIABLES:
13436 flags |= JIM_SUBST_NOVAR;
13437 break;
13440 if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
13441 return JIM_ERR;
13443 Jim_SetResult(interp, objPtr);
13444 return JIM_OK;
13447 /* [info] */
13448 static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13450 int cmd;
13451 Jim_Obj *objPtr;
13452 int mode = 0;
13454 static const char * const commands[] = {
13455 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13456 "vars", "version", "patchlevel", "complete", "args", "hostname",
13457 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13458 "references", NULL
13460 enum
13461 { INFO_BODY, INFO_COMMANDS, INFO_PROCS, INFO_CHANNELS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,
13462 INFO_FRAME, INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_PATCHLEVEL, INFO_COMPLETE, INFO_ARGS,
13463 INFO_HOSTNAME, INFO_SCRIPT, INFO_SOURCE, INFO_STACKTRACE, INFO_NAMEOFEXECUTABLE,
13464 INFO_RETURNCODES, INFO_REFERENCES,
13467 if (argc < 2) {
13468 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?args ...?");
13469 return JIM_ERR;
13471 if (Jim_GetEnum(interp, argv[1], commands, &cmd, "subcommand", JIM_ERRMSG | JIM_ENUM_ABBREV)
13472 != JIM_OK) {
13473 return JIM_ERR;
13476 /* Test for the the most common commands first, just in case it makes a difference */
13477 switch (cmd) {
13478 case INFO_EXISTS:{
13479 if (argc != 3) {
13480 Jim_WrongNumArgs(interp, 2, argv, "varName");
13481 return JIM_ERR;
13483 Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
13484 break;
13487 case INFO_CHANNELS:
13488 #ifndef jim_ext_aio
13489 Jim_SetResultString(interp, "aio not enabled", -1);
13490 return JIM_ERR;
13491 #endif
13492 case INFO_COMMANDS:
13493 case INFO_PROCS:
13494 if (argc != 2 && argc != 3) {
13495 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13496 return JIM_ERR;
13498 Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL,
13499 (cmd - INFO_COMMANDS)));
13500 break;
13502 case INFO_VARS:
13503 mode++; /* JIM_VARLIST_VARS */
13504 case INFO_LOCALS:
13505 mode++; /* JIM_VARLIST_LOCALS */
13506 case INFO_GLOBALS:
13507 /* mode 0 => JIM_VARLIST_GLOBALS */
13508 if (argc != 2 && argc != 3) {
13509 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13510 return JIM_ERR;
13512 Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
13513 break;
13515 case INFO_SCRIPT:
13516 if (argc != 2) {
13517 Jim_WrongNumArgs(interp, 2, argv, "");
13518 return JIM_ERR;
13520 Jim_SetResult(interp, Jim_GetScript(interp, interp->currentScriptObj)->fileNameObj);
13521 break;
13523 case INFO_SOURCE:{
13524 int line;
13525 Jim_Obj *resObjPtr;
13526 Jim_Obj *fileNameObj;
13528 if (argc != 3) {
13529 Jim_WrongNumArgs(interp, 2, argv, "source");
13530 return JIM_ERR;
13532 if (argv[2]->typePtr == &sourceObjType) {
13533 fileNameObj = argv[2]->internalRep.sourceValue.fileNameObj;
13534 line = argv[2]->internalRep.sourceValue.lineNumber;
13536 else if (argv[2]->typePtr == &scriptObjType) {
13537 ScriptObj *script = Jim_GetScript(interp, argv[2]);
13538 fileNameObj = script->fileNameObj;
13539 line = script->line;
13541 else {
13542 fileNameObj = interp->emptyObj;
13543 line = 1;
13545 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13546 Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
13547 Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
13548 Jim_SetResult(interp, resObjPtr);
13549 break;
13552 case INFO_STACKTRACE:
13553 Jim_SetResult(interp, interp->stackTrace);
13554 break;
13556 case INFO_LEVEL:
13557 case INFO_FRAME:
13558 switch (argc) {
13559 case 2:
13560 Jim_SetResultInt(interp, interp->framePtr->level);
13561 break;
13563 case 3:
13564 if (JimInfoLevel(interp, argv[2], &objPtr, cmd == INFO_LEVEL) != JIM_OK) {
13565 return JIM_ERR;
13567 Jim_SetResult(interp, objPtr);
13568 break;
13570 default:
13571 Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");
13572 return JIM_ERR;
13574 break;
13576 case INFO_BODY:
13577 case INFO_ARGS:{
13578 Jim_Cmd *cmdPtr;
13580 if (argc != 3) {
13581 Jim_WrongNumArgs(interp, 2, argv, "procname");
13582 return JIM_ERR;
13584 if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
13585 return JIM_ERR;
13587 if (!cmdPtr->isproc) {
13588 Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
13589 return JIM_ERR;
13591 Jim_SetResult(interp,
13592 cmd == INFO_BODY ? cmdPtr->u.proc.bodyObjPtr : cmdPtr->u.proc.argListObjPtr);
13593 break;
13596 case INFO_VERSION:
13597 case INFO_PATCHLEVEL:{
13598 char buf[(JIM_INTEGER_SPACE * 2) + 1];
13600 sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
13601 Jim_SetResultString(interp, buf, -1);
13602 break;
13605 case INFO_COMPLETE:
13606 if (argc != 3 && argc != 4) {
13607 Jim_WrongNumArgs(interp, 2, argv, "script ?missing?");
13608 return JIM_ERR;
13610 else {
13611 int len;
13612 const char *s = Jim_GetString(argv[2], &len);
13613 char missing;
13615 Jim_SetResultBool(interp, Jim_ScriptIsComplete(s, len, &missing));
13616 if (missing != ' ' && argc == 4) {
13617 Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
13620 break;
13622 case INFO_HOSTNAME:
13623 /* Redirect to os.gethostname if it exists */
13624 return Jim_Eval(interp, "os.gethostname");
13626 case INFO_NAMEOFEXECUTABLE:
13627 /* Redirect to Tcl proc */
13628 return Jim_Eval(interp, "{info nameofexecutable}");
13630 case INFO_RETURNCODES:
13631 if (argc == 2) {
13632 int i;
13633 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
13635 for (i = 0; jimReturnCodes[i]; i++) {
13636 Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
13637 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
13638 jimReturnCodes[i], -1));
13641 Jim_SetResult(interp, listObjPtr);
13643 else if (argc == 3) {
13644 long code;
13645 const char *name;
13647 if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
13648 return JIM_ERR;
13650 name = Jim_ReturnCode(code);
13651 if (*name == '?') {
13652 Jim_SetResultInt(interp, code);
13654 else {
13655 Jim_SetResultString(interp, name, -1);
13658 else {
13659 Jim_WrongNumArgs(interp, 2, argv, "?code?");
13660 return JIM_ERR;
13662 break;
13663 case INFO_REFERENCES:
13664 #ifdef JIM_REFERENCES
13665 return JimInfoReferences(interp, argc, argv);
13666 #else
13667 Jim_SetResultString(interp, "not supported", -1);
13668 return JIM_ERR;
13669 #endif
13671 return JIM_OK;
13674 /* [exists] */
13675 static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13677 Jim_Obj *objPtr;
13679 static const char * const options[] = {
13680 "-command", "-proc", "-var", NULL
13682 enum
13684 OPT_COMMAND, OPT_PROC, OPT_VAR
13686 int option;
13688 if (argc == 2) {
13689 option = OPT_VAR;
13690 objPtr = argv[1];
13692 else if (argc == 3) {
13693 if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13694 return JIM_ERR;
13696 objPtr = argv[2];
13698 else {
13699 Jim_WrongNumArgs(interp, 1, argv, "?option? name");
13700 return JIM_ERR;
13703 /* Test for the the most common commands first, just in case it makes a difference */
13704 switch (option) {
13705 case OPT_VAR:
13706 Jim_SetResultBool(interp, Jim_GetVariable(interp, objPtr, 0) != NULL);
13707 break;
13709 case OPT_COMMAND:
13710 case OPT_PROC: {
13711 Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
13712 Jim_SetResultBool(interp, cmd != NULL && (option == OPT_COMMAND || cmd->isproc));
13713 break;
13716 return JIM_OK;
13719 /* [split] */
13720 static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13722 const char *str, *splitChars, *noMatchStart;
13723 int splitLen, strLen;
13724 Jim_Obj *resObjPtr;
13725 int c;
13726 int len;
13728 if (argc != 2 && argc != 3) {
13729 Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
13730 return JIM_ERR;
13733 str = Jim_GetString(argv[1], &len);
13734 if (len == 0) {
13735 return JIM_OK;
13737 strLen = Jim_Utf8Length(interp, argv[1]);
13739 /* Init */
13740 if (argc == 2) {
13741 splitChars = " \n\t\r";
13742 splitLen = 4;
13744 else {
13745 splitChars = Jim_String(argv[2]);
13746 splitLen = Jim_Utf8Length(interp, argv[2]);
13749 noMatchStart = str;
13750 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13752 /* Split */
13753 if (splitLen) {
13754 Jim_Obj *objPtr;
13755 while (strLen--) {
13756 const char *sc = splitChars;
13757 int scLen = splitLen;
13758 int sl = utf8_tounicode(str, &c);
13759 while (scLen--) {
13760 int pc;
13761 sc += utf8_tounicode(sc, &pc);
13762 if (c == pc) {
13763 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13764 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13765 noMatchStart = str + sl;
13766 break;
13769 str += sl;
13771 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13772 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13774 else {
13775 /* This handles the special case of splitchars eq {}
13776 * Optimise by sharing common (ASCII) characters
13778 Jim_Obj **commonObj = NULL;
13779 #define NUM_COMMON (128 - 9)
13780 while (strLen--) {
13781 int n = utf8_tounicode(str, &c);
13782 #ifdef JIM_OPTIMIZATION
13783 if (c >= 9 && c < 128) {
13784 /* Common ASCII char. Note that 9 is the tab character */
13785 c -= 9;
13786 if (!commonObj) {
13787 commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
13788 memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
13790 if (!commonObj[c]) {
13791 commonObj[c] = Jim_NewStringObj(interp, str, 1);
13793 Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
13794 str++;
13795 continue;
13797 #endif
13798 Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
13799 str += n;
13801 Jim_Free(commonObj);
13804 Jim_SetResult(interp, resObjPtr);
13805 return JIM_OK;
13808 /* [join] */
13809 static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13811 const char *joinStr;
13812 int joinStrLen, i, listLen;
13813 Jim_Obj *resObjPtr;
13815 if (argc != 2 && argc != 3) {
13816 Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
13817 return JIM_ERR;
13819 /* Init */
13820 if (argc == 2) {
13821 joinStr = " ";
13822 joinStrLen = 1;
13824 else {
13825 joinStr = Jim_GetString(argv[2], &joinStrLen);
13827 listLen = Jim_ListLength(interp, argv[1]);
13828 resObjPtr = Jim_NewStringObj(interp, NULL, 0);
13829 /* Split */
13830 for (i = 0; i < listLen; i++) {
13831 Jim_Obj *objPtr = 0;
13833 Jim_ListIndex(interp, argv[1], i, &objPtr, JIM_NONE);
13834 Jim_AppendObj(interp, resObjPtr, objPtr);
13835 if (i + 1 != listLen) {
13836 Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
13839 Jim_SetResult(interp, resObjPtr);
13840 return JIM_OK;
13843 /* [format] */
13844 static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13846 Jim_Obj *objPtr;
13848 if (argc < 2) {
13849 Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
13850 return JIM_ERR;
13852 objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
13853 if (objPtr == NULL)
13854 return JIM_ERR;
13855 Jim_SetResult(interp, objPtr);
13856 return JIM_OK;
13859 /* [scan] */
13860 static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13862 Jim_Obj *listPtr, **outVec;
13863 int outc, i;
13865 if (argc < 3) {
13866 Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
13867 return JIM_ERR;
13869 if (argv[2]->typePtr != &scanFmtStringObjType)
13870 SetScanFmtFromAny(interp, argv[2]);
13871 if (FormatGetError(argv[2]) != 0) {
13872 Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
13873 return JIM_ERR;
13875 if (argc > 3) {
13876 int maxPos = FormatGetMaxPos(argv[2]);
13877 int count = FormatGetCnvCount(argv[2]);
13879 if (maxPos > argc - 3) {
13880 Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
13881 return JIM_ERR;
13883 else if (count > argc - 3) {
13884 Jim_SetResultString(interp, "different numbers of variable names and "
13885 "field specifiers", -1);
13886 return JIM_ERR;
13888 else if (count < argc - 3) {
13889 Jim_SetResultString(interp, "variable is not assigned by any "
13890 "conversion specifiers", -1);
13891 return JIM_ERR;
13894 listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
13895 if (listPtr == 0)
13896 return JIM_ERR;
13897 if (argc > 3) {
13898 int rc = JIM_OK;
13899 int count = 0;
13901 if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
13902 int len = Jim_ListLength(interp, listPtr);
13904 if (len != 0) {
13905 JimListGetElements(interp, listPtr, &outc, &outVec);
13906 for (i = 0; i < outc; ++i) {
13907 if (Jim_Length(outVec[i]) > 0) {
13908 ++count;
13909 if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
13910 rc = JIM_ERR;
13915 Jim_FreeNewObj(interp, listPtr);
13917 else {
13918 count = -1;
13920 if (rc == JIM_OK) {
13921 Jim_SetResultInt(interp, count);
13923 return rc;
13925 else {
13926 if (listPtr == (Jim_Obj *)EOF) {
13927 Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
13928 return JIM_OK;
13930 Jim_SetResult(interp, listPtr);
13932 return JIM_OK;
13935 /* [error] */
13936 static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13938 if (argc != 2 && argc != 3) {
13939 Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
13940 return JIM_ERR;
13942 Jim_SetResult(interp, argv[1]);
13943 if (argc == 3) {
13944 JimSetStackTrace(interp, argv[2]);
13945 return JIM_ERR;
13947 interp->addStackTrace++;
13948 return JIM_ERR;
13951 /* [lrange] */
13952 static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13954 Jim_Obj *objPtr;
13956 if (argc != 4) {
13957 Jim_WrongNumArgs(interp, 1, argv, "list first last");
13958 return JIM_ERR;
13960 if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
13961 return JIM_ERR;
13962 Jim_SetResult(interp, objPtr);
13963 return JIM_OK;
13966 /* [lrepeat] */
13967 static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13969 Jim_Obj *objPtr;
13970 long count;
13972 if (argc < 2 || Jim_GetLong(interp, argv[1], &count) != JIM_OK || count < 0) {
13973 Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
13974 return JIM_ERR;
13977 if (count == 0 || argc == 2) {
13978 return JIM_OK;
13981 argc -= 2;
13982 argv += 2;
13984 objPtr = Jim_NewListObj(interp, argv, argc);
13985 while (--count) {
13986 int i;
13988 for (i = 0; i < argc; i++) {
13989 ListAppendElement(objPtr, argv[i]);
13993 Jim_SetResult(interp, objPtr);
13994 return JIM_OK;
13997 char **Jim_GetEnviron(void)
13999 #if defined(HAVE__NSGETENVIRON)
14000 return *_NSGetEnviron();
14001 #else
14002 #if !defined(NO_ENVIRON_EXTERN)
14003 extern char **environ;
14004 #endif
14006 return environ;
14007 #endif
14010 void Jim_SetEnviron(char **env)
14012 #if defined(HAVE__NSGETENVIRON)
14013 *_NSGetEnviron() = env;
14014 #else
14015 #if !defined(NO_ENVIRON_EXTERN)
14016 extern char **environ;
14017 #endif
14019 environ = env;
14020 #endif
14023 /* [env] */
14024 static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14026 const char *key;
14027 const char *val;
14029 if (argc == 1) {
14030 char **e = Jim_GetEnviron();
14032 int i;
14033 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
14035 for (i = 0; e[i]; i++) {
14036 const char *equals = strchr(e[i], '=');
14038 if (equals) {
14039 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
14040 equals - e[i]));
14041 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
14045 Jim_SetResult(interp, listObjPtr);
14046 return JIM_OK;
14049 if (argc < 2) {
14050 Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
14051 return JIM_ERR;
14053 key = Jim_String(argv[1]);
14054 val = getenv(key);
14055 if (val == NULL) {
14056 if (argc < 3) {
14057 Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
14058 return JIM_ERR;
14060 val = Jim_String(argv[2]);
14062 Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
14063 return JIM_OK;
14066 /* [source] */
14067 static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14069 int retval;
14071 if (argc != 2) {
14072 Jim_WrongNumArgs(interp, 1, argv, "fileName");
14073 return JIM_ERR;
14075 retval = Jim_EvalFile(interp, Jim_String(argv[1]));
14076 if (retval == JIM_RETURN)
14077 return JIM_OK;
14078 return retval;
14081 /* [lreverse] */
14082 static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14084 Jim_Obj *revObjPtr, **ele;
14085 int len;
14087 if (argc != 2) {
14088 Jim_WrongNumArgs(interp, 1, argv, "list");
14089 return JIM_ERR;
14091 JimListGetElements(interp, argv[1], &len, &ele);
14092 len--;
14093 revObjPtr = Jim_NewListObj(interp, NULL, 0);
14094 while (len >= 0)
14095 ListAppendElement(revObjPtr, ele[len--]);
14096 Jim_SetResult(interp, revObjPtr);
14097 return JIM_OK;
14100 static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
14102 jim_wide len;
14104 if (step == 0)
14105 return -1;
14106 if (start == end)
14107 return 0;
14108 else if (step > 0 && start > end)
14109 return -1;
14110 else if (step < 0 && end > start)
14111 return -1;
14112 len = end - start;
14113 if (len < 0)
14114 len = -len; /* abs(len) */
14115 if (step < 0)
14116 step = -step; /* abs(step) */
14117 len = 1 + ((len - 1) / step);
14118 /* We can truncate safely to INT_MAX, the range command
14119 * will always return an error for a such long range
14120 * because Tcl lists can't be so long. */
14121 if (len > INT_MAX)
14122 len = INT_MAX;
14123 return (int)((len < 0) ? -1 : len);
14126 /* [range] */
14127 static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14129 jim_wide start = 0, end, step = 1;
14130 int len, i;
14131 Jim_Obj *objPtr;
14133 if (argc < 2 || argc > 4) {
14134 Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
14135 return JIM_ERR;
14137 if (argc == 2) {
14138 if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)
14139 return JIM_ERR;
14141 else {
14142 if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||
14143 Jim_GetWide(interp, argv[2], &end) != JIM_OK)
14144 return JIM_ERR;
14145 if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)
14146 return JIM_ERR;
14148 if ((len = JimRangeLen(start, end, step)) == -1) {
14149 Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
14150 return JIM_ERR;
14152 objPtr = Jim_NewListObj(interp, NULL, 0);
14153 for (i = 0; i < len; i++)
14154 ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
14155 Jim_SetResult(interp, objPtr);
14156 return JIM_OK;
14159 /* [rand] */
14160 static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14162 jim_wide min = 0, max = 0, len, maxMul;
14164 if (argc < 1 || argc > 3) {
14165 Jim_WrongNumArgs(interp, 1, argv, "?min? max");
14166 return JIM_ERR;
14168 if (argc == 1) {
14169 max = JIM_WIDE_MAX;
14170 } else if (argc == 2) {
14171 if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)
14172 return JIM_ERR;
14173 } else if (argc == 3) {
14174 if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||
14175 Jim_GetWide(interp, argv[2], &max) != JIM_OK)
14176 return JIM_ERR;
14178 len = max-min;
14179 if (len < 0) {
14180 Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
14181 return JIM_ERR;
14183 maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
14184 while (1) {
14185 jim_wide r;
14187 JimRandomBytes(interp, &r, sizeof(jim_wide));
14188 if (r < 0 || r >= maxMul) continue;
14189 r = (len == 0) ? 0 : r%len;
14190 Jim_SetResultInt(interp, min+r);
14191 return JIM_OK;
14195 static const struct {
14196 const char *name;
14197 Jim_CmdProc cmdProc;
14198 } Jim_CoreCommandsTable[] = {
14199 {"set", Jim_SetCoreCommand},
14200 {"unset", Jim_UnsetCoreCommand},
14201 {"puts", Jim_PutsCoreCommand},
14202 {"+", Jim_AddCoreCommand},
14203 {"*", Jim_MulCoreCommand},
14204 {"-", Jim_SubCoreCommand},
14205 {"/", Jim_DivCoreCommand},
14206 {"incr", Jim_IncrCoreCommand},
14207 {"while", Jim_WhileCoreCommand},
14208 {"loop", Jim_LoopCoreCommand},
14209 {"for", Jim_ForCoreCommand},
14210 {"foreach", Jim_ForeachCoreCommand},
14211 {"lmap", Jim_LmapCoreCommand},
14212 {"if", Jim_IfCoreCommand},
14213 {"switch", Jim_SwitchCoreCommand},
14214 {"list", Jim_ListCoreCommand},
14215 {"lindex", Jim_LindexCoreCommand},
14216 {"lset", Jim_LsetCoreCommand},
14217 {"lsearch", Jim_LsearchCoreCommand},
14218 {"llength", Jim_LlengthCoreCommand},
14219 {"lappend", Jim_LappendCoreCommand},
14220 {"linsert", Jim_LinsertCoreCommand},
14221 {"lreplace", Jim_LreplaceCoreCommand},
14222 {"lsort", Jim_LsortCoreCommand},
14223 {"append", Jim_AppendCoreCommand},
14224 {"debug", Jim_DebugCoreCommand},
14225 {"eval", Jim_EvalCoreCommand},
14226 {"uplevel", Jim_UplevelCoreCommand},
14227 {"expr", Jim_ExprCoreCommand},
14228 {"break", Jim_BreakCoreCommand},
14229 {"continue", Jim_ContinueCoreCommand},
14230 {"proc", Jim_ProcCoreCommand},
14231 {"concat", Jim_ConcatCoreCommand},
14232 {"return", Jim_ReturnCoreCommand},
14233 {"upvar", Jim_UpvarCoreCommand},
14234 {"global", Jim_GlobalCoreCommand},
14235 {"string", Jim_StringCoreCommand},
14236 {"time", Jim_TimeCoreCommand},
14237 {"exit", Jim_ExitCoreCommand},
14238 {"catch", Jim_CatchCoreCommand},
14239 #ifdef JIM_REFERENCES
14240 {"ref", Jim_RefCoreCommand},
14241 {"getref", Jim_GetrefCoreCommand},
14242 {"setref", Jim_SetrefCoreCommand},
14243 {"finalize", Jim_FinalizeCoreCommand},
14244 {"collect", Jim_CollectCoreCommand},
14245 #endif
14246 {"rename", Jim_RenameCoreCommand},
14247 {"dict", Jim_DictCoreCommand},
14248 {"subst", Jim_SubstCoreCommand},
14249 {"info", Jim_InfoCoreCommand},
14250 {"exists", Jim_ExistsCoreCommand},
14251 {"split", Jim_SplitCoreCommand},
14252 {"join", Jim_JoinCoreCommand},
14253 {"format", Jim_FormatCoreCommand},
14254 {"scan", Jim_ScanCoreCommand},
14255 {"error", Jim_ErrorCoreCommand},
14256 {"lrange", Jim_LrangeCoreCommand},
14257 {"lrepeat", Jim_LrepeatCoreCommand},
14258 {"env", Jim_EnvCoreCommand},
14259 {"source", Jim_SourceCoreCommand},
14260 {"lreverse", Jim_LreverseCoreCommand},
14261 {"range", Jim_RangeCoreCommand},
14262 {"rand", Jim_RandCoreCommand},
14263 {"tailcall", Jim_TailcallCoreCommand},
14264 {"local", Jim_LocalCoreCommand},
14265 {"upcall", Jim_UpcallCoreCommand},
14266 {NULL, NULL},
14269 void Jim_RegisterCoreCommands(Jim_Interp *interp)
14271 int i = 0;
14273 while (Jim_CoreCommandsTable[i].name != NULL) {
14274 Jim_CreateCommand(interp,
14275 Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
14276 i++;
14280 /* -----------------------------------------------------------------------------
14281 * Interactive prompt
14282 * ---------------------------------------------------------------------------*/
14283 void Jim_MakeErrorMessage(Jim_Interp *interp)
14285 Jim_Obj *argv[2];
14287 argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
14288 argv[1] = interp->result;
14290 Jim_EvalObjVector(interp, 2, argv);
14293 static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
14294 const char *prefix, const char *const *tablePtr, const char *name)
14296 int count;
14297 char **tablePtrSorted;
14298 int i;
14300 for (count = 0; tablePtr[count]; count++) {
14303 if (name == NULL) {
14304 name = "option";
14307 Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
14308 tablePtrSorted = Jim_Alloc(sizeof(char *) * count);
14309 memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
14310 qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
14311 for (i = 0; i < count; i++) {
14312 if (i + 1 == count && count > 1) {
14313 Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
14315 Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
14316 if (i + 1 != count) {
14317 Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
14320 Jim_Free(tablePtrSorted);
14323 int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
14324 const char *const *tablePtr, int *indexPtr, const char *name, int flags)
14326 const char *bad = "bad ";
14327 const char *const *entryPtr = NULL;
14328 int i;
14329 int match = -1;
14330 int arglen;
14331 const char *arg = Jim_GetString(objPtr, &arglen);
14333 *indexPtr = -1;
14335 for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
14336 if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
14337 /* Found an exact match */
14338 *indexPtr = i;
14339 return JIM_OK;
14341 if (flags & JIM_ENUM_ABBREV) {
14342 /* Accept an unambiguous abbreviation.
14343 * Note that '-' doesnt' consitute a valid abbreviation
14345 if (strncmp(arg, *entryPtr, arglen) == 0) {
14346 if (*arg == '-' && arglen == 1) {
14347 break;
14349 if (match >= 0) {
14350 bad = "ambiguous ";
14351 goto ambiguous;
14353 match = i;
14358 /* If we had an unambiguous partial match */
14359 if (match >= 0) {
14360 *indexPtr = match;
14361 return JIM_OK;
14364 ambiguous:
14365 if (flags & JIM_ERRMSG) {
14366 JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
14368 return JIM_ERR;
14371 int Jim_FindByName(const char *name, const char * const array[], size_t len)
14373 int i;
14375 for (i = 0; i < (int)len; i++) {
14376 if (array[i] && strcmp(array[i], name) == 0) {
14377 return i;
14380 return -1;
14383 int Jim_IsDict(Jim_Obj *objPtr)
14385 return objPtr->typePtr == &dictObjType;
14388 int Jim_IsList(Jim_Obj *objPtr)
14390 return objPtr->typePtr == &listObjType;
14394 * Very simple printf-like formatting, designed for error messages.
14396 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14397 * The resulting string is created and set as the result.
14399 * Each '%s' should correspond to a regular string parameter.
14400 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14401 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14403 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14405 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14407 void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
14409 /* Initial space needed */
14410 int len = strlen(format);
14411 int extra = 0;
14412 int n = 0;
14413 const char *params[5];
14414 char *buf;
14415 va_list args;
14416 int i;
14418 va_start(args, format);
14420 for (i = 0; i < len && n < 5; i++) {
14421 int l;
14423 if (strncmp(format + i, "%s", 2) == 0) {
14424 params[n] = va_arg(args, char *);
14426 l = strlen(params[n]);
14428 else if (strncmp(format + i, "%#s", 3) == 0) {
14429 Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
14431 params[n] = Jim_GetString(objPtr, &l);
14433 else {
14434 if (format[i] == '%') {
14435 i++;
14437 continue;
14439 n++;
14440 extra += l;
14443 len += extra;
14444 buf = Jim_Alloc(len + 1);
14445 len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
14447 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
14450 /* stubs */
14451 #ifndef jim_ext_package
14452 int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
14454 return JIM_OK;
14456 #endif
14457 #ifndef jim_ext_aio
14458 FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
14460 Jim_SetResultString(interp, "aio not enabled", -1);
14461 return NULL;
14463 #endif
14467 * Local Variables: ***
14468 * c-basic-offset: 4 ***
14469 * tab-width: 4 ***
14470 * End: ***