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
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.
44 #define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
59 #include "jimautoconf.h"
62 #ifdef HAVE_SYS_TIME_H
68 #ifdef HAVE_CRT_EXTERNS_H
69 #include <crt_externs.h>
72 /* For INFINITY, even if math functions are not enabled */
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 */
80 #define TCL_LIBRARY "."
82 #ifndef TCL_PLATFORM_OS
83 #define TCL_PLATFORM_OS "unknown"
85 #ifndef TCL_PLATFORM_PLATFORM
86 #define TCL_PLATFORM_PLATFORM "unknown"
88 #ifndef TCL_PLATFORM_PATH_SEPARATOR
89 #define TCL_PLATFORM_PATH_SEPARATOR ":"
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*/
99 #define JIM_DEBUG_COMMAND
100 #define JIM_DEBUG_PANIC
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
112 /* -----------------------------------------------------------------------------
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
,
127 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
128 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
129 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
130 const char *prefix
, const char *const *tablePtr
, const char *name
);
131 static void JimDeleteLocalProcs(Jim_Interp
*interp
);
132 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, Jim_Obj
*fileNameObj
, int linenr
,
133 int argc
, Jim_Obj
*const *argv
);
134 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
135 Jim_Obj
*fileNameObj
, int linenr
);
136 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
);
137 static int JimSign(jim_wide w
);
138 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
);
139 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
);
140 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
);
143 /* Fast access to the int (wide) value of an object which is known to be of int type */
144 #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
146 #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
148 static int utf8_tounicode_case(const char *s
, int *uc
, int upper
)
150 int l
= utf8_tounicode(s
, uc
);
152 *uc
= utf8_upper(*uc
);
157 /* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
158 #define JIM_CHARSET_SCAN 2
159 #define JIM_CHARSET_GLOB 0
162 * pattern points to a string like "[^a-z\ub5]"
164 * The pattern may contain trailing chars, which are ignored.
166 * The pattern is matched against unicode char 'c'.
168 * If (flags & JIM_NOCASE), case is ignored when matching.
169 * If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
170 * of the charset, per scan, rather than glob/string match.
172 * If the unicode char 'c' matches that set, returns a pointer to the ']' character,
173 * or the null character if the ']' is missing.
175 * Returns NULL on no match.
177 static const char *JimCharsetMatch(const char *pattern
, int c
, int flags
)
184 if (flags
& JIM_NOCASE
) {
189 if (flags
& JIM_CHARSET_SCAN
) {
190 if (*pattern
== '^') {
195 /* Special case. If the first char is ']', it is part of the set */
196 if (*pattern
== ']') {
201 while (*pattern
&& *pattern
!= ']') {
203 if (pattern
[0] == '\\') {
205 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
208 /* Is this a range? a-z */
212 pattern
+= utf8_tounicode_case(pattern
, &start
, nocase
);
213 if (pattern
[0] == '-' && pattern
[1]) {
215 pattern
+= utf8_tounicode(pattern
, &pchar
);
216 pattern
+= utf8_tounicode_case(pattern
, &end
, nocase
);
218 /* Handle reversed range too */
219 if ((c
>= start
&& c
<= end
) || (c
>= end
&& c
<= start
)) {
235 return match
? pattern
: NULL
;
238 /* Glob-style pattern matching. */
240 /* Note: string *must* be valid UTF-8 sequences
241 * slen is a char length, not byte counts.
243 static int JimGlobMatch(const char *pattern
, const char *string
, int nocase
)
248 switch (pattern
[0]) {
250 while (pattern
[1] == '*') {
255 return 1; /* match */
258 /* Recursive call - Does the remaining pattern match anywhere? */
259 if (JimGlobMatch(pattern
, string
, nocase
))
260 return 1; /* match */
261 string
+= utf8_tounicode(string
, &c
);
263 return 0; /* no match */
266 string
+= utf8_tounicode(string
, &c
);
270 string
+= utf8_tounicode(string
, &c
);
271 pattern
= JimCharsetMatch(pattern
+ 1, c
, nocase
? JIM_NOCASE
: 0);
276 /* Ran out of pattern (no ']') */
287 string
+= utf8_tounicode_case(string
, &c
, nocase
);
288 utf8_tounicode_case(pattern
, &pchar
, nocase
);
294 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
296 while (*pattern
== '*') {
302 if (!*pattern
&& !*string
) {
308 static int JimStringMatch(Jim_Interp
*interp
, Jim_Obj
*patternObj
, const char *string
, int nocase
)
310 return JimGlobMatch(Jim_String(patternObj
), string
, nocase
);
314 * string comparison works on binary data.
316 * Note that the lengths are byte lengths, not char lengths.
318 static int JimStringCompare(const char *s1
, int l1
, const char *s2
, int l2
)
321 return memcmp(s1
, s2
, l1
) <= 0 ? -1 : 1;
324 return memcmp(s1
, s2
, l2
) >= 0 ? 1 : -1;
327 return JimSign(memcmp(s1
, s2
, l1
));
334 * If maxchars is -1, compares to end of string.
335 * Otherwise compares at most 'maxchars' characters.
337 static int JimStringCompareNoCase(const char *s1
, const char *s2
, int maxchars
)
339 while (*s1
&& *s2
&& maxchars
) {
341 s1
+= utf8_tounicode_case(s1
, &c1
, 1);
342 s2
+= utf8_tounicode_case(s2
, &c2
, 1);
344 return JimSign(c1
- c2
);
351 /* One string or both terminated */
361 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
362 * The index of the first occurrence of s1 in s2 is returned.
363 * If s1 is not found inside s2, -1 is returned. */
364 static int JimStringFirst(const char *s1
, int l1
, const char *s2
, int l2
, int idx
)
369 if (!l1
|| !l2
|| l1
> l2
) {
374 s2
+= utf8_index(s2
, idx
);
376 l1bytelen
= utf8_index(s1
, l1
);
378 for (i
= idx
; i
<= l2
- l1
; i
++) {
380 if (memcmp(s2
, s1
, l1bytelen
) == 0) {
383 s2
+= utf8_tounicode(s2
, &c
);
389 * Note: Lengths and return value are in bytes, not chars.
391 static int JimStringLast(const char *s1
, int l1
, const char *s2
, int l2
)
395 if (!l1
|| !l2
|| l1
> l2
)
398 /* Now search for the needle */
399 for (p
= s2
+ l2
- 1; p
!= s2
- 1; p
--) {
400 if (*p
== *s1
&& memcmp(s1
, p
, l1
) == 0) {
409 * Note: Lengths and return value are in chars.
411 static int JimStringLastUtf8(const char *s1
, int l1
, const char *s2
, int l2
)
413 int n
= JimStringLast(s1
, utf8_index(s1
, l1
), s2
, utf8_index(s2
, l2
));
415 n
= utf8_strlen(s2
, n
);
421 int Jim_WideToString(char *buf
, jim_wide wideValue
)
423 const char *fmt
= "%" JIM_WIDE_MODIFIER
;
425 return sprintf(buf
, fmt
, wideValue
);
429 * After an strtol()/strtod()-like conversion,
430 * check whether something was converted and that
431 * the only thing left is white space.
433 * Returns JIM_OK or JIM_ERR.
435 static int JimCheckConversion(const char *str
, const char *endptr
)
437 if (str
[0] == '\0' || str
== endptr
) {
441 if (endptr
[0] != '\0') {
443 if (!isspace(UCHAR(*endptr
))) {
452 int Jim_StringToWide(const char *str
, jim_wide
* widePtr
, int base
)
456 *widePtr
= strtoull(str
, &endptr
, base
);
458 return JimCheckConversion(str
, endptr
);
461 int Jim_DoubleToString(char *buf
, double doubleValue
)
466 len
= sprintf(buf
, "%.12g", doubleValue
);
468 /* Add a final ".0" if it's a number. But not
471 if (*buf
== '.' || isalpha(UCHAR(*buf
))) {
472 /* inf -> Inf, nan -> Nan */
473 if (*buf
== 'i' || *buf
== 'n') {
474 *buf
= toupper(UCHAR(*buf
));
477 /* Infinity -> Inf */
479 len
= buf
- buf0
+ 3;
493 int Jim_StringToDouble(const char *str
, double *doublePtr
)
497 /* Callers can check for underflow via ERANGE */
500 *doublePtr
= strtod(str
, &endptr
);
502 return JimCheckConversion(str
, endptr
);
505 static jim_wide
JimPowWide(jim_wide b
, jim_wide e
)
509 if ((b
== 0 && e
!= 0) || (e
< 0))
511 for (i
= 0; i
< e
; i
++) {
517 /* -----------------------------------------------------------------------------
519 * ---------------------------------------------------------------------------*/
520 #ifdef JIM_DEBUG_PANIC
521 void JimPanicDump(int condition
, const char *fmt
, ...)
531 fprintf(stderr
, JIM_NL
"JIM INTERPRETER PANIC: ");
532 vfprintf(stderr
, fmt
, ap
);
533 fprintf(stderr
, JIM_NL JIM_NL
);
536 #ifdef HAVE_BACKTRACE
542 size
= backtrace(array
, 40);
543 strings
= backtrace_symbols(array
, size
);
544 for (i
= 0; i
< size
; i
++)
545 fprintf(stderr
, "[backtrace] %s" JIM_NL
, strings
[i
]);
546 fprintf(stderr
, "[backtrace] Include the above lines and the output" JIM_NL
);
547 fprintf(stderr
, "[backtrace] of 'nm <executable>' in the bug report." JIM_NL
);
555 /* -----------------------------------------------------------------------------
557 * ---------------------------------------------------------------------------*/
559 void *Jim_Alloc(int size
)
564 void Jim_Free(void *ptr
)
569 void *Jim_Realloc(void *ptr
, int size
)
571 return realloc(ptr
, size
);
574 char *Jim_StrDup(const char *s
)
579 char *Jim_StrDupLen(const char *s
, int l
)
581 char *copy
= Jim_Alloc(l
+ 1);
583 memcpy(copy
, s
, l
+ 1);
584 copy
[l
] = 0; /* Just to be sure, original could be substring */
588 /* -----------------------------------------------------------------------------
589 * Time related functions
590 * ---------------------------------------------------------------------------*/
592 /* Returns microseconds of CPU used since start. */
593 static jim_wide
JimClock(void)
597 gettimeofday(&tv
, NULL
);
598 return (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
;
601 /* -----------------------------------------------------------------------------
603 * ---------------------------------------------------------------------------*/
605 /* -------------------------- private prototypes ---------------------------- */
606 static void JimExpandHashTableIfNeeded(Jim_HashTable
*ht
);
607 static unsigned int JimHashTableNextPower(unsigned int size
);
608 static Jim_HashEntry
*JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
, int replace
);
610 /* -------------------------- hash functions -------------------------------- */
612 /* Thomas Wang's 32 bit Mix Function */
613 unsigned int Jim_IntHashFunction(unsigned int key
)
624 /* Generic hash function (we are using to multiply by 9 and add the byte
626 unsigned int Jim_GenHashFunction(const unsigned char *buf
, int len
)
631 h
+= (h
<< 3) + *buf
++;
635 /* ----------------------------- API implementation ------------------------- */
637 /* reset a hashtable already initialized with ht_init().
638 * NOTE: This function should only called by ht_destroy(). */
639 static void JimResetHashTable(Jim_HashTable
*ht
)
648 /* Initialize the hash table */
649 int Jim_InitHashTable(Jim_HashTable
*ht
, const Jim_HashTableType
*type
, void *privDataPtr
)
651 JimResetHashTable(ht
);
653 ht
->privdata
= privDataPtr
;
657 /* Resize the table to the minimal size that contains all the elements,
658 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
659 void Jim_ResizeHashTable(Jim_HashTable
*ht
)
661 int minimal
= ht
->used
;
663 if (minimal
< JIM_HT_INITIAL_SIZE
)
664 minimal
= JIM_HT_INITIAL_SIZE
;
665 Jim_ExpandHashTable(ht
, minimal
);
668 /* Expand or create the hashtable */
669 void Jim_ExpandHashTable(Jim_HashTable
*ht
, unsigned int size
)
671 Jim_HashTable n
; /* the new hashtable */
672 unsigned int realsize
= JimHashTableNextPower(size
), i
;
674 /* the size is invalid if it is smaller than the number of
675 * elements already inside the hashtable */
676 if (size
<= ht
->used
)
679 Jim_InitHashTable(&n
, ht
->type
, ht
->privdata
);
681 n
.sizemask
= realsize
- 1;
682 n
.table
= Jim_Alloc(realsize
* sizeof(Jim_HashEntry
*));
684 /* Initialize all the pointers to NULL */
685 memset(n
.table
, 0, realsize
* sizeof(Jim_HashEntry
*));
687 /* Copy all the elements from the old to the new table:
688 * note that if the old hash table is empty ht->used is zero,
689 * so Jim_ExpandHashTable just creates an empty hash table. */
691 for (i
= 0; ht
->used
> 0; i
++) {
692 Jim_HashEntry
*he
, *nextHe
;
694 if (ht
->table
[i
] == NULL
)
697 /* For each hash entry on this slot... */
703 /* Get the new element index */
704 h
= Jim_HashKey(ht
, he
->key
) & n
.sizemask
;
705 he
->next
= n
.table
[h
];
708 /* Pass to the next element */
712 assert(ht
->used
== 0);
715 /* Remap the new hashtable in the old */
719 /* Add an element to the target hash table */
720 int Jim_AddHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
722 Jim_HashEntry
*entry
;
724 /* Get the index of the new element, or -1 if
725 * the element already exists. */
726 entry
= JimInsertHashEntry(ht
, key
, 0);
730 /* Set the hash entry fields. */
731 Jim_SetHashKey(ht
, entry
, key
);
732 Jim_SetHashVal(ht
, entry
, val
);
736 /* Add an element, discarding the old if the key already exists */
737 int Jim_ReplaceHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
740 Jim_HashEntry
*entry
;
742 /* Get the index of the new element, or -1 if
743 * the element already exists. */
744 entry
= JimInsertHashEntry(ht
, key
, 1);
746 /* It already exists, so replace the value */
747 Jim_FreeEntryVal(ht
, entry
);
751 /* Doesn't exist, so set the key */
752 Jim_SetHashKey(ht
, entry
, key
);
755 Jim_SetHashVal(ht
, entry
, val
);
760 /* Search and remove an element */
761 int Jim_DeleteHashEntry(Jim_HashTable
*ht
, const void *key
)
764 Jim_HashEntry
*he
, *prevHe
;
768 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
773 if (Jim_CompareHashKeys(ht
, key
, he
->key
)) {
774 /* Unlink the element from the list */
776 prevHe
->next
= he
->next
;
778 ht
->table
[h
] = he
->next
;
779 Jim_FreeEntryKey(ht
, he
);
780 Jim_FreeEntryVal(ht
, he
);
788 return JIM_ERR
; /* not found */
791 /* Destroy an entire hash table */
792 int Jim_FreeHashTable(Jim_HashTable
*ht
)
796 /* Free all the elements */
797 for (i
= 0; ht
->used
> 0; i
++) {
798 Jim_HashEntry
*he
, *nextHe
;
800 if ((he
= ht
->table
[i
]) == NULL
)
804 Jim_FreeEntryKey(ht
, he
);
805 Jim_FreeEntryVal(ht
, he
);
811 /* Free the table and the allocated cache structure */
813 /* Re-initialize the table */
814 JimResetHashTable(ht
);
815 return JIM_OK
; /* never fails */
818 Jim_HashEntry
*Jim_FindHashEntry(Jim_HashTable
*ht
, const void *key
)
825 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
828 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
835 Jim_HashTableIterator
*Jim_GetHashTableIterator(Jim_HashTable
*ht
)
837 Jim_HashTableIterator
*iter
= Jim_Alloc(sizeof(*iter
));
842 iter
->nextEntry
= NULL
;
846 Jim_HashEntry
*Jim_NextHashEntry(Jim_HashTableIterator
*iter
)
849 if (iter
->entry
== NULL
) {
851 if (iter
->index
>= (signed)iter
->ht
->size
)
853 iter
->entry
= iter
->ht
->table
[iter
->index
];
856 iter
->entry
= iter
->nextEntry
;
859 /* We need to save the 'next' here, the iterator user
860 * may delete the entry we are returning. */
861 iter
->nextEntry
= iter
->entry
->next
;
868 /* ------------------------- private functions ------------------------------ */
870 /* Expand the hash table if needed */
871 static void JimExpandHashTableIfNeeded(Jim_HashTable
*ht
)
873 /* If the hash table is empty expand it to the intial size,
874 * if the table is "full" dobule its size. */
876 Jim_ExpandHashTable(ht
, JIM_HT_INITIAL_SIZE
);
877 if (ht
->size
== ht
->used
)
878 Jim_ExpandHashTable(ht
, ht
->size
* 2);
881 /* Our hash table capability is a power of two */
882 static unsigned int JimHashTableNextPower(unsigned int size
)
884 unsigned int i
= JIM_HT_INITIAL_SIZE
;
886 if (size
>= 2147483648U)
895 /* Returns the index of a free slot that can be populated with
896 * an hash entry for the given 'key'.
897 * If the key already exists, -1 is returned. */
898 static Jim_HashEntry
*JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
, int replace
)
903 /* Expand the hashtable if needed */
904 JimExpandHashTableIfNeeded(ht
);
906 /* Compute the key hash value */
907 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
908 /* Search if this slot does not already contain the given key */
911 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
912 return replace
? he
: NULL
;
916 /* Allocates the memory and stores key */
917 he
= Jim_Alloc(sizeof(*he
));
918 he
->next
= ht
->table
[h
];
926 /* ----------------------- StringCopy Hash Table Type ------------------------*/
928 static unsigned int JimStringCopyHTHashFunction(const void *key
)
930 return Jim_GenHashFunction(key
, strlen(key
));
933 static void *JimStringCopyHTDup(void *privdata
, const void *key
)
938 static int JimStringCopyHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
940 return strcmp(key1
, key2
) == 0;
943 static void JimStringCopyHTKeyDestructor(void *privdata
, void *key
)
948 static const Jim_HashTableType JimPackageHashTableType
= {
949 JimStringCopyHTHashFunction
, /* hash function */
950 JimStringCopyHTDup
, /* key dup */
952 JimStringCopyHTKeyCompare
, /* key compare */
953 JimStringCopyHTKeyDestructor
, /* key destructor */
954 NULL
/* val destructor */
957 typedef struct AssocDataValue
959 Jim_InterpDeleteProc
*delProc
;
963 static void JimAssocDataHashTableValueDestructor(void *privdata
, void *data
)
965 AssocDataValue
*assocPtr
= (AssocDataValue
*) data
;
967 if (assocPtr
->delProc
!= NULL
)
968 assocPtr
->delProc((Jim_Interp
*)privdata
, assocPtr
->data
);
972 static const Jim_HashTableType JimAssocDataHashTableType
= {
973 JimStringCopyHTHashFunction
, /* hash function */
974 JimStringCopyHTDup
, /* key dup */
976 JimStringCopyHTKeyCompare
, /* key compare */
977 JimStringCopyHTKeyDestructor
, /* key destructor */
978 JimAssocDataHashTableValueDestructor
/* val destructor */
981 /* -----------------------------------------------------------------------------
982 * Stack - This is a simple generic stack implementation. It is used for
983 * example in the 'expr' expression compiler.
984 * ---------------------------------------------------------------------------*/
985 void Jim_InitStack(Jim_Stack
*stack
)
989 stack
->vector
= NULL
;
992 void Jim_FreeStack(Jim_Stack
*stack
)
994 Jim_Free(stack
->vector
);
997 int Jim_StackLen(Jim_Stack
*stack
)
1002 void Jim_StackPush(Jim_Stack
*stack
, void *element
)
1004 int neededLen
= stack
->len
+ 1;
1006 if (neededLen
> stack
->maxlen
) {
1007 stack
->maxlen
= neededLen
< 20 ? 20 : neededLen
* 2;
1008 stack
->vector
= Jim_Realloc(stack
->vector
, sizeof(void *) * stack
->maxlen
);
1010 stack
->vector
[stack
->len
] = element
;
1014 void *Jim_StackPop(Jim_Stack
*stack
)
1016 if (stack
->len
== 0)
1019 return stack
->vector
[stack
->len
];
1022 void *Jim_StackPeek(Jim_Stack
*stack
)
1024 if (stack
->len
== 0)
1026 return stack
->vector
[stack
->len
- 1];
1029 void Jim_FreeStackElements(Jim_Stack
*stack
, void (*freeFunc
) (void *ptr
))
1033 for (i
= 0; i
< stack
->len
; i
++)
1034 freeFunc(stack
->vector
[i
]);
1037 /* -----------------------------------------------------------------------------
1039 * ---------------------------------------------------------------------------*/
1042 #define JIM_TT_NONE 0 /* No token returned */
1043 #define JIM_TT_STR 1 /* simple string */
1044 #define JIM_TT_ESC 2 /* string that needs escape chars conversion */
1045 #define JIM_TT_VAR 3 /* var substitution */
1046 #define JIM_TT_DICTSUGAR 4 /* Syntax sugar for [dict get], $foo(bar) */
1047 #define JIM_TT_CMD 5 /* command substitution */
1048 /* Note: Keep these three together for TOKEN_IS_SEP() */
1049 #define JIM_TT_SEP 6 /* word separator. arg is # of tokens. -ve if {*} */
1050 #define JIM_TT_EOL 7 /* line separator */
1051 #define JIM_TT_EOF 8 /* end of script */
1053 #define JIM_TT_LINE 9 /* special 'start-of-line' token. arg is # of arguments to the command. -ve if {*} */
1054 #define JIM_TT_WORD 10 /* special 'start-of-word' token. arg is # of tokens to combine. -ve if {*} */
1056 /* Additional token types needed for expressions */
1057 #define JIM_TT_SUBEXPR_START 11
1058 #define JIM_TT_SUBEXPR_END 12
1059 #define JIM_TT_SUBEXPR_COMMA 13
1060 #define JIM_TT_EXPR_INT 14
1061 #define JIM_TT_EXPR_DOUBLE 15
1063 #define JIM_TT_EXPRSUGAR 16 /* $(expression) */
1065 /* Operator token types start here */
1066 #define JIM_TT_EXPR_OP 20
1068 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1071 #define JIM_PS_DEF 0 /* Default state */
1072 #define JIM_PS_QUOTE 1 /* Inside "" */
1073 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1075 /* Parser context structure. The same context is used both to parse
1076 * Tcl scripts and lists. */
1079 const char *p
; /* Pointer to the point of the program we are parsing */
1080 int len
; /* Remaining length */
1081 int linenr
; /* Current line number */
1083 const char *tend
; /* Returned token is at tstart-tend in 'prg'. */
1084 int tline
; /* Line number of the returned token */
1085 int tt
; /* Token type */
1086 int eof
; /* Non zero if EOF condition is true. */
1087 int state
; /* Parser state */
1088 int comment
; /* Non zero if the next chars may be a comment. */
1089 char missing
; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1090 int missingline
; /* Line number starting the missing token */
1094 * Results of missing quotes, braces, etc. from parsing.
1096 struct JimParseResult
{
1097 char missing
; /* From JimParserCtx.missing */
1098 int line
; /* From JimParserCtx.missingline */
1101 static int JimParseScript(struct JimParserCtx
*pc
);
1102 static int JimParseSep(struct JimParserCtx
*pc
);
1103 static int JimParseEol(struct JimParserCtx
*pc
);
1104 static int JimParseCmd(struct JimParserCtx
*pc
);
1105 static int JimParseQuote(struct JimParserCtx
*pc
);
1106 static int JimParseVar(struct JimParserCtx
*pc
);
1107 static int JimParseBrace(struct JimParserCtx
*pc
);
1108 static int JimParseStr(struct JimParserCtx
*pc
);
1109 static int JimParseComment(struct JimParserCtx
*pc
);
1110 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1111 static int JimParseSubQuote(struct JimParserCtx
*pc
);
1112 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1113 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
);
1115 /* Initialize a parser context.
1116 * 'prg' is a pointer to the program text, linenr is the line
1117 * number of the first line contained in the program. */
1118 static void JimParserInit(struct JimParserCtx
*pc
, const char *prg
, int len
, int linenr
)
1125 pc
->tt
= JIM_TT_NONE
;
1127 pc
->state
= JIM_PS_DEF
;
1128 pc
->linenr
= linenr
;
1131 pc
->missingline
= linenr
;
1134 static int JimParseScript(struct JimParserCtx
*pc
)
1136 while (1) { /* the while is used to reiterate with continue if needed */
1139 pc
->tend
= pc
->p
- 1;
1140 pc
->tline
= pc
->linenr
;
1141 pc
->tt
= JIM_TT_EOL
;
1147 if (*(pc
->p
+ 1) == '\n' && pc
->state
== JIM_PS_DEF
) {
1148 return JimParseSep(pc
);
1151 return JimParseStr(pc
);
1156 if (pc
->state
== JIM_PS_DEF
)
1157 return JimParseSep(pc
);
1159 return JimParseStr(pc
);
1163 if (pc
->state
== JIM_PS_DEF
)
1164 return JimParseEol(pc
);
1165 return JimParseStr(pc
);
1168 return JimParseCmd(pc
);
1171 if (JimParseVar(pc
) == JIM_ERR
) {
1172 /* An orphan $. Create as a separate token */
1173 pc
->tstart
= pc
->tend
= pc
->p
++;
1175 pc
->tt
= JIM_TT_ESC
;
1180 JimParseComment(pc
);
1183 return JimParseStr(pc
);
1186 return JimParseStr(pc
);
1192 static int JimParseSep(struct JimParserCtx
*pc
)
1195 pc
->tline
= pc
->linenr
;
1196 while (isspace(UCHAR(*pc
->p
)) || (*pc
->p
== '\\' && *(pc
->p
+ 1) == '\n')) {
1197 if (*pc
->p
== '\n') {
1200 if (*pc
->p
== '\\') {
1208 pc
->tend
= pc
->p
- 1;
1209 pc
->tt
= JIM_TT_SEP
;
1213 static int JimParseEol(struct JimParserCtx
*pc
)
1216 pc
->tline
= pc
->linenr
;
1217 while (isspace(UCHAR(*pc
->p
)) || *pc
->p
== ';') {
1223 pc
->tend
= pc
->p
- 1;
1224 pc
->tt
= JIM_TT_EOL
;
1229 ** Here are the rules for parsing:
1230 ** {braced expression}
1231 ** - Count open and closing braces
1232 ** - Backslash escapes meaning of braces
1234 ** "quoted expression"
1235 ** - First double quote at start of word terminates the expression
1236 ** - Backslash escapes quote and bracket
1237 ** - [commands brackets] are counted/nested
1238 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1240 ** [command expression]
1241 ** - Count open and closing brackets
1242 ** - Backslash escapes quote, bracket and brace
1243 ** - [commands brackets] are counted/nested
1244 ** - "quoted expressions" are parsed according to quoting rules
1245 ** - {braced expressions} are parsed according to brace rules
1247 ** For everything, backslash escapes the next char, newline increments current line
1251 * Parses a braced expression starting at pc->p.
1253 * Positions the parser at the end of the braced expression,
1254 * sets pc->tend and possibly pc->missing.
1256 static void JimParseSubBrace(struct JimParserCtx
*pc
)
1260 /* Skip the brace */
1267 if (*++pc
->p
== '\n') {
1280 pc
->tend
= pc
->p
- 1;
1295 pc
->missingline
= pc
->tline
;
1296 pc
->tend
= pc
->p
- 1;
1300 * Parses a quoted expression starting at pc->p.
1302 * Positions the parser at the end of the quoted expression,
1303 * sets pc->tend and possibly pc->missing.
1305 * Returns the type of the token of the string,
1306 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1309 static int JimParseSubQuote(struct JimParserCtx
*pc
)
1311 int tt
= JIM_TT_STR
;
1312 int line
= pc
->tline
;
1314 /* Skip the quote */
1321 if (*++pc
->p
== '\n') {
1330 pc
->tend
= pc
->p
- 1;
1352 pc
->missingline
= line
;
1353 pc
->tend
= pc
->p
- 1;
1358 * Parses a [command] expression starting at pc->p.
1360 * Positions the parser at the end of the command expression,
1361 * sets pc->tend and possibly pc->missing.
1363 static void JimParseSubCmd(struct JimParserCtx
*pc
)
1366 int startofword
= 1;
1367 int line
= pc
->tline
;
1369 /* Skip the bracket */
1376 if (*++pc
->p
== '\n') {
1389 pc
->tend
= pc
->p
- 1;
1398 JimParseSubQuote(pc
);
1404 JimParseSubBrace(pc
);
1412 startofword
= isspace(UCHAR(*pc
->p
));
1417 pc
->missingline
= line
;
1418 pc
->tend
= pc
->p
- 1;
1421 static int JimParseBrace(struct JimParserCtx
*pc
)
1423 pc
->tstart
= pc
->p
+ 1;
1424 pc
->tline
= pc
->linenr
;
1425 pc
->tt
= JIM_TT_STR
;
1426 JimParseSubBrace(pc
);
1430 static int JimParseCmd(struct JimParserCtx
*pc
)
1432 pc
->tstart
= pc
->p
+ 1;
1433 pc
->tline
= pc
->linenr
;
1434 pc
->tt
= JIM_TT_CMD
;
1439 static int JimParseQuote(struct JimParserCtx
*pc
)
1441 pc
->tstart
= pc
->p
+ 1;
1442 pc
->tline
= pc
->linenr
;
1443 pc
->tt
= JimParseSubQuote(pc
);
1447 static int JimParseVar(struct JimParserCtx
*pc
)
1453 #ifdef EXPRSUGAR_BRACKET
1454 if (*pc
->p
== '[') {
1455 /* Parse $[...] expr shorthand syntax */
1457 pc
->tt
= JIM_TT_EXPRSUGAR
;
1463 pc
->tt
= JIM_TT_VAR
;
1464 pc
->tline
= pc
->linenr
;
1466 if (*pc
->p
== '{') {
1467 pc
->tstart
= ++pc
->p
;
1470 while (pc
->len
&& *pc
->p
!= '}') {
1471 if (*pc
->p
== '\n') {
1477 pc
->tend
= pc
->p
- 1;
1485 /* Skip double colon, but not single colon! */
1486 if (pc
->p
[0] == ':' && pc
->p
[1] == ':') {
1491 if (isalnum(UCHAR(*pc
->p
)) || *pc
->p
== '_') {
1498 /* Parse [dict get] syntax sugar. */
1499 if (*pc
->p
== '(') {
1501 const char *paren
= NULL
;
1503 pc
->tt
= JIM_TT_DICTSUGAR
;
1505 while (count
&& pc
->len
) {
1508 if (*pc
->p
== '\\' && pc
->len
>= 1) {
1512 else if (*pc
->p
== '(') {
1515 else if (*pc
->p
== ')') {
1525 /* Did not find a matching paren. Back up */
1527 pc
->len
+= (pc
->p
- paren
);
1530 #ifndef EXPRSUGAR_BRACKET
1531 if (*pc
->tstart
== '(') {
1532 pc
->tt
= JIM_TT_EXPRSUGAR
;
1536 pc
->tend
= pc
->p
- 1;
1538 /* Check if we parsed just the '$' character.
1539 * That's not a variable so an error is returned
1540 * to tell the state machine to consider this '$' just
1542 if (pc
->tstart
== pc
->p
) {
1550 static int JimParseStr(struct JimParserCtx
*pc
)
1552 if (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1553 pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_STR
) {
1554 /* Starting a new word */
1555 if (*pc
->p
== '{') {
1556 return JimParseBrace(pc
);
1558 if (*pc
->p
== '"') {
1559 pc
->state
= JIM_PS_QUOTE
;
1562 /* In case the end quote is missing */
1563 pc
->missingline
= pc
->tline
;
1567 pc
->tline
= pc
->linenr
;
1570 if (pc
->state
== JIM_PS_QUOTE
) {
1573 pc
->tend
= pc
->p
- 1;
1574 pc
->tt
= JIM_TT_ESC
;
1579 if (pc
->state
== JIM_PS_DEF
&& *(pc
->p
+ 1) == '\n') {
1580 pc
->tend
= pc
->p
- 1;
1581 pc
->tt
= JIM_TT_ESC
;
1585 if (*(pc
->p
+ 1) == '\n') {
1593 /* If the following token is not '$' just keep going */
1594 if (pc
->len
> 1 && pc
->p
[1] != '$') {
1598 /* Only need a separate ')' token if the previous was a var */
1599 if (*pc
->p
== '(' || pc
->tt
== JIM_TT_VAR
) {
1600 if (pc
->p
== pc
->tstart
) {
1601 /* At the start of the token, so just return this char */
1605 pc
->tend
= pc
->p
- 1;
1606 pc
->tt
= JIM_TT_ESC
;
1613 pc
->tend
= pc
->p
- 1;
1614 pc
->tt
= JIM_TT_ESC
;
1622 if (pc
->state
== JIM_PS_DEF
) {
1623 pc
->tend
= pc
->p
- 1;
1624 pc
->tt
= JIM_TT_ESC
;
1627 else if (*pc
->p
== '\n') {
1632 if (pc
->state
== JIM_PS_QUOTE
) {
1633 pc
->tend
= pc
->p
- 1;
1634 pc
->tt
= JIM_TT_ESC
;
1637 pc
->state
= JIM_PS_DEF
;
1645 return JIM_OK
; /* unreached */
1648 static int JimParseComment(struct JimParserCtx
*pc
)
1651 if (*pc
->p
== '\n') {
1653 if (*(pc
->p
- 1) != '\\') {
1665 /* xdigitval and odigitval are helper functions for JimEscape() */
1666 static int xdigitval(int c
)
1668 if (c
>= '0' && c
<= '9')
1670 if (c
>= 'a' && c
<= 'f')
1671 return c
- 'a' + 10;
1672 if (c
>= 'A' && c
<= 'F')
1673 return c
- 'A' + 10;
1677 static int odigitval(int c
)
1679 if (c
>= '0' && c
<= '7')
1684 /* Perform Tcl escape substitution of 's', storing the result
1685 * string into 'dest'. The escaped string is guaranteed to
1686 * be the same length or shorted than the source string.
1687 * Slen is the length of the string at 's', if it's -1 the string
1688 * length will be calculated by the function.
1690 * The function returns the length of the resulting string. */
1691 static int JimEscape(char *dest
, const char *s
, int slen
)
1699 for (i
= 0; i
< slen
; i
++) {
1729 /* A unicode or hex sequence.
1730 * \u Expect 1-4 hex chars and convert to utf-8.
1731 * \x Expect 1-2 hex chars and convert to hex.
1732 * An invalid sequence means simply the escaped char.
1740 for (k
= 0; k
< (s
[i
] == 'u' ? 4 : 2); k
++) {
1741 int c
= xdigitval(s
[i
+ k
+ 1]);
1745 val
= (val
<< 4) | c
;
1748 /* Got a valid sequence, so convert */
1750 p
+= utf8_fromunicode(p
, val
);
1758 /* Not a valid codepoint, just an escaped char */
1771 /* Replace all spaces and tabs after backslash newline with a single space*/
1775 } while (s
[i
+ 1] == ' ' || s
[i
+ 1] == '\t');
1788 int c
= odigitval(s
[i
+ 1]);
1791 c
= odigitval(s
[i
+ 2]);
1797 val
= (val
* 8) + c
;
1798 c
= odigitval(s
[i
+ 3]);
1804 val
= (val
* 8) + c
;
1825 /* Returns a dynamically allocated copy of the current token in the
1826 * parser context. The function performs conversion of escapes if
1827 * the token is of type JIM_TT_ESC.
1829 * Note that after the conversion, tokens that are grouped with
1830 * braces in the source code, are always recognizable from the
1831 * identical string obtained in a different way from the type.
1833 * For example the string:
1837 * will return as first token "*", of type JIM_TT_STR
1843 * will return as first token "*", of type JIM_TT_ESC
1845 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
)
1847 const char *start
, *end
;
1855 token
= Jim_Alloc(1);
1859 len
= (end
- start
) + 1;
1860 token
= Jim_Alloc(len
+ 1);
1861 if (pc
->tt
!= JIM_TT_ESC
) {
1862 /* No escape conversion needed? Just copy it. */
1863 memcpy(token
, start
, len
);
1867 /* Else convert the escape chars. */
1868 len
= JimEscape(token
, start
, len
);
1872 return Jim_NewStringObjNoAlloc(interp
, token
, len
);
1875 /* Parses the given string to determine if it represents a complete script.
1877 * This is useful for interactive shells implementation, for [info complete].
1879 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1880 * '{' on scripts incomplete missing one or more '}' to be balanced.
1881 * '[' on scripts incomplete missing one or more ']' to be balanced.
1882 * '"' on scripts incomplete missing a '"' char.
1884 * If the script is complete, 1 is returned, otherwise 0.
1886 int Jim_ScriptIsComplete(const char *s
, int len
, char *stateCharPtr
)
1888 struct JimParserCtx parser
;
1890 JimParserInit(&parser
, s
, len
, 1);
1891 while (!parser
.eof
) {
1892 JimParseScript(&parser
);
1895 *stateCharPtr
= parser
.missing
;
1897 return parser
.missing
== ' ';
1900 /* -----------------------------------------------------------------------------
1902 * ---------------------------------------------------------------------------*/
1903 static int JimParseListSep(struct JimParserCtx
*pc
);
1904 static int JimParseListStr(struct JimParserCtx
*pc
);
1905 static int JimParseListQuote(struct JimParserCtx
*pc
);
1907 static int JimParseList(struct JimParserCtx
*pc
)
1909 if (isspace(UCHAR(*pc
->p
))) {
1910 return JimParseListSep(pc
);
1914 return JimParseListQuote(pc
);
1917 return JimParseBrace(pc
);
1921 return JimParseListStr(pc
);
1926 pc
->tstart
= pc
->tend
= pc
->p
;
1927 pc
->tline
= pc
->linenr
;
1928 pc
->tt
= JIM_TT_EOL
;
1933 static int JimParseListSep(struct JimParserCtx
*pc
)
1936 pc
->tline
= pc
->linenr
;
1937 while (isspace(UCHAR(*pc
->p
))) {
1938 if (*pc
->p
== '\n') {
1944 pc
->tend
= pc
->p
- 1;
1945 pc
->tt
= JIM_TT_SEP
;
1949 static int JimParseListQuote(struct JimParserCtx
*pc
)
1955 pc
->tline
= pc
->linenr
;
1956 pc
->tt
= JIM_TT_STR
;
1961 pc
->tt
= JIM_TT_ESC
;
1962 if (--pc
->len
== 0) {
1963 /* Trailing backslash */
1973 pc
->tend
= pc
->p
- 1;
1982 pc
->tend
= pc
->p
- 1;
1986 static int JimParseListStr(struct JimParserCtx
*pc
)
1989 pc
->tline
= pc
->linenr
;
1990 pc
->tt
= JIM_TT_STR
;
1993 if (isspace(UCHAR(*pc
->p
))) {
1994 pc
->tend
= pc
->p
- 1;
1997 if (*pc
->p
== '\\') {
1998 if (--pc
->len
== 0) {
1999 /* Trailing backslash */
2003 pc
->tt
= JIM_TT_ESC
;
2009 pc
->tend
= pc
->p
- 1;
2013 /* -----------------------------------------------------------------------------
2014 * Jim_Obj related functions
2015 * ---------------------------------------------------------------------------*/
2017 /* Return a new initialized object. */
2018 Jim_Obj
*Jim_NewObj(Jim_Interp
*interp
)
2022 /* -- Check if there are objects in the free list -- */
2023 if (interp
->freeList
!= NULL
) {
2024 /* -- Unlink the object from the free list -- */
2025 objPtr
= interp
->freeList
;
2026 interp
->freeList
= objPtr
->nextObjPtr
;
2029 /* -- No ready to use objects: allocate a new one -- */
2030 objPtr
= Jim_Alloc(sizeof(*objPtr
));
2033 /* Object is returned with refCount of 0. Every
2034 * kind of GC implemented should take care to don't try
2035 * to scan objects with refCount == 0. */
2036 objPtr
->refCount
= 0;
2037 /* All the other fields are left not initialized to save time.
2038 * The caller will probably want to set them to the right
2041 /* -- Put the object into the live list -- */
2042 objPtr
->prevObjPtr
= NULL
;
2043 objPtr
->nextObjPtr
= interp
->liveList
;
2044 if (interp
->liveList
)
2045 interp
->liveList
->prevObjPtr
= objPtr
;
2046 interp
->liveList
= objPtr
;
2051 /* Free an object. Actually objects are never freed, but
2052 * just moved to the free objects list, where they will be
2053 * reused by Jim_NewObj(). */
2054 void Jim_FreeObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2056 /* Check if the object was already freed, panic. */
2057 JimPanic((objPtr
->refCount
!= 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr
,
2058 objPtr
->refCount
, objPtr
->typePtr
? objPtr
->typePtr
->name
: "<none>"));
2060 /* Free the internal representation */
2061 Jim_FreeIntRep(interp
, objPtr
);
2062 /* Free the string representation */
2063 if (objPtr
->bytes
!= NULL
) {
2064 if (objPtr
->bytes
!= JimEmptyStringRep
)
2065 Jim_Free(objPtr
->bytes
);
2067 /* Unlink the object from the live objects list */
2068 if (objPtr
->prevObjPtr
)
2069 objPtr
->prevObjPtr
->nextObjPtr
= objPtr
->nextObjPtr
;
2070 if (objPtr
->nextObjPtr
)
2071 objPtr
->nextObjPtr
->prevObjPtr
= objPtr
->prevObjPtr
;
2072 if (interp
->liveList
== objPtr
)
2073 interp
->liveList
= objPtr
->nextObjPtr
;
2074 /* Link the object into the free objects list */
2075 objPtr
->prevObjPtr
= NULL
;
2076 objPtr
->nextObjPtr
= interp
->freeList
;
2077 if (interp
->freeList
)
2078 interp
->freeList
->prevObjPtr
= objPtr
;
2079 interp
->freeList
= objPtr
;
2080 objPtr
->refCount
= -1;
2083 /* Invalidate the string representation of an object. */
2084 void Jim_InvalidateStringRep(Jim_Obj
*objPtr
)
2086 if (objPtr
->bytes
!= NULL
) {
2087 if (objPtr
->bytes
!= JimEmptyStringRep
)
2088 Jim_Free(objPtr
->bytes
);
2090 objPtr
->bytes
= NULL
;
2093 #define Jim_SetStringRep(o, b, l) \
2094 do { (o)->bytes = b; (o)->length = l; } while (0)
2096 /* Set the initial string representation for an object.
2097 * Does not try to free an old one. */
2098 void Jim_InitStringRep(Jim_Obj
*objPtr
, const char *bytes
, int length
)
2101 objPtr
->bytes
= JimEmptyStringRep
;
2105 objPtr
->bytes
= Jim_Alloc(length
+ 1);
2106 objPtr
->length
= length
;
2107 memcpy(objPtr
->bytes
, bytes
, length
);
2108 objPtr
->bytes
[length
] = '\0';
2112 /* Duplicate an object. The returned object has refcount = 0. */
2113 Jim_Obj
*Jim_DuplicateObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2117 dupPtr
= Jim_NewObj(interp
);
2118 if (objPtr
->bytes
== NULL
) {
2119 /* Object does not have a valid string representation. */
2120 dupPtr
->bytes
= NULL
;
2123 Jim_InitStringRep(dupPtr
, objPtr
->bytes
, objPtr
->length
);
2126 /* By default, the new object has the same type as the old object */
2127 dupPtr
->typePtr
= objPtr
->typePtr
;
2128 if (objPtr
->typePtr
!= NULL
) {
2129 if (objPtr
->typePtr
->dupIntRepProc
== NULL
) {
2130 dupPtr
->internalRep
= objPtr
->internalRep
;
2133 /* The dup proc may set a different type, e.g. NULL */
2134 objPtr
->typePtr
->dupIntRepProc(interp
, objPtr
, dupPtr
);
2140 /* Return the string representation for objPtr. If the object
2141 * string representation is invalid, calls the method to create
2142 * a new one starting from the internal representation of the object. */
2143 const char *Jim_GetString(Jim_Obj
*objPtr
, int *lenPtr
)
2145 if (objPtr
->bytes
== NULL
) {
2146 /* Invalid string repr. Generate it. */
2147 JimPanic((objPtr
->typePtr
->updateStringProc
== NULL
, "UpdateStringProc called against '%s' type.", objPtr
->typePtr
->name
));
2148 objPtr
->typePtr
->updateStringProc(objPtr
);
2151 *lenPtr
= objPtr
->length
;
2152 return objPtr
->bytes
;
2155 /* Just returns the length of the object's string rep */
2156 int Jim_Length(Jim_Obj
*objPtr
)
2160 Jim_GetString(objPtr
, &len
);
2164 static void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2165 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2167 static const Jim_ObjType dictSubstObjType
= {
2168 "dict-substitution",
2169 FreeDictSubstInternalRep
,
2170 DupDictSubstInternalRep
,
2175 static void FreeInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2177 Jim_DecrRefCount(interp
, (Jim_Obj
*)objPtr
->internalRep
.twoPtrValue
.ptr2
);
2180 static const Jim_ObjType interpolatedObjType
= {
2182 FreeInterpolatedInternalRep
,
2188 /* -----------------------------------------------------------------------------
2190 * ---------------------------------------------------------------------------*/
2191 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2192 static int SetStringFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2194 static const Jim_ObjType stringObjType
= {
2197 DupStringInternalRep
,
2199 JIM_TYPE_REFERENCES
,
2202 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2204 JIM_NOTUSED(interp
);
2206 /* This is a bit subtle: the only caller of this function
2207 * should be Jim_DuplicateObj(), that will copy the
2208 * string representaion. After the copy, the duplicated
2209 * object will not have more room in teh buffer than
2210 * srcPtr->length bytes. So we just set it to length. */
2211 dupPtr
->internalRep
.strValue
.maxLength
= srcPtr
->length
;
2213 dupPtr
->internalRep
.strValue
.charLength
= srcPtr
->internalRep
.strValue
.charLength
;
2216 static int SetStringFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2218 /* Get a fresh string representation. */
2219 (void)Jim_String(objPtr
);
2220 /* Free any other internal representation. */
2221 Jim_FreeIntRep(interp
, objPtr
);
2222 /* Set it as string, i.e. just set the maxLength field. */
2223 objPtr
->typePtr
= &stringObjType
;
2224 objPtr
->internalRep
.strValue
.maxLength
= objPtr
->length
;
2225 /* Don't know the utf-8 length yet */
2226 objPtr
->internalRep
.strValue
.charLength
= -1;
2231 * Returns the length of the object string in chars, not bytes.
2233 * These may be different for a utf-8 string.
2235 int Jim_Utf8Length(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2238 if (objPtr
->typePtr
!= &stringObjType
)
2239 SetStringFromAny(interp
, objPtr
);
2241 if (objPtr
->internalRep
.strValue
.charLength
< 0) {
2242 objPtr
->internalRep
.strValue
.charLength
= utf8_strlen(objPtr
->bytes
, objPtr
->length
);
2244 return objPtr
->internalRep
.strValue
.charLength
;
2246 return Jim_Length(objPtr
);
2250 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2251 Jim_Obj
*Jim_NewStringObj(Jim_Interp
*interp
, const char *s
, int len
)
2253 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2255 /* Need to find out how many bytes the string requires */
2258 /* Alloc/Set the string rep. */
2260 objPtr
->bytes
= JimEmptyStringRep
;
2264 objPtr
->bytes
= Jim_Alloc(len
+ 1);
2265 objPtr
->length
= len
;
2266 memcpy(objPtr
->bytes
, s
, len
);
2267 objPtr
->bytes
[len
] = '\0';
2270 /* No typePtr field for the vanilla string object. */
2271 objPtr
->typePtr
= NULL
;
2275 /* charlen is in characters -- see also Jim_NewStringObj() */
2276 Jim_Obj
*Jim_NewStringObjUtf8(Jim_Interp
*interp
, const char *s
, int charlen
)
2279 /* Need to find out how many bytes the string requires */
2280 int bytelen
= utf8_index(s
, charlen
);
2282 Jim_Obj
*objPtr
= Jim_NewStringObj(interp
, s
, bytelen
);
2284 /* Remember the utf8 length, so set the type */
2285 objPtr
->typePtr
= &stringObjType
;
2286 objPtr
->internalRep
.strValue
.maxLength
= bytelen
;
2287 objPtr
->internalRep
.strValue
.charLength
= charlen
;
2291 return Jim_NewStringObj(interp
, s
, charlen
);
2295 /* This version does not try to duplicate the 's' pointer, but
2296 * use it directly. */
2297 Jim_Obj
*Jim_NewStringObjNoAlloc(Jim_Interp
*interp
, char *s
, int len
)
2299 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2303 Jim_SetStringRep(objPtr
, s
, len
);
2304 objPtr
->typePtr
= NULL
;
2308 /* Low-level string append. Use it only against objects
2309 * of type "string". */
2310 static void StringAppendString(Jim_Obj
*objPtr
, const char *str
, int len
)
2316 needlen
= objPtr
->length
+ len
;
2317 if (objPtr
->internalRep
.strValue
.maxLength
< needlen
||
2318 objPtr
->internalRep
.strValue
.maxLength
== 0) {
2320 /* Inefficient to malloc() for less than 8 bytes */
2324 if (objPtr
->bytes
== JimEmptyStringRep
) {
2325 objPtr
->bytes
= Jim_Alloc(needlen
+ 1);
2328 objPtr
->bytes
= Jim_Realloc(objPtr
->bytes
, needlen
+ 1);
2330 objPtr
->internalRep
.strValue
.maxLength
= needlen
;
2332 memcpy(objPtr
->bytes
+ objPtr
->length
, str
, len
);
2333 objPtr
->bytes
[objPtr
->length
+ len
] = '\0';
2334 if (objPtr
->internalRep
.strValue
.charLength
>= 0) {
2335 /* Update the utf-8 char length */
2336 objPtr
->internalRep
.strValue
.charLength
+= utf8_strlen(objPtr
->bytes
+ objPtr
->length
, len
);
2338 objPtr
->length
+= len
;
2341 /* Higher level API to append strings to objects. */
2342 void Jim_AppendString(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
, int len
)
2344 JimPanic((Jim_IsShared(objPtr
), "Jim_AppendString called with shared object"));
2345 if (objPtr
->typePtr
!= &stringObjType
)
2346 SetStringFromAny(interp
, objPtr
);
2347 StringAppendString(objPtr
, str
, len
);
2350 void Jim_AppendObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*appendObjPtr
)
2355 str
= Jim_GetString(appendObjPtr
, &len
);
2356 Jim_AppendString(interp
, objPtr
, str
, len
);
2359 void Jim_AppendStrings(Jim_Interp
*interp
, Jim_Obj
*objPtr
, ...)
2363 if (objPtr
->typePtr
!= &stringObjType
)
2364 SetStringFromAny(interp
, objPtr
);
2365 va_start(ap
, objPtr
);
2367 char *s
= va_arg(ap
, char *);
2371 Jim_AppendString(interp
, objPtr
, s
, -1);
2376 int Jim_StringEqObj(Jim_Obj
*aObjPtr
, Jim_Obj
*bObjPtr
)
2378 const char *aStr
, *bStr
;
2381 if (aObjPtr
== bObjPtr
)
2383 aStr
= Jim_GetString(aObjPtr
, &aLen
);
2384 bStr
= Jim_GetString(bObjPtr
, &bLen
);
2387 return JimStringCompare(aStr
, aLen
, bStr
, bLen
) == 0;
2390 int Jim_StringMatchObj(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, Jim_Obj
*objPtr
, int nocase
)
2392 return JimStringMatch(interp
, patternObjPtr
, Jim_String(objPtr
), nocase
);
2395 int Jim_StringCompareObj(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*secondObjPtr
, int nocase
)
2397 const char *s1
, *s2
;
2400 s1
= Jim_GetString(firstObjPtr
, &l1
);
2401 s2
= Jim_GetString(secondObjPtr
, &l2
);
2404 return JimStringCompareNoCase(s1
, s2
, -1);
2406 return JimStringCompare(s1
, l1
, s2
, l2
);
2409 /* Convert a range, as returned by Jim_GetRange(), into
2410 * an absolute index into an object of the specified length.
2411 * This function may return negative values, or values
2412 * bigger or equal to the length of the list if the index
2413 * is out of range. */
2414 static int JimRelToAbsIndex(int len
, int idx
)
2421 /* Convert a pair of index (*firstPtr, *lastPtr) as normalized by JimRelToAbsIndex(),
2422 * into form suitable for implementation of commands like [string range] and [lrange].
2424 * The resulting range is guaranteed to address valid elements of
2428 static void JimRelToAbsRange(int len
, int *firstPtr
, int *lastPtr
, int *rangeLenPtr
)
2432 if (*firstPtr
> *lastPtr
) {
2436 rangeLen
= *lastPtr
- *firstPtr
+ 1;
2438 if (*firstPtr
< 0) {
2439 rangeLen
+= *firstPtr
;
2442 if (*lastPtr
>= len
) {
2443 rangeLen
-= (*lastPtr
- (len
- 1));
2451 *rangeLenPtr
= rangeLen
;
2454 static int JimStringGetRange(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
,
2455 int len
, int *first
, int *last
, int *range
)
2457 if (Jim_GetIndex(interp
, firstObjPtr
, first
) != JIM_OK
) {
2460 if (Jim_GetIndex(interp
, lastObjPtr
, last
) != JIM_OK
) {
2463 *first
= JimRelToAbsIndex(len
, *first
);
2464 *last
= JimRelToAbsIndex(len
, *last
);
2465 JimRelToAbsRange(len
, first
, last
, range
);
2469 Jim_Obj
*Jim_StringByteRangeObj(Jim_Interp
*interp
,
2470 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2477 str
= Jim_GetString(strObjPtr
, &bytelen
);
2479 if (JimStringGetRange(interp
, firstObjPtr
, lastObjPtr
, bytelen
, &first
, &last
, &rangeLen
) != JIM_OK
) {
2483 if (first
== 0 && rangeLen
== bytelen
) {
2486 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2489 Jim_Obj
*Jim_StringRangeObj(Jim_Interp
*interp
,
2490 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2498 str
= Jim_GetString(strObjPtr
, &bytelen
);
2499 len
= Jim_Utf8Length(interp
, strObjPtr
);
2501 if (JimStringGetRange(interp
, firstObjPtr
, lastObjPtr
, len
, &first
, &last
, &rangeLen
) != JIM_OK
) {
2505 if (first
== 0 && rangeLen
== len
) {
2508 if (len
== bytelen
) {
2509 /* ASCII optimisation */
2510 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2512 return Jim_NewStringObjUtf8(interp
, str
+ utf8_index(str
, first
), rangeLen
);
2514 return Jim_StringByteRangeObj(interp
, strObjPtr
, firstObjPtr
, lastObjPtr
);
2518 static Jim_Obj
*JimStringToLower(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2524 if (strObjPtr
->typePtr
!= &stringObjType
) {
2525 SetStringFromAny(interp
, strObjPtr
);
2528 str
= Jim_GetString(strObjPtr
, &len
);
2530 buf
= p
= Jim_Alloc(len
+ 1);
2533 str
+= utf8_tounicode(str
, &c
);
2534 p
+= utf8_fromunicode(p
, utf8_lower(c
));
2537 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2540 static Jim_Obj
*JimStringToUpper(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2546 if (strObjPtr
->typePtr
!= &stringObjType
) {
2547 SetStringFromAny(interp
, strObjPtr
);
2550 str
= Jim_GetString(strObjPtr
, &len
);
2552 buf
= p
= Jim_Alloc(len
+ 1);
2555 str
+= utf8_tounicode(str
, &c
);
2556 p
+= utf8_fromunicode(p
, utf8_upper(c
));
2559 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2562 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2563 * for unicode character 'c'.
2564 * Returns the position if found or NULL if not
2566 static const char *utf8_memchr(const char *str
, int len
, int c
)
2571 int n
= utf8_tounicode(str
, &sc
);
2580 return memchr(str
, c
, len
);
2585 * Searches for the first non-trim char in string (str, len)
2587 * If none is found, returns just past the last char.
2589 * Lengths are in bytes.
2591 static const char *JimFindTrimLeft(const char *str
, int len
, const char *trimchars
, int trimlen
)
2595 int n
= utf8_tounicode(str
, &c
);
2597 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2598 /* Not a trim char, so stop */
2608 * Searches backwards for a non-trim char in string (str, len).
2610 * Returns a pointer to just after the non-trim char, or NULL if not found.
2612 * Lengths are in bytes.
2614 static const char *JimFindTrimRight(const char *str
, int len
, const char *trimchars
, int trimlen
)
2620 int n
= utf8_prev_len(str
, len
);
2625 n
= utf8_tounicode(str
, &c
);
2627 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2635 static const char default_trim_chars
[] = " \t\n\r";
2636 /* sizeof() here includes the null byte */
2637 static int default_trim_chars_len
= sizeof(default_trim_chars
);
2639 static Jim_Obj
*JimStringTrimLeft(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2642 const char *str
= Jim_GetString(strObjPtr
, &len
);
2643 const char *trimchars
= default_trim_chars
;
2644 int trimcharslen
= default_trim_chars_len
;
2647 if (trimcharsObjPtr
) {
2648 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2651 newstr
= JimFindTrimLeft(str
, len
, trimchars
, trimcharslen
);
2652 if (newstr
== str
) {
2656 return Jim_NewStringObj(interp
, newstr
, len
- (newstr
- str
));
2659 static Jim_Obj
*JimStringTrimRight(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2662 const char *trimchars
= default_trim_chars
;
2663 int trimcharslen
= default_trim_chars_len
;
2664 const char *nontrim
;
2666 if (trimcharsObjPtr
) {
2667 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2670 if (strObjPtr
->typePtr
!= &stringObjType
) {
2671 SetStringFromAny(interp
, strObjPtr
);
2673 len
= Jim_Length(strObjPtr
);
2674 nontrim
= JimFindTrimRight(strObjPtr
->bytes
, len
, trimchars
, trimcharslen
);
2676 if (nontrim
== NULL
) {
2677 /* All trim, so return a zero-length string */
2678 return Jim_NewEmptyStringObj(interp
);
2680 if (nontrim
== strObjPtr
->bytes
+ len
) {
2684 if (Jim_IsShared(strObjPtr
)) {
2685 strObjPtr
= Jim_NewStringObj(interp
, strObjPtr
->bytes
, (nontrim
- strObjPtr
->bytes
));
2688 /* Can modify this string in place */
2689 strObjPtr
->bytes
[nontrim
- strObjPtr
->bytes
] = 0;
2690 strObjPtr
->length
= (nontrim
- strObjPtr
->bytes
);
2696 static Jim_Obj
*JimStringTrim(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2698 /* First trim left. */
2699 Jim_Obj
*objPtr
= JimStringTrimLeft(interp
, strObjPtr
, trimcharsObjPtr
);
2701 /* Now trim right */
2702 strObjPtr
= JimStringTrimRight(interp
, objPtr
, trimcharsObjPtr
);
2704 if (objPtr
!= strObjPtr
) {
2705 /* Note that we don't want this object to be leaked */
2706 Jim_IncrRefCount(objPtr
);
2707 Jim_DecrRefCount(interp
, objPtr
);
2714 static int JimStringIs(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*strClass
, int strict
)
2716 static const char * const strclassnames
[] = {
2717 "integer", "alpha", "alnum", "ascii", "digit",
2718 "double", "lower", "upper", "space", "xdigit",
2719 "control", "print", "graph", "punct",
2723 STR_IS_INTEGER
, STR_IS_ALPHA
, STR_IS_ALNUM
, STR_IS_ASCII
, STR_IS_DIGIT
,
2724 STR_IS_DOUBLE
, STR_IS_LOWER
, STR_IS_UPPER
, STR_IS_SPACE
, STR_IS_XDIGIT
,
2725 STR_IS_CONTROL
, STR_IS_PRINT
, STR_IS_GRAPH
, STR_IS_PUNCT
2731 int (*isclassfunc
)(int c
) = NULL
;
2733 if (Jim_GetEnum(interp
, strClass
, strclassnames
, &strclass
, "class", JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
2737 str
= Jim_GetString(strObjPtr
, &len
);
2739 Jim_SetResultInt(interp
, !strict
);
2744 case STR_IS_INTEGER
:
2747 Jim_SetResultInt(interp
, JimGetWideNoErr(interp
, strObjPtr
, &w
) == JIM_OK
);
2754 Jim_SetResultInt(interp
, Jim_GetDouble(interp
, strObjPtr
, &d
) == JIM_OK
&& errno
!= ERANGE
);
2758 case STR_IS_ALPHA
: isclassfunc
= isalpha
; break;
2759 case STR_IS_ALNUM
: isclassfunc
= isalnum
; break;
2760 case STR_IS_ASCII
: isclassfunc
= isascii
; break;
2761 case STR_IS_DIGIT
: isclassfunc
= isdigit
; break;
2762 case STR_IS_LOWER
: isclassfunc
= islower
; break;
2763 case STR_IS_UPPER
: isclassfunc
= isupper
; break;
2764 case STR_IS_SPACE
: isclassfunc
= isspace
; break;
2765 case STR_IS_XDIGIT
: isclassfunc
= isxdigit
; break;
2766 case STR_IS_CONTROL
: isclassfunc
= iscntrl
; break;
2767 case STR_IS_PRINT
: isclassfunc
= isprint
; break;
2768 case STR_IS_GRAPH
: isclassfunc
= isgraph
; break;
2769 case STR_IS_PUNCT
: isclassfunc
= ispunct
; break;
2774 for (i
= 0; i
< len
; i
++) {
2775 if (!isclassfunc(str
[i
])) {
2776 Jim_SetResultInt(interp
, 0);
2780 Jim_SetResultInt(interp
, 1);
2784 /* -----------------------------------------------------------------------------
2785 * Compared String Object
2786 * ---------------------------------------------------------------------------*/
2788 /* This is strange object that allows to compare a C literal string
2789 * with a Jim object in very short time if the same comparison is done
2790 * multiple times. For example every time the [if] command is executed,
2791 * Jim has to check if a given argument is "else". This comparions if
2792 * the code has no errors are true most of the times, so we can cache
2793 * inside the object the pointer of the string of the last matching
2794 * comparison. Because most C compilers perform literal sharing,
2795 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2796 * this works pretty well even if comparisons are at different places
2797 * inside the C code. */
2799 static const Jim_ObjType comparedStringObjType
= {
2804 JIM_TYPE_REFERENCES
,
2807 /* The only way this object is exposed to the API is via the following
2808 * function. Returns true if the string and the object string repr.
2809 * are the same, otherwise zero is returned.
2811 * Note: this isn't binary safe, but it hardly needs to be.*/
2812 int Jim_CompareStringImmediate(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
)
2814 if (objPtr
->typePtr
== &comparedStringObjType
&& objPtr
->internalRep
.ptr
== str
)
2817 const char *objStr
= Jim_String(objPtr
);
2819 if (strcmp(str
, objStr
) != 0)
2821 if (objPtr
->typePtr
!= &comparedStringObjType
) {
2822 Jim_FreeIntRep(interp
, objPtr
);
2823 objPtr
->typePtr
= &comparedStringObjType
;
2825 objPtr
->internalRep
.ptr
= (char *)str
; /*ATTENTION: const cast */
2830 static int qsortCompareStringPointers(const void *a
, const void *b
)
2832 char *const *sa
= (char *const *)a
;
2833 char *const *sb
= (char *const *)b
;
2835 return strcmp(*sa
, *sb
);
2839 /* -----------------------------------------------------------------------------
2842 * This object is just a string from the language point of view, but
2843 * in the internal representation it contains the filename and line number
2844 * where this given token was read. This information is used by
2845 * Jim_EvalObj() if the object passed happens to be of type "source".
2847 * This allows to propagate the information about line numbers and file
2848 * names and give error messages with absolute line numbers.
2850 * Note that this object uses shared strings for filenames, and the
2851 * pointer to the filename together with the line number is taken into
2852 * the space for the "inline" internal representation of the Jim_Object,
2853 * so there is almost memory zero-overhead.
2855 * Also the object will be converted to something else if the given
2856 * token it represents in the source file is not something to be
2857 * evaluated (not a script), and will be specialized in some other way,
2858 * so the time overhead is also null.
2859 * ---------------------------------------------------------------------------*/
2861 static void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2862 static void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2864 static const Jim_ObjType sourceObjType
= {
2866 FreeSourceInternalRep
,
2867 DupSourceInternalRep
,
2869 JIM_TYPE_REFERENCES
,
2872 void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2874 Jim_DecrRefCount(interp
, objPtr
->internalRep
.sourceValue
.fileNameObj
);
2877 void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2879 dupPtr
->internalRep
= srcPtr
->internalRep
;
2880 Jim_IncrRefCount(dupPtr
->internalRep
.sourceValue
.fileNameObj
);
2883 static void JimSetSourceInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2884 Jim_Obj
*fileNameObj
, int lineNumber
)
2886 JimPanic((Jim_IsShared(objPtr
), "JimSetSourceInfo called with shared object"));
2887 JimPanic((objPtr
->typePtr
!= NULL
, "JimSetSourceInfo called with typePtr != NULL"));
2888 Jim_IncrRefCount(fileNameObj
);
2889 objPtr
->internalRep
.sourceValue
.fileNameObj
= fileNameObj
;
2890 objPtr
->internalRep
.sourceValue
.lineNumber
= lineNumber
;
2891 objPtr
->typePtr
= &sourceObjType
;
2894 /* -----------------------------------------------------------------------------
2896 * ---------------------------------------------------------------------------*/
2898 static const Jim_ObjType scriptLineObjType
= {
2906 static Jim_Obj
*JimNewScriptLineObj(Jim_Interp
*interp
, int argc
, int line
)
2910 #ifdef DEBUG_SHOW_SCRIPT
2912 snprintf(buf
, sizeof(buf
), "line=%d, argc=%d", line
, argc
);
2913 objPtr
= Jim_NewStringObj(interp
, buf
, -1);
2915 objPtr
= Jim_NewEmptyStringObj(interp
);
2917 objPtr
->typePtr
= &scriptLineObjType
;
2918 objPtr
->internalRep
.scriptLineValue
.argc
= argc
;
2919 objPtr
->internalRep
.scriptLineValue
.line
= line
;
2924 #define JIM_CMDSTRUCT_EXPAND -1
2926 static void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2927 static void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2928 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
);
2930 static const Jim_ObjType scriptObjType
= {
2932 FreeScriptInternalRep
,
2933 DupScriptInternalRep
,
2935 JIM_TYPE_REFERENCES
,
2938 /* The ScriptToken structure represents every token into a scriptObj.
2939 * Every token contains an associated Jim_Obj that can be specialized
2940 * by commands operating on it. */
2941 typedef struct ScriptToken
2947 /* This is the script object internal representation. An array of
2948 * ScriptToken structures, including a pre-computed representation of the
2949 * command length and arguments.
2951 * For example the script:
2954 * set $i $x$y [foo]BAR
2956 * will produce a ScriptObj with the following Tokens:
2971 * "puts hello" has two args (LIN 2), composed of single tokens.
2972 * (Note that the WRD token is omitted for the common case of a single token.)
2974 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
2975 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
2977 * The precomputation of the command structure makes Jim_Eval() faster,
2978 * and simpler because there aren't dynamic lengths / allocations.
2980 * -- {expand}/{*} handling --
2982 * Expand is handled in a special way.
2984 * If a "word" begins with {*}, the word token count is -ve.
2986 * For example the command:
2990 * Will produce the following cmdstruct array:
2997 * Note that the 'LIN' token also contains the source information for the
2998 * first word of the line for error reporting purposes
3000 * -- the substFlags field of the structure --
3002 * The scriptObj structure is used to represent both "script" objects
3003 * and "subst" objects. In the second case, the there are no LIN and WRD
3004 * tokens. Instead SEP and EOL tokens are added as-is.
3005 * In addition, the field 'substFlags' is used to represent the flags used to turn
3006 * the string into the internal representation used to perform the
3007 * substitution. If this flags are not what the application requires
3008 * the scriptObj is created again. For example the script:
3010 * subst -nocommands $string
3011 * subst -novariables $string
3013 * Will recreate the internal representation of the $string object
3016 typedef struct ScriptObj
3018 int len
; /* Length as number of tokens. */
3019 ScriptToken
*token
; /* Tokens array. */
3020 int substFlags
; /* flags used for the compilation of "subst" objects */
3021 int inUse
; /* Used to share a ScriptObj. Currently
3022 only used by Jim_EvalObj() as protection against
3023 shimmering of the currently evaluated object. */
3024 Jim_Obj
*fileNameObj
;
3025 int line
; /* Line number of the first line */
3028 void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3031 struct ScriptObj
*script
= (void *)objPtr
->internalRep
.ptr
;
3034 if (script
->inUse
!= 0)
3036 for (i
= 0; i
< script
->len
; i
++) {
3037 Jim_DecrRefCount(interp
, script
->token
[i
].objPtr
);
3039 Jim_Free(script
->token
);
3040 Jim_DecrRefCount(interp
, script
->fileNameObj
);
3044 void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
3046 JIM_NOTUSED(interp
);
3047 JIM_NOTUSED(srcPtr
);
3049 /* Just returns an simple string. */
3050 dupPtr
->typePtr
= NULL
;
3053 /* A simple parser token.
3054 * All the simple tokens for the script point into the same script string rep.
3058 const char *token
; /* Pointer to the start of the token */
3059 int len
; /* Length of this token */
3060 int type
; /* Token type */
3061 int line
; /* Line number */
3064 /* A list of parsed tokens representing a script.
3065 * Tokens are added to this list as the script is parsed.
3066 * It grows as needed.
3070 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3071 ParseToken
*list
; /* Array of tokens */
3072 int size
; /* Current size of the list */
3073 int count
; /* Number of entries used */
3074 ParseToken static_list
[20]; /* Small initial token space to avoid allocation */
3077 static void ScriptTokenListInit(ParseTokenList
*tokenlist
)
3079 tokenlist
->list
= tokenlist
->static_list
;
3080 tokenlist
->size
= sizeof(tokenlist
->static_list
) / sizeof(ParseToken
);
3081 tokenlist
->count
= 0;
3084 static void ScriptTokenListFree(ParseTokenList
*tokenlist
)
3086 if (tokenlist
->list
!= tokenlist
->static_list
) {
3087 Jim_Free(tokenlist
->list
);
3092 * Adds the new token to the tokenlist.
3093 * The token has the given length, type and line number.
3094 * The token list is resized as necessary.
3096 static void ScriptAddToken(ParseTokenList
*tokenlist
, const char *token
, int len
, int type
,
3101 if (tokenlist
->count
== tokenlist
->size
) {
3102 /* Resize the list */
3103 tokenlist
->size
*= 2;
3104 if (tokenlist
->list
!= tokenlist
->static_list
) {
3106 Jim_Realloc(tokenlist
->list
, tokenlist
->size
* sizeof(*tokenlist
->list
));
3109 /* The list needs to become allocated */
3110 tokenlist
->list
= Jim_Alloc(tokenlist
->size
* sizeof(*tokenlist
->list
));
3111 memcpy(tokenlist
->list
, tokenlist
->static_list
,
3112 tokenlist
->count
* sizeof(*tokenlist
->list
));
3115 t
= &tokenlist
->list
[tokenlist
->count
++];
3122 /* Counts the number of adjoining non-separator.
3124 * Returns -ve if the first token is the expansion
3125 * operator (in which case the count doesn't include
3128 static int JimCountWordTokens(ParseToken
*t
)
3133 /* Is the first word {*} or {expand}? */
3134 if (t
->type
== JIM_TT_STR
&& !TOKEN_IS_SEP(t
[1].type
)) {
3135 if ((t
->len
== 1 && *t
->token
== '*') || (t
->len
== 6 && strncmp(t
->token
, "expand", 6) == 0)) {
3136 /* Create an expand token */
3142 /* Now count non-separator words */
3143 while (!TOKEN_IS_SEP(t
->type
)) {
3148 return count
* expand
;
3152 * Create a script/subst object from the given token.
3154 static Jim_Obj
*JimMakeScriptObj(Jim_Interp
*interp
, const ParseToken
*t
)
3158 if (t
->type
== JIM_TT_ESC
&& memchr(t
->token
, '\\', t
->len
) != NULL
) {
3159 /* Convert the backlash escapes . */
3161 char *str
= Jim_Alloc(len
+ 1);
3162 len
= JimEscape(str
, t
->token
, len
);
3163 objPtr
= Jim_NewStringObjNoAlloc(interp
, str
, len
);
3166 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3167 * with a single space. This is currently not done.
3169 objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
3175 * Takes a tokenlist and creates the allocated list of script tokens
3176 * in script->token, of length script->len.
3178 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3181 * Also sets script->line to the line number of the first token
3183 static void ScriptObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3184 ParseTokenList
*tokenlist
)
3187 struct ScriptToken
*token
;
3188 /* Number of tokens so far for the current command */
3190 /* This is the first token for the current command */
3191 ScriptToken
*linefirst
;
3195 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3196 printf("==== Tokens ====\n");
3197 for (i
= 0; i
< tokenlist
->count
; i
++) {
3198 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
->list
[i
].line
, jim_tt_name(tokenlist
->list
[i
].type
),
3199 tokenlist
->list
[i
].len
, tokenlist
->list
[i
].token
);
3203 /* May need up to one extra script token for each EOL in the worst case */
3204 count
= tokenlist
->count
;
3205 for (i
= 0; i
< tokenlist
->count
; i
++) {
3206 if (tokenlist
->list
[i
].type
== JIM_TT_EOL
) {
3210 linenr
= script
->line
= tokenlist
->list
[0].line
;
3212 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
3214 /* This is the first token for the current command */
3215 linefirst
= token
++;
3217 for (i
= 0; i
< tokenlist
->count
; ) {
3218 /* Look ahead to find out how many tokens make up the next word */
3221 /* Skip any leading separators */
3222 while (tokenlist
->list
[i
].type
== JIM_TT_SEP
) {
3226 wordtokens
= JimCountWordTokens(tokenlist
->list
+ i
);
3228 if (wordtokens
== 0) {
3229 /* None, so at end of line */
3231 linefirst
->type
= JIM_TT_LINE
;
3232 linefirst
->objPtr
= JimNewScriptLineObj(interp
, lineargs
, linenr
);
3233 Jim_IncrRefCount(linefirst
->objPtr
);
3235 /* Reset for new line */
3237 linefirst
= token
++;
3242 else if (wordtokens
!= 1) {
3243 /* More than 1, or {expand}, so insert a WORD token */
3244 token
->type
= JIM_TT_WORD
;
3245 token
->objPtr
= Jim_NewIntObj(interp
, wordtokens
);
3246 Jim_IncrRefCount(token
->objPtr
);
3248 if (wordtokens
< 0) {
3249 /* Skip the expand token */
3251 wordtokens
= -wordtokens
- 1;
3256 if (lineargs
== 0) {
3257 /* First real token on the line, so record the line number */
3258 linenr
= tokenlist
->list
[i
].line
;
3262 /* Add each non-separator word token to the line */
3263 while (wordtokens
--) {
3264 const ParseToken
*t
= &tokenlist
->list
[i
++];
3266 token
->type
= t
->type
;
3267 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3268 Jim_IncrRefCount(token
->objPtr
);
3270 /* Every object is initially a string, but the
3271 * internal type may be specialized during execution of the
3273 JimSetSourceInfo(interp
, token
->objPtr
, script
->fileNameObj
, t
->line
);
3278 if (lineargs
== 0) {
3282 script
->len
= token
- script
->token
;
3284 assert(script
->len
< count
);
3286 #ifdef DEBUG_SHOW_SCRIPT
3287 printf("==== Script (%s) ====\n", Jim_String(script
->fileNameObj
));
3288 for (i
= 0; i
< script
->len
; i
++) {
3289 const ScriptToken
*t
= &script
->token
[i
];
3290 printf("[%2d] %s %s\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
3297 * Similar to ScriptObjAddTokens(), but for subst objects.
3299 static void SubstObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3300 ParseTokenList
*tokenlist
)
3303 struct ScriptToken
*token
;
3305 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * tokenlist
->count
);
3307 for (i
= 0; i
< tokenlist
->count
; i
++) {
3308 const ParseToken
*t
= &tokenlist
->list
[i
];
3310 /* Create a token for 't' */
3311 token
->type
= t
->type
;
3312 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3313 Jim_IncrRefCount(token
->objPtr
);
3320 /* This method takes the string representation of an object
3321 * as a Tcl script, and generates the pre-parsed internal representation
3323 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
)
3326 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
3327 struct JimParserCtx parser
;
3328 struct ScriptObj
*script
;
3329 ParseTokenList tokenlist
;
3332 /* Try to get information about filename / line number */
3333 if (objPtr
->typePtr
== &sourceObjType
) {
3334 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
3337 /* Initially parse the script into tokens (in tokenlist) */
3338 ScriptTokenListInit(&tokenlist
);
3340 JimParserInit(&parser
, scriptText
, scriptTextLen
, line
);
3341 while (!parser
.eof
) {
3342 JimParseScript(&parser
);
3343 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
3346 if (result
&& parser
.missing
!= ' ') {
3347 ScriptTokenListFree(&tokenlist
);
3348 result
->missing
= parser
.missing
;
3349 result
->line
= parser
.missingline
;
3353 /* Add a final EOF token */
3354 ScriptAddToken(&tokenlist
, scriptText
+ scriptTextLen
, 0, JIM_TT_EOF
, 0);
3356 /* Create the "real" script tokens from the initial token list */
3357 script
= Jim_Alloc(sizeof(*script
));
3358 memset(script
, 0, sizeof(*script
));
3360 script
->line
= line
;
3361 if (objPtr
->typePtr
== &sourceObjType
) {
3362 script
->fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
3365 script
->fileNameObj
= interp
->emptyObj
;
3367 Jim_IncrRefCount(script
->fileNameObj
);
3369 ScriptObjAddTokens(interp
, script
, &tokenlist
);
3371 /* No longer need the token list */
3372 ScriptTokenListFree(&tokenlist
);
3374 /* Free the old internal rep and set the new one. */
3375 Jim_FreeIntRep(interp
, objPtr
);
3376 Jim_SetIntRepPtr(objPtr
, script
);
3377 objPtr
->typePtr
= &scriptObjType
;
3382 ScriptObj
*Jim_GetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3384 struct ScriptObj
*script
= Jim_GetIntRepPtr(objPtr
);
3386 if (objPtr
->typePtr
!= &scriptObjType
|| script
->substFlags
) {
3387 SetScriptFromAny(interp
, objPtr
, NULL
);
3389 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
3392 /* -----------------------------------------------------------------------------
3394 * ---------------------------------------------------------------------------*/
3395 static void JimIncrCmdRefCount(Jim_Cmd
*cmdPtr
)
3400 static void JimDecrCmdRefCount(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
)
3402 if (--cmdPtr
->inUse
== 0) {
3403 if (cmdPtr
->isproc
) {
3404 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.argListObjPtr
);
3405 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.bodyObjPtr
);
3406 if (cmdPtr
->u
.proc
.staticVars
) {
3407 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3408 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3410 if (cmdPtr
->u
.proc
.prevCmd
) {
3411 /* Delete any pushed command too */
3412 JimDecrCmdRefCount(interp
, cmdPtr
->u
.proc
.prevCmd
);
3417 if (cmdPtr
->u
.native
.delProc
) {
3418 cmdPtr
->u
.native
.delProc(interp
, cmdPtr
->u
.native
.privData
);
3425 /* Variables HashTable Type.
3427 * Keys are dynamic allocated strings, Values are Jim_Var structures.
3430 /* Variables HashTable Type.
3432 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3433 static void JimVariablesHTValDestructor(void *interp
, void *val
)
3435 Jim_DecrRefCount(interp
, ((Jim_Var
*)val
)->objPtr
);
3439 static const Jim_HashTableType JimVariablesHashTableType
= {
3440 JimStringCopyHTHashFunction
, /* hash function */
3441 JimStringCopyHTDup
, /* key dup */
3443 JimStringCopyHTKeyCompare
, /* key compare */
3444 JimStringCopyHTKeyDestructor
, /* key destructor */
3445 JimVariablesHTValDestructor
/* val destructor */
3448 /* Commands HashTable Type.
3450 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3451 static void JimCommandsHT_ValDestructor(void *interp
, void *val
)
3453 JimDecrCmdRefCount(interp
, val
);
3456 static const Jim_HashTableType JimCommandsHashTableType
= {
3457 JimStringCopyHTHashFunction
, /* hash function */
3458 JimStringCopyHTDup
, /* key dup */
3460 JimStringCopyHTKeyCompare
, /* key compare */
3461 JimStringCopyHTKeyDestructor
, /* key destructor */
3462 JimCommandsHT_ValDestructor
/* val destructor */
3465 /* ------------------------- Commands related functions --------------------- */
3467 int Jim_CreateCommand(Jim_Interp
*interp
, const char *cmdName
,
3468 Jim_CmdProc cmdProc
, void *privData
, Jim_DelCmdProc delProc
)
3472 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) != JIM_ERR
) {
3473 /* Command existed so incr proc epoch */
3474 Jim_InterpIncrProcEpoch(interp
);
3477 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3479 /* Store the new details for this proc */
3480 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3482 cmdPtr
->u
.native
.delProc
= delProc
;
3483 cmdPtr
->u
.native
.cmdProc
= cmdProc
;
3484 cmdPtr
->u
.native
.privData
= privData
;
3486 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3488 /* There is no need to increment the 'proc epoch' because
3489 * creation of a new procedure can never affect existing
3490 * cached commands. We don't do negative caching. */
3494 static int JimCreateProcedureStatics(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
, Jim_Obj
*staticsListObjPtr
)
3498 len
= Jim_ListLength(interp
, staticsListObjPtr
);
3503 cmdPtr
->u
.proc
.staticVars
= Jim_Alloc(sizeof(Jim_HashTable
));
3504 Jim_InitHashTable(cmdPtr
->u
.proc
.staticVars
, &JimVariablesHashTableType
, interp
);
3505 for (i
= 0; i
< len
; i
++) {
3506 Jim_Obj
*objPtr
= NULL
, *initObjPtr
= NULL
, *nameObjPtr
= NULL
;
3510 Jim_ListIndex(interp
, staticsListObjPtr
, i
, &objPtr
, JIM_NONE
);
3511 /* Check if it's composed of two elements. */
3512 subLen
= Jim_ListLength(interp
, objPtr
);
3513 if (subLen
== 1 || subLen
== 2) {
3514 /* Try to get the variable value from the current
3516 Jim_ListIndex(interp
, objPtr
, 0, &nameObjPtr
, JIM_NONE
);
3518 initObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, JIM_NONE
);
3519 if (initObjPtr
== NULL
) {
3520 Jim_SetResultFormatted(interp
,
3521 "variable for initialization of static \"%#s\" not found in the local context",
3527 Jim_ListIndex(interp
, objPtr
, 1, &initObjPtr
, JIM_NONE
);
3529 if (JimValidName(interp
, "static variable", nameObjPtr
) != JIM_OK
) {
3533 varPtr
= Jim_Alloc(sizeof(*varPtr
));
3534 varPtr
->objPtr
= initObjPtr
;
3535 Jim_IncrRefCount(initObjPtr
);
3536 varPtr
->linkFramePtr
= NULL
;
3537 if (Jim_AddHashEntry(cmdPtr
->u
.proc
.staticVars
,
3538 Jim_String(nameObjPtr
), varPtr
) != JIM_OK
) {
3539 Jim_SetResultFormatted(interp
,
3540 "static variable name \"%#s\" duplicated in statics list", nameObjPtr
);
3541 Jim_DecrRefCount(interp
, initObjPtr
);
3547 Jim_SetResultFormatted(interp
, "too many fields in static specifier \"%#s\"",
3555 static int JimCreateProcedure(Jim_Interp
*interp
, Jim_Obj
*cmdName
,
3556 Jim_Obj
*argListObjPtr
, Jim_Obj
*staticsListObjPtr
, Jim_Obj
*bodyObjPtr
)
3563 if (JimValidName(interp
, "procedure", cmdName
) != JIM_OK
) {
3567 argListLen
= Jim_ListLength(interp
, argListObjPtr
);
3569 /* Allocate space for both the command pointer and the arg list */
3570 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
) + sizeof(struct Jim_ProcArg
) * argListLen
);
3571 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3574 cmdPtr
->u
.proc
.argListObjPtr
= argListObjPtr
;
3575 cmdPtr
->u
.proc
.argListLen
= argListLen
;
3576 cmdPtr
->u
.proc
.bodyObjPtr
= bodyObjPtr
;
3577 cmdPtr
->u
.proc
.argsPos
= -1;
3578 cmdPtr
->u
.proc
.arglist
= (struct Jim_ProcArg
*)(cmdPtr
+ 1);
3579 Jim_IncrRefCount(argListObjPtr
);
3580 Jim_IncrRefCount(bodyObjPtr
);
3582 /* Create the statics hash table. */
3583 if (staticsListObjPtr
&& JimCreateProcedureStatics(interp
, cmdPtr
, staticsListObjPtr
) != JIM_OK
) {
3587 /* Parse the args out into arglist, validating as we go */
3588 /* Examine the argument list for default parameters and 'args' */
3589 for (i
= 0; i
< argListLen
; i
++) {
3591 Jim_Obj
*nameObjPtr
;
3592 Jim_Obj
*defaultObjPtr
;
3596 /* Examine a parameter */
3597 Jim_ListIndex(interp
, argListObjPtr
, i
, &argPtr
, JIM_NONE
);
3598 len
= Jim_ListLength(interp
, argPtr
);
3600 Jim_SetResultString(interp
, "procedure has argument with no name", -1);
3604 Jim_SetResultString(interp
, "procedure has argument with too many fields", -1);
3609 /* Optional parameter */
3610 Jim_ListIndex(interp
, argPtr
, 0, &nameObjPtr
, JIM_NONE
);
3611 Jim_ListIndex(interp
, argPtr
, 1, &defaultObjPtr
, JIM_NONE
);
3614 /* Required parameter */
3615 nameObjPtr
= argPtr
;
3616 defaultObjPtr
= NULL
;
3620 if (Jim_CompareStringImmediate(interp
, nameObjPtr
, "args")) {
3621 if (cmdPtr
->u
.proc
.argsPos
>= 0) {
3622 Jim_SetResultString(interp
, "procedure has 'args' specified more than once", -1);
3625 cmdPtr
->u
.proc
.argsPos
= i
;
3629 cmdPtr
->u
.proc
.optArity
+= n
;
3632 cmdPtr
->u
.proc
.reqArity
+= n
;
3636 cmdPtr
->u
.proc
.arglist
[i
].nameObjPtr
= nameObjPtr
;
3637 cmdPtr
->u
.proc
.arglist
[i
].defaultObjPtr
= defaultObjPtr
;
3640 /* Add the new command */
3642 /* It may already exist, so we try to delete the old one.
3643 * Note that reference count means that it won't be deleted yet if
3644 * it exists in the call stack.
3646 * BUT, if 'local' is in force, instead of deleting the existing
3647 * proc, we stash a reference to the old proc here.
3649 he
= Jim_FindHashEntry(&interp
->commands
, Jim_String(cmdName
));
3651 /* There was an old procedure with the same name, this requires
3652 * a 'proc epoch' update. */
3654 /* If a procedure with the same name didn't existed there is no need
3655 * to increment the 'proc epoch' because creation of a new procedure
3656 * can never affect existing cached commands. We don't do
3657 * negative caching. */
3658 Jim_InterpIncrProcEpoch(interp
);
3661 if (he
&& interp
->local
) {
3662 /* Just push this proc over the top of the previous one */
3663 cmdPtr
->u
.proc
.prevCmd
= he
->u
.val
;
3668 /* Replace the existing proc */
3669 Jim_DeleteHashEntry(&interp
->commands
, Jim_String(cmdName
));
3672 Jim_AddHashEntry(&interp
->commands
, Jim_String(cmdName
), cmdPtr
);
3675 /* Unlike Tcl, set the name of the proc as the result */
3676 Jim_SetResult(interp
, cmdName
);
3680 if (cmdPtr
->u
.proc
.staticVars
) {
3681 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3683 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3684 Jim_DecrRefCount(interp
, argListObjPtr
);
3685 Jim_DecrRefCount(interp
, bodyObjPtr
);
3690 int Jim_DeleteCommand(Jim_Interp
*interp
, const char *cmdName
)
3692 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) == JIM_ERR
)
3694 Jim_InterpIncrProcEpoch(interp
);
3698 int Jim_RenameCommand(Jim_Interp
*interp
, const char *oldName
, const char *newName
)
3702 /* Does it exist? */
3703 he
= Jim_FindHashEntry(&interp
->commands
, oldName
);
3705 Jim_SetResultFormatted(interp
, "can't %s \"%s\": command doesn't exist",
3706 newName
[0] ? "rename" : "delete", oldName
);
3710 if (newName
[0] == '\0') /* Delete! */
3711 return Jim_DeleteCommand(interp
, oldName
);
3714 if (Jim_FindHashEntry(&interp
->commands
, newName
)) {
3715 Jim_SetResultFormatted(interp
, "can't rename to \"%s\": command already exists", newName
);
3719 /* Add the new name first */
3720 JimIncrCmdRefCount(he
->u
.val
);
3721 Jim_AddHashEntry(&interp
->commands
, newName
, he
->u
.val
);
3723 /* Now remove the old name */
3724 Jim_DeleteHashEntry(&interp
->commands
, oldName
);
3726 /* Increment the epoch */
3727 Jim_InterpIncrProcEpoch(interp
);
3731 /* -----------------------------------------------------------------------------
3733 * ---------------------------------------------------------------------------*/
3735 static int SetCommandFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3737 static const Jim_ObjType commandObjType
= {
3742 JIM_TYPE_REFERENCES
,
3745 int SetCommandFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3748 const char *cmdName
;
3750 /* Get the string representation */
3751 cmdName
= Jim_String(objPtr
);
3752 /* Lookup this name into the commands hash table */
3753 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3757 /* Free the old internal repr and set the new one. */
3758 Jim_FreeIntRep(interp
, objPtr
);
3759 objPtr
->typePtr
= &commandObjType
;
3760 objPtr
->internalRep
.cmdValue
.procEpoch
= interp
->procEpoch
;
3761 objPtr
->internalRep
.cmdValue
.cmdPtr
= (void *)he
->u
.val
;
3765 /* This function returns the command structure for the command name
3766 * stored in objPtr. It tries to specialize the objPtr to contain
3767 * a cached info instead to perform the lookup into the hash table
3768 * every time. The information cached may not be uptodate, in such
3769 * a case the lookup is performed and the cache updated.
3771 * Respects the 'upcall' setting
3773 Jim_Cmd
*Jim_GetCommand(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
3777 if ((objPtr
->typePtr
!= &commandObjType
||
3778 objPtr
->internalRep
.cmdValue
.procEpoch
!= interp
->procEpoch
) &&
3779 SetCommandFromAny(interp
, objPtr
) == JIM_ERR
) {
3780 if (flags
& JIM_ERRMSG
) {
3781 Jim_SetResultFormatted(interp
, "invalid command name \"%#s\"", objPtr
);
3785 cmd
= objPtr
->internalRep
.cmdValue
.cmdPtr
;
3786 while (cmd
->isproc
&& cmd
->u
.proc
.upcall
) {
3787 cmd
= cmd
->u
.proc
.prevCmd
;
3792 /* -----------------------------------------------------------------------------
3794 * ---------------------------------------------------------------------------*/
3796 /* -----------------------------------------------------------------------------
3798 * ---------------------------------------------------------------------------*/
3800 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3802 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3804 static const Jim_ObjType variableObjType
= {
3809 JIM_TYPE_REFERENCES
,
3813 * Check that the name does not contain embedded nulls.
3815 * Variable and procedure names are maniplated as null terminated strings, so
3816 * don't allow names with embedded nulls.
3818 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
)
3820 /* Variable names and proc names can't contain embedded nulls */
3821 if (nameObjPtr
->typePtr
!= &variableObjType
) {
3823 const char *str
= Jim_GetString(nameObjPtr
, &len
);
3824 if (memchr(str
, '\0', len
)) {
3825 Jim_SetResultFormatted(interp
, "%s name contains embedded null", type
);
3832 static const char *JimUnscopedName(Jim_Interp
*interp
, const char *varName
, Jim_CallFrame
**framePtr
)
3834 if (varName
[0] == ':' && varName
[1] == ':') {
3835 *framePtr
= interp
->topFramePtr
;
3838 *framePtr
= interp
->framePtr
;
3842 /* This method should be called only by the variable API.
3843 * It returns JIM_OK on success (variable already exists),
3844 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3845 * a variable name, but syntax glue for [dict] i.e. the last
3846 * character is ')' */
3847 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3849 const char *varName
;
3850 Jim_CallFrame
*framePtr
;
3853 /* Check if the object is already an uptodate variable */
3854 if (objPtr
->typePtr
== &variableObjType
) {
3855 varName
= objPtr
->bytes
;
3856 if (varName
[0] == ':' && varName
[1] == ':') {
3857 framePtr
= interp
->topFramePtr
;
3861 framePtr
= interp
->framePtr
;
3864 if (objPtr
->internalRep
.varValue
.callFrameId
== framePtr
->id
) {
3868 /* Need to re-resolve the variable in the updated callframe */
3870 else if (objPtr
->typePtr
== &dictSubstObjType
) {
3871 return JIM_DICT_SUGAR
;
3873 else if (JimValidName(interp
, "variable", objPtr
) != JIM_OK
) {
3879 varName
= Jim_GetString(objPtr
, &len
);
3881 /* Make sure it's not syntax glue to get/set dict. */
3882 if (len
&& varName
[len
- 1] == ')' && strchr(varName
, '(') != NULL
) {
3883 return JIM_DICT_SUGAR
;
3886 varName
= JimUnscopedName(interp
, varName
, &framePtr
);
3889 /* Resolve this name in the variables hash table */
3890 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
);
3892 if (framePtr
->staticVars
) {
3893 /* Try with static vars. */
3894 he
= Jim_FindHashEntry(framePtr
->staticVars
, varName
);
3901 /* Free the old internal repr and set the new one. */
3902 Jim_FreeIntRep(interp
, objPtr
);
3903 objPtr
->typePtr
= &variableObjType
;
3904 objPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3905 objPtr
->internalRep
.varValue
.varPtr
= he
->u
.val
;
3909 /* -------------------- Variables related functions ------------------------- */
3910 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, Jim_Obj
*valObjPtr
);
3911 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, int flags
);
3913 static Jim_Var
*JimCreateVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
3916 Jim_CallFrame
*framePtr
;
3918 /* New variable to create */
3919 Jim_Var
*var
= Jim_Alloc(sizeof(*var
));
3921 var
->objPtr
= valObjPtr
;
3922 Jim_IncrRefCount(valObjPtr
);
3923 var
->linkFramePtr
= NULL
;
3925 name
= JimUnscopedName(interp
, Jim_String(nameObjPtr
), &framePtr
);
3927 /* Insert the new variable */
3928 Jim_AddHashEntry(&framePtr
->vars
, name
, var
);
3930 /* Make the object int rep a variable */
3931 Jim_FreeIntRep(interp
, nameObjPtr
);
3932 nameObjPtr
->typePtr
= &variableObjType
;
3933 nameObjPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3934 nameObjPtr
->internalRep
.varValue
.varPtr
= var
;
3939 /* For now that's dummy. Variables lookup should be optimized
3940 * in many ways, with caching of lookups, and possibly with
3941 * a table of pre-allocated vars in every CallFrame for local vars.
3942 * All the caching should also have an 'epoch' mechanism similar
3943 * to the one used by Tcl for procedures lookup caching. */
3945 int Jim_SetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
3950 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
3951 case JIM_DICT_SUGAR
:
3952 return JimDictSugarSet(interp
, nameObjPtr
, valObjPtr
);
3955 if (JimValidName(interp
, "variable", nameObjPtr
) != JIM_OK
) {
3958 JimCreateVariable(interp
, nameObjPtr
, valObjPtr
);
3962 var
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3963 if (var
->linkFramePtr
== NULL
) {
3964 Jim_IncrRefCount(valObjPtr
);
3965 Jim_DecrRefCount(interp
, var
->objPtr
);
3966 var
->objPtr
= valObjPtr
;
3968 else { /* Else handle the link */
3969 Jim_CallFrame
*savedCallFrame
;
3971 savedCallFrame
= interp
->framePtr
;
3972 interp
->framePtr
= var
->linkFramePtr
;
3973 err
= Jim_SetVariable(interp
, var
->objPtr
, valObjPtr
);
3974 interp
->framePtr
= savedCallFrame
;
3982 int Jim_SetVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
3984 Jim_Obj
*nameObjPtr
;
3987 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
3988 Jim_IncrRefCount(nameObjPtr
);
3989 result
= Jim_SetVariable(interp
, nameObjPtr
, objPtr
);
3990 Jim_DecrRefCount(interp
, nameObjPtr
);
3994 int Jim_SetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
3996 Jim_CallFrame
*savedFramePtr
;
3999 savedFramePtr
= interp
->framePtr
;
4000 interp
->framePtr
= interp
->topFramePtr
;
4001 result
= Jim_SetVariableStr(interp
, name
, objPtr
);
4002 interp
->framePtr
= savedFramePtr
;
4006 int Jim_SetVariableStrWithStr(Jim_Interp
*interp
, const char *name
, const char *val
)
4008 Jim_Obj
*nameObjPtr
, *valObjPtr
;
4011 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4012 valObjPtr
= Jim_NewStringObj(interp
, val
, -1);
4013 Jim_IncrRefCount(nameObjPtr
);
4014 Jim_IncrRefCount(valObjPtr
);
4015 result
= Jim_SetVariable(interp
, nameObjPtr
, valObjPtr
);
4016 Jim_DecrRefCount(interp
, nameObjPtr
);
4017 Jim_DecrRefCount(interp
, valObjPtr
);
4021 int Jim_SetVariableLink(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
4022 Jim_Obj
*targetNameObjPtr
, Jim_CallFrame
*targetCallFrame
)
4024 const char *varName
;
4025 const char *targetName
;
4026 Jim_CallFrame
*framePtr
;
4029 /* Check for an existing variable or link */
4030 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4031 case JIM_DICT_SUGAR
:
4032 /* XXX: This message seem unnecessarily verbose, but it matches Tcl */
4033 Jim_SetResultFormatted(interp
, "bad variable name \"%#s\": upvar won't create a scalar variable that looks like an array element", nameObjPtr
);
4037 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4039 if (varPtr
->linkFramePtr
== NULL
) {
4040 Jim_SetResultFormatted(interp
, "variable \"%#s\" already exists", nameObjPtr
);
4044 /* It exists, but is a link, so first delete the link */
4045 varPtr
->linkFramePtr
= NULL
;
4049 /* Resolve the call frames for both variables */
4050 /* XXX: SetVariableFromAny() already did this! */
4051 varName
= Jim_String(nameObjPtr
);
4053 if (varName
[0] == ':' && varName
[1] == ':') {
4054 /* Linking a global var does nothing */
4056 framePtr
= interp
->topFramePtr
;
4059 framePtr
= interp
->framePtr
;
4062 targetName
= Jim_String(targetNameObjPtr
);
4063 if (targetName
[0] == ':' && targetName
[1] == ':') {
4064 targetNameObjPtr
= Jim_NewStringObj(interp
, targetName
+ 2, -1);
4065 targetCallFrame
= interp
->topFramePtr
;
4067 Jim_IncrRefCount(targetNameObjPtr
);
4069 if (framePtr
->level
< targetCallFrame
->level
) {
4070 Jim_SetResultFormatted(interp
,
4071 "bad variable name \"%#s\": upvar won't create namespace variable that refers to procedure variable",
4073 Jim_DecrRefCount(interp
, targetNameObjPtr
);
4077 /* Check for cycles. */
4078 if (framePtr
== targetCallFrame
) {
4079 Jim_Obj
*objPtr
= targetNameObjPtr
;
4081 /* Cycles are only possible with 'uplevel 0' */
4083 if (strcmp(Jim_String(objPtr
), varName
) == 0) {
4084 Jim_SetResultString(interp
, "can't upvar from variable to itself", -1);
4085 Jim_DecrRefCount(interp
, targetNameObjPtr
);
4088 if (SetVariableFromAny(interp
, objPtr
) != JIM_OK
)
4090 varPtr
= objPtr
->internalRep
.varValue
.varPtr
;
4091 if (varPtr
->linkFramePtr
!= targetCallFrame
)
4093 objPtr
= varPtr
->objPtr
;
4097 /* Perform the binding */
4098 Jim_SetVariable(interp
, nameObjPtr
, targetNameObjPtr
);
4099 /* We are now sure 'nameObjPtr' type is variableObjType */
4100 nameObjPtr
->internalRep
.varValue
.varPtr
->linkFramePtr
= targetCallFrame
;
4101 Jim_DecrRefCount(interp
, targetNameObjPtr
);
4105 /* Return the Jim_Obj pointer associated with a variable name,
4106 * or NULL if the variable was not found in the current context.
4107 * The same optimization discussed in the comment to the
4108 * 'SetVariable' function should apply here.
4110 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4111 * in a dictionary which is shared, the array variable value is duplicated first.
4112 * This allows the array element to be updated (e.g. append, lappend) without
4113 * affecting other references to the dictionary.
4115 Jim_Obj
*Jim_GetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4117 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4119 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4121 if (varPtr
->linkFramePtr
== NULL
) {
4122 return varPtr
->objPtr
;
4127 /* The variable is a link? Resolve it. */
4128 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
4130 interp
->framePtr
= varPtr
->linkFramePtr
;
4131 objPtr
= Jim_GetVariable(interp
, varPtr
->objPtr
, flags
);
4132 interp
->framePtr
= savedCallFrame
;
4136 /* Error, so fall through to the error message */
4141 case JIM_DICT_SUGAR
:
4142 /* [dict] syntax sugar. */
4143 return JimDictSugarGet(interp
, nameObjPtr
, flags
);
4145 if (flags
& JIM_ERRMSG
) {
4146 Jim_SetResultFormatted(interp
, "can't read \"%#s\": no such variable", nameObjPtr
);
4151 Jim_Obj
*Jim_GetGlobalVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4153 Jim_CallFrame
*savedFramePtr
;
4156 savedFramePtr
= interp
->framePtr
;
4157 interp
->framePtr
= interp
->topFramePtr
;
4158 objPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4159 interp
->framePtr
= savedFramePtr
;
4164 Jim_Obj
*Jim_GetVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4166 Jim_Obj
*nameObjPtr
, *varObjPtr
;
4168 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4169 Jim_IncrRefCount(nameObjPtr
);
4170 varObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4171 Jim_DecrRefCount(interp
, nameObjPtr
);
4175 Jim_Obj
*Jim_GetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4177 Jim_CallFrame
*savedFramePtr
;
4180 savedFramePtr
= interp
->framePtr
;
4181 interp
->framePtr
= interp
->topFramePtr
;
4182 objPtr
= Jim_GetVariableStr(interp
, name
, flags
);
4183 interp
->framePtr
= savedFramePtr
;
4188 /* Unset a variable.
4189 * Note: On success unset invalidates all the variable objects created
4190 * in the current call frame incrementing. */
4191 int Jim_UnsetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4197 retval
= SetVariableFromAny(interp
, nameObjPtr
);
4198 if (retval
== JIM_DICT_SUGAR
) {
4199 /* [dict] syntax sugar. */
4200 return JimDictSugarSet(interp
, nameObjPtr
, NULL
);
4202 else if (retval
== JIM_OK
) {
4203 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4205 /* If it's a link call UnsetVariable recursively */
4206 if (varPtr
->linkFramePtr
) {
4207 Jim_CallFrame
*savedCallFrame
;
4209 savedCallFrame
= interp
->framePtr
;
4210 interp
->framePtr
= varPtr
->linkFramePtr
;
4211 retval
= Jim_UnsetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
4212 interp
->framePtr
= savedCallFrame
;
4215 Jim_CallFrame
*framePtr
;
4217 name
= JimUnscopedName(interp
, Jim_String(nameObjPtr
), &framePtr
);
4219 retval
= Jim_DeleteHashEntry(&framePtr
->vars
, name
);
4220 if (retval
== JIM_OK
) {
4221 /* Change the callframe id, invalidating var lookup caching */
4222 JimChangeCallFrameId(interp
, framePtr
);
4226 if (retval
!= JIM_OK
&& (flags
& JIM_ERRMSG
)) {
4227 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such variable", nameObjPtr
);
4232 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4234 /* Given a variable name for [dict] operation syntax sugar,
4235 * this function returns two objects, the first with the name
4236 * of the variable to set, and the second with the rispective key.
4237 * For example "foo(bar)" will return objects with string repr. of
4240 * The returned objects have refcount = 1. The function can't fail. */
4241 static void JimDictSugarParseVarKey(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
4242 Jim_Obj
**varPtrPtr
, Jim_Obj
**keyPtrPtr
)
4244 const char *str
, *p
;
4246 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4248 str
= Jim_GetString(objPtr
, &len
);
4250 p
= strchr(str
, '(');
4251 JimPanic((p
== NULL
, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str
));
4253 varObjPtr
= Jim_NewStringObj(interp
, str
, p
- str
);
4256 keyLen
= (str
+ len
) - p
;
4257 if (str
[len
- 1] == ')') {
4261 /* Create the objects with the variable name and key. */
4262 keyObjPtr
= Jim_NewStringObj(interp
, p
, keyLen
);
4264 Jim_IncrRefCount(varObjPtr
);
4265 Jim_IncrRefCount(keyObjPtr
);
4266 *varPtrPtr
= varObjPtr
;
4267 *keyPtrPtr
= keyObjPtr
;
4270 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4271 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4272 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*valObjPtr
)
4276 SetDictSubstFromAny(interp
, objPtr
);
4278 err
= Jim_SetDictKeysVector(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4279 &objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, 1, valObjPtr
, JIM_ERRMSG
);
4281 if (err
== JIM_OK
) {
4282 /* Don't keep an extra ref to the result */
4283 Jim_SetEmptyResult(interp
);
4287 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4288 if (Jim_GetVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
, JIM_NONE
)) {
4289 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such element in array",
4294 /* Make the error more informative and Tcl-compatible */
4295 Jim_SetResultFormatted(interp
, "can't %s \"%#s\": variable isn't array",
4296 (valObjPtr
? "set" : "unset"), objPtr
);
4302 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4304 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4305 * and stored back to the variable before expansion.
4307 static Jim_Obj
*JimDictExpandArrayVariable(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
,
4308 Jim_Obj
*keyObjPtr
, int flags
)
4310 Jim_Obj
*dictObjPtr
;
4311 Jim_Obj
*resObjPtr
= NULL
;
4314 dictObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
4319 ret
= Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4320 if (ret
!= JIM_OK
) {
4323 Jim_SetResultFormatted(interp
,
4324 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr
, keyObjPtr
);
4327 Jim_SetResultFormatted(interp
,
4328 "can't read \"%#s(%#s)\": no such element in array", varObjPtr
, keyObjPtr
);
4331 else if ((flags
& JIM_UNSHARED
) && Jim_IsShared(dictObjPtr
)) {
4332 dictObjPtr
= Jim_DuplicateObj(interp
, dictObjPtr
);
4333 if (Jim_SetVariable(interp
, varObjPtr
, dictObjPtr
) != JIM_OK
) {
4334 /* This can probably never happen */
4335 JimPanic((1, "SetVariable failed for JIM_UNSHARED"));
4337 /* We know that the key exists. Get the result in the now-unshared dictionary */
4338 Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4344 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4345 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4347 SetDictSubstFromAny(interp
, objPtr
);
4349 return JimDictExpandArrayVariable(interp
,
4350 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4351 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, flags
);
4354 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4356 void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4358 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
4359 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
4362 void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4364 JIM_NOTUSED(interp
);
4366 dupPtr
->internalRep
.dictSubstValue
.varNameObjPtr
=
4367 srcPtr
->internalRep
.dictSubstValue
.varNameObjPtr
;
4368 dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
= srcPtr
->internalRep
.dictSubstValue
.indexObjPtr
;
4369 dupPtr
->typePtr
= &dictSubstObjType
;
4372 /* Note: The object *must* be in dict-sugar format */
4373 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4375 if (objPtr
->typePtr
!= &dictSubstObjType
) {
4376 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4378 if (objPtr
->typePtr
== &interpolatedObjType
) {
4379 /* An interpolated object in dict-sugar form */
4381 const ScriptToken
*token
= objPtr
->internalRep
.twoPtrValue
.ptr1
;
4383 varObjPtr
= token
[0].objPtr
;
4384 keyObjPtr
= objPtr
->internalRep
.twoPtrValue
.ptr2
;
4386 Jim_IncrRefCount(varObjPtr
);
4387 Jim_IncrRefCount(keyObjPtr
);
4390 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
4393 Jim_FreeIntRep(interp
, objPtr
);
4394 objPtr
->typePtr
= &dictSubstObjType
;
4395 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= varObjPtr
;
4396 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= keyObjPtr
;
4400 /* This function is used to expand [dict get] sugar in the form
4401 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4402 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4403 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4404 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4405 * the [dict]ionary contained in variable VARNAME. */
4406 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4408 Jim_Obj
*resObjPtr
= NULL
;
4409 Jim_Obj
*substKeyObjPtr
= NULL
;
4411 SetDictSubstFromAny(interp
, objPtr
);
4413 if (Jim_SubstObj(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
,
4414 &substKeyObjPtr
, JIM_NONE
)
4418 Jim_IncrRefCount(substKeyObjPtr
);
4420 JimDictExpandArrayVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4422 Jim_DecrRefCount(interp
, substKeyObjPtr
);
4427 static Jim_Obj
*JimExpandExprSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4429 Jim_Obj
*resultObjPtr
;
4431 if (Jim_EvalExpression(interp
, objPtr
, &resultObjPtr
) == JIM_OK
) {
4432 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4433 resultObjPtr
->refCount
--;
4434 return resultObjPtr
;
4439 /* -----------------------------------------------------------------------------
4441 * ---------------------------------------------------------------------------*/
4443 static Jim_CallFrame
*JimCreateCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*parent
)
4447 if (interp
->freeFramesList
) {
4448 cf
= interp
->freeFramesList
;
4449 interp
->freeFramesList
= cf
->nextFramePtr
;
4452 cf
= Jim_Alloc(sizeof(*cf
));
4453 cf
->vars
.table
= NULL
;
4456 cf
->id
= interp
->callFrameEpoch
++;
4457 cf
->parentCallFrame
= parent
;
4458 cf
->level
= parent
? parent
->level
+ 1 : 0;
4461 cf
->procArgsObjPtr
= NULL
;
4462 cf
->procBodyObjPtr
= NULL
;
4463 cf
->nextFramePtr
= NULL
;
4464 cf
->staticVars
= NULL
;
4465 if (cf
->vars
.table
== NULL
)
4466 Jim_InitHashTable(&cf
->vars
, &JimVariablesHashTableType
, interp
);
4470 /* Used to invalidate every caching related to callframe stability. */
4471 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
)
4473 cf
->id
= interp
->callFrameEpoch
++;
4476 #define JIM_FCF_NONE 0 /* no flags */
4477 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4478 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
)
4480 if (cf
->procArgsObjPtr
)
4481 Jim_DecrRefCount(interp
, cf
->procArgsObjPtr
);
4482 if (cf
->procBodyObjPtr
)
4483 Jim_DecrRefCount(interp
, cf
->procBodyObjPtr
);
4484 if (!(flags
& JIM_FCF_NOHT
))
4485 Jim_FreeHashTable(&cf
->vars
);
4488 Jim_HashEntry
**table
= cf
->vars
.table
, *he
;
4490 for (i
= 0; i
< JIM_HT_INITIAL_SIZE
; i
++) {
4492 while (he
!= NULL
) {
4493 Jim_HashEntry
*nextEntry
= he
->next
;
4494 Jim_Var
*varPtr
= (void *)he
->u
.val
;
4496 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
4497 Jim_Free(he
->u
.val
);
4498 Jim_Free((void *)he
->key
); /* ATTENTION: const cast */
4506 cf
->nextFramePtr
= interp
->freeFramesList
;
4507 interp
->freeFramesList
= cf
;
4510 /* -----------------------------------------------------------------------------
4512 * ---------------------------------------------------------------------------*/
4513 #ifdef JIM_REFERENCES
4515 /* References HashTable Type.
4517 * Keys are jim_wide integers, dynamically allocated for now but in the
4518 * future it's worth to cache this 8 bytes objects. Values are poitners
4519 * to Jim_References. */
4520 static void JimReferencesHTValDestructor(void *interp
, void *val
)
4522 Jim_Reference
*refPtr
= (void *)val
;
4524 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
4525 if (refPtr
->finalizerCmdNamePtr
!= NULL
) {
4526 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4531 static unsigned int JimReferencesHTHashFunction(const void *key
)
4533 /* Only the least significant bits are used. */
4534 const jim_wide
*widePtr
= key
;
4535 unsigned int intValue
= (unsigned int)*widePtr
;
4537 return Jim_IntHashFunction(intValue
);
4540 static void *JimReferencesHTKeyDup(void *privdata
, const void *key
)
4542 void *copy
= Jim_Alloc(sizeof(jim_wide
));
4544 JIM_NOTUSED(privdata
);
4546 memcpy(copy
, key
, sizeof(jim_wide
));
4550 static int JimReferencesHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
4552 JIM_NOTUSED(privdata
);
4554 return memcmp(key1
, key2
, sizeof(jim_wide
)) == 0;
4557 static void JimReferencesHTKeyDestructor(void *privdata
, void *key
)
4559 JIM_NOTUSED(privdata
);
4564 static const Jim_HashTableType JimReferencesHashTableType
= {
4565 JimReferencesHTHashFunction
, /* hash function */
4566 JimReferencesHTKeyDup
, /* key dup */
4568 JimReferencesHTKeyCompare
, /* key compare */
4569 JimReferencesHTKeyDestructor
, /* key destructor */
4570 JimReferencesHTValDestructor
/* val destructor */
4573 /* -----------------------------------------------------------------------------
4574 * Reference object type and References API
4575 * ---------------------------------------------------------------------------*/
4577 /* The string representation of references has two features in order
4578 * to make the GC faster. The first is that every reference starts
4579 * with a non common character '<', in order to make the string matching
4580 * faster. The second is that the reference string rep is 42 characters
4581 * in length, this allows to avoid to check every object with a string
4582 * repr < 42, and usually there aren't many of these objects. */
4584 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4586 static int JimFormatReference(char *buf
, Jim_Reference
*refPtr
, jim_wide id
)
4588 const char *fmt
= "<reference.<%s>.%020" JIM_WIDE_MODIFIER
">";
4590 sprintf(buf
, fmt
, refPtr
->tag
, id
);
4591 return JIM_REFERENCE_SPACE
;
4594 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
);
4596 static const Jim_ObjType referenceObjType
= {
4600 UpdateStringOfReference
,
4601 JIM_TYPE_REFERENCES
,
4604 void UpdateStringOfReference(struct Jim_Obj
*objPtr
)
4607 char buf
[JIM_REFERENCE_SPACE
+ 1];
4608 Jim_Reference
*refPtr
;
4610 refPtr
= objPtr
->internalRep
.refValue
.refPtr
;
4611 len
= JimFormatReference(buf
, refPtr
, objPtr
->internalRep
.refValue
.id
);
4612 objPtr
->bytes
= Jim_Alloc(len
+ 1);
4613 memcpy(objPtr
->bytes
, buf
, len
+ 1);
4614 objPtr
->length
= len
;
4617 /* returns true if 'c' is a valid reference tag character.
4618 * i.e. inside the range [_a-zA-Z0-9] */
4619 static int isrefchar(int c
)
4621 return (c
== '_' || isalnum(c
));
4624 static int SetReferenceFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4628 const char *str
, *start
, *end
;
4630 Jim_Reference
*refPtr
;
4633 /* Get the string representation */
4634 str
= Jim_GetString(objPtr
, &len
);
4635 /* Check if it looks like a reference */
4636 if (len
< JIM_REFERENCE_SPACE
)
4640 end
= str
+ len
- 1;
4641 while (*start
== ' ')
4643 while (*end
== ' ' && end
> start
)
4645 if (end
- start
+ 1 != JIM_REFERENCE_SPACE
)
4647 /* <reference.<1234567>.%020> */
4648 if (memcmp(start
, "<reference.<", 12) != 0)
4650 if (start
[12 + JIM_REFERENCE_TAGLEN
] != '>' || end
[0] != '>')
4652 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4653 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4654 if (!isrefchar(start
[12 + i
]))
4657 /* Extract info from the reference. */
4658 memcpy(refId
, start
+ 14 + JIM_REFERENCE_TAGLEN
, 20);
4660 /* Try to convert the ID into a jim_wide */
4661 if (Jim_StringToWide(refId
, &wideValue
, 10) != JIM_OK
)
4663 /* Check if the reference really exists! */
4664 he
= Jim_FindHashEntry(&interp
->references
, &wideValue
);
4666 Jim_SetResultFormatted(interp
, "invalid reference id \"%#s\"", objPtr
);
4670 /* Free the old internal repr and set the new one. */
4671 Jim_FreeIntRep(interp
, objPtr
);
4672 objPtr
->typePtr
= &referenceObjType
;
4673 objPtr
->internalRep
.refValue
.id
= wideValue
;
4674 objPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4678 Jim_SetResultFormatted(interp
, "expected reference but got \"%#s\"", objPtr
);
4682 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4683 * as finalizer command (or NULL if there is no finalizer).
4684 * The returned reference object has refcount = 0. */
4685 Jim_Obj
*Jim_NewReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*tagPtr
, Jim_Obj
*cmdNamePtr
)
4687 struct Jim_Reference
*refPtr
;
4688 jim_wide wideValue
= interp
->referenceNextId
;
4693 /* Perform the Garbage Collection if needed. */
4694 Jim_CollectIfNeeded(interp
);
4696 refPtr
= Jim_Alloc(sizeof(*refPtr
));
4697 refPtr
->objPtr
= objPtr
;
4698 Jim_IncrRefCount(objPtr
);
4699 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4701 Jim_IncrRefCount(cmdNamePtr
);
4702 Jim_AddHashEntry(&interp
->references
, &wideValue
, refPtr
);
4703 refObjPtr
= Jim_NewObj(interp
);
4704 refObjPtr
->typePtr
= &referenceObjType
;
4705 refObjPtr
->bytes
= NULL
;
4706 refObjPtr
->internalRep
.refValue
.id
= interp
->referenceNextId
;
4707 refObjPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4708 interp
->referenceNextId
++;
4709 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4710 * that does not pass the 'isrefchar' test is replaced with '_' */
4711 tag
= Jim_GetString(tagPtr
, &tagLen
);
4712 if (tagLen
> JIM_REFERENCE_TAGLEN
)
4713 tagLen
= JIM_REFERENCE_TAGLEN
;
4714 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4715 if (i
< tagLen
&& isrefchar(tag
[i
]))
4716 refPtr
->tag
[i
] = tag
[i
];
4718 refPtr
->tag
[i
] = '_';
4720 refPtr
->tag
[JIM_REFERENCE_TAGLEN
] = '\0';
4724 Jim_Reference
*Jim_GetReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4726 if (objPtr
->typePtr
!= &referenceObjType
&& SetReferenceFromAny(interp
, objPtr
) == JIM_ERR
)
4728 return objPtr
->internalRep
.refValue
.refPtr
;
4731 int Jim_SetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*cmdNamePtr
)
4733 Jim_Reference
*refPtr
;
4735 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4737 Jim_IncrRefCount(cmdNamePtr
);
4738 if (refPtr
->finalizerCmdNamePtr
)
4739 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4740 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4744 int Jim_GetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
**cmdNamePtrPtr
)
4746 Jim_Reference
*refPtr
;
4748 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4750 *cmdNamePtrPtr
= refPtr
->finalizerCmdNamePtr
;
4754 /* -----------------------------------------------------------------------------
4755 * References Garbage Collection
4756 * ---------------------------------------------------------------------------*/
4758 /* This the hash table type for the "MARK" phase of the GC */
4759 static const Jim_HashTableType JimRefMarkHashTableType
= {
4760 JimReferencesHTHashFunction
, /* hash function */
4761 JimReferencesHTKeyDup
, /* key dup */
4763 JimReferencesHTKeyCompare
, /* key compare */
4764 JimReferencesHTKeyDestructor
, /* key destructor */
4765 NULL
/* val destructor */
4768 /* Performs the garbage collection. */
4769 int Jim_Collect(Jim_Interp
*interp
)
4772 #ifndef JIM_BOOTSTRAP
4773 Jim_HashTable marks
;
4774 Jim_HashTableIterator
*htiter
;
4778 /* Avoid recursive calls */
4779 if (interp
->lastCollectId
== -1) {
4780 /* Jim_Collect() already running. Return just now. */
4783 interp
->lastCollectId
= -1;
4785 /* Mark all the references found into the 'mark' hash table.
4786 * The references are searched in every live object that
4787 * is of a type that can contain references. */
4788 Jim_InitHashTable(&marks
, &JimRefMarkHashTableType
, NULL
);
4789 objPtr
= interp
->liveList
;
4791 if (objPtr
->typePtr
== NULL
|| objPtr
->typePtr
->flags
& JIM_TYPE_REFERENCES
) {
4792 const char *str
, *p
;
4795 /* If the object is of type reference, to get the
4796 * Id is simple... */
4797 if (objPtr
->typePtr
== &referenceObjType
) {
4798 Jim_AddHashEntry(&marks
, &objPtr
->internalRep
.refValue
.id
, NULL
);
4800 printf("MARK (reference): %d refcount: %d" JIM_NL
,
4801 (int)objPtr
->internalRep
.refValue
.id
, objPtr
->refCount
);
4803 objPtr
= objPtr
->nextObjPtr
;
4806 /* Get the string repr of the object we want
4807 * to scan for references. */
4808 p
= str
= Jim_GetString(objPtr
, &len
);
4809 /* Skip objects too little to contain references. */
4810 if (len
< JIM_REFERENCE_SPACE
) {
4811 objPtr
= objPtr
->nextObjPtr
;
4814 /* Extract references from the object string repr. */
4820 if ((p
= strstr(p
, "<reference.<")) == NULL
)
4822 /* Check if it's a valid reference. */
4823 if (len
- (p
- str
) < JIM_REFERENCE_SPACE
)
4825 if (p
[41] != '>' || p
[19] != '>' || p
[20] != '.')
4827 for (i
= 21; i
<= 40; i
++)
4828 if (!isdigit(UCHAR(p
[i
])))
4831 memcpy(buf
, p
+ 21, 20);
4833 Jim_StringToWide(buf
, &id
, 10);
4835 /* Ok, a reference for the given ID
4836 * was found. Mark it. */
4837 Jim_AddHashEntry(&marks
, &id
, NULL
);
4839 printf("MARK: %d" JIM_NL
, (int)id
);
4841 p
+= JIM_REFERENCE_SPACE
;
4844 objPtr
= objPtr
->nextObjPtr
;
4847 /* Run the references hash table to destroy every reference that
4848 * is not referenced outside (not present in the mark HT). */
4849 htiter
= Jim_GetHashTableIterator(&interp
->references
);
4850 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
4851 const jim_wide
*refId
;
4852 Jim_Reference
*refPtr
;
4855 /* Check if in the mark phase we encountered
4856 * this reference. */
4857 if (Jim_FindHashEntry(&marks
, refId
) == NULL
) {
4859 printf("COLLECTING %d" JIM_NL
, (int)*refId
);
4862 /* Drop the reference, but call the
4863 * finalizer first if registered. */
4865 if (refPtr
->finalizerCmdNamePtr
) {
4866 char *refstr
= Jim_Alloc(JIM_REFERENCE_SPACE
+ 1);
4867 Jim_Obj
*objv
[3], *oldResult
;
4869 JimFormatReference(refstr
, refPtr
, *refId
);
4871 objv
[0] = refPtr
->finalizerCmdNamePtr
;
4872 objv
[1] = Jim_NewStringObjNoAlloc(interp
, refstr
, 32);
4873 objv
[2] = refPtr
->objPtr
;
4874 Jim_IncrRefCount(objv
[0]);
4875 Jim_IncrRefCount(objv
[1]);
4876 Jim_IncrRefCount(objv
[2]);
4878 /* Drop the reference itself */
4879 Jim_DeleteHashEntry(&interp
->references
, refId
);
4881 /* Call the finalizer. Errors ignored. */
4882 oldResult
= interp
->result
;
4883 Jim_IncrRefCount(oldResult
);
4884 Jim_EvalObjVector(interp
, 3, objv
);
4885 Jim_SetResult(interp
, oldResult
);
4886 Jim_DecrRefCount(interp
, oldResult
);
4888 Jim_DecrRefCount(interp
, objv
[0]);
4889 Jim_DecrRefCount(interp
, objv
[1]);
4890 Jim_DecrRefCount(interp
, objv
[2]);
4893 Jim_DeleteHashEntry(&interp
->references
, refId
);
4897 Jim_FreeHashTableIterator(htiter
);
4898 Jim_FreeHashTable(&marks
);
4899 interp
->lastCollectId
= interp
->referenceNextId
;
4900 interp
->lastCollectTime
= time(NULL
);
4901 #endif /* JIM_BOOTSTRAP */
4905 #define JIM_COLLECT_ID_PERIOD 5000
4906 #define JIM_COLLECT_TIME_PERIOD 300
4908 void Jim_CollectIfNeeded(Jim_Interp
*interp
)
4913 elapsedId
= interp
->referenceNextId
- interp
->lastCollectId
;
4914 elapsedTime
= time(NULL
) - interp
->lastCollectTime
;
4917 if (elapsedId
> JIM_COLLECT_ID_PERIOD
|| elapsedTime
> JIM_COLLECT_TIME_PERIOD
) {
4918 Jim_Collect(interp
);
4923 static int JimIsBigEndian(void)
4930 return uval
.c
[0] == 1;
4933 /* -----------------------------------------------------------------------------
4934 * Interpreter related functions
4935 * ---------------------------------------------------------------------------*/
4937 Jim_Interp
*Jim_CreateInterp(void)
4939 Jim_Interp
*i
= Jim_Alloc(sizeof(*i
));
4941 memset(i
, 0, sizeof(*i
));
4943 i
->maxNestingDepth
= JIM_MAX_NESTING_DEPTH
;
4944 i
->lastCollectTime
= time(NULL
);
4946 /* Note that we can create objects only after the
4947 * interpreter liveList and freeList pointers are
4948 * initialized to NULL. */
4949 Jim_InitHashTable(&i
->commands
, &JimCommandsHashTableType
, i
);
4950 #ifdef JIM_REFERENCES
4951 Jim_InitHashTable(&i
->references
, &JimReferencesHashTableType
, i
);
4953 Jim_InitHashTable(&i
->assocData
, &JimAssocDataHashTableType
, i
);
4954 Jim_InitHashTable(&i
->packages
, &JimPackageHashTableType
, NULL
);
4955 i
->framePtr
= i
->topFramePtr
= JimCreateCallFrame(i
, NULL
);
4956 i
->emptyObj
= Jim_NewEmptyStringObj(i
);
4957 i
->trueObj
= Jim_NewIntObj(i
, 1);
4958 i
->falseObj
= Jim_NewIntObj(i
, 0);
4959 i
->errorFileNameObj
= i
->emptyObj
;
4960 i
->result
= i
->emptyObj
;
4961 i
->stackTrace
= Jim_NewListObj(i
, NULL
, 0);
4962 i
->unknown
= Jim_NewStringObj(i
, "unknown", -1);
4963 i
->errorProc
= i
->emptyObj
;
4964 i
->currentScriptObj
= Jim_NewEmptyStringObj(i
);
4965 Jim_IncrRefCount(i
->emptyObj
);
4966 Jim_IncrRefCount(i
->errorFileNameObj
);
4967 Jim_IncrRefCount(i
->result
);
4968 Jim_IncrRefCount(i
->stackTrace
);
4969 Jim_IncrRefCount(i
->unknown
);
4970 Jim_IncrRefCount(i
->currentScriptObj
);
4971 Jim_IncrRefCount(i
->errorProc
);
4972 Jim_IncrRefCount(i
->trueObj
);
4973 Jim_IncrRefCount(i
->falseObj
);
4975 /* Initialize key variables every interpreter should contain */
4976 Jim_SetVariableStrWithStr(i
, JIM_LIBPATH
, TCL_LIBRARY
);
4977 Jim_SetVariableStrWithStr(i
, JIM_INTERACTIVE
, "0");
4979 Jim_SetVariableStrWithStr(i
, "tcl_platform(os)", TCL_PLATFORM_OS
);
4980 Jim_SetVariableStrWithStr(i
, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM
);
4981 Jim_SetVariableStrWithStr(i
, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR
);
4982 Jim_SetVariableStrWithStr(i
, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4983 Jim_SetVariableStrWithStr(i
, "tcl_platform(threaded)", "0");
4984 Jim_SetVariableStr(i
, "tcl_platform(pointerSize)", Jim_NewIntObj(i
, sizeof(void *)));
4985 Jim_SetVariableStr(i
, "tcl_platform(wordSize)", Jim_NewIntObj(i
, sizeof(jim_wide
)));
4990 void Jim_FreeInterp(Jim_Interp
*i
)
4992 Jim_CallFrame
*cf
= i
->framePtr
, *prevcf
, *nextcf
;
4993 Jim_Obj
*objPtr
, *nextObjPtr
;
4995 Jim_DecrRefCount(i
, i
->emptyObj
);
4996 Jim_DecrRefCount(i
, i
->trueObj
);
4997 Jim_DecrRefCount(i
, i
->falseObj
);
4998 Jim_DecrRefCount(i
, i
->result
);
4999 Jim_DecrRefCount(i
, i
->stackTrace
);
5000 Jim_DecrRefCount(i
, i
->errorProc
);
5001 Jim_DecrRefCount(i
, i
->unknown
);
5002 Jim_DecrRefCount(i
, i
->errorFileNameObj
);
5003 Jim_DecrRefCount(i
, i
->currentScriptObj
);
5004 Jim_FreeHashTable(&i
->commands
);
5005 #ifdef JIM_REFERENCES
5006 Jim_FreeHashTable(&i
->references
);
5008 Jim_FreeHashTable(&i
->packages
);
5009 Jim_Free(i
->prngState
);
5010 Jim_FreeHashTable(&i
->assocData
);
5011 JimDeleteLocalProcs(i
);
5013 /* Free the call frames list */
5015 prevcf
= cf
->parentCallFrame
;
5016 JimFreeCallFrame(i
, cf
, JIM_FCF_NONE
);
5019 /* Check that the live object list is empty, otherwise
5020 * there is a memory leak. */
5021 if (i
->liveList
!= NULL
) {
5022 objPtr
= i
->liveList
;
5024 printf(JIM_NL
"-------------------------------------" JIM_NL
);
5025 printf("Objects still in the free list:" JIM_NL
);
5027 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "string";
5029 printf("%p (%d) %-10s: '%.20s'" JIM_NL
,
5030 (void *)objPtr
, objPtr
->refCount
, type
, objPtr
->bytes
? objPtr
->bytes
: "(null)");
5031 if (objPtr
->typePtr
== &sourceObjType
) {
5032 printf("FILE %s LINE %d" JIM_NL
,
5033 Jim_String(objPtr
->internalRep
.sourceValue
.fileNameObj
),
5034 objPtr
->internalRep
.sourceValue
.lineNumber
);
5036 objPtr
= objPtr
->nextObjPtr
;
5038 printf("-------------------------------------" JIM_NL JIM_NL
);
5039 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5041 /* Free all the freed objects. */
5042 objPtr
= i
->freeList
;
5044 nextObjPtr
= objPtr
->nextObjPtr
;
5046 objPtr
= nextObjPtr
;
5048 /* Free cached CallFrame structures */
5049 cf
= i
->freeFramesList
;
5051 nextcf
= cf
->nextFramePtr
;
5052 if (cf
->vars
.table
!= NULL
)
5053 Jim_Free(cf
->vars
.table
);
5058 Jim_FreeLoadHandles(i
);
5061 /* Free the interpreter structure. */
5065 /* Returns the call frame relative to the level represented by
5066 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5068 * This function accepts the 'level' argument in the form
5069 * of the commands [uplevel] and [upvar].
5071 * For a function accepting a relative integer as level suitable
5072 * for implementation of [info level ?level?] check the
5073 * JimGetCallFrameByInteger() function.
5075 * Returns NULL on error.
5077 Jim_CallFrame
*Jim_GetCallFrameByLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5081 Jim_CallFrame
*framePtr
;
5084 str
= Jim_String(levelObjPtr
);
5085 if (str
[0] == '#') {
5088 level
= strtol(str
+ 1, &endptr
, 0);
5089 if (str
[1] == '\0' || endptr
[0] != '\0') {
5094 if (Jim_GetLong(interp
, levelObjPtr
, &level
) != JIM_OK
|| level
< 0) {
5098 /* Convert from a relative to an absolute level */
5099 level
= interp
->framePtr
->level
- level
;
5104 str
= "1"; /* Needed to format the error message. */
5105 level
= interp
->framePtr
->level
- 1;
5109 return interp
->topFramePtr
;
5113 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5114 if (framePtr
->level
== level
) {
5120 Jim_SetResultFormatted(interp
, "bad level \"%s\"", str
);
5124 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5125 * as a relative integer like in the [info level ?level?] command.
5127 static Jim_CallFrame
*JimGetCallFrameByInteger(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5130 Jim_CallFrame
*framePtr
;
5132 if (Jim_GetLong(interp
, levelObjPtr
, &level
) == JIM_OK
) {
5134 /* Convert from a relative to an absolute level */
5135 level
= interp
->framePtr
->level
+ level
;
5139 return interp
->topFramePtr
;
5143 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5144 if (framePtr
->level
== level
) {
5150 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
5154 static void JimResetStackTrace(Jim_Interp
*interp
)
5156 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5157 interp
->stackTrace
= Jim_NewListObj(interp
, NULL
, 0);
5158 Jim_IncrRefCount(interp
->stackTrace
);
5161 static void JimSetStackTrace(Jim_Interp
*interp
, Jim_Obj
*stackTraceObj
)
5165 /* Increment reference first in case these are the same object */
5166 Jim_IncrRefCount(stackTraceObj
);
5167 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5168 interp
->stackTrace
= stackTraceObj
;
5169 interp
->errorFlag
= 1;
5171 /* This is a bit ugly.
5172 * If the filename of the last entry of the stack trace is empty,
5173 * the next stack level should be added.
5175 len
= Jim_ListLength(interp
, interp
->stackTrace
);
5177 Jim_Obj
*filenameObj
;
5179 Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &filenameObj
, JIM_NONE
);
5181 Jim_GetString(filenameObj
, &len
);
5183 if (!Jim_Length(filenameObj
)) {
5184 interp
->addStackTrace
= 1;
5189 /* Returns 1 if the stack trace information was used or 0 if not */
5190 static void JimAppendStackTrace(Jim_Interp
*interp
, const char *procname
,
5191 Jim_Obj
*fileNameObj
, int linenr
)
5193 if (strcmp(procname
, "unknown") == 0) {
5196 if (!*procname
&& !Jim_Length(fileNameObj
)) {
5197 /* No useful info here */
5201 if (Jim_IsShared(interp
->stackTrace
)) {
5202 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5203 interp
->stackTrace
= Jim_DuplicateObj(interp
, interp
->stackTrace
);
5204 Jim_IncrRefCount(interp
->stackTrace
);
5207 /* If we have no procname but the previous element did, merge with that frame */
5208 if (!*procname
&& Jim_Length(fileNameObj
)) {
5209 /* Just a filename. Check the previous entry */
5210 int len
= Jim_ListLength(interp
, interp
->stackTrace
);
5214 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 3, &objPtr
, JIM_NONE
) == JIM_OK
&& Jim_Length(objPtr
)) {
5215 /* Yes, the previous level had procname */
5216 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &objPtr
, JIM_NONE
) == JIM_OK
&& !Jim_Length(objPtr
)) {
5217 /* But no filename, so merge the new info with that frame */
5218 ListSetIndex(interp
, interp
->stackTrace
, len
- 2, fileNameObj
, 0);
5219 ListSetIndex(interp
, interp
->stackTrace
, len
- 1, Jim_NewIntObj(interp
, linenr
), 0);
5226 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewStringObj(interp
, procname
, -1));
5227 Jim_ListAppendElement(interp
, interp
->stackTrace
, fileNameObj
);
5228 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewIntObj(interp
, linenr
));
5231 int Jim_SetAssocData(Jim_Interp
*interp
, const char *key
, Jim_InterpDeleteProc
* delProc
,
5234 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) Jim_Alloc(sizeof(AssocDataValue
));
5236 assocEntryPtr
->delProc
= delProc
;
5237 assocEntryPtr
->data
= data
;
5238 return Jim_AddHashEntry(&interp
->assocData
, key
, assocEntryPtr
);
5241 void *Jim_GetAssocData(Jim_Interp
*interp
, const char *key
)
5243 Jim_HashEntry
*entryPtr
= Jim_FindHashEntry(&interp
->assocData
, key
);
5245 if (entryPtr
!= NULL
) {
5246 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) entryPtr
->u
.val
;
5248 return assocEntryPtr
->data
;
5253 int Jim_DeleteAssocData(Jim_Interp
*interp
, const char *key
)
5255 return Jim_DeleteHashEntry(&interp
->assocData
, key
);
5258 int Jim_GetExitCode(Jim_Interp
*interp
)
5260 return interp
->exitCode
;
5263 /* -----------------------------------------------------------------------------
5265 * ---------------------------------------------------------------------------*/
5266 #define JIM_INTEGER_SPACE 24
5268 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
);
5269 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
5271 static const Jim_ObjType intObjType
= {
5279 /* A coerced double is closer to an int than a double.
5280 * It is an int value temporarily masquerading as a double value.
5281 * i.e. it has the same string value as an int and Jim_GetWide()
5282 * succeeds, but also Jim_GetDouble() returns the value directly.
5284 static const Jim_ObjType coercedDoubleObjType
= {
5293 void UpdateStringOfInt(struct Jim_Obj
*objPtr
)
5296 char buf
[JIM_INTEGER_SPACE
+ 1];
5298 len
= Jim_WideToString(buf
, JimWideValue(objPtr
));
5299 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5300 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5301 objPtr
->length
= len
;
5304 int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
5309 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5310 /* Simple switcheroo */
5311 objPtr
->typePtr
= &intObjType
;
5315 /* Get the string representation */
5316 str
= Jim_String(objPtr
);
5317 /* Try to convert into a jim_wide */
5318 if (Jim_StringToWide(str
, &wideValue
, 0) != JIM_OK
) {
5319 if (flags
& JIM_ERRMSG
) {
5320 Jim_SetResultFormatted(interp
, "expected integer but got \"%#s\"", objPtr
);
5324 if ((wideValue
== JIM_WIDE_MIN
|| wideValue
== JIM_WIDE_MAX
) && errno
== ERANGE
) {
5325 Jim_SetResultString(interp
, "Integer value too big to be represented", -1);
5328 /* Free the old internal repr and set the new one. */
5329 Jim_FreeIntRep(interp
, objPtr
);
5330 objPtr
->typePtr
= &intObjType
;
5331 objPtr
->internalRep
.wideValue
= wideValue
;
5335 #ifdef JIM_OPTIMIZATION
5336 static int JimIsWide(Jim_Obj
*objPtr
)
5338 return objPtr
->typePtr
== &intObjType
;
5342 int Jim_GetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5344 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
5346 *widePtr
= JimWideValue(objPtr
);
5350 /* Get a wide but does not set an error if the format is bad. */
5351 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5353 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_NONE
) == JIM_ERR
)
5355 *widePtr
= JimWideValue(objPtr
);
5359 int Jim_GetLong(Jim_Interp
*interp
, Jim_Obj
*objPtr
, long *longPtr
)
5364 retval
= Jim_GetWide(interp
, objPtr
, &wideValue
);
5365 if (retval
== JIM_OK
) {
5366 *longPtr
= (long)wideValue
;
5372 Jim_Obj
*Jim_NewIntObj(Jim_Interp
*interp
, jim_wide wideValue
)
5376 objPtr
= Jim_NewObj(interp
);
5377 objPtr
->typePtr
= &intObjType
;
5378 objPtr
->bytes
= NULL
;
5379 objPtr
->internalRep
.wideValue
= wideValue
;
5383 /* -----------------------------------------------------------------------------
5385 * ---------------------------------------------------------------------------*/
5386 #define JIM_DOUBLE_SPACE 30
5388 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
);
5389 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5391 static const Jim_ObjType doubleObjType
= {
5395 UpdateStringOfDouble
,
5399 void UpdateStringOfDouble(struct Jim_Obj
*objPtr
)
5402 char buf
[JIM_DOUBLE_SPACE
+ 1];
5404 len
= Jim_DoubleToString(buf
, objPtr
->internalRep
.doubleValue
);
5405 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5406 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5407 objPtr
->length
= len
;
5410 int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5416 /* Preserve the string representation.
5417 * Needed so we can convert back to int without loss
5419 str
= Jim_String(objPtr
);
5421 #ifdef HAVE_LONG_LONG
5422 /* Assume a 53 bit mantissa */
5423 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5424 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5426 if (objPtr
->typePtr
== &intObjType
5427 && JimWideValue(objPtr
) >= MIN_INT_IN_DOUBLE
5428 && JimWideValue(objPtr
) <= MAX_INT_IN_DOUBLE
) {
5430 /* Direct conversion to coerced double */
5431 objPtr
->typePtr
= &coercedDoubleObjType
;
5436 if (Jim_StringToWide(str
, &wideValue
, 10) == JIM_OK
) {
5437 /* Managed to convert to an int, so we can use this as a cooerced double */
5438 Jim_FreeIntRep(interp
, objPtr
);
5439 objPtr
->typePtr
= &coercedDoubleObjType
;
5440 objPtr
->internalRep
.wideValue
= wideValue
;
5444 /* Try to convert into a double */
5445 if (Jim_StringToDouble(str
, &doubleValue
) != JIM_OK
) {
5446 Jim_SetResultFormatted(interp
, "expected number but got \"%#s\"", objPtr
);
5449 /* Free the old internal repr and set the new one. */
5450 Jim_FreeIntRep(interp
, objPtr
);
5452 objPtr
->typePtr
= &doubleObjType
;
5453 objPtr
->internalRep
.doubleValue
= doubleValue
;
5457 int Jim_GetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double *doublePtr
)
5459 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5460 *doublePtr
= JimWideValue(objPtr
);
5463 if (objPtr
->typePtr
!= &doubleObjType
&& SetDoubleFromAny(interp
, objPtr
) == JIM_ERR
)
5466 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5467 *doublePtr
= JimWideValue(objPtr
);
5470 *doublePtr
= objPtr
->internalRep
.doubleValue
;
5475 Jim_Obj
*Jim_NewDoubleObj(Jim_Interp
*interp
, double doubleValue
)
5479 objPtr
= Jim_NewObj(interp
);
5480 objPtr
->typePtr
= &doubleObjType
;
5481 objPtr
->bytes
= NULL
;
5482 objPtr
->internalRep
.doubleValue
= doubleValue
;
5486 /* -----------------------------------------------------------------------------
5488 * ---------------------------------------------------------------------------*/
5489 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
);
5490 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
);
5491 static void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5492 static void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
5493 static void UpdateStringOfList(struct Jim_Obj
*objPtr
);
5494 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
5496 /* Note that while the elements of the list may contain references,
5497 * the list object itself can't. This basically means that the
5498 * list object string representation as a whole can't contain references
5499 * that are not presents in the single elements. */
5500 static const Jim_ObjType listObjType
= {
5502 FreeListInternalRep
,
5508 void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5512 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5513 Jim_DecrRefCount(interp
, objPtr
->internalRep
.listValue
.ele
[i
]);
5515 Jim_Free(objPtr
->internalRep
.listValue
.ele
);
5518 void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
5522 JIM_NOTUSED(interp
);
5524 dupPtr
->internalRep
.listValue
.len
= srcPtr
->internalRep
.listValue
.len
;
5525 dupPtr
->internalRep
.listValue
.maxLen
= srcPtr
->internalRep
.listValue
.maxLen
;
5526 dupPtr
->internalRep
.listValue
.ele
=
5527 Jim_Alloc(sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.maxLen
);
5528 memcpy(dupPtr
->internalRep
.listValue
.ele
, srcPtr
->internalRep
.listValue
.ele
,
5529 sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.len
);
5530 for (i
= 0; i
< dupPtr
->internalRep
.listValue
.len
; i
++) {
5531 Jim_IncrRefCount(dupPtr
->internalRep
.listValue
.ele
[i
]);
5533 dupPtr
->typePtr
= &listObjType
;
5536 /* The following function checks if a given string can be encoded
5537 * into a list element without any kind of quoting, surrounded by braces,
5538 * or using escapes to quote. */
5539 #define JIM_ELESTR_SIMPLE 0
5540 #define JIM_ELESTR_BRACE 1
5541 #define JIM_ELESTR_QUOTE 2
5542 static int ListElementQuotingType(const char *s
, int len
)
5544 int i
, level
, blevel
, trySimple
= 1;
5546 /* Try with the SIMPLE case */
5548 return JIM_ELESTR_BRACE
;
5549 if (s
[0] == '"' || s
[0] == '{') {
5553 for (i
= 0; i
< len
; i
++) {
5573 return JIM_ELESTR_SIMPLE
;
5576 /* Test if it's possible to do with braces */
5577 if (s
[len
- 1] == '\\')
5578 return JIM_ELESTR_QUOTE
;
5581 for (i
= 0; i
< len
; i
++) {
5589 return JIM_ELESTR_QUOTE
;
5598 if (s
[i
+ 1] == '\n')
5599 return JIM_ELESTR_QUOTE
;
5600 else if (s
[i
+ 1] != '\0')
5606 return JIM_ELESTR_QUOTE
;
5611 return JIM_ELESTR_BRACE
;
5612 for (i
= 0; i
< len
; i
++) {
5626 return JIM_ELESTR_BRACE
;
5630 return JIM_ELESTR_SIMPLE
;
5632 return JIM_ELESTR_QUOTE
;
5635 /* Returns the malloc-ed representation of a string
5636 * using backslash to quote special chars. */
5637 static char *BackslashQuoteString(const char *s
, int len
, int *qlenPtr
)
5639 char *q
= Jim_Alloc(len
* 2 + 1), *p
;
5691 static void UpdateStringOfList(struct Jim_Obj
*objPtr
)
5693 int i
, bufLen
, realLength
;
5697 Jim_Obj
**ele
= objPtr
->internalRep
.listValue
.ele
;
5699 /* (Over) Estimate the space needed. */
5700 quotingType
= Jim_Alloc(sizeof(int) * objPtr
->internalRep
.listValue
.len
+ 1);
5702 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5705 strRep
= Jim_GetString(ele
[i
], &len
);
5706 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
5707 switch (quotingType
[i
]) {
5708 case JIM_ELESTR_SIMPLE
:
5709 if (i
!= 0 || strRep
[0] != '#') {
5713 /* Special case '#' on first element needs braces */
5714 quotingType
[i
] = JIM_ELESTR_BRACE
;
5716 case JIM_ELESTR_BRACE
:
5719 case JIM_ELESTR_QUOTE
:
5723 bufLen
++; /* elements separator. */
5727 /* Generate the string rep. */
5728 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
5730 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5734 strRep
= Jim_GetString(ele
[i
], &len
);
5736 switch (quotingType
[i
]) {
5737 case JIM_ELESTR_SIMPLE
:
5738 memcpy(p
, strRep
, len
);
5742 case JIM_ELESTR_BRACE
:
5744 memcpy(p
, strRep
, len
);
5747 realLength
+= len
+ 2;
5749 case JIM_ELESTR_QUOTE
:
5750 q
= BackslashQuoteString(strRep
, len
, &qlen
);
5757 /* Add a separating space */
5758 if (i
+ 1 != objPtr
->internalRep
.listValue
.len
) {
5763 *p
= '\0'; /* nul term. */
5764 objPtr
->length
= realLength
;
5765 Jim_Free(quotingType
);
5768 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
5770 struct JimParserCtx parser
;
5773 Jim_Obj
*fileNameObj
;
5777 /* Optimise dict -> list. XXX: Is it worth it? */
5778 if (Jim_IsDict(objPtr
)) {
5779 Jim_Obj
**listObjPtrPtr
;
5783 Jim_DictPairs(interp
, objPtr
, &listObjPtrPtr
, &len
);
5784 for (i
= 0; i
< len
; i
++) {
5785 Jim_IncrRefCount(listObjPtrPtr
[i
]);
5788 /* Now just switch the internal rep */
5789 Jim_FreeIntRep(interp
, objPtr
);
5790 objPtr
->typePtr
= &listObjType
;
5791 objPtr
->internalRep
.listValue
.len
= len
;
5792 objPtr
->internalRep
.listValue
.maxLen
= len
;
5793 objPtr
->internalRep
.listValue
.ele
= listObjPtrPtr
;
5799 /* Try to preserve information about filename / line number */
5800 if (objPtr
->typePtr
== &sourceObjType
) {
5801 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
5802 linenr
= objPtr
->internalRep
.sourceValue
.lineNumber
;
5805 fileNameObj
= interp
->emptyObj
;
5808 Jim_IncrRefCount(fileNameObj
);
5810 /* Get the string representation */
5811 str
= Jim_GetString(objPtr
, &strLen
);
5813 /* Free the old internal repr just now and initialize the
5814 * new one just now. The string->list conversion can't fail. */
5815 Jim_FreeIntRep(interp
, objPtr
);
5816 objPtr
->typePtr
= &listObjType
;
5817 objPtr
->internalRep
.listValue
.len
= 0;
5818 objPtr
->internalRep
.listValue
.maxLen
= 0;
5819 objPtr
->internalRep
.listValue
.ele
= NULL
;
5821 /* Convert into a list */
5822 JimParserInit(&parser
, str
, strLen
, linenr
);
5823 while (!parser
.eof
) {
5824 Jim_Obj
*elementPtr
;
5826 JimParseList(&parser
);
5827 if (parser
.tt
!= JIM_TT_STR
&& parser
.tt
!= JIM_TT_ESC
)
5829 elementPtr
= JimParserGetTokenObj(interp
, &parser
);
5830 JimSetSourceInfo(interp
, elementPtr
, fileNameObj
, parser
.tline
);
5831 ListAppendElement(objPtr
, elementPtr
);
5833 Jim_DecrRefCount(interp
, fileNameObj
);
5837 Jim_Obj
*Jim_NewListObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
5841 objPtr
= Jim_NewObj(interp
);
5842 objPtr
->typePtr
= &listObjType
;
5843 objPtr
->bytes
= NULL
;
5844 objPtr
->internalRep
.listValue
.ele
= NULL
;
5845 objPtr
->internalRep
.listValue
.len
= 0;
5846 objPtr
->internalRep
.listValue
.maxLen
= 0;
5849 ListInsertElements(objPtr
, 0, len
, elements
);
5855 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5856 * length of the vector. Note that the user of this function should make
5857 * sure that the list object can't shimmer while the vector returned
5858 * is in use, this vector is the one stored inside the internal representation
5859 * of the list object. This function is not exported, extensions should
5860 * always access to the List object elements using Jim_ListIndex(). */
5861 static void JimListGetElements(Jim_Interp
*interp
, Jim_Obj
*listObj
, int *listLen
,
5864 *listLen
= Jim_ListLength(interp
, listObj
);
5865 *listVec
= listObj
->internalRep
.listValue
.ele
;
5868 /* Sorting uses ints, but commands may return wide */
5869 static int JimSign(jim_wide w
)
5880 /* ListSortElements type values */
5894 int (*subfn
)(Jim_Obj
**, Jim_Obj
**);
5897 static struct lsort_info
*sort_info
;
5899 static int ListSortIndexHelper(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5901 Jim_Obj
*lObj
, *rObj
;
5903 if (Jim_ListIndex(sort_info
->interp
, *lhsObj
, sort_info
->index
, &lObj
, JIM_ERRMSG
) != JIM_OK
||
5904 Jim_ListIndex(sort_info
->interp
, *rhsObj
, sort_info
->index
, &rObj
, JIM_ERRMSG
) != JIM_OK
) {
5905 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5907 return sort_info
->subfn(&lObj
, &rObj
);
5910 /* Sort the internal rep of a list. */
5911 static int ListSortString(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5913 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 0) * sort_info
->order
;
5916 static int ListSortStringNoCase(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5918 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 1) * sort_info
->order
;
5921 static int ListSortInteger(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5923 jim_wide lhs
= 0, rhs
= 0;
5925 if (Jim_GetWide(sort_info
->interp
, *lhsObj
, &lhs
) != JIM_OK
||
5926 Jim_GetWide(sort_info
->interp
, *rhsObj
, &rhs
) != JIM_OK
) {
5927 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5930 return JimSign(lhs
- rhs
) * sort_info
->order
;
5933 static int ListSortCommand(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5935 Jim_Obj
*compare_script
;
5940 /* This must be a valid list */
5941 compare_script
= Jim_DuplicateObj(sort_info
->interp
, sort_info
->command
);
5942 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *lhsObj
);
5943 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *rhsObj
);
5945 rc
= Jim_EvalObj(sort_info
->interp
, compare_script
);
5947 if (rc
!= JIM_OK
|| Jim_GetWide(sort_info
->interp
, Jim_GetResult(sort_info
->interp
), &ret
) != JIM_OK
) {
5948 longjmp(sort_info
->jmpbuf
, rc
);
5951 return JimSign(ret
) * sort_info
->order
;
5954 /* Sort a list *in place*. MUST be called with non-shared objects. */
5955 static int ListSortElements(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, struct lsort_info
*info
)
5957 struct lsort_info
*prev_info
;
5959 typedef int (qsort_comparator
) (const void *, const void *);
5960 int (*fn
) (Jim_Obj
**, Jim_Obj
**);
5965 JimPanic((Jim_IsShared(listObjPtr
), "Jim_ListSortElements called with shared object"));
5966 if (!Jim_IsList(listObjPtr
))
5967 SetListFromAny(interp
, listObjPtr
);
5969 /* Allow lsort to be called reentrantly */
5970 prev_info
= sort_info
;
5973 vector
= listObjPtr
->internalRep
.listValue
.ele
;
5974 len
= listObjPtr
->internalRep
.listValue
.len
;
5975 switch (info
->type
) {
5976 case JIM_LSORT_ASCII
:
5977 fn
= ListSortString
;
5979 case JIM_LSORT_NOCASE
:
5980 fn
= ListSortStringNoCase
;
5982 case JIM_LSORT_INTEGER
:
5983 fn
= ListSortInteger
;
5985 case JIM_LSORT_COMMAND
:
5986 fn
= ListSortCommand
;
5989 fn
= NULL
; /* avoid warning */
5990 JimPanic((1, "ListSort called with invalid sort type"));
5993 if (info
->indexed
) {
5994 /* Need to interpose a "list index" function */
5996 fn
= ListSortIndexHelper
;
5999 if ((rc
= setjmp(info
->jmpbuf
)) == 0) {
6000 qsort(vector
, len
, sizeof(Jim_Obj
*), (qsort_comparator
*) fn
);
6002 Jim_InvalidateStringRep(listObjPtr
);
6003 sort_info
= prev_info
;
6008 /* This is the low-level function to insert elements into a list.
6009 * The higher-level Jim_ListInsertElements() performs shared object
6010 * check and invalidate the string repr. This version is used
6011 * in the internals of the List Object and is not exported.
6013 * NOTE: this function can be called only against objects
6014 * with internal type of List.
6016 * An insertion point (idx) of -1 means end-of-list.
6018 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
)
6020 int currentLen
= listPtr
->internalRep
.listValue
.len
;
6021 int requiredLen
= currentLen
+ elemc
;
6025 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
6026 listPtr
->internalRep
.listValue
.maxLen
= requiredLen
* 2;
6028 listPtr
->internalRep
.listValue
.ele
= Jim_Realloc(listPtr
->internalRep
.listValue
.ele
,
6029 sizeof(Jim_Obj
*) * listPtr
->internalRep
.listValue
.maxLen
);
6034 point
= listPtr
->internalRep
.listValue
.ele
+ idx
;
6035 memmove(point
+ elemc
, point
, (currentLen
- idx
) * sizeof(Jim_Obj
*));
6036 for (i
= 0; i
< elemc
; ++i
) {
6037 point
[i
] = elemVec
[i
];
6038 Jim_IncrRefCount(point
[i
]);
6040 listPtr
->internalRep
.listValue
.len
+= elemc
;
6043 /* Convenience call to ListInsertElements() to append a single element.
6045 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6047 ListInsertElements(listPtr
, -1, 1, &objPtr
);
6050 /* Appends every element of appendListPtr into listPtr.
6051 * Both have to be of the list type.
6052 * Convenience call to ListInsertElements()
6054 static void ListAppendList(Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6056 ListInsertElements(listPtr
, -1,
6057 appendListPtr
->internalRep
.listValue
.len
, appendListPtr
->internalRep
.listValue
.ele
);
6060 void Jim_ListAppendElement(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6062 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendElement called with shared object"));
6063 if (!Jim_IsList(listPtr
))
6064 SetListFromAny(interp
, listPtr
);
6065 Jim_InvalidateStringRep(listPtr
);
6066 ListAppendElement(listPtr
, objPtr
);
6069 void Jim_ListAppendList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6071 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendList called with shared object"));
6072 if (!Jim_IsList(listPtr
))
6073 SetListFromAny(interp
, listPtr
);
6074 Jim_InvalidateStringRep(listPtr
);
6075 ListAppendList(listPtr
, appendListPtr
);
6078 int Jim_ListLength(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6080 if (!Jim_IsList(objPtr
))
6081 SetListFromAny(interp
, objPtr
);
6082 return objPtr
->internalRep
.listValue
.len
;
6085 void Jim_ListInsertElements(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6086 int objc
, Jim_Obj
*const *objVec
)
6088 JimPanic((Jim_IsShared(listPtr
), "Jim_ListInsertElement called with shared object"));
6089 if (!Jim_IsList(listPtr
))
6090 SetListFromAny(interp
, listPtr
);
6091 if (idx
>= 0 && idx
> listPtr
->internalRep
.listValue
.len
)
6092 idx
= listPtr
->internalRep
.listValue
.len
;
6095 Jim_InvalidateStringRep(listPtr
);
6096 ListInsertElements(listPtr
, idx
, objc
, objVec
);
6099 int Jim_ListIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
, Jim_Obj
**objPtrPtr
, int flags
)
6101 if (!Jim_IsList(listPtr
))
6102 SetListFromAny(interp
, listPtr
);
6103 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6104 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6105 if (flags
& JIM_ERRMSG
) {
6106 Jim_SetResultString(interp
, "list index out of range", -1);
6112 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6113 *objPtrPtr
= listPtr
->internalRep
.listValue
.ele
[idx
];
6117 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6118 Jim_Obj
*newObjPtr
, int flags
)
6120 if (!Jim_IsList(listPtr
))
6121 SetListFromAny(interp
, listPtr
);
6122 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6123 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6124 if (flags
& JIM_ERRMSG
) {
6125 Jim_SetResultString(interp
, "list index out of range", -1);
6130 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6131 Jim_DecrRefCount(interp
, listPtr
->internalRep
.listValue
.ele
[idx
]);
6132 listPtr
->internalRep
.listValue
.ele
[idx
] = newObjPtr
;
6133 Jim_IncrRefCount(newObjPtr
);
6137 /* Modify the list stored into the variable named 'varNamePtr'
6138 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6139 * with the new element 'newObjptr'. */
6140 int Jim_SetListIndex(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6141 Jim_Obj
*const *indexv
, int indexc
, Jim_Obj
*newObjPtr
)
6143 Jim_Obj
*varObjPtr
, *objPtr
, *listObjPtr
;
6146 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
| JIM_UNSHARED
);
6149 if ((shared
= Jim_IsShared(objPtr
)))
6150 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6151 for (i
= 0; i
< indexc
- 1; i
++) {
6152 listObjPtr
= objPtr
;
6153 if (Jim_GetIndex(interp
, indexv
[i
], &idx
) != JIM_OK
)
6155 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_ERRMSG
) != JIM_OK
) {
6158 if (Jim_IsShared(objPtr
)) {
6159 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6160 ListSetIndex(interp
, listObjPtr
, idx
, objPtr
, JIM_NONE
);
6162 Jim_InvalidateStringRep(listObjPtr
);
6164 if (Jim_GetIndex(interp
, indexv
[indexc
- 1], &idx
) != JIM_OK
)
6166 if (ListSetIndex(interp
, objPtr
, idx
, newObjPtr
, JIM_ERRMSG
) == JIM_ERR
)
6168 Jim_InvalidateStringRep(objPtr
);
6169 Jim_InvalidateStringRep(varObjPtr
);
6170 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
6172 Jim_SetResult(interp
, varObjPtr
);
6176 Jim_FreeNewObj(interp
, varObjPtr
);
6181 Jim_Obj
*Jim_ConcatObj(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
6185 /* If all the objects in objv are lists,
6186 * it's possible to return a list as result, that's the
6187 * concatenation of all the lists. */
6188 for (i
= 0; i
< objc
; i
++) {
6189 if (!Jim_IsList(objv
[i
]))
6193 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
6195 for (i
= 0; i
< objc
; i
++)
6196 ListAppendList(objPtr
, objv
[i
]);
6200 /* Else... we have to glue strings together */
6201 int len
= 0, objLen
;
6204 /* Compute the length */
6205 for (i
= 0; i
< objc
; i
++) {
6206 Jim_GetString(objv
[i
], &objLen
);
6211 /* Create the string rep, and a string object holding it. */
6212 p
= bytes
= Jim_Alloc(len
+ 1);
6213 for (i
= 0; i
< objc
; i
++) {
6214 const char *s
= Jim_GetString(objv
[i
], &objLen
);
6216 /* Remove leading space */
6217 while (objLen
&& (*s
== ' ' || *s
== '\t' || *s
== '\n')) {
6222 /* And trailing space */
6223 while (objLen
&& (s
[objLen
- 1] == ' ' ||
6224 s
[objLen
- 1] == '\n' || s
[objLen
- 1] == '\t')) {
6225 /* Handle trailing backslash-space case */
6226 if (objLen
> 1 && s
[objLen
- 2] == '\\') {
6232 memcpy(p
, s
, objLen
);
6234 if (objLen
&& i
+ 1 != objc
) {
6237 else if (i
+ 1 != objc
) {
6238 /* Drop the space calcuated for this
6239 * element that is instead null. */
6244 return Jim_NewStringObjNoAlloc(interp
, bytes
, len
);
6248 /* Returns a list composed of the elements in the specified range.
6249 * first and start are directly accepted as Jim_Objects and
6250 * processed for the end?-index? case. */
6251 Jim_Obj
*Jim_ListRange(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*firstObjPtr
,
6252 Jim_Obj
*lastObjPtr
)
6257 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
6258 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
6260 len
= Jim_ListLength(interp
, listObjPtr
); /* will convert into list */
6261 first
= JimRelToAbsIndex(len
, first
);
6262 last
= JimRelToAbsIndex(len
, last
);
6263 JimRelToAbsRange(len
, &first
, &last
, &rangeLen
);
6264 if (first
== 0 && last
== len
) {
6267 return Jim_NewListObj(interp
, listObjPtr
->internalRep
.listValue
.ele
+ first
, rangeLen
);
6270 /* -----------------------------------------------------------------------------
6272 * ---------------------------------------------------------------------------*/
6273 static void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6274 static void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
6275 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
);
6276 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6278 /* Dict HashTable Type.
6280 * Keys and Values are Jim objects. */
6282 static unsigned int JimObjectHTHashFunction(const void *key
)
6285 const char *str
= Jim_GetString((Jim_Obj
*)key
, &len
);
6286 return Jim_GenHashFunction((const unsigned char *)str
, len
);
6289 static int JimObjectHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
6291 return Jim_StringEqObj((Jim_Obj
*)key1
, (Jim_Obj
*)key2
);
6294 static void JimObjectHTKeyValDestructor(void *interp
, void *val
)
6296 Jim_DecrRefCount(interp
, (Jim_Obj
*)val
);
6299 static const Jim_HashTableType JimDictHashTableType
= {
6300 JimObjectHTHashFunction
, /* hash function */
6303 JimObjectHTKeyCompare
, /* key compare */
6304 JimObjectHTKeyValDestructor
, /* key destructor */
6305 JimObjectHTKeyValDestructor
/* val destructor */
6308 /* Note that while the elements of the dict may contain references,
6309 * the list object itself can't. This basically means that the
6310 * dict object string representation as a whole can't contain references
6311 * that are not presents in the single elements. */
6312 static const Jim_ObjType dictObjType
= {
6314 FreeDictInternalRep
,
6320 void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6322 JIM_NOTUSED(interp
);
6324 Jim_FreeHashTable(objPtr
->internalRep
.ptr
);
6325 Jim_Free(objPtr
->internalRep
.ptr
);
6328 void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
6330 Jim_HashTable
*ht
, *dupHt
;
6331 Jim_HashTableIterator
*htiter
;
6334 /* Create a new hash table */
6335 ht
= srcPtr
->internalRep
.ptr
;
6336 dupHt
= Jim_Alloc(sizeof(*dupHt
));
6337 Jim_InitHashTable(dupHt
, &JimDictHashTableType
, interp
);
6339 Jim_ExpandHashTable(dupHt
, ht
->size
);
6340 /* Copy every element from the source to the dup hash table */
6341 htiter
= Jim_GetHashTableIterator(ht
);
6342 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6343 const Jim_Obj
*keyObjPtr
= he
->key
;
6344 Jim_Obj
*valObjPtr
= he
->u
.val
;
6346 Jim_IncrRefCount((Jim_Obj
*)keyObjPtr
); /* ATTENTION: const cast */
6347 Jim_IncrRefCount(valObjPtr
);
6348 Jim_AddHashEntry(dupHt
, keyObjPtr
, valObjPtr
);
6350 Jim_FreeHashTableIterator(htiter
);
6352 dupPtr
->internalRep
.ptr
= dupHt
;
6353 dupPtr
->typePtr
= &dictObjType
;
6356 void UpdateStringOfDict(struct Jim_Obj
*objPtr
)
6358 int i
, bufLen
, realLength
;
6361 int *quotingType
, objc
;
6363 Jim_HashTableIterator
*htiter
;
6367 /* Trun the hash table into a flat vector of Jim_Objects. */
6368 ht
= objPtr
->internalRep
.ptr
;
6369 objc
= ht
->used
* 2;
6370 objv
= Jim_Alloc(objc
* sizeof(Jim_Obj
*));
6371 htiter
= Jim_GetHashTableIterator(ht
);
6373 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6374 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6375 objv
[i
++] = he
->u
.val
;
6377 Jim_FreeHashTableIterator(htiter
);
6378 /* (Over) Estimate the space needed. */
6379 quotingType
= Jim_Alloc(sizeof(int) * objc
);
6381 for (i
= 0; i
< objc
; i
++) {
6384 strRep
= Jim_GetString(objv
[i
], &len
);
6385 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
6386 switch (quotingType
[i
]) {
6387 case JIM_ELESTR_SIMPLE
:
6388 if (i
!= 0 || strRep
[0] != '#') {
6392 /* Special case '#' on first element needs braces */
6393 quotingType
[i
] = JIM_ELESTR_BRACE
;
6395 case JIM_ELESTR_BRACE
:
6398 case JIM_ELESTR_QUOTE
:
6402 bufLen
++; /* elements separator. */
6406 /* Generate the string rep. */
6407 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
6409 for (i
= 0; i
< objc
; i
++) {
6413 strRep
= Jim_GetString(objv
[i
], &len
);
6415 switch (quotingType
[i
]) {
6416 case JIM_ELESTR_SIMPLE
:
6417 memcpy(p
, strRep
, len
);
6421 case JIM_ELESTR_BRACE
:
6423 memcpy(p
, strRep
, len
);
6426 realLength
+= len
+ 2;
6428 case JIM_ELESTR_QUOTE
:
6429 q
= BackslashQuoteString(strRep
, len
, &qlen
);
6436 /* Add a separating space */
6437 if (i
+ 1 != objc
) {
6442 *p
= '\0'; /* nul term. */
6443 objPtr
->length
= realLength
;
6444 Jim_Free(quotingType
);
6448 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
6452 if (objPtr
->typePtr
== &dictObjType
) {
6456 /* Get the string representation. Do this first so we don't
6457 * change order in case of fast conversion to dict.
6461 /* For simplicity, convert a non-list object to a list and then to a dict */
6462 listlen
= Jim_ListLength(interp
, objPtr
);
6464 Jim_SetResultString(interp
,
6465 "invalid dictionary value: must be a list with an even number of elements", -1);
6469 /* Now it is easy to convert to a dict from a list, and it can't fail */
6473 ht
= Jim_Alloc(sizeof(*ht
));
6474 Jim_InitHashTable(ht
, &JimDictHashTableType
, interp
);
6476 for (i
= 0; i
< listlen
; i
+= 2) {
6480 Jim_ListIndex(interp
, objPtr
, i
, &keyObjPtr
, JIM_NONE
);
6481 Jim_ListIndex(interp
, objPtr
, i
+ 1, &valObjPtr
, JIM_NONE
);
6483 Jim_IncrRefCount(keyObjPtr
);
6484 Jim_IncrRefCount(valObjPtr
);
6486 if (Jim_AddHashEntry(ht
, keyObjPtr
, valObjPtr
) != JIM_OK
) {
6489 he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6490 Jim_DecrRefCount(interp
, keyObjPtr
);
6491 /* ATTENTION: const cast */
6492 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6493 he
->u
.val
= valObjPtr
;
6497 Jim_FreeIntRep(interp
, objPtr
);
6498 objPtr
->typePtr
= &dictObjType
;
6499 objPtr
->internalRep
.ptr
= ht
;
6505 /* Dict object API */
6507 /* Add an element to a dict. objPtr must be of the "dict" type.
6508 * The higer-level exported function is Jim_DictAddElement().
6509 * If an element with the specified key already exists, the value
6510 * associated is replaced with the new one.
6512 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6513 static int DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6514 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6516 Jim_HashTable
*ht
= objPtr
->internalRep
.ptr
;
6518 if (valueObjPtr
== NULL
) { /* unset */
6519 return Jim_DeleteHashEntry(ht
, keyObjPtr
);
6521 Jim_IncrRefCount(keyObjPtr
);
6522 Jim_IncrRefCount(valueObjPtr
);
6523 if (Jim_ReplaceHashEntry(ht
, keyObjPtr
, valueObjPtr
)) {
6524 /* Value existed, so need to decrement key ref count */
6525 Jim_DecrRefCount(interp
, keyObjPtr
);
6530 /* Add an element, higher-level interface for DictAddElement().
6531 * If valueObjPtr == NULL, the key is removed if it exists. */
6532 int Jim_DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6533 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6537 JimPanic((Jim_IsShared(objPtr
), "Jim_DictAddElement called with shared object"));
6538 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
6541 retcode
= DictAddElement(interp
, objPtr
, keyObjPtr
, valueObjPtr
);
6542 Jim_InvalidateStringRep(objPtr
);
6546 Jim_Obj
*Jim_NewDictObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
6551 JimPanic((len
% 2, "Jim_NewDictObj() 'len' argument must be even"));
6553 objPtr
= Jim_NewObj(interp
);
6554 objPtr
->typePtr
= &dictObjType
;
6555 objPtr
->bytes
= NULL
;
6556 objPtr
->internalRep
.ptr
= Jim_Alloc(sizeof(Jim_HashTable
));
6557 Jim_InitHashTable(objPtr
->internalRep
.ptr
, &JimDictHashTableType
, interp
);
6558 for (i
= 0; i
< len
; i
+= 2)
6559 DictAddElement(interp
, objPtr
, elements
[i
], elements
[i
+ 1]);
6563 /* Return the value associated to the specified dict key
6564 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6566 int Jim_DictKey(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
*keyPtr
,
6567 Jim_Obj
**objPtrPtr
, int flags
)
6572 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
) {
6575 ht
= dictPtr
->internalRep
.ptr
;
6576 if ((he
= Jim_FindHashEntry(ht
, keyPtr
)) == NULL
) {
6577 if (flags
& JIM_ERRMSG
) {
6578 Jim_SetResultFormatted(interp
, "key \"%#s\" not found in dictionary", keyPtr
);
6582 *objPtrPtr
= he
->u
.val
;
6586 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6587 int Jim_DictPairs(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
***objPtrPtr
, int *len
)
6590 Jim_HashTableIterator
*htiter
;
6595 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
) {
6598 ht
= dictPtr
->internalRep
.ptr
;
6600 /* Turn the hash table into a flat vector of Jim_Objects. */
6601 objv
= Jim_Alloc((ht
->used
* 2) * sizeof(Jim_Obj
*));
6602 htiter
= Jim_GetHashTableIterator(ht
);
6604 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6605 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6606 objv
[i
++] = he
->u
.val
;
6609 Jim_FreeHashTableIterator(htiter
);
6615 /* Return the value associated to the specified dict keys */
6616 int Jim_DictKeysVector(Jim_Interp
*interp
, Jim_Obj
*dictPtr
,
6617 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
**objPtrPtr
, int flags
)
6622 *objPtrPtr
= dictPtr
;
6626 for (i
= 0; i
< keyc
; i
++) {
6629 int rc
= Jim_DictKey(interp
, dictPtr
, keyv
[i
], &objPtr
, flags
);
6635 *objPtrPtr
= dictPtr
;
6639 /* Modify the dict stored into the variable named 'varNamePtr'
6640 * setting the element specified by the 'keyc' keys objects in 'keyv',
6641 * with the new value of the element 'newObjPtr'.
6643 * If newObjPtr == NULL the operation is to remove the given key
6644 * from the dictionary.
6646 * If flags & JIM_ERRMSG, then failure to remove the key is considered an error
6647 * and JIM_ERR is returned. Otherwise it is ignored and JIM_OK is returned.
6649 int Jim_SetDictKeysVector(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6650 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*newObjPtr
, int flags
)
6652 Jim_Obj
*varObjPtr
, *objPtr
, *dictObjPtr
;
6655 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, flags
);
6656 if (objPtr
== NULL
) {
6657 if (newObjPtr
== NULL
&& (flags
& JIM_ERRMSG
)) {
6658 /* Cannot remove a key from non existing var */
6661 varObjPtr
= objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6662 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
6663 Jim_FreeNewObj(interp
, varObjPtr
);
6667 if ((shared
= Jim_IsShared(objPtr
)))
6668 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6669 for (i
= 0; i
< keyc
; i
++) {
6670 dictObjPtr
= objPtr
;
6672 /* Check if it's a valid dictionary */
6673 if (SetDictFromAny(interp
, dictObjPtr
) != JIM_OK
) {
6677 if (i
== keyc
- 1) {
6678 /* Last key: Note that error on unset with missing last key is OK */
6679 if (Jim_DictAddElement(interp
, objPtr
, keyv
[keyc
- 1], newObjPtr
) != JIM_OK
) {
6680 if (newObjPtr
|| (flags
& JIM_ERRMSG
)) {
6687 /* Check if the given key exists. */
6688 Jim_InvalidateStringRep(dictObjPtr
);
6689 if (Jim_DictKey(interp
, dictObjPtr
, keyv
[i
], &objPtr
,
6690 newObjPtr
? JIM_NONE
: JIM_ERRMSG
) == JIM_OK
) {
6691 /* This key exists at the current level.
6692 * Make sure it's not shared!. */
6693 if (Jim_IsShared(objPtr
)) {
6694 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6695 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6699 /* Key not found. If it's an [unset] operation
6700 * this is an error. Only the last key may not
6702 if (newObjPtr
== NULL
) {
6705 /* Otherwise set an empty dictionary
6706 * as key's value. */
6707 objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6708 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6711 Jim_InvalidateStringRep(objPtr
);
6712 Jim_InvalidateStringRep(varObjPtr
);
6713 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
) {
6716 Jim_SetResult(interp
, varObjPtr
);
6720 Jim_FreeNewObj(interp
, varObjPtr
);
6725 /* -----------------------------------------------------------------------------
6727 * ---------------------------------------------------------------------------*/
6728 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
);
6729 static int SetIndexFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6731 static const Jim_ObjType indexObjType
= {
6735 UpdateStringOfIndex
,
6739 void UpdateStringOfIndex(struct Jim_Obj
*objPtr
)
6742 char buf
[JIM_INTEGER_SPACE
+ 1];
6744 if (objPtr
->internalRep
.indexValue
>= 0)
6745 len
= sprintf(buf
, "%d", objPtr
->internalRep
.indexValue
);
6746 else if (objPtr
->internalRep
.indexValue
== -1)
6747 len
= sprintf(buf
, "end");
6749 len
= sprintf(buf
, "end%d", objPtr
->internalRep
.indexValue
+ 1);
6751 objPtr
->bytes
= Jim_Alloc(len
+ 1);
6752 memcpy(objPtr
->bytes
, buf
, len
+ 1);
6753 objPtr
->length
= len
;
6756 int SetIndexFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6762 /* Get the string representation */
6763 str
= Jim_String(objPtr
);
6765 /* Try to convert into an index */
6766 if (strncmp(str
, "end", 3) == 0) {
6772 idx
= strtol(str
, &endptr
, 10);
6774 if (endptr
== str
) {
6780 /* Now str may include or +<num> or -<num> */
6781 if (*str
== '+' || *str
== '-') {
6782 int sign
= (*str
== '+' ? 1 : -1);
6784 idx
+= sign
* strtol(++str
, &endptr
, 10);
6785 if (str
== endptr
|| *endptr
) {
6790 /* The only thing left should be spaces */
6791 while (isspace(UCHAR(*str
))) {
6802 /* end-1 is repesented as -2 */
6810 /* Free the old internal repr and set the new one. */
6811 Jim_FreeIntRep(interp
, objPtr
);
6812 objPtr
->typePtr
= &indexObjType
;
6813 objPtr
->internalRep
.indexValue
= idx
;
6817 Jim_SetResultFormatted(interp
,
6818 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr
);
6822 int Jim_GetIndex(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *indexPtr
)
6824 /* Avoid shimmering if the object is an integer. */
6825 if (objPtr
->typePtr
== &intObjType
) {
6826 jim_wide val
= JimWideValue(objPtr
);
6828 if (!(val
< LONG_MIN
) && !(val
> LONG_MAX
)) {
6829 *indexPtr
= (val
< 0) ? -INT_MAX
: (long)val
;;
6833 if (objPtr
->typePtr
!= &indexObjType
&& SetIndexFromAny(interp
, objPtr
) == JIM_ERR
)
6835 *indexPtr
= objPtr
->internalRep
.indexValue
;
6839 /* -----------------------------------------------------------------------------
6840 * Return Code Object.
6841 * ---------------------------------------------------------------------------*/
6843 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6844 static const char * const jimReturnCodes
[] = {
6856 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6858 static int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6860 static const Jim_ObjType returnCodeObjType
= {
6868 /* Converts a (standard) return code to a string. Returns "?" for
6869 * non-standard return codes.
6871 const char *Jim_ReturnCode(int code
)
6873 if (code
< 0 || code
>= (int)jimReturnCodesSize
) {
6877 return jimReturnCodes
[code
];
6881 int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6886 /* Try to convert into an integer */
6887 if (JimGetWideNoErr(interp
, objPtr
, &wideValue
) != JIM_ERR
)
6888 returnCode
= (int)wideValue
;
6889 else if (Jim_GetEnum(interp
, objPtr
, jimReturnCodes
, &returnCode
, NULL
, JIM_NONE
) != JIM_OK
) {
6890 Jim_SetResultFormatted(interp
, "expected return code but got \"%#s\"", objPtr
);
6893 /* Free the old internal repr and set the new one. */
6894 Jim_FreeIntRep(interp
, objPtr
);
6895 objPtr
->typePtr
= &returnCodeObjType
;
6896 objPtr
->internalRep
.returnCode
= returnCode
;
6900 int Jim_GetReturnCode(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *intPtr
)
6902 if (objPtr
->typePtr
!= &returnCodeObjType
&& SetReturnCodeFromAny(interp
, objPtr
) == JIM_ERR
)
6904 *intPtr
= objPtr
->internalRep
.returnCode
;
6908 /* -----------------------------------------------------------------------------
6909 * Expression Parsing
6910 * ---------------------------------------------------------------------------*/
6911 static int JimParseExprOperator(struct JimParserCtx
*pc
);
6912 static int JimParseExprNumber(struct JimParserCtx
*pc
);
6913 static int JimParseExprIrrational(struct JimParserCtx
*pc
);
6915 /* Exrp's Stack machine operators opcodes. */
6917 /* Binary operators (numbers) */
6920 /* Continues on from the JIM_TT_ space */
6922 JIM_EXPROP_MUL
= JIM_TT_EXPR_OP
, /* 20 */
6937 JIM_EXPROP_BITAND
, /* 35 */
6941 /* Note must keep these together */
6942 JIM_EXPROP_LOGICAND
, /* 38 */
6943 JIM_EXPROP_LOGICAND_LEFT
,
6944 JIM_EXPROP_LOGICAND_RIGHT
,
6947 JIM_EXPROP_LOGICOR
, /* 41 */
6948 JIM_EXPROP_LOGICOR_LEFT
,
6949 JIM_EXPROP_LOGICOR_RIGHT
,
6952 /* Ternary operators */
6953 JIM_EXPROP_TERNARY
, /* 44 */
6954 JIM_EXPROP_TERNARY_LEFT
,
6955 JIM_EXPROP_TERNARY_RIGHT
,
6958 JIM_EXPROP_COLON
, /* 47 */
6959 JIM_EXPROP_COLON_LEFT
,
6960 JIM_EXPROP_COLON_RIGHT
,
6962 JIM_EXPROP_POW
, /* 50 */
6964 /* Binary operators (strings) */
6965 JIM_EXPROP_STREQ
, /* 51 */
6970 /* Unary operators (numbers) */
6971 JIM_EXPROP_NOT
, /* 55 */
6973 JIM_EXPROP_UNARYMINUS
,
6974 JIM_EXPROP_UNARYPLUS
,
6977 JIM_EXPROP_FUNC_FIRST
, /* 59 */
6978 JIM_EXPROP_FUNC_INT
= JIM_EXPROP_FUNC_FIRST
,
6979 JIM_EXPROP_FUNC_ABS
,
6980 JIM_EXPROP_FUNC_DOUBLE
,
6981 JIM_EXPROP_FUNC_ROUND
,
6982 JIM_EXPROP_FUNC_RAND
,
6983 JIM_EXPROP_FUNC_SRAND
,
6985 /* math functions from libm */
6986 JIM_EXPROP_FUNC_SIN
, /* 64 */
6987 JIM_EXPROP_FUNC_COS
,
6988 JIM_EXPROP_FUNC_TAN
,
6989 JIM_EXPROP_FUNC_ASIN
,
6990 JIM_EXPROP_FUNC_ACOS
,
6991 JIM_EXPROP_FUNC_ATAN
,
6992 JIM_EXPROP_FUNC_SINH
,
6993 JIM_EXPROP_FUNC_COSH
,
6994 JIM_EXPROP_FUNC_TANH
,
6995 JIM_EXPROP_FUNC_CEIL
,
6996 JIM_EXPROP_FUNC_FLOOR
,
6997 JIM_EXPROP_FUNC_EXP
,
6998 JIM_EXPROP_FUNC_LOG
,
6999 JIM_EXPROP_FUNC_LOG10
,
7000 JIM_EXPROP_FUNC_SQRT
,
7001 JIM_EXPROP_FUNC_POW
,
7012 /* Operators table */
7013 typedef struct Jim_ExprOperator
7018 int (*funcop
) (Jim_Interp
*interp
, struct JimExprState
* e
);
7022 static void ExprPush(struct JimExprState
*e
, Jim_Obj
*obj
)
7024 Jim_IncrRefCount(obj
);
7025 e
->stack
[e
->stacklen
++] = obj
;
7028 static Jim_Obj
*ExprPop(struct JimExprState
*e
)
7030 return e
->stack
[--e
->stacklen
];
7033 static int JimExprOpNumUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7037 Jim_Obj
*A
= ExprPop(e
);
7039 jim_wide wA
, wC
= 0;
7041 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) && JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
) {
7044 switch (e
->opcode
) {
7045 case JIM_EXPROP_FUNC_INT
:
7048 case JIM_EXPROP_FUNC_ROUND
:
7051 case JIM_EXPROP_FUNC_DOUBLE
:
7055 case JIM_EXPROP_FUNC_ABS
:
7056 wC
= wA
>= 0 ? wA
: -wA
;
7058 case JIM_EXPROP_UNARYMINUS
:
7061 case JIM_EXPROP_UNARYPLUS
:
7064 case JIM_EXPROP_NOT
:
7071 else if ((rc
= Jim_GetDouble(interp
, A
, &dA
)) == JIM_OK
) {
7072 switch (e
->opcode
) {
7073 case JIM_EXPROP_FUNC_INT
:
7077 case JIM_EXPROP_FUNC_ROUND
:
7078 wC
= dA
< 0 ? (dA
- 0.5) : (dA
+ 0.5);
7081 case JIM_EXPROP_FUNC_DOUBLE
:
7084 case JIM_EXPROP_FUNC_ABS
:
7085 dC
= dA
>= 0 ? dA
: -dA
;
7087 case JIM_EXPROP_UNARYMINUS
:
7090 case JIM_EXPROP_UNARYPLUS
:
7093 case JIM_EXPROP_NOT
:
7104 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7107 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7111 Jim_DecrRefCount(interp
, A
);
7116 static double JimRandDouble(Jim_Interp
*interp
)
7119 JimRandomBytes(interp
, &x
, sizeof(x
));
7121 return (double)x
/ (unsigned long)~0;
7124 static int JimExprOpIntUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7126 Jim_Obj
*A
= ExprPop(e
);
7129 int rc
= Jim_GetWide(interp
, A
, &wA
);
7131 switch (e
->opcode
) {
7132 case JIM_EXPROP_BITNOT
:
7133 ExprPush(e
, Jim_NewIntObj(interp
, ~wA
));
7135 case JIM_EXPROP_FUNC_SRAND
:
7136 JimPrngSeed(interp
, (unsigned char *)&wA
, sizeof(wA
));
7137 ExprPush(e
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7144 Jim_DecrRefCount(interp
, A
);
7149 static int JimExprOpNone(Jim_Interp
*interp
, struct JimExprState
*e
)
7151 JimPanic((e
->opcode
!= JIM_EXPROP_FUNC_RAND
, "JimExprOpNone only support rand()"));
7153 ExprPush(e
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7158 #ifdef JIM_MATH_FUNCTIONS
7159 static int JimExprOpDoubleUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7162 Jim_Obj
*A
= ExprPop(e
);
7165 rc
= Jim_GetDouble(interp
, A
, &dA
);
7167 switch (e
->opcode
) {
7168 case JIM_EXPROP_FUNC_SIN
:
7171 case JIM_EXPROP_FUNC_COS
:
7174 case JIM_EXPROP_FUNC_TAN
:
7177 case JIM_EXPROP_FUNC_ASIN
:
7180 case JIM_EXPROP_FUNC_ACOS
:
7183 case JIM_EXPROP_FUNC_ATAN
:
7186 case JIM_EXPROP_FUNC_SINH
:
7189 case JIM_EXPROP_FUNC_COSH
:
7192 case JIM_EXPROP_FUNC_TANH
:
7195 case JIM_EXPROP_FUNC_CEIL
:
7198 case JIM_EXPROP_FUNC_FLOOR
:
7201 case JIM_EXPROP_FUNC_EXP
:
7204 case JIM_EXPROP_FUNC_LOG
:
7207 case JIM_EXPROP_FUNC_LOG10
:
7210 case JIM_EXPROP_FUNC_SQRT
:
7216 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7219 Jim_DecrRefCount(interp
, A
);
7225 /* A binary operation on two ints */
7226 static int JimExprOpIntBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7228 Jim_Obj
*B
= ExprPop(e
);
7229 Jim_Obj
*A
= ExprPop(e
);
7233 if (Jim_GetWide(interp
, A
, &wA
) == JIM_OK
&& Jim_GetWide(interp
, B
, &wB
) == JIM_OK
) {
7238 switch (e
->opcode
) {
7239 case JIM_EXPROP_LSHIFT
:
7242 case JIM_EXPROP_RSHIFT
:
7245 case JIM_EXPROP_BITAND
:
7248 case JIM_EXPROP_BITXOR
:
7251 case JIM_EXPROP_BITOR
:
7254 case JIM_EXPROP_MOD
:
7257 Jim_SetResultString(interp
, "Division by zero", -1);
7264 * This code is tricky: C doesn't guarantee much
7265 * about the quotient or remainder, but Tcl does.
7266 * The remainder always has the same sign as the
7267 * divisor and a smaller absolute value.
7285 case JIM_EXPROP_ROTL
:
7286 case JIM_EXPROP_ROTR
:{
7287 /* uint32_t would be better. But not everyone has inttypes.h? */
7288 unsigned long uA
= (unsigned long)wA
;
7289 unsigned long uB
= (unsigned long)wB
;
7290 const unsigned int S
= sizeof(unsigned long) * 8;
7292 /* Shift left by the word size or more is undefined. */
7295 if (e
->opcode
== JIM_EXPROP_ROTR
) {
7298 wC
= (unsigned long)(uA
<< uB
) | (uA
>> (S
- uB
));
7304 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7308 Jim_DecrRefCount(interp
, A
);
7309 Jim_DecrRefCount(interp
, B
);
7315 /* A binary operation on two ints or two doubles (or two strings for some ops) */
7316 static int JimExprOpBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7320 double dA
, dB
, dC
= 0;
7321 jim_wide wA
, wB
, wC
= 0;
7323 Jim_Obj
*B
= ExprPop(e
);
7324 Jim_Obj
*A
= ExprPop(e
);
7326 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) &&
7327 (B
->typePtr
!= &doubleObjType
|| B
->bytes
) &&
7328 JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
&& JimGetWideNoErr(interp
, B
, &wB
) == JIM_OK
) {
7334 switch (e
->opcode
) {
7335 case JIM_EXPROP_POW
:
7336 case JIM_EXPROP_FUNC_POW
:
7337 wC
= JimPowWide(wA
, wB
);
7339 case JIM_EXPROP_ADD
:
7342 case JIM_EXPROP_SUB
:
7345 case JIM_EXPROP_MUL
:
7348 case JIM_EXPROP_DIV
:
7350 Jim_SetResultString(interp
, "Division by zero", -1);
7357 * This code is tricky: C doesn't guarantee much
7358 * about the quotient or remainder, but Tcl does.
7359 * The remainder always has the same sign as the
7360 * divisor and a smaller absolute value.
7378 case JIM_EXPROP_LTE
:
7381 case JIM_EXPROP_GTE
:
7384 case JIM_EXPROP_NUMEQ
:
7387 case JIM_EXPROP_NUMNE
:
7394 else if (Jim_GetDouble(interp
, A
, &dA
) == JIM_OK
&& Jim_GetDouble(interp
, B
, &dB
) == JIM_OK
) {
7395 switch (e
->opcode
) {
7396 case JIM_EXPROP_POW
:
7397 case JIM_EXPROP_FUNC_POW
:
7398 #ifdef JIM_MATH_FUNCTIONS
7401 Jim_SetResultString(interp
, "unsupported", -1);
7405 case JIM_EXPROP_ADD
:
7408 case JIM_EXPROP_SUB
:
7411 case JIM_EXPROP_MUL
:
7414 case JIM_EXPROP_DIV
:
7417 dC
= dA
< 0 ? -INFINITY
: INFINITY
;
7419 dC
= (dA
< 0 ? -1.0 : 1.0) * strtod("Inf", NULL
);
7434 case JIM_EXPROP_LTE
:
7438 case JIM_EXPROP_GTE
:
7442 case JIM_EXPROP_NUMEQ
:
7446 case JIM_EXPROP_NUMNE
:
7455 /* Handle the string case */
7457 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7458 int i
= Jim_StringCompareObj(interp
, A
, B
, 0);
7462 switch (e
->opcode
) {
7469 case JIM_EXPROP_LTE
:
7472 case JIM_EXPROP_GTE
:
7475 case JIM_EXPROP_NUMEQ
:
7478 case JIM_EXPROP_NUMNE
:
7489 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7492 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7496 Jim_DecrRefCount(interp
, A
);
7497 Jim_DecrRefCount(interp
, B
);
7502 static int JimSearchList(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*valObj
)
7507 listlen
= Jim_ListLength(interp
, listObjPtr
);
7508 for (i
= 0; i
< listlen
; i
++) {
7511 Jim_ListIndex(interp
, listObjPtr
, i
, &objPtr
, JIM_NONE
);
7513 if (Jim_StringEqObj(objPtr
, valObj
)) {
7520 static int JimExprOpStrBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7522 Jim_Obj
*B
= ExprPop(e
);
7523 Jim_Obj
*A
= ExprPop(e
);
7527 switch (e
->opcode
) {
7528 case JIM_EXPROP_STREQ
:
7529 case JIM_EXPROP_STRNE
: {
7531 const char *sA
= Jim_GetString(A
, &Alen
);
7532 const char *sB
= Jim_GetString(B
, &Blen
);
7534 if (e
->opcode
== JIM_EXPROP_STREQ
) {
7535 wC
= (Alen
== Blen
&& memcmp(sA
, sB
, Alen
) == 0);
7538 wC
= (Alen
!= Blen
|| memcmp(sA
, sB
, Alen
) != 0);
7542 case JIM_EXPROP_STRIN
:
7543 wC
= JimSearchList(interp
, B
, A
);
7545 case JIM_EXPROP_STRNI
:
7546 wC
= !JimSearchList(interp
, B
, A
);
7551 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7553 Jim_DecrRefCount(interp
, A
);
7554 Jim_DecrRefCount(interp
, B
);
7559 static int ExprBool(Jim_Interp
*interp
, Jim_Obj
*obj
)
7564 if (Jim_GetLong(interp
, obj
, &l
) == JIM_OK
) {
7567 if (Jim_GetDouble(interp
, obj
, &d
) == JIM_OK
) {
7573 static int JimExprOpAndLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7575 Jim_Obj
*skip
= ExprPop(e
);
7576 Jim_Obj
*A
= ExprPop(e
);
7579 switch (ExprBool(interp
, A
)) {
7581 /* false, so skip RHS opcodes with a 0 result */
7582 e
->skip
= JimWideValue(skip
);
7583 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7587 /* true so continue */
7594 Jim_DecrRefCount(interp
, A
);
7595 Jim_DecrRefCount(interp
, skip
);
7600 static int JimExprOpOrLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7602 Jim_Obj
*skip
= ExprPop(e
);
7603 Jim_Obj
*A
= ExprPop(e
);
7606 switch (ExprBool(interp
, A
)) {
7608 /* false, so do nothing */
7612 /* true so skip RHS opcodes with a 1 result */
7613 e
->skip
= JimWideValue(skip
);
7614 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7622 Jim_DecrRefCount(interp
, A
);
7623 Jim_DecrRefCount(interp
, skip
);
7628 static int JimExprOpAndOrRight(Jim_Interp
*interp
, struct JimExprState
*e
)
7630 Jim_Obj
*A
= ExprPop(e
);
7633 switch (ExprBool(interp
, A
)) {
7635 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7639 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7647 Jim_DecrRefCount(interp
, A
);
7652 static int JimExprOpTernaryLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7654 Jim_Obj
*skip
= ExprPop(e
);
7655 Jim_Obj
*A
= ExprPop(e
);
7661 switch (ExprBool(interp
, A
)) {
7663 /* false, skip RHS opcodes */
7664 e
->skip
= JimWideValue(skip
);
7665 /* Push a dummy value */
7666 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7670 /* true so do nothing */
7678 Jim_DecrRefCount(interp
, A
);
7679 Jim_DecrRefCount(interp
, skip
);
7684 static int JimExprOpColonLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7686 Jim_Obj
*skip
= ExprPop(e
);
7687 Jim_Obj
*B
= ExprPop(e
);
7688 Jim_Obj
*A
= ExprPop(e
);
7690 /* No need to check for A as non-boolean */
7691 if (ExprBool(interp
, A
)) {
7692 /* true, so skip RHS opcodes */
7693 e
->skip
= JimWideValue(skip
);
7694 /* Repush B as the answer */
7698 Jim_DecrRefCount(interp
, skip
);
7699 Jim_DecrRefCount(interp
, A
);
7700 Jim_DecrRefCount(interp
, B
);
7704 static int JimExprOpNull(Jim_Interp
*interp
, struct JimExprState
*e
)
7717 /* name - precedence - arity - opcode
7719 * This array *must* be kept in sync with the JIM_EXPROP enum
7721 static const struct Jim_ExprOperator Jim_ExprOperators
[] = {
7722 {"*", 200, 2, JimExprOpBin
, LAZY_NONE
},
7723 {"/", 200, 2, JimExprOpBin
, LAZY_NONE
},
7724 {"%", 200, 2, JimExprOpIntBin
, LAZY_NONE
},
7726 {"-", 100, 2, JimExprOpBin
, LAZY_NONE
},
7727 {"+", 100, 2, JimExprOpBin
, LAZY_NONE
},
7729 {"<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7730 {">>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7732 {"<<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7733 {">>>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7735 {"<", 80, 2, JimExprOpBin
, LAZY_NONE
},
7736 {">", 80, 2, JimExprOpBin
, LAZY_NONE
},
7737 {"<=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7738 {">=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7740 {"==", 70, 2, JimExprOpBin
, LAZY_NONE
},
7741 {"!=", 70, 2, JimExprOpBin
, LAZY_NONE
},
7743 {"&", 50, 2, JimExprOpIntBin
, LAZY_NONE
},
7744 {"^", 49, 2, JimExprOpIntBin
, LAZY_NONE
},
7745 {"|", 48, 2, JimExprOpIntBin
, LAZY_NONE
},
7747 {"&&", 10, 2, NULL
, LAZY_OP
},
7748 {NULL
, 10, 2, JimExprOpAndLeft
, LAZY_LEFT
},
7749 {NULL
, 10, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7751 {"||", 9, 2, NULL
, LAZY_OP
},
7752 {NULL
, 9, 2, JimExprOpOrLeft
, LAZY_LEFT
},
7753 {NULL
, 9, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7755 {"?", 5, 2, JimExprOpNull
, LAZY_OP
},
7756 {NULL
, 5, 2, JimExprOpTernaryLeft
, LAZY_LEFT
},
7757 {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7759 {":", 5, 2, JimExprOpNull
, LAZY_OP
},
7760 {NULL
, 5, 2, JimExprOpColonLeft
, LAZY_LEFT
},
7761 {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7763 {"**", 250, 2, JimExprOpBin
, LAZY_NONE
},
7765 {"eq", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7766 {"ne", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7768 {"in", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7769 {"ni", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7771 {"!", 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7772 {"~", 300, 1, JimExprOpIntUnary
, LAZY_NONE
},
7773 {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7774 {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7778 {"int", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7779 {"abs", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7780 {"double", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7781 {"round", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7782 {"rand", 400, 0, JimExprOpNone
, LAZY_NONE
},
7783 {"srand", 400, 1, JimExprOpIntUnary
, LAZY_NONE
},
7785 #ifdef JIM_MATH_FUNCTIONS
7786 {"sin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7787 {"cos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7788 {"tan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7789 {"asin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7790 {"acos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7791 {"atan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7792 {"sinh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7793 {"cosh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7794 {"tanh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7795 {"ceil", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7796 {"floor", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7797 {"exp", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7798 {"log", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7799 {"log10", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7800 {"sqrt", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7801 {"pow", 400, 2, JimExprOpBin
, LAZY_NONE
},
7805 #define JIM_EXPR_OPERATORS_NUM \
7806 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7808 static int JimParseExpression(struct JimParserCtx
*pc
)
7810 /* Discard spaces and quoted newline */
7811 while (isspace(UCHAR(*pc
->p
)) || (*(pc
->p
) == '\\' && *(pc
->p
+ 1) == '\n')) {
7812 if (*pc
->p
== '\n') {
7820 pc
->tstart
= pc
->tend
= pc
->p
;
7821 pc
->tline
= pc
->linenr
;
7822 pc
->tt
= JIM_TT_EOL
;
7828 pc
->tt
= JIM_TT_SUBEXPR_START
;
7831 pc
->tt
= JIM_TT_SUBEXPR_END
;
7834 pc
->tt
= JIM_TT_SUBEXPR_COMMA
;
7836 pc
->tstart
= pc
->tend
= pc
->p
;
7837 pc
->tline
= pc
->linenr
;
7842 return JimParseCmd(pc
);
7844 if (JimParseVar(pc
) == JIM_ERR
)
7845 return JimParseExprOperator(pc
);
7847 /* Don't allow expr sugar in expressions */
7848 if (pc
->tt
== JIM_TT_EXPRSUGAR
) {
7865 return JimParseExprNumber(pc
);
7867 return JimParseQuote(pc
);
7869 return JimParseBrace(pc
);
7875 if (JimParseExprIrrational(pc
) == JIM_ERR
)
7876 return JimParseExprOperator(pc
);
7879 return JimParseExprOperator(pc
);
7885 static int JimParseExprNumber(struct JimParserCtx
*pc
)
7890 /* Assume an integer for now */
7891 pc
->tt
= JIM_TT_EXPR_INT
;
7893 pc
->tline
= pc
->linenr
;
7894 while (isdigit(UCHAR(*pc
->p
))
7895 || (allowhex
&& isxdigit(UCHAR(*pc
->p
)))
7896 || (allowdot
&& *pc
->p
== '.')
7897 || (pc
->p
- pc
->tstart
== 1 && *pc
->tstart
== '0' && (*pc
->p
== 'x' || *pc
->p
== 'X'))
7899 if ((*pc
->p
== 'x') || (*pc
->p
== 'X')) {
7903 if (*pc
->p
== '.') {
7905 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7909 if (!allowhex
&& (*pc
->p
== 'e' || *pc
->p
== 'E') && (pc
->p
[1] == '-' || pc
->p
[1] == '+'
7910 || isdigit(UCHAR(pc
->p
[1])))) {
7913 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7916 pc
->tend
= pc
->p
- 1;
7920 static int JimParseExprIrrational(struct JimParserCtx
*pc
)
7922 const char *Tokens
[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL
};
7925 for (token
= Tokens
; *token
!= NULL
; token
++) {
7926 int len
= strlen(*token
);
7928 if (strncmp(*token
, pc
->p
, len
) == 0) {
7930 pc
->tend
= pc
->p
+ len
- 1;
7933 pc
->tline
= pc
->linenr
;
7934 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7941 static int JimParseExprOperator(struct JimParserCtx
*pc
)
7944 int bestIdx
= -1, bestLen
= 0;
7946 /* Try to get the longest match. */
7947 for (i
= 0; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++) {
7951 opname
= Jim_ExprOperators
[i
].name
;
7952 if (opname
== NULL
) {
7955 oplen
= strlen(opname
);
7957 if (strncmp(opname
, pc
->p
, oplen
) == 0 && oplen
> bestLen
) {
7958 bestIdx
= i
+ JIM_TT_EXPR_OP
;
7962 if (bestIdx
== -1) {
7966 /* Validate paretheses around function arguments */
7967 if (bestIdx
>= JIM_EXPROP_FUNC_FIRST
) {
7968 const char *p
= pc
->p
+ bestLen
;
7969 int len
= pc
->len
- bestLen
;
7971 while (len
&& isspace(UCHAR(*p
))) {
7980 pc
->tend
= pc
->p
+ bestLen
- 1;
7983 pc
->tline
= pc
->linenr
;
7989 static const struct Jim_ExprOperator
*JimExprOperatorInfoByOpcode(int opcode
)
7991 static Jim_ExprOperator dummy_op
;
7992 if (opcode
< JIM_TT_EXPR_OP
) {
7995 return &Jim_ExprOperators
[opcode
- JIM_TT_EXPR_OP
];
7998 const char *jim_tt_name(int type
)
8000 static const char * const tt_names
[JIM_TT_EXPR_OP
] =
8001 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", ",,,", "INT",
8003 if (type
< JIM_TT_EXPR_OP
) {
8004 return tt_names
[type
];
8007 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(type
);
8008 static char buf
[20];
8013 sprintf(buf
, "(%d)", type
);
8018 /* -----------------------------------------------------------------------------
8020 * ---------------------------------------------------------------------------*/
8021 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
8022 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
8023 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
8025 static const Jim_ObjType exprObjType
= {
8027 FreeExprInternalRep
,
8030 JIM_TYPE_REFERENCES
,
8033 /* Expr bytecode structure */
8034 typedef struct ExprByteCode
8036 int len
; /* Length as number of tokens. */
8037 ScriptToken
*token
; /* Tokens array. */
8038 int inUse
; /* Used for sharing. */
8041 static void ExprFreeByteCode(Jim_Interp
*interp
, ExprByteCode
* expr
)
8045 for (i
= 0; i
< expr
->len
; i
++) {
8046 Jim_DecrRefCount(interp
, expr
->token
[i
].objPtr
);
8048 Jim_Free(expr
->token
);
8052 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8054 ExprByteCode
*expr
= (void *)objPtr
->internalRep
.ptr
;
8057 if (--expr
->inUse
!= 0) {
8061 ExprFreeByteCode(interp
, expr
);
8065 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8067 JIM_NOTUSED(interp
);
8068 JIM_NOTUSED(srcPtr
);
8070 /* Just returns an simple string. */
8071 dupPtr
->typePtr
= NULL
;
8074 /* Check if an expr program looks correct. */
8075 static int ExprCheckCorrectness(ExprByteCode
* expr
)
8081 /* Try to check if there are stack underflows,
8082 * and make sure at the end of the program there is
8083 * a single result on the stack. */
8084 for (i
= 0; i
< expr
->len
; i
++) {
8085 ScriptToken
*t
= &expr
->token
[i
];
8086 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8088 stacklen
-= op
->arity
;
8092 if (t
->type
== JIM_EXPROP_TERNARY
|| t
->type
== JIM_EXPROP_TERNARY_LEFT
) {
8095 else if (t
->type
== JIM_EXPROP_COLON
|| t
->type
== JIM_EXPROP_COLON_LEFT
) {
8099 /* All operations and operands add one to the stack */
8102 if (stacklen
!= 1 || ternary
!= 0) {
8108 /* This procedure converts every occurrence of || and && opereators
8109 * in lazy unary versions.
8111 * a b || is converted into:
8113 * a <offset> |L b |R
8115 * a b && is converted into:
8117 * a <offset> &L b &R
8119 * "|L" checks if 'a' is true:
8120 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8121 * the opcode just after |R.
8122 * 2) if it is false does nothing.
8123 * "|R" checks if 'b' is true:
8124 * 1) if it is true pushes 1, otherwise pushes 0.
8126 * "&L" checks if 'a' is true:
8127 * 1) if it is true does nothing.
8128 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8129 * the opcode just after &R
8130 * "&R" checks if 'a' is true:
8131 * if it is true pushes 1, otherwise pushes 0.
8133 static int ExprAddLazyOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8137 int leftindex
, arity
, offset
;
8139 /* Search for the end of the first operator */
8140 leftindex
= expr
->len
- 1;
8144 ScriptToken
*tt
= &expr
->token
[leftindex
];
8146 if (tt
->type
>= JIM_TT_EXPR_OP
) {
8147 arity
+= JimExprOperatorInfoByOpcode(tt
->type
)->arity
;
8150 if (--leftindex
< 0) {
8157 memmove(&expr
->token
[leftindex
+ 2], &expr
->token
[leftindex
],
8158 sizeof(*expr
->token
) * (expr
->len
- leftindex
));
8160 offset
= (expr
->len
- leftindex
) - 1;
8162 /* Now we rely on the fact the the left and right version have opcodes
8163 * 1 and 2 after the main opcode respectively
8165 expr
->token
[leftindex
+ 1].type
= t
->type
+ 1;
8166 expr
->token
[leftindex
+ 1].objPtr
= interp
->emptyObj
;
8168 expr
->token
[leftindex
].type
= JIM_TT_EXPR_INT
;
8169 expr
->token
[leftindex
].objPtr
= Jim_NewIntObj(interp
, offset
);
8171 /* Now add the 'R' operator */
8172 expr
->token
[expr
->len
].objPtr
= interp
->emptyObj
;
8173 expr
->token
[expr
->len
].type
= t
->type
+ 2;
8176 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8177 for (i
= leftindex
- 1; i
> 0; i
--) {
8178 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(expr
->token
[i
].type
);
8179 if (op
->lazy
== LAZY_LEFT
) {
8180 if (JimWideValue(expr
->token
[i
- 1].objPtr
) + i
- 1 >= leftindex
) {
8181 JimWideValue(expr
->token
[i
- 1].objPtr
) += 2;
8188 static int ExprAddOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8190 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8191 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8193 if (op
->lazy
== LAZY_OP
) {
8194 if (ExprAddLazyOperator(interp
, expr
, t
) != JIM_OK
) {
8195 Jim_SetResultFormatted(interp
, "Expression has bad operands to %s", op
->name
);
8200 token
->objPtr
= interp
->emptyObj
;
8201 token
->type
= t
->type
;
8208 * Returns the index of the COLON_LEFT to the left of 'right_index'
8209 * taking into account nesting.
8211 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8213 static int ExprTernaryGetColonLeftIndex(ExprByteCode
*expr
, int right_index
)
8215 int ternary_count
= 1;
8219 while (right_index
> 1) {
8220 if (expr
->token
[right_index
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8223 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_RIGHT
) {
8226 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_LEFT
&& ternary_count
== 1) {
8237 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8239 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8240 * Otherwise returns 0.
8242 static int ExprTernaryGetMoveIndices(ExprByteCode
*expr
, int right_index
, int *prev_right_index
, int *prev_left_index
)
8244 int i
= right_index
- 1;
8245 int ternary_count
= 1;
8248 if (expr
->token
[i
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8249 if (--ternary_count
== 0 && expr
->token
[i
- 2].type
== JIM_EXPROP_COLON_RIGHT
) {
8250 *prev_right_index
= i
- 2;
8251 *prev_left_index
= ExprTernaryGetColonLeftIndex(expr
, *prev_right_index
);
8255 else if (expr
->token
[i
].type
== JIM_EXPROP_COLON_RIGHT
) {
8256 if (ternary_count
== 0) {
8267 * ExprTernaryReorderExpression description
8268 * ========================================
8270 * ?: is right-to-left associative which doesn't work with the stack-based
8271 * expression engine. The fix is to reorder the bytecode.
8277 * Has initial bytecode:
8279 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8280 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8282 * The fix involves simulating this expression instead:
8286 * With the following bytecode:
8288 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8289 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8291 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8292 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8293 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8294 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8296 * ExprTernaryReorderExpression works thus as follows :
8297 * - start from the end of the stack
8298 * - while walking towards the beginning of the stack
8299 * if token=JIM_EXPROP_COLON_RIGHT then
8300 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8301 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8302 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8304 * perform the rotation
8305 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8309 * Note: care has to be taken for nested ternary constructs!!!
8311 static void ExprTernaryReorderExpression(Jim_Interp
*interp
, ExprByteCode
*expr
)
8315 for (i
= expr
->len
- 1; i
> 1; i
--) {
8316 int prev_right_index
;
8317 int prev_left_index
;
8321 if (expr
->token
[i
].type
!= JIM_EXPROP_COLON_RIGHT
) {
8325 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8326 if (ExprTernaryGetMoveIndices(expr
, i
, &prev_right_index
, &prev_left_index
) == 0) {
8331 ** rotate tokens down
8333 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8342 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8344 tmp
= expr
->token
[prev_right_index
];
8345 for (j
= prev_right_index
; j
< i
; j
++) {
8346 expr
->token
[j
] = expr
->token
[j
+ 1];
8348 expr
->token
[i
] = tmp
;
8350 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8352 * This is 'colon left increment' = i - prev_right_index
8354 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8355 * [prev_left_index-1] : skip_count
8358 JimWideValue(expr
->token
[prev_left_index
-1].objPtr
) += (i
- prev_right_index
);
8360 /* Adjust for i-- in the loop */
8365 static ExprByteCode
*ExprCreateByteCode(Jim_Interp
*interp
, const ParseTokenList
*tokenlist
, Jim_Obj
*fileNameObj
)
8371 int prevtt
= JIM_TT_NONE
;
8372 int have_ternary
= 0;
8375 int count
= tokenlist
->count
- 1;
8377 expr
= Jim_Alloc(sizeof(*expr
));
8381 Jim_InitStack(&stack
);
8383 /* Need extra bytecodes for lazy operators.
8384 * Also check for the ternary operator
8386 for (i
= 0; i
< tokenlist
->count
; i
++) {
8387 ParseToken
*t
= &tokenlist
->list
[i
];
8388 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8390 if (op
->lazy
== LAZY_OP
) {
8392 /* Ternary is a lazy op but also needs reordering */
8393 if (t
->type
== JIM_EXPROP_TERNARY
) {
8399 expr
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
8401 for (i
= 0; i
< tokenlist
->count
&& ok
; i
++) {
8402 ParseToken
*t
= &tokenlist
->list
[i
];
8404 /* Next token will be stored here */
8405 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8407 if (t
->type
== JIM_TT_EOL
) {
8415 case JIM_TT_DICTSUGAR
:
8416 case JIM_TT_EXPRSUGAR
:
8418 token
->objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
8419 token
->type
= t
->type
;
8420 if (t
->type
== JIM_TT_CMD
) {
8421 /* Only commands need source info */
8422 JimSetSourceInfo(interp
, token
->objPtr
, fileNameObj
, t
->line
);
8427 case JIM_TT_EXPR_INT
:
8428 token
->objPtr
= Jim_NewIntObj(interp
, strtoull(t
->token
, NULL
, 0));
8429 token
->type
= t
->type
;
8433 case JIM_TT_EXPR_DOUBLE
:
8434 token
->objPtr
= Jim_NewDoubleObj(interp
, strtod(t
->token
, NULL
));
8435 token
->type
= t
->type
;
8439 case JIM_TT_SUBEXPR_START
:
8440 Jim_StackPush(&stack
, t
);
8441 prevtt
= JIM_TT_NONE
;
8444 case JIM_TT_SUBEXPR_COMMA
:
8445 /* Simple approach. Comma is simply ignored */
8448 case JIM_TT_SUBEXPR_END
:
8450 while (Jim_StackLen(&stack
)) {
8451 ParseToken
*tt
= Jim_StackPop(&stack
);
8453 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8458 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8463 Jim_SetResultString(interp
, "Unexpected close parenthesis", -1);
8470 /* Must be an operator */
8471 const struct Jim_ExprOperator
*op
;
8474 /* Convert -/+ to unary minus or unary plus if necessary */
8475 if (prevtt
== JIM_TT_NONE
|| prevtt
>= JIM_TT_EXPR_OP
) {
8476 if (t
->type
== JIM_EXPROP_SUB
) {
8477 t
->type
= JIM_EXPROP_UNARYMINUS
;
8479 else if (t
->type
== JIM_EXPROP_ADD
) {
8480 t
->type
= JIM_EXPROP_UNARYPLUS
;
8484 op
= JimExprOperatorInfoByOpcode(t
->type
);
8486 /* Now handle precedence */
8487 while ((tt
= Jim_StackPeek(&stack
)) != NULL
) {
8488 const struct Jim_ExprOperator
*tt_op
=
8489 JimExprOperatorInfoByOpcode(tt
->type
);
8491 /* Note that right-to-left associativity of ?: operator is handled later */
8493 if (op
->arity
!= 1 && tt_op
->precedence
>= op
->precedence
) {
8494 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8498 Jim_StackPop(&stack
);
8504 Jim_StackPush(&stack
, t
);
8511 /* Reduce any remaining subexpr */
8512 while (Jim_StackLen(&stack
)) {
8513 ParseToken
*tt
= Jim_StackPop(&stack
);
8515 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8517 Jim_SetResultString(interp
, "Missing close parenthesis", -1);
8520 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8527 ExprTernaryReorderExpression(interp
, expr
);
8531 /* Free the stack used for the compilation. */
8532 Jim_FreeStack(&stack
);
8534 for (i
= 0; i
< expr
->len
; i
++) {
8535 Jim_IncrRefCount(expr
->token
[i
].objPtr
);
8539 ExprFreeByteCode(interp
, expr
);
8547 /* This method takes the string representation of an expression
8548 * and generates a program for the Expr's stack-based VM. */
8549 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
8552 const char *exprText
;
8553 struct JimParserCtx parser
;
8554 struct ExprByteCode
*expr
;
8555 ParseTokenList tokenlist
;
8557 Jim_Obj
*fileNameObj
;
8560 /* Try to get information about filename / line number */
8561 if (objPtr
->typePtr
== &sourceObjType
) {
8562 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
8563 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
8566 fileNameObj
= interp
->emptyObj
;
8569 Jim_IncrRefCount(fileNameObj
);
8571 exprText
= Jim_GetString(objPtr
, &exprTextLen
);
8573 /* Initially tokenise the expression into tokenlist */
8574 ScriptTokenListInit(&tokenlist
);
8576 JimParserInit(&parser
, exprText
, exprTextLen
, line
);
8577 while (!parser
.eof
) {
8578 if (JimParseExpression(&parser
) != JIM_OK
) {
8579 ScriptTokenListFree(&tokenlist
);
8581 Jim_SetResultFormatted(interp
, "syntax error in expression: \"%#s\"", objPtr
);
8586 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
8590 #ifdef DEBUG_SHOW_EXPR_TOKENS
8593 printf("==== Expr Tokens ====\n");
8594 for (i
= 0; i
< tokenlist
.count
; i
++) {
8595 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
.list
[i
].line
, jim_tt_name(tokenlist
.list
[i
].type
),
8596 tokenlist
.list
[i
].len
, tokenlist
.list
[i
].token
);
8601 /* Now create the expression bytecode from the tokenlist */
8602 expr
= ExprCreateByteCode(interp
, &tokenlist
, fileNameObj
);
8604 /* No longer need the token list */
8605 ScriptTokenListFree(&tokenlist
);
8611 #ifdef DEBUG_SHOW_EXPR
8615 printf("==== Expr ====\n");
8616 for (i
= 0; i
< expr
->len
; i
++) {
8617 ScriptToken
*t
= &expr
->token
[i
];
8619 printf("[%2d] %s '%s'\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
8624 /* Check program correctness. */
8625 if (ExprCheckCorrectness(expr
) != JIM_OK
) {
8626 ExprFreeByteCode(interp
, expr
);
8633 /* Free the old internal rep and set the new one. */
8634 Jim_DecrRefCount(interp
, fileNameObj
);
8635 Jim_FreeIntRep(interp
, objPtr
);
8636 Jim_SetIntRepPtr(objPtr
, expr
);
8637 objPtr
->typePtr
= &exprObjType
;
8641 static ExprByteCode
*JimGetExpression(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8643 if (objPtr
->typePtr
!= &exprObjType
) {
8644 if (SetExprFromAny(interp
, objPtr
) != JIM_OK
) {
8648 return (ExprByteCode
*) Jim_GetIntRepPtr(objPtr
);
8651 /* -----------------------------------------------------------------------------
8652 * Expressions evaluation.
8653 * Jim uses a specialized stack-based virtual machine for expressions,
8654 * that takes advantage of the fact that expr's operators
8655 * can't be redefined.
8657 * Jim_EvalExpression() uses the bytecode compiled by
8658 * SetExprFromAny() method of the "expression" object.
8660 * On success a Tcl Object containing the result of the evaluation
8661 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8663 * On error the function returns a retcode != to JIM_OK and set a suitable
8664 * error on the interp.
8665 * ---------------------------------------------------------------------------*/
8666 #define JIM_EE_STATICSTACK_LEN 10
8668 int Jim_EvalExpression(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, Jim_Obj
**exprResultPtrPtr
)
8671 Jim_Obj
*staticStack
[JIM_EE_STATICSTACK_LEN
];
8673 int retcode
= JIM_OK
;
8674 struct JimExprState e
;
8676 expr
= JimGetExpression(interp
, exprObjPtr
);
8678 return JIM_ERR
; /* error in expression. */
8681 #ifdef JIM_OPTIMIZATION
8682 /* Check for one of the following common expressions used by while/for
8687 * $a < CONST, $a < $b
8688 * $a <= CONST, $a <= $b
8689 * $a > CONST, $a > $b
8690 * $a >= CONST, $a >= $b
8691 * $a != CONST, $a != $b
8692 * $a == CONST, $a == $b
8697 /* STEP 1 -- Check if there are the conditions to run the specialized
8698 * version of while */
8700 switch (expr
->len
) {
8702 if (expr
->token
[0].type
== JIM_TT_EXPR_INT
) {
8703 *exprResultPtrPtr
= expr
->token
[0].objPtr
;
8704 Jim_IncrRefCount(*exprResultPtrPtr
);
8707 if (expr
->token
[0].type
== JIM_TT_VAR
) {
8708 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_ERRMSG
);
8710 *exprResultPtrPtr
= objPtr
;
8711 Jim_IncrRefCount(*exprResultPtrPtr
);
8718 if (expr
->token
[1].type
== JIM_EXPROP_NOT
&& expr
->token
[0].type
== JIM_TT_VAR
) {
8721 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8722 if (objPtr
&& JimIsWide(objPtr
)
8723 && Jim_GetWide(interp
, objPtr
, &wideValue
) == JIM_OK
) {
8724 *exprResultPtrPtr
= wideValue
? interp
->falseObj
: interp
->trueObj
;
8725 Jim_IncrRefCount(*exprResultPtrPtr
);
8732 if (expr
->token
[0].type
== JIM_TT_VAR
&& (expr
->token
[1].type
== JIM_TT_EXPR_INT
8733 || expr
->token
[1].type
== JIM_TT_VAR
)) {
8734 switch (expr
->token
[2].type
) {
8736 case JIM_EXPROP_LTE
:
8738 case JIM_EXPROP_GTE
:
8739 case JIM_EXPROP_NUMEQ
:
8740 case JIM_EXPROP_NUMNE
:{
8742 jim_wide wideValueA
;
8743 jim_wide wideValueB
;
8745 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8746 if (objPtr
&& JimIsWide(objPtr
)
8747 && Jim_GetWide(interp
, objPtr
, &wideValueA
) == JIM_OK
) {
8748 if (expr
->token
[1].type
== JIM_TT_VAR
) {
8750 Jim_GetVariable(interp
, expr
->token
[1].objPtr
,
8754 objPtr
= expr
->token
[1].objPtr
;
8756 if (objPtr
&& JimIsWide(objPtr
)
8757 && Jim_GetWide(interp
, objPtr
, &wideValueB
) == JIM_OK
) {
8760 switch (expr
->token
[2].type
) {
8762 cmpRes
= wideValueA
< wideValueB
;
8764 case JIM_EXPROP_LTE
:
8765 cmpRes
= wideValueA
<= wideValueB
;
8768 cmpRes
= wideValueA
> wideValueB
;
8770 case JIM_EXPROP_GTE
:
8771 cmpRes
= wideValueA
>= wideValueB
;
8773 case JIM_EXPROP_NUMEQ
:
8774 cmpRes
= wideValueA
== wideValueB
;
8776 case JIM_EXPROP_NUMNE
:
8777 cmpRes
= wideValueA
!= wideValueB
;
8779 default: /*notreached */
8783 cmpRes
? interp
->trueObj
: interp
->falseObj
;
8784 Jim_IncrRefCount(*exprResultPtrPtr
);
8796 /* In order to avoid that the internal repr gets freed due to
8797 * shimmering of the exprObjPtr's object, we make the internal rep
8801 /* The stack-based expr VM itself */
8803 /* Stack allocation. Expr programs have the feature that
8804 * a program of length N can't require a stack longer than
8806 if (expr
->len
> JIM_EE_STATICSTACK_LEN
)
8807 e
.stack
= Jim_Alloc(sizeof(Jim_Obj
*) * expr
->len
);
8809 e
.stack
= staticStack
;
8813 /* Execute every instruction */
8814 for (i
= 0; i
< expr
->len
&& retcode
== JIM_OK
; i
++) {
8817 switch (expr
->token
[i
].type
) {
8818 case JIM_TT_EXPR_INT
:
8819 case JIM_TT_EXPR_DOUBLE
:
8821 ExprPush(&e
, expr
->token
[i
].objPtr
);
8825 objPtr
= Jim_GetVariable(interp
, expr
->token
[i
].objPtr
, JIM_ERRMSG
);
8827 ExprPush(&e
, objPtr
);
8834 case JIM_TT_DICTSUGAR
:
8835 objPtr
= JimExpandDictSugar(interp
, expr
->token
[i
].objPtr
);
8837 ExprPush(&e
, objPtr
);
8845 retcode
= Jim_SubstObj(interp
, expr
->token
[i
].objPtr
, &objPtr
, JIM_NONE
);
8846 if (retcode
== JIM_OK
) {
8847 ExprPush(&e
, objPtr
);
8852 retcode
= Jim_EvalObj(interp
, expr
->token
[i
].objPtr
);
8853 if (retcode
== JIM_OK
) {
8854 ExprPush(&e
, Jim_GetResult(interp
));
8859 /* Find and execute the operation */
8861 e
.opcode
= expr
->token
[i
].type
;
8863 retcode
= JimExprOperatorInfoByOpcode(e
.opcode
)->funcop(interp
, &e
);
8864 /* Skip some opcodes if necessary */
8873 if (retcode
== JIM_OK
) {
8874 *exprResultPtrPtr
= ExprPop(&e
);
8877 for (i
= 0; i
< e
.stacklen
; i
++) {
8878 Jim_DecrRefCount(interp
, e
.stack
[i
]);
8881 if (e
.stack
!= staticStack
) {
8887 int Jim_GetBoolFromExpr(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, int *boolPtr
)
8892 Jim_Obj
*exprResultPtr
;
8894 retcode
= Jim_EvalExpression(interp
, exprObjPtr
, &exprResultPtr
);
8895 if (retcode
!= JIM_OK
)
8898 if (JimGetWideNoErr(interp
, exprResultPtr
, &wideValue
) != JIM_OK
) {
8899 if (Jim_GetDouble(interp
, exprResultPtr
, &doubleValue
) != JIM_OK
) {
8900 Jim_DecrRefCount(interp
, exprResultPtr
);
8904 Jim_DecrRefCount(interp
, exprResultPtr
);
8905 *boolPtr
= doubleValue
!= 0;
8909 *boolPtr
= wideValue
!= 0;
8911 Jim_DecrRefCount(interp
, exprResultPtr
);
8915 /* -----------------------------------------------------------------------------
8916 * ScanFormat String Object
8917 * ---------------------------------------------------------------------------*/
8919 /* This Jim_Obj will held a parsed representation of a format string passed to
8920 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8921 * to be parsed in its entirely first and then, if correct, can be used for
8922 * scanning. To avoid endless re-parsing, the parsed representation will be
8923 * stored in an internal representation and re-used for performance reason. */
8925 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8926 * scanformat string. This part will later be used to extract information
8927 * out from the string to be parsed by Jim_ScanString */
8929 typedef struct ScanFmtPartDescr
8931 char type
; /* Type of conversion (e.g. c, d, f) */
8932 char modifier
; /* Modify type (e.g. l - long, h - short */
8933 size_t width
; /* Maximal width of input to be converted */
8934 int pos
; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8935 char *arg
; /* Specification of a CHARSET conversion */
8936 char *prefix
; /* Prefix to be scanned literally before conversion */
8939 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8940 * string parsed and separated in part descriptions. Furthermore it contains
8941 * the original string representation of the scanformat string to allow for
8942 * fast update of the Jim_Obj's string representation part.
8944 * As an add-on the internal object representation adds some scratch pad area
8945 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8946 * memory for purpose of string scanning.
8948 * The error member points to a static allocated string in case of a mal-
8949 * formed scanformat string or it contains '0' (NULL) in case of a valid
8950 * parse representation.
8952 * The whole memory of the internal representation is allocated as a single
8953 * area of memory that will be internally separated. So freeing and duplicating
8954 * of such an object is cheap */
8956 typedef struct ScanFmtStringObj
8958 jim_wide size
; /* Size of internal repr in bytes */
8959 char *stringRep
; /* Original string representation */
8960 size_t count
; /* Number of ScanFmtPartDescr contained */
8961 size_t convCount
; /* Number of conversions that will assign */
8962 size_t maxPos
; /* Max position index if XPG3 is used */
8963 const char *error
; /* Ptr to error text (NULL if no error */
8964 char *scratch
; /* Some scratch pad used by Jim_ScanString */
8965 ScanFmtPartDescr descr
[1]; /* The vector of partial descriptions */
8969 static void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
8970 static void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
8971 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
);
8973 static const Jim_ObjType scanFmtStringObjType
= {
8975 FreeScanFmtInternalRep
,
8976 DupScanFmtInternalRep
,
8977 UpdateStringOfScanFmt
,
8981 void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8983 JIM_NOTUSED(interp
);
8984 Jim_Free((char *)objPtr
->internalRep
.ptr
);
8985 objPtr
->internalRep
.ptr
= 0;
8988 void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8990 size_t size
= (size_t) ((ScanFmtStringObj
*) srcPtr
->internalRep
.ptr
)->size
;
8991 ScanFmtStringObj
*newVec
= (ScanFmtStringObj
*) Jim_Alloc(size
);
8993 JIM_NOTUSED(interp
);
8994 memcpy(newVec
, srcPtr
->internalRep
.ptr
, size
);
8995 dupPtr
->internalRep
.ptr
= newVec
;
8996 dupPtr
->typePtr
= &scanFmtStringObjType
;
8999 void UpdateStringOfScanFmt(Jim_Obj
*objPtr
)
9001 char *bytes
= ((ScanFmtStringObj
*) objPtr
->internalRep
.ptr
)->stringRep
;
9003 objPtr
->bytes
= Jim_StrDup(bytes
);
9004 objPtr
->length
= strlen(bytes
);
9007 /* SetScanFmtFromAny will parse a given string and create the internal
9008 * representation of the format specification. In case of an error
9009 * the error data member of the internal representation will be set
9010 * to an descriptive error text and the function will be left with
9011 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
9014 static int SetScanFmtFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
9016 ScanFmtStringObj
*fmtObj
;
9018 int maxCount
, i
, approxSize
, lastPos
= -1;
9019 const char *fmt
= objPtr
->bytes
;
9020 int maxFmtLen
= objPtr
->length
;
9021 const char *fmtEnd
= fmt
+ maxFmtLen
;
9024 Jim_FreeIntRep(interp
, objPtr
);
9025 /* Count how many conversions could take place maximally */
9026 for (i
= 0, maxCount
= 0; i
< maxFmtLen
; ++i
)
9029 /* Calculate an approximation of the memory necessary */
9030 approxSize
= sizeof(ScanFmtStringObj
) /* Size of the container */
9031 +(maxCount
+ 1) * sizeof(ScanFmtPartDescr
) /* Size of all partials */
9032 +maxFmtLen
* sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
9033 + maxFmtLen
* sizeof(char) + 1 /* Original stringrep */
9034 + maxFmtLen
* sizeof(char) /* Arg for CHARSETs */
9035 +(maxCount
+ 1) * sizeof(char) /* '\0' for every partial */
9036 +1; /* safety byte */
9037 fmtObj
= (ScanFmtStringObj
*) Jim_Alloc(approxSize
);
9038 memset(fmtObj
, 0, approxSize
);
9039 fmtObj
->size
= approxSize
;
9041 fmtObj
->scratch
= (char *)&fmtObj
->descr
[maxCount
+ 1];
9042 fmtObj
->stringRep
= fmtObj
->scratch
+ maxFmtLen
+ 3 + 1;
9043 memcpy(fmtObj
->stringRep
, fmt
, maxFmtLen
);
9044 buffer
= fmtObj
->stringRep
+ maxFmtLen
+ 1;
9045 objPtr
->internalRep
.ptr
= fmtObj
;
9046 objPtr
->typePtr
= &scanFmtStringObjType
;
9047 for (i
= 0, curr
= 0; fmt
< fmtEnd
; ++fmt
) {
9048 int width
= 0, skip
;
9049 ScanFmtPartDescr
*descr
= &fmtObj
->descr
[curr
];
9052 descr
->width
= 0; /* Assume width unspecified */
9053 /* Overread and store any "literal" prefix */
9054 if (*fmt
!= '%' || fmt
[1] == '%') {
9056 descr
->prefix
= &buffer
[i
];
9057 for (; fmt
< fmtEnd
; ++fmt
) {
9067 /* Skip the conversion introducing '%' sign */
9069 /* End reached due to non-conversion literal only? */
9072 descr
->pos
= 0; /* Assume "natural" positioning */
9074 descr
->pos
= -1; /* Okay, conversion will not be assigned */
9078 fmtObj
->convCount
++; /* Otherwise count as assign-conversion */
9079 /* Check if next token is a number (could be width or pos */
9080 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9082 /* Was the number a XPG3 position specifier? */
9083 if (descr
->pos
!= -1 && *fmt
== '$') {
9089 /* Look if "natural" postioning and XPG3 one was mixed */
9090 if ((lastPos
== 0 && descr
->pos
> 0)
9091 || (lastPos
> 0 && descr
->pos
== 0)) {
9092 fmtObj
->error
= "cannot mix \"%\" and \"%n$\" conversion specifiers";
9095 /* Look if this position was already used */
9096 for (prev
= 0; prev
< curr
; ++prev
) {
9097 if (fmtObj
->descr
[prev
].pos
== -1)
9099 if (fmtObj
->descr
[prev
].pos
== descr
->pos
) {
9101 "variable is assigned by multiple \"%n$\" conversion specifiers";
9105 /* Try to find a width after the XPG3 specifier */
9106 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9107 descr
->width
= width
;
9110 if (descr
->pos
> 0 && (size_t) descr
->pos
> fmtObj
->maxPos
)
9111 fmtObj
->maxPos
= descr
->pos
;
9114 /* Number was not a XPG3, so it has to be a width */
9115 descr
->width
= width
;
9118 /* If positioning mode was undetermined yet, fix this */
9120 lastPos
= descr
->pos
;
9121 /* Handle CHARSET conversion type ... */
9123 int swapped
= 1, beg
= i
, end
, j
;
9126 descr
->arg
= &buffer
[i
];
9129 buffer
[i
++] = *fmt
++;
9131 buffer
[i
++] = *fmt
++;
9132 while (*fmt
&& *fmt
!= ']')
9133 buffer
[i
++] = *fmt
++;
9135 fmtObj
->error
= "unmatched [ in format string";
9140 /* In case a range fence was given "backwards", swap it */
9143 for (j
= beg
+ 1; j
< end
- 1; ++j
) {
9144 if (buffer
[j
] == '-' && buffer
[j
- 1] > buffer
[j
+ 1]) {
9145 char tmp
= buffer
[j
- 1];
9147 buffer
[j
- 1] = buffer
[j
+ 1];
9148 buffer
[j
+ 1] = tmp
;
9155 /* Remember any valid modifier if given */
9156 if (strchr("hlL", *fmt
) != 0)
9157 descr
->modifier
= tolower((int)*fmt
++);
9160 if (strchr("efgcsndoxui", *fmt
) == 0) {
9161 fmtObj
->error
= "bad scan conversion character";
9164 else if (*fmt
== 'c' && descr
->width
!= 0) {
9165 fmtObj
->error
= "field width may not be specified in %c " "conversion";
9168 else if (*fmt
== 'u' && descr
->modifier
== 'l') {
9169 fmtObj
->error
= "unsigned wide not supported";
9179 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9181 #define FormatGetCnvCount(_fo_) \
9182 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9183 #define FormatGetMaxPos(_fo_) \
9184 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9185 #define FormatGetError(_fo_) \
9186 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9188 /* JimScanAString is used to scan an unspecified string that ends with
9189 * next WS, or a string that is specified via a charset.
9192 static Jim_Obj
*JimScanAString(Jim_Interp
*interp
, const char *sdescr
, const char *str
)
9194 char *buffer
= Jim_StrDup(str
);
9201 if (!sdescr
&& isspace(UCHAR(*str
)))
9202 break; /* EOS via WS if unspecified */
9204 n
= utf8_tounicode(str
, &c
);
9205 if (sdescr
&& !JimCharsetMatch(sdescr
, c
, JIM_CHARSET_SCAN
))
9211 return Jim_NewStringObjNoAlloc(interp
, buffer
, p
- buffer
);
9214 /* ScanOneEntry will scan one entry out of the string passed as argument.
9215 * It use the sscanf() function for this task. After extracting and
9216 * converting of the value, the count of scanned characters will be
9217 * returned of -1 in case of no conversion tool place and string was
9218 * already scanned thru */
9220 static int ScanOneEntry(Jim_Interp
*interp
, const char *str
, int pos
, int strLen
,
9221 ScanFmtStringObj
* fmtObj
, long idx
, Jim_Obj
**valObjPtr
)
9224 const ScanFmtPartDescr
*descr
= &fmtObj
->descr
[idx
];
9226 size_t anchor
= pos
;
9228 Jim_Obj
*tmpObj
= NULL
;
9230 /* First pessimistically assume, we will not scan anything :-) */
9232 if (descr
->prefix
) {
9233 /* There was a prefix given before the conversion, skip it and adjust
9234 * the string-to-be-parsed accordingly */
9235 /* XXX: Should be checking strLen, not str[pos] */
9236 for (i
= 0; pos
< strLen
&& descr
->prefix
[i
]; ++i
) {
9237 /* If prefix require, skip WS */
9238 if (isspace(UCHAR(descr
->prefix
[i
])))
9239 while (pos
< strLen
&& isspace(UCHAR(str
[pos
])))
9241 else if (descr
->prefix
[i
] != str
[pos
])
9242 break; /* Prefix do not match here, leave the loop */
9244 ++pos
; /* Prefix matched so far, next round */
9246 if (pos
>= strLen
) {
9247 return -1; /* All of str consumed: EOF condition */
9249 else if (descr
->prefix
[i
] != 0)
9250 return 0; /* Not whole prefix consumed, no conversion possible */
9252 /* For all but following conversion, skip leading WS */
9253 if (descr
->type
!= 'c' && descr
->type
!= '[' && descr
->type
!= 'n')
9254 while (isspace(UCHAR(str
[pos
])))
9256 /* Determine how much skipped/scanned so far */
9257 scanned
= pos
- anchor
;
9259 /* %c is a special, simple case. no width */
9260 if (descr
->type
== 'n') {
9261 /* Return pseudo conversion means: how much scanned so far? */
9262 *valObjPtr
= Jim_NewIntObj(interp
, anchor
+ scanned
);
9264 else if (pos
>= strLen
) {
9265 /* Cannot scan anything, as str is totally consumed */
9268 else if (descr
->type
== 'c') {
9270 scanned
+= utf8_tounicode(&str
[pos
], &c
);
9271 *valObjPtr
= Jim_NewIntObj(interp
, c
);
9275 /* Processing of conversions follows ... */
9276 if (descr
->width
> 0) {
9277 /* Do not try to scan as fas as possible but only the given width.
9278 * To ensure this, we copy the part that should be scanned. */
9279 size_t sLen
= utf8_strlen(&str
[pos
], strLen
- pos
);
9280 size_t tLen
= descr
->width
> sLen
? sLen
: descr
->width
;
9282 tmpObj
= Jim_NewStringObjUtf8(interp
, str
+ pos
, tLen
);
9283 tok
= tmpObj
->bytes
;
9286 /* As no width was given, simply refer to the original string */
9289 switch (descr
->type
) {
9295 char *endp
; /* Position where the number finished */
9298 int base
= descr
->type
== 'o' ? 8
9299 : descr
->type
== 'x' ? 16 : descr
->type
== 'i' ? 0 : 10;
9301 /* Try to scan a number with the given base */
9302 w
= strtoull(tok
, &endp
, base
);
9303 if (endp
== tok
&& base
== 0) {
9304 /* If scanning failed, and base was undetermined, simply
9305 * put it to 10 and try once more. This should catch the
9306 * case where %i begin to parse a number prefix (e.g.
9307 * '0x' but no further digits follows. This will be
9308 * handled as a ZERO followed by a char 'x' by Tcl */
9309 w
= strtoull(tok
, &endp
, 10);
9313 /* There was some number sucessfully scanned! */
9314 *valObjPtr
= Jim_NewIntObj(interp
, w
);
9316 /* Adjust the number-of-chars scanned so far */
9317 scanned
+= endp
- tok
;
9320 /* Nothing was scanned. We have to determine if this
9321 * happened due to e.g. prefix mismatch or input str
9323 scanned
= *tok
? 0 : -1;
9329 *valObjPtr
= JimScanAString(interp
, descr
->arg
, tok
);
9330 scanned
+= Jim_Length(*valObjPtr
);
9337 double value
= strtod(tok
, &endp
);
9340 /* There was some number sucessfully scanned! */
9341 *valObjPtr
= Jim_NewDoubleObj(interp
, value
);
9342 /* Adjust the number-of-chars scanned so far */
9343 scanned
+= endp
- tok
;
9346 /* Nothing was scanned. We have to determine if this
9347 * happened due to e.g. prefix mismatch or input str
9349 scanned
= *tok
? 0 : -1;
9354 /* If a substring was allocated (due to pre-defined width) do not
9355 * forget to free it */
9357 Jim_FreeNewObj(interp
, tmpObj
);
9363 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9364 * string and returns all converted (and not ignored) values in a list back
9365 * to the caller. If an error occured, a NULL pointer will be returned */
9367 Jim_Obj
*Jim_ScanString(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*fmtObjPtr
, int flags
)
9371 const char *str
= Jim_String(strObjPtr
);
9372 int strLen
= Jim_Utf8Length(interp
, strObjPtr
);
9373 Jim_Obj
*resultList
= 0;
9374 Jim_Obj
**resultVec
= 0;
9376 Jim_Obj
*emptyStr
= 0;
9377 ScanFmtStringObj
*fmtObj
;
9379 /* This should never happen. The format object should already be of the correct type */
9380 JimPanic((fmtObjPtr
->typePtr
!= &scanFmtStringObjType
, "Jim_ScanString() for non-scan format"));
9382 fmtObj
= (ScanFmtStringObj
*) fmtObjPtr
->internalRep
.ptr
;
9383 /* Check if format specification was valid */
9384 if (fmtObj
->error
!= 0) {
9385 if (flags
& JIM_ERRMSG
)
9386 Jim_SetResultString(interp
, fmtObj
->error
, -1);
9389 /* Allocate a new "shared" empty string for all unassigned conversions */
9390 emptyStr
= Jim_NewEmptyStringObj(interp
);
9391 Jim_IncrRefCount(emptyStr
);
9392 /* Create a list and fill it with empty strings up to max specified XPG3 */
9393 resultList
= Jim_NewListObj(interp
, NULL
, 0);
9394 if (fmtObj
->maxPos
> 0) {
9395 for (i
= 0; i
< fmtObj
->maxPos
; ++i
)
9396 Jim_ListAppendElement(interp
, resultList
, emptyStr
);
9397 JimListGetElements(interp
, resultList
, &resultc
, &resultVec
);
9399 /* Now handle every partial format description */
9400 for (i
= 0, pos
= 0; i
< fmtObj
->count
; ++i
) {
9401 ScanFmtPartDescr
*descr
= &(fmtObj
->descr
[i
]);
9404 /* Only last type may be "literal" w/o conversion - skip it! */
9405 if (descr
->type
== 0)
9407 /* As long as any conversion could be done, we will proceed */
9409 scanned
= ScanOneEntry(interp
, str
, pos
, strLen
, fmtObj
, i
, &value
);
9410 /* In case our first try results in EOF, we will leave */
9411 if (scanned
== -1 && i
== 0)
9413 /* Advance next pos-to-be-scanned for the amount scanned already */
9416 /* value == 0 means no conversion took place so take empty string */
9418 value
= Jim_NewEmptyStringObj(interp
);
9419 /* If value is a non-assignable one, skip it */
9420 if (descr
->pos
== -1) {
9421 Jim_FreeNewObj(interp
, value
);
9423 else if (descr
->pos
== 0)
9424 /* Otherwise append it to the result list if no XPG3 was given */
9425 Jim_ListAppendElement(interp
, resultList
, value
);
9426 else if (resultVec
[descr
->pos
- 1] == emptyStr
) {
9427 /* But due to given XPG3, put the value into the corr. slot */
9428 Jim_DecrRefCount(interp
, resultVec
[descr
->pos
- 1]);
9429 Jim_IncrRefCount(value
);
9430 resultVec
[descr
->pos
- 1] = value
;
9433 /* Otherwise, the slot was already used - free obj and ERROR */
9434 Jim_FreeNewObj(interp
, value
);
9438 Jim_DecrRefCount(interp
, emptyStr
);
9441 Jim_DecrRefCount(interp
, emptyStr
);
9442 Jim_FreeNewObj(interp
, resultList
);
9443 return (Jim_Obj
*)EOF
;
9445 Jim_DecrRefCount(interp
, emptyStr
);
9446 Jim_FreeNewObj(interp
, resultList
);
9450 /* -----------------------------------------------------------------------------
9451 * Pseudo Random Number Generation
9452 * ---------------------------------------------------------------------------*/
9453 /* Initialize the sbox with the numbers from 0 to 255 */
9454 static void JimPrngInit(Jim_Interp
*interp
)
9456 #define PRNG_SEED_SIZE 256
9459 time_t t
= time(NULL
);
9461 interp
->prngState
= Jim_Alloc(sizeof(Jim_PrngState
));
9463 seed
= Jim_Alloc(PRNG_SEED_SIZE
* sizeof(*seed
));
9464 for (i
= 0; i
< PRNG_SEED_SIZE
; i
++) {
9465 seed
[i
] = (rand() ^ t
^ clock());
9467 JimPrngSeed(interp
, (unsigned char *)seed
, PRNG_SEED_SIZE
* sizeof(*seed
));
9471 /* Generates N bytes of random data */
9472 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
)
9474 Jim_PrngState
*prng
;
9475 unsigned char *destByte
= (unsigned char *)dest
;
9476 unsigned int si
, sj
, x
;
9478 /* initialization, only needed the first time */
9479 if (interp
->prngState
== NULL
)
9480 JimPrngInit(interp
);
9481 prng
= interp
->prngState
;
9482 /* generates 'len' bytes of pseudo-random numbers */
9483 for (x
= 0; x
< len
; x
++) {
9484 prng
->i
= (prng
->i
+ 1) & 0xff;
9485 si
= prng
->sbox
[prng
->i
];
9486 prng
->j
= (prng
->j
+ si
) & 0xff;
9487 sj
= prng
->sbox
[prng
->j
];
9488 prng
->sbox
[prng
->i
] = sj
;
9489 prng
->sbox
[prng
->j
] = si
;
9490 *destByte
++ = prng
->sbox
[(si
+ sj
) & 0xff];
9494 /* Re-seed the generator with user-provided bytes */
9495 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
)
9498 Jim_PrngState
*prng
;
9500 /* initialization, only needed the first time */
9501 if (interp
->prngState
== NULL
)
9502 JimPrngInit(interp
);
9503 prng
= interp
->prngState
;
9505 /* Set the sbox[i] with i */
9506 for (i
= 0; i
< 256; i
++)
9508 /* Now use the seed to perform a random permutation of the sbox */
9509 for (i
= 0; i
< seedLen
; i
++) {
9512 t
= prng
->sbox
[i
& 0xFF];
9513 prng
->sbox
[i
& 0xFF] = prng
->sbox
[seed
[i
]];
9514 prng
->sbox
[seed
[i
]] = t
;
9516 prng
->i
= prng
->j
= 0;
9518 /* discard at least the first 256 bytes of stream.
9519 * borrow the seed buffer for this
9521 for (i
= 0; i
< 256; i
+= seedLen
) {
9522 JimRandomBytes(interp
, seed
, seedLen
);
9527 static int Jim_IncrCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
9529 jim_wide wideValue
, increment
= 1;
9532 if (argc
!= 2 && argc
!= 3) {
9533 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?increment?");
9537 if (Jim_GetWide(interp
, argv
[2], &increment
) != JIM_OK
)
9540 intObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
9542 /* Set missing variable to 0 */
9545 else if (Jim_GetWide(interp
, intObjPtr
, &wideValue
) != JIM_OK
) {
9548 if (!intObjPtr
|| Jim_IsShared(intObjPtr
)) {
9549 intObjPtr
= Jim_NewIntObj(interp
, wideValue
+ increment
);
9550 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
9551 Jim_FreeNewObj(interp
, intObjPtr
);
9556 /* Can do it the quick way */
9557 Jim_InvalidateStringRep(intObjPtr
);
9558 JimWideValue(intObjPtr
) = wideValue
+ increment
;
9560 /* The following step is required in order to invalidate the
9561 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9562 if (argv
[1]->typePtr
!= &variableObjType
) {
9563 /* Note that this can't fail since GetVariable already succeeded */
9564 Jim_SetVariable(interp
, argv
[1], intObjPtr
);
9567 Jim_SetResult(interp
, intObjPtr
);
9572 /* -----------------------------------------------------------------------------
9574 * ---------------------------------------------------------------------------*/
9575 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9576 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9578 /* Handle calls to the [unknown] command */
9579 static int JimUnknown(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, Jim_Obj
*fileNameObj
,
9582 Jim_Obj
**v
, *sv
[JIM_EVAL_SARGV_LEN
];
9585 /* If JimUnknown() is recursively called too many times...
9588 if (interp
->unknown_called
> 50) {
9592 /* If the [unknown] command does not exists returns
9594 if (Jim_GetCommand(interp
, interp
->unknown
, JIM_NONE
) == NULL
)
9597 /* The object interp->unknown just contains
9598 * the "unknown" string, it is used in order to
9599 * avoid to lookup the unknown command every time
9600 * but instread to cache the result. */
9601 if (argc
+ 1 <= JIM_EVAL_SARGV_LEN
)
9604 v
= Jim_Alloc(sizeof(Jim_Obj
*) * (argc
+ 1));
9605 /* Make a copy of the arguments vector, but shifted on
9606 * the right of one position. The command name of the
9607 * command will be instead the first argument of the
9608 * [unknown] call. */
9609 memcpy(v
+ 1, argv
, sizeof(Jim_Obj
*) * argc
);
9610 v
[0] = interp
->unknown
;
9612 interp
->unknown_called
++;
9613 retCode
= JimEvalObjVector(interp
, argc
+ 1, v
, fileNameObj
, linenr
);
9614 interp
->unknown_called
--;
9622 /* Eval the object vector 'objv' composed of 'objc' elements.
9623 * Every element is used as single argument.
9624 * Jim_EvalObj() will call this function every time its object
9625 * argument is of "list" type, with no string representation.
9627 * This is possible because the string representation of a
9628 * list object generated by the UpdateStringOfList is made
9629 * in a way that ensures that every list element is a different
9630 * command argument. */
9631 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
9632 Jim_Obj
*fileNameObj
, int linenr
)
9637 /* Incr refcount of arguments. */
9638 for (i
= 0; i
< objc
; i
++)
9639 Jim_IncrRefCount(objv
[i
]);
9640 /* Command lookup */
9641 cmdPtr
= Jim_GetCommand(interp
, objv
[0], JIM_ERRMSG
);
9642 if (cmdPtr
== NULL
) {
9643 retcode
= JimUnknown(interp
, objc
, objv
, fileNameObj
, linenr
);
9646 /* Call it -- Make sure result is an empty object. */
9647 JimIncrCmdRefCount(cmdPtr
);
9648 Jim_SetEmptyResult(interp
);
9649 if (cmdPtr
->isproc
) {
9650 retcode
= JimCallProcedure(interp
, cmdPtr
, fileNameObj
, linenr
, objc
, objv
);
9653 interp
->cmdPrivData
= cmdPtr
->u
.native
.privData
;
9654 retcode
= cmdPtr
->u
.native
.cmdProc(interp
, objc
, objv
);
9656 JimDecrCmdRefCount(interp
, cmdPtr
);
9658 /* Decr refcount of arguments and return the retcode */
9659 for (i
= 0; i
< objc
; i
++)
9660 Jim_DecrRefCount(interp
, objv
[i
]);
9665 int Jim_EvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
9667 return JimEvalObjVector(interp
, objc
, objv
, interp
->emptyObj
, 1);
9671 * Invokes 'prefix' as a command with the objv array as arguments.
9673 int Jim_EvalObjPrefix(Jim_Interp
*interp
, Jim_Obj
*prefix
, int objc
, Jim_Obj
*const *objv
)
9677 Jim_Obj
**nargv
= Jim_Alloc((objc
+ 1) * sizeof(*nargv
));
9680 for (i
= 0; i
< objc
; i
++) {
9681 nargv
[i
+ 1] = objv
[i
];
9683 ret
= Jim_EvalObjVector(interp
, objc
+ 1, nargv
);
9688 static void JimAddErrorToStack(Jim_Interp
*interp
, int retcode
, Jim_Obj
*fileNameObj
, int line
)
9692 if (rc
== JIM_ERR
&& !interp
->errorFlag
) {
9693 /* This is the first error, so save the file/line information and reset the stack */
9694 interp
->errorFlag
= 1;
9695 Jim_IncrRefCount(fileNameObj
);
9696 Jim_DecrRefCount(interp
, interp
->errorFileNameObj
);
9697 interp
->errorFileNameObj
= fileNameObj
;
9698 interp
->errorLine
= line
;
9700 JimResetStackTrace(interp
);
9701 /* Always add a level where the error first occurs */
9702 interp
->addStackTrace
++;
9705 /* Now if this is an "interesting" level, add it to the stack trace */
9706 if (rc
== JIM_ERR
&& interp
->addStackTrace
> 0) {
9707 /* Add the stack info for the current level */
9709 JimAppendStackTrace(interp
, Jim_String(interp
->errorProc
), fileNameObj
, line
);
9711 /* Note: if we didn't have a filename for this level,
9712 * don't clear the addStackTrace flag
9713 * so we can pick it up at the next level
9715 if (Jim_Length(fileNameObj
)) {
9716 interp
->addStackTrace
= 0;
9719 Jim_DecrRefCount(interp
, interp
->errorProc
);
9720 interp
->errorProc
= interp
->emptyObj
;
9721 Jim_IncrRefCount(interp
->errorProc
);
9723 else if (rc
== JIM_RETURN
&& interp
->returnCode
== JIM_ERR
) {
9724 /* Propagate the addStackTrace value through 'return -code error' */
9727 interp
->addStackTrace
= 0;
9731 /* And delete any local procs */
9732 static void JimDeleteLocalProcs(Jim_Interp
*interp
)
9734 if (interp
->localProcs
) {
9737 while ((procname
= Jim_StackPop(interp
->localProcs
)) != NULL
) {
9738 /* If there is a pushed command, find it */
9739 Jim_Cmd
*prevCmd
= NULL
;
9740 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->commands
, procname
);
9742 Jim_Cmd
*cmd
= (Jim_Cmd
*)he
->u
.val
;
9743 if (cmd
->isproc
&& cmd
->u
.proc
.prevCmd
) {
9744 prevCmd
= cmd
->u
.proc
.prevCmd
;
9745 cmd
->u
.proc
.prevCmd
= NULL
;
9749 /* Delete the local proc */
9750 Jim_DeleteCommand(interp
, procname
);
9753 /* And restore the pushed command */
9754 Jim_AddHashEntry(&interp
->commands
, procname
, prevCmd
);
9758 Jim_FreeStack(interp
->localProcs
);
9759 Jim_Free(interp
->localProcs
);
9760 interp
->localProcs
= NULL
;
9764 static int JimSubstOneToken(Jim_Interp
*interp
, const ScriptToken
*token
, Jim_Obj
**objPtrPtr
)
9768 switch (token
->type
) {
9771 objPtr
= token
->objPtr
;
9774 objPtr
= Jim_GetVariable(interp
, token
->objPtr
, JIM_ERRMSG
);
9776 case JIM_TT_DICTSUGAR
:
9777 objPtr
= JimExpandDictSugar(interp
, token
->objPtr
);
9779 case JIM_TT_EXPRSUGAR
:
9780 objPtr
= JimExpandExprSugar(interp
, token
->objPtr
);
9783 switch (Jim_EvalObj(interp
, token
->objPtr
)) {
9786 objPtr
= interp
->result
;
9789 /* Stop substituting */
9792 /* just skip this one */
9793 return JIM_CONTINUE
;
9800 "default token type (%d) reached " "in Jim_SubstObj().", token
->type
));
9805 *objPtrPtr
= objPtr
;
9811 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9812 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9813 * The returned object has refcount = 0.
9815 static Jim_Obj
*JimInterpolateTokens(Jim_Interp
*interp
, const ScriptToken
* token
, int tokens
, int flags
)
9819 Jim_Obj
*sintv
[JIM_EVAL_SINTV_LEN
];
9823 if (tokens
<= JIM_EVAL_SINTV_LEN
)
9826 intv
= Jim_Alloc(sizeof(Jim_Obj
*) * tokens
);
9828 /* Compute every token forming the argument
9829 * in the intv objects vector. */
9830 for (i
= 0; i
< tokens
; i
++) {
9831 switch (JimSubstOneToken(interp
, &token
[i
], &intv
[i
])) {
9836 if (flags
& JIM_SUBST_FLAG
) {
9841 /* XXX: Should probably set an error about break outside loop */
9842 /* fall through to error */
9844 if (flags
& JIM_SUBST_FLAG
) {
9848 /* XXX: Ditto continue outside loop */
9849 /* fall through to error */
9852 Jim_DecrRefCount(interp
, intv
[i
]);
9854 if (intv
!= sintv
) {
9859 Jim_IncrRefCount(intv
[i
]);
9860 Jim_String(intv
[i
]);
9861 totlen
+= intv
[i
]->length
;
9864 /* Fast path return for a single token */
9865 if (tokens
== 1 && intv
[0] && intv
== sintv
) {
9866 Jim_DecrRefCount(interp
, intv
[0]);
9870 /* Concatenate every token in an unique
9872 objPtr
= Jim_NewStringObjNoAlloc(interp
, NULL
, 0);
9874 if (tokens
== 4 && token
[0].type
== JIM_TT_ESC
&& token
[1].type
== JIM_TT_ESC
9875 && token
[2].type
== JIM_TT_VAR
) {
9876 /* May be able to do fast interpolated object -> dictSubst */
9877 objPtr
->typePtr
= &interpolatedObjType
;
9878 objPtr
->internalRep
.twoPtrValue
.ptr1
= (void *)token
;
9879 objPtr
->internalRep
.twoPtrValue
.ptr2
= intv
[2];
9880 Jim_IncrRefCount(intv
[2]);
9883 s
= objPtr
->bytes
= Jim_Alloc(totlen
+ 1);
9884 objPtr
->length
= totlen
;
9885 for (i
= 0; i
< tokens
; i
++) {
9887 memcpy(s
, intv
[i
]->bytes
, intv
[i
]->length
);
9888 s
+= intv
[i
]->length
;
9889 Jim_DecrRefCount(interp
, intv
[i
]);
9892 objPtr
->bytes
[totlen
] = '\0';
9893 /* Free the intv vector if not static. */
9894 if (intv
!= sintv
) {
9902 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9903 * Otherwise eval with Jim_EvalObj()
9905 static int JimEvalObjList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*fileNameObj
, int linenr
)
9907 int retcode
= JIM_OK
;
9909 JimPanic((!Jim_IsList(listPtr
), "JimEvalObjList() called without list arg"));
9911 if (listPtr
->internalRep
.listValue
.len
) {
9912 Jim_IncrRefCount(listPtr
);
9913 retcode
= JimEvalObjVector(interp
,
9914 listPtr
->internalRep
.listValue
.len
,
9915 listPtr
->internalRep
.listValue
.ele
, fileNameObj
, linenr
);
9916 Jim_DecrRefCount(interp
, listPtr
);
9921 int Jim_EvalObj(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
9926 int retcode
= JIM_OK
;
9927 Jim_Obj
*sargv
[JIM_EVAL_SARGV_LEN
], **argv
= NULL
;
9930 interp
->errorFlag
= 0;
9932 /* If the object is of type "list", with no string rep we can call
9933 * a specialized version of Jim_EvalObj() */
9934 if (Jim_IsList(scriptObjPtr
) && scriptObjPtr
->bytes
== NULL
) {
9935 return JimEvalObjList(interp
, scriptObjPtr
, interp
->emptyObj
, 1);
9938 Jim_IncrRefCount(scriptObjPtr
); /* Make sure it's shared. */
9939 script
= Jim_GetScript(interp
, scriptObjPtr
);
9941 /* Reset the interpreter result. This is useful to
9942 * return the empty result in the case of empty program. */
9943 Jim_SetEmptyResult(interp
);
9945 #ifdef JIM_OPTIMIZATION
9946 /* Check for one of the following common scripts used by for, while
9951 if (script
->len
== 0) {
9952 Jim_DecrRefCount(interp
, scriptObjPtr
);
9955 if (script
->len
== 3
9956 && script
->token
[1].objPtr
->typePtr
== &commandObjType
9957 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->isproc
== 0
9958 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->u
.native
.cmdProc
== Jim_IncrCoreCommand
9959 && script
->token
[2].objPtr
->typePtr
== &variableObjType
) {
9961 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, script
->token
[2].objPtr
, JIM_NONE
);
9963 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
9964 JimWideValue(objPtr
)++;
9965 Jim_InvalidateStringRep(objPtr
);
9966 Jim_DecrRefCount(interp
, scriptObjPtr
);
9967 Jim_SetResult(interp
, objPtr
);
9973 /* Now we have to make sure the internal repr will not be
9974 * freed on shimmering.
9976 * Think for example to this:
9978 * set x {llength $x; ... some more code ...}; eval $x
9980 * In order to preserve the internal rep, we increment the
9981 * inUse field of the script internal rep structure. */
9984 token
= script
->token
;
9987 /* Execute every command sequentially until the end of the script
9988 * or an error occurs.
9990 for (i
= 0; i
< script
->len
&& retcode
== JIM_OK
; ) {
9995 /* First token of the line is always JIM_TT_LINE */
9996 argc
= token
[i
].objPtr
->internalRep
.scriptLineValue
.argc
;
9997 linenr
= token
[i
].objPtr
->internalRep
.scriptLineValue
.line
;
9999 /* Allocate the arguments vector if required */
10000 if (argc
> JIM_EVAL_SARGV_LEN
)
10001 argv
= Jim_Alloc(sizeof(Jim_Obj
*) * argc
);
10003 /* Skip the JIM_TT_LINE token */
10006 /* Populate the arguments objects.
10007 * If an error occurs, retcode will be set and
10008 * 'j' will be set to the number of args expanded
10010 for (j
= 0; j
< argc
; j
++) {
10011 long wordtokens
= 1;
10013 Jim_Obj
*wordObjPtr
= NULL
;
10015 if (token
[i
].type
== JIM_TT_WORD
) {
10016 wordtokens
= JimWideValue(token
[i
++].objPtr
);
10017 if (wordtokens
< 0) {
10019 wordtokens
= -wordtokens
;
10023 if (wordtokens
== 1) {
10024 /* Fast path if the token does not
10025 * need interpolation */
10027 switch (token
[i
].type
) {
10030 wordObjPtr
= token
[i
].objPtr
;
10033 wordObjPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
10035 case JIM_TT_EXPRSUGAR
:
10036 wordObjPtr
= JimExpandExprSugar(interp
, token
[i
].objPtr
);
10038 case JIM_TT_DICTSUGAR
:
10039 wordObjPtr
= JimExpandDictSugar(interp
, token
[i
].objPtr
);
10042 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
10043 if (retcode
== JIM_OK
) {
10044 wordObjPtr
= Jim_GetResult(interp
);
10048 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10052 /* For interpolation we call a helper
10053 * function to do the work for us. */
10054 wordObjPtr
= JimInterpolateTokens(interp
, token
+ i
, wordtokens
, JIM_NONE
);
10058 if (retcode
== JIM_OK
) {
10064 Jim_IncrRefCount(wordObjPtr
);
10068 argv
[j
] = wordObjPtr
;
10071 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10072 int len
= Jim_ListLength(interp
, wordObjPtr
);
10073 int newargc
= argc
+ len
- 1;
10077 if (argv
== sargv
) {
10078 if (newargc
> JIM_EVAL_SARGV_LEN
) {
10079 argv
= Jim_Alloc(sizeof(*argv
) * newargc
);
10080 memcpy(argv
, sargv
, sizeof(*argv
) * j
);
10084 /* Need to realloc to make room for (len - 1) more entries */
10085 argv
= Jim_Realloc(argv
, sizeof(*argv
) * newargc
);
10089 /* Now copy in the expanded version */
10090 for (k
= 0; k
< len
; k
++) {
10091 argv
[j
++] = wordObjPtr
->internalRep
.listValue
.ele
[k
];
10092 Jim_IncrRefCount(wordObjPtr
->internalRep
.listValue
.ele
[k
]);
10095 /* The original object reference is no longer needed,
10096 * after the expansion it is no longer present on
10097 * the argument vector, but the single elements are
10099 Jim_DecrRefCount(interp
, wordObjPtr
);
10101 /* And update the indexes */
10107 if (retcode
== JIM_OK
&& argc
) {
10108 /* Lookup the command to call */
10109 cmd
= Jim_GetCommand(interp
, argv
[0], JIM_ERRMSG
);
10111 /* Call it -- Make sure result is an empty object. */
10112 JimIncrCmdRefCount(cmd
);
10113 Jim_SetEmptyResult(interp
);
10116 JimCallProcedure(interp
, cmd
, script
->fileNameObj
, linenr
, argc
, argv
);
10118 interp
->cmdPrivData
= cmd
->u
.native
.privData
;
10119 retcode
= cmd
->u
.native
.cmdProc(interp
, argc
, argv
);
10121 JimDecrCmdRefCount(interp
, cmd
);
10124 /* Call [unknown] */
10125 retcode
= JimUnknown(interp
, argc
, argv
, script
->fileNameObj
, linenr
);
10127 if (interp
->signal_level
&& interp
->sigmask
) {
10128 /* Check for a signal after each command */
10129 retcode
= JIM_SIGNAL
;
10133 /* Finished with the command, so decrement ref counts of each argument */
10135 Jim_DecrRefCount(interp
, argv
[j
]);
10138 if (argv
!= sargv
) {
10144 /* Possibly add to the error stack trace */
10145 JimAddErrorToStack(interp
, retcode
, script
->fileNameObj
, linenr
);
10147 /* Note that we don't have to decrement inUse, because the
10148 * following code transfers our use of the reference again to
10149 * the script object. */
10150 Jim_FreeIntRep(interp
, scriptObjPtr
);
10151 scriptObjPtr
->typePtr
= &scriptObjType
;
10152 Jim_SetIntRepPtr(scriptObjPtr
, script
);
10153 Jim_DecrRefCount(interp
, scriptObjPtr
);
10158 static int JimSetProcArg(Jim_Interp
*interp
, Jim_Obj
*argNameObj
, Jim_Obj
*argValObj
)
10161 /* If argObjPtr begins with '&', do an automatic upvar */
10162 const char *varname
= Jim_String(argNameObj
);
10163 if (*varname
== '&') {
10164 /* First check that the target variable exists */
10166 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
10168 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10169 objPtr
= Jim_GetVariable(interp
, argValObj
, JIM_ERRMSG
);
10170 interp
->framePtr
= savedCallFrame
;
10175 /* It exists, so perform the binding. */
10176 objPtr
= Jim_NewStringObj(interp
, varname
+ 1, -1);
10177 Jim_IncrRefCount(objPtr
);
10178 retcode
= Jim_SetVariableLink(interp
, objPtr
, argValObj
, interp
->framePtr
->parentCallFrame
);
10179 Jim_DecrRefCount(interp
, objPtr
);
10182 retcode
= Jim_SetVariable(interp
, argNameObj
, argValObj
);
10188 * Sets the interp result to be an error message indicating the required proc args.
10190 static void JimSetProcWrongArgs(Jim_Interp
*interp
, Jim_Obj
*procNameObj
, Jim_Cmd
*cmd
)
10192 /* Create a nice error message, consistent with Tcl 8.5 */
10193 Jim_Obj
*argmsg
= Jim_NewStringObj(interp
, "", 0);
10196 for (i
= 0; i
< cmd
->u
.proc
.argListLen
; i
++) {
10197 Jim_AppendString(interp
, argmsg
, " ", 1);
10199 if (i
== cmd
->u
.proc
.argsPos
) {
10200 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10202 Jim_AppendString(interp
, argmsg
, "?", 1);
10203 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].defaultObjPtr
);
10204 Jim_AppendString(interp
, argmsg
, " ...?", -1);
10207 /* We have plain args */
10208 Jim_AppendString(interp
, argmsg
, "?argument ...?", -1);
10212 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10213 Jim_AppendString(interp
, argmsg
, "?", 1);
10214 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10215 Jim_AppendString(interp
, argmsg
, "?", 1);
10218 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10222 Jim_SetResultFormatted(interp
, "wrong # args: should be \"%#s%#s\"", procNameObj
, argmsg
);
10223 Jim_FreeNewObj(interp
, argmsg
);
10226 /* Call a procedure implemented in Tcl.
10227 * It's possible to speed-up a lot this function, currently
10228 * the callframes are not cached, but allocated and
10229 * destroied every time. What is expecially costly is
10230 * to create/destroy the local vars hash table every time.
10232 * This can be fixed just implementing callframes caching
10233 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10234 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, Jim_Obj
*fileNameObj
, int linenr
, int argc
,
10235 Jim_Obj
*const *argv
)
10237 Jim_CallFrame
*callFramePtr
;
10238 Jim_Stack
*prevLocalProcs
;
10239 int i
, d
, retcode
, optargs
;
10242 if (argc
- 1 < cmd
->u
.proc
.reqArity
||
10243 (cmd
->u
.proc
.argsPos
< 0 && argc
- 1 > cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
)) {
10244 JimSetProcWrongArgs(interp
, argv
[0], cmd
);
10248 /* Check if there are too nested calls */
10249 if (interp
->framePtr
->level
== interp
->maxNestingDepth
) {
10250 Jim_SetResultString(interp
, "Too many nested calls. Infinite recursion?", -1);
10254 /* Create a new callframe */
10255 callFramePtr
= JimCreateCallFrame(interp
, interp
->framePtr
);
10256 callFramePtr
->argv
= argv
;
10257 callFramePtr
->argc
= argc
;
10258 callFramePtr
->procArgsObjPtr
= cmd
->u
.proc
.argListObjPtr
;
10259 callFramePtr
->procBodyObjPtr
= cmd
->u
.proc
.bodyObjPtr
;
10260 callFramePtr
->staticVars
= cmd
->u
.proc
.staticVars
;
10261 callFramePtr
->fileNameObj
= fileNameObj
;
10262 callFramePtr
->line
= linenr
;
10263 Jim_IncrRefCount(cmd
->u
.proc
.argListObjPtr
);
10264 Jim_IncrRefCount(cmd
->u
.proc
.bodyObjPtr
);
10265 interp
->framePtr
= callFramePtr
;
10267 /* Install a new stack for local procs */
10268 prevLocalProcs
= interp
->localProcs
;
10269 interp
->localProcs
= NULL
;
10271 /* How many optional args are available */
10272 optargs
= (argc
- 1 - cmd
->u
.proc
.reqArity
);
10274 /* Step 'i' along the actual args, and step 'd' along the formal args */
10276 for (d
= 0; d
< cmd
->u
.proc
.argListLen
; d
++) {
10277 Jim_Obj
*nameObjPtr
= cmd
->u
.proc
.arglist
[d
].nameObjPtr
;
10278 if (d
== cmd
->u
.proc
.argsPos
) {
10280 Jim_Obj
*listObjPtr
;
10282 if (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
< argc
- 1) {
10283 argsLen
= argc
- 1 - (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
);
10285 listObjPtr
= Jim_NewListObj(interp
, &argv
[i
], argsLen
);
10287 /* It is possible to rename args. */
10288 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
) {
10289 nameObjPtr
=cmd
->u
.proc
.arglist
[d
].defaultObjPtr
;
10291 retcode
= Jim_SetVariable(interp
, nameObjPtr
, listObjPtr
);
10292 if (retcode
!= JIM_OK
) {
10300 /* Optional or required? */
10301 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
== NULL
|| optargs
-- > 0) {
10302 retcode
= JimSetProcArg(interp
, nameObjPtr
, argv
[i
++]);
10305 /* Ran out, so use the default */
10306 retcode
= Jim_SetVariable(interp
, nameObjPtr
, cmd
->u
.proc
.arglist
[d
].defaultObjPtr
);
10308 if (retcode
!= JIM_OK
) {
10313 /* Eval the body */
10314 retcode
= Jim_EvalObj(interp
, cmd
->u
.proc
.bodyObjPtr
);
10317 /* Destroy the callframe */
10318 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10319 if (callFramePtr
->vars
.size
!= JIM_HT_INITIAL_SIZE
) {
10320 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NONE
);
10323 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NOHT
);
10325 /* Handle the JIM_EVAL return code */
10326 while (retcode
== JIM_EVAL
) {
10327 Jim_Obj
*resultScriptObjPtr
= Jim_GetResult(interp
);
10329 Jim_IncrRefCount(resultScriptObjPtr
);
10330 /* Result must be a list */
10331 retcode
= JimEvalObjList(interp
, resultScriptObjPtr
, fileNameObj
, linenr
);
10332 if (retcode
== JIM_RETURN
) {
10333 /* If the result of the tailcall invokes 'return', push
10334 * it up to the caller
10336 interp
->returnLevel
++;
10338 Jim_DecrRefCount(interp
, resultScriptObjPtr
);
10340 /* Handle the JIM_RETURN return code */
10341 if (retcode
== JIM_RETURN
) {
10342 if (--interp
->returnLevel
<= 0) {
10343 retcode
= interp
->returnCode
;
10344 interp
->returnCode
= JIM_OK
;
10345 interp
->returnLevel
= 0;
10348 else if (retcode
== JIM_ERR
) {
10349 interp
->addStackTrace
++;
10350 Jim_DecrRefCount(interp
, interp
->errorProc
);
10351 interp
->errorProc
= argv
[0];
10352 Jim_IncrRefCount(interp
->errorProc
);
10355 /* Delete any local procs */
10356 JimDeleteLocalProcs(interp
);
10357 interp
->localProcs
= prevLocalProcs
;
10362 int Jim_EvalSource(Jim_Interp
*interp
, const char *filename
, int lineno
, const char *script
)
10365 Jim_Obj
*scriptObjPtr
;
10367 scriptObjPtr
= Jim_NewStringObj(interp
, script
, -1);
10368 Jim_IncrRefCount(scriptObjPtr
);
10371 Jim_Obj
*prevScriptObj
;
10373 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), lineno
);
10375 prevScriptObj
= interp
->currentScriptObj
;
10376 interp
->currentScriptObj
= scriptObjPtr
;
10378 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10380 interp
->currentScriptObj
= prevScriptObj
;
10383 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10385 Jim_DecrRefCount(interp
, scriptObjPtr
);
10389 int Jim_Eval(Jim_Interp
*interp
, const char *script
)
10391 return Jim_EvalObj(interp
, Jim_NewStringObj(interp
, script
, -1));
10394 /* Execute script in the scope of the global level */
10395 int Jim_EvalGlobal(Jim_Interp
*interp
, const char *script
)
10398 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10400 interp
->framePtr
= interp
->topFramePtr
;
10401 retval
= Jim_Eval(interp
, script
);
10402 interp
->framePtr
= savedFramePtr
;
10407 int Jim_EvalFileGlobal(Jim_Interp
*interp
, const char *filename
)
10410 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10412 interp
->framePtr
= interp
->topFramePtr
;
10413 retval
= Jim_EvalFile(interp
, filename
);
10414 interp
->framePtr
= savedFramePtr
;
10419 #include <sys/stat.h>
10421 int Jim_EvalFile(Jim_Interp
*interp
, const char *filename
)
10425 Jim_Obj
*scriptObjPtr
;
10426 Jim_Obj
*prevScriptObj
;
10430 struct JimParseResult result
;
10432 if (stat(filename
, &sb
) != 0 || (fp
= fopen(filename
, "rt")) == NULL
) {
10433 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", filename
, strerror(errno
));
10436 if (sb
.st_size
== 0) {
10441 buf
= Jim_Alloc(sb
.st_size
+ 1);
10442 readlen
= fread(buf
, 1, sb
.st_size
, fp
);
10446 Jim_SetResultFormatted(interp
, "failed to load file \"%s\": %s", filename
, strerror(errno
));
10452 scriptObjPtr
= Jim_NewStringObjNoAlloc(interp
, buf
, readlen
);
10453 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), 1);
10454 Jim_IncrRefCount(scriptObjPtr
);
10456 /* Now check the script for unmatched braces, etc. */
10457 if (SetScriptFromAny(interp
, scriptObjPtr
, &result
) == JIM_ERR
) {
10461 switch (result
.missing
) {
10463 msg
= "unmatched \"[\"";
10466 msg
= "missing close-brace";
10470 msg
= "missing quote";
10474 snprintf(linebuf
, sizeof(linebuf
), "%d", result
.line
);
10476 Jim_SetResultFormatted(interp
, "%s in \"%s\" at line %s",
10477 msg
, filename
, linebuf
);
10478 Jim_DecrRefCount(interp
, scriptObjPtr
);
10482 prevScriptObj
= interp
->currentScriptObj
;
10483 interp
->currentScriptObj
= scriptObjPtr
;
10485 retcode
= Jim_EvalObj(interp
, scriptObjPtr
);
10487 /* Handle the JIM_RETURN return code */
10488 if (retcode
== JIM_RETURN
) {
10489 if (--interp
->returnLevel
<= 0) {
10490 retcode
= interp
->returnCode
;
10491 interp
->returnCode
= JIM_OK
;
10492 interp
->returnLevel
= 0;
10495 if (retcode
== JIM_ERR
) {
10496 /* EvalFile changes context, so add a stack frame here */
10497 interp
->addStackTrace
++;
10500 interp
->currentScriptObj
= prevScriptObj
;
10502 Jim_DecrRefCount(interp
, scriptObjPtr
);
10507 /* -----------------------------------------------------------------------------
10509 * ---------------------------------------------------------------------------*/
10510 static int JimParseSubstStr(struct JimParserCtx
*pc
)
10512 pc
->tstart
= pc
->p
;
10513 pc
->tline
= pc
->linenr
;
10514 while (pc
->len
&& *pc
->p
!= '$' && *pc
->p
!= '[') {
10515 if (*pc
->p
== '\\' && pc
->len
> 1) {
10522 pc
->tend
= pc
->p
- 1;
10523 pc
->tt
= JIM_TT_ESC
;
10527 static int JimParseSubst(struct JimParserCtx
*pc
, int flags
)
10531 if (pc
->len
== 0) {
10532 pc
->tstart
= pc
->tend
= pc
->p
;
10533 pc
->tline
= pc
->linenr
;
10534 pc
->tt
= JIM_TT_EOL
;
10540 retval
= JimParseCmd(pc
);
10541 if (flags
& JIM_SUBST_NOCMD
) {
10544 pc
->tt
= (flags
& JIM_SUBST_NOESC
) ? JIM_TT_STR
: JIM_TT_ESC
;
10549 if (JimParseVar(pc
) == JIM_ERR
) {
10550 pc
->tstart
= pc
->tend
= pc
->p
++;
10552 pc
->tline
= pc
->linenr
;
10553 pc
->tt
= JIM_TT_STR
;
10556 if (flags
& JIM_SUBST_NOVAR
) {
10558 if (flags
& JIM_SUBST_NOESC
)
10559 pc
->tt
= JIM_TT_STR
;
10561 pc
->tt
= JIM_TT_ESC
;
10562 if (*pc
->tstart
== '{') {
10564 if (*(pc
->tend
+ 1))
10571 retval
= JimParseSubstStr(pc
);
10572 if (flags
& JIM_SUBST_NOESC
)
10573 pc
->tt
= JIM_TT_STR
;
10580 /* The subst object type reuses most of the data structures and functions
10581 * of the script object. Script's data structures are a bit more complex
10582 * for what is needed for [subst]itution tasks, but the reuse helps to
10583 * deal with a single data structure at the cost of some more memory
10584 * usage for substitutions. */
10586 /* This method takes the string representation of an object
10587 * as a Tcl string where to perform [subst]itution, and generates
10588 * the pre-parsed internal representation. */
10589 static int SetSubstFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, int flags
)
10592 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
10593 struct JimParserCtx parser
;
10594 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
10595 ParseTokenList tokenlist
;
10597 /* Initially parse the subst into tokens (in tokenlist) */
10598 ScriptTokenListInit(&tokenlist
);
10600 JimParserInit(&parser
, scriptText
, scriptTextLen
, 1);
10602 JimParseSubst(&parser
, flags
);
10604 /* Note that subst doesn't need the EOL token */
10607 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
10611 /* Create the "real" subst/script tokens from the initial token list */
10613 script
->substFlags
= flags
;
10614 script
->fileNameObj
= interp
->emptyObj
;
10615 Jim_IncrRefCount(script
->fileNameObj
);
10616 SubstObjAddTokens(interp
, script
, &tokenlist
);
10618 /* No longer need the token list */
10619 ScriptTokenListFree(&tokenlist
);
10621 #ifdef DEBUG_SHOW_SUBST
10625 printf("==== Subst ====\n");
10626 for (i
= 0; i
< script
->len
; i
++) {
10627 printf("[%2d] %s '%s'\n", i
, jim_tt_name(script
->token
[i
].type
),
10628 Jim_String(script
->token
[i
].objPtr
));
10633 /* Free the old internal rep and set the new one. */
10634 Jim_FreeIntRep(interp
, objPtr
);
10635 Jim_SetIntRepPtr(objPtr
, script
);
10636 objPtr
->typePtr
= &scriptObjType
;
10640 static ScriptObj
*Jim_GetSubst(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
10642 if (objPtr
->typePtr
!= &scriptObjType
|| ((ScriptObj
*)Jim_GetIntRepPtr(objPtr
))->substFlags
!= flags
)
10643 SetSubstFromAny(interp
, objPtr
, flags
);
10644 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
10647 /* Performs commands,variables,blackslashes substitution,
10648 * storing the result object (with refcount 0) into
10650 int Jim_SubstObj(Jim_Interp
*interp
, Jim_Obj
*substObjPtr
, Jim_Obj
**resObjPtrPtr
, int flags
)
10652 ScriptObj
*script
= Jim_GetSubst(interp
, substObjPtr
, flags
);
10654 Jim_IncrRefCount(substObjPtr
); /* Make sure it's shared. */
10655 /* In order to preserve the internal rep, we increment the
10656 * inUse field of the script internal rep structure. */
10659 *resObjPtrPtr
= JimInterpolateTokens(interp
, script
->token
, script
->len
, flags
);
10662 Jim_DecrRefCount(interp
, substObjPtr
);
10663 if (*resObjPtrPtr
== NULL
) {
10669 /* -----------------------------------------------------------------------------
10670 * Core commands utility functions
10671 * ---------------------------------------------------------------------------*/
10672 void Jim_WrongNumArgs(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, const char *msg
)
10675 Jim_Obj
*objPtr
= Jim_NewEmptyStringObj(interp
);
10677 Jim_AppendString(interp
, objPtr
, "wrong # args: should be \"", -1);
10678 for (i
= 0; i
< argc
; i
++) {
10679 Jim_AppendObj(interp
, objPtr
, argv
[i
]);
10680 if (!(i
+ 1 == argc
&& msg
[0] == '\0'))
10681 Jim_AppendString(interp
, objPtr
, " ", 1);
10683 Jim_AppendString(interp
, objPtr
, msg
, -1);
10684 Jim_AppendString(interp
, objPtr
, "\"", 1);
10685 Jim_SetResult(interp
, objPtr
);
10689 * May add the key and/or value to the list.
10691 typedef void JimHashtableIteratorCallbackType(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
10692 Jim_HashEntry
*he
, void *privdata
);
10694 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10697 * For each key of the hash table 'ht' which matches the glob pattern (all if NULL),
10698 * invoke the callback to add entries to a list.
10699 * Returns the list.
10701 * If 'string_keys' is set, the hash table keys are plain strings instead of objects.
10703 static Jim_Obj
*JimHashtablePatternMatch(Jim_Interp
*interp
, Jim_HashTable
*ht
, Jim_Obj
*patternObjPtr
,
10704 JimHashtableIteratorCallbackType
*callback
, void *privdata
, int string_keys
)
10707 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10709 /* Check for the non-pattern case. We can do this much more efficiently. */
10710 if (patternObjPtr
&& JimTrivialMatch(Jim_String(patternObjPtr
))) {
10711 he
= Jim_FindHashEntry(ht
, string_keys
? (void *)Jim_String(patternObjPtr
) : (void *)patternObjPtr
);
10713 callback(interp
, listObjPtr
, he
, privdata
);
10717 Jim_HashTableIterator
*htiter
;
10719 htiter
= Jim_GetHashTableIterator(ht
);
10720 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10721 if (patternObjPtr
== NULL
|| JimStringMatch(interp
, patternObjPtr
, string_keys
? he
->key
: Jim_String((Jim_Obj
*)he
->key
), 0)) {
10722 callback(interp
, listObjPtr
, he
, privdata
);
10725 Jim_FreeHashTableIterator(htiter
);
10730 /* Keep these in order */
10731 #define JIM_CMDLIST_COMMANDS 0
10732 #define JIM_CMDLIST_PROCS 1
10733 #define JIM_CMDLIST_CHANNELS 2
10736 * Adds matching command names (procs, channels) to the list.
10738 static void JimCommandMatch(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
10739 Jim_HashEntry
*he
, void *privdata
)
10741 Jim_Cmd
*cmdPtr
= (Jim_Cmd
*)he
->u
.val
;
10742 int type
= *(int *)privdata
;
10745 if (type
== JIM_CMDLIST_PROCS
&& !cmdPtr
->isproc
) {
10750 objPtr
= Jim_NewStringObj(interp
, he
->key
, -1);
10752 if (type
== JIM_CMDLIST_CHANNELS
&& !Jim_AioFilehandle(interp
, objPtr
)) {
10753 /* not a channel */
10754 Jim_FreeNewObj(interp
, objPtr
);
10758 Jim_ListAppendElement(interp
, listObjPtr
, objPtr
);
10761 /* type is JIM_CMDLIST_xxx */
10762 static Jim_Obj
*JimCommandsList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int type
)
10764 return JimHashtablePatternMatch(interp
, &interp
->commands
, patternObjPtr
, JimCommandMatch
, &type
, 1);
10767 /* Keep these in order */
10768 #define JIM_VARLIST_GLOBALS 0
10769 #define JIM_VARLIST_LOCALS 1
10770 #define JIM_VARLIST_VARS 2
10773 * Adds matching variable names to the list.
10775 static void JimVariablesMatch(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
10776 Jim_HashEntry
*he
, void *privdata
)
10778 Jim_Var
*varPtr
= (Jim_Var
*)he
->u
.val
;
10779 int mode
= *(int *)privdata
;
10781 if (mode
!= JIM_VARLIST_LOCALS
|| varPtr
->linkFramePtr
== NULL
) {
10782 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, he
->key
, -1));
10786 /* mode is JIM_VARLIST_xxx */
10787 static Jim_Obj
*JimVariablesList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int mode
)
10789 if (mode
== JIM_VARLIST_LOCALS
&& interp
->framePtr
== interp
->topFramePtr
) {
10790 /* For [info locals], if we are at top level an emtpy list
10791 * is returned. I don't agree, but we aim at compatibility (SS) */
10792 return interp
->emptyObj
;
10795 Jim_CallFrame
*framePtr
= (mode
== JIM_VARLIST_GLOBALS
) ? interp
->topFramePtr
: interp
->framePtr
;
10796 return JimHashtablePatternMatch(interp
, &framePtr
->vars
, patternObjPtr
, JimVariablesMatch
, &mode
, 1);
10800 static int JimInfoLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
10801 Jim_Obj
**objPtrPtr
, int info_level_cmd
)
10803 Jim_CallFrame
*targetCallFrame
;
10805 targetCallFrame
= JimGetCallFrameByInteger(interp
, levelObjPtr
);
10806 if (targetCallFrame
== NULL
) {
10809 /* No proc call at toplevel callframe */
10810 if (targetCallFrame
== interp
->topFramePtr
) {
10811 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
10814 if (info_level_cmd
) {
10815 *objPtrPtr
= Jim_NewListObj(interp
, targetCallFrame
->argv
, targetCallFrame
->argc
);
10818 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
10820 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->argv
[0]);
10821 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->fileNameObj
);
10822 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, targetCallFrame
->line
));
10823 *objPtrPtr
= listObj
;
10828 /* -----------------------------------------------------------------------------
10830 * ---------------------------------------------------------------------------*/
10832 /* fake [puts] -- not the real puts, just for debugging. */
10833 static int Jim_PutsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10835 if (argc
!= 2 && argc
!= 3) {
10836 Jim_WrongNumArgs(interp
, 1, argv
, "?-nonewline? string");
10840 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-nonewline")) {
10841 Jim_SetResultString(interp
, "The second argument must " "be -nonewline", -1);
10845 fputs(Jim_String(argv
[2]), stdout
);
10849 puts(Jim_String(argv
[1]));
10854 /* Helper for [+] and [*] */
10855 static int JimAddMulHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10857 jim_wide wideValue
, res
;
10858 double doubleValue
, doubleRes
;
10861 res
= (op
== JIM_EXPROP_ADD
) ? 0 : 1;
10863 for (i
= 1; i
< argc
; i
++) {
10864 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
)
10866 if (op
== JIM_EXPROP_ADD
)
10871 Jim_SetResultInt(interp
, res
);
10874 doubleRes
= (double)res
;
10875 for (; i
< argc
; i
++) {
10876 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10878 if (op
== JIM_EXPROP_ADD
)
10879 doubleRes
+= doubleValue
;
10881 doubleRes
*= doubleValue
;
10883 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10887 /* Helper for [-] and [/] */
10888 static int JimSubDivHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10890 jim_wide wideValue
, res
= 0;
10891 double doubleValue
, doubleRes
= 0;
10895 Jim_WrongNumArgs(interp
, 1, argv
, "number ?number ... number?");
10898 else if (argc
== 2) {
10899 /* The arity = 2 case is different. For [- x] returns -x,
10900 * while [/ x] returns 1/x. */
10901 if (Jim_GetWide(interp
, argv
[1], &wideValue
) != JIM_OK
) {
10902 if (Jim_GetDouble(interp
, argv
[1], &doubleValue
) != JIM_OK
) {
10906 if (op
== JIM_EXPROP_SUB
)
10907 doubleRes
= -doubleValue
;
10909 doubleRes
= 1.0 / doubleValue
;
10910 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10914 if (op
== JIM_EXPROP_SUB
) {
10916 Jim_SetResultInt(interp
, res
);
10919 doubleRes
= 1.0 / wideValue
;
10920 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10925 if (Jim_GetWide(interp
, argv
[1], &res
) != JIM_OK
) {
10926 if (Jim_GetDouble(interp
, argv
[1], &doubleRes
)
10935 for (i
= 2; i
< argc
; i
++) {
10936 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
) {
10937 doubleRes
= (double)res
;
10940 if (op
== JIM_EXPROP_SUB
)
10945 Jim_SetResultInt(interp
, res
);
10948 for (; i
< argc
; i
++) {
10949 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10951 if (op
== JIM_EXPROP_SUB
)
10952 doubleRes
-= doubleValue
;
10954 doubleRes
/= doubleValue
;
10956 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10962 static int Jim_AddCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10964 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_ADD
);
10968 static int Jim_MulCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10970 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_MUL
);
10974 static int Jim_SubCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10976 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_SUB
);
10980 static int Jim_DivCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10982 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_DIV
);
10986 static int Jim_SetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10988 if (argc
!= 2 && argc
!= 3) {
10989 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?newValue?");
10995 objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
10998 Jim_SetResult(interp
, objPtr
);
11001 /* argc == 3 case. */
11002 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
11004 Jim_SetResult(interp
, argv
[2]);
11010 * unset ?-nocomplain? ?--? ?varName ...?
11012 static int Jim_UnsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11018 if (Jim_CompareStringImmediate(interp
, argv
[i
], "--")) {
11022 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-nocomplain")) {
11031 if (Jim_UnsetVariable(interp
, argv
[i
], complain
? JIM_ERRMSG
: JIM_NONE
) != JIM_OK
11041 static int Jim_WhileCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11044 Jim_WrongNumArgs(interp
, 1, argv
, "condition body");
11048 /* The general purpose implementation of while starts here */
11050 int boolean
, retval
;
11052 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[1], &boolean
)) != JIM_OK
)
11057 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
11071 Jim_SetEmptyResult(interp
);
11076 static int Jim_ForCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11080 Jim_Obj
*varNamePtr
= NULL
;
11081 Jim_Obj
*stopVarNamePtr
= NULL
;
11084 Jim_WrongNumArgs(interp
, 1, argv
, "start test next body");
11088 /* Do the initialisation */
11089 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
) {
11093 /* And do the first test now. Better for optimisation
11094 * if we can do next/test at the bottom of the loop
11096 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11098 /* Ready to do the body as follows:
11100 * body // check retcode
11101 * next // check retcode
11102 * test // check retcode/test bool
11106 #ifdef JIM_OPTIMIZATION
11107 /* Check if the for is on the form:
11108 * for ... {$i < CONST} {incr i}
11109 * for ... {$i < $j} {incr i}
11111 if (retval
== JIM_OK
&& boolean
) {
11112 ScriptObj
*incrScript
;
11113 ExprByteCode
*expr
;
11114 jim_wide stop
, currentVal
;
11115 unsigned jim_wide procEpoch
;
11119 /* Do it only if there aren't shared arguments */
11120 expr
= JimGetExpression(interp
, argv
[2]);
11121 incrScript
= Jim_GetScript(interp
, argv
[3]);
11123 /* Ensure proper lengths to start */
11124 if (incrScript
->len
!= 3 || !expr
|| expr
->len
!= 3) {
11127 /* Ensure proper token types. */
11128 if (incrScript
->token
[1].type
!= JIM_TT_ESC
||
11129 expr
->token
[0].type
!= JIM_TT_VAR
||
11130 (expr
->token
[1].type
!= JIM_TT_EXPR_INT
&& expr
->token
[1].type
!= JIM_TT_VAR
)) {
11134 if (expr
->token
[2].type
== JIM_EXPROP_LT
) {
11137 else if (expr
->token
[2].type
== JIM_EXPROP_LTE
) {
11144 /* Update command must be incr */
11145 if (!Jim_CompareStringImmediate(interp
, incrScript
->token
[1].objPtr
, "incr")) {
11149 /* incr, expression must be about the same variable */
11150 if (!Jim_StringEqObj(incrScript
->token
[2].objPtr
, expr
->token
[0].objPtr
)) {
11154 /* Get the stop condition (must be a variable or integer) */
11155 if (expr
->token
[1].type
== JIM_TT_EXPR_INT
) {
11156 if (Jim_GetWide(interp
, expr
->token
[1].objPtr
, &stop
) == JIM_ERR
) {
11161 stopVarNamePtr
= expr
->token
[1].objPtr
;
11162 Jim_IncrRefCount(stopVarNamePtr
);
11163 /* Keep the compiler happy */
11167 /* Initialization */
11168 procEpoch
= interp
->procEpoch
;
11169 varNamePtr
= expr
->token
[0].objPtr
;
11170 Jim_IncrRefCount(varNamePtr
);
11172 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_NONE
);
11173 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
) {
11177 /* --- OPTIMIZED FOR --- */
11178 while (retval
== JIM_OK
) {
11179 /* === Check condition === */
11180 /* Note that currentVal is already set here */
11182 /* Immediate or Variable? get the 'stop' value if the latter. */
11183 if (stopVarNamePtr
) {
11184 objPtr
= Jim_GetVariable(interp
, stopVarNamePtr
, JIM_NONE
);
11185 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, &stop
) != JIM_OK
) {
11190 if (currentVal
>= stop
+ cmpOffset
) {
11195 retval
= Jim_EvalObj(interp
, argv
[4]);
11196 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11198 /* If there was a change in procedures/command continue
11199 * with the usual [for] command implementation */
11200 if (procEpoch
!= interp
->procEpoch
) {
11204 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
11207 if (objPtr
== NULL
) {
11211 if (!Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11212 currentVal
= ++JimWideValue(objPtr
);
11213 Jim_InvalidateStringRep(objPtr
);
11216 if (Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
||
11217 Jim_SetVariable(interp
, varNamePtr
, Jim_NewIntObj(interp
,
11218 ++currentVal
)) != JIM_OK
) {
11229 while (boolean
&& (retval
== JIM_OK
|| retval
== JIM_CONTINUE
)) {
11231 retval
= Jim_EvalObj(interp
, argv
[4]);
11233 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11236 retval
= Jim_EvalObj(interp
, argv
[3]);
11237 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11240 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11245 if (stopVarNamePtr
) {
11246 Jim_DecrRefCount(interp
, stopVarNamePtr
);
11249 Jim_DecrRefCount(interp
, varNamePtr
);
11252 if (retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
|| retval
== JIM_OK
) {
11253 Jim_SetEmptyResult(interp
);
11261 static int Jim_LoopCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11267 Jim_Obj
*bodyObjPtr
;
11269 if (argc
!= 5 && argc
!= 6) {
11270 Jim_WrongNumArgs(interp
, 1, argv
, "var first limit ?incr? body");
11274 if (Jim_GetWide(interp
, argv
[2], &i
) != JIM_OK
||
11275 Jim_GetWide(interp
, argv
[3], &limit
) != JIM_OK
||
11276 (argc
== 6 && Jim_GetWide(interp
, argv
[4], &incr
) != JIM_OK
)) {
11279 bodyObjPtr
= (argc
== 5) ? argv
[4] : argv
[5];
11281 retval
= Jim_SetVariable(interp
, argv
[1], argv
[2]);
11283 while (((i
< limit
&& incr
> 0) || (i
> limit
&& incr
< 0)) && retval
== JIM_OK
) {
11284 retval
= Jim_EvalObj(interp
, bodyObjPtr
);
11285 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11286 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11293 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11294 if (argv
[1]->typePtr
!= &variableObjType
) {
11295 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11299 JimWideValue(objPtr
) = i
;
11300 Jim_InvalidateStringRep(objPtr
);
11302 /* The following step is required in order to invalidate the
11303 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11304 if (argv
[1]->typePtr
!= &variableObjType
) {
11305 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11312 objPtr
= Jim_NewIntObj(interp
, i
);
11313 retval
= Jim_SetVariable(interp
, argv
[1], objPtr
);
11314 if (retval
!= JIM_OK
) {
11315 Jim_FreeNewObj(interp
, objPtr
);
11321 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
) {
11322 Jim_SetEmptyResult(interp
);
11328 /* foreach + lmap implementation. */
11329 static int JimForeachMapHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int doMap
)
11331 int result
= JIM_ERR
, i
, nbrOfLists
, *listsIdx
, *listsEnd
;
11332 int nbrOfLoops
= 0;
11333 Jim_Obj
*emptyStr
, *script
, *mapRes
= NULL
;
11335 if (argc
< 4 || argc
% 2 != 0) {
11336 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varList list ...? script");
11340 mapRes
= Jim_NewListObj(interp
, NULL
, 0);
11341 Jim_IncrRefCount(mapRes
);
11343 emptyStr
= Jim_NewEmptyStringObj(interp
);
11344 Jim_IncrRefCount(emptyStr
);
11345 script
= argv
[argc
- 1]; /* Last argument is a script */
11346 nbrOfLists
= (argc
- 1 - 1) / 2; /* argc - 'foreach' - script */
11347 listsIdx
= (int *)Jim_Alloc(nbrOfLists
* sizeof(int));
11348 listsEnd
= (int *)Jim_Alloc(nbrOfLists
* 2 * sizeof(int));
11349 /* Initialize iterators and remember max nbr elements each list */
11350 memset(listsIdx
, 0, nbrOfLists
* sizeof(int));
11351 /* Remember lengths of all lists and calculate how much rounds to loop */
11352 for (i
= 0; i
< nbrOfLists
* 2; i
+= 2) {
11356 listsEnd
[i
] = Jim_ListLength(interp
, argv
[i
+ 1]);
11357 listsEnd
[i
+ 1] = Jim_ListLength(interp
, argv
[i
+ 2]);
11358 if (listsEnd
[i
] == 0) {
11359 Jim_SetResultString(interp
, "foreach varlist is empty", -1);
11362 cnt
= div(listsEnd
[i
+ 1], listsEnd
[i
]);
11363 count
= cnt
.quot
+ (cnt
.rem
? 1 : 0);
11364 if (count
> nbrOfLoops
)
11365 nbrOfLoops
= count
;
11367 for (; nbrOfLoops
-- > 0;) {
11368 for (i
= 0; i
< nbrOfLists
; ++i
) {
11369 int varIdx
= 0, var
= i
* 2;
11371 while (varIdx
< listsEnd
[var
]) {
11372 Jim_Obj
*varName
, *ele
;
11373 int lst
= i
* 2 + 1;
11375 /* List index operations below can't fail */
11376 Jim_ListIndex(interp
, argv
[var
+ 1], varIdx
, &varName
, JIM_NONE
);
11377 if (listsIdx
[i
] < listsEnd
[lst
]) {
11378 Jim_ListIndex(interp
, argv
[lst
+ 1], listsIdx
[i
], &ele
, JIM_NONE
);
11379 /* Avoid shimmering */
11380 Jim_IncrRefCount(ele
);
11381 result
= Jim_SetVariable(interp
, varName
, ele
);
11382 Jim_DecrRefCount(interp
, ele
);
11383 if (result
== JIM_OK
) {
11384 ++listsIdx
[i
]; /* Remember next iterator of current list */
11385 ++varIdx
; /* Next variable */
11389 else if (Jim_SetVariable(interp
, varName
, emptyStr
) == JIM_OK
) {
11390 ++varIdx
; /* Next variable */
11396 switch (result
= Jim_EvalObj(interp
, script
)) {
11399 Jim_ListAppendElement(interp
, mapRes
, interp
->result
);
11413 Jim_SetResult(interp
, mapRes
);
11415 Jim_SetEmptyResult(interp
);
11418 Jim_DecrRefCount(interp
, mapRes
);
11419 Jim_DecrRefCount(interp
, emptyStr
);
11420 Jim_Free(listsIdx
);
11421 Jim_Free(listsEnd
);
11426 static int Jim_ForeachCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11428 return JimForeachMapHelper(interp
, argc
, argv
, 0);
11432 static int Jim_LmapCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11434 return JimForeachMapHelper(interp
, argc
, argv
, 1);
11438 static int Jim_IfCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11440 int boolean
, retval
, current
= 1, falsebody
= 0;
11444 /* Far not enough arguments given! */
11445 if (current
>= argc
)
11447 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[current
++], &boolean
))
11450 /* There lacks something, isn't it? */
11451 if (current
>= argc
)
11453 if (Jim_CompareStringImmediate(interp
, argv
[current
], "then"))
11455 /* Tsk tsk, no then-clause? */
11456 if (current
>= argc
)
11459 return Jim_EvalObj(interp
, argv
[current
]);
11460 /* Ok: no else-clause follows */
11461 if (++current
>= argc
) {
11462 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11465 falsebody
= current
++;
11466 if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "else")) {
11467 /* IIICKS - else-clause isn't last cmd? */
11468 if (current
!= argc
- 1)
11470 return Jim_EvalObj(interp
, argv
[current
]);
11472 else if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "elseif"))
11473 /* Ok: elseif follows meaning all the stuff
11474 * again (how boring...) */
11476 /* OOPS - else-clause is not last cmd? */
11477 else if (falsebody
!= argc
- 1)
11479 return Jim_EvalObj(interp
, argv
[falsebody
]);
11484 Jim_WrongNumArgs(interp
, 1, argv
, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11489 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11490 int Jim_CommandMatchObj(Jim_Interp
*interp
, Jim_Obj
*commandObj
, Jim_Obj
*patternObj
,
11491 Jim_Obj
*stringObj
, int nocase
)
11498 parms
[argc
++] = commandObj
;
11500 parms
[argc
++] = Jim_NewStringObj(interp
, "-nocase", -1);
11502 parms
[argc
++] = patternObj
;
11503 parms
[argc
++] = stringObj
;
11505 rc
= Jim_EvalObjVector(interp
, argc
, parms
);
11507 if (rc
!= JIM_OK
|| Jim_GetLong(interp
, Jim_GetResult(interp
), &eq
) != JIM_OK
) {
11515 { SWITCH_EXACT
, SWITCH_GLOB
, SWITCH_RE
, SWITCH_CMD
};
11518 static int Jim_SwitchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11520 int matchOpt
= SWITCH_EXACT
, opt
= 1, patCount
, i
;
11521 Jim_Obj
*command
= 0, *const *caseList
= 0, *strObj
;
11522 Jim_Obj
*script
= 0;
11526 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string "
11527 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11530 for (opt
= 1; opt
< argc
; ++opt
) {
11531 const char *option
= Jim_String(argv
[opt
]);
11533 if (*option
!= '-')
11535 else if (strncmp(option
, "--", 2) == 0) {
11539 else if (strncmp(option
, "-exact", 2) == 0)
11540 matchOpt
= SWITCH_EXACT
;
11541 else if (strncmp(option
, "-glob", 2) == 0)
11542 matchOpt
= SWITCH_GLOB
;
11543 else if (strncmp(option
, "-regexp", 2) == 0)
11544 matchOpt
= SWITCH_RE
;
11545 else if (strncmp(option
, "-command", 2) == 0) {
11546 matchOpt
= SWITCH_CMD
;
11547 if ((argc
- opt
) < 2)
11549 command
= argv
[++opt
];
11552 Jim_SetResultFormatted(interp
,
11553 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11557 if ((argc
- opt
) < 2)
11560 strObj
= argv
[opt
++];
11561 patCount
= argc
- opt
;
11562 if (patCount
== 1) {
11565 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11569 caseList
= &argv
[opt
];
11570 if (patCount
== 0 || patCount
% 2 != 0)
11572 for (i
= 0; script
== 0 && i
< patCount
; i
+= 2) {
11573 Jim_Obj
*patObj
= caseList
[i
];
11575 if (!Jim_CompareStringImmediate(interp
, patObj
, "default")
11576 || i
< (patCount
- 2)) {
11577 switch (matchOpt
) {
11579 if (Jim_StringEqObj(strObj
, patObj
))
11580 script
= caseList
[i
+ 1];
11583 if (Jim_StringMatchObj(interp
, patObj
, strObj
, 0))
11584 script
= caseList
[i
+ 1];
11587 command
= Jim_NewStringObj(interp
, "regexp", -1);
11588 /* Fall thru intentionally */
11590 int rc
= Jim_CommandMatchObj(interp
, command
, patObj
, strObj
, 0);
11592 /* After the execution of a command we need to
11593 * make sure to reconvert the object into a list
11594 * again. Only for the single-list style [switch]. */
11595 if (argc
- opt
== 1) {
11598 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11601 /* command is here already decref'd */
11606 script
= caseList
[i
+ 1];
11612 script
= caseList
[i
+ 1];
11615 for (; i
< patCount
&& Jim_CompareStringImmediate(interp
, script
, "-"); i
+= 2)
11616 script
= caseList
[i
+ 1];
11617 if (script
&& Jim_CompareStringImmediate(interp
, script
, "-")) {
11618 Jim_SetResultFormatted(interp
, "no body specified for pattern \"%#s\"", caseList
[i
- 2]);
11621 Jim_SetEmptyResult(interp
);
11623 return Jim_EvalObj(interp
, script
);
11629 static int Jim_ListCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11631 Jim_Obj
*listObjPtr
;
11633 listObjPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
11634 Jim_SetResult(interp
, listObjPtr
);
11639 static int Jim_LindexCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11641 Jim_Obj
*objPtr
, *listObjPtr
;
11646 Jim_WrongNumArgs(interp
, 1, argv
, "list index ?...?");
11650 Jim_IncrRefCount(objPtr
);
11651 for (i
= 2; i
< argc
; i
++) {
11652 listObjPtr
= objPtr
;
11653 if (Jim_GetIndex(interp
, argv
[i
], &idx
) != JIM_OK
) {
11654 Jim_DecrRefCount(interp
, listObjPtr
);
11657 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_NONE
) != JIM_OK
) {
11658 /* Returns an empty object if the index
11659 * is out of range. */
11660 Jim_DecrRefCount(interp
, listObjPtr
);
11661 Jim_SetEmptyResult(interp
);
11664 Jim_IncrRefCount(objPtr
);
11665 Jim_DecrRefCount(interp
, listObjPtr
);
11667 Jim_SetResult(interp
, objPtr
);
11668 Jim_DecrRefCount(interp
, objPtr
);
11673 static int Jim_LlengthCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11676 Jim_WrongNumArgs(interp
, 1, argv
, "list");
11679 Jim_SetResultInt(interp
, Jim_ListLength(interp
, argv
[1]));
11684 static int Jim_LsearchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11686 static const char * const options
[] = {
11687 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11691 { OPT_BOOL
, OPT_NOT
, OPT_NOCASE
, OPT_EXACT
, OPT_GLOB
, OPT_REGEXP
, OPT_ALL
, OPT_INLINE
,
11696 int opt_nocase
= 0;
11698 int opt_inline
= 0;
11699 int opt_match
= OPT_EXACT
;
11702 Jim_Obj
*listObjPtr
= NULL
;
11703 Jim_Obj
*commandObj
= NULL
;
11707 Jim_WrongNumArgs(interp
, 1, argv
,
11708 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11712 for (i
= 1; i
< argc
- 2; i
++) {
11715 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
11737 if (i
>= argc
- 2) {
11740 commandObj
= argv
[++i
];
11745 opt_match
= option
;
11753 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11755 if (opt_match
== OPT_REGEXP
) {
11756 commandObj
= Jim_NewStringObj(interp
, "regexp", -1);
11759 Jim_IncrRefCount(commandObj
);
11762 listlen
= Jim_ListLength(interp
, argv
[0]);
11763 for (i
= 0; i
< listlen
; i
++) {
11767 Jim_ListIndex(interp
, argv
[0], i
, &objPtr
, JIM_NONE
);
11768 switch (opt_match
) {
11770 eq
= Jim_StringCompareObj(interp
, objPtr
, argv
[1], opt_nocase
) == 0;
11774 eq
= Jim_StringMatchObj(interp
, argv
[1], objPtr
, opt_nocase
);
11779 eq
= Jim_CommandMatchObj(interp
, commandObj
, argv
[1], objPtr
, opt_nocase
);
11782 Jim_FreeNewObj(interp
, listObjPtr
);
11790 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11791 if (!eq
&& opt_bool
&& opt_not
&& !opt_all
) {
11795 if ((!opt_bool
&& eq
== !opt_not
) || (opt_bool
&& (eq
|| opt_all
))) {
11796 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11797 Jim_Obj
*resultObj
;
11800 resultObj
= Jim_NewIntObj(interp
, eq
^ opt_not
);
11802 else if (!opt_inline
) {
11803 resultObj
= Jim_NewIntObj(interp
, i
);
11806 resultObj
= objPtr
;
11810 Jim_ListAppendElement(interp
, listObjPtr
, resultObj
);
11813 Jim_SetResult(interp
, resultObj
);
11820 Jim_SetResult(interp
, listObjPtr
);
11825 Jim_SetResultBool(interp
, opt_not
);
11827 else if (!opt_inline
) {
11828 Jim_SetResultInt(interp
, -1);
11834 Jim_DecrRefCount(interp
, commandObj
);
11840 static int Jim_LappendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11842 Jim_Obj
*listObjPtr
;
11846 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
11849 listObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
11851 /* Create the list if it does not exists */
11852 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11853 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11854 Jim_FreeNewObj(interp
, listObjPtr
);
11858 shared
= Jim_IsShared(listObjPtr
);
11860 listObjPtr
= Jim_DuplicateObj(interp
, listObjPtr
);
11861 for (i
= 2; i
< argc
; i
++)
11862 Jim_ListAppendElement(interp
, listObjPtr
, argv
[i
]);
11863 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11865 Jim_FreeNewObj(interp
, listObjPtr
);
11868 Jim_SetResult(interp
, listObjPtr
);
11873 static int Jim_LinsertCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11879 Jim_WrongNumArgs(interp
, 1, argv
, "list index element " "?element ...?");
11883 if (Jim_IsShared(listPtr
))
11884 listPtr
= Jim_DuplicateObj(interp
, listPtr
);
11885 if (Jim_GetIndex(interp
, argv
[2], &idx
) != JIM_OK
)
11887 len
= Jim_ListLength(interp
, listPtr
);
11891 idx
= len
+ idx
+ 1;
11892 Jim_ListInsertElements(interp
, listPtr
, idx
, argc
- 3, &argv
[3]);
11893 Jim_SetResult(interp
, listPtr
);
11896 if (listPtr
!= argv
[1]) {
11897 Jim_FreeNewObj(interp
, listPtr
);
11903 static int Jim_LreplaceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11905 int first
, last
, len
, rangeLen
;
11907 Jim_Obj
*newListObj
;
11910 Jim_WrongNumArgs(interp
, 1, argv
, "list first last ?element element ...?");
11913 if (Jim_GetIndex(interp
, argv
[2], &first
) != JIM_OK
||
11914 Jim_GetIndex(interp
, argv
[3], &last
) != JIM_OK
) {
11919 len
= Jim_ListLength(interp
, listObj
);
11921 first
= JimRelToAbsIndex(len
, first
);
11922 last
= JimRelToAbsIndex(len
, last
);
11923 JimRelToAbsRange(len
, &first
, &last
, &rangeLen
);
11925 /* Now construct a new list which consists of:
11926 * <elements before first> <supplied elements> <elements after last>
11929 /* Check to see if trying to replace past the end of the list */
11931 /* OK. Not past the end */
11933 else if (len
== 0) {
11934 /* Special for empty list, adjust first to 0 */
11938 Jim_SetResultString(interp
, "list doesn't contain element ", -1);
11939 Jim_AppendObj(interp
, Jim_GetResult(interp
), argv
[2]);
11943 /* Add the first set of elements */
11944 newListObj
= Jim_NewListObj(interp
, listObj
->internalRep
.listValue
.ele
, first
);
11946 /* Add supplied elements */
11947 ListInsertElements(newListObj
, -1, argc
- 4, argv
+ 4);
11949 /* Add the remaining elements */
11950 ListInsertElements(newListObj
, -1, len
- first
- rangeLen
, listObj
->internalRep
.listValue
.ele
+ first
+ rangeLen
);
11952 Jim_SetResult(interp
, newListObj
);
11957 static int Jim_LsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11960 Jim_WrongNumArgs(interp
, 1, argv
, "listVar ?index...? newVal");
11963 else if (argc
== 3) {
11964 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
11966 Jim_SetResult(interp
, argv
[2]);
11969 if (Jim_SetListIndex(interp
, argv
[1], argv
+ 2, argc
- 3, argv
[argc
- 1])
11976 static int Jim_LsortCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const argv
[])
11978 static const char * const options
[] = {
11979 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11982 { OPT_ASCII
, OPT_NOCASE
, OPT_INCREASING
, OPT_DECREASING
, OPT_COMMAND
, OPT_INTEGER
, OPT_INDEX
};
11987 struct lsort_info info
;
11990 Jim_WrongNumArgs(interp
, 1, argv
, "?options? list");
11994 info
.type
= JIM_LSORT_ASCII
;
11997 info
.command
= NULL
;
11998 info
.interp
= interp
;
12000 for (i
= 1; i
< (argc
- 1); i
++) {
12003 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
)
12008 info
.type
= JIM_LSORT_ASCII
;
12011 info
.type
= JIM_LSORT_NOCASE
;
12014 info
.type
= JIM_LSORT_INTEGER
;
12016 case OPT_INCREASING
:
12019 case OPT_DECREASING
:
12023 if (i
>= (argc
- 2)) {
12024 Jim_SetResultString(interp
, "\"-command\" option must be followed by comparison command", -1);
12027 info
.type
= JIM_LSORT_COMMAND
;
12028 info
.command
= argv
[i
+ 1];
12032 if (i
>= (argc
- 2)) {
12033 Jim_SetResultString(interp
, "\"-index\" option must be followed by list index", -1);
12036 if (Jim_GetIndex(interp
, argv
[i
+ 1], &info
.index
) != JIM_OK
) {
12044 resObj
= Jim_DuplicateObj(interp
, argv
[argc
- 1]);
12045 retCode
= ListSortElements(interp
, resObj
, &info
);
12046 if (retCode
== JIM_OK
) {
12047 Jim_SetResult(interp
, resObj
);
12050 Jim_FreeNewObj(interp
, resObj
);
12056 static int Jim_AppendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12058 Jim_Obj
*stringObjPtr
;
12062 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
12066 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
12072 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
12073 if (!stringObjPtr
) {
12074 /* Create the string if it doesn't exist */
12075 stringObjPtr
= Jim_NewEmptyStringObj(interp
);
12078 else if (Jim_IsShared(stringObjPtr
)) {
12080 stringObjPtr
= Jim_DuplicateObj(interp
, stringObjPtr
);
12082 for (i
= 2; i
< argc
; i
++) {
12083 Jim_AppendObj(interp
, stringObjPtr
, argv
[i
]);
12085 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
) != JIM_OK
) {
12087 Jim_FreeNewObj(interp
, stringObjPtr
);
12092 Jim_SetResult(interp
, stringObjPtr
);
12097 static int Jim_DebugCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12099 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12100 static const char * const options
[] = {
12101 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12107 OPT_REFCOUNT
, OPT_OBJCOUNT
, OPT_OBJECTS
, OPT_INVSTR
, OPT_SCRIPTLEN
,
12108 OPT_EXPRLEN
, OPT_EXPRBC
, OPT_SHOW
,
12113 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?...?");
12116 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
)
12118 if (option
== OPT_REFCOUNT
) {
12120 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12123 Jim_SetResultInt(interp
, argv
[2]->refCount
);
12126 else if (option
== OPT_OBJCOUNT
) {
12127 int freeobj
= 0, liveobj
= 0;
12132 Jim_WrongNumArgs(interp
, 2, argv
, "");
12135 /* Count the number of free objects. */
12136 objPtr
= interp
->freeList
;
12139 objPtr
= objPtr
->nextObjPtr
;
12141 /* Count the number of live objects. */
12142 objPtr
= interp
->liveList
;
12145 objPtr
= objPtr
->nextObjPtr
;
12147 /* Set the result string and return. */
12148 sprintf(buf
, "free %d used %d", freeobj
, liveobj
);
12149 Jim_SetResultString(interp
, buf
, -1);
12152 else if (option
== OPT_OBJECTS
) {
12153 Jim_Obj
*objPtr
, *listObjPtr
, *subListObjPtr
;
12155 /* Count the number of live objects. */
12156 objPtr
= interp
->liveList
;
12157 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12160 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "";
12162 subListObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12163 sprintf(buf
, "%p", objPtr
);
12164 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
12165 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, type
, -1));
12166 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewIntObj(interp
, objPtr
->refCount
));
12167 Jim_ListAppendElement(interp
, subListObjPtr
, objPtr
);
12168 Jim_ListAppendElement(interp
, listObjPtr
, subListObjPtr
);
12169 objPtr
= objPtr
->nextObjPtr
;
12171 Jim_SetResult(interp
, listObjPtr
);
12174 else if (option
== OPT_INVSTR
) {
12178 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12182 if (objPtr
->typePtr
!= NULL
)
12183 Jim_InvalidateStringRep(objPtr
);
12184 Jim_SetEmptyResult(interp
);
12187 else if (option
== OPT_SHOW
) {
12192 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12195 s
= Jim_GetString(argv
[2], &len
);
12197 charlen
= utf8_strlen(s
, len
);
12201 printf("refcount: %d, type: %s\n", argv
[2]->refCount
, JimObjTypeName(argv
[2]));
12202 printf("chars (%d): <<%s>>\n", charlen
, s
);
12203 printf("bytes (%d):", len
);
12205 printf(" %02x", (unsigned char)*s
++);
12210 else if (option
== OPT_SCRIPTLEN
) {
12214 Jim_WrongNumArgs(interp
, 2, argv
, "script");
12217 script
= Jim_GetScript(interp
, argv
[2]);
12218 Jim_SetResultInt(interp
, script
->len
);
12221 else if (option
== OPT_EXPRLEN
) {
12222 ExprByteCode
*expr
;
12225 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12228 expr
= JimGetExpression(interp
, argv
[2]);
12231 Jim_SetResultInt(interp
, expr
->len
);
12234 else if (option
== OPT_EXPRBC
) {
12236 ExprByteCode
*expr
;
12240 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12243 expr
= JimGetExpression(interp
, argv
[2]);
12246 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
12247 for (i
= 0; i
< expr
->len
; i
++) {
12249 const Jim_ExprOperator
*op
;
12250 Jim_Obj
*obj
= expr
->token
[i
].objPtr
;
12252 switch (expr
->token
[i
].type
) {
12253 case JIM_TT_EXPR_INT
:
12256 case JIM_TT_EXPR_DOUBLE
:
12265 case JIM_TT_DICTSUGAR
:
12266 type
= "dictsugar";
12268 case JIM_TT_EXPRSUGAR
:
12269 type
= "exprsugar";
12278 op
= JimExprOperatorInfoByOpcode(expr
->token
[i
].type
);
12285 obj
= Jim_NewStringObj(interp
, op
? op
->name
: "", -1);
12288 Jim_ListAppendElement(interp
, objPtr
, Jim_NewStringObj(interp
, type
, -1));
12289 Jim_ListAppendElement(interp
, objPtr
, obj
);
12291 Jim_SetResult(interp
, objPtr
);
12295 Jim_SetResultString(interp
,
12296 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12300 #endif /* JIM_BOOTSTRAP */
12301 #if !defined(JIM_DEBUG_COMMAND)
12302 Jim_SetResultString(interp
, "unsupported", -1);
12308 static int Jim_EvalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12313 Jim_WrongNumArgs(interp
, 1, argv
, "script ?...?");
12318 rc
= Jim_EvalObj(interp
, argv
[1]);
12321 rc
= Jim_EvalObj(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12324 if (rc
== JIM_ERR
) {
12325 /* eval is "interesting", so add a stack frame here */
12326 interp
->addStackTrace
++;
12332 static int Jim_UplevelCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12336 Jim_CallFrame
*savedCallFrame
, *targetCallFrame
;
12340 /* Save the old callframe pointer */
12341 savedCallFrame
= interp
->framePtr
;
12343 /* Lookup the target frame pointer */
12344 str
= Jim_String(argv
[1]);
12345 if ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#') {
12346 targetCallFrame
=Jim_GetCallFrameByLevel(interp
, argv
[1]);
12351 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12353 if (targetCallFrame
== NULL
) {
12358 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12361 /* Eval the code in the target callframe. */
12362 interp
->framePtr
= targetCallFrame
;
12364 retcode
= Jim_EvalObj(interp
, argv
[1]);
12367 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12368 Jim_IncrRefCount(objPtr
);
12369 retcode
= Jim_EvalObj(interp
, objPtr
);
12370 Jim_DecrRefCount(interp
, objPtr
);
12372 interp
->framePtr
= savedCallFrame
;
12376 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12382 static int Jim_ExprCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12384 Jim_Obj
*exprResultPtr
;
12388 retcode
= Jim_EvalExpression(interp
, argv
[1], &exprResultPtr
);
12390 else if (argc
> 2) {
12393 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12394 Jim_IncrRefCount(objPtr
);
12395 retcode
= Jim_EvalExpression(interp
, objPtr
, &exprResultPtr
);
12396 Jim_DecrRefCount(interp
, objPtr
);
12399 Jim_WrongNumArgs(interp
, 1, argv
, "expression ?...?");
12402 if (retcode
!= JIM_OK
)
12404 Jim_SetResult(interp
, exprResultPtr
);
12405 Jim_DecrRefCount(interp
, exprResultPtr
);
12410 static int Jim_BreakCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12413 Jim_WrongNumArgs(interp
, 1, argv
, "");
12420 static int Jim_ContinueCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12423 Jim_WrongNumArgs(interp
, 1, argv
, "");
12426 return JIM_CONTINUE
;
12430 static int Jim_ReturnCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12433 Jim_Obj
*stackTraceObj
= NULL
;
12434 Jim_Obj
*errorCodeObj
= NULL
;
12435 int returnCode
= JIM_OK
;
12438 for (i
= 1; i
< argc
- 1; i
+= 2) {
12439 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-code")) {
12440 if (Jim_GetReturnCode(interp
, argv
[i
+ 1], &returnCode
) == JIM_ERR
) {
12444 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorinfo")) {
12445 stackTraceObj
= argv
[i
+ 1];
12447 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorcode")) {
12448 errorCodeObj
= argv
[i
+ 1];
12450 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-level")) {
12451 if (Jim_GetLong(interp
, argv
[i
+ 1], &level
) != JIM_OK
|| level
< 0) {
12452 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", argv
[i
+ 1]);
12461 if (i
!= argc
- 1 && i
!= argc
) {
12462 Jim_WrongNumArgs(interp
, 1, argv
,
12463 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12466 /* If a stack trace is supplied and code is error, set the stack trace */
12467 if (stackTraceObj
&& returnCode
== JIM_ERR
) {
12468 JimSetStackTrace(interp
, stackTraceObj
);
12470 /* If an error code list is supplied, set the global $errorCode */
12471 if (errorCodeObj
&& returnCode
== JIM_ERR
) {
12472 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCodeObj
);
12474 interp
->returnCode
= returnCode
;
12475 interp
->returnLevel
= level
;
12477 if (i
== argc
- 1) {
12478 Jim_SetResult(interp
, argv
[i
]);
12484 static int Jim_TailcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12488 objPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
12489 Jim_SetResult(interp
, objPtr
);
12494 static int Jim_ProcCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12496 if (argc
!= 4 && argc
!= 5) {
12497 Jim_WrongNumArgs(interp
, 1, argv
, "name arglist ?statics? body");
12502 return JimCreateProcedure(interp
, argv
[1], argv
[2], NULL
, argv
[3]);
12505 return JimCreateProcedure(interp
, argv
[1], argv
[2], argv
[3], argv
[4]);
12510 static int Jim_LocalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12514 /* Evaluate the arguments with 'local' in force */
12516 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12520 /* If OK, and the result is a proc, add it to the list of local procs */
12521 if (retcode
== 0) {
12522 const char *procname
= Jim_String(Jim_GetResult(interp
));
12524 if (Jim_FindHashEntry(&interp
->commands
, procname
) == NULL
) {
12525 Jim_SetResultFormatted(interp
, "not a proc: \"%s\"", procname
);
12528 if (interp
->localProcs
== NULL
) {
12529 interp
->localProcs
= Jim_Alloc(sizeof(*interp
->localProcs
));
12530 Jim_InitStack(interp
->localProcs
);
12532 Jim_StackPush(interp
->localProcs
, Jim_StrDup(procname
));
12539 static int Jim_UpcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12542 Jim_WrongNumArgs(interp
, 1, argv
, "cmd ?args ...?");
12548 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, argv
[1], JIM_ERRMSG
);
12549 if (cmdPtr
== NULL
|| !cmdPtr
->isproc
|| !cmdPtr
->u
.proc
.prevCmd
) {
12550 Jim_SetResultFormatted(interp
, "no previous proc: \"%#s\"", argv
[1]);
12553 /* OK. Mark this command as being in an upcall */
12554 cmdPtr
->u
.proc
.upcall
++;
12555 JimIncrCmdRefCount(cmdPtr
);
12557 /* Invoke the command as normal */
12558 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12560 /* No longer in an upcall */
12561 cmdPtr
->u
.proc
.upcall
--;
12562 JimDecrCmdRefCount(interp
, cmdPtr
);
12569 static int Jim_ConcatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12571 Jim_SetResult(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12576 static int Jim_UpvarCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12579 Jim_CallFrame
*targetCallFrame
;
12581 /* Lookup the target frame pointer */
12582 if (argc
> 3 && (argc
% 2 == 0)) {
12583 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, argv
[1]);
12588 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12590 if (targetCallFrame
== NULL
) {
12594 /* Check for arity */
12596 Jim_WrongNumArgs(interp
, 1, argv
, "?level? otherVar localVar ?otherVar localVar ...?");
12600 /* Now... for every other/local couple: */
12601 for (i
= 1; i
< argc
; i
+= 2) {
12602 if (Jim_SetVariableLink(interp
, argv
[i
+ 1], argv
[i
], targetCallFrame
) != JIM_OK
)
12609 static int Jim_GlobalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12614 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
12617 /* Link every var to the toplevel having the same name */
12618 if (interp
->framePtr
->level
== 0)
12619 return JIM_OK
; /* global at toplevel... */
12620 for (i
= 1; i
< argc
; i
++) {
12621 /* global ::blah does nothing */
12622 const char *name
= Jim_String(argv
[i
]);
12623 if (name
[0] != ':' || name
[1] != ':') {
12624 if (Jim_SetVariableLink(interp
, argv
[i
], argv
[i
], interp
->topFramePtr
) != JIM_OK
)
12631 /* does the [string map] operation. On error NULL is returned,
12632 * otherwise a new string object with the result, having refcount = 0,
12634 static Jim_Obj
*JimStringMap(Jim_Interp
*interp
, Jim_Obj
*mapListObjPtr
,
12635 Jim_Obj
*objPtr
, int nocase
)
12638 const char *str
, *noMatchStart
= NULL
;
12640 Jim_Obj
*resultObjPtr
;
12642 numMaps
= Jim_ListLength(interp
, mapListObjPtr
);
12644 Jim_SetResultString(interp
, "list must contain an even number of elements", -1);
12648 str
= Jim_String(objPtr
);
12649 strLen
= Jim_Utf8Length(interp
, objPtr
);
12652 resultObjPtr
= Jim_NewStringObj(interp
, "", 0);
12654 for (i
= 0; i
< numMaps
; i
+= 2) {
12659 Jim_ListIndex(interp
, mapListObjPtr
, i
, &objPtr
, JIM_NONE
);
12660 k
= Jim_String(objPtr
);
12661 kl
= Jim_Utf8Length(interp
, objPtr
);
12663 if (strLen
>= kl
&& kl
) {
12666 rc
= JimStringCompareNoCase(str
, k
, kl
);
12669 rc
= JimStringCompare(str
, kl
, k
, kl
);
12672 if (noMatchStart
) {
12673 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12674 noMatchStart
= NULL
;
12676 Jim_ListIndex(interp
, mapListObjPtr
, i
+ 1, &objPtr
, JIM_NONE
);
12677 Jim_AppendObj(interp
, resultObjPtr
, objPtr
);
12678 str
+= utf8_index(str
, kl
);
12684 if (i
== numMaps
) { /* no match */
12686 if (noMatchStart
== NULL
)
12687 noMatchStart
= str
;
12688 str
+= utf8_tounicode(str
, &c
);
12692 if (noMatchStart
) {
12693 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12695 return resultObjPtr
;
12699 static int Jim_StringCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12704 static const char * const options
[] = {
12705 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12706 "repeat", "reverse", "index", "first", "last",
12707 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12711 OPT_BYTELENGTH
, OPT_LENGTH
, OPT_COMPARE
, OPT_MATCH
, OPT_EQUAL
, OPT_IS
, OPT_BYTERANGE
, OPT_RANGE
, OPT_MAP
,
12712 OPT_REPEAT
, OPT_REVERSE
, OPT_INDEX
, OPT_FIRST
, OPT_LAST
,
12713 OPT_TRIM
, OPT_TRIMLEFT
, OPT_TRIMRIGHT
, OPT_TOLOWER
, OPT_TOUPPER
12715 static const char * const nocase_options
[] = {
12720 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
12723 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
,
12724 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
)
12729 case OPT_BYTELENGTH
:
12731 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12734 if (option
== OPT_LENGTH
) {
12735 len
= Jim_Utf8Length(interp
, argv
[2]);
12738 len
= Jim_Length(argv
[2]);
12740 Jim_SetResultInt(interp
, len
);
12747 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12748 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12749 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? string1 string2");
12752 if (opt_case
== 0) {
12755 if (option
== OPT_COMPARE
|| !opt_case
) {
12756 Jim_SetResultInt(interp
, Jim_StringCompareObj(interp
, argv
[2], argv
[3], !opt_case
));
12759 Jim_SetResultBool(interp
, Jim_StringEqObj(argv
[2], argv
[3]));
12766 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12767 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12768 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? pattern string");
12771 if (opt_case
== 0) {
12774 Jim_SetResultBool(interp
, Jim_StringMatchObj(interp
, argv
[2], argv
[3], !opt_case
));
12782 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12783 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12784 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? mapList string");
12788 if (opt_case
== 0) {
12791 objPtr
= JimStringMap(interp
, argv
[2], argv
[3], !opt_case
);
12792 if (objPtr
== NULL
) {
12795 Jim_SetResult(interp
, objPtr
);
12800 case OPT_BYTERANGE
:{
12804 Jim_WrongNumArgs(interp
, 2, argv
, "string first last");
12807 if (option
== OPT_RANGE
) {
12808 objPtr
= Jim_StringRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12812 objPtr
= Jim_StringByteRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12815 if (objPtr
== NULL
) {
12818 Jim_SetResult(interp
, objPtr
);
12827 Jim_WrongNumArgs(interp
, 2, argv
, "string count");
12830 if (Jim_GetWide(interp
, argv
[3], &count
) != JIM_OK
) {
12833 objPtr
= Jim_NewStringObj(interp
, "", 0);
12836 Jim_AppendObj(interp
, objPtr
, argv
[2]);
12839 Jim_SetResult(interp
, objPtr
);
12850 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12854 str
= Jim_GetString(argv
[2], &len
);
12855 buf
= Jim_Alloc(len
+ 1);
12858 for (i
= 0; i
< len
; ) {
12860 int l
= utf8_tounicode(str
, &c
);
12861 memcpy(p
- l
, str
, l
);
12866 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
12875 Jim_WrongNumArgs(interp
, 2, argv
, "string index");
12878 if (Jim_GetIndex(interp
, argv
[3], &idx
) != JIM_OK
) {
12881 str
= Jim_String(argv
[2]);
12882 len
= Jim_Utf8Length(interp
, argv
[2]);
12883 if (idx
!= INT_MIN
&& idx
!= INT_MAX
) {
12884 idx
= JimRelToAbsIndex(len
, idx
);
12886 if (idx
< 0 || idx
>= len
|| str
== NULL
) {
12887 Jim_SetResultString(interp
, "", 0);
12889 else if (len
== Jim_Length(argv
[2])) {
12890 /* ASCII optimisation */
12891 Jim_SetResultString(interp
, str
+ idx
, 1);
12895 int i
= utf8_index(str
, idx
);
12896 Jim_SetResultString(interp
, str
+ i
, utf8_tounicode(str
+ i
, &c
));
12903 int idx
= 0, l1
, l2
;
12904 const char *s1
, *s2
;
12906 if (argc
!= 4 && argc
!= 5) {
12907 Jim_WrongNumArgs(interp
, 2, argv
, "subString string ?index?");
12910 s1
= Jim_String(argv
[2]);
12911 s2
= Jim_String(argv
[3]);
12912 l1
= Jim_Utf8Length(interp
, argv
[2]);
12913 l2
= Jim_Utf8Length(interp
, argv
[3]);
12915 if (Jim_GetIndex(interp
, argv
[4], &idx
) != JIM_OK
) {
12918 idx
= JimRelToAbsIndex(l2
, idx
);
12920 else if (option
== OPT_LAST
) {
12923 if (option
== OPT_FIRST
) {
12924 Jim_SetResultInt(interp
, JimStringFirst(s1
, l1
, s2
, l2
, idx
));
12928 Jim_SetResultInt(interp
, JimStringLastUtf8(s1
, l1
, s2
, idx
));
12930 Jim_SetResultInt(interp
, JimStringLast(s1
, l1
, s2
, idx
));
12938 case OPT_TRIMRIGHT
:{
12939 Jim_Obj
*trimchars
;
12941 if (argc
!= 3 && argc
!= 4) {
12942 Jim_WrongNumArgs(interp
, 2, argv
, "string ?trimchars?");
12945 trimchars
= (argc
== 4 ? argv
[3] : NULL
);
12946 if (option
== OPT_TRIM
) {
12947 Jim_SetResult(interp
, JimStringTrim(interp
, argv
[2], trimchars
));
12949 else if (option
== OPT_TRIMLEFT
) {
12950 Jim_SetResult(interp
, JimStringTrimLeft(interp
, argv
[2], trimchars
));
12952 else if (option
== OPT_TRIMRIGHT
) {
12953 Jim_SetResult(interp
, JimStringTrimRight(interp
, argv
[2], trimchars
));
12961 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12964 if (option
== OPT_TOLOWER
) {
12965 Jim_SetResult(interp
, JimStringToLower(interp
, argv
[2]));
12968 Jim_SetResult(interp
, JimStringToUpper(interp
, argv
[2]));
12973 if (argc
== 4 || (argc
== 5 && Jim_CompareStringImmediate(interp
, argv
[3], "-strict"))) {
12974 return JimStringIs(interp
, argv
[argc
- 1], argv
[2], argc
== 5);
12976 Jim_WrongNumArgs(interp
, 2, argv
, "class ?-strict? str");
12983 static int Jim_TimeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12986 jim_wide start
, elapsed
;
12988 const char *fmt
= "%" JIM_WIDE_MODIFIER
" microseconds per iteration";
12991 Jim_WrongNumArgs(interp
, 1, argv
, "script ?count?");
12995 if (Jim_GetLong(interp
, argv
[2], &count
) != JIM_OK
)
13001 start
= JimClock();
13005 retval
= Jim_EvalObj(interp
, argv
[1]);
13006 if (retval
!= JIM_OK
) {
13010 elapsed
= JimClock() - start
;
13011 sprintf(buf
, fmt
, count
== 0 ? 0 : elapsed
/ count
);
13012 Jim_SetResultString(interp
, buf
, -1);
13017 static int Jim_ExitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13022 Jim_WrongNumArgs(interp
, 1, argv
, "?exitCode?");
13026 if (Jim_GetLong(interp
, argv
[1], &exitCode
) != JIM_OK
)
13029 interp
->exitCode
= exitCode
;
13034 static int Jim_CatchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13040 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
13041 jim_wide ignore_mask
= (1 << JIM_EXIT
) | (1 << JIM_EVAL
) | (1 << JIM_SIGNAL
);
13042 static const int max_ignore_code
= sizeof(ignore_mask
) * 8;
13044 /* Reset the error code before catch.
13045 * Note that this is not strictly correct.
13047 Jim_SetGlobalVariableStr(interp
, "errorCode", Jim_NewStringObj(interp
, "NONE", -1));
13049 for (i
= 1; i
< argc
- 1; i
++) {
13050 const char *arg
= Jim_String(argv
[i
]);
13054 /* It's a pity we can't use Jim_GetEnum here :-( */
13055 if (strcmp(arg
, "--") == 0) {
13063 if (strncmp(arg
, "-no", 3) == 0) {
13072 if (Jim_StringToWide(arg
, &option
, 10) != JIM_OK
) {
13076 option
= Jim_FindByName(arg
, jimReturnCodes
, jimReturnCodesSize
);
13083 ignore_mask
|= (1 << option
);
13086 ignore_mask
&= ~(1 << option
);
13091 if (argc
< 1 || argc
> 3) {
13093 Jim_WrongNumArgs(interp
, 1, argv
,
13094 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13099 if ((ignore_mask
& (1 << JIM_SIGNAL
)) == 0) {
13103 interp
->signal_level
+= sig
;
13104 if (interp
->signal_level
&& interp
->sigmask
) {
13105 /* If a signal is set, don't even try to execute the body */
13106 exitCode
= JIM_SIGNAL
;
13109 exitCode
= Jim_EvalObj(interp
, argv
[0]);
13111 interp
->signal_level
-= sig
;
13113 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13114 if (exitCode
>= 0 && exitCode
< max_ignore_code
&& ((1 << exitCode
) & ignore_mask
)) {
13115 /* Not caught, pass it up */
13119 if (sig
&& exitCode
== JIM_SIGNAL
) {
13120 /* Catch the signal at this level */
13121 if (interp
->signal_set_result
) {
13122 interp
->signal_set_result(interp
, interp
->sigmask
);
13125 Jim_SetResultInt(interp
, interp
->sigmask
);
13127 interp
->sigmask
= 0;
13131 if (Jim_SetVariable(interp
, argv
[1], Jim_GetResult(interp
)) != JIM_OK
) {
13135 Jim_Obj
*optListObj
= Jim_NewListObj(interp
, NULL
, 0);
13137 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-code", -1));
13138 Jim_ListAppendElement(interp
, optListObj
,
13139 Jim_NewIntObj(interp
, exitCode
== JIM_RETURN
? interp
->returnCode
: exitCode
));
13140 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-level", -1));
13141 Jim_ListAppendElement(interp
, optListObj
, Jim_NewIntObj(interp
, interp
->returnLevel
));
13142 if (exitCode
== JIM_ERR
) {
13143 Jim_Obj
*errorCode
;
13144 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorinfo",
13146 Jim_ListAppendElement(interp
, optListObj
, interp
->stackTrace
);
13148 errorCode
= Jim_GetGlobalVariableStr(interp
, "errorCode", JIM_NONE
);
13150 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorcode", -1));
13151 Jim_ListAppendElement(interp
, optListObj
, errorCode
);
13154 if (Jim_SetVariable(interp
, argv
[2], optListObj
) != JIM_OK
) {
13159 Jim_SetResultInt(interp
, exitCode
);
13163 #ifdef JIM_REFERENCES
13166 static int Jim_RefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13168 if (argc
!= 3 && argc
!= 4) {
13169 Jim_WrongNumArgs(interp
, 1, argv
, "string tag ?finalizer?");
13173 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], NULL
));
13176 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], argv
[3]));
13182 static int Jim_GetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13184 Jim_Reference
*refPtr
;
13187 Jim_WrongNumArgs(interp
, 1, argv
, "reference");
13190 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13192 Jim_SetResult(interp
, refPtr
->objPtr
);
13197 static int Jim_SetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13199 Jim_Reference
*refPtr
;
13202 Jim_WrongNumArgs(interp
, 1, argv
, "reference newValue");
13205 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13207 Jim_IncrRefCount(argv
[2]);
13208 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
13209 refPtr
->objPtr
= argv
[2];
13210 Jim_SetResult(interp
, argv
[2]);
13215 static int Jim_CollectCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13218 Jim_WrongNumArgs(interp
, 1, argv
, "");
13221 Jim_SetResultInt(interp
, Jim_Collect(interp
));
13223 /* Free all the freed objects. */
13224 while (interp
->freeList
) {
13225 Jim_Obj
*nextObjPtr
= interp
->freeList
->nextObjPtr
;
13226 Jim_Free(interp
->freeList
);
13227 interp
->freeList
= nextObjPtr
;
13233 /* [finalize] reference ?newValue? */
13234 static int Jim_FinalizeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13236 if (argc
!= 2 && argc
!= 3) {
13237 Jim_WrongNumArgs(interp
, 1, argv
, "reference ?finalizerProc?");
13241 Jim_Obj
*cmdNamePtr
;
13243 if (Jim_GetFinalizer(interp
, argv
[1], &cmdNamePtr
) != JIM_OK
)
13245 if (cmdNamePtr
!= NULL
) /* otherwise the null string is returned. */
13246 Jim_SetResult(interp
, cmdNamePtr
);
13249 if (Jim_SetFinalizer(interp
, argv
[1], argv
[2]) != JIM_OK
)
13251 Jim_SetResult(interp
, argv
[2]);
13256 /* [info references] */
13257 static int JimInfoReferences(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13259 Jim_Obj
*listObjPtr
;
13260 Jim_HashTableIterator
*htiter
;
13263 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13265 htiter
= Jim_GetHashTableIterator(&interp
->references
);
13266 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
13267 char buf
[JIM_REFERENCE_SPACE
];
13268 Jim_Reference
*refPtr
= he
->u
.val
;
13269 const jim_wide
*refId
= he
->key
;
13271 JimFormatReference(buf
, refPtr
, *refId
);
13272 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
13274 Jim_FreeHashTableIterator(htiter
);
13275 Jim_SetResult(interp
, listObjPtr
);
13281 static int Jim_RenameCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13283 const char *oldName
, *newName
;
13286 Jim_WrongNumArgs(interp
, 1, argv
, "oldName newName");
13290 if (JimValidName(interp
, "new procedure", argv
[2])) {
13294 oldName
= Jim_String(argv
[1]);
13295 newName
= Jim_String(argv
[2]);
13296 return Jim_RenameCommand(interp
, oldName
, newName
);
13299 static void JimDictMatchKeys(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
13300 Jim_HashEntry
*he
, void *privdata
)
13302 Jim_ListAppendElement(interp
, listObjPtr
, (Jim_Obj
*)he
->key
);
13305 int Jim_DictKeys(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*patternObjPtr
)
13307 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
13310 Jim_SetResult(interp
, JimHashtablePatternMatch(interp
, objPtr
->internalRep
.ptr
, patternObjPtr
, JimDictMatchKeys
, NULL
, 0));
13314 static void JimDictMatchValues(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
,
13315 Jim_HashEntry
*he
, void *privdata
)
13317 Jim_ListAppendElement(interp
, listObjPtr
, (Jim_Obj
*)he
->key
);
13318 Jim_ListAppendElement(interp
, listObjPtr
, (Jim_Obj
*)he
->u
.val
);
13321 int Jim_DictValues(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*patternObjPtr
)
13323 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
13326 Jim_SetResult(interp
, JimHashtablePatternMatch(interp
, objPtr
->internalRep
.ptr
, patternObjPtr
, JimDictMatchValues
, NULL
, 0));
13330 int Jim_DictSize(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
13332 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
13335 return ((Jim_HashTable
*)objPtr
->internalRep
.ptr
)->used
;
13339 static int Jim_DictCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13343 static const char * const options
[] = {
13344 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13348 OPT_CREATE
, OPT_GET
, OPT_SET
, OPT_UNSET
, OPT_EXIST
, OPT_KEYS
, OPT_MERGE
, OPT_SIZE
, OPT_WITH
,
13352 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?arguments ...?");
13356 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
) {
13363 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13366 if (Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, &objPtr
,
13367 JIM_ERRMSG
) != JIM_OK
) {
13370 Jim_SetResult(interp
, objPtr
);
13375 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...? value");
13378 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 4, argv
[argc
- 1], JIM_ERRMSG
);
13382 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13385 Jim_SetResultBool(interp
, Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3,
13386 &objPtr
, JIM_ERRMSG
) == JIM_OK
);
13391 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...?");
13394 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, NULL
, JIM_NONE
);
13397 if (argc
!= 3 && argc
!= 4) {
13398 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?pattern?");
13401 return Jim_DictKeys(interp
, argv
[2], argc
== 4 ? argv
[3] : NULL
);
13407 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar");
13411 size
= Jim_DictSize(interp
, argv
[2]);
13415 Jim_SetResultInt(interp
, size
);
13423 else if (SetDictFromAny(interp
, argv
[2]) != JIM_OK
) {
13427 return Jim_EvalPrefix(interp
, "dict merge", argc
- 2, argv
+ 2);
13432 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?key ...? script");
13435 else if (Jim_GetVariable(interp
, argv
[2], JIM_ERRMSG
) == NULL
) {
13439 return Jim_EvalPrefix(interp
, "dict with", argc
- 2, argv
+ 2);
13444 Jim_WrongNumArgs(interp
, 2, argv
, "?key value ...?");
13447 objPtr
= Jim_NewDictObj(interp
, argv
+ 2, argc
- 2);
13448 Jim_SetResult(interp
, objPtr
);
13455 static int Jim_SubstCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13457 static const char * const options
[] = {
13458 "-nobackslashes", "-nocommands", "-novariables", NULL
13461 { OPT_NOBACKSLASHES
, OPT_NOCOMMANDS
, OPT_NOVARIABLES
};
13463 int flags
= JIM_SUBST_FLAG
;
13467 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string");
13470 for (i
= 1; i
< (argc
- 1); i
++) {
13473 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
,
13474 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13478 case OPT_NOBACKSLASHES
:
13479 flags
|= JIM_SUBST_NOESC
;
13481 case OPT_NOCOMMANDS
:
13482 flags
|= JIM_SUBST_NOCMD
;
13484 case OPT_NOVARIABLES
:
13485 flags
|= JIM_SUBST_NOVAR
;
13489 if (Jim_SubstObj(interp
, argv
[argc
- 1], &objPtr
, flags
) != JIM_OK
) {
13492 Jim_SetResult(interp
, objPtr
);
13497 static int Jim_InfoCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13503 static const char * const commands
[] = {
13504 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13505 "vars", "version", "patchlevel", "complete", "args", "hostname",
13506 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13510 { INFO_BODY
, INFO_COMMANDS
, INFO_PROCS
, INFO_CHANNELS
, INFO_EXISTS
, INFO_GLOBALS
, INFO_LEVEL
,
13511 INFO_FRAME
, INFO_LOCALS
, INFO_VARS
, INFO_VERSION
, INFO_PATCHLEVEL
, INFO_COMPLETE
, INFO_ARGS
,
13512 INFO_HOSTNAME
, INFO_SCRIPT
, INFO_SOURCE
, INFO_STACKTRACE
, INFO_NAMEOFEXECUTABLE
,
13513 INFO_RETURNCODES
, INFO_REFERENCES
,
13517 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?args ...?");
13520 if (Jim_GetEnum(interp
, argv
[1], commands
, &cmd
, "subcommand", JIM_ERRMSG
| JIM_ENUM_ABBREV
)
13525 /* Test for the the most common commands first, just in case it makes a difference */
13529 Jim_WrongNumArgs(interp
, 2, argv
, "varName");
13532 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, argv
[2], 0) != NULL
);
13536 case INFO_CHANNELS
:
13537 mode
++; /* JIM_CMDLIST_CHANNELS */
13538 #ifndef jim_ext_aio
13539 Jim_SetResultString(interp
, "aio not enabled", -1);
13543 mode
++; /* JIM_CMDLIST_PROCS */
13544 case INFO_COMMANDS
:
13545 /* mode 0 => JIM_CMDLIST_COMMANDS */
13546 if (argc
!= 2 && argc
!= 3) {
13547 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13550 Jim_SetResult(interp
, JimCommandsList(interp
, (argc
== 3) ? argv
[2] : NULL
, mode
));
13554 mode
++; /* JIM_VARLIST_VARS */
13556 mode
++; /* JIM_VARLIST_LOCALS */
13558 /* mode 0 => JIM_VARLIST_GLOBALS */
13559 if (argc
!= 2 && argc
!= 3) {
13560 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13563 Jim_SetResult(interp
, JimVariablesList(interp
, argc
== 3 ? argv
[2] : NULL
, mode
));
13568 Jim_WrongNumArgs(interp
, 2, argv
, "");
13571 Jim_SetResult(interp
, Jim_GetScript(interp
, interp
->currentScriptObj
)->fileNameObj
);
13576 Jim_Obj
*resObjPtr
;
13577 Jim_Obj
*fileNameObj
;
13580 Jim_WrongNumArgs(interp
, 2, argv
, "source");
13583 if (argv
[2]->typePtr
== &sourceObjType
) {
13584 fileNameObj
= argv
[2]->internalRep
.sourceValue
.fileNameObj
;
13585 line
= argv
[2]->internalRep
.sourceValue
.lineNumber
;
13587 else if (argv
[2]->typePtr
== &scriptObjType
) {
13588 ScriptObj
*script
= Jim_GetScript(interp
, argv
[2]);
13589 fileNameObj
= script
->fileNameObj
;
13590 line
= script
->line
;
13593 fileNameObj
= interp
->emptyObj
;
13596 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13597 Jim_ListAppendElement(interp
, resObjPtr
, fileNameObj
);
13598 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewIntObj(interp
, line
));
13599 Jim_SetResult(interp
, resObjPtr
);
13603 case INFO_STACKTRACE
:
13604 Jim_SetResult(interp
, interp
->stackTrace
);
13611 Jim_SetResultInt(interp
, interp
->framePtr
->level
);
13615 if (JimInfoLevel(interp
, argv
[2], &objPtr
, cmd
== INFO_LEVEL
) != JIM_OK
) {
13618 Jim_SetResult(interp
, objPtr
);
13622 Jim_WrongNumArgs(interp
, 2, argv
, "?levelNum?");
13632 Jim_WrongNumArgs(interp
, 2, argv
, "procname");
13635 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
) {
13638 if (!cmdPtr
->isproc
) {
13639 Jim_SetResultFormatted(interp
, "command \"%#s\" is not a procedure", argv
[2]);
13642 Jim_SetResult(interp
,
13643 cmd
== INFO_BODY
? cmdPtr
->u
.proc
.bodyObjPtr
: cmdPtr
->u
.proc
.argListObjPtr
);
13648 case INFO_PATCHLEVEL
:{
13649 char buf
[(JIM_INTEGER_SPACE
* 2) + 1];
13651 sprintf(buf
, "%d.%d", JIM_VERSION
/ 100, JIM_VERSION
% 100);
13652 Jim_SetResultString(interp
, buf
, -1);
13656 case INFO_COMPLETE
:
13657 if (argc
!= 3 && argc
!= 4) {
13658 Jim_WrongNumArgs(interp
, 2, argv
, "script ?missing?");
13663 const char *s
= Jim_GetString(argv
[2], &len
);
13666 Jim_SetResultBool(interp
, Jim_ScriptIsComplete(s
, len
, &missing
));
13667 if (missing
!= ' ' && argc
== 4) {
13668 Jim_SetVariable(interp
, argv
[3], Jim_NewStringObj(interp
, &missing
, 1));
13673 case INFO_HOSTNAME
:
13674 /* Redirect to os.gethostname if it exists */
13675 return Jim_Eval(interp
, "os.gethostname");
13677 case INFO_NAMEOFEXECUTABLE
:
13678 /* Redirect to Tcl proc */
13679 return Jim_Eval(interp
, "{info nameofexecutable}");
13681 case INFO_RETURNCODES
:
13684 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13686 for (i
= 0; jimReturnCodes
[i
]; i
++) {
13687 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewIntObj(interp
, i
));
13688 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
,
13689 jimReturnCodes
[i
], -1));
13692 Jim_SetResult(interp
, listObjPtr
);
13694 else if (argc
== 3) {
13698 if (Jim_GetLong(interp
, argv
[2], &code
) != JIM_OK
) {
13701 name
= Jim_ReturnCode(code
);
13702 if (*name
== '?') {
13703 Jim_SetResultInt(interp
, code
);
13706 Jim_SetResultString(interp
, name
, -1);
13710 Jim_WrongNumArgs(interp
, 2, argv
, "?code?");
13714 case INFO_REFERENCES
:
13715 #ifdef JIM_REFERENCES
13716 return JimInfoReferences(interp
, argc
, argv
);
13718 Jim_SetResultString(interp
, "not supported", -1);
13726 static int Jim_ExistsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13730 static const char * const options
[] = {
13731 "-command", "-proc", "-var", NULL
13735 OPT_COMMAND
, OPT_PROC
, OPT_VAR
13743 else if (argc
== 3) {
13744 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13750 Jim_WrongNumArgs(interp
, 1, argv
, "?option? name");
13754 /* Test for the the most common commands first, just in case it makes a difference */
13757 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, objPtr
, 0) != NULL
);
13762 Jim_Cmd
*cmd
= Jim_GetCommand(interp
, objPtr
, JIM_NONE
);
13763 Jim_SetResultBool(interp
, cmd
!= NULL
&& (option
== OPT_COMMAND
|| cmd
->isproc
));
13771 static int Jim_SplitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13773 const char *str
, *splitChars
, *noMatchStart
;
13774 int splitLen
, strLen
;
13775 Jim_Obj
*resObjPtr
;
13779 if (argc
!= 2 && argc
!= 3) {
13780 Jim_WrongNumArgs(interp
, 1, argv
, "string ?splitChars?");
13784 str
= Jim_GetString(argv
[1], &len
);
13788 strLen
= Jim_Utf8Length(interp
, argv
[1]);
13792 splitChars
= " \n\t\r";
13796 splitChars
= Jim_String(argv
[2]);
13797 splitLen
= Jim_Utf8Length(interp
, argv
[2]);
13800 noMatchStart
= str
;
13801 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13807 const char *sc
= splitChars
;
13808 int scLen
= splitLen
;
13809 int sl
= utf8_tounicode(str
, &c
);
13812 sc
+= utf8_tounicode(sc
, &pc
);
13814 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13815 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13816 noMatchStart
= str
+ sl
;
13822 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13823 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13826 /* This handles the special case of splitchars eq {}
13827 * Optimise by sharing common (ASCII) characters
13829 Jim_Obj
**commonObj
= NULL
;
13830 #define NUM_COMMON (128 - 9)
13832 int n
= utf8_tounicode(str
, &c
);
13833 #ifdef JIM_OPTIMIZATION
13834 if (c
>= 9 && c
< 128) {
13835 /* Common ASCII char. Note that 9 is the tab character */
13838 commonObj
= Jim_Alloc(sizeof(*commonObj
) * NUM_COMMON
);
13839 memset(commonObj
, 0, sizeof(*commonObj
) * NUM_COMMON
);
13841 if (!commonObj
[c
]) {
13842 commonObj
[c
] = Jim_NewStringObj(interp
, str
, 1);
13844 Jim_ListAppendElement(interp
, resObjPtr
, commonObj
[c
]);
13849 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewStringObjUtf8(interp
, str
, 1));
13852 Jim_Free(commonObj
);
13855 Jim_SetResult(interp
, resObjPtr
);
13860 static int Jim_JoinCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13862 const char *joinStr
;
13863 int joinStrLen
, i
, listLen
;
13864 Jim_Obj
*resObjPtr
;
13866 if (argc
!= 2 && argc
!= 3) {
13867 Jim_WrongNumArgs(interp
, 1, argv
, "list ?joinString?");
13876 joinStr
= Jim_GetString(argv
[2], &joinStrLen
);
13878 listLen
= Jim_ListLength(interp
, argv
[1]);
13879 resObjPtr
= Jim_NewStringObj(interp
, NULL
, 0);
13881 for (i
= 0; i
< listLen
; i
++) {
13882 Jim_Obj
*objPtr
= 0;
13884 Jim_ListIndex(interp
, argv
[1], i
, &objPtr
, JIM_NONE
);
13885 Jim_AppendObj(interp
, resObjPtr
, objPtr
);
13886 if (i
+ 1 != listLen
) {
13887 Jim_AppendString(interp
, resObjPtr
, joinStr
, joinStrLen
);
13890 Jim_SetResult(interp
, resObjPtr
);
13895 static int Jim_FormatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13900 Jim_WrongNumArgs(interp
, 1, argv
, "formatString ?arg arg ...?");
13903 objPtr
= Jim_FormatString(interp
, argv
[1], argc
- 2, argv
+ 2);
13904 if (objPtr
== NULL
)
13906 Jim_SetResult(interp
, objPtr
);
13911 static int Jim_ScanCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13913 Jim_Obj
*listPtr
, **outVec
;
13917 Jim_WrongNumArgs(interp
, 1, argv
, "string format ?varName varName ...?");
13920 if (argv
[2]->typePtr
!= &scanFmtStringObjType
)
13921 SetScanFmtFromAny(interp
, argv
[2]);
13922 if (FormatGetError(argv
[2]) != 0) {
13923 Jim_SetResultString(interp
, FormatGetError(argv
[2]), -1);
13927 int maxPos
= FormatGetMaxPos(argv
[2]);
13928 int count
= FormatGetCnvCount(argv
[2]);
13930 if (maxPos
> argc
- 3) {
13931 Jim_SetResultString(interp
, "\"%n$\" argument index out of range", -1);
13934 else if (count
> argc
- 3) {
13935 Jim_SetResultString(interp
, "different numbers of variable names and "
13936 "field specifiers", -1);
13939 else if (count
< argc
- 3) {
13940 Jim_SetResultString(interp
, "variable is not assigned by any "
13941 "conversion specifiers", -1);
13945 listPtr
= Jim_ScanString(interp
, argv
[1], argv
[2], JIM_ERRMSG
);
13952 if (listPtr
!= 0 && listPtr
!= (Jim_Obj
*)EOF
) {
13953 int len
= Jim_ListLength(interp
, listPtr
);
13956 JimListGetElements(interp
, listPtr
, &outc
, &outVec
);
13957 for (i
= 0; i
< outc
; ++i
) {
13958 if (Jim_Length(outVec
[i
]) > 0) {
13960 if (Jim_SetVariable(interp
, argv
[3 + i
], outVec
[i
]) != JIM_OK
) {
13966 Jim_FreeNewObj(interp
, listPtr
);
13971 if (rc
== JIM_OK
) {
13972 Jim_SetResultInt(interp
, count
);
13977 if (listPtr
== (Jim_Obj
*)EOF
) {
13978 Jim_SetResult(interp
, Jim_NewListObj(interp
, 0, 0));
13981 Jim_SetResult(interp
, listPtr
);
13987 static int Jim_ErrorCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13989 if (argc
!= 2 && argc
!= 3) {
13990 Jim_WrongNumArgs(interp
, 1, argv
, "message ?stacktrace?");
13993 Jim_SetResult(interp
, argv
[1]);
13995 JimSetStackTrace(interp
, argv
[2]);
13998 interp
->addStackTrace
++;
14003 static int Jim_LrangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14008 Jim_WrongNumArgs(interp
, 1, argv
, "list first last");
14011 if ((objPtr
= Jim_ListRange(interp
, argv
[1], argv
[2], argv
[3])) == NULL
)
14013 Jim_SetResult(interp
, objPtr
);
14018 static int Jim_LrepeatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14023 if (argc
< 2 || Jim_GetLong(interp
, argv
[1], &count
) != JIM_OK
|| count
< 0) {
14024 Jim_WrongNumArgs(interp
, 1, argv
, "count ?value ...?");
14028 if (count
== 0 || argc
== 2) {
14035 objPtr
= Jim_NewListObj(interp
, argv
, argc
);
14037 ListInsertElements(objPtr
, -1, argc
, argv
);
14040 Jim_SetResult(interp
, objPtr
);
14044 char **Jim_GetEnviron(void)
14046 #if defined(HAVE__NSGETENVIRON)
14047 return *_NSGetEnviron();
14049 #if !defined(NO_ENVIRON_EXTERN)
14050 extern char **environ
;
14057 void Jim_SetEnviron(char **env
)
14059 #if defined(HAVE__NSGETENVIRON)
14060 *_NSGetEnviron() = env
;
14062 #if !defined(NO_ENVIRON_EXTERN)
14063 extern char **environ
;
14071 static int Jim_EnvCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14077 char **e
= Jim_GetEnviron();
14080 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14082 for (i
= 0; e
[i
]; i
++) {
14083 const char *equals
= strchr(e
[i
], '=');
14086 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, e
[i
],
14088 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, equals
+ 1, -1));
14092 Jim_SetResult(interp
, listObjPtr
);
14097 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?default?");
14100 key
= Jim_String(argv
[1]);
14104 Jim_SetResultFormatted(interp
, "environment variable \"%#s\" does not exist", argv
[1]);
14107 val
= Jim_String(argv
[2]);
14109 Jim_SetResult(interp
, Jim_NewStringObj(interp
, val
, -1));
14114 static int Jim_SourceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14119 Jim_WrongNumArgs(interp
, 1, argv
, "fileName");
14122 retval
= Jim_EvalFile(interp
, Jim_String(argv
[1]));
14123 if (retval
== JIM_RETURN
)
14129 static int Jim_LreverseCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14131 Jim_Obj
*revObjPtr
, **ele
;
14135 Jim_WrongNumArgs(interp
, 1, argv
, "list");
14138 JimListGetElements(interp
, argv
[1], &len
, &ele
);
14140 revObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14142 ListAppendElement(revObjPtr
, ele
[len
--]);
14143 Jim_SetResult(interp
, revObjPtr
);
14147 static int JimRangeLen(jim_wide start
, jim_wide end
, jim_wide step
)
14155 else if (step
> 0 && start
> end
)
14157 else if (step
< 0 && end
> start
)
14161 len
= -len
; /* abs(len) */
14163 step
= -step
; /* abs(step) */
14164 len
= 1 + ((len
- 1) / step
);
14165 /* We can truncate safely to INT_MAX, the range command
14166 * will always return an error for a such long range
14167 * because Tcl lists can't be so long. */
14170 return (int)((len
< 0) ? -1 : len
);
14174 static int Jim_RangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14176 jim_wide start
= 0, end
, step
= 1;
14180 if (argc
< 2 || argc
> 4) {
14181 Jim_WrongNumArgs(interp
, 1, argv
, "?start? end ?step?");
14185 if (Jim_GetWide(interp
, argv
[1], &end
) != JIM_OK
)
14189 if (Jim_GetWide(interp
, argv
[1], &start
) != JIM_OK
||
14190 Jim_GetWide(interp
, argv
[2], &end
) != JIM_OK
)
14192 if (argc
== 4 && Jim_GetWide(interp
, argv
[3], &step
) != JIM_OK
)
14195 if ((len
= JimRangeLen(start
, end
, step
)) == -1) {
14196 Jim_SetResultString(interp
, "Invalid (infinite?) range specified", -1);
14199 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
14200 for (i
= 0; i
< len
; i
++)
14201 ListAppendElement(objPtr
, Jim_NewIntObj(interp
, start
+ i
* step
));
14202 Jim_SetResult(interp
, objPtr
);
14207 static int Jim_RandCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14209 jim_wide min
= 0, max
= 0, len
, maxMul
;
14211 if (argc
< 1 || argc
> 3) {
14212 Jim_WrongNumArgs(interp
, 1, argv
, "?min? max");
14216 max
= JIM_WIDE_MAX
;
14217 } else if (argc
== 2) {
14218 if (Jim_GetWide(interp
, argv
[1], &max
) != JIM_OK
)
14220 } else if (argc
== 3) {
14221 if (Jim_GetWide(interp
, argv
[1], &min
) != JIM_OK
||
14222 Jim_GetWide(interp
, argv
[2], &max
) != JIM_OK
)
14227 Jim_SetResultString(interp
, "Invalid arguments (max < min)", -1);
14230 maxMul
= JIM_WIDE_MAX
- (len
? (JIM_WIDE_MAX
%len
) : 0);
14234 JimRandomBytes(interp
, &r
, sizeof(jim_wide
));
14235 if (r
< 0 || r
>= maxMul
) continue;
14236 r
= (len
== 0) ? 0 : r
%len
;
14237 Jim_SetResultInt(interp
, min
+r
);
14242 static const struct {
14244 Jim_CmdProc cmdProc
;
14245 } Jim_CoreCommandsTable
[] = {
14246 {"set", Jim_SetCoreCommand
},
14247 {"unset", Jim_UnsetCoreCommand
},
14248 {"puts", Jim_PutsCoreCommand
},
14249 {"+", Jim_AddCoreCommand
},
14250 {"*", Jim_MulCoreCommand
},
14251 {"-", Jim_SubCoreCommand
},
14252 {"/", Jim_DivCoreCommand
},
14253 {"incr", Jim_IncrCoreCommand
},
14254 {"while", Jim_WhileCoreCommand
},
14255 {"loop", Jim_LoopCoreCommand
},
14256 {"for", Jim_ForCoreCommand
},
14257 {"foreach", Jim_ForeachCoreCommand
},
14258 {"lmap", Jim_LmapCoreCommand
},
14259 {"if", Jim_IfCoreCommand
},
14260 {"switch", Jim_SwitchCoreCommand
},
14261 {"list", Jim_ListCoreCommand
},
14262 {"lindex", Jim_LindexCoreCommand
},
14263 {"lset", Jim_LsetCoreCommand
},
14264 {"lsearch", Jim_LsearchCoreCommand
},
14265 {"llength", Jim_LlengthCoreCommand
},
14266 {"lappend", Jim_LappendCoreCommand
},
14267 {"linsert", Jim_LinsertCoreCommand
},
14268 {"lreplace", Jim_LreplaceCoreCommand
},
14269 {"lsort", Jim_LsortCoreCommand
},
14270 {"append", Jim_AppendCoreCommand
},
14271 {"debug", Jim_DebugCoreCommand
},
14272 {"eval", Jim_EvalCoreCommand
},
14273 {"uplevel", Jim_UplevelCoreCommand
},
14274 {"expr", Jim_ExprCoreCommand
},
14275 {"break", Jim_BreakCoreCommand
},
14276 {"continue", Jim_ContinueCoreCommand
},
14277 {"proc", Jim_ProcCoreCommand
},
14278 {"concat", Jim_ConcatCoreCommand
},
14279 {"return", Jim_ReturnCoreCommand
},
14280 {"upvar", Jim_UpvarCoreCommand
},
14281 {"global", Jim_GlobalCoreCommand
},
14282 {"string", Jim_StringCoreCommand
},
14283 {"time", Jim_TimeCoreCommand
},
14284 {"exit", Jim_ExitCoreCommand
},
14285 {"catch", Jim_CatchCoreCommand
},
14286 #ifdef JIM_REFERENCES
14287 {"ref", Jim_RefCoreCommand
},
14288 {"getref", Jim_GetrefCoreCommand
},
14289 {"setref", Jim_SetrefCoreCommand
},
14290 {"finalize", Jim_FinalizeCoreCommand
},
14291 {"collect", Jim_CollectCoreCommand
},
14293 {"rename", Jim_RenameCoreCommand
},
14294 {"dict", Jim_DictCoreCommand
},
14295 {"subst", Jim_SubstCoreCommand
},
14296 {"info", Jim_InfoCoreCommand
},
14297 {"exists", Jim_ExistsCoreCommand
},
14298 {"split", Jim_SplitCoreCommand
},
14299 {"join", Jim_JoinCoreCommand
},
14300 {"format", Jim_FormatCoreCommand
},
14301 {"scan", Jim_ScanCoreCommand
},
14302 {"error", Jim_ErrorCoreCommand
},
14303 {"lrange", Jim_LrangeCoreCommand
},
14304 {"lrepeat", Jim_LrepeatCoreCommand
},
14305 {"env", Jim_EnvCoreCommand
},
14306 {"source", Jim_SourceCoreCommand
},
14307 {"lreverse", Jim_LreverseCoreCommand
},
14308 {"range", Jim_RangeCoreCommand
},
14309 {"rand", Jim_RandCoreCommand
},
14310 {"tailcall", Jim_TailcallCoreCommand
},
14311 {"local", Jim_LocalCoreCommand
},
14312 {"upcall", Jim_UpcallCoreCommand
},
14316 void Jim_RegisterCoreCommands(Jim_Interp
*interp
)
14320 while (Jim_CoreCommandsTable
[i
].name
!= NULL
) {
14321 Jim_CreateCommand(interp
,
14322 Jim_CoreCommandsTable
[i
].name
, Jim_CoreCommandsTable
[i
].cmdProc
, NULL
, NULL
);
14327 /* -----------------------------------------------------------------------------
14328 * Interactive prompt
14329 * ---------------------------------------------------------------------------*/
14330 void Jim_MakeErrorMessage(Jim_Interp
*interp
)
14334 argv
[0] = Jim_NewStringObj(interp
, "errorInfo", -1);
14335 argv
[1] = interp
->result
;
14337 Jim_EvalObjVector(interp
, 2, argv
);
14340 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
14341 const char *prefix
, const char *const *tablePtr
, const char *name
)
14344 char **tablePtrSorted
;
14347 for (count
= 0; tablePtr
[count
]; count
++) {
14350 if (name
== NULL
) {
14354 Jim_SetResultFormatted(interp
, "%s%s \"%s\": must be ", badtype
, name
, arg
);
14355 tablePtrSorted
= Jim_Alloc(sizeof(char *) * count
);
14356 memcpy(tablePtrSorted
, tablePtr
, sizeof(char *) * count
);
14357 qsort(tablePtrSorted
, count
, sizeof(char *), qsortCompareStringPointers
);
14358 for (i
= 0; i
< count
; i
++) {
14359 if (i
+ 1 == count
&& count
> 1) {
14360 Jim_AppendString(interp
, Jim_GetResult(interp
), "or ", -1);
14362 Jim_AppendStrings(interp
, Jim_GetResult(interp
), prefix
, tablePtrSorted
[i
], NULL
);
14363 if (i
+ 1 != count
) {
14364 Jim_AppendString(interp
, Jim_GetResult(interp
), ", ", -1);
14367 Jim_Free(tablePtrSorted
);
14370 int Jim_GetEnum(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
14371 const char *const *tablePtr
, int *indexPtr
, const char *name
, int flags
)
14373 const char *bad
= "bad ";
14374 const char *const *entryPtr
= NULL
;
14378 const char *arg
= Jim_GetString(objPtr
, &arglen
);
14382 for (entryPtr
= tablePtr
, i
= 0; *entryPtr
!= NULL
; entryPtr
++, i
++) {
14383 if (Jim_CompareStringImmediate(interp
, objPtr
, *entryPtr
)) {
14384 /* Found an exact match */
14388 if (flags
& JIM_ENUM_ABBREV
) {
14389 /* Accept an unambiguous abbreviation.
14390 * Note that '-' doesnt' consitute a valid abbreviation
14392 if (strncmp(arg
, *entryPtr
, arglen
) == 0) {
14393 if (*arg
== '-' && arglen
== 1) {
14397 bad
= "ambiguous ";
14405 /* If we had an unambiguous partial match */
14412 if (flags
& JIM_ERRMSG
) {
14413 JimSetFailedEnumResult(interp
, arg
, bad
, "", tablePtr
, name
);
14418 int Jim_FindByName(const char *name
, const char * const array
[], size_t len
)
14422 for (i
= 0; i
< (int)len
; i
++) {
14423 if (array
[i
] && strcmp(array
[i
], name
) == 0) {
14430 int Jim_IsDict(Jim_Obj
*objPtr
)
14432 return objPtr
->typePtr
== &dictObjType
;
14435 int Jim_IsList(Jim_Obj
*objPtr
)
14437 return objPtr
->typePtr
== &listObjType
;
14441 * Very simple printf-like formatting, designed for error messages.
14443 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14444 * The resulting string is created and set as the result.
14446 * Each '%s' should correspond to a regular string parameter.
14447 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14448 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14450 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14452 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14454 void Jim_SetResultFormatted(Jim_Interp
*interp
, const char *format
, ...)
14456 /* Initial space needed */
14457 int len
= strlen(format
);
14460 const char *params
[5];
14465 va_start(args
, format
);
14467 for (i
= 0; i
< len
&& n
< 5; i
++) {
14470 if (strncmp(format
+ i
, "%s", 2) == 0) {
14471 params
[n
] = va_arg(args
, char *);
14473 l
= strlen(params
[n
]);
14475 else if (strncmp(format
+ i
, "%#s", 3) == 0) {
14476 Jim_Obj
*objPtr
= va_arg(args
, Jim_Obj
*);
14478 params
[n
] = Jim_GetString(objPtr
, &l
);
14481 if (format
[i
] == '%') {
14491 buf
= Jim_Alloc(len
+ 1);
14492 len
= snprintf(buf
, len
+ 1, format
, params
[0], params
[1], params
[2], params
[3], params
[4]);
14494 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
14498 #ifndef jim_ext_package
14499 int Jim_PackageProvide(Jim_Interp
*interp
, const char *name
, const char *ver
, int flags
)
14504 #ifndef jim_ext_aio
14505 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*fhObj
)
14507 Jim_SetResultString(interp
, "aio not enabled", -1);
14514 * Local Variables: ***
14515 * c-basic-offset: 4 ***