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 */
62 #include "jimautoconf.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 static const Jim_HashTableType JimVariablesHashTableType
;
145 /* Fast access to the int (wide) value of an object which is known to be of int type */
146 #define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
148 #define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
150 static int utf8_tounicode_case(const char *s
, int *uc
, int upper
)
152 int l
= utf8_tounicode(s
, uc
);
154 *uc
= utf8_upper(*uc
);
159 /* These can be used in addition to JIM_CASESENS/JIM_NOCASE */
160 #define JIM_CHARSET_SCAN 2
161 #define JIM_CHARSET_GLOB 0
164 * pattern points to a string like "[^a-z\ub5]"
166 * The pattern may contain trailing chars, which are ignored.
168 * The pattern is matched against unicode char 'c'.
170 * If (flags & JIM_NOCASE), case is ignored when matching.
171 * If (flags & JIM_CHARSET_SCAN), the considers ^ and ] special at the start
172 * of the charset, per scan, rather than glob/string match.
174 * If the unicode char 'c' matches that set, returns a pointer to the ']' character,
175 * or the null character if the ']' is missing.
177 * Returns NULL on no match.
179 static const char *JimCharsetMatch(const char *pattern
, int c
, int flags
)
186 if (flags
& JIM_NOCASE
) {
191 if (flags
& JIM_CHARSET_SCAN
) {
192 if (*pattern
== '^') {
197 /* Special case. If the first char is ']', it is part of the set */
198 if (*pattern
== ']') {
203 while (*pattern
&& *pattern
!= ']') {
205 if (pattern
[0] == '\\') {
207 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
210 /* Is this a range? a-z */
214 pattern
+= utf8_tounicode_case(pattern
, &start
, nocase
);
215 if (pattern
[0] == '-' && pattern
[1]) {
217 pattern
+= utf8_tounicode(pattern
, &pchar
);
218 pattern
+= utf8_tounicode_case(pattern
, &end
, nocase
);
220 /* Handle reversed range too */
221 if ((c
>= start
&& c
<= end
) || (c
>= end
&& c
<= start
)) {
237 return match
? pattern
: NULL
;
240 /* Glob-style pattern matching. */
242 /* Note: string *must* be valid UTF-8 sequences
243 * slen is a char length, not byte counts.
245 static int GlobMatch(const char *pattern
, const char *string
, int nocase
)
250 switch (pattern
[0]) {
252 while (pattern
[1] == '*') {
257 return 1; /* match */
260 /* Recursive call - Does the remaining pattern match anywhere? */
261 if (GlobMatch(pattern
, string
, nocase
))
262 return 1; /* match */
263 string
+= utf8_tounicode(string
, &c
);
265 return 0; /* no match */
268 string
+= utf8_tounicode(string
, &c
);
272 string
+= utf8_tounicode(string
, &c
);
273 pattern
= JimCharsetMatch(pattern
+ 1, c
, nocase
? JIM_NOCASE
: 0);
278 /* Ran out of pattern (no ']') */
289 string
+= utf8_tounicode_case(string
, &c
, nocase
);
290 utf8_tounicode_case(pattern
, &pchar
, nocase
);
296 pattern
+= utf8_tounicode_case(pattern
, &pchar
, nocase
);
298 while (*pattern
== '*') {
304 if (!*pattern
&& !*string
) {
310 static int JimStringMatch(Jim_Interp
*interp
, Jim_Obj
*patternObj
, const char *string
, int nocase
)
312 return GlobMatch(Jim_String(patternObj
), string
, nocase
);
316 * string comparison works on binary data.
318 * Note that the lengths are byte lengths, not char lengths.
320 static int JimStringCompare(const char *s1
, int l1
, const char *s2
, int l2
)
323 return memcmp(s1
, s2
, l1
) <= 0 ? -1 : 1;
326 return memcmp(s1
, s2
, l2
) >= 0 ? 1 : -1;
329 return JimSign(memcmp(s1
, s2
, l1
));
336 * If maxchars is -1, compares to end of string.
337 * Otherwise compares at most 'maxchars' characters.
339 static int JimStringCompareNoCase(const char *s1
, const char *s2
, int maxchars
)
341 while (*s1
&& *s2
&& maxchars
) {
343 s1
+= utf8_tounicode_case(s1
, &c1
, 1);
344 s2
+= utf8_tounicode_case(s2
, &c2
, 1);
346 return JimSign(c1
- c2
);
353 /* One string or both terminated */
363 /* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
364 * The index of the first occurrence of s1 in s2 is returned.
365 * If s1 is not found inside s2, -1 is returned. */
366 static int JimStringFirst(const char *s1
, int l1
, const char *s2
, int l2
, int idx
)
371 if (!l1
|| !l2
|| l1
> l2
) {
376 s2
+= utf8_index(s2
, idx
);
378 l1bytelen
= utf8_index(s1
, l1
);
380 for (i
= idx
; i
<= l2
- l1
; i
++) {
382 if (memcmp(s2
, s1
, l1bytelen
) == 0) {
385 s2
+= utf8_tounicode(s2
, &c
);
391 * Note: Lengths and return value are in bytes, not chars.
393 static int JimStringLast(const char *s1
, int l1
, const char *s2
, int l2
)
397 if (!l1
|| !l2
|| l1
> l2
)
400 /* Now search for the needle */
401 for (p
= s2
+ l2
- 1; p
!= s2
- 1; p
--) {
402 if (*p
== *s1
&& memcmp(s1
, p
, l1
) == 0) {
411 * Note: Lengths and return value are in chars.
413 static int JimStringLastUtf8(const char *s1
, int l1
, const char *s2
, int l2
)
415 int n
= JimStringLast(s1
, utf8_index(s1
, l1
), s2
, utf8_index(s2
, l2
));
417 n
= utf8_strlen(s2
, n
);
423 int Jim_WideToString(char *buf
, jim_wide wideValue
)
425 const char *fmt
= "%" JIM_WIDE_MODIFIER
;
427 return sprintf(buf
, fmt
, wideValue
);
431 * After an strtol()/strtod()-like conversion,
432 * check whether something was converted and that
433 * the only thing left is white space.
435 * Returns JIM_OK or JIM_ERR.
437 static int JimCheckConversion(const char *str
, const char *endptr
)
439 if (str
[0] == '\0' || str
== endptr
) {
443 if (endptr
[0] != '\0') {
445 if (!isspace(UCHAR(*endptr
))) {
454 int Jim_StringToWide(const char *str
, jim_wide
* widePtr
, int base
)
458 *widePtr
= strtoull(str
, &endptr
, base
);
460 return JimCheckConversion(str
, endptr
);
463 int Jim_DoubleToString(char *buf
, double doubleValue
)
468 len
= sprintf(buf
, "%.12g", doubleValue
);
470 /* Add a final ".0" if it's a number. But not
473 if (*buf
== '.' || isalpha(UCHAR(*buf
))) {
474 /* inf -> Inf, nan -> Nan */
475 if (*buf
== 'i' || *buf
== 'n') {
476 *buf
= toupper(UCHAR(*buf
));
479 /* Infinity -> Inf */
481 len
= buf
- buf0
+ 3;
495 int Jim_StringToDouble(const char *str
, double *doublePtr
)
499 /* Callers can check for underflow via ERANGE */
502 *doublePtr
= strtod(str
, &endptr
);
504 return JimCheckConversion(str
, endptr
);
507 static jim_wide
JimPowWide(jim_wide b
, jim_wide e
)
511 if ((b
== 0 && e
!= 0) || (e
< 0))
513 for (i
= 0; i
< e
; i
++) {
519 /* -----------------------------------------------------------------------------
521 * ---------------------------------------------------------------------------*/
522 #ifdef JIM_DEBUG_PANIC
523 void JimPanicDump(int condition
, const char *fmt
, ...)
533 fprintf(stderr
, JIM_NL
"JIM INTERPRETER PANIC: ");
534 vfprintf(stderr
, fmt
, ap
);
535 fprintf(stderr
, JIM_NL JIM_NL
);
538 #ifdef HAVE_BACKTRACE
544 size
= backtrace(array
, 40);
545 strings
= backtrace_symbols(array
, size
);
546 for (i
= 0; i
< size
; i
++)
547 fprintf(stderr
, "[backtrace] %s" JIM_NL
, strings
[i
]);
548 fprintf(stderr
, "[backtrace] Include the above lines and the output" JIM_NL
);
549 fprintf(stderr
, "[backtrace] of 'nm <executable>' in the bug report." JIM_NL
);
557 /* -----------------------------------------------------------------------------
559 * ---------------------------------------------------------------------------*/
561 void *Jim_Alloc(int size
)
566 void Jim_Free(void *ptr
)
571 void *Jim_Realloc(void *ptr
, int size
)
573 return realloc(ptr
, size
);
576 char *Jim_StrDup(const char *s
)
581 char *Jim_StrDupLen(const char *s
, int l
)
583 char *copy
= Jim_Alloc(l
+ 1);
585 memcpy(copy
, s
, l
+ 1);
586 copy
[l
] = 0; /* Just to be sure, original could be substring */
590 /* -----------------------------------------------------------------------------
591 * Time related functions
592 * ---------------------------------------------------------------------------*/
594 /* Returns microseconds of CPU used since start. */
595 static jim_wide
JimClock(void)
599 gettimeofday(&tv
, NULL
);
600 return (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
;
603 /* -----------------------------------------------------------------------------
605 * ---------------------------------------------------------------------------*/
607 /* -------------------------- private prototypes ---------------------------- */
608 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
);
609 static unsigned int JimHashTableNextPower(unsigned int size
);
610 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
);
612 /* -------------------------- hash functions -------------------------------- */
614 /* Thomas Wang's 32 bit Mix Function */
615 unsigned int Jim_IntHashFunction(unsigned int key
)
626 /* Generic hash function (we are using to multiply by 9 and add the byte
628 unsigned int Jim_GenHashFunction(const unsigned char *buf
, int len
)
633 h
+= (h
<< 3) + *buf
++;
637 /* ----------------------------- API implementation ------------------------- */
639 /* reset a hashtable already initialized with ht_init().
640 * NOTE: This function should only called by ht_destroy(). */
641 static void JimResetHashTable(Jim_HashTable
*ht
)
650 /* Initialize the hash table */
651 int Jim_InitHashTable(Jim_HashTable
*ht
, const Jim_HashTableType
*type
, void *privDataPtr
)
653 JimResetHashTable(ht
);
655 ht
->privdata
= privDataPtr
;
659 /* Resize the table to the minimal size that contains all the elements,
660 * but with the invariant of a USER/BUCKETS ration near to <= 1 */
661 int Jim_ResizeHashTable(Jim_HashTable
*ht
)
663 int minimal
= ht
->used
;
665 if (minimal
< JIM_HT_INITIAL_SIZE
)
666 minimal
= JIM_HT_INITIAL_SIZE
;
667 return Jim_ExpandHashTable(ht
, minimal
);
670 /* Expand or create the hashtable */
671 int Jim_ExpandHashTable(Jim_HashTable
*ht
, unsigned int size
)
673 Jim_HashTable n
; /* the new hashtable */
674 unsigned int realsize
= JimHashTableNextPower(size
), i
;
676 /* the size is invalid if it is smaller than the number of
677 * elements already inside the hashtable */
678 if (ht
->used
>= size
)
681 Jim_InitHashTable(&n
, ht
->type
, ht
->privdata
);
683 n
.sizemask
= realsize
- 1;
684 n
.table
= Jim_Alloc(realsize
* sizeof(Jim_HashEntry
*));
686 /* Initialize all the pointers to NULL */
687 memset(n
.table
, 0, realsize
* sizeof(Jim_HashEntry
*));
689 /* Copy all the elements from the old to the new table:
690 * note that if the old hash table is empty ht->used is zero,
691 * so Jim_ExpandHashTable just creates an empty hash table. */
693 for (i
= 0; ht
->used
> 0; i
++) {
694 Jim_HashEntry
*he
, *nextHe
;
696 if (ht
->table
[i
] == NULL
)
699 /* For each hash entry on this slot... */
705 /* Get the new element index */
706 h
= Jim_HashKey(ht
, he
->key
) & n
.sizemask
;
707 he
->next
= n
.table
[h
];
710 /* Pass to the next element */
714 assert(ht
->used
== 0);
717 /* Remap the new hashtable in the old */
722 /* Add an element to the target hash table */
723 int Jim_AddHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
726 Jim_HashEntry
*entry
;
728 /* Get the index of the new element, or -1 if
729 * the element already exists. */
730 if ((idx
= JimInsertHashEntry(ht
, key
)) == -1)
733 /* Allocates the memory and stores key */
734 entry
= Jim_Alloc(sizeof(*entry
));
735 entry
->next
= ht
->table
[idx
];
736 ht
->table
[idx
] = entry
;
738 /* Set the hash entry fields. */
739 Jim_SetHashKey(ht
, entry
, key
);
740 Jim_SetHashVal(ht
, entry
, val
);
745 /* Add an element, discarding the old if the key already exists */
746 int Jim_ReplaceHashEntry(Jim_HashTable
*ht
, const void *key
, void *val
)
748 Jim_HashEntry
*entry
;
750 /* Try to add the element. If the key
751 * does not exists Jim_AddHashEntry will suceed. */
752 if (Jim_AddHashEntry(ht
, key
, val
) == JIM_OK
)
754 /* It already exists, get the entry */
755 entry
= Jim_FindHashEntry(ht
, key
);
756 /* Free the old value and set the new one */
757 Jim_FreeEntryVal(ht
, entry
);
758 Jim_SetHashVal(ht
, entry
, val
);
762 /* Search and remove an element */
763 int Jim_DeleteHashEntry(Jim_HashTable
*ht
, const void *key
)
766 Jim_HashEntry
*he
, *prevHe
;
770 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
775 if (Jim_CompareHashKeys(ht
, key
, he
->key
)) {
776 /* Unlink the element from the list */
778 prevHe
->next
= he
->next
;
780 ht
->table
[h
] = he
->next
;
781 Jim_FreeEntryKey(ht
, he
);
782 Jim_FreeEntryVal(ht
, he
);
790 return JIM_ERR
; /* not found */
793 /* Destroy an entire hash table */
794 int Jim_FreeHashTable(Jim_HashTable
*ht
)
798 /* Free all the elements */
799 for (i
= 0; ht
->used
> 0; i
++) {
800 Jim_HashEntry
*he
, *nextHe
;
802 if ((he
= ht
->table
[i
]) == NULL
)
806 Jim_FreeEntryKey(ht
, he
);
807 Jim_FreeEntryVal(ht
, he
);
813 /* Free the table and the allocated cache structure */
815 /* Re-initialize the table */
816 JimResetHashTable(ht
);
817 return JIM_OK
; /* never fails */
820 Jim_HashEntry
*Jim_FindHashEntry(Jim_HashTable
*ht
, const void *key
)
827 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
830 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
837 Jim_HashTableIterator
*Jim_GetHashTableIterator(Jim_HashTable
*ht
)
839 Jim_HashTableIterator
*iter
= Jim_Alloc(sizeof(*iter
));
844 iter
->nextEntry
= NULL
;
848 Jim_HashEntry
*Jim_NextHashEntry(Jim_HashTableIterator
*iter
)
851 if (iter
->entry
== NULL
) {
853 if (iter
->index
>= (signed)iter
->ht
->size
)
855 iter
->entry
= iter
->ht
->table
[iter
->index
];
858 iter
->entry
= iter
->nextEntry
;
861 /* We need to save the 'next' here, the iterator user
862 * may delete the entry we are returning. */
863 iter
->nextEntry
= iter
->entry
->next
;
870 /* ------------------------- private functions ------------------------------ */
872 /* Expand the hash table if needed */
873 static int JimExpandHashTableIfNeeded(Jim_HashTable
*ht
)
875 /* If the hash table is empty expand it to the intial size,
876 * if the table is "full" dobule its size. */
878 return Jim_ExpandHashTable(ht
, JIM_HT_INITIAL_SIZE
);
879 if (ht
->size
== ht
->used
)
880 return Jim_ExpandHashTable(ht
, ht
->size
* 2);
884 /* Our hash table capability is a power of two */
885 static unsigned int JimHashTableNextPower(unsigned int size
)
887 unsigned int i
= JIM_HT_INITIAL_SIZE
;
889 if (size
>= 2147483648U)
898 /* Returns the index of a free slot that can be populated with
899 * an hash entry for the given 'key'.
900 * If the key already exists, -1 is returned. */
901 static int JimInsertHashEntry(Jim_HashTable
*ht
, const void *key
)
906 /* Expand the hashtable if needed */
907 if (JimExpandHashTableIfNeeded(ht
) == JIM_ERR
)
909 /* Compute the key hash value */
910 h
= Jim_HashKey(ht
, key
) & ht
->sizemask
;
911 /* Search if this slot does not already contain the given key */
914 if (Jim_CompareHashKeys(ht
, key
, he
->key
))
921 /* ----------------------- StringCopy Hash Table Type ------------------------*/
923 static unsigned int JimStringCopyHTHashFunction(const void *key
)
925 return Jim_GenHashFunction(key
, strlen(key
));
928 static const void *JimStringCopyHTKeyDup(void *privdata
, const void *key
)
930 int len
= strlen(key
);
931 char *copy
= Jim_Alloc(len
+ 1);
933 JIM_NOTUSED(privdata
);
935 memcpy(copy
, key
, len
);
940 static void *JimStringKeyValCopyHTValDup(void *privdata
, const void *val
)
942 int len
= strlen(val
);
943 char *copy
= Jim_Alloc(len
+ 1);
945 JIM_NOTUSED(privdata
);
947 memcpy(copy
, val
, len
);
952 static int JimStringCopyHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
954 JIM_NOTUSED(privdata
);
956 return strcmp(key1
, key2
) == 0;
959 static void JimStringCopyHTKeyDestructor(void *privdata
, const void *key
)
961 JIM_NOTUSED(privdata
);
963 Jim_Free((void *)key
); /* ATTENTION: const cast */
966 static void JimStringKeyValCopyHTValDestructor(void *privdata
, void *val
)
968 JIM_NOTUSED(privdata
);
970 Jim_Free((void *)val
); /* ATTENTION: const cast */
974 static Jim_HashTableType JimStringCopyHashTableType
= {
975 JimStringCopyHTHashFunction
, /* hash function */
976 JimStringCopyHTKeyDup
, /* key dup */
978 JimStringCopyHTKeyCompare
, /* key compare */
979 JimStringCopyHTKeyDestructor
, /* key destructor */
980 NULL
/* val destructor */
984 /* This is like StringCopy but does not auto-duplicate the key.
985 * It's used for intepreter's shared strings. */
986 static const Jim_HashTableType JimSharedStringsHashTableType
= {
987 JimStringCopyHTHashFunction
, /* hash function */
990 JimStringCopyHTKeyCompare
, /* key compare */
991 JimStringCopyHTKeyDestructor
, /* key destructor */
992 NULL
/* val destructor */
995 /* This is like StringCopy but also automatically handle dynamic
996 * allocated C strings as values. */
997 static const Jim_HashTableType JimStringKeyValCopyHashTableType
= {
998 JimStringCopyHTHashFunction
, /* hash function */
999 JimStringCopyHTKeyDup
, /* key dup */
1000 JimStringKeyValCopyHTValDup
, /* val dup */
1001 JimStringCopyHTKeyCompare
, /* key compare */
1002 JimStringCopyHTKeyDestructor
, /* key destructor */
1003 JimStringKeyValCopyHTValDestructor
, /* val destructor */
1006 typedef struct AssocDataValue
1008 Jim_InterpDeleteProc
*delProc
;
1012 static void JimAssocDataHashTableValueDestructor(void *privdata
, void *data
)
1014 AssocDataValue
*assocPtr
= (AssocDataValue
*) data
;
1016 if (assocPtr
->delProc
!= NULL
)
1017 assocPtr
->delProc((Jim_Interp
*)privdata
, assocPtr
->data
);
1021 static const Jim_HashTableType JimAssocDataHashTableType
= {
1022 JimStringCopyHTHashFunction
, /* hash function */
1023 JimStringCopyHTKeyDup
, /* key dup */
1025 JimStringCopyHTKeyCompare
, /* key compare */
1026 JimStringCopyHTKeyDestructor
, /* key destructor */
1027 JimAssocDataHashTableValueDestructor
/* val destructor */
1030 /* -----------------------------------------------------------------------------
1031 * Stack - This is a simple generic stack implementation. It is used for
1032 * example in the 'expr' expression compiler.
1033 * ---------------------------------------------------------------------------*/
1034 void Jim_InitStack(Jim_Stack
*stack
)
1038 stack
->vector
= NULL
;
1041 void Jim_FreeStack(Jim_Stack
*stack
)
1043 Jim_Free(stack
->vector
);
1046 int Jim_StackLen(Jim_Stack
*stack
)
1051 void Jim_StackPush(Jim_Stack
*stack
, void *element
)
1053 int neededLen
= stack
->len
+ 1;
1055 if (neededLen
> stack
->maxlen
) {
1056 stack
->maxlen
= neededLen
< 20 ? 20 : neededLen
* 2;
1057 stack
->vector
= Jim_Realloc(stack
->vector
, sizeof(void *) * stack
->maxlen
);
1059 stack
->vector
[stack
->len
] = element
;
1063 void *Jim_StackPop(Jim_Stack
*stack
)
1065 if (stack
->len
== 0)
1068 return stack
->vector
[stack
->len
];
1071 void *Jim_StackPeek(Jim_Stack
*stack
)
1073 if (stack
->len
== 0)
1075 return stack
->vector
[stack
->len
- 1];
1078 void Jim_FreeStackElements(Jim_Stack
*stack
, void (*freeFunc
) (void *ptr
))
1082 for (i
= 0; i
< stack
->len
; i
++)
1083 freeFunc(stack
->vector
[i
]);
1086 /* -----------------------------------------------------------------------------
1088 * ---------------------------------------------------------------------------*/
1091 #define JIM_TT_NONE 0 /* No token returned */
1092 #define JIM_TT_STR 1 /* simple string */
1093 #define JIM_TT_ESC 2 /* string that needs escape chars conversion */
1094 #define JIM_TT_VAR 3 /* var substitution */
1095 #define JIM_TT_DICTSUGAR 4 /* Syntax sugar for [dict get], $foo(bar) */
1096 #define JIM_TT_CMD 5 /* command substitution */
1097 /* Note: Keep these three together for TOKEN_IS_SEP() */
1098 #define JIM_TT_SEP 6 /* word separator. arg is # of tokens. -ve if {*} */
1099 #define JIM_TT_EOL 7 /* line separator */
1100 #define JIM_TT_EOF 8 /* end of script */
1102 #define JIM_TT_LINE 9 /* special 'start-of-line' token. arg is # of arguments to the command. -ve if {*} */
1103 #define JIM_TT_WORD 10 /* special 'start-of-word' token. arg is # of tokens to combine. -ve if {*} */
1105 /* Additional token types needed for expressions */
1106 #define JIM_TT_SUBEXPR_START 11
1107 #define JIM_TT_SUBEXPR_END 12
1108 #define JIM_TT_EXPR_INT 13
1109 #define JIM_TT_EXPR_DOUBLE 14
1111 #define JIM_TT_EXPRSUGAR 15 /* $(expression) */
1113 /* Operator token types start here */
1114 #define JIM_TT_EXPR_OP 20
1116 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1119 #define JIM_PS_DEF 0 /* Default state */
1120 #define JIM_PS_QUOTE 1 /* Inside "" */
1121 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1123 /* Parser context structure. The same context is used both to parse
1124 * Tcl scripts and lists. */
1127 const char *p
; /* Pointer to the point of the program we are parsing */
1128 int len
; /* Remaining length */
1129 int linenr
; /* Current line number */
1131 const char *tend
; /* Returned token is at tstart-tend in 'prg'. */
1132 int tline
; /* Line number of the returned token */
1133 int tt
; /* Token type */
1134 int eof
; /* Non zero if EOF condition is true. */
1135 int state
; /* Parser state */
1136 int comment
; /* Non zero if the next chars may be a comment. */
1137 char missing
; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1138 int missingline
; /* Line number starting the missing token */
1142 * Results of missing quotes, braces, etc. from parsing.
1144 struct JimParseResult
{
1145 char missing
; /* From JimParserCtx.missing */
1146 int line
; /* From JimParserCtx.missingline */
1149 static int JimParseScript(struct JimParserCtx
*pc
);
1150 static int JimParseSep(struct JimParserCtx
*pc
);
1151 static int JimParseEol(struct JimParserCtx
*pc
);
1152 static int JimParseCmd(struct JimParserCtx
*pc
);
1153 static int JimParseQuote(struct JimParserCtx
*pc
);
1154 static int JimParseVar(struct JimParserCtx
*pc
);
1155 static int JimParseBrace(struct JimParserCtx
*pc
);
1156 static int JimParseStr(struct JimParserCtx
*pc
);
1157 static int JimParseComment(struct JimParserCtx
*pc
);
1158 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1159 static int JimParseSubQuote(struct JimParserCtx
*pc
);
1160 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1161 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
);
1163 /* Initialize a parser context.
1164 * 'prg' is a pointer to the program text, linenr is the line
1165 * number of the first line contained in the program. */
1166 static void JimParserInit(struct JimParserCtx
*pc
, const char *prg
, int len
, int linenr
)
1173 pc
->tt
= JIM_TT_NONE
;
1175 pc
->state
= JIM_PS_DEF
;
1176 pc
->linenr
= linenr
;
1179 pc
->missingline
= linenr
;
1182 static int JimParseScript(struct JimParserCtx
*pc
)
1184 while (1) { /* the while is used to reiterate with continue if needed */
1187 pc
->tend
= pc
->p
- 1;
1188 pc
->tline
= pc
->linenr
;
1189 pc
->tt
= JIM_TT_EOL
;
1195 if (*(pc
->p
+ 1) == '\n' && pc
->state
== JIM_PS_DEF
) {
1196 return JimParseSep(pc
);
1200 return JimParseStr(pc
);
1206 if (pc
->state
== JIM_PS_DEF
)
1207 return JimParseSep(pc
);
1210 return JimParseStr(pc
);
1216 if (pc
->state
== JIM_PS_DEF
)
1217 return JimParseEol(pc
);
1219 return JimParseStr(pc
);
1223 return JimParseCmd(pc
);
1227 if (JimParseVar(pc
) == JIM_ERR
) {
1228 pc
->tstart
= pc
->tend
= pc
->p
++;
1230 pc
->tline
= pc
->linenr
;
1231 pc
->tt
= JIM_TT_STR
;
1239 JimParseComment(pc
);
1243 return JimParseStr(pc
);
1247 return JimParseStr(pc
);
1254 static int JimParseSep(struct JimParserCtx
*pc
)
1257 pc
->tline
= pc
->linenr
;
1258 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' ||
1259 (*pc
->p
== '\\' && *(pc
->p
+ 1) == '\n')) {
1260 if (*pc
->p
== '\\') {
1268 pc
->tend
= pc
->p
- 1;
1269 pc
->tt
= JIM_TT_SEP
;
1273 static int JimParseEol(struct JimParserCtx
*pc
)
1276 pc
->tline
= pc
->linenr
;
1277 while (*pc
->p
== ' ' || *pc
->p
== '\n' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== ';') {
1283 pc
->tend
= pc
->p
- 1;
1284 pc
->tt
= JIM_TT_EOL
;
1289 ** Here are the rules for parsing:
1290 ** {braced expression}
1291 ** - Count open and closing braces
1292 ** - Backslash escapes meaning of braces
1294 ** "quoted expression"
1295 ** - First double quote at start of word terminates the expression
1296 ** - Backslash escapes quote and bracket
1297 ** - [commands brackets] are counted/nested
1298 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1300 ** [command expression]
1301 ** - Count open and closing brackets
1302 ** - Backslash escapes quote, bracket and brace
1303 ** - [commands brackets] are counted/nested
1304 ** - "quoted expressions" are parsed according to quoting rules
1305 ** - {braced expressions} are parsed according to brace rules
1307 ** For everything, backslash escapes the next char, newline increments current line
1311 * Parses a braced expression starting at pc->p.
1313 * Positions the parser at the end of the braced expression,
1314 * sets pc->tend and possibly pc->missing.
1316 static void JimParseSubBrace(struct JimParserCtx
*pc
)
1320 /* Skip the brace */
1327 if (*++pc
->p
== '\n') {
1340 pc
->tend
= pc
->p
- 1;
1355 pc
->missingline
= pc
->tline
;
1356 pc
->tend
= pc
->p
- 1;
1360 * Parses a quoted expression starting at pc->p.
1362 * Positions the parser at the end of the quoted expression,
1363 * sets pc->tend and possibly pc->missing.
1365 * Returns the type of the token of the string,
1366 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1369 static int JimParseSubQuote(struct JimParserCtx
*pc
)
1371 int tt
= JIM_TT_STR
;
1372 int line
= pc
->tline
;
1374 /* Skip the quote */
1381 if (*++pc
->p
== '\n') {
1390 pc
->tend
= pc
->p
- 1;
1412 pc
->missingline
= line
;
1413 pc
->tend
= pc
->p
- 1;
1418 * Parses a [command] expression starting at pc->p.
1420 * Positions the parser at the end of the command expression,
1421 * sets pc->tend and possibly pc->missing.
1423 static void JimParseSubCmd(struct JimParserCtx
*pc
)
1426 int startofword
= 1;
1427 int line
= pc
->tline
;
1429 /* Skip the bracket */
1436 if (*++pc
->p
== '\n') {
1449 pc
->tend
= pc
->p
- 1;
1458 JimParseSubQuote(pc
);
1464 JimParseSubBrace(pc
);
1472 startofword
= isspace(UCHAR(*pc
->p
));
1477 pc
->missingline
= line
;
1478 pc
->tend
= pc
->p
- 1;
1481 static int JimParseBrace(struct JimParserCtx
*pc
)
1483 pc
->tstart
= pc
->p
+ 1;
1484 pc
->tline
= pc
->linenr
;
1485 pc
->tt
= JIM_TT_STR
;
1486 JimParseSubBrace(pc
);
1490 static int JimParseCmd(struct JimParserCtx
*pc
)
1492 pc
->tstart
= pc
->p
+ 1;
1493 pc
->tline
= pc
->linenr
;
1494 pc
->tt
= JIM_TT_CMD
;
1499 static int JimParseQuote(struct JimParserCtx
*pc
)
1501 pc
->tstart
= pc
->p
+ 1;
1502 pc
->tline
= pc
->linenr
;
1503 pc
->tt
= JimParseSubQuote(pc
);
1507 static int JimParseVar(struct JimParserCtx
*pc
)
1513 #ifdef EXPRSUGAR_BRACKET
1514 if (*pc
->p
== '[') {
1515 /* Parse $[...] expr shorthand syntax */
1517 pc
->tt
= JIM_TT_EXPRSUGAR
;
1523 pc
->tt
= JIM_TT_VAR
;
1524 pc
->tline
= pc
->linenr
;
1526 if (*pc
->p
== '{') {
1527 pc
->tstart
= ++pc
->p
;
1530 while (pc
->len
&& *pc
->p
!= '}') {
1531 if (*pc
->p
== '\n') {
1537 pc
->tend
= pc
->p
- 1;
1545 /* Skip double colon, but not single colon! */
1546 if (pc
->p
[0] == ':' && pc
->p
[1] == ':') {
1551 if (isalnum(UCHAR(*pc
->p
)) || *pc
->p
== '_') {
1558 /* Parse [dict get] syntax sugar. */
1559 if (*pc
->p
== '(') {
1561 const char *paren
= NULL
;
1563 pc
->tt
= JIM_TT_DICTSUGAR
;
1565 while (count
&& pc
->len
) {
1568 if (*pc
->p
== '\\' && pc
->len
>= 1) {
1572 else if (*pc
->p
== '(') {
1575 else if (*pc
->p
== ')') {
1585 /* Did not find a matching paren. Back up */
1587 pc
->len
+= (pc
->p
- paren
);
1590 #ifndef EXPRSUGAR_BRACKET
1591 if (*pc
->tstart
== '(') {
1592 pc
->tt
= JIM_TT_EXPRSUGAR
;
1596 pc
->tend
= pc
->p
- 1;
1598 /* Check if we parsed just the '$' character.
1599 * That's not a variable so an error is returned
1600 * to tell the state machine to consider this '$' just
1602 if (pc
->tstart
== pc
->p
) {
1610 static int JimParseStr(struct JimParserCtx
*pc
)
1612 int newword
= (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1613 pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_STR
);
1614 if (newword
&& *pc
->p
== '{') {
1615 return JimParseBrace(pc
);
1617 else if (newword
&& *pc
->p
== '"') {
1618 pc
->state
= JIM_PS_QUOTE
;
1621 /* In case the end quote is missing */
1622 pc
->missingline
= pc
->tline
;
1625 pc
->tline
= pc
->linenr
;
1628 if (pc
->state
== JIM_PS_QUOTE
) {
1631 pc
->tend
= pc
->p
- 1;
1632 pc
->tt
= JIM_TT_ESC
;
1637 if (pc
->state
== JIM_PS_DEF
&& *(pc
->p
+ 1) == '\n') {
1638 pc
->tend
= pc
->p
- 1;
1639 pc
->tt
= JIM_TT_ESC
;
1643 if (*(pc
->p
+ 1) == '\n') {
1651 /* If the following token is not '$' just keep going */
1652 if (pc
->len
> 1 && pc
->p
[1] != '$') {
1656 /* Only need a separate ')' token if the previous was a var */
1657 if (*pc
->p
== '(' || pc
->tt
== JIM_TT_VAR
) {
1658 if (pc
->p
== pc
->tstart
) {
1659 /* At the start of the token, so just return this char */
1663 pc
->tend
= pc
->p
- 1;
1664 pc
->tt
= JIM_TT_ESC
;
1671 pc
->tend
= pc
->p
- 1;
1672 pc
->tt
= JIM_TT_ESC
;
1679 if (pc
->state
== JIM_PS_DEF
) {
1680 pc
->tend
= pc
->p
- 1;
1681 pc
->tt
= JIM_TT_ESC
;
1684 else if (*pc
->p
== '\n') {
1689 if (pc
->state
== JIM_PS_QUOTE
) {
1690 pc
->tend
= pc
->p
- 1;
1691 pc
->tt
= JIM_TT_ESC
;
1694 pc
->state
= JIM_PS_DEF
;
1702 return JIM_OK
; /* unreached */
1705 static int JimParseComment(struct JimParserCtx
*pc
)
1708 if (*pc
->p
== '\n') {
1710 if (*(pc
->p
- 1) != '\\') {
1722 /* xdigitval and odigitval are helper functions for JimEscape() */
1723 static int xdigitval(int c
)
1725 if (c
>= '0' && c
<= '9')
1727 if (c
>= 'a' && c
<= 'f')
1728 return c
- 'a' + 10;
1729 if (c
>= 'A' && c
<= 'F')
1730 return c
- 'A' + 10;
1734 static int odigitval(int c
)
1736 if (c
>= '0' && c
<= '7')
1741 /* Perform Tcl escape substitution of 's', storing the result
1742 * string into 'dest'. The escaped string is guaranteed to
1743 * be the same length or shorted than the source string.
1744 * Slen is the length of the string at 's', if it's -1 the string
1745 * length will be calculated by the function.
1747 * The function returns the length of the resulting string. */
1748 static int JimEscape(char *dest
, const char *s
, int slen
)
1756 for (i
= 0; i
< slen
; i
++) {
1786 /* A unicode or hex sequence.
1787 * \u Expect 1-4 hex chars and convert to utf-8.
1788 * \x Expect 1-2 hex chars and convert to hex.
1789 * An invalid sequence means simply the escaped char.
1797 for (k
= 0; k
< (s
[i
] == 'u' ? 4 : 2); k
++) {
1798 int c
= xdigitval(s
[i
+ k
+ 1]);
1802 val
= (val
<< 4) | c
;
1805 /* Got a valid sequence, so convert */
1807 p
+= utf8_fromunicode(p
, val
);
1815 /* Not a valid codepoint, just an escaped char */
1828 /* Replace all spaces and tabs after backslash newline with a single space*/
1832 } while (s
[i
+ 1] == ' ' || s
[i
+ 1] == '\t');
1845 int c
= odigitval(s
[i
+ 1]);
1848 c
= odigitval(s
[i
+ 2]);
1854 val
= (val
* 8) + c
;
1855 c
= odigitval(s
[i
+ 3]);
1861 val
= (val
* 8) + c
;
1882 /* Returns a dynamically allocated copy of the current token in the
1883 * parser context. The function performs conversion of escapes if
1884 * the token is of type JIM_TT_ESC.
1886 * Note that after the conversion, tokens that are grouped with
1887 * braces in the source code, are always recognizable from the
1888 * identical string obtained in a different way from the type.
1890 * For example the string:
1894 * will return as first token "*", of type JIM_TT_STR
1900 * will return as first token "*", of type JIM_TT_ESC
1902 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
)
1904 const char *start
, *end
;
1912 token
= Jim_Alloc(1);
1916 len
= (end
- start
) + 1;
1917 token
= Jim_Alloc(len
+ 1);
1918 if (pc
->tt
!= JIM_TT_ESC
) {
1919 /* No escape conversion needed? Just copy it. */
1920 memcpy(token
, start
, len
);
1924 /* Else convert the escape chars. */
1925 len
= JimEscape(token
, start
, len
);
1929 return Jim_NewStringObjNoAlloc(interp
, token
, len
);
1932 /* Parses the given string to determine if it represents a complete script.
1934 * This is useful for interactive shells implementation, for [info complete].
1936 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1937 * '{' on scripts incomplete missing one or more '}' to be balanced.
1938 * '[' on scripts incomplete missing one or more ']' to be balanced.
1939 * '"' on scripts incomplete missing a '"' char.
1941 * If the script is complete, 1 is returned, otherwise 0.
1943 int Jim_ScriptIsComplete(const char *s
, int len
, char *stateCharPtr
)
1945 struct JimParserCtx parser
;
1947 JimParserInit(&parser
, s
, len
, 1);
1948 while (!parser
.eof
) {
1949 JimParseScript(&parser
);
1952 *stateCharPtr
= parser
.missing
;
1954 return parser
.missing
== ' ';
1957 /* -----------------------------------------------------------------------------
1959 * ---------------------------------------------------------------------------*/
1960 static int JimParseListSep(struct JimParserCtx
*pc
);
1961 static int JimParseListStr(struct JimParserCtx
*pc
);
1962 static int JimParseListQuote(struct JimParserCtx
*pc
);
1964 static int JimParseList(struct JimParserCtx
*pc
)
1971 return JimParseListSep(pc
);
1974 return JimParseListQuote(pc
);
1977 return JimParseBrace(pc
);
1981 return JimParseListStr(pc
);
1986 pc
->tstart
= pc
->tend
= pc
->p
;
1987 pc
->tline
= pc
->linenr
;
1988 pc
->tt
= JIM_TT_EOL
;
1993 static int JimParseListSep(struct JimParserCtx
*pc
)
1996 pc
->tline
= pc
->linenr
;
1997 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== '\n') {
1998 if (*pc
->p
== '\n') {
2004 pc
->tend
= pc
->p
- 1;
2005 pc
->tt
= JIM_TT_SEP
;
2009 static int JimParseListQuote(struct JimParserCtx
*pc
)
2015 pc
->tline
= pc
->linenr
;
2016 pc
->tt
= JIM_TT_STR
;
2021 pc
->tt
= JIM_TT_ESC
;
2022 if (--pc
->len
== 0) {
2023 /* Trailing backslash */
2033 pc
->tend
= pc
->p
- 1;
2042 pc
->tend
= pc
->p
- 1;
2046 static int JimParseListStr(struct JimParserCtx
*pc
)
2049 pc
->tline
= pc
->linenr
;
2050 pc
->tt
= JIM_TT_STR
;
2055 if (--pc
->len
== 0) {
2056 /* Trailing backslash */
2060 pc
->tt
= JIM_TT_ESC
;
2067 pc
->tend
= pc
->p
- 1;
2073 pc
->tend
= pc
->p
- 1;
2077 /* -----------------------------------------------------------------------------
2078 * Jim_Obj related functions
2079 * ---------------------------------------------------------------------------*/
2081 /* Return a new initialized object. */
2082 Jim_Obj
*Jim_NewObj(Jim_Interp
*interp
)
2086 /* -- Check if there are objects in the free list -- */
2087 if (interp
->freeList
!= NULL
) {
2088 /* -- Unlink the object from the free list -- */
2089 objPtr
= interp
->freeList
;
2090 interp
->freeList
= objPtr
->nextObjPtr
;
2093 /* -- No ready to use objects: allocate a new one -- */
2094 objPtr
= Jim_Alloc(sizeof(*objPtr
));
2097 /* Object is returned with refCount of 0. Every
2098 * kind of GC implemented should take care to don't try
2099 * to scan objects with refCount == 0. */
2100 objPtr
->refCount
= 0;
2101 /* All the other fields are left not initialized to save time.
2102 * The caller will probably want to set them to the right
2105 /* -- Put the object into the live list -- */
2106 objPtr
->prevObjPtr
= NULL
;
2107 objPtr
->nextObjPtr
= interp
->liveList
;
2108 if (interp
->liveList
)
2109 interp
->liveList
->prevObjPtr
= objPtr
;
2110 interp
->liveList
= objPtr
;
2115 /* Free an object. Actually objects are never freed, but
2116 * just moved to the free objects list, where they will be
2117 * reused by Jim_NewObj(). */
2118 void Jim_FreeObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2120 /* Check if the object was already freed, panic. */
2121 JimPanic((objPtr
->refCount
!= 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr
,
2122 objPtr
->refCount
, objPtr
->typePtr
? objPtr
->typePtr
->name
: "<none>"));
2124 /* Free the internal representation */
2125 Jim_FreeIntRep(interp
, objPtr
);
2126 /* Free the string representation */
2127 if (objPtr
->bytes
!= NULL
) {
2128 if (objPtr
->bytes
!= JimEmptyStringRep
)
2129 Jim_Free(objPtr
->bytes
);
2131 /* Unlink the object from the live objects list */
2132 if (objPtr
->prevObjPtr
)
2133 objPtr
->prevObjPtr
->nextObjPtr
= objPtr
->nextObjPtr
;
2134 if (objPtr
->nextObjPtr
)
2135 objPtr
->nextObjPtr
->prevObjPtr
= objPtr
->prevObjPtr
;
2136 if (interp
->liveList
== objPtr
)
2137 interp
->liveList
= objPtr
->nextObjPtr
;
2138 /* Link the object into the free objects list */
2139 objPtr
->prevObjPtr
= NULL
;
2140 objPtr
->nextObjPtr
= interp
->freeList
;
2141 if (interp
->freeList
)
2142 interp
->freeList
->prevObjPtr
= objPtr
;
2143 interp
->freeList
= objPtr
;
2144 objPtr
->refCount
= -1;
2147 /* Invalidate the string representation of an object. */
2148 void Jim_InvalidateStringRep(Jim_Obj
*objPtr
)
2150 if (objPtr
->bytes
!= NULL
) {
2151 if (objPtr
->bytes
!= JimEmptyStringRep
)
2152 Jim_Free(objPtr
->bytes
);
2154 objPtr
->bytes
= NULL
;
2157 #define Jim_SetStringRep(o, b, l) \
2158 do { (o)->bytes = b; (o)->length = l; } while (0)
2160 /* Set the initial string representation for an object.
2161 * Does not try to free an old one. */
2162 void Jim_InitStringRep(Jim_Obj
*objPtr
, const char *bytes
, int length
)
2165 objPtr
->bytes
= JimEmptyStringRep
;
2169 objPtr
->bytes
= Jim_Alloc(length
+ 1);
2170 objPtr
->length
= length
;
2171 memcpy(objPtr
->bytes
, bytes
, length
);
2172 objPtr
->bytes
[length
] = '\0';
2176 /* Duplicate an object. The returned object has refcount = 0. */
2177 Jim_Obj
*Jim_DuplicateObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2181 dupPtr
= Jim_NewObj(interp
);
2182 if (objPtr
->bytes
== NULL
) {
2183 /* Object does not have a valid string representation. */
2184 dupPtr
->bytes
= NULL
;
2187 Jim_InitStringRep(dupPtr
, objPtr
->bytes
, objPtr
->length
);
2190 /* By default, the new object has the same type as the old object */
2191 dupPtr
->typePtr
= objPtr
->typePtr
;
2192 if (objPtr
->typePtr
!= NULL
) {
2193 if (objPtr
->typePtr
->dupIntRepProc
== NULL
) {
2194 dupPtr
->internalRep
= objPtr
->internalRep
;
2197 /* The dup proc may set a different type, e.g. NULL */
2198 objPtr
->typePtr
->dupIntRepProc(interp
, objPtr
, dupPtr
);
2204 /* Return the string representation for objPtr. If the object
2205 * string representation is invalid, calls the method to create
2206 * a new one starting from the internal representation of the object. */
2207 const char *Jim_GetString(Jim_Obj
*objPtr
, int *lenPtr
)
2209 if (objPtr
->bytes
== NULL
) {
2210 /* Invalid string repr. Generate it. */
2211 JimPanic((objPtr
->typePtr
->updateStringProc
== NULL
, "UpdateStringProc called against '%s' type.", objPtr
->typePtr
->name
));
2212 objPtr
->typePtr
->updateStringProc(objPtr
);
2215 *lenPtr
= objPtr
->length
;
2216 return objPtr
->bytes
;
2219 /* Just returns the length of the object's string rep */
2220 int Jim_Length(Jim_Obj
*objPtr
)
2224 Jim_GetString(objPtr
, &len
);
2228 static void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2229 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2231 static const Jim_ObjType dictSubstObjType
= {
2232 "dict-substitution",
2233 FreeDictSubstInternalRep
,
2234 DupDictSubstInternalRep
,
2239 static void FreeInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2241 Jim_DecrRefCount(interp
, (Jim_Obj
*)objPtr
->internalRep
.twoPtrValue
.ptr2
);
2244 static const Jim_ObjType interpolatedObjType
= {
2246 FreeInterpolatedInternalRep
,
2252 /* -----------------------------------------------------------------------------
2254 * ---------------------------------------------------------------------------*/
2255 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2256 static int SetStringFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2258 static const Jim_ObjType stringObjType
= {
2261 DupStringInternalRep
,
2263 JIM_TYPE_REFERENCES
,
2266 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2268 JIM_NOTUSED(interp
);
2270 /* This is a bit subtle: the only caller of this function
2271 * should be Jim_DuplicateObj(), that will copy the
2272 * string representaion. After the copy, the duplicated
2273 * object will not have more room in teh buffer than
2274 * srcPtr->length bytes. So we just set it to length. */
2275 dupPtr
->internalRep
.strValue
.maxLength
= srcPtr
->length
;
2277 dupPtr
->internalRep
.strValue
.charLength
= srcPtr
->internalRep
.strValue
.charLength
;
2280 static int SetStringFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2282 /* Get a fresh string representation. */
2283 (void)Jim_String(objPtr
);
2284 /* Free any other internal representation. */
2285 Jim_FreeIntRep(interp
, objPtr
);
2286 /* Set it as string, i.e. just set the maxLength field. */
2287 objPtr
->typePtr
= &stringObjType
;
2288 objPtr
->internalRep
.strValue
.maxLength
= objPtr
->length
;
2289 /* Don't know the utf-8 length yet */
2290 objPtr
->internalRep
.strValue
.charLength
= -1;
2295 * Returns the length of the object string in chars, not bytes.
2297 * These may be different for a utf-8 string.
2299 int Jim_Utf8Length(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2302 if (objPtr
->typePtr
!= &stringObjType
)
2303 SetStringFromAny(interp
, objPtr
);
2305 if (objPtr
->internalRep
.strValue
.charLength
< 0) {
2306 objPtr
->internalRep
.strValue
.charLength
= utf8_strlen(objPtr
->bytes
, objPtr
->length
);
2308 return objPtr
->internalRep
.strValue
.charLength
;
2310 return Jim_Length(objPtr
);
2314 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2315 Jim_Obj
*Jim_NewStringObj(Jim_Interp
*interp
, const char *s
, int len
)
2317 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2319 /* Need to find out how many bytes the string requires */
2322 /* Alloc/Set the string rep. */
2324 objPtr
->bytes
= JimEmptyStringRep
;
2328 objPtr
->bytes
= Jim_Alloc(len
+ 1);
2329 objPtr
->length
= len
;
2330 memcpy(objPtr
->bytes
, s
, len
);
2331 objPtr
->bytes
[len
] = '\0';
2334 /* No typePtr field for the vanilla string object. */
2335 objPtr
->typePtr
= NULL
;
2339 /* charlen is in characters -- see also Jim_NewStringObj() */
2340 Jim_Obj
*Jim_NewStringObjUtf8(Jim_Interp
*interp
, const char *s
, int charlen
)
2343 /* Need to find out how many bytes the string requires */
2344 int bytelen
= utf8_index(s
, charlen
);
2346 Jim_Obj
*objPtr
= Jim_NewStringObj(interp
, s
, bytelen
);
2348 /* Remember the utf8 length, so set the type */
2349 objPtr
->typePtr
= &stringObjType
;
2350 objPtr
->internalRep
.strValue
.maxLength
= bytelen
;
2351 objPtr
->internalRep
.strValue
.charLength
= charlen
;
2355 return Jim_NewStringObj(interp
, s
, charlen
);
2359 /* This version does not try to duplicate the 's' pointer, but
2360 * use it directly. */
2361 Jim_Obj
*Jim_NewStringObjNoAlloc(Jim_Interp
*interp
, char *s
, int len
)
2363 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2367 Jim_SetStringRep(objPtr
, s
, len
);
2368 objPtr
->typePtr
= NULL
;
2372 /* Low-level string append. Use it only against objects
2373 * of type "string". */
2374 static void StringAppendString(Jim_Obj
*objPtr
, const char *str
, int len
)
2380 needlen
= objPtr
->length
+ len
;
2381 if (objPtr
->internalRep
.strValue
.maxLength
< needlen
||
2382 objPtr
->internalRep
.strValue
.maxLength
== 0) {
2384 /* Inefficient to malloc() for less than 8 bytes */
2388 if (objPtr
->bytes
== JimEmptyStringRep
) {
2389 objPtr
->bytes
= Jim_Alloc(needlen
+ 1);
2392 objPtr
->bytes
= Jim_Realloc(objPtr
->bytes
, needlen
+ 1);
2394 objPtr
->internalRep
.strValue
.maxLength
= needlen
;
2396 memcpy(objPtr
->bytes
+ objPtr
->length
, str
, len
);
2397 objPtr
->bytes
[objPtr
->length
+ len
] = '\0';
2398 if (objPtr
->internalRep
.strValue
.charLength
>= 0) {
2399 /* Update the utf-8 char length */
2400 objPtr
->internalRep
.strValue
.charLength
+= utf8_strlen(objPtr
->bytes
+ objPtr
->length
, len
);
2402 objPtr
->length
+= len
;
2405 /* Higher level API to append strings to objects. */
2406 void Jim_AppendString(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
, int len
)
2408 JimPanic((Jim_IsShared(objPtr
), "Jim_AppendString called with shared object"));
2409 if (objPtr
->typePtr
!= &stringObjType
)
2410 SetStringFromAny(interp
, objPtr
);
2411 StringAppendString(objPtr
, str
, len
);
2414 void Jim_AppendObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*appendObjPtr
)
2419 str
= Jim_GetString(appendObjPtr
, &len
);
2420 Jim_AppendString(interp
, objPtr
, str
, len
);
2423 void Jim_AppendStrings(Jim_Interp
*interp
, Jim_Obj
*objPtr
, ...)
2427 if (objPtr
->typePtr
!= &stringObjType
)
2428 SetStringFromAny(interp
, objPtr
);
2429 va_start(ap
, objPtr
);
2431 char *s
= va_arg(ap
, char *);
2435 Jim_AppendString(interp
, objPtr
, s
, -1);
2440 int Jim_StringEqObj(Jim_Obj
*aObjPtr
, Jim_Obj
*bObjPtr
)
2442 const char *aStr
, *bStr
;
2445 if (aObjPtr
== bObjPtr
)
2447 aStr
= Jim_GetString(aObjPtr
, &aLen
);
2448 bStr
= Jim_GetString(bObjPtr
, &bLen
);
2451 return JimStringCompare(aStr
, aLen
, bStr
, bLen
) == 0;
2454 int Jim_StringMatchObj(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, Jim_Obj
*objPtr
, int nocase
)
2456 return JimStringMatch(interp
, patternObjPtr
, Jim_String(objPtr
), nocase
);
2459 int Jim_StringCompareObj(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*secondObjPtr
, int nocase
)
2461 const char *s1
, *s2
;
2464 s1
= Jim_GetString(firstObjPtr
, &l1
);
2465 s2
= Jim_GetString(secondObjPtr
, &l2
);
2468 return JimStringCompareNoCase(s1
, s2
, -1);
2470 return JimStringCompare(s1
, l1
, s2
, l2
);
2473 /* Convert a range, as returned by Jim_GetRange(), into
2474 * an absolute index into an object of the specified length.
2475 * This function may return negative values, or values
2476 * bigger or equal to the length of the list if the index
2477 * is out of range. */
2478 static int JimRelToAbsIndex(int len
, int idx
)
2485 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2486 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2487 * for implementation of commands like [string range] and [lrange].
2489 * The resulting range is guaranteed to address valid elements of
2491 static void JimRelToAbsRange(int len
, int first
, int last
,
2492 int *firstPtr
, int *lastPtr
, int *rangeLenPtr
)
2500 rangeLen
= last
- first
+ 1;
2507 rangeLen
-= (last
- (len
- 1));
2517 *rangeLenPtr
= rangeLen
;
2520 Jim_Obj
*Jim_StringByteRangeObj(Jim_Interp
*interp
,
2521 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2528 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2529 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2531 str
= Jim_GetString(strObjPtr
, &bytelen
);
2532 first
= JimRelToAbsIndex(bytelen
, first
);
2533 last
= JimRelToAbsIndex(bytelen
, last
);
2534 JimRelToAbsRange(bytelen
, first
, last
, &first
, &last
, &rangeLen
);
2535 if (first
== 0 && rangeLen
== bytelen
) {
2538 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2541 Jim_Obj
*Jim_StringRangeObj(Jim_Interp
*interp
,
2542 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2550 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2551 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2553 str
= Jim_GetString(strObjPtr
, &bytelen
);
2554 len
= Jim_Utf8Length(interp
, strObjPtr
);
2555 first
= JimRelToAbsIndex(len
, first
);
2556 last
= JimRelToAbsIndex(len
, last
);
2557 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
2558 if (first
== 0 && rangeLen
== len
) {
2561 if (len
== bytelen
) {
2562 /* ASCII optimisation */
2563 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2565 return Jim_NewStringObjUtf8(interp
, str
+ utf8_index(str
, first
), rangeLen
);
2567 return Jim_StringByteRangeObj(interp
, strObjPtr
, firstObjPtr
, lastObjPtr
);
2571 static Jim_Obj
*JimStringToLower(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2577 if (strObjPtr
->typePtr
!= &stringObjType
) {
2578 SetStringFromAny(interp
, strObjPtr
);
2581 str
= Jim_GetString(strObjPtr
, &len
);
2583 buf
= p
= Jim_Alloc(len
+ 1);
2586 str
+= utf8_tounicode(str
, &c
);
2587 p
+= utf8_fromunicode(p
, utf8_lower(c
));
2590 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2593 static Jim_Obj
*JimStringToUpper(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2599 if (strObjPtr
->typePtr
!= &stringObjType
) {
2600 SetStringFromAny(interp
, strObjPtr
);
2603 str
= Jim_GetString(strObjPtr
, &len
);
2605 buf
= p
= Jim_Alloc(len
+ 1);
2608 str
+= utf8_tounicode(str
, &c
);
2609 p
+= utf8_fromunicode(p
, utf8_upper(c
));
2612 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2615 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2616 * for unicode character 'c'.
2617 * Returns the position if found or NULL if not
2619 static const char *utf8_memchr(const char *str
, int len
, int c
)
2624 int n
= utf8_tounicode(str
, &sc
);
2633 return memchr(str
, c
, len
);
2638 * Searches for the first non-trim char in string (str, len)
2640 * If none is found, returns just past the last char.
2642 * Lengths are in bytes.
2644 static const char *JimFindTrimLeft(const char *str
, int len
, const char *trimchars
, int trimlen
)
2648 int n
= utf8_tounicode(str
, &c
);
2650 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2651 /* Not a trim char, so stop */
2661 * Searches backwards for a non-trim char in string (str, len).
2663 * Returns a pointer to just after the non-trim char, or NULL if not found.
2665 * Lengths are in bytes.
2667 static const char *JimFindTrimRight(const char *str
, int len
, const char *trimchars
, int trimlen
)
2673 int n
= utf8_prev_len(str
, len
);
2678 n
= utf8_tounicode(str
, &c
);
2680 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2688 static const char default_trim_chars
[] = " \t\n\r";
2689 /* sizeof() here includes the null byte */
2690 static int default_trim_chars_len
= sizeof(default_trim_chars
);
2692 static Jim_Obj
*JimStringTrimLeft(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2695 const char *str
= Jim_GetString(strObjPtr
, &len
);
2696 const char *trimchars
= default_trim_chars
;
2697 int trimcharslen
= default_trim_chars_len
;
2700 if (trimcharsObjPtr
) {
2701 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2704 newstr
= JimFindTrimLeft(str
, len
, trimchars
, trimcharslen
);
2705 if (newstr
== str
) {
2709 return Jim_NewStringObj(interp
, newstr
, len
- (newstr
- str
));
2712 static Jim_Obj
*JimStringTrimRight(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2715 const char *trimchars
= default_trim_chars
;
2716 int trimcharslen
= default_trim_chars_len
;
2717 const char *nontrim
;
2719 if (trimcharsObjPtr
) {
2720 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2723 if (strObjPtr
->typePtr
!= &stringObjType
) {
2724 SetStringFromAny(interp
, strObjPtr
);
2726 len
= Jim_Length(strObjPtr
);
2727 nontrim
= JimFindTrimRight(strObjPtr
->bytes
, len
, trimchars
, trimcharslen
);
2729 if (nontrim
== NULL
) {
2730 /* All trim, so return a zero-length string */
2731 return Jim_NewEmptyStringObj(interp
);
2733 if (nontrim
== strObjPtr
->bytes
+ len
) {
2737 if (Jim_IsShared(strObjPtr
)) {
2738 strObjPtr
= Jim_NewStringObj(interp
, strObjPtr
->bytes
, (nontrim
- strObjPtr
->bytes
));
2741 /* Can modify this string in place */
2742 strObjPtr
->bytes
[nontrim
- strObjPtr
->bytes
] = 0;
2743 strObjPtr
->length
= (nontrim
- strObjPtr
->bytes
);
2749 static Jim_Obj
*JimStringTrim(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2751 /* First trim left. */
2752 Jim_Obj
*objPtr
= JimStringTrimLeft(interp
, strObjPtr
, trimcharsObjPtr
);
2754 /* Now trim right */
2755 strObjPtr
= JimStringTrimRight(interp
, objPtr
, trimcharsObjPtr
);
2757 if (objPtr
!= strObjPtr
) {
2758 /* Note that we don't want this object to be leaked */
2759 Jim_IncrRefCount(objPtr
);
2760 Jim_DecrRefCount(interp
, objPtr
);
2767 static int JimStringIs(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*strClass
, int strict
)
2769 static const char * const strclassnames
[] = {
2770 "integer", "alpha", "alnum", "ascii", "digit",
2771 "double", "lower", "upper", "space", "xdigit",
2772 "control", "print", "graph", "punct",
2776 STR_IS_INTEGER
, STR_IS_ALPHA
, STR_IS_ALNUM
, STR_IS_ASCII
, STR_IS_DIGIT
,
2777 STR_IS_DOUBLE
, STR_IS_LOWER
, STR_IS_UPPER
, STR_IS_SPACE
, STR_IS_XDIGIT
,
2778 STR_IS_CONTROL
, STR_IS_PRINT
, STR_IS_GRAPH
, STR_IS_PUNCT
2784 int (*isclassfunc
)(int c
) = NULL
;
2786 if (Jim_GetEnum(interp
, strClass
, strclassnames
, &strclass
, "class", JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
2790 str
= Jim_GetString(strObjPtr
, &len
);
2792 Jim_SetResultInt(interp
, !strict
);
2797 case STR_IS_INTEGER
:
2800 Jim_SetResultInt(interp
, JimGetWideNoErr(interp
, strObjPtr
, &w
) == JIM_OK
);
2807 Jim_SetResultInt(interp
, Jim_GetDouble(interp
, strObjPtr
, &d
) == JIM_OK
&& errno
!= ERANGE
);
2811 case STR_IS_ALPHA
: isclassfunc
= isalpha
; break;
2812 case STR_IS_ALNUM
: isclassfunc
= isalnum
; break;
2813 case STR_IS_ASCII
: isclassfunc
= isascii
; break;
2814 case STR_IS_DIGIT
: isclassfunc
= isdigit
; break;
2815 case STR_IS_LOWER
: isclassfunc
= islower
; break;
2816 case STR_IS_UPPER
: isclassfunc
= isupper
; break;
2817 case STR_IS_SPACE
: isclassfunc
= isspace
; break;
2818 case STR_IS_XDIGIT
: isclassfunc
= isxdigit
; break;
2819 case STR_IS_CONTROL
: isclassfunc
= iscntrl
; break;
2820 case STR_IS_PRINT
: isclassfunc
= isprint
; break;
2821 case STR_IS_GRAPH
: isclassfunc
= isgraph
; break;
2822 case STR_IS_PUNCT
: isclassfunc
= ispunct
; break;
2827 for (i
= 0; i
< len
; i
++) {
2828 if (!isclassfunc(str
[i
])) {
2829 Jim_SetResultInt(interp
, 0);
2833 Jim_SetResultInt(interp
, 1);
2837 /* -----------------------------------------------------------------------------
2838 * Compared String Object
2839 * ---------------------------------------------------------------------------*/
2841 /* This is strange object that allows to compare a C literal string
2842 * with a Jim object in very short time if the same comparison is done
2843 * multiple times. For example every time the [if] command is executed,
2844 * Jim has to check if a given argument is "else". This comparions if
2845 * the code has no errors are true most of the times, so we can cache
2846 * inside the object the pointer of the string of the last matching
2847 * comparison. Because most C compilers perform literal sharing,
2848 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2849 * this works pretty well even if comparisons are at different places
2850 * inside the C code. */
2852 static const Jim_ObjType comparedStringObjType
= {
2857 JIM_TYPE_REFERENCES
,
2860 /* The only way this object is exposed to the API is via the following
2861 * function. Returns true if the string and the object string repr.
2862 * are the same, otherwise zero is returned.
2864 * Note: this isn't binary safe, but it hardly needs to be.*/
2865 int Jim_CompareStringImmediate(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
)
2867 if (objPtr
->typePtr
== &comparedStringObjType
&& objPtr
->internalRep
.ptr
== str
)
2870 const char *objStr
= Jim_String(objPtr
);
2872 if (strcmp(str
, objStr
) != 0)
2874 if (objPtr
->typePtr
!= &comparedStringObjType
) {
2875 Jim_FreeIntRep(interp
, objPtr
);
2876 objPtr
->typePtr
= &comparedStringObjType
;
2878 objPtr
->internalRep
.ptr
= (char *)str
; /*ATTENTION: const cast */
2883 static int qsortCompareStringPointers(const void *a
, const void *b
)
2885 char *const *sa
= (char *const *)a
;
2886 char *const *sb
= (char *const *)b
;
2888 return strcmp(*sa
, *sb
);
2892 /* -----------------------------------------------------------------------------
2895 * This object is just a string from the language point of view, but
2896 * in the internal representation it contains the filename and line number
2897 * where this given token was read. This information is used by
2898 * Jim_EvalObj() if the object passed happens to be of type "source".
2900 * This allows to propagate the information about line numbers and file
2901 * names and give error messages with absolute line numbers.
2903 * Note that this object uses shared strings for filenames, and the
2904 * pointer to the filename together with the line number is taken into
2905 * the space for the "inline" internal representation of the Jim_Object,
2906 * so there is almost memory zero-overhead.
2908 * Also the object will be converted to something else if the given
2909 * token it represents in the source file is not something to be
2910 * evaluated (not a script), and will be specialized in some other way,
2911 * so the time overhead is also null.
2912 * ---------------------------------------------------------------------------*/
2914 static void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2915 static void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2917 static const Jim_ObjType sourceObjType
= {
2919 FreeSourceInternalRep
,
2920 DupSourceInternalRep
,
2922 JIM_TYPE_REFERENCES
,
2925 void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2927 Jim_DecrRefCount(interp
, objPtr
->internalRep
.sourceValue
.fileNameObj
);
2930 void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2932 dupPtr
->internalRep
= srcPtr
->internalRep
;
2933 Jim_IncrRefCount(dupPtr
->internalRep
.sourceValue
.fileNameObj
);
2936 static void JimSetSourceInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2937 Jim_Obj
*fileNameObj
, int lineNumber
)
2939 JimPanic((Jim_IsShared(objPtr
), "JimSetSourceInfo called with shared object"));
2940 JimPanic((objPtr
->typePtr
!= NULL
, "JimSetSourceInfo called with typePtr != NULL"));
2941 Jim_IncrRefCount(fileNameObj
);
2942 objPtr
->internalRep
.sourceValue
.fileNameObj
= fileNameObj
;
2943 objPtr
->internalRep
.sourceValue
.lineNumber
= lineNumber
;
2944 objPtr
->typePtr
= &sourceObjType
;
2947 /* -----------------------------------------------------------------------------
2949 * ---------------------------------------------------------------------------*/
2951 static const Jim_ObjType scriptLineObjType
= {
2959 static Jim_Obj
*JimNewScriptLineObj(Jim_Interp
*interp
, int argc
, int line
)
2963 #ifdef DEBUG_SHOW_SCRIPT
2965 snprintf(buf
, sizeof(buf
), "line=%d, argc=%d", line
, argc
);
2966 objPtr
= Jim_NewStringObj(interp
, buf
, -1);
2968 objPtr
= Jim_NewEmptyStringObj(interp
);
2970 objPtr
->typePtr
= &scriptLineObjType
;
2971 objPtr
->internalRep
.scriptLineValue
.argc
= argc
;
2972 objPtr
->internalRep
.scriptLineValue
.line
= line
;
2977 #define JIM_CMDSTRUCT_EXPAND -1
2979 static void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2980 static void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2981 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
);
2983 static const Jim_ObjType scriptObjType
= {
2985 FreeScriptInternalRep
,
2986 DupScriptInternalRep
,
2988 JIM_TYPE_REFERENCES
,
2991 /* The ScriptToken structure represents every token into a scriptObj.
2992 * Every token contains an associated Jim_Obj that can be specialized
2993 * by commands operating on it. */
2994 typedef struct ScriptToken
3000 /* This is the script object internal representation. An array of
3001 * ScriptToken structures, including a pre-computed representation of the
3002 * command length and arguments.
3004 * For example the script:
3007 * set $i $x$y [foo]BAR
3009 * will produce a ScriptObj with the following Tokens:
3024 * "puts hello" has two args (LIN 2), composed of single tokens.
3025 * (Note that the WRD token is omitted for the common case of a single token.)
3027 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
3028 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
3030 * The precomputation of the command structure makes Jim_Eval() faster,
3031 * and simpler because there aren't dynamic lengths / allocations.
3033 * -- {expand}/{*} handling --
3035 * Expand is handled in a special way.
3037 * If a "word" begins with {*}, the word token count is -ve.
3039 * For example the command:
3043 * Will produce the following cmdstruct array:
3050 * Note that the 'LIN' token also contains the source information for the
3051 * first word of the line for error reporting purposes
3053 * -- the substFlags field of the structure --
3055 * The scriptObj structure is used to represent both "script" objects
3056 * and "subst" objects. In the second case, the there are no LIN and WRD
3057 * tokens. Instead SEP and EOL tokens are added as-is.
3058 * In addition, the field 'substFlags' is used to represent the flags used to turn
3059 * the string into the internal representation used to perform the
3060 * substitution. If this flags are not what the application requires
3061 * the scriptObj is created again. For example the script:
3063 * subst -nocommands $string
3064 * subst -novariables $string
3066 * Will recreate the internal representation of the $string object
3069 typedef struct ScriptObj
3071 int len
; /* Length as number of tokens. */
3072 ScriptToken
*token
; /* Tokens array. */
3073 int substFlags
; /* flags used for the compilation of "subst" objects */
3074 int inUse
; /* Used to share a ScriptObj. Currently
3075 only used by Jim_EvalObj() as protection against
3076 shimmering of the currently evaluated object. */
3077 Jim_Obj
*fileNameObj
;
3078 int line
; /* Line number of the first line */
3081 void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3084 struct ScriptObj
*script
= (void *)objPtr
->internalRep
.ptr
;
3087 if (script
->inUse
!= 0)
3089 for (i
= 0; i
< script
->len
; i
++) {
3090 Jim_DecrRefCount(interp
, script
->token
[i
].objPtr
);
3092 Jim_Free(script
->token
);
3093 Jim_DecrRefCount(interp
, script
->fileNameObj
);
3097 void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
3099 JIM_NOTUSED(interp
);
3100 JIM_NOTUSED(srcPtr
);
3102 /* Just returns an simple string. */
3103 dupPtr
->typePtr
= NULL
;
3106 /* A simple parser token.
3107 * All the simple tokens for the script point into the same script string rep.
3111 const char *token
; /* Pointer to the start of the token */
3112 int len
; /* Length of this token */
3113 int type
; /* Token type */
3114 int line
; /* Line number */
3117 /* A list of parsed tokens representing a script.
3118 * Tokens are added to this list as the script is parsed.
3119 * It grows as needed.
3123 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3124 ParseToken
*list
; /* Array of tokens */
3125 int size
; /* Current size of the list */
3126 int count
; /* Number of entries used */
3127 ParseToken static_list
[20]; /* Small initial token space to avoid allocation */
3130 static void ScriptTokenListInit(ParseTokenList
*tokenlist
)
3132 tokenlist
->list
= tokenlist
->static_list
;
3133 tokenlist
->size
= sizeof(tokenlist
->static_list
) / sizeof(ParseToken
);
3134 tokenlist
->count
= 0;
3137 static void ScriptTokenListFree(ParseTokenList
*tokenlist
)
3139 if (tokenlist
->list
!= tokenlist
->static_list
) {
3140 Jim_Free(tokenlist
->list
);
3145 * Adds the new token to the tokenlist.
3146 * The token has the given length, type and line number.
3147 * The token list is resized as necessary.
3149 static void ScriptAddToken(ParseTokenList
*tokenlist
, const char *token
, int len
, int type
,
3154 if (tokenlist
->count
== tokenlist
->size
) {
3155 /* Resize the list */
3156 tokenlist
->size
*= 2;
3157 if (tokenlist
->list
!= tokenlist
->static_list
) {
3159 Jim_Realloc(tokenlist
->list
, tokenlist
->size
* sizeof(*tokenlist
->list
));
3162 /* The list needs to become allocated */
3163 tokenlist
->list
= Jim_Alloc(tokenlist
->size
* sizeof(*tokenlist
->list
));
3164 memcpy(tokenlist
->list
, tokenlist
->static_list
,
3165 tokenlist
->count
* sizeof(*tokenlist
->list
));
3168 t
= &tokenlist
->list
[tokenlist
->count
++];
3175 /* Counts the number of adjoining non-separator.
3177 * Returns -ve if the first token is the expansion
3178 * operator (in which case the count doesn't include
3181 static int JimCountWordTokens(ParseToken
*t
)
3186 /* Is the first word {*} or {expand}? */
3187 if (t
->type
== JIM_TT_STR
&& !TOKEN_IS_SEP(t
[1].type
)) {
3188 if ((t
->len
== 1 && *t
->token
== '*') || (t
->len
== 6 && strncmp(t
->token
, "expand", 6) == 0)) {
3189 /* Create an expand token */
3195 /* Now count non-separator words */
3196 while (!TOKEN_IS_SEP(t
->type
)) {
3201 return count
* expand
;
3205 * Create a script/subst object from the given token.
3207 static Jim_Obj
*JimMakeScriptObj(Jim_Interp
*interp
, const ParseToken
*t
)
3211 if (t
->type
== JIM_TT_ESC
&& memchr(t
->token
, '\\', t
->len
) != NULL
) {
3212 /* Convert the backlash escapes . */
3214 char *str
= Jim_Alloc(len
+ 1);
3215 len
= JimEscape(str
, t
->token
, len
);
3216 objPtr
= Jim_NewStringObjNoAlloc(interp
, str
, len
);
3219 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3220 * with a single space. This is currently not done.
3222 objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
3228 * Takes a tokenlist and creates the allocated list of script tokens
3229 * in script->token, of length script->len.
3231 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3234 * Also sets script->line to the line number of the first token
3236 static void ScriptObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3237 ParseTokenList
*tokenlist
)
3240 struct ScriptToken
*token
;
3241 /* Number of tokens so far for the current command */
3243 /* This is the first token for the current command */
3244 ScriptToken
*linefirst
;
3248 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3249 printf("==== Tokens ====\n");
3250 for (i
= 0; i
< tokenlist
->count
; i
++) {
3251 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
->list
[i
].line
, jim_tt_name(tokenlist
->list
[i
].type
),
3252 tokenlist
->list
[i
].len
, tokenlist
->list
[i
].token
);
3256 /* May need up to one extra script token for each EOL in the worst case */
3257 count
= tokenlist
->count
;
3258 for (i
= 0; i
< tokenlist
->count
; i
++) {
3259 if (tokenlist
->list
[i
].type
== JIM_TT_EOL
) {
3263 linenr
= script
->line
= tokenlist
->list
[0].line
;
3265 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
3267 /* This is the first token for the current command */
3268 linefirst
= token
++;
3270 for (i
= 0; i
< tokenlist
->count
; ) {
3271 /* Look ahead to find out how many tokens make up the next word */
3274 /* Skip any leading separators */
3275 while (tokenlist
->list
[i
].type
== JIM_TT_SEP
) {
3279 wordtokens
= JimCountWordTokens(tokenlist
->list
+ i
);
3281 if (wordtokens
== 0) {
3282 /* None, so at end of line */
3284 linefirst
->type
= JIM_TT_LINE
;
3285 linefirst
->objPtr
= JimNewScriptLineObj(interp
, lineargs
, linenr
);
3286 Jim_IncrRefCount(linefirst
->objPtr
);
3288 /* Reset for new line */
3290 linefirst
= token
++;
3295 else if (wordtokens
!= 1) {
3296 /* More than 1, or {expand}, so insert a WORD token */
3297 token
->type
= JIM_TT_WORD
;
3298 token
->objPtr
= Jim_NewIntObj(interp
, wordtokens
);
3299 Jim_IncrRefCount(token
->objPtr
);
3301 if (wordtokens
< 0) {
3302 /* Skip the expand token */
3304 wordtokens
= -wordtokens
- 1;
3309 if (lineargs
== 0) {
3310 /* First real token on the line, so record the line number */
3311 linenr
= tokenlist
->list
[i
].line
;
3315 /* Add each non-separator word token to the line */
3316 while (wordtokens
--) {
3317 const ParseToken
*t
= &tokenlist
->list
[i
++];
3319 token
->type
= t
->type
;
3320 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3321 Jim_IncrRefCount(token
->objPtr
);
3323 /* Every object is initially a string, but the
3324 * internal type may be specialized during execution of the
3326 JimSetSourceInfo(interp
, token
->objPtr
, script
->fileNameObj
, t
->line
);
3331 if (lineargs
== 0) {
3335 script
->len
= token
- script
->token
;
3337 assert(script
->len
< count
);
3339 #ifdef DEBUG_SHOW_SCRIPT
3340 printf("==== Script (%s) ====\n", Jim_String(script
->fileNameObj
));
3341 for (i
= 0; i
< script
->len
; i
++) {
3342 const ScriptToken
*t
= &script
->token
[i
];
3343 printf("[%2d] %s %s\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
3350 * Similar to ScriptObjAddTokens(), but for subst objects.
3352 static void SubstObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3353 ParseTokenList
*tokenlist
)
3356 struct ScriptToken
*token
;
3358 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * tokenlist
->count
);
3360 for (i
= 0; i
< tokenlist
->count
; i
++) {
3361 const ParseToken
*t
= &tokenlist
->list
[i
];
3363 /* Create a token for 't' */
3364 token
->type
= t
->type
;
3365 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3366 Jim_IncrRefCount(token
->objPtr
);
3373 /* This method takes the string representation of an object
3374 * as a Tcl script, and generates the pre-parsed internal representation
3376 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
)
3379 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
3380 struct JimParserCtx parser
;
3381 struct ScriptObj
*script
;
3382 ParseTokenList tokenlist
;
3385 /* Try to get information about filename / line number */
3386 if (objPtr
->typePtr
== &sourceObjType
) {
3387 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
3390 /* Initially parse the script into tokens (in tokenlist) */
3391 ScriptTokenListInit(&tokenlist
);
3393 JimParserInit(&parser
, scriptText
, scriptTextLen
, line
);
3394 while (!parser
.eof
) {
3395 JimParseScript(&parser
);
3396 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
3399 if (result
&& parser
.missing
!= ' ') {
3400 ScriptTokenListFree(&tokenlist
);
3401 result
->missing
= parser
.missing
;
3402 result
->line
= parser
.missingline
;
3406 /* Add a final EOF token */
3407 ScriptAddToken(&tokenlist
, scriptText
+ scriptTextLen
, 0, JIM_TT_EOF
, 0);
3409 /* Create the "real" script tokens from the initial token list */
3410 script
= Jim_Alloc(sizeof(*script
));
3411 memset(script
, 0, sizeof(*script
));
3413 script
->line
= line
;
3414 if (objPtr
->typePtr
== &sourceObjType
) {
3415 script
->fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
3418 script
->fileNameObj
= interp
->emptyObj
;
3420 Jim_IncrRefCount(script
->fileNameObj
);
3422 ScriptObjAddTokens(interp
, script
, &tokenlist
);
3424 /* No longer need the token list */
3425 ScriptTokenListFree(&tokenlist
);
3427 /* Free the old internal rep and set the new one. */
3428 Jim_FreeIntRep(interp
, objPtr
);
3429 Jim_SetIntRepPtr(objPtr
, script
);
3430 objPtr
->typePtr
= &scriptObjType
;
3435 ScriptObj
*Jim_GetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3437 struct ScriptObj
*script
= Jim_GetIntRepPtr(objPtr
);
3439 if (objPtr
->typePtr
!= &scriptObjType
|| script
->substFlags
) {
3440 SetScriptFromAny(interp
, objPtr
, NULL
);
3442 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
3445 /* -----------------------------------------------------------------------------
3447 * ---------------------------------------------------------------------------*/
3448 static void JimIncrCmdRefCount(Jim_Cmd
*cmdPtr
)
3453 static void JimDecrCmdRefCount(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
)
3455 if (--cmdPtr
->inUse
== 0) {
3456 if (cmdPtr
->isproc
) {
3457 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.argListObjPtr
);
3458 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.bodyObjPtr
);
3459 if (cmdPtr
->u
.proc
.staticVars
) {
3460 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3461 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3463 if (cmdPtr
->u
.proc
.prevCmd
) {
3464 /* Delete any pushed command too */
3465 JimDecrCmdRefCount(interp
, cmdPtr
->u
.proc
.prevCmd
);
3470 if (cmdPtr
->u
.native
.delProc
) {
3471 cmdPtr
->u
.native
.delProc(interp
, cmdPtr
->u
.native
.privData
);
3478 /* Commands HashTable Type.
3480 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3481 static void JimCommandsHT_ValDestructor(void *interp
, void *val
)
3483 JimDecrCmdRefCount(interp
, val
);
3486 static const Jim_HashTableType JimCommandsHashTableType
= {
3487 JimStringCopyHTHashFunction
, /* hash function */
3488 JimStringCopyHTKeyDup
, /* key dup */
3490 JimStringCopyHTKeyCompare
, /* key compare */
3491 JimStringCopyHTKeyDestructor
, /* key destructor */
3492 JimCommandsHT_ValDestructor
/* val destructor */
3495 /* ------------------------- Commands related functions --------------------- */
3497 int Jim_CreateCommand(Jim_Interp
*interp
, const char *cmdName
,
3498 Jim_CmdProc cmdProc
, void *privData
, Jim_DelCmdProc delProc
)
3502 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) != JIM_ERR
) {
3503 /* Command existed so incr proc epoch */
3504 Jim_InterpIncrProcEpoch(interp
);
3507 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3509 /* Store the new details for this proc */
3510 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3512 cmdPtr
->u
.native
.delProc
= delProc
;
3513 cmdPtr
->u
.native
.cmdProc
= cmdProc
;
3514 cmdPtr
->u
.native
.privData
= privData
;
3516 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3518 /* There is no need to increment the 'proc epoch' because
3519 * creation of a new procedure can never affect existing
3520 * cached commands. We don't do negative caching. */
3524 static int JimCreateProcedure(Jim_Interp
*interp
, Jim_Obj
*cmdName
,
3525 Jim_Obj
*argListObjPtr
, Jim_Obj
*staticsListObjPtr
, Jim_Obj
*bodyObjPtr
)
3532 if (JimValidName(interp
, "procedure", cmdName
) != JIM_OK
) {
3536 argListLen
= Jim_ListLength(interp
, argListObjPtr
);
3538 /* Allocate space for both the command pointer and the arg list */
3539 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
) + sizeof(struct Jim_ProcArg
) * argListLen
);
3540 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3543 cmdPtr
->u
.proc
.argListObjPtr
= argListObjPtr
;
3544 cmdPtr
->u
.proc
.argListLen
= argListLen
;
3545 cmdPtr
->u
.proc
.bodyObjPtr
= bodyObjPtr
;
3546 cmdPtr
->u
.proc
.argsPos
= -1;
3547 cmdPtr
->u
.proc
.arglist
= (struct Jim_ProcArg
*)(cmdPtr
+ 1);
3548 Jim_IncrRefCount(argListObjPtr
);
3549 Jim_IncrRefCount(bodyObjPtr
);
3551 /* Create the statics hash table. */
3552 if (staticsListObjPtr
) {
3555 len
= Jim_ListLength(interp
, staticsListObjPtr
);
3557 cmdPtr
->u
.proc
.staticVars
= Jim_Alloc(sizeof(Jim_HashTable
));
3558 Jim_InitHashTable(cmdPtr
->u
.proc
.staticVars
, &JimVariablesHashTableType
, interp
);
3559 for (i
= 0; i
< len
; i
++) {
3560 Jim_Obj
*objPtr
= 0, *initObjPtr
= 0, *nameObjPtr
= 0;
3564 Jim_ListIndex(interp
, staticsListObjPtr
, i
, &objPtr
, JIM_NONE
);
3565 /* Check if it's composed of two elements. */
3566 subLen
= Jim_ListLength(interp
, objPtr
);
3567 if (subLen
== 1 || subLen
== 2) {
3568 /* Try to get the variable value from the current
3570 Jim_ListIndex(interp
, objPtr
, 0, &nameObjPtr
, JIM_NONE
);
3572 initObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, JIM_NONE
);
3573 if (initObjPtr
== NULL
) {
3574 Jim_SetResultFormatted(interp
,
3575 "variable for initialization of static \"%#s\" not found in the local context",
3581 Jim_ListIndex(interp
, objPtr
, 1, &initObjPtr
, JIM_NONE
);
3583 if (JimValidName(interp
, "static variable", nameObjPtr
) != JIM_OK
) {
3587 varPtr
= Jim_Alloc(sizeof(*varPtr
));
3588 varPtr
->objPtr
= initObjPtr
;
3589 Jim_IncrRefCount(initObjPtr
);
3590 varPtr
->linkFramePtr
= NULL
;
3591 if (Jim_AddHashEntry(cmdPtr
->u
.proc
.staticVars
,
3592 Jim_String(nameObjPtr
), varPtr
) != JIM_OK
) {
3593 Jim_SetResultFormatted(interp
,
3594 "static variable name \"%#s\" duplicated in statics list", nameObjPtr
);
3595 Jim_DecrRefCount(interp
, initObjPtr
);
3601 Jim_SetResultFormatted(interp
, "too many fields in static specifier \"%#s\"",
3609 /* Parse the args out into arglist, validating as we go */
3610 /* Examine the argument list for default parameters and 'args' */
3611 for (i
= 0; i
< argListLen
; i
++) {
3613 Jim_Obj
*nameObjPtr
;
3614 Jim_Obj
*defaultObjPtr
;
3618 /* Examine a parameter */
3619 Jim_ListIndex(interp
, argListObjPtr
, i
, &argPtr
, JIM_NONE
);
3620 len
= Jim_ListLength(interp
, argPtr
);
3622 Jim_SetResultString(interp
, "procedure has argument with no name", -1);
3626 Jim_SetResultString(interp
, "procedure has argument with too many fields", -1);
3631 /* Optional parameter */
3632 Jim_ListIndex(interp
, argPtr
, 0, &nameObjPtr
, JIM_NONE
);
3633 Jim_ListIndex(interp
, argPtr
, 1, &defaultObjPtr
, JIM_NONE
);
3636 /* Required parameter */
3637 nameObjPtr
= argPtr
;
3638 defaultObjPtr
= NULL
;
3642 if (Jim_CompareStringImmediate(interp
, nameObjPtr
, "args")) {
3643 if (cmdPtr
->u
.proc
.argsPos
>= 0) {
3644 Jim_SetResultString(interp
, "procedure has 'args' specified more than once", -1);
3647 cmdPtr
->u
.proc
.argsPos
= i
;
3651 cmdPtr
->u
.proc
.optArity
+= n
;
3654 cmdPtr
->u
.proc
.reqArity
+= n
;
3658 cmdPtr
->u
.proc
.arglist
[i
].nameObjPtr
= nameObjPtr
;
3659 cmdPtr
->u
.proc
.arglist
[i
].defaultObjPtr
= defaultObjPtr
;
3662 /* Add the new command */
3664 /* It may already exist, so we try to delete the old one.
3665 * Note that reference count means that it won't be deleted yet if
3666 * it exists in the call stack.
3668 * BUT, if 'local' is in force, instead of deleting the existing
3669 * proc, we stash a reference to the old proc here.
3671 he
= Jim_FindHashEntry(&interp
->commands
, Jim_String(cmdName
));
3673 /* There was an old procedure with the same name, this requires
3674 * a 'proc epoch' update. */
3676 /* If a procedure with the same name didn't existed there is no need
3677 * to increment the 'proc epoch' because creation of a new procedure
3678 * can never affect existing cached commands. We don't do
3679 * negative caching. */
3680 Jim_InterpIncrProcEpoch(interp
);
3683 if (he
&& interp
->local
) {
3684 /* Just push this proc over the top of the previous one */
3685 cmdPtr
->u
.proc
.prevCmd
= he
->u
.val
;
3690 /* Replace the existing proc */
3691 Jim_DeleteHashEntry(&interp
->commands
, Jim_String(cmdName
));
3694 Jim_AddHashEntry(&interp
->commands
, Jim_String(cmdName
), cmdPtr
);
3697 /* Unlike Tcl, set the name of the proc as the result */
3698 Jim_SetResult(interp
, cmdName
);
3702 if (cmdPtr
->u
.proc
.staticVars
) {
3703 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3705 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3706 Jim_DecrRefCount(interp
, argListObjPtr
);
3707 Jim_DecrRefCount(interp
, bodyObjPtr
);
3712 int Jim_DeleteCommand(Jim_Interp
*interp
, const char *cmdName
)
3714 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) == JIM_ERR
)
3716 Jim_InterpIncrProcEpoch(interp
);
3720 int Jim_RenameCommand(Jim_Interp
*interp
, const char *oldName
, const char *newName
)
3724 /* Does it exist? */
3725 he
= Jim_FindHashEntry(&interp
->commands
, oldName
);
3727 Jim_SetResultFormatted(interp
, "can't %s \"%s\": command doesn't exist",
3728 newName
[0] ? "rename" : "delete", oldName
);
3732 if (newName
[0] == '\0') /* Delete! */
3733 return Jim_DeleteCommand(interp
, oldName
);
3736 if (Jim_FindHashEntry(&interp
->commands
, newName
)) {
3737 Jim_SetResultFormatted(interp
, "can't rename to \"%s\": command already exists", newName
);
3741 /* Add the new name first */
3742 JimIncrCmdRefCount(he
->u
.val
);
3743 Jim_AddHashEntry(&interp
->commands
, newName
, he
->u
.val
);
3745 /* Now remove the old name */
3746 Jim_DeleteHashEntry(&interp
->commands
, oldName
);
3748 /* Increment the epoch */
3749 Jim_InterpIncrProcEpoch(interp
);
3753 /* -----------------------------------------------------------------------------
3755 * ---------------------------------------------------------------------------*/
3757 static int SetCommandFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3759 static const Jim_ObjType commandObjType
= {
3764 JIM_TYPE_REFERENCES
,
3767 int SetCommandFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3770 const char *cmdName
;
3772 /* Get the string representation */
3773 cmdName
= Jim_String(objPtr
);
3774 /* Lookup this name into the commands hash table */
3775 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3779 /* Free the old internal repr and set the new one. */
3780 Jim_FreeIntRep(interp
, objPtr
);
3781 objPtr
->typePtr
= &commandObjType
;
3782 objPtr
->internalRep
.cmdValue
.procEpoch
= interp
->procEpoch
;
3783 objPtr
->internalRep
.cmdValue
.cmdPtr
= (void *)he
->u
.val
;
3787 /* This function returns the command structure for the command name
3788 * stored in objPtr. It tries to specialize the objPtr to contain
3789 * a cached info instead to perform the lookup into the hash table
3790 * every time. The information cached may not be uptodate, in such
3791 * a case the lookup is performed and the cache updated.
3793 * Respects the 'upcall' setting
3795 Jim_Cmd
*Jim_GetCommand(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
3799 if ((objPtr
->typePtr
!= &commandObjType
||
3800 objPtr
->internalRep
.cmdValue
.procEpoch
!= interp
->procEpoch
) &&
3801 SetCommandFromAny(interp
, objPtr
) == JIM_ERR
) {
3802 if (flags
& JIM_ERRMSG
) {
3803 Jim_SetResultFormatted(interp
, "invalid command name \"%#s\"", objPtr
);
3807 cmd
= objPtr
->internalRep
.cmdValue
.cmdPtr
;
3808 while (cmd
->isproc
&& cmd
->u
.proc
.upcall
) {
3809 cmd
= cmd
->u
.proc
.prevCmd
;
3814 /* -----------------------------------------------------------------------------
3816 * ---------------------------------------------------------------------------*/
3818 /* Variables HashTable Type.
3820 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3821 static void JimVariablesHTValDestructor(void *interp
, void *val
)
3823 Jim_Var
*varPtr
= (void *)val
;
3825 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
3829 static const Jim_HashTableType JimVariablesHashTableType
= {
3830 JimStringCopyHTHashFunction
, /* hash function */
3831 JimStringCopyHTKeyDup
, /* key dup */
3833 JimStringCopyHTKeyCompare
, /* key compare */
3834 JimStringCopyHTKeyDestructor
, /* key destructor */
3835 JimVariablesHTValDestructor
/* val destructor */
3838 /* -----------------------------------------------------------------------------
3840 * ---------------------------------------------------------------------------*/
3842 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3844 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3846 static const Jim_ObjType variableObjType
= {
3851 JIM_TYPE_REFERENCES
,
3854 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3855 * is in the form "varname(key)". */
3856 static int JimNameIsDictSugar(const char *str
, int len
)
3858 if (len
&& str
[len
- 1] == ')' && strchr(str
, '(') != NULL
)
3864 * Check that the name does not contain embedded nulls.
3866 * Variable and procedure names are maniplated as null terminated strings, so
3867 * don't allow names with embedded nulls.
3869 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
)
3871 /* Variable names and proc names can't contain embedded nulls */
3872 if (nameObjPtr
->typePtr
!= &variableObjType
) {
3874 const char *str
= Jim_GetString(nameObjPtr
, &len
);
3875 if (memchr(str
, '\0', len
)) {
3876 Jim_SetResultFormatted(interp
, "%s name contains embedded null", type
);
3883 /* This method should be called only by the variable API.
3884 * It returns JIM_OK on success (variable already exists),
3885 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3886 * a variable name, but syntax glue for [dict] i.e. the last
3887 * character is ')' */
3888 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3891 const char *varName
;
3893 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3895 /* Check if the object is already an uptodate variable */
3896 if (objPtr
->typePtr
== &variableObjType
&&
3897 objPtr
->internalRep
.varValue
.callFrameId
== framePtr
->id
) {
3898 return JIM_OK
; /* nothing to do */
3901 if (objPtr
->typePtr
== &dictSubstObjType
) {
3902 return JIM_DICT_SUGAR
;
3905 if (JimValidName(interp
, "variable", objPtr
) != JIM_OK
) {
3909 /* Get the string representation */
3910 varName
= Jim_GetString(objPtr
, &len
);
3912 /* Make sure it's not syntax glue to get/set dict. */
3913 if (JimNameIsDictSugar(varName
, len
)) {
3914 return JIM_DICT_SUGAR
;
3917 if (varName
[0] == ':' && varName
[1] == ':') {
3918 framePtr
= interp
->topFramePtr
;
3919 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
+ 2);
3925 /* Lookup this name into the variables hash table */
3926 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
);
3928 /* Try with static vars. */
3929 if (framePtr
->staticVars
== NULL
)
3931 if (!(he
= Jim_FindHashEntry(framePtr
->staticVars
, varName
)))
3935 /* Free the old internal repr and set the new one. */
3936 Jim_FreeIntRep(interp
, objPtr
);
3937 objPtr
->typePtr
= &variableObjType
;
3938 objPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3939 objPtr
->internalRep
.varValue
.varPtr
= (void *)he
->u
.val
;
3943 /* -------------------- Variables related functions ------------------------- */
3944 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, Jim_Obj
*valObjPtr
);
3945 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, int flags
);
3947 /* For now that's dummy. Variables lookup should be optimized
3948 * in many ways, with caching of lookups, and possibly with
3949 * a table of pre-allocated vars in every CallFrame for local vars.
3950 * All the caching should also have an 'epoch' mechanism similar
3951 * to the one used by Tcl for procedures lookup caching. */
3953 int Jim_SetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
3959 if ((err
= SetVariableFromAny(interp
, nameObjPtr
)) != JIM_OK
) {
3960 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3962 /* Check for [dict] syntax sugar. */
3963 if (err
== JIM_DICT_SUGAR
)
3964 return JimDictSugarSet(interp
, nameObjPtr
, valObjPtr
);
3966 if (JimValidName(interp
, "variable", nameObjPtr
) != JIM_OK
) {
3970 /* New variable to create */
3971 name
= Jim_String(nameObjPtr
);
3973 var
= Jim_Alloc(sizeof(*var
));
3974 var
->objPtr
= valObjPtr
;
3975 Jim_IncrRefCount(valObjPtr
);
3976 var
->linkFramePtr
= NULL
;
3977 /* Insert the new variable */
3978 if (name
[0] == ':' && name
[1] == ':') {
3979 /* Into the top level frame */
3980 framePtr
= interp
->topFramePtr
;
3981 Jim_AddHashEntry(&framePtr
->vars
, name
+ 2, var
);
3984 Jim_AddHashEntry(&framePtr
->vars
, name
, var
);
3986 /* Make the object int rep a variable */
3987 Jim_FreeIntRep(interp
, nameObjPtr
);
3988 nameObjPtr
->typePtr
= &variableObjType
;
3989 nameObjPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3990 nameObjPtr
->internalRep
.varValue
.varPtr
= var
;
3993 var
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3994 if (var
->linkFramePtr
== NULL
) {
3995 Jim_IncrRefCount(valObjPtr
);
3996 Jim_DecrRefCount(interp
, var
->objPtr
);
3997 var
->objPtr
= valObjPtr
;
3999 else { /* Else handle the link */
4000 Jim_CallFrame
*savedCallFrame
;
4002 savedCallFrame
= interp
->framePtr
;
4003 interp
->framePtr
= var
->linkFramePtr
;
4004 err
= Jim_SetVariable(interp
, var
->objPtr
, valObjPtr
);
4005 interp
->framePtr
= savedCallFrame
;
4013 int Jim_SetVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4015 Jim_Obj
*nameObjPtr
;
4018 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4019 Jim_IncrRefCount(nameObjPtr
);
4020 result
= Jim_SetVariable(interp
, nameObjPtr
, objPtr
);
4021 Jim_DecrRefCount(interp
, nameObjPtr
);
4025 int Jim_SetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4027 Jim_CallFrame
*savedFramePtr
;
4030 savedFramePtr
= interp
->framePtr
;
4031 interp
->framePtr
= interp
->topFramePtr
;
4032 result
= Jim_SetVariableStr(interp
, name
, objPtr
);
4033 interp
->framePtr
= savedFramePtr
;
4037 int Jim_SetVariableStrWithStr(Jim_Interp
*interp
, const char *name
, const char *val
)
4039 Jim_Obj
*nameObjPtr
, *valObjPtr
;
4042 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4043 valObjPtr
= Jim_NewStringObj(interp
, val
, -1);
4044 Jim_IncrRefCount(nameObjPtr
);
4045 Jim_IncrRefCount(valObjPtr
);
4046 result
= Jim_SetVariable(interp
, nameObjPtr
, valObjPtr
);
4047 Jim_DecrRefCount(interp
, nameObjPtr
);
4048 Jim_DecrRefCount(interp
, valObjPtr
);
4052 int Jim_SetVariableLink(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
4053 Jim_Obj
*targetNameObjPtr
, Jim_CallFrame
*targetCallFrame
)
4055 const char *varName
;
4058 varName
= Jim_GetString(nameObjPtr
, &len
);
4060 if (varName
[0] == ':' && varName
[1] == ':') {
4061 /* Linking a global var does nothing */
4065 if (JimNameIsDictSugar(varName
, len
)) {
4066 Jim_SetResultString(interp
, "Dict key syntax invalid as link source", -1);
4070 /* Check for an existing variable or link */
4071 if (SetVariableFromAny(interp
, nameObjPtr
) == JIM_OK
) {
4072 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4074 if (varPtr
->linkFramePtr
== NULL
) {
4075 Jim_SetResultFormatted(interp
, "variable \"%#s\" already exists", nameObjPtr
);
4079 /* It exists, but is a link, so delete the link */
4080 varPtr
->linkFramePtr
= NULL
;
4083 /* Check for cycles. */
4084 if (interp
->framePtr
== targetCallFrame
) {
4085 Jim_Obj
*objPtr
= targetNameObjPtr
;
4088 /* Cycles are only possible with 'uplevel 0' */
4090 if (Jim_StringEqObj(objPtr
, nameObjPtr
)) {
4091 Jim_SetResultString(interp
, "can't upvar from variable to itself", -1);
4094 if (SetVariableFromAny(interp
, objPtr
) != JIM_OK
)
4096 varPtr
= objPtr
->internalRep
.varValue
.varPtr
;
4097 if (varPtr
->linkFramePtr
!= targetCallFrame
)
4099 objPtr
= varPtr
->objPtr
;
4103 /* Perform the binding */
4104 Jim_SetVariable(interp
, nameObjPtr
, targetNameObjPtr
);
4105 /* We are now sure 'nameObjPtr' type is variableObjType */
4106 nameObjPtr
->internalRep
.varValue
.varPtr
->linkFramePtr
= targetCallFrame
;
4110 /* Return the Jim_Obj pointer associated with a variable name,
4111 * or NULL if the variable was not found in the current context.
4112 * The same optimization discussed in the comment to the
4113 * 'SetVariable' function should apply here.
4115 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4116 * in a dictionary which is shared, the array variable value is duplicated first.
4117 * This allows the array element to be updated (e.g. append, lappend) without
4118 * affecting other references to the dictionary.
4120 Jim_Obj
*Jim_GetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4122 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4124 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4126 if (varPtr
->linkFramePtr
== NULL
) {
4127 return varPtr
->objPtr
;
4132 /* The variable is a link? Resolve it. */
4133 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
4135 interp
->framePtr
= varPtr
->linkFramePtr
;
4136 objPtr
= Jim_GetVariable(interp
, varPtr
->objPtr
, flags
);
4137 interp
->framePtr
= savedCallFrame
;
4141 /* Error, so fall through to the error message */
4146 case JIM_DICT_SUGAR
:
4147 /* [dict] syntax sugar. */
4148 return JimDictSugarGet(interp
, nameObjPtr
, flags
);
4150 if (flags
& JIM_ERRMSG
) {
4151 Jim_SetResultFormatted(interp
, "can't read \"%#s\": no such variable", nameObjPtr
);
4156 Jim_Obj
*Jim_GetGlobalVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4158 Jim_CallFrame
*savedFramePtr
;
4161 savedFramePtr
= interp
->framePtr
;
4162 interp
->framePtr
= interp
->topFramePtr
;
4163 objPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4164 interp
->framePtr
= savedFramePtr
;
4169 Jim_Obj
*Jim_GetVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4171 Jim_Obj
*nameObjPtr
, *varObjPtr
;
4173 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4174 Jim_IncrRefCount(nameObjPtr
);
4175 varObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4176 Jim_DecrRefCount(interp
, nameObjPtr
);
4180 Jim_Obj
*Jim_GetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4182 Jim_CallFrame
*savedFramePtr
;
4185 savedFramePtr
= interp
->framePtr
;
4186 interp
->framePtr
= interp
->topFramePtr
;
4187 objPtr
= Jim_GetVariableStr(interp
, name
, flags
);
4188 interp
->framePtr
= savedFramePtr
;
4193 /* Unset a variable.
4194 * Note: On success unset invalidates all the variable objects created
4195 * in the current call frame incrementing. */
4196 int Jim_UnsetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4202 retval
= SetVariableFromAny(interp
, nameObjPtr
);
4203 if (retval
== JIM_DICT_SUGAR
) {
4204 /* [dict] syntax sugar. */
4205 return JimDictSugarSet(interp
, nameObjPtr
, NULL
);
4207 else if (retval
== JIM_OK
) {
4208 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4210 /* If it's a link call UnsetVariable recursively */
4211 if (varPtr
->linkFramePtr
) {
4212 Jim_CallFrame
*savedCallFrame
;
4214 savedCallFrame
= interp
->framePtr
;
4215 interp
->framePtr
= varPtr
->linkFramePtr
;
4216 retval
= Jim_UnsetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
4217 interp
->framePtr
= savedCallFrame
;
4220 Jim_CallFrame
*framePtr
= interp
->framePtr
;
4222 name
= Jim_String(nameObjPtr
);
4223 if (name
[0] == ':' && name
[1] == ':') {
4224 framePtr
= interp
->topFramePtr
;
4227 retval
= Jim_DeleteHashEntry(&framePtr
->vars
, name
);
4228 if (retval
== JIM_OK
) {
4229 /* Change the callframe id, invalidating var lookup caching */
4230 JimChangeCallFrameId(interp
, framePtr
);
4234 if (retval
!= JIM_OK
&& (flags
& JIM_ERRMSG
)) {
4235 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such variable", nameObjPtr
);
4240 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4242 /* Given a variable name for [dict] operation syntax sugar,
4243 * this function returns two objects, the first with the name
4244 * of the variable to set, and the second with the rispective key.
4245 * For example "foo(bar)" will return objects with string repr. of
4248 * The returned objects have refcount = 1. The function can't fail. */
4249 static void JimDictSugarParseVarKey(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
4250 Jim_Obj
**varPtrPtr
, Jim_Obj
**keyPtrPtr
)
4252 const char *str
, *p
;
4254 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4256 str
= Jim_GetString(objPtr
, &len
);
4258 p
= strchr(str
, '(');
4259 JimPanic((p
== NULL
, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str
));
4261 varObjPtr
= Jim_NewStringObj(interp
, str
, p
- str
);
4264 keyLen
= (str
+ len
) - p
;
4265 if (str
[len
- 1] == ')') {
4269 /* Create the objects with the variable name and key. */
4270 keyObjPtr
= Jim_NewStringObj(interp
, p
, keyLen
);
4272 Jim_IncrRefCount(varObjPtr
);
4273 Jim_IncrRefCount(keyObjPtr
);
4274 *varPtrPtr
= varObjPtr
;
4275 *keyPtrPtr
= keyObjPtr
;
4278 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4279 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4280 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*valObjPtr
)
4284 SetDictSubstFromAny(interp
, objPtr
);
4286 err
= Jim_SetDictKeysVector(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4287 &objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, 1, valObjPtr
, JIM_ERRMSG
);
4289 if (err
== JIM_OK
) {
4290 /* Don't keep an extra ref to the result */
4291 Jim_SetEmptyResult(interp
);
4295 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4296 if (Jim_GetVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
, JIM_NONE
)) {
4297 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such element in array",
4302 /* Make the error more informative and Tcl-compatible */
4303 Jim_SetResultFormatted(interp
, "can't %s \"%#s\": variable isn't array",
4304 (valObjPtr
? "set" : "unset"), objPtr
);
4310 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4312 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4313 * and stored back to the variable before expansion.
4315 static Jim_Obj
*JimDictExpandArrayVariable(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
,
4316 Jim_Obj
*keyObjPtr
, int flags
)
4318 Jim_Obj
*dictObjPtr
;
4319 Jim_Obj
*resObjPtr
= NULL
;
4322 dictObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
4327 ret
= Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4328 if (ret
!= JIM_OK
) {
4331 Jim_SetResultFormatted(interp
,
4332 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr
, keyObjPtr
);
4335 Jim_SetResultFormatted(interp
,
4336 "can't read \"%#s(%#s)\": no such element in array", varObjPtr
, keyObjPtr
);
4339 else if ((flags
& JIM_UNSHARED
) && Jim_IsShared(dictObjPtr
)) {
4340 dictObjPtr
= Jim_DuplicateObj(interp
, dictObjPtr
);
4341 if (Jim_SetVariable(interp
, varObjPtr
, dictObjPtr
) != JIM_OK
) {
4342 /* This can probably never happen */
4343 JimPanic((1, "SetVariable failed for JIM_UNSHARED"));
4345 /* We know that the key exists. Get the result in the now-unshared dictionary */
4346 Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4352 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4353 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4355 SetDictSubstFromAny(interp
, objPtr
);
4357 return JimDictExpandArrayVariable(interp
,
4358 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4359 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, flags
);
4362 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4364 void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4366 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
4367 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
4370 void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4372 JIM_NOTUSED(interp
);
4374 dupPtr
->internalRep
.dictSubstValue
.varNameObjPtr
=
4375 srcPtr
->internalRep
.dictSubstValue
.varNameObjPtr
;
4376 dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
= srcPtr
->internalRep
.dictSubstValue
.indexObjPtr
;
4377 dupPtr
->typePtr
= &dictSubstObjType
;
4380 /* Note: The object *must* be in dict-sugar format */
4381 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4383 if (objPtr
->typePtr
!= &dictSubstObjType
) {
4384 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4386 if (objPtr
->typePtr
== &interpolatedObjType
) {
4387 /* An interpolated object in dict-sugar form */
4389 const ScriptToken
*token
= objPtr
->internalRep
.twoPtrValue
.ptr1
;
4391 varObjPtr
= token
[0].objPtr
;
4392 keyObjPtr
= objPtr
->internalRep
.twoPtrValue
.ptr2
;
4394 Jim_IncrRefCount(varObjPtr
);
4395 Jim_IncrRefCount(keyObjPtr
);
4398 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
4401 Jim_FreeIntRep(interp
, objPtr
);
4402 objPtr
->typePtr
= &dictSubstObjType
;
4403 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= varObjPtr
;
4404 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= keyObjPtr
;
4408 /* This function is used to expand [dict get] sugar in the form
4409 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4410 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4411 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4412 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4413 * the [dict]ionary contained in variable VARNAME. */
4414 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4416 Jim_Obj
*resObjPtr
= NULL
;
4417 Jim_Obj
*substKeyObjPtr
= NULL
;
4419 SetDictSubstFromAny(interp
, objPtr
);
4421 if (Jim_SubstObj(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
,
4422 &substKeyObjPtr
, JIM_NONE
)
4426 Jim_IncrRefCount(substKeyObjPtr
);
4428 JimDictExpandArrayVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4430 Jim_DecrRefCount(interp
, substKeyObjPtr
);
4435 static Jim_Obj
*JimExpandExprSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4437 Jim_Obj
*resultObjPtr
;
4439 if (Jim_EvalExpression(interp
, objPtr
, &resultObjPtr
) == JIM_OK
) {
4440 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4441 resultObjPtr
->refCount
--;
4442 return resultObjPtr
;
4447 /* -----------------------------------------------------------------------------
4449 * ---------------------------------------------------------------------------*/
4451 static Jim_CallFrame
*JimCreateCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*parent
)
4455 if (interp
->freeFramesList
) {
4456 cf
= interp
->freeFramesList
;
4457 interp
->freeFramesList
= cf
->nextFramePtr
;
4460 cf
= Jim_Alloc(sizeof(*cf
));
4461 cf
->vars
.table
= NULL
;
4464 cf
->id
= interp
->callFrameEpoch
++;
4465 cf
->parentCallFrame
= parent
;
4466 cf
->level
= parent
? parent
->level
+ 1 : 0;
4469 cf
->procArgsObjPtr
= NULL
;
4470 cf
->procBodyObjPtr
= NULL
;
4471 cf
->nextFramePtr
= NULL
;
4472 cf
->staticVars
= NULL
;
4473 if (cf
->vars
.table
== NULL
)
4474 Jim_InitHashTable(&cf
->vars
, &JimVariablesHashTableType
, interp
);
4478 /* Used to invalidate every caching related to callframe stability. */
4479 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
)
4481 cf
->id
= interp
->callFrameEpoch
++;
4484 #define JIM_FCF_NONE 0 /* no flags */
4485 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4486 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
)
4488 if (cf
->procArgsObjPtr
)
4489 Jim_DecrRefCount(interp
, cf
->procArgsObjPtr
);
4490 if (cf
->procBodyObjPtr
)
4491 Jim_DecrRefCount(interp
, cf
->procBodyObjPtr
);
4492 if (!(flags
& JIM_FCF_NOHT
))
4493 Jim_FreeHashTable(&cf
->vars
);
4496 Jim_HashEntry
**table
= cf
->vars
.table
, *he
;
4498 for (i
= 0; i
< JIM_HT_INITIAL_SIZE
; i
++) {
4500 while (he
!= NULL
) {
4501 Jim_HashEntry
*nextEntry
= he
->next
;
4502 Jim_Var
*varPtr
= (void *)he
->u
.val
;
4504 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
4505 Jim_Free(he
->u
.val
);
4506 Jim_Free((void *)he
->key
); /* ATTENTION: const cast */
4514 cf
->nextFramePtr
= interp
->freeFramesList
;
4515 interp
->freeFramesList
= cf
;
4518 /* -----------------------------------------------------------------------------
4520 * ---------------------------------------------------------------------------*/
4521 #ifdef JIM_REFERENCES
4523 /* References HashTable Type.
4525 * Keys are jim_wide integers, dynamically allocated for now but in the
4526 * future it's worth to cache this 8 bytes objects. Values are poitners
4527 * to Jim_References. */
4528 static void JimReferencesHTValDestructor(void *interp
, void *val
)
4530 Jim_Reference
*refPtr
= (void *)val
;
4532 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
4533 if (refPtr
->finalizerCmdNamePtr
!= NULL
) {
4534 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4539 static unsigned int JimReferencesHTHashFunction(const void *key
)
4541 /* Only the least significant bits are used. */
4542 const jim_wide
*widePtr
= key
;
4543 unsigned int intValue
= (unsigned int)*widePtr
;
4545 return Jim_IntHashFunction(intValue
);
4548 static const void *JimReferencesHTKeyDup(void *privdata
, const void *key
)
4550 void *copy
= Jim_Alloc(sizeof(jim_wide
));
4552 JIM_NOTUSED(privdata
);
4554 memcpy(copy
, key
, sizeof(jim_wide
));
4558 static int JimReferencesHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
4560 JIM_NOTUSED(privdata
);
4562 return memcmp(key1
, key2
, sizeof(jim_wide
)) == 0;
4565 static void JimReferencesHTKeyDestructor(void *privdata
, const void *key
)
4567 JIM_NOTUSED(privdata
);
4569 Jim_Free((void *)key
);
4572 static const Jim_HashTableType JimReferencesHashTableType
= {
4573 JimReferencesHTHashFunction
, /* hash function */
4574 JimReferencesHTKeyDup
, /* key dup */
4576 JimReferencesHTKeyCompare
, /* key compare */
4577 JimReferencesHTKeyDestructor
, /* key destructor */
4578 JimReferencesHTValDestructor
/* val destructor */
4581 /* -----------------------------------------------------------------------------
4582 * Reference object type and References API
4583 * ---------------------------------------------------------------------------*/
4585 /* The string representation of references has two features in order
4586 * to make the GC faster. The first is that every reference starts
4587 * with a non common character '<', in order to make the string matching
4588 * faster. The second is that the reference string rep is 42 characters
4589 * in length, this allows to avoid to check every object with a string
4590 * repr < 42, and usually there aren't many of these objects. */
4592 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4594 static int JimFormatReference(char *buf
, Jim_Reference
*refPtr
, jim_wide id
)
4596 const char *fmt
= "<reference.<%s>.%020" JIM_WIDE_MODIFIER
">";
4598 sprintf(buf
, fmt
, refPtr
->tag
, id
);
4599 return JIM_REFERENCE_SPACE
;
4602 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
);
4604 static const Jim_ObjType referenceObjType
= {
4608 UpdateStringOfReference
,
4609 JIM_TYPE_REFERENCES
,
4612 void UpdateStringOfReference(struct Jim_Obj
*objPtr
)
4615 char buf
[JIM_REFERENCE_SPACE
+ 1];
4616 Jim_Reference
*refPtr
;
4618 refPtr
= objPtr
->internalRep
.refValue
.refPtr
;
4619 len
= JimFormatReference(buf
, refPtr
, objPtr
->internalRep
.refValue
.id
);
4620 objPtr
->bytes
= Jim_Alloc(len
+ 1);
4621 memcpy(objPtr
->bytes
, buf
, len
+ 1);
4622 objPtr
->length
= len
;
4625 /* returns true if 'c' is a valid reference tag character.
4626 * i.e. inside the range [_a-zA-Z0-9] */
4627 static int isrefchar(int c
)
4629 return (c
== '_' || isalnum(c
));
4632 static int SetReferenceFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4636 const char *str
, *start
, *end
;
4638 Jim_Reference
*refPtr
;
4641 /* Get the string representation */
4642 str
= Jim_GetString(objPtr
, &len
);
4643 /* Check if it looks like a reference */
4644 if (len
< JIM_REFERENCE_SPACE
)
4648 end
= str
+ len
- 1;
4649 while (*start
== ' ')
4651 while (*end
== ' ' && end
> start
)
4653 if (end
- start
+ 1 != JIM_REFERENCE_SPACE
)
4655 /* <reference.<1234567>.%020> */
4656 if (memcmp(start
, "<reference.<", 12) != 0)
4658 if (start
[12 + JIM_REFERENCE_TAGLEN
] != '>' || end
[0] != '>')
4660 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4661 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4662 if (!isrefchar(start
[12 + i
]))
4665 /* Extract info from the reference. */
4666 memcpy(refId
, start
+ 14 + JIM_REFERENCE_TAGLEN
, 20);
4668 /* Try to convert the ID into a jim_wide */
4669 if (Jim_StringToWide(refId
, &wideValue
, 10) != JIM_OK
)
4671 /* Check if the reference really exists! */
4672 he
= Jim_FindHashEntry(&interp
->references
, &wideValue
);
4674 Jim_SetResultFormatted(interp
, "invalid reference id \"%#s\"", objPtr
);
4678 /* Free the old internal repr and set the new one. */
4679 Jim_FreeIntRep(interp
, objPtr
);
4680 objPtr
->typePtr
= &referenceObjType
;
4681 objPtr
->internalRep
.refValue
.id
= wideValue
;
4682 objPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4686 Jim_SetResultFormatted(interp
, "expected reference but got \"%#s\"", objPtr
);
4690 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4691 * as finalizer command (or NULL if there is no finalizer).
4692 * The returned reference object has refcount = 0. */
4693 Jim_Obj
*Jim_NewReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*tagPtr
, Jim_Obj
*cmdNamePtr
)
4695 struct Jim_Reference
*refPtr
;
4696 jim_wide wideValue
= interp
->referenceNextId
;
4701 /* Perform the Garbage Collection if needed. */
4702 Jim_CollectIfNeeded(interp
);
4704 refPtr
= Jim_Alloc(sizeof(*refPtr
));
4705 refPtr
->objPtr
= objPtr
;
4706 Jim_IncrRefCount(objPtr
);
4707 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4709 Jim_IncrRefCount(cmdNamePtr
);
4710 Jim_AddHashEntry(&interp
->references
, &wideValue
, refPtr
);
4711 refObjPtr
= Jim_NewObj(interp
);
4712 refObjPtr
->typePtr
= &referenceObjType
;
4713 refObjPtr
->bytes
= NULL
;
4714 refObjPtr
->internalRep
.refValue
.id
= interp
->referenceNextId
;
4715 refObjPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4716 interp
->referenceNextId
++;
4717 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4718 * that does not pass the 'isrefchar' test is replaced with '_' */
4719 tag
= Jim_GetString(tagPtr
, &tagLen
);
4720 if (tagLen
> JIM_REFERENCE_TAGLEN
)
4721 tagLen
= JIM_REFERENCE_TAGLEN
;
4722 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4723 if (i
< tagLen
&& isrefchar(tag
[i
]))
4724 refPtr
->tag
[i
] = tag
[i
];
4726 refPtr
->tag
[i
] = '_';
4728 refPtr
->tag
[JIM_REFERENCE_TAGLEN
] = '\0';
4732 Jim_Reference
*Jim_GetReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4734 if (objPtr
->typePtr
!= &referenceObjType
&& SetReferenceFromAny(interp
, objPtr
) == JIM_ERR
)
4736 return objPtr
->internalRep
.refValue
.refPtr
;
4739 int Jim_SetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*cmdNamePtr
)
4741 Jim_Reference
*refPtr
;
4743 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4745 Jim_IncrRefCount(cmdNamePtr
);
4746 if (refPtr
->finalizerCmdNamePtr
)
4747 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4748 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4752 int Jim_GetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
**cmdNamePtrPtr
)
4754 Jim_Reference
*refPtr
;
4756 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4758 *cmdNamePtrPtr
= refPtr
->finalizerCmdNamePtr
;
4762 /* -----------------------------------------------------------------------------
4763 * References Garbage Collection
4764 * ---------------------------------------------------------------------------*/
4766 /* This the hash table type for the "MARK" phase of the GC */
4767 static const Jim_HashTableType JimRefMarkHashTableType
= {
4768 JimReferencesHTHashFunction
, /* hash function */
4769 JimReferencesHTKeyDup
, /* key dup */
4771 JimReferencesHTKeyCompare
, /* key compare */
4772 JimReferencesHTKeyDestructor
, /* key destructor */
4773 NULL
/* val destructor */
4776 /* Performs the garbage collection. */
4777 int Jim_Collect(Jim_Interp
*interp
)
4780 #ifndef JIM_BOOTSTRAP
4781 Jim_HashTable marks
;
4782 Jim_HashTableIterator
*htiter
;
4786 /* Avoid recursive calls */
4787 if (interp
->lastCollectId
== -1) {
4788 /* Jim_Collect() already running. Return just now. */
4791 interp
->lastCollectId
= -1;
4793 /* Mark all the references found into the 'mark' hash table.
4794 * The references are searched in every live object that
4795 * is of a type that can contain references. */
4796 Jim_InitHashTable(&marks
, &JimRefMarkHashTableType
, NULL
);
4797 objPtr
= interp
->liveList
;
4799 if (objPtr
->typePtr
== NULL
|| objPtr
->typePtr
->flags
& JIM_TYPE_REFERENCES
) {
4800 const char *str
, *p
;
4803 /* If the object is of type reference, to get the
4804 * Id is simple... */
4805 if (objPtr
->typePtr
== &referenceObjType
) {
4806 Jim_AddHashEntry(&marks
, &objPtr
->internalRep
.refValue
.id
, NULL
);
4808 printf("MARK (reference): %d refcount: %d" JIM_NL
,
4809 (int)objPtr
->internalRep
.refValue
.id
, objPtr
->refCount
);
4811 objPtr
= objPtr
->nextObjPtr
;
4814 /* Get the string repr of the object we want
4815 * to scan for references. */
4816 p
= str
= Jim_GetString(objPtr
, &len
);
4817 /* Skip objects too little to contain references. */
4818 if (len
< JIM_REFERENCE_SPACE
) {
4819 objPtr
= objPtr
->nextObjPtr
;
4822 /* Extract references from the object string repr. */
4828 if ((p
= strstr(p
, "<reference.<")) == NULL
)
4830 /* Check if it's a valid reference. */
4831 if (len
- (p
- str
) < JIM_REFERENCE_SPACE
)
4833 if (p
[41] != '>' || p
[19] != '>' || p
[20] != '.')
4835 for (i
= 21; i
<= 40; i
++)
4836 if (!isdigit(UCHAR(p
[i
])))
4839 memcpy(buf
, p
+ 21, 20);
4841 Jim_StringToWide(buf
, &id
, 10);
4843 /* Ok, a reference for the given ID
4844 * was found. Mark it. */
4845 Jim_AddHashEntry(&marks
, &id
, NULL
);
4847 printf("MARK: %d" JIM_NL
, (int)id
);
4849 p
+= JIM_REFERENCE_SPACE
;
4852 objPtr
= objPtr
->nextObjPtr
;
4855 /* Run the references hash table to destroy every reference that
4856 * is not referenced outside (not present in the mark HT). */
4857 htiter
= Jim_GetHashTableIterator(&interp
->references
);
4858 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
4859 const jim_wide
*refId
;
4860 Jim_Reference
*refPtr
;
4863 /* Check if in the mark phase we encountered
4864 * this reference. */
4865 if (Jim_FindHashEntry(&marks
, refId
) == NULL
) {
4867 printf("COLLECTING %d" JIM_NL
, (int)*refId
);
4870 /* Drop the reference, but call the
4871 * finalizer first if registered. */
4873 if (refPtr
->finalizerCmdNamePtr
) {
4874 char *refstr
= Jim_Alloc(JIM_REFERENCE_SPACE
+ 1);
4875 Jim_Obj
*objv
[3], *oldResult
;
4877 JimFormatReference(refstr
, refPtr
, *refId
);
4879 objv
[0] = refPtr
->finalizerCmdNamePtr
;
4880 objv
[1] = Jim_NewStringObjNoAlloc(interp
, refstr
, 32);
4881 objv
[2] = refPtr
->objPtr
;
4882 Jim_IncrRefCount(objv
[0]);
4883 Jim_IncrRefCount(objv
[1]);
4884 Jim_IncrRefCount(objv
[2]);
4886 /* Drop the reference itself */
4887 Jim_DeleteHashEntry(&interp
->references
, refId
);
4889 /* Call the finalizer. Errors ignored. */
4890 oldResult
= interp
->result
;
4891 Jim_IncrRefCount(oldResult
);
4892 Jim_EvalObjVector(interp
, 3, objv
);
4893 Jim_SetResult(interp
, oldResult
);
4894 Jim_DecrRefCount(interp
, oldResult
);
4896 Jim_DecrRefCount(interp
, objv
[0]);
4897 Jim_DecrRefCount(interp
, objv
[1]);
4898 Jim_DecrRefCount(interp
, objv
[2]);
4901 Jim_DeleteHashEntry(&interp
->references
, refId
);
4905 Jim_FreeHashTableIterator(htiter
);
4906 Jim_FreeHashTable(&marks
);
4907 interp
->lastCollectId
= interp
->referenceNextId
;
4908 interp
->lastCollectTime
= time(NULL
);
4909 #endif /* JIM_BOOTSTRAP */
4913 #define JIM_COLLECT_ID_PERIOD 5000
4914 #define JIM_COLLECT_TIME_PERIOD 300
4916 void Jim_CollectIfNeeded(Jim_Interp
*interp
)
4921 elapsedId
= interp
->referenceNextId
- interp
->lastCollectId
;
4922 elapsedTime
= time(NULL
) - interp
->lastCollectTime
;
4925 if (elapsedId
> JIM_COLLECT_ID_PERIOD
|| elapsedTime
> JIM_COLLECT_TIME_PERIOD
) {
4926 Jim_Collect(interp
);
4931 static int JimIsBigEndian(void)
4938 return uval
.c
[0] == 1;
4941 /* -----------------------------------------------------------------------------
4942 * Interpreter related functions
4943 * ---------------------------------------------------------------------------*/
4945 Jim_Interp
*Jim_CreateInterp(void)
4947 Jim_Interp
*i
= Jim_Alloc(sizeof(*i
));
4949 memset(i
, 0, sizeof(*i
));
4951 i
->maxNestingDepth
= JIM_MAX_NESTING_DEPTH
;
4952 i
->lastCollectTime
= time(NULL
);
4954 /* Note that we can create objects only after the
4955 * interpreter liveList and freeList pointers are
4956 * initialized to NULL. */
4957 Jim_InitHashTable(&i
->commands
, &JimCommandsHashTableType
, i
);
4958 #ifdef JIM_REFERENCES
4959 Jim_InitHashTable(&i
->references
, &JimReferencesHashTableType
, i
);
4961 Jim_InitHashTable(&i
->assocData
, &JimAssocDataHashTableType
, i
);
4962 Jim_InitHashTable(&i
->packages
, &JimStringKeyValCopyHashTableType
, NULL
);
4963 i
->framePtr
= i
->topFramePtr
= JimCreateCallFrame(i
, NULL
);
4964 i
->emptyObj
= Jim_NewEmptyStringObj(i
);
4965 i
->trueObj
= Jim_NewIntObj(i
, 1);
4966 i
->falseObj
= Jim_NewIntObj(i
, 0);
4967 i
->errorFileNameObj
= i
->emptyObj
;
4968 i
->result
= i
->emptyObj
;
4969 i
->stackTrace
= Jim_NewListObj(i
, NULL
, 0);
4970 i
->unknown
= Jim_NewStringObj(i
, "unknown", -1);
4971 i
->errorProc
= i
->emptyObj
;
4972 i
->currentScriptObj
= Jim_NewEmptyStringObj(i
);
4973 Jim_IncrRefCount(i
->emptyObj
);
4974 Jim_IncrRefCount(i
->errorFileNameObj
);
4975 Jim_IncrRefCount(i
->result
);
4976 Jim_IncrRefCount(i
->stackTrace
);
4977 Jim_IncrRefCount(i
->unknown
);
4978 Jim_IncrRefCount(i
->currentScriptObj
);
4979 Jim_IncrRefCount(i
->errorProc
);
4980 Jim_IncrRefCount(i
->trueObj
);
4981 Jim_IncrRefCount(i
->falseObj
);
4983 /* Initialize key variables every interpreter should contain */
4984 Jim_SetVariableStrWithStr(i
, JIM_LIBPATH
, TCL_LIBRARY
);
4985 Jim_SetVariableStrWithStr(i
, JIM_INTERACTIVE
, "0");
4987 Jim_SetVariableStrWithStr(i
, "tcl_platform(os)", TCL_PLATFORM_OS
);
4988 Jim_SetVariableStrWithStr(i
, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM
);
4989 Jim_SetVariableStrWithStr(i
, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR
);
4990 Jim_SetVariableStrWithStr(i
, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4991 Jim_SetVariableStrWithStr(i
, "tcl_platform(threaded)", "0");
4992 Jim_SetVariableStr(i
, "tcl_platform(pointerSize)", Jim_NewIntObj(i
, sizeof(void *)));
4993 Jim_SetVariableStr(i
, "tcl_platform(wordSize)", Jim_NewIntObj(i
, sizeof(jim_wide
)));
4998 void Jim_FreeInterp(Jim_Interp
*i
)
5000 Jim_CallFrame
*cf
= i
->framePtr
, *prevcf
, *nextcf
;
5001 Jim_Obj
*objPtr
, *nextObjPtr
;
5003 Jim_DecrRefCount(i
, i
->emptyObj
);
5004 Jim_DecrRefCount(i
, i
->trueObj
);
5005 Jim_DecrRefCount(i
, i
->falseObj
);
5006 Jim_DecrRefCount(i
, i
->result
);
5007 Jim_DecrRefCount(i
, i
->stackTrace
);
5008 Jim_DecrRefCount(i
, i
->errorProc
);
5009 Jim_DecrRefCount(i
, i
->unknown
);
5010 Jim_DecrRefCount(i
, i
->errorFileNameObj
);
5011 Jim_DecrRefCount(i
, i
->currentScriptObj
);
5012 Jim_FreeHashTable(&i
->commands
);
5013 #ifdef JIM_REFERENCES
5014 Jim_FreeHashTable(&i
->references
);
5016 Jim_FreeHashTable(&i
->packages
);
5017 Jim_Free(i
->prngState
);
5018 Jim_FreeHashTable(&i
->assocData
);
5019 JimDeleteLocalProcs(i
);
5021 /* Free the call frames list */
5023 prevcf
= cf
->parentCallFrame
;
5024 JimFreeCallFrame(i
, cf
, JIM_FCF_NONE
);
5027 /* Check that the live object list is empty, otherwise
5028 * there is a memory leak. */
5029 if (i
->liveList
!= NULL
) {
5030 objPtr
= i
->liveList
;
5032 printf(JIM_NL
"-------------------------------------" JIM_NL
);
5033 printf("Objects still in the free list:" JIM_NL
);
5035 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "string";
5037 printf("%p (%d) %-10s: '%.20s'" JIM_NL
,
5038 (void *)objPtr
, objPtr
->refCount
, type
, objPtr
->bytes
? objPtr
->bytes
: "(null)");
5039 if (objPtr
->typePtr
== &sourceObjType
) {
5040 printf("FILE %s LINE %d" JIM_NL
,
5041 Jim_String(objPtr
->internalRep
.sourceValue
.fileNameObj
),
5042 objPtr
->internalRep
.sourceValue
.lineNumber
);
5044 objPtr
= objPtr
->nextObjPtr
;
5046 printf("-------------------------------------" JIM_NL JIM_NL
);
5047 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5049 /* Free all the freed objects. */
5050 objPtr
= i
->freeList
;
5052 nextObjPtr
= objPtr
->nextObjPtr
;
5054 objPtr
= nextObjPtr
;
5056 /* Free cached CallFrame structures */
5057 cf
= i
->freeFramesList
;
5059 nextcf
= cf
->nextFramePtr
;
5060 if (cf
->vars
.table
!= NULL
)
5061 Jim_Free(cf
->vars
.table
);
5066 Jim_FreeLoadHandles(i
);
5069 /* Free the interpreter structure. */
5073 /* Returns the call frame relative to the level represented by
5074 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5076 * This function accepts the 'level' argument in the form
5077 * of the commands [uplevel] and [upvar].
5079 * For a function accepting a relative integer as level suitable
5080 * for implementation of [info level ?level?] check the
5081 * JimGetCallFrameByInteger() function.
5083 * Returns NULL on error.
5085 Jim_CallFrame
*Jim_GetCallFrameByLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5089 Jim_CallFrame
*framePtr
;
5092 str
= Jim_String(levelObjPtr
);
5093 if (str
[0] == '#') {
5096 level
= strtol(str
+ 1, &endptr
, 0);
5097 if (str
[1] == '\0' || endptr
[0] != '\0') {
5102 if (Jim_GetLong(interp
, levelObjPtr
, &level
) != JIM_OK
|| level
< 0) {
5106 /* Convert from a relative to an absolute level */
5107 level
= interp
->framePtr
->level
- level
;
5112 str
= "1"; /* Needed to format the error message. */
5113 level
= interp
->framePtr
->level
- 1;
5117 return interp
->topFramePtr
;
5121 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5122 if (framePtr
->level
== level
) {
5128 Jim_SetResultFormatted(interp
, "bad level \"%s\"", str
);
5132 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5133 * as a relative integer like in the [info level ?level?] command.
5135 static Jim_CallFrame
*JimGetCallFrameByInteger(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5138 Jim_CallFrame
*framePtr
;
5140 if (Jim_GetLong(interp
, levelObjPtr
, &level
) == JIM_OK
) {
5142 /* Convert from a relative to an absolute level */
5143 level
= interp
->framePtr
->level
+ level
;
5147 return interp
->topFramePtr
;
5151 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5152 if (framePtr
->level
== level
) {
5158 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
5162 static void JimResetStackTrace(Jim_Interp
*interp
)
5164 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5165 interp
->stackTrace
= Jim_NewListObj(interp
, NULL
, 0);
5166 Jim_IncrRefCount(interp
->stackTrace
);
5169 static void JimSetStackTrace(Jim_Interp
*interp
, Jim_Obj
*stackTraceObj
)
5173 /* Increment reference first in case these are the same object */
5174 Jim_IncrRefCount(stackTraceObj
);
5175 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5176 interp
->stackTrace
= stackTraceObj
;
5177 interp
->errorFlag
= 1;
5179 /* This is a bit ugly.
5180 * If the filename of the last entry of the stack trace is empty,
5181 * the next stack level should be added.
5183 len
= Jim_ListLength(interp
, interp
->stackTrace
);
5185 Jim_Obj
*filenameObj
;
5187 Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &filenameObj
, JIM_NONE
);
5189 Jim_GetString(filenameObj
, &len
);
5191 if (!Jim_Length(filenameObj
)) {
5192 interp
->addStackTrace
= 1;
5197 /* Returns 1 if the stack trace information was used or 0 if not */
5198 static void JimAppendStackTrace(Jim_Interp
*interp
, const char *procname
,
5199 Jim_Obj
*fileNameObj
, int linenr
)
5201 if (strcmp(procname
, "unknown") == 0) {
5204 if (!*procname
&& !Jim_Length(fileNameObj
)) {
5205 /* No useful info here */
5209 if (Jim_IsShared(interp
->stackTrace
)) {
5210 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5211 interp
->stackTrace
= Jim_DuplicateObj(interp
, interp
->stackTrace
);
5212 Jim_IncrRefCount(interp
->stackTrace
);
5215 /* If we have no procname but the previous element did, merge with that frame */
5216 if (!*procname
&& Jim_Length(fileNameObj
)) {
5217 /* Just a filename. Check the previous entry */
5218 int len
= Jim_ListLength(interp
, interp
->stackTrace
);
5222 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 3, &objPtr
, JIM_NONE
) == JIM_OK
&& Jim_Length(objPtr
)) {
5223 /* Yes, the previous level had procname */
5224 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &objPtr
, JIM_NONE
) == JIM_OK
&& !Jim_Length(objPtr
)) {
5225 /* But no filename, so merge the new info with that frame */
5226 ListSetIndex(interp
, interp
->stackTrace
, len
- 2, fileNameObj
, 0);
5227 ListSetIndex(interp
, interp
->stackTrace
, len
- 1, Jim_NewIntObj(interp
, linenr
), 0);
5234 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewStringObj(interp
, procname
, -1));
5235 Jim_ListAppendElement(interp
, interp
->stackTrace
, fileNameObj
);
5236 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewIntObj(interp
, linenr
));
5239 int Jim_SetAssocData(Jim_Interp
*interp
, const char *key
, Jim_InterpDeleteProc
* delProc
,
5242 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) Jim_Alloc(sizeof(AssocDataValue
));
5244 assocEntryPtr
->delProc
= delProc
;
5245 assocEntryPtr
->data
= data
;
5246 return Jim_AddHashEntry(&interp
->assocData
, key
, assocEntryPtr
);
5249 void *Jim_GetAssocData(Jim_Interp
*interp
, const char *key
)
5251 Jim_HashEntry
*entryPtr
= Jim_FindHashEntry(&interp
->assocData
, key
);
5253 if (entryPtr
!= NULL
) {
5254 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) entryPtr
->u
.val
;
5256 return assocEntryPtr
->data
;
5261 int Jim_DeleteAssocData(Jim_Interp
*interp
, const char *key
)
5263 return Jim_DeleteHashEntry(&interp
->assocData
, key
);
5266 int Jim_GetExitCode(Jim_Interp
*interp
)
5268 return interp
->exitCode
;
5271 /* -----------------------------------------------------------------------------
5273 * ---------------------------------------------------------------------------*/
5274 #define JIM_INTEGER_SPACE 24
5276 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
);
5277 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
5279 static const Jim_ObjType intObjType
= {
5287 /* A coerced double is closer to an int than a double.
5288 * It is an int value temporarily masquerading as a double value.
5289 * i.e. it has the same string value as an int and Jim_GetWide()
5290 * succeeds, but also Jim_GetDouble() returns the value directly.
5292 static const Jim_ObjType coercedDoubleObjType
= {
5301 void UpdateStringOfInt(struct Jim_Obj
*objPtr
)
5304 char buf
[JIM_INTEGER_SPACE
+ 1];
5306 len
= Jim_WideToString(buf
, JimWideValue(objPtr
));
5307 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5308 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5309 objPtr
->length
= len
;
5312 int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
5317 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5318 /* Simple switcheroo */
5319 objPtr
->typePtr
= &intObjType
;
5323 /* Get the string representation */
5324 str
= Jim_String(objPtr
);
5325 /* Try to convert into a jim_wide */
5326 if (Jim_StringToWide(str
, &wideValue
, 0) != JIM_OK
) {
5327 if (flags
& JIM_ERRMSG
) {
5328 Jim_SetResultFormatted(interp
, "expected integer but got \"%#s\"", objPtr
);
5332 if ((wideValue
== JIM_WIDE_MIN
|| wideValue
== JIM_WIDE_MAX
) && errno
== ERANGE
) {
5333 Jim_SetResultString(interp
, "Integer value too big to be represented", -1);
5336 /* Free the old internal repr and set the new one. */
5337 Jim_FreeIntRep(interp
, objPtr
);
5338 objPtr
->typePtr
= &intObjType
;
5339 objPtr
->internalRep
.wideValue
= wideValue
;
5343 #ifdef JIM_OPTIMIZATION
5344 static int JimIsWide(Jim_Obj
*objPtr
)
5346 return objPtr
->typePtr
== &intObjType
;
5350 int Jim_GetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5352 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
5354 *widePtr
= JimWideValue(objPtr
);
5358 /* Get a wide but does not set an error if the format is bad. */
5359 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5361 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_NONE
) == JIM_ERR
)
5363 *widePtr
= JimWideValue(objPtr
);
5367 int Jim_GetLong(Jim_Interp
*interp
, Jim_Obj
*objPtr
, long *longPtr
)
5372 retval
= Jim_GetWide(interp
, objPtr
, &wideValue
);
5373 if (retval
== JIM_OK
) {
5374 *longPtr
= (long)wideValue
;
5380 Jim_Obj
*Jim_NewIntObj(Jim_Interp
*interp
, jim_wide wideValue
)
5384 objPtr
= Jim_NewObj(interp
);
5385 objPtr
->typePtr
= &intObjType
;
5386 objPtr
->bytes
= NULL
;
5387 objPtr
->internalRep
.wideValue
= wideValue
;
5391 /* -----------------------------------------------------------------------------
5393 * ---------------------------------------------------------------------------*/
5394 #define JIM_DOUBLE_SPACE 30
5396 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
);
5397 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5399 static const Jim_ObjType doubleObjType
= {
5403 UpdateStringOfDouble
,
5407 void UpdateStringOfDouble(struct Jim_Obj
*objPtr
)
5410 char buf
[JIM_DOUBLE_SPACE
+ 1];
5412 len
= Jim_DoubleToString(buf
, objPtr
->internalRep
.doubleValue
);
5413 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5414 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5415 objPtr
->length
= len
;
5418 int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5424 /* Preserve the string representation.
5425 * Needed so we can convert back to int without loss
5427 str
= Jim_String(objPtr
);
5429 #ifdef HAVE_LONG_LONG
5430 /* Assume a 53 bit mantissa */
5431 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5432 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5434 if (objPtr
->typePtr
== &intObjType
5435 && JimWideValue(objPtr
) >= MIN_INT_IN_DOUBLE
5436 && JimWideValue(objPtr
) <= MAX_INT_IN_DOUBLE
) {
5438 /* Direct conversion to coerced double */
5439 objPtr
->typePtr
= &coercedDoubleObjType
;
5444 if (Jim_StringToWide(str
, &wideValue
, 10) == JIM_OK
) {
5445 /* Managed to convert to an int, so we can use this as a cooerced double */
5446 Jim_FreeIntRep(interp
, objPtr
);
5447 objPtr
->typePtr
= &coercedDoubleObjType
;
5448 objPtr
->internalRep
.wideValue
= wideValue
;
5452 /* Try to convert into a double */
5453 if (Jim_StringToDouble(str
, &doubleValue
) != JIM_OK
) {
5454 Jim_SetResultFormatted(interp
, "expected number but got \"%#s\"", objPtr
);
5457 /* Free the old internal repr and set the new one. */
5458 Jim_FreeIntRep(interp
, objPtr
);
5460 objPtr
->typePtr
= &doubleObjType
;
5461 objPtr
->internalRep
.doubleValue
= doubleValue
;
5465 int Jim_GetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double *doublePtr
)
5467 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5468 *doublePtr
= JimWideValue(objPtr
);
5471 if (objPtr
->typePtr
!= &doubleObjType
&& SetDoubleFromAny(interp
, objPtr
) == JIM_ERR
)
5474 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5475 *doublePtr
= JimWideValue(objPtr
);
5478 *doublePtr
= objPtr
->internalRep
.doubleValue
;
5483 Jim_Obj
*Jim_NewDoubleObj(Jim_Interp
*interp
, double doubleValue
)
5487 objPtr
= Jim_NewObj(interp
);
5488 objPtr
->typePtr
= &doubleObjType
;
5489 objPtr
->bytes
= NULL
;
5490 objPtr
->internalRep
.doubleValue
= doubleValue
;
5494 /* -----------------------------------------------------------------------------
5496 * ---------------------------------------------------------------------------*/
5497 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
);
5498 static void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5499 static void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
5500 static void UpdateStringOfList(struct Jim_Obj
*objPtr
);
5501 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
5503 /* Note that while the elements of the list may contain references,
5504 * the list object itself can't. This basically means that the
5505 * list object string representation as a whole can't contain references
5506 * that are not presents in the single elements. */
5507 static const Jim_ObjType listObjType
= {
5509 FreeListInternalRep
,
5515 void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5519 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5520 Jim_DecrRefCount(interp
, objPtr
->internalRep
.listValue
.ele
[i
]);
5522 Jim_Free(objPtr
->internalRep
.listValue
.ele
);
5525 void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
5529 JIM_NOTUSED(interp
);
5531 dupPtr
->internalRep
.listValue
.len
= srcPtr
->internalRep
.listValue
.len
;
5532 dupPtr
->internalRep
.listValue
.maxLen
= srcPtr
->internalRep
.listValue
.maxLen
;
5533 dupPtr
->internalRep
.listValue
.ele
=
5534 Jim_Alloc(sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.maxLen
);
5535 memcpy(dupPtr
->internalRep
.listValue
.ele
, srcPtr
->internalRep
.listValue
.ele
,
5536 sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.len
);
5537 for (i
= 0; i
< dupPtr
->internalRep
.listValue
.len
; i
++) {
5538 Jim_IncrRefCount(dupPtr
->internalRep
.listValue
.ele
[i
]);
5540 dupPtr
->typePtr
= &listObjType
;
5543 /* The following function checks if a given string can be encoded
5544 * into a list element without any kind of quoting, surrounded by braces,
5545 * or using escapes to quote. */
5546 #define JIM_ELESTR_SIMPLE 0
5547 #define JIM_ELESTR_BRACE 1
5548 #define JIM_ELESTR_QUOTE 2
5549 static int ListElementQuotingType(const char *s
, int len
)
5551 int i
, level
, blevel
, trySimple
= 1;
5553 /* Try with the SIMPLE case */
5555 return JIM_ELESTR_BRACE
;
5557 return JIM_ELESTR_BRACE
;
5558 if (s
[0] == '"' || s
[0] == '{') {
5562 for (i
= 0; i
< len
; i
++) {
5582 return JIM_ELESTR_SIMPLE
;
5585 /* Test if it's possible to do with braces */
5586 if (s
[len
- 1] == '\\')
5587 return JIM_ELESTR_QUOTE
;
5590 for (i
= 0; i
< len
; i
++) {
5598 return JIM_ELESTR_QUOTE
;
5607 if (s
[i
+ 1] == '\n')
5608 return JIM_ELESTR_QUOTE
;
5609 else if (s
[i
+ 1] != '\0')
5615 return JIM_ELESTR_QUOTE
;
5620 return JIM_ELESTR_BRACE
;
5621 for (i
= 0; i
< len
; i
++) {
5635 return JIM_ELESTR_BRACE
;
5639 return JIM_ELESTR_SIMPLE
;
5641 return JIM_ELESTR_QUOTE
;
5644 /* Returns the malloc-ed representation of a string
5645 * using backslash to quote special chars. */
5646 static char *BackslashQuoteString(const char *s
, int len
, int *qlenPtr
)
5648 char *q
= Jim_Alloc(len
* 2 + 1), *p
;
5700 static void UpdateStringOfList(struct Jim_Obj
*objPtr
)
5702 int i
, bufLen
, realLength
;
5706 Jim_Obj
**ele
= objPtr
->internalRep
.listValue
.ele
;
5708 /* (Over) Estimate the space needed. */
5709 quotingType
= Jim_Alloc(sizeof(int) * objPtr
->internalRep
.listValue
.len
+ 1);
5711 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5714 strRep
= Jim_GetString(ele
[i
], &len
);
5715 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
5716 switch (quotingType
[i
]) {
5717 case JIM_ELESTR_SIMPLE
:
5720 case JIM_ELESTR_BRACE
:
5723 case JIM_ELESTR_QUOTE
:
5727 bufLen
++; /* elements separator. */
5731 /* Generate the string rep. */
5732 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
5734 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5738 strRep
= Jim_GetString(ele
[i
], &len
);
5740 switch (quotingType
[i
]) {
5741 case JIM_ELESTR_SIMPLE
:
5742 memcpy(p
, strRep
, len
);
5746 case JIM_ELESTR_BRACE
:
5748 memcpy(p
, strRep
, len
);
5751 realLength
+= len
+ 2;
5753 case JIM_ELESTR_QUOTE
:
5754 q
= BackslashQuoteString(strRep
, len
, &qlen
);
5761 /* Add a separating space */
5762 if (i
+ 1 != objPtr
->internalRep
.listValue
.len
) {
5767 *p
= '\0'; /* nul term. */
5768 objPtr
->length
= realLength
;
5769 Jim_Free(quotingType
);
5772 int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
5774 struct JimParserCtx parser
;
5777 Jim_Obj
*fileNameObj
;
5780 /* Try to preserve information about filename / line number */
5781 if (objPtr
->typePtr
== &sourceObjType
) {
5782 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
5783 linenr
= objPtr
->internalRep
.sourceValue
.lineNumber
;
5786 fileNameObj
= interp
->emptyObj
;
5789 Jim_IncrRefCount(fileNameObj
);
5791 /* Get the string representation */
5792 str
= Jim_GetString(objPtr
, &strLen
);
5794 /* Free the old internal repr just now and initialize the
5795 * new one just now. The string->list conversion can't fail. */
5796 Jim_FreeIntRep(interp
, objPtr
);
5797 objPtr
->typePtr
= &listObjType
;
5798 objPtr
->internalRep
.listValue
.len
= 0;
5799 objPtr
->internalRep
.listValue
.maxLen
= 0;
5800 objPtr
->internalRep
.listValue
.ele
= NULL
;
5802 /* Convert into a list */
5803 JimParserInit(&parser
, str
, strLen
, linenr
);
5804 while (!parser
.eof
) {
5805 Jim_Obj
*elementPtr
;
5807 JimParseList(&parser
);
5808 if (parser
.tt
!= JIM_TT_STR
&& parser
.tt
!= JIM_TT_ESC
)
5810 elementPtr
= JimParserGetTokenObj(interp
, &parser
);
5811 JimSetSourceInfo(interp
, elementPtr
, fileNameObj
, parser
.tline
);
5812 ListAppendElement(objPtr
, elementPtr
);
5814 Jim_DecrRefCount(interp
, fileNameObj
);
5818 Jim_Obj
*Jim_NewListObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
5823 objPtr
= Jim_NewObj(interp
);
5824 objPtr
->typePtr
= &listObjType
;
5825 objPtr
->bytes
= NULL
;
5826 objPtr
->internalRep
.listValue
.ele
= NULL
;
5827 objPtr
->internalRep
.listValue
.len
= 0;
5828 objPtr
->internalRep
.listValue
.maxLen
= 0;
5829 for (i
= 0; i
< len
; i
++) {
5830 ListAppendElement(objPtr
, elements
[i
]);
5835 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5836 * length of the vector. Note that the user of this function should make
5837 * sure that the list object can't shimmer while the vector returned
5838 * is in use, this vector is the one stored inside the internal representation
5839 * of the list object. This function is not exported, extensions should
5840 * always access to the List object elements using Jim_ListIndex(). */
5841 static void JimListGetElements(Jim_Interp
*interp
, Jim_Obj
*listObj
, int *listLen
,
5844 *listLen
= Jim_ListLength(interp
, listObj
);
5845 *listVec
= listObj
->internalRep
.listValue
.ele
;
5848 /* Sorting uses ints, but commands may return wide */
5849 static int JimSign(jim_wide w
)
5860 /* ListSortElements type values */
5874 int (*subfn
)(Jim_Obj
**, Jim_Obj
**);
5877 static struct lsort_info
*sort_info
;
5879 static int ListSortIndexHelper(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5881 Jim_Obj
*lObj
, *rObj
;
5883 if (Jim_ListIndex(sort_info
->interp
, *lhsObj
, sort_info
->index
, &lObj
, JIM_ERRMSG
) != JIM_OK
||
5884 Jim_ListIndex(sort_info
->interp
, *rhsObj
, sort_info
->index
, &rObj
, JIM_ERRMSG
) != JIM_OK
) {
5885 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5887 return sort_info
->subfn(&lObj
, &rObj
);
5890 /* Sort the internal rep of a list. */
5891 static int ListSortString(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5893 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 0) * sort_info
->order
;
5896 static int ListSortStringNoCase(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5898 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 1) * sort_info
->order
;
5901 static int ListSortInteger(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5903 jim_wide lhs
= 0, rhs
= 0;
5905 if (Jim_GetWide(sort_info
->interp
, *lhsObj
, &lhs
) != JIM_OK
||
5906 Jim_GetWide(sort_info
->interp
, *rhsObj
, &rhs
) != JIM_OK
) {
5907 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5910 return JimSign(lhs
- rhs
) * sort_info
->order
;
5913 static int ListSortCommand(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5915 Jim_Obj
*compare_script
;
5920 /* This must be a valid list */
5921 compare_script
= Jim_DuplicateObj(sort_info
->interp
, sort_info
->command
);
5922 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *lhsObj
);
5923 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *rhsObj
);
5925 rc
= Jim_EvalObj(sort_info
->interp
, compare_script
);
5927 if (rc
!= JIM_OK
|| Jim_GetWide(sort_info
->interp
, Jim_GetResult(sort_info
->interp
), &ret
) != JIM_OK
) {
5928 longjmp(sort_info
->jmpbuf
, rc
);
5931 return JimSign(ret
) * sort_info
->order
;
5934 /* Sort a list *in place*. MUST be called with non-shared objects. */
5935 static int ListSortElements(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, struct lsort_info
*info
)
5937 struct lsort_info
*prev_info
;
5939 typedef int (qsort_comparator
) (const void *, const void *);
5940 int (*fn
) (Jim_Obj
**, Jim_Obj
**);
5945 JimPanic((Jim_IsShared(listObjPtr
), "Jim_ListSortElements called with shared object"));
5946 if (!Jim_IsList(listObjPtr
))
5947 SetListFromAny(interp
, listObjPtr
);
5949 /* Allow lsort to be called reentrantly */
5950 prev_info
= sort_info
;
5953 vector
= listObjPtr
->internalRep
.listValue
.ele
;
5954 len
= listObjPtr
->internalRep
.listValue
.len
;
5955 switch (info
->type
) {
5956 case JIM_LSORT_ASCII
:
5957 fn
= ListSortString
;
5959 case JIM_LSORT_NOCASE
:
5960 fn
= ListSortStringNoCase
;
5962 case JIM_LSORT_INTEGER
:
5963 fn
= ListSortInteger
;
5965 case JIM_LSORT_COMMAND
:
5966 fn
= ListSortCommand
;
5969 fn
= NULL
; /* avoid warning */
5970 JimPanic((1, "ListSort called with invalid sort type"));
5973 if (info
->indexed
) {
5974 /* Need to interpose a "list index" function */
5976 fn
= ListSortIndexHelper
;
5979 if ((rc
= setjmp(info
->jmpbuf
)) == 0) {
5980 qsort(vector
, len
, sizeof(Jim_Obj
*), (qsort_comparator
*) fn
);
5982 Jim_InvalidateStringRep(listObjPtr
);
5983 sort_info
= prev_info
;
5988 /* This is the low-level function to insert elements into a list.
5989 * The higher-level Jim_ListInsertElements() performs shared object
5990 * check and invalidate the string repr. This version is used
5991 * in the internals of the List Object and is not exported.
5993 * NOTE: this function can be called only against objects
5994 * with internal type of List. */
5995 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
)
5997 int currentLen
= listPtr
->internalRep
.listValue
.len
;
5998 int requiredLen
= currentLen
+ elemc
;
6002 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
6003 int maxLen
= requiredLen
* 2;
6005 listPtr
->internalRep
.listValue
.ele
=
6006 Jim_Realloc(listPtr
->internalRep
.listValue
.ele
, sizeof(Jim_Obj
*) * maxLen
);
6007 listPtr
->internalRep
.listValue
.maxLen
= maxLen
;
6009 point
= listPtr
->internalRep
.listValue
.ele
+ idx
;
6010 memmove(point
+ elemc
, point
, (currentLen
- idx
) * sizeof(Jim_Obj
*));
6011 for (i
= 0; i
< elemc
; ++i
) {
6012 point
[i
] = elemVec
[i
];
6013 Jim_IncrRefCount(point
[i
]);
6015 listPtr
->internalRep
.listValue
.len
+= elemc
;
6018 /* Convenience call to ListInsertElements() to append a single element.
6020 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6022 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
, 1, &objPtr
);
6026 /* Appends every element of appendListPtr into listPtr.
6027 * Both have to be of the list type.
6028 * Convenience call to ListInsertElements()
6030 static void ListAppendList(Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6032 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
,
6033 appendListPtr
->internalRep
.listValue
.len
, appendListPtr
->internalRep
.listValue
.ele
);
6036 void Jim_ListAppendElement(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6038 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendElement called with shared object"));
6039 if (!Jim_IsList(listPtr
))
6040 SetListFromAny(interp
, listPtr
);
6041 Jim_InvalidateStringRep(listPtr
);
6042 ListAppendElement(listPtr
, objPtr
);
6045 void Jim_ListAppendList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6047 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendList called with shared object"));
6048 if (!Jim_IsList(listPtr
))
6049 SetListFromAny(interp
, listPtr
);
6050 Jim_InvalidateStringRep(listPtr
);
6051 ListAppendList(listPtr
, appendListPtr
);
6054 int Jim_ListLength(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6056 if (!Jim_IsList(objPtr
))
6057 SetListFromAny(interp
, objPtr
);
6058 return objPtr
->internalRep
.listValue
.len
;
6061 void Jim_ListInsertElements(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6062 int objc
, Jim_Obj
*const *objVec
)
6064 JimPanic((Jim_IsShared(listPtr
), "Jim_ListInsertElement called with shared object"));
6065 if (!Jim_IsList(listPtr
))
6066 SetListFromAny(interp
, listPtr
);
6067 if (idx
>= 0 && idx
> listPtr
->internalRep
.listValue
.len
)
6068 idx
= listPtr
->internalRep
.listValue
.len
;
6071 Jim_InvalidateStringRep(listPtr
);
6072 ListInsertElements(listPtr
, idx
, objc
, objVec
);
6075 int Jim_ListIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
, Jim_Obj
**objPtrPtr
, int flags
)
6077 if (!Jim_IsList(listPtr
))
6078 SetListFromAny(interp
, listPtr
);
6079 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6080 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6081 if (flags
& JIM_ERRMSG
) {
6082 Jim_SetResultString(interp
, "list index out of range", -1);
6088 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6089 *objPtrPtr
= listPtr
->internalRep
.listValue
.ele
[idx
];
6093 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6094 Jim_Obj
*newObjPtr
, int flags
)
6096 if (!Jim_IsList(listPtr
))
6097 SetListFromAny(interp
, listPtr
);
6098 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6099 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6100 if (flags
& JIM_ERRMSG
) {
6101 Jim_SetResultString(interp
, "list index out of range", -1);
6106 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6107 Jim_DecrRefCount(interp
, listPtr
->internalRep
.listValue
.ele
[idx
]);
6108 listPtr
->internalRep
.listValue
.ele
[idx
] = newObjPtr
;
6109 Jim_IncrRefCount(newObjPtr
);
6113 /* Modify the list stored into the variable named 'varNamePtr'
6114 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6115 * with the new element 'newObjptr'. */
6116 int Jim_SetListIndex(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6117 Jim_Obj
*const *indexv
, int indexc
, Jim_Obj
*newObjPtr
)
6119 Jim_Obj
*varObjPtr
, *objPtr
, *listObjPtr
;
6122 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
| JIM_UNSHARED
);
6125 if ((shared
= Jim_IsShared(objPtr
)))
6126 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6127 for (i
= 0; i
< indexc
- 1; i
++) {
6128 listObjPtr
= objPtr
;
6129 if (Jim_GetIndex(interp
, indexv
[i
], &idx
) != JIM_OK
)
6131 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_ERRMSG
) != JIM_OK
) {
6134 if (Jim_IsShared(objPtr
)) {
6135 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6136 ListSetIndex(interp
, listObjPtr
, idx
, objPtr
, JIM_NONE
);
6138 Jim_InvalidateStringRep(listObjPtr
);
6140 if (Jim_GetIndex(interp
, indexv
[indexc
- 1], &idx
) != JIM_OK
)
6142 if (ListSetIndex(interp
, objPtr
, idx
, newObjPtr
, JIM_ERRMSG
) == JIM_ERR
)
6144 Jim_InvalidateStringRep(objPtr
);
6145 Jim_InvalidateStringRep(varObjPtr
);
6146 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
6148 Jim_SetResult(interp
, varObjPtr
);
6152 Jim_FreeNewObj(interp
, varObjPtr
);
6157 Jim_Obj
*Jim_ConcatObj(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
6161 /* If all the objects in objv are lists,
6162 * it's possible to return a list as result, that's the
6163 * concatenation of all the lists. */
6164 for (i
= 0; i
< objc
; i
++) {
6165 if (!Jim_IsList(objv
[i
]))
6169 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
6171 for (i
= 0; i
< objc
; i
++)
6172 Jim_ListAppendList(interp
, objPtr
, objv
[i
]);
6176 /* Else... we have to glue strings together */
6177 int len
= 0, objLen
;
6180 /* Compute the length */
6181 for (i
= 0; i
< objc
; i
++) {
6182 Jim_GetString(objv
[i
], &objLen
);
6187 /* Create the string rep, and a string object holding it. */
6188 p
= bytes
= Jim_Alloc(len
+ 1);
6189 for (i
= 0; i
< objc
; i
++) {
6190 const char *s
= Jim_GetString(objv
[i
], &objLen
);
6192 /* Remove leading space */
6193 while (objLen
&& (*s
== ' ' || *s
== '\t' || *s
== '\n')) {
6198 /* And trailing space */
6199 while (objLen
&& (s
[objLen
- 1] == ' ' ||
6200 s
[objLen
- 1] == '\n' || s
[objLen
- 1] == '\t')) {
6201 /* Handle trailing backslash-space case */
6202 if (objLen
> 1 && s
[objLen
- 2] == '\\') {
6208 memcpy(p
, s
, objLen
);
6210 if (objLen
&& i
+ 1 != objc
) {
6213 else if (i
+ 1 != objc
) {
6214 /* Drop the space calcuated for this
6215 * element that is instead null. */
6220 return Jim_NewStringObjNoAlloc(interp
, bytes
, len
);
6224 /* Returns a list composed of the elements in the specified range.
6225 * first and start are directly accepted as Jim_Objects and
6226 * processed for the end?-index? case. */
6227 Jim_Obj
*Jim_ListRange(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*firstObjPtr
,
6228 Jim_Obj
*lastObjPtr
)
6233 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
6234 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
6236 len
= Jim_ListLength(interp
, listObjPtr
); /* will convert into list */
6237 first
= JimRelToAbsIndex(len
, first
);
6238 last
= JimRelToAbsIndex(len
, last
);
6239 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
6240 if (first
== 0 && last
== len
) {
6243 return Jim_NewListObj(interp
, listObjPtr
->internalRep
.listValue
.ele
+ first
, rangeLen
);
6246 /* -----------------------------------------------------------------------------
6248 * ---------------------------------------------------------------------------*/
6249 static void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6250 static void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
6251 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
);
6252 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6254 /* Dict HashTable Type.
6256 * Keys and Values are Jim objects. */
6258 static unsigned int JimObjectHTHashFunction(const void *key
)
6261 Jim_Obj
*objPtr
= (Jim_Obj
*)key
;
6264 str
= Jim_GetString(objPtr
, &len
);
6265 return Jim_GenHashFunction((unsigned char *)str
, len
);
6268 static int JimObjectHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
6270 JIM_NOTUSED(privdata
);
6272 return Jim_StringEqObj((Jim_Obj
*)key1
, (Jim_Obj
*)key2
);
6275 static void JimObjectHTKeyValDestructor(void *interp
, void *val
)
6277 Jim_Obj
*objPtr
= val
;
6279 Jim_DecrRefCount(interp
, objPtr
);
6282 static const Jim_HashTableType JimDictHashTableType
= {
6283 JimObjectHTHashFunction
, /* hash function */
6286 JimObjectHTKeyCompare
, /* key compare */
6287 (void (*)(void *, const void *)) /* ATTENTION: const cast */
6288 JimObjectHTKeyValDestructor
, /* key destructor */
6289 JimObjectHTKeyValDestructor
/* val destructor */
6292 /* Note that while the elements of the dict may contain references,
6293 * the list object itself can't. This basically means that the
6294 * dict object string representation as a whole can't contain references
6295 * that are not presents in the single elements. */
6296 static const Jim_ObjType dictObjType
= {
6298 FreeDictInternalRep
,
6304 void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6306 JIM_NOTUSED(interp
);
6308 Jim_FreeHashTable(objPtr
->internalRep
.ptr
);
6309 Jim_Free(objPtr
->internalRep
.ptr
);
6312 void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
6314 Jim_HashTable
*ht
, *dupHt
;
6315 Jim_HashTableIterator
*htiter
;
6318 /* Create a new hash table */
6319 ht
= srcPtr
->internalRep
.ptr
;
6320 dupHt
= Jim_Alloc(sizeof(*dupHt
));
6321 Jim_InitHashTable(dupHt
, &JimDictHashTableType
, interp
);
6323 Jim_ExpandHashTable(dupHt
, ht
->size
);
6324 /* Copy every element from the source to the dup hash table */
6325 htiter
= Jim_GetHashTableIterator(ht
);
6326 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6327 const Jim_Obj
*keyObjPtr
= he
->key
;
6328 Jim_Obj
*valObjPtr
= he
->u
.val
;
6330 Jim_IncrRefCount((Jim_Obj
*)keyObjPtr
); /* ATTENTION: const cast */
6331 Jim_IncrRefCount(valObjPtr
);
6332 Jim_AddHashEntry(dupHt
, keyObjPtr
, valObjPtr
);
6334 Jim_FreeHashTableIterator(htiter
);
6336 dupPtr
->internalRep
.ptr
= dupHt
;
6337 dupPtr
->typePtr
= &dictObjType
;
6340 void UpdateStringOfDict(struct Jim_Obj
*objPtr
)
6342 int i
, bufLen
, realLength
;
6345 int *quotingType
, objc
;
6347 Jim_HashTableIterator
*htiter
;
6351 /* Trun the hash table into a flat vector of Jim_Objects. */
6352 ht
= objPtr
->internalRep
.ptr
;
6353 objc
= ht
->used
* 2;
6354 objv
= Jim_Alloc(objc
* sizeof(Jim_Obj
*));
6355 htiter
= Jim_GetHashTableIterator(ht
);
6357 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6358 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6359 objv
[i
++] = he
->u
.val
;
6361 Jim_FreeHashTableIterator(htiter
);
6362 /* (Over) Estimate the space needed. */
6363 quotingType
= Jim_Alloc(sizeof(int) * objc
);
6365 for (i
= 0; i
< objc
; i
++) {
6368 strRep
= Jim_GetString(objv
[i
], &len
);
6369 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
6370 switch (quotingType
[i
]) {
6371 case JIM_ELESTR_SIMPLE
:
6374 case JIM_ELESTR_BRACE
:
6377 case JIM_ELESTR_QUOTE
:
6381 bufLen
++; /* elements separator. */
6385 /* Generate the string rep. */
6386 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
6388 for (i
= 0; i
< objc
; i
++) {
6392 strRep
= Jim_GetString(objv
[i
], &len
);
6394 switch (quotingType
[i
]) {
6395 case JIM_ELESTR_SIMPLE
:
6396 memcpy(p
, strRep
, len
);
6400 case JIM_ELESTR_BRACE
:
6402 memcpy(p
, strRep
, len
);
6405 realLength
+= len
+ 2;
6407 case JIM_ELESTR_QUOTE
:
6408 q
= BackslashQuoteString(strRep
, len
, &qlen
);
6415 /* Add a separating space */
6416 if (i
+ 1 != objc
) {
6421 *p
= '\0'; /* nul term. */
6422 objPtr
->length
= realLength
;
6423 Jim_Free(quotingType
);
6427 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
6431 /* Get the string representation. Do this first so we don't
6432 * change order in case of fast conversion to dict.
6436 /* For simplicity, convert a non-list object to a list and then to a dict */
6437 listlen
= Jim_ListLength(interp
, objPtr
);
6439 Jim_SetResultString(interp
,
6440 "invalid dictionary value: must be a list with an even number of elements", -1);
6444 /* Now it is easy to convert to a dict from a list, and it can't fail */
6448 ht
= Jim_Alloc(sizeof(*ht
));
6449 Jim_InitHashTable(ht
, &JimDictHashTableType
, interp
);
6451 for (i
= 0; i
< listlen
; i
+= 2) {
6455 Jim_ListIndex(interp
, objPtr
, i
, &keyObjPtr
, JIM_NONE
);
6456 Jim_ListIndex(interp
, objPtr
, i
+ 1, &valObjPtr
, JIM_NONE
);
6458 Jim_IncrRefCount(keyObjPtr
);
6459 Jim_IncrRefCount(valObjPtr
);
6461 if (Jim_AddHashEntry(ht
, keyObjPtr
, valObjPtr
) != JIM_OK
) {
6464 he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6465 Jim_DecrRefCount(interp
, keyObjPtr
);
6466 /* ATTENTION: const cast */
6467 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6468 he
->u
.val
= valObjPtr
;
6472 Jim_FreeIntRep(interp
, objPtr
);
6473 objPtr
->typePtr
= &dictObjType
;
6474 objPtr
->internalRep
.ptr
= ht
;
6480 /* Dict object API */
6482 /* Add an element to a dict. objPtr must be of the "dict" type.
6483 * The higer-level exported function is Jim_DictAddElement().
6484 * If an element with the specified key already exists, the value
6485 * associated is replaced with the new one.
6487 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6488 static int DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6489 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6491 Jim_HashTable
*ht
= objPtr
->internalRep
.ptr
;
6493 if (valueObjPtr
== NULL
) { /* unset */
6494 return Jim_DeleteHashEntry(ht
, keyObjPtr
);
6496 Jim_IncrRefCount(keyObjPtr
);
6497 Jim_IncrRefCount(valueObjPtr
);
6498 if (Jim_AddHashEntry(ht
, keyObjPtr
, valueObjPtr
) != JIM_OK
) {
6499 Jim_HashEntry
*he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6501 Jim_DecrRefCount(interp
, keyObjPtr
);
6502 /* ATTENTION: const cast */
6503 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6504 he
->u
.val
= valueObjPtr
;
6509 /* Add an element, higher-level interface for DictAddElement().
6510 * If valueObjPtr == NULL, the key is removed if it exists. */
6511 int Jim_DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6512 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6516 JimPanic((Jim_IsShared(objPtr
), "Jim_DictAddElement called with shared object"));
6517 if (objPtr
->typePtr
!= &dictObjType
) {
6518 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
)
6521 retcode
= DictAddElement(interp
, objPtr
, keyObjPtr
, valueObjPtr
);
6522 Jim_InvalidateStringRep(objPtr
);
6526 Jim_Obj
*Jim_NewDictObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
6531 JimPanic((len
% 2, "Jim_NewDictObj() 'len' argument must be even"));
6533 objPtr
= Jim_NewObj(interp
);
6534 objPtr
->typePtr
= &dictObjType
;
6535 objPtr
->bytes
= NULL
;
6536 objPtr
->internalRep
.ptr
= Jim_Alloc(sizeof(Jim_HashTable
));
6537 Jim_InitHashTable(objPtr
->internalRep
.ptr
, &JimDictHashTableType
, interp
);
6538 for (i
= 0; i
< len
; i
+= 2)
6539 DictAddElement(interp
, objPtr
, elements
[i
], elements
[i
+ 1]);
6543 /* Return the value associated to the specified dict key
6544 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6546 int Jim_DictKey(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
*keyPtr
,
6547 Jim_Obj
**objPtrPtr
, int flags
)
6552 if (dictPtr
->typePtr
!= &dictObjType
) {
6553 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6556 ht
= dictPtr
->internalRep
.ptr
;
6557 if ((he
= Jim_FindHashEntry(ht
, keyPtr
)) == NULL
) {
6558 if (flags
& JIM_ERRMSG
) {
6559 Jim_SetResultFormatted(interp
, "key \"%#s\" not found in dictionary", keyPtr
);
6563 *objPtrPtr
= he
->u
.val
;
6567 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6568 int Jim_DictPairs(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
***objPtrPtr
, int *len
)
6571 Jim_HashTableIterator
*htiter
;
6576 if (dictPtr
->typePtr
!= &dictObjType
) {
6577 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6580 ht
= dictPtr
->internalRep
.ptr
;
6582 /* Turn the hash table into a flat vector of Jim_Objects. */
6583 objv
= Jim_Alloc((ht
->used
* 2) * sizeof(Jim_Obj
*));
6584 htiter
= Jim_GetHashTableIterator(ht
);
6586 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6587 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6588 objv
[i
++] = he
->u
.val
;
6591 Jim_FreeHashTableIterator(htiter
);
6597 /* Return the value associated to the specified dict keys */
6598 int Jim_DictKeysVector(Jim_Interp
*interp
, Jim_Obj
*dictPtr
,
6599 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
**objPtrPtr
, int flags
)
6604 *objPtrPtr
= dictPtr
;
6608 for (i
= 0; i
< keyc
; i
++) {
6611 if (Jim_DictKey(interp
, dictPtr
, keyv
[i
], &objPtr
, flags
)
6616 *objPtrPtr
= dictPtr
;
6620 /* Modify the dict stored into the variable named 'varNamePtr'
6621 * setting the element specified by the 'keyc' keys objects in 'keyv',
6622 * with the new value of the element 'newObjPtr'.
6624 * If newObjPtr == NULL the operation is to remove the given key
6625 * from the dictionary.
6627 * If flags & JIM_ERRMSG, then failure to remove the key is considered an error
6628 * and JIM_ERR is returned. Otherwise it is ignored and JIM_OK is returned.
6630 int Jim_SetDictKeysVector(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6631 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*newObjPtr
, int flags
)
6633 Jim_Obj
*varObjPtr
, *objPtr
, *dictObjPtr
;
6636 varObjPtr
= objPtr
=
6637 Jim_GetVariable(interp
, varNamePtr
, newObjPtr
== NULL
? JIM_ERRMSG
: JIM_NONE
);
6638 if (objPtr
== NULL
) {
6639 if (newObjPtr
== NULL
) /* Cannot remove a key from non existing var */ {
6642 varObjPtr
= objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6643 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
6644 Jim_FreeNewObj(interp
, varObjPtr
);
6648 if ((shared
= Jim_IsShared(objPtr
)))
6649 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6650 for (i
= 0; i
< keyc
- 1; i
++) {
6651 dictObjPtr
= objPtr
;
6653 /* Check if it's a valid dictionary */
6654 if (dictObjPtr
->typePtr
!= &dictObjType
) {
6655 if (SetDictFromAny(interp
, dictObjPtr
) != JIM_OK
) {
6659 /* Check if the given key exists. */
6660 Jim_InvalidateStringRep(dictObjPtr
);
6661 if (Jim_DictKey(interp
, dictObjPtr
, keyv
[i
], &objPtr
,
6662 newObjPtr
? JIM_NONE
: JIM_ERRMSG
) == JIM_OK
) {
6663 /* This key exists at the current level.
6664 * Make sure it's not shared!. */
6665 if (Jim_IsShared(objPtr
)) {
6666 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6667 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6671 /* Key not found. If it's an [unset] operation
6672 * this is an error. Only the last key may not
6674 if (newObjPtr
== NULL
) {
6677 /* Otherwise set an empty dictionary
6678 * as key's value. */
6679 objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6680 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6683 /* Note error on unset with missing last key is OK */
6684 if (Jim_DictAddElement(interp
, objPtr
, keyv
[keyc
- 1], newObjPtr
) != JIM_OK
) {
6685 if (newObjPtr
|| (flags
& JIM_ERRMSG
)) {
6689 Jim_InvalidateStringRep(objPtr
);
6690 Jim_InvalidateStringRep(varObjPtr
);
6691 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
) {
6694 Jim_SetResult(interp
, varObjPtr
);
6698 Jim_FreeNewObj(interp
, varObjPtr
);
6703 /* -----------------------------------------------------------------------------
6705 * ---------------------------------------------------------------------------*/
6706 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
);
6707 static int SetIndexFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6709 static const Jim_ObjType indexObjType
= {
6713 UpdateStringOfIndex
,
6717 void UpdateStringOfIndex(struct Jim_Obj
*objPtr
)
6720 char buf
[JIM_INTEGER_SPACE
+ 1];
6722 if (objPtr
->internalRep
.indexValue
>= 0)
6723 len
= sprintf(buf
, "%d", objPtr
->internalRep
.indexValue
);
6724 else if (objPtr
->internalRep
.indexValue
== -1)
6725 len
= sprintf(buf
, "end");
6727 len
= sprintf(buf
, "end%d", objPtr
->internalRep
.indexValue
+ 1);
6729 objPtr
->bytes
= Jim_Alloc(len
+ 1);
6730 memcpy(objPtr
->bytes
, buf
, len
+ 1);
6731 objPtr
->length
= len
;
6734 int SetIndexFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6740 /* Get the string representation */
6741 str
= Jim_String(objPtr
);
6743 /* Try to convert into an index */
6744 if (strncmp(str
, "end", 3) == 0) {
6750 idx
= strtol(str
, &endptr
, 10);
6752 if (endptr
== str
) {
6758 /* Now str may include or +<num> or -<num> */
6759 if (*str
== '+' || *str
== '-') {
6760 int sign
= (*str
== '+' ? 1 : -1);
6762 idx
+= sign
* strtol(++str
, &endptr
, 10);
6763 if (str
== endptr
|| *endptr
) {
6768 /* The only thing left should be spaces */
6769 while (isspace(UCHAR(*str
))) {
6780 /* end-1 is repesented as -2 */
6788 /* Free the old internal repr and set the new one. */
6789 Jim_FreeIntRep(interp
, objPtr
);
6790 objPtr
->typePtr
= &indexObjType
;
6791 objPtr
->internalRep
.indexValue
= idx
;
6795 Jim_SetResultFormatted(interp
,
6796 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr
);
6800 int Jim_GetIndex(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *indexPtr
)
6802 /* Avoid shimmering if the object is an integer. */
6803 if (objPtr
->typePtr
== &intObjType
) {
6804 jim_wide val
= JimWideValue(objPtr
);
6806 if (!(val
< LONG_MIN
) && !(val
> LONG_MAX
)) {
6807 *indexPtr
= (val
< 0) ? -INT_MAX
: (long)val
;;
6811 if (objPtr
->typePtr
!= &indexObjType
&& SetIndexFromAny(interp
, objPtr
) == JIM_ERR
)
6813 *indexPtr
= objPtr
->internalRep
.indexValue
;
6817 /* -----------------------------------------------------------------------------
6818 * Return Code Object.
6819 * ---------------------------------------------------------------------------*/
6821 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6822 static const char * const jimReturnCodes
[] = {
6824 [JIM_ERR
] = "error",
6825 [JIM_RETURN
] = "return",
6826 [JIM_BREAK
] = "break",
6827 [JIM_CONTINUE
] = "continue",
6828 [JIM_SIGNAL
] = "signal",
6829 [JIM_EXIT
] = "exit",
6830 [JIM_EVAL
] = "eval",
6834 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6836 static int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6838 static const Jim_ObjType returnCodeObjType
= {
6846 /* Converts a (standard) return code to a string. Returns "?" for
6847 * non-standard return codes.
6849 const char *Jim_ReturnCode(int code
)
6851 if (code
< 0 || code
>= (int)jimReturnCodesSize
) {
6855 return jimReturnCodes
[code
];
6859 int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6864 /* Try to convert into an integer */
6865 if (JimGetWideNoErr(interp
, objPtr
, &wideValue
) != JIM_ERR
)
6866 returnCode
= (int)wideValue
;
6867 else if (Jim_GetEnum(interp
, objPtr
, jimReturnCodes
, &returnCode
, NULL
, JIM_NONE
) != JIM_OK
) {
6868 Jim_SetResultFormatted(interp
, "expected return code but got \"%#s\"", objPtr
);
6871 /* Free the old internal repr and set the new one. */
6872 Jim_FreeIntRep(interp
, objPtr
);
6873 objPtr
->typePtr
= &returnCodeObjType
;
6874 objPtr
->internalRep
.returnCode
= returnCode
;
6878 int Jim_GetReturnCode(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *intPtr
)
6880 if (objPtr
->typePtr
!= &returnCodeObjType
&& SetReturnCodeFromAny(interp
, objPtr
) == JIM_ERR
)
6882 *intPtr
= objPtr
->internalRep
.returnCode
;
6886 /* -----------------------------------------------------------------------------
6887 * Expression Parsing
6888 * ---------------------------------------------------------------------------*/
6889 static int JimParseExprOperator(struct JimParserCtx
*pc
);
6890 static int JimParseExprNumber(struct JimParserCtx
*pc
);
6891 static int JimParseExprIrrational(struct JimParserCtx
*pc
);
6893 /* Exrp's Stack machine operators opcodes. */
6895 /* Binary operators (numbers) */
6898 /* Continues on from the JIM_TT_ space */
6900 JIM_EXPROP_MUL
= JIM_TT_EXPR_OP
, /* 15 */
6915 JIM_EXPROP_BITAND
, /* 30 */
6919 /* Note must keep these together */
6920 JIM_EXPROP_LOGICAND
, /* 33 */
6921 JIM_EXPROP_LOGICAND_LEFT
,
6922 JIM_EXPROP_LOGICAND_RIGHT
,
6925 JIM_EXPROP_LOGICOR
, /* 36 */
6926 JIM_EXPROP_LOGICOR_LEFT
,
6927 JIM_EXPROP_LOGICOR_RIGHT
,
6930 /* Ternary operators */
6931 JIM_EXPROP_TERNARY
, /* 39 */
6932 JIM_EXPROP_TERNARY_LEFT
,
6933 JIM_EXPROP_TERNARY_RIGHT
,
6936 JIM_EXPROP_COLON
, /* 42 */
6937 JIM_EXPROP_COLON_LEFT
,
6938 JIM_EXPROP_COLON_RIGHT
,
6940 JIM_EXPROP_POW
, /* 45 */
6942 /* Binary operators (strings) */
6948 /* Unary operators (numbers) */
6951 JIM_EXPROP_UNARYMINUS
,
6952 JIM_EXPROP_UNARYPLUS
,
6955 JIM_EXPROP_FUNC_FIRST
,
6956 JIM_EXPROP_FUNC_INT
= JIM_EXPROP_FUNC_FIRST
,
6957 JIM_EXPROP_FUNC_ABS
,
6958 JIM_EXPROP_FUNC_DOUBLE
,
6959 JIM_EXPROP_FUNC_ROUND
,
6960 JIM_EXPROP_FUNC_RAND
,
6961 JIM_EXPROP_FUNC_SRAND
,
6963 #ifdef JIM_MATH_FUNCTIONS
6964 /* math functions from libm */
6965 JIM_EXPROP_FUNC_SIN
,
6966 JIM_EXPROP_FUNC_COS
,
6967 JIM_EXPROP_FUNC_TAN
,
6968 JIM_EXPROP_FUNC_ASIN
,
6969 JIM_EXPROP_FUNC_ACOS
,
6970 JIM_EXPROP_FUNC_ATAN
,
6971 JIM_EXPROP_FUNC_SINH
,
6972 JIM_EXPROP_FUNC_COSH
,
6973 JIM_EXPROP_FUNC_TANH
,
6974 JIM_EXPROP_FUNC_CEIL
,
6975 JIM_EXPROP_FUNC_FLOOR
,
6976 JIM_EXPROP_FUNC_EXP
,
6977 JIM_EXPROP_FUNC_LOG
,
6978 JIM_EXPROP_FUNC_LOG10
,
6979 JIM_EXPROP_FUNC_SQRT
,
6991 /* Operators table */
6992 typedef struct Jim_ExprOperator
6997 int (*funcop
) (Jim_Interp
*interp
, struct JimExprState
* e
);
7001 static void ExprPush(struct JimExprState
*e
, Jim_Obj
*obj
)
7003 Jim_IncrRefCount(obj
);
7004 e
->stack
[e
->stacklen
++] = obj
;
7007 static Jim_Obj
*ExprPop(struct JimExprState
*e
)
7009 return e
->stack
[--e
->stacklen
];
7012 static int JimExprOpNumUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7016 Jim_Obj
*A
= ExprPop(e
);
7018 jim_wide wA
, wC
= 0;
7020 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) && JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
) {
7023 switch (e
->opcode
) {
7024 case JIM_EXPROP_FUNC_INT
:
7027 case JIM_EXPROP_FUNC_ROUND
:
7030 case JIM_EXPROP_FUNC_DOUBLE
:
7034 case JIM_EXPROP_FUNC_ABS
:
7035 wC
= wA
>= 0 ? wA
: -wA
;
7037 case JIM_EXPROP_UNARYMINUS
:
7040 case JIM_EXPROP_UNARYPLUS
:
7043 case JIM_EXPROP_NOT
:
7050 else if ((rc
= Jim_GetDouble(interp
, A
, &dA
)) == JIM_OK
) {
7051 switch (e
->opcode
) {
7052 case JIM_EXPROP_FUNC_INT
:
7056 case JIM_EXPROP_FUNC_ROUND
:
7057 wC
= dA
< 0 ? (dA
- 0.5) : (dA
+ 0.5);
7060 case JIM_EXPROP_FUNC_DOUBLE
:
7063 case JIM_EXPROP_FUNC_ABS
:
7064 dC
= dA
>= 0 ? dA
: -dA
;
7066 case JIM_EXPROP_UNARYMINUS
:
7069 case JIM_EXPROP_UNARYPLUS
:
7072 case JIM_EXPROP_NOT
:
7083 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7086 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7090 Jim_DecrRefCount(interp
, A
);
7095 static double JimRandDouble(Jim_Interp
*interp
)
7098 JimRandomBytes(interp
, &x
, sizeof(x
));
7100 return (double)x
/ (unsigned long)~0;
7103 static int JimExprOpIntUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7105 Jim_Obj
*A
= ExprPop(e
);
7108 int rc
= Jim_GetWide(interp
, A
, &wA
);
7110 switch (e
->opcode
) {
7111 case JIM_EXPROP_BITNOT
:
7112 ExprPush(e
, Jim_NewIntObj(interp
, ~wA
));
7114 case JIM_EXPROP_FUNC_SRAND
:
7115 JimPrngSeed(interp
, (unsigned char *)&wA
, sizeof(wA
));
7116 ExprPush(e
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7123 Jim_DecrRefCount(interp
, A
);
7128 static int JimExprOpNone(Jim_Interp
*interp
, struct JimExprState
*e
)
7130 JimPanic((e
->opcode
!= JIM_EXPROP_FUNC_RAND
, "JimExprOpNone only support rand()"));
7132 ExprPush(e
, Jim_NewDoubleObj(interp
, JimRandDouble(interp
)));
7137 #ifdef JIM_MATH_FUNCTIONS
7138 static int JimExprOpDoubleUnary(Jim_Interp
*interp
, struct JimExprState
*e
)
7141 Jim_Obj
*A
= ExprPop(e
);
7144 rc
= Jim_GetDouble(interp
, A
, &dA
);
7146 switch (e
->opcode
) {
7147 case JIM_EXPROP_FUNC_SIN
:
7150 case JIM_EXPROP_FUNC_COS
:
7153 case JIM_EXPROP_FUNC_TAN
:
7156 case JIM_EXPROP_FUNC_ASIN
:
7159 case JIM_EXPROP_FUNC_ACOS
:
7162 case JIM_EXPROP_FUNC_ATAN
:
7165 case JIM_EXPROP_FUNC_SINH
:
7168 case JIM_EXPROP_FUNC_COSH
:
7171 case JIM_EXPROP_FUNC_TANH
:
7174 case JIM_EXPROP_FUNC_CEIL
:
7177 case JIM_EXPROP_FUNC_FLOOR
:
7180 case JIM_EXPROP_FUNC_EXP
:
7183 case JIM_EXPROP_FUNC_LOG
:
7186 case JIM_EXPROP_FUNC_LOG10
:
7189 case JIM_EXPROP_FUNC_SQRT
:
7195 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7198 Jim_DecrRefCount(interp
, A
);
7204 /* A binary operation on two ints */
7205 static int JimExprOpIntBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7207 Jim_Obj
*B
= ExprPop(e
);
7208 Jim_Obj
*A
= ExprPop(e
);
7212 if (Jim_GetWide(interp
, A
, &wA
) == JIM_OK
&& Jim_GetWide(interp
, B
, &wB
) == JIM_OK
) {
7217 switch (e
->opcode
) {
7218 case JIM_EXPROP_LSHIFT
:
7221 case JIM_EXPROP_RSHIFT
:
7224 case JIM_EXPROP_BITAND
:
7227 case JIM_EXPROP_BITXOR
:
7230 case JIM_EXPROP_BITOR
:
7233 case JIM_EXPROP_MOD
:
7236 Jim_SetResultString(interp
, "Division by zero", -1);
7243 * This code is tricky: C doesn't guarantee much
7244 * about the quotient or remainder, but Tcl does.
7245 * The remainder always has the same sign as the
7246 * divisor and a smaller absolute value.
7264 case JIM_EXPROP_ROTL
:
7265 case JIM_EXPROP_ROTR
:{
7266 /* uint32_t would be better. But not everyone has inttypes.h? */
7267 unsigned long uA
= (unsigned long)wA
;
7268 unsigned long uB
= (unsigned long)wB
;
7269 const unsigned int S
= sizeof(unsigned long) * 8;
7271 /* Shift left by the word size or more is undefined. */
7274 if (e
->opcode
== JIM_EXPROP_ROTR
) {
7277 wC
= (unsigned long)(uA
<< uB
) | (uA
>> (S
- uB
));
7283 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7287 Jim_DecrRefCount(interp
, A
);
7288 Jim_DecrRefCount(interp
, B
);
7294 /* A binary operation on two ints or two doubles (or two strings for some ops) */
7295 static int JimExprOpBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7299 double dA
, dB
, dC
= 0;
7300 jim_wide wA
, wB
, wC
= 0;
7302 Jim_Obj
*B
= ExprPop(e
);
7303 Jim_Obj
*A
= ExprPop(e
);
7305 if ((A
->typePtr
!= &doubleObjType
|| A
->bytes
) &&
7306 (B
->typePtr
!= &doubleObjType
|| B
->bytes
) &&
7307 JimGetWideNoErr(interp
, A
, &wA
) == JIM_OK
&& JimGetWideNoErr(interp
, B
, &wB
) == JIM_OK
) {
7313 switch (e
->opcode
) {
7314 case JIM_EXPROP_POW
:
7315 wC
= JimPowWide(wA
, wB
);
7317 case JIM_EXPROP_ADD
:
7320 case JIM_EXPROP_SUB
:
7323 case JIM_EXPROP_MUL
:
7326 case JIM_EXPROP_DIV
:
7328 Jim_SetResultString(interp
, "Division by zero", -1);
7335 * This code is tricky: C doesn't guarantee much
7336 * about the quotient or remainder, but Tcl does.
7337 * The remainder always has the same sign as the
7338 * divisor and a smaller absolute value.
7356 case JIM_EXPROP_LTE
:
7359 case JIM_EXPROP_GTE
:
7362 case JIM_EXPROP_NUMEQ
:
7365 case JIM_EXPROP_NUMNE
:
7372 else if (Jim_GetDouble(interp
, A
, &dA
) == JIM_OK
&& Jim_GetDouble(interp
, B
, &dB
) == JIM_OK
) {
7373 switch (e
->opcode
) {
7374 case JIM_EXPROP_POW
:
7375 #ifdef JIM_MATH_FUNCTIONS
7378 Jim_SetResultString(interp
, "unsupported", -1);
7382 case JIM_EXPROP_ADD
:
7385 case JIM_EXPROP_SUB
:
7388 case JIM_EXPROP_MUL
:
7391 case JIM_EXPROP_DIV
:
7394 dC
= dA
< 0 ? -INFINITY
: INFINITY
;
7396 dC
= (dA
< 0 ? -1.0 : 1.0) * strtod("Inf", NULL
);
7411 case JIM_EXPROP_LTE
:
7415 case JIM_EXPROP_GTE
:
7419 case JIM_EXPROP_NUMEQ
:
7423 case JIM_EXPROP_NUMNE
:
7432 /* Handle the string case */
7434 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7435 int i
= Jim_StringCompareObj(interp
, A
, B
, 0);
7439 switch (e
->opcode
) {
7446 case JIM_EXPROP_LTE
:
7449 case JIM_EXPROP_GTE
:
7452 case JIM_EXPROP_NUMEQ
:
7455 case JIM_EXPROP_NUMNE
:
7466 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7469 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7473 Jim_DecrRefCount(interp
, A
);
7474 Jim_DecrRefCount(interp
, B
);
7479 static int JimSearchList(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*valObj
)
7484 listlen
= Jim_ListLength(interp
, listObjPtr
);
7485 for (i
= 0; i
< listlen
; i
++) {
7488 Jim_ListIndex(interp
, listObjPtr
, i
, &objPtr
, JIM_NONE
);
7490 if (Jim_StringEqObj(objPtr
, valObj
)) {
7497 static int JimExprOpStrBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7499 Jim_Obj
*B
= ExprPop(e
);
7500 Jim_Obj
*A
= ExprPop(e
);
7504 switch (e
->opcode
) {
7505 case JIM_EXPROP_STREQ
:
7506 case JIM_EXPROP_STRNE
: {
7508 const char *sA
= Jim_GetString(A
, &Alen
);
7509 const char *sB
= Jim_GetString(B
, &Blen
);
7511 if (e
->opcode
== JIM_EXPROP_STREQ
) {
7512 wC
= (Alen
== Blen
&& memcmp(sA
, sB
, Alen
) == 0);
7515 wC
= (Alen
!= Blen
|| memcmp(sA
, sB
, Alen
) != 0);
7519 case JIM_EXPROP_STRIN
:
7520 wC
= JimSearchList(interp
, B
, A
);
7522 case JIM_EXPROP_STRNI
:
7523 wC
= !JimSearchList(interp
, B
, A
);
7528 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7530 Jim_DecrRefCount(interp
, A
);
7531 Jim_DecrRefCount(interp
, B
);
7536 static int ExprBool(Jim_Interp
*interp
, Jim_Obj
*obj
)
7541 if (Jim_GetLong(interp
, obj
, &l
) == JIM_OK
) {
7544 if (Jim_GetDouble(interp
, obj
, &d
) == JIM_OK
) {
7550 static int JimExprOpAndLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7552 Jim_Obj
*skip
= ExprPop(e
);
7553 Jim_Obj
*A
= ExprPop(e
);
7556 switch (ExprBool(interp
, A
)) {
7558 /* false, so skip RHS opcodes with a 0 result */
7559 e
->skip
= JimWideValue(skip
);
7560 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7564 /* true so continue */
7571 Jim_DecrRefCount(interp
, A
);
7572 Jim_DecrRefCount(interp
, skip
);
7577 static int JimExprOpOrLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7579 Jim_Obj
*skip
= ExprPop(e
);
7580 Jim_Obj
*A
= ExprPop(e
);
7583 switch (ExprBool(interp
, A
)) {
7585 /* false, so do nothing */
7589 /* true so skip RHS opcodes with a 1 result */
7590 e
->skip
= JimWideValue(skip
);
7591 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7599 Jim_DecrRefCount(interp
, A
);
7600 Jim_DecrRefCount(interp
, skip
);
7605 static int JimExprOpAndOrRight(Jim_Interp
*interp
, struct JimExprState
*e
)
7607 Jim_Obj
*A
= ExprPop(e
);
7610 switch (ExprBool(interp
, A
)) {
7612 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7616 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7624 Jim_DecrRefCount(interp
, A
);
7629 static int JimExprOpTernaryLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7631 Jim_Obj
*skip
= ExprPop(e
);
7632 Jim_Obj
*A
= ExprPop(e
);
7638 switch (ExprBool(interp
, A
)) {
7640 /* false, skip RHS opcodes */
7641 e
->skip
= JimWideValue(skip
);
7642 /* Push a dummy value */
7643 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7647 /* true so do nothing */
7655 Jim_DecrRefCount(interp
, A
);
7656 Jim_DecrRefCount(interp
, skip
);
7661 static int JimExprOpColonLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7663 Jim_Obj
*skip
= ExprPop(e
);
7664 Jim_Obj
*B
= ExprPop(e
);
7665 Jim_Obj
*A
= ExprPop(e
);
7667 /* No need to check for A as non-boolean */
7668 if (ExprBool(interp
, A
)) {
7669 /* true, so skip RHS opcodes */
7670 e
->skip
= JimWideValue(skip
);
7671 /* Repush B as the answer */
7675 Jim_DecrRefCount(interp
, skip
);
7676 Jim_DecrRefCount(interp
, A
);
7677 Jim_DecrRefCount(interp
, B
);
7681 static int JimExprOpNull(Jim_Interp
*interp
, struct JimExprState
*e
)
7694 /* name - precedence - arity - opcode */
7695 static const struct Jim_ExprOperator Jim_ExprOperators
[] = {
7696 [JIM_EXPROP_FUNC_INT
] = {"int", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7697 [JIM_EXPROP_FUNC_DOUBLE
] = {"double", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7698 [JIM_EXPROP_FUNC_ABS
] = {"abs", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7699 [JIM_EXPROP_FUNC_ROUND
] = {"round", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7700 [JIM_EXPROP_FUNC_RAND
] = {"rand", 400, 0, JimExprOpNone
, LAZY_NONE
},
7701 [JIM_EXPROP_FUNC_SRAND
] = {"srand", 400, 1, JimExprOpIntUnary
, LAZY_NONE
},
7703 #ifdef JIM_MATH_FUNCTIONS
7704 [JIM_EXPROP_FUNC_SIN
] = {"sin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7705 [JIM_EXPROP_FUNC_COS
] = {"cos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7706 [JIM_EXPROP_FUNC_TAN
] = {"tan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7707 [JIM_EXPROP_FUNC_ASIN
] = {"asin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7708 [JIM_EXPROP_FUNC_ACOS
] = {"acos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7709 [JIM_EXPROP_FUNC_ATAN
] = {"atan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7710 [JIM_EXPROP_FUNC_SINH
] = {"sinh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7711 [JIM_EXPROP_FUNC_COSH
] = {"cosh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7712 [JIM_EXPROP_FUNC_TANH
] = {"tanh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7713 [JIM_EXPROP_FUNC_CEIL
] = {"ceil", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7714 [JIM_EXPROP_FUNC_FLOOR
] = {"floor", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7715 [JIM_EXPROP_FUNC_EXP
] = {"exp", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7716 [JIM_EXPROP_FUNC_LOG
] = {"log", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7717 [JIM_EXPROP_FUNC_LOG10
] = {"log10", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7718 [JIM_EXPROP_FUNC_SQRT
] = {"sqrt", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7721 [JIM_EXPROP_NOT
] = {"!", 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7722 [JIM_EXPROP_BITNOT
] = {"~", 300, 1, JimExprOpIntUnary
, LAZY_NONE
},
7723 [JIM_EXPROP_UNARYMINUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7724 [JIM_EXPROP_UNARYPLUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7726 [JIM_EXPROP_POW
] = {"**", 250, 2, JimExprOpBin
, LAZY_NONE
},
7728 [JIM_EXPROP_MUL
] = {"*", 200, 2, JimExprOpBin
, LAZY_NONE
},
7729 [JIM_EXPROP_DIV
] = {"/", 200, 2, JimExprOpBin
, LAZY_NONE
},
7730 [JIM_EXPROP_MOD
] = {"%", 200, 2, JimExprOpIntBin
, LAZY_NONE
},
7732 [JIM_EXPROP_SUB
] = {"-", 100, 2, JimExprOpBin
, LAZY_NONE
},
7733 [JIM_EXPROP_ADD
] = {"+", 100, 2, JimExprOpBin
, LAZY_NONE
},
7735 [JIM_EXPROP_ROTL
] = {"<<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7736 [JIM_EXPROP_ROTR
] = {">>>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7737 [JIM_EXPROP_LSHIFT
] = {"<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7738 [JIM_EXPROP_RSHIFT
] = {">>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7740 [JIM_EXPROP_LT
] = {"<", 80, 2, JimExprOpBin
, LAZY_NONE
},
7741 [JIM_EXPROP_GT
] = {">", 80, 2, JimExprOpBin
, LAZY_NONE
},
7742 [JIM_EXPROP_LTE
] = {"<=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7743 [JIM_EXPROP_GTE
] = {">=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7745 [JIM_EXPROP_NUMEQ
] = {"==", 70, 2, JimExprOpBin
, LAZY_NONE
},
7746 [JIM_EXPROP_NUMNE
] = {"!=", 70, 2, JimExprOpBin
, LAZY_NONE
},
7748 [JIM_EXPROP_STREQ
] = {"eq", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7749 [JIM_EXPROP_STRNE
] = {"ne", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7751 [JIM_EXPROP_STRIN
] = {"in", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7752 [JIM_EXPROP_STRNI
] = {"ni", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7754 [JIM_EXPROP_BITAND
] = {"&", 50, 2, JimExprOpIntBin
, LAZY_NONE
},
7755 [JIM_EXPROP_BITXOR
] = {"^", 49, 2, JimExprOpIntBin
, LAZY_NONE
},
7756 [JIM_EXPROP_BITOR
] = {"|", 48, 2, JimExprOpIntBin
, LAZY_NONE
},
7758 [JIM_EXPROP_LOGICAND
] = {"&&", 10, 2, NULL
, LAZY_OP
},
7759 [JIM_EXPROP_LOGICOR
] = {"||", 9, 2, NULL
, LAZY_OP
},
7761 [JIM_EXPROP_TERNARY
] = {"?", 5, 2, JimExprOpNull
, LAZY_OP
},
7762 [JIM_EXPROP_COLON
] = {":", 5, 2, JimExprOpNull
, LAZY_OP
},
7764 /* private operators */
7765 [JIM_EXPROP_TERNARY_LEFT
] = {NULL
, 5, 2, JimExprOpTernaryLeft
, LAZY_LEFT
},
7766 [JIM_EXPROP_TERNARY_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7767 [JIM_EXPROP_COLON_LEFT
] = {NULL
, 5, 2, JimExprOpColonLeft
, LAZY_LEFT
},
7768 [JIM_EXPROP_COLON_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7769 [JIM_EXPROP_LOGICAND_LEFT
] = {NULL
, 10, 2, JimExprOpAndLeft
, LAZY_LEFT
},
7770 [JIM_EXPROP_LOGICAND_RIGHT
] = {NULL
, 10, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7771 [JIM_EXPROP_LOGICOR_LEFT
] = {NULL
, 9, 2, JimExprOpOrLeft
, LAZY_LEFT
},
7772 [JIM_EXPROP_LOGICOR_RIGHT
] = {NULL
, 9, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7775 #define JIM_EXPR_OPERATORS_NUM \
7776 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7778 static int JimParseExpression(struct JimParserCtx
*pc
)
7780 /* Discard spaces and quoted newline */
7781 while (isspace(UCHAR(*pc
->p
)) || (*(pc
->p
) == '\\' && *(pc
->p
+ 1) == '\n')) {
7782 if (*pc
->p
== '\n') {
7790 pc
->tstart
= pc
->tend
= pc
->p
;
7791 pc
->tline
= pc
->linenr
;
7792 pc
->tt
= JIM_TT_EOL
;
7798 pc
->tstart
= pc
->tend
= pc
->p
;
7799 pc
->tline
= pc
->linenr
;
7800 pc
->tt
= JIM_TT_SUBEXPR_START
;
7805 pc
->tstart
= pc
->tend
= pc
->p
;
7806 pc
->tline
= pc
->linenr
;
7807 pc
->tt
= JIM_TT_SUBEXPR_END
;
7812 return JimParseCmd(pc
);
7814 if (JimParseVar(pc
) == JIM_ERR
)
7815 return JimParseExprOperator(pc
);
7817 /* Don't allow expr sugar in expressions */
7818 if (pc
->tt
== JIM_TT_EXPRSUGAR
) {
7835 return JimParseExprNumber(pc
);
7837 return JimParseQuote(pc
);
7839 return JimParseBrace(pc
);
7845 if (JimParseExprIrrational(pc
) == JIM_ERR
)
7846 return JimParseExprOperator(pc
);
7849 return JimParseExprOperator(pc
);
7855 static int JimParseExprNumber(struct JimParserCtx
*pc
)
7860 /* Assume an integer for now */
7861 pc
->tt
= JIM_TT_EXPR_INT
;
7863 pc
->tline
= pc
->linenr
;
7864 while (isdigit(UCHAR(*pc
->p
))
7865 || (allowhex
&& isxdigit(UCHAR(*pc
->p
)))
7866 || (allowdot
&& *pc
->p
== '.')
7867 || (pc
->p
- pc
->tstart
== 1 && *pc
->tstart
== '0' && (*pc
->p
== 'x' || *pc
->p
== 'X'))
7869 if ((*pc
->p
== 'x') || (*pc
->p
== 'X')) {
7873 if (*pc
->p
== '.') {
7875 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7879 if (!allowhex
&& (*pc
->p
== 'e' || *pc
->p
== 'E') && (pc
->p
[1] == '-' || pc
->p
[1] == '+'
7880 || isdigit(UCHAR(pc
->p
[1])))) {
7883 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7886 pc
->tend
= pc
->p
- 1;
7890 static int JimParseExprIrrational(struct JimParserCtx
*pc
)
7892 const char *Tokens
[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL
};
7895 for (token
= Tokens
; *token
!= NULL
; token
++) {
7896 int len
= strlen(*token
);
7898 if (strncmp(*token
, pc
->p
, len
) == 0) {
7900 pc
->tend
= pc
->p
+ len
- 1;
7903 pc
->tline
= pc
->linenr
;
7904 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7911 static int JimParseExprOperator(struct JimParserCtx
*pc
)
7914 int bestIdx
= -1, bestLen
= 0;
7916 /* Try to get the longest match. */
7917 for (i
= JIM_TT_EXPR_OP
; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++) {
7921 opname
= Jim_ExprOperators
[i
].name
;
7922 if (opname
== NULL
) {
7925 oplen
= strlen(opname
);
7927 if (strncmp(opname
, pc
->p
, oplen
) == 0 && oplen
> bestLen
) {
7932 if (bestIdx
== -1) {
7936 /* Validate paretheses around function arguments */
7937 if (bestIdx
>= JIM_EXPROP_FUNC_FIRST
) {
7938 const char *p
= pc
->p
+ bestLen
;
7939 int len
= pc
->len
- bestLen
;
7941 while (len
&& isspace(UCHAR(*p
))) {
7950 pc
->tend
= pc
->p
+ bestLen
- 1;
7953 pc
->tline
= pc
->linenr
;
7959 static const struct Jim_ExprOperator
*JimExprOperatorInfoByOpcode(int opcode
)
7961 return &Jim_ExprOperators
[opcode
];
7964 const char *jim_tt_name(int type
)
7966 static const char * const tt_names
[JIM_TT_EXPR_OP
] =
7967 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", "INT",
7969 if (type
< JIM_TT_EXPR_OP
) {
7970 return tt_names
[type
];
7973 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(type
);
7974 static char buf
[20];
7976 if (op
&& op
->name
) {
7979 sprintf(buf
, "(%d)", type
);
7984 /* -----------------------------------------------------------------------------
7986 * ---------------------------------------------------------------------------*/
7987 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
7988 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
7989 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
7991 static const Jim_ObjType exprObjType
= {
7993 FreeExprInternalRep
,
7996 JIM_TYPE_REFERENCES
,
7999 /* Expr bytecode structure */
8000 typedef struct ExprByteCode
8002 int len
; /* Length as number of tokens. */
8003 ScriptToken
*token
; /* Tokens array. */
8004 int inUse
; /* Used for sharing. */
8007 static void ExprFreeByteCode(Jim_Interp
*interp
, ExprByteCode
* expr
)
8011 for (i
= 0; i
< expr
->len
; i
++) {
8012 Jim_DecrRefCount(interp
, expr
->token
[i
].objPtr
);
8014 Jim_Free(expr
->token
);
8018 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8020 ExprByteCode
*expr
= (void *)objPtr
->internalRep
.ptr
;
8023 if (--expr
->inUse
!= 0) {
8027 ExprFreeByteCode(interp
, expr
);
8031 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8033 JIM_NOTUSED(interp
);
8034 JIM_NOTUSED(srcPtr
);
8036 /* Just returns an simple string. */
8037 dupPtr
->typePtr
= NULL
;
8040 /* Check if an expr program looks correct. */
8041 static int ExprCheckCorrectness(ExprByteCode
* expr
)
8047 /* Try to check if there are stack underflows,
8048 * and make sure at the end of the program there is
8049 * a single result on the stack. */
8050 for (i
= 0; i
< expr
->len
; i
++) {
8051 ScriptToken
*t
= &expr
->token
[i
];
8052 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8055 stacklen
-= op
->arity
;
8059 if (t
->type
== JIM_EXPROP_TERNARY
|| t
->type
== JIM_EXPROP_TERNARY_LEFT
) {
8062 else if (t
->type
== JIM_EXPROP_COLON
|| t
->type
== JIM_EXPROP_COLON_LEFT
) {
8067 /* All operations and operands add one to the stack */
8070 if (stacklen
!= 1 || ternary
!= 0) {
8076 /* This procedure converts every occurrence of || and && opereators
8077 * in lazy unary versions.
8079 * a b || is converted into:
8081 * a <offset> |L b |R
8083 * a b && is converted into:
8085 * a <offset> &L b &R
8087 * "|L" checks if 'a' is true:
8088 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8089 * the opcode just after |R.
8090 * 2) if it is false does nothing.
8091 * "|R" checks if 'b' is true:
8092 * 1) if it is true pushes 1, otherwise pushes 0.
8094 * "&L" checks if 'a' is true:
8095 * 1) if it is true does nothing.
8096 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8097 * the opcode just after &R
8098 * "&R" checks if 'a' is true:
8099 * if it is true pushes 1, otherwise pushes 0.
8101 static int ExprAddLazyOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8105 int leftindex
, arity
, offset
;
8107 /* Search for the end of the first operator */
8108 leftindex
= expr
->len
- 1;
8112 ScriptToken
*tt
= &expr
->token
[leftindex
];
8114 if (tt
->type
>= JIM_TT_EXPR_OP
) {
8115 arity
+= JimExprOperatorInfoByOpcode(tt
->type
)->arity
;
8118 if (--leftindex
< 0) {
8125 memmove(&expr
->token
[leftindex
+ 2], &expr
->token
[leftindex
],
8126 sizeof(*expr
->token
) * (expr
->len
- leftindex
));
8128 offset
= (expr
->len
- leftindex
) - 1;
8130 /* Now we rely on the fact the the left and right version have opcodes
8131 * 1 and 2 after the main opcode respectively
8133 expr
->token
[leftindex
+ 1].type
= t
->type
+ 1;
8134 expr
->token
[leftindex
+ 1].objPtr
= interp
->emptyObj
;
8136 expr
->token
[leftindex
].type
= JIM_TT_EXPR_INT
;
8137 expr
->token
[leftindex
].objPtr
= Jim_NewIntObj(interp
, offset
);
8139 /* Now add the 'R' operator */
8140 expr
->token
[expr
->len
].objPtr
= interp
->emptyObj
;
8141 expr
->token
[expr
->len
].type
= t
->type
+ 2;
8144 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8145 for (i
= leftindex
- 1; i
> 0; i
--) {
8146 if (JimExprOperatorInfoByOpcode(expr
->token
[i
].type
)->lazy
== LAZY_LEFT
) {
8147 if (JimWideValue(expr
->token
[i
- 1].objPtr
) + i
- 1 >= leftindex
) {
8148 JimWideValue(expr
->token
[i
- 1].objPtr
) += 2;
8155 static int ExprAddOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8157 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8158 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8160 if (op
->lazy
== LAZY_OP
) {
8161 if (ExprAddLazyOperator(interp
, expr
, t
) != JIM_OK
) {
8162 Jim_SetResultFormatted(interp
, "Expression has bad operands to %s", op
->name
);
8167 token
->objPtr
= interp
->emptyObj
;
8168 token
->type
= t
->type
;
8175 * Returns the index of the COLON_LEFT to the left of 'right_index'
8176 * taking into account nesting.
8178 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8180 static int ExprTernaryGetColonLeftIndex(ExprByteCode
*expr
, int right_index
)
8182 int ternary_count
= 1;
8186 while (right_index
> 1) {
8187 if (expr
->token
[right_index
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8190 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_RIGHT
) {
8193 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_LEFT
&& ternary_count
== 1) {
8204 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8206 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8207 * Otherwise returns 0.
8209 static int ExprTernaryGetMoveIndices(ExprByteCode
*expr
, int right_index
, int *prev_right_index
, int *prev_left_index
)
8211 int i
= right_index
- 1;
8212 int ternary_count
= 1;
8215 if (expr
->token
[i
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8216 if (--ternary_count
== 0 && expr
->token
[i
- 2].type
== JIM_EXPROP_COLON_RIGHT
) {
8217 *prev_right_index
= i
- 2;
8218 *prev_left_index
= ExprTernaryGetColonLeftIndex(expr
, *prev_right_index
);
8222 else if (expr
->token
[i
].type
== JIM_EXPROP_COLON_RIGHT
) {
8223 if (ternary_count
== 0) {
8234 * ExprTernaryReorderExpression description
8235 * ========================================
8237 * ?: is right-to-left associative which doesn't work with the stack-based
8238 * expression engine. The fix is to reorder the bytecode.
8244 * Has initial bytecode:
8246 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8247 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8249 * The fix involves simulating this expression instead:
8253 * With the following bytecode:
8255 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8256 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8258 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8259 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8260 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8261 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8263 * ExprTernaryReorderExpression works thus as follows :
8264 * - start from the end of the stack
8265 * - while walking towards the beginning of the stack
8266 * if token=JIM_EXPROP_COLON_RIGHT then
8267 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8268 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8269 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8271 * perform the rotation
8272 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8276 * Note: care has to be taken for nested ternary constructs!!!
8278 static void ExprTernaryReorderExpression(Jim_Interp
*interp
, ExprByteCode
*expr
)
8282 for (i
= expr
->len
- 1; i
> 1; i
--) {
8283 int prev_right_index
;
8284 int prev_left_index
;
8288 if (expr
->token
[i
].type
!= JIM_EXPROP_COLON_RIGHT
) {
8292 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8293 if (ExprTernaryGetMoveIndices(expr
, i
, &prev_right_index
, &prev_left_index
) == 0) {
8298 ** rotate tokens down
8300 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8309 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8311 tmp
= expr
->token
[prev_right_index
];
8312 for (j
= prev_right_index
; j
< i
; j
++) {
8313 expr
->token
[j
] = expr
->token
[j
+ 1];
8315 expr
->token
[i
] = tmp
;
8317 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8319 * This is 'colon left increment' = i - prev_right_index
8321 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8322 * [prev_left_index-1] : skip_count
8325 JimWideValue(expr
->token
[prev_left_index
-1].objPtr
) += (i
- prev_right_index
);
8327 /* Adjust for i-- in the loop */
8332 static ExprByteCode
*ExprCreateByteCode(Jim_Interp
*interp
, const ParseTokenList
*tokenlist
, Jim_Obj
*fileNameObj
)
8338 int prevtt
= JIM_TT_NONE
;
8339 int have_ternary
= 0;
8342 int count
= tokenlist
->count
- 1;
8344 expr
= Jim_Alloc(sizeof(*expr
));
8348 Jim_InitStack(&stack
);
8350 /* Need extra bytecodes for lazy operators.
8351 * Also check for the ternary operator
8353 for (i
= 0; i
< tokenlist
->count
; i
++) {
8354 ParseToken
*t
= &tokenlist
->list
[i
];
8356 if (JimExprOperatorInfoByOpcode(t
->type
)->lazy
== LAZY_OP
) {
8358 /* Ternary is a lazy op but also needs reordering */
8359 if (t
->type
== JIM_EXPROP_TERNARY
) {
8365 expr
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
8367 for (i
= 0; i
< tokenlist
->count
&& ok
; i
++) {
8368 ParseToken
*t
= &tokenlist
->list
[i
];
8370 /* Next token will be stored here */
8371 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8373 if (t
->type
== JIM_TT_EOL
) {
8381 case JIM_TT_DICTSUGAR
:
8382 case JIM_TT_EXPRSUGAR
:
8384 token
->objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
8385 token
->type
= t
->type
;
8386 if (t
->type
== JIM_TT_CMD
) {
8387 /* Only commands need source info */
8388 JimSetSourceInfo(interp
, token
->objPtr
, fileNameObj
, t
->line
);
8393 case JIM_TT_EXPR_INT
:
8394 token
->objPtr
= Jim_NewIntObj(interp
, strtoull(t
->token
, NULL
, 0));
8395 token
->type
= t
->type
;
8399 case JIM_TT_EXPR_DOUBLE
:
8400 token
->objPtr
= Jim_NewDoubleObj(interp
, strtod(t
->token
, NULL
));
8401 token
->type
= t
->type
;
8405 case JIM_TT_SUBEXPR_START
:
8406 Jim_StackPush(&stack
, t
);
8407 prevtt
= JIM_TT_NONE
;
8410 case JIM_TT_SUBEXPR_END
:
8412 while (Jim_StackLen(&stack
)) {
8413 ParseToken
*tt
= Jim_StackPop(&stack
);
8415 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8420 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8425 Jim_SetResultString(interp
, "Unexpected close parenthesis", -1);
8432 /* Must be an operator */
8433 const struct Jim_ExprOperator
*op
;
8436 /* Convert -/+ to unary minus or unary plus if necessary */
8437 if (prevtt
== JIM_TT_NONE
|| prevtt
>= JIM_TT_EXPR_OP
) {
8438 if (t
->type
== JIM_EXPROP_SUB
) {
8439 t
->type
= JIM_EXPROP_UNARYMINUS
;
8441 else if (t
->type
== JIM_EXPROP_ADD
) {
8442 t
->type
= JIM_EXPROP_UNARYPLUS
;
8446 op
= JimExprOperatorInfoByOpcode(t
->type
);
8448 /* Now handle precedence */
8449 while ((tt
= Jim_StackPeek(&stack
)) != NULL
) {
8450 const struct Jim_ExprOperator
*tt_op
=
8451 JimExprOperatorInfoByOpcode(tt
->type
);
8453 /* Note that right-to-left associativity of ?: operator is handled later */
8455 if (op
->arity
!= 1 && tt_op
->precedence
>= op
->precedence
) {
8456 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8460 Jim_StackPop(&stack
);
8466 Jim_StackPush(&stack
, t
);
8473 /* Reduce any remaining subexpr */
8474 while (Jim_StackLen(&stack
)) {
8475 ParseToken
*tt
= Jim_StackPop(&stack
);
8477 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8479 Jim_SetResultString(interp
, "Missing close parenthesis", -1);
8482 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8489 ExprTernaryReorderExpression(interp
, expr
);
8493 /* Free the stack used for the compilation. */
8494 Jim_FreeStack(&stack
);
8496 for (i
= 0; i
< expr
->len
; i
++) {
8497 Jim_IncrRefCount(expr
->token
[i
].objPtr
);
8501 ExprFreeByteCode(interp
, expr
);
8509 /* This method takes the string representation of an expression
8510 * and generates a program for the Expr's stack-based VM. */
8511 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
8514 const char *exprText
;
8515 struct JimParserCtx parser
;
8516 struct ExprByteCode
*expr
;
8517 ParseTokenList tokenlist
;
8519 Jim_Obj
*fileNameObj
;
8522 /* Try to get information about filename / line number */
8523 if (objPtr
->typePtr
== &sourceObjType
) {
8524 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
8525 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
8528 fileNameObj
= interp
->emptyObj
;
8531 Jim_IncrRefCount(fileNameObj
);
8533 exprText
= Jim_GetString(objPtr
, &exprTextLen
);
8535 /* Initially tokenise the expression into tokenlist */
8536 ScriptTokenListInit(&tokenlist
);
8538 JimParserInit(&parser
, exprText
, exprTextLen
, line
);
8539 while (!parser
.eof
) {
8540 if (JimParseExpression(&parser
) != JIM_OK
) {
8541 ScriptTokenListFree(&tokenlist
);
8543 Jim_SetResultFormatted(interp
, "syntax error in expression: \"%#s\"", objPtr
);
8548 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
8552 #ifdef DEBUG_SHOW_EXPR_TOKENS
8555 printf("==== Expr Tokens ====\n");
8556 for (i
= 0; i
< tokenlist
.count
; i
++) {
8557 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
.list
[i
].line
, jim_tt_name(tokenlist
.list
[i
].type
),
8558 tokenlist
.list
[i
].len
, tokenlist
.list
[i
].token
);
8563 /* Now create the expression bytecode from the tokenlist */
8564 expr
= ExprCreateByteCode(interp
, &tokenlist
, fileNameObj
);
8566 /* No longer need the token list */
8567 ScriptTokenListFree(&tokenlist
);
8573 #ifdef DEBUG_SHOW_EXPR
8577 printf("==== Expr ====\n");
8578 for (i
= 0; i
< expr
->len
; i
++) {
8579 ScriptToken
*t
= &expr
->token
[i
];
8581 printf("[%2d] %s '%s'\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
8586 /* Check program correctness. */
8587 if (ExprCheckCorrectness(expr
) != JIM_OK
) {
8588 ExprFreeByteCode(interp
, expr
);
8595 /* Free the old internal rep and set the new one. */
8596 Jim_DecrRefCount(interp
, fileNameObj
);
8597 Jim_FreeIntRep(interp
, objPtr
);
8598 Jim_SetIntRepPtr(objPtr
, expr
);
8599 objPtr
->typePtr
= &exprObjType
;
8603 static ExprByteCode
*JimGetExpression(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8605 if (objPtr
->typePtr
!= &exprObjType
) {
8606 if (SetExprFromAny(interp
, objPtr
) != JIM_OK
) {
8610 return (ExprByteCode
*) Jim_GetIntRepPtr(objPtr
);
8613 /* -----------------------------------------------------------------------------
8614 * Expressions evaluation.
8615 * Jim uses a specialized stack-based virtual machine for expressions,
8616 * that takes advantage of the fact that expr's operators
8617 * can't be redefined.
8619 * Jim_EvalExpression() uses the bytecode compiled by
8620 * SetExprFromAny() method of the "expression" object.
8622 * On success a Tcl Object containing the result of the evaluation
8623 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8625 * On error the function returns a retcode != to JIM_OK and set a suitable
8626 * error on the interp.
8627 * ---------------------------------------------------------------------------*/
8628 #define JIM_EE_STATICSTACK_LEN 10
8630 int Jim_EvalExpression(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, Jim_Obj
**exprResultPtrPtr
)
8633 Jim_Obj
*staticStack
[JIM_EE_STATICSTACK_LEN
];
8635 int retcode
= JIM_OK
;
8636 struct JimExprState e
;
8638 expr
= JimGetExpression(interp
, exprObjPtr
);
8640 return JIM_ERR
; /* error in expression. */
8643 #ifdef JIM_OPTIMIZATION
8644 /* Check for one of the following common expressions used by while/for
8649 * $a < CONST, $a < $b
8650 * $a <= CONST, $a <= $b
8651 * $a > CONST, $a > $b
8652 * $a >= CONST, $a >= $b
8653 * $a != CONST, $a != $b
8654 * $a == CONST, $a == $b
8659 /* STEP 1 -- Check if there are the conditions to run the specialized
8660 * version of while */
8662 switch (expr
->len
) {
8664 if (expr
->token
[0].type
== JIM_TT_EXPR_INT
) {
8665 *exprResultPtrPtr
= expr
->token
[0].objPtr
;
8666 Jim_IncrRefCount(*exprResultPtrPtr
);
8669 if (expr
->token
[0].type
== JIM_TT_VAR
) {
8670 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_ERRMSG
);
8672 *exprResultPtrPtr
= objPtr
;
8673 Jim_IncrRefCount(*exprResultPtrPtr
);
8680 if (expr
->token
[1].type
== JIM_EXPROP_NOT
&& expr
->token
[0].type
== JIM_TT_VAR
) {
8683 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8684 if (objPtr
&& JimIsWide(objPtr
)
8685 && Jim_GetWide(interp
, objPtr
, &wideValue
) == JIM_OK
) {
8686 *exprResultPtrPtr
= wideValue
? interp
->falseObj
: interp
->trueObj
;
8687 Jim_IncrRefCount(*exprResultPtrPtr
);
8694 if (expr
->token
[0].type
== JIM_TT_VAR
&& (expr
->token
[1].type
== JIM_TT_EXPR_INT
8695 || expr
->token
[1].type
== JIM_TT_VAR
)) {
8696 switch (expr
->token
[2].type
) {
8698 case JIM_EXPROP_LTE
:
8700 case JIM_EXPROP_GTE
:
8701 case JIM_EXPROP_NUMEQ
:
8702 case JIM_EXPROP_NUMNE
:{
8704 jim_wide wideValueA
;
8705 jim_wide wideValueB
;
8707 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8708 if (objPtr
&& JimIsWide(objPtr
)
8709 && Jim_GetWide(interp
, objPtr
, &wideValueA
) == JIM_OK
) {
8710 if (expr
->token
[1].type
== JIM_TT_VAR
) {
8712 Jim_GetVariable(interp
, expr
->token
[1].objPtr
,
8716 objPtr
= expr
->token
[1].objPtr
;
8718 if (objPtr
&& JimIsWide(objPtr
)
8719 && Jim_GetWide(interp
, objPtr
, &wideValueB
) == JIM_OK
) {
8722 switch (expr
->token
[2].type
) {
8724 cmpRes
= wideValueA
< wideValueB
;
8726 case JIM_EXPROP_LTE
:
8727 cmpRes
= wideValueA
<= wideValueB
;
8730 cmpRes
= wideValueA
> wideValueB
;
8732 case JIM_EXPROP_GTE
:
8733 cmpRes
= wideValueA
>= wideValueB
;
8735 case JIM_EXPROP_NUMEQ
:
8736 cmpRes
= wideValueA
== wideValueB
;
8738 case JIM_EXPROP_NUMNE
:
8739 cmpRes
= wideValueA
!= wideValueB
;
8741 default: /*notreached */
8745 cmpRes
? interp
->trueObj
: interp
->falseObj
;
8746 Jim_IncrRefCount(*exprResultPtrPtr
);
8758 /* In order to avoid that the internal repr gets freed due to
8759 * shimmering of the exprObjPtr's object, we make the internal rep
8763 /* The stack-based expr VM itself */
8765 /* Stack allocation. Expr programs have the feature that
8766 * a program of length N can't require a stack longer than
8768 if (expr
->len
> JIM_EE_STATICSTACK_LEN
)
8769 e
.stack
= Jim_Alloc(sizeof(Jim_Obj
*) * expr
->len
);
8771 e
.stack
= staticStack
;
8775 /* Execute every instruction */
8776 for (i
= 0; i
< expr
->len
&& retcode
== JIM_OK
; i
++) {
8779 switch (expr
->token
[i
].type
) {
8780 case JIM_TT_EXPR_INT
:
8781 case JIM_TT_EXPR_DOUBLE
:
8783 ExprPush(&e
, expr
->token
[i
].objPtr
);
8787 objPtr
= Jim_GetVariable(interp
, expr
->token
[i
].objPtr
, JIM_ERRMSG
);
8789 ExprPush(&e
, objPtr
);
8796 case JIM_TT_DICTSUGAR
:
8797 objPtr
= JimExpandDictSugar(interp
, expr
->token
[i
].objPtr
);
8799 ExprPush(&e
, objPtr
);
8807 retcode
= Jim_SubstObj(interp
, expr
->token
[i
].objPtr
, &objPtr
, JIM_NONE
);
8808 if (retcode
== JIM_OK
) {
8809 ExprPush(&e
, objPtr
);
8814 retcode
= Jim_EvalObj(interp
, expr
->token
[i
].objPtr
);
8815 if (retcode
== JIM_OK
) {
8816 ExprPush(&e
, Jim_GetResult(interp
));
8821 /* Find and execute the operation */
8823 e
.opcode
= expr
->token
[i
].type
;
8825 retcode
= JimExprOperatorInfoByOpcode(e
.opcode
)->funcop(interp
, &e
);
8826 /* Skip some opcodes if necessary */
8835 if (retcode
== JIM_OK
) {
8836 *exprResultPtrPtr
= ExprPop(&e
);
8839 for (i
= 0; i
< e
.stacklen
; i
++) {
8840 Jim_DecrRefCount(interp
, e
.stack
[i
]);
8843 if (e
.stack
!= staticStack
) {
8849 int Jim_GetBoolFromExpr(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, int *boolPtr
)
8854 Jim_Obj
*exprResultPtr
;
8856 retcode
= Jim_EvalExpression(interp
, exprObjPtr
, &exprResultPtr
);
8857 if (retcode
!= JIM_OK
)
8860 if (JimGetWideNoErr(interp
, exprResultPtr
, &wideValue
) != JIM_OK
) {
8861 if (Jim_GetDouble(interp
, exprResultPtr
, &doubleValue
) != JIM_OK
) {
8862 Jim_DecrRefCount(interp
, exprResultPtr
);
8866 Jim_DecrRefCount(interp
, exprResultPtr
);
8867 *boolPtr
= doubleValue
!= 0;
8871 *boolPtr
= wideValue
!= 0;
8873 Jim_DecrRefCount(interp
, exprResultPtr
);
8877 /* -----------------------------------------------------------------------------
8878 * ScanFormat String Object
8879 * ---------------------------------------------------------------------------*/
8881 /* This Jim_Obj will held a parsed representation of a format string passed to
8882 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8883 * to be parsed in its entirely first and then, if correct, can be used for
8884 * scanning. To avoid endless re-parsing, the parsed representation will be
8885 * stored in an internal representation and re-used for performance reason. */
8887 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8888 * scanformat string. This part will later be used to extract information
8889 * out from the string to be parsed by Jim_ScanString */
8891 typedef struct ScanFmtPartDescr
8893 char type
; /* Type of conversion (e.g. c, d, f) */
8894 char modifier
; /* Modify type (e.g. l - long, h - short */
8895 size_t width
; /* Maximal width of input to be converted */
8896 int pos
; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8897 char *arg
; /* Specification of a CHARSET conversion */
8898 char *prefix
; /* Prefix to be scanned literally before conversion */
8901 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8902 * string parsed and separated in part descriptions. Furthermore it contains
8903 * the original string representation of the scanformat string to allow for
8904 * fast update of the Jim_Obj's string representation part.
8906 * As an add-on the internal object representation adds some scratch pad area
8907 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8908 * memory for purpose of string scanning.
8910 * The error member points to a static allocated string in case of a mal-
8911 * formed scanformat string or it contains '0' (NULL) in case of a valid
8912 * parse representation.
8914 * The whole memory of the internal representation is allocated as a single
8915 * area of memory that will be internally separated. So freeing and duplicating
8916 * of such an object is cheap */
8918 typedef struct ScanFmtStringObj
8920 jim_wide size
; /* Size of internal repr in bytes */
8921 char *stringRep
; /* Original string representation */
8922 size_t count
; /* Number of ScanFmtPartDescr contained */
8923 size_t convCount
; /* Number of conversions that will assign */
8924 size_t maxPos
; /* Max position index if XPG3 is used */
8925 const char *error
; /* Ptr to error text (NULL if no error */
8926 char *scratch
; /* Some scratch pad used by Jim_ScanString */
8927 ScanFmtPartDescr descr
[1]; /* The vector of partial descriptions */
8931 static void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
8932 static void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
8933 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
);
8935 static const Jim_ObjType scanFmtStringObjType
= {
8937 FreeScanFmtInternalRep
,
8938 DupScanFmtInternalRep
,
8939 UpdateStringOfScanFmt
,
8943 void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8945 JIM_NOTUSED(interp
);
8946 Jim_Free((char *)objPtr
->internalRep
.ptr
);
8947 objPtr
->internalRep
.ptr
= 0;
8950 void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8952 size_t size
= (size_t) ((ScanFmtStringObj
*) srcPtr
->internalRep
.ptr
)->size
;
8953 ScanFmtStringObj
*newVec
= (ScanFmtStringObj
*) Jim_Alloc(size
);
8955 JIM_NOTUSED(interp
);
8956 memcpy(newVec
, srcPtr
->internalRep
.ptr
, size
);
8957 dupPtr
->internalRep
.ptr
= newVec
;
8958 dupPtr
->typePtr
= &scanFmtStringObjType
;
8961 void UpdateStringOfScanFmt(Jim_Obj
*objPtr
)
8963 char *bytes
= ((ScanFmtStringObj
*) objPtr
->internalRep
.ptr
)->stringRep
;
8965 objPtr
->bytes
= Jim_StrDup(bytes
);
8966 objPtr
->length
= strlen(bytes
);
8969 /* SetScanFmtFromAny will parse a given string and create the internal
8970 * representation of the format specification. In case of an error
8971 * the error data member of the internal representation will be set
8972 * to an descriptive error text and the function will be left with
8973 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
8976 static int SetScanFmtFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8978 ScanFmtStringObj
*fmtObj
;
8980 int maxCount
, i
, approxSize
, lastPos
= -1;
8981 const char *fmt
= objPtr
->bytes
;
8982 int maxFmtLen
= objPtr
->length
;
8983 const char *fmtEnd
= fmt
+ maxFmtLen
;
8986 Jim_FreeIntRep(interp
, objPtr
);
8987 /* Count how many conversions could take place maximally */
8988 for (i
= 0, maxCount
= 0; i
< maxFmtLen
; ++i
)
8991 /* Calculate an approximation of the memory necessary */
8992 approxSize
= sizeof(ScanFmtStringObj
) /* Size of the container */
8993 +(maxCount
+ 1) * sizeof(ScanFmtPartDescr
) /* Size of all partials */
8994 +maxFmtLen
* sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
8995 + maxFmtLen
* sizeof(char) + 1 /* Original stringrep */
8996 + maxFmtLen
* sizeof(char) /* Arg for CHARSETs */
8997 +(maxCount
+ 1) * sizeof(char) /* '\0' for every partial */
8998 +1; /* safety byte */
8999 fmtObj
= (ScanFmtStringObj
*) Jim_Alloc(approxSize
);
9000 memset(fmtObj
, 0, approxSize
);
9001 fmtObj
->size
= approxSize
;
9003 fmtObj
->scratch
= (char *)&fmtObj
->descr
[maxCount
+ 1];
9004 fmtObj
->stringRep
= fmtObj
->scratch
+ maxFmtLen
+ 3 + 1;
9005 memcpy(fmtObj
->stringRep
, fmt
, maxFmtLen
);
9006 buffer
= fmtObj
->stringRep
+ maxFmtLen
+ 1;
9007 objPtr
->internalRep
.ptr
= fmtObj
;
9008 objPtr
->typePtr
= &scanFmtStringObjType
;
9009 for (i
= 0, curr
= 0; fmt
< fmtEnd
; ++fmt
) {
9010 int width
= 0, skip
;
9011 ScanFmtPartDescr
*descr
= &fmtObj
->descr
[curr
];
9014 descr
->width
= 0; /* Assume width unspecified */
9015 /* Overread and store any "literal" prefix */
9016 if (*fmt
!= '%' || fmt
[1] == '%') {
9018 descr
->prefix
= &buffer
[i
];
9019 for (; fmt
< fmtEnd
; ++fmt
) {
9029 /* Skip the conversion introducing '%' sign */
9031 /* End reached due to non-conversion literal only? */
9034 descr
->pos
= 0; /* Assume "natural" positioning */
9036 descr
->pos
= -1; /* Okay, conversion will not be assigned */
9040 fmtObj
->convCount
++; /* Otherwise count as assign-conversion */
9041 /* Check if next token is a number (could be width or pos */
9042 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9044 /* Was the number a XPG3 position specifier? */
9045 if (descr
->pos
!= -1 && *fmt
== '$') {
9051 /* Look if "natural" postioning and XPG3 one was mixed */
9052 if ((lastPos
== 0 && descr
->pos
> 0)
9053 || (lastPos
> 0 && descr
->pos
== 0)) {
9054 fmtObj
->error
= "cannot mix \"%\" and \"%n$\" conversion specifiers";
9057 /* Look if this position was already used */
9058 for (prev
= 0; prev
< curr
; ++prev
) {
9059 if (fmtObj
->descr
[prev
].pos
== -1)
9061 if (fmtObj
->descr
[prev
].pos
== descr
->pos
) {
9063 "variable is assigned by multiple \"%n$\" conversion specifiers";
9067 /* Try to find a width after the XPG3 specifier */
9068 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9069 descr
->width
= width
;
9072 if (descr
->pos
> 0 && (size_t) descr
->pos
> fmtObj
->maxPos
)
9073 fmtObj
->maxPos
= descr
->pos
;
9076 /* Number was not a XPG3, so it has to be a width */
9077 descr
->width
= width
;
9080 /* If positioning mode was undetermined yet, fix this */
9082 lastPos
= descr
->pos
;
9083 /* Handle CHARSET conversion type ... */
9085 int swapped
= 1, beg
= i
, end
, j
;
9088 descr
->arg
= &buffer
[i
];
9091 buffer
[i
++] = *fmt
++;
9093 buffer
[i
++] = *fmt
++;
9094 while (*fmt
&& *fmt
!= ']')
9095 buffer
[i
++] = *fmt
++;
9097 fmtObj
->error
= "unmatched [ in format string";
9102 /* In case a range fence was given "backwards", swap it */
9105 for (j
= beg
+ 1; j
< end
- 1; ++j
) {
9106 if (buffer
[j
] == '-' && buffer
[j
- 1] > buffer
[j
+ 1]) {
9107 char tmp
= buffer
[j
- 1];
9109 buffer
[j
- 1] = buffer
[j
+ 1];
9110 buffer
[j
+ 1] = tmp
;
9117 /* Remember any valid modifier if given */
9118 if (strchr("hlL", *fmt
) != 0)
9119 descr
->modifier
= tolower((int)*fmt
++);
9122 if (strchr("efgcsndoxui", *fmt
) == 0) {
9123 fmtObj
->error
= "bad scan conversion character";
9126 else if (*fmt
== 'c' && descr
->width
!= 0) {
9127 fmtObj
->error
= "field width may not be specified in %c " "conversion";
9130 else if (*fmt
== 'u' && descr
->modifier
== 'l') {
9131 fmtObj
->error
= "unsigned wide not supported";
9141 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9143 #define FormatGetCnvCount(_fo_) \
9144 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9145 #define FormatGetMaxPos(_fo_) \
9146 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9147 #define FormatGetError(_fo_) \
9148 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9150 /* JimScanAString is used to scan an unspecified string that ends with
9151 * next WS, or a string that is specified via a charset.
9154 static Jim_Obj
*JimScanAString(Jim_Interp
*interp
, const char *sdescr
, const char *str
)
9156 char *buffer
= Jim_StrDup(str
);
9163 if (!sdescr
&& isspace(UCHAR(*str
)))
9164 break; /* EOS via WS if unspecified */
9166 n
= utf8_tounicode(str
, &c
);
9167 if (sdescr
&& !JimCharsetMatch(sdescr
, c
, JIM_CHARSET_SCAN
))
9173 return Jim_NewStringObjNoAlloc(interp
, buffer
, p
- buffer
);
9176 /* ScanOneEntry will scan one entry out of the string passed as argument.
9177 * It use the sscanf() function for this task. After extracting and
9178 * converting of the value, the count of scanned characters will be
9179 * returned of -1 in case of no conversion tool place and string was
9180 * already scanned thru */
9182 static int ScanOneEntry(Jim_Interp
*interp
, const char *str
, int pos
, int strLen
,
9183 ScanFmtStringObj
* fmtObj
, long idx
, Jim_Obj
**valObjPtr
)
9186 const ScanFmtPartDescr
*descr
= &fmtObj
->descr
[idx
];
9188 size_t anchor
= pos
;
9190 Jim_Obj
*tmpObj
= NULL
;
9192 /* First pessimistically assume, we will not scan anything :-) */
9194 if (descr
->prefix
) {
9195 /* There was a prefix given before the conversion, skip it and adjust
9196 * the string-to-be-parsed accordingly */
9197 /* XXX: Should be checking strLen, not str[pos] */
9198 for (i
= 0; pos
< strLen
&& descr
->prefix
[i
]; ++i
) {
9199 /* If prefix require, skip WS */
9200 if (isspace(UCHAR(descr
->prefix
[i
])))
9201 while (pos
< strLen
&& isspace(UCHAR(str
[pos
])))
9203 else if (descr
->prefix
[i
] != str
[pos
])
9204 break; /* Prefix do not match here, leave the loop */
9206 ++pos
; /* Prefix matched so far, next round */
9208 if (pos
>= strLen
) {
9209 return -1; /* All of str consumed: EOF condition */
9211 else if (descr
->prefix
[i
] != 0)
9212 return 0; /* Not whole prefix consumed, no conversion possible */
9214 /* For all but following conversion, skip leading WS */
9215 if (descr
->type
!= 'c' && descr
->type
!= '[' && descr
->type
!= 'n')
9216 while (isspace(UCHAR(str
[pos
])))
9218 /* Determine how much skipped/scanned so far */
9219 scanned
= pos
- anchor
;
9221 /* %c is a special, simple case. no width */
9222 if (descr
->type
== 'n') {
9223 /* Return pseudo conversion means: how much scanned so far? */
9224 *valObjPtr
= Jim_NewIntObj(interp
, anchor
+ scanned
);
9226 else if (pos
>= strLen
) {
9227 /* Cannot scan anything, as str is totally consumed */
9230 else if (descr
->type
== 'c') {
9232 scanned
+= utf8_tounicode(&str
[pos
], &c
);
9233 *valObjPtr
= Jim_NewIntObj(interp
, c
);
9237 /* Processing of conversions follows ... */
9238 if (descr
->width
> 0) {
9239 /* Do not try to scan as fas as possible but only the given width.
9240 * To ensure this, we copy the part that should be scanned. */
9241 size_t sLen
= utf8_strlen(&str
[pos
], strLen
- pos
);
9242 size_t tLen
= descr
->width
> sLen
? sLen
: descr
->width
;
9244 tmpObj
= Jim_NewStringObjUtf8(interp
, str
+ pos
, tLen
);
9245 tok
= tmpObj
->bytes
;
9248 /* As no width was given, simply refer to the original string */
9251 switch (descr
->type
) {
9257 char *endp
; /* Position where the number finished */
9260 int base
= descr
->type
== 'o' ? 8
9261 : descr
->type
== 'x' ? 16 : descr
->type
== 'i' ? 0 : 10;
9263 /* Try to scan a number with the given base */
9264 w
= strtoull(tok
, &endp
, base
);
9265 if (endp
== tok
&& base
== 0) {
9266 /* If scanning failed, and base was undetermined, simply
9267 * put it to 10 and try once more. This should catch the
9268 * case where %i begin to parse a number prefix (e.g.
9269 * '0x' but no further digits follows. This will be
9270 * handled as a ZERO followed by a char 'x' by Tcl */
9271 w
= strtoull(tok
, &endp
, 10);
9275 /* There was some number sucessfully scanned! */
9276 *valObjPtr
= Jim_NewIntObj(interp
, w
);
9278 /* Adjust the number-of-chars scanned so far */
9279 scanned
+= endp
- tok
;
9282 /* Nothing was scanned. We have to determine if this
9283 * happened due to e.g. prefix mismatch or input str
9285 scanned
= *tok
? 0 : -1;
9291 *valObjPtr
= JimScanAString(interp
, descr
->arg
, tok
);
9292 scanned
+= Jim_Length(*valObjPtr
);
9299 double value
= strtod(tok
, &endp
);
9302 /* There was some number sucessfully scanned! */
9303 *valObjPtr
= Jim_NewDoubleObj(interp
, value
);
9304 /* Adjust the number-of-chars scanned so far */
9305 scanned
+= endp
- tok
;
9308 /* Nothing was scanned. We have to determine if this
9309 * happened due to e.g. prefix mismatch or input str
9311 scanned
= *tok
? 0 : -1;
9316 /* If a substring was allocated (due to pre-defined width) do not
9317 * forget to free it */
9319 Jim_FreeNewObj(interp
, tmpObj
);
9325 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9326 * string and returns all converted (and not ignored) values in a list back
9327 * to the caller. If an error occured, a NULL pointer will be returned */
9329 Jim_Obj
*Jim_ScanString(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*fmtObjPtr
, int flags
)
9333 const char *str
= Jim_String(strObjPtr
);
9334 int strLen
= Jim_Utf8Length(interp
, strObjPtr
);
9335 Jim_Obj
*resultList
= 0;
9336 Jim_Obj
**resultVec
= 0;
9338 Jim_Obj
*emptyStr
= 0;
9339 ScanFmtStringObj
*fmtObj
;
9341 /* This should never happen. The format object should already be of the correct type */
9342 JimPanic((fmtObjPtr
->typePtr
!= &scanFmtStringObjType
, "Jim_ScanString() for non-scan format"));
9344 fmtObj
= (ScanFmtStringObj
*) fmtObjPtr
->internalRep
.ptr
;
9345 /* Check if format specification was valid */
9346 if (fmtObj
->error
!= 0) {
9347 if (flags
& JIM_ERRMSG
)
9348 Jim_SetResultString(interp
, fmtObj
->error
, -1);
9351 /* Allocate a new "shared" empty string for all unassigned conversions */
9352 emptyStr
= Jim_NewEmptyStringObj(interp
);
9353 Jim_IncrRefCount(emptyStr
);
9354 /* Create a list and fill it with empty strings up to max specified XPG3 */
9355 resultList
= Jim_NewListObj(interp
, 0, 0);
9356 if (fmtObj
->maxPos
> 0) {
9357 for (i
= 0; i
< fmtObj
->maxPos
; ++i
)
9358 Jim_ListAppendElement(interp
, resultList
, emptyStr
);
9359 JimListGetElements(interp
, resultList
, &resultc
, &resultVec
);
9361 /* Now handle every partial format description */
9362 for (i
= 0, pos
= 0; i
< fmtObj
->count
; ++i
) {
9363 ScanFmtPartDescr
*descr
= &(fmtObj
->descr
[i
]);
9366 /* Only last type may be "literal" w/o conversion - skip it! */
9367 if (descr
->type
== 0)
9369 /* As long as any conversion could be done, we will proceed */
9371 scanned
= ScanOneEntry(interp
, str
, pos
, strLen
, fmtObj
, i
, &value
);
9372 /* In case our first try results in EOF, we will leave */
9373 if (scanned
== -1 && i
== 0)
9375 /* Advance next pos-to-be-scanned for the amount scanned already */
9378 /* value == 0 means no conversion took place so take empty string */
9380 value
= Jim_NewEmptyStringObj(interp
);
9381 /* If value is a non-assignable one, skip it */
9382 if (descr
->pos
== -1) {
9383 Jim_FreeNewObj(interp
, value
);
9385 else if (descr
->pos
== 0)
9386 /* Otherwise append it to the result list if no XPG3 was given */
9387 Jim_ListAppendElement(interp
, resultList
, value
);
9388 else if (resultVec
[descr
->pos
- 1] == emptyStr
) {
9389 /* But due to given XPG3, put the value into the corr. slot */
9390 Jim_DecrRefCount(interp
, resultVec
[descr
->pos
- 1]);
9391 Jim_IncrRefCount(value
);
9392 resultVec
[descr
->pos
- 1] = value
;
9395 /* Otherwise, the slot was already used - free obj and ERROR */
9396 Jim_FreeNewObj(interp
, value
);
9400 Jim_DecrRefCount(interp
, emptyStr
);
9403 Jim_DecrRefCount(interp
, emptyStr
);
9404 Jim_FreeNewObj(interp
, resultList
);
9405 return (Jim_Obj
*)EOF
;
9407 Jim_DecrRefCount(interp
, emptyStr
);
9408 Jim_FreeNewObj(interp
, resultList
);
9412 /* -----------------------------------------------------------------------------
9413 * Pseudo Random Number Generation
9414 * ---------------------------------------------------------------------------*/
9415 /* Initialize the sbox with the numbers from 0 to 255 */
9416 static void JimPrngInit(Jim_Interp
*interp
)
9418 #define PRNG_SEED_SIZE 256
9421 time_t t
= time(NULL
);
9423 interp
->prngState
= Jim_Alloc(sizeof(Jim_PrngState
));
9425 seed
= Jim_Alloc(PRNG_SEED_SIZE
* sizeof(*seed
));
9426 for (i
= 0; i
< PRNG_SEED_SIZE
; i
++) {
9427 seed
[i
] = (rand() ^ t
^ clock());
9429 JimPrngSeed(interp
, (unsigned char *)seed
, PRNG_SEED_SIZE
* sizeof(*seed
));
9433 /* Generates N bytes of random data */
9434 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
)
9436 Jim_PrngState
*prng
;
9437 unsigned char *destByte
= (unsigned char *)dest
;
9438 unsigned int si
, sj
, x
;
9440 /* initialization, only needed the first time */
9441 if (interp
->prngState
== NULL
)
9442 JimPrngInit(interp
);
9443 prng
= interp
->prngState
;
9444 /* generates 'len' bytes of pseudo-random numbers */
9445 for (x
= 0; x
< len
; x
++) {
9446 prng
->i
= (prng
->i
+ 1) & 0xff;
9447 si
= prng
->sbox
[prng
->i
];
9448 prng
->j
= (prng
->j
+ si
) & 0xff;
9449 sj
= prng
->sbox
[prng
->j
];
9450 prng
->sbox
[prng
->i
] = sj
;
9451 prng
->sbox
[prng
->j
] = si
;
9452 *destByte
++ = prng
->sbox
[(si
+ sj
) & 0xff];
9456 /* Re-seed the generator with user-provided bytes */
9457 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
)
9460 Jim_PrngState
*prng
;
9462 /* initialization, only needed the first time */
9463 if (interp
->prngState
== NULL
)
9464 JimPrngInit(interp
);
9465 prng
= interp
->prngState
;
9467 /* Set the sbox[i] with i */
9468 for (i
= 0; i
< 256; i
++)
9470 /* Now use the seed to perform a random permutation of the sbox */
9471 for (i
= 0; i
< seedLen
; i
++) {
9474 t
= prng
->sbox
[i
& 0xFF];
9475 prng
->sbox
[i
& 0xFF] = prng
->sbox
[seed
[i
]];
9476 prng
->sbox
[seed
[i
]] = t
;
9478 prng
->i
= prng
->j
= 0;
9480 /* discard at least the first 256 bytes of stream.
9481 * borrow the seed buffer for this
9483 for (i
= 0; i
< 256; i
+= seedLen
) {
9484 JimRandomBytes(interp
, seed
, seedLen
);
9489 static int Jim_IncrCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
9491 jim_wide wideValue
, increment
= 1;
9494 if (argc
!= 2 && argc
!= 3) {
9495 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?increment?");
9499 if (Jim_GetWide(interp
, argv
[2], &increment
) != JIM_OK
)
9502 intObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
9504 /* Set missing variable to 0 */
9507 else if (Jim_GetWide(interp
, intObjPtr
, &wideValue
) != JIM_OK
) {
9510 if (!intObjPtr
|| Jim_IsShared(intObjPtr
)) {
9511 intObjPtr
= Jim_NewIntObj(interp
, wideValue
+ increment
);
9512 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
9513 Jim_FreeNewObj(interp
, intObjPtr
);
9518 /* Can do it the quick way */
9519 Jim_InvalidateStringRep(intObjPtr
);
9520 JimWideValue(intObjPtr
) = wideValue
+ increment
;
9522 /* The following step is required in order to invalidate the
9523 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9524 if (argv
[1]->typePtr
!= &variableObjType
) {
9525 /* Note that this can't fail since GetVariable already succeeded */
9526 Jim_SetVariable(interp
, argv
[1], intObjPtr
);
9529 Jim_SetResult(interp
, intObjPtr
);
9534 /* -----------------------------------------------------------------------------
9536 * ---------------------------------------------------------------------------*/
9537 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9538 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9540 /* Handle calls to the [unknown] command */
9541 static int JimUnknown(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, Jim_Obj
*fileNameObj
,
9544 Jim_Obj
**v
, *sv
[JIM_EVAL_SARGV_LEN
];
9547 /* If JimUnknown() is recursively called too many times...
9550 if (interp
->unknown_called
> 50) {
9554 /* If the [unknown] command does not exists returns
9556 if (Jim_GetCommand(interp
, interp
->unknown
, JIM_NONE
) == NULL
)
9559 /* The object interp->unknown just contains
9560 * the "unknown" string, it is used in order to
9561 * avoid to lookup the unknown command every time
9562 * but instread to cache the result. */
9563 if (argc
+ 1 <= JIM_EVAL_SARGV_LEN
)
9566 v
= Jim_Alloc(sizeof(Jim_Obj
*) * (argc
+ 1));
9567 /* Make a copy of the arguments vector, but shifted on
9568 * the right of one position. The command name of the
9569 * command will be instead the first argument of the
9570 * [unknown] call. */
9571 memcpy(v
+ 1, argv
, sizeof(Jim_Obj
*) * argc
);
9572 v
[0] = interp
->unknown
;
9574 interp
->unknown_called
++;
9575 retCode
= JimEvalObjVector(interp
, argc
+ 1, v
, fileNameObj
, linenr
);
9576 interp
->unknown_called
--;
9584 /* Eval the object vector 'objv' composed of 'objc' elements.
9585 * Every element is used as single argument.
9586 * Jim_EvalObj() will call this function every time its object
9587 * argument is of "list" type, with no string representation.
9589 * This is possible because the string representation of a
9590 * list object generated by the UpdateStringOfList is made
9591 * in a way that ensures that every list element is a different
9592 * command argument. */
9593 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
9594 Jim_Obj
*fileNameObj
, int linenr
)
9599 /* Incr refcount of arguments. */
9600 for (i
= 0; i
< objc
; i
++)
9601 Jim_IncrRefCount(objv
[i
]);
9602 /* Command lookup */
9603 cmdPtr
= Jim_GetCommand(interp
, objv
[0], JIM_ERRMSG
);
9604 if (cmdPtr
== NULL
) {
9605 retcode
= JimUnknown(interp
, objc
, objv
, fileNameObj
, linenr
);
9608 /* Call it -- Make sure result is an empty object. */
9609 JimIncrCmdRefCount(cmdPtr
);
9610 Jim_SetEmptyResult(interp
);
9611 if (cmdPtr
->isproc
) {
9612 retcode
= JimCallProcedure(interp
, cmdPtr
, fileNameObj
, linenr
, objc
, objv
);
9615 interp
->cmdPrivData
= cmdPtr
->u
.native
.privData
;
9616 retcode
= cmdPtr
->u
.native
.cmdProc(interp
, objc
, objv
);
9618 JimDecrCmdRefCount(interp
, cmdPtr
);
9620 /* Decr refcount of arguments and return the retcode */
9621 for (i
= 0; i
< objc
; i
++)
9622 Jim_DecrRefCount(interp
, objv
[i
]);
9627 int Jim_EvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
9629 return JimEvalObjVector(interp
, objc
, objv
, interp
->emptyObj
, 1);
9633 * Invokes 'prefix' as a command with the objv array as arguments.
9635 int Jim_EvalObjPrefix(Jim_Interp
*interp
, Jim_Obj
*prefix
, int objc
, Jim_Obj
*const *objv
)
9639 Jim_Obj
**nargv
= Jim_Alloc((objc
+ 1) * sizeof(*nargv
));
9642 for (i
= 0; i
< objc
; i
++) {
9643 nargv
[i
+ 1] = objv
[i
];
9645 ret
= Jim_EvalObjVector(interp
, objc
+ 1, nargv
);
9650 static void JimAddErrorToStack(Jim_Interp
*interp
, int retcode
, Jim_Obj
*fileNameObj
, int line
)
9654 if (rc
== JIM_ERR
&& !interp
->errorFlag
) {
9655 /* This is the first error, so save the file/line information and reset the stack */
9656 interp
->errorFlag
= 1;
9657 Jim_IncrRefCount(fileNameObj
);
9658 Jim_DecrRefCount(interp
, interp
->errorFileNameObj
);
9659 interp
->errorFileNameObj
= fileNameObj
;
9660 interp
->errorLine
= line
;
9662 JimResetStackTrace(interp
);
9663 /* Always add a level where the error first occurs */
9664 interp
->addStackTrace
++;
9667 /* Now if this is an "interesting" level, add it to the stack trace */
9668 if (rc
== JIM_ERR
&& interp
->addStackTrace
> 0) {
9669 /* Add the stack info for the current level */
9671 JimAppendStackTrace(interp
, Jim_String(interp
->errorProc
), fileNameObj
, line
);
9673 /* Note: if we didn't have a filename for this level,
9674 * don't clear the addStackTrace flag
9675 * so we can pick it up at the next level
9677 if (Jim_Length(fileNameObj
)) {
9678 interp
->addStackTrace
= 0;
9681 Jim_DecrRefCount(interp
, interp
->errorProc
);
9682 interp
->errorProc
= interp
->emptyObj
;
9683 Jim_IncrRefCount(interp
->errorProc
);
9685 else if (rc
== JIM_RETURN
&& interp
->returnCode
== JIM_ERR
) {
9686 /* Propagate the addStackTrace value through 'return -code error' */
9689 interp
->addStackTrace
= 0;
9693 /* And delete any local procs */
9694 static void JimDeleteLocalProcs(Jim_Interp
*interp
)
9696 if (interp
->localProcs
) {
9699 while ((procname
= Jim_StackPop(interp
->localProcs
)) != NULL
) {
9700 /* If there is a pushed command, find it */
9701 Jim_Cmd
*prevCmd
= NULL
;
9702 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->commands
, procname
);
9704 Jim_Cmd
*cmd
= (Jim_Cmd
*)he
->u
.val
;
9705 if (cmd
->isproc
&& cmd
->u
.proc
.prevCmd
) {
9706 prevCmd
= cmd
->u
.proc
.prevCmd
;
9707 cmd
->u
.proc
.prevCmd
= NULL
;
9711 /* Delete the local proc */
9712 Jim_DeleteCommand(interp
, procname
);
9715 /* And restore the pushed command */
9716 Jim_AddHashEntry(&interp
->commands
, procname
, prevCmd
);
9720 Jim_FreeStack(interp
->localProcs
);
9721 Jim_Free(interp
->localProcs
);
9722 interp
->localProcs
= NULL
;
9726 static int JimSubstOneToken(Jim_Interp
*interp
, const ScriptToken
*token
, Jim_Obj
**objPtrPtr
)
9730 switch (token
->type
) {
9733 objPtr
= token
->objPtr
;
9736 objPtr
= Jim_GetVariable(interp
, token
->objPtr
, JIM_ERRMSG
);
9738 case JIM_TT_DICTSUGAR
:
9739 objPtr
= JimExpandDictSugar(interp
, token
->objPtr
);
9741 case JIM_TT_EXPRSUGAR
:
9742 objPtr
= JimExpandExprSugar(interp
, token
->objPtr
);
9745 switch (Jim_EvalObj(interp
, token
->objPtr
)) {
9748 objPtr
= interp
->result
;
9751 /* Stop substituting */
9754 /* just skip this one */
9755 return JIM_CONTINUE
;
9762 "default token type (%d) reached " "in Jim_SubstObj().", token
->type
));
9767 *objPtrPtr
= objPtr
;
9773 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9774 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9775 * The returned object has refcount = 0.
9777 static Jim_Obj
*JimInterpolateTokens(Jim_Interp
*interp
, const ScriptToken
* token
, int tokens
, int flags
)
9781 Jim_Obj
*sintv
[JIM_EVAL_SINTV_LEN
];
9785 if (tokens
<= JIM_EVAL_SINTV_LEN
)
9788 intv
= Jim_Alloc(sizeof(Jim_Obj
*) * tokens
);
9790 /* Compute every token forming the argument
9791 * in the intv objects vector. */
9792 for (i
= 0; i
< tokens
; i
++) {
9793 switch (JimSubstOneToken(interp
, &token
[i
], &intv
[i
])) {
9798 if (flags
& JIM_SUBST_FLAG
) {
9803 /* XXX: Should probably set an error about break outside loop */
9804 /* fall through to error */
9806 if (flags
& JIM_SUBST_FLAG
) {
9810 /* XXX: Ditto continue outside loop */
9811 /* fall through to error */
9814 Jim_DecrRefCount(interp
, intv
[i
]);
9816 if (intv
!= sintv
) {
9821 Jim_IncrRefCount(intv
[i
]);
9822 Jim_String(intv
[i
]);
9823 totlen
+= intv
[i
]->length
;
9826 /* Fast path return for a single token */
9827 if (tokens
== 1 && intv
[0] && intv
== sintv
) {
9828 Jim_DecrRefCount(interp
, intv
[0]);
9832 /* Concatenate every token in an unique
9834 objPtr
= Jim_NewStringObjNoAlloc(interp
, NULL
, 0);
9836 if (tokens
== 4 && token
[0].type
== JIM_TT_ESC
&& token
[1].type
== JIM_TT_ESC
9837 && token
[2].type
== JIM_TT_VAR
) {
9838 /* May be able to do fast interpolated object -> dictSubst */
9839 objPtr
->typePtr
= &interpolatedObjType
;
9840 objPtr
->internalRep
.twoPtrValue
.ptr1
= (void *)token
;
9841 objPtr
->internalRep
.twoPtrValue
.ptr2
= intv
[2];
9842 Jim_IncrRefCount(intv
[2]);
9845 s
= objPtr
->bytes
= Jim_Alloc(totlen
+ 1);
9846 objPtr
->length
= totlen
;
9847 for (i
= 0; i
< tokens
; i
++) {
9849 memcpy(s
, intv
[i
]->bytes
, intv
[i
]->length
);
9850 s
+= intv
[i
]->length
;
9851 Jim_DecrRefCount(interp
, intv
[i
]);
9854 objPtr
->bytes
[totlen
] = '\0';
9855 /* Free the intv vector if not static. */
9856 if (intv
!= sintv
) {
9864 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9865 * Otherwise eval with Jim_EvalObj()
9867 static int JimEvalObjList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*fileNameObj
, int linenr
)
9869 if (!Jim_IsList(listPtr
)) {
9870 return Jim_EvalObj(interp
, listPtr
);
9873 int retcode
= JIM_OK
;
9875 if (listPtr
->internalRep
.listValue
.len
) {
9876 Jim_IncrRefCount(listPtr
);
9877 retcode
= JimEvalObjVector(interp
,
9878 listPtr
->internalRep
.listValue
.len
,
9879 listPtr
->internalRep
.listValue
.ele
, fileNameObj
, linenr
);
9880 Jim_DecrRefCount(interp
, listPtr
);
9886 int Jim_EvalObj(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
9891 int retcode
= JIM_OK
;
9892 Jim_Obj
*sargv
[JIM_EVAL_SARGV_LEN
], **argv
= NULL
;
9895 interp
->errorFlag
= 0;
9897 /* If the object is of type "list", with no string rep we can call
9898 * a specialized version of Jim_EvalObj() */
9899 if (Jim_IsList(scriptObjPtr
) && scriptObjPtr
->bytes
== NULL
) {
9900 return JimEvalObjList(interp
, scriptObjPtr
, interp
->emptyObj
, 1);
9903 Jim_IncrRefCount(scriptObjPtr
); /* Make sure it's shared. */
9904 script
= Jim_GetScript(interp
, scriptObjPtr
);
9906 /* Reset the interpreter result. This is useful to
9907 * return the empty result in the case of empty program. */
9908 Jim_SetEmptyResult(interp
);
9910 #ifdef JIM_OPTIMIZATION
9911 /* Check for one of the following common scripts used by for, while
9916 if (script
->len
== 0) {
9917 Jim_DecrRefCount(interp
, scriptObjPtr
);
9920 if (script
->len
== 3
9921 && script
->token
[1].objPtr
->typePtr
== &commandObjType
9922 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->isproc
== 0
9923 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->u
.native
.cmdProc
== Jim_IncrCoreCommand
9924 && script
->token
[2].objPtr
->typePtr
== &variableObjType
) {
9926 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, script
->token
[2].objPtr
, JIM_NONE
);
9928 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
9929 JimWideValue(objPtr
)++;
9930 Jim_InvalidateStringRep(objPtr
);
9931 Jim_DecrRefCount(interp
, scriptObjPtr
);
9932 Jim_SetResult(interp
, objPtr
);
9938 /* Now we have to make sure the internal repr will not be
9939 * freed on shimmering.
9941 * Think for example to this:
9943 * set x {llength $x; ... some more code ...}; eval $x
9945 * In order to preserve the internal rep, we increment the
9946 * inUse field of the script internal rep structure. */
9949 token
= script
->token
;
9952 /* Execute every command sequentially until the end of the script
9953 * or an error occurs.
9955 for (i
= 0; i
< script
->len
&& retcode
== JIM_OK
; ) {
9960 /* First token of the line is always JIM_TT_LINE */
9961 argc
= token
[i
].objPtr
->internalRep
.scriptLineValue
.argc
;
9962 linenr
= token
[i
].objPtr
->internalRep
.scriptLineValue
.line
;
9964 /* Allocate the arguments vector if required */
9965 if (argc
> JIM_EVAL_SARGV_LEN
)
9966 argv
= Jim_Alloc(sizeof(Jim_Obj
*) * argc
);
9968 /* Skip the JIM_TT_LINE token */
9971 /* Populate the arguments objects.
9972 * If an error occurs, retcode will be set and
9973 * 'j' will be set to the number of args expanded
9975 for (j
= 0; j
< argc
; j
++) {
9976 long wordtokens
= 1;
9978 Jim_Obj
*wordObjPtr
= NULL
;
9980 if (token
[i
].type
== JIM_TT_WORD
) {
9981 wordtokens
= JimWideValue(token
[i
++].objPtr
);
9982 if (wordtokens
< 0) {
9984 wordtokens
= -wordtokens
;
9988 if (wordtokens
== 1) {
9989 /* Fast path if the token does not
9990 * need interpolation */
9992 switch (token
[i
].type
) {
9995 wordObjPtr
= token
[i
].objPtr
;
9998 wordObjPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
10000 case JIM_TT_EXPRSUGAR
:
10001 wordObjPtr
= JimExpandExprSugar(interp
, token
[i
].objPtr
);
10003 case JIM_TT_DICTSUGAR
:
10004 wordObjPtr
= JimExpandDictSugar(interp
, token
[i
].objPtr
);
10007 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
10008 if (retcode
== JIM_OK
) {
10009 wordObjPtr
= Jim_GetResult(interp
);
10013 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10017 /* For interpolation we call a helper
10018 * function to do the work for us. */
10019 wordObjPtr
= JimInterpolateTokens(interp
, token
+ i
, wordtokens
, JIM_NONE
);
10023 if (retcode
== JIM_OK
) {
10029 Jim_IncrRefCount(wordObjPtr
);
10033 argv
[j
] = wordObjPtr
;
10036 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10037 int len
= Jim_ListLength(interp
, wordObjPtr
);
10038 int newargc
= argc
+ len
- 1;
10042 if (argv
== sargv
) {
10043 if (newargc
> JIM_EVAL_SARGV_LEN
) {
10044 argv
= Jim_Alloc(sizeof(*argv
) * newargc
);
10045 memcpy(argv
, sargv
, sizeof(*argv
) * j
);
10049 /* Need to realloc to make room for (len - 1) more entries */
10050 argv
= Jim_Realloc(argv
, sizeof(*argv
) * newargc
);
10054 /* Now copy in the expanded version */
10055 for (k
= 0; k
< len
; k
++) {
10056 argv
[j
++] = wordObjPtr
->internalRep
.listValue
.ele
[k
];
10057 Jim_IncrRefCount(wordObjPtr
->internalRep
.listValue
.ele
[k
]);
10060 /* The original object reference is no longer needed,
10061 * after the expansion it is no longer present on
10062 * the argument vector, but the single elements are
10064 Jim_DecrRefCount(interp
, wordObjPtr
);
10066 /* And update the indexes */
10072 if (retcode
== JIM_OK
&& argc
) {
10073 /* Lookup the command to call */
10074 cmd
= Jim_GetCommand(interp
, argv
[0], JIM_ERRMSG
);
10076 /* Call it -- Make sure result is an empty object. */
10077 JimIncrCmdRefCount(cmd
);
10078 Jim_SetEmptyResult(interp
);
10081 JimCallProcedure(interp
, cmd
, script
->fileNameObj
, linenr
, argc
, argv
);
10083 interp
->cmdPrivData
= cmd
->u
.native
.privData
;
10084 retcode
= cmd
->u
.native
.cmdProc(interp
, argc
, argv
);
10086 JimDecrCmdRefCount(interp
, cmd
);
10089 /* Call [unknown] */
10090 retcode
= JimUnknown(interp
, argc
, argv
, script
->fileNameObj
, linenr
);
10092 if (interp
->signal_level
&& interp
->sigmask
) {
10093 /* Check for a signal after each command */
10094 retcode
= JIM_SIGNAL
;
10098 /* Finished with the command, so decrement ref counts of each argument */
10100 Jim_DecrRefCount(interp
, argv
[j
]);
10103 if (argv
!= sargv
) {
10109 /* Possibly add to the error stack trace */
10110 JimAddErrorToStack(interp
, retcode
, script
->fileNameObj
, linenr
);
10112 /* Note that we don't have to decrement inUse, because the
10113 * following code transfers our use of the reference again to
10114 * the script object. */
10115 Jim_FreeIntRep(interp
, scriptObjPtr
);
10116 scriptObjPtr
->typePtr
= &scriptObjType
;
10117 Jim_SetIntRepPtr(scriptObjPtr
, script
);
10118 Jim_DecrRefCount(interp
, scriptObjPtr
);
10123 static int JimSetProcArg(Jim_Interp
*interp
, Jim_Obj
*argNameObj
, Jim_Obj
*argValObj
)
10126 /* If argObjPtr begins with '&', do an automatic upvar */
10127 const char *varname
= Jim_String(argNameObj
);
10128 if (*varname
== '&') {
10129 /* First check that the target variable exists */
10131 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
10133 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10134 objPtr
= Jim_GetVariable(interp
, argValObj
, JIM_ERRMSG
);
10135 interp
->framePtr
= savedCallFrame
;
10140 /* It exists, so perform the binding. */
10141 objPtr
= Jim_NewStringObj(interp
, varname
+ 1, -1);
10142 Jim_IncrRefCount(objPtr
);
10143 retcode
= Jim_SetVariableLink(interp
, objPtr
, argValObj
, interp
->framePtr
->parentCallFrame
);
10144 Jim_DecrRefCount(interp
, objPtr
);
10147 retcode
= Jim_SetVariable(interp
, argNameObj
, argValObj
);
10153 * Sets the interp result to be an error message indicating the required proc args.
10155 static void JimSetProcWrongArgs(Jim_Interp
*interp
, Jim_Obj
*procNameObj
, Jim_Cmd
*cmd
)
10157 /* Create a nice error message, consistent with Tcl 8.5 */
10158 Jim_Obj
*argmsg
= Jim_NewStringObj(interp
, "", 0);
10161 for (i
= 0; i
< cmd
->u
.proc
.argListLen
; i
++) {
10162 Jim_AppendString(interp
, argmsg
, " ", 1);
10164 if (i
== cmd
->u
.proc
.argsPos
) {
10165 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10167 Jim_AppendString(interp
, argmsg
, "?", 1);
10168 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].defaultObjPtr
);
10169 Jim_AppendString(interp
, argmsg
, " ...?", -1);
10172 /* We have plain args */
10173 Jim_AppendString(interp
, argmsg
, "?argument ...?", -1);
10177 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10178 Jim_AppendString(interp
, argmsg
, "?", 1);
10179 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10180 Jim_AppendString(interp
, argmsg
, "?", 1);
10183 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10187 Jim_SetResultFormatted(interp
, "wrong # args: should be \"%#s%#s\"", procNameObj
, argmsg
);
10188 Jim_FreeNewObj(interp
, argmsg
);
10191 /* Call a procedure implemented in Tcl.
10192 * It's possible to speed-up a lot this function, currently
10193 * the callframes are not cached, but allocated and
10194 * destroied every time. What is expecially costly is
10195 * to create/destroy the local vars hash table every time.
10197 * This can be fixed just implementing callframes caching
10198 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10199 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, Jim_Obj
*fileNameObj
, int linenr
, int argc
,
10200 Jim_Obj
*const *argv
)
10202 Jim_CallFrame
*callFramePtr
;
10203 Jim_Stack
*prevLocalProcs
;
10204 int i
, d
, retcode
, optargs
;
10207 if (argc
- 1 < cmd
->u
.proc
.reqArity
||
10208 (cmd
->u
.proc
.argsPos
< 0 && argc
- 1 > cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
)) {
10209 JimSetProcWrongArgs(interp
, argv
[0], cmd
);
10213 /* Check if there are too nested calls */
10214 if (interp
->framePtr
->level
== interp
->maxNestingDepth
) {
10215 Jim_SetResultString(interp
, "Too many nested calls. Infinite recursion?", -1);
10219 /* Create a new callframe */
10220 callFramePtr
= JimCreateCallFrame(interp
, interp
->framePtr
);
10221 callFramePtr
->argv
= argv
;
10222 callFramePtr
->argc
= argc
;
10223 callFramePtr
->procArgsObjPtr
= cmd
->u
.proc
.argListObjPtr
;
10224 callFramePtr
->procBodyObjPtr
= cmd
->u
.proc
.bodyObjPtr
;
10225 callFramePtr
->staticVars
= cmd
->u
.proc
.staticVars
;
10226 callFramePtr
->fileNameObj
= fileNameObj
;
10227 callFramePtr
->line
= linenr
;
10228 Jim_IncrRefCount(cmd
->u
.proc
.argListObjPtr
);
10229 Jim_IncrRefCount(cmd
->u
.proc
.bodyObjPtr
);
10230 interp
->framePtr
= callFramePtr
;
10232 /* How many optional args are available */
10233 optargs
= (argc
- 1 - cmd
->u
.proc
.reqArity
);
10235 /* Step 'i' along the actual args, and step 'd' along the formal args */
10237 for (d
= 0; d
< cmd
->u
.proc
.argListLen
; d
++) {
10238 Jim_Obj
*nameObjPtr
= cmd
->u
.proc
.arglist
[d
].nameObjPtr
;
10239 if (d
== cmd
->u
.proc
.argsPos
) {
10241 Jim_Obj
*listObjPtr
;
10243 if (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
< argc
- 1) {
10244 argsLen
= argc
- 1 - (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
);
10246 listObjPtr
= Jim_NewListObj(interp
, &argv
[i
], argsLen
);
10248 /* It is possible to rename args. */
10249 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
) {
10250 nameObjPtr
=cmd
->u
.proc
.arglist
[d
].defaultObjPtr
;
10252 retcode
= Jim_SetVariable(interp
, nameObjPtr
, listObjPtr
);
10253 if (retcode
!= JIM_OK
) {
10261 /* Optional or required? */
10262 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
== NULL
|| optargs
-- > 0) {
10263 retcode
= JimSetProcArg(interp
, nameObjPtr
, argv
[i
++]);
10266 /* Ran out, so use the default */
10267 retcode
= Jim_SetVariable(interp
, nameObjPtr
, cmd
->u
.proc
.arglist
[d
].defaultObjPtr
);
10269 if (retcode
!= JIM_OK
) {
10274 /* Install a new stack for local procs */
10275 prevLocalProcs
= interp
->localProcs
;
10276 interp
->localProcs
= NULL
;
10278 /* Eval the body */
10279 retcode
= Jim_EvalObj(interp
, cmd
->u
.proc
.bodyObjPtr
);
10281 /* Delete any local procs */
10282 JimDeleteLocalProcs(interp
);
10283 interp
->localProcs
= prevLocalProcs
;
10286 /* Destroy the callframe */
10287 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10288 if (callFramePtr
->vars
.size
!= JIM_HT_INITIAL_SIZE
) {
10289 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NONE
);
10292 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NOHT
);
10294 /* Handle the JIM_EVAL return code */
10295 while (retcode
== JIM_EVAL
) {
10296 Jim_Obj
*resultScriptObjPtr
= Jim_GetResult(interp
);
10298 Jim_IncrRefCount(resultScriptObjPtr
);
10299 /* Should be a list! */
10300 retcode
= JimEvalObjList(interp
, resultScriptObjPtr
, fileNameObj
, linenr
);
10301 Jim_DecrRefCount(interp
, resultScriptObjPtr
);
10303 /* Handle the JIM_RETURN return code */
10304 if (retcode
== JIM_RETURN
) {
10305 if (--interp
->returnLevel
<= 0) {
10306 retcode
= interp
->returnCode
;
10307 interp
->returnCode
= JIM_OK
;
10308 interp
->returnLevel
= 0;
10311 else if (retcode
== JIM_ERR
) {
10312 interp
->addStackTrace
++;
10313 Jim_DecrRefCount(interp
, interp
->errorProc
);
10314 interp
->errorProc
= argv
[0];
10315 Jim_IncrRefCount(interp
->errorProc
);
10320 int Jim_EvalSource(Jim_Interp
*interp
, const char *filename
, int lineno
, const char *script
)
10323 Jim_Obj
*scriptObjPtr
;
10325 scriptObjPtr
= Jim_NewStringObj(interp
, script
, -1);
10326 Jim_IncrRefCount(scriptObjPtr
);
10329 Jim_Obj
*prevScriptObj
;
10331 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), lineno
);
10333 prevScriptObj
= interp
->currentScriptObj
;
10334 interp
->currentScriptObj
= scriptObjPtr
;
10336 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10338 interp
->currentScriptObj
= prevScriptObj
;
10341 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10343 Jim_DecrRefCount(interp
, scriptObjPtr
);
10347 int Jim_Eval(Jim_Interp
*interp
, const char *script
)
10349 return Jim_EvalObj(interp
, Jim_NewStringObj(interp
, script
, -1));
10352 /* Execute script in the scope of the global level */
10353 int Jim_EvalGlobal(Jim_Interp
*interp
, const char *script
)
10356 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10358 interp
->framePtr
= interp
->topFramePtr
;
10359 retval
= Jim_Eval(interp
, script
);
10360 interp
->framePtr
= savedFramePtr
;
10365 int Jim_EvalFileGlobal(Jim_Interp
*interp
, const char *filename
)
10368 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10370 interp
->framePtr
= interp
->topFramePtr
;
10371 retval
= Jim_EvalFile(interp
, filename
);
10372 interp
->framePtr
= savedFramePtr
;
10377 #include <sys/stat.h>
10379 int Jim_EvalFile(Jim_Interp
*interp
, const char *filename
)
10383 Jim_Obj
*scriptObjPtr
;
10384 Jim_Obj
*prevScriptObj
;
10388 struct JimParseResult result
;
10390 if (stat(filename
, &sb
) != 0 || (fp
= fopen(filename
, "rt")) == NULL
) {
10391 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", filename
, strerror(errno
));
10394 if (sb
.st_size
== 0) {
10399 buf
= Jim_Alloc(sb
.st_size
+ 1);
10400 readlen
= fread(buf
, 1, sb
.st_size
, fp
);
10404 Jim_SetResultFormatted(interp
, "failed to load file \"%s\": %s", filename
, strerror(errno
));
10410 scriptObjPtr
= Jim_NewStringObjNoAlloc(interp
, buf
, readlen
);
10411 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), 1);
10412 Jim_IncrRefCount(scriptObjPtr
);
10414 /* Now check the script for unmatched braces, etc. */
10415 if (SetScriptFromAny(interp
, scriptObjPtr
, &result
) == JIM_ERR
) {
10419 switch (result
.missing
) {
10421 msg
= "unmatched \"[\"";
10424 msg
= "missing close-brace";
10428 msg
= "missing quote";
10432 snprintf(linebuf
, sizeof(linebuf
), "%d", result
.line
);
10434 Jim_SetResultFormatted(interp
, "%s in \"%s\" at line %s",
10435 msg
, filename
, linebuf
);
10436 Jim_DecrRefCount(interp
, scriptObjPtr
);
10440 prevScriptObj
= interp
->currentScriptObj
;
10441 interp
->currentScriptObj
= scriptObjPtr
;
10443 retcode
= Jim_EvalObj(interp
, scriptObjPtr
);
10445 /* Handle the JIM_RETURN return code */
10446 if (retcode
== JIM_RETURN
) {
10447 if (--interp
->returnLevel
<= 0) {
10448 retcode
= interp
->returnCode
;
10449 interp
->returnCode
= JIM_OK
;
10450 interp
->returnLevel
= 0;
10453 if (retcode
== JIM_ERR
) {
10454 /* EvalFile changes context, so add a stack frame here */
10455 interp
->addStackTrace
++;
10458 interp
->currentScriptObj
= prevScriptObj
;
10460 Jim_DecrRefCount(interp
, scriptObjPtr
);
10465 /* -----------------------------------------------------------------------------
10467 * ---------------------------------------------------------------------------*/
10468 static int JimParseSubstStr(struct JimParserCtx
*pc
)
10470 pc
->tstart
= pc
->p
;
10471 pc
->tline
= pc
->linenr
;
10472 while (pc
->len
&& *pc
->p
!= '$' && *pc
->p
!= '[') {
10473 if (*pc
->p
== '\\' && pc
->len
> 1) {
10480 pc
->tend
= pc
->p
- 1;
10481 pc
->tt
= JIM_TT_ESC
;
10485 static int JimParseSubst(struct JimParserCtx
*pc
, int flags
)
10489 if (pc
->len
== 0) {
10490 pc
->tstart
= pc
->tend
= pc
->p
;
10491 pc
->tline
= pc
->linenr
;
10492 pc
->tt
= JIM_TT_EOL
;
10498 retval
= JimParseCmd(pc
);
10499 if (flags
& JIM_SUBST_NOCMD
) {
10502 pc
->tt
= (flags
& JIM_SUBST_NOESC
) ? JIM_TT_STR
: JIM_TT_ESC
;
10507 if (JimParseVar(pc
) == JIM_ERR
) {
10508 pc
->tstart
= pc
->tend
= pc
->p
++;
10510 pc
->tline
= pc
->linenr
;
10511 pc
->tt
= JIM_TT_STR
;
10514 if (flags
& JIM_SUBST_NOVAR
) {
10516 if (flags
& JIM_SUBST_NOESC
)
10517 pc
->tt
= JIM_TT_STR
;
10519 pc
->tt
= JIM_TT_ESC
;
10520 if (*pc
->tstart
== '{') {
10522 if (*(pc
->tend
+ 1))
10529 retval
= JimParseSubstStr(pc
);
10530 if (flags
& JIM_SUBST_NOESC
)
10531 pc
->tt
= JIM_TT_STR
;
10538 /* The subst object type reuses most of the data structures and functions
10539 * of the script object. Script's data structures are a bit more complex
10540 * for what is needed for [subst]itution tasks, but the reuse helps to
10541 * deal with a single data structure at the cost of some more memory
10542 * usage for substitutions. */
10544 /* This method takes the string representation of an object
10545 * as a Tcl string where to perform [subst]itution, and generates
10546 * the pre-parsed internal representation. */
10547 static int SetSubstFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, int flags
)
10550 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
10551 struct JimParserCtx parser
;
10552 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
10553 ParseTokenList tokenlist
;
10555 /* Initially parse the subst into tokens (in tokenlist) */
10556 ScriptTokenListInit(&tokenlist
);
10558 JimParserInit(&parser
, scriptText
, scriptTextLen
, 1);
10560 JimParseSubst(&parser
, flags
);
10562 /* Note that subst doesn't need the EOL token */
10565 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
10569 /* Create the "real" subst/script tokens from the initial token list */
10571 script
->substFlags
= flags
;
10572 script
->fileNameObj
= interp
->emptyObj
;
10573 Jim_IncrRefCount(script
->fileNameObj
);
10574 SubstObjAddTokens(interp
, script
, &tokenlist
);
10576 /* No longer need the token list */
10577 ScriptTokenListFree(&tokenlist
);
10579 #ifdef DEBUG_SHOW_SUBST
10583 printf("==== Subst ====\n");
10584 for (i
= 0; i
< script
->len
; i
++) {
10585 printf("[%2d] %s '%s'\n", i
, jim_tt_name(script
->token
[i
].type
),
10586 Jim_String(script
->token
[i
].objPtr
));
10591 /* Free the old internal rep and set the new one. */
10592 Jim_FreeIntRep(interp
, objPtr
);
10593 Jim_SetIntRepPtr(objPtr
, script
);
10594 objPtr
->typePtr
= &scriptObjType
;
10598 static ScriptObj
*Jim_GetSubst(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
10600 if (objPtr
->typePtr
!= &scriptObjType
|| ((ScriptObj
*)Jim_GetIntRepPtr(objPtr
))->substFlags
!= flags
)
10601 SetSubstFromAny(interp
, objPtr
, flags
);
10602 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
10605 /* Performs commands,variables,blackslashes substitution,
10606 * storing the result object (with refcount 0) into
10608 int Jim_SubstObj(Jim_Interp
*interp
, Jim_Obj
*substObjPtr
, Jim_Obj
**resObjPtrPtr
, int flags
)
10610 ScriptObj
*script
= Jim_GetSubst(interp
, substObjPtr
, flags
);
10612 Jim_IncrRefCount(substObjPtr
); /* Make sure it's shared. */
10613 /* In order to preserve the internal rep, we increment the
10614 * inUse field of the script internal rep structure. */
10617 *resObjPtrPtr
= JimInterpolateTokens(interp
, script
->token
, script
->len
, flags
);
10620 Jim_DecrRefCount(interp
, substObjPtr
);
10621 if (*resObjPtrPtr
== NULL
) {
10627 /* -----------------------------------------------------------------------------
10628 * Core commands utility functions
10629 * ---------------------------------------------------------------------------*/
10630 void Jim_WrongNumArgs(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, const char *msg
)
10633 Jim_Obj
*objPtr
= Jim_NewEmptyStringObj(interp
);
10635 Jim_AppendString(interp
, objPtr
, "wrong # args: should be \"", -1);
10636 for (i
= 0; i
< argc
; i
++) {
10637 Jim_AppendObj(interp
, objPtr
, argv
[i
]);
10638 if (!(i
+ 1 == argc
&& msg
[0] == '\0'))
10639 Jim_AppendString(interp
, objPtr
, " ", 1);
10641 Jim_AppendString(interp
, objPtr
, msg
, -1);
10642 Jim_AppendString(interp
, objPtr
, "\"", 1);
10643 Jim_SetResult(interp
, objPtr
);
10646 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10648 /* type is: 0=commands, 1=procs, 2=channels */
10649 static Jim_Obj
*JimCommandsList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int type
)
10651 Jim_HashTableIterator
*htiter
;
10653 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10655 /* Check for the non-pattern case. We can do this much more efficiently. */
10656 if (patternObjPtr
&& JimTrivialMatch(Jim_String(patternObjPtr
))) {
10657 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, patternObjPtr
, JIM_NONE
);
10659 if (type
== 1 && !cmdPtr
->isproc
) {
10662 else if (type
== 2 && !Jim_AioFilehandle(interp
, patternObjPtr
)) {
10663 /* not a channel */
10666 Jim_ListAppendElement(interp
, listObjPtr
, patternObjPtr
);
10672 htiter
= Jim_GetHashTableIterator(&interp
->commands
);
10673 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10674 Jim_Cmd
*cmdPtr
= he
->u
.val
;
10675 Jim_Obj
*cmdNameObj
;
10677 if (type
== 1 && !cmdPtr
->isproc
) {
10681 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10684 cmdNameObj
= Jim_NewStringObj(interp
, he
->key
, -1);
10686 /* Is it a channel? */
10687 if (type
== 2 && !Jim_AioFilehandle(interp
, cmdNameObj
)) {
10688 Jim_FreeNewObj(interp
, cmdNameObj
);
10692 Jim_ListAppendElement(interp
, listObjPtr
, cmdNameObj
);
10694 Jim_FreeHashTableIterator(htiter
);
10698 /* Keep this in order */
10699 #define JIM_VARLIST_GLOBALS 0
10700 #define JIM_VARLIST_LOCALS 1
10701 #define JIM_VARLIST_VARS 2
10703 static Jim_Obj
*JimVariablesList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int mode
)
10705 Jim_HashTableIterator
*htiter
;
10707 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10709 if (mode
== JIM_VARLIST_GLOBALS
) {
10710 htiter
= Jim_GetHashTableIterator(&interp
->topFramePtr
->vars
);
10713 /* For [info locals], if we are at top level an emtpy list
10714 * is returned. I don't agree, but we aim at compatibility (SS) */
10715 if (mode
== JIM_VARLIST_LOCALS
&& interp
->framePtr
== interp
->topFramePtr
)
10717 htiter
= Jim_GetHashTableIterator(&interp
->framePtr
->vars
);
10719 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10720 Jim_Var
*varPtr
= (Jim_Var
*)he
->u
.val
;
10722 if (mode
== JIM_VARLIST_LOCALS
) {
10723 if (varPtr
->linkFramePtr
!= NULL
)
10726 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10728 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, he
->key
, -1));
10730 Jim_FreeHashTableIterator(htiter
);
10734 static int JimInfoLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
10735 Jim_Obj
**objPtrPtr
, int info_level_cmd
)
10737 Jim_CallFrame
*targetCallFrame
;
10739 targetCallFrame
= JimGetCallFrameByInteger(interp
, levelObjPtr
);
10740 if (targetCallFrame
== NULL
) {
10743 /* No proc call at toplevel callframe */
10744 if (targetCallFrame
== interp
->topFramePtr
) {
10745 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
10748 if (info_level_cmd
) {
10749 *objPtrPtr
= Jim_NewListObj(interp
, targetCallFrame
->argv
, targetCallFrame
->argc
);
10752 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
10754 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->argv
[0]);
10755 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->fileNameObj
);
10756 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, targetCallFrame
->line
));
10757 *objPtrPtr
= listObj
;
10762 /* -----------------------------------------------------------------------------
10764 * ---------------------------------------------------------------------------*/
10766 /* fake [puts] -- not the real puts, just for debugging. */
10767 static int Jim_PutsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10769 if (argc
!= 2 && argc
!= 3) {
10770 Jim_WrongNumArgs(interp
, 1, argv
, "?-nonewline? string");
10774 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-nonewline")) {
10775 Jim_SetResultString(interp
, "The second argument must " "be -nonewline", -1);
10779 fputs(Jim_String(argv
[2]), stdout
);
10783 puts(Jim_String(argv
[1]));
10788 /* Helper for [+] and [*] */
10789 static int JimAddMulHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10791 jim_wide wideValue
, res
;
10792 double doubleValue
, doubleRes
;
10795 res
= (op
== JIM_EXPROP_ADD
) ? 0 : 1;
10797 for (i
= 1; i
< argc
; i
++) {
10798 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
)
10800 if (op
== JIM_EXPROP_ADD
)
10805 Jim_SetResultInt(interp
, res
);
10808 doubleRes
= (double)res
;
10809 for (; i
< argc
; i
++) {
10810 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10812 if (op
== JIM_EXPROP_ADD
)
10813 doubleRes
+= doubleValue
;
10815 doubleRes
*= doubleValue
;
10817 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10821 /* Helper for [-] and [/] */
10822 static int JimSubDivHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10824 jim_wide wideValue
, res
= 0;
10825 double doubleValue
, doubleRes
= 0;
10829 Jim_WrongNumArgs(interp
, 1, argv
, "number ?number ... number?");
10832 else if (argc
== 2) {
10833 /* The arity = 2 case is different. For [- x] returns -x,
10834 * while [/ x] returns 1/x. */
10835 if (Jim_GetWide(interp
, argv
[1], &wideValue
) != JIM_OK
) {
10836 if (Jim_GetDouble(interp
, argv
[1], &doubleValue
) != JIM_OK
) {
10840 if (op
== JIM_EXPROP_SUB
)
10841 doubleRes
= -doubleValue
;
10843 doubleRes
= 1.0 / doubleValue
;
10844 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10848 if (op
== JIM_EXPROP_SUB
) {
10850 Jim_SetResultInt(interp
, res
);
10853 doubleRes
= 1.0 / wideValue
;
10854 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10859 if (Jim_GetWide(interp
, argv
[1], &res
) != JIM_OK
) {
10860 if (Jim_GetDouble(interp
, argv
[1], &doubleRes
)
10869 for (i
= 2; i
< argc
; i
++) {
10870 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
) {
10871 doubleRes
= (double)res
;
10874 if (op
== JIM_EXPROP_SUB
)
10879 Jim_SetResultInt(interp
, res
);
10882 for (; i
< argc
; i
++) {
10883 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10885 if (op
== JIM_EXPROP_SUB
)
10886 doubleRes
-= doubleValue
;
10888 doubleRes
/= doubleValue
;
10890 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10896 static int Jim_AddCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10898 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_ADD
);
10902 static int Jim_MulCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10904 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_MUL
);
10908 static int Jim_SubCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10910 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_SUB
);
10914 static int Jim_DivCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10916 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_DIV
);
10920 static int Jim_SetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10922 if (argc
!= 2 && argc
!= 3) {
10923 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?newValue?");
10929 objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
10932 Jim_SetResult(interp
, objPtr
);
10935 /* argc == 3 case. */
10936 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
10938 Jim_SetResult(interp
, argv
[2]);
10944 * unset ?-nocomplain? ?--? ?varName ...?
10946 static int Jim_UnsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10952 if (Jim_CompareStringImmediate(interp
, argv
[i
], "--")) {
10956 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-nocomplain")) {
10965 if (Jim_UnsetVariable(interp
, argv
[i
], complain
? JIM_ERRMSG
: JIM_NONE
) != JIM_OK
10975 static int Jim_WhileCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10978 Jim_WrongNumArgs(interp
, 1, argv
, "condition body");
10982 /* The general purpose implementation of while starts here */
10984 int boolean
, retval
;
10986 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[1], &boolean
)) != JIM_OK
)
10991 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
11005 Jim_SetEmptyResult(interp
);
11010 static int Jim_ForCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11014 Jim_Obj
*varNamePtr
= NULL
;
11015 Jim_Obj
*stopVarNamePtr
= NULL
;
11018 Jim_WrongNumArgs(interp
, 1, argv
, "start test next body");
11022 /* Do the initialisation */
11023 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
) {
11027 /* And do the first test now. Better for optimisation
11028 * if we can do next/test at the bottom of the loop
11030 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11032 /* Ready to do the body as follows:
11034 * body // check retcode
11035 * next // check retcode
11036 * test // check retcode/test bool
11040 #ifdef JIM_OPTIMIZATION
11041 /* Check if the for is on the form:
11042 * for ... {$i < CONST} {incr i}
11043 * for ... {$i < $j} {incr i}
11045 if (retval
== JIM_OK
&& boolean
) {
11046 ScriptObj
*incrScript
;
11047 ExprByteCode
*expr
;
11048 jim_wide stop
, currentVal
;
11049 unsigned jim_wide procEpoch
;
11053 /* Do it only if there aren't shared arguments */
11054 expr
= JimGetExpression(interp
, argv
[2]);
11055 incrScript
= Jim_GetScript(interp
, argv
[3]);
11057 /* Ensure proper lengths to start */
11058 if (incrScript
->len
!= 3 || !expr
|| expr
->len
!= 3) {
11061 /* Ensure proper token types. */
11062 if (incrScript
->token
[1].type
!= JIM_TT_ESC
||
11063 expr
->token
[0].type
!= JIM_TT_VAR
||
11064 (expr
->token
[1].type
!= JIM_TT_EXPR_INT
&& expr
->token
[1].type
!= JIM_TT_VAR
)) {
11068 if (expr
->token
[2].type
== JIM_EXPROP_LT
) {
11071 else if (expr
->token
[2].type
== JIM_EXPROP_LTE
) {
11078 /* Update command must be incr */
11079 if (!Jim_CompareStringImmediate(interp
, incrScript
->token
[1].objPtr
, "incr")) {
11083 /* incr, expression must be about the same variable */
11084 if (!Jim_StringEqObj(incrScript
->token
[2].objPtr
, expr
->token
[0].objPtr
)) {
11088 /* Get the stop condition (must be a variable or integer) */
11089 if (expr
->token
[1].type
== JIM_TT_EXPR_INT
) {
11090 if (Jim_GetWide(interp
, expr
->token
[1].objPtr
, &stop
) == JIM_ERR
) {
11095 stopVarNamePtr
= expr
->token
[1].objPtr
;
11096 Jim_IncrRefCount(stopVarNamePtr
);
11097 /* Keep the compiler happy */
11101 /* Initialization */
11102 procEpoch
= interp
->procEpoch
;
11103 varNamePtr
= expr
->token
[0].objPtr
;
11104 Jim_IncrRefCount(varNamePtr
);
11106 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_NONE
);
11107 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
) {
11111 /* --- OPTIMIZED FOR --- */
11112 while (retval
== JIM_OK
) {
11113 /* === Check condition === */
11114 /* Note that currentVal is already set here */
11116 /* Immediate or Variable? get the 'stop' value if the latter. */
11117 if (stopVarNamePtr
) {
11118 objPtr
= Jim_GetVariable(interp
, stopVarNamePtr
, JIM_NONE
);
11119 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, &stop
) != JIM_OK
) {
11124 if (currentVal
>= stop
+ cmpOffset
) {
11129 retval
= Jim_EvalObj(interp
, argv
[4]);
11130 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11132 /* If there was a change in procedures/command continue
11133 * with the usual [for] command implementation */
11134 if (procEpoch
!= interp
->procEpoch
) {
11138 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
11141 if (objPtr
== NULL
) {
11145 if (!Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11146 currentVal
= ++JimWideValue(objPtr
);
11147 Jim_InvalidateStringRep(objPtr
);
11150 if (Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
||
11151 Jim_SetVariable(interp
, varNamePtr
, Jim_NewIntObj(interp
,
11152 ++currentVal
)) != JIM_OK
) {
11163 while (boolean
&& (retval
== JIM_OK
|| retval
== JIM_CONTINUE
)) {
11165 retval
= Jim_EvalObj(interp
, argv
[4]);
11167 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11170 retval
= Jim_EvalObj(interp
, argv
[3]);
11171 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11174 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11179 if (stopVarNamePtr
) {
11180 Jim_DecrRefCount(interp
, stopVarNamePtr
);
11183 Jim_DecrRefCount(interp
, varNamePtr
);
11186 if (retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
|| retval
== JIM_OK
) {
11187 Jim_SetEmptyResult(interp
);
11195 static int Jim_LoopCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11201 Jim_Obj
*bodyObjPtr
;
11203 if (argc
!= 5 && argc
!= 6) {
11204 Jim_WrongNumArgs(interp
, 1, argv
, "var first limit ?incr? body");
11208 if (Jim_GetWide(interp
, argv
[2], &i
) != JIM_OK
||
11209 Jim_GetWide(interp
, argv
[3], &limit
) != JIM_OK
||
11210 (argc
== 6 && Jim_GetWide(interp
, argv
[4], &incr
) != JIM_OK
)) {
11213 bodyObjPtr
= (argc
== 5) ? argv
[4] : argv
[5];
11215 retval
= Jim_SetVariable(interp
, argv
[1], argv
[2]);
11217 while (((i
< limit
&& incr
> 0) || (i
> limit
&& incr
< 0)) && retval
== JIM_OK
) {
11218 retval
= Jim_EvalObj(interp
, bodyObjPtr
);
11219 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11220 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11227 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11228 if (argv
[1]->typePtr
!= &variableObjType
) {
11229 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11233 JimWideValue(objPtr
) = i
;
11234 Jim_InvalidateStringRep(objPtr
);
11236 /* The following step is required in order to invalidate the
11237 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11238 if (argv
[1]->typePtr
!= &variableObjType
) {
11239 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11246 objPtr
= Jim_NewIntObj(interp
, i
);
11247 retval
= Jim_SetVariable(interp
, argv
[1], objPtr
);
11248 if (retval
!= JIM_OK
) {
11249 Jim_FreeNewObj(interp
, objPtr
);
11255 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
) {
11256 Jim_SetEmptyResult(interp
);
11262 /* foreach + lmap implementation. */
11263 static int JimForeachMapHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int doMap
)
11265 int result
= JIM_ERR
, i
, nbrOfLists
, *listsIdx
, *listsEnd
;
11266 int nbrOfLoops
= 0;
11267 Jim_Obj
*emptyStr
, *script
, *mapRes
= NULL
;
11269 if (argc
< 4 || argc
% 2 != 0) {
11270 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varList list ...? script");
11274 mapRes
= Jim_NewListObj(interp
, NULL
, 0);
11275 Jim_IncrRefCount(mapRes
);
11277 emptyStr
= Jim_NewEmptyStringObj(interp
);
11278 Jim_IncrRefCount(emptyStr
);
11279 script
= argv
[argc
- 1]; /* Last argument is a script */
11280 nbrOfLists
= (argc
- 1 - 1) / 2; /* argc - 'foreach' - script */
11281 listsIdx
= (int *)Jim_Alloc(nbrOfLists
* sizeof(int));
11282 listsEnd
= (int *)Jim_Alloc(nbrOfLists
* 2 * sizeof(int));
11283 /* Initialize iterators and remember max nbr elements each list */
11284 memset(listsIdx
, 0, nbrOfLists
* sizeof(int));
11285 /* Remember lengths of all lists and calculate how much rounds to loop */
11286 for (i
= 0; i
< nbrOfLists
* 2; i
+= 2) {
11290 listsEnd
[i
] = Jim_ListLength(interp
, argv
[i
+ 1]);
11291 listsEnd
[i
+ 1] = Jim_ListLength(interp
, argv
[i
+ 2]);
11292 if (listsEnd
[i
] == 0) {
11293 Jim_SetResultString(interp
, "foreach varlist is empty", -1);
11296 cnt
= div(listsEnd
[i
+ 1], listsEnd
[i
]);
11297 count
= cnt
.quot
+ (cnt
.rem
? 1 : 0);
11298 if (count
> nbrOfLoops
)
11299 nbrOfLoops
= count
;
11301 for (; nbrOfLoops
-- > 0;) {
11302 for (i
= 0; i
< nbrOfLists
; ++i
) {
11303 int varIdx
= 0, var
= i
* 2;
11305 while (varIdx
< listsEnd
[var
]) {
11306 Jim_Obj
*varName
, *ele
;
11307 int lst
= i
* 2 + 1;
11309 /* List index operations below can't fail */
11310 Jim_ListIndex(interp
, argv
[var
+ 1], varIdx
, &varName
, JIM_NONE
);
11311 if (listsIdx
[i
] < listsEnd
[lst
]) {
11312 Jim_ListIndex(interp
, argv
[lst
+ 1], listsIdx
[i
], &ele
, JIM_NONE
);
11313 /* Avoid shimmering */
11314 Jim_IncrRefCount(ele
);
11315 result
= Jim_SetVariable(interp
, varName
, ele
);
11316 Jim_DecrRefCount(interp
, ele
);
11317 if (result
== JIM_OK
) {
11318 ++listsIdx
[i
]; /* Remember next iterator of current list */
11319 ++varIdx
; /* Next variable */
11323 else if (Jim_SetVariable(interp
, varName
, emptyStr
) == JIM_OK
) {
11324 ++varIdx
; /* Next variable */
11330 switch (result
= Jim_EvalObj(interp
, script
)) {
11333 Jim_ListAppendElement(interp
, mapRes
, interp
->result
);
11347 Jim_SetResult(interp
, mapRes
);
11349 Jim_SetEmptyResult(interp
);
11352 Jim_DecrRefCount(interp
, mapRes
);
11353 Jim_DecrRefCount(interp
, emptyStr
);
11354 Jim_Free(listsIdx
);
11355 Jim_Free(listsEnd
);
11360 static int Jim_ForeachCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11362 return JimForeachMapHelper(interp
, argc
, argv
, 0);
11366 static int Jim_LmapCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11368 return JimForeachMapHelper(interp
, argc
, argv
, 1);
11372 static int Jim_IfCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11374 int boolean
, retval
, current
= 1, falsebody
= 0;
11378 /* Far not enough arguments given! */
11379 if (current
>= argc
)
11381 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[current
++], &boolean
))
11384 /* There lacks something, isn't it? */
11385 if (current
>= argc
)
11387 if (Jim_CompareStringImmediate(interp
, argv
[current
], "then"))
11389 /* Tsk tsk, no then-clause? */
11390 if (current
>= argc
)
11393 return Jim_EvalObj(interp
, argv
[current
]);
11394 /* Ok: no else-clause follows */
11395 if (++current
>= argc
) {
11396 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11399 falsebody
= current
++;
11400 if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "else")) {
11401 /* IIICKS - else-clause isn't last cmd? */
11402 if (current
!= argc
- 1)
11404 return Jim_EvalObj(interp
, argv
[current
]);
11406 else if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "elseif"))
11407 /* Ok: elseif follows meaning all the stuff
11408 * again (how boring...) */
11410 /* OOPS - else-clause is not last cmd? */
11411 else if (falsebody
!= argc
- 1)
11413 return Jim_EvalObj(interp
, argv
[falsebody
]);
11418 Jim_WrongNumArgs(interp
, 1, argv
, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11423 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11424 int Jim_CommandMatchObj(Jim_Interp
*interp
, Jim_Obj
*commandObj
, Jim_Obj
*patternObj
,
11425 Jim_Obj
*stringObj
, int nocase
)
11432 parms
[argc
++] = commandObj
;
11434 parms
[argc
++] = Jim_NewStringObj(interp
, "-nocase", -1);
11436 parms
[argc
++] = patternObj
;
11437 parms
[argc
++] = stringObj
;
11439 rc
= Jim_EvalObjVector(interp
, argc
, parms
);
11441 if (rc
!= JIM_OK
|| Jim_GetLong(interp
, Jim_GetResult(interp
), &eq
) != JIM_OK
) {
11449 { SWITCH_EXACT
, SWITCH_GLOB
, SWITCH_RE
, SWITCH_CMD
};
11452 static int Jim_SwitchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11454 int matchOpt
= SWITCH_EXACT
, opt
= 1, patCount
, i
;
11455 Jim_Obj
*command
= 0, *const *caseList
= 0, *strObj
;
11456 Jim_Obj
*script
= 0;
11460 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string "
11461 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11464 for (opt
= 1; opt
< argc
; ++opt
) {
11465 const char *option
= Jim_String(argv
[opt
]);
11467 if (*option
!= '-')
11469 else if (strncmp(option
, "--", 2) == 0) {
11473 else if (strncmp(option
, "-exact", 2) == 0)
11474 matchOpt
= SWITCH_EXACT
;
11475 else if (strncmp(option
, "-glob", 2) == 0)
11476 matchOpt
= SWITCH_GLOB
;
11477 else if (strncmp(option
, "-regexp", 2) == 0)
11478 matchOpt
= SWITCH_RE
;
11479 else if (strncmp(option
, "-command", 2) == 0) {
11480 matchOpt
= SWITCH_CMD
;
11481 if ((argc
- opt
) < 2)
11483 command
= argv
[++opt
];
11486 Jim_SetResultFormatted(interp
,
11487 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11491 if ((argc
- opt
) < 2)
11494 strObj
= argv
[opt
++];
11495 patCount
= argc
- opt
;
11496 if (patCount
== 1) {
11499 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11503 caseList
= &argv
[opt
];
11504 if (patCount
== 0 || patCount
% 2 != 0)
11506 for (i
= 0; script
== 0 && i
< patCount
; i
+= 2) {
11507 Jim_Obj
*patObj
= caseList
[i
];
11509 if (!Jim_CompareStringImmediate(interp
, patObj
, "default")
11510 || i
< (patCount
- 2)) {
11511 switch (matchOpt
) {
11513 if (Jim_StringEqObj(strObj
, patObj
))
11514 script
= caseList
[i
+ 1];
11517 if (Jim_StringMatchObj(interp
, patObj
, strObj
, 0))
11518 script
= caseList
[i
+ 1];
11521 command
= Jim_NewStringObj(interp
, "regexp", -1);
11522 /* Fall thru intentionally */
11524 int rc
= Jim_CommandMatchObj(interp
, command
, patObj
, strObj
, 0);
11526 /* After the execution of a command we need to
11527 * make sure to reconvert the object into a list
11528 * again. Only for the single-list style [switch]. */
11529 if (argc
- opt
== 1) {
11532 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11535 /* command is here already decref'd */
11540 script
= caseList
[i
+ 1];
11546 script
= caseList
[i
+ 1];
11549 for (; i
< patCount
&& Jim_CompareStringImmediate(interp
, script
, "-"); i
+= 2)
11550 script
= caseList
[i
+ 1];
11551 if (script
&& Jim_CompareStringImmediate(interp
, script
, "-")) {
11552 Jim_SetResultFormatted(interp
, "no body specified for pattern \"%#s\"", caseList
[i
- 2]);
11555 Jim_SetEmptyResult(interp
);
11557 return Jim_EvalObj(interp
, script
);
11563 static int Jim_ListCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11565 Jim_Obj
*listObjPtr
;
11567 listObjPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
11568 Jim_SetResult(interp
, listObjPtr
);
11573 static int Jim_LindexCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11575 Jim_Obj
*objPtr
, *listObjPtr
;
11580 Jim_WrongNumArgs(interp
, 1, argv
, "list index ?...?");
11584 Jim_IncrRefCount(objPtr
);
11585 for (i
= 2; i
< argc
; i
++) {
11586 listObjPtr
= objPtr
;
11587 if (Jim_GetIndex(interp
, argv
[i
], &idx
) != JIM_OK
) {
11588 Jim_DecrRefCount(interp
, listObjPtr
);
11591 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_NONE
) != JIM_OK
) {
11592 /* Returns an empty object if the index
11593 * is out of range. */
11594 Jim_DecrRefCount(interp
, listObjPtr
);
11595 Jim_SetEmptyResult(interp
);
11598 Jim_IncrRefCount(objPtr
);
11599 Jim_DecrRefCount(interp
, listObjPtr
);
11601 Jim_SetResult(interp
, objPtr
);
11602 Jim_DecrRefCount(interp
, objPtr
);
11607 static int Jim_LlengthCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11610 Jim_WrongNumArgs(interp
, 1, argv
, "list");
11613 Jim_SetResultInt(interp
, Jim_ListLength(interp
, argv
[1]));
11618 static int Jim_LsearchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11620 static const char * const options
[] = {
11621 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11625 { OPT_BOOL
, OPT_NOT
, OPT_NOCASE
, OPT_EXACT
, OPT_GLOB
, OPT_REGEXP
, OPT_ALL
, OPT_INLINE
,
11630 int opt_nocase
= 0;
11632 int opt_inline
= 0;
11633 int opt_match
= OPT_EXACT
;
11636 Jim_Obj
*listObjPtr
= NULL
;
11637 Jim_Obj
*commandObj
= NULL
;
11641 Jim_WrongNumArgs(interp
, 1, argv
,
11642 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11646 for (i
= 1; i
< argc
- 2; i
++) {
11649 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
11671 if (i
>= argc
- 2) {
11674 commandObj
= argv
[++i
];
11679 opt_match
= option
;
11687 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11689 if (opt_match
== OPT_REGEXP
) {
11690 commandObj
= Jim_NewStringObj(interp
, "regexp", -1);
11693 Jim_IncrRefCount(commandObj
);
11696 listlen
= Jim_ListLength(interp
, argv
[0]);
11697 for (i
= 0; i
< listlen
; i
++) {
11701 Jim_ListIndex(interp
, argv
[0], i
, &objPtr
, JIM_NONE
);
11702 switch (opt_match
) {
11704 eq
= Jim_StringCompareObj(interp
, objPtr
, argv
[1], opt_nocase
) == 0;
11708 eq
= Jim_StringMatchObj(interp
, argv
[1], objPtr
, opt_nocase
);
11713 eq
= Jim_CommandMatchObj(interp
, commandObj
, argv
[1], objPtr
, opt_nocase
);
11716 Jim_FreeNewObj(interp
, listObjPtr
);
11724 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11725 if (!eq
&& opt_bool
&& opt_not
&& !opt_all
) {
11729 if ((!opt_bool
&& eq
== !opt_not
) || (opt_bool
&& (eq
|| opt_all
))) {
11730 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11731 Jim_Obj
*resultObj
;
11734 resultObj
= Jim_NewIntObj(interp
, eq
^ opt_not
);
11736 else if (!opt_inline
) {
11737 resultObj
= Jim_NewIntObj(interp
, i
);
11740 resultObj
= objPtr
;
11744 Jim_ListAppendElement(interp
, listObjPtr
, resultObj
);
11747 Jim_SetResult(interp
, resultObj
);
11754 Jim_SetResult(interp
, listObjPtr
);
11759 Jim_SetResultBool(interp
, opt_not
);
11761 else if (!opt_inline
) {
11762 Jim_SetResultInt(interp
, -1);
11768 Jim_DecrRefCount(interp
, commandObj
);
11774 static int Jim_LappendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11776 Jim_Obj
*listObjPtr
;
11780 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
11783 listObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
11785 /* Create the list if it does not exists */
11786 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11787 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11788 Jim_FreeNewObj(interp
, listObjPtr
);
11792 shared
= Jim_IsShared(listObjPtr
);
11794 listObjPtr
= Jim_DuplicateObj(interp
, listObjPtr
);
11795 for (i
= 2; i
< argc
; i
++)
11796 Jim_ListAppendElement(interp
, listObjPtr
, argv
[i
]);
11797 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11799 Jim_FreeNewObj(interp
, listObjPtr
);
11802 Jim_SetResult(interp
, listObjPtr
);
11807 static int Jim_LinsertCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11813 Jim_WrongNumArgs(interp
, 1, argv
, "list index element " "?element ...?");
11817 if (Jim_IsShared(listPtr
))
11818 listPtr
= Jim_DuplicateObj(interp
, listPtr
);
11819 if (Jim_GetIndex(interp
, argv
[2], &idx
) != JIM_OK
)
11821 len
= Jim_ListLength(interp
, listPtr
);
11825 idx
= len
+ idx
+ 1;
11826 Jim_ListInsertElements(interp
, listPtr
, idx
, argc
- 3, &argv
[3]);
11827 Jim_SetResult(interp
, listPtr
);
11830 if (listPtr
!= argv
[1]) {
11831 Jim_FreeNewObj(interp
, listPtr
);
11837 static int Jim_LreplaceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11839 int first
, last
, len
, rangeLen
;
11841 Jim_Obj
*newListObj
;
11846 Jim_WrongNumArgs(interp
, 1, argv
, "list first last ?element element ...?");
11849 if (Jim_GetIndex(interp
, argv
[2], &first
) != JIM_OK
||
11850 Jim_GetIndex(interp
, argv
[3], &last
) != JIM_OK
) {
11855 len
= Jim_ListLength(interp
, listObj
);
11857 first
= JimRelToAbsIndex(len
, first
);
11858 last
= JimRelToAbsIndex(len
, last
);
11859 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
11861 /* Now construct a new list which consists of:
11862 * <elements before first> <supplied elements> <elements after last>
11865 /* Check to see if trying to replace past the end of the list */
11867 /* OK. Not past the end */
11869 else if (len
== 0) {
11870 /* Special for empty list, adjust first to 0 */
11874 Jim_SetResultString(interp
, "list doesn't contain element ", -1);
11875 Jim_AppendObj(interp
, Jim_GetResult(interp
), argv
[2]);
11879 newListObj
= Jim_NewListObj(interp
, NULL
, 0);
11881 shared
= Jim_IsShared(listObj
);
11883 listObj
= Jim_DuplicateObj(interp
, listObj
);
11886 /* Add the first set of elements */
11887 for (i
= 0; i
< first
; i
++) {
11888 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11891 /* Add supplied elements */
11892 for (i
= 4; i
< argc
; i
++) {
11893 Jim_ListAppendElement(interp
, newListObj
, argv
[i
]);
11896 /* Add the remaining elements */
11897 for (i
= first
+ rangeLen
; i
< len
; i
++) {
11898 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11900 Jim_SetResult(interp
, newListObj
);
11902 Jim_FreeNewObj(interp
, listObj
);
11908 static int Jim_LsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11911 Jim_WrongNumArgs(interp
, 1, argv
, "listVar ?index...? newVal");
11914 else if (argc
== 3) {
11915 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
11917 Jim_SetResult(interp
, argv
[2]);
11920 if (Jim_SetListIndex(interp
, argv
[1], argv
+ 2, argc
- 3, argv
[argc
- 1])
11927 static int Jim_LsortCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const argv
[])
11929 static const char * const options
[] = {
11930 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11933 { OPT_ASCII
, OPT_NOCASE
, OPT_INCREASING
, OPT_DECREASING
, OPT_COMMAND
, OPT_INTEGER
, OPT_INDEX
};
11938 struct lsort_info info
;
11941 Jim_WrongNumArgs(interp
, 1, argv
, "?options? list");
11945 info
.type
= JIM_LSORT_ASCII
;
11948 info
.command
= NULL
;
11949 info
.interp
= interp
;
11951 for (i
= 1; i
< (argc
- 1); i
++) {
11954 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
)
11959 info
.type
= JIM_LSORT_ASCII
;
11962 info
.type
= JIM_LSORT_NOCASE
;
11965 info
.type
= JIM_LSORT_INTEGER
;
11967 case OPT_INCREASING
:
11970 case OPT_DECREASING
:
11974 if (i
>= (argc
- 2)) {
11975 Jim_SetResultString(interp
, "\"-command\" option must be followed by comparison command", -1);
11978 info
.type
= JIM_LSORT_COMMAND
;
11979 info
.command
= argv
[i
+ 1];
11983 if (i
>= (argc
- 2)) {
11984 Jim_SetResultString(interp
, "\"-index\" option must be followed by list index", -1);
11987 if (Jim_GetIndex(interp
, argv
[i
+ 1], &info
.index
) != JIM_OK
) {
11995 resObj
= Jim_DuplicateObj(interp
, argv
[argc
- 1]);
11996 retCode
= ListSortElements(interp
, resObj
, &info
);
11997 if (retCode
== JIM_OK
) {
11998 Jim_SetResult(interp
, resObj
);
12001 Jim_FreeNewObj(interp
, resObj
);
12007 static int Jim_AppendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12009 Jim_Obj
*stringObjPtr
;
12013 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
12017 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
12023 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
12024 if (!stringObjPtr
) {
12025 /* Create the string if it doesn't exist */
12026 stringObjPtr
= Jim_NewEmptyStringObj(interp
);
12029 else if (Jim_IsShared(stringObjPtr
)) {
12031 stringObjPtr
= Jim_DuplicateObj(interp
, stringObjPtr
);
12033 for (i
= 2; i
< argc
; i
++) {
12034 Jim_AppendObj(interp
, stringObjPtr
, argv
[i
]);
12036 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
) != JIM_OK
) {
12038 Jim_FreeNewObj(interp
, stringObjPtr
);
12043 Jim_SetResult(interp
, stringObjPtr
);
12048 static int Jim_DebugCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12050 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12051 static const char * const options
[] = {
12052 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12058 OPT_REFCOUNT
, OPT_OBJCOUNT
, OPT_OBJECTS
, OPT_INVSTR
, OPT_SCRIPTLEN
,
12059 OPT_EXPRLEN
, OPT_EXPRBC
, OPT_SHOW
,
12064 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?...?");
12067 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
)
12069 if (option
== OPT_REFCOUNT
) {
12071 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12074 Jim_SetResultInt(interp
, argv
[2]->refCount
);
12077 else if (option
== OPT_OBJCOUNT
) {
12078 int freeobj
= 0, liveobj
= 0;
12083 Jim_WrongNumArgs(interp
, 2, argv
, "");
12086 /* Count the number of free objects. */
12087 objPtr
= interp
->freeList
;
12090 objPtr
= objPtr
->nextObjPtr
;
12092 /* Count the number of live objects. */
12093 objPtr
= interp
->liveList
;
12096 objPtr
= objPtr
->nextObjPtr
;
12098 /* Set the result string and return. */
12099 sprintf(buf
, "free %d used %d", freeobj
, liveobj
);
12100 Jim_SetResultString(interp
, buf
, -1);
12103 else if (option
== OPT_OBJECTS
) {
12104 Jim_Obj
*objPtr
, *listObjPtr
, *subListObjPtr
;
12106 /* Count the number of live objects. */
12107 objPtr
= interp
->liveList
;
12108 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12111 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "";
12113 subListObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12114 sprintf(buf
, "%p", objPtr
);
12115 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
12116 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, type
, -1));
12117 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewIntObj(interp
, objPtr
->refCount
));
12118 Jim_ListAppendElement(interp
, subListObjPtr
, objPtr
);
12119 Jim_ListAppendElement(interp
, listObjPtr
, subListObjPtr
);
12120 objPtr
= objPtr
->nextObjPtr
;
12122 Jim_SetResult(interp
, listObjPtr
);
12125 else if (option
== OPT_INVSTR
) {
12129 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12133 if (objPtr
->typePtr
!= NULL
)
12134 Jim_InvalidateStringRep(objPtr
);
12135 Jim_SetEmptyResult(interp
);
12138 else if (option
== OPT_SHOW
) {
12143 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12146 s
= Jim_GetString(argv
[2], &len
);
12148 charlen
= utf8_strlen(s
, len
);
12152 printf("refcount: %d, type: %s\n", argv
[2]->refCount
, JimObjTypeName(argv
[2]));
12153 printf("chars (%d): <<%s>>\n", charlen
, s
);
12154 printf("bytes (%d):", len
);
12156 printf(" %02x", (unsigned char)*s
++);
12161 else if (option
== OPT_SCRIPTLEN
) {
12165 Jim_WrongNumArgs(interp
, 2, argv
, "script");
12168 script
= Jim_GetScript(interp
, argv
[2]);
12169 Jim_SetResultInt(interp
, script
->len
);
12172 else if (option
== OPT_EXPRLEN
) {
12173 ExprByteCode
*expr
;
12176 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12179 expr
= JimGetExpression(interp
, argv
[2]);
12182 Jim_SetResultInt(interp
, expr
->len
);
12185 else if (option
== OPT_EXPRBC
) {
12187 ExprByteCode
*expr
;
12191 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12194 expr
= JimGetExpression(interp
, argv
[2]);
12197 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
12198 for (i
= 0; i
< expr
->len
; i
++) {
12200 const Jim_ExprOperator
*op
;
12201 Jim_Obj
*obj
= expr
->token
[i
].objPtr
;
12203 switch (expr
->token
[i
].type
) {
12204 case JIM_TT_EXPR_INT
:
12207 case JIM_TT_EXPR_DOUBLE
:
12216 case JIM_TT_DICTSUGAR
:
12217 type
= "dictsugar";
12219 case JIM_TT_EXPRSUGAR
:
12220 type
= "exprsugar";
12229 op
= JimExprOperatorInfoByOpcode(expr
->token
[i
].type
);
12236 obj
= Jim_NewStringObj(interp
, op
? op
->name
: "", -1);
12239 Jim_ListAppendElement(interp
, objPtr
, Jim_NewStringObj(interp
, type
, -1));
12240 Jim_ListAppendElement(interp
, objPtr
, obj
);
12242 Jim_SetResult(interp
, objPtr
);
12246 Jim_SetResultString(interp
,
12247 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12251 #endif /* JIM_BOOTSTRAP */
12252 #if !defined(JIM_DEBUG_COMMAND)
12253 Jim_SetResultString(interp
, "unsupported", -1);
12259 static int Jim_EvalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12264 Jim_WrongNumArgs(interp
, 1, argv
, "script ?...?");
12269 rc
= Jim_EvalObj(interp
, argv
[1]);
12272 rc
= Jim_EvalObj(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12275 if (rc
== JIM_ERR
) {
12276 /* eval is "interesting", so add a stack frame here */
12277 interp
->addStackTrace
++;
12283 static int Jim_UplevelCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12287 Jim_CallFrame
*savedCallFrame
, *targetCallFrame
;
12291 /* Save the old callframe pointer */
12292 savedCallFrame
= interp
->framePtr
;
12294 /* Lookup the target frame pointer */
12295 str
= Jim_String(argv
[1]);
12296 if ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#') {
12297 targetCallFrame
=Jim_GetCallFrameByLevel(interp
, argv
[1]);
12302 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12304 if (targetCallFrame
== NULL
) {
12309 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12312 /* Eval the code in the target callframe. */
12313 interp
->framePtr
= targetCallFrame
;
12315 retcode
= Jim_EvalObj(interp
, argv
[1]);
12318 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12319 Jim_IncrRefCount(objPtr
);
12320 retcode
= Jim_EvalObj(interp
, objPtr
);
12321 Jim_DecrRefCount(interp
, objPtr
);
12323 interp
->framePtr
= savedCallFrame
;
12327 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12333 static int Jim_ExprCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12335 Jim_Obj
*exprResultPtr
;
12339 retcode
= Jim_EvalExpression(interp
, argv
[1], &exprResultPtr
);
12341 else if (argc
> 2) {
12344 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12345 Jim_IncrRefCount(objPtr
);
12346 retcode
= Jim_EvalExpression(interp
, objPtr
, &exprResultPtr
);
12347 Jim_DecrRefCount(interp
, objPtr
);
12350 Jim_WrongNumArgs(interp
, 1, argv
, "expression ?...?");
12353 if (retcode
!= JIM_OK
)
12355 Jim_SetResult(interp
, exprResultPtr
);
12356 Jim_DecrRefCount(interp
, exprResultPtr
);
12361 static int Jim_BreakCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12364 Jim_WrongNumArgs(interp
, 1, argv
, "");
12371 static int Jim_ContinueCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12374 Jim_WrongNumArgs(interp
, 1, argv
, "");
12377 return JIM_CONTINUE
;
12381 static int Jim_ReturnCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12384 Jim_Obj
*stackTraceObj
= NULL
;
12385 Jim_Obj
*errorCodeObj
= NULL
;
12386 int returnCode
= JIM_OK
;
12389 for (i
= 1; i
< argc
- 1; i
+= 2) {
12390 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-code")) {
12391 if (Jim_GetReturnCode(interp
, argv
[i
+ 1], &returnCode
) == JIM_ERR
) {
12395 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorinfo")) {
12396 stackTraceObj
= argv
[i
+ 1];
12398 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorcode")) {
12399 errorCodeObj
= argv
[i
+ 1];
12401 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-level")) {
12402 if (Jim_GetLong(interp
, argv
[i
+ 1], &level
) != JIM_OK
|| level
< 0) {
12403 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", argv
[i
+ 1]);
12412 if (i
!= argc
- 1 && i
!= argc
) {
12413 Jim_WrongNumArgs(interp
, 1, argv
,
12414 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12417 /* If a stack trace is supplied and code is error, set the stack trace */
12418 if (stackTraceObj
&& returnCode
== JIM_ERR
) {
12419 JimSetStackTrace(interp
, stackTraceObj
);
12421 /* If an error code list is supplied, set the global $errorCode */
12422 if (errorCodeObj
&& returnCode
== JIM_ERR
) {
12423 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCodeObj
);
12425 interp
->returnCode
= returnCode
;
12426 interp
->returnLevel
= level
;
12428 if (i
== argc
- 1) {
12429 Jim_SetResult(interp
, argv
[i
]);
12435 static int Jim_TailcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12439 objPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
12440 Jim_SetResult(interp
, objPtr
);
12445 static int Jim_ProcCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12447 if (argc
!= 4 && argc
!= 5) {
12448 Jim_WrongNumArgs(interp
, 1, argv
, "name arglist ?statics? body");
12453 return JimCreateProcedure(interp
, argv
[1], argv
[2], NULL
, argv
[3]);
12456 return JimCreateProcedure(interp
, argv
[1], argv
[2], argv
[3], argv
[4]);
12461 static int Jim_LocalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12465 /* Evaluate the arguments with 'local' in force */
12467 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12471 /* If OK, and the result is a proc, add it to the list of local procs */
12472 if (retcode
== 0) {
12473 const char *procname
= Jim_String(Jim_GetResult(interp
));
12475 if (Jim_FindHashEntry(&interp
->commands
, procname
) == NULL
) {
12476 Jim_SetResultFormatted(interp
, "not a proc: \"%s\"", procname
);
12479 if (interp
->localProcs
== NULL
) {
12480 interp
->localProcs
= Jim_Alloc(sizeof(*interp
->localProcs
));
12481 Jim_InitStack(interp
->localProcs
);
12483 Jim_StackPush(interp
->localProcs
, Jim_StrDup(procname
));
12490 static int Jim_UpcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12493 Jim_WrongNumArgs(interp
, 1, argv
, "cmd ?args ...?");
12499 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, argv
[1], JIM_ERRMSG
);
12500 if (cmdPtr
== NULL
|| !cmdPtr
->isproc
|| !cmdPtr
->u
.proc
.prevCmd
) {
12501 Jim_SetResultFormatted(interp
, "no previous proc: \"%#s\"", argv
[1]);
12504 /* OK. Mark this command as being in an upcall */
12505 cmdPtr
->u
.proc
.upcall
++;
12506 JimIncrCmdRefCount(cmdPtr
);
12508 /* Invoke the command as normal */
12509 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12511 /* No longer in an upcall */
12512 cmdPtr
->u
.proc
.upcall
--;
12513 JimDecrCmdRefCount(interp
, cmdPtr
);
12520 static int Jim_ConcatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12522 Jim_SetResult(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12527 static int Jim_UpvarCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12530 Jim_CallFrame
*targetCallFrame
;
12532 /* Lookup the target frame pointer */
12533 if (argc
> 3 && (argc
% 2 == 0)) {
12534 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, argv
[1]);
12539 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12541 if (targetCallFrame
== NULL
) {
12545 /* Check for arity */
12547 Jim_WrongNumArgs(interp
, 1, argv
, "?level? otherVar localVar ?otherVar localVar ...?");
12551 /* Now... for every other/local couple: */
12552 for (i
= 1; i
< argc
; i
+= 2) {
12553 if (Jim_SetVariableLink(interp
, argv
[i
+ 1], argv
[i
], targetCallFrame
) != JIM_OK
)
12560 static int Jim_GlobalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12565 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
12568 /* Link every var to the toplevel having the same name */
12569 if (interp
->framePtr
->level
== 0)
12570 return JIM_OK
; /* global at toplevel... */
12571 for (i
= 1; i
< argc
; i
++) {
12572 if (Jim_SetVariableLink(interp
, argv
[i
], argv
[i
], interp
->topFramePtr
) != JIM_OK
)
12578 /* does the [string map] operation. On error NULL is returned,
12579 * otherwise a new string object with the result, having refcount = 0,
12581 static Jim_Obj
*JimStringMap(Jim_Interp
*interp
, Jim_Obj
*mapListObjPtr
,
12582 Jim_Obj
*objPtr
, int nocase
)
12585 const char *str
, *noMatchStart
= NULL
;
12587 Jim_Obj
*resultObjPtr
;
12589 numMaps
= Jim_ListLength(interp
, mapListObjPtr
);
12591 Jim_SetResultString(interp
, "list must contain an even number of elements", -1);
12595 str
= Jim_String(objPtr
);
12596 strLen
= Jim_Utf8Length(interp
, objPtr
);
12599 resultObjPtr
= Jim_NewStringObj(interp
, "", 0);
12601 for (i
= 0; i
< numMaps
; i
+= 2) {
12606 Jim_ListIndex(interp
, mapListObjPtr
, i
, &objPtr
, JIM_NONE
);
12607 k
= Jim_String(objPtr
);
12608 kl
= Jim_Utf8Length(interp
, objPtr
);
12610 if (strLen
>= kl
&& kl
) {
12613 rc
= JimStringCompareNoCase(str
, k
, kl
);
12616 rc
= JimStringCompare(str
, kl
, k
, kl
);
12619 if (noMatchStart
) {
12620 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12621 noMatchStart
= NULL
;
12623 Jim_ListIndex(interp
, mapListObjPtr
, i
+ 1, &objPtr
, JIM_NONE
);
12624 Jim_AppendObj(interp
, resultObjPtr
, objPtr
);
12625 str
+= utf8_index(str
, kl
);
12631 if (i
== numMaps
) { /* no match */
12633 if (noMatchStart
== NULL
)
12634 noMatchStart
= str
;
12635 str
+= utf8_tounicode(str
, &c
);
12639 if (noMatchStart
) {
12640 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12642 return resultObjPtr
;
12646 static int Jim_StringCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12651 static const char * const options
[] = {
12652 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12653 "repeat", "reverse", "index", "first", "last",
12654 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12658 OPT_BYTELENGTH
, OPT_LENGTH
, OPT_COMPARE
, OPT_MATCH
, OPT_EQUAL
, OPT_IS
, OPT_BYTERANGE
, OPT_RANGE
, OPT_MAP
,
12659 OPT_REPEAT
, OPT_REVERSE
, OPT_INDEX
, OPT_FIRST
, OPT_LAST
,
12660 OPT_TRIM
, OPT_TRIMLEFT
, OPT_TRIMRIGHT
, OPT_TOLOWER
, OPT_TOUPPER
12662 static const char * const nocase_options
[] = {
12667 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
12670 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
,
12671 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
)
12676 case OPT_BYTELENGTH
:
12678 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12681 if (option
== OPT_LENGTH
) {
12682 len
= Jim_Utf8Length(interp
, argv
[2]);
12685 len
= Jim_Length(argv
[2]);
12687 Jim_SetResultInt(interp
, len
);
12694 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12695 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12696 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? string1 string2");
12699 if (opt_case
== 0) {
12702 if (option
== OPT_COMPARE
|| !opt_case
) {
12703 Jim_SetResultInt(interp
, Jim_StringCompareObj(interp
, argv
[2], argv
[3], !opt_case
));
12706 Jim_SetResultBool(interp
, Jim_StringEqObj(argv
[2], argv
[3]));
12713 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12714 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12715 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? pattern string");
12718 if (opt_case
== 0) {
12721 Jim_SetResultBool(interp
, Jim_StringMatchObj(interp
, argv
[2], argv
[3], !opt_case
));
12729 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12730 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12731 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? mapList string");
12735 if (opt_case
== 0) {
12738 objPtr
= JimStringMap(interp
, argv
[2], argv
[3], !opt_case
);
12739 if (objPtr
== NULL
) {
12742 Jim_SetResult(interp
, objPtr
);
12747 case OPT_BYTERANGE
:{
12751 Jim_WrongNumArgs(interp
, 2, argv
, "string first last");
12754 if (option
== OPT_RANGE
) {
12755 objPtr
= Jim_StringRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12759 objPtr
= Jim_StringByteRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12762 if (objPtr
== NULL
) {
12765 Jim_SetResult(interp
, objPtr
);
12774 Jim_WrongNumArgs(interp
, 2, argv
, "string count");
12777 if (Jim_GetWide(interp
, argv
[3], &count
) != JIM_OK
) {
12780 objPtr
= Jim_NewStringObj(interp
, "", 0);
12783 Jim_AppendObj(interp
, objPtr
, argv
[2]);
12786 Jim_SetResult(interp
, objPtr
);
12797 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12801 str
= Jim_GetString(argv
[2], &len
);
12802 buf
= Jim_Alloc(len
+ 1);
12805 for (i
= 0; i
< len
; ) {
12807 int l
= utf8_tounicode(str
, &c
);
12808 memcpy(p
- l
, str
, l
);
12813 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
12822 Jim_WrongNumArgs(interp
, 2, argv
, "string index");
12825 if (Jim_GetIndex(interp
, argv
[3], &idx
) != JIM_OK
) {
12828 str
= Jim_String(argv
[2]);
12829 len
= Jim_Utf8Length(interp
, argv
[2]);
12830 if (idx
!= INT_MIN
&& idx
!= INT_MAX
) {
12831 idx
= JimRelToAbsIndex(len
, idx
);
12833 if (idx
< 0 || idx
>= len
|| str
== NULL
) {
12834 Jim_SetResultString(interp
, "", 0);
12836 else if (len
== Jim_Length(argv
[2])) {
12837 /* ASCII optimisation */
12838 Jim_SetResultString(interp
, str
+ idx
, 1);
12842 int i
= utf8_index(str
, idx
);
12843 Jim_SetResultString(interp
, str
+ i
, utf8_tounicode(str
+ i
, &c
));
12850 int idx
= 0, l1
, l2
;
12851 const char *s1
, *s2
;
12853 if (argc
!= 4 && argc
!= 5) {
12854 Jim_WrongNumArgs(interp
, 2, argv
, "subString string ?index?");
12857 s1
= Jim_String(argv
[2]);
12858 s2
= Jim_String(argv
[3]);
12859 l1
= Jim_Utf8Length(interp
, argv
[2]);
12860 l2
= Jim_Utf8Length(interp
, argv
[3]);
12862 if (Jim_GetIndex(interp
, argv
[4], &idx
) != JIM_OK
) {
12865 idx
= JimRelToAbsIndex(l2
, idx
);
12867 else if (option
== OPT_LAST
) {
12870 if (option
== OPT_FIRST
) {
12871 Jim_SetResultInt(interp
, JimStringFirst(s1
, l1
, s2
, l2
, idx
));
12875 Jim_SetResultInt(interp
, JimStringLastUtf8(s1
, l1
, s2
, idx
));
12877 Jim_SetResultInt(interp
, JimStringLast(s1
, l1
, s2
, idx
));
12885 case OPT_TRIMRIGHT
:{
12886 Jim_Obj
*trimchars
;
12888 if (argc
!= 3 && argc
!= 4) {
12889 Jim_WrongNumArgs(interp
, 2, argv
, "string ?trimchars?");
12892 trimchars
= (argc
== 4 ? argv
[3] : NULL
);
12893 if (option
== OPT_TRIM
) {
12894 Jim_SetResult(interp
, JimStringTrim(interp
, argv
[2], trimchars
));
12896 else if (option
== OPT_TRIMLEFT
) {
12897 Jim_SetResult(interp
, JimStringTrimLeft(interp
, argv
[2], trimchars
));
12899 else if (option
== OPT_TRIMRIGHT
) {
12900 Jim_SetResult(interp
, JimStringTrimRight(interp
, argv
[2], trimchars
));
12908 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12911 if (option
== OPT_TOLOWER
) {
12912 Jim_SetResult(interp
, JimStringToLower(interp
, argv
[2]));
12915 Jim_SetResult(interp
, JimStringToUpper(interp
, argv
[2]));
12920 if (argc
== 4 || (argc
== 5 && Jim_CompareStringImmediate(interp
, argv
[3], "-strict"))) {
12921 return JimStringIs(interp
, argv
[argc
- 1], argv
[2], argc
== 5);
12923 Jim_WrongNumArgs(interp
, 2, argv
, "class ?-strict? str");
12930 static int Jim_TimeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12933 jim_wide start
, elapsed
;
12935 const char *fmt
= "%" JIM_WIDE_MODIFIER
" microseconds per iteration";
12938 Jim_WrongNumArgs(interp
, 1, argv
, "script ?count?");
12942 if (Jim_GetLong(interp
, argv
[2], &count
) != JIM_OK
)
12948 start
= JimClock();
12952 retval
= Jim_EvalObj(interp
, argv
[1]);
12953 if (retval
!= JIM_OK
) {
12957 elapsed
= JimClock() - start
;
12958 sprintf(buf
, fmt
, count
== 0 ? 0 : elapsed
/ count
);
12959 Jim_SetResultString(interp
, buf
, -1);
12964 static int Jim_ExitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12969 Jim_WrongNumArgs(interp
, 1, argv
, "?exitCode?");
12973 if (Jim_GetLong(interp
, argv
[1], &exitCode
) != JIM_OK
)
12976 interp
->exitCode
= exitCode
;
12981 static int Jim_CatchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12987 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
12988 jim_wide ignore_mask
= (1 << JIM_EXIT
) | (1 << JIM_EVAL
) | (1 << JIM_SIGNAL
);
12989 static const int max_ignore_code
= sizeof(ignore_mask
) * 8;
12991 /* Reset the error code before catch.
12992 * Note that this is not strictly correct.
12994 Jim_SetGlobalVariableStr(interp
, "errorCode", Jim_NewStringObj(interp
, "NONE", -1));
12996 for (i
= 1; i
< argc
- 1; i
++) {
12997 const char *arg
= Jim_String(argv
[i
]);
13001 /* It's a pity we can't use Jim_GetEnum here :-( */
13002 if (strcmp(arg
, "--") == 0) {
13010 if (strncmp(arg
, "-no", 3) == 0) {
13019 if (Jim_StringToWide(arg
, &option
, 10) != JIM_OK
) {
13023 option
= Jim_FindByName(arg
, jimReturnCodes
, jimReturnCodesSize
);
13030 ignore_mask
|= (1 << option
);
13033 ignore_mask
&= ~(1 << option
);
13038 if (argc
< 1 || argc
> 3) {
13040 Jim_WrongNumArgs(interp
, 1, argv
,
13041 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13046 if ((ignore_mask
& (1 << JIM_SIGNAL
)) == 0) {
13050 interp
->signal_level
+= sig
;
13051 if (interp
->signal_level
&& interp
->sigmask
) {
13052 /* If a signal is set, don't even try to execute the body */
13053 exitCode
= JIM_SIGNAL
;
13056 exitCode
= Jim_EvalObj(interp
, argv
[0]);
13058 interp
->signal_level
-= sig
;
13060 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13061 if (exitCode
>= 0 && exitCode
< max_ignore_code
&& ((1 << exitCode
) & ignore_mask
)) {
13062 /* Not caught, pass it up */
13066 if (sig
&& exitCode
== JIM_SIGNAL
) {
13067 /* Catch the signal at this level */
13068 if (interp
->signal_set_result
) {
13069 interp
->signal_set_result(interp
, interp
->sigmask
);
13072 Jim_SetResultInt(interp
, interp
->sigmask
);
13074 interp
->sigmask
= 0;
13078 if (Jim_SetVariable(interp
, argv
[1], Jim_GetResult(interp
)) != JIM_OK
) {
13082 Jim_Obj
*optListObj
= Jim_NewListObj(interp
, NULL
, 0);
13084 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-code", -1));
13085 Jim_ListAppendElement(interp
, optListObj
,
13086 Jim_NewIntObj(interp
, exitCode
== JIM_RETURN
? interp
->returnCode
: exitCode
));
13087 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-level", -1));
13088 Jim_ListAppendElement(interp
, optListObj
, Jim_NewIntObj(interp
, interp
->returnLevel
));
13089 if (exitCode
== JIM_ERR
) {
13090 Jim_Obj
*errorCode
;
13091 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorinfo",
13093 Jim_ListAppendElement(interp
, optListObj
, interp
->stackTrace
);
13095 errorCode
= Jim_GetGlobalVariableStr(interp
, "errorCode", JIM_NONE
);
13097 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorcode", -1));
13098 Jim_ListAppendElement(interp
, optListObj
, errorCode
);
13101 if (Jim_SetVariable(interp
, argv
[2], optListObj
) != JIM_OK
) {
13106 Jim_SetResultInt(interp
, exitCode
);
13110 #ifdef JIM_REFERENCES
13113 static int Jim_RefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13115 if (argc
!= 3 && argc
!= 4) {
13116 Jim_WrongNumArgs(interp
, 1, argv
, "string tag ?finalizer?");
13120 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], NULL
));
13123 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], argv
[3]));
13129 static int Jim_GetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13131 Jim_Reference
*refPtr
;
13134 Jim_WrongNumArgs(interp
, 1, argv
, "reference");
13137 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13139 Jim_SetResult(interp
, refPtr
->objPtr
);
13144 static int Jim_SetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13146 Jim_Reference
*refPtr
;
13149 Jim_WrongNumArgs(interp
, 1, argv
, "reference newValue");
13152 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13154 Jim_IncrRefCount(argv
[2]);
13155 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
13156 refPtr
->objPtr
= argv
[2];
13157 Jim_SetResult(interp
, argv
[2]);
13162 static int Jim_CollectCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13165 Jim_WrongNumArgs(interp
, 1, argv
, "");
13168 Jim_SetResultInt(interp
, Jim_Collect(interp
));
13170 /* Free all the freed objects. */
13171 while (interp
->freeList
) {
13172 Jim_Obj
*nextObjPtr
= interp
->freeList
->nextObjPtr
;
13173 Jim_Free(interp
->freeList
);
13174 interp
->freeList
= nextObjPtr
;
13180 /* [finalize] reference ?newValue? */
13181 static int Jim_FinalizeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13183 if (argc
!= 2 && argc
!= 3) {
13184 Jim_WrongNumArgs(interp
, 1, argv
, "reference ?finalizerProc?");
13188 Jim_Obj
*cmdNamePtr
;
13190 if (Jim_GetFinalizer(interp
, argv
[1], &cmdNamePtr
) != JIM_OK
)
13192 if (cmdNamePtr
!= NULL
) /* otherwise the null string is returned. */
13193 Jim_SetResult(interp
, cmdNamePtr
);
13196 if (Jim_SetFinalizer(interp
, argv
[1], argv
[2]) != JIM_OK
)
13198 Jim_SetResult(interp
, argv
[2]);
13203 /* [info references] */
13204 static int JimInfoReferences(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13206 Jim_Obj
*listObjPtr
;
13207 Jim_HashTableIterator
*htiter
;
13210 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13212 htiter
= Jim_GetHashTableIterator(&interp
->references
);
13213 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
13214 char buf
[JIM_REFERENCE_SPACE
];
13215 Jim_Reference
*refPtr
= he
->u
.val
;
13216 const jim_wide
*refId
= he
->key
;
13218 JimFormatReference(buf
, refPtr
, *refId
);
13219 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
13221 Jim_FreeHashTableIterator(htiter
);
13222 Jim_SetResult(interp
, listObjPtr
);
13228 static int Jim_RenameCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13230 const char *oldName
, *newName
;
13233 Jim_WrongNumArgs(interp
, 1, argv
, "oldName newName");
13237 if (JimValidName(interp
, "new procedure", argv
[2])) {
13241 oldName
= Jim_String(argv
[1]);
13242 newName
= Jim_String(argv
[2]);
13243 return Jim_RenameCommand(interp
, oldName
, newName
);
13246 int Jim_DictKeys(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*patternObj
)
13250 Jim_Obj
*resultObj
;
13252 Jim_Obj
**dictValuesObj
;
13254 if (Jim_DictKeysVector(interp
, objPtr
, NULL
, 0, &dictObj
, JIM_ERRMSG
) != JIM_OK
) {
13258 /* XXX: Could make the exact-match case much more efficient here.
13259 * See JimCommandsList()
13261 if (Jim_DictPairs(interp
, dictObj
, &dictValuesObj
, &len
) != JIM_OK
) {
13265 /* Only return the matching values */
13266 resultObj
= Jim_NewListObj(interp
, NULL
, 0);
13268 for (i
= 0; i
< len
; i
+= 2) {
13269 if (patternObj
== NULL
|| Jim_StringMatchObj(interp
, patternObj
, dictValuesObj
[i
], 0)) {
13270 Jim_ListAppendElement(interp
, resultObj
, dictValuesObj
[i
]);
13273 Jim_Free(dictValuesObj
);
13275 Jim_SetResult(interp
, resultObj
);
13279 int Jim_DictSize(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
13281 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
13284 return ((Jim_HashTable
*)objPtr
->internalRep
.ptr
)->used
;
13288 static int Jim_DictCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13292 static const char * const options
[] = {
13293 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13297 OPT_CREATE
, OPT_GET
, OPT_SET
, OPT_UNSET
, OPT_EXIST
, OPT_KEYS
, OPT_MERGE
, OPT_SIZE
, OPT_WITH
,
13301 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?arguments ...?");
13305 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
) {
13312 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13315 if (Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, &objPtr
,
13316 JIM_ERRMSG
) != JIM_OK
) {
13319 Jim_SetResult(interp
, objPtr
);
13324 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...? value");
13327 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 4, argv
[argc
- 1], JIM_ERRMSG
);
13331 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13334 Jim_SetResultBool(interp
, Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3,
13335 &objPtr
, JIM_ERRMSG
) == JIM_OK
);
13340 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...?");
13343 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, NULL
, JIM_NONE
);
13346 if (argc
!= 3 && argc
!= 4) {
13347 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?pattern?");
13350 return Jim_DictKeys(interp
, argv
[2], argc
== 4 ? argv
[3] : NULL
);
13356 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar");
13360 size
= Jim_DictSize(interp
, argv
[2]);
13364 Jim_SetResultInt(interp
, size
);
13372 else if (argv
[2]->typePtr
!= &dictObjType
&& SetDictFromAny(interp
, argv
[2]) != JIM_OK
) {
13376 return Jim_EvalPrefix(interp
, "dict merge", argc
- 2, argv
+ 2);
13381 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?key ...? script");
13384 else if (Jim_GetVariable(interp
, argv
[2], JIM_ERRMSG
) == NULL
) {
13388 return Jim_EvalPrefix(interp
, "dict with", argc
- 2, argv
+ 2);
13393 Jim_WrongNumArgs(interp
, 2, argv
, "?key value ...?");
13396 objPtr
= Jim_NewDictObj(interp
, argv
+ 2, argc
- 2);
13397 Jim_SetResult(interp
, objPtr
);
13406 static int Jim_SubstCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13408 static const char * const options
[] = {
13409 "-nobackslashes", "-nocommands", "-novariables", NULL
13412 { OPT_NOBACKSLASHES
, OPT_NOCOMMANDS
, OPT_NOVARIABLES
};
13414 int flags
= JIM_SUBST_FLAG
;
13418 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string");
13421 for (i
= 1; i
< (argc
- 1); i
++) {
13424 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
,
13425 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13429 case OPT_NOBACKSLASHES
:
13430 flags
|= JIM_SUBST_NOESC
;
13432 case OPT_NOCOMMANDS
:
13433 flags
|= JIM_SUBST_NOCMD
;
13435 case OPT_NOVARIABLES
:
13436 flags
|= JIM_SUBST_NOVAR
;
13440 if (Jim_SubstObj(interp
, argv
[argc
- 1], &objPtr
, flags
) != JIM_OK
) {
13443 Jim_SetResult(interp
, objPtr
);
13448 static int Jim_InfoCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13454 static const char * const commands
[] = {
13455 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13456 "vars", "version", "patchlevel", "complete", "args", "hostname",
13457 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13461 { INFO_BODY
, INFO_COMMANDS
, INFO_PROCS
, INFO_CHANNELS
, INFO_EXISTS
, INFO_GLOBALS
, INFO_LEVEL
,
13462 INFO_FRAME
, INFO_LOCALS
, INFO_VARS
, INFO_VERSION
, INFO_PATCHLEVEL
, INFO_COMPLETE
, INFO_ARGS
,
13463 INFO_HOSTNAME
, INFO_SCRIPT
, INFO_SOURCE
, INFO_STACKTRACE
, INFO_NAMEOFEXECUTABLE
,
13464 INFO_RETURNCODES
, INFO_REFERENCES
,
13468 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?args ...?");
13471 if (Jim_GetEnum(interp
, argv
[1], commands
, &cmd
, "subcommand", JIM_ERRMSG
| JIM_ENUM_ABBREV
)
13476 /* Test for the the most common commands first, just in case it makes a difference */
13480 Jim_WrongNumArgs(interp
, 2, argv
, "varName");
13483 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, argv
[2], 0) != NULL
);
13487 case INFO_CHANNELS
:
13488 #ifndef jim_ext_aio
13489 Jim_SetResultString(interp
, "aio not enabled", -1);
13492 case INFO_COMMANDS
:
13494 if (argc
!= 2 && argc
!= 3) {
13495 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13498 Jim_SetResult(interp
, JimCommandsList(interp
, (argc
== 3) ? argv
[2] : NULL
,
13499 (cmd
- INFO_COMMANDS
)));
13503 mode
++; /* JIM_VARLIST_VARS */
13505 mode
++; /* JIM_VARLIST_LOCALS */
13507 /* mode 0 => JIM_VARLIST_GLOBALS */
13508 if (argc
!= 2 && argc
!= 3) {
13509 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13512 Jim_SetResult(interp
, JimVariablesList(interp
, argc
== 3 ? argv
[2] : NULL
, mode
));
13517 Jim_WrongNumArgs(interp
, 2, argv
, "");
13520 Jim_SetResult(interp
, Jim_GetScript(interp
, interp
->currentScriptObj
)->fileNameObj
);
13525 Jim_Obj
*resObjPtr
;
13526 Jim_Obj
*fileNameObj
;
13529 Jim_WrongNumArgs(interp
, 2, argv
, "source");
13532 if (argv
[2]->typePtr
== &sourceObjType
) {
13533 fileNameObj
= argv
[2]->internalRep
.sourceValue
.fileNameObj
;
13534 line
= argv
[2]->internalRep
.sourceValue
.lineNumber
;
13536 else if (argv
[2]->typePtr
== &scriptObjType
) {
13537 ScriptObj
*script
= Jim_GetScript(interp
, argv
[2]);
13538 fileNameObj
= script
->fileNameObj
;
13539 line
= script
->line
;
13542 fileNameObj
= interp
->emptyObj
;
13545 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13546 Jim_ListAppendElement(interp
, resObjPtr
, fileNameObj
);
13547 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewIntObj(interp
, line
));
13548 Jim_SetResult(interp
, resObjPtr
);
13552 case INFO_STACKTRACE
:
13553 Jim_SetResult(interp
, interp
->stackTrace
);
13560 Jim_SetResultInt(interp
, interp
->framePtr
->level
);
13564 if (JimInfoLevel(interp
, argv
[2], &objPtr
, cmd
== INFO_LEVEL
) != JIM_OK
) {
13567 Jim_SetResult(interp
, objPtr
);
13571 Jim_WrongNumArgs(interp
, 2, argv
, "?levelNum?");
13581 Jim_WrongNumArgs(interp
, 2, argv
, "procname");
13584 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
) {
13587 if (!cmdPtr
->isproc
) {
13588 Jim_SetResultFormatted(interp
, "command \"%#s\" is not a procedure", argv
[2]);
13591 Jim_SetResult(interp
,
13592 cmd
== INFO_BODY
? cmdPtr
->u
.proc
.bodyObjPtr
: cmdPtr
->u
.proc
.argListObjPtr
);
13597 case INFO_PATCHLEVEL
:{
13598 char buf
[(JIM_INTEGER_SPACE
* 2) + 1];
13600 sprintf(buf
, "%d.%d", JIM_VERSION
/ 100, JIM_VERSION
% 100);
13601 Jim_SetResultString(interp
, buf
, -1);
13605 case INFO_COMPLETE
:
13606 if (argc
!= 3 && argc
!= 4) {
13607 Jim_WrongNumArgs(interp
, 2, argv
, "script ?missing?");
13612 const char *s
= Jim_GetString(argv
[2], &len
);
13615 Jim_SetResultBool(interp
, Jim_ScriptIsComplete(s
, len
, &missing
));
13616 if (missing
!= ' ' && argc
== 4) {
13617 Jim_SetVariable(interp
, argv
[3], Jim_NewStringObj(interp
, &missing
, 1));
13622 case INFO_HOSTNAME
:
13623 /* Redirect to os.gethostname if it exists */
13624 return Jim_Eval(interp
, "os.gethostname");
13626 case INFO_NAMEOFEXECUTABLE
:
13627 /* Redirect to Tcl proc */
13628 return Jim_Eval(interp
, "{info nameofexecutable}");
13630 case INFO_RETURNCODES
:
13633 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13635 for (i
= 0; jimReturnCodes
[i
]; i
++) {
13636 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewIntObj(interp
, i
));
13637 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
,
13638 jimReturnCodes
[i
], -1));
13641 Jim_SetResult(interp
, listObjPtr
);
13643 else if (argc
== 3) {
13647 if (Jim_GetLong(interp
, argv
[2], &code
) != JIM_OK
) {
13650 name
= Jim_ReturnCode(code
);
13651 if (*name
== '?') {
13652 Jim_SetResultInt(interp
, code
);
13655 Jim_SetResultString(interp
, name
, -1);
13659 Jim_WrongNumArgs(interp
, 2, argv
, "?code?");
13663 case INFO_REFERENCES
:
13664 #ifdef JIM_REFERENCES
13665 return JimInfoReferences(interp
, argc
, argv
);
13667 Jim_SetResultString(interp
, "not supported", -1);
13675 static int Jim_ExistsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13679 static const char * const options
[] = {
13680 "-command", "-proc", "-var", NULL
13684 OPT_COMMAND
, OPT_PROC
, OPT_VAR
13692 else if (argc
== 3) {
13693 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13699 Jim_WrongNumArgs(interp
, 1, argv
, "?option? name");
13703 /* Test for the the most common commands first, just in case it makes a difference */
13706 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, objPtr
, 0) != NULL
);
13711 Jim_Cmd
*cmd
= Jim_GetCommand(interp
, objPtr
, JIM_NONE
);
13712 Jim_SetResultBool(interp
, cmd
!= NULL
&& (option
== OPT_COMMAND
|| cmd
->isproc
));
13720 static int Jim_SplitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13722 const char *str
, *splitChars
, *noMatchStart
;
13723 int splitLen
, strLen
;
13724 Jim_Obj
*resObjPtr
;
13728 if (argc
!= 2 && argc
!= 3) {
13729 Jim_WrongNumArgs(interp
, 1, argv
, "string ?splitChars?");
13733 str
= Jim_GetString(argv
[1], &len
);
13737 strLen
= Jim_Utf8Length(interp
, argv
[1]);
13741 splitChars
= " \n\t\r";
13745 splitChars
= Jim_String(argv
[2]);
13746 splitLen
= Jim_Utf8Length(interp
, argv
[2]);
13749 noMatchStart
= str
;
13750 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13756 const char *sc
= splitChars
;
13757 int scLen
= splitLen
;
13758 int sl
= utf8_tounicode(str
, &c
);
13761 sc
+= utf8_tounicode(sc
, &pc
);
13763 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13764 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13765 noMatchStart
= str
+ sl
;
13771 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13772 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13775 /* This handles the special case of splitchars eq {}
13776 * Optimise by sharing common (ASCII) characters
13778 Jim_Obj
**commonObj
= NULL
;
13779 #define NUM_COMMON (128 - 9)
13781 int n
= utf8_tounicode(str
, &c
);
13782 #ifdef JIM_OPTIMIZATION
13783 if (c
>= 9 && c
< 128) {
13784 /* Common ASCII char. Note that 9 is the tab character */
13787 commonObj
= Jim_Alloc(sizeof(*commonObj
) * NUM_COMMON
);
13788 memset(commonObj
, 0, sizeof(*commonObj
) * NUM_COMMON
);
13790 if (!commonObj
[c
]) {
13791 commonObj
[c
] = Jim_NewStringObj(interp
, str
, 1);
13793 Jim_ListAppendElement(interp
, resObjPtr
, commonObj
[c
]);
13798 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewStringObjUtf8(interp
, str
, 1));
13801 Jim_Free(commonObj
);
13804 Jim_SetResult(interp
, resObjPtr
);
13809 static int Jim_JoinCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13811 const char *joinStr
;
13812 int joinStrLen
, i
, listLen
;
13813 Jim_Obj
*resObjPtr
;
13815 if (argc
!= 2 && argc
!= 3) {
13816 Jim_WrongNumArgs(interp
, 1, argv
, "list ?joinString?");
13825 joinStr
= Jim_GetString(argv
[2], &joinStrLen
);
13827 listLen
= Jim_ListLength(interp
, argv
[1]);
13828 resObjPtr
= Jim_NewStringObj(interp
, NULL
, 0);
13830 for (i
= 0; i
< listLen
; i
++) {
13831 Jim_Obj
*objPtr
= 0;
13833 Jim_ListIndex(interp
, argv
[1], i
, &objPtr
, JIM_NONE
);
13834 Jim_AppendObj(interp
, resObjPtr
, objPtr
);
13835 if (i
+ 1 != listLen
) {
13836 Jim_AppendString(interp
, resObjPtr
, joinStr
, joinStrLen
);
13839 Jim_SetResult(interp
, resObjPtr
);
13844 static int Jim_FormatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13849 Jim_WrongNumArgs(interp
, 1, argv
, "formatString ?arg arg ...?");
13852 objPtr
= Jim_FormatString(interp
, argv
[1], argc
- 2, argv
+ 2);
13853 if (objPtr
== NULL
)
13855 Jim_SetResult(interp
, objPtr
);
13860 static int Jim_ScanCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13862 Jim_Obj
*listPtr
, **outVec
;
13866 Jim_WrongNumArgs(interp
, 1, argv
, "string format ?varName varName ...?");
13869 if (argv
[2]->typePtr
!= &scanFmtStringObjType
)
13870 SetScanFmtFromAny(interp
, argv
[2]);
13871 if (FormatGetError(argv
[2]) != 0) {
13872 Jim_SetResultString(interp
, FormatGetError(argv
[2]), -1);
13876 int maxPos
= FormatGetMaxPos(argv
[2]);
13877 int count
= FormatGetCnvCount(argv
[2]);
13879 if (maxPos
> argc
- 3) {
13880 Jim_SetResultString(interp
, "\"%n$\" argument index out of range", -1);
13883 else if (count
> argc
- 3) {
13884 Jim_SetResultString(interp
, "different numbers of variable names and "
13885 "field specifiers", -1);
13888 else if (count
< argc
- 3) {
13889 Jim_SetResultString(interp
, "variable is not assigned by any "
13890 "conversion specifiers", -1);
13894 listPtr
= Jim_ScanString(interp
, argv
[1], argv
[2], JIM_ERRMSG
);
13901 if (listPtr
!= 0 && listPtr
!= (Jim_Obj
*)EOF
) {
13902 int len
= Jim_ListLength(interp
, listPtr
);
13905 JimListGetElements(interp
, listPtr
, &outc
, &outVec
);
13906 for (i
= 0; i
< outc
; ++i
) {
13907 if (Jim_Length(outVec
[i
]) > 0) {
13909 if (Jim_SetVariable(interp
, argv
[3 + i
], outVec
[i
]) != JIM_OK
) {
13915 Jim_FreeNewObj(interp
, listPtr
);
13920 if (rc
== JIM_OK
) {
13921 Jim_SetResultInt(interp
, count
);
13926 if (listPtr
== (Jim_Obj
*)EOF
) {
13927 Jim_SetResult(interp
, Jim_NewListObj(interp
, 0, 0));
13930 Jim_SetResult(interp
, listPtr
);
13936 static int Jim_ErrorCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13938 if (argc
!= 2 && argc
!= 3) {
13939 Jim_WrongNumArgs(interp
, 1, argv
, "message ?stacktrace?");
13942 Jim_SetResult(interp
, argv
[1]);
13944 JimSetStackTrace(interp
, argv
[2]);
13947 interp
->addStackTrace
++;
13952 static int Jim_LrangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13957 Jim_WrongNumArgs(interp
, 1, argv
, "list first last");
13960 if ((objPtr
= Jim_ListRange(interp
, argv
[1], argv
[2], argv
[3])) == NULL
)
13962 Jim_SetResult(interp
, objPtr
);
13967 static int Jim_LrepeatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13972 if (argc
< 2 || Jim_GetLong(interp
, argv
[1], &count
) != JIM_OK
|| count
< 0) {
13973 Jim_WrongNumArgs(interp
, 1, argv
, "count ?value ...?");
13977 if (count
== 0 || argc
== 2) {
13984 objPtr
= Jim_NewListObj(interp
, argv
, argc
);
13988 for (i
= 0; i
< argc
; i
++) {
13989 ListAppendElement(objPtr
, argv
[i
]);
13993 Jim_SetResult(interp
, objPtr
);
13997 char **Jim_GetEnviron(void)
13999 #if defined(HAVE__NSGETENVIRON)
14000 return *_NSGetEnviron();
14002 #if !defined(NO_ENVIRON_EXTERN)
14003 extern char **environ
;
14010 void Jim_SetEnviron(char **env
)
14012 #if defined(HAVE__NSGETENVIRON)
14013 *_NSGetEnviron() = env
;
14015 #if !defined(NO_ENVIRON_EXTERN)
14016 extern char **environ
;
14024 static int Jim_EnvCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14030 char **e
= Jim_GetEnviron();
14033 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14035 for (i
= 0; e
[i
]; i
++) {
14036 const char *equals
= strchr(e
[i
], '=');
14039 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, e
[i
],
14041 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, equals
+ 1, -1));
14045 Jim_SetResult(interp
, listObjPtr
);
14050 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?default?");
14053 key
= Jim_String(argv
[1]);
14057 Jim_SetResultFormatted(interp
, "environment variable \"%#s\" does not exist", argv
[1]);
14060 val
= Jim_String(argv
[2]);
14062 Jim_SetResult(interp
, Jim_NewStringObj(interp
, val
, -1));
14067 static int Jim_SourceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14072 Jim_WrongNumArgs(interp
, 1, argv
, "fileName");
14075 retval
= Jim_EvalFile(interp
, Jim_String(argv
[1]));
14076 if (retval
== JIM_RETURN
)
14082 static int Jim_LreverseCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14084 Jim_Obj
*revObjPtr
, **ele
;
14088 Jim_WrongNumArgs(interp
, 1, argv
, "list");
14091 JimListGetElements(interp
, argv
[1], &len
, &ele
);
14093 revObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14095 ListAppendElement(revObjPtr
, ele
[len
--]);
14096 Jim_SetResult(interp
, revObjPtr
);
14100 static int JimRangeLen(jim_wide start
, jim_wide end
, jim_wide step
)
14108 else if (step
> 0 && start
> end
)
14110 else if (step
< 0 && end
> start
)
14114 len
= -len
; /* abs(len) */
14116 step
= -step
; /* abs(step) */
14117 len
= 1 + ((len
- 1) / step
);
14118 /* We can truncate safely to INT_MAX, the range command
14119 * will always return an error for a such long range
14120 * because Tcl lists can't be so long. */
14123 return (int)((len
< 0) ? -1 : len
);
14127 static int Jim_RangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14129 jim_wide start
= 0, end
, step
= 1;
14133 if (argc
< 2 || argc
> 4) {
14134 Jim_WrongNumArgs(interp
, 1, argv
, "?start? end ?step?");
14138 if (Jim_GetWide(interp
, argv
[1], &end
) != JIM_OK
)
14142 if (Jim_GetWide(interp
, argv
[1], &start
) != JIM_OK
||
14143 Jim_GetWide(interp
, argv
[2], &end
) != JIM_OK
)
14145 if (argc
== 4 && Jim_GetWide(interp
, argv
[3], &step
) != JIM_OK
)
14148 if ((len
= JimRangeLen(start
, end
, step
)) == -1) {
14149 Jim_SetResultString(interp
, "Invalid (infinite?) range specified", -1);
14152 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
14153 for (i
= 0; i
< len
; i
++)
14154 ListAppendElement(objPtr
, Jim_NewIntObj(interp
, start
+ i
* step
));
14155 Jim_SetResult(interp
, objPtr
);
14160 static int Jim_RandCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14162 jim_wide min
= 0, max
= 0, len
, maxMul
;
14164 if (argc
< 1 || argc
> 3) {
14165 Jim_WrongNumArgs(interp
, 1, argv
, "?min? max");
14169 max
= JIM_WIDE_MAX
;
14170 } else if (argc
== 2) {
14171 if (Jim_GetWide(interp
, argv
[1], &max
) != JIM_OK
)
14173 } else if (argc
== 3) {
14174 if (Jim_GetWide(interp
, argv
[1], &min
) != JIM_OK
||
14175 Jim_GetWide(interp
, argv
[2], &max
) != JIM_OK
)
14180 Jim_SetResultString(interp
, "Invalid arguments (max < min)", -1);
14183 maxMul
= JIM_WIDE_MAX
- (len
? (JIM_WIDE_MAX
%len
) : 0);
14187 JimRandomBytes(interp
, &r
, sizeof(jim_wide
));
14188 if (r
< 0 || r
>= maxMul
) continue;
14189 r
= (len
== 0) ? 0 : r
%len
;
14190 Jim_SetResultInt(interp
, min
+r
);
14195 static const struct {
14197 Jim_CmdProc cmdProc
;
14198 } Jim_CoreCommandsTable
[] = {
14199 {"set", Jim_SetCoreCommand
},
14200 {"unset", Jim_UnsetCoreCommand
},
14201 {"puts", Jim_PutsCoreCommand
},
14202 {"+", Jim_AddCoreCommand
},
14203 {"*", Jim_MulCoreCommand
},
14204 {"-", Jim_SubCoreCommand
},
14205 {"/", Jim_DivCoreCommand
},
14206 {"incr", Jim_IncrCoreCommand
},
14207 {"while", Jim_WhileCoreCommand
},
14208 {"loop", Jim_LoopCoreCommand
},
14209 {"for", Jim_ForCoreCommand
},
14210 {"foreach", Jim_ForeachCoreCommand
},
14211 {"lmap", Jim_LmapCoreCommand
},
14212 {"if", Jim_IfCoreCommand
},
14213 {"switch", Jim_SwitchCoreCommand
},
14214 {"list", Jim_ListCoreCommand
},
14215 {"lindex", Jim_LindexCoreCommand
},
14216 {"lset", Jim_LsetCoreCommand
},
14217 {"lsearch", Jim_LsearchCoreCommand
},
14218 {"llength", Jim_LlengthCoreCommand
},
14219 {"lappend", Jim_LappendCoreCommand
},
14220 {"linsert", Jim_LinsertCoreCommand
},
14221 {"lreplace", Jim_LreplaceCoreCommand
},
14222 {"lsort", Jim_LsortCoreCommand
},
14223 {"append", Jim_AppendCoreCommand
},
14224 {"debug", Jim_DebugCoreCommand
},
14225 {"eval", Jim_EvalCoreCommand
},
14226 {"uplevel", Jim_UplevelCoreCommand
},
14227 {"expr", Jim_ExprCoreCommand
},
14228 {"break", Jim_BreakCoreCommand
},
14229 {"continue", Jim_ContinueCoreCommand
},
14230 {"proc", Jim_ProcCoreCommand
},
14231 {"concat", Jim_ConcatCoreCommand
},
14232 {"return", Jim_ReturnCoreCommand
},
14233 {"upvar", Jim_UpvarCoreCommand
},
14234 {"global", Jim_GlobalCoreCommand
},
14235 {"string", Jim_StringCoreCommand
},
14236 {"time", Jim_TimeCoreCommand
},
14237 {"exit", Jim_ExitCoreCommand
},
14238 {"catch", Jim_CatchCoreCommand
},
14239 #ifdef JIM_REFERENCES
14240 {"ref", Jim_RefCoreCommand
},
14241 {"getref", Jim_GetrefCoreCommand
},
14242 {"setref", Jim_SetrefCoreCommand
},
14243 {"finalize", Jim_FinalizeCoreCommand
},
14244 {"collect", Jim_CollectCoreCommand
},
14246 {"rename", Jim_RenameCoreCommand
},
14247 {"dict", Jim_DictCoreCommand
},
14248 {"subst", Jim_SubstCoreCommand
},
14249 {"info", Jim_InfoCoreCommand
},
14250 {"exists", Jim_ExistsCoreCommand
},
14251 {"split", Jim_SplitCoreCommand
},
14252 {"join", Jim_JoinCoreCommand
},
14253 {"format", Jim_FormatCoreCommand
},
14254 {"scan", Jim_ScanCoreCommand
},
14255 {"error", Jim_ErrorCoreCommand
},
14256 {"lrange", Jim_LrangeCoreCommand
},
14257 {"lrepeat", Jim_LrepeatCoreCommand
},
14258 {"env", Jim_EnvCoreCommand
},
14259 {"source", Jim_SourceCoreCommand
},
14260 {"lreverse", Jim_LreverseCoreCommand
},
14261 {"range", Jim_RangeCoreCommand
},
14262 {"rand", Jim_RandCoreCommand
},
14263 {"tailcall", Jim_TailcallCoreCommand
},
14264 {"local", Jim_LocalCoreCommand
},
14265 {"upcall", Jim_UpcallCoreCommand
},
14269 void Jim_RegisterCoreCommands(Jim_Interp
*interp
)
14273 while (Jim_CoreCommandsTable
[i
].name
!= NULL
) {
14274 Jim_CreateCommand(interp
,
14275 Jim_CoreCommandsTable
[i
].name
, Jim_CoreCommandsTable
[i
].cmdProc
, NULL
, NULL
);
14280 /* -----------------------------------------------------------------------------
14281 * Interactive prompt
14282 * ---------------------------------------------------------------------------*/
14283 void Jim_MakeErrorMessage(Jim_Interp
*interp
)
14287 argv
[0] = Jim_NewStringObj(interp
, "errorInfo", -1);
14288 argv
[1] = interp
->result
;
14290 Jim_EvalObjVector(interp
, 2, argv
);
14293 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
14294 const char *prefix
, const char *const *tablePtr
, const char *name
)
14297 char **tablePtrSorted
;
14300 for (count
= 0; tablePtr
[count
]; count
++) {
14303 if (name
== NULL
) {
14307 Jim_SetResultFormatted(interp
, "%s%s \"%s\": must be ", badtype
, name
, arg
);
14308 tablePtrSorted
= Jim_Alloc(sizeof(char *) * count
);
14309 memcpy(tablePtrSorted
, tablePtr
, sizeof(char *) * count
);
14310 qsort(tablePtrSorted
, count
, sizeof(char *), qsortCompareStringPointers
);
14311 for (i
= 0; i
< count
; i
++) {
14312 if (i
+ 1 == count
&& count
> 1) {
14313 Jim_AppendString(interp
, Jim_GetResult(interp
), "or ", -1);
14315 Jim_AppendStrings(interp
, Jim_GetResult(interp
), prefix
, tablePtrSorted
[i
], NULL
);
14316 if (i
+ 1 != count
) {
14317 Jim_AppendString(interp
, Jim_GetResult(interp
), ", ", -1);
14320 Jim_Free(tablePtrSorted
);
14323 int Jim_GetEnum(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
14324 const char *const *tablePtr
, int *indexPtr
, const char *name
, int flags
)
14326 const char *bad
= "bad ";
14327 const char *const *entryPtr
= NULL
;
14331 const char *arg
= Jim_GetString(objPtr
, &arglen
);
14335 for (entryPtr
= tablePtr
, i
= 0; *entryPtr
!= NULL
; entryPtr
++, i
++) {
14336 if (Jim_CompareStringImmediate(interp
, objPtr
, *entryPtr
)) {
14337 /* Found an exact match */
14341 if (flags
& JIM_ENUM_ABBREV
) {
14342 /* Accept an unambiguous abbreviation.
14343 * Note that '-' doesnt' consitute a valid abbreviation
14345 if (strncmp(arg
, *entryPtr
, arglen
) == 0) {
14346 if (*arg
== '-' && arglen
== 1) {
14350 bad
= "ambiguous ";
14358 /* If we had an unambiguous partial match */
14365 if (flags
& JIM_ERRMSG
) {
14366 JimSetFailedEnumResult(interp
, arg
, bad
, "", tablePtr
, name
);
14371 int Jim_FindByName(const char *name
, const char * const array
[], size_t len
)
14375 for (i
= 0; i
< (int)len
; i
++) {
14376 if (array
[i
] && strcmp(array
[i
], name
) == 0) {
14383 int Jim_IsDict(Jim_Obj
*objPtr
)
14385 return objPtr
->typePtr
== &dictObjType
;
14388 int Jim_IsList(Jim_Obj
*objPtr
)
14390 return objPtr
->typePtr
== &listObjType
;
14394 * Very simple printf-like formatting, designed for error messages.
14396 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14397 * The resulting string is created and set as the result.
14399 * Each '%s' should correspond to a regular string parameter.
14400 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14401 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14403 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14405 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14407 void Jim_SetResultFormatted(Jim_Interp
*interp
, const char *format
, ...)
14409 /* Initial space needed */
14410 int len
= strlen(format
);
14413 const char *params
[5];
14418 va_start(args
, format
);
14420 for (i
= 0; i
< len
&& n
< 5; i
++) {
14423 if (strncmp(format
+ i
, "%s", 2) == 0) {
14424 params
[n
] = va_arg(args
, char *);
14426 l
= strlen(params
[n
]);
14428 else if (strncmp(format
+ i
, "%#s", 3) == 0) {
14429 Jim_Obj
*objPtr
= va_arg(args
, Jim_Obj
*);
14431 params
[n
] = Jim_GetString(objPtr
, &l
);
14434 if (format
[i
] == '%') {
14444 buf
= Jim_Alloc(len
+ 1);
14445 len
= snprintf(buf
, len
+ 1, format
, params
[0], params
[1], params
[2], params
[3], params
[4]);
14447 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
14451 #ifndef jim_ext_package
14452 int Jim_PackageProvide(Jim_Interp
*interp
, const char *name
, const char *ver
, int flags
)
14457 #ifndef jim_ext_aio
14458 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*fhObj
)
14460 Jim_SetResultString(interp
, "aio not enabled", -1);
14467 * Local Variables: ***
14468 * c-basic-offset: 4 ***