Switch to using Jim_Obj for filename tracking
[jimtcl.git] / jim.c
blobc50319afd955f3746ae684bcb613889eee91f688
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 Jim_GetString(strObjPtr, &len);
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);
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 Jim_HashTable marks;
4780 Jim_HashTableIterator *htiter;
4781 Jim_HashEntry *he;
4782 Jim_Obj *objPtr;
4783 int collected = 0;
4785 /* Avoid recursive calls */
4786 if (interp->lastCollectId == -1) {
4787 /* Jim_Collect() already running. Return just now. */
4788 return 0;
4790 interp->lastCollectId = -1;
4792 /* Mark all the references found into the 'mark' hash table.
4793 * The references are searched in every live object that
4794 * is of a type that can contain references. */
4795 Jim_InitHashTable(&marks, &JimRefMarkHashTableType, NULL);
4796 objPtr = interp->liveList;
4797 while (objPtr) {
4798 if (objPtr->typePtr == NULL || objPtr->typePtr->flags & JIM_TYPE_REFERENCES) {
4799 const char *str, *p;
4800 int len;
4802 /* If the object is of type reference, to get the
4803 * Id is simple... */
4804 if (objPtr->typePtr == &referenceObjType) {
4805 Jim_AddHashEntry(&marks, &objPtr->internalRep.refValue.id, NULL);
4806 #ifdef JIM_DEBUG_GC
4807 printf("MARK (reference): %d refcount: %d" JIM_NL,
4808 (int)objPtr->internalRep.refValue.id, objPtr->refCount);
4809 #endif
4810 objPtr = objPtr->nextObjPtr;
4811 continue;
4813 /* Get the string repr of the object we want
4814 * to scan for references. */
4815 p = str = Jim_GetString(objPtr, &len);
4816 /* Skip objects too little to contain references. */
4817 if (len < JIM_REFERENCE_SPACE) {
4818 objPtr = objPtr->nextObjPtr;
4819 continue;
4821 /* Extract references from the object string repr. */
4822 while (1) {
4823 int i;
4824 jim_wide id;
4825 char buf[21];
4827 if ((p = strstr(p, "<reference.<")) == NULL)
4828 break;
4829 /* Check if it's a valid reference. */
4830 if (len - (p - str) < JIM_REFERENCE_SPACE)
4831 break;
4832 if (p[41] != '>' || p[19] != '>' || p[20] != '.')
4833 break;
4834 for (i = 21; i <= 40; i++)
4835 if (!isdigit(UCHAR(p[i])))
4836 break;
4837 /* Get the ID */
4838 memcpy(buf, p + 21, 20);
4839 buf[20] = '\0';
4840 Jim_StringToWide(buf, &id, 10);
4842 /* Ok, a reference for the given ID
4843 * was found. Mark it. */
4844 Jim_AddHashEntry(&marks, &id, NULL);
4845 #ifdef JIM_DEBUG_GC
4846 printf("MARK: %d" JIM_NL, (int)id);
4847 #endif
4848 p += JIM_REFERENCE_SPACE;
4851 objPtr = objPtr->nextObjPtr;
4854 /* Run the references hash table to destroy every reference that
4855 * is not referenced outside (not present in the mark HT). */
4856 htiter = Jim_GetHashTableIterator(&interp->references);
4857 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
4858 const jim_wide *refId;
4859 Jim_Reference *refPtr;
4861 refId = he->key;
4862 /* Check if in the mark phase we encountered
4863 * this reference. */
4864 if (Jim_FindHashEntry(&marks, refId) == NULL) {
4865 #ifdef JIM_DEBUG_GC
4866 printf("COLLECTING %d" JIM_NL, (int)*refId);
4867 #endif
4868 collected++;
4869 /* Drop the reference, but call the
4870 * finalizer first if registered. */
4871 refPtr = he->u.val;
4872 if (refPtr->finalizerCmdNamePtr) {
4873 char *refstr = Jim_Alloc(JIM_REFERENCE_SPACE + 1);
4874 Jim_Obj *objv[3], *oldResult;
4876 JimFormatReference(refstr, refPtr, *refId);
4878 objv[0] = refPtr->finalizerCmdNamePtr;
4879 objv[1] = Jim_NewStringObjNoAlloc(interp, refstr, 32);
4880 objv[2] = refPtr->objPtr;
4881 Jim_IncrRefCount(objv[0]);
4882 Jim_IncrRefCount(objv[1]);
4883 Jim_IncrRefCount(objv[2]);
4885 /* Drop the reference itself */
4886 Jim_DeleteHashEntry(&interp->references, refId);
4888 /* Call the finalizer. Errors ignored. */
4889 oldResult = interp->result;
4890 Jim_IncrRefCount(oldResult);
4891 Jim_EvalObjVector(interp, 3, objv);
4892 Jim_SetResult(interp, oldResult);
4893 Jim_DecrRefCount(interp, oldResult);
4895 Jim_DecrRefCount(interp, objv[0]);
4896 Jim_DecrRefCount(interp, objv[1]);
4897 Jim_DecrRefCount(interp, objv[2]);
4899 else {
4900 Jim_DeleteHashEntry(&interp->references, refId);
4904 Jim_FreeHashTableIterator(htiter);
4905 Jim_FreeHashTable(&marks);
4906 interp->lastCollectId = interp->referenceNextId;
4907 interp->lastCollectTime = time(NULL);
4908 return collected;
4911 #define JIM_COLLECT_ID_PERIOD 5000
4912 #define JIM_COLLECT_TIME_PERIOD 300
4914 void Jim_CollectIfNeeded(Jim_Interp *interp)
4916 jim_wide elapsedId;
4917 int elapsedTime;
4919 elapsedId = interp->referenceNextId - interp->lastCollectId;
4920 elapsedTime = time(NULL) - interp->lastCollectTime;
4923 if (elapsedId > JIM_COLLECT_ID_PERIOD || elapsedTime > JIM_COLLECT_TIME_PERIOD) {
4924 Jim_Collect(interp);
4927 #endif
4929 static int JimIsBigEndian(void)
4931 union {
4932 unsigned short s;
4933 unsigned char c[2];
4934 } uval = {0x0102};
4936 return uval.c[0] == 1;
4939 /* -----------------------------------------------------------------------------
4940 * Interpreter related functions
4941 * ---------------------------------------------------------------------------*/
4943 Jim_Interp *Jim_CreateInterp(void)
4945 Jim_Interp *i = Jim_Alloc(sizeof(*i));
4947 memset(i, 0, sizeof(*i));
4949 i->maxNestingDepth = JIM_MAX_NESTING_DEPTH;
4950 i->lastCollectTime = time(NULL);
4952 /* Note that we can create objects only after the
4953 * interpreter liveList and freeList pointers are
4954 * initialized to NULL. */
4955 Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
4956 #ifdef JIM_REFERENCES
4957 Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
4958 #endif
4959 Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
4960 Jim_InitHashTable(&i->packages, &JimStringKeyValCopyHashTableType, NULL);
4961 i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL);
4962 i->emptyObj = Jim_NewEmptyStringObj(i);
4963 i->trueObj = Jim_NewIntObj(i, 1);
4964 i->falseObj = Jim_NewIntObj(i, 0);
4965 i->errorFileNameObj = i->emptyObj;
4966 i->result = i->emptyObj;
4967 i->stackTrace = Jim_NewListObj(i, NULL, 0);
4968 i->unknown = Jim_NewStringObj(i, "unknown", -1);
4969 i->errorProc = i->emptyObj;
4970 i->currentScriptObj = Jim_NewEmptyStringObj(i);
4971 Jim_IncrRefCount(i->emptyObj);
4972 Jim_IncrRefCount(i->errorFileNameObj);
4973 Jim_IncrRefCount(i->result);
4974 Jim_IncrRefCount(i->stackTrace);
4975 Jim_IncrRefCount(i->unknown);
4976 Jim_IncrRefCount(i->currentScriptObj);
4977 Jim_IncrRefCount(i->errorProc);
4978 Jim_IncrRefCount(i->trueObj);
4979 Jim_IncrRefCount(i->falseObj);
4981 /* Initialize key variables every interpreter should contain */
4982 Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
4983 Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
4985 Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
4986 Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
4987 Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
4988 Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4989 Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
4990 Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
4991 Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
4993 return i;
4996 void Jim_FreeInterp(Jim_Interp *i)
4998 Jim_CallFrame *cf = i->framePtr, *prevcf, *nextcf;
4999 Jim_Obj *objPtr, *nextObjPtr;
5001 Jim_DecrRefCount(i, i->emptyObj);
5002 Jim_DecrRefCount(i, i->trueObj);
5003 Jim_DecrRefCount(i, i->falseObj);
5004 Jim_DecrRefCount(i, i->result);
5005 Jim_DecrRefCount(i, i->stackTrace);
5006 Jim_DecrRefCount(i, i->errorProc);
5007 Jim_DecrRefCount(i, i->unknown);
5008 Jim_DecrRefCount(i, i->errorFileNameObj);
5009 Jim_DecrRefCount(i, i->currentScriptObj);
5010 Jim_FreeHashTable(&i->commands);
5011 #ifdef JIM_REFERENCES
5012 Jim_FreeHashTable(&i->references);
5013 #endif
5014 Jim_FreeHashTable(&i->packages);
5015 Jim_Free(i->prngState);
5016 Jim_FreeHashTable(&i->assocData);
5017 JimDeleteLocalProcs(i);
5019 /* Free the call frames list */
5020 while (cf) {
5021 prevcf = cf->parentCallFrame;
5022 JimFreeCallFrame(i, cf, JIM_FCF_NONE);
5023 cf = prevcf;
5025 /* Check that the live object list is empty, otherwise
5026 * there is a memory leak. */
5027 if (i->liveList != NULL) {
5028 objPtr = i->liveList;
5030 printf(JIM_NL "-------------------------------------" JIM_NL);
5031 printf("Objects still in the free list:" JIM_NL);
5032 while (objPtr) {
5033 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
5035 printf("%p (%d) %-10s: '%.20s'" JIM_NL,
5036 (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
5037 if (objPtr->typePtr == &sourceObjType) {
5038 printf("FILE %s LINE %d" JIM_NL,
5039 Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
5040 objPtr->internalRep.sourceValue.lineNumber);
5042 objPtr = objPtr->nextObjPtr;
5044 printf("-------------------------------------" JIM_NL JIM_NL);
5045 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5047 /* Free all the freed objects. */
5048 objPtr = i->freeList;
5049 while (objPtr) {
5050 nextObjPtr = objPtr->nextObjPtr;
5051 Jim_Free(objPtr);
5052 objPtr = nextObjPtr;
5054 /* Free cached CallFrame structures */
5055 cf = i->freeFramesList;
5056 while (cf) {
5057 nextcf = cf->nextFramePtr;
5058 if (cf->vars.table != NULL)
5059 Jim_Free(cf->vars.table);
5060 Jim_Free(cf);
5061 cf = nextcf;
5063 #ifdef jim_ext_load
5064 Jim_FreeLoadHandles(i);
5065 #endif
5067 /* Free the interpreter structure. */
5068 Jim_Free(i);
5071 /* Returns the call frame relative to the level represented by
5072 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5074 * This function accepts the 'level' argument in the form
5075 * of the commands [uplevel] and [upvar].
5077 * For a function accepting a relative integer as level suitable
5078 * for implementation of [info level ?level?] check the
5079 * JimGetCallFrameByInteger() function.
5081 * Returns NULL on error.
5083 Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5085 long level;
5086 const char *str;
5087 Jim_CallFrame *framePtr;
5089 if (levelObjPtr) {
5090 str = Jim_String(levelObjPtr);
5091 if (str[0] == '#') {
5092 char *endptr;
5094 level = strtol(str + 1, &endptr, 0);
5095 if (str[1] == '\0' || endptr[0] != '\0') {
5096 level = -1;
5099 else {
5100 if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
5101 level = -1;
5103 else {
5104 /* Convert from a relative to an absolute level */
5105 level = interp->framePtr->level - level;
5109 else {
5110 str = "1"; /* Needed to format the error message. */
5111 level = interp->framePtr->level - 1;
5114 if (level == 0) {
5115 return interp->topFramePtr;
5117 if (level > 0) {
5118 /* Lookup */
5119 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5120 if (framePtr->level == level) {
5121 return framePtr;
5126 Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
5127 return NULL;
5130 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5131 * as a relative integer like in the [info level ?level?] command.
5133 static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr)
5135 long level;
5136 Jim_CallFrame *framePtr;
5138 if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
5139 if (level <= 0) {
5140 /* Convert from a relative to an absolute level */
5141 level = interp->framePtr->level + level;
5144 if (level == 0) {
5145 return interp->topFramePtr;
5148 /* Lookup */
5149 for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parentCallFrame) {
5150 if (framePtr->level == level) {
5151 return framePtr;
5156 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
5157 return NULL;
5160 static void JimResetStackTrace(Jim_Interp *interp)
5162 Jim_DecrRefCount(interp, interp->stackTrace);
5163 interp->stackTrace = Jim_NewListObj(interp, NULL, 0);
5164 Jim_IncrRefCount(interp->stackTrace);
5167 static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
5169 int len;
5171 /* Increment reference first in case these are the same object */
5172 Jim_IncrRefCount(stackTraceObj);
5173 Jim_DecrRefCount(interp, interp->stackTrace);
5174 interp->stackTrace = stackTraceObj;
5175 interp->errorFlag = 1;
5177 /* This is a bit ugly.
5178 * If the filename of the last entry of the stack trace is empty,
5179 * the next stack level should be added.
5181 len = Jim_ListLength(interp, interp->stackTrace);
5182 if (len >= 3) {
5183 Jim_Obj *filenameObj;
5185 Jim_ListIndex(interp, interp->stackTrace, len - 2, &filenameObj, JIM_NONE);
5187 Jim_GetString(filenameObj, &len);
5189 if (len == 0) {
5190 interp->addStackTrace = 1;
5195 /* Returns 1 if the stack trace information was used or 0 if not */
5196 static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,
5197 Jim_Obj *fileNameObj, int linenr)
5199 if (strcmp(procname, "unknown") == 0) {
5200 procname = "";
5202 if (!*procname && !Jim_Length(fileNameObj)) {
5203 /* No useful info here */
5204 return;
5207 if (Jim_IsShared(interp->stackTrace)) {
5208 Jim_DecrRefCount(interp, interp->stackTrace);
5209 interp->stackTrace = Jim_DuplicateObj(interp, interp->stackTrace);
5210 Jim_IncrRefCount(interp->stackTrace);
5213 /* If we have no procname but the previous element did, merge with that frame */
5214 if (!*procname && Jim_Length(fileNameObj)) {
5215 /* Just a filename. Check the previous entry */
5216 int len = Jim_ListLength(interp, interp->stackTrace);
5218 if (len >= 3) {
5219 Jim_Obj *objPtr;
5220 if (Jim_ListIndex(interp, interp->stackTrace, len - 3, &objPtr, JIM_NONE) == JIM_OK && Jim_Length(objPtr)) {
5221 /* Yes, the previous level had procname */
5222 if (Jim_ListIndex(interp, interp->stackTrace, len - 2, &objPtr, JIM_NONE) == JIM_OK && !Jim_Length(objPtr)) {
5223 /* But no filename, so merge the new info with that frame */
5224 ListSetIndex(interp, interp->stackTrace, len - 2, fileNameObj, 0);
5225 ListSetIndex(interp, interp->stackTrace, len - 1, Jim_NewIntObj(interp, linenr), 0);
5226 return;
5232 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewStringObj(interp, procname, -1));
5233 Jim_ListAppendElement(interp, interp->stackTrace, fileNameObj);
5234 Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewIntObj(interp, linenr));
5237 int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
5238 void *data)
5240 AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
5242 assocEntryPtr->delProc = delProc;
5243 assocEntryPtr->data = data;
5244 return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
5247 void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
5249 Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
5251 if (entryPtr != NULL) {
5252 AssocDataValue *assocEntryPtr = (AssocDataValue *) entryPtr->u.val;
5254 return assocEntryPtr->data;
5256 return NULL;
5259 int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
5261 return Jim_DeleteHashEntry(&interp->assocData, key);
5264 int Jim_GetExitCode(Jim_Interp *interp)
5266 return interp->exitCode;
5269 /* -----------------------------------------------------------------------------
5270 * Integer object
5271 * ---------------------------------------------------------------------------*/
5272 #define JIM_INTEGER_SPACE 24
5274 static void UpdateStringOfInt(struct Jim_Obj *objPtr);
5275 static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
5277 static const Jim_ObjType intObjType = {
5278 "int",
5279 NULL,
5280 NULL,
5281 UpdateStringOfInt,
5282 JIM_TYPE_NONE,
5285 /* A coerced double is closer to an int than a double.
5286 * It is an int value temporarily masquerading as a double value.
5287 * i.e. it has the same string value as an int and Jim_GetWide()
5288 * succeeds, but also Jim_GetDouble() returns the value directly.
5290 static const Jim_ObjType coercedDoubleObjType = {
5291 "coerced-double",
5292 NULL,
5293 NULL,
5294 UpdateStringOfInt,
5295 JIM_TYPE_NONE,
5299 void UpdateStringOfInt(struct Jim_Obj *objPtr)
5301 int len;
5302 char buf[JIM_INTEGER_SPACE + 1];
5304 len = Jim_WideToString(buf, JimWideValue(objPtr));
5305 objPtr->bytes = Jim_Alloc(len + 1);
5306 memcpy(objPtr->bytes, buf, len + 1);
5307 objPtr->length = len;
5310 int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
5312 jim_wide wideValue;
5313 const char *str;
5315 if (objPtr->typePtr == &coercedDoubleObjType) {
5316 /* Simple switcheroo */
5317 objPtr->typePtr = &intObjType;
5318 return JIM_OK;
5321 /* Get the string representation */
5322 str = Jim_String(objPtr);
5323 /* Try to convert into a jim_wide */
5324 if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
5325 if (flags & JIM_ERRMSG) {
5326 Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
5328 return JIM_ERR;
5330 if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
5331 Jim_SetResultString(interp, "Integer value too big to be represented", -1);
5332 return JIM_ERR;
5334 /* Free the old internal repr and set the new one. */
5335 Jim_FreeIntRep(interp, objPtr);
5336 objPtr->typePtr = &intObjType;
5337 objPtr->internalRep.wideValue = wideValue;
5338 return JIM_OK;
5341 #ifdef JIM_OPTIMIZATION
5342 static int JimIsWide(Jim_Obj *objPtr)
5344 return objPtr->typePtr == &intObjType;
5346 #endif
5348 int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5350 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
5351 return JIM_ERR;
5352 *widePtr = JimWideValue(objPtr);
5353 return JIM_OK;
5356 /* Get a wide but does not set an error if the format is bad. */
5357 static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
5359 if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
5360 return JIM_ERR;
5361 *widePtr = JimWideValue(objPtr);
5362 return JIM_OK;
5365 int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
5367 jim_wide wideValue;
5368 int retval;
5370 retval = Jim_GetWide(interp, objPtr, &wideValue);
5371 if (retval == JIM_OK) {
5372 *longPtr = (long)wideValue;
5373 return JIM_OK;
5375 return JIM_ERR;
5378 Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
5380 Jim_Obj *objPtr;
5382 objPtr = Jim_NewObj(interp);
5383 objPtr->typePtr = &intObjType;
5384 objPtr->bytes = NULL;
5385 objPtr->internalRep.wideValue = wideValue;
5386 return objPtr;
5389 /* -----------------------------------------------------------------------------
5390 * Double object
5391 * ---------------------------------------------------------------------------*/
5392 #define JIM_DOUBLE_SPACE 30
5394 static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
5395 static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
5397 static const Jim_ObjType doubleObjType = {
5398 "double",
5399 NULL,
5400 NULL,
5401 UpdateStringOfDouble,
5402 JIM_TYPE_NONE,
5405 void UpdateStringOfDouble(struct Jim_Obj *objPtr)
5407 int len;
5408 char buf[JIM_DOUBLE_SPACE + 1];
5410 len = Jim_DoubleToString(buf, objPtr->internalRep.doubleValue);
5411 objPtr->bytes = Jim_Alloc(len + 1);
5412 memcpy(objPtr->bytes, buf, len + 1);
5413 objPtr->length = len;
5416 int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
5418 double doubleValue;
5419 jim_wide wideValue;
5420 const char *str;
5422 /* Preserve the string representation.
5423 * Needed so we can convert back to int without loss
5425 str = Jim_String(objPtr);
5427 #ifdef HAVE_LONG_LONG
5428 /* Assume a 53 bit mantissa */
5429 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5430 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5432 if (objPtr->typePtr == &intObjType
5433 && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
5434 && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
5436 /* Direct conversion to coerced double */
5437 objPtr->typePtr = &coercedDoubleObjType;
5438 return JIM_OK;
5440 else
5441 #endif
5442 if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
5443 /* Managed to convert to an int, so we can use this as a cooerced double */
5444 Jim_FreeIntRep(interp, objPtr);
5445 objPtr->typePtr = &coercedDoubleObjType;
5446 objPtr->internalRep.wideValue = wideValue;
5447 return JIM_OK;
5449 else {
5450 /* Try to convert into a double */
5451 if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
5452 Jim_SetResultFormatted(interp, "expected number but got \"%#s\"", objPtr);
5453 return JIM_ERR;
5455 /* Free the old internal repr and set the new one. */
5456 Jim_FreeIntRep(interp, objPtr);
5458 objPtr->typePtr = &doubleObjType;
5459 objPtr->internalRep.doubleValue = doubleValue;
5460 return JIM_OK;
5463 int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
5465 if (objPtr->typePtr == &coercedDoubleObjType) {
5466 *doublePtr = JimWideValue(objPtr);
5467 return JIM_OK;
5469 if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
5470 return JIM_ERR;
5472 if (objPtr->typePtr == &coercedDoubleObjType) {
5473 *doublePtr = JimWideValue(objPtr);
5475 else {
5476 *doublePtr = objPtr->internalRep.doubleValue;
5478 return JIM_OK;
5481 Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
5483 Jim_Obj *objPtr;
5485 objPtr = Jim_NewObj(interp);
5486 objPtr->typePtr = &doubleObjType;
5487 objPtr->bytes = NULL;
5488 objPtr->internalRep.doubleValue = doubleValue;
5489 return objPtr;
5492 /* -----------------------------------------------------------------------------
5493 * List object
5494 * ---------------------------------------------------------------------------*/
5495 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
5496 static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
5497 static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
5498 static void UpdateStringOfList(struct Jim_Obj *objPtr);
5499 static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
5501 /* Note that while the elements of the list may contain references,
5502 * the list object itself can't. This basically means that the
5503 * list object string representation as a whole can't contain references
5504 * that are not presents in the single elements. */
5505 static const Jim_ObjType listObjType = {
5506 "list",
5507 FreeListInternalRep,
5508 DupListInternalRep,
5509 UpdateStringOfList,
5510 JIM_TYPE_NONE,
5513 void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
5515 int i;
5517 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5518 Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
5520 Jim_Free(objPtr->internalRep.listValue.ele);
5523 void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
5525 int i;
5527 JIM_NOTUSED(interp);
5529 dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
5530 dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
5531 dupPtr->internalRep.listValue.ele =
5532 Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
5533 memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
5534 sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
5535 for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
5536 Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
5538 dupPtr->typePtr = &listObjType;
5541 /* The following function checks if a given string can be encoded
5542 * into a list element without any kind of quoting, surrounded by braces,
5543 * or using escapes to quote. */
5544 #define JIM_ELESTR_SIMPLE 0
5545 #define JIM_ELESTR_BRACE 1
5546 #define JIM_ELESTR_QUOTE 2
5547 static int ListElementQuotingType(const char *s, int len)
5549 int i, level, blevel, trySimple = 1;
5551 /* Try with the SIMPLE case */
5552 if (len == 0)
5553 return JIM_ELESTR_BRACE;
5554 if (s[0] == '#')
5555 return JIM_ELESTR_BRACE;
5556 if (s[0] == '"' || s[0] == '{') {
5557 trySimple = 0;
5558 goto testbrace;
5560 for (i = 0; i < len; i++) {
5561 switch (s[i]) {
5562 case ' ':
5563 case '$':
5564 case '"':
5565 case '[':
5566 case ']':
5567 case ';':
5568 case '\\':
5569 case '\r':
5570 case '\n':
5571 case '\t':
5572 case '\f':
5573 case '\v':
5574 trySimple = 0;
5575 case '{':
5576 case '}':
5577 goto testbrace;
5580 return JIM_ELESTR_SIMPLE;
5582 testbrace:
5583 /* Test if it's possible to do with braces */
5584 if (s[len - 1] == '\\')
5585 return JIM_ELESTR_QUOTE;
5586 level = 0;
5587 blevel = 0;
5588 for (i = 0; i < len; i++) {
5589 switch (s[i]) {
5590 case '{':
5591 level++;
5592 break;
5593 case '}':
5594 level--;
5595 if (level < 0)
5596 return JIM_ELESTR_QUOTE;
5597 break;
5598 case '[':
5599 blevel++;
5600 break;
5601 case ']':
5602 blevel--;
5603 break;
5604 case '\\':
5605 if (s[i + 1] == '\n')
5606 return JIM_ELESTR_QUOTE;
5607 else if (s[i + 1] != '\0')
5608 i++;
5609 break;
5612 if (blevel < 0) {
5613 return JIM_ELESTR_QUOTE;
5616 if (level == 0) {
5617 if (!trySimple)
5618 return JIM_ELESTR_BRACE;
5619 for (i = 0; i < len; i++) {
5620 switch (s[i]) {
5621 case ' ':
5622 case '$':
5623 case '"':
5624 case '[':
5625 case ']':
5626 case ';':
5627 case '\\':
5628 case '\r':
5629 case '\n':
5630 case '\t':
5631 case '\f':
5632 case '\v':
5633 return JIM_ELESTR_BRACE;
5634 break;
5637 return JIM_ELESTR_SIMPLE;
5639 return JIM_ELESTR_QUOTE;
5642 /* Returns the malloc-ed representation of a string
5643 * using backslash to quote special chars. */
5644 static char *BackslashQuoteString(const char *s, int len, int *qlenPtr)
5646 char *q = Jim_Alloc(len * 2 + 1), *p;
5648 p = q;
5649 while (*s) {
5650 switch (*s) {
5651 case ' ':
5652 case '$':
5653 case '"':
5654 case '[':
5655 case ']':
5656 case '{':
5657 case '}':
5658 case ';':
5659 case '\\':
5660 *p++ = '\\';
5661 *p++ = *s++;
5662 break;
5663 case '\n':
5664 *p++ = '\\';
5665 *p++ = 'n';
5666 s++;
5667 break;
5668 case '\r':
5669 *p++ = '\\';
5670 *p++ = 'r';
5671 s++;
5672 break;
5673 case '\t':
5674 *p++ = '\\';
5675 *p++ = 't';
5676 s++;
5677 break;
5678 case '\f':
5679 *p++ = '\\';
5680 *p++ = 'f';
5681 s++;
5682 break;
5683 case '\v':
5684 *p++ = '\\';
5685 *p++ = 'v';
5686 s++;
5687 break;
5688 default:
5689 *p++ = *s++;
5690 break;
5693 *p = '\0';
5694 *qlenPtr = p - q;
5695 return q;
5698 static void UpdateStringOfList(struct Jim_Obj *objPtr)
5700 int i, bufLen, realLength;
5701 const char *strRep;
5702 char *p;
5703 int *quotingType;
5704 Jim_Obj **ele = objPtr->internalRep.listValue.ele;
5706 /* (Over) Estimate the space needed. */
5707 quotingType = Jim_Alloc(sizeof(int) * objPtr->internalRep.listValue.len + 1);
5708 bufLen = 0;
5709 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5710 int len;
5712 strRep = Jim_GetString(ele[i], &len);
5713 quotingType[i] = ListElementQuotingType(strRep, len);
5714 switch (quotingType[i]) {
5715 case JIM_ELESTR_SIMPLE:
5716 bufLen += len;
5717 break;
5718 case JIM_ELESTR_BRACE:
5719 bufLen += len + 2;
5720 break;
5721 case JIM_ELESTR_QUOTE:
5722 bufLen += len * 2;
5723 break;
5725 bufLen++; /* elements separator. */
5727 bufLen++;
5729 /* Generate the string rep. */
5730 p = objPtr->bytes = Jim_Alloc(bufLen + 1);
5731 realLength = 0;
5732 for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
5733 int len, qlen;
5734 char *q;
5736 strRep = Jim_GetString(ele[i], &len);
5738 switch (quotingType[i]) {
5739 case JIM_ELESTR_SIMPLE:
5740 memcpy(p, strRep, len);
5741 p += len;
5742 realLength += len;
5743 break;
5744 case JIM_ELESTR_BRACE:
5745 *p++ = '{';
5746 memcpy(p, strRep, len);
5747 p += len;
5748 *p++ = '}';
5749 realLength += len + 2;
5750 break;
5751 case JIM_ELESTR_QUOTE:
5752 q = BackslashQuoteString(strRep, len, &qlen);
5753 memcpy(p, q, qlen);
5754 Jim_Free(q);
5755 p += qlen;
5756 realLength += qlen;
5757 break;
5759 /* Add a separating space */
5760 if (i + 1 != objPtr->internalRep.listValue.len) {
5761 *p++ = ' ';
5762 realLength++;
5765 *p = '\0'; /* nul term. */
5766 objPtr->length = realLength;
5767 Jim_Free(quotingType);
5770 int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
5772 struct JimParserCtx parser;
5773 const char *str;
5774 int strLen;
5775 Jim_Obj *fileNameObj;
5776 int linenr;
5778 /* Try to preserve information about filename / line number */
5779 if (objPtr->typePtr == &sourceObjType) {
5780 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
5781 linenr = objPtr->internalRep.sourceValue.lineNumber;
5783 else {
5784 fileNameObj = interp->emptyObj;
5785 linenr = 1;
5787 Jim_IncrRefCount(fileNameObj);
5788 //printf("%s:%d incr %s\n", __FILE__, __LINE__, Jim_String(fileNameObj));
5790 /* Get the string representation */
5791 str = Jim_GetString(objPtr, &strLen);
5793 /* Free the old internal repr just now and initialize the
5794 * new one just now. The string->list conversion can't fail. */
5795 Jim_FreeIntRep(interp, objPtr);
5796 objPtr->typePtr = &listObjType;
5797 objPtr->internalRep.listValue.len = 0;
5798 objPtr->internalRep.listValue.maxLen = 0;
5799 objPtr->internalRep.listValue.ele = NULL;
5801 /* Convert into a list */
5802 JimParserInit(&parser, str, strLen, linenr);
5803 while (!parser.eof) {
5804 Jim_Obj *elementPtr;
5806 JimParseList(&parser);
5807 if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
5808 continue;
5809 elementPtr = JimParserGetTokenObj(interp, &parser);
5810 JimSetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
5811 ListAppendElement(objPtr, elementPtr);
5813 Jim_DecrRefCount(interp, fileNameObj);
5814 return JIM_OK;
5817 Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
5819 Jim_Obj *objPtr;
5820 int i;
5822 objPtr = Jim_NewObj(interp);
5823 objPtr->typePtr = &listObjType;
5824 objPtr->bytes = NULL;
5825 objPtr->internalRep.listValue.ele = NULL;
5826 objPtr->internalRep.listValue.len = 0;
5827 objPtr->internalRep.listValue.maxLen = 0;
5828 for (i = 0; i < len; i++) {
5829 ListAppendElement(objPtr, elements[i]);
5831 return objPtr;
5834 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5835 * length of the vector. Note that the user of this function should make
5836 * sure that the list object can't shimmer while the vector returned
5837 * is in use, this vector is the one stored inside the internal representation
5838 * of the list object. This function is not exported, extensions should
5839 * always access to the List object elements using Jim_ListIndex(). */
5840 static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
5841 Jim_Obj ***listVec)
5843 *listLen = Jim_ListLength(interp, listObj);
5844 *listVec = listObj->internalRep.listValue.ele;
5847 /* Sorting uses ints, but commands may return wide */
5848 static int JimSign(jim_wide w)
5850 if (w == 0) {
5851 return 0;
5853 else if (w < 0) {
5854 return -1;
5856 return 1;
5859 /* ListSortElements type values */
5860 struct lsort_info {
5861 jmp_buf jmpbuf;
5862 Jim_Obj *command;
5863 Jim_Interp *interp;
5864 enum {
5865 JIM_LSORT_ASCII,
5866 JIM_LSORT_NOCASE,
5867 JIM_LSORT_INTEGER,
5868 JIM_LSORT_COMMAND
5869 } type;
5870 int order;
5871 int index;
5872 int indexed;
5873 int (*subfn)(Jim_Obj **, Jim_Obj **);
5876 static struct lsort_info *sort_info;
5878 static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5880 Jim_Obj *lObj, *rObj;
5882 if (Jim_ListIndex(sort_info->interp, *lhsObj, sort_info->index, &lObj, JIM_ERRMSG) != JIM_OK ||
5883 Jim_ListIndex(sort_info->interp, *rhsObj, sort_info->index, &rObj, JIM_ERRMSG) != JIM_OK) {
5884 longjmp(sort_info->jmpbuf, JIM_ERR);
5886 return sort_info->subfn(&lObj, &rObj);
5889 /* Sort the internal rep of a list. */
5890 static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5892 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
5895 static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5897 return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
5900 static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5902 jim_wide lhs = 0, rhs = 0;
5904 if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
5905 Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
5906 longjmp(sort_info->jmpbuf, JIM_ERR);
5909 return JimSign(lhs - rhs) * sort_info->order;
5912 static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
5914 Jim_Obj *compare_script;
5915 int rc;
5917 jim_wide ret = 0;
5919 /* This must be a valid list */
5920 compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
5921 Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
5922 Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
5924 rc = Jim_EvalObj(sort_info->interp, compare_script);
5926 if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
5927 longjmp(sort_info->jmpbuf, rc);
5930 return JimSign(ret) * sort_info->order;
5933 /* Sort a list *in place*. MUST be called with non-shared objects. */
5934 static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
5936 struct lsort_info *prev_info;
5938 typedef int (qsort_comparator) (const void *, const void *);
5939 int (*fn) (Jim_Obj **, Jim_Obj **);
5940 Jim_Obj **vector;
5941 int len;
5942 int rc;
5944 JimPanic((Jim_IsShared(listObjPtr), "Jim_ListSortElements called with shared object"));
5945 if (!Jim_IsList(listObjPtr))
5946 SetListFromAny(interp, listObjPtr);
5948 /* Allow lsort to be called reentrantly */
5949 prev_info = sort_info;
5950 sort_info = info;
5952 vector = listObjPtr->internalRep.listValue.ele;
5953 len = listObjPtr->internalRep.listValue.len;
5954 switch (info->type) {
5955 case JIM_LSORT_ASCII:
5956 fn = ListSortString;
5957 break;
5958 case JIM_LSORT_NOCASE:
5959 fn = ListSortStringNoCase;
5960 break;
5961 case JIM_LSORT_INTEGER:
5962 fn = ListSortInteger;
5963 break;
5964 case JIM_LSORT_COMMAND:
5965 fn = ListSortCommand;
5966 break;
5967 default:
5968 fn = NULL; /* avoid warning */
5969 JimPanic((1, "ListSort called with invalid sort type"));
5972 if (info->indexed) {
5973 /* Need to interpose a "list index" function */
5974 info->subfn = fn;
5975 fn = ListSortIndexHelper;
5978 if ((rc = setjmp(info->jmpbuf)) == 0) {
5979 qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
5981 Jim_InvalidateStringRep(listObjPtr);
5982 sort_info = prev_info;
5984 return rc;
5987 /* This is the low-level function to insert elements into a list.
5988 * The higher-level Jim_ListInsertElements() performs shared object
5989 * check and invalidate the string repr. This version is used
5990 * in the internals of the List Object and is not exported.
5992 * NOTE: this function can be called only against objects
5993 * with internal type of List. */
5994 static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
5996 int currentLen = listPtr->internalRep.listValue.len;
5997 int requiredLen = currentLen + elemc;
5998 int i;
5999 Jim_Obj **point;
6001 if (requiredLen > listPtr->internalRep.listValue.maxLen) {
6002 int maxLen = requiredLen * 2;
6004 listPtr->internalRep.listValue.ele =
6005 Jim_Realloc(listPtr->internalRep.listValue.ele, sizeof(Jim_Obj *) * maxLen);
6006 listPtr->internalRep.listValue.maxLen = maxLen;
6008 point = listPtr->internalRep.listValue.ele + idx;
6009 memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
6010 for (i = 0; i < elemc; ++i) {
6011 point[i] = elemVec[i];
6012 Jim_IncrRefCount(point[i]);
6014 listPtr->internalRep.listValue.len += elemc;
6017 /* Convenience call to ListInsertElements() to append a single element.
6019 static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
6021 ListInsertElements(listPtr, listPtr->internalRep.listValue.len, 1, &objPtr);
6025 /* Appends every element of appendListPtr into listPtr.
6026 * Both have to be of the list type.
6027 * Convenience call to ListInsertElements()
6029 static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6031 ListInsertElements(listPtr, listPtr->internalRep.listValue.len,
6032 appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
6035 void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
6037 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
6038 if (!Jim_IsList(listPtr))
6039 SetListFromAny(interp, listPtr);
6040 Jim_InvalidateStringRep(listPtr);
6041 ListAppendElement(listPtr, objPtr);
6044 void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
6046 JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
6047 if (!Jim_IsList(listPtr))
6048 SetListFromAny(interp, listPtr);
6049 Jim_InvalidateStringRep(listPtr);
6050 ListAppendList(listPtr, appendListPtr);
6053 int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
6055 if (!Jim_IsList(objPtr))
6056 SetListFromAny(interp, objPtr);
6057 return objPtr->internalRep.listValue.len;
6060 void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6061 int objc, Jim_Obj *const *objVec)
6063 JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
6064 if (!Jim_IsList(listPtr))
6065 SetListFromAny(interp, listPtr);
6066 if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
6067 idx = listPtr->internalRep.listValue.len;
6068 else if (idx < 0)
6069 idx = 0;
6070 Jim_InvalidateStringRep(listPtr);
6071 ListInsertElements(listPtr, idx, objc, objVec);
6074 int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
6076 if (!Jim_IsList(listPtr))
6077 SetListFromAny(interp, listPtr);
6078 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6079 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6080 if (flags & JIM_ERRMSG) {
6081 Jim_SetResultString(interp, "list index out of range", -1);
6083 *objPtrPtr = NULL;
6084 return JIM_ERR;
6086 if (idx < 0)
6087 idx = listPtr->internalRep.listValue.len + idx;
6088 *objPtrPtr = listPtr->internalRep.listValue.ele[idx];
6089 return JIM_OK;
6092 static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
6093 Jim_Obj *newObjPtr, int flags)
6095 if (!Jim_IsList(listPtr))
6096 SetListFromAny(interp, listPtr);
6097 if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
6098 (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
6099 if (flags & JIM_ERRMSG) {
6100 Jim_SetResultString(interp, "list index out of range", -1);
6102 return JIM_ERR;
6104 if (idx < 0)
6105 idx = listPtr->internalRep.listValue.len + idx;
6106 Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
6107 listPtr->internalRep.listValue.ele[idx] = newObjPtr;
6108 Jim_IncrRefCount(newObjPtr);
6109 return JIM_OK;
6112 /* Modify the list stored into the variable named 'varNamePtr'
6113 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6114 * with the new element 'newObjptr'. */
6115 int Jim_SetListIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
6116 Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
6118 Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
6119 int shared, i, idx;
6121 varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
6122 if (objPtr == NULL)
6123 return JIM_ERR;
6124 if ((shared = Jim_IsShared(objPtr)))
6125 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6126 for (i = 0; i < indexc - 1; i++) {
6127 listObjPtr = objPtr;
6128 if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
6129 goto err;
6130 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_ERRMSG) != JIM_OK) {
6131 goto err;
6133 if (Jim_IsShared(objPtr)) {
6134 objPtr = Jim_DuplicateObj(interp, objPtr);
6135 ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
6137 Jim_InvalidateStringRep(listObjPtr);
6139 if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
6140 goto err;
6141 if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
6142 goto err;
6143 Jim_InvalidateStringRep(objPtr);
6144 Jim_InvalidateStringRep(varObjPtr);
6145 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
6146 goto err;
6147 Jim_SetResult(interp, varObjPtr);
6148 return JIM_OK;
6149 err:
6150 if (shared) {
6151 Jim_FreeNewObj(interp, varObjPtr);
6153 return JIM_ERR;
6156 Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
6158 int i;
6160 /* If all the objects in objv are lists,
6161 * it's possible to return a list as result, that's the
6162 * concatenation of all the lists. */
6163 for (i = 0; i < objc; i++) {
6164 if (!Jim_IsList(objv[i]))
6165 break;
6167 if (i == objc) {
6168 Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
6170 for (i = 0; i < objc; i++)
6171 Jim_ListAppendList(interp, objPtr, objv[i]);
6172 return objPtr;
6174 else {
6175 /* Else... we have to glue strings together */
6176 int len = 0, objLen;
6177 char *bytes, *p;
6179 /* Compute the length */
6180 for (i = 0; i < objc; i++) {
6181 Jim_GetString(objv[i], &objLen);
6182 len += objLen;
6184 if (objc)
6185 len += objc - 1;
6186 /* Create the string rep, and a string object holding it. */
6187 p = bytes = Jim_Alloc(len + 1);
6188 for (i = 0; i < objc; i++) {
6189 const char *s = Jim_GetString(objv[i], &objLen);
6191 /* Remove leading space */
6192 while (objLen && (*s == ' ' || *s == '\t' || *s == '\n')) {
6193 s++;
6194 objLen--;
6195 len--;
6197 /* And trailing space */
6198 while (objLen && (s[objLen - 1] == ' ' ||
6199 s[objLen - 1] == '\n' || s[objLen - 1] == '\t')) {
6200 /* Handle trailing backslash-space case */
6201 if (objLen > 1 && s[objLen - 2] == '\\') {
6202 break;
6204 objLen--;
6205 len--;
6207 memcpy(p, s, objLen);
6208 p += objLen;
6209 if (objLen && i + 1 != objc) {
6210 *p++ = ' ';
6212 else if (i + 1 != objc) {
6213 /* Drop the space calcuated for this
6214 * element that is instead null. */
6215 len--;
6218 *p = '\0';
6219 return Jim_NewStringObjNoAlloc(interp, bytes, len);
6223 /* Returns a list composed of the elements in the specified range.
6224 * first and start are directly accepted as Jim_Objects and
6225 * processed for the end?-index? case. */
6226 Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
6227 Jim_Obj *lastObjPtr)
6229 int first, last;
6230 int len, rangeLen;
6232 if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
6233 Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
6234 return NULL;
6235 len = Jim_ListLength(interp, listObjPtr); /* will convert into list */
6236 first = JimRelToAbsIndex(len, first);
6237 last = JimRelToAbsIndex(len, last);
6238 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
6239 if (first == 0 && last == len) {
6240 return listObjPtr;
6242 return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
6245 /* -----------------------------------------------------------------------------
6246 * Dict object
6247 * ---------------------------------------------------------------------------*/
6248 static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
6249 static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
6250 static void UpdateStringOfDict(struct Jim_Obj *objPtr);
6251 static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6253 /* Dict HashTable Type.
6255 * Keys and Values are Jim objects. */
6257 static unsigned int JimObjectHTHashFunction(const void *key)
6259 const char *str;
6260 Jim_Obj *objPtr = (Jim_Obj *)key;
6261 int len, h;
6263 str = Jim_GetString(objPtr, &len);
6264 h = Jim_GenHashFunction((unsigned char *)str, len);
6265 return h;
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. */
6626 int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
6627 Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr)
6629 Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
6630 int shared, i;
6632 varObjPtr = objPtr =
6633 Jim_GetVariable(interp, varNamePtr, newObjPtr == NULL ? JIM_ERRMSG : JIM_NONE);
6634 if (objPtr == NULL) {
6635 if (newObjPtr == NULL) /* Cannot remove a key from non existing var */
6636 return JIM_ERR;
6637 varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
6638 if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
6639 Jim_FreeNewObj(interp, varObjPtr);
6640 return JIM_ERR;
6643 if ((shared = Jim_IsShared(objPtr)))
6644 varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
6645 for (i = 0; i < keyc - 1; i++) {
6646 dictObjPtr = objPtr;
6648 /* Check if it's a valid dictionary */
6649 if (dictObjPtr->typePtr != &dictObjType) {
6650 if (SetDictFromAny(interp, dictObjPtr) != JIM_OK)
6651 goto err;
6653 /* Check if the given key exists. */
6654 Jim_InvalidateStringRep(dictObjPtr);
6655 if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
6656 newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
6657 /* This key exists at the current level.
6658 * Make sure it's not shared!. */
6659 if (Jim_IsShared(objPtr)) {
6660 objPtr = Jim_DuplicateObj(interp, objPtr);
6661 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6664 else {
6665 /* Key not found. If it's an [unset] operation
6666 * this is an error. Only the last key may not
6667 * exist. */
6668 if (newObjPtr == NULL)
6669 goto err;
6670 /* Otherwise set an empty dictionary
6671 * as key's value. */
6672 objPtr = Jim_NewDictObj(interp, NULL, 0);
6673 DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
6676 if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
6677 goto err;
6679 Jim_InvalidateStringRep(objPtr);
6680 Jim_InvalidateStringRep(varObjPtr);
6681 if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
6682 goto err;
6683 Jim_SetResult(interp, varObjPtr);
6684 return JIM_OK;
6685 err:
6686 if (shared) {
6687 Jim_FreeNewObj(interp, varObjPtr);
6689 return JIM_ERR;
6692 /* -----------------------------------------------------------------------------
6693 * Index object
6694 * ---------------------------------------------------------------------------*/
6695 static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
6696 static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
6698 static const Jim_ObjType indexObjType = {
6699 "index",
6700 NULL,
6701 NULL,
6702 UpdateStringOfIndex,
6703 JIM_TYPE_NONE,
6706 void UpdateStringOfIndex(struct Jim_Obj *objPtr)
6708 int len;
6709 char buf[JIM_INTEGER_SPACE + 1];
6711 if (objPtr->internalRep.indexValue >= 0)
6712 len = sprintf(buf, "%d", objPtr->internalRep.indexValue);
6713 else if (objPtr->internalRep.indexValue == -1)
6714 len = sprintf(buf, "end");
6715 else {
6716 len = sprintf(buf, "end%d", objPtr->internalRep.indexValue + 1);
6718 objPtr->bytes = Jim_Alloc(len + 1);
6719 memcpy(objPtr->bytes, buf, len + 1);
6720 objPtr->length = len;
6723 int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6725 int idx, end = 0;
6726 const char *str;
6727 char *endptr;
6729 /* Get the string representation */
6730 str = Jim_String(objPtr);
6732 /* Try to convert into an index */
6733 if (strncmp(str, "end", 3) == 0) {
6734 end = 1;
6735 str += 3;
6736 idx = 0;
6738 else {
6739 idx = strtol(str, &endptr, 10);
6741 if (endptr == str) {
6742 goto badindex;
6744 str = endptr;
6747 /* Now str may include or +<num> or -<num> */
6748 if (*str == '+' || *str == '-') {
6749 int sign = (*str == '+' ? 1 : -1);
6751 idx += sign * strtol(++str, &endptr, 10);
6752 if (str == endptr || *endptr) {
6753 goto badindex;
6755 str = endptr;
6757 /* The only thing left should be spaces */
6758 while (isspace(UCHAR(*str))) {
6759 str++;
6761 if (*str) {
6762 goto badindex;
6764 if (end) {
6765 if (idx > 0) {
6766 idx = INT_MAX;
6768 else {
6769 /* end-1 is repesented as -2 */
6770 idx--;
6773 else if (idx < 0) {
6774 idx = -INT_MAX;
6777 /* Free the old internal repr and set the new one. */
6778 Jim_FreeIntRep(interp, objPtr);
6779 objPtr->typePtr = &indexObjType;
6780 objPtr->internalRep.indexValue = idx;
6781 return JIM_OK;
6783 badindex:
6784 Jim_SetResultFormatted(interp,
6785 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr);
6786 return JIM_ERR;
6789 int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
6791 /* Avoid shimmering if the object is an integer. */
6792 if (objPtr->typePtr == &intObjType) {
6793 jim_wide val = JimWideValue(objPtr);
6795 if (!(val < LONG_MIN) && !(val > LONG_MAX)) {
6796 *indexPtr = (val < 0) ? -INT_MAX : (long)val;;
6797 return JIM_OK;
6800 if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
6801 return JIM_ERR;
6802 *indexPtr = objPtr->internalRep.indexValue;
6803 return JIM_OK;
6806 /* -----------------------------------------------------------------------------
6807 * Return Code Object.
6808 * ---------------------------------------------------------------------------*/
6810 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6811 static const char * const jimReturnCodes[] = {
6812 [JIM_OK] = "ok",
6813 [JIM_ERR] = "error",
6814 [JIM_RETURN] = "return",
6815 [JIM_BREAK] = "break",
6816 [JIM_CONTINUE] = "continue",
6817 [JIM_SIGNAL] = "signal",
6818 [JIM_EXIT] = "exit",
6819 [JIM_EVAL] = "eval",
6820 NULL
6823 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6825 static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
6827 static const Jim_ObjType returnCodeObjType = {
6828 "return-code",
6829 NULL,
6830 NULL,
6831 NULL,
6832 JIM_TYPE_NONE,
6835 /* Converts a (standard) return code to a string. Returns "?" for
6836 * non-standard return codes.
6838 const char *Jim_ReturnCode(int code)
6840 if (code < 0 || code >= (int)jimReturnCodesSize) {
6841 return "?";
6843 else {
6844 return jimReturnCodes[code];
6848 int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
6850 int returnCode;
6851 jim_wide wideValue;
6853 /* Try to convert into an integer */
6854 if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
6855 returnCode = (int)wideValue;
6856 else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
6857 Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
6858 return JIM_ERR;
6860 /* Free the old internal repr and set the new one. */
6861 Jim_FreeIntRep(interp, objPtr);
6862 objPtr->typePtr = &returnCodeObjType;
6863 objPtr->internalRep.returnCode = returnCode;
6864 return JIM_OK;
6867 int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
6869 if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
6870 return JIM_ERR;
6871 *intPtr = objPtr->internalRep.returnCode;
6872 return JIM_OK;
6875 /* -----------------------------------------------------------------------------
6876 * Expression Parsing
6877 * ---------------------------------------------------------------------------*/
6878 static int JimParseExprOperator(struct JimParserCtx *pc);
6879 static int JimParseExprNumber(struct JimParserCtx *pc);
6880 static int JimParseExprIrrational(struct JimParserCtx *pc);
6882 /* Exrp's Stack machine operators opcodes. */
6884 /* Binary operators (numbers) */
6885 enum
6887 /* Continues on from the JIM_TT_ space */
6888 /* Operations */
6889 JIM_EXPROP_MUL = JIM_TT_EXPR_OP, /* 15 */
6890 JIM_EXPROP_DIV,
6891 JIM_EXPROP_MOD,
6892 JIM_EXPROP_SUB,
6893 JIM_EXPROP_ADD,
6894 JIM_EXPROP_LSHIFT,
6895 JIM_EXPROP_RSHIFT,
6896 JIM_EXPROP_ROTL,
6897 JIM_EXPROP_ROTR,
6898 JIM_EXPROP_LT,
6899 JIM_EXPROP_GT,
6900 JIM_EXPROP_LTE,
6901 JIM_EXPROP_GTE,
6902 JIM_EXPROP_NUMEQ,
6903 JIM_EXPROP_NUMNE,
6904 JIM_EXPROP_BITAND, /* 30 */
6905 JIM_EXPROP_BITXOR,
6906 JIM_EXPROP_BITOR,
6908 /* Note must keep these together */
6909 JIM_EXPROP_LOGICAND, /* 33 */
6910 JIM_EXPROP_LOGICAND_LEFT,
6911 JIM_EXPROP_LOGICAND_RIGHT,
6913 /* and these */
6914 JIM_EXPROP_LOGICOR, /* 36 */
6915 JIM_EXPROP_LOGICOR_LEFT,
6916 JIM_EXPROP_LOGICOR_RIGHT,
6918 /* and these */
6919 /* Ternary operators */
6920 JIM_EXPROP_TERNARY, /* 39 */
6921 JIM_EXPROP_TERNARY_LEFT,
6922 JIM_EXPROP_TERNARY_RIGHT,
6924 /* and these */
6925 JIM_EXPROP_COLON, /* 42 */
6926 JIM_EXPROP_COLON_LEFT,
6927 JIM_EXPROP_COLON_RIGHT,
6929 JIM_EXPROP_POW, /* 45 */
6931 /* Binary operators (strings) */
6932 JIM_EXPROP_STREQ,
6933 JIM_EXPROP_STRNE,
6934 JIM_EXPROP_STRIN,
6935 JIM_EXPROP_STRNI,
6937 /* Unary operators (numbers) */
6938 JIM_EXPROP_NOT,
6939 JIM_EXPROP_BITNOT,
6940 JIM_EXPROP_UNARYMINUS,
6941 JIM_EXPROP_UNARYPLUS,
6943 /* Functions */
6944 JIM_EXPROP_FUNC_FIRST,
6945 JIM_EXPROP_FUNC_INT = JIM_EXPROP_FUNC_FIRST,
6946 JIM_EXPROP_FUNC_ABS,
6947 JIM_EXPROP_FUNC_DOUBLE,
6948 JIM_EXPROP_FUNC_ROUND,
6949 JIM_EXPROP_FUNC_RAND,
6950 JIM_EXPROP_FUNC_SRAND,
6952 #ifdef JIM_MATH_FUNCTIONS
6953 /* math functions from libm */
6954 JIM_EXPROP_FUNC_SIN,
6955 JIM_EXPROP_FUNC_COS,
6956 JIM_EXPROP_FUNC_TAN,
6957 JIM_EXPROP_FUNC_ASIN,
6958 JIM_EXPROP_FUNC_ACOS,
6959 JIM_EXPROP_FUNC_ATAN,
6960 JIM_EXPROP_FUNC_SINH,
6961 JIM_EXPROP_FUNC_COSH,
6962 JIM_EXPROP_FUNC_TANH,
6963 JIM_EXPROP_FUNC_CEIL,
6964 JIM_EXPROP_FUNC_FLOOR,
6965 JIM_EXPROP_FUNC_EXP,
6966 JIM_EXPROP_FUNC_LOG,
6967 JIM_EXPROP_FUNC_LOG10,
6968 JIM_EXPROP_FUNC_SQRT,
6969 #endif
6972 struct JimExprState
6974 Jim_Obj **stack;
6975 int stacklen;
6976 int opcode;
6977 int skip;
6980 /* Operators table */
6981 typedef struct Jim_ExprOperator
6983 const char *name;
6984 int precedence;
6985 int arity;
6986 int (*funcop) (Jim_Interp *interp, struct JimExprState * e);
6987 int lazy;
6988 } Jim_ExprOperator;
6990 static void ExprPush(struct JimExprState *e, Jim_Obj *obj)
6992 Jim_IncrRefCount(obj);
6993 e->stack[e->stacklen++] = obj;
6996 static Jim_Obj *ExprPop(struct JimExprState *e)
6998 return e->stack[--e->stacklen];
7001 static int JimExprOpNumUnary(Jim_Interp *interp, struct JimExprState *e)
7003 int intresult = 0;
7004 int rc = JIM_OK;
7005 Jim_Obj *A = ExprPop(e);
7006 double dA, dC = 0;
7007 jim_wide wA, wC = 0;
7009 if ((A->typePtr != &doubleObjType || A->bytes) && JimGetWideNoErr(interp, A, &wA) == JIM_OK) {
7010 intresult = 1;
7012 switch (e->opcode) {
7013 case JIM_EXPROP_FUNC_INT:
7014 wC = wA;
7015 break;
7016 case JIM_EXPROP_FUNC_ROUND:
7017 wC = wA;
7018 break;
7019 case JIM_EXPROP_FUNC_DOUBLE:
7020 dC = wA;
7021 intresult = 0;
7022 break;
7023 case JIM_EXPROP_FUNC_ABS:
7024 wC = wA >= 0 ? wA : -wA;
7025 break;
7026 case JIM_EXPROP_UNARYMINUS:
7027 wC = -wA;
7028 break;
7029 case JIM_EXPROP_UNARYPLUS:
7030 wC = wA;
7031 break;
7032 case JIM_EXPROP_NOT:
7033 wC = !wA;
7034 break;
7035 default:
7036 abort();
7039 else if ((rc = Jim_GetDouble(interp, A, &dA)) == JIM_OK) {
7040 switch (e->opcode) {
7041 case JIM_EXPROP_FUNC_INT:
7042 wC = dA;
7043 intresult = 1;
7044 break;
7045 case JIM_EXPROP_FUNC_ROUND:
7046 wC = dA < 0 ? (dA - 0.5) : (dA + 0.5);
7047 intresult = 1;
7048 break;
7049 case JIM_EXPROP_FUNC_DOUBLE:
7050 dC = dA;
7051 break;
7052 case JIM_EXPROP_FUNC_ABS:
7053 dC = dA >= 0 ? dA : -dA;
7054 break;
7055 case JIM_EXPROP_UNARYMINUS:
7056 dC = -dA;
7057 break;
7058 case JIM_EXPROP_UNARYPLUS:
7059 dC = dA;
7060 break;
7061 case JIM_EXPROP_NOT:
7062 wC = !dA;
7063 intresult = 1;
7064 break;
7065 default:
7066 abort();
7070 if (rc == JIM_OK) {
7071 if (intresult) {
7072 ExprPush(e, Jim_NewIntObj(interp, wC));
7074 else {
7075 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7079 Jim_DecrRefCount(interp, A);
7081 return rc;
7084 static double JimRandDouble(Jim_Interp *interp)
7086 unsigned long x;
7087 JimRandomBytes(interp, &x, sizeof(x));
7089 return (double)x / (unsigned long)~0;
7092 static int JimExprOpIntUnary(Jim_Interp *interp, struct JimExprState *e)
7094 Jim_Obj *A = ExprPop(e);
7095 jim_wide wA;
7097 int rc = Jim_GetWide(interp, A, &wA);
7098 if (rc == JIM_OK) {
7099 switch (e->opcode) {
7100 case JIM_EXPROP_BITNOT:
7101 ExprPush(e, Jim_NewIntObj(interp, ~wA));
7102 break;
7103 case JIM_EXPROP_FUNC_SRAND:
7104 JimPrngSeed(interp, (unsigned char *)&wA, sizeof(wA));
7105 ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
7106 break;
7107 default:
7108 abort();
7112 Jim_DecrRefCount(interp, A);
7114 return rc;
7117 static int JimExprOpNone(Jim_Interp *interp, struct JimExprState *e)
7119 JimPanic((e->opcode != JIM_EXPROP_FUNC_RAND, "JimExprOpNone only support rand()"));
7121 ExprPush(e, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
7123 return JIM_OK;
7126 #ifdef JIM_MATH_FUNCTIONS
7127 static int JimExprOpDoubleUnary(Jim_Interp *interp, struct JimExprState *e)
7129 int rc;
7130 Jim_Obj *A = ExprPop(e);
7131 double dA, dC;
7133 rc = Jim_GetDouble(interp, A, &dA);
7134 if (rc == JIM_OK) {
7135 switch (e->opcode) {
7136 case JIM_EXPROP_FUNC_SIN:
7137 dC = sin(dA);
7138 break;
7139 case JIM_EXPROP_FUNC_COS:
7140 dC = cos(dA);
7141 break;
7142 case JIM_EXPROP_FUNC_TAN:
7143 dC = tan(dA);
7144 break;
7145 case JIM_EXPROP_FUNC_ASIN:
7146 dC = asin(dA);
7147 break;
7148 case JIM_EXPROP_FUNC_ACOS:
7149 dC = acos(dA);
7150 break;
7151 case JIM_EXPROP_FUNC_ATAN:
7152 dC = atan(dA);
7153 break;
7154 case JIM_EXPROP_FUNC_SINH:
7155 dC = sinh(dA);
7156 break;
7157 case JIM_EXPROP_FUNC_COSH:
7158 dC = cosh(dA);
7159 break;
7160 case JIM_EXPROP_FUNC_TANH:
7161 dC = tanh(dA);
7162 break;
7163 case JIM_EXPROP_FUNC_CEIL:
7164 dC = ceil(dA);
7165 break;
7166 case JIM_EXPROP_FUNC_FLOOR:
7167 dC = floor(dA);
7168 break;
7169 case JIM_EXPROP_FUNC_EXP:
7170 dC = exp(dA);
7171 break;
7172 case JIM_EXPROP_FUNC_LOG:
7173 dC = log(dA);
7174 break;
7175 case JIM_EXPROP_FUNC_LOG10:
7176 dC = log10(dA);
7177 break;
7178 case JIM_EXPROP_FUNC_SQRT:
7179 dC = sqrt(dA);
7180 break;
7181 default:
7182 abort();
7184 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7187 Jim_DecrRefCount(interp, A);
7189 return rc;
7191 #endif
7193 /* A binary operation on two ints */
7194 static int JimExprOpIntBin(Jim_Interp *interp, struct JimExprState *e)
7196 Jim_Obj *B = ExprPop(e);
7197 Jim_Obj *A = ExprPop(e);
7198 jim_wide wA, wB;
7199 int rc = JIM_ERR;
7201 if (Jim_GetWide(interp, A, &wA) == JIM_OK && Jim_GetWide(interp, B, &wB) == JIM_OK) {
7202 jim_wide wC;
7204 rc = JIM_OK;
7206 switch (e->opcode) {
7207 case JIM_EXPROP_LSHIFT:
7208 wC = wA << wB;
7209 break;
7210 case JIM_EXPROP_RSHIFT:
7211 wC = wA >> wB;
7212 break;
7213 case JIM_EXPROP_BITAND:
7214 wC = wA & wB;
7215 break;
7216 case JIM_EXPROP_BITXOR:
7217 wC = wA ^ wB;
7218 break;
7219 case JIM_EXPROP_BITOR:
7220 wC = wA | wB;
7221 break;
7222 case JIM_EXPROP_MOD:
7223 if (wB == 0) {
7224 wC = 0;
7225 Jim_SetResultString(interp, "Division by zero", -1);
7226 rc = JIM_ERR;
7228 else {
7230 * From Tcl 8.x
7232 * This code is tricky: C doesn't guarantee much
7233 * about the quotient or remainder, but Tcl does.
7234 * The remainder always has the same sign as the
7235 * divisor and a smaller absolute value.
7237 int negative = 0;
7239 if (wB < 0) {
7240 wB = -wB;
7241 wA = -wA;
7242 negative = 1;
7244 wC = wA % wB;
7245 if (wC < 0) {
7246 wC += wB;
7248 if (negative) {
7249 wC = -wC;
7252 break;
7253 case JIM_EXPROP_ROTL:
7254 case JIM_EXPROP_ROTR:{
7255 /* uint32_t would be better. But not everyone has inttypes.h? */
7256 unsigned long uA = (unsigned long)wA;
7257 unsigned long uB = (unsigned long)wB;
7258 const unsigned int S = sizeof(unsigned long) * 8;
7260 /* Shift left by the word size or more is undefined. */
7261 uB %= S;
7263 if (e->opcode == JIM_EXPROP_ROTR) {
7264 uB = S - uB;
7266 wC = (unsigned long)(uA << uB) | (uA >> (S - uB));
7267 break;
7269 default:
7270 abort();
7272 ExprPush(e, Jim_NewIntObj(interp, wC));
7276 Jim_DecrRefCount(interp, A);
7277 Jim_DecrRefCount(interp, B);
7279 return rc;
7283 /* A binary operation on two ints or two doubles (or two strings for some ops) */
7284 static int JimExprOpBin(Jim_Interp *interp, struct JimExprState *e)
7286 int intresult = 0;
7287 int rc = JIM_OK;
7288 double dA, dB, dC = 0;
7289 jim_wide wA, wB, wC = 0;
7291 Jim_Obj *B = ExprPop(e);
7292 Jim_Obj *A = ExprPop(e);
7294 if ((A->typePtr != &doubleObjType || A->bytes) &&
7295 (B->typePtr != &doubleObjType || B->bytes) &&
7296 JimGetWideNoErr(interp, A, &wA) == JIM_OK && JimGetWideNoErr(interp, B, &wB) == JIM_OK) {
7298 /* Both are ints */
7300 intresult = 1;
7302 switch (e->opcode) {
7303 case JIM_EXPROP_POW:
7304 wC = JimPowWide(wA, wB);
7305 break;
7306 case JIM_EXPROP_ADD:
7307 wC = wA + wB;
7308 break;
7309 case JIM_EXPROP_SUB:
7310 wC = wA - wB;
7311 break;
7312 case JIM_EXPROP_MUL:
7313 wC = wA * wB;
7314 break;
7315 case JIM_EXPROP_DIV:
7316 if (wB == 0) {
7317 Jim_SetResultString(interp, "Division by zero", -1);
7318 rc = JIM_ERR;
7320 else {
7322 * From Tcl 8.x
7324 * This code is tricky: C doesn't guarantee much
7325 * about the quotient or remainder, but Tcl does.
7326 * The remainder always has the same sign as the
7327 * divisor and a smaller absolute value.
7329 if (wB < 0) {
7330 wB = -wB;
7331 wA = -wA;
7333 wC = wA / wB;
7334 if (wA % wB < 0) {
7335 wC--;
7338 break;
7339 case JIM_EXPROP_LT:
7340 wC = wA < wB;
7341 break;
7342 case JIM_EXPROP_GT:
7343 wC = wA > wB;
7344 break;
7345 case JIM_EXPROP_LTE:
7346 wC = wA <= wB;
7347 break;
7348 case JIM_EXPROP_GTE:
7349 wC = wA >= wB;
7350 break;
7351 case JIM_EXPROP_NUMEQ:
7352 wC = wA == wB;
7353 break;
7354 case JIM_EXPROP_NUMNE:
7355 wC = wA != wB;
7356 break;
7357 default:
7358 abort();
7361 else if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
7362 switch (e->opcode) {
7363 case JIM_EXPROP_POW:
7364 #ifdef JIM_MATH_FUNCTIONS
7365 dC = pow(dA, dB);
7366 #else
7367 Jim_SetResultString(interp, "unsupported", -1);
7368 rc = JIM_ERR;
7369 #endif
7370 break;
7371 case JIM_EXPROP_ADD:
7372 dC = dA + dB;
7373 break;
7374 case JIM_EXPROP_SUB:
7375 dC = dA - dB;
7376 break;
7377 case JIM_EXPROP_MUL:
7378 dC = dA * dB;
7379 break;
7380 case JIM_EXPROP_DIV:
7381 if (dB == 0) {
7382 #ifdef INFINITY
7383 dC = dA < 0 ? -INFINITY : INFINITY;
7384 #else
7385 dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
7386 #endif
7388 else {
7389 dC = dA / dB;
7391 break;
7392 case JIM_EXPROP_LT:
7393 wC = dA < dB;
7394 intresult = 1;
7395 break;
7396 case JIM_EXPROP_GT:
7397 wC = dA > dB;
7398 intresult = 1;
7399 break;
7400 case JIM_EXPROP_LTE:
7401 wC = dA <= dB;
7402 intresult = 1;
7403 break;
7404 case JIM_EXPROP_GTE:
7405 wC = dA >= dB;
7406 intresult = 1;
7407 break;
7408 case JIM_EXPROP_NUMEQ:
7409 wC = dA == dB;
7410 intresult = 1;
7411 break;
7412 case JIM_EXPROP_NUMNE:
7413 wC = dA != dB;
7414 intresult = 1;
7415 break;
7416 default:
7417 abort();
7420 else {
7421 /* Handle the string case */
7423 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7424 int i = Jim_StringCompareObj(interp, A, B, 0);
7426 intresult = 1;
7428 switch (e->opcode) {
7429 case JIM_EXPROP_LT:
7430 wC = i < 0;
7431 break;
7432 case JIM_EXPROP_GT:
7433 wC = i > 0;
7434 break;
7435 case JIM_EXPROP_LTE:
7436 wC = i <= 0;
7437 break;
7438 case JIM_EXPROP_GTE:
7439 wC = i >= 0;
7440 break;
7441 case JIM_EXPROP_NUMEQ:
7442 wC = i == 0;
7443 break;
7444 case JIM_EXPROP_NUMNE:
7445 wC = i != 0;
7446 break;
7447 default:
7448 rc = JIM_ERR;
7449 break;
7453 if (rc == JIM_OK) {
7454 if (intresult) {
7455 ExprPush(e, Jim_NewIntObj(interp, wC));
7457 else {
7458 ExprPush(e, Jim_NewDoubleObj(interp, dC));
7462 Jim_DecrRefCount(interp, A);
7463 Jim_DecrRefCount(interp, B);
7465 return rc;
7468 static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
7470 int listlen;
7471 int i;
7473 listlen = Jim_ListLength(interp, listObjPtr);
7474 for (i = 0; i < listlen; i++) {
7475 Jim_Obj *objPtr;
7477 Jim_ListIndex(interp, listObjPtr, i, &objPtr, JIM_NONE);
7479 if (Jim_StringEqObj(objPtr, valObj)) {
7480 return 1;
7483 return 0;
7486 static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprState *e)
7488 Jim_Obj *B = ExprPop(e);
7489 Jim_Obj *A = ExprPop(e);
7491 jim_wide wC;
7493 switch (e->opcode) {
7494 case JIM_EXPROP_STREQ:
7495 case JIM_EXPROP_STRNE: {
7496 int Alen, Blen;
7497 const char *sA = Jim_GetString(A, &Alen);
7498 const char *sB = Jim_GetString(B, &Blen);
7500 if (e->opcode == JIM_EXPROP_STREQ) {
7501 wC = (Alen == Blen && memcmp(sA, sB, Alen) == 0);
7503 else {
7504 wC = (Alen != Blen || memcmp(sA, sB, Alen) != 0);
7506 break;
7508 case JIM_EXPROP_STRIN:
7509 wC = JimSearchList(interp, B, A);
7510 break;
7511 case JIM_EXPROP_STRNI:
7512 wC = !JimSearchList(interp, B, A);
7513 break;
7514 default:
7515 abort();
7517 ExprPush(e, Jim_NewIntObj(interp, wC));
7519 Jim_DecrRefCount(interp, A);
7520 Jim_DecrRefCount(interp, B);
7522 return JIM_OK;
7525 static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
7527 long l;
7528 double d;
7530 if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
7531 return l != 0;
7533 if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
7534 return d != 0;
7536 return -1;
7539 static int JimExprOpAndLeft(Jim_Interp *interp, struct JimExprState *e)
7541 Jim_Obj *skip = ExprPop(e);
7542 Jim_Obj *A = ExprPop(e);
7543 int rc = JIM_OK;
7545 switch (ExprBool(interp, A)) {
7546 case 0:
7547 /* false, so skip RHS opcodes with a 0 result */
7548 e->skip = JimWideValue(skip);
7549 ExprPush(e, Jim_NewIntObj(interp, 0));
7550 break;
7552 case 1:
7553 /* true so continue */
7554 break;
7556 case -1:
7557 /* Invalid */
7558 rc = JIM_ERR;
7560 Jim_DecrRefCount(interp, A);
7561 Jim_DecrRefCount(interp, skip);
7563 return rc;
7566 static int JimExprOpOrLeft(Jim_Interp *interp, struct JimExprState *e)
7568 Jim_Obj *skip = ExprPop(e);
7569 Jim_Obj *A = ExprPop(e);
7570 int rc = JIM_OK;
7572 switch (ExprBool(interp, A)) {
7573 case 0:
7574 /* false, so do nothing */
7575 break;
7577 case 1:
7578 /* true so skip RHS opcodes with a 1 result */
7579 e->skip = JimWideValue(skip);
7580 ExprPush(e, Jim_NewIntObj(interp, 1));
7581 break;
7583 case -1:
7584 /* Invalid */
7585 rc = JIM_ERR;
7586 break;
7588 Jim_DecrRefCount(interp, A);
7589 Jim_DecrRefCount(interp, skip);
7591 return rc;
7594 static int JimExprOpAndOrRight(Jim_Interp *interp, struct JimExprState *e)
7596 Jim_Obj *A = ExprPop(e);
7597 int rc = JIM_OK;
7599 switch (ExprBool(interp, A)) {
7600 case 0:
7601 ExprPush(e, Jim_NewIntObj(interp, 0));
7602 break;
7604 case 1:
7605 ExprPush(e, Jim_NewIntObj(interp, 1));
7606 break;
7608 case -1:
7609 /* Invalid */
7610 rc = JIM_ERR;
7611 break;
7613 Jim_DecrRefCount(interp, A);
7615 return rc;
7618 static int JimExprOpTernaryLeft(Jim_Interp *interp, struct JimExprState *e)
7620 Jim_Obj *skip = ExprPop(e);
7621 Jim_Obj *A = ExprPop(e);
7622 int rc = JIM_OK;
7624 /* Repush A */
7625 ExprPush(e, A);
7627 switch (ExprBool(interp, A)) {
7628 case 0:
7629 /* false, skip RHS opcodes */
7630 e->skip = JimWideValue(skip);
7631 /* Push a dummy value */
7632 ExprPush(e, Jim_NewIntObj(interp, 0));
7633 break;
7635 case 1:
7636 /* true so do nothing */
7637 break;
7639 case -1:
7640 /* Invalid */
7641 rc = JIM_ERR;
7642 break;
7644 Jim_DecrRefCount(interp, A);
7645 Jim_DecrRefCount(interp, skip);
7647 return rc;
7650 static int JimExprOpColonLeft(Jim_Interp *interp, struct JimExprState *e)
7652 Jim_Obj *skip = ExprPop(e);
7653 Jim_Obj *B = ExprPop(e);
7654 Jim_Obj *A = ExprPop(e);
7656 /* No need to check for A as non-boolean */
7657 if (ExprBool(interp, A)) {
7658 /* true, so skip RHS opcodes */
7659 e->skip = JimWideValue(skip);
7660 /* Repush B as the answer */
7661 ExprPush(e, B);
7664 Jim_DecrRefCount(interp, skip);
7665 Jim_DecrRefCount(interp, A);
7666 Jim_DecrRefCount(interp, B);
7667 return JIM_OK;
7670 static int JimExprOpNull(Jim_Interp *interp, struct JimExprState *e)
7672 return JIM_OK;
7675 enum
7677 LAZY_NONE,
7678 LAZY_OP,
7679 LAZY_LEFT,
7680 LAZY_RIGHT
7683 /* name - precedence - arity - opcode */
7684 static const struct Jim_ExprOperator Jim_ExprOperators[] = {
7685 [JIM_EXPROP_FUNC_INT] = {"int", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7686 [JIM_EXPROP_FUNC_DOUBLE] = {"double", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7687 [JIM_EXPROP_FUNC_ABS] = {"abs", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7688 [JIM_EXPROP_FUNC_ROUND] = {"round", 400, 1, JimExprOpNumUnary, LAZY_NONE},
7689 [JIM_EXPROP_FUNC_RAND] = {"rand", 400, 0, JimExprOpNone, LAZY_NONE},
7690 [JIM_EXPROP_FUNC_SRAND] = {"srand", 400, 1, JimExprOpIntUnary, LAZY_NONE},
7692 #ifdef JIM_MATH_FUNCTIONS
7693 [JIM_EXPROP_FUNC_SIN] = {"sin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7694 [JIM_EXPROP_FUNC_COS] = {"cos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7695 [JIM_EXPROP_FUNC_TAN] = {"tan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7696 [JIM_EXPROP_FUNC_ASIN] = {"asin", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7697 [JIM_EXPROP_FUNC_ACOS] = {"acos", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7698 [JIM_EXPROP_FUNC_ATAN] = {"atan", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7699 [JIM_EXPROP_FUNC_SINH] = {"sinh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7700 [JIM_EXPROP_FUNC_COSH] = {"cosh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7701 [JIM_EXPROP_FUNC_TANH] = {"tanh", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7702 [JIM_EXPROP_FUNC_CEIL] = {"ceil", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7703 [JIM_EXPROP_FUNC_FLOOR] = {"floor", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7704 [JIM_EXPROP_FUNC_EXP] = {"exp", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7705 [JIM_EXPROP_FUNC_LOG] = {"log", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7706 [JIM_EXPROP_FUNC_LOG10] = {"log10", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7707 [JIM_EXPROP_FUNC_SQRT] = {"sqrt", 400, 1, JimExprOpDoubleUnary, LAZY_NONE},
7708 #endif
7710 [JIM_EXPROP_NOT] = {"!", 300, 1, JimExprOpNumUnary, LAZY_NONE},
7711 [JIM_EXPROP_BITNOT] = {"~", 300, 1, JimExprOpIntUnary, LAZY_NONE},
7712 [JIM_EXPROP_UNARYMINUS] = {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7713 [JIM_EXPROP_UNARYPLUS] = {NULL, 300, 1, JimExprOpNumUnary, LAZY_NONE},
7715 [JIM_EXPROP_POW] = {"**", 250, 2, JimExprOpBin, LAZY_NONE},
7717 [JIM_EXPROP_MUL] = {"*", 200, 2, JimExprOpBin, LAZY_NONE},
7718 [JIM_EXPROP_DIV] = {"/", 200, 2, JimExprOpBin, LAZY_NONE},
7719 [JIM_EXPROP_MOD] = {"%", 200, 2, JimExprOpIntBin, LAZY_NONE},
7721 [JIM_EXPROP_SUB] = {"-", 100, 2, JimExprOpBin, LAZY_NONE},
7722 [JIM_EXPROP_ADD] = {"+", 100, 2, JimExprOpBin, LAZY_NONE},
7724 [JIM_EXPROP_ROTL] = {"<<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7725 [JIM_EXPROP_ROTR] = {">>>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7726 [JIM_EXPROP_LSHIFT] = {"<<", 90, 2, JimExprOpIntBin, LAZY_NONE},
7727 [JIM_EXPROP_RSHIFT] = {">>", 90, 2, JimExprOpIntBin, LAZY_NONE},
7729 [JIM_EXPROP_LT] = {"<", 80, 2, JimExprOpBin, LAZY_NONE},
7730 [JIM_EXPROP_GT] = {">", 80, 2, JimExprOpBin, LAZY_NONE},
7731 [JIM_EXPROP_LTE] = {"<=", 80, 2, JimExprOpBin, LAZY_NONE},
7732 [JIM_EXPROP_GTE] = {">=", 80, 2, JimExprOpBin, LAZY_NONE},
7734 [JIM_EXPROP_NUMEQ] = {"==", 70, 2, JimExprOpBin, LAZY_NONE},
7735 [JIM_EXPROP_NUMNE] = {"!=", 70, 2, JimExprOpBin, LAZY_NONE},
7737 [JIM_EXPROP_STREQ] = {"eq", 60, 2, JimExprOpStrBin, LAZY_NONE},
7738 [JIM_EXPROP_STRNE] = {"ne", 60, 2, JimExprOpStrBin, LAZY_NONE},
7740 [JIM_EXPROP_STRIN] = {"in", 55, 2, JimExprOpStrBin, LAZY_NONE},
7741 [JIM_EXPROP_STRNI] = {"ni", 55, 2, JimExprOpStrBin, LAZY_NONE},
7743 [JIM_EXPROP_BITAND] = {"&", 50, 2, JimExprOpIntBin, LAZY_NONE},
7744 [JIM_EXPROP_BITXOR] = {"^", 49, 2, JimExprOpIntBin, LAZY_NONE},
7745 [JIM_EXPROP_BITOR] = {"|", 48, 2, JimExprOpIntBin, LAZY_NONE},
7747 [JIM_EXPROP_LOGICAND] = {"&&", 10, 2, NULL, LAZY_OP},
7748 [JIM_EXPROP_LOGICOR] = {"||", 9, 2, NULL, LAZY_OP},
7750 [JIM_EXPROP_TERNARY] = {"?", 5, 2, JimExprOpNull, LAZY_OP},
7751 [JIM_EXPROP_COLON] = {":", 5, 2, JimExprOpNull, LAZY_OP},
7753 /* private operators */
7754 [JIM_EXPROP_TERNARY_LEFT] = {NULL, 5, 2, JimExprOpTernaryLeft, LAZY_LEFT},
7755 [JIM_EXPROP_TERNARY_RIGHT] = {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7756 [JIM_EXPROP_COLON_LEFT] = {NULL, 5, 2, JimExprOpColonLeft, LAZY_LEFT},
7757 [JIM_EXPROP_COLON_RIGHT] = {NULL, 5, 2, JimExprOpNull, LAZY_RIGHT},
7758 [JIM_EXPROP_LOGICAND_LEFT] = {NULL, 10, 2, JimExprOpAndLeft, LAZY_LEFT},
7759 [JIM_EXPROP_LOGICAND_RIGHT] = {NULL, 10, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7760 [JIM_EXPROP_LOGICOR_LEFT] = {NULL, 9, 2, JimExprOpOrLeft, LAZY_LEFT},
7761 [JIM_EXPROP_LOGICOR_RIGHT] = {NULL, 9, 2, JimExprOpAndOrRight, LAZY_RIGHT},
7764 #define JIM_EXPR_OPERATORS_NUM \
7765 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7767 static int JimParseExpression(struct JimParserCtx *pc)
7769 /* Discard spaces and quoted newline */
7770 while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
7771 if (*pc->p == '\n') {
7772 pc->linenr++;
7774 pc->p++;
7775 pc->len--;
7778 if (pc->len == 0) {
7779 pc->tstart = pc->tend = pc->p;
7780 pc->tline = pc->linenr;
7781 pc->tt = JIM_TT_EOL;
7782 pc->eof = 1;
7783 return JIM_OK;
7785 switch (*(pc->p)) {
7786 case '(':
7787 pc->tstart = pc->tend = pc->p;
7788 pc->tline = pc->linenr;
7789 pc->tt = JIM_TT_SUBEXPR_START;
7790 pc->p++;
7791 pc->len--;
7792 break;
7793 case ')':
7794 pc->tstart = pc->tend = pc->p;
7795 pc->tline = pc->linenr;
7796 pc->tt = JIM_TT_SUBEXPR_END;
7797 pc->p++;
7798 pc->len--;
7799 break;
7800 case '[':
7801 return JimParseCmd(pc);
7802 case '$':
7803 if (JimParseVar(pc) == JIM_ERR)
7804 return JimParseExprOperator(pc);
7805 else {
7806 /* Don't allow expr sugar in expressions */
7807 if (pc->tt == JIM_TT_EXPRSUGAR) {
7808 return JIM_ERR;
7810 return JIM_OK;
7812 break;
7813 case '0':
7814 case '1':
7815 case '2':
7816 case '3':
7817 case '4':
7818 case '5':
7819 case '6':
7820 case '7':
7821 case '8':
7822 case '9':
7823 case '.':
7824 return JimParseExprNumber(pc);
7825 case '"':
7826 return JimParseQuote(pc);
7827 case '{':
7828 return JimParseBrace(pc);
7830 case 'N':
7831 case 'I':
7832 case 'n':
7833 case 'i':
7834 if (JimParseExprIrrational(pc) == JIM_ERR)
7835 return JimParseExprOperator(pc);
7836 break;
7837 default:
7838 return JimParseExprOperator(pc);
7839 break;
7841 return JIM_OK;
7844 static int JimParseExprNumber(struct JimParserCtx *pc)
7846 int allowdot = 1;
7847 int allowhex = 0;
7849 /* Assume an integer for now */
7850 pc->tt = JIM_TT_EXPR_INT;
7851 pc->tstart = pc->p;
7852 pc->tline = pc->linenr;
7853 while (isdigit(UCHAR(*pc->p))
7854 || (allowhex && isxdigit(UCHAR(*pc->p)))
7855 || (allowdot && *pc->p == '.')
7856 || (pc->p - pc->tstart == 1 && *pc->tstart == '0' && (*pc->p == 'x' || *pc->p == 'X'))
7858 if ((*pc->p == 'x') || (*pc->p == 'X')) {
7859 allowhex = 1;
7860 allowdot = 0;
7862 if (*pc->p == '.') {
7863 allowdot = 0;
7864 pc->tt = JIM_TT_EXPR_DOUBLE;
7866 pc->p++;
7867 pc->len--;
7868 if (!allowhex && (*pc->p == 'e' || *pc->p == 'E') && (pc->p[1] == '-' || pc->p[1] == '+'
7869 || isdigit(UCHAR(pc->p[1])))) {
7870 pc->p += 2;
7871 pc->len -= 2;
7872 pc->tt = JIM_TT_EXPR_DOUBLE;
7875 pc->tend = pc->p - 1;
7876 return JIM_OK;
7879 static int JimParseExprIrrational(struct JimParserCtx *pc)
7881 const char *Tokens[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
7882 const char **token;
7884 for (token = Tokens; *token != NULL; token++) {
7885 int len = strlen(*token);
7887 if (strncmp(*token, pc->p, len) == 0) {
7888 pc->tstart = pc->p;
7889 pc->tend = pc->p + len - 1;
7890 pc->p += len;
7891 pc->len -= len;
7892 pc->tline = pc->linenr;
7893 pc->tt = JIM_TT_EXPR_DOUBLE;
7894 return JIM_OK;
7897 return JIM_ERR;
7900 static int JimParseExprOperator(struct JimParserCtx *pc)
7902 int i;
7903 int bestIdx = -1, bestLen = 0;
7905 /* Try to get the longest match. */
7906 for (i = JIM_TT_EXPR_OP; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
7907 const char *opname;
7908 int oplen;
7910 opname = Jim_ExprOperators[i].name;
7911 if (opname == NULL) {
7912 continue;
7914 oplen = strlen(opname);
7916 if (strncmp(opname, pc->p, oplen) == 0 && oplen > bestLen) {
7917 bestIdx = i;
7918 bestLen = oplen;
7921 if (bestIdx == -1) {
7922 return JIM_ERR;
7925 /* Validate paretheses around function arguments */
7926 if (bestIdx >= JIM_EXPROP_FUNC_FIRST) {
7927 const char *p = pc->p + bestLen;
7928 int len = pc->len - bestLen;
7930 while (len && isspace(UCHAR(*p))) {
7931 len--;
7932 p++;
7934 if (*p != '(') {
7935 return JIM_ERR;
7938 pc->tstart = pc->p;
7939 pc->tend = pc->p + bestLen - 1;
7940 pc->p += bestLen;
7941 pc->len -= bestLen;
7942 pc->tline = pc->linenr;
7944 pc->tt = bestIdx;
7945 return JIM_OK;
7948 static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
7950 return &Jim_ExprOperators[opcode];
7953 const char *jim_tt_name(int type)
7955 static const char * const tt_names[JIM_TT_EXPR_OP] =
7956 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", "INT",
7957 "DBL", "$()" };
7958 if (type < JIM_TT_EXPR_OP) {
7959 return tt_names[type];
7961 else {
7962 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(type);
7963 static char buf[20];
7965 if (op && op->name) {
7966 return op->name;
7968 sprintf(buf, "(%d)", type);
7969 return buf;
7973 /* -----------------------------------------------------------------------------
7974 * Expression Object
7975 * ---------------------------------------------------------------------------*/
7976 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
7977 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
7978 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
7980 static const Jim_ObjType exprObjType = {
7981 "expression",
7982 FreeExprInternalRep,
7983 DupExprInternalRep,
7984 NULL,
7985 JIM_TYPE_REFERENCES,
7988 /* Expr bytecode structure */
7989 typedef struct ExprByteCode
7991 int len; /* Length as number of tokens. */
7992 ScriptToken *token; /* Tokens array. */
7993 int inUse; /* Used for sharing. */
7994 } ExprByteCode;
7996 static void ExprFreeByteCode(Jim_Interp *interp, ExprByteCode * expr)
7998 int i;
8000 for (i = 0; i < expr->len; i++) {
8001 Jim_DecrRefCount(interp, expr->token[i].objPtr);
8003 Jim_Free(expr->token);
8004 Jim_Free(expr);
8007 static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8009 ExprByteCode *expr = (void *)objPtr->internalRep.ptr;
8011 if (expr) {
8012 if (--expr->inUse != 0) {
8013 return;
8016 ExprFreeByteCode(interp, expr);
8020 static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8022 JIM_NOTUSED(interp);
8023 JIM_NOTUSED(srcPtr);
8025 /* Just returns an simple string. */
8026 dupPtr->typePtr = NULL;
8029 /* Check if an expr program looks correct. */
8030 static int ExprCheckCorrectness(ExprByteCode * expr)
8032 int i;
8033 int stacklen = 0;
8034 int ternary = 0;
8036 /* Try to check if there are stack underflows,
8037 * and make sure at the end of the program there is
8038 * a single result on the stack. */
8039 for (i = 0; i < expr->len; i++) {
8040 ScriptToken *t = &expr->token[i];
8041 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8043 if (op) {
8044 stacklen -= op->arity;
8045 if (stacklen < 0) {
8046 break;
8048 if (t->type == JIM_EXPROP_TERNARY || t->type == JIM_EXPROP_TERNARY_LEFT) {
8049 ternary++;
8051 else if (t->type == JIM_EXPROP_COLON || t->type == JIM_EXPROP_COLON_LEFT) {
8052 ternary--;
8056 /* All operations and operands add one to the stack */
8057 stacklen++;
8059 if (stacklen != 1 || ternary != 0) {
8060 return JIM_ERR;
8062 return JIM_OK;
8065 /* This procedure converts every occurrence of || and && opereators
8066 * in lazy unary versions.
8068 * a b || is converted into:
8070 * a <offset> |L b |R
8072 * a b && is converted into:
8074 * a <offset> &L b &R
8076 * "|L" checks if 'a' is true:
8077 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8078 * the opcode just after |R.
8079 * 2) if it is false does nothing.
8080 * "|R" checks if 'b' is true:
8081 * 1) if it is true pushes 1, otherwise pushes 0.
8083 * "&L" checks if 'a' is true:
8084 * 1) if it is true does nothing.
8085 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8086 * the opcode just after &R
8087 * "&R" checks if 'a' is true:
8088 * if it is true pushes 1, otherwise pushes 0.
8090 static int ExprAddLazyOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8092 int i;
8094 int leftindex, arity, offset;
8096 /* Search for the end of the first operator */
8097 leftindex = expr->len - 1;
8099 arity = 1;
8100 while (arity) {
8101 ScriptToken *tt = &expr->token[leftindex];
8103 if (tt->type >= JIM_TT_EXPR_OP) {
8104 arity += JimExprOperatorInfoByOpcode(tt->type)->arity;
8106 arity--;
8107 if (--leftindex < 0) {
8108 return JIM_ERR;
8111 leftindex++;
8113 /* Move them up */
8114 memmove(&expr->token[leftindex + 2], &expr->token[leftindex],
8115 sizeof(*expr->token) * (expr->len - leftindex));
8116 expr->len += 2;
8117 offset = (expr->len - leftindex) - 1;
8119 /* Now we rely on the fact the the left and right version have opcodes
8120 * 1 and 2 after the main opcode respectively
8122 expr->token[leftindex + 1].type = t->type + 1;
8123 expr->token[leftindex + 1].objPtr = interp->emptyObj;
8125 expr->token[leftindex].type = JIM_TT_EXPR_INT;
8126 expr->token[leftindex].objPtr = Jim_NewIntObj(interp, offset);
8128 /* Now add the 'R' operator */
8129 expr->token[expr->len].objPtr = interp->emptyObj;
8130 expr->token[expr->len].type = t->type + 2;
8131 expr->len++;
8133 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8134 for (i = leftindex - 1; i > 0; i--) {
8135 if (JimExprOperatorInfoByOpcode(expr->token[i].type)->lazy == LAZY_LEFT) {
8136 if (JimWideValue(expr->token[i - 1].objPtr) + i - 1 >= leftindex) {
8137 JimWideValue(expr->token[i - 1].objPtr) += 2;
8141 return JIM_OK;
8144 static int ExprAddOperator(Jim_Interp *interp, ExprByteCode * expr, ParseToken *t)
8146 struct ScriptToken *token = &expr->token[expr->len];
8147 const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(t->type);
8149 if (op->lazy == LAZY_OP) {
8150 if (ExprAddLazyOperator(interp, expr, t) != JIM_OK) {
8151 Jim_SetResultFormatted(interp, "Expression has bad operands to %s", op->name);
8152 return JIM_ERR;
8155 else {
8156 token->objPtr = interp->emptyObj;
8157 token->type = t->type;
8158 expr->len++;
8160 return JIM_OK;
8164 * Returns the index of the COLON_LEFT to the left of 'right_index'
8165 * taking into account nesting.
8167 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8169 static int ExprTernaryGetColonLeftIndex(ExprByteCode *expr, int right_index)
8171 int ternary_count = 1;
8173 right_index--;
8175 while (right_index > 1) {
8176 if (expr->token[right_index].type == JIM_EXPROP_TERNARY_LEFT) {
8177 ternary_count--;
8179 else if (expr->token[right_index].type == JIM_EXPROP_COLON_RIGHT) {
8180 ternary_count++;
8182 else if (expr->token[right_index].type == JIM_EXPROP_COLON_LEFT && ternary_count == 1) {
8183 return right_index;
8185 right_index--;
8188 /*notreached*/
8189 return -1;
8193 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8195 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8196 * Otherwise returns 0.
8198 static int ExprTernaryGetMoveIndices(ExprByteCode *expr, int right_index, int *prev_right_index, int *prev_left_index)
8200 int i = right_index - 1;
8201 int ternary_count = 1;
8203 while (i > 1) {
8204 if (expr->token[i].type == JIM_EXPROP_TERNARY_LEFT) {
8205 if (--ternary_count == 0 && expr->token[i - 2].type == JIM_EXPROP_COLON_RIGHT) {
8206 *prev_right_index = i - 2;
8207 *prev_left_index = ExprTernaryGetColonLeftIndex(expr, *prev_right_index);
8208 return 1;
8211 else if (expr->token[i].type == JIM_EXPROP_COLON_RIGHT) {
8212 if (ternary_count == 0) {
8213 return 0;
8215 ternary_count++;
8217 i--;
8219 return 0;
8223 * ExprTernaryReorderExpression description
8224 * ========================================
8226 * ?: is right-to-left associative which doesn't work with the stack-based
8227 * expression engine. The fix is to reorder the bytecode.
8229 * The expression:
8231 * expr 1?2:0?3:4
8233 * Has initial bytecode:
8235 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8236 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8238 * The fix involves simulating this expression instead:
8240 * expr 1?2:(0?3:4)
8242 * With the following bytecode:
8244 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8245 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8247 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8248 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8249 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8250 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8252 * ExprTernaryReorderExpression works thus as follows :
8253 * - start from the end of the stack
8254 * - while walking towards the beginning of the stack
8255 * if token=JIM_EXPROP_COLON_RIGHT then
8256 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8257 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8258 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8259 * if all found then
8260 * perform the rotation
8261 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8262 * end if
8263 * end if
8265 * Note: care has to be taken for nested ternary constructs!!!
8267 static void ExprTernaryReorderExpression(Jim_Interp *interp, ExprByteCode *expr)
8269 int i;
8271 for (i = expr->len - 1; i > 1; i--) {
8272 int prev_right_index;
8273 int prev_left_index;
8274 int j;
8275 ScriptToken tmp;
8277 if (expr->token[i].type != JIM_EXPROP_COLON_RIGHT) {
8278 continue;
8281 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8282 if (ExprTernaryGetMoveIndices(expr, i, &prev_right_index, &prev_left_index) == 0) {
8283 continue;
8287 ** rotate tokens down
8289 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8290 ** | | |
8291 ** | V V
8292 ** | [...] : ...
8293 ** | | |
8294 ** | V V
8295 ** | [...] : ...
8296 ** | | |
8297 ** | V V
8298 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8300 tmp = expr->token[prev_right_index];
8301 for (j = prev_right_index; j < i; j++) {
8302 expr->token[j] = expr->token[j + 1];
8304 expr->token[i] = tmp;
8306 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8308 * This is 'colon left increment' = i - prev_right_index
8310 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8311 * [prev_left_index-1] : skip_count
8314 JimWideValue(expr->token[prev_left_index-1].objPtr) += (i - prev_right_index);
8316 /* Adjust for i-- in the loop */
8317 i++;
8321 static ExprByteCode *ExprCreateByteCode(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *fileNameObj)
8323 Jim_Stack stack;
8324 ExprByteCode *expr;
8325 int ok = 1;
8326 int i;
8327 int prevtt = JIM_TT_NONE;
8328 int have_ternary = 0;
8330 /* -1 for EOL */
8331 int count = tokenlist->count - 1;
8333 expr = Jim_Alloc(sizeof(*expr));
8334 expr->inUse = 1;
8335 expr->len = 0;
8337 Jim_InitStack(&stack);
8339 /* Need extra bytecodes for lazy operators.
8340 * Also check for the ternary operator
8342 for (i = 0; i < tokenlist->count; i++) {
8343 ParseToken *t = &tokenlist->list[i];
8345 if (JimExprOperatorInfoByOpcode(t->type)->lazy == LAZY_OP) {
8346 count += 2;
8347 /* Ternary is a lazy op but also needs reordering */
8348 if (t->type == JIM_EXPROP_TERNARY) {
8349 have_ternary = 1;
8354 expr->token = Jim_Alloc(sizeof(ScriptToken) * count);
8356 for (i = 0; i < tokenlist->count && ok; i++) {
8357 ParseToken *t = &tokenlist->list[i];
8359 /* Next token will be stored here */
8360 struct ScriptToken *token = &expr->token[expr->len];
8362 if (t->type == JIM_TT_EOL) {
8363 break;
8366 switch (t->type) {
8367 case JIM_TT_STR:
8368 case JIM_TT_ESC:
8369 case JIM_TT_VAR:
8370 case JIM_TT_DICTSUGAR:
8371 case JIM_TT_EXPRSUGAR:
8372 case JIM_TT_CMD:
8373 token->objPtr = Jim_NewStringObj(interp, t->token, t->len);
8374 token->type = t->type;
8375 if (t->type == JIM_TT_CMD) {
8376 /* Only commands need source info */
8377 JimSetSourceInfo(interp, token->objPtr, fileNameObj, t->line);
8379 expr->len++;
8380 break;
8382 case JIM_TT_EXPR_INT:
8383 token->objPtr = Jim_NewIntObj(interp, strtoull(t->token, NULL, 0));
8384 token->type = t->type;
8385 expr->len++;
8386 break;
8388 case JIM_TT_EXPR_DOUBLE:
8389 token->objPtr = Jim_NewDoubleObj(interp, strtod(t->token, NULL));
8390 token->type = t->type;
8391 expr->len++;
8392 break;
8394 case JIM_TT_SUBEXPR_START:
8395 Jim_StackPush(&stack, t);
8396 prevtt = JIM_TT_NONE;
8397 continue;
8399 case JIM_TT_SUBEXPR_END:
8400 ok = 0;
8401 while (Jim_StackLen(&stack)) {
8402 ParseToken *tt = Jim_StackPop(&stack);
8404 if (tt->type == JIM_TT_SUBEXPR_START) {
8405 ok = 1;
8406 break;
8409 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8410 goto err;
8413 if (!ok) {
8414 Jim_SetResultString(interp, "Unexpected close parenthesis", -1);
8415 goto err;
8417 break;
8420 default:{
8421 /* Must be an operator */
8422 const struct Jim_ExprOperator *op;
8423 ParseToken *tt;
8425 /* Convert -/+ to unary minus or unary plus if necessary */
8426 if (prevtt == JIM_TT_NONE || prevtt >= JIM_TT_EXPR_OP) {
8427 if (t->type == JIM_EXPROP_SUB) {
8428 t->type = JIM_EXPROP_UNARYMINUS;
8430 else if (t->type == JIM_EXPROP_ADD) {
8431 t->type = JIM_EXPROP_UNARYPLUS;
8435 op = JimExprOperatorInfoByOpcode(t->type);
8437 /* Now handle precedence */
8438 while ((tt = Jim_StackPeek(&stack)) != NULL) {
8439 const struct Jim_ExprOperator *tt_op =
8440 JimExprOperatorInfoByOpcode(tt->type);
8442 /* Note that right-to-left associativity of ?: operator is handled later */
8444 if (op->arity != 1 && tt_op->precedence >= op->precedence) {
8445 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8446 ok = 0;
8447 goto err;
8449 Jim_StackPop(&stack);
8451 else {
8452 break;
8455 Jim_StackPush(&stack, t);
8456 break;
8459 prevtt = t->type;
8462 /* Reduce any remaining subexpr */
8463 while (Jim_StackLen(&stack)) {
8464 ParseToken *tt = Jim_StackPop(&stack);
8466 if (tt->type == JIM_TT_SUBEXPR_START) {
8467 ok = 0;
8468 Jim_SetResultString(interp, "Missing close parenthesis", -1);
8469 goto err;
8471 if (ExprAddOperator(interp, expr, tt) != JIM_OK) {
8472 ok = 0;
8473 goto err;
8477 if (have_ternary) {
8478 ExprTernaryReorderExpression(interp, expr);
8481 err:
8482 /* Free the stack used for the compilation. */
8483 Jim_FreeStack(&stack);
8485 for (i = 0; i < expr->len; i++) {
8486 Jim_IncrRefCount(expr->token[i].objPtr);
8489 if (!ok) {
8490 ExprFreeByteCode(interp, expr);
8491 return NULL;
8494 return expr;
8498 /* This method takes the string representation of an expression
8499 * and generates a program for the Expr's stack-based VM. */
8500 static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
8502 int exprTextLen;
8503 const char *exprText;
8504 struct JimParserCtx parser;
8505 struct ExprByteCode *expr;
8506 ParseTokenList tokenlist;
8507 int line;
8508 Jim_Obj *fileNameObj;
8509 int rc = JIM_ERR;
8511 /* Try to get information about filename / line number */
8512 if (objPtr->typePtr == &sourceObjType) {
8513 fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
8514 line = objPtr->internalRep.sourceValue.lineNumber;
8516 else {
8517 fileNameObj = interp->emptyObj;
8518 line = 1;
8520 Jim_IncrRefCount(fileNameObj);
8522 exprText = Jim_GetString(objPtr, &exprTextLen);
8524 /* Initially tokenise the expression into tokenlist */
8525 ScriptTokenListInit(&tokenlist);
8527 JimParserInit(&parser, exprText, exprTextLen, line);
8528 while (!parser.eof) {
8529 if (JimParseExpression(&parser) != JIM_OK) {
8530 ScriptTokenListFree(&tokenlist);
8531 invalidexpr:
8532 Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
8533 expr = NULL;
8534 goto err;
8537 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
8538 parser.tline);
8541 #ifdef DEBUG_SHOW_EXPR_TOKENS
8543 int i;
8544 printf("==== Expr Tokens ====\n");
8545 for (i = 0; i < tokenlist.count; i++) {
8546 printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
8547 tokenlist.list[i].len, tokenlist.list[i].token);
8550 #endif
8552 /* Now create the expression bytecode from the tokenlist */
8553 expr = ExprCreateByteCode(interp, &tokenlist, fileNameObj);
8555 /* No longer need the token list */
8556 ScriptTokenListFree(&tokenlist);
8558 if (!expr) {
8559 goto err;
8562 #ifdef DEBUG_SHOW_EXPR
8564 int i;
8566 printf("==== Expr ====\n");
8567 for (i = 0; i < expr->len; i++) {
8568 ScriptToken *t = &expr->token[i];
8570 printf("[%2d] %s '%s'\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
8573 #endif
8575 /* Check program correctness. */
8576 if (ExprCheckCorrectness(expr) != JIM_OK) {
8577 ExprFreeByteCode(interp, expr);
8578 goto invalidexpr;
8581 rc = JIM_OK;
8583 err:
8584 /* Free the old internal rep and set the new one. */
8585 Jim_DecrRefCount(interp, fileNameObj);
8586 Jim_FreeIntRep(interp, objPtr);
8587 Jim_SetIntRepPtr(objPtr, expr);
8588 objPtr->typePtr = &exprObjType;
8589 return rc;
8592 static ExprByteCode *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
8594 if (objPtr->typePtr != &exprObjType) {
8595 if (SetExprFromAny(interp, objPtr) != JIM_OK) {
8596 return NULL;
8599 return (ExprByteCode *) Jim_GetIntRepPtr(objPtr);
8602 /* -----------------------------------------------------------------------------
8603 * Expressions evaluation.
8604 * Jim uses a specialized stack-based virtual machine for expressions,
8605 * that takes advantage of the fact that expr's operators
8606 * can't be redefined.
8608 * Jim_EvalExpression() uses the bytecode compiled by
8609 * SetExprFromAny() method of the "expression" object.
8611 * On success a Tcl Object containing the result of the evaluation
8612 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8613 * returned.
8614 * On error the function returns a retcode != to JIM_OK and set a suitable
8615 * error on the interp.
8616 * ---------------------------------------------------------------------------*/
8617 #define JIM_EE_STATICSTACK_LEN 10
8619 int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr, Jim_Obj **exprResultPtrPtr)
8621 ExprByteCode *expr;
8622 Jim_Obj *staticStack[JIM_EE_STATICSTACK_LEN];
8623 int i;
8624 int retcode = JIM_OK;
8625 struct JimExprState e;
8627 expr = JimGetExpression(interp, exprObjPtr);
8628 if (!expr) {
8629 return JIM_ERR; /* error in expression. */
8632 #ifdef JIM_OPTIMIZATION
8633 /* Check for one of the following common expressions used by while/for
8635 * CONST
8636 * $a
8637 * !$a
8638 * $a < CONST, $a < $b
8639 * $a <= CONST, $a <= $b
8640 * $a > CONST, $a > $b
8641 * $a >= CONST, $a >= $b
8642 * $a != CONST, $a != $b
8643 * $a == CONST, $a == $b
8646 Jim_Obj *objPtr;
8648 /* STEP 1 -- Check if there are the conditions to run the specialized
8649 * version of while */
8651 switch (expr->len) {
8652 case 1:
8653 if (expr->token[0].type == JIM_TT_EXPR_INT) {
8654 *exprResultPtrPtr = expr->token[0].objPtr;
8655 Jim_IncrRefCount(*exprResultPtrPtr);
8656 return JIM_OK;
8658 if (expr->token[0].type == JIM_TT_VAR) {
8659 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_ERRMSG);
8660 if (objPtr) {
8661 *exprResultPtrPtr = objPtr;
8662 Jim_IncrRefCount(*exprResultPtrPtr);
8663 return JIM_OK;
8666 break;
8668 case 2:
8669 if (expr->token[1].type == JIM_EXPROP_NOT && expr->token[0].type == JIM_TT_VAR) {
8670 jim_wide wideValue;
8672 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8673 if (objPtr && JimIsWide(objPtr)
8674 && Jim_GetWide(interp, objPtr, &wideValue) == JIM_OK) {
8675 *exprResultPtrPtr = wideValue ? interp->falseObj : interp->trueObj;
8676 Jim_IncrRefCount(*exprResultPtrPtr);
8677 return JIM_OK;
8680 break;
8682 case 3:
8683 if (expr->token[0].type == JIM_TT_VAR && (expr->token[1].type == JIM_TT_EXPR_INT
8684 || expr->token[1].type == JIM_TT_VAR)) {
8685 switch (expr->token[2].type) {
8686 case JIM_EXPROP_LT:
8687 case JIM_EXPROP_LTE:
8688 case JIM_EXPROP_GT:
8689 case JIM_EXPROP_GTE:
8690 case JIM_EXPROP_NUMEQ:
8691 case JIM_EXPROP_NUMNE:{
8692 /* optimise ok */
8693 jim_wide wideValueA;
8694 jim_wide wideValueB;
8696 objPtr = Jim_GetVariable(interp, expr->token[0].objPtr, JIM_NONE);
8697 if (objPtr && JimIsWide(objPtr)
8698 && Jim_GetWide(interp, objPtr, &wideValueA) == JIM_OK) {
8699 if (expr->token[1].type == JIM_TT_VAR) {
8700 objPtr =
8701 Jim_GetVariable(interp, expr->token[1].objPtr,
8702 JIM_NONE);
8704 else {
8705 objPtr = expr->token[1].objPtr;
8707 if (objPtr && JimIsWide(objPtr)
8708 && Jim_GetWide(interp, objPtr, &wideValueB) == JIM_OK) {
8709 int cmpRes;
8711 switch (expr->token[2].type) {
8712 case JIM_EXPROP_LT:
8713 cmpRes = wideValueA < wideValueB;
8714 break;
8715 case JIM_EXPROP_LTE:
8716 cmpRes = wideValueA <= wideValueB;
8717 break;
8718 case JIM_EXPROP_GT:
8719 cmpRes = wideValueA > wideValueB;
8720 break;
8721 case JIM_EXPROP_GTE:
8722 cmpRes = wideValueA >= wideValueB;
8723 break;
8724 case JIM_EXPROP_NUMEQ:
8725 cmpRes = wideValueA == wideValueB;
8726 break;
8727 case JIM_EXPROP_NUMNE:
8728 cmpRes = wideValueA != wideValueB;
8729 break;
8730 default: /*notreached */
8731 cmpRes = 0;
8733 *exprResultPtrPtr =
8734 cmpRes ? interp->trueObj : interp->falseObj;
8735 Jim_IncrRefCount(*exprResultPtrPtr);
8736 return JIM_OK;
8742 break;
8745 #endif
8747 /* In order to avoid that the internal repr gets freed due to
8748 * shimmering of the exprObjPtr's object, we make the internal rep
8749 * shared. */
8750 expr->inUse++;
8752 /* The stack-based expr VM itself */
8754 /* Stack allocation. Expr programs have the feature that
8755 * a program of length N can't require a stack longer than
8756 * N. */
8757 if (expr->len > JIM_EE_STATICSTACK_LEN)
8758 e.stack = Jim_Alloc(sizeof(Jim_Obj *) * expr->len);
8759 else
8760 e.stack = staticStack;
8762 e.stacklen = 0;
8764 /* Execute every instruction */
8765 for (i = 0; i < expr->len && retcode == JIM_OK; i++) {
8766 Jim_Obj *objPtr;
8768 switch (expr->token[i].type) {
8769 case JIM_TT_EXPR_INT:
8770 case JIM_TT_EXPR_DOUBLE:
8771 case JIM_TT_STR:
8772 ExprPush(&e, expr->token[i].objPtr);
8773 break;
8775 case JIM_TT_VAR:
8776 objPtr = Jim_GetVariable(interp, expr->token[i].objPtr, JIM_ERRMSG);
8777 if (objPtr) {
8778 ExprPush(&e, objPtr);
8780 else {
8781 retcode = JIM_ERR;
8783 break;
8785 case JIM_TT_DICTSUGAR:
8786 objPtr = JimExpandDictSugar(interp, expr->token[i].objPtr);
8787 if (objPtr) {
8788 ExprPush(&e, objPtr);
8790 else {
8791 retcode = JIM_ERR;
8793 break;
8795 case JIM_TT_ESC:
8796 retcode = Jim_SubstObj(interp, expr->token[i].objPtr, &objPtr, JIM_NONE);
8797 if (retcode == JIM_OK) {
8798 ExprPush(&e, objPtr);
8800 break;
8802 case JIM_TT_CMD:
8803 retcode = Jim_EvalObj(interp, expr->token[i].objPtr);
8804 if (retcode == JIM_OK) {
8805 ExprPush(&e, Jim_GetResult(interp));
8807 break;
8809 default:{
8810 /* Find and execute the operation */
8811 e.skip = 0;
8812 e.opcode = expr->token[i].type;
8814 retcode = JimExprOperatorInfoByOpcode(e.opcode)->funcop(interp, &e);
8815 /* Skip some opcodes if necessary */
8816 i += e.skip;
8817 continue;
8822 expr->inUse--;
8824 if (retcode == JIM_OK) {
8825 *exprResultPtrPtr = ExprPop(&e);
8827 else {
8828 for (i = 0; i < e.stacklen; i++) {
8829 Jim_DecrRefCount(interp, e.stack[i]);
8832 if (e.stack != staticStack) {
8833 Jim_Free(e.stack);
8835 return retcode;
8838 int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
8840 int retcode;
8841 jim_wide wideValue;
8842 double doubleValue;
8843 Jim_Obj *exprResultPtr;
8845 retcode = Jim_EvalExpression(interp, exprObjPtr, &exprResultPtr);
8846 if (retcode != JIM_OK)
8847 return retcode;
8849 if (JimGetWideNoErr(interp, exprResultPtr, &wideValue) != JIM_OK) {
8850 if (Jim_GetDouble(interp, exprResultPtr, &doubleValue) != JIM_OK) {
8851 Jim_DecrRefCount(interp, exprResultPtr);
8852 return JIM_ERR;
8854 else {
8855 Jim_DecrRefCount(interp, exprResultPtr);
8856 *boolPtr = doubleValue != 0;
8857 return JIM_OK;
8860 *boolPtr = wideValue != 0;
8862 Jim_DecrRefCount(interp, exprResultPtr);
8863 return JIM_OK;
8866 /* -----------------------------------------------------------------------------
8867 * ScanFormat String Object
8868 * ---------------------------------------------------------------------------*/
8870 /* This Jim_Obj will held a parsed representation of a format string passed to
8871 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8872 * to be parsed in its entirely first and then, if correct, can be used for
8873 * scanning. To avoid endless re-parsing, the parsed representation will be
8874 * stored in an internal representation and re-used for performance reason. */
8876 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8877 * scanformat string. This part will later be used to extract information
8878 * out from the string to be parsed by Jim_ScanString */
8880 typedef struct ScanFmtPartDescr
8882 char type; /* Type of conversion (e.g. c, d, f) */
8883 char modifier; /* Modify type (e.g. l - long, h - short */
8884 size_t width; /* Maximal width of input to be converted */
8885 int pos; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8886 char *arg; /* Specification of a CHARSET conversion */
8887 char *prefix; /* Prefix to be scanned literally before conversion */
8888 } ScanFmtPartDescr;
8890 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8891 * string parsed and separated in part descriptions. Furthermore it contains
8892 * the original string representation of the scanformat string to allow for
8893 * fast update of the Jim_Obj's string representation part.
8895 * As an add-on the internal object representation adds some scratch pad area
8896 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8897 * memory for purpose of string scanning.
8899 * The error member points to a static allocated string in case of a mal-
8900 * formed scanformat string or it contains '0' (NULL) in case of a valid
8901 * parse representation.
8903 * The whole memory of the internal representation is allocated as a single
8904 * area of memory that will be internally separated. So freeing and duplicating
8905 * of such an object is cheap */
8907 typedef struct ScanFmtStringObj
8909 jim_wide size; /* Size of internal repr in bytes */
8910 char *stringRep; /* Original string representation */
8911 size_t count; /* Number of ScanFmtPartDescr contained */
8912 size_t convCount; /* Number of conversions that will assign */
8913 size_t maxPos; /* Max position index if XPG3 is used */
8914 const char *error; /* Ptr to error text (NULL if no error */
8915 char *scratch; /* Some scratch pad used by Jim_ScanString */
8916 ScanFmtPartDescr descr[1]; /* The vector of partial descriptions */
8917 } ScanFmtStringObj;
8920 static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
8921 static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
8922 static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
8924 static const Jim_ObjType scanFmtStringObjType = {
8925 "scanformatstring",
8926 FreeScanFmtInternalRep,
8927 DupScanFmtInternalRep,
8928 UpdateStringOfScanFmt,
8929 JIM_TYPE_NONE,
8932 void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
8934 JIM_NOTUSED(interp);
8935 Jim_Free((char *)objPtr->internalRep.ptr);
8936 objPtr->internalRep.ptr = 0;
8939 void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
8941 size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
8942 ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
8944 JIM_NOTUSED(interp);
8945 memcpy(newVec, srcPtr->internalRep.ptr, size);
8946 dupPtr->internalRep.ptr = newVec;
8947 dupPtr->typePtr = &scanFmtStringObjType;
8950 void UpdateStringOfScanFmt(Jim_Obj *objPtr)
8952 char *bytes = ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep;
8954 objPtr->bytes = Jim_StrDup(bytes);
8955 objPtr->length = strlen(bytes);
8958 /* SetScanFmtFromAny will parse a given string and create the internal
8959 * representation of the format specification. In case of an error
8960 * the error data member of the internal representation will be set
8961 * to an descriptive error text and the function will be left with
8962 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
8963 * specification */
8965 static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
8967 ScanFmtStringObj *fmtObj;
8968 char *buffer;
8969 int maxCount, i, approxSize, lastPos = -1;
8970 const char *fmt = objPtr->bytes;
8971 int maxFmtLen = objPtr->length;
8972 const char *fmtEnd = fmt + maxFmtLen;
8973 int curr;
8975 Jim_FreeIntRep(interp, objPtr);
8976 /* Count how many conversions could take place maximally */
8977 for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
8978 if (fmt[i] == '%')
8979 ++maxCount;
8980 /* Calculate an approximation of the memory necessary */
8981 approxSize = sizeof(ScanFmtStringObj) /* Size of the container */
8982 +(maxCount + 1) * sizeof(ScanFmtPartDescr) /* Size of all partials */
8983 +maxFmtLen * sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
8984 + maxFmtLen * sizeof(char) + 1 /* Original stringrep */
8985 + maxFmtLen * sizeof(char) /* Arg for CHARSETs */
8986 +(maxCount + 1) * sizeof(char) /* '\0' for every partial */
8987 +1; /* safety byte */
8988 fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
8989 memset(fmtObj, 0, approxSize);
8990 fmtObj->size = approxSize;
8991 fmtObj->maxPos = 0;
8992 fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
8993 fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
8994 memcpy(fmtObj->stringRep, fmt, maxFmtLen);
8995 buffer = fmtObj->stringRep + maxFmtLen + 1;
8996 objPtr->internalRep.ptr = fmtObj;
8997 objPtr->typePtr = &scanFmtStringObjType;
8998 for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
8999 int width = 0, skip;
9000 ScanFmtPartDescr *descr = &fmtObj->descr[curr];
9002 fmtObj->count++;
9003 descr->width = 0; /* Assume width unspecified */
9004 /* Overread and store any "literal" prefix */
9005 if (*fmt != '%' || fmt[1] == '%') {
9006 descr->type = 0;
9007 descr->prefix = &buffer[i];
9008 for (; fmt < fmtEnd; ++fmt) {
9009 if (*fmt == '%') {
9010 if (fmt[1] != '%')
9011 break;
9012 ++fmt;
9014 buffer[i++] = *fmt;
9016 buffer[i++] = 0;
9018 /* Skip the conversion introducing '%' sign */
9019 ++fmt;
9020 /* End reached due to non-conversion literal only? */
9021 if (fmt >= fmtEnd)
9022 goto done;
9023 descr->pos = 0; /* Assume "natural" positioning */
9024 if (*fmt == '*') {
9025 descr->pos = -1; /* Okay, conversion will not be assigned */
9026 ++fmt;
9028 else
9029 fmtObj->convCount++; /* Otherwise count as assign-conversion */
9030 /* Check if next token is a number (could be width or pos */
9031 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9032 fmt += skip;
9033 /* Was the number a XPG3 position specifier? */
9034 if (descr->pos != -1 && *fmt == '$') {
9035 int prev;
9037 ++fmt;
9038 descr->pos = width;
9039 width = 0;
9040 /* Look if "natural" postioning and XPG3 one was mixed */
9041 if ((lastPos == 0 && descr->pos > 0)
9042 || (lastPos > 0 && descr->pos == 0)) {
9043 fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
9044 return JIM_ERR;
9046 /* Look if this position was already used */
9047 for (prev = 0; prev < curr; ++prev) {
9048 if (fmtObj->descr[prev].pos == -1)
9049 continue;
9050 if (fmtObj->descr[prev].pos == descr->pos) {
9051 fmtObj->error =
9052 "variable is assigned by multiple \"%n$\" conversion specifiers";
9053 return JIM_ERR;
9056 /* Try to find a width after the XPG3 specifier */
9057 if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
9058 descr->width = width;
9059 fmt += skip;
9061 if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
9062 fmtObj->maxPos = descr->pos;
9064 else {
9065 /* Number was not a XPG3, so it has to be a width */
9066 descr->width = width;
9069 /* If positioning mode was undetermined yet, fix this */
9070 if (lastPos == -1)
9071 lastPos = descr->pos;
9072 /* Handle CHARSET conversion type ... */
9073 if (*fmt == '[') {
9074 int swapped = 1, beg = i, end, j;
9076 descr->type = '[';
9077 descr->arg = &buffer[i];
9078 ++fmt;
9079 if (*fmt == '^')
9080 buffer[i++] = *fmt++;
9081 if (*fmt == ']')
9082 buffer[i++] = *fmt++;
9083 while (*fmt && *fmt != ']')
9084 buffer[i++] = *fmt++;
9085 if (*fmt != ']') {
9086 fmtObj->error = "unmatched [ in format string";
9087 return JIM_ERR;
9089 end = i;
9090 buffer[i++] = 0;
9091 /* In case a range fence was given "backwards", swap it */
9092 while (swapped) {
9093 swapped = 0;
9094 for (j = beg + 1; j < end - 1; ++j) {
9095 if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
9096 char tmp = buffer[j - 1];
9098 buffer[j - 1] = buffer[j + 1];
9099 buffer[j + 1] = tmp;
9100 swapped = 1;
9105 else {
9106 /* Remember any valid modifier if given */
9107 if (strchr("hlL", *fmt) != 0)
9108 descr->modifier = tolower((int)*fmt++);
9110 descr->type = *fmt;
9111 if (strchr("efgcsndoxui", *fmt) == 0) {
9112 fmtObj->error = "bad scan conversion character";
9113 return JIM_ERR;
9115 else if (*fmt == 'c' && descr->width != 0) {
9116 fmtObj->error = "field width may not be specified in %c " "conversion";
9117 return JIM_ERR;
9119 else if (*fmt == 'u' && descr->modifier == 'l') {
9120 fmtObj->error = "unsigned wide not supported";
9121 return JIM_ERR;
9124 curr++;
9126 done:
9127 return JIM_OK;
9130 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9132 #define FormatGetCnvCount(_fo_) \
9133 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9134 #define FormatGetMaxPos(_fo_) \
9135 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9136 #define FormatGetError(_fo_) \
9137 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9139 /* JimScanAString is used to scan an unspecified string that ends with
9140 * next WS, or a string that is specified via a charset.
9143 static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
9145 char *buffer = Jim_StrDup(str);
9146 char *p = buffer;
9148 while (*str) {
9149 int c;
9150 int n;
9152 if (!sdescr && isspace(UCHAR(*str)))
9153 break; /* EOS via WS if unspecified */
9155 n = utf8_tounicode(str, &c);
9156 if (sdescr && !JimCharsetMatch(sdescr, c, JIM_CHARSET_SCAN))
9157 break;
9158 while (n--)
9159 *p++ = *str++;
9161 *p = 0;
9162 return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
9165 /* ScanOneEntry will scan one entry out of the string passed as argument.
9166 * It use the sscanf() function for this task. After extracting and
9167 * converting of the value, the count of scanned characters will be
9168 * returned of -1 in case of no conversion tool place and string was
9169 * already scanned thru */
9171 static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int strLen,
9172 ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
9174 const char *tok;
9175 const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
9176 size_t scanned = 0;
9177 size_t anchor = pos;
9178 int i;
9179 Jim_Obj *tmpObj = NULL;
9181 /* First pessimistically assume, we will not scan anything :-) */
9182 *valObjPtr = 0;
9183 if (descr->prefix) {
9184 /* There was a prefix given before the conversion, skip it and adjust
9185 * the string-to-be-parsed accordingly */
9186 /* XXX: Should be checking strLen, not str[pos] */
9187 for (i = 0; pos < strLen && descr->prefix[i]; ++i) {
9188 /* If prefix require, skip WS */
9189 if (isspace(UCHAR(descr->prefix[i])))
9190 while (pos < strLen && isspace(UCHAR(str[pos])))
9191 ++pos;
9192 else if (descr->prefix[i] != str[pos])
9193 break; /* Prefix do not match here, leave the loop */
9194 else
9195 ++pos; /* Prefix matched so far, next round */
9197 if (pos >= strLen) {
9198 return -1; /* All of str consumed: EOF condition */
9200 else if (descr->prefix[i] != 0)
9201 return 0; /* Not whole prefix consumed, no conversion possible */
9203 /* For all but following conversion, skip leading WS */
9204 if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
9205 while (isspace(UCHAR(str[pos])))
9206 ++pos;
9207 /* Determine how much skipped/scanned so far */
9208 scanned = pos - anchor;
9210 /* %c is a special, simple case. no width */
9211 if (descr->type == 'n') {
9212 /* Return pseudo conversion means: how much scanned so far? */
9213 *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
9215 else if (pos >= strLen) {
9216 /* Cannot scan anything, as str is totally consumed */
9217 return -1;
9219 else if (descr->type == 'c') {
9220 int c;
9221 scanned += utf8_tounicode(&str[pos], &c);
9222 *valObjPtr = Jim_NewIntObj(interp, c);
9223 return scanned;
9225 else {
9226 /* Processing of conversions follows ... */
9227 if (descr->width > 0) {
9228 /* Do not try to scan as fas as possible but only the given width.
9229 * To ensure this, we copy the part that should be scanned. */
9230 size_t sLen = utf8_strlen(&str[pos], strLen - pos);
9231 size_t tLen = descr->width > sLen ? sLen : descr->width;
9233 tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
9234 tok = tmpObj->bytes;
9236 else {
9237 /* As no width was given, simply refer to the original string */
9238 tok = &str[pos];
9240 switch (descr->type) {
9241 case 'd':
9242 case 'o':
9243 case 'x':
9244 case 'u':
9245 case 'i':{
9246 char *endp; /* Position where the number finished */
9247 jim_wide w;
9249 int base = descr->type == 'o' ? 8
9250 : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
9252 /* Try to scan a number with the given base */
9253 w = strtoull(tok, &endp, base);
9254 if (endp == tok && base == 0) {
9255 /* If scanning failed, and base was undetermined, simply
9256 * put it to 10 and try once more. This should catch the
9257 * case where %i begin to parse a number prefix (e.g.
9258 * '0x' but no further digits follows. This will be
9259 * handled as a ZERO followed by a char 'x' by Tcl */
9260 w = strtoull(tok, &endp, 10);
9263 if (endp != tok) {
9264 /* There was some number sucessfully scanned! */
9265 *valObjPtr = Jim_NewIntObj(interp, w);
9267 /* Adjust the number-of-chars scanned so far */
9268 scanned += endp - tok;
9270 else {
9271 /* Nothing was scanned. We have to determine if this
9272 * happened due to e.g. prefix mismatch or input str
9273 * exhausted */
9274 scanned = *tok ? 0 : -1;
9276 break;
9278 case 's':
9279 case '[':{
9280 *valObjPtr = JimScanAString(interp, descr->arg, tok);
9281 scanned += Jim_Length(*valObjPtr);
9282 break;
9284 case 'e':
9285 case 'f':
9286 case 'g':{
9287 char *endp;
9288 double value = strtod(tok, &endp);
9290 if (endp != tok) {
9291 /* There was some number sucessfully scanned! */
9292 *valObjPtr = Jim_NewDoubleObj(interp, value);
9293 /* Adjust the number-of-chars scanned so far */
9294 scanned += endp - tok;
9296 else {
9297 /* Nothing was scanned. We have to determine if this
9298 * happened due to e.g. prefix mismatch or input str
9299 * exhausted */
9300 scanned = *tok ? 0 : -1;
9302 break;
9305 /* If a substring was allocated (due to pre-defined width) do not
9306 * forget to free it */
9307 if (tmpObj) {
9308 Jim_FreeNewObj(interp, tmpObj);
9311 return scanned;
9314 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9315 * string and returns all converted (and not ignored) values in a list back
9316 * to the caller. If an error occured, a NULL pointer will be returned */
9318 Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
9320 size_t i, pos;
9321 int scanned = 1;
9322 const char *str = Jim_String(strObjPtr);
9323 int strLen = Jim_Utf8Length(interp, strObjPtr);
9324 Jim_Obj *resultList = 0;
9325 Jim_Obj **resultVec = 0;
9326 int resultc;
9327 Jim_Obj *emptyStr = 0;
9328 ScanFmtStringObj *fmtObj;
9330 /* This should never happen. The format object should already be of the correct type */
9331 JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
9333 fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
9334 /* Check if format specification was valid */
9335 if (fmtObj->error != 0) {
9336 if (flags & JIM_ERRMSG)
9337 Jim_SetResultString(interp, fmtObj->error, -1);
9338 return 0;
9340 /* Allocate a new "shared" empty string for all unassigned conversions */
9341 emptyStr = Jim_NewEmptyStringObj(interp);
9342 Jim_IncrRefCount(emptyStr);
9343 /* Create a list and fill it with empty strings up to max specified XPG3 */
9344 resultList = Jim_NewListObj(interp, 0, 0);
9345 if (fmtObj->maxPos > 0) {
9346 for (i = 0; i < fmtObj->maxPos; ++i)
9347 Jim_ListAppendElement(interp, resultList, emptyStr);
9348 JimListGetElements(interp, resultList, &resultc, &resultVec);
9350 /* Now handle every partial format description */
9351 for (i = 0, pos = 0; i < fmtObj->count; ++i) {
9352 ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
9353 Jim_Obj *value = 0;
9355 /* Only last type may be "literal" w/o conversion - skip it! */
9356 if (descr->type == 0)
9357 continue;
9358 /* As long as any conversion could be done, we will proceed */
9359 if (scanned > 0)
9360 scanned = ScanOneEntry(interp, str, pos, strLen, fmtObj, i, &value);
9361 /* In case our first try results in EOF, we will leave */
9362 if (scanned == -1 && i == 0)
9363 goto eof;
9364 /* Advance next pos-to-be-scanned for the amount scanned already */
9365 pos += scanned;
9367 /* value == 0 means no conversion took place so take empty string */
9368 if (value == 0)
9369 value = Jim_NewEmptyStringObj(interp);
9370 /* If value is a non-assignable one, skip it */
9371 if (descr->pos == -1) {
9372 Jim_FreeNewObj(interp, value);
9374 else if (descr->pos == 0)
9375 /* Otherwise append it to the result list if no XPG3 was given */
9376 Jim_ListAppendElement(interp, resultList, value);
9377 else if (resultVec[descr->pos - 1] == emptyStr) {
9378 /* But due to given XPG3, put the value into the corr. slot */
9379 Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
9380 Jim_IncrRefCount(value);
9381 resultVec[descr->pos - 1] = value;
9383 else {
9384 /* Otherwise, the slot was already used - free obj and ERROR */
9385 Jim_FreeNewObj(interp, value);
9386 goto err;
9389 Jim_DecrRefCount(interp, emptyStr);
9390 return resultList;
9391 eof:
9392 Jim_DecrRefCount(interp, emptyStr);
9393 Jim_FreeNewObj(interp, resultList);
9394 return (Jim_Obj *)EOF;
9395 err:
9396 Jim_DecrRefCount(interp, emptyStr);
9397 Jim_FreeNewObj(interp, resultList);
9398 return 0;
9401 /* -----------------------------------------------------------------------------
9402 * Pseudo Random Number Generation
9403 * ---------------------------------------------------------------------------*/
9404 /* Initialize the sbox with the numbers from 0 to 255 */
9405 static void JimPrngInit(Jim_Interp *interp)
9407 #define PRNG_SEED_SIZE 256
9408 int i;
9409 unsigned int *seed;
9410 time_t t = time(NULL);
9412 interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
9414 seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
9415 for (i = 0; i < PRNG_SEED_SIZE; i++) {
9416 seed[i] = (rand() ^ t ^ clock());
9418 JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
9419 Jim_Free(seed);
9422 /* Generates N bytes of random data */
9423 static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
9425 Jim_PrngState *prng;
9426 unsigned char *destByte = (unsigned char *)dest;
9427 unsigned int si, sj, x;
9429 /* initialization, only needed the first time */
9430 if (interp->prngState == NULL)
9431 JimPrngInit(interp);
9432 prng = interp->prngState;
9433 /* generates 'len' bytes of pseudo-random numbers */
9434 for (x = 0; x < len; x++) {
9435 prng->i = (prng->i + 1) & 0xff;
9436 si = prng->sbox[prng->i];
9437 prng->j = (prng->j + si) & 0xff;
9438 sj = prng->sbox[prng->j];
9439 prng->sbox[prng->i] = sj;
9440 prng->sbox[prng->j] = si;
9441 *destByte++ = prng->sbox[(si + sj) & 0xff];
9445 /* Re-seed the generator with user-provided bytes */
9446 static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
9448 int i;
9449 Jim_PrngState *prng;
9451 /* initialization, only needed the first time */
9452 if (interp->prngState == NULL)
9453 JimPrngInit(interp);
9454 prng = interp->prngState;
9456 /* Set the sbox[i] with i */
9457 for (i = 0; i < 256; i++)
9458 prng->sbox[i] = i;
9459 /* Now use the seed to perform a random permutation of the sbox */
9460 for (i = 0; i < seedLen; i++) {
9461 unsigned char t;
9463 t = prng->sbox[i & 0xFF];
9464 prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
9465 prng->sbox[seed[i]] = t;
9467 prng->i = prng->j = 0;
9469 /* discard at least the first 256 bytes of stream.
9470 * borrow the seed buffer for this
9472 for (i = 0; i < 256; i += seedLen) {
9473 JimRandomBytes(interp, seed, seedLen);
9477 /* [incr] */
9478 static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
9480 jim_wide wideValue, increment = 1;
9481 Jim_Obj *intObjPtr;
9483 if (argc != 2 && argc != 3) {
9484 Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
9485 return JIM_ERR;
9487 if (argc == 3) {
9488 if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)
9489 return JIM_ERR;
9491 intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
9492 if (!intObjPtr) {
9493 /* Set missing variable to 0 */
9494 wideValue = 0;
9496 else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
9497 return JIM_ERR;
9499 if (!intObjPtr || Jim_IsShared(intObjPtr)) {
9500 intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
9501 if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
9502 Jim_FreeNewObj(interp, intObjPtr);
9503 return JIM_ERR;
9506 else {
9507 /* Can do it the quick way */
9508 Jim_InvalidateStringRep(intObjPtr);
9509 JimWideValue(intObjPtr) = wideValue + increment;
9511 /* The following step is required in order to invalidate the
9512 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9513 if (argv[1]->typePtr != &variableObjType) {
9514 /* Note that this can't fail since GetVariable already succeeded */
9515 Jim_SetVariable(interp, argv[1], intObjPtr);
9518 Jim_SetResult(interp, intObjPtr);
9519 return JIM_OK;
9523 /* -----------------------------------------------------------------------------
9524 * Eval
9525 * ---------------------------------------------------------------------------*/
9526 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9527 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9529 /* Handle calls to the [unknown] command */
9530 static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv, Jim_Obj *fileNameObj,
9531 int linenr)
9533 Jim_Obj **v, *sv[JIM_EVAL_SARGV_LEN];
9534 int retCode;
9536 /* If JimUnknown() is recursively called too many times...
9537 * done here
9539 if (interp->unknown_called > 50) {
9540 return JIM_ERR;
9543 /* If the [unknown] command does not exists returns
9544 * just now */
9545 if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
9546 return JIM_ERR;
9548 /* The object interp->unknown just contains
9549 * the "unknown" string, it is used in order to
9550 * avoid to lookup the unknown command every time
9551 * but instread to cache the result. */
9552 if (argc + 1 <= JIM_EVAL_SARGV_LEN)
9553 v = sv;
9554 else
9555 v = Jim_Alloc(sizeof(Jim_Obj *) * (argc + 1));
9556 /* Make a copy of the arguments vector, but shifted on
9557 * the right of one position. The command name of the
9558 * command will be instead the first argument of the
9559 * [unknown] call. */
9560 memcpy(v + 1, argv, sizeof(Jim_Obj *) * argc);
9561 v[0] = interp->unknown;
9562 /* Call it */
9563 interp->unknown_called++;
9564 retCode = JimEvalObjVector(interp, argc + 1, v, fileNameObj, linenr);
9565 interp->unknown_called--;
9567 /* Clean up */
9568 if (v != sv)
9569 Jim_Free(v);
9570 return retCode;
9573 /* Eval the object vector 'objv' composed of 'objc' elements.
9574 * Every element is used as single argument.
9575 * Jim_EvalObj() will call this function every time its object
9576 * argument is of "list" type, with no string representation.
9578 * This is possible because the string representation of a
9579 * list object generated by the UpdateStringOfList is made
9580 * in a way that ensures that every list element is a different
9581 * command argument. */
9582 static int JimEvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv,
9583 Jim_Obj *fileNameObj, int linenr)
9585 int i, retcode;
9586 Jim_Cmd *cmdPtr;
9588 /* Incr refcount of arguments. */
9589 for (i = 0; i < objc; i++)
9590 Jim_IncrRefCount(objv[i]);
9591 /* Command lookup */
9592 cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
9593 if (cmdPtr == NULL) {
9594 retcode = JimUnknown(interp, objc, objv, fileNameObj, linenr);
9596 else {
9597 /* Call it -- Make sure result is an empty object. */
9598 JimIncrCmdRefCount(cmdPtr);
9599 Jim_SetEmptyResult(interp);
9600 if (cmdPtr->isproc) {
9601 retcode = JimCallProcedure(interp, cmdPtr, fileNameObj, linenr, objc, objv);
9603 else {
9604 interp->cmdPrivData = cmdPtr->u.native.privData;
9605 retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
9607 JimDecrCmdRefCount(interp, cmdPtr);
9609 /* Decr refcount of arguments and return the retcode */
9610 for (i = 0; i < objc; i++)
9611 Jim_DecrRefCount(interp, objv[i]);
9613 return retcode;
9616 int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
9618 return JimEvalObjVector(interp, objc, objv, NULL, 0);
9622 * Invokes 'prefix' as a command with the objv array as arguments.
9624 int Jim_EvalObjPrefix(Jim_Interp *interp, const char *prefix, int objc, Jim_Obj *const *objv)
9626 int i;
9627 int ret;
9628 Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
9630 nargv[0] = Jim_NewStringObj(interp, prefix, -1);
9631 for (i = 0; i < objc; i++) {
9632 nargv[i + 1] = objv[i];
9634 ret = Jim_EvalObjVector(interp, objc + 1, nargv);
9635 Jim_Free(nargv);
9636 return ret;
9639 static void JimAddErrorToStack(Jim_Interp *interp, int retcode, Jim_Obj *fileNameObj, int line)
9641 int rc = retcode;
9643 if (rc == JIM_ERR && !interp->errorFlag) {
9644 /* This is the first error, so save the file/line information and reset the stack */
9645 interp->errorFlag = 1;
9646 Jim_IncrRefCount(fileNameObj);
9647 Jim_DecrRefCount(interp, interp->errorFileNameObj);
9648 interp->errorFileNameObj = fileNameObj;
9649 interp->errorLine = line;
9651 JimResetStackTrace(interp);
9652 /* Always add a level where the error first occurs */
9653 interp->addStackTrace++;
9656 /* Now if this is an "interesting" level, add it to the stack trace */
9657 if (rc == JIM_ERR && interp->addStackTrace > 0) {
9658 /* Add the stack info for the current level */
9660 JimAppendStackTrace(interp, Jim_String(interp->errorProc), fileNameObj, line);
9662 /* Note: if we didn't have a filename for this level,
9663 * don't clear the addStackTrace flag
9664 * so we can pick it up at the next level
9666 if (Jim_Length(fileNameObj)) {
9667 interp->addStackTrace = 0;
9670 Jim_DecrRefCount(interp, interp->errorProc);
9671 interp->errorProc = interp->emptyObj;
9672 Jim_IncrRefCount(interp->errorProc);
9674 else if (rc == JIM_RETURN && interp->returnCode == JIM_ERR) {
9675 /* Propagate the addStackTrace value through 'return -code error' */
9677 else {
9678 interp->addStackTrace = 0;
9682 /* And delete any local procs */
9683 static void JimDeleteLocalProcs(Jim_Interp *interp)
9685 if (interp->localProcs) {
9686 char *procname;
9688 while ((procname = Jim_StackPop(interp->localProcs)) != NULL) {
9689 /* If there is a pushed command, find it */
9690 Jim_Cmd *prevCmd = NULL;
9691 Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, procname);
9692 if (he) {
9693 Jim_Cmd *cmd = (Jim_Cmd *)he->u.val;
9694 if (cmd->isproc && cmd->u.proc.prevCmd) {
9695 prevCmd = cmd->u.proc.prevCmd;
9696 cmd->u.proc.prevCmd = NULL;
9700 /* Delete the local proc */
9701 Jim_DeleteCommand(interp, procname);
9703 if (prevCmd) {
9704 /* And restore the pushed command */
9705 Jim_AddHashEntry(&interp->commands, procname, prevCmd);
9707 Jim_Free(procname);
9709 Jim_FreeStack(interp->localProcs);
9710 Jim_Free(interp->localProcs);
9711 interp->localProcs = NULL;
9715 static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
9717 Jim_Obj *objPtr;
9719 switch (token->type) {
9720 case JIM_TT_STR:
9721 case JIM_TT_ESC:
9722 objPtr = token->objPtr;
9723 break;
9724 case JIM_TT_VAR:
9725 objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
9726 break;
9727 case JIM_TT_DICTSUGAR:
9728 objPtr = JimExpandDictSugar(interp, token->objPtr);
9729 break;
9730 case JIM_TT_EXPRSUGAR:
9731 objPtr = JimExpandExprSugar(interp, token->objPtr);
9732 break;
9733 case JIM_TT_CMD:
9734 switch (Jim_EvalObj(interp, token->objPtr)) {
9735 case JIM_OK:
9736 case JIM_RETURN:
9737 objPtr = interp->result;
9738 break;
9739 case JIM_BREAK:
9740 /* Stop substituting */
9741 return JIM_BREAK;
9742 case JIM_CONTINUE:
9743 /* just skip this one */
9744 return JIM_CONTINUE;
9745 default:
9746 return JIM_ERR;
9748 break;
9749 default:
9750 JimPanic((1,
9751 "default token type (%d) reached " "in Jim_SubstObj().", token->type));
9752 objPtr = NULL;
9753 break;
9755 if (objPtr) {
9756 *objPtrPtr = objPtr;
9757 return JIM_OK;
9759 return JIM_ERR;
9762 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9763 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9764 * The returned object has refcount = 0.
9766 static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
9768 int totlen = 0, i;
9769 Jim_Obj **intv;
9770 Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
9771 Jim_Obj *objPtr;
9772 char *s;
9774 if (tokens <= JIM_EVAL_SINTV_LEN)
9775 intv = sintv;
9776 else
9777 intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
9779 /* Compute every token forming the argument
9780 * in the intv objects vector. */
9781 for (i = 0; i < tokens; i++) {
9782 switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
9783 case JIM_OK:
9784 case JIM_RETURN:
9785 break;
9786 case JIM_BREAK:
9787 if (flags & JIM_SUBST_FLAG) {
9788 /* Stop here */
9789 tokens = i;
9790 continue;
9792 /* XXX: Should probably set an error about break outside loop */
9793 /* fall through to error */
9794 case JIM_CONTINUE:
9795 if (flags & JIM_SUBST_FLAG) {
9796 intv[i] = NULL;
9797 continue;
9799 /* XXX: Ditto continue outside loop */
9800 /* fall through to error */
9801 default:
9802 while (i--) {
9803 Jim_DecrRefCount(interp, intv[i]);
9805 if (intv != sintv) {
9806 Jim_Free(intv);
9808 return NULL;
9810 Jim_IncrRefCount(intv[i]);
9811 Jim_String(intv[i]);
9812 totlen += intv[i]->length;
9815 /* Fast path return for a single token */
9816 if (tokens == 1 && intv[0] && intv == sintv) {
9817 Jim_DecrRefCount(interp, intv[0]);
9818 return intv[0];
9821 /* Concatenate every token in an unique
9822 * object. */
9823 objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
9825 if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
9826 && token[2].type == JIM_TT_VAR) {
9827 /* May be able to do fast interpolated object -> dictSubst */
9828 objPtr->typePtr = &interpolatedObjType;
9829 objPtr->internalRep.twoPtrValue.ptr1 = (void *)token;
9830 objPtr->internalRep.twoPtrValue.ptr2 = intv[2];
9831 Jim_IncrRefCount(intv[2]);
9834 s = objPtr->bytes = Jim_Alloc(totlen + 1);
9835 objPtr->length = totlen;
9836 for (i = 0; i < tokens; i++) {
9837 if (intv[i]) {
9838 memcpy(s, intv[i]->bytes, intv[i]->length);
9839 s += intv[i]->length;
9840 Jim_DecrRefCount(interp, intv[i]);
9843 objPtr->bytes[totlen] = '\0';
9844 /* Free the intv vector if not static. */
9845 if (intv != sintv) {
9846 Jim_Free(intv);
9849 return objPtr;
9853 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9854 * Otherwise eval with Jim_EvalObj()
9856 static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *fileNameObj, int linenr)
9858 if (!Jim_IsList(listPtr)) {
9859 return Jim_EvalObj(interp, listPtr);
9861 else {
9862 int retcode = JIM_OK;
9864 if (listPtr->internalRep.listValue.len) {
9865 Jim_IncrRefCount(listPtr);
9866 retcode = JimEvalObjVector(interp,
9867 listPtr->internalRep.listValue.len,
9868 listPtr->internalRep.listValue.ele, fileNameObj, linenr);
9869 Jim_DecrRefCount(interp, listPtr);
9871 return retcode;
9875 int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
9877 int i;
9878 ScriptObj *script;
9879 ScriptToken *token;
9880 int retcode = JIM_OK;
9881 Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
9882 int linenr = 0;
9884 interp->errorFlag = 0;
9886 /* If the object is of type "list", we can call
9887 * a specialized version of Jim_EvalObj() */
9888 if (Jim_IsList(scriptObjPtr)) {
9889 return JimEvalObjList(interp, scriptObjPtr, NULL, 0);
9892 Jim_IncrRefCount(scriptObjPtr); /* Make sure it's shared. */
9893 script = Jim_GetScript(interp, scriptObjPtr);
9895 /* Reset the interpreter result. This is useful to
9896 * return the empty result in the case of empty program. */
9897 Jim_SetEmptyResult(interp);
9899 #ifdef JIM_OPTIMIZATION
9900 /* Check for one of the following common scripts used by for, while
9902 * {}
9903 * incr a
9905 if (script->len == 0) {
9906 Jim_DecrRefCount(interp, scriptObjPtr);
9907 return JIM_OK;
9909 if (script->len == 3
9910 && script->token[1].objPtr->typePtr == &commandObjType
9911 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
9912 && script->token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
9913 && script->token[2].objPtr->typePtr == &variableObjType) {
9915 Jim_Obj *objPtr = Jim_GetVariable(interp, script->token[2].objPtr, JIM_NONE);
9917 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
9918 JimWideValue(objPtr)++;
9919 Jim_InvalidateStringRep(objPtr);
9920 Jim_DecrRefCount(interp, scriptObjPtr);
9921 Jim_SetResult(interp, objPtr);
9922 return JIM_OK;
9925 #endif
9927 /* Now we have to make sure the internal repr will not be
9928 * freed on shimmering.
9930 * Think for example to this:
9932 * set x {llength $x; ... some more code ...}; eval $x
9934 * In order to preserve the internal rep, we increment the
9935 * inUse field of the script internal rep structure. */
9936 script->inUse++;
9938 token = script->token;
9939 argv = sargv;
9941 /* Execute every command sequentially until the end of the script
9942 * or an error occurs.
9944 for (i = 0; i < script->len && retcode == JIM_OK; ) {
9945 int argc;
9946 int j;
9947 Jim_Cmd *cmd;
9949 /* First token of the line is always JIM_TT_LINE */
9950 argc = token[i].objPtr->internalRep.scriptLineValue.argc;
9951 linenr = token[i].objPtr->internalRep.scriptLineValue.line;
9953 /* Allocate the arguments vector if required */
9954 if (argc > JIM_EVAL_SARGV_LEN)
9955 argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
9957 /* Skip the JIM_TT_LINE token */
9958 i++;
9960 /* Populate the arguments objects.
9961 * If an error occurs, retcode will be set and
9962 * 'j' will be set to the number of args expanded
9964 for (j = 0; j < argc; j++) {
9965 long wordtokens = 1;
9966 int expand = 0;
9967 Jim_Obj *wordObjPtr = NULL;
9969 if (token[i].type == JIM_TT_WORD) {
9970 wordtokens = JimWideValue(token[i++].objPtr);
9971 if (wordtokens < 0) {
9972 expand = 1;
9973 wordtokens = -wordtokens;
9977 if (wordtokens == 1) {
9978 /* Fast path if the token does not
9979 * need interpolation */
9981 switch (token[i].type) {
9982 case JIM_TT_ESC:
9983 case JIM_TT_STR:
9984 wordObjPtr = token[i].objPtr;
9985 break;
9986 case JIM_TT_VAR:
9987 wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
9988 break;
9989 case JIM_TT_EXPRSUGAR:
9990 wordObjPtr = JimExpandExprSugar(interp, token[i].objPtr);
9991 break;
9992 case JIM_TT_DICTSUGAR:
9993 wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
9994 break;
9995 case JIM_TT_CMD:
9996 retcode = Jim_EvalObj(interp, token[i].objPtr);
9997 if (retcode == JIM_OK) {
9998 wordObjPtr = Jim_GetResult(interp);
10000 break;
10001 default:
10002 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10005 else {
10006 /* For interpolation we call a helper
10007 * function to do the work for us. */
10008 wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
10011 if (!wordObjPtr) {
10012 if (retcode == JIM_OK) {
10013 retcode = JIM_ERR;
10015 break;
10018 Jim_IncrRefCount(wordObjPtr);
10019 i += wordtokens;
10021 if (!expand) {
10022 argv[j] = wordObjPtr;
10024 else {
10025 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10026 int len = Jim_ListLength(interp, wordObjPtr);
10027 int newargc = argc + len - 1;
10028 int k;
10030 if (len > 1) {
10031 if (argv == sargv) {
10032 if (newargc > JIM_EVAL_SARGV_LEN) {
10033 argv = Jim_Alloc(sizeof(*argv) * newargc);
10034 memcpy(argv, sargv, sizeof(*argv) * j);
10037 else {
10038 /* Need to realloc to make room for (len - 1) more entries */
10039 argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
10043 /* Now copy in the expanded version */
10044 for (k = 0; k < len; k++) {
10045 argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
10046 Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
10049 /* The original object reference is no longer needed,
10050 * after the expansion it is no longer present on
10051 * the argument vector, but the single elements are
10052 * in its place. */
10053 Jim_DecrRefCount(interp, wordObjPtr);
10055 /* And update the indexes */
10056 j--;
10057 argc += len - 1;
10061 if (retcode == JIM_OK && argc) {
10062 /* Lookup the command to call */
10063 cmd = Jim_GetCommand(interp, argv[0], JIM_ERRMSG);
10064 if (cmd != NULL) {
10065 /* Call it -- Make sure result is an empty object. */
10066 JimIncrCmdRefCount(cmd);
10067 Jim_SetEmptyResult(interp);
10068 if (cmd->isproc) {
10069 retcode =
10070 JimCallProcedure(interp, cmd, script->fileNameObj, linenr, argc, argv);
10071 } else {
10072 interp->cmdPrivData = cmd->u.native.privData;
10073 retcode = cmd->u.native.cmdProc(interp, argc, argv);
10075 JimDecrCmdRefCount(interp, cmd);
10077 else {
10078 /* Call [unknown] */
10079 retcode = JimUnknown(interp, argc, argv, script->fileNameObj, linenr);
10081 if (interp->signal_level && interp->sigmask) {
10082 /* Check for a signal after each command */
10083 retcode = JIM_SIGNAL;
10087 /* Finished with the command, so decrement ref counts of each argument */
10088 while (j-- > 0) {
10089 Jim_DecrRefCount(interp, argv[j]);
10092 if (argv != sargv) {
10093 Jim_Free(argv);
10094 argv = sargv;
10098 /* Possibly add to the error stack trace */
10099 JimAddErrorToStack(interp, retcode, script->fileNameObj, linenr);
10101 /* Note that we don't have to decrement inUse, because the
10102 * following code transfers our use of the reference again to
10103 * the script object. */
10104 Jim_FreeIntRep(interp, scriptObjPtr);
10105 scriptObjPtr->typePtr = &scriptObjType;
10106 Jim_SetIntRepPtr(scriptObjPtr, script);
10107 Jim_DecrRefCount(interp, scriptObjPtr);
10109 return retcode;
10112 static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
10114 int retcode;
10115 /* If argObjPtr begins with '&', do an automatic upvar */
10116 const char *varname = Jim_String(argNameObj);
10117 if (*varname == '&') {
10118 /* First check that the target variable exists */
10119 Jim_Obj *objPtr;
10120 Jim_CallFrame *savedCallFrame = interp->framePtr;
10122 interp->framePtr = interp->framePtr->parentCallFrame;
10123 objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
10124 interp->framePtr = savedCallFrame;
10125 if (!objPtr) {
10126 return JIM_ERR;
10129 /* It exists, so perform the binding. */
10130 objPtr = Jim_NewStringObj(interp, varname + 1, -1);
10131 Jim_IncrRefCount(objPtr);
10132 retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parentCallFrame);
10133 Jim_DecrRefCount(interp, objPtr);
10135 else {
10136 retcode = Jim_SetVariable(interp, argNameObj, argValObj);
10138 return retcode;
10142 * Sets the interp result to be an error message indicating the required proc args.
10144 static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
10146 /* Create a nice error message, consistent with Tcl 8.5 */
10147 Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
10148 int i;
10150 for (i = 0; i < cmd->u.proc.argListLen; i++) {
10151 Jim_AppendString(interp, argmsg, " ", 1);
10153 if (i == cmd->u.proc.argsPos) {
10154 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10155 /* Renamed args */
10156 Jim_AppendString(interp, argmsg, "?", 1);
10157 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
10158 Jim_AppendString(interp, argmsg, " ...?", -1);
10160 else {
10161 /* We have plain args */
10162 Jim_AppendString(interp, argmsg, "?argument ...?", -1);
10165 else {
10166 if (cmd->u.proc.arglist[i].defaultObjPtr) {
10167 Jim_AppendString(interp, argmsg, "?", 1);
10168 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10169 Jim_AppendString(interp, argmsg, "?", 1);
10171 else {
10172 Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
10176 Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
10177 Jim_FreeNewObj(interp, argmsg);
10180 /* Call a procedure implemented in Tcl.
10181 * It's possible to speed-up a lot this function, currently
10182 * the callframes are not cached, but allocated and
10183 * destroied every time. What is expecially costly is
10184 * to create/destroy the local vars hash table every time.
10186 * This can be fixed just implementing callframes caching
10187 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10188 static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, Jim_Obj *fileNameObj, int linenr, int argc,
10189 Jim_Obj *const *argv)
10191 Jim_CallFrame *callFramePtr;
10192 Jim_Stack *prevLocalProcs;
10193 int i, d, retcode, optargs;
10195 /* Check arity */
10196 if (argc - 1 < cmd->u.proc.reqArity ||
10197 (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
10198 JimSetProcWrongArgs(interp, argv[0], cmd);
10199 return JIM_ERR;
10202 /* Check if there are too nested calls */
10203 if (interp->framePtr->level == interp->maxNestingDepth) {
10204 Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
10205 return JIM_ERR;
10208 /* Create a new callframe */
10209 callFramePtr = JimCreateCallFrame(interp, interp->framePtr);
10210 callFramePtr->argv = argv;
10211 callFramePtr->argc = argc;
10212 callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
10213 callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
10214 callFramePtr->staticVars = cmd->u.proc.staticVars;
10215 callFramePtr->fileNameObj = fileNameObj;
10216 callFramePtr->line = linenr;
10217 Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
10218 Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
10219 interp->framePtr = callFramePtr;
10221 /* How many optional args are available */
10222 optargs = (argc - 1 - cmd->u.proc.reqArity);
10224 /* Step 'i' along the actual args, and step 'd' along the formal args */
10225 i = 1;
10226 for (d = 0; d < cmd->u.proc.argListLen; d++) {
10227 Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
10228 if (d == cmd->u.proc.argsPos) {
10229 /* assign $args */
10230 Jim_Obj *listObjPtr;
10231 int argsLen = 0;
10232 if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
10233 argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
10235 listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
10237 /* It is possible to rename args. */
10238 if (cmd->u.proc.arglist[d].defaultObjPtr) {
10239 nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
10241 retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
10242 if (retcode != JIM_OK) {
10243 goto badargset;
10246 i += argsLen;
10247 continue;
10250 /* Optional or required? */
10251 if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
10252 retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
10254 else {
10255 /* Ran out, so use the default */
10256 retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
10258 if (retcode != JIM_OK) {
10259 goto badargset;
10263 /* Install a new stack for local procs */
10264 prevLocalProcs = interp->localProcs;
10265 interp->localProcs = NULL;
10267 /* Eval the body */
10268 retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
10270 /* Delete any local procs */
10271 JimDeleteLocalProcs(interp);
10272 interp->localProcs = prevLocalProcs;
10274 badargset:
10275 /* Destroy the callframe */
10276 interp->framePtr = interp->framePtr->parentCallFrame;
10277 if (callFramePtr->vars.size != JIM_HT_INITIAL_SIZE) {
10278 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NONE);
10280 else {
10281 JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NOHT);
10283 /* Handle the JIM_EVAL return code */
10284 while (retcode == JIM_EVAL) {
10285 Jim_Obj *resultScriptObjPtr = Jim_GetResult(interp);
10287 Jim_IncrRefCount(resultScriptObjPtr);
10288 /* Should be a list! */
10289 retcode = JimEvalObjList(interp, resultScriptObjPtr, fileNameObj, linenr);
10290 Jim_DecrRefCount(interp, resultScriptObjPtr);
10292 /* Handle the JIM_RETURN return code */
10293 if (retcode == JIM_RETURN) {
10294 if (--interp->returnLevel <= 0) {
10295 retcode = interp->returnCode;
10296 interp->returnCode = JIM_OK;
10297 interp->returnLevel = 0;
10300 else if (retcode == JIM_ERR) {
10301 interp->addStackTrace++;
10302 Jim_DecrRefCount(interp, interp->errorProc);
10303 interp->errorProc = argv[0];
10304 Jim_IncrRefCount(interp->errorProc);
10306 return retcode;
10309 int Jim_Eval_Named(Jim_Interp *interp, const char *script, const char *filename, int lineno)
10311 int retval;
10312 Jim_Obj *scriptObjPtr;
10314 scriptObjPtr = Jim_NewStringObj(interp, script, -1);
10315 Jim_IncrRefCount(scriptObjPtr);
10318 if (filename) {
10319 Jim_Obj *prevScriptObj;
10321 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
10323 prevScriptObj = interp->currentScriptObj;
10324 interp->currentScriptObj = scriptObjPtr;
10326 retval = Jim_EvalObj(interp, scriptObjPtr);
10328 interp->currentScriptObj = prevScriptObj;
10330 else {
10331 retval = Jim_EvalObj(interp, scriptObjPtr);
10333 Jim_DecrRefCount(interp, scriptObjPtr);
10334 return retval;
10337 int Jim_Eval(Jim_Interp *interp, const char *script)
10339 return Jim_Eval_Named(interp, script, NULL, 0);
10342 /* Execute script in the scope of the global level */
10343 int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
10345 int retval;
10346 Jim_CallFrame *savedFramePtr = interp->framePtr;
10348 interp->framePtr = interp->topFramePtr;
10349 retval = Jim_Eval(interp, script);
10350 interp->framePtr = savedFramePtr;
10352 return retval;
10355 int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
10357 int retval;
10358 Jim_CallFrame *savedFramePtr = interp->framePtr;
10360 interp->framePtr = interp->topFramePtr;
10361 retval = Jim_EvalFile(interp, filename);
10362 interp->framePtr = savedFramePtr;
10364 return retval;
10367 #include <sys/stat.h>
10369 int Jim_EvalFile(Jim_Interp *interp, const char *filename)
10371 FILE *fp;
10372 char *buf;
10373 Jim_Obj *scriptObjPtr;
10374 Jim_Obj *prevScriptObj;
10375 struct stat sb;
10376 int retcode;
10377 int readlen;
10378 struct JimParseResult result;
10380 if (stat(filename, &sb) != 0 || (fp = fopen(filename, "rt")) == NULL) {
10381 Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
10382 return JIM_ERR;
10384 if (sb.st_size == 0) {
10385 fclose(fp);
10386 return JIM_OK;
10389 buf = Jim_Alloc(sb.st_size + 1);
10390 readlen = fread(buf, 1, sb.st_size, fp);
10391 if (ferror(fp)) {
10392 fclose(fp);
10393 Jim_Free(buf);
10394 Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
10395 return JIM_ERR;
10397 fclose(fp);
10398 buf[readlen] = 0;
10400 scriptObjPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
10401 JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), 1);
10402 Jim_IncrRefCount(scriptObjPtr);
10404 /* Now check the script for unmatched braces, etc. */
10405 if (SetScriptFromAny(interp, scriptObjPtr, &result) == JIM_ERR) {
10406 const char *msg;
10407 char linebuf[20];
10409 switch (result.missing) {
10410 case '[':
10411 msg = "unmatched \"[\"";
10412 break;
10413 case '{':
10414 msg = "missing close-brace";
10415 break;
10416 case '"':
10417 default:
10418 msg = "missing quote";
10419 break;
10422 snprintf(linebuf, sizeof(linebuf), "%d", result.line);
10424 Jim_SetResultFormatted(interp, "%s in \"%s\" at line %s",
10425 msg, filename, linebuf);
10426 Jim_DecrRefCount(interp, scriptObjPtr);
10427 return JIM_ERR;
10430 prevScriptObj = interp->currentScriptObj;
10431 interp->currentScriptObj = scriptObjPtr;
10433 retcode = Jim_EvalObj(interp, scriptObjPtr);
10435 /* Handle the JIM_RETURN return code */
10436 if (retcode == JIM_RETURN) {
10437 if (--interp->returnLevel <= 0) {
10438 retcode = interp->returnCode;
10439 interp->returnCode = JIM_OK;
10440 interp->returnLevel = 0;
10443 if (retcode == JIM_ERR) {
10444 /* EvalFile changes context, so add a stack frame here */
10445 interp->addStackTrace++;
10448 interp->currentScriptObj = prevScriptObj;
10450 Jim_DecrRefCount(interp, scriptObjPtr);
10452 return retcode;
10455 /* -----------------------------------------------------------------------------
10456 * Subst
10457 * ---------------------------------------------------------------------------*/
10458 static int JimParseSubstStr(struct JimParserCtx *pc)
10460 pc->tstart = pc->p;
10461 pc->tline = pc->linenr;
10462 while (pc->len && *pc->p != '$' && *pc->p != '[') {
10463 if (*pc->p == '\\' && pc->len > 1) {
10464 pc->p++;
10465 pc->len--;
10467 pc->p++;
10468 pc->len--;
10470 pc->tend = pc->p - 1;
10471 pc->tt = JIM_TT_ESC;
10472 return JIM_OK;
10475 static int JimParseSubst(struct JimParserCtx *pc, int flags)
10477 int retval;
10479 if (pc->len == 0) {
10480 pc->tstart = pc->tend = pc->p;
10481 pc->tline = pc->linenr;
10482 pc->tt = JIM_TT_EOL;
10483 pc->eof = 1;
10484 return JIM_OK;
10486 switch (*pc->p) {
10487 case '[':
10488 retval = JimParseCmd(pc);
10489 if (flags & JIM_SUBST_NOCMD) {
10490 pc->tstart--;
10491 pc->tend++;
10492 pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
10494 return retval;
10495 break;
10496 case '$':
10497 if (JimParseVar(pc) == JIM_ERR) {
10498 pc->tstart = pc->tend = pc->p++;
10499 pc->len--;
10500 pc->tline = pc->linenr;
10501 pc->tt = JIM_TT_STR;
10503 else {
10504 if (flags & JIM_SUBST_NOVAR) {
10505 pc->tstart--;
10506 if (flags & JIM_SUBST_NOESC)
10507 pc->tt = JIM_TT_STR;
10508 else
10509 pc->tt = JIM_TT_ESC;
10510 if (*pc->tstart == '{') {
10511 pc->tstart--;
10512 if (*(pc->tend + 1))
10513 pc->tend++;
10517 break;
10518 default:
10519 retval = JimParseSubstStr(pc);
10520 if (flags & JIM_SUBST_NOESC)
10521 pc->tt = JIM_TT_STR;
10522 return retval;
10523 break;
10525 return JIM_OK;
10528 /* The subst object type reuses most of the data structures and functions
10529 * of the script object. Script's data structures are a bit more complex
10530 * for what is needed for [subst]itution tasks, but the reuse helps to
10531 * deal with a single data structure at the cost of some more memory
10532 * usage for substitutions. */
10534 /* This method takes the string representation of an object
10535 * as a Tcl string where to perform [subst]itution, and generates
10536 * the pre-parsed internal representation. */
10537 static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
10539 int scriptTextLen;
10540 const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
10541 struct JimParserCtx parser;
10542 struct ScriptObj *script = Jim_Alloc(sizeof(*script));
10543 ParseTokenList tokenlist;
10545 /* Initially parse the subst into tokens (in tokenlist) */
10546 ScriptTokenListInit(&tokenlist);
10548 JimParserInit(&parser, scriptText, scriptTextLen, 1);
10549 while (1) {
10550 JimParseSubst(&parser, flags);
10551 if (parser.eof) {
10552 /* Note that subst doesn't need the EOL token */
10553 break;
10555 ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
10556 parser.tline);
10559 /* Create the "real" subst/script tokens from the initial token list */
10560 script->inUse = 1;
10561 script->substFlags = flags;
10562 script->fileNameObj = interp->emptyObj;
10563 Jim_IncrRefCount(script->fileNameObj);
10564 SubstObjAddTokens(interp, script, &tokenlist);
10566 /* No longer need the token list */
10567 ScriptTokenListFree(&tokenlist);
10569 #ifdef DEBUG_SHOW_SUBST
10571 int i;
10573 printf("==== Subst ====\n");
10574 for (i = 0; i < script->len; i++) {
10575 printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
10576 Jim_String(script->token[i].objPtr));
10579 #endif
10581 /* Free the old internal rep and set the new one. */
10582 Jim_FreeIntRep(interp, objPtr);
10583 Jim_SetIntRepPtr(objPtr, script);
10584 objPtr->typePtr = &scriptObjType;
10585 return JIM_OK;
10588 static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
10590 if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
10591 SetSubstFromAny(interp, objPtr, flags);
10592 return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
10595 /* Performs commands,variables,blackslashes substitution,
10596 * storing the result object (with refcount 0) into
10597 * resObjPtrPtr. */
10598 int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
10600 ScriptObj *script = Jim_GetSubst(interp, substObjPtr, flags);
10602 Jim_IncrRefCount(substObjPtr); /* Make sure it's shared. */
10603 /* In order to preserve the internal rep, we increment the
10604 * inUse field of the script internal rep structure. */
10605 script->inUse++;
10607 *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
10609 script->inUse--;
10610 Jim_DecrRefCount(interp, substObjPtr);
10611 if (*resObjPtrPtr == NULL) {
10612 return JIM_ERR;
10614 return JIM_OK;
10617 /* -----------------------------------------------------------------------------
10618 * Core commands utility functions
10619 * ---------------------------------------------------------------------------*/
10620 void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
10622 int i;
10623 Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);
10625 Jim_AppendString(interp, objPtr, "wrong # args: should be \"", -1);
10626 for (i = 0; i < argc; i++) {
10627 Jim_AppendObj(interp, objPtr, argv[i]);
10628 if (!(i + 1 == argc && msg[0] == '\0'))
10629 Jim_AppendString(interp, objPtr, " ", 1);
10631 Jim_AppendString(interp, objPtr, msg, -1);
10632 Jim_AppendString(interp, objPtr, "\"", 1);
10633 Jim_SetResult(interp, objPtr);
10636 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10638 /* type is: 0=commands, 1=procs, 2=channels */
10639 static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
10641 Jim_HashTableIterator *htiter;
10642 Jim_HashEntry *he;
10643 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
10645 /* Check for the non-pattern case. We can do this much more efficiently. */
10646 if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
10647 Jim_Cmd *cmdPtr = Jim_GetCommand(interp, patternObjPtr, JIM_NONE);
10648 if (cmdPtr) {
10649 if (type == 1 && !cmdPtr->isproc) {
10650 /* not a proc */
10652 else if (type == 2 && !Jim_AioFilehandle(interp, patternObjPtr)) {
10653 /* not a channel */
10655 else {
10656 Jim_ListAppendElement(interp, listObjPtr, patternObjPtr);
10659 return listObjPtr;
10662 htiter = Jim_GetHashTableIterator(&interp->commands);
10663 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
10664 Jim_Cmd *cmdPtr = he->u.val;
10665 Jim_Obj *cmdNameObj;
10667 if (type == 1 && !cmdPtr->isproc) {
10668 /* not a proc */
10669 continue;
10671 if (patternObjPtr && !JimStringMatch(interp, patternObjPtr, he->key, 0))
10672 continue;
10674 cmdNameObj = Jim_NewStringObj(interp, he->key, -1);
10676 /* Is it a channel? */
10677 if (type == 2 && !Jim_AioFilehandle(interp, cmdNameObj)) {
10678 Jim_FreeNewObj(interp, cmdNameObj);
10679 continue;
10682 Jim_ListAppendElement(interp, listObjPtr, cmdNameObj);
10684 Jim_FreeHashTableIterator(htiter);
10685 return listObjPtr;
10688 /* Keep this in order */
10689 #define JIM_VARLIST_GLOBALS 0
10690 #define JIM_VARLIST_LOCALS 1
10691 #define JIM_VARLIST_VARS 2
10693 static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
10695 Jim_HashTableIterator *htiter;
10696 Jim_HashEntry *he;
10697 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
10699 if (mode == JIM_VARLIST_GLOBALS) {
10700 htiter = Jim_GetHashTableIterator(&interp->topFramePtr->vars);
10702 else {
10703 /* For [info locals], if we are at top level an emtpy list
10704 * is returned. I don't agree, but we aim at compatibility (SS) */
10705 if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr)
10706 return listObjPtr;
10707 htiter = Jim_GetHashTableIterator(&interp->framePtr->vars);
10709 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
10710 Jim_Var *varPtr = (Jim_Var *)he->u.val;
10712 if (mode == JIM_VARLIST_LOCALS) {
10713 if (varPtr->linkFramePtr != NULL)
10714 continue;
10716 if (patternObjPtr && !JimStringMatch(interp, patternObjPtr, he->key, 0))
10717 continue;
10718 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, he->key, -1));
10720 Jim_FreeHashTableIterator(htiter);
10721 return listObjPtr;
10724 static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
10725 Jim_Obj **objPtrPtr, int info_level_cmd)
10727 Jim_CallFrame *targetCallFrame;
10729 targetCallFrame = JimGetCallFrameByInteger(interp, levelObjPtr);
10730 if (targetCallFrame == NULL) {
10731 return JIM_ERR;
10733 /* No proc call at toplevel callframe */
10734 if (targetCallFrame == interp->topFramePtr) {
10735 Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
10736 return JIM_ERR;
10738 if (info_level_cmd) {
10739 *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
10741 else {
10742 Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
10744 Jim_ListAppendElement(interp, listObj, targetCallFrame->argv[0]);
10745 Jim_ListAppendElement(interp, listObj, targetCallFrame->fileNameObj);
10746 Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, targetCallFrame->line));
10747 *objPtrPtr = listObj;
10749 return JIM_OK;
10752 /* -----------------------------------------------------------------------------
10753 * Core commands
10754 * ---------------------------------------------------------------------------*/
10756 /* fake [puts] -- not the real puts, just for debugging. */
10757 static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10759 if (argc != 2 && argc != 3) {
10760 Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
10761 return JIM_ERR;
10763 if (argc == 3) {
10764 if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
10765 Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
10766 return JIM_ERR;
10768 else {
10769 fputs(Jim_String(argv[2]), stdout);
10772 else {
10773 puts(Jim_String(argv[1]));
10775 return JIM_OK;
10778 /* Helper for [+] and [*] */
10779 static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10781 jim_wide wideValue, res;
10782 double doubleValue, doubleRes;
10783 int i;
10785 res = (op == JIM_EXPROP_ADD) ? 0 : 1;
10787 for (i = 1; i < argc; i++) {
10788 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
10789 goto trydouble;
10790 if (op == JIM_EXPROP_ADD)
10791 res += wideValue;
10792 else
10793 res *= wideValue;
10795 Jim_SetResultInt(interp, res);
10796 return JIM_OK;
10797 trydouble:
10798 doubleRes = (double)res;
10799 for (; i < argc; i++) {
10800 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10801 return JIM_ERR;
10802 if (op == JIM_EXPROP_ADD)
10803 doubleRes += doubleValue;
10804 else
10805 doubleRes *= doubleValue;
10807 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10808 return JIM_OK;
10811 /* Helper for [-] and [/] */
10812 static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
10814 jim_wide wideValue, res = 0;
10815 double doubleValue, doubleRes = 0;
10816 int i = 2;
10818 if (argc < 2) {
10819 Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
10820 return JIM_ERR;
10822 else if (argc == 2) {
10823 /* The arity = 2 case is different. For [- x] returns -x,
10824 * while [/ x] returns 1/x. */
10825 if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
10826 if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
10827 return JIM_ERR;
10829 else {
10830 if (op == JIM_EXPROP_SUB)
10831 doubleRes = -doubleValue;
10832 else
10833 doubleRes = 1.0 / doubleValue;
10834 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10835 return JIM_OK;
10838 if (op == JIM_EXPROP_SUB) {
10839 res = -wideValue;
10840 Jim_SetResultInt(interp, res);
10842 else {
10843 doubleRes = 1.0 / wideValue;
10844 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10846 return JIM_OK;
10848 else {
10849 if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
10850 if (Jim_GetDouble(interp, argv[1], &doubleRes)
10851 != JIM_OK) {
10852 return JIM_ERR;
10854 else {
10855 goto trydouble;
10859 for (i = 2; i < argc; i++) {
10860 if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
10861 doubleRes = (double)res;
10862 goto trydouble;
10864 if (op == JIM_EXPROP_SUB)
10865 res -= wideValue;
10866 else
10867 res /= wideValue;
10869 Jim_SetResultInt(interp, res);
10870 return JIM_OK;
10871 trydouble:
10872 for (; i < argc; i++) {
10873 if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
10874 return JIM_ERR;
10875 if (op == JIM_EXPROP_SUB)
10876 doubleRes -= doubleValue;
10877 else
10878 doubleRes /= doubleValue;
10880 Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
10881 return JIM_OK;
10885 /* [+] */
10886 static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10888 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
10891 /* [*] */
10892 static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10894 return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
10897 /* [-] */
10898 static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10900 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
10903 /* [/] */
10904 static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10906 return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
10909 /* [set] */
10910 static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10912 if (argc != 2 && argc != 3) {
10913 Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
10914 return JIM_ERR;
10916 if (argc == 2) {
10917 Jim_Obj *objPtr;
10919 objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
10920 if (!objPtr)
10921 return JIM_ERR;
10922 Jim_SetResult(interp, objPtr);
10923 return JIM_OK;
10925 /* argc == 3 case. */
10926 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
10927 return JIM_ERR;
10928 Jim_SetResult(interp, argv[2]);
10929 return JIM_OK;
10932 /* [unset]
10934 * unset ?-nocomplain? ?--? ?varName ...?
10936 static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10938 int i = 1;
10939 int complain = 1;
10941 while (i < argc) {
10942 if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
10943 i++;
10944 break;
10946 if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
10947 complain = 0;
10948 i++;
10949 continue;
10951 break;
10954 while (i < argc) {
10955 if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
10956 && complain) {
10957 return JIM_ERR;
10959 i++;
10961 return JIM_OK;
10964 /* [while] */
10965 static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
10967 if (argc != 3) {
10968 Jim_WrongNumArgs(interp, 1, argv, "condition body");
10969 return JIM_ERR;
10972 /* The general purpose implementation of while starts here */
10973 while (1) {
10974 int boolean, retval;
10976 if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
10977 return retval;
10978 if (!boolean)
10979 break;
10981 if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
10982 switch (retval) {
10983 case JIM_BREAK:
10984 goto out;
10985 break;
10986 case JIM_CONTINUE:
10987 continue;
10988 break;
10989 default:
10990 return retval;
10994 out:
10995 Jim_SetEmptyResult(interp);
10996 return JIM_OK;
10999 /* [for] */
11000 static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11002 int retval;
11003 int boolean = 1;
11004 Jim_Obj *varNamePtr = NULL;
11005 Jim_Obj *stopVarNamePtr = NULL;
11007 if (argc != 5) {
11008 Jim_WrongNumArgs(interp, 1, argv, "start test next body");
11009 return JIM_ERR;
11012 /* Do the initialisation */
11013 if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
11014 return retval;
11017 /* And do the first test now. Better for optimisation
11018 * if we can do next/test at the bottom of the loop
11020 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11022 /* Ready to do the body as follows:
11023 * while (1) {
11024 * body // check retcode
11025 * next // check retcode
11026 * test // check retcode/test bool
11030 #ifdef JIM_OPTIMIZATION
11031 /* Check if the for is on the form:
11032 * for ... {$i < CONST} {incr i}
11033 * for ... {$i < $j} {incr i}
11035 if (retval == JIM_OK && boolean) {
11036 ScriptObj *incrScript;
11037 ExprByteCode *expr;
11038 jim_wide stop, currentVal;
11039 unsigned jim_wide procEpoch;
11040 Jim_Obj *objPtr;
11041 int cmpOffset;
11043 /* Do it only if there aren't shared arguments */
11044 expr = JimGetExpression(interp, argv[2]);
11045 incrScript = Jim_GetScript(interp, argv[3]);
11047 /* Ensure proper lengths to start */
11048 if (incrScript->len != 3 || !expr || expr->len != 3) {
11049 goto evalstart;
11051 /* Ensure proper token types. */
11052 if (incrScript->token[1].type != JIM_TT_ESC ||
11053 expr->token[0].type != JIM_TT_VAR ||
11054 (expr->token[1].type != JIM_TT_EXPR_INT && expr->token[1].type != JIM_TT_VAR)) {
11055 goto evalstart;
11058 if (expr->token[2].type == JIM_EXPROP_LT) {
11059 cmpOffset = 0;
11061 else if (expr->token[2].type == JIM_EXPROP_LTE) {
11062 cmpOffset = 1;
11064 else {
11065 goto evalstart;
11068 /* Update command must be incr */
11069 if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
11070 goto evalstart;
11073 /* incr, expression must be about the same variable */
11074 if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->token[0].objPtr)) {
11075 goto evalstart;
11078 /* Get the stop condition (must be a variable or integer) */
11079 if (expr->token[1].type == JIM_TT_EXPR_INT) {
11080 if (Jim_GetWide(interp, expr->token[1].objPtr, &stop) == JIM_ERR) {
11081 goto evalstart;
11084 else {
11085 stopVarNamePtr = expr->token[1].objPtr;
11086 Jim_IncrRefCount(stopVarNamePtr);
11087 /* Keep the compiler happy */
11088 stop = 0;
11091 /* Initialization */
11092 procEpoch = interp->procEpoch;
11093 varNamePtr = expr->token[0].objPtr;
11094 Jim_IncrRefCount(varNamePtr);
11096 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
11097 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK) {
11098 goto testcond;
11101 /* --- OPTIMIZED FOR --- */
11102 while (retval == JIM_OK) {
11103 /* === Check condition === */
11104 /* Note that currentVal is already set here */
11106 /* Immediate or Variable? get the 'stop' value if the latter. */
11107 if (stopVarNamePtr) {
11108 objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
11109 if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
11110 goto testcond;
11114 if (currentVal >= stop + cmpOffset) {
11115 break;
11118 /* Eval body */
11119 retval = Jim_EvalObj(interp, argv[4]);
11120 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11121 retval = JIM_OK;
11122 /* If there was a change in procedures/command continue
11123 * with the usual [for] command implementation */
11124 if (procEpoch != interp->procEpoch) {
11125 goto evalnext;
11128 objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
11130 /* Increment */
11131 if (objPtr == NULL) {
11132 retval = JIM_ERR;
11133 goto out;
11135 if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11136 currentVal = ++JimWideValue(objPtr);
11137 Jim_InvalidateStringRep(objPtr);
11139 else {
11140 if (Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK ||
11141 Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
11142 ++currentVal)) != JIM_OK) {
11143 goto evalnext;
11148 goto out;
11150 evalstart:
11151 #endif
11153 while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
11154 /* Body */
11155 retval = Jim_EvalObj(interp, argv[4]);
11157 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11158 /* increment */
11159 evalnext:
11160 retval = Jim_EvalObj(interp, argv[3]);
11161 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11162 /* test */
11163 testcond:
11164 retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
11168 out:
11169 if (stopVarNamePtr) {
11170 Jim_DecrRefCount(interp, stopVarNamePtr);
11172 if (varNamePtr) {
11173 Jim_DecrRefCount(interp, varNamePtr);
11176 if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
11177 Jim_SetEmptyResult(interp);
11178 return JIM_OK;
11181 return retval;
11184 /* [loop] */
11185 static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11187 int retval;
11188 jim_wide i;
11189 jim_wide limit;
11190 jim_wide incr = 1;
11191 Jim_Obj *bodyObjPtr;
11193 if (argc != 5 && argc != 6) {
11194 Jim_WrongNumArgs(interp, 1, argv, "var first limit ?incr? body");
11195 return JIM_ERR;
11198 if (Jim_GetWide(interp, argv[2], &i) != JIM_OK ||
11199 Jim_GetWide(interp, argv[3], &limit) != JIM_OK ||
11200 (argc == 6 && Jim_GetWide(interp, argv[4], &incr) != JIM_OK)) {
11201 return JIM_ERR;
11203 bodyObjPtr = (argc == 5) ? argv[4] : argv[5];
11205 retval = Jim_SetVariable(interp, argv[1], argv[2]);
11207 while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
11208 retval = Jim_EvalObj(interp, bodyObjPtr);
11209 if (retval == JIM_OK || retval == JIM_CONTINUE) {
11210 Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
11212 retval = JIM_OK;
11214 /* Increment */
11215 i += incr;
11217 if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
11218 if (argv[1]->typePtr != &variableObjType) {
11219 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11220 return JIM_ERR;
11223 JimWideValue(objPtr) = i;
11224 Jim_InvalidateStringRep(objPtr);
11226 /* The following step is required in order to invalidate the
11227 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11228 if (argv[1]->typePtr != &variableObjType) {
11229 if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
11230 retval = JIM_ERR;
11231 break;
11235 else {
11236 objPtr = Jim_NewIntObj(interp, i);
11237 retval = Jim_SetVariable(interp, argv[1], objPtr);
11238 if (retval != JIM_OK) {
11239 Jim_FreeNewObj(interp, objPtr);
11245 if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
11246 Jim_SetEmptyResult(interp);
11247 return JIM_OK;
11249 return retval;
11252 /* foreach + lmap implementation. */
11253 static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
11255 int result = JIM_ERR, i, nbrOfLists, *listsIdx, *listsEnd;
11256 int nbrOfLoops = 0;
11257 Jim_Obj *emptyStr, *script, *mapRes = NULL;
11259 if (argc < 4 || argc % 2 != 0) {
11260 Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
11261 return JIM_ERR;
11263 if (doMap) {
11264 mapRes = Jim_NewListObj(interp, NULL, 0);
11265 Jim_IncrRefCount(mapRes);
11267 emptyStr = Jim_NewEmptyStringObj(interp);
11268 Jim_IncrRefCount(emptyStr);
11269 script = argv[argc - 1]; /* Last argument is a script */
11270 nbrOfLists = (argc - 1 - 1) / 2; /* argc - 'foreach' - script */
11271 listsIdx = (int *)Jim_Alloc(nbrOfLists * sizeof(int));
11272 listsEnd = (int *)Jim_Alloc(nbrOfLists * 2 * sizeof(int));
11273 /* Initialize iterators and remember max nbr elements each list */
11274 memset(listsIdx, 0, nbrOfLists * sizeof(int));
11275 /* Remember lengths of all lists and calculate how much rounds to loop */
11276 for (i = 0; i < nbrOfLists * 2; i += 2) {
11277 div_t cnt;
11278 int count;
11280 listsEnd[i] = Jim_ListLength(interp, argv[i + 1]);
11281 listsEnd[i + 1] = Jim_ListLength(interp, argv[i + 2]);
11282 if (listsEnd[i] == 0) {
11283 Jim_SetResultString(interp, "foreach varlist is empty", -1);
11284 goto err;
11286 cnt = div(listsEnd[i + 1], listsEnd[i]);
11287 count = cnt.quot + (cnt.rem ? 1 : 0);
11288 if (count > nbrOfLoops)
11289 nbrOfLoops = count;
11291 for (; nbrOfLoops-- > 0;) {
11292 for (i = 0; i < nbrOfLists; ++i) {
11293 int varIdx = 0, var = i * 2;
11295 while (varIdx < listsEnd[var]) {
11296 Jim_Obj *varName, *ele;
11297 int lst = i * 2 + 1;
11299 /* List index operations below can't fail */
11300 Jim_ListIndex(interp, argv[var + 1], varIdx, &varName, JIM_NONE);
11301 if (listsIdx[i] < listsEnd[lst]) {
11302 Jim_ListIndex(interp, argv[lst + 1], listsIdx[i], &ele, JIM_NONE);
11303 /* Avoid shimmering */
11304 Jim_IncrRefCount(ele);
11305 result = Jim_SetVariable(interp, varName, ele);
11306 Jim_DecrRefCount(interp, ele);
11307 if (result == JIM_OK) {
11308 ++listsIdx[i]; /* Remember next iterator of current list */
11309 ++varIdx; /* Next variable */
11310 continue;
11313 else if (Jim_SetVariable(interp, varName, emptyStr) == JIM_OK) {
11314 ++varIdx; /* Next variable */
11315 continue;
11317 goto err;
11320 switch (result = Jim_EvalObj(interp, script)) {
11321 case JIM_OK:
11322 if (doMap)
11323 Jim_ListAppendElement(interp, mapRes, interp->result);
11324 break;
11325 case JIM_CONTINUE:
11326 break;
11327 case JIM_BREAK:
11328 goto out;
11329 break;
11330 default:
11331 goto err;
11334 out:
11335 result = JIM_OK;
11336 if (doMap)
11337 Jim_SetResult(interp, mapRes);
11338 else
11339 Jim_SetEmptyResult(interp);
11340 err:
11341 if (doMap)
11342 Jim_DecrRefCount(interp, mapRes);
11343 Jim_DecrRefCount(interp, emptyStr);
11344 Jim_Free(listsIdx);
11345 Jim_Free(listsEnd);
11346 return result;
11349 /* [foreach] */
11350 static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11352 return JimForeachMapHelper(interp, argc, argv, 0);
11355 /* [lmap] */
11356 static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11358 return JimForeachMapHelper(interp, argc, argv, 1);
11361 /* [if] */
11362 static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11364 int boolean, retval, current = 1, falsebody = 0;
11366 if (argc >= 3) {
11367 while (1) {
11368 /* Far not enough arguments given! */
11369 if (current >= argc)
11370 goto err;
11371 if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
11372 != JIM_OK)
11373 return retval;
11374 /* There lacks something, isn't it? */
11375 if (current >= argc)
11376 goto err;
11377 if (Jim_CompareStringImmediate(interp, argv[current], "then"))
11378 current++;
11379 /* Tsk tsk, no then-clause? */
11380 if (current >= argc)
11381 goto err;
11382 if (boolean)
11383 return Jim_EvalObj(interp, argv[current]);
11384 /* Ok: no else-clause follows */
11385 if (++current >= argc) {
11386 Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
11387 return JIM_OK;
11389 falsebody = current++;
11390 if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
11391 /* IIICKS - else-clause isn't last cmd? */
11392 if (current != argc - 1)
11393 goto err;
11394 return Jim_EvalObj(interp, argv[current]);
11396 else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
11397 /* Ok: elseif follows meaning all the stuff
11398 * again (how boring...) */
11399 continue;
11400 /* OOPS - else-clause is not last cmd? */
11401 else if (falsebody != argc - 1)
11402 goto err;
11403 return Jim_EvalObj(interp, argv[falsebody]);
11405 return JIM_OK;
11407 err:
11408 Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11409 return JIM_ERR;
11413 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11414 int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
11415 Jim_Obj *stringObj, int nocase)
11417 Jim_Obj *parms[4];
11418 int argc = 0;
11419 long eq;
11420 int rc;
11422 parms[argc++] = commandObj;
11423 if (nocase) {
11424 parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
11426 parms[argc++] = patternObj;
11427 parms[argc++] = stringObj;
11429 rc = Jim_EvalObjVector(interp, argc, parms);
11431 if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
11432 eq = -rc;
11435 return eq;
11438 enum
11439 { SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
11441 /* [switch] */
11442 static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11444 int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
11445 Jim_Obj *command = 0, *const *caseList = 0, *strObj;
11446 Jim_Obj *script = 0;
11448 if (argc < 3) {
11449 wrongnumargs:
11450 Jim_WrongNumArgs(interp, 1, argv, "?options? string "
11451 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11452 return JIM_ERR;
11454 for (opt = 1; opt < argc; ++opt) {
11455 const char *option = Jim_GetString(argv[opt], 0);
11457 if (*option != '-')
11458 break;
11459 else if (strncmp(option, "--", 2) == 0) {
11460 ++opt;
11461 break;
11463 else if (strncmp(option, "-exact", 2) == 0)
11464 matchOpt = SWITCH_EXACT;
11465 else if (strncmp(option, "-glob", 2) == 0)
11466 matchOpt = SWITCH_GLOB;
11467 else if (strncmp(option, "-regexp", 2) == 0)
11468 matchOpt = SWITCH_RE;
11469 else if (strncmp(option, "-command", 2) == 0) {
11470 matchOpt = SWITCH_CMD;
11471 if ((argc - opt) < 2)
11472 goto wrongnumargs;
11473 command = argv[++opt];
11475 else {
11476 Jim_SetResultFormatted(interp,
11477 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11478 argv[opt]);
11479 return JIM_ERR;
11481 if ((argc - opt) < 2)
11482 goto wrongnumargs;
11484 strObj = argv[opt++];
11485 patCount = argc - opt;
11486 if (patCount == 1) {
11487 Jim_Obj **vector;
11489 JimListGetElements(interp, argv[opt], &patCount, &vector);
11490 caseList = vector;
11492 else
11493 caseList = &argv[opt];
11494 if (patCount == 0 || patCount % 2 != 0)
11495 goto wrongnumargs;
11496 for (i = 0; script == 0 && i < patCount; i += 2) {
11497 Jim_Obj *patObj = caseList[i];
11499 if (!Jim_CompareStringImmediate(interp, patObj, "default")
11500 || i < (patCount - 2)) {
11501 switch (matchOpt) {
11502 case SWITCH_EXACT:
11503 if (Jim_StringEqObj(strObj, patObj))
11504 script = caseList[i + 1];
11505 break;
11506 case SWITCH_GLOB:
11507 if (Jim_StringMatchObj(interp, patObj, strObj, 0))
11508 script = caseList[i + 1];
11509 break;
11510 case SWITCH_RE:
11511 command = Jim_NewStringObj(interp, "regexp", -1);
11512 /* Fall thru intentionally */
11513 case SWITCH_CMD:{
11514 int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, 0);
11516 /* After the execution of a command we need to
11517 * make sure to reconvert the object into a list
11518 * again. Only for the single-list style [switch]. */
11519 if (argc - opt == 1) {
11520 Jim_Obj **vector;
11522 JimListGetElements(interp, argv[opt], &patCount, &vector);
11523 caseList = vector;
11525 /* command is here already decref'd */
11526 if (rc < 0) {
11527 return -rc;
11529 if (rc)
11530 script = caseList[i + 1];
11531 break;
11535 else {
11536 script = caseList[i + 1];
11539 for (; i < patCount && Jim_CompareStringImmediate(interp, script, "-"); i += 2)
11540 script = caseList[i + 1];
11541 if (script && Jim_CompareStringImmediate(interp, script, "-")) {
11542 Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
11543 return JIM_ERR;
11545 Jim_SetEmptyResult(interp);
11546 if (script) {
11547 return Jim_EvalObj(interp, script);
11549 return JIM_OK;
11552 /* [list] */
11553 static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11555 Jim_Obj *listObjPtr;
11557 listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
11558 Jim_SetResult(interp, listObjPtr);
11559 return JIM_OK;
11562 /* [lindex] */
11563 static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11565 Jim_Obj *objPtr, *listObjPtr;
11566 int i;
11567 int idx;
11569 if (argc < 3) {
11570 Jim_WrongNumArgs(interp, 1, argv, "list index ?...?");
11571 return JIM_ERR;
11573 objPtr = argv[1];
11574 Jim_IncrRefCount(objPtr);
11575 for (i = 2; i < argc; i++) {
11576 listObjPtr = objPtr;
11577 if (Jim_GetIndex(interp, argv[i], &idx) != JIM_OK) {
11578 Jim_DecrRefCount(interp, listObjPtr);
11579 return JIM_ERR;
11581 if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_NONE) != JIM_OK) {
11582 /* Returns an empty object if the index
11583 * is out of range. */
11584 Jim_DecrRefCount(interp, listObjPtr);
11585 Jim_SetEmptyResult(interp);
11586 return JIM_OK;
11588 Jim_IncrRefCount(objPtr);
11589 Jim_DecrRefCount(interp, listObjPtr);
11591 Jim_SetResult(interp, objPtr);
11592 Jim_DecrRefCount(interp, objPtr);
11593 return JIM_OK;
11596 /* [llength] */
11597 static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11599 if (argc != 2) {
11600 Jim_WrongNumArgs(interp, 1, argv, "list");
11601 return JIM_ERR;
11603 Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
11604 return JIM_OK;
11607 /* [lsearch] */
11608 static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11610 static const char * const options[] = {
11611 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11612 NULL
11614 enum
11615 { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
11616 OPT_COMMAND };
11617 int i;
11618 int opt_bool = 0;
11619 int opt_not = 0;
11620 int opt_nocase = 0;
11621 int opt_all = 0;
11622 int opt_inline = 0;
11623 int opt_match = OPT_EXACT;
11624 int listlen;
11625 int rc = JIM_OK;
11626 Jim_Obj *listObjPtr = NULL;
11627 Jim_Obj *commandObj = NULL;
11629 if (argc < 3) {
11630 wrongargs:
11631 Jim_WrongNumArgs(interp, 1, argv,
11632 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11633 return JIM_ERR;
11636 for (i = 1; i < argc - 2; i++) {
11637 int option;
11639 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
11640 return JIM_ERR;
11642 switch (option) {
11643 case OPT_BOOL:
11644 opt_bool = 1;
11645 opt_inline = 0;
11646 break;
11647 case OPT_NOT:
11648 opt_not = 1;
11649 break;
11650 case OPT_NOCASE:
11651 opt_nocase = 1;
11652 break;
11653 case OPT_INLINE:
11654 opt_inline = 1;
11655 opt_bool = 0;
11656 break;
11657 case OPT_ALL:
11658 opt_all = 1;
11659 break;
11660 case OPT_COMMAND:
11661 if (i >= argc - 2) {
11662 goto wrongargs;
11664 commandObj = argv[++i];
11665 /* fallthru */
11666 case OPT_EXACT:
11667 case OPT_GLOB:
11668 case OPT_REGEXP:
11669 opt_match = option;
11670 break;
11674 argv += i;
11676 if (opt_all) {
11677 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11679 if (opt_match == OPT_REGEXP) {
11680 commandObj = Jim_NewStringObj(interp, "regexp", -1);
11682 if (commandObj) {
11683 Jim_IncrRefCount(commandObj);
11686 listlen = Jim_ListLength(interp, argv[0]);
11687 for (i = 0; i < listlen; i++) {
11688 Jim_Obj *objPtr;
11689 int eq = 0;
11691 Jim_ListIndex(interp, argv[0], i, &objPtr, JIM_NONE);
11692 switch (opt_match) {
11693 case OPT_EXACT:
11694 eq = Jim_StringCompareObj(interp, objPtr, argv[1], opt_nocase) == 0;
11695 break;
11697 case OPT_GLOB:
11698 eq = Jim_StringMatchObj(interp, argv[1], objPtr, opt_nocase);
11699 break;
11701 case OPT_REGEXP:
11702 case OPT_COMMAND:
11703 eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, opt_nocase);
11704 if (eq < 0) {
11705 if (listObjPtr) {
11706 Jim_FreeNewObj(interp, listObjPtr);
11708 rc = JIM_ERR;
11709 goto done;
11711 break;
11714 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11715 if (!eq && opt_bool && opt_not && !opt_all) {
11716 continue;
11719 if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
11720 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11721 Jim_Obj *resultObj;
11723 if (opt_bool) {
11724 resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
11726 else if (!opt_inline) {
11727 resultObj = Jim_NewIntObj(interp, i);
11729 else {
11730 resultObj = objPtr;
11733 if (opt_all) {
11734 Jim_ListAppendElement(interp, listObjPtr, resultObj);
11736 else {
11737 Jim_SetResult(interp, resultObj);
11738 goto done;
11743 if (opt_all) {
11744 Jim_SetResult(interp, listObjPtr);
11746 else {
11747 /* No match */
11748 if (opt_bool) {
11749 Jim_SetResultBool(interp, opt_not);
11751 else if (!opt_inline) {
11752 Jim_SetResultInt(interp, -1);
11756 done:
11757 if (commandObj) {
11758 Jim_DecrRefCount(interp, commandObj);
11760 return rc;
11763 /* [lappend] */
11764 static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11766 Jim_Obj *listObjPtr;
11767 int shared, i;
11769 if (argc < 2) {
11770 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
11771 return JIM_ERR;
11773 listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
11774 if (!listObjPtr) {
11775 /* Create the list if it does not exists */
11776 listObjPtr = Jim_NewListObj(interp, NULL, 0);
11777 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11778 Jim_FreeNewObj(interp, listObjPtr);
11779 return JIM_ERR;
11782 shared = Jim_IsShared(listObjPtr);
11783 if (shared)
11784 listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
11785 for (i = 2; i < argc; i++)
11786 Jim_ListAppendElement(interp, listObjPtr, argv[i]);
11787 if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
11788 if (shared)
11789 Jim_FreeNewObj(interp, listObjPtr);
11790 return JIM_ERR;
11792 Jim_SetResult(interp, listObjPtr);
11793 return JIM_OK;
11796 /* [linsert] */
11797 static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11799 int idx, len;
11800 Jim_Obj *listPtr;
11802 if (argc < 4) {
11803 Jim_WrongNumArgs(interp, 1, argv, "list index element " "?element ...?");
11804 return JIM_ERR;
11806 listPtr = argv[1];
11807 if (Jim_IsShared(listPtr))
11808 listPtr = Jim_DuplicateObj(interp, listPtr);
11809 if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
11810 goto err;
11811 len = Jim_ListLength(interp, listPtr);
11812 if (idx >= len)
11813 idx = len;
11814 else if (idx < 0)
11815 idx = len + idx + 1;
11816 Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
11817 Jim_SetResult(interp, listPtr);
11818 return JIM_OK;
11819 err:
11820 if (listPtr != argv[1]) {
11821 Jim_FreeNewObj(interp, listPtr);
11823 return JIM_ERR;
11826 /* [lreplace] */
11827 static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11829 int first, last, len, rangeLen;
11830 Jim_Obj *listObj;
11831 Jim_Obj *newListObj;
11832 int i;
11833 int shared;
11835 if (argc < 4) {
11836 Jim_WrongNumArgs(interp, 1, argv, "list first last ?element element ...?");
11837 return JIM_ERR;
11839 if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
11840 Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
11841 return JIM_ERR;
11844 listObj = argv[1];
11845 len = Jim_ListLength(interp, listObj);
11847 first = JimRelToAbsIndex(len, first);
11848 last = JimRelToAbsIndex(len, last);
11849 JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
11851 /* Now construct a new list which consists of:
11852 * <elements before first> <supplied elements> <elements after last>
11855 /* Check to see if trying to replace past the end of the list */
11856 if (first < len) {
11857 /* OK. Not past the end */
11859 else if (len == 0) {
11860 /* Special for empty list, adjust first to 0 */
11861 first = 0;
11863 else {
11864 Jim_SetResultString(interp, "list doesn't contain element ", -1);
11865 Jim_AppendObj(interp, Jim_GetResult(interp), argv[2]);
11866 return JIM_ERR;
11869 newListObj = Jim_NewListObj(interp, NULL, 0);
11871 shared = Jim_IsShared(listObj);
11872 if (shared) {
11873 listObj = Jim_DuplicateObj(interp, listObj);
11876 /* Add the first set of elements */
11877 for (i = 0; i < first; i++) {
11878 Jim_ListAppendElement(interp, newListObj, listObj->internalRep.listValue.ele[i]);
11881 /* Add supplied elements */
11882 for (i = 4; i < argc; i++) {
11883 Jim_ListAppendElement(interp, newListObj, argv[i]);
11886 /* Add the remaining elements */
11887 for (i = first + rangeLen; i < len; i++) {
11888 Jim_ListAppendElement(interp, newListObj, listObj->internalRep.listValue.ele[i]);
11890 Jim_SetResult(interp, newListObj);
11891 if (shared) {
11892 Jim_FreeNewObj(interp, listObj);
11894 return JIM_OK;
11897 /* [lset] */
11898 static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11900 if (argc < 3) {
11901 Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");
11902 return JIM_ERR;
11904 else if (argc == 3) {
11905 if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
11906 return JIM_ERR;
11907 Jim_SetResult(interp, argv[2]);
11908 return JIM_OK;
11910 if (Jim_SetListIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1])
11911 == JIM_ERR)
11912 return JIM_ERR;
11913 return JIM_OK;
11916 /* [lsort] */
11917 static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
11919 static const char * const options[] = {
11920 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11922 enum
11923 { OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_INDEX };
11924 Jim_Obj *resObj;
11925 int i;
11926 int retCode;
11928 struct lsort_info info;
11930 if (argc < 2) {
11931 Jim_WrongNumArgs(interp, 1, argv, "?options? list");
11932 return JIM_ERR;
11935 info.type = JIM_LSORT_ASCII;
11936 info.order = 1;
11937 info.indexed = 0;
11938 info.command = NULL;
11939 info.interp = interp;
11941 for (i = 1; i < (argc - 1); i++) {
11942 int option;
11944 if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG)
11945 != JIM_OK)
11946 return JIM_ERR;
11947 switch (option) {
11948 case OPT_ASCII:
11949 info.type = JIM_LSORT_ASCII;
11950 break;
11951 case OPT_NOCASE:
11952 info.type = JIM_LSORT_NOCASE;
11953 break;
11954 case OPT_INTEGER:
11955 info.type = JIM_LSORT_INTEGER;
11956 break;
11957 case OPT_INCREASING:
11958 info.order = 1;
11959 break;
11960 case OPT_DECREASING:
11961 info.order = -1;
11962 break;
11963 case OPT_COMMAND:
11964 if (i >= (argc - 2)) {
11965 Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
11966 return JIM_ERR;
11968 info.type = JIM_LSORT_COMMAND;
11969 info.command = argv[i + 1];
11970 i++;
11971 break;
11972 case OPT_INDEX:
11973 if (i >= (argc - 2)) {
11974 Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
11975 return JIM_ERR;
11977 if (Jim_GetIndex(interp, argv[i + 1], &info.index) != JIM_OK) {
11978 return JIM_ERR;
11980 info.indexed = 1;
11981 i++;
11982 break;
11985 resObj = Jim_DuplicateObj(interp, argv[argc - 1]);
11986 retCode = ListSortElements(interp, resObj, &info);
11987 if (retCode == JIM_OK) {
11988 Jim_SetResult(interp, resObj);
11990 else {
11991 Jim_FreeNewObj(interp, resObj);
11993 return retCode;
11996 /* [append] */
11997 static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
11999 Jim_Obj *stringObjPtr;
12000 int i;
12002 if (argc < 2) {
12003 Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
12004 return JIM_ERR;
12006 if (argc == 2) {
12007 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
12008 if (!stringObjPtr)
12009 return JIM_ERR;
12011 else {
12012 int freeobj = 0;
12013 stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
12014 if (!stringObjPtr) {
12015 /* Create the string if it doesn't exist */
12016 stringObjPtr = Jim_NewEmptyStringObj(interp);
12017 freeobj = 1;
12019 else if (Jim_IsShared(stringObjPtr)) {
12020 freeobj = 1;
12021 stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
12023 for (i = 2; i < argc; i++) {
12024 Jim_AppendObj(interp, stringObjPtr, argv[i]);
12026 if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
12027 if (freeobj) {
12028 Jim_FreeNewObj(interp, stringObjPtr);
12030 return JIM_ERR;
12033 Jim_SetResult(interp, stringObjPtr);
12034 return JIM_OK;
12037 /* [debug] */
12038 static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12040 #ifdef JIM_DEBUG_COMMAND
12041 static const char * const options[] = {
12042 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12043 "exprbc", "show",
12044 NULL
12046 enum
12048 OPT_REFCOUNT, OPT_OBJCOUNT, OPT_OBJECTS, OPT_INVSTR, OPT_SCRIPTLEN,
12049 OPT_EXPRLEN, OPT_EXPRBC, OPT_SHOW,
12051 int option;
12053 if (argc < 2) {
12054 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?...?");
12055 return JIM_ERR;
12057 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK)
12058 return JIM_ERR;
12059 if (option == OPT_REFCOUNT) {
12060 if (argc != 3) {
12061 Jim_WrongNumArgs(interp, 2, argv, "object");
12062 return JIM_ERR;
12064 Jim_SetResultInt(interp, argv[2]->refCount);
12065 return JIM_OK;
12067 else if (option == OPT_OBJCOUNT) {
12068 int freeobj = 0, liveobj = 0;
12069 char buf[256];
12070 Jim_Obj *objPtr;
12072 if (argc != 2) {
12073 Jim_WrongNumArgs(interp, 2, argv, "");
12074 return JIM_ERR;
12076 /* Count the number of free objects. */
12077 objPtr = interp->freeList;
12078 while (objPtr) {
12079 freeobj++;
12080 objPtr = objPtr->nextObjPtr;
12082 /* Count the number of live objects. */
12083 objPtr = interp->liveList;
12084 while (objPtr) {
12085 liveobj++;
12086 objPtr = objPtr->nextObjPtr;
12088 /* Set the result string and return. */
12089 sprintf(buf, "free %d used %d", freeobj, liveobj);
12090 Jim_SetResultString(interp, buf, -1);
12091 return JIM_OK;
12093 else if (option == OPT_OBJECTS) {
12094 Jim_Obj *objPtr, *listObjPtr, *subListObjPtr;
12096 /* Count the number of live objects. */
12097 objPtr = interp->liveList;
12098 listObjPtr = Jim_NewListObj(interp, NULL, 0);
12099 while (objPtr) {
12100 char buf[128];
12101 const char *type = objPtr->typePtr ? objPtr->typePtr->name : "";
12103 subListObjPtr = Jim_NewListObj(interp, NULL, 0);
12104 sprintf(buf, "%p", objPtr);
12105 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, buf, -1));
12106 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewStringObj(interp, type, -1));
12107 Jim_ListAppendElement(interp, subListObjPtr, Jim_NewIntObj(interp, objPtr->refCount));
12108 Jim_ListAppendElement(interp, subListObjPtr, objPtr);
12109 Jim_ListAppendElement(interp, listObjPtr, subListObjPtr);
12110 objPtr = objPtr->nextObjPtr;
12112 Jim_SetResult(interp, listObjPtr);
12113 return JIM_OK;
12115 else if (option == OPT_INVSTR) {
12116 Jim_Obj *objPtr;
12118 if (argc != 3) {
12119 Jim_WrongNumArgs(interp, 2, argv, "object");
12120 return JIM_ERR;
12122 objPtr = argv[2];
12123 if (objPtr->typePtr != NULL)
12124 Jim_InvalidateStringRep(objPtr);
12125 Jim_SetEmptyResult(interp);
12126 return JIM_OK;
12128 else if (option == OPT_SHOW) {
12129 const char *s;
12130 int len, charlen;
12132 if (argc != 3) {
12133 Jim_WrongNumArgs(interp, 2, argv, "object");
12134 return JIM_ERR;
12136 s = Jim_GetString(argv[2], &len);
12137 charlen = Jim_Utf8Length(interp, argv[2]);
12138 printf("refcount: %d, type: %s\n", argv[2]->refCount, JimObjTypeName(argv[2]));
12139 printf("chars (%d): <<%s>>\n", charlen, s);
12140 printf("bytes (%d):", len);
12141 while (len--) {
12142 printf(" %02x", (unsigned char)*s++);
12144 printf("\n");
12145 return JIM_OK;
12147 else if (option == OPT_SCRIPTLEN) {
12148 ScriptObj *script;
12150 if (argc != 3) {
12151 Jim_WrongNumArgs(interp, 2, argv, "script");
12152 return JIM_ERR;
12154 script = Jim_GetScript(interp, argv[2]);
12155 Jim_SetResultInt(interp, script->len);
12156 return JIM_OK;
12158 else if (option == OPT_EXPRLEN) {
12159 ExprByteCode *expr;
12161 if (argc != 3) {
12162 Jim_WrongNumArgs(interp, 2, argv, "expression");
12163 return JIM_ERR;
12165 expr = JimGetExpression(interp, argv[2]);
12166 if (expr == NULL)
12167 return JIM_ERR;
12168 Jim_SetResultInt(interp, expr->len);
12169 return JIM_OK;
12171 else if (option == OPT_EXPRBC) {
12172 Jim_Obj *objPtr;
12173 ExprByteCode *expr;
12174 int i;
12176 if (argc != 3) {
12177 Jim_WrongNumArgs(interp, 2, argv, "expression");
12178 return JIM_ERR;
12180 expr = JimGetExpression(interp, argv[2]);
12181 if (expr == NULL)
12182 return JIM_ERR;
12183 objPtr = Jim_NewListObj(interp, NULL, 0);
12184 for (i = 0; i < expr->len; i++) {
12185 const char *type;
12186 const Jim_ExprOperator *op;
12187 Jim_Obj *obj = expr->token[i].objPtr;
12189 switch (expr->token[i].type) {
12190 case JIM_TT_EXPR_INT:
12191 type = "int";
12192 break;
12193 case JIM_TT_EXPR_DOUBLE:
12194 type = "double";
12195 break;
12196 case JIM_TT_CMD:
12197 type = "command";
12198 break;
12199 case JIM_TT_VAR:
12200 type = "variable";
12201 break;
12202 case JIM_TT_DICTSUGAR:
12203 type = "dictsugar";
12204 break;
12205 case JIM_TT_EXPRSUGAR:
12206 type = "exprsugar";
12207 break;
12208 case JIM_TT_ESC:
12209 type = "subst";
12210 break;
12211 case JIM_TT_STR:
12212 type = "string";
12213 break;
12214 default:
12215 op = JimExprOperatorInfoByOpcode(expr->token[i].type);
12216 if (op == NULL) {
12217 type = "private";
12219 else {
12220 type = "operator";
12222 obj = Jim_NewStringObj(interp, op ? op->name : "", -1);
12223 break;
12225 Jim_ListAppendElement(interp, objPtr, Jim_NewStringObj(interp, type, -1));
12226 Jim_ListAppendElement(interp, objPtr, obj);
12228 Jim_SetResult(interp, objPtr);
12229 return JIM_OK;
12231 else {
12232 Jim_SetResultString(interp,
12233 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12234 return JIM_ERR;
12236 /* unreached */
12237 #else
12238 Jim_SetResultString(interp, "unsupported", -1);
12239 return JIM_ERR;
12240 #endif
12243 /* [eval] */
12244 static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12246 int rc;
12248 if (argc < 2) {
12249 Jim_WrongNumArgs(interp, 1, argv, "script ?...?");
12250 return JIM_ERR;
12253 if (argc == 2) {
12254 rc = Jim_EvalObj(interp, argv[1]);
12256 else {
12257 rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12260 if (rc == JIM_ERR) {
12261 /* eval is "interesting", so add a stack frame here */
12262 interp->addStackTrace++;
12264 return rc;
12267 /* [uplevel] */
12268 static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12270 if (argc >= 2) {
12271 int retcode;
12272 Jim_CallFrame *savedCallFrame, *targetCallFrame;
12273 Jim_Obj *objPtr;
12274 const char *str;
12276 /* Save the old callframe pointer */
12277 savedCallFrame = interp->framePtr;
12279 /* Lookup the target frame pointer */
12280 str = Jim_String(argv[1]);
12281 if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
12282 targetCallFrame =Jim_GetCallFrameByLevel(interp, argv[1]);
12283 argc--;
12284 argv++;
12286 else {
12287 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12289 if (targetCallFrame == NULL) {
12290 return JIM_ERR;
12292 if (argc < 2) {
12293 argv--;
12294 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12295 return JIM_ERR;
12297 /* Eval the code in the target callframe. */
12298 interp->framePtr = targetCallFrame;
12299 if (argc == 2) {
12300 retcode = Jim_EvalObj(interp, argv[1]);
12302 else {
12303 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12304 Jim_IncrRefCount(objPtr);
12305 retcode = Jim_EvalObj(interp, objPtr);
12306 Jim_DecrRefCount(interp, objPtr);
12308 interp->framePtr = savedCallFrame;
12309 return retcode;
12311 else {
12312 Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
12313 return JIM_ERR;
12317 /* [expr] */
12318 static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12320 Jim_Obj *exprResultPtr;
12321 int retcode;
12323 if (argc == 2) {
12324 retcode = Jim_EvalExpression(interp, argv[1], &exprResultPtr);
12326 else if (argc > 2) {
12327 Jim_Obj *objPtr;
12329 objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
12330 Jim_IncrRefCount(objPtr);
12331 retcode = Jim_EvalExpression(interp, objPtr, &exprResultPtr);
12332 Jim_DecrRefCount(interp, objPtr);
12334 else {
12335 Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
12336 return JIM_ERR;
12338 if (retcode != JIM_OK)
12339 return retcode;
12340 Jim_SetResult(interp, exprResultPtr);
12341 Jim_DecrRefCount(interp, exprResultPtr);
12342 return JIM_OK;
12345 /* [break] */
12346 static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12348 if (argc != 1) {
12349 Jim_WrongNumArgs(interp, 1, argv, "");
12350 return JIM_ERR;
12352 return JIM_BREAK;
12355 /* [continue] */
12356 static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12358 if (argc != 1) {
12359 Jim_WrongNumArgs(interp, 1, argv, "");
12360 return JIM_ERR;
12362 return JIM_CONTINUE;
12365 /* [return] */
12366 static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12368 int i;
12369 Jim_Obj *stackTraceObj = NULL;
12370 Jim_Obj *errorCodeObj = NULL;
12371 int returnCode = JIM_OK;
12372 long level = 1;
12374 for (i = 1; i < argc - 1; i += 2) {
12375 if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
12376 if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
12377 return JIM_ERR;
12380 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
12381 stackTraceObj = argv[i + 1];
12383 else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
12384 errorCodeObj = argv[i + 1];
12386 else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
12387 if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
12388 Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
12389 return JIM_ERR;
12392 else {
12393 break;
12397 if (i != argc - 1 && i != argc) {
12398 Jim_WrongNumArgs(interp, 1, argv,
12399 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12402 /* If a stack trace is supplied and code is error, set the stack trace */
12403 if (stackTraceObj && returnCode == JIM_ERR) {
12404 JimSetStackTrace(interp, stackTraceObj);
12406 /* If an error code list is supplied, set the global $errorCode */
12407 if (errorCodeObj && returnCode == JIM_ERR) {
12408 Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
12410 interp->returnCode = returnCode;
12411 interp->returnLevel = level;
12413 if (i == argc - 1) {
12414 Jim_SetResult(interp, argv[i]);
12416 return JIM_RETURN;
12419 /* [tailcall] */
12420 static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12422 Jim_Obj *objPtr;
12424 objPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
12425 Jim_SetResult(interp, objPtr);
12426 return JIM_EVAL;
12429 /* [proc] */
12430 static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12432 if (argc != 4 && argc != 5) {
12433 Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
12434 return JIM_ERR;
12437 if (argc == 4) {
12438 return JimCreateProcedure(interp, argv[1], argv[2], NULL, argv[3]);
12440 else {
12441 return JimCreateProcedure(interp, argv[1], argv[2], argv[3], argv[4]);
12445 /* [local] */
12446 static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12448 int retcode;
12450 /* Evaluate the arguments with 'local' in force */
12451 interp->local++;
12452 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12453 interp->local--;
12456 /* If OK, and the result is a proc, add it to the list of local procs */
12457 if (retcode == 0) {
12458 const char *procname = Jim_String(Jim_GetResult(interp));
12460 if (Jim_FindHashEntry(&interp->commands, procname) == NULL) {
12461 Jim_SetResultFormatted(interp, "not a proc: \"%s\"", procname);
12462 return JIM_ERR;
12464 if (interp->localProcs == NULL) {
12465 interp->localProcs = Jim_Alloc(sizeof(*interp->localProcs));
12466 Jim_InitStack(interp->localProcs);
12468 Jim_StackPush(interp->localProcs, Jim_StrDup(procname));
12471 return retcode;
12474 /* [upcall] */
12475 static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12477 if (argc < 2) {
12478 Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
12479 return JIM_ERR;
12481 else {
12482 int retcode;
12484 Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
12485 if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->u.proc.prevCmd) {
12486 Jim_SetResultFormatted(interp, "no previous proc: \"%#s\"", argv[1]);
12487 return JIM_ERR;
12489 /* OK. Mark this command as being in an upcall */
12490 cmdPtr->u.proc.upcall++;
12491 JimIncrCmdRefCount(cmdPtr);
12493 /* Invoke the command as normal */
12494 retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
12496 /* No longer in an upcall */
12497 cmdPtr->u.proc.upcall--;
12498 JimDecrCmdRefCount(interp, cmdPtr);
12500 return retcode;
12504 /* [concat] */
12505 static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12507 Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
12508 return JIM_OK;
12511 /* [upvar] */
12512 static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12514 int i;
12515 Jim_CallFrame *targetCallFrame;
12517 /* Lookup the target frame pointer */
12518 if (argc > 3 && (argc % 2 == 0)) {
12519 targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
12520 argc--;
12521 argv++;
12523 else {
12524 targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
12526 if (targetCallFrame == NULL) {
12527 return JIM_ERR;
12530 /* Check for arity */
12531 if (argc < 3) {
12532 Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
12533 return JIM_ERR;
12536 /* Now... for every other/local couple: */
12537 for (i = 1; i < argc; i += 2) {
12538 if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
12539 return JIM_ERR;
12541 return JIM_OK;
12544 /* [global] */
12545 static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12547 int i;
12549 if (argc < 2) {
12550 Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
12551 return JIM_ERR;
12553 /* Link every var to the toplevel having the same name */
12554 if (interp->framePtr->level == 0)
12555 return JIM_OK; /* global at toplevel... */
12556 for (i = 1; i < argc; i++) {
12557 if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
12558 return JIM_ERR;
12560 return JIM_OK;
12563 /* does the [string map] operation. On error NULL is returned,
12564 * otherwise a new string object with the result, having refcount = 0,
12565 * is returned. */
12566 static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
12567 Jim_Obj *objPtr, int nocase)
12569 int numMaps;
12570 const char *str, *noMatchStart = NULL;
12571 int strLen, i;
12572 Jim_Obj *resultObjPtr;
12574 numMaps = Jim_ListLength(interp, mapListObjPtr);
12575 if (numMaps % 2) {
12576 Jim_SetResultString(interp, "list must contain an even number of elements", -1);
12577 return NULL;
12580 str = Jim_String(objPtr);
12581 strLen = Jim_Utf8Length(interp, objPtr);
12583 /* Map it */
12584 resultObjPtr = Jim_NewStringObj(interp, "", 0);
12585 while (strLen) {
12586 for (i = 0; i < numMaps; i += 2) {
12587 Jim_Obj *objPtr;
12588 const char *k;
12589 int kl;
12591 Jim_ListIndex(interp, mapListObjPtr, i, &objPtr, JIM_NONE);
12592 k = Jim_String(objPtr);
12593 kl = Jim_Utf8Length(interp, objPtr);
12595 if (strLen >= kl && kl) {
12596 int rc;
12597 if (nocase) {
12598 rc = JimStringCompareNoCase(str, k, kl);
12600 else {
12601 rc = JimStringCompare(str, kl, k, kl);
12603 if (rc == 0) {
12604 if (noMatchStart) {
12605 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12606 noMatchStart = NULL;
12608 Jim_ListIndex(interp, mapListObjPtr, i + 1, &objPtr, JIM_NONE);
12609 Jim_AppendObj(interp, resultObjPtr, objPtr);
12610 str += utf8_index(str, kl);
12611 strLen -= kl;
12612 break;
12616 if (i == numMaps) { /* no match */
12617 int c;
12618 if (noMatchStart == NULL)
12619 noMatchStart = str;
12620 str += utf8_tounicode(str, &c);
12621 strLen--;
12624 if (noMatchStart) {
12625 Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
12627 return resultObjPtr;
12630 /* [string] */
12631 static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12633 int len;
12634 int opt_case = 1;
12635 int option;
12636 static const char * const options[] = {
12637 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12638 "repeat", "reverse", "index", "first", "last",
12639 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12641 enum
12643 OPT_BYTELENGTH, OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_IS, OPT_BYTERANGE, OPT_RANGE, OPT_MAP,
12644 OPT_REPEAT, OPT_REVERSE, OPT_INDEX, OPT_FIRST, OPT_LAST,
12645 OPT_TRIM, OPT_TRIMLEFT, OPT_TRIMRIGHT, OPT_TOLOWER, OPT_TOUPPER
12647 static const char * const nocase_options[] = {
12648 "-nocase", NULL
12651 if (argc < 2) {
12652 Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
12653 return JIM_ERR;
12655 if (Jim_GetEnum(interp, argv[1], options, &option, NULL,
12656 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK)
12657 return JIM_ERR;
12659 switch (option) {
12660 case OPT_LENGTH:
12661 case OPT_BYTELENGTH:
12662 if (argc != 3) {
12663 Jim_WrongNumArgs(interp, 2, argv, "string");
12664 return JIM_ERR;
12666 if (option == OPT_LENGTH) {
12667 len = Jim_Utf8Length(interp, argv[2]);
12669 else {
12670 len = Jim_Length(argv[2]);
12672 Jim_SetResultInt(interp, len);
12673 return JIM_OK;
12675 case OPT_COMPARE:
12676 case OPT_EQUAL:
12677 if (argc != 4 &&
12678 (argc != 5 ||
12679 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12680 JIM_ENUM_ABBREV) != JIM_OK)) {
12681 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? string1 string2");
12682 return JIM_ERR;
12684 if (opt_case == 0) {
12685 argv++;
12687 if (option == OPT_COMPARE || !opt_case) {
12688 Jim_SetResultInt(interp, Jim_StringCompareObj(interp, argv[2], argv[3], !opt_case));
12690 else {
12691 Jim_SetResultBool(interp, Jim_StringEqObj(argv[2], argv[3]));
12693 return JIM_OK;
12695 case OPT_MATCH:
12696 if (argc != 4 &&
12697 (argc != 5 ||
12698 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12699 JIM_ENUM_ABBREV) != JIM_OK)) {
12700 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
12701 return JIM_ERR;
12703 if (opt_case == 0) {
12704 argv++;
12706 Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
12707 return JIM_OK;
12709 case OPT_MAP:{
12710 Jim_Obj *objPtr;
12712 if (argc != 4 &&
12713 (argc != 5 ||
12714 Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
12715 JIM_ENUM_ABBREV) != JIM_OK)) {
12716 Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
12717 return JIM_ERR;
12720 if (opt_case == 0) {
12721 argv++;
12723 objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
12724 if (objPtr == NULL) {
12725 return JIM_ERR;
12727 Jim_SetResult(interp, objPtr);
12728 return JIM_OK;
12731 case OPT_RANGE:
12732 case OPT_BYTERANGE:{
12733 Jim_Obj *objPtr;
12735 if (argc != 5) {
12736 Jim_WrongNumArgs(interp, 2, argv, "string first last");
12737 return JIM_ERR;
12739 if (option == OPT_RANGE) {
12740 objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
12742 else
12744 objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
12747 if (objPtr == NULL) {
12748 return JIM_ERR;
12750 Jim_SetResult(interp, objPtr);
12751 return JIM_OK;
12754 case OPT_REPEAT:{
12755 Jim_Obj *objPtr;
12756 jim_wide count;
12758 if (argc != 4) {
12759 Jim_WrongNumArgs(interp, 2, argv, "string count");
12760 return JIM_ERR;
12762 if (Jim_GetWide(interp, argv[3], &count) != JIM_OK) {
12763 return JIM_ERR;
12765 objPtr = Jim_NewStringObj(interp, "", 0);
12766 if (count > 0) {
12767 while (count--) {
12768 Jim_AppendObj(interp, objPtr, argv[2]);
12771 Jim_SetResult(interp, objPtr);
12772 return JIM_OK;
12775 case OPT_REVERSE:{
12776 char *buf, *p;
12777 const char *str;
12778 int len;
12779 int i;
12781 if (argc != 3) {
12782 Jim_WrongNumArgs(interp, 2, argv, "string");
12783 return JIM_ERR;
12786 str = Jim_GetString(argv[2], &len);
12787 if (!str) {
12788 return JIM_ERR;
12791 buf = Jim_Alloc(len + 1);
12792 p = buf + len;
12793 *p = 0;
12794 for (i = 0; i < len; ) {
12795 int c;
12796 int l = utf8_tounicode(str, &c);
12797 memcpy(p - l, str, l);
12798 p -= l;
12799 i += l;
12800 str += l;
12802 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
12803 return JIM_OK;
12806 case OPT_INDEX:{
12807 int idx;
12808 const char *str;
12810 if (argc != 4) {
12811 Jim_WrongNumArgs(interp, 2, argv, "string index");
12812 return JIM_ERR;
12814 if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
12815 return JIM_ERR;
12817 str = Jim_String(argv[2]);
12818 len = Jim_Utf8Length(interp, argv[2]);
12819 if (idx != INT_MIN && idx != INT_MAX) {
12820 idx = JimRelToAbsIndex(len, idx);
12822 if (idx < 0 || idx >= len || str == NULL) {
12823 Jim_SetResultString(interp, "", 0);
12825 else if (len == Jim_Length(argv[2])) {
12826 /* ASCII optimisation */
12827 Jim_SetResultString(interp, str + idx, 1);
12829 else {
12830 int c;
12831 int i = utf8_index(str, idx);
12832 Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
12834 return JIM_OK;
12837 case OPT_FIRST:
12838 case OPT_LAST:{
12839 int idx = 0, l1, l2;
12840 const char *s1, *s2;
12842 if (argc != 4 && argc != 5) {
12843 Jim_WrongNumArgs(interp, 2, argv, "subString string ?index?");
12844 return JIM_ERR;
12846 s1 = Jim_String(argv[2]);
12847 s2 = Jim_String(argv[3]);
12848 l1 = Jim_Utf8Length(interp, argv[2]);
12849 l2 = Jim_Utf8Length(interp, argv[3]);
12850 if (argc == 5) {
12851 if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
12852 return JIM_ERR;
12854 idx = JimRelToAbsIndex(l2, idx);
12856 else if (option == OPT_LAST) {
12857 idx = l2;
12859 if (option == OPT_FIRST) {
12860 Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
12862 else {
12863 #ifdef JIM_UTF8
12864 Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
12865 #else
12866 Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
12867 #endif
12869 return JIM_OK;
12872 case OPT_TRIM:
12873 case OPT_TRIMLEFT:
12874 case OPT_TRIMRIGHT:{
12875 Jim_Obj *trimchars;
12877 if (argc != 3 && argc != 4) {
12878 Jim_WrongNumArgs(interp, 2, argv, "string ?trimchars?");
12879 return JIM_ERR;
12881 trimchars = (argc == 4 ? argv[3] : NULL);
12882 if (option == OPT_TRIM) {
12883 Jim_SetResult(interp, JimStringTrim(interp, argv[2], trimchars));
12885 else if (option == OPT_TRIMLEFT) {
12886 Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], trimchars));
12888 else if (option == OPT_TRIMRIGHT) {
12889 Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], trimchars));
12891 return JIM_OK;
12894 case OPT_TOLOWER:
12895 case OPT_TOUPPER:
12896 if (argc != 3) {
12897 Jim_WrongNumArgs(interp, 2, argv, "string");
12898 return JIM_ERR;
12900 if (option == OPT_TOLOWER) {
12901 Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
12903 else {
12904 Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
12906 return JIM_OK;
12908 case OPT_IS:
12909 if (argc == 4 || (argc == 5 && Jim_CompareStringImmediate(interp, argv[3], "-strict"))) {
12910 return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
12912 Jim_WrongNumArgs(interp, 2, argv, "class ?-strict? str");
12913 return JIM_ERR;
12915 return JIM_OK;
12918 /* [time] */
12919 static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12921 long i, count = 1;
12922 jim_wide start, elapsed;
12923 char buf[60];
12924 const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";
12926 if (argc < 2) {
12927 Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
12928 return JIM_ERR;
12930 if (argc == 3) {
12931 if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
12932 return JIM_ERR;
12934 if (count < 0)
12935 return JIM_OK;
12936 i = count;
12937 start = JimClock();
12938 while (i-- > 0) {
12939 int retval;
12941 retval = Jim_EvalObj(interp, argv[1]);
12942 if (retval != JIM_OK) {
12943 return retval;
12946 elapsed = JimClock() - start;
12947 sprintf(buf, fmt, count == 0 ? 0 : elapsed / count);
12948 Jim_SetResultString(interp, buf, -1);
12949 return JIM_OK;
12952 /* [exit] */
12953 static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12955 long exitCode = 0;
12957 if (argc > 2) {
12958 Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
12959 return JIM_ERR;
12961 if (argc == 2) {
12962 if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
12963 return JIM_ERR;
12965 interp->exitCode = exitCode;
12966 return JIM_EXIT;
12969 /* [catch] */
12970 static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
12972 int exitCode = 0;
12973 int i;
12974 int sig = 0;
12976 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
12977 jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
12978 static const int max_ignore_code = sizeof(ignore_mask) * 8;
12980 /* Reset the error code before catch.
12981 * Note that this is not strictly correct.
12983 Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
12985 for (i = 1; i < argc - 1; i++) {
12986 const char *arg = Jim_String(argv[i]);
12987 jim_wide option;
12988 int ignore;
12990 /* It's a pity we can't use Jim_GetEnum here :-( */
12991 if (strcmp(arg, "--") == 0) {
12992 i++;
12993 break;
12995 if (*arg != '-') {
12996 break;
12999 if (strncmp(arg, "-no", 3) == 0) {
13000 arg += 3;
13001 ignore = 1;
13003 else {
13004 arg++;
13005 ignore = 0;
13008 if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
13009 option = -1;
13011 if (option < 0) {
13012 option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
13014 if (option < 0) {
13015 goto wrongargs;
13018 if (ignore) {
13019 ignore_mask |= (1 << option);
13021 else {
13022 ignore_mask &= ~(1 << option);
13026 argc -= i;
13027 if (argc < 1 || argc > 3) {
13028 wrongargs:
13029 Jim_WrongNumArgs(interp, 1, argv,
13030 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13031 return JIM_ERR;
13033 argv += i;
13035 if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
13036 sig++;
13039 interp->signal_level += sig;
13040 if (interp->signal_level && interp->sigmask) {
13041 /* If a signal is set, don't even try to execute the body */
13042 exitCode = JIM_SIGNAL;
13044 else {
13045 exitCode = Jim_EvalObj(interp, argv[0]);
13047 interp->signal_level -= sig;
13049 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13050 if (exitCode >= 0 && exitCode < max_ignore_code && ((1 << exitCode) & ignore_mask)) {
13051 /* Not caught, pass it up */
13052 return exitCode;
13055 if (sig && exitCode == JIM_SIGNAL) {
13056 /* Catch the signal at this level */
13057 if (interp->signal_set_result) {
13058 interp->signal_set_result(interp, interp->sigmask);
13060 else {
13061 Jim_SetResultInt(interp, interp->sigmask);
13063 interp->sigmask = 0;
13066 if (argc >= 2) {
13067 if (Jim_SetVariable(interp, argv[1], Jim_GetResult(interp)) != JIM_OK) {
13068 return JIM_ERR;
13070 if (argc == 3) {
13071 Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
13073 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
13074 Jim_ListAppendElement(interp, optListObj,
13075 Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
13076 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
13077 Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
13078 if (exitCode == JIM_ERR) {
13079 Jim_Obj *errorCode;
13080 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
13081 -1));
13082 Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
13084 errorCode = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
13085 if (errorCode) {
13086 Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
13087 Jim_ListAppendElement(interp, optListObj, errorCode);
13090 if (Jim_SetVariable(interp, argv[2], optListObj) != JIM_OK) {
13091 return JIM_ERR;
13095 Jim_SetResultInt(interp, exitCode);
13096 return JIM_OK;
13099 #ifdef JIM_REFERENCES
13101 /* [ref] */
13102 static int Jim_RefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13104 if (argc != 3 && argc != 4) {
13105 Jim_WrongNumArgs(interp, 1, argv, "string tag ?finalizer?");
13106 return JIM_ERR;
13108 if (argc == 3) {
13109 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], NULL));
13111 else {
13112 Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], argv[3]));
13114 return JIM_OK;
13117 /* [getref] */
13118 static int Jim_GetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13120 Jim_Reference *refPtr;
13122 if (argc != 2) {
13123 Jim_WrongNumArgs(interp, 1, argv, "reference");
13124 return JIM_ERR;
13126 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13127 return JIM_ERR;
13128 Jim_SetResult(interp, refPtr->objPtr);
13129 return JIM_OK;
13132 /* [setref] */
13133 static int Jim_SetrefCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13135 Jim_Reference *refPtr;
13137 if (argc != 3) {
13138 Jim_WrongNumArgs(interp, 1, argv, "reference newValue");
13139 return JIM_ERR;
13141 if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
13142 return JIM_ERR;
13143 Jim_IncrRefCount(argv[2]);
13144 Jim_DecrRefCount(interp, refPtr->objPtr);
13145 refPtr->objPtr = argv[2];
13146 Jim_SetResult(interp, argv[2]);
13147 return JIM_OK;
13150 /* [collect] */
13151 static int Jim_CollectCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13153 if (argc != 1) {
13154 Jim_WrongNumArgs(interp, 1, argv, "");
13155 return JIM_ERR;
13157 Jim_SetResultInt(interp, Jim_Collect(interp));
13159 /* Free all the freed objects. */
13160 while (interp->freeList) {
13161 Jim_Obj *nextObjPtr = interp->freeList->nextObjPtr;
13162 Jim_Free(interp->freeList);
13163 interp->freeList = nextObjPtr;
13166 return JIM_OK;
13169 /* [finalize] reference ?newValue? */
13170 static int Jim_FinalizeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13172 if (argc != 2 && argc != 3) {
13173 Jim_WrongNumArgs(interp, 1, argv, "reference ?finalizerProc?");
13174 return JIM_ERR;
13176 if (argc == 2) {
13177 Jim_Obj *cmdNamePtr;
13179 if (Jim_GetFinalizer(interp, argv[1], &cmdNamePtr) != JIM_OK)
13180 return JIM_ERR;
13181 if (cmdNamePtr != NULL) /* otherwise the null string is returned. */
13182 Jim_SetResult(interp, cmdNamePtr);
13184 else {
13185 if (Jim_SetFinalizer(interp, argv[1], argv[2]) != JIM_OK)
13186 return JIM_ERR;
13187 Jim_SetResult(interp, argv[2]);
13189 return JIM_OK;
13192 /* [info references] */
13193 static int JimInfoReferences(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13195 Jim_Obj *listObjPtr;
13196 Jim_HashTableIterator *htiter;
13197 Jim_HashEntry *he;
13199 listObjPtr = Jim_NewListObj(interp, NULL, 0);
13201 htiter = Jim_GetHashTableIterator(&interp->references);
13202 while ((he = Jim_NextHashEntry(htiter)) != NULL) {
13203 char buf[JIM_REFERENCE_SPACE];
13204 Jim_Reference *refPtr = he->u.val;
13205 const jim_wide *refId = he->key;
13207 JimFormatReference(buf, refPtr, *refId);
13208 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, buf, -1));
13210 Jim_FreeHashTableIterator(htiter);
13211 Jim_SetResult(interp, listObjPtr);
13212 return JIM_OK;
13214 #endif
13216 /* [rename] */
13217 static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13219 const char *oldName, *newName;
13221 if (argc != 3) {
13222 Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
13223 return JIM_ERR;
13226 if (JimValidName(interp, "new procedure", argv[2])) {
13227 return JIM_ERR;
13230 oldName = Jim_String(argv[1]);
13231 newName = Jim_String(argv[2]);
13232 return Jim_RenameCommand(interp, oldName, newName);
13235 int Jim_DictKeys(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj)
13237 int i;
13238 int len;
13239 Jim_Obj *resultObj;
13240 Jim_Obj *dictObj;
13241 Jim_Obj **dictValuesObj;
13243 if (Jim_DictKeysVector(interp, objPtr, NULL, 0, &dictObj, JIM_ERRMSG) != JIM_OK) {
13244 return JIM_ERR;
13247 /* XXX: Could make the exact-match case much more efficient here.
13248 * See JimCommandsList()
13250 if (Jim_DictPairs(interp, dictObj, &dictValuesObj, &len) != JIM_OK) {
13251 return JIM_ERR;
13254 /* Only return the matching values */
13255 resultObj = Jim_NewListObj(interp, NULL, 0);
13257 for (i = 0; i < len; i += 2) {
13258 if (patternObj == NULL || Jim_StringMatchObj(interp, patternObj, dictValuesObj[i], 0)) {
13259 Jim_ListAppendElement(interp, resultObj, dictValuesObj[i]);
13262 Jim_Free(dictValuesObj);
13264 Jim_SetResult(interp, resultObj);
13265 return JIM_OK;
13268 int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
13270 if (SetDictFromAny(interp, objPtr) != JIM_OK) {
13271 return -1;
13273 return ((Jim_HashTable *)objPtr->internalRep.ptr)->used;
13276 /* [dict] */
13277 static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13279 Jim_Obj *objPtr;
13280 int option;
13281 static const char * const options[] = {
13282 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13284 enum
13286 OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXIST, OPT_KEYS, OPT_MERGE, OPT_SIZE, OPT_WITH,
13289 if (argc < 2) {
13290 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?arguments ...?");
13291 return JIM_ERR;
13294 if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK) {
13295 return JIM_ERR;
13298 switch (option) {
13299 case OPT_GET:
13300 if (argc < 3) {
13301 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13302 return JIM_ERR;
13304 if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
13305 JIM_ERRMSG) != JIM_OK) {
13306 return JIM_ERR;
13308 Jim_SetResult(interp, objPtr);
13309 return JIM_OK;
13311 case OPT_SET:
13312 if (argc < 5) {
13313 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");
13314 return JIM_ERR;
13316 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1]);
13318 case OPT_EXIST:
13319 if (argc < 3) {
13320 Jim_WrongNumArgs(interp, 2, argv, "varName ?key ...?");
13321 return JIM_ERR;
13323 Jim_SetResultBool(interp, Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3,
13324 &objPtr, JIM_ERRMSG) == JIM_OK);
13325 return JIM_OK;
13327 case OPT_UNSET:
13328 if (argc < 4) {
13329 Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");
13330 return JIM_ERR;
13332 return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL);
13334 case OPT_KEYS:
13335 if (argc != 3 && argc != 4) {
13336 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?pattern?");
13337 return JIM_ERR;
13339 return Jim_DictKeys(interp, argv[2], argc == 4 ? argv[3] : NULL);
13341 case OPT_SIZE: {
13342 int size;
13344 if (argc != 3) {
13345 Jim_WrongNumArgs(interp, 2, argv, "dictVar");
13346 return JIM_ERR;
13349 size = Jim_DictSize(interp, argv[2]);
13350 if (size < 0) {
13351 return JIM_ERR;
13353 Jim_SetResultInt(interp, size);
13354 return JIM_OK;
13357 case OPT_MERGE:
13358 if (argc == 2) {
13359 return JIM_OK;
13361 else if (argv[2]->typePtr != &dictObjType && SetDictFromAny(interp, argv[2]) != JIM_OK) {
13362 return JIM_ERR;
13364 else {
13365 return Jim_EvalObjPrefix(interp, "dict merge", argc - 2, argv + 2);
13368 case OPT_WITH:
13369 if (argc < 4) {
13370 Jim_WrongNumArgs(interp, 2, argv, "dictVar ?key ...? script");
13371 return JIM_ERR;
13373 else if (Jim_GetVariable(interp, argv[2], JIM_ERRMSG) == NULL) {
13374 return JIM_ERR;
13376 else {
13377 return Jim_EvalObjPrefix(interp, "dict with", argc - 2, argv + 2);
13380 case OPT_CREATE:
13381 if (argc % 2) {
13382 Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");
13383 return JIM_ERR;
13385 objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
13386 Jim_SetResult(interp, objPtr);
13387 return JIM_OK;
13389 default:
13390 abort();
13394 /* [subst] */
13395 static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13397 static const char * const options[] = {
13398 "-nobackslashes", "-nocommands", "-novariables", NULL
13400 enum
13401 { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
13402 int i;
13403 int flags = JIM_SUBST_FLAG;
13404 Jim_Obj *objPtr;
13406 if (argc < 2) {
13407 Jim_WrongNumArgs(interp, 1, argv, "?options? string");
13408 return JIM_ERR;
13410 for (i = 1; i < (argc - 1); i++) {
13411 int option;
13413 if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
13414 JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13415 return JIM_ERR;
13417 switch (option) {
13418 case OPT_NOBACKSLASHES:
13419 flags |= JIM_SUBST_NOESC;
13420 break;
13421 case OPT_NOCOMMANDS:
13422 flags |= JIM_SUBST_NOCMD;
13423 break;
13424 case OPT_NOVARIABLES:
13425 flags |= JIM_SUBST_NOVAR;
13426 break;
13429 if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
13430 return JIM_ERR;
13432 Jim_SetResult(interp, objPtr);
13433 return JIM_OK;
13436 /* [info] */
13437 static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13439 int cmd;
13440 Jim_Obj *objPtr;
13441 int mode = 0;
13443 static const char * const commands[] = {
13444 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13445 "vars", "version", "patchlevel", "complete", "args", "hostname",
13446 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13447 "references", NULL
13449 enum
13450 { INFO_BODY, INFO_COMMANDS, INFO_PROCS, INFO_CHANNELS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,
13451 INFO_FRAME, INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_PATCHLEVEL, INFO_COMPLETE, INFO_ARGS,
13452 INFO_HOSTNAME, INFO_SCRIPT, INFO_SOURCE, INFO_STACKTRACE, INFO_NAMEOFEXECUTABLE,
13453 INFO_RETURNCODES, INFO_REFERENCES,
13456 if (argc < 2) {
13457 Jim_WrongNumArgs(interp, 1, argv, "subcommand ?args ...?");
13458 return JIM_ERR;
13460 if (Jim_GetEnum(interp, argv[1], commands, &cmd, "subcommand", JIM_ERRMSG | JIM_ENUM_ABBREV)
13461 != JIM_OK) {
13462 return JIM_ERR;
13465 /* Test for the the most common commands first, just in case it makes a difference */
13466 switch (cmd) {
13467 case INFO_EXISTS:{
13468 if (argc != 3) {
13469 Jim_WrongNumArgs(interp, 2, argv, "varName");
13470 return JIM_ERR;
13472 Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
13473 break;
13476 case INFO_CHANNELS:
13477 #ifndef jim_ext_aio
13478 Jim_SetResultString(interp, "aio not enabled", -1);
13479 return JIM_ERR;
13480 #endif
13481 case INFO_COMMANDS:
13482 case INFO_PROCS:
13483 if (argc != 2 && argc != 3) {
13484 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13485 return JIM_ERR;
13487 Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL,
13488 (cmd - INFO_COMMANDS)));
13489 break;
13491 case INFO_VARS:
13492 mode++; /* JIM_VARLIST_VARS */
13493 case INFO_LOCALS:
13494 mode++; /* JIM_VARLIST_LOCALS */
13495 case INFO_GLOBALS:
13496 /* mode 0 => JIM_VARLIST_GLOBALS */
13497 if (argc != 2 && argc != 3) {
13498 Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
13499 return JIM_ERR;
13501 Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
13502 break;
13504 case INFO_SCRIPT:
13505 if (argc != 2) {
13506 Jim_WrongNumArgs(interp, 2, argv, "");
13507 return JIM_ERR;
13509 Jim_SetResult(interp, Jim_GetScript(interp, interp->currentScriptObj)->fileNameObj);
13510 break;
13512 case INFO_SOURCE:{
13513 int line;
13514 Jim_Obj *resObjPtr;
13515 Jim_Obj *fileNameObj;
13517 if (argc != 3) {
13518 Jim_WrongNumArgs(interp, 2, argv, "source");
13519 return JIM_ERR;
13521 if (argv[2]->typePtr == &sourceObjType) {
13522 fileNameObj = argv[2]->internalRep.sourceValue.fileNameObj;
13523 line = argv[2]->internalRep.sourceValue.lineNumber;
13525 else if (argv[2]->typePtr == &scriptObjType) {
13526 ScriptObj *script = Jim_GetScript(interp, argv[2]);
13527 fileNameObj = script->fileNameObj;
13528 line = script->line;
13530 else {
13531 fileNameObj = interp->emptyObj;
13532 line = 1;
13534 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13535 Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
13536 Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
13537 Jim_SetResult(interp, resObjPtr);
13538 break;
13541 case INFO_STACKTRACE:
13542 Jim_SetResult(interp, interp->stackTrace);
13543 break;
13545 case INFO_LEVEL:
13546 case INFO_FRAME:
13547 switch (argc) {
13548 case 2:
13549 Jim_SetResultInt(interp, interp->framePtr->level);
13550 break;
13552 case 3:
13553 if (JimInfoLevel(interp, argv[2], &objPtr, cmd == INFO_LEVEL) != JIM_OK) {
13554 return JIM_ERR;
13556 Jim_SetResult(interp, objPtr);
13557 break;
13559 default:
13560 Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");
13561 return JIM_ERR;
13563 break;
13565 case INFO_BODY:
13566 case INFO_ARGS:{
13567 Jim_Cmd *cmdPtr;
13569 if (argc != 3) {
13570 Jim_WrongNumArgs(interp, 2, argv, "procname");
13571 return JIM_ERR;
13573 if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
13574 return JIM_ERR;
13576 if (!cmdPtr->isproc) {
13577 Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
13578 return JIM_ERR;
13580 Jim_SetResult(interp,
13581 cmd == INFO_BODY ? cmdPtr->u.proc.bodyObjPtr : cmdPtr->u.proc.argListObjPtr);
13582 break;
13585 case INFO_VERSION:
13586 case INFO_PATCHLEVEL:{
13587 char buf[(JIM_INTEGER_SPACE * 2) + 1];
13589 sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
13590 Jim_SetResultString(interp, buf, -1);
13591 break;
13594 case INFO_COMPLETE:
13595 if (argc != 3 && argc != 4) {
13596 Jim_WrongNumArgs(interp, 2, argv, "script ?missing?");
13597 return JIM_ERR;
13599 else {
13600 int len;
13601 const char *s = Jim_GetString(argv[2], &len);
13602 char missing;
13604 Jim_SetResultBool(interp, Jim_ScriptIsComplete(s, len, &missing));
13605 if (missing != ' ' && argc == 4) {
13606 Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
13609 break;
13611 case INFO_HOSTNAME:
13612 /* Redirect to os.gethostname if it exists */
13613 return Jim_Eval(interp, "os.gethostname");
13615 case INFO_NAMEOFEXECUTABLE:
13616 /* Redirect to Tcl proc */
13617 return Jim_Eval(interp, "{info nameofexecutable}");
13619 case INFO_RETURNCODES:
13620 if (argc == 2) {
13621 int i;
13622 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
13624 for (i = 0; jimReturnCodes[i]; i++) {
13625 Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
13626 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
13627 jimReturnCodes[i], -1));
13630 Jim_SetResult(interp, listObjPtr);
13632 else if (argc == 3) {
13633 long code;
13634 const char *name;
13636 if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
13637 return JIM_ERR;
13639 name = Jim_ReturnCode(code);
13640 if (*name == '?') {
13641 Jim_SetResultInt(interp, code);
13643 else {
13644 Jim_SetResultString(interp, name, -1);
13647 else {
13648 Jim_WrongNumArgs(interp, 2, argv, "?code?");
13649 return JIM_ERR;
13651 break;
13652 case INFO_REFERENCES:
13653 #ifdef JIM_REFERENCES
13654 return JimInfoReferences(interp, argc, argv);
13655 #else
13656 Jim_SetResultString(interp, "not supported", -1);
13657 return JIM_ERR;
13658 #endif
13660 return JIM_OK;
13663 /* [exists] */
13664 static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13666 Jim_Obj *objPtr;
13668 static const char * const options[] = {
13669 "-command", "-proc", "-var", NULL
13671 enum
13673 OPT_COMMAND, OPT_PROC, OPT_VAR
13675 int option;
13677 if (argc == 2) {
13678 option = OPT_VAR;
13679 objPtr = argv[1];
13681 else if (argc == 3) {
13682 if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
13683 return JIM_ERR;
13685 objPtr = argv[2];
13687 else {
13688 Jim_WrongNumArgs(interp, 1, argv, "?option? name");
13689 return JIM_ERR;
13692 /* Test for the the most common commands first, just in case it makes a difference */
13693 switch (option) {
13694 case OPT_VAR:
13695 Jim_SetResultBool(interp, Jim_GetVariable(interp, objPtr, 0) != NULL);
13696 break;
13698 case OPT_COMMAND:
13699 case OPT_PROC: {
13700 Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
13701 Jim_SetResultBool(interp, cmd != NULL && (option == OPT_COMMAND || cmd->isproc));
13702 break;
13705 return JIM_OK;
13708 /* [split] */
13709 static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13711 const char *str, *splitChars, *noMatchStart;
13712 int splitLen, strLen;
13713 Jim_Obj *resObjPtr;
13714 int c;
13715 int len;
13717 if (argc != 2 && argc != 3) {
13718 Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
13719 return JIM_ERR;
13722 str = Jim_GetString(argv[1], &len);
13723 if (len == 0) {
13724 return JIM_OK;
13726 strLen = Jim_Utf8Length(interp, argv[1]);
13728 /* Init */
13729 if (argc == 2) {
13730 splitChars = " \n\t\r";
13731 splitLen = 4;
13733 else {
13734 splitChars = Jim_String(argv[2]);
13735 splitLen = Jim_Utf8Length(interp, argv[2]);
13738 noMatchStart = str;
13739 resObjPtr = Jim_NewListObj(interp, NULL, 0);
13741 /* Split */
13742 if (splitLen) {
13743 Jim_Obj *objPtr;
13744 while (strLen--) {
13745 const char *sc = splitChars;
13746 int scLen = splitLen;
13747 int sl = utf8_tounicode(str, &c);
13748 while (scLen--) {
13749 int pc;
13750 sc += utf8_tounicode(sc, &pc);
13751 if (c == pc) {
13752 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13753 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13754 noMatchStart = str + sl;
13755 break;
13758 str += sl;
13760 objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
13761 Jim_ListAppendElement(interp, resObjPtr, objPtr);
13763 else {
13764 /* This handles the special case of splitchars eq {}
13765 * Optimise by sharing common (ASCII) characters
13767 Jim_Obj **commonObj = NULL;
13768 #define NUM_COMMON (128 - 9)
13769 while (strLen--) {
13770 int n = utf8_tounicode(str, &c);
13771 #ifdef JIM_OPTIMIZATION
13772 if (c >= 9 && c < 128) {
13773 /* Common ASCII char. Note that 9 is the tab character */
13774 c -= 9;
13775 if (!commonObj) {
13776 commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
13777 memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
13779 if (!commonObj[c]) {
13780 commonObj[c] = Jim_NewStringObj(interp, str, 1);
13782 Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
13783 str++;
13784 continue;
13786 #endif
13787 Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
13788 str += n;
13790 Jim_Free(commonObj);
13793 Jim_SetResult(interp, resObjPtr);
13794 return JIM_OK;
13797 /* [join] */
13798 static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13800 const char *joinStr;
13801 int joinStrLen, i, listLen;
13802 Jim_Obj *resObjPtr;
13804 if (argc != 2 && argc != 3) {
13805 Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
13806 return JIM_ERR;
13808 /* Init */
13809 if (argc == 2) {
13810 joinStr = " ";
13811 joinStrLen = 1;
13813 else {
13814 joinStr = Jim_GetString(argv[2], &joinStrLen);
13816 listLen = Jim_ListLength(interp, argv[1]);
13817 resObjPtr = Jim_NewStringObj(interp, NULL, 0);
13818 /* Split */
13819 for (i = 0; i < listLen; i++) {
13820 Jim_Obj *objPtr = 0;
13822 Jim_ListIndex(interp, argv[1], i, &objPtr, JIM_NONE);
13823 Jim_AppendObj(interp, resObjPtr, objPtr);
13824 if (i + 1 != listLen) {
13825 Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
13828 Jim_SetResult(interp, resObjPtr);
13829 return JIM_OK;
13832 /* [format] */
13833 static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13835 Jim_Obj *objPtr;
13837 if (argc < 2) {
13838 Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
13839 return JIM_ERR;
13841 objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
13842 if (objPtr == NULL)
13843 return JIM_ERR;
13844 Jim_SetResult(interp, objPtr);
13845 return JIM_OK;
13848 /* [scan] */
13849 static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13851 Jim_Obj *listPtr, **outVec;
13852 int outc, i;
13854 if (argc < 3) {
13855 Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
13856 return JIM_ERR;
13858 if (argv[2]->typePtr != &scanFmtStringObjType)
13859 SetScanFmtFromAny(interp, argv[2]);
13860 if (FormatGetError(argv[2]) != 0) {
13861 Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
13862 return JIM_ERR;
13864 if (argc > 3) {
13865 int maxPos = FormatGetMaxPos(argv[2]);
13866 int count = FormatGetCnvCount(argv[2]);
13868 if (maxPos > argc - 3) {
13869 Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
13870 return JIM_ERR;
13872 else if (count > argc - 3) {
13873 Jim_SetResultString(interp, "different numbers of variable names and "
13874 "field specifiers", -1);
13875 return JIM_ERR;
13877 else if (count < argc - 3) {
13878 Jim_SetResultString(interp, "variable is not assigned by any "
13879 "conversion specifiers", -1);
13880 return JIM_ERR;
13883 listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
13884 if (listPtr == 0)
13885 return JIM_ERR;
13886 if (argc > 3) {
13887 int rc = JIM_OK;
13888 int count = 0;
13890 if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
13891 int len = Jim_ListLength(interp, listPtr);
13893 if (len != 0) {
13894 JimListGetElements(interp, listPtr, &outc, &outVec);
13895 for (i = 0; i < outc; ++i) {
13896 if (Jim_Length(outVec[i]) > 0) {
13897 ++count;
13898 if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
13899 rc = JIM_ERR;
13904 Jim_FreeNewObj(interp, listPtr);
13906 else {
13907 count = -1;
13909 if (rc == JIM_OK) {
13910 Jim_SetResultInt(interp, count);
13912 return rc;
13914 else {
13915 if (listPtr == (Jim_Obj *)EOF) {
13916 Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
13917 return JIM_OK;
13919 Jim_SetResult(interp, listPtr);
13921 return JIM_OK;
13924 /* [error] */
13925 static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13927 if (argc != 2 && argc != 3) {
13928 Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
13929 return JIM_ERR;
13931 Jim_SetResult(interp, argv[1]);
13932 if (argc == 3) {
13933 JimSetStackTrace(interp, argv[2]);
13934 return JIM_ERR;
13936 interp->addStackTrace++;
13937 return JIM_ERR;
13940 /* [lrange] */
13941 static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13943 Jim_Obj *objPtr;
13945 if (argc != 4) {
13946 Jim_WrongNumArgs(interp, 1, argv, "list first last");
13947 return JIM_ERR;
13949 if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
13950 return JIM_ERR;
13951 Jim_SetResult(interp, objPtr);
13952 return JIM_OK;
13955 /* [lrepeat] */
13956 static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
13958 Jim_Obj *objPtr;
13959 long count;
13961 if (argc < 2 || Jim_GetLong(interp, argv[1], &count) != JIM_OK || count < 0) {
13962 Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
13963 return JIM_ERR;
13966 if (count == 0 || argc == 2) {
13967 return JIM_OK;
13970 argc -= 2;
13971 argv += 2;
13973 objPtr = Jim_NewListObj(interp, argv, argc);
13974 while (--count) {
13975 int i;
13977 for (i = 0; i < argc; i++) {
13978 ListAppendElement(objPtr, argv[i]);
13982 Jim_SetResult(interp, objPtr);
13983 return JIM_OK;
13986 char **Jim_GetEnviron(void)
13988 #if defined(HAVE__NSGETENVIRON)
13989 return *_NSGetEnviron();
13990 #else
13991 #if !defined(NO_ENVIRON_EXTERN)
13992 extern char **environ;
13993 #endif
13995 return environ;
13996 #endif
13999 void Jim_SetEnviron(char **env)
14001 #if defined(HAVE__NSGETENVIRON)
14002 *_NSGetEnviron() = env;
14003 #else
14004 #if !defined(NO_ENVIRON_EXTERN)
14005 extern char **environ;
14006 #endif
14008 environ = env;
14009 #endif
14012 /* [env] */
14013 static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14015 const char *key;
14016 const char *val;
14018 if (argc == 1) {
14019 char **e = Jim_GetEnviron();
14021 int i;
14022 Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
14024 for (i = 0; e[i]; i++) {
14025 const char *equals = strchr(e[i], '=');
14027 if (equals) {
14028 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
14029 equals - e[i]));
14030 Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
14034 Jim_SetResult(interp, listObjPtr);
14035 return JIM_OK;
14038 if (argc < 2) {
14039 Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
14040 return JIM_ERR;
14042 key = Jim_String(argv[1]);
14043 val = getenv(key);
14044 if (val == NULL) {
14045 if (argc < 3) {
14046 Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
14047 return JIM_ERR;
14049 val = Jim_String(argv[2]);
14051 Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
14052 return JIM_OK;
14055 /* [source] */
14056 static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14058 int retval;
14060 if (argc != 2) {
14061 Jim_WrongNumArgs(interp, 1, argv, "fileName");
14062 return JIM_ERR;
14064 retval = Jim_EvalFile(interp, Jim_String(argv[1]));
14065 if (retval == JIM_RETURN)
14066 return JIM_OK;
14067 return retval;
14070 /* [lreverse] */
14071 static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14073 Jim_Obj *revObjPtr, **ele;
14074 int len;
14076 if (argc != 2) {
14077 Jim_WrongNumArgs(interp, 1, argv, "list");
14078 return JIM_ERR;
14080 JimListGetElements(interp, argv[1], &len, &ele);
14081 len--;
14082 revObjPtr = Jim_NewListObj(interp, NULL, 0);
14083 while (len >= 0)
14084 ListAppendElement(revObjPtr, ele[len--]);
14085 Jim_SetResult(interp, revObjPtr);
14086 return JIM_OK;
14089 static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
14091 jim_wide len;
14093 if (step == 0)
14094 return -1;
14095 if (start == end)
14096 return 0;
14097 else if (step > 0 && start > end)
14098 return -1;
14099 else if (step < 0 && end > start)
14100 return -1;
14101 len = end - start;
14102 if (len < 0)
14103 len = -len; /* abs(len) */
14104 if (step < 0)
14105 step = -step; /* abs(step) */
14106 len = 1 + ((len - 1) / step);
14107 /* We can truncate safely to INT_MAX, the range command
14108 * will always return an error for a such long range
14109 * because Tcl lists can't be so long. */
14110 if (len > INT_MAX)
14111 len = INT_MAX;
14112 return (int)((len < 0) ? -1 : len);
14115 /* [range] */
14116 static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14118 jim_wide start = 0, end, step = 1;
14119 int len, i;
14120 Jim_Obj *objPtr;
14122 if (argc < 2 || argc > 4) {
14123 Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
14124 return JIM_ERR;
14126 if (argc == 2) {
14127 if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)
14128 return JIM_ERR;
14130 else {
14131 if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||
14132 Jim_GetWide(interp, argv[2], &end) != JIM_OK)
14133 return JIM_ERR;
14134 if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)
14135 return JIM_ERR;
14137 if ((len = JimRangeLen(start, end, step)) == -1) {
14138 Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
14139 return JIM_ERR;
14141 objPtr = Jim_NewListObj(interp, NULL, 0);
14142 for (i = 0; i < len; i++)
14143 ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
14144 Jim_SetResult(interp, objPtr);
14145 return JIM_OK;
14148 /* [rand] */
14149 static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
14151 jim_wide min = 0, max = 0, len, maxMul;
14153 if (argc < 1 || argc > 3) {
14154 Jim_WrongNumArgs(interp, 1, argv, "?min? max");
14155 return JIM_ERR;
14157 if (argc == 1) {
14158 max = JIM_WIDE_MAX;
14159 } else if (argc == 2) {
14160 if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)
14161 return JIM_ERR;
14162 } else if (argc == 3) {
14163 if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||
14164 Jim_GetWide(interp, argv[2], &max) != JIM_OK)
14165 return JIM_ERR;
14167 len = max-min;
14168 if (len < 0) {
14169 Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
14170 return JIM_ERR;
14172 maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
14173 while (1) {
14174 jim_wide r;
14176 JimRandomBytes(interp, &r, sizeof(jim_wide));
14177 if (r < 0 || r >= maxMul) continue;
14178 r = (len == 0) ? 0 : r%len;
14179 Jim_SetResultInt(interp, min+r);
14180 return JIM_OK;
14184 static const struct {
14185 const char *name;
14186 Jim_CmdProc cmdProc;
14187 } Jim_CoreCommandsTable[] = {
14188 {"set", Jim_SetCoreCommand},
14189 {"unset", Jim_UnsetCoreCommand},
14190 {"puts", Jim_PutsCoreCommand},
14191 {"+", Jim_AddCoreCommand},
14192 {"*", Jim_MulCoreCommand},
14193 {"-", Jim_SubCoreCommand},
14194 {"/", Jim_DivCoreCommand},
14195 {"incr", Jim_IncrCoreCommand},
14196 {"while", Jim_WhileCoreCommand},
14197 {"loop", Jim_LoopCoreCommand},
14198 {"for", Jim_ForCoreCommand},
14199 {"foreach", Jim_ForeachCoreCommand},
14200 {"lmap", Jim_LmapCoreCommand},
14201 {"if", Jim_IfCoreCommand},
14202 {"switch", Jim_SwitchCoreCommand},
14203 {"list", Jim_ListCoreCommand},
14204 {"lindex", Jim_LindexCoreCommand},
14205 {"lset", Jim_LsetCoreCommand},
14206 {"lsearch", Jim_LsearchCoreCommand},
14207 {"llength", Jim_LlengthCoreCommand},
14208 {"lappend", Jim_LappendCoreCommand},
14209 {"linsert", Jim_LinsertCoreCommand},
14210 {"lreplace", Jim_LreplaceCoreCommand},
14211 {"lsort", Jim_LsortCoreCommand},
14212 {"append", Jim_AppendCoreCommand},
14213 {"debug", Jim_DebugCoreCommand},
14214 {"eval", Jim_EvalCoreCommand},
14215 {"uplevel", Jim_UplevelCoreCommand},
14216 {"expr", Jim_ExprCoreCommand},
14217 {"break", Jim_BreakCoreCommand},
14218 {"continue", Jim_ContinueCoreCommand},
14219 {"proc", Jim_ProcCoreCommand},
14220 {"concat", Jim_ConcatCoreCommand},
14221 {"return", Jim_ReturnCoreCommand},
14222 {"upvar", Jim_UpvarCoreCommand},
14223 {"global", Jim_GlobalCoreCommand},
14224 {"string", Jim_StringCoreCommand},
14225 {"time", Jim_TimeCoreCommand},
14226 {"exit", Jim_ExitCoreCommand},
14227 {"catch", Jim_CatchCoreCommand},
14228 #ifdef JIM_REFERENCES
14229 {"ref", Jim_RefCoreCommand},
14230 {"getref", Jim_GetrefCoreCommand},
14231 {"setref", Jim_SetrefCoreCommand},
14232 {"finalize", Jim_FinalizeCoreCommand},
14233 {"collect", Jim_CollectCoreCommand},
14234 #endif
14235 {"rename", Jim_RenameCoreCommand},
14236 {"dict", Jim_DictCoreCommand},
14237 {"subst", Jim_SubstCoreCommand},
14238 {"info", Jim_InfoCoreCommand},
14239 {"exists", Jim_ExistsCoreCommand},
14240 {"split", Jim_SplitCoreCommand},
14241 {"join", Jim_JoinCoreCommand},
14242 {"format", Jim_FormatCoreCommand},
14243 {"scan", Jim_ScanCoreCommand},
14244 {"error", Jim_ErrorCoreCommand},
14245 {"lrange", Jim_LrangeCoreCommand},
14246 {"lrepeat", Jim_LrepeatCoreCommand},
14247 {"env", Jim_EnvCoreCommand},
14248 {"source", Jim_SourceCoreCommand},
14249 {"lreverse", Jim_LreverseCoreCommand},
14250 {"range", Jim_RangeCoreCommand},
14251 {"rand", Jim_RandCoreCommand},
14252 {"tailcall", Jim_TailcallCoreCommand},
14253 {"local", Jim_LocalCoreCommand},
14254 {"upcall", Jim_UpcallCoreCommand},
14255 {NULL, NULL},
14258 void Jim_RegisterCoreCommands(Jim_Interp *interp)
14260 int i = 0;
14262 while (Jim_CoreCommandsTable[i].name != NULL) {
14263 Jim_CreateCommand(interp,
14264 Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
14265 i++;
14269 /* -----------------------------------------------------------------------------
14270 * Interactive prompt
14271 * ---------------------------------------------------------------------------*/
14272 void Jim_MakeErrorMessage(Jim_Interp *interp)
14274 Jim_Obj *argv[2];
14276 argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
14277 argv[1] = interp->result;
14279 Jim_EvalObjVector(interp, 2, argv);
14282 static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
14283 const char *prefix, const char *const *tablePtr, const char *name)
14285 int count;
14286 char **tablePtrSorted;
14287 int i;
14289 for (count = 0; tablePtr[count]; count++) {
14292 if (name == NULL) {
14293 name = "option";
14296 Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
14297 tablePtrSorted = Jim_Alloc(sizeof(char *) * count);
14298 memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
14299 qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
14300 for (i = 0; i < count; i++) {
14301 if (i + 1 == count && count > 1) {
14302 Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
14304 Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
14305 if (i + 1 != count) {
14306 Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
14309 Jim_Free(tablePtrSorted);
14312 int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
14313 const char *const *tablePtr, int *indexPtr, const char *name, int flags)
14315 const char *bad = "bad ";
14316 const char *const *entryPtr = NULL;
14317 int i;
14318 int match = -1;
14319 int arglen;
14320 const char *arg = Jim_GetString(objPtr, &arglen);
14322 *indexPtr = -1;
14324 for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
14325 if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
14326 /* Found an exact match */
14327 *indexPtr = i;
14328 return JIM_OK;
14330 if (flags & JIM_ENUM_ABBREV) {
14331 /* Accept an unambiguous abbreviation.
14332 * Note that '-' doesnt' consitute a valid abbreviation
14334 if (strncmp(arg, *entryPtr, arglen) == 0) {
14335 if (*arg == '-' && arglen == 1) {
14336 break;
14338 if (match >= 0) {
14339 bad = "ambiguous ";
14340 goto ambiguous;
14342 match = i;
14347 /* If we had an unambiguous partial match */
14348 if (match >= 0) {
14349 *indexPtr = match;
14350 return JIM_OK;
14353 ambiguous:
14354 if (flags & JIM_ERRMSG) {
14355 JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
14357 return JIM_ERR;
14360 int Jim_FindByName(const char *name, const char * const array[], size_t len)
14362 int i;
14364 for (i = 0; i < (int)len; i++) {
14365 if (array[i] && strcmp(array[i], name) == 0) {
14366 return i;
14369 return -1;
14372 int Jim_IsDict(Jim_Obj *objPtr)
14374 return objPtr->typePtr == &dictObjType;
14377 int Jim_IsList(Jim_Obj *objPtr)
14379 return objPtr->typePtr == &listObjType;
14383 * Very simple printf-like formatting, designed for error messages.
14385 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14386 * The resulting string is created and set as the result.
14388 * Each '%s' should correspond to a regular string parameter.
14389 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14390 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14392 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14394 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14396 void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
14398 /* Initial space needed */
14399 int len = strlen(format);
14400 int extra = 0;
14401 int n = 0;
14402 const char *params[5];
14403 char *buf;
14404 va_list args;
14405 int i;
14407 va_start(args, format);
14409 for (i = 0; i < len && n < 5; i++) {
14410 int l;
14412 if (strncmp(format + i, "%s", 2) == 0) {
14413 params[n] = va_arg(args, char *);
14415 l = strlen(params[n]);
14417 else if (strncmp(format + i, "%#s", 3) == 0) {
14418 Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
14420 params[n] = Jim_GetString(objPtr, &l);
14422 else {
14423 if (format[i] == '%') {
14424 i++;
14426 continue;
14428 n++;
14429 extra += l;
14432 len += extra;
14433 buf = Jim_Alloc(len + 1);
14434 len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
14436 Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
14439 /* stubs */
14440 #ifndef jim_ext_package
14441 int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
14443 return JIM_OK;
14445 #endif
14446 #ifndef jim_ext_aio
14447 FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
14449 Jim_SetResultString(interp, "aio not enabled", -1);
14450 return NULL;
14452 #endif
14456 * Local Variables: ***
14457 * c-basic-offset: 4 ***
14458 * tab-width: 4 ***
14459 * End: ***