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_SUBEXPR_COMMA 13
1109 #define JIM_TT_EXPR_INT 14
1110 #define JIM_TT_EXPR_DOUBLE 15
1112 #define JIM_TT_EXPRSUGAR 16 /* $(expression) */
1114 /* Operator token types start here */
1115 #define JIM_TT_EXPR_OP 20
1117 #define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
1120 #define JIM_PS_DEF 0 /* Default state */
1121 #define JIM_PS_QUOTE 1 /* Inside "" */
1122 #define JIM_PS_DICTSUGAR 2 /* Tokenising abc(def) into 4 separate tokens */
1124 /* Parser context structure. The same context is used both to parse
1125 * Tcl scripts and lists. */
1128 const char *p
; /* Pointer to the point of the program we are parsing */
1129 int len
; /* Remaining length */
1130 int linenr
; /* Current line number */
1132 const char *tend
; /* Returned token is at tstart-tend in 'prg'. */
1133 int tline
; /* Line number of the returned token */
1134 int tt
; /* Token type */
1135 int eof
; /* Non zero if EOF condition is true. */
1136 int state
; /* Parser state */
1137 int comment
; /* Non zero if the next chars may be a comment. */
1138 char missing
; /* At end of parse, ' ' if complete, '{' if braces incomplete, '"' if quotes incomplete */
1139 int missingline
; /* Line number starting the missing token */
1143 * Results of missing quotes, braces, etc. from parsing.
1145 struct JimParseResult
{
1146 char missing
; /* From JimParserCtx.missing */
1147 int line
; /* From JimParserCtx.missingline */
1150 static int JimParseScript(struct JimParserCtx
*pc
);
1151 static int JimParseSep(struct JimParserCtx
*pc
);
1152 static int JimParseEol(struct JimParserCtx
*pc
);
1153 static int JimParseCmd(struct JimParserCtx
*pc
);
1154 static int JimParseQuote(struct JimParserCtx
*pc
);
1155 static int JimParseVar(struct JimParserCtx
*pc
);
1156 static int JimParseBrace(struct JimParserCtx
*pc
);
1157 static int JimParseStr(struct JimParserCtx
*pc
);
1158 static int JimParseComment(struct JimParserCtx
*pc
);
1159 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1160 static int JimParseSubQuote(struct JimParserCtx
*pc
);
1161 static void JimParseSubCmd(struct JimParserCtx
*pc
);
1162 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
);
1164 /* Initialize a parser context.
1165 * 'prg' is a pointer to the program text, linenr is the line
1166 * number of the first line contained in the program. */
1167 static void JimParserInit(struct JimParserCtx
*pc
, const char *prg
, int len
, int linenr
)
1174 pc
->tt
= JIM_TT_NONE
;
1176 pc
->state
= JIM_PS_DEF
;
1177 pc
->linenr
= linenr
;
1180 pc
->missingline
= linenr
;
1183 static int JimParseScript(struct JimParserCtx
*pc
)
1185 while (1) { /* the while is used to reiterate with continue if needed */
1188 pc
->tend
= pc
->p
- 1;
1189 pc
->tline
= pc
->linenr
;
1190 pc
->tt
= JIM_TT_EOL
;
1196 if (*(pc
->p
+ 1) == '\n' && pc
->state
== JIM_PS_DEF
) {
1197 return JimParseSep(pc
);
1201 return JimParseStr(pc
);
1207 if (pc
->state
== JIM_PS_DEF
)
1208 return JimParseSep(pc
);
1211 return JimParseStr(pc
);
1217 if (pc
->state
== JIM_PS_DEF
)
1218 return JimParseEol(pc
);
1220 return JimParseStr(pc
);
1224 return JimParseCmd(pc
);
1228 if (JimParseVar(pc
) == JIM_ERR
) {
1229 pc
->tstart
= pc
->tend
= pc
->p
++;
1231 pc
->tline
= pc
->linenr
;
1232 pc
->tt
= JIM_TT_STR
;
1240 JimParseComment(pc
);
1244 return JimParseStr(pc
);
1248 return JimParseStr(pc
);
1255 static int JimParseSep(struct JimParserCtx
*pc
)
1258 pc
->tline
= pc
->linenr
;
1259 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' ||
1260 (*pc
->p
== '\\' && *(pc
->p
+ 1) == '\n')) {
1261 if (*pc
->p
== '\\') {
1269 pc
->tend
= pc
->p
- 1;
1270 pc
->tt
= JIM_TT_SEP
;
1274 static int JimParseEol(struct JimParserCtx
*pc
)
1277 pc
->tline
= pc
->linenr
;
1278 while (*pc
->p
== ' ' || *pc
->p
== '\n' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== ';') {
1284 pc
->tend
= pc
->p
- 1;
1285 pc
->tt
= JIM_TT_EOL
;
1290 ** Here are the rules for parsing:
1291 ** {braced expression}
1292 ** - Count open and closing braces
1293 ** - Backslash escapes meaning of braces
1295 ** "quoted expression"
1296 ** - First double quote at start of word terminates the expression
1297 ** - Backslash escapes quote and bracket
1298 ** - [commands brackets] are counted/nested
1299 ** - command rules apply within [brackets], not quoting rules (i.e. quotes have their own rules)
1301 ** [command expression]
1302 ** - Count open and closing brackets
1303 ** - Backslash escapes quote, bracket and brace
1304 ** - [commands brackets] are counted/nested
1305 ** - "quoted expressions" are parsed according to quoting rules
1306 ** - {braced expressions} are parsed according to brace rules
1308 ** For everything, backslash escapes the next char, newline increments current line
1312 * Parses a braced expression starting at pc->p.
1314 * Positions the parser at the end of the braced expression,
1315 * sets pc->tend and possibly pc->missing.
1317 static void JimParseSubBrace(struct JimParserCtx
*pc
)
1321 /* Skip the brace */
1328 if (*++pc
->p
== '\n') {
1341 pc
->tend
= pc
->p
- 1;
1356 pc
->missingline
= pc
->tline
;
1357 pc
->tend
= pc
->p
- 1;
1361 * Parses a quoted expression starting at pc->p.
1363 * Positions the parser at the end of the quoted expression,
1364 * sets pc->tend and possibly pc->missing.
1366 * Returns the type of the token of the string,
1367 * either JIM_TT_ESC (if it contains values which need to be [subst]ed)
1370 static int JimParseSubQuote(struct JimParserCtx
*pc
)
1372 int tt
= JIM_TT_STR
;
1373 int line
= pc
->tline
;
1375 /* Skip the quote */
1382 if (*++pc
->p
== '\n') {
1391 pc
->tend
= pc
->p
- 1;
1413 pc
->missingline
= line
;
1414 pc
->tend
= pc
->p
- 1;
1419 * Parses a [command] expression starting at pc->p.
1421 * Positions the parser at the end of the command expression,
1422 * sets pc->tend and possibly pc->missing.
1424 static void JimParseSubCmd(struct JimParserCtx
*pc
)
1427 int startofword
= 1;
1428 int line
= pc
->tline
;
1430 /* Skip the bracket */
1437 if (*++pc
->p
== '\n') {
1450 pc
->tend
= pc
->p
- 1;
1459 JimParseSubQuote(pc
);
1465 JimParseSubBrace(pc
);
1473 startofword
= isspace(UCHAR(*pc
->p
));
1478 pc
->missingline
= line
;
1479 pc
->tend
= pc
->p
- 1;
1482 static int JimParseBrace(struct JimParserCtx
*pc
)
1484 pc
->tstart
= pc
->p
+ 1;
1485 pc
->tline
= pc
->linenr
;
1486 pc
->tt
= JIM_TT_STR
;
1487 JimParseSubBrace(pc
);
1491 static int JimParseCmd(struct JimParserCtx
*pc
)
1493 pc
->tstart
= pc
->p
+ 1;
1494 pc
->tline
= pc
->linenr
;
1495 pc
->tt
= JIM_TT_CMD
;
1500 static int JimParseQuote(struct JimParserCtx
*pc
)
1502 pc
->tstart
= pc
->p
+ 1;
1503 pc
->tline
= pc
->linenr
;
1504 pc
->tt
= JimParseSubQuote(pc
);
1508 static int JimParseVar(struct JimParserCtx
*pc
)
1514 #ifdef EXPRSUGAR_BRACKET
1515 if (*pc
->p
== '[') {
1516 /* Parse $[...] expr shorthand syntax */
1518 pc
->tt
= JIM_TT_EXPRSUGAR
;
1524 pc
->tt
= JIM_TT_VAR
;
1525 pc
->tline
= pc
->linenr
;
1527 if (*pc
->p
== '{') {
1528 pc
->tstart
= ++pc
->p
;
1531 while (pc
->len
&& *pc
->p
!= '}') {
1532 if (*pc
->p
== '\n') {
1538 pc
->tend
= pc
->p
- 1;
1546 /* Skip double colon, but not single colon! */
1547 if (pc
->p
[0] == ':' && pc
->p
[1] == ':') {
1552 if (isalnum(UCHAR(*pc
->p
)) || *pc
->p
== '_') {
1559 /* Parse [dict get] syntax sugar. */
1560 if (*pc
->p
== '(') {
1562 const char *paren
= NULL
;
1564 pc
->tt
= JIM_TT_DICTSUGAR
;
1566 while (count
&& pc
->len
) {
1569 if (*pc
->p
== '\\' && pc
->len
>= 1) {
1573 else if (*pc
->p
== '(') {
1576 else if (*pc
->p
== ')') {
1586 /* Did not find a matching paren. Back up */
1588 pc
->len
+= (pc
->p
- paren
);
1591 #ifndef EXPRSUGAR_BRACKET
1592 if (*pc
->tstart
== '(') {
1593 pc
->tt
= JIM_TT_EXPRSUGAR
;
1597 pc
->tend
= pc
->p
- 1;
1599 /* Check if we parsed just the '$' character.
1600 * That's not a variable so an error is returned
1601 * to tell the state machine to consider this '$' just
1603 if (pc
->tstart
== pc
->p
) {
1611 static int JimParseStr(struct JimParserCtx
*pc
)
1613 int newword
= (pc
->tt
== JIM_TT_SEP
|| pc
->tt
== JIM_TT_EOL
||
1614 pc
->tt
== JIM_TT_NONE
|| pc
->tt
== JIM_TT_STR
);
1615 if (newword
&& *pc
->p
== '{') {
1616 return JimParseBrace(pc
);
1618 else if (newword
&& *pc
->p
== '"') {
1619 pc
->state
= JIM_PS_QUOTE
;
1622 /* In case the end quote is missing */
1623 pc
->missingline
= pc
->tline
;
1626 pc
->tline
= pc
->linenr
;
1629 if (pc
->state
== JIM_PS_QUOTE
) {
1632 pc
->tend
= pc
->p
- 1;
1633 pc
->tt
= JIM_TT_ESC
;
1638 if (pc
->state
== JIM_PS_DEF
&& *(pc
->p
+ 1) == '\n') {
1639 pc
->tend
= pc
->p
- 1;
1640 pc
->tt
= JIM_TT_ESC
;
1644 if (*(pc
->p
+ 1) == '\n') {
1652 /* If the following token is not '$' just keep going */
1653 if (pc
->len
> 1 && pc
->p
[1] != '$') {
1657 /* Only need a separate ')' token if the previous was a var */
1658 if (*pc
->p
== '(' || pc
->tt
== JIM_TT_VAR
) {
1659 if (pc
->p
== pc
->tstart
) {
1660 /* At the start of the token, so just return this char */
1664 pc
->tend
= pc
->p
- 1;
1665 pc
->tt
= JIM_TT_ESC
;
1672 pc
->tend
= pc
->p
- 1;
1673 pc
->tt
= JIM_TT_ESC
;
1680 if (pc
->state
== JIM_PS_DEF
) {
1681 pc
->tend
= pc
->p
- 1;
1682 pc
->tt
= JIM_TT_ESC
;
1685 else if (*pc
->p
== '\n') {
1690 if (pc
->state
== JIM_PS_QUOTE
) {
1691 pc
->tend
= pc
->p
- 1;
1692 pc
->tt
= JIM_TT_ESC
;
1695 pc
->state
= JIM_PS_DEF
;
1703 return JIM_OK
; /* unreached */
1706 static int JimParseComment(struct JimParserCtx
*pc
)
1709 if (*pc
->p
== '\n') {
1711 if (*(pc
->p
- 1) != '\\') {
1723 /* xdigitval and odigitval are helper functions for JimEscape() */
1724 static int xdigitval(int c
)
1726 if (c
>= '0' && c
<= '9')
1728 if (c
>= 'a' && c
<= 'f')
1729 return c
- 'a' + 10;
1730 if (c
>= 'A' && c
<= 'F')
1731 return c
- 'A' + 10;
1735 static int odigitval(int c
)
1737 if (c
>= '0' && c
<= '7')
1742 /* Perform Tcl escape substitution of 's', storing the result
1743 * string into 'dest'. The escaped string is guaranteed to
1744 * be the same length or shorted than the source string.
1745 * Slen is the length of the string at 's', if it's -1 the string
1746 * length will be calculated by the function.
1748 * The function returns the length of the resulting string. */
1749 static int JimEscape(char *dest
, const char *s
, int slen
)
1757 for (i
= 0; i
< slen
; i
++) {
1787 /* A unicode or hex sequence.
1788 * \u Expect 1-4 hex chars and convert to utf-8.
1789 * \x Expect 1-2 hex chars and convert to hex.
1790 * An invalid sequence means simply the escaped char.
1798 for (k
= 0; k
< (s
[i
] == 'u' ? 4 : 2); k
++) {
1799 int c
= xdigitval(s
[i
+ k
+ 1]);
1803 val
= (val
<< 4) | c
;
1806 /* Got a valid sequence, so convert */
1808 p
+= utf8_fromunicode(p
, val
);
1816 /* Not a valid codepoint, just an escaped char */
1829 /* Replace all spaces and tabs after backslash newline with a single space*/
1833 } while (s
[i
+ 1] == ' ' || s
[i
+ 1] == '\t');
1846 int c
= odigitval(s
[i
+ 1]);
1849 c
= odigitval(s
[i
+ 2]);
1855 val
= (val
* 8) + c
;
1856 c
= odigitval(s
[i
+ 3]);
1862 val
= (val
* 8) + c
;
1883 /* Returns a dynamically allocated copy of the current token in the
1884 * parser context. The function performs conversion of escapes if
1885 * the token is of type JIM_TT_ESC.
1887 * Note that after the conversion, tokens that are grouped with
1888 * braces in the source code, are always recognizable from the
1889 * identical string obtained in a different way from the type.
1891 * For example the string:
1895 * will return as first token "*", of type JIM_TT_STR
1901 * will return as first token "*", of type JIM_TT_ESC
1903 static Jim_Obj
*JimParserGetTokenObj(Jim_Interp
*interp
, struct JimParserCtx
*pc
)
1905 const char *start
, *end
;
1913 token
= Jim_Alloc(1);
1917 len
= (end
- start
) + 1;
1918 token
= Jim_Alloc(len
+ 1);
1919 if (pc
->tt
!= JIM_TT_ESC
) {
1920 /* No escape conversion needed? Just copy it. */
1921 memcpy(token
, start
, len
);
1925 /* Else convert the escape chars. */
1926 len
= JimEscape(token
, start
, len
);
1930 return Jim_NewStringObjNoAlloc(interp
, token
, len
);
1933 /* Parses the given string to determine if it represents a complete script.
1935 * This is useful for interactive shells implementation, for [info complete].
1937 * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
1938 * '{' on scripts incomplete missing one or more '}' to be balanced.
1939 * '[' on scripts incomplete missing one or more ']' to be balanced.
1940 * '"' on scripts incomplete missing a '"' char.
1942 * If the script is complete, 1 is returned, otherwise 0.
1944 int Jim_ScriptIsComplete(const char *s
, int len
, char *stateCharPtr
)
1946 struct JimParserCtx parser
;
1948 JimParserInit(&parser
, s
, len
, 1);
1949 while (!parser
.eof
) {
1950 JimParseScript(&parser
);
1953 *stateCharPtr
= parser
.missing
;
1955 return parser
.missing
== ' ';
1958 /* -----------------------------------------------------------------------------
1960 * ---------------------------------------------------------------------------*/
1961 static int JimParseListSep(struct JimParserCtx
*pc
);
1962 static int JimParseListStr(struct JimParserCtx
*pc
);
1963 static int JimParseListQuote(struct JimParserCtx
*pc
);
1965 static int JimParseList(struct JimParserCtx
*pc
)
1972 return JimParseListSep(pc
);
1975 return JimParseListQuote(pc
);
1978 return JimParseBrace(pc
);
1982 return JimParseListStr(pc
);
1987 pc
->tstart
= pc
->tend
= pc
->p
;
1988 pc
->tline
= pc
->linenr
;
1989 pc
->tt
= JIM_TT_EOL
;
1994 static int JimParseListSep(struct JimParserCtx
*pc
)
1997 pc
->tline
= pc
->linenr
;
1998 while (*pc
->p
== ' ' || *pc
->p
== '\t' || *pc
->p
== '\r' || *pc
->p
== '\n') {
1999 if (*pc
->p
== '\n') {
2005 pc
->tend
= pc
->p
- 1;
2006 pc
->tt
= JIM_TT_SEP
;
2010 static int JimParseListQuote(struct JimParserCtx
*pc
)
2016 pc
->tline
= pc
->linenr
;
2017 pc
->tt
= JIM_TT_STR
;
2022 pc
->tt
= JIM_TT_ESC
;
2023 if (--pc
->len
== 0) {
2024 /* Trailing backslash */
2034 pc
->tend
= pc
->p
- 1;
2043 pc
->tend
= pc
->p
- 1;
2047 static int JimParseListStr(struct JimParserCtx
*pc
)
2050 pc
->tline
= pc
->linenr
;
2051 pc
->tt
= JIM_TT_STR
;
2056 if (--pc
->len
== 0) {
2057 /* Trailing backslash */
2061 pc
->tt
= JIM_TT_ESC
;
2068 pc
->tend
= pc
->p
- 1;
2074 pc
->tend
= pc
->p
- 1;
2078 /* -----------------------------------------------------------------------------
2079 * Jim_Obj related functions
2080 * ---------------------------------------------------------------------------*/
2082 /* Return a new initialized object. */
2083 Jim_Obj
*Jim_NewObj(Jim_Interp
*interp
)
2087 /* -- Check if there are objects in the free list -- */
2088 if (interp
->freeList
!= NULL
) {
2089 /* -- Unlink the object from the free list -- */
2090 objPtr
= interp
->freeList
;
2091 interp
->freeList
= objPtr
->nextObjPtr
;
2094 /* -- No ready to use objects: allocate a new one -- */
2095 objPtr
= Jim_Alloc(sizeof(*objPtr
));
2098 /* Object is returned with refCount of 0. Every
2099 * kind of GC implemented should take care to don't try
2100 * to scan objects with refCount == 0. */
2101 objPtr
->refCount
= 0;
2102 /* All the other fields are left not initialized to save time.
2103 * The caller will probably want to set them to the right
2106 /* -- Put the object into the live list -- */
2107 objPtr
->prevObjPtr
= NULL
;
2108 objPtr
->nextObjPtr
= interp
->liveList
;
2109 if (interp
->liveList
)
2110 interp
->liveList
->prevObjPtr
= objPtr
;
2111 interp
->liveList
= objPtr
;
2116 /* Free an object. Actually objects are never freed, but
2117 * just moved to the free objects list, where they will be
2118 * reused by Jim_NewObj(). */
2119 void Jim_FreeObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2121 /* Check if the object was already freed, panic. */
2122 JimPanic((objPtr
->refCount
!= 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr
,
2123 objPtr
->refCount
, objPtr
->typePtr
? objPtr
->typePtr
->name
: "<none>"));
2125 /* Free the internal representation */
2126 Jim_FreeIntRep(interp
, objPtr
);
2127 /* Free the string representation */
2128 if (objPtr
->bytes
!= NULL
) {
2129 if (objPtr
->bytes
!= JimEmptyStringRep
)
2130 Jim_Free(objPtr
->bytes
);
2132 /* Unlink the object from the live objects list */
2133 if (objPtr
->prevObjPtr
)
2134 objPtr
->prevObjPtr
->nextObjPtr
= objPtr
->nextObjPtr
;
2135 if (objPtr
->nextObjPtr
)
2136 objPtr
->nextObjPtr
->prevObjPtr
= objPtr
->prevObjPtr
;
2137 if (interp
->liveList
== objPtr
)
2138 interp
->liveList
= objPtr
->nextObjPtr
;
2139 /* Link the object into the free objects list */
2140 objPtr
->prevObjPtr
= NULL
;
2141 objPtr
->nextObjPtr
= interp
->freeList
;
2142 if (interp
->freeList
)
2143 interp
->freeList
->prevObjPtr
= objPtr
;
2144 interp
->freeList
= objPtr
;
2145 objPtr
->refCount
= -1;
2148 /* Invalidate the string representation of an object. */
2149 void Jim_InvalidateStringRep(Jim_Obj
*objPtr
)
2151 if (objPtr
->bytes
!= NULL
) {
2152 if (objPtr
->bytes
!= JimEmptyStringRep
)
2153 Jim_Free(objPtr
->bytes
);
2155 objPtr
->bytes
= NULL
;
2158 #define Jim_SetStringRep(o, b, l) \
2159 do { (o)->bytes = b; (o)->length = l; } while (0)
2161 /* Set the initial string representation for an object.
2162 * Does not try to free an old one. */
2163 void Jim_InitStringRep(Jim_Obj
*objPtr
, const char *bytes
, int length
)
2166 objPtr
->bytes
= JimEmptyStringRep
;
2170 objPtr
->bytes
= Jim_Alloc(length
+ 1);
2171 objPtr
->length
= length
;
2172 memcpy(objPtr
->bytes
, bytes
, length
);
2173 objPtr
->bytes
[length
] = '\0';
2177 /* Duplicate an object. The returned object has refcount = 0. */
2178 Jim_Obj
*Jim_DuplicateObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2182 dupPtr
= Jim_NewObj(interp
);
2183 if (objPtr
->bytes
== NULL
) {
2184 /* Object does not have a valid string representation. */
2185 dupPtr
->bytes
= NULL
;
2188 Jim_InitStringRep(dupPtr
, objPtr
->bytes
, objPtr
->length
);
2191 /* By default, the new object has the same type as the old object */
2192 dupPtr
->typePtr
= objPtr
->typePtr
;
2193 if (objPtr
->typePtr
!= NULL
) {
2194 if (objPtr
->typePtr
->dupIntRepProc
== NULL
) {
2195 dupPtr
->internalRep
= objPtr
->internalRep
;
2198 /* The dup proc may set a different type, e.g. NULL */
2199 objPtr
->typePtr
->dupIntRepProc(interp
, objPtr
, dupPtr
);
2205 /* Return the string representation for objPtr. If the object
2206 * string representation is invalid, calls the method to create
2207 * a new one starting from the internal representation of the object. */
2208 const char *Jim_GetString(Jim_Obj
*objPtr
, int *lenPtr
)
2210 if (objPtr
->bytes
== NULL
) {
2211 /* Invalid string repr. Generate it. */
2212 JimPanic((objPtr
->typePtr
->updateStringProc
== NULL
, "UpdateStringProc called against '%s' type.", objPtr
->typePtr
->name
));
2213 objPtr
->typePtr
->updateStringProc(objPtr
);
2216 *lenPtr
= objPtr
->length
;
2217 return objPtr
->bytes
;
2220 /* Just returns the length of the object's string rep */
2221 int Jim_Length(Jim_Obj
*objPtr
)
2225 Jim_GetString(objPtr
, &len
);
2229 static void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2230 static void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2232 static const Jim_ObjType dictSubstObjType
= {
2233 "dict-substitution",
2234 FreeDictSubstInternalRep
,
2235 DupDictSubstInternalRep
,
2240 static void FreeInterpolatedInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2242 Jim_DecrRefCount(interp
, (Jim_Obj
*)objPtr
->internalRep
.twoPtrValue
.ptr2
);
2245 static const Jim_ObjType interpolatedObjType
= {
2247 FreeInterpolatedInternalRep
,
2253 /* -----------------------------------------------------------------------------
2255 * ---------------------------------------------------------------------------*/
2256 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2257 static int SetStringFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
2259 static const Jim_ObjType stringObjType
= {
2262 DupStringInternalRep
,
2264 JIM_TYPE_REFERENCES
,
2267 static void DupStringInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2269 JIM_NOTUSED(interp
);
2271 /* This is a bit subtle: the only caller of this function
2272 * should be Jim_DuplicateObj(), that will copy the
2273 * string representaion. After the copy, the duplicated
2274 * object will not have more room in teh buffer than
2275 * srcPtr->length bytes. So we just set it to length. */
2276 dupPtr
->internalRep
.strValue
.maxLength
= srcPtr
->length
;
2278 dupPtr
->internalRep
.strValue
.charLength
= srcPtr
->internalRep
.strValue
.charLength
;
2281 static int SetStringFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2283 /* Get a fresh string representation. */
2284 (void)Jim_String(objPtr
);
2285 /* Free any other internal representation. */
2286 Jim_FreeIntRep(interp
, objPtr
);
2287 /* Set it as string, i.e. just set the maxLength field. */
2288 objPtr
->typePtr
= &stringObjType
;
2289 objPtr
->internalRep
.strValue
.maxLength
= objPtr
->length
;
2290 /* Don't know the utf-8 length yet */
2291 objPtr
->internalRep
.strValue
.charLength
= -1;
2296 * Returns the length of the object string in chars, not bytes.
2298 * These may be different for a utf-8 string.
2300 int Jim_Utf8Length(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2303 if (objPtr
->typePtr
!= &stringObjType
)
2304 SetStringFromAny(interp
, objPtr
);
2306 if (objPtr
->internalRep
.strValue
.charLength
< 0) {
2307 objPtr
->internalRep
.strValue
.charLength
= utf8_strlen(objPtr
->bytes
, objPtr
->length
);
2309 return objPtr
->internalRep
.strValue
.charLength
;
2311 return Jim_Length(objPtr
);
2315 /* len is in bytes -- see also Jim_NewStringObjUtf8() */
2316 Jim_Obj
*Jim_NewStringObj(Jim_Interp
*interp
, const char *s
, int len
)
2318 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2320 /* Need to find out how many bytes the string requires */
2323 /* Alloc/Set the string rep. */
2325 objPtr
->bytes
= JimEmptyStringRep
;
2329 objPtr
->bytes
= Jim_Alloc(len
+ 1);
2330 objPtr
->length
= len
;
2331 memcpy(objPtr
->bytes
, s
, len
);
2332 objPtr
->bytes
[len
] = '\0';
2335 /* No typePtr field for the vanilla string object. */
2336 objPtr
->typePtr
= NULL
;
2340 /* charlen is in characters -- see also Jim_NewStringObj() */
2341 Jim_Obj
*Jim_NewStringObjUtf8(Jim_Interp
*interp
, const char *s
, int charlen
)
2344 /* Need to find out how many bytes the string requires */
2345 int bytelen
= utf8_index(s
, charlen
);
2347 Jim_Obj
*objPtr
= Jim_NewStringObj(interp
, s
, bytelen
);
2349 /* Remember the utf8 length, so set the type */
2350 objPtr
->typePtr
= &stringObjType
;
2351 objPtr
->internalRep
.strValue
.maxLength
= bytelen
;
2352 objPtr
->internalRep
.strValue
.charLength
= charlen
;
2356 return Jim_NewStringObj(interp
, s
, charlen
);
2360 /* This version does not try to duplicate the 's' pointer, but
2361 * use it directly. */
2362 Jim_Obj
*Jim_NewStringObjNoAlloc(Jim_Interp
*interp
, char *s
, int len
)
2364 Jim_Obj
*objPtr
= Jim_NewObj(interp
);
2368 Jim_SetStringRep(objPtr
, s
, len
);
2369 objPtr
->typePtr
= NULL
;
2373 /* Low-level string append. Use it only against objects
2374 * of type "string". */
2375 static void StringAppendString(Jim_Obj
*objPtr
, const char *str
, int len
)
2381 needlen
= objPtr
->length
+ len
;
2382 if (objPtr
->internalRep
.strValue
.maxLength
< needlen
||
2383 objPtr
->internalRep
.strValue
.maxLength
== 0) {
2385 /* Inefficient to malloc() for less than 8 bytes */
2389 if (objPtr
->bytes
== JimEmptyStringRep
) {
2390 objPtr
->bytes
= Jim_Alloc(needlen
+ 1);
2393 objPtr
->bytes
= Jim_Realloc(objPtr
->bytes
, needlen
+ 1);
2395 objPtr
->internalRep
.strValue
.maxLength
= needlen
;
2397 memcpy(objPtr
->bytes
+ objPtr
->length
, str
, len
);
2398 objPtr
->bytes
[objPtr
->length
+ len
] = '\0';
2399 if (objPtr
->internalRep
.strValue
.charLength
>= 0) {
2400 /* Update the utf-8 char length */
2401 objPtr
->internalRep
.strValue
.charLength
+= utf8_strlen(objPtr
->bytes
+ objPtr
->length
, len
);
2403 objPtr
->length
+= len
;
2406 /* Higher level API to append strings to objects. */
2407 void Jim_AppendString(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
, int len
)
2409 JimPanic((Jim_IsShared(objPtr
), "Jim_AppendString called with shared object"));
2410 if (objPtr
->typePtr
!= &stringObjType
)
2411 SetStringFromAny(interp
, objPtr
);
2412 StringAppendString(objPtr
, str
, len
);
2415 void Jim_AppendObj(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*appendObjPtr
)
2420 str
= Jim_GetString(appendObjPtr
, &len
);
2421 Jim_AppendString(interp
, objPtr
, str
, len
);
2424 void Jim_AppendStrings(Jim_Interp
*interp
, Jim_Obj
*objPtr
, ...)
2428 if (objPtr
->typePtr
!= &stringObjType
)
2429 SetStringFromAny(interp
, objPtr
);
2430 va_start(ap
, objPtr
);
2432 char *s
= va_arg(ap
, char *);
2436 Jim_AppendString(interp
, objPtr
, s
, -1);
2441 int Jim_StringEqObj(Jim_Obj
*aObjPtr
, Jim_Obj
*bObjPtr
)
2443 const char *aStr
, *bStr
;
2446 if (aObjPtr
== bObjPtr
)
2448 aStr
= Jim_GetString(aObjPtr
, &aLen
);
2449 bStr
= Jim_GetString(bObjPtr
, &bLen
);
2452 return JimStringCompare(aStr
, aLen
, bStr
, bLen
) == 0;
2455 int Jim_StringMatchObj(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, Jim_Obj
*objPtr
, int nocase
)
2457 return JimStringMatch(interp
, patternObjPtr
, Jim_String(objPtr
), nocase
);
2460 int Jim_StringCompareObj(Jim_Interp
*interp
, Jim_Obj
*firstObjPtr
, Jim_Obj
*secondObjPtr
, int nocase
)
2462 const char *s1
, *s2
;
2465 s1
= Jim_GetString(firstObjPtr
, &l1
);
2466 s2
= Jim_GetString(secondObjPtr
, &l2
);
2469 return JimStringCompareNoCase(s1
, s2
, -1);
2471 return JimStringCompare(s1
, l1
, s2
, l2
);
2474 /* Convert a range, as returned by Jim_GetRange(), into
2475 * an absolute index into an object of the specified length.
2476 * This function may return negative values, or values
2477 * bigger or equal to the length of the list if the index
2478 * is out of range. */
2479 static int JimRelToAbsIndex(int len
, int idx
)
2486 /* Convert a pair of index as normalize by JimRelToAbsIndex(),
2487 * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
2488 * for implementation of commands like [string range] and [lrange].
2490 * The resulting range is guaranteed to address valid elements of
2492 static void JimRelToAbsRange(int len
, int first
, int last
,
2493 int *firstPtr
, int *lastPtr
, int *rangeLenPtr
)
2501 rangeLen
= last
- first
+ 1;
2508 rangeLen
-= (last
- (len
- 1));
2518 *rangeLenPtr
= rangeLen
;
2521 Jim_Obj
*Jim_StringByteRangeObj(Jim_Interp
*interp
,
2522 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2529 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2530 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2532 str
= Jim_GetString(strObjPtr
, &bytelen
);
2533 first
= JimRelToAbsIndex(bytelen
, first
);
2534 last
= JimRelToAbsIndex(bytelen
, last
);
2535 JimRelToAbsRange(bytelen
, first
, last
, &first
, &last
, &rangeLen
);
2536 if (first
== 0 && rangeLen
== bytelen
) {
2539 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2542 Jim_Obj
*Jim_StringRangeObj(Jim_Interp
*interp
,
2543 Jim_Obj
*strObjPtr
, Jim_Obj
*firstObjPtr
, Jim_Obj
*lastObjPtr
)
2551 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
2552 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
2554 str
= Jim_GetString(strObjPtr
, &bytelen
);
2555 len
= Jim_Utf8Length(interp
, strObjPtr
);
2556 first
= JimRelToAbsIndex(len
, first
);
2557 last
= JimRelToAbsIndex(len
, last
);
2558 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
2559 if (first
== 0 && rangeLen
== len
) {
2562 if (len
== bytelen
) {
2563 /* ASCII optimisation */
2564 return Jim_NewStringObj(interp
, str
+ first
, rangeLen
);
2566 return Jim_NewStringObjUtf8(interp
, str
+ utf8_index(str
, first
), rangeLen
);
2568 return Jim_StringByteRangeObj(interp
, strObjPtr
, firstObjPtr
, lastObjPtr
);
2572 static Jim_Obj
*JimStringToLower(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2578 if (strObjPtr
->typePtr
!= &stringObjType
) {
2579 SetStringFromAny(interp
, strObjPtr
);
2582 str
= Jim_GetString(strObjPtr
, &len
);
2584 buf
= p
= Jim_Alloc(len
+ 1);
2587 str
+= utf8_tounicode(str
, &c
);
2588 p
+= utf8_fromunicode(p
, utf8_lower(c
));
2591 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2594 static Jim_Obj
*JimStringToUpper(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
)
2600 if (strObjPtr
->typePtr
!= &stringObjType
) {
2601 SetStringFromAny(interp
, strObjPtr
);
2604 str
= Jim_GetString(strObjPtr
, &len
);
2606 buf
= p
= Jim_Alloc(len
+ 1);
2609 str
+= utf8_tounicode(str
, &c
);
2610 p
+= utf8_fromunicode(p
, utf8_upper(c
));
2613 return Jim_NewStringObjNoAlloc(interp
, buf
, len
);
2616 /* Similar to memchr() except searches a UTF-8 string 'str' of byte length 'len'
2617 * for unicode character 'c'.
2618 * Returns the position if found or NULL if not
2620 static const char *utf8_memchr(const char *str
, int len
, int c
)
2625 int n
= utf8_tounicode(str
, &sc
);
2634 return memchr(str
, c
, len
);
2639 * Searches for the first non-trim char in string (str, len)
2641 * If none is found, returns just past the last char.
2643 * Lengths are in bytes.
2645 static const char *JimFindTrimLeft(const char *str
, int len
, const char *trimchars
, int trimlen
)
2649 int n
= utf8_tounicode(str
, &c
);
2651 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2652 /* Not a trim char, so stop */
2662 * Searches backwards for a non-trim char in string (str, len).
2664 * Returns a pointer to just after the non-trim char, or NULL if not found.
2666 * Lengths are in bytes.
2668 static const char *JimFindTrimRight(const char *str
, int len
, const char *trimchars
, int trimlen
)
2674 int n
= utf8_prev_len(str
, len
);
2679 n
= utf8_tounicode(str
, &c
);
2681 if (utf8_memchr(trimchars
, trimlen
, c
) == NULL
) {
2689 static const char default_trim_chars
[] = " \t\n\r";
2690 /* sizeof() here includes the null byte */
2691 static int default_trim_chars_len
= sizeof(default_trim_chars
);
2693 static Jim_Obj
*JimStringTrimLeft(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2696 const char *str
= Jim_GetString(strObjPtr
, &len
);
2697 const char *trimchars
= default_trim_chars
;
2698 int trimcharslen
= default_trim_chars_len
;
2701 if (trimcharsObjPtr
) {
2702 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2705 newstr
= JimFindTrimLeft(str
, len
, trimchars
, trimcharslen
);
2706 if (newstr
== str
) {
2710 return Jim_NewStringObj(interp
, newstr
, len
- (newstr
- str
));
2713 static Jim_Obj
*JimStringTrimRight(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2716 const char *trimchars
= default_trim_chars
;
2717 int trimcharslen
= default_trim_chars_len
;
2718 const char *nontrim
;
2720 if (trimcharsObjPtr
) {
2721 trimchars
= Jim_GetString(trimcharsObjPtr
, &trimcharslen
);
2724 if (strObjPtr
->typePtr
!= &stringObjType
) {
2725 SetStringFromAny(interp
, strObjPtr
);
2727 len
= Jim_Length(strObjPtr
);
2728 nontrim
= JimFindTrimRight(strObjPtr
->bytes
, len
, trimchars
, trimcharslen
);
2730 if (nontrim
== NULL
) {
2731 /* All trim, so return a zero-length string */
2732 return Jim_NewEmptyStringObj(interp
);
2734 if (nontrim
== strObjPtr
->bytes
+ len
) {
2738 if (Jim_IsShared(strObjPtr
)) {
2739 strObjPtr
= Jim_NewStringObj(interp
, strObjPtr
->bytes
, (nontrim
- strObjPtr
->bytes
));
2742 /* Can modify this string in place */
2743 strObjPtr
->bytes
[nontrim
- strObjPtr
->bytes
] = 0;
2744 strObjPtr
->length
= (nontrim
- strObjPtr
->bytes
);
2750 static Jim_Obj
*JimStringTrim(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*trimcharsObjPtr
)
2752 /* First trim left. */
2753 Jim_Obj
*objPtr
= JimStringTrimLeft(interp
, strObjPtr
, trimcharsObjPtr
);
2755 /* Now trim right */
2756 strObjPtr
= JimStringTrimRight(interp
, objPtr
, trimcharsObjPtr
);
2758 if (objPtr
!= strObjPtr
) {
2759 /* Note that we don't want this object to be leaked */
2760 Jim_IncrRefCount(objPtr
);
2761 Jim_DecrRefCount(interp
, objPtr
);
2768 static int JimStringIs(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*strClass
, int strict
)
2770 static const char * const strclassnames
[] = {
2771 "integer", "alpha", "alnum", "ascii", "digit",
2772 "double", "lower", "upper", "space", "xdigit",
2773 "control", "print", "graph", "punct",
2777 STR_IS_INTEGER
, STR_IS_ALPHA
, STR_IS_ALNUM
, STR_IS_ASCII
, STR_IS_DIGIT
,
2778 STR_IS_DOUBLE
, STR_IS_LOWER
, STR_IS_UPPER
, STR_IS_SPACE
, STR_IS_XDIGIT
,
2779 STR_IS_CONTROL
, STR_IS_PRINT
, STR_IS_GRAPH
, STR_IS_PUNCT
2785 int (*isclassfunc
)(int c
) = NULL
;
2787 if (Jim_GetEnum(interp
, strClass
, strclassnames
, &strclass
, "class", JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
2791 str
= Jim_GetString(strObjPtr
, &len
);
2793 Jim_SetResultInt(interp
, !strict
);
2798 case STR_IS_INTEGER
:
2801 Jim_SetResultInt(interp
, JimGetWideNoErr(interp
, strObjPtr
, &w
) == JIM_OK
);
2808 Jim_SetResultInt(interp
, Jim_GetDouble(interp
, strObjPtr
, &d
) == JIM_OK
&& errno
!= ERANGE
);
2812 case STR_IS_ALPHA
: isclassfunc
= isalpha
; break;
2813 case STR_IS_ALNUM
: isclassfunc
= isalnum
; break;
2814 case STR_IS_ASCII
: isclassfunc
= isascii
; break;
2815 case STR_IS_DIGIT
: isclassfunc
= isdigit
; break;
2816 case STR_IS_LOWER
: isclassfunc
= islower
; break;
2817 case STR_IS_UPPER
: isclassfunc
= isupper
; break;
2818 case STR_IS_SPACE
: isclassfunc
= isspace
; break;
2819 case STR_IS_XDIGIT
: isclassfunc
= isxdigit
; break;
2820 case STR_IS_CONTROL
: isclassfunc
= iscntrl
; break;
2821 case STR_IS_PRINT
: isclassfunc
= isprint
; break;
2822 case STR_IS_GRAPH
: isclassfunc
= isgraph
; break;
2823 case STR_IS_PUNCT
: isclassfunc
= ispunct
; break;
2828 for (i
= 0; i
< len
; i
++) {
2829 if (!isclassfunc(str
[i
])) {
2830 Jim_SetResultInt(interp
, 0);
2834 Jim_SetResultInt(interp
, 1);
2838 /* -----------------------------------------------------------------------------
2839 * Compared String Object
2840 * ---------------------------------------------------------------------------*/
2842 /* This is strange object that allows to compare a C literal string
2843 * with a Jim object in very short time if the same comparison is done
2844 * multiple times. For example every time the [if] command is executed,
2845 * Jim has to check if a given argument is "else". This comparions if
2846 * the code has no errors are true most of the times, so we can cache
2847 * inside the object the pointer of the string of the last matching
2848 * comparison. Because most C compilers perform literal sharing,
2849 * so that: char *x = "foo", char *y = "foo", will lead to x == y,
2850 * this works pretty well even if comparisons are at different places
2851 * inside the C code. */
2853 static const Jim_ObjType comparedStringObjType
= {
2858 JIM_TYPE_REFERENCES
,
2861 /* The only way this object is exposed to the API is via the following
2862 * function. Returns true if the string and the object string repr.
2863 * are the same, otherwise zero is returned.
2865 * Note: this isn't binary safe, but it hardly needs to be.*/
2866 int Jim_CompareStringImmediate(Jim_Interp
*interp
, Jim_Obj
*objPtr
, const char *str
)
2868 if (objPtr
->typePtr
== &comparedStringObjType
&& objPtr
->internalRep
.ptr
== str
)
2871 const char *objStr
= Jim_String(objPtr
);
2873 if (strcmp(str
, objStr
) != 0)
2875 if (objPtr
->typePtr
!= &comparedStringObjType
) {
2876 Jim_FreeIntRep(interp
, objPtr
);
2877 objPtr
->typePtr
= &comparedStringObjType
;
2879 objPtr
->internalRep
.ptr
= (char *)str
; /*ATTENTION: const cast */
2884 static int qsortCompareStringPointers(const void *a
, const void *b
)
2886 char *const *sa
= (char *const *)a
;
2887 char *const *sb
= (char *const *)b
;
2889 return strcmp(*sa
, *sb
);
2893 /* -----------------------------------------------------------------------------
2896 * This object is just a string from the language point of view, but
2897 * in the internal representation it contains the filename and line number
2898 * where this given token was read. This information is used by
2899 * Jim_EvalObj() if the object passed happens to be of type "source".
2901 * This allows to propagate the information about line numbers and file
2902 * names and give error messages with absolute line numbers.
2904 * Note that this object uses shared strings for filenames, and the
2905 * pointer to the filename together with the line number is taken into
2906 * the space for the "inline" internal representation of the Jim_Object,
2907 * so there is almost memory zero-overhead.
2909 * Also the object will be converted to something else if the given
2910 * token it represents in the source file is not something to be
2911 * evaluated (not a script), and will be specialized in some other way,
2912 * so the time overhead is also null.
2913 * ---------------------------------------------------------------------------*/
2915 static void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2916 static void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2918 static const Jim_ObjType sourceObjType
= {
2920 FreeSourceInternalRep
,
2921 DupSourceInternalRep
,
2923 JIM_TYPE_REFERENCES
,
2926 void FreeSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
2928 Jim_DecrRefCount(interp
, objPtr
->internalRep
.sourceValue
.fileNameObj
);
2931 void DupSourceInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
2933 dupPtr
->internalRep
= srcPtr
->internalRep
;
2934 Jim_IncrRefCount(dupPtr
->internalRep
.sourceValue
.fileNameObj
);
2937 static void JimSetSourceInfo(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
2938 Jim_Obj
*fileNameObj
, int lineNumber
)
2940 JimPanic((Jim_IsShared(objPtr
), "JimSetSourceInfo called with shared object"));
2941 JimPanic((objPtr
->typePtr
!= NULL
, "JimSetSourceInfo called with typePtr != NULL"));
2942 Jim_IncrRefCount(fileNameObj
);
2943 objPtr
->internalRep
.sourceValue
.fileNameObj
= fileNameObj
;
2944 objPtr
->internalRep
.sourceValue
.lineNumber
= lineNumber
;
2945 objPtr
->typePtr
= &sourceObjType
;
2948 /* -----------------------------------------------------------------------------
2950 * ---------------------------------------------------------------------------*/
2952 static const Jim_ObjType scriptLineObjType
= {
2960 static Jim_Obj
*JimNewScriptLineObj(Jim_Interp
*interp
, int argc
, int line
)
2964 #ifdef DEBUG_SHOW_SCRIPT
2966 snprintf(buf
, sizeof(buf
), "line=%d, argc=%d", line
, argc
);
2967 objPtr
= Jim_NewStringObj(interp
, buf
, -1);
2969 objPtr
= Jim_NewEmptyStringObj(interp
);
2971 objPtr
->typePtr
= &scriptLineObjType
;
2972 objPtr
->internalRep
.scriptLineValue
.argc
= argc
;
2973 objPtr
->internalRep
.scriptLineValue
.line
= line
;
2978 #define JIM_CMDSTRUCT_EXPAND -1
2980 static void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
2981 static void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
2982 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
);
2984 static const Jim_ObjType scriptObjType
= {
2986 FreeScriptInternalRep
,
2987 DupScriptInternalRep
,
2989 JIM_TYPE_REFERENCES
,
2992 /* The ScriptToken structure represents every token into a scriptObj.
2993 * Every token contains an associated Jim_Obj that can be specialized
2994 * by commands operating on it. */
2995 typedef struct ScriptToken
3001 /* This is the script object internal representation. An array of
3002 * ScriptToken structures, including a pre-computed representation of the
3003 * command length and arguments.
3005 * For example the script:
3008 * set $i $x$y [foo]BAR
3010 * will produce a ScriptObj with the following Tokens:
3025 * "puts hello" has two args (LIN 2), composed of single tokens.
3026 * (Note that the WRD token is omitted for the common case of a single token.)
3028 * "set $i $x$y [foo]BAR" has four (LIN 4) args, the first word
3029 * has 1 token (ESC SET), and the last has two tokens (WRD 2 CMD foo ESC BAR)
3031 * The precomputation of the command structure makes Jim_Eval() faster,
3032 * and simpler because there aren't dynamic lengths / allocations.
3034 * -- {expand}/{*} handling --
3036 * Expand is handled in a special way.
3038 * If a "word" begins with {*}, the word token count is -ve.
3040 * For example the command:
3044 * Will produce the following cmdstruct array:
3051 * Note that the 'LIN' token also contains the source information for the
3052 * first word of the line for error reporting purposes
3054 * -- the substFlags field of the structure --
3056 * The scriptObj structure is used to represent both "script" objects
3057 * and "subst" objects. In the second case, the there are no LIN and WRD
3058 * tokens. Instead SEP and EOL tokens are added as-is.
3059 * In addition, the field 'substFlags' is used to represent the flags used to turn
3060 * the string into the internal representation used to perform the
3061 * substitution. If this flags are not what the application requires
3062 * the scriptObj is created again. For example the script:
3064 * subst -nocommands $string
3065 * subst -novariables $string
3067 * Will recreate the internal representation of the $string object
3070 typedef struct ScriptObj
3072 int len
; /* Length as number of tokens. */
3073 ScriptToken
*token
; /* Tokens array. */
3074 int substFlags
; /* flags used for the compilation of "subst" objects */
3075 int inUse
; /* Used to share a ScriptObj. Currently
3076 only used by Jim_EvalObj() as protection against
3077 shimmering of the currently evaluated object. */
3078 Jim_Obj
*fileNameObj
;
3079 int line
; /* Line number of the first line */
3082 void FreeScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3085 struct ScriptObj
*script
= (void *)objPtr
->internalRep
.ptr
;
3088 if (script
->inUse
!= 0)
3090 for (i
= 0; i
< script
->len
; i
++) {
3091 Jim_DecrRefCount(interp
, script
->token
[i
].objPtr
);
3093 Jim_Free(script
->token
);
3094 Jim_DecrRefCount(interp
, script
->fileNameObj
);
3098 void DupScriptInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
3100 JIM_NOTUSED(interp
);
3101 JIM_NOTUSED(srcPtr
);
3103 /* Just returns an simple string. */
3104 dupPtr
->typePtr
= NULL
;
3107 /* A simple parser token.
3108 * All the simple tokens for the script point into the same script string rep.
3112 const char *token
; /* Pointer to the start of the token */
3113 int len
; /* Length of this token */
3114 int type
; /* Token type */
3115 int line
; /* Line number */
3118 /* A list of parsed tokens representing a script.
3119 * Tokens are added to this list as the script is parsed.
3120 * It grows as needed.
3124 /* Start with a statically allocated list of tokens which will be expanded with realloc if needed */
3125 ParseToken
*list
; /* Array of tokens */
3126 int size
; /* Current size of the list */
3127 int count
; /* Number of entries used */
3128 ParseToken static_list
[20]; /* Small initial token space to avoid allocation */
3131 static void ScriptTokenListInit(ParseTokenList
*tokenlist
)
3133 tokenlist
->list
= tokenlist
->static_list
;
3134 tokenlist
->size
= sizeof(tokenlist
->static_list
) / sizeof(ParseToken
);
3135 tokenlist
->count
= 0;
3138 static void ScriptTokenListFree(ParseTokenList
*tokenlist
)
3140 if (tokenlist
->list
!= tokenlist
->static_list
) {
3141 Jim_Free(tokenlist
->list
);
3146 * Adds the new token to the tokenlist.
3147 * The token has the given length, type and line number.
3148 * The token list is resized as necessary.
3150 static void ScriptAddToken(ParseTokenList
*tokenlist
, const char *token
, int len
, int type
,
3155 if (tokenlist
->count
== tokenlist
->size
) {
3156 /* Resize the list */
3157 tokenlist
->size
*= 2;
3158 if (tokenlist
->list
!= tokenlist
->static_list
) {
3160 Jim_Realloc(tokenlist
->list
, tokenlist
->size
* sizeof(*tokenlist
->list
));
3163 /* The list needs to become allocated */
3164 tokenlist
->list
= Jim_Alloc(tokenlist
->size
* sizeof(*tokenlist
->list
));
3165 memcpy(tokenlist
->list
, tokenlist
->static_list
,
3166 tokenlist
->count
* sizeof(*tokenlist
->list
));
3169 t
= &tokenlist
->list
[tokenlist
->count
++];
3176 /* Counts the number of adjoining non-separator.
3178 * Returns -ve if the first token is the expansion
3179 * operator (in which case the count doesn't include
3182 static int JimCountWordTokens(ParseToken
*t
)
3187 /* Is the first word {*} or {expand}? */
3188 if (t
->type
== JIM_TT_STR
&& !TOKEN_IS_SEP(t
[1].type
)) {
3189 if ((t
->len
== 1 && *t
->token
== '*') || (t
->len
== 6 && strncmp(t
->token
, "expand", 6) == 0)) {
3190 /* Create an expand token */
3196 /* Now count non-separator words */
3197 while (!TOKEN_IS_SEP(t
->type
)) {
3202 return count
* expand
;
3206 * Create a script/subst object from the given token.
3208 static Jim_Obj
*JimMakeScriptObj(Jim_Interp
*interp
, const ParseToken
*t
)
3212 if (t
->type
== JIM_TT_ESC
&& memchr(t
->token
, '\\', t
->len
) != NULL
) {
3213 /* Convert the backlash escapes . */
3215 char *str
= Jim_Alloc(len
+ 1);
3216 len
= JimEscape(str
, t
->token
, len
);
3217 objPtr
= Jim_NewStringObjNoAlloc(interp
, str
, len
);
3220 /* REVIST: Strictly, JIM_TT_STR should replace <backslash><newline><whitespace>
3221 * with a single space. This is currently not done.
3223 objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
3229 * Takes a tokenlist and creates the allocated list of script tokens
3230 * in script->token, of length script->len.
3232 * Unnecessary tokens are discarded, and LINE and WORD tokens are inserted
3235 * Also sets script->line to the line number of the first token
3237 static void ScriptObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3238 ParseTokenList
*tokenlist
)
3241 struct ScriptToken
*token
;
3242 /* Number of tokens so far for the current command */
3244 /* This is the first token for the current command */
3245 ScriptToken
*linefirst
;
3249 #ifdef DEBUG_SHOW_SCRIPT_TOKENS
3250 printf("==== Tokens ====\n");
3251 for (i
= 0; i
< tokenlist
->count
; i
++) {
3252 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
->list
[i
].line
, jim_tt_name(tokenlist
->list
[i
].type
),
3253 tokenlist
->list
[i
].len
, tokenlist
->list
[i
].token
);
3257 /* May need up to one extra script token for each EOL in the worst case */
3258 count
= tokenlist
->count
;
3259 for (i
= 0; i
< tokenlist
->count
; i
++) {
3260 if (tokenlist
->list
[i
].type
== JIM_TT_EOL
) {
3264 linenr
= script
->line
= tokenlist
->list
[0].line
;
3266 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
3268 /* This is the first token for the current command */
3269 linefirst
= token
++;
3271 for (i
= 0; i
< tokenlist
->count
; ) {
3272 /* Look ahead to find out how many tokens make up the next word */
3275 /* Skip any leading separators */
3276 while (tokenlist
->list
[i
].type
== JIM_TT_SEP
) {
3280 wordtokens
= JimCountWordTokens(tokenlist
->list
+ i
);
3282 if (wordtokens
== 0) {
3283 /* None, so at end of line */
3285 linefirst
->type
= JIM_TT_LINE
;
3286 linefirst
->objPtr
= JimNewScriptLineObj(interp
, lineargs
, linenr
);
3287 Jim_IncrRefCount(linefirst
->objPtr
);
3289 /* Reset for new line */
3291 linefirst
= token
++;
3296 else if (wordtokens
!= 1) {
3297 /* More than 1, or {expand}, so insert a WORD token */
3298 token
->type
= JIM_TT_WORD
;
3299 token
->objPtr
= Jim_NewIntObj(interp
, wordtokens
);
3300 Jim_IncrRefCount(token
->objPtr
);
3302 if (wordtokens
< 0) {
3303 /* Skip the expand token */
3305 wordtokens
= -wordtokens
- 1;
3310 if (lineargs
== 0) {
3311 /* First real token on the line, so record the line number */
3312 linenr
= tokenlist
->list
[i
].line
;
3316 /* Add each non-separator word token to the line */
3317 while (wordtokens
--) {
3318 const ParseToken
*t
= &tokenlist
->list
[i
++];
3320 token
->type
= t
->type
;
3321 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3322 Jim_IncrRefCount(token
->objPtr
);
3324 /* Every object is initially a string, but the
3325 * internal type may be specialized during execution of the
3327 JimSetSourceInfo(interp
, token
->objPtr
, script
->fileNameObj
, t
->line
);
3332 if (lineargs
== 0) {
3336 script
->len
= token
- script
->token
;
3338 assert(script
->len
< count
);
3340 #ifdef DEBUG_SHOW_SCRIPT
3341 printf("==== Script (%s) ====\n", Jim_String(script
->fileNameObj
));
3342 for (i
= 0; i
< script
->len
; i
++) {
3343 const ScriptToken
*t
= &script
->token
[i
];
3344 printf("[%2d] %s %s\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
3351 * Similar to ScriptObjAddTokens(), but for subst objects.
3353 static void SubstObjAddTokens(Jim_Interp
*interp
, struct ScriptObj
*script
,
3354 ParseTokenList
*tokenlist
)
3357 struct ScriptToken
*token
;
3359 token
= script
->token
= Jim_Alloc(sizeof(ScriptToken
) * tokenlist
->count
);
3361 for (i
= 0; i
< tokenlist
->count
; i
++) {
3362 const ParseToken
*t
= &tokenlist
->list
[i
];
3364 /* Create a token for 't' */
3365 token
->type
= t
->type
;
3366 token
->objPtr
= JimMakeScriptObj(interp
, t
);
3367 Jim_IncrRefCount(token
->objPtr
);
3374 /* This method takes the string representation of an object
3375 * as a Tcl script, and generates the pre-parsed internal representation
3377 static int SetScriptFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, struct JimParseResult
*result
)
3380 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
3381 struct JimParserCtx parser
;
3382 struct ScriptObj
*script
;
3383 ParseTokenList tokenlist
;
3386 /* Try to get information about filename / line number */
3387 if (objPtr
->typePtr
== &sourceObjType
) {
3388 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
3391 /* Initially parse the script into tokens (in tokenlist) */
3392 ScriptTokenListInit(&tokenlist
);
3394 JimParserInit(&parser
, scriptText
, scriptTextLen
, line
);
3395 while (!parser
.eof
) {
3396 JimParseScript(&parser
);
3397 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
3400 if (result
&& parser
.missing
!= ' ') {
3401 ScriptTokenListFree(&tokenlist
);
3402 result
->missing
= parser
.missing
;
3403 result
->line
= parser
.missingline
;
3407 /* Add a final EOF token */
3408 ScriptAddToken(&tokenlist
, scriptText
+ scriptTextLen
, 0, JIM_TT_EOF
, 0);
3410 /* Create the "real" script tokens from the initial token list */
3411 script
= Jim_Alloc(sizeof(*script
));
3412 memset(script
, 0, sizeof(*script
));
3414 script
->line
= line
;
3415 if (objPtr
->typePtr
== &sourceObjType
) {
3416 script
->fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
3419 script
->fileNameObj
= interp
->emptyObj
;
3421 Jim_IncrRefCount(script
->fileNameObj
);
3423 ScriptObjAddTokens(interp
, script
, &tokenlist
);
3425 /* No longer need the token list */
3426 ScriptTokenListFree(&tokenlist
);
3428 /* Free the old internal rep and set the new one. */
3429 Jim_FreeIntRep(interp
, objPtr
);
3430 Jim_SetIntRepPtr(objPtr
, script
);
3431 objPtr
->typePtr
= &scriptObjType
;
3436 ScriptObj
*Jim_GetScript(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3438 struct ScriptObj
*script
= Jim_GetIntRepPtr(objPtr
);
3440 if (objPtr
->typePtr
!= &scriptObjType
|| script
->substFlags
) {
3441 SetScriptFromAny(interp
, objPtr
, NULL
);
3443 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
3446 /* -----------------------------------------------------------------------------
3448 * ---------------------------------------------------------------------------*/
3449 static void JimIncrCmdRefCount(Jim_Cmd
*cmdPtr
)
3454 static void JimDecrCmdRefCount(Jim_Interp
*interp
, Jim_Cmd
*cmdPtr
)
3456 if (--cmdPtr
->inUse
== 0) {
3457 if (cmdPtr
->isproc
) {
3458 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.argListObjPtr
);
3459 Jim_DecrRefCount(interp
, cmdPtr
->u
.proc
.bodyObjPtr
);
3460 if (cmdPtr
->u
.proc
.staticVars
) {
3461 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3462 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3464 if (cmdPtr
->u
.proc
.prevCmd
) {
3465 /* Delete any pushed command too */
3466 JimDecrCmdRefCount(interp
, cmdPtr
->u
.proc
.prevCmd
);
3471 if (cmdPtr
->u
.native
.delProc
) {
3472 cmdPtr
->u
.native
.delProc(interp
, cmdPtr
->u
.native
.privData
);
3479 /* Commands HashTable Type.
3481 * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
3482 static void JimCommandsHT_ValDestructor(void *interp
, void *val
)
3484 JimDecrCmdRefCount(interp
, val
);
3487 static const Jim_HashTableType JimCommandsHashTableType
= {
3488 JimStringCopyHTHashFunction
, /* hash function */
3489 JimStringCopyHTKeyDup
, /* key dup */
3491 JimStringCopyHTKeyCompare
, /* key compare */
3492 JimStringCopyHTKeyDestructor
, /* key destructor */
3493 JimCommandsHT_ValDestructor
/* val destructor */
3496 /* ------------------------- Commands related functions --------------------- */
3498 int Jim_CreateCommand(Jim_Interp
*interp
, const char *cmdName
,
3499 Jim_CmdProc cmdProc
, void *privData
, Jim_DelCmdProc delProc
)
3503 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) != JIM_ERR
) {
3504 /* Command existed so incr proc epoch */
3505 Jim_InterpIncrProcEpoch(interp
);
3508 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
));
3510 /* Store the new details for this proc */
3511 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3513 cmdPtr
->u
.native
.delProc
= delProc
;
3514 cmdPtr
->u
.native
.cmdProc
= cmdProc
;
3515 cmdPtr
->u
.native
.privData
= privData
;
3517 Jim_AddHashEntry(&interp
->commands
, cmdName
, cmdPtr
);
3519 /* There is no need to increment the 'proc epoch' because
3520 * creation of a new procedure can never affect existing
3521 * cached commands. We don't do negative caching. */
3525 static int JimCreateProcedure(Jim_Interp
*interp
, Jim_Obj
*cmdName
,
3526 Jim_Obj
*argListObjPtr
, Jim_Obj
*staticsListObjPtr
, Jim_Obj
*bodyObjPtr
)
3533 if (JimValidName(interp
, "procedure", cmdName
) != JIM_OK
) {
3537 argListLen
= Jim_ListLength(interp
, argListObjPtr
);
3539 /* Allocate space for both the command pointer and the arg list */
3540 cmdPtr
= Jim_Alloc(sizeof(*cmdPtr
) + sizeof(struct Jim_ProcArg
) * argListLen
);
3541 memset(cmdPtr
, 0, sizeof(*cmdPtr
));
3544 cmdPtr
->u
.proc
.argListObjPtr
= argListObjPtr
;
3545 cmdPtr
->u
.proc
.argListLen
= argListLen
;
3546 cmdPtr
->u
.proc
.bodyObjPtr
= bodyObjPtr
;
3547 cmdPtr
->u
.proc
.argsPos
= -1;
3548 cmdPtr
->u
.proc
.arglist
= (struct Jim_ProcArg
*)(cmdPtr
+ 1);
3549 Jim_IncrRefCount(argListObjPtr
);
3550 Jim_IncrRefCount(bodyObjPtr
);
3552 /* Create the statics hash table. */
3553 if (staticsListObjPtr
) {
3556 len
= Jim_ListLength(interp
, staticsListObjPtr
);
3558 cmdPtr
->u
.proc
.staticVars
= Jim_Alloc(sizeof(Jim_HashTable
));
3559 Jim_InitHashTable(cmdPtr
->u
.proc
.staticVars
, &JimVariablesHashTableType
, interp
);
3560 for (i
= 0; i
< len
; i
++) {
3561 Jim_Obj
*objPtr
= 0, *initObjPtr
= 0, *nameObjPtr
= 0;
3565 Jim_ListIndex(interp
, staticsListObjPtr
, i
, &objPtr
, JIM_NONE
);
3566 /* Check if it's composed of two elements. */
3567 subLen
= Jim_ListLength(interp
, objPtr
);
3568 if (subLen
== 1 || subLen
== 2) {
3569 /* Try to get the variable value from the current
3571 Jim_ListIndex(interp
, objPtr
, 0, &nameObjPtr
, JIM_NONE
);
3573 initObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, JIM_NONE
);
3574 if (initObjPtr
== NULL
) {
3575 Jim_SetResultFormatted(interp
,
3576 "variable for initialization of static \"%#s\" not found in the local context",
3582 Jim_ListIndex(interp
, objPtr
, 1, &initObjPtr
, JIM_NONE
);
3584 if (JimValidName(interp
, "static variable", nameObjPtr
) != JIM_OK
) {
3588 varPtr
= Jim_Alloc(sizeof(*varPtr
));
3589 varPtr
->objPtr
= initObjPtr
;
3590 Jim_IncrRefCount(initObjPtr
);
3591 varPtr
->linkFramePtr
= NULL
;
3592 if (Jim_AddHashEntry(cmdPtr
->u
.proc
.staticVars
,
3593 Jim_String(nameObjPtr
), varPtr
) != JIM_OK
) {
3594 Jim_SetResultFormatted(interp
,
3595 "static variable name \"%#s\" duplicated in statics list", nameObjPtr
);
3596 Jim_DecrRefCount(interp
, initObjPtr
);
3602 Jim_SetResultFormatted(interp
, "too many fields in static specifier \"%#s\"",
3610 /* Parse the args out into arglist, validating as we go */
3611 /* Examine the argument list for default parameters and 'args' */
3612 for (i
= 0; i
< argListLen
; i
++) {
3614 Jim_Obj
*nameObjPtr
;
3615 Jim_Obj
*defaultObjPtr
;
3619 /* Examine a parameter */
3620 Jim_ListIndex(interp
, argListObjPtr
, i
, &argPtr
, JIM_NONE
);
3621 len
= Jim_ListLength(interp
, argPtr
);
3623 Jim_SetResultString(interp
, "procedure has argument with no name", -1);
3627 Jim_SetResultString(interp
, "procedure has argument with too many fields", -1);
3632 /* Optional parameter */
3633 Jim_ListIndex(interp
, argPtr
, 0, &nameObjPtr
, JIM_NONE
);
3634 Jim_ListIndex(interp
, argPtr
, 1, &defaultObjPtr
, JIM_NONE
);
3637 /* Required parameter */
3638 nameObjPtr
= argPtr
;
3639 defaultObjPtr
= NULL
;
3643 if (Jim_CompareStringImmediate(interp
, nameObjPtr
, "args")) {
3644 if (cmdPtr
->u
.proc
.argsPos
>= 0) {
3645 Jim_SetResultString(interp
, "procedure has 'args' specified more than once", -1);
3648 cmdPtr
->u
.proc
.argsPos
= i
;
3652 cmdPtr
->u
.proc
.optArity
+= n
;
3655 cmdPtr
->u
.proc
.reqArity
+= n
;
3659 cmdPtr
->u
.proc
.arglist
[i
].nameObjPtr
= nameObjPtr
;
3660 cmdPtr
->u
.proc
.arglist
[i
].defaultObjPtr
= defaultObjPtr
;
3663 /* Add the new command */
3665 /* It may already exist, so we try to delete the old one.
3666 * Note that reference count means that it won't be deleted yet if
3667 * it exists in the call stack.
3669 * BUT, if 'local' is in force, instead of deleting the existing
3670 * proc, we stash a reference to the old proc here.
3672 he
= Jim_FindHashEntry(&interp
->commands
, Jim_String(cmdName
));
3674 /* There was an old procedure with the same name, this requires
3675 * a 'proc epoch' update. */
3677 /* If a procedure with the same name didn't existed there is no need
3678 * to increment the 'proc epoch' because creation of a new procedure
3679 * can never affect existing cached commands. We don't do
3680 * negative caching. */
3681 Jim_InterpIncrProcEpoch(interp
);
3684 if (he
&& interp
->local
) {
3685 /* Just push this proc over the top of the previous one */
3686 cmdPtr
->u
.proc
.prevCmd
= he
->u
.val
;
3691 /* Replace the existing proc */
3692 Jim_DeleteHashEntry(&interp
->commands
, Jim_String(cmdName
));
3695 Jim_AddHashEntry(&interp
->commands
, Jim_String(cmdName
), cmdPtr
);
3698 /* Unlike Tcl, set the name of the proc as the result */
3699 Jim_SetResult(interp
, cmdName
);
3703 if (cmdPtr
->u
.proc
.staticVars
) {
3704 Jim_FreeHashTable(cmdPtr
->u
.proc
.staticVars
);
3706 Jim_Free(cmdPtr
->u
.proc
.staticVars
);
3707 Jim_DecrRefCount(interp
, argListObjPtr
);
3708 Jim_DecrRefCount(interp
, bodyObjPtr
);
3713 int Jim_DeleteCommand(Jim_Interp
*interp
, const char *cmdName
)
3715 if (Jim_DeleteHashEntry(&interp
->commands
, cmdName
) == JIM_ERR
)
3717 Jim_InterpIncrProcEpoch(interp
);
3721 int Jim_RenameCommand(Jim_Interp
*interp
, const char *oldName
, const char *newName
)
3725 /* Does it exist? */
3726 he
= Jim_FindHashEntry(&interp
->commands
, oldName
);
3728 Jim_SetResultFormatted(interp
, "can't %s \"%s\": command doesn't exist",
3729 newName
[0] ? "rename" : "delete", oldName
);
3733 if (newName
[0] == '\0') /* Delete! */
3734 return Jim_DeleteCommand(interp
, oldName
);
3737 if (Jim_FindHashEntry(&interp
->commands
, newName
)) {
3738 Jim_SetResultFormatted(interp
, "can't rename to \"%s\": command already exists", newName
);
3742 /* Add the new name first */
3743 JimIncrCmdRefCount(he
->u
.val
);
3744 Jim_AddHashEntry(&interp
->commands
, newName
, he
->u
.val
);
3746 /* Now remove the old name */
3747 Jim_DeleteHashEntry(&interp
->commands
, oldName
);
3749 /* Increment the epoch */
3750 Jim_InterpIncrProcEpoch(interp
);
3754 /* -----------------------------------------------------------------------------
3756 * ---------------------------------------------------------------------------*/
3758 static int SetCommandFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3760 static const Jim_ObjType commandObjType
= {
3765 JIM_TYPE_REFERENCES
,
3768 int SetCommandFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
3771 const char *cmdName
;
3773 /* Get the string representation */
3774 cmdName
= Jim_String(objPtr
);
3775 /* Lookup this name into the commands hash table */
3776 he
= Jim_FindHashEntry(&interp
->commands
, cmdName
);
3780 /* Free the old internal repr and set the new one. */
3781 Jim_FreeIntRep(interp
, objPtr
);
3782 objPtr
->typePtr
= &commandObjType
;
3783 objPtr
->internalRep
.cmdValue
.procEpoch
= interp
->procEpoch
;
3784 objPtr
->internalRep
.cmdValue
.cmdPtr
= (void *)he
->u
.val
;
3788 /* This function returns the command structure for the command name
3789 * stored in objPtr. It tries to specialize the objPtr to contain
3790 * a cached info instead to perform the lookup into the hash table
3791 * every time. The information cached may not be uptodate, in such
3792 * a case the lookup is performed and the cache updated.
3794 * Respects the 'upcall' setting
3796 Jim_Cmd
*Jim_GetCommand(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
3800 if ((objPtr
->typePtr
!= &commandObjType
||
3801 objPtr
->internalRep
.cmdValue
.procEpoch
!= interp
->procEpoch
) &&
3802 SetCommandFromAny(interp
, objPtr
) == JIM_ERR
) {
3803 if (flags
& JIM_ERRMSG
) {
3804 Jim_SetResultFormatted(interp
, "invalid command name \"%#s\"", objPtr
);
3808 cmd
= objPtr
->internalRep
.cmdValue
.cmdPtr
;
3809 while (cmd
->isproc
&& cmd
->u
.proc
.upcall
) {
3810 cmd
= cmd
->u
.proc
.prevCmd
;
3815 /* -----------------------------------------------------------------------------
3817 * ---------------------------------------------------------------------------*/
3819 /* Variables HashTable Type.
3821 * Keys are dynamic allocated strings, Values are Jim_Var structures. */
3822 static void JimVariablesHTValDestructor(void *interp
, void *val
)
3824 Jim_Var
*varPtr
= (void *)val
;
3826 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
3830 static const Jim_HashTableType JimVariablesHashTableType
= {
3831 JimStringCopyHTHashFunction
, /* hash function */
3832 JimStringCopyHTKeyDup
, /* key dup */
3834 JimStringCopyHTKeyCompare
, /* key compare */
3835 JimStringCopyHTKeyDestructor
, /* key destructor */
3836 JimVariablesHTValDestructor
/* val destructor */
3839 /* -----------------------------------------------------------------------------
3841 * ---------------------------------------------------------------------------*/
3843 #define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
3845 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
3847 static const Jim_ObjType variableObjType
= {
3852 JIM_TYPE_REFERENCES
,
3855 /* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
3856 * is in the form "varname(key)". */
3857 static int JimNameIsDictSugar(const char *str
, int len
)
3859 if (len
&& str
[len
- 1] == ')' && strchr(str
, '(') != NULL
)
3865 * Check that the name does not contain embedded nulls.
3867 * Variable and procedure names are maniplated as null terminated strings, so
3868 * don't allow names with embedded nulls.
3870 static int JimValidName(Jim_Interp
*interp
, const char *type
, Jim_Obj
*nameObjPtr
)
3872 /* Variable names and proc names can't contain embedded nulls */
3873 if (nameObjPtr
->typePtr
!= &variableObjType
) {
3875 const char *str
= Jim_GetString(nameObjPtr
, &len
);
3876 if (memchr(str
, '\0', len
)) {
3877 Jim_SetResultFormatted(interp
, "%s name contains embedded null", type
);
3884 /* This method should be called only by the variable API.
3885 * It returns JIM_OK on success (variable already exists),
3886 * JIM_ERR if it does not exists, JIM_DICT_SUGAR if it's not
3887 * a variable name, but syntax glue for [dict] i.e. the last
3888 * character is ')' */
3889 static int SetVariableFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
3892 const char *varName
;
3894 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3896 /* Check if the object is already an uptodate variable */
3897 if (objPtr
->typePtr
== &variableObjType
&&
3898 objPtr
->internalRep
.varValue
.callFrameId
== framePtr
->id
) {
3899 return JIM_OK
; /* nothing to do */
3902 if (objPtr
->typePtr
== &dictSubstObjType
) {
3903 return JIM_DICT_SUGAR
;
3906 if (JimValidName(interp
, "variable", objPtr
) != JIM_OK
) {
3910 /* Get the string representation */
3911 varName
= Jim_GetString(objPtr
, &len
);
3913 /* Make sure it's not syntax glue to get/set dict. */
3914 if (JimNameIsDictSugar(varName
, len
)) {
3915 return JIM_DICT_SUGAR
;
3918 if (varName
[0] == ':' && varName
[1] == ':') {
3919 framePtr
= interp
->topFramePtr
;
3920 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
+ 2);
3926 /* Lookup this name into the variables hash table */
3927 he
= Jim_FindHashEntry(&framePtr
->vars
, varName
);
3929 /* Try with static vars. */
3930 if (framePtr
->staticVars
== NULL
)
3932 if (!(he
= Jim_FindHashEntry(framePtr
->staticVars
, varName
)))
3936 /* Free the old internal repr and set the new one. */
3937 Jim_FreeIntRep(interp
, objPtr
);
3938 objPtr
->typePtr
= &variableObjType
;
3939 objPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3940 objPtr
->internalRep
.varValue
.varPtr
= (void *)he
->u
.val
;
3944 /* -------------------- Variables related functions ------------------------- */
3945 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, Jim_Obj
*valObjPtr
);
3946 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*ObjPtr
, int flags
);
3948 /* For now that's dummy. Variables lookup should be optimized
3949 * in many ways, with caching of lookups, and possibly with
3950 * a table of pre-allocated vars in every CallFrame for local vars.
3951 * All the caching should also have an 'epoch' mechanism similar
3952 * to the one used by Tcl for procedures lookup caching. */
3954 int Jim_SetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, Jim_Obj
*valObjPtr
)
3960 if ((err
= SetVariableFromAny(interp
, nameObjPtr
)) != JIM_OK
) {
3961 Jim_CallFrame
*framePtr
= interp
->framePtr
;
3963 /* Check for [dict] syntax sugar. */
3964 if (err
== JIM_DICT_SUGAR
)
3965 return JimDictSugarSet(interp
, nameObjPtr
, valObjPtr
);
3967 if (JimValidName(interp
, "variable", nameObjPtr
) != JIM_OK
) {
3971 /* New variable to create */
3972 name
= Jim_String(nameObjPtr
);
3974 var
= Jim_Alloc(sizeof(*var
));
3975 var
->objPtr
= valObjPtr
;
3976 Jim_IncrRefCount(valObjPtr
);
3977 var
->linkFramePtr
= NULL
;
3978 /* Insert the new variable */
3979 if (name
[0] == ':' && name
[1] == ':') {
3980 /* Into the top level frame */
3981 framePtr
= interp
->topFramePtr
;
3982 Jim_AddHashEntry(&framePtr
->vars
, name
+ 2, var
);
3985 Jim_AddHashEntry(&framePtr
->vars
, name
, var
);
3987 /* Make the object int rep a variable */
3988 Jim_FreeIntRep(interp
, nameObjPtr
);
3989 nameObjPtr
->typePtr
= &variableObjType
;
3990 nameObjPtr
->internalRep
.varValue
.callFrameId
= framePtr
->id
;
3991 nameObjPtr
->internalRep
.varValue
.varPtr
= var
;
3994 var
= nameObjPtr
->internalRep
.varValue
.varPtr
;
3995 if (var
->linkFramePtr
== NULL
) {
3996 Jim_IncrRefCount(valObjPtr
);
3997 Jim_DecrRefCount(interp
, var
->objPtr
);
3998 var
->objPtr
= valObjPtr
;
4000 else { /* Else handle the link */
4001 Jim_CallFrame
*savedCallFrame
;
4003 savedCallFrame
= interp
->framePtr
;
4004 interp
->framePtr
= var
->linkFramePtr
;
4005 err
= Jim_SetVariable(interp
, var
->objPtr
, valObjPtr
);
4006 interp
->framePtr
= savedCallFrame
;
4014 int Jim_SetVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4016 Jim_Obj
*nameObjPtr
;
4019 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4020 Jim_IncrRefCount(nameObjPtr
);
4021 result
= Jim_SetVariable(interp
, nameObjPtr
, objPtr
);
4022 Jim_DecrRefCount(interp
, nameObjPtr
);
4026 int Jim_SetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, Jim_Obj
*objPtr
)
4028 Jim_CallFrame
*savedFramePtr
;
4031 savedFramePtr
= interp
->framePtr
;
4032 interp
->framePtr
= interp
->topFramePtr
;
4033 result
= Jim_SetVariableStr(interp
, name
, objPtr
);
4034 interp
->framePtr
= savedFramePtr
;
4038 int Jim_SetVariableStrWithStr(Jim_Interp
*interp
, const char *name
, const char *val
)
4040 Jim_Obj
*nameObjPtr
, *valObjPtr
;
4043 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4044 valObjPtr
= Jim_NewStringObj(interp
, val
, -1);
4045 Jim_IncrRefCount(nameObjPtr
);
4046 Jim_IncrRefCount(valObjPtr
);
4047 result
= Jim_SetVariable(interp
, nameObjPtr
, valObjPtr
);
4048 Jim_DecrRefCount(interp
, nameObjPtr
);
4049 Jim_DecrRefCount(interp
, valObjPtr
);
4053 int Jim_SetVariableLink(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
,
4054 Jim_Obj
*targetNameObjPtr
, Jim_CallFrame
*targetCallFrame
)
4056 const char *varName
;
4059 varName
= Jim_GetString(nameObjPtr
, &len
);
4061 if (varName
[0] == ':' && varName
[1] == ':') {
4062 /* Linking a global var does nothing */
4066 if (JimNameIsDictSugar(varName
, len
)) {
4067 Jim_SetResultString(interp
, "Dict key syntax invalid as link source", -1);
4071 /* Check for an existing variable or link */
4072 if (SetVariableFromAny(interp
, nameObjPtr
) == JIM_OK
) {
4073 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4075 if (varPtr
->linkFramePtr
== NULL
) {
4076 Jim_SetResultFormatted(interp
, "variable \"%#s\" already exists", nameObjPtr
);
4080 /* It exists, but is a link, so delete the link */
4081 varPtr
->linkFramePtr
= NULL
;
4084 /* Check for cycles. */
4085 if (interp
->framePtr
== targetCallFrame
) {
4086 Jim_Obj
*objPtr
= targetNameObjPtr
;
4089 /* Cycles are only possible with 'uplevel 0' */
4091 if (Jim_StringEqObj(objPtr
, nameObjPtr
)) {
4092 Jim_SetResultString(interp
, "can't upvar from variable to itself", -1);
4095 if (SetVariableFromAny(interp
, objPtr
) != JIM_OK
)
4097 varPtr
= objPtr
->internalRep
.varValue
.varPtr
;
4098 if (varPtr
->linkFramePtr
!= targetCallFrame
)
4100 objPtr
= varPtr
->objPtr
;
4104 /* Perform the binding */
4105 Jim_SetVariable(interp
, nameObjPtr
, targetNameObjPtr
);
4106 /* We are now sure 'nameObjPtr' type is variableObjType */
4107 nameObjPtr
->internalRep
.varValue
.varPtr
->linkFramePtr
= targetCallFrame
;
4111 /* Return the Jim_Obj pointer associated with a variable name,
4112 * or NULL if the variable was not found in the current context.
4113 * The same optimization discussed in the comment to the
4114 * 'SetVariable' function should apply here.
4116 * If JIM_UNSHARED is set and the variable is an array element (dict sugar)
4117 * in a dictionary which is shared, the array variable value is duplicated first.
4118 * This allows the array element to be updated (e.g. append, lappend) without
4119 * affecting other references to the dictionary.
4121 Jim_Obj
*Jim_GetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4123 switch (SetVariableFromAny(interp
, nameObjPtr
)) {
4125 Jim_Var
*varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4127 if (varPtr
->linkFramePtr
== NULL
) {
4128 return varPtr
->objPtr
;
4133 /* The variable is a link? Resolve it. */
4134 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
4136 interp
->framePtr
= varPtr
->linkFramePtr
;
4137 objPtr
= Jim_GetVariable(interp
, varPtr
->objPtr
, flags
);
4138 interp
->framePtr
= savedCallFrame
;
4142 /* Error, so fall through to the error message */
4147 case JIM_DICT_SUGAR
:
4148 /* [dict] syntax sugar. */
4149 return JimDictSugarGet(interp
, nameObjPtr
, flags
);
4151 if (flags
& JIM_ERRMSG
) {
4152 Jim_SetResultFormatted(interp
, "can't read \"%#s\": no such variable", nameObjPtr
);
4157 Jim_Obj
*Jim_GetGlobalVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4159 Jim_CallFrame
*savedFramePtr
;
4162 savedFramePtr
= interp
->framePtr
;
4163 interp
->framePtr
= interp
->topFramePtr
;
4164 objPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4165 interp
->framePtr
= savedFramePtr
;
4170 Jim_Obj
*Jim_GetVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4172 Jim_Obj
*nameObjPtr
, *varObjPtr
;
4174 nameObjPtr
= Jim_NewStringObj(interp
, name
, -1);
4175 Jim_IncrRefCount(nameObjPtr
);
4176 varObjPtr
= Jim_GetVariable(interp
, nameObjPtr
, flags
);
4177 Jim_DecrRefCount(interp
, nameObjPtr
);
4181 Jim_Obj
*Jim_GetGlobalVariableStr(Jim_Interp
*interp
, const char *name
, int flags
)
4183 Jim_CallFrame
*savedFramePtr
;
4186 savedFramePtr
= interp
->framePtr
;
4187 interp
->framePtr
= interp
->topFramePtr
;
4188 objPtr
= Jim_GetVariableStr(interp
, name
, flags
);
4189 interp
->framePtr
= savedFramePtr
;
4194 /* Unset a variable.
4195 * Note: On success unset invalidates all the variable objects created
4196 * in the current call frame incrementing. */
4197 int Jim_UnsetVariable(Jim_Interp
*interp
, Jim_Obj
*nameObjPtr
, int flags
)
4203 retval
= SetVariableFromAny(interp
, nameObjPtr
);
4204 if (retval
== JIM_DICT_SUGAR
) {
4205 /* [dict] syntax sugar. */
4206 return JimDictSugarSet(interp
, nameObjPtr
, NULL
);
4208 else if (retval
== JIM_OK
) {
4209 varPtr
= nameObjPtr
->internalRep
.varValue
.varPtr
;
4211 /* If it's a link call UnsetVariable recursively */
4212 if (varPtr
->linkFramePtr
) {
4213 Jim_CallFrame
*savedCallFrame
;
4215 savedCallFrame
= interp
->framePtr
;
4216 interp
->framePtr
= varPtr
->linkFramePtr
;
4217 retval
= Jim_UnsetVariable(interp
, varPtr
->objPtr
, JIM_NONE
);
4218 interp
->framePtr
= savedCallFrame
;
4221 Jim_CallFrame
*framePtr
= interp
->framePtr
;
4223 name
= Jim_String(nameObjPtr
);
4224 if (name
[0] == ':' && name
[1] == ':') {
4225 framePtr
= interp
->topFramePtr
;
4228 retval
= Jim_DeleteHashEntry(&framePtr
->vars
, name
);
4229 if (retval
== JIM_OK
) {
4230 /* Change the callframe id, invalidating var lookup caching */
4231 JimChangeCallFrameId(interp
, framePtr
);
4235 if (retval
!= JIM_OK
&& (flags
& JIM_ERRMSG
)) {
4236 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such variable", nameObjPtr
);
4241 /* ---------- Dict syntax sugar (similar to array Tcl syntax) -------------- */
4243 /* Given a variable name for [dict] operation syntax sugar,
4244 * this function returns two objects, the first with the name
4245 * of the variable to set, and the second with the rispective key.
4246 * For example "foo(bar)" will return objects with string repr. of
4249 * The returned objects have refcount = 1. The function can't fail. */
4250 static void JimDictSugarParseVarKey(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
4251 Jim_Obj
**varPtrPtr
, Jim_Obj
**keyPtrPtr
)
4253 const char *str
, *p
;
4255 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4257 str
= Jim_GetString(objPtr
, &len
);
4259 p
= strchr(str
, '(');
4260 JimPanic((p
== NULL
, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str
));
4262 varObjPtr
= Jim_NewStringObj(interp
, str
, p
- str
);
4265 keyLen
= (str
+ len
) - p
;
4266 if (str
[len
- 1] == ')') {
4270 /* Create the objects with the variable name and key. */
4271 keyObjPtr
= Jim_NewStringObj(interp
, p
, keyLen
);
4273 Jim_IncrRefCount(varObjPtr
);
4274 Jim_IncrRefCount(keyObjPtr
);
4275 *varPtrPtr
= varObjPtr
;
4276 *keyPtrPtr
= keyObjPtr
;
4279 /* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
4280 * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
4281 static int JimDictSugarSet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*valObjPtr
)
4285 SetDictSubstFromAny(interp
, objPtr
);
4287 err
= Jim_SetDictKeysVector(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4288 &objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, 1, valObjPtr
, JIM_ERRMSG
);
4290 if (err
== JIM_OK
) {
4291 /* Don't keep an extra ref to the result */
4292 Jim_SetEmptyResult(interp
);
4296 /* Better error message for unset a(2) where a exists but a(2) doesn't */
4297 if (Jim_GetVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
, JIM_NONE
)) {
4298 Jim_SetResultFormatted(interp
, "can't unset \"%#s\": no such element in array",
4303 /* Make the error more informative and Tcl-compatible */
4304 Jim_SetResultFormatted(interp
, "can't %s \"%#s\": variable isn't array",
4305 (valObjPtr
? "set" : "unset"), objPtr
);
4311 * Expands the array variable (dict sugar) and returns the result, or NULL on error.
4313 * If JIM_UNSHARED is set and the dictionary is shared, it will be duplicated
4314 * and stored back to the variable before expansion.
4316 static Jim_Obj
*JimDictExpandArrayVariable(Jim_Interp
*interp
, Jim_Obj
*varObjPtr
,
4317 Jim_Obj
*keyObjPtr
, int flags
)
4319 Jim_Obj
*dictObjPtr
;
4320 Jim_Obj
*resObjPtr
= NULL
;
4323 dictObjPtr
= Jim_GetVariable(interp
, varObjPtr
, JIM_ERRMSG
);
4328 ret
= Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4329 if (ret
!= JIM_OK
) {
4332 Jim_SetResultFormatted(interp
,
4333 "can't read \"%#s(%#s)\": variable isn't array", varObjPtr
, keyObjPtr
);
4336 Jim_SetResultFormatted(interp
,
4337 "can't read \"%#s(%#s)\": no such element in array", varObjPtr
, keyObjPtr
);
4340 else if ((flags
& JIM_UNSHARED
) && Jim_IsShared(dictObjPtr
)) {
4341 dictObjPtr
= Jim_DuplicateObj(interp
, dictObjPtr
);
4342 if (Jim_SetVariable(interp
, varObjPtr
, dictObjPtr
) != JIM_OK
) {
4343 /* This can probably never happen */
4344 JimPanic((1, "SetVariable failed for JIM_UNSHARED"));
4346 /* We know that the key exists. Get the result in the now-unshared dictionary */
4347 Jim_DictKey(interp
, dictObjPtr
, keyObjPtr
, &resObjPtr
, JIM_NONE
);
4353 /* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
4354 static Jim_Obj
*JimDictSugarGet(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
4356 SetDictSubstFromAny(interp
, objPtr
);
4358 return JimDictExpandArrayVariable(interp
,
4359 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4360 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
, flags
);
4363 /* --------- $var(INDEX) substitution, using a specialized object ----------- */
4365 void FreeDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4367 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
);
4368 Jim_DecrRefCount(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
);
4371 void DupDictSubstInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
4373 JIM_NOTUSED(interp
);
4375 dupPtr
->internalRep
.dictSubstValue
.varNameObjPtr
=
4376 srcPtr
->internalRep
.dictSubstValue
.varNameObjPtr
;
4377 dupPtr
->internalRep
.dictSubstValue
.indexObjPtr
= srcPtr
->internalRep
.dictSubstValue
.indexObjPtr
;
4378 dupPtr
->typePtr
= &dictSubstObjType
;
4381 /* Note: The object *must* be in dict-sugar format */
4382 static void SetDictSubstFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4384 if (objPtr
->typePtr
!= &dictSubstObjType
) {
4385 Jim_Obj
*varObjPtr
, *keyObjPtr
;
4387 if (objPtr
->typePtr
== &interpolatedObjType
) {
4388 /* An interpolated object in dict-sugar form */
4390 const ScriptToken
*token
= objPtr
->internalRep
.twoPtrValue
.ptr1
;
4392 varObjPtr
= token
[0].objPtr
;
4393 keyObjPtr
= objPtr
->internalRep
.twoPtrValue
.ptr2
;
4395 Jim_IncrRefCount(varObjPtr
);
4396 Jim_IncrRefCount(keyObjPtr
);
4399 JimDictSugarParseVarKey(interp
, objPtr
, &varObjPtr
, &keyObjPtr
);
4402 Jim_FreeIntRep(interp
, objPtr
);
4403 objPtr
->typePtr
= &dictSubstObjType
;
4404 objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
= varObjPtr
;
4405 objPtr
->internalRep
.dictSubstValue
.indexObjPtr
= keyObjPtr
;
4409 /* This function is used to expand [dict get] sugar in the form
4410 * of $var(INDEX). The function is mainly used by Jim_EvalObj()
4411 * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
4412 * object that is *guaranteed* to be in the form VARNAME(INDEX).
4413 * The 'index' part is [subst]ituted, and is used to lookup a key inside
4414 * the [dict]ionary contained in variable VARNAME. */
4415 static Jim_Obj
*JimExpandDictSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4417 Jim_Obj
*resObjPtr
= NULL
;
4418 Jim_Obj
*substKeyObjPtr
= NULL
;
4420 SetDictSubstFromAny(interp
, objPtr
);
4422 if (Jim_SubstObj(interp
, objPtr
->internalRep
.dictSubstValue
.indexObjPtr
,
4423 &substKeyObjPtr
, JIM_NONE
)
4427 Jim_IncrRefCount(substKeyObjPtr
);
4429 JimDictExpandArrayVariable(interp
, objPtr
->internalRep
.dictSubstValue
.varNameObjPtr
,
4431 Jim_DecrRefCount(interp
, substKeyObjPtr
);
4436 static Jim_Obj
*JimExpandExprSugar(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4438 Jim_Obj
*resultObjPtr
;
4440 if (Jim_EvalExpression(interp
, objPtr
, &resultObjPtr
) == JIM_OK
) {
4441 /* Note that the result has a ref count of 1, but we need a ref count of 0 */
4442 resultObjPtr
->refCount
--;
4443 return resultObjPtr
;
4448 /* -----------------------------------------------------------------------------
4450 * ---------------------------------------------------------------------------*/
4452 static Jim_CallFrame
*JimCreateCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*parent
)
4456 if (interp
->freeFramesList
) {
4457 cf
= interp
->freeFramesList
;
4458 interp
->freeFramesList
= cf
->nextFramePtr
;
4461 cf
= Jim_Alloc(sizeof(*cf
));
4462 cf
->vars
.table
= NULL
;
4465 cf
->id
= interp
->callFrameEpoch
++;
4466 cf
->parentCallFrame
= parent
;
4467 cf
->level
= parent
? parent
->level
+ 1 : 0;
4470 cf
->procArgsObjPtr
= NULL
;
4471 cf
->procBodyObjPtr
= NULL
;
4472 cf
->nextFramePtr
= NULL
;
4473 cf
->staticVars
= NULL
;
4474 if (cf
->vars
.table
== NULL
)
4475 Jim_InitHashTable(&cf
->vars
, &JimVariablesHashTableType
, interp
);
4479 /* Used to invalidate every caching related to callframe stability. */
4480 static void JimChangeCallFrameId(Jim_Interp
*interp
, Jim_CallFrame
*cf
)
4482 cf
->id
= interp
->callFrameEpoch
++;
4485 #define JIM_FCF_NONE 0 /* no flags */
4486 #define JIM_FCF_NOHT 1 /* don't free the hash table */
4487 static void JimFreeCallFrame(Jim_Interp
*interp
, Jim_CallFrame
*cf
, int flags
)
4489 if (cf
->procArgsObjPtr
)
4490 Jim_DecrRefCount(interp
, cf
->procArgsObjPtr
);
4491 if (cf
->procBodyObjPtr
)
4492 Jim_DecrRefCount(interp
, cf
->procBodyObjPtr
);
4493 if (!(flags
& JIM_FCF_NOHT
))
4494 Jim_FreeHashTable(&cf
->vars
);
4497 Jim_HashEntry
**table
= cf
->vars
.table
, *he
;
4499 for (i
= 0; i
< JIM_HT_INITIAL_SIZE
; i
++) {
4501 while (he
!= NULL
) {
4502 Jim_HashEntry
*nextEntry
= he
->next
;
4503 Jim_Var
*varPtr
= (void *)he
->u
.val
;
4505 Jim_DecrRefCount(interp
, varPtr
->objPtr
);
4506 Jim_Free(he
->u
.val
);
4507 Jim_Free((void *)he
->key
); /* ATTENTION: const cast */
4515 cf
->nextFramePtr
= interp
->freeFramesList
;
4516 interp
->freeFramesList
= cf
;
4519 /* -----------------------------------------------------------------------------
4521 * ---------------------------------------------------------------------------*/
4522 #ifdef JIM_REFERENCES
4524 /* References HashTable Type.
4526 * Keys are jim_wide integers, dynamically allocated for now but in the
4527 * future it's worth to cache this 8 bytes objects. Values are poitners
4528 * to Jim_References. */
4529 static void JimReferencesHTValDestructor(void *interp
, void *val
)
4531 Jim_Reference
*refPtr
= (void *)val
;
4533 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
4534 if (refPtr
->finalizerCmdNamePtr
!= NULL
) {
4535 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4540 static unsigned int JimReferencesHTHashFunction(const void *key
)
4542 /* Only the least significant bits are used. */
4543 const jim_wide
*widePtr
= key
;
4544 unsigned int intValue
= (unsigned int)*widePtr
;
4546 return Jim_IntHashFunction(intValue
);
4549 static const void *JimReferencesHTKeyDup(void *privdata
, const void *key
)
4551 void *copy
= Jim_Alloc(sizeof(jim_wide
));
4553 JIM_NOTUSED(privdata
);
4555 memcpy(copy
, key
, sizeof(jim_wide
));
4559 static int JimReferencesHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
4561 JIM_NOTUSED(privdata
);
4563 return memcmp(key1
, key2
, sizeof(jim_wide
)) == 0;
4566 static void JimReferencesHTKeyDestructor(void *privdata
, const void *key
)
4568 JIM_NOTUSED(privdata
);
4570 Jim_Free((void *)key
);
4573 static const Jim_HashTableType JimReferencesHashTableType
= {
4574 JimReferencesHTHashFunction
, /* hash function */
4575 JimReferencesHTKeyDup
, /* key dup */
4577 JimReferencesHTKeyCompare
, /* key compare */
4578 JimReferencesHTKeyDestructor
, /* key destructor */
4579 JimReferencesHTValDestructor
/* val destructor */
4582 /* -----------------------------------------------------------------------------
4583 * Reference object type and References API
4584 * ---------------------------------------------------------------------------*/
4586 /* The string representation of references has two features in order
4587 * to make the GC faster. The first is that every reference starts
4588 * with a non common character '<', in order to make the string matching
4589 * faster. The second is that the reference string rep is 42 characters
4590 * in length, this allows to avoid to check every object with a string
4591 * repr < 42, and usually there aren't many of these objects. */
4593 #define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
4595 static int JimFormatReference(char *buf
, Jim_Reference
*refPtr
, jim_wide id
)
4597 const char *fmt
= "<reference.<%s>.%020" JIM_WIDE_MODIFIER
">";
4599 sprintf(buf
, fmt
, refPtr
->tag
, id
);
4600 return JIM_REFERENCE_SPACE
;
4603 static void UpdateStringOfReference(struct Jim_Obj
*objPtr
);
4605 static const Jim_ObjType referenceObjType
= {
4609 UpdateStringOfReference
,
4610 JIM_TYPE_REFERENCES
,
4613 void UpdateStringOfReference(struct Jim_Obj
*objPtr
)
4616 char buf
[JIM_REFERENCE_SPACE
+ 1];
4617 Jim_Reference
*refPtr
;
4619 refPtr
= objPtr
->internalRep
.refValue
.refPtr
;
4620 len
= JimFormatReference(buf
, refPtr
, objPtr
->internalRep
.refValue
.id
);
4621 objPtr
->bytes
= Jim_Alloc(len
+ 1);
4622 memcpy(objPtr
->bytes
, buf
, len
+ 1);
4623 objPtr
->length
= len
;
4626 /* returns true if 'c' is a valid reference tag character.
4627 * i.e. inside the range [_a-zA-Z0-9] */
4628 static int isrefchar(int c
)
4630 return (c
== '_' || isalnum(c
));
4633 static int SetReferenceFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4637 const char *str
, *start
, *end
;
4639 Jim_Reference
*refPtr
;
4642 /* Get the string representation */
4643 str
= Jim_GetString(objPtr
, &len
);
4644 /* Check if it looks like a reference */
4645 if (len
< JIM_REFERENCE_SPACE
)
4649 end
= str
+ len
- 1;
4650 while (*start
== ' ')
4652 while (*end
== ' ' && end
> start
)
4654 if (end
- start
+ 1 != JIM_REFERENCE_SPACE
)
4656 /* <reference.<1234567>.%020> */
4657 if (memcmp(start
, "<reference.<", 12) != 0)
4659 if (start
[12 + JIM_REFERENCE_TAGLEN
] != '>' || end
[0] != '>')
4661 /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
4662 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4663 if (!isrefchar(start
[12 + i
]))
4666 /* Extract info from the reference. */
4667 memcpy(refId
, start
+ 14 + JIM_REFERENCE_TAGLEN
, 20);
4669 /* Try to convert the ID into a jim_wide */
4670 if (Jim_StringToWide(refId
, &wideValue
, 10) != JIM_OK
)
4672 /* Check if the reference really exists! */
4673 he
= Jim_FindHashEntry(&interp
->references
, &wideValue
);
4675 Jim_SetResultFormatted(interp
, "invalid reference id \"%#s\"", objPtr
);
4679 /* Free the old internal repr and set the new one. */
4680 Jim_FreeIntRep(interp
, objPtr
);
4681 objPtr
->typePtr
= &referenceObjType
;
4682 objPtr
->internalRep
.refValue
.id
= wideValue
;
4683 objPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4687 Jim_SetResultFormatted(interp
, "expected reference but got \"%#s\"", objPtr
);
4691 /* Returns a new reference pointing to objPtr, having cmdNamePtr
4692 * as finalizer command (or NULL if there is no finalizer).
4693 * The returned reference object has refcount = 0. */
4694 Jim_Obj
*Jim_NewReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*tagPtr
, Jim_Obj
*cmdNamePtr
)
4696 struct Jim_Reference
*refPtr
;
4697 jim_wide wideValue
= interp
->referenceNextId
;
4702 /* Perform the Garbage Collection if needed. */
4703 Jim_CollectIfNeeded(interp
);
4705 refPtr
= Jim_Alloc(sizeof(*refPtr
));
4706 refPtr
->objPtr
= objPtr
;
4707 Jim_IncrRefCount(objPtr
);
4708 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4710 Jim_IncrRefCount(cmdNamePtr
);
4711 Jim_AddHashEntry(&interp
->references
, &wideValue
, refPtr
);
4712 refObjPtr
= Jim_NewObj(interp
);
4713 refObjPtr
->typePtr
= &referenceObjType
;
4714 refObjPtr
->bytes
= NULL
;
4715 refObjPtr
->internalRep
.refValue
.id
= interp
->referenceNextId
;
4716 refObjPtr
->internalRep
.refValue
.refPtr
= refPtr
;
4717 interp
->referenceNextId
++;
4718 /* Set the tag. Trimmed at JIM_REFERENCE_TAGLEN. Everything
4719 * that does not pass the 'isrefchar' test is replaced with '_' */
4720 tag
= Jim_GetString(tagPtr
, &tagLen
);
4721 if (tagLen
> JIM_REFERENCE_TAGLEN
)
4722 tagLen
= JIM_REFERENCE_TAGLEN
;
4723 for (i
= 0; i
< JIM_REFERENCE_TAGLEN
; i
++) {
4724 if (i
< tagLen
&& isrefchar(tag
[i
]))
4725 refPtr
->tag
[i
] = tag
[i
];
4727 refPtr
->tag
[i
] = '_';
4729 refPtr
->tag
[JIM_REFERENCE_TAGLEN
] = '\0';
4733 Jim_Reference
*Jim_GetReference(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
4735 if (objPtr
->typePtr
!= &referenceObjType
&& SetReferenceFromAny(interp
, objPtr
) == JIM_ERR
)
4737 return objPtr
->internalRep
.refValue
.refPtr
;
4740 int Jim_SetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*cmdNamePtr
)
4742 Jim_Reference
*refPtr
;
4744 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4746 Jim_IncrRefCount(cmdNamePtr
);
4747 if (refPtr
->finalizerCmdNamePtr
)
4748 Jim_DecrRefCount(interp
, refPtr
->finalizerCmdNamePtr
);
4749 refPtr
->finalizerCmdNamePtr
= cmdNamePtr
;
4753 int Jim_GetFinalizer(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
**cmdNamePtrPtr
)
4755 Jim_Reference
*refPtr
;
4757 if ((refPtr
= Jim_GetReference(interp
, objPtr
)) == NULL
)
4759 *cmdNamePtrPtr
= refPtr
->finalizerCmdNamePtr
;
4763 /* -----------------------------------------------------------------------------
4764 * References Garbage Collection
4765 * ---------------------------------------------------------------------------*/
4767 /* This the hash table type for the "MARK" phase of the GC */
4768 static const Jim_HashTableType JimRefMarkHashTableType
= {
4769 JimReferencesHTHashFunction
, /* hash function */
4770 JimReferencesHTKeyDup
, /* key dup */
4772 JimReferencesHTKeyCompare
, /* key compare */
4773 JimReferencesHTKeyDestructor
, /* key destructor */
4774 NULL
/* val destructor */
4777 /* Performs the garbage collection. */
4778 int Jim_Collect(Jim_Interp
*interp
)
4781 #ifndef JIM_BOOTSTRAP
4782 Jim_HashTable marks
;
4783 Jim_HashTableIterator
*htiter
;
4787 /* Avoid recursive calls */
4788 if (interp
->lastCollectId
== -1) {
4789 /* Jim_Collect() already running. Return just now. */
4792 interp
->lastCollectId
= -1;
4794 /* Mark all the references found into the 'mark' hash table.
4795 * The references are searched in every live object that
4796 * is of a type that can contain references. */
4797 Jim_InitHashTable(&marks
, &JimRefMarkHashTableType
, NULL
);
4798 objPtr
= interp
->liveList
;
4800 if (objPtr
->typePtr
== NULL
|| objPtr
->typePtr
->flags
& JIM_TYPE_REFERENCES
) {
4801 const char *str
, *p
;
4804 /* If the object is of type reference, to get the
4805 * Id is simple... */
4806 if (objPtr
->typePtr
== &referenceObjType
) {
4807 Jim_AddHashEntry(&marks
, &objPtr
->internalRep
.refValue
.id
, NULL
);
4809 printf("MARK (reference): %d refcount: %d" JIM_NL
,
4810 (int)objPtr
->internalRep
.refValue
.id
, objPtr
->refCount
);
4812 objPtr
= objPtr
->nextObjPtr
;
4815 /* Get the string repr of the object we want
4816 * to scan for references. */
4817 p
= str
= Jim_GetString(objPtr
, &len
);
4818 /* Skip objects too little to contain references. */
4819 if (len
< JIM_REFERENCE_SPACE
) {
4820 objPtr
= objPtr
->nextObjPtr
;
4823 /* Extract references from the object string repr. */
4829 if ((p
= strstr(p
, "<reference.<")) == NULL
)
4831 /* Check if it's a valid reference. */
4832 if (len
- (p
- str
) < JIM_REFERENCE_SPACE
)
4834 if (p
[41] != '>' || p
[19] != '>' || p
[20] != '.')
4836 for (i
= 21; i
<= 40; i
++)
4837 if (!isdigit(UCHAR(p
[i
])))
4840 memcpy(buf
, p
+ 21, 20);
4842 Jim_StringToWide(buf
, &id
, 10);
4844 /* Ok, a reference for the given ID
4845 * was found. Mark it. */
4846 Jim_AddHashEntry(&marks
, &id
, NULL
);
4848 printf("MARK: %d" JIM_NL
, (int)id
);
4850 p
+= JIM_REFERENCE_SPACE
;
4853 objPtr
= objPtr
->nextObjPtr
;
4856 /* Run the references hash table to destroy every reference that
4857 * is not referenced outside (not present in the mark HT). */
4858 htiter
= Jim_GetHashTableIterator(&interp
->references
);
4859 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
4860 const jim_wide
*refId
;
4861 Jim_Reference
*refPtr
;
4864 /* Check if in the mark phase we encountered
4865 * this reference. */
4866 if (Jim_FindHashEntry(&marks
, refId
) == NULL
) {
4868 printf("COLLECTING %d" JIM_NL
, (int)*refId
);
4871 /* Drop the reference, but call the
4872 * finalizer first if registered. */
4874 if (refPtr
->finalizerCmdNamePtr
) {
4875 char *refstr
= Jim_Alloc(JIM_REFERENCE_SPACE
+ 1);
4876 Jim_Obj
*objv
[3], *oldResult
;
4878 JimFormatReference(refstr
, refPtr
, *refId
);
4880 objv
[0] = refPtr
->finalizerCmdNamePtr
;
4881 objv
[1] = Jim_NewStringObjNoAlloc(interp
, refstr
, 32);
4882 objv
[2] = refPtr
->objPtr
;
4883 Jim_IncrRefCount(objv
[0]);
4884 Jim_IncrRefCount(objv
[1]);
4885 Jim_IncrRefCount(objv
[2]);
4887 /* Drop the reference itself */
4888 Jim_DeleteHashEntry(&interp
->references
, refId
);
4890 /* Call the finalizer. Errors ignored. */
4891 oldResult
= interp
->result
;
4892 Jim_IncrRefCount(oldResult
);
4893 Jim_EvalObjVector(interp
, 3, objv
);
4894 Jim_SetResult(interp
, oldResult
);
4895 Jim_DecrRefCount(interp
, oldResult
);
4897 Jim_DecrRefCount(interp
, objv
[0]);
4898 Jim_DecrRefCount(interp
, objv
[1]);
4899 Jim_DecrRefCount(interp
, objv
[2]);
4902 Jim_DeleteHashEntry(&interp
->references
, refId
);
4906 Jim_FreeHashTableIterator(htiter
);
4907 Jim_FreeHashTable(&marks
);
4908 interp
->lastCollectId
= interp
->referenceNextId
;
4909 interp
->lastCollectTime
= time(NULL
);
4910 #endif /* JIM_BOOTSTRAP */
4914 #define JIM_COLLECT_ID_PERIOD 5000
4915 #define JIM_COLLECT_TIME_PERIOD 300
4917 void Jim_CollectIfNeeded(Jim_Interp
*interp
)
4922 elapsedId
= interp
->referenceNextId
- interp
->lastCollectId
;
4923 elapsedTime
= time(NULL
) - interp
->lastCollectTime
;
4926 if (elapsedId
> JIM_COLLECT_ID_PERIOD
|| elapsedTime
> JIM_COLLECT_TIME_PERIOD
) {
4927 Jim_Collect(interp
);
4932 static int JimIsBigEndian(void)
4939 return uval
.c
[0] == 1;
4942 /* -----------------------------------------------------------------------------
4943 * Interpreter related functions
4944 * ---------------------------------------------------------------------------*/
4946 Jim_Interp
*Jim_CreateInterp(void)
4948 Jim_Interp
*i
= Jim_Alloc(sizeof(*i
));
4950 memset(i
, 0, sizeof(*i
));
4952 i
->maxNestingDepth
= JIM_MAX_NESTING_DEPTH
;
4953 i
->lastCollectTime
= time(NULL
);
4955 /* Note that we can create objects only after the
4956 * interpreter liveList and freeList pointers are
4957 * initialized to NULL. */
4958 Jim_InitHashTable(&i
->commands
, &JimCommandsHashTableType
, i
);
4959 #ifdef JIM_REFERENCES
4960 Jim_InitHashTable(&i
->references
, &JimReferencesHashTableType
, i
);
4962 Jim_InitHashTable(&i
->assocData
, &JimAssocDataHashTableType
, i
);
4963 Jim_InitHashTable(&i
->packages
, &JimStringKeyValCopyHashTableType
, NULL
);
4964 i
->framePtr
= i
->topFramePtr
= JimCreateCallFrame(i
, NULL
);
4965 i
->emptyObj
= Jim_NewEmptyStringObj(i
);
4966 i
->trueObj
= Jim_NewIntObj(i
, 1);
4967 i
->falseObj
= Jim_NewIntObj(i
, 0);
4968 i
->errorFileNameObj
= i
->emptyObj
;
4969 i
->result
= i
->emptyObj
;
4970 i
->stackTrace
= Jim_NewListObj(i
, NULL
, 0);
4971 i
->unknown
= Jim_NewStringObj(i
, "unknown", -1);
4972 i
->errorProc
= i
->emptyObj
;
4973 i
->currentScriptObj
= Jim_NewEmptyStringObj(i
);
4974 Jim_IncrRefCount(i
->emptyObj
);
4975 Jim_IncrRefCount(i
->errorFileNameObj
);
4976 Jim_IncrRefCount(i
->result
);
4977 Jim_IncrRefCount(i
->stackTrace
);
4978 Jim_IncrRefCount(i
->unknown
);
4979 Jim_IncrRefCount(i
->currentScriptObj
);
4980 Jim_IncrRefCount(i
->errorProc
);
4981 Jim_IncrRefCount(i
->trueObj
);
4982 Jim_IncrRefCount(i
->falseObj
);
4984 /* Initialize key variables every interpreter should contain */
4985 Jim_SetVariableStrWithStr(i
, JIM_LIBPATH
, TCL_LIBRARY
);
4986 Jim_SetVariableStrWithStr(i
, JIM_INTERACTIVE
, "0");
4988 Jim_SetVariableStrWithStr(i
, "tcl_platform(os)", TCL_PLATFORM_OS
);
4989 Jim_SetVariableStrWithStr(i
, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM
);
4990 Jim_SetVariableStrWithStr(i
, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR
);
4991 Jim_SetVariableStrWithStr(i
, "tcl_platform(byteOrder)", JimIsBigEndian() ? "bigEndian" : "littleEndian");
4992 Jim_SetVariableStrWithStr(i
, "tcl_platform(threaded)", "0");
4993 Jim_SetVariableStr(i
, "tcl_platform(pointerSize)", Jim_NewIntObj(i
, sizeof(void *)));
4994 Jim_SetVariableStr(i
, "tcl_platform(wordSize)", Jim_NewIntObj(i
, sizeof(jim_wide
)));
4999 void Jim_FreeInterp(Jim_Interp
*i
)
5001 Jim_CallFrame
*cf
= i
->framePtr
, *prevcf
, *nextcf
;
5002 Jim_Obj
*objPtr
, *nextObjPtr
;
5004 Jim_DecrRefCount(i
, i
->emptyObj
);
5005 Jim_DecrRefCount(i
, i
->trueObj
);
5006 Jim_DecrRefCount(i
, i
->falseObj
);
5007 Jim_DecrRefCount(i
, i
->result
);
5008 Jim_DecrRefCount(i
, i
->stackTrace
);
5009 Jim_DecrRefCount(i
, i
->errorProc
);
5010 Jim_DecrRefCount(i
, i
->unknown
);
5011 Jim_DecrRefCount(i
, i
->errorFileNameObj
);
5012 Jim_DecrRefCount(i
, i
->currentScriptObj
);
5013 Jim_FreeHashTable(&i
->commands
);
5014 #ifdef JIM_REFERENCES
5015 Jim_FreeHashTable(&i
->references
);
5017 Jim_FreeHashTable(&i
->packages
);
5018 Jim_Free(i
->prngState
);
5019 Jim_FreeHashTable(&i
->assocData
);
5020 JimDeleteLocalProcs(i
);
5022 /* Free the call frames list */
5024 prevcf
= cf
->parentCallFrame
;
5025 JimFreeCallFrame(i
, cf
, JIM_FCF_NONE
);
5028 /* Check that the live object list is empty, otherwise
5029 * there is a memory leak. */
5030 if (i
->liveList
!= NULL
) {
5031 objPtr
= i
->liveList
;
5033 printf(JIM_NL
"-------------------------------------" JIM_NL
);
5034 printf("Objects still in the free list:" JIM_NL
);
5036 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "string";
5038 printf("%p (%d) %-10s: '%.20s'" JIM_NL
,
5039 (void *)objPtr
, objPtr
->refCount
, type
, objPtr
->bytes
? objPtr
->bytes
: "(null)");
5040 if (objPtr
->typePtr
== &sourceObjType
) {
5041 printf("FILE %s LINE %d" JIM_NL
,
5042 Jim_String(objPtr
->internalRep
.sourceValue
.fileNameObj
),
5043 objPtr
->internalRep
.sourceValue
.lineNumber
);
5045 objPtr
= objPtr
->nextObjPtr
;
5047 printf("-------------------------------------" JIM_NL JIM_NL
);
5048 JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
5050 /* Free all the freed objects. */
5051 objPtr
= i
->freeList
;
5053 nextObjPtr
= objPtr
->nextObjPtr
;
5055 objPtr
= nextObjPtr
;
5057 /* Free cached CallFrame structures */
5058 cf
= i
->freeFramesList
;
5060 nextcf
= cf
->nextFramePtr
;
5061 if (cf
->vars
.table
!= NULL
)
5062 Jim_Free(cf
->vars
.table
);
5067 Jim_FreeLoadHandles(i
);
5070 /* Free the interpreter structure. */
5074 /* Returns the call frame relative to the level represented by
5075 * levelObjPtr. If levelObjPtr == NULL, the * level is assumed to be '1'.
5077 * This function accepts the 'level' argument in the form
5078 * of the commands [uplevel] and [upvar].
5080 * For a function accepting a relative integer as level suitable
5081 * for implementation of [info level ?level?] check the
5082 * JimGetCallFrameByInteger() function.
5084 * Returns NULL on error.
5086 Jim_CallFrame
*Jim_GetCallFrameByLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5090 Jim_CallFrame
*framePtr
;
5093 str
= Jim_String(levelObjPtr
);
5094 if (str
[0] == '#') {
5097 level
= strtol(str
+ 1, &endptr
, 0);
5098 if (str
[1] == '\0' || endptr
[0] != '\0') {
5103 if (Jim_GetLong(interp
, levelObjPtr
, &level
) != JIM_OK
|| level
< 0) {
5107 /* Convert from a relative to an absolute level */
5108 level
= interp
->framePtr
->level
- level
;
5113 str
= "1"; /* Needed to format the error message. */
5114 level
= interp
->framePtr
->level
- 1;
5118 return interp
->topFramePtr
;
5122 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5123 if (framePtr
->level
== level
) {
5129 Jim_SetResultFormatted(interp
, "bad level \"%s\"", str
);
5133 /* Similar to Jim_GetCallFrameByLevel() but the level is specified
5134 * as a relative integer like in the [info level ?level?] command.
5136 static Jim_CallFrame
*JimGetCallFrameByInteger(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
)
5139 Jim_CallFrame
*framePtr
;
5141 if (Jim_GetLong(interp
, levelObjPtr
, &level
) == JIM_OK
) {
5143 /* Convert from a relative to an absolute level */
5144 level
= interp
->framePtr
->level
+ level
;
5148 return interp
->topFramePtr
;
5152 for (framePtr
= interp
->framePtr
; framePtr
; framePtr
= framePtr
->parentCallFrame
) {
5153 if (framePtr
->level
== level
) {
5159 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
5163 static void JimResetStackTrace(Jim_Interp
*interp
)
5165 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5166 interp
->stackTrace
= Jim_NewListObj(interp
, NULL
, 0);
5167 Jim_IncrRefCount(interp
->stackTrace
);
5170 static void JimSetStackTrace(Jim_Interp
*interp
, Jim_Obj
*stackTraceObj
)
5174 /* Increment reference first in case these are the same object */
5175 Jim_IncrRefCount(stackTraceObj
);
5176 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5177 interp
->stackTrace
= stackTraceObj
;
5178 interp
->errorFlag
= 1;
5180 /* This is a bit ugly.
5181 * If the filename of the last entry of the stack trace is empty,
5182 * the next stack level should be added.
5184 len
= Jim_ListLength(interp
, interp
->stackTrace
);
5186 Jim_Obj
*filenameObj
;
5188 Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &filenameObj
, JIM_NONE
);
5190 Jim_GetString(filenameObj
, &len
);
5192 if (!Jim_Length(filenameObj
)) {
5193 interp
->addStackTrace
= 1;
5198 /* Returns 1 if the stack trace information was used or 0 if not */
5199 static void JimAppendStackTrace(Jim_Interp
*interp
, const char *procname
,
5200 Jim_Obj
*fileNameObj
, int linenr
)
5202 if (strcmp(procname
, "unknown") == 0) {
5205 if (!*procname
&& !Jim_Length(fileNameObj
)) {
5206 /* No useful info here */
5210 if (Jim_IsShared(interp
->stackTrace
)) {
5211 Jim_DecrRefCount(interp
, interp
->stackTrace
);
5212 interp
->stackTrace
= Jim_DuplicateObj(interp
, interp
->stackTrace
);
5213 Jim_IncrRefCount(interp
->stackTrace
);
5216 /* If we have no procname but the previous element did, merge with that frame */
5217 if (!*procname
&& Jim_Length(fileNameObj
)) {
5218 /* Just a filename. Check the previous entry */
5219 int len
= Jim_ListLength(interp
, interp
->stackTrace
);
5223 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 3, &objPtr
, JIM_NONE
) == JIM_OK
&& Jim_Length(objPtr
)) {
5224 /* Yes, the previous level had procname */
5225 if (Jim_ListIndex(interp
, interp
->stackTrace
, len
- 2, &objPtr
, JIM_NONE
) == JIM_OK
&& !Jim_Length(objPtr
)) {
5226 /* But no filename, so merge the new info with that frame */
5227 ListSetIndex(interp
, interp
->stackTrace
, len
- 2, fileNameObj
, 0);
5228 ListSetIndex(interp
, interp
->stackTrace
, len
- 1, Jim_NewIntObj(interp
, linenr
), 0);
5235 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewStringObj(interp
, procname
, -1));
5236 Jim_ListAppendElement(interp
, interp
->stackTrace
, fileNameObj
);
5237 Jim_ListAppendElement(interp
, interp
->stackTrace
, Jim_NewIntObj(interp
, linenr
));
5240 int Jim_SetAssocData(Jim_Interp
*interp
, const char *key
, Jim_InterpDeleteProc
* delProc
,
5243 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) Jim_Alloc(sizeof(AssocDataValue
));
5245 assocEntryPtr
->delProc
= delProc
;
5246 assocEntryPtr
->data
= data
;
5247 return Jim_AddHashEntry(&interp
->assocData
, key
, assocEntryPtr
);
5250 void *Jim_GetAssocData(Jim_Interp
*interp
, const char *key
)
5252 Jim_HashEntry
*entryPtr
= Jim_FindHashEntry(&interp
->assocData
, key
);
5254 if (entryPtr
!= NULL
) {
5255 AssocDataValue
*assocEntryPtr
= (AssocDataValue
*) entryPtr
->u
.val
;
5257 return assocEntryPtr
->data
;
5262 int Jim_DeleteAssocData(Jim_Interp
*interp
, const char *key
)
5264 return Jim_DeleteHashEntry(&interp
->assocData
, key
);
5267 int Jim_GetExitCode(Jim_Interp
*interp
)
5269 return interp
->exitCode
;
5272 /* -----------------------------------------------------------------------------
5274 * ---------------------------------------------------------------------------*/
5275 #define JIM_INTEGER_SPACE 24
5277 static void UpdateStringOfInt(struct Jim_Obj
*objPtr
);
5278 static int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
);
5280 static const Jim_ObjType intObjType
= {
5288 /* A coerced double is closer to an int than a double.
5289 * It is an int value temporarily masquerading as a double value.
5290 * i.e. it has the same string value as an int and Jim_GetWide()
5291 * succeeds, but also Jim_GetDouble() returns the value directly.
5293 static const Jim_ObjType coercedDoubleObjType
= {
5302 void UpdateStringOfInt(struct Jim_Obj
*objPtr
)
5305 char buf
[JIM_INTEGER_SPACE
+ 1];
5307 len
= Jim_WideToString(buf
, JimWideValue(objPtr
));
5308 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5309 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5310 objPtr
->length
= len
;
5313 int SetIntFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
5318 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5319 /* Simple switcheroo */
5320 objPtr
->typePtr
= &intObjType
;
5324 /* Get the string representation */
5325 str
= Jim_String(objPtr
);
5326 /* Try to convert into a jim_wide */
5327 if (Jim_StringToWide(str
, &wideValue
, 0) != JIM_OK
) {
5328 if (flags
& JIM_ERRMSG
) {
5329 Jim_SetResultFormatted(interp
, "expected integer but got \"%#s\"", objPtr
);
5333 if ((wideValue
== JIM_WIDE_MIN
|| wideValue
== JIM_WIDE_MAX
) && errno
== ERANGE
) {
5334 Jim_SetResultString(interp
, "Integer value too big to be represented", -1);
5337 /* Free the old internal repr and set the new one. */
5338 Jim_FreeIntRep(interp
, objPtr
);
5339 objPtr
->typePtr
= &intObjType
;
5340 objPtr
->internalRep
.wideValue
= wideValue
;
5344 #ifdef JIM_OPTIMIZATION
5345 static int JimIsWide(Jim_Obj
*objPtr
)
5347 return objPtr
->typePtr
== &intObjType
;
5351 int Jim_GetWide(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5353 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_ERRMSG
) == JIM_ERR
)
5355 *widePtr
= JimWideValue(objPtr
);
5359 /* Get a wide but does not set an error if the format is bad. */
5360 static int JimGetWideNoErr(Jim_Interp
*interp
, Jim_Obj
*objPtr
, jim_wide
* widePtr
)
5362 if (objPtr
->typePtr
!= &intObjType
&& SetIntFromAny(interp
, objPtr
, JIM_NONE
) == JIM_ERR
)
5364 *widePtr
= JimWideValue(objPtr
);
5368 int Jim_GetLong(Jim_Interp
*interp
, Jim_Obj
*objPtr
, long *longPtr
)
5373 retval
= Jim_GetWide(interp
, objPtr
, &wideValue
);
5374 if (retval
== JIM_OK
) {
5375 *longPtr
= (long)wideValue
;
5381 Jim_Obj
*Jim_NewIntObj(Jim_Interp
*interp
, jim_wide wideValue
)
5385 objPtr
= Jim_NewObj(interp
);
5386 objPtr
->typePtr
= &intObjType
;
5387 objPtr
->bytes
= NULL
;
5388 objPtr
->internalRep
.wideValue
= wideValue
;
5392 /* -----------------------------------------------------------------------------
5394 * ---------------------------------------------------------------------------*/
5395 #define JIM_DOUBLE_SPACE 30
5397 static void UpdateStringOfDouble(struct Jim_Obj
*objPtr
);
5398 static int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5400 static const Jim_ObjType doubleObjType
= {
5404 UpdateStringOfDouble
,
5408 void UpdateStringOfDouble(struct Jim_Obj
*objPtr
)
5411 char buf
[JIM_DOUBLE_SPACE
+ 1];
5413 len
= Jim_DoubleToString(buf
, objPtr
->internalRep
.doubleValue
);
5414 objPtr
->bytes
= Jim_Alloc(len
+ 1);
5415 memcpy(objPtr
->bytes
, buf
, len
+ 1);
5416 objPtr
->length
= len
;
5419 int SetDoubleFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5425 /* Preserve the string representation.
5426 * Needed so we can convert back to int without loss
5428 str
= Jim_String(objPtr
);
5430 #ifdef HAVE_LONG_LONG
5431 /* Assume a 53 bit mantissa */
5432 #define MIN_INT_IN_DOUBLE -(1LL << 53)
5433 #define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
5435 if (objPtr
->typePtr
== &intObjType
5436 && JimWideValue(objPtr
) >= MIN_INT_IN_DOUBLE
5437 && JimWideValue(objPtr
) <= MAX_INT_IN_DOUBLE
) {
5439 /* Direct conversion to coerced double */
5440 objPtr
->typePtr
= &coercedDoubleObjType
;
5445 if (Jim_StringToWide(str
, &wideValue
, 10) == JIM_OK
) {
5446 /* Managed to convert to an int, so we can use this as a cooerced double */
5447 Jim_FreeIntRep(interp
, objPtr
);
5448 objPtr
->typePtr
= &coercedDoubleObjType
;
5449 objPtr
->internalRep
.wideValue
= wideValue
;
5453 /* Try to convert into a double */
5454 if (Jim_StringToDouble(str
, &doubleValue
) != JIM_OK
) {
5455 Jim_SetResultFormatted(interp
, "expected number but got \"%#s\"", objPtr
);
5458 /* Free the old internal repr and set the new one. */
5459 Jim_FreeIntRep(interp
, objPtr
);
5461 objPtr
->typePtr
= &doubleObjType
;
5462 objPtr
->internalRep
.doubleValue
= doubleValue
;
5466 int Jim_GetDouble(Jim_Interp
*interp
, Jim_Obj
*objPtr
, double *doublePtr
)
5468 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5469 *doublePtr
= JimWideValue(objPtr
);
5472 if (objPtr
->typePtr
!= &doubleObjType
&& SetDoubleFromAny(interp
, objPtr
) == JIM_ERR
)
5475 if (objPtr
->typePtr
== &coercedDoubleObjType
) {
5476 *doublePtr
= JimWideValue(objPtr
);
5479 *doublePtr
= objPtr
->internalRep
.doubleValue
;
5484 Jim_Obj
*Jim_NewDoubleObj(Jim_Interp
*interp
, double doubleValue
)
5488 objPtr
= Jim_NewObj(interp
);
5489 objPtr
->typePtr
= &doubleObjType
;
5490 objPtr
->bytes
= NULL
;
5491 objPtr
->internalRep
.doubleValue
= doubleValue
;
5495 /* -----------------------------------------------------------------------------
5497 * ---------------------------------------------------------------------------*/
5498 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
);
5499 static void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
5500 static void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
5501 static void UpdateStringOfList(struct Jim_Obj
*objPtr
);
5502 static int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
5504 /* Note that while the elements of the list may contain references,
5505 * the list object itself can't. This basically means that the
5506 * list object string representation as a whole can't contain references
5507 * that are not presents in the single elements. */
5508 static const Jim_ObjType listObjType
= {
5510 FreeListInternalRep
,
5516 void FreeListInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
5520 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5521 Jim_DecrRefCount(interp
, objPtr
->internalRep
.listValue
.ele
[i
]);
5523 Jim_Free(objPtr
->internalRep
.listValue
.ele
);
5526 void DupListInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
5530 JIM_NOTUSED(interp
);
5532 dupPtr
->internalRep
.listValue
.len
= srcPtr
->internalRep
.listValue
.len
;
5533 dupPtr
->internalRep
.listValue
.maxLen
= srcPtr
->internalRep
.listValue
.maxLen
;
5534 dupPtr
->internalRep
.listValue
.ele
=
5535 Jim_Alloc(sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.maxLen
);
5536 memcpy(dupPtr
->internalRep
.listValue
.ele
, srcPtr
->internalRep
.listValue
.ele
,
5537 sizeof(Jim_Obj
*) * srcPtr
->internalRep
.listValue
.len
);
5538 for (i
= 0; i
< dupPtr
->internalRep
.listValue
.len
; i
++) {
5539 Jim_IncrRefCount(dupPtr
->internalRep
.listValue
.ele
[i
]);
5541 dupPtr
->typePtr
= &listObjType
;
5544 /* The following function checks if a given string can be encoded
5545 * into a list element without any kind of quoting, surrounded by braces,
5546 * or using escapes to quote. */
5547 #define JIM_ELESTR_SIMPLE 0
5548 #define JIM_ELESTR_BRACE 1
5549 #define JIM_ELESTR_QUOTE 2
5550 static int ListElementQuotingType(const char *s
, int len
)
5552 int i
, level
, blevel
, trySimple
= 1;
5554 /* Try with the SIMPLE case */
5556 return JIM_ELESTR_BRACE
;
5558 return JIM_ELESTR_BRACE
;
5559 if (s
[0] == '"' || s
[0] == '{') {
5563 for (i
= 0; i
< len
; i
++) {
5583 return JIM_ELESTR_SIMPLE
;
5586 /* Test if it's possible to do with braces */
5587 if (s
[len
- 1] == '\\')
5588 return JIM_ELESTR_QUOTE
;
5591 for (i
= 0; i
< len
; i
++) {
5599 return JIM_ELESTR_QUOTE
;
5608 if (s
[i
+ 1] == '\n')
5609 return JIM_ELESTR_QUOTE
;
5610 else if (s
[i
+ 1] != '\0')
5616 return JIM_ELESTR_QUOTE
;
5621 return JIM_ELESTR_BRACE
;
5622 for (i
= 0; i
< len
; i
++) {
5636 return JIM_ELESTR_BRACE
;
5640 return JIM_ELESTR_SIMPLE
;
5642 return JIM_ELESTR_QUOTE
;
5645 /* Returns the malloc-ed representation of a string
5646 * using backslash to quote special chars. */
5647 static char *BackslashQuoteString(const char *s
, int len
, int *qlenPtr
)
5649 char *q
= Jim_Alloc(len
* 2 + 1), *p
;
5701 static void UpdateStringOfList(struct Jim_Obj
*objPtr
)
5703 int i
, bufLen
, realLength
;
5707 Jim_Obj
**ele
= objPtr
->internalRep
.listValue
.ele
;
5709 /* (Over) Estimate the space needed. */
5710 quotingType
= Jim_Alloc(sizeof(int) * objPtr
->internalRep
.listValue
.len
+ 1);
5712 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5715 strRep
= Jim_GetString(ele
[i
], &len
);
5716 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
5717 switch (quotingType
[i
]) {
5718 case JIM_ELESTR_SIMPLE
:
5721 case JIM_ELESTR_BRACE
:
5724 case JIM_ELESTR_QUOTE
:
5728 bufLen
++; /* elements separator. */
5732 /* Generate the string rep. */
5733 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
5735 for (i
= 0; i
< objPtr
->internalRep
.listValue
.len
; i
++) {
5739 strRep
= Jim_GetString(ele
[i
], &len
);
5741 switch (quotingType
[i
]) {
5742 case JIM_ELESTR_SIMPLE
:
5743 memcpy(p
, strRep
, len
);
5747 case JIM_ELESTR_BRACE
:
5749 memcpy(p
, strRep
, len
);
5752 realLength
+= len
+ 2;
5754 case JIM_ELESTR_QUOTE
:
5755 q
= BackslashQuoteString(strRep
, len
, &qlen
);
5762 /* Add a separating space */
5763 if (i
+ 1 != objPtr
->internalRep
.listValue
.len
) {
5768 *p
= '\0'; /* nul term. */
5769 objPtr
->length
= realLength
;
5770 Jim_Free(quotingType
);
5773 int SetListFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
5775 struct JimParserCtx parser
;
5778 Jim_Obj
*fileNameObj
;
5781 /* Try to preserve information about filename / line number */
5782 if (objPtr
->typePtr
== &sourceObjType
) {
5783 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
5784 linenr
= objPtr
->internalRep
.sourceValue
.lineNumber
;
5787 fileNameObj
= interp
->emptyObj
;
5790 Jim_IncrRefCount(fileNameObj
);
5792 /* Get the string representation */
5793 str
= Jim_GetString(objPtr
, &strLen
);
5795 /* Free the old internal repr just now and initialize the
5796 * new one just now. The string->list conversion can't fail. */
5797 Jim_FreeIntRep(interp
, objPtr
);
5798 objPtr
->typePtr
= &listObjType
;
5799 objPtr
->internalRep
.listValue
.len
= 0;
5800 objPtr
->internalRep
.listValue
.maxLen
= 0;
5801 objPtr
->internalRep
.listValue
.ele
= NULL
;
5803 /* Convert into a list */
5804 JimParserInit(&parser
, str
, strLen
, linenr
);
5805 while (!parser
.eof
) {
5806 Jim_Obj
*elementPtr
;
5808 JimParseList(&parser
);
5809 if (parser
.tt
!= JIM_TT_STR
&& parser
.tt
!= JIM_TT_ESC
)
5811 elementPtr
= JimParserGetTokenObj(interp
, &parser
);
5812 JimSetSourceInfo(interp
, elementPtr
, fileNameObj
, parser
.tline
);
5813 ListAppendElement(objPtr
, elementPtr
);
5815 Jim_DecrRefCount(interp
, fileNameObj
);
5819 Jim_Obj
*Jim_NewListObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
5824 objPtr
= Jim_NewObj(interp
);
5825 objPtr
->typePtr
= &listObjType
;
5826 objPtr
->bytes
= NULL
;
5827 objPtr
->internalRep
.listValue
.ele
= NULL
;
5828 objPtr
->internalRep
.listValue
.len
= 0;
5829 objPtr
->internalRep
.listValue
.maxLen
= 0;
5830 for (i
= 0; i
< len
; i
++) {
5831 ListAppendElement(objPtr
, elements
[i
]);
5836 /* Return a vector of Jim_Obj with the elements of a Jim list, and the
5837 * length of the vector. Note that the user of this function should make
5838 * sure that the list object can't shimmer while the vector returned
5839 * is in use, this vector is the one stored inside the internal representation
5840 * of the list object. This function is not exported, extensions should
5841 * always access to the List object elements using Jim_ListIndex(). */
5842 static void JimListGetElements(Jim_Interp
*interp
, Jim_Obj
*listObj
, int *listLen
,
5845 *listLen
= Jim_ListLength(interp
, listObj
);
5846 *listVec
= listObj
->internalRep
.listValue
.ele
;
5849 /* Sorting uses ints, but commands may return wide */
5850 static int JimSign(jim_wide w
)
5861 /* ListSortElements type values */
5875 int (*subfn
)(Jim_Obj
**, Jim_Obj
**);
5878 static struct lsort_info
*sort_info
;
5880 static int ListSortIndexHelper(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5882 Jim_Obj
*lObj
, *rObj
;
5884 if (Jim_ListIndex(sort_info
->interp
, *lhsObj
, sort_info
->index
, &lObj
, JIM_ERRMSG
) != JIM_OK
||
5885 Jim_ListIndex(sort_info
->interp
, *rhsObj
, sort_info
->index
, &rObj
, JIM_ERRMSG
) != JIM_OK
) {
5886 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5888 return sort_info
->subfn(&lObj
, &rObj
);
5891 /* Sort the internal rep of a list. */
5892 static int ListSortString(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5894 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 0) * sort_info
->order
;
5897 static int ListSortStringNoCase(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5899 return Jim_StringCompareObj(sort_info
->interp
, *lhsObj
, *rhsObj
, 1) * sort_info
->order
;
5902 static int ListSortInteger(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5904 jim_wide lhs
= 0, rhs
= 0;
5906 if (Jim_GetWide(sort_info
->interp
, *lhsObj
, &lhs
) != JIM_OK
||
5907 Jim_GetWide(sort_info
->interp
, *rhsObj
, &rhs
) != JIM_OK
) {
5908 longjmp(sort_info
->jmpbuf
, JIM_ERR
);
5911 return JimSign(lhs
- rhs
) * sort_info
->order
;
5914 static int ListSortCommand(Jim_Obj
**lhsObj
, Jim_Obj
**rhsObj
)
5916 Jim_Obj
*compare_script
;
5921 /* This must be a valid list */
5922 compare_script
= Jim_DuplicateObj(sort_info
->interp
, sort_info
->command
);
5923 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *lhsObj
);
5924 Jim_ListAppendElement(sort_info
->interp
, compare_script
, *rhsObj
);
5926 rc
= Jim_EvalObj(sort_info
->interp
, compare_script
);
5928 if (rc
!= JIM_OK
|| Jim_GetWide(sort_info
->interp
, Jim_GetResult(sort_info
->interp
), &ret
) != JIM_OK
) {
5929 longjmp(sort_info
->jmpbuf
, rc
);
5932 return JimSign(ret
) * sort_info
->order
;
5935 /* Sort a list *in place*. MUST be called with non-shared objects. */
5936 static int ListSortElements(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, struct lsort_info
*info
)
5938 struct lsort_info
*prev_info
;
5940 typedef int (qsort_comparator
) (const void *, const void *);
5941 int (*fn
) (Jim_Obj
**, Jim_Obj
**);
5946 JimPanic((Jim_IsShared(listObjPtr
), "Jim_ListSortElements called with shared object"));
5947 if (!Jim_IsList(listObjPtr
))
5948 SetListFromAny(interp
, listObjPtr
);
5950 /* Allow lsort to be called reentrantly */
5951 prev_info
= sort_info
;
5954 vector
= listObjPtr
->internalRep
.listValue
.ele
;
5955 len
= listObjPtr
->internalRep
.listValue
.len
;
5956 switch (info
->type
) {
5957 case JIM_LSORT_ASCII
:
5958 fn
= ListSortString
;
5960 case JIM_LSORT_NOCASE
:
5961 fn
= ListSortStringNoCase
;
5963 case JIM_LSORT_INTEGER
:
5964 fn
= ListSortInteger
;
5966 case JIM_LSORT_COMMAND
:
5967 fn
= ListSortCommand
;
5970 fn
= NULL
; /* avoid warning */
5971 JimPanic((1, "ListSort called with invalid sort type"));
5974 if (info
->indexed
) {
5975 /* Need to interpose a "list index" function */
5977 fn
= ListSortIndexHelper
;
5980 if ((rc
= setjmp(info
->jmpbuf
)) == 0) {
5981 qsort(vector
, len
, sizeof(Jim_Obj
*), (qsort_comparator
*) fn
);
5983 Jim_InvalidateStringRep(listObjPtr
);
5984 sort_info
= prev_info
;
5989 /* This is the low-level function to insert elements into a list.
5990 * The higher-level Jim_ListInsertElements() performs shared object
5991 * check and invalidate the string repr. This version is used
5992 * in the internals of the List Object and is not exported.
5994 * NOTE: this function can be called only against objects
5995 * with internal type of List. */
5996 static void ListInsertElements(Jim_Obj
*listPtr
, int idx
, int elemc
, Jim_Obj
*const *elemVec
)
5998 int currentLen
= listPtr
->internalRep
.listValue
.len
;
5999 int requiredLen
= currentLen
+ elemc
;
6003 if (requiredLen
> listPtr
->internalRep
.listValue
.maxLen
) {
6004 int maxLen
= requiredLen
* 2;
6006 listPtr
->internalRep
.listValue
.ele
=
6007 Jim_Realloc(listPtr
->internalRep
.listValue
.ele
, sizeof(Jim_Obj
*) * maxLen
);
6008 listPtr
->internalRep
.listValue
.maxLen
= maxLen
;
6010 point
= listPtr
->internalRep
.listValue
.ele
+ idx
;
6011 memmove(point
+ elemc
, point
, (currentLen
- idx
) * sizeof(Jim_Obj
*));
6012 for (i
= 0; i
< elemc
; ++i
) {
6013 point
[i
] = elemVec
[i
];
6014 Jim_IncrRefCount(point
[i
]);
6016 listPtr
->internalRep
.listValue
.len
+= elemc
;
6019 /* Convenience call to ListInsertElements() to append a single element.
6021 static void ListAppendElement(Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6023 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
, 1, &objPtr
);
6027 /* Appends every element of appendListPtr into listPtr.
6028 * Both have to be of the list type.
6029 * Convenience call to ListInsertElements()
6031 static void ListAppendList(Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6033 ListInsertElements(listPtr
, listPtr
->internalRep
.listValue
.len
,
6034 appendListPtr
->internalRep
.listValue
.len
, appendListPtr
->internalRep
.listValue
.ele
);
6037 void Jim_ListAppendElement(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*objPtr
)
6039 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendElement called with shared object"));
6040 if (!Jim_IsList(listPtr
))
6041 SetListFromAny(interp
, listPtr
);
6042 Jim_InvalidateStringRep(listPtr
);
6043 ListAppendElement(listPtr
, objPtr
);
6046 void Jim_ListAppendList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*appendListPtr
)
6048 JimPanic((Jim_IsShared(listPtr
), "Jim_ListAppendList called with shared object"));
6049 if (!Jim_IsList(listPtr
))
6050 SetListFromAny(interp
, listPtr
);
6051 Jim_InvalidateStringRep(listPtr
);
6052 ListAppendList(listPtr
, appendListPtr
);
6055 int Jim_ListLength(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6057 if (!Jim_IsList(objPtr
))
6058 SetListFromAny(interp
, objPtr
);
6059 return objPtr
->internalRep
.listValue
.len
;
6062 void Jim_ListInsertElements(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6063 int objc
, Jim_Obj
*const *objVec
)
6065 JimPanic((Jim_IsShared(listPtr
), "Jim_ListInsertElement called with shared object"));
6066 if (!Jim_IsList(listPtr
))
6067 SetListFromAny(interp
, listPtr
);
6068 if (idx
>= 0 && idx
> listPtr
->internalRep
.listValue
.len
)
6069 idx
= listPtr
->internalRep
.listValue
.len
;
6072 Jim_InvalidateStringRep(listPtr
);
6073 ListInsertElements(listPtr
, idx
, objc
, objVec
);
6076 int Jim_ListIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
, Jim_Obj
**objPtrPtr
, int flags
)
6078 if (!Jim_IsList(listPtr
))
6079 SetListFromAny(interp
, listPtr
);
6080 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6081 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6082 if (flags
& JIM_ERRMSG
) {
6083 Jim_SetResultString(interp
, "list index out of range", -1);
6089 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6090 *objPtrPtr
= listPtr
->internalRep
.listValue
.ele
[idx
];
6094 static int ListSetIndex(Jim_Interp
*interp
, Jim_Obj
*listPtr
, int idx
,
6095 Jim_Obj
*newObjPtr
, int flags
)
6097 if (!Jim_IsList(listPtr
))
6098 SetListFromAny(interp
, listPtr
);
6099 if ((idx
>= 0 && idx
>= listPtr
->internalRep
.listValue
.len
) ||
6100 (idx
< 0 && (-idx
- 1) >= listPtr
->internalRep
.listValue
.len
)) {
6101 if (flags
& JIM_ERRMSG
) {
6102 Jim_SetResultString(interp
, "list index out of range", -1);
6107 idx
= listPtr
->internalRep
.listValue
.len
+ idx
;
6108 Jim_DecrRefCount(interp
, listPtr
->internalRep
.listValue
.ele
[idx
]);
6109 listPtr
->internalRep
.listValue
.ele
[idx
] = newObjPtr
;
6110 Jim_IncrRefCount(newObjPtr
);
6114 /* Modify the list stored into the variable named 'varNamePtr'
6115 * setting the element specified by the 'indexc' indexes objects in 'indexv',
6116 * with the new element 'newObjptr'. */
6117 int Jim_SetListIndex(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6118 Jim_Obj
*const *indexv
, int indexc
, Jim_Obj
*newObjPtr
)
6120 Jim_Obj
*varObjPtr
, *objPtr
, *listObjPtr
;
6123 varObjPtr
= objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
| JIM_UNSHARED
);
6126 if ((shared
= Jim_IsShared(objPtr
)))
6127 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6128 for (i
= 0; i
< indexc
- 1; i
++) {
6129 listObjPtr
= objPtr
;
6130 if (Jim_GetIndex(interp
, indexv
[i
], &idx
) != JIM_OK
)
6132 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_ERRMSG
) != JIM_OK
) {
6135 if (Jim_IsShared(objPtr
)) {
6136 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6137 ListSetIndex(interp
, listObjPtr
, idx
, objPtr
, JIM_NONE
);
6139 Jim_InvalidateStringRep(listObjPtr
);
6141 if (Jim_GetIndex(interp
, indexv
[indexc
- 1], &idx
) != JIM_OK
)
6143 if (ListSetIndex(interp
, objPtr
, idx
, newObjPtr
, JIM_ERRMSG
) == JIM_ERR
)
6145 Jim_InvalidateStringRep(objPtr
);
6146 Jim_InvalidateStringRep(varObjPtr
);
6147 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
)
6149 Jim_SetResult(interp
, varObjPtr
);
6153 Jim_FreeNewObj(interp
, varObjPtr
);
6158 Jim_Obj
*Jim_ConcatObj(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
6162 /* If all the objects in objv are lists,
6163 * it's possible to return a list as result, that's the
6164 * concatenation of all the lists. */
6165 for (i
= 0; i
< objc
; i
++) {
6166 if (!Jim_IsList(objv
[i
]))
6170 Jim_Obj
*objPtr
= Jim_NewListObj(interp
, NULL
, 0);
6172 for (i
= 0; i
< objc
; i
++)
6173 Jim_ListAppendList(interp
, objPtr
, objv
[i
]);
6177 /* Else... we have to glue strings together */
6178 int len
= 0, objLen
;
6181 /* Compute the length */
6182 for (i
= 0; i
< objc
; i
++) {
6183 Jim_GetString(objv
[i
], &objLen
);
6188 /* Create the string rep, and a string object holding it. */
6189 p
= bytes
= Jim_Alloc(len
+ 1);
6190 for (i
= 0; i
< objc
; i
++) {
6191 const char *s
= Jim_GetString(objv
[i
], &objLen
);
6193 /* Remove leading space */
6194 while (objLen
&& (*s
== ' ' || *s
== '\t' || *s
== '\n')) {
6199 /* And trailing space */
6200 while (objLen
&& (s
[objLen
- 1] == ' ' ||
6201 s
[objLen
- 1] == '\n' || s
[objLen
- 1] == '\t')) {
6202 /* Handle trailing backslash-space case */
6203 if (objLen
> 1 && s
[objLen
- 2] == '\\') {
6209 memcpy(p
, s
, objLen
);
6211 if (objLen
&& i
+ 1 != objc
) {
6214 else if (i
+ 1 != objc
) {
6215 /* Drop the space calcuated for this
6216 * element that is instead null. */
6221 return Jim_NewStringObjNoAlloc(interp
, bytes
, len
);
6225 /* Returns a list composed of the elements in the specified range.
6226 * first and start are directly accepted as Jim_Objects and
6227 * processed for the end?-index? case. */
6228 Jim_Obj
*Jim_ListRange(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*firstObjPtr
,
6229 Jim_Obj
*lastObjPtr
)
6234 if (Jim_GetIndex(interp
, firstObjPtr
, &first
) != JIM_OK
||
6235 Jim_GetIndex(interp
, lastObjPtr
, &last
) != JIM_OK
)
6237 len
= Jim_ListLength(interp
, listObjPtr
); /* will convert into list */
6238 first
= JimRelToAbsIndex(len
, first
);
6239 last
= JimRelToAbsIndex(len
, last
);
6240 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
6241 if (first
== 0 && last
== len
) {
6244 return Jim_NewListObj(interp
, listObjPtr
->internalRep
.listValue
.ele
+ first
, rangeLen
);
6247 /* -----------------------------------------------------------------------------
6249 * ---------------------------------------------------------------------------*/
6250 static void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6251 static void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
6252 static void UpdateStringOfDict(struct Jim_Obj
*objPtr
);
6253 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6255 /* Dict HashTable Type.
6257 * Keys and Values are Jim objects. */
6259 static unsigned int JimObjectHTHashFunction(const void *key
)
6262 Jim_Obj
*objPtr
= (Jim_Obj
*)key
;
6265 str
= Jim_GetString(objPtr
, &len
);
6266 return Jim_GenHashFunction((unsigned char *)str
, len
);
6269 static int JimObjectHTKeyCompare(void *privdata
, const void *key1
, const void *key2
)
6271 JIM_NOTUSED(privdata
);
6273 return Jim_StringEqObj((Jim_Obj
*)key1
, (Jim_Obj
*)key2
);
6276 static void JimObjectHTKeyValDestructor(void *interp
, void *val
)
6278 Jim_Obj
*objPtr
= val
;
6280 Jim_DecrRefCount(interp
, objPtr
);
6283 static const Jim_HashTableType JimDictHashTableType
= {
6284 JimObjectHTHashFunction
, /* hash function */
6287 JimObjectHTKeyCompare
, /* key compare */
6288 (void (*)(void *, const void *)) /* ATTENTION: const cast */
6289 JimObjectHTKeyValDestructor
, /* key destructor */
6290 JimObjectHTKeyValDestructor
/* val destructor */
6293 /* Note that while the elements of the dict may contain references,
6294 * the list object itself can't. This basically means that the
6295 * dict object string representation as a whole can't contain references
6296 * that are not presents in the single elements. */
6297 static const Jim_ObjType dictObjType
= {
6299 FreeDictInternalRep
,
6305 void FreeDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6307 JIM_NOTUSED(interp
);
6309 Jim_FreeHashTable(objPtr
->internalRep
.ptr
);
6310 Jim_Free(objPtr
->internalRep
.ptr
);
6313 void DupDictInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
6315 Jim_HashTable
*ht
, *dupHt
;
6316 Jim_HashTableIterator
*htiter
;
6319 /* Create a new hash table */
6320 ht
= srcPtr
->internalRep
.ptr
;
6321 dupHt
= Jim_Alloc(sizeof(*dupHt
));
6322 Jim_InitHashTable(dupHt
, &JimDictHashTableType
, interp
);
6324 Jim_ExpandHashTable(dupHt
, ht
->size
);
6325 /* Copy every element from the source to the dup hash table */
6326 htiter
= Jim_GetHashTableIterator(ht
);
6327 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6328 const Jim_Obj
*keyObjPtr
= he
->key
;
6329 Jim_Obj
*valObjPtr
= he
->u
.val
;
6331 Jim_IncrRefCount((Jim_Obj
*)keyObjPtr
); /* ATTENTION: const cast */
6332 Jim_IncrRefCount(valObjPtr
);
6333 Jim_AddHashEntry(dupHt
, keyObjPtr
, valObjPtr
);
6335 Jim_FreeHashTableIterator(htiter
);
6337 dupPtr
->internalRep
.ptr
= dupHt
;
6338 dupPtr
->typePtr
= &dictObjType
;
6341 void UpdateStringOfDict(struct Jim_Obj
*objPtr
)
6343 int i
, bufLen
, realLength
;
6346 int *quotingType
, objc
;
6348 Jim_HashTableIterator
*htiter
;
6352 /* Trun the hash table into a flat vector of Jim_Objects. */
6353 ht
= objPtr
->internalRep
.ptr
;
6354 objc
= ht
->used
* 2;
6355 objv
= Jim_Alloc(objc
* sizeof(Jim_Obj
*));
6356 htiter
= Jim_GetHashTableIterator(ht
);
6358 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6359 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6360 objv
[i
++] = he
->u
.val
;
6362 Jim_FreeHashTableIterator(htiter
);
6363 /* (Over) Estimate the space needed. */
6364 quotingType
= Jim_Alloc(sizeof(int) * objc
);
6366 for (i
= 0; i
< objc
; i
++) {
6369 strRep
= Jim_GetString(objv
[i
], &len
);
6370 quotingType
[i
] = ListElementQuotingType(strRep
, len
);
6371 switch (quotingType
[i
]) {
6372 case JIM_ELESTR_SIMPLE
:
6375 case JIM_ELESTR_BRACE
:
6378 case JIM_ELESTR_QUOTE
:
6382 bufLen
++; /* elements separator. */
6386 /* Generate the string rep. */
6387 p
= objPtr
->bytes
= Jim_Alloc(bufLen
+ 1);
6389 for (i
= 0; i
< objc
; i
++) {
6393 strRep
= Jim_GetString(objv
[i
], &len
);
6395 switch (quotingType
[i
]) {
6396 case JIM_ELESTR_SIMPLE
:
6397 memcpy(p
, strRep
, len
);
6401 case JIM_ELESTR_BRACE
:
6403 memcpy(p
, strRep
, len
);
6406 realLength
+= len
+ 2;
6408 case JIM_ELESTR_QUOTE
:
6409 q
= BackslashQuoteString(strRep
, len
, &qlen
);
6416 /* Add a separating space */
6417 if (i
+ 1 != objc
) {
6422 *p
= '\0'; /* nul term. */
6423 objPtr
->length
= realLength
;
6424 Jim_Free(quotingType
);
6428 static int SetDictFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
6432 /* Get the string representation. Do this first so we don't
6433 * change order in case of fast conversion to dict.
6437 /* For simplicity, convert a non-list object to a list and then to a dict */
6438 listlen
= Jim_ListLength(interp
, objPtr
);
6440 Jim_SetResultString(interp
,
6441 "invalid dictionary value: must be a list with an even number of elements", -1);
6445 /* Now it is easy to convert to a dict from a list, and it can't fail */
6449 ht
= Jim_Alloc(sizeof(*ht
));
6450 Jim_InitHashTable(ht
, &JimDictHashTableType
, interp
);
6452 for (i
= 0; i
< listlen
; i
+= 2) {
6456 Jim_ListIndex(interp
, objPtr
, i
, &keyObjPtr
, JIM_NONE
);
6457 Jim_ListIndex(interp
, objPtr
, i
+ 1, &valObjPtr
, JIM_NONE
);
6459 Jim_IncrRefCount(keyObjPtr
);
6460 Jim_IncrRefCount(valObjPtr
);
6462 if (Jim_AddHashEntry(ht
, keyObjPtr
, valObjPtr
) != JIM_OK
) {
6465 he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6466 Jim_DecrRefCount(interp
, keyObjPtr
);
6467 /* ATTENTION: const cast */
6468 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6469 he
->u
.val
= valObjPtr
;
6473 Jim_FreeIntRep(interp
, objPtr
);
6474 objPtr
->typePtr
= &dictObjType
;
6475 objPtr
->internalRep
.ptr
= ht
;
6481 /* Dict object API */
6483 /* Add an element to a dict. objPtr must be of the "dict" type.
6484 * The higer-level exported function is Jim_DictAddElement().
6485 * If an element with the specified key already exists, the value
6486 * associated is replaced with the new one.
6488 * if valueObjPtr == NULL, the key is instead removed if it exists. */
6489 static int DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6490 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6492 Jim_HashTable
*ht
= objPtr
->internalRep
.ptr
;
6494 if (valueObjPtr
== NULL
) { /* unset */
6495 return Jim_DeleteHashEntry(ht
, keyObjPtr
);
6497 Jim_IncrRefCount(keyObjPtr
);
6498 Jim_IncrRefCount(valueObjPtr
);
6499 if (Jim_AddHashEntry(ht
, keyObjPtr
, valueObjPtr
) != JIM_OK
) {
6500 Jim_HashEntry
*he
= Jim_FindHashEntry(ht
, keyObjPtr
);
6502 Jim_DecrRefCount(interp
, keyObjPtr
);
6503 /* ATTENTION: const cast */
6504 Jim_DecrRefCount(interp
, (Jim_Obj
*)he
->u
.val
);
6505 he
->u
.val
= valueObjPtr
;
6510 /* Add an element, higher-level interface for DictAddElement().
6511 * If valueObjPtr == NULL, the key is removed if it exists. */
6512 int Jim_DictAddElement(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
6513 Jim_Obj
*keyObjPtr
, Jim_Obj
*valueObjPtr
)
6517 JimPanic((Jim_IsShared(objPtr
), "Jim_DictAddElement called with shared object"));
6518 if (objPtr
->typePtr
!= &dictObjType
) {
6519 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
)
6522 retcode
= DictAddElement(interp
, objPtr
, keyObjPtr
, valueObjPtr
);
6523 Jim_InvalidateStringRep(objPtr
);
6527 Jim_Obj
*Jim_NewDictObj(Jim_Interp
*interp
, Jim_Obj
*const *elements
, int len
)
6532 JimPanic((len
% 2, "Jim_NewDictObj() 'len' argument must be even"));
6534 objPtr
= Jim_NewObj(interp
);
6535 objPtr
->typePtr
= &dictObjType
;
6536 objPtr
->bytes
= NULL
;
6537 objPtr
->internalRep
.ptr
= Jim_Alloc(sizeof(Jim_HashTable
));
6538 Jim_InitHashTable(objPtr
->internalRep
.ptr
, &JimDictHashTableType
, interp
);
6539 for (i
= 0; i
< len
; i
+= 2)
6540 DictAddElement(interp
, objPtr
, elements
[i
], elements
[i
+ 1]);
6544 /* Return the value associated to the specified dict key
6545 * Note: Returns JIM_OK if OK, JIM_ERR if entry not found or -1 if can't create dict value
6547 int Jim_DictKey(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
*keyPtr
,
6548 Jim_Obj
**objPtrPtr
, int flags
)
6553 if (dictPtr
->typePtr
!= &dictObjType
) {
6554 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6557 ht
= dictPtr
->internalRep
.ptr
;
6558 if ((he
= Jim_FindHashEntry(ht
, keyPtr
)) == NULL
) {
6559 if (flags
& JIM_ERRMSG
) {
6560 Jim_SetResultFormatted(interp
, "key \"%#s\" not found in dictionary", keyPtr
);
6564 *objPtrPtr
= he
->u
.val
;
6568 /* Return an allocated array of key/value pairs for the dictionary. Stores the length in *len */
6569 int Jim_DictPairs(Jim_Interp
*interp
, Jim_Obj
*dictPtr
, Jim_Obj
***objPtrPtr
, int *len
)
6572 Jim_HashTableIterator
*htiter
;
6577 if (dictPtr
->typePtr
!= &dictObjType
) {
6578 if (SetDictFromAny(interp
, dictPtr
) != JIM_OK
)
6581 ht
= dictPtr
->internalRep
.ptr
;
6583 /* Turn the hash table into a flat vector of Jim_Objects. */
6584 objv
= Jim_Alloc((ht
->used
* 2) * sizeof(Jim_Obj
*));
6585 htiter
= Jim_GetHashTableIterator(ht
);
6587 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
6588 objv
[i
++] = (Jim_Obj
*)he
->key
; /* ATTENTION: const cast */
6589 objv
[i
++] = he
->u
.val
;
6592 Jim_FreeHashTableIterator(htiter
);
6598 /* Return the value associated to the specified dict keys */
6599 int Jim_DictKeysVector(Jim_Interp
*interp
, Jim_Obj
*dictPtr
,
6600 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
**objPtrPtr
, int flags
)
6605 *objPtrPtr
= dictPtr
;
6609 for (i
= 0; i
< keyc
; i
++) {
6612 if (Jim_DictKey(interp
, dictPtr
, keyv
[i
], &objPtr
, flags
)
6617 *objPtrPtr
= dictPtr
;
6621 /* Modify the dict stored into the variable named 'varNamePtr'
6622 * setting the element specified by the 'keyc' keys objects in 'keyv',
6623 * with the new value of the element 'newObjPtr'.
6625 * If newObjPtr == NULL the operation is to remove the given key
6626 * from the dictionary.
6628 * If flags & JIM_ERRMSG, then failure to remove the key is considered an error
6629 * and JIM_ERR is returned. Otherwise it is ignored and JIM_OK is returned.
6631 int Jim_SetDictKeysVector(Jim_Interp
*interp
, Jim_Obj
*varNamePtr
,
6632 Jim_Obj
*const *keyv
, int keyc
, Jim_Obj
*newObjPtr
, int flags
)
6634 Jim_Obj
*varObjPtr
, *objPtr
, *dictObjPtr
;
6637 varObjPtr
= objPtr
=
6638 Jim_GetVariable(interp
, varNamePtr
, newObjPtr
== NULL
? JIM_ERRMSG
: JIM_NONE
);
6639 if (objPtr
== NULL
) {
6640 if (newObjPtr
== NULL
) /* Cannot remove a key from non existing var */ {
6643 varObjPtr
= objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6644 if (Jim_SetVariable(interp
, varNamePtr
, objPtr
) != JIM_OK
) {
6645 Jim_FreeNewObj(interp
, varObjPtr
);
6649 if ((shared
= Jim_IsShared(objPtr
)))
6650 varObjPtr
= objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6651 for (i
= 0; i
< keyc
- 1; i
++) {
6652 dictObjPtr
= objPtr
;
6654 /* Check if it's a valid dictionary */
6655 if (dictObjPtr
->typePtr
!= &dictObjType
) {
6656 if (SetDictFromAny(interp
, dictObjPtr
) != JIM_OK
) {
6660 /* Check if the given key exists. */
6661 Jim_InvalidateStringRep(dictObjPtr
);
6662 if (Jim_DictKey(interp
, dictObjPtr
, keyv
[i
], &objPtr
,
6663 newObjPtr
? JIM_NONE
: JIM_ERRMSG
) == JIM_OK
) {
6664 /* This key exists at the current level.
6665 * Make sure it's not shared!. */
6666 if (Jim_IsShared(objPtr
)) {
6667 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
6668 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6672 /* Key not found. If it's an [unset] operation
6673 * this is an error. Only the last key may not
6675 if (newObjPtr
== NULL
) {
6678 /* Otherwise set an empty dictionary
6679 * as key's value. */
6680 objPtr
= Jim_NewDictObj(interp
, NULL
, 0);
6681 DictAddElement(interp
, dictObjPtr
, keyv
[i
], objPtr
);
6684 /* Note error on unset with missing last key is OK */
6685 if (Jim_DictAddElement(interp
, objPtr
, keyv
[keyc
- 1], newObjPtr
) != JIM_OK
) {
6686 if (newObjPtr
|| (flags
& JIM_ERRMSG
)) {
6690 Jim_InvalidateStringRep(objPtr
);
6691 Jim_InvalidateStringRep(varObjPtr
);
6692 if (Jim_SetVariable(interp
, varNamePtr
, varObjPtr
) != JIM_OK
) {
6695 Jim_SetResult(interp
, varObjPtr
);
6699 Jim_FreeNewObj(interp
, varObjPtr
);
6704 /* -----------------------------------------------------------------------------
6706 * ---------------------------------------------------------------------------*/
6707 static void UpdateStringOfIndex(struct Jim_Obj
*objPtr
);
6708 static int SetIndexFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
6710 static const Jim_ObjType indexObjType
= {
6714 UpdateStringOfIndex
,
6718 void UpdateStringOfIndex(struct Jim_Obj
*objPtr
)
6721 char buf
[JIM_INTEGER_SPACE
+ 1];
6723 if (objPtr
->internalRep
.indexValue
>= 0)
6724 len
= sprintf(buf
, "%d", objPtr
->internalRep
.indexValue
);
6725 else if (objPtr
->internalRep
.indexValue
== -1)
6726 len
= sprintf(buf
, "end");
6728 len
= sprintf(buf
, "end%d", objPtr
->internalRep
.indexValue
+ 1);
6730 objPtr
->bytes
= Jim_Alloc(len
+ 1);
6731 memcpy(objPtr
->bytes
, buf
, len
+ 1);
6732 objPtr
->length
= len
;
6735 int SetIndexFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6741 /* Get the string representation */
6742 str
= Jim_String(objPtr
);
6744 /* Try to convert into an index */
6745 if (strncmp(str
, "end", 3) == 0) {
6751 idx
= strtol(str
, &endptr
, 10);
6753 if (endptr
== str
) {
6759 /* Now str may include or +<num> or -<num> */
6760 if (*str
== '+' || *str
== '-') {
6761 int sign
= (*str
== '+' ? 1 : -1);
6763 idx
+= sign
* strtol(++str
, &endptr
, 10);
6764 if (str
== endptr
|| *endptr
) {
6769 /* The only thing left should be spaces */
6770 while (isspace(UCHAR(*str
))) {
6781 /* end-1 is repesented as -2 */
6789 /* Free the old internal repr and set the new one. */
6790 Jim_FreeIntRep(interp
, objPtr
);
6791 objPtr
->typePtr
= &indexObjType
;
6792 objPtr
->internalRep
.indexValue
= idx
;
6796 Jim_SetResultFormatted(interp
,
6797 "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr
);
6801 int Jim_GetIndex(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *indexPtr
)
6803 /* Avoid shimmering if the object is an integer. */
6804 if (objPtr
->typePtr
== &intObjType
) {
6805 jim_wide val
= JimWideValue(objPtr
);
6807 if (!(val
< LONG_MIN
) && !(val
> LONG_MAX
)) {
6808 *indexPtr
= (val
< 0) ? -INT_MAX
: (long)val
;;
6812 if (objPtr
->typePtr
!= &indexObjType
&& SetIndexFromAny(interp
, objPtr
) == JIM_ERR
)
6814 *indexPtr
= objPtr
->internalRep
.indexValue
;
6818 /* -----------------------------------------------------------------------------
6819 * Return Code Object.
6820 * ---------------------------------------------------------------------------*/
6822 /* NOTE: These must be kept in the same order as JIM_OK, JIM_ERR, ... */
6823 static const char * const jimReturnCodes
[] = {
6825 [JIM_ERR
] = "error",
6826 [JIM_RETURN
] = "return",
6827 [JIM_BREAK
] = "break",
6828 [JIM_CONTINUE
] = "continue",
6829 [JIM_SIGNAL
] = "signal",
6830 [JIM_EXIT
] = "exit",
6831 [JIM_EVAL
] = "eval",
6835 #define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes))
6837 static int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
6839 static const Jim_ObjType returnCodeObjType
= {
6847 /* Converts a (standard) return code to a string. Returns "?" for
6848 * non-standard return codes.
6850 const char *Jim_ReturnCode(int code
)
6852 if (code
< 0 || code
>= (int)jimReturnCodesSize
) {
6856 return jimReturnCodes
[code
];
6860 int SetReturnCodeFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
6865 /* Try to convert into an integer */
6866 if (JimGetWideNoErr(interp
, objPtr
, &wideValue
) != JIM_ERR
)
6867 returnCode
= (int)wideValue
;
6868 else if (Jim_GetEnum(interp
, objPtr
, jimReturnCodes
, &returnCode
, NULL
, JIM_NONE
) != JIM_OK
) {
6869 Jim_SetResultFormatted(interp
, "expected return code but got \"%#s\"", objPtr
);
6872 /* Free the old internal repr and set the new one. */
6873 Jim_FreeIntRep(interp
, objPtr
);
6874 objPtr
->typePtr
= &returnCodeObjType
;
6875 objPtr
->internalRep
.returnCode
= returnCode
;
6879 int Jim_GetReturnCode(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int *intPtr
)
6881 if (objPtr
->typePtr
!= &returnCodeObjType
&& SetReturnCodeFromAny(interp
, objPtr
) == JIM_ERR
)
6883 *intPtr
= objPtr
->internalRep
.returnCode
;
6887 /* -----------------------------------------------------------------------------
6888 * Expression Parsing
6889 * ---------------------------------------------------------------------------*/
6890 static int JimParseExprOperator(struct JimParserCtx
*pc
);
6891 static int JimParseExprNumber(struct JimParserCtx
*pc
);
6892 static int JimParseExprIrrational(struct JimParserCtx
*pc
);
6894 /* Exrp's Stack machine operators opcodes. */
6896 /* Binary operators (numbers) */
6899 /* Continues on from the JIM_TT_ space */
6901 JIM_EXPROP_MUL
= JIM_TT_EXPR_OP
, /* 15 */
6916 JIM_EXPROP_BITAND
, /* 30 */
6920 /* Note must keep these together */
6921 JIM_EXPROP_LOGICAND
, /* 33 */
6922 JIM_EXPROP_LOGICAND_LEFT
,
6923 JIM_EXPROP_LOGICAND_RIGHT
,
6926 JIM_EXPROP_LOGICOR
, /* 36 */
6927 JIM_EXPROP_LOGICOR_LEFT
,
6928 JIM_EXPROP_LOGICOR_RIGHT
,
6931 /* Ternary operators */
6932 JIM_EXPROP_TERNARY
, /* 39 */
6933 JIM_EXPROP_TERNARY_LEFT
,
6934 JIM_EXPROP_TERNARY_RIGHT
,
6937 JIM_EXPROP_COLON
, /* 42 */
6938 JIM_EXPROP_COLON_LEFT
,
6939 JIM_EXPROP_COLON_RIGHT
,
6941 JIM_EXPROP_POW
, /* 45 */
6943 /* Binary operators (strings) */
6949 /* Unary operators (numbers) */
6952 JIM_EXPROP_UNARYMINUS
,
6953 JIM_EXPROP_UNARYPLUS
,
6956 JIM_EXPROP_FUNC_FIRST
,
6957 JIM_EXPROP_FUNC_INT
= JIM_EXPROP_FUNC_FIRST
,
6958 JIM_EXPROP_FUNC_ABS
,
6959 JIM_EXPROP_FUNC_DOUBLE
,
6960 JIM_EXPROP_FUNC_ROUND
,
6961 JIM_EXPROP_FUNC_RAND
,
6962 JIM_EXPROP_FUNC_SRAND
,
6964 /* math functions from libm */
6965 JIM_EXPROP_FUNC_SIN
,
6966 JIM_EXPROP_FUNC_COS
,
6967 JIM_EXPROP_FUNC_TAN
,
6968 JIM_EXPROP_FUNC_ASIN
,
6969 JIM_EXPROP_FUNC_ACOS
,
6970 JIM_EXPROP_FUNC_ATAN
,
6971 JIM_EXPROP_FUNC_SINH
,
6972 JIM_EXPROP_FUNC_COSH
,
6973 JIM_EXPROP_FUNC_TANH
,
6974 JIM_EXPROP_FUNC_CEIL
,
6975 JIM_EXPROP_FUNC_FLOOR
,
6976 JIM_EXPROP_FUNC_EXP
,
6977 JIM_EXPROP_FUNC_LOG
,
6978 JIM_EXPROP_FUNC_LOG10
,
6979 JIM_EXPROP_FUNC_SQRT
,
6980 JIM_EXPROP_FUNC_POW
,
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 case JIM_EXPROP_FUNC_POW
:
7316 wC
= JimPowWide(wA
, wB
);
7318 case JIM_EXPROP_ADD
:
7321 case JIM_EXPROP_SUB
:
7324 case JIM_EXPROP_MUL
:
7327 case JIM_EXPROP_DIV
:
7329 Jim_SetResultString(interp
, "Division by zero", -1);
7336 * This code is tricky: C doesn't guarantee much
7337 * about the quotient or remainder, but Tcl does.
7338 * The remainder always has the same sign as the
7339 * divisor and a smaller absolute value.
7357 case JIM_EXPROP_LTE
:
7360 case JIM_EXPROP_GTE
:
7363 case JIM_EXPROP_NUMEQ
:
7366 case JIM_EXPROP_NUMNE
:
7373 else if (Jim_GetDouble(interp
, A
, &dA
) == JIM_OK
&& Jim_GetDouble(interp
, B
, &dB
) == JIM_OK
) {
7374 switch (e
->opcode
) {
7375 case JIM_EXPROP_POW
:
7376 case JIM_EXPROP_FUNC_POW
:
7377 #ifdef JIM_MATH_FUNCTIONS
7380 Jim_SetResultString(interp
, "unsupported", -1);
7384 case JIM_EXPROP_ADD
:
7387 case JIM_EXPROP_SUB
:
7390 case JIM_EXPROP_MUL
:
7393 case JIM_EXPROP_DIV
:
7396 dC
= dA
< 0 ? -INFINITY
: INFINITY
;
7398 dC
= (dA
< 0 ? -1.0 : 1.0) * strtod("Inf", NULL
);
7413 case JIM_EXPROP_LTE
:
7417 case JIM_EXPROP_GTE
:
7421 case JIM_EXPROP_NUMEQ
:
7425 case JIM_EXPROP_NUMNE
:
7434 /* Handle the string case */
7436 /* REVISIT: Could optimise the eq/ne case by checking lengths */
7437 int i
= Jim_StringCompareObj(interp
, A
, B
, 0);
7441 switch (e
->opcode
) {
7448 case JIM_EXPROP_LTE
:
7451 case JIM_EXPROP_GTE
:
7454 case JIM_EXPROP_NUMEQ
:
7457 case JIM_EXPROP_NUMNE
:
7468 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7471 ExprPush(e
, Jim_NewDoubleObj(interp
, dC
));
7475 Jim_DecrRefCount(interp
, A
);
7476 Jim_DecrRefCount(interp
, B
);
7481 static int JimSearchList(Jim_Interp
*interp
, Jim_Obj
*listObjPtr
, Jim_Obj
*valObj
)
7486 listlen
= Jim_ListLength(interp
, listObjPtr
);
7487 for (i
= 0; i
< listlen
; i
++) {
7490 Jim_ListIndex(interp
, listObjPtr
, i
, &objPtr
, JIM_NONE
);
7492 if (Jim_StringEqObj(objPtr
, valObj
)) {
7499 static int JimExprOpStrBin(Jim_Interp
*interp
, struct JimExprState
*e
)
7501 Jim_Obj
*B
= ExprPop(e
);
7502 Jim_Obj
*A
= ExprPop(e
);
7506 switch (e
->opcode
) {
7507 case JIM_EXPROP_STREQ
:
7508 case JIM_EXPROP_STRNE
: {
7510 const char *sA
= Jim_GetString(A
, &Alen
);
7511 const char *sB
= Jim_GetString(B
, &Blen
);
7513 if (e
->opcode
== JIM_EXPROP_STREQ
) {
7514 wC
= (Alen
== Blen
&& memcmp(sA
, sB
, Alen
) == 0);
7517 wC
= (Alen
!= Blen
|| memcmp(sA
, sB
, Alen
) != 0);
7521 case JIM_EXPROP_STRIN
:
7522 wC
= JimSearchList(interp
, B
, A
);
7524 case JIM_EXPROP_STRNI
:
7525 wC
= !JimSearchList(interp
, B
, A
);
7530 ExprPush(e
, Jim_NewIntObj(interp
, wC
));
7532 Jim_DecrRefCount(interp
, A
);
7533 Jim_DecrRefCount(interp
, B
);
7538 static int ExprBool(Jim_Interp
*interp
, Jim_Obj
*obj
)
7543 if (Jim_GetLong(interp
, obj
, &l
) == JIM_OK
) {
7546 if (Jim_GetDouble(interp
, obj
, &d
) == JIM_OK
) {
7552 static int JimExprOpAndLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7554 Jim_Obj
*skip
= ExprPop(e
);
7555 Jim_Obj
*A
= ExprPop(e
);
7558 switch (ExprBool(interp
, A
)) {
7560 /* false, so skip RHS opcodes with a 0 result */
7561 e
->skip
= JimWideValue(skip
);
7562 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7566 /* true so continue */
7573 Jim_DecrRefCount(interp
, A
);
7574 Jim_DecrRefCount(interp
, skip
);
7579 static int JimExprOpOrLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7581 Jim_Obj
*skip
= ExprPop(e
);
7582 Jim_Obj
*A
= ExprPop(e
);
7585 switch (ExprBool(interp
, A
)) {
7587 /* false, so do nothing */
7591 /* true so skip RHS opcodes with a 1 result */
7592 e
->skip
= JimWideValue(skip
);
7593 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7601 Jim_DecrRefCount(interp
, A
);
7602 Jim_DecrRefCount(interp
, skip
);
7607 static int JimExprOpAndOrRight(Jim_Interp
*interp
, struct JimExprState
*e
)
7609 Jim_Obj
*A
= ExprPop(e
);
7612 switch (ExprBool(interp
, A
)) {
7614 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7618 ExprPush(e
, Jim_NewIntObj(interp
, 1));
7626 Jim_DecrRefCount(interp
, A
);
7631 static int JimExprOpTernaryLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7633 Jim_Obj
*skip
= ExprPop(e
);
7634 Jim_Obj
*A
= ExprPop(e
);
7640 switch (ExprBool(interp
, A
)) {
7642 /* false, skip RHS opcodes */
7643 e
->skip
= JimWideValue(skip
);
7644 /* Push a dummy value */
7645 ExprPush(e
, Jim_NewIntObj(interp
, 0));
7649 /* true so do nothing */
7657 Jim_DecrRefCount(interp
, A
);
7658 Jim_DecrRefCount(interp
, skip
);
7663 static int JimExprOpColonLeft(Jim_Interp
*interp
, struct JimExprState
*e
)
7665 Jim_Obj
*skip
= ExprPop(e
);
7666 Jim_Obj
*B
= ExprPop(e
);
7667 Jim_Obj
*A
= ExprPop(e
);
7669 /* No need to check for A as non-boolean */
7670 if (ExprBool(interp
, A
)) {
7671 /* true, so skip RHS opcodes */
7672 e
->skip
= JimWideValue(skip
);
7673 /* Repush B as the answer */
7677 Jim_DecrRefCount(interp
, skip
);
7678 Jim_DecrRefCount(interp
, A
);
7679 Jim_DecrRefCount(interp
, B
);
7683 static int JimExprOpNull(Jim_Interp
*interp
, struct JimExprState
*e
)
7696 /* name - precedence - arity - opcode */
7697 static const struct Jim_ExprOperator Jim_ExprOperators
[] = {
7698 [JIM_EXPROP_FUNC_INT
] = {"int", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7699 [JIM_EXPROP_FUNC_DOUBLE
] = {"double", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7700 [JIM_EXPROP_FUNC_ABS
] = {"abs", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7701 [JIM_EXPROP_FUNC_ROUND
] = {"round", 400, 1, JimExprOpNumUnary
, LAZY_NONE
},
7702 [JIM_EXPROP_FUNC_RAND
] = {"rand", 400, 0, JimExprOpNone
, LAZY_NONE
},
7703 [JIM_EXPROP_FUNC_SRAND
] = {"srand", 400, 1, JimExprOpIntUnary
, LAZY_NONE
},
7705 #ifdef JIM_MATH_FUNCTIONS
7706 [JIM_EXPROP_FUNC_SIN
] = {"sin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7707 [JIM_EXPROP_FUNC_COS
] = {"cos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7708 [JIM_EXPROP_FUNC_TAN
] = {"tan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7709 [JIM_EXPROP_FUNC_ASIN
] = {"asin", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7710 [JIM_EXPROP_FUNC_ACOS
] = {"acos", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7711 [JIM_EXPROP_FUNC_ATAN
] = {"atan", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7712 [JIM_EXPROP_FUNC_SINH
] = {"sinh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7713 [JIM_EXPROP_FUNC_COSH
] = {"cosh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7714 [JIM_EXPROP_FUNC_TANH
] = {"tanh", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7715 [JIM_EXPROP_FUNC_CEIL
] = {"ceil", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7716 [JIM_EXPROP_FUNC_FLOOR
] = {"floor", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7717 [JIM_EXPROP_FUNC_EXP
] = {"exp", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7718 [JIM_EXPROP_FUNC_LOG
] = {"log", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7719 [JIM_EXPROP_FUNC_LOG10
] = {"log10", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7720 [JIM_EXPROP_FUNC_SQRT
] = {"sqrt", 400, 1, JimExprOpDoubleUnary
, LAZY_NONE
},
7721 [JIM_EXPROP_FUNC_POW
] = {"pow", 400, 2, JimExprOpBin
, LAZY_NONE
},
7724 [JIM_EXPROP_NOT
] = {"!", 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7725 [JIM_EXPROP_BITNOT
] = {"~", 300, 1, JimExprOpIntUnary
, LAZY_NONE
},
7726 [JIM_EXPROP_UNARYMINUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7727 [JIM_EXPROP_UNARYPLUS
] = {NULL
, 300, 1, JimExprOpNumUnary
, LAZY_NONE
},
7729 [JIM_EXPROP_POW
] = {"**", 250, 2, JimExprOpBin
, LAZY_NONE
},
7731 [JIM_EXPROP_MUL
] = {"*", 200, 2, JimExprOpBin
, LAZY_NONE
},
7732 [JIM_EXPROP_DIV
] = {"/", 200, 2, JimExprOpBin
, LAZY_NONE
},
7733 [JIM_EXPROP_MOD
] = {"%", 200, 2, JimExprOpIntBin
, LAZY_NONE
},
7735 [JIM_EXPROP_SUB
] = {"-", 100, 2, JimExprOpBin
, LAZY_NONE
},
7736 [JIM_EXPROP_ADD
] = {"+", 100, 2, JimExprOpBin
, LAZY_NONE
},
7738 [JIM_EXPROP_ROTL
] = {"<<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7739 [JIM_EXPROP_ROTR
] = {">>>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7740 [JIM_EXPROP_LSHIFT
] = {"<<", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7741 [JIM_EXPROP_RSHIFT
] = {">>", 90, 2, JimExprOpIntBin
, LAZY_NONE
},
7743 [JIM_EXPROP_LT
] = {"<", 80, 2, JimExprOpBin
, LAZY_NONE
},
7744 [JIM_EXPROP_GT
] = {">", 80, 2, JimExprOpBin
, LAZY_NONE
},
7745 [JIM_EXPROP_LTE
] = {"<=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7746 [JIM_EXPROP_GTE
] = {">=", 80, 2, JimExprOpBin
, LAZY_NONE
},
7748 [JIM_EXPROP_NUMEQ
] = {"==", 70, 2, JimExprOpBin
, LAZY_NONE
},
7749 [JIM_EXPROP_NUMNE
] = {"!=", 70, 2, JimExprOpBin
, LAZY_NONE
},
7751 [JIM_EXPROP_STREQ
] = {"eq", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7752 [JIM_EXPROP_STRNE
] = {"ne", 60, 2, JimExprOpStrBin
, LAZY_NONE
},
7754 [JIM_EXPROP_STRIN
] = {"in", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7755 [JIM_EXPROP_STRNI
] = {"ni", 55, 2, JimExprOpStrBin
, LAZY_NONE
},
7757 [JIM_EXPROP_BITAND
] = {"&", 50, 2, JimExprOpIntBin
, LAZY_NONE
},
7758 [JIM_EXPROP_BITXOR
] = {"^", 49, 2, JimExprOpIntBin
, LAZY_NONE
},
7759 [JIM_EXPROP_BITOR
] = {"|", 48, 2, JimExprOpIntBin
, LAZY_NONE
},
7761 [JIM_EXPROP_LOGICAND
] = {"&&", 10, 2, NULL
, LAZY_OP
},
7762 [JIM_EXPROP_LOGICOR
] = {"||", 9, 2, NULL
, LAZY_OP
},
7764 [JIM_EXPROP_TERNARY
] = {"?", 5, 2, JimExprOpNull
, LAZY_OP
},
7765 [JIM_EXPROP_COLON
] = {":", 5, 2, JimExprOpNull
, LAZY_OP
},
7767 /* private operators */
7768 [JIM_EXPROP_TERNARY_LEFT
] = {NULL
, 5, 2, JimExprOpTernaryLeft
, LAZY_LEFT
},
7769 [JIM_EXPROP_TERNARY_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7770 [JIM_EXPROP_COLON_LEFT
] = {NULL
, 5, 2, JimExprOpColonLeft
, LAZY_LEFT
},
7771 [JIM_EXPROP_COLON_RIGHT
] = {NULL
, 5, 2, JimExprOpNull
, LAZY_RIGHT
},
7772 [JIM_EXPROP_LOGICAND_LEFT
] = {NULL
, 10, 2, JimExprOpAndLeft
, LAZY_LEFT
},
7773 [JIM_EXPROP_LOGICAND_RIGHT
] = {NULL
, 10, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7774 [JIM_EXPROP_LOGICOR_LEFT
] = {NULL
, 9, 2, JimExprOpOrLeft
, LAZY_LEFT
},
7775 [JIM_EXPROP_LOGICOR_RIGHT
] = {NULL
, 9, 2, JimExprOpAndOrRight
, LAZY_RIGHT
},
7778 #define JIM_EXPR_OPERATORS_NUM \
7779 (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
7781 static int JimParseExpression(struct JimParserCtx
*pc
)
7783 /* Discard spaces and quoted newline */
7784 while (isspace(UCHAR(*pc
->p
)) || (*(pc
->p
) == '\\' && *(pc
->p
+ 1) == '\n')) {
7785 if (*pc
->p
== '\n') {
7793 pc
->tstart
= pc
->tend
= pc
->p
;
7794 pc
->tline
= pc
->linenr
;
7795 pc
->tt
= JIM_TT_EOL
;
7801 pc
->tt
= JIM_TT_SUBEXPR_START
;
7804 pc
->tt
= JIM_TT_SUBEXPR_END
;
7807 pc
->tt
= JIM_TT_SUBEXPR_COMMA
;
7809 pc
->tstart
= pc
->tend
= pc
->p
;
7810 pc
->tline
= pc
->linenr
;
7815 return JimParseCmd(pc
);
7817 if (JimParseVar(pc
) == JIM_ERR
)
7818 return JimParseExprOperator(pc
);
7820 /* Don't allow expr sugar in expressions */
7821 if (pc
->tt
== JIM_TT_EXPRSUGAR
) {
7838 return JimParseExprNumber(pc
);
7840 return JimParseQuote(pc
);
7842 return JimParseBrace(pc
);
7848 if (JimParseExprIrrational(pc
) == JIM_ERR
)
7849 return JimParseExprOperator(pc
);
7852 return JimParseExprOperator(pc
);
7858 static int JimParseExprNumber(struct JimParserCtx
*pc
)
7863 /* Assume an integer for now */
7864 pc
->tt
= JIM_TT_EXPR_INT
;
7866 pc
->tline
= pc
->linenr
;
7867 while (isdigit(UCHAR(*pc
->p
))
7868 || (allowhex
&& isxdigit(UCHAR(*pc
->p
)))
7869 || (allowdot
&& *pc
->p
== '.')
7870 || (pc
->p
- pc
->tstart
== 1 && *pc
->tstart
== '0' && (*pc
->p
== 'x' || *pc
->p
== 'X'))
7872 if ((*pc
->p
== 'x') || (*pc
->p
== 'X')) {
7876 if (*pc
->p
== '.') {
7878 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7882 if (!allowhex
&& (*pc
->p
== 'e' || *pc
->p
== 'E') && (pc
->p
[1] == '-' || pc
->p
[1] == '+'
7883 || isdigit(UCHAR(pc
->p
[1])))) {
7886 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7889 pc
->tend
= pc
->p
- 1;
7893 static int JimParseExprIrrational(struct JimParserCtx
*pc
)
7895 const char *Tokens
[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL
};
7898 for (token
= Tokens
; *token
!= NULL
; token
++) {
7899 int len
= strlen(*token
);
7901 if (strncmp(*token
, pc
->p
, len
) == 0) {
7903 pc
->tend
= pc
->p
+ len
- 1;
7906 pc
->tline
= pc
->linenr
;
7907 pc
->tt
= JIM_TT_EXPR_DOUBLE
;
7914 static int JimParseExprOperator(struct JimParserCtx
*pc
)
7917 int bestIdx
= -1, bestLen
= 0;
7919 /* Try to get the longest match. */
7920 for (i
= JIM_TT_EXPR_OP
; i
< (signed)JIM_EXPR_OPERATORS_NUM
; i
++) {
7924 opname
= Jim_ExprOperators
[i
].name
;
7925 if (opname
== NULL
) {
7928 oplen
= strlen(opname
);
7930 if (strncmp(opname
, pc
->p
, oplen
) == 0 && oplen
> bestLen
) {
7935 if (bestIdx
== -1) {
7939 /* Validate paretheses around function arguments */
7940 if (bestIdx
>= JIM_EXPROP_FUNC_FIRST
) {
7941 const char *p
= pc
->p
+ bestLen
;
7942 int len
= pc
->len
- bestLen
;
7944 while (len
&& isspace(UCHAR(*p
))) {
7953 pc
->tend
= pc
->p
+ bestLen
- 1;
7956 pc
->tline
= pc
->linenr
;
7962 static const struct Jim_ExprOperator
*JimExprOperatorInfoByOpcode(int opcode
)
7964 return &Jim_ExprOperators
[opcode
];
7967 const char *jim_tt_name(int type
)
7969 static const char * const tt_names
[JIM_TT_EXPR_OP
] =
7970 { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", ",,,", "INT",
7972 if (type
< JIM_TT_EXPR_OP
) {
7973 return tt_names
[type
];
7976 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(type
);
7977 static char buf
[20];
7979 if (op
&& op
->name
) {
7982 sprintf(buf
, "(%d)", type
);
7987 /* -----------------------------------------------------------------------------
7989 * ---------------------------------------------------------------------------*/
7990 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
7991 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
7992 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
);
7994 static const Jim_ObjType exprObjType
= {
7996 FreeExprInternalRep
,
7999 JIM_TYPE_REFERENCES
,
8002 /* Expr bytecode structure */
8003 typedef struct ExprByteCode
8005 int len
; /* Length as number of tokens. */
8006 ScriptToken
*token
; /* Tokens array. */
8007 int inUse
; /* Used for sharing. */
8010 static void ExprFreeByteCode(Jim_Interp
*interp
, ExprByteCode
* expr
)
8014 for (i
= 0; i
< expr
->len
; i
++) {
8015 Jim_DecrRefCount(interp
, expr
->token
[i
].objPtr
);
8017 Jim_Free(expr
->token
);
8021 static void FreeExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8023 ExprByteCode
*expr
= (void *)objPtr
->internalRep
.ptr
;
8026 if (--expr
->inUse
!= 0) {
8030 ExprFreeByteCode(interp
, expr
);
8034 static void DupExprInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8036 JIM_NOTUSED(interp
);
8037 JIM_NOTUSED(srcPtr
);
8039 /* Just returns an simple string. */
8040 dupPtr
->typePtr
= NULL
;
8043 /* Check if an expr program looks correct. */
8044 static int ExprCheckCorrectness(ExprByteCode
* expr
)
8050 /* Try to check if there are stack underflows,
8051 * and make sure at the end of the program there is
8052 * a single result on the stack. */
8053 for (i
= 0; i
< expr
->len
; i
++) {
8054 ScriptToken
*t
= &expr
->token
[i
];
8055 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8058 stacklen
-= op
->arity
;
8062 if (t
->type
== JIM_EXPROP_TERNARY
|| t
->type
== JIM_EXPROP_TERNARY_LEFT
) {
8065 else if (t
->type
== JIM_EXPROP_COLON
|| t
->type
== JIM_EXPROP_COLON_LEFT
) {
8070 /* All operations and operands add one to the stack */
8073 if (stacklen
!= 1 || ternary
!= 0) {
8079 /* This procedure converts every occurrence of || and && opereators
8080 * in lazy unary versions.
8082 * a b || is converted into:
8084 * a <offset> |L b |R
8086 * a b && is converted into:
8088 * a <offset> &L b &R
8090 * "|L" checks if 'a' is true:
8091 * 1) if it is true pushes 1 and skips <offset> instructions to reach
8092 * the opcode just after |R.
8093 * 2) if it is false does nothing.
8094 * "|R" checks if 'b' is true:
8095 * 1) if it is true pushes 1, otherwise pushes 0.
8097 * "&L" checks if 'a' is true:
8098 * 1) if it is true does nothing.
8099 * 2) If it is false pushes 0 and skips <offset> instructions to reach
8100 * the opcode just after &R
8101 * "&R" checks if 'a' is true:
8102 * if it is true pushes 1, otherwise pushes 0.
8104 static int ExprAddLazyOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8108 int leftindex
, arity
, offset
;
8110 /* Search for the end of the first operator */
8111 leftindex
= expr
->len
- 1;
8115 ScriptToken
*tt
= &expr
->token
[leftindex
];
8117 if (tt
->type
>= JIM_TT_EXPR_OP
) {
8118 arity
+= JimExprOperatorInfoByOpcode(tt
->type
)->arity
;
8121 if (--leftindex
< 0) {
8128 memmove(&expr
->token
[leftindex
+ 2], &expr
->token
[leftindex
],
8129 sizeof(*expr
->token
) * (expr
->len
- leftindex
));
8131 offset
= (expr
->len
- leftindex
) - 1;
8133 /* Now we rely on the fact the the left and right version have opcodes
8134 * 1 and 2 after the main opcode respectively
8136 expr
->token
[leftindex
+ 1].type
= t
->type
+ 1;
8137 expr
->token
[leftindex
+ 1].objPtr
= interp
->emptyObj
;
8139 expr
->token
[leftindex
].type
= JIM_TT_EXPR_INT
;
8140 expr
->token
[leftindex
].objPtr
= Jim_NewIntObj(interp
, offset
);
8142 /* Now add the 'R' operator */
8143 expr
->token
[expr
->len
].objPtr
= interp
->emptyObj
;
8144 expr
->token
[expr
->len
].type
= t
->type
+ 2;
8147 /* Do we need to adjust the skip count for any &L, |L, ?L or :L in the left operand? */
8148 for (i
= leftindex
- 1; i
> 0; i
--) {
8149 if (JimExprOperatorInfoByOpcode(expr
->token
[i
].type
)->lazy
== LAZY_LEFT
) {
8150 if (JimWideValue(expr
->token
[i
- 1].objPtr
) + i
- 1 >= leftindex
) {
8151 JimWideValue(expr
->token
[i
- 1].objPtr
) += 2;
8158 static int ExprAddOperator(Jim_Interp
*interp
, ExprByteCode
* expr
, ParseToken
*t
)
8160 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8161 const struct Jim_ExprOperator
*op
= JimExprOperatorInfoByOpcode(t
->type
);
8163 if (op
->lazy
== LAZY_OP
) {
8164 if (ExprAddLazyOperator(interp
, expr
, t
) != JIM_OK
) {
8165 Jim_SetResultFormatted(interp
, "Expression has bad operands to %s", op
->name
);
8170 token
->objPtr
= interp
->emptyObj
;
8171 token
->type
= t
->type
;
8178 * Returns the index of the COLON_LEFT to the left of 'right_index'
8179 * taking into account nesting.
8181 * The expression *must* be well formed, thus a COLON_LEFT will always be found.
8183 static int ExprTernaryGetColonLeftIndex(ExprByteCode
*expr
, int right_index
)
8185 int ternary_count
= 1;
8189 while (right_index
> 1) {
8190 if (expr
->token
[right_index
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8193 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_RIGHT
) {
8196 else if (expr
->token
[right_index
].type
== JIM_EXPROP_COLON_LEFT
&& ternary_count
== 1) {
8207 * Find the left/right indices for the ternary expression to the left of 'right_index'.
8209 * Returns 1 if found, and fills in *prev_right_index and *prev_left_index.
8210 * Otherwise returns 0.
8212 static int ExprTernaryGetMoveIndices(ExprByteCode
*expr
, int right_index
, int *prev_right_index
, int *prev_left_index
)
8214 int i
= right_index
- 1;
8215 int ternary_count
= 1;
8218 if (expr
->token
[i
].type
== JIM_EXPROP_TERNARY_LEFT
) {
8219 if (--ternary_count
== 0 && expr
->token
[i
- 2].type
== JIM_EXPROP_COLON_RIGHT
) {
8220 *prev_right_index
= i
- 2;
8221 *prev_left_index
= ExprTernaryGetColonLeftIndex(expr
, *prev_right_index
);
8225 else if (expr
->token
[i
].type
== JIM_EXPROP_COLON_RIGHT
) {
8226 if (ternary_count
== 0) {
8237 * ExprTernaryReorderExpression description
8238 * ========================================
8240 * ?: is right-to-left associative which doesn't work with the stack-based
8241 * expression engine. The fix is to reorder the bytecode.
8247 * Has initial bytecode:
8249 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '0' (44=COLON_RIGHT)
8250 * '2' (40=TERNARY_LEFT) '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT)
8252 * The fix involves simulating this expression instead:
8256 * With the following bytecode:
8258 * '1' '2' (40=TERNARY_LEFT) '2' (41=TERNARY_RIGHT) '10' (43=COLON_LEFT) '0' '2' (40=TERNARY_LEFT)
8259 * '3' (41=TERNARY_RIGHT) '2' (43=COLON_LEFT) '4' (44=COLON_RIGHT) (44=COLON_RIGHT)
8261 * i.e. The token COLON_RIGHT at index 8 is moved towards the end of the stack, all tokens above 8
8262 * are shifted down and the skip count of the token JIM_EXPROP_COLON_LEFT at index 5 is
8263 * incremented by the amount tokens shifted down. The token JIM_EXPROP_COLON_RIGHT that is moved
8264 * is identified as immediately preceeding a token JIM_EXPROP_TERNARY_LEFT
8266 * ExprTernaryReorderExpression works thus as follows :
8267 * - start from the end of the stack
8268 * - while walking towards the beginning of the stack
8269 * if token=JIM_EXPROP_COLON_RIGHT then
8270 * find the associated token JIM_EXPROP_TERNARY_LEFT, which allows to
8271 * find the associated token previous(JIM_EXPROP_COLON_RIGHT)
8272 * find the associated token previous(JIM_EXPROP_LEFT_RIGHT)
8274 * perform the rotation
8275 * update the skip count of the token previous(JIM_EXPROP_LEFT_RIGHT)
8279 * Note: care has to be taken for nested ternary constructs!!!
8281 static void ExprTernaryReorderExpression(Jim_Interp
*interp
, ExprByteCode
*expr
)
8285 for (i
= expr
->len
- 1; i
> 1; i
--) {
8286 int prev_right_index
;
8287 int prev_left_index
;
8291 if (expr
->token
[i
].type
!= JIM_EXPROP_COLON_RIGHT
) {
8295 /* COLON_RIGHT found: get the indexes needed to move the tokens in the stack (if any) */
8296 if (ExprTernaryGetMoveIndices(expr
, i
, &prev_right_index
, &prev_left_index
) == 0) {
8301 ** rotate tokens down
8303 ** +-> [i] : JIM_EXPROP_COLON_RIGHT
8312 ** +- [prev_right_index] : JIM_EXPROP_COLON_RIGHT
8314 tmp
= expr
->token
[prev_right_index
];
8315 for (j
= prev_right_index
; j
< i
; j
++) {
8316 expr
->token
[j
] = expr
->token
[j
+ 1];
8318 expr
->token
[i
] = tmp
;
8320 /* Increment the 'skip' count associated to the previous JIM_EXPROP_COLON_LEFT token
8322 * This is 'colon left increment' = i - prev_right_index
8324 * [prev_left_index] : JIM_EXPROP_LEFT_RIGHT
8325 * [prev_left_index-1] : skip_count
8328 JimWideValue(expr
->token
[prev_left_index
-1].objPtr
) += (i
- prev_right_index
);
8330 /* Adjust for i-- in the loop */
8335 static ExprByteCode
*ExprCreateByteCode(Jim_Interp
*interp
, const ParseTokenList
*tokenlist
, Jim_Obj
*fileNameObj
)
8341 int prevtt
= JIM_TT_NONE
;
8342 int have_ternary
= 0;
8345 int count
= tokenlist
->count
- 1;
8347 expr
= Jim_Alloc(sizeof(*expr
));
8351 Jim_InitStack(&stack
);
8353 /* Need extra bytecodes for lazy operators.
8354 * Also check for the ternary operator
8356 for (i
= 0; i
< tokenlist
->count
; i
++) {
8357 ParseToken
*t
= &tokenlist
->list
[i
];
8359 if (JimExprOperatorInfoByOpcode(t
->type
)->lazy
== LAZY_OP
) {
8361 /* Ternary is a lazy op but also needs reordering */
8362 if (t
->type
== JIM_EXPROP_TERNARY
) {
8368 expr
->token
= Jim_Alloc(sizeof(ScriptToken
) * count
);
8370 for (i
= 0; i
< tokenlist
->count
&& ok
; i
++) {
8371 ParseToken
*t
= &tokenlist
->list
[i
];
8373 /* Next token will be stored here */
8374 struct ScriptToken
*token
= &expr
->token
[expr
->len
];
8376 if (t
->type
== JIM_TT_EOL
) {
8384 case JIM_TT_DICTSUGAR
:
8385 case JIM_TT_EXPRSUGAR
:
8387 token
->objPtr
= Jim_NewStringObj(interp
, t
->token
, t
->len
);
8388 token
->type
= t
->type
;
8389 if (t
->type
== JIM_TT_CMD
) {
8390 /* Only commands need source info */
8391 JimSetSourceInfo(interp
, token
->objPtr
, fileNameObj
, t
->line
);
8396 case JIM_TT_EXPR_INT
:
8397 token
->objPtr
= Jim_NewIntObj(interp
, strtoull(t
->token
, NULL
, 0));
8398 token
->type
= t
->type
;
8402 case JIM_TT_EXPR_DOUBLE
:
8403 token
->objPtr
= Jim_NewDoubleObj(interp
, strtod(t
->token
, NULL
));
8404 token
->type
= t
->type
;
8408 case JIM_TT_SUBEXPR_START
:
8409 Jim_StackPush(&stack
, t
);
8410 prevtt
= JIM_TT_NONE
;
8413 case JIM_TT_SUBEXPR_COMMA
:
8414 /* Simple approach. Comma is simply ignored */
8417 case JIM_TT_SUBEXPR_END
:
8419 while (Jim_StackLen(&stack
)) {
8420 ParseToken
*tt
= Jim_StackPop(&stack
);
8422 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8427 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8432 Jim_SetResultString(interp
, "Unexpected close parenthesis", -1);
8439 /* Must be an operator */
8440 const struct Jim_ExprOperator
*op
;
8443 /* Convert -/+ to unary minus or unary plus if necessary */
8444 if (prevtt
== JIM_TT_NONE
|| prevtt
>= JIM_TT_EXPR_OP
) {
8445 if (t
->type
== JIM_EXPROP_SUB
) {
8446 t
->type
= JIM_EXPROP_UNARYMINUS
;
8448 else if (t
->type
== JIM_EXPROP_ADD
) {
8449 t
->type
= JIM_EXPROP_UNARYPLUS
;
8453 op
= JimExprOperatorInfoByOpcode(t
->type
);
8455 /* Now handle precedence */
8456 while ((tt
= Jim_StackPeek(&stack
)) != NULL
) {
8457 const struct Jim_ExprOperator
*tt_op
=
8458 JimExprOperatorInfoByOpcode(tt
->type
);
8460 /* Note that right-to-left associativity of ?: operator is handled later */
8462 if (op
->arity
!= 1 && tt_op
->precedence
>= op
->precedence
) {
8463 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8467 Jim_StackPop(&stack
);
8473 Jim_StackPush(&stack
, t
);
8480 /* Reduce any remaining subexpr */
8481 while (Jim_StackLen(&stack
)) {
8482 ParseToken
*tt
= Jim_StackPop(&stack
);
8484 if (tt
->type
== JIM_TT_SUBEXPR_START
) {
8486 Jim_SetResultString(interp
, "Missing close parenthesis", -1);
8489 if (ExprAddOperator(interp
, expr
, tt
) != JIM_OK
) {
8496 ExprTernaryReorderExpression(interp
, expr
);
8500 /* Free the stack used for the compilation. */
8501 Jim_FreeStack(&stack
);
8503 for (i
= 0; i
< expr
->len
; i
++) {
8504 Jim_IncrRefCount(expr
->token
[i
].objPtr
);
8508 ExprFreeByteCode(interp
, expr
);
8516 /* This method takes the string representation of an expression
8517 * and generates a program for the Expr's stack-based VM. */
8518 static int SetExprFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
)
8521 const char *exprText
;
8522 struct JimParserCtx parser
;
8523 struct ExprByteCode
*expr
;
8524 ParseTokenList tokenlist
;
8526 Jim_Obj
*fileNameObj
;
8529 /* Try to get information about filename / line number */
8530 if (objPtr
->typePtr
== &sourceObjType
) {
8531 fileNameObj
= objPtr
->internalRep
.sourceValue
.fileNameObj
;
8532 line
= objPtr
->internalRep
.sourceValue
.lineNumber
;
8535 fileNameObj
= interp
->emptyObj
;
8538 Jim_IncrRefCount(fileNameObj
);
8540 exprText
= Jim_GetString(objPtr
, &exprTextLen
);
8542 /* Initially tokenise the expression into tokenlist */
8543 ScriptTokenListInit(&tokenlist
);
8545 JimParserInit(&parser
, exprText
, exprTextLen
, line
);
8546 while (!parser
.eof
) {
8547 if (JimParseExpression(&parser
) != JIM_OK
) {
8548 ScriptTokenListFree(&tokenlist
);
8550 Jim_SetResultFormatted(interp
, "syntax error in expression: \"%#s\"", objPtr
);
8555 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
8559 #ifdef DEBUG_SHOW_EXPR_TOKENS
8562 printf("==== Expr Tokens ====\n");
8563 for (i
= 0; i
< tokenlist
.count
; i
++) {
8564 printf("[%2d]@%d %s '%.*s'\n", i
, tokenlist
.list
[i
].line
, jim_tt_name(tokenlist
.list
[i
].type
),
8565 tokenlist
.list
[i
].len
, tokenlist
.list
[i
].token
);
8570 /* Now create the expression bytecode from the tokenlist */
8571 expr
= ExprCreateByteCode(interp
, &tokenlist
, fileNameObj
);
8573 /* No longer need the token list */
8574 ScriptTokenListFree(&tokenlist
);
8580 #ifdef DEBUG_SHOW_EXPR
8584 printf("==== Expr ====\n");
8585 for (i
= 0; i
< expr
->len
; i
++) {
8586 ScriptToken
*t
= &expr
->token
[i
];
8588 printf("[%2d] %s '%s'\n", i
, jim_tt_name(t
->type
), Jim_String(t
->objPtr
));
8593 /* Check program correctness. */
8594 if (ExprCheckCorrectness(expr
) != JIM_OK
) {
8595 ExprFreeByteCode(interp
, expr
);
8602 /* Free the old internal rep and set the new one. */
8603 Jim_DecrRefCount(interp
, fileNameObj
);
8604 Jim_FreeIntRep(interp
, objPtr
);
8605 Jim_SetIntRepPtr(objPtr
, expr
);
8606 objPtr
->typePtr
= &exprObjType
;
8610 static ExprByteCode
*JimGetExpression(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8612 if (objPtr
->typePtr
!= &exprObjType
) {
8613 if (SetExprFromAny(interp
, objPtr
) != JIM_OK
) {
8617 return (ExprByteCode
*) Jim_GetIntRepPtr(objPtr
);
8620 /* -----------------------------------------------------------------------------
8621 * Expressions evaluation.
8622 * Jim uses a specialized stack-based virtual machine for expressions,
8623 * that takes advantage of the fact that expr's operators
8624 * can't be redefined.
8626 * Jim_EvalExpression() uses the bytecode compiled by
8627 * SetExprFromAny() method of the "expression" object.
8629 * On success a Tcl Object containing the result of the evaluation
8630 * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
8632 * On error the function returns a retcode != to JIM_OK and set a suitable
8633 * error on the interp.
8634 * ---------------------------------------------------------------------------*/
8635 #define JIM_EE_STATICSTACK_LEN 10
8637 int Jim_EvalExpression(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, Jim_Obj
**exprResultPtrPtr
)
8640 Jim_Obj
*staticStack
[JIM_EE_STATICSTACK_LEN
];
8642 int retcode
= JIM_OK
;
8643 struct JimExprState e
;
8645 expr
= JimGetExpression(interp
, exprObjPtr
);
8647 return JIM_ERR
; /* error in expression. */
8650 #ifdef JIM_OPTIMIZATION
8651 /* Check for one of the following common expressions used by while/for
8656 * $a < CONST, $a < $b
8657 * $a <= CONST, $a <= $b
8658 * $a > CONST, $a > $b
8659 * $a >= CONST, $a >= $b
8660 * $a != CONST, $a != $b
8661 * $a == CONST, $a == $b
8666 /* STEP 1 -- Check if there are the conditions to run the specialized
8667 * version of while */
8669 switch (expr
->len
) {
8671 if (expr
->token
[0].type
== JIM_TT_EXPR_INT
) {
8672 *exprResultPtrPtr
= expr
->token
[0].objPtr
;
8673 Jim_IncrRefCount(*exprResultPtrPtr
);
8676 if (expr
->token
[0].type
== JIM_TT_VAR
) {
8677 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_ERRMSG
);
8679 *exprResultPtrPtr
= objPtr
;
8680 Jim_IncrRefCount(*exprResultPtrPtr
);
8687 if (expr
->token
[1].type
== JIM_EXPROP_NOT
&& expr
->token
[0].type
== JIM_TT_VAR
) {
8690 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8691 if (objPtr
&& JimIsWide(objPtr
)
8692 && Jim_GetWide(interp
, objPtr
, &wideValue
) == JIM_OK
) {
8693 *exprResultPtrPtr
= wideValue
? interp
->falseObj
: interp
->trueObj
;
8694 Jim_IncrRefCount(*exprResultPtrPtr
);
8701 if (expr
->token
[0].type
== JIM_TT_VAR
&& (expr
->token
[1].type
== JIM_TT_EXPR_INT
8702 || expr
->token
[1].type
== JIM_TT_VAR
)) {
8703 switch (expr
->token
[2].type
) {
8705 case JIM_EXPROP_LTE
:
8707 case JIM_EXPROP_GTE
:
8708 case JIM_EXPROP_NUMEQ
:
8709 case JIM_EXPROP_NUMNE
:{
8711 jim_wide wideValueA
;
8712 jim_wide wideValueB
;
8714 objPtr
= Jim_GetVariable(interp
, expr
->token
[0].objPtr
, JIM_NONE
);
8715 if (objPtr
&& JimIsWide(objPtr
)
8716 && Jim_GetWide(interp
, objPtr
, &wideValueA
) == JIM_OK
) {
8717 if (expr
->token
[1].type
== JIM_TT_VAR
) {
8719 Jim_GetVariable(interp
, expr
->token
[1].objPtr
,
8723 objPtr
= expr
->token
[1].objPtr
;
8725 if (objPtr
&& JimIsWide(objPtr
)
8726 && Jim_GetWide(interp
, objPtr
, &wideValueB
) == JIM_OK
) {
8729 switch (expr
->token
[2].type
) {
8731 cmpRes
= wideValueA
< wideValueB
;
8733 case JIM_EXPROP_LTE
:
8734 cmpRes
= wideValueA
<= wideValueB
;
8737 cmpRes
= wideValueA
> wideValueB
;
8739 case JIM_EXPROP_GTE
:
8740 cmpRes
= wideValueA
>= wideValueB
;
8742 case JIM_EXPROP_NUMEQ
:
8743 cmpRes
= wideValueA
== wideValueB
;
8745 case JIM_EXPROP_NUMNE
:
8746 cmpRes
= wideValueA
!= wideValueB
;
8748 default: /*notreached */
8752 cmpRes
? interp
->trueObj
: interp
->falseObj
;
8753 Jim_IncrRefCount(*exprResultPtrPtr
);
8765 /* In order to avoid that the internal repr gets freed due to
8766 * shimmering of the exprObjPtr's object, we make the internal rep
8770 /* The stack-based expr VM itself */
8772 /* Stack allocation. Expr programs have the feature that
8773 * a program of length N can't require a stack longer than
8775 if (expr
->len
> JIM_EE_STATICSTACK_LEN
)
8776 e
.stack
= Jim_Alloc(sizeof(Jim_Obj
*) * expr
->len
);
8778 e
.stack
= staticStack
;
8782 /* Execute every instruction */
8783 for (i
= 0; i
< expr
->len
&& retcode
== JIM_OK
; i
++) {
8786 switch (expr
->token
[i
].type
) {
8787 case JIM_TT_EXPR_INT
:
8788 case JIM_TT_EXPR_DOUBLE
:
8790 ExprPush(&e
, expr
->token
[i
].objPtr
);
8794 objPtr
= Jim_GetVariable(interp
, expr
->token
[i
].objPtr
, JIM_ERRMSG
);
8796 ExprPush(&e
, objPtr
);
8803 case JIM_TT_DICTSUGAR
:
8804 objPtr
= JimExpandDictSugar(interp
, expr
->token
[i
].objPtr
);
8806 ExprPush(&e
, objPtr
);
8814 retcode
= Jim_SubstObj(interp
, expr
->token
[i
].objPtr
, &objPtr
, JIM_NONE
);
8815 if (retcode
== JIM_OK
) {
8816 ExprPush(&e
, objPtr
);
8821 retcode
= Jim_EvalObj(interp
, expr
->token
[i
].objPtr
);
8822 if (retcode
== JIM_OK
) {
8823 ExprPush(&e
, Jim_GetResult(interp
));
8828 /* Find and execute the operation */
8830 e
.opcode
= expr
->token
[i
].type
;
8832 retcode
= JimExprOperatorInfoByOpcode(e
.opcode
)->funcop(interp
, &e
);
8833 /* Skip some opcodes if necessary */
8842 if (retcode
== JIM_OK
) {
8843 *exprResultPtrPtr
= ExprPop(&e
);
8846 for (i
= 0; i
< e
.stacklen
; i
++) {
8847 Jim_DecrRefCount(interp
, e
.stack
[i
]);
8850 if (e
.stack
!= staticStack
) {
8856 int Jim_GetBoolFromExpr(Jim_Interp
*interp
, Jim_Obj
*exprObjPtr
, int *boolPtr
)
8861 Jim_Obj
*exprResultPtr
;
8863 retcode
= Jim_EvalExpression(interp
, exprObjPtr
, &exprResultPtr
);
8864 if (retcode
!= JIM_OK
)
8867 if (JimGetWideNoErr(interp
, exprResultPtr
, &wideValue
) != JIM_OK
) {
8868 if (Jim_GetDouble(interp
, exprResultPtr
, &doubleValue
) != JIM_OK
) {
8869 Jim_DecrRefCount(interp
, exprResultPtr
);
8873 Jim_DecrRefCount(interp
, exprResultPtr
);
8874 *boolPtr
= doubleValue
!= 0;
8878 *boolPtr
= wideValue
!= 0;
8880 Jim_DecrRefCount(interp
, exprResultPtr
);
8884 /* -----------------------------------------------------------------------------
8885 * ScanFormat String Object
8886 * ---------------------------------------------------------------------------*/
8888 /* This Jim_Obj will held a parsed representation of a format string passed to
8889 * the Jim_ScanString command. For error diagnostics, the scanformat string has
8890 * to be parsed in its entirely first and then, if correct, can be used for
8891 * scanning. To avoid endless re-parsing, the parsed representation will be
8892 * stored in an internal representation and re-used for performance reason. */
8894 /* A ScanFmtPartDescr will held the information of /one/ part of the whole
8895 * scanformat string. This part will later be used to extract information
8896 * out from the string to be parsed by Jim_ScanString */
8898 typedef struct ScanFmtPartDescr
8900 char type
; /* Type of conversion (e.g. c, d, f) */
8901 char modifier
; /* Modify type (e.g. l - long, h - short */
8902 size_t width
; /* Maximal width of input to be converted */
8903 int pos
; /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */
8904 char *arg
; /* Specification of a CHARSET conversion */
8905 char *prefix
; /* Prefix to be scanned literally before conversion */
8908 /* The ScanFmtStringObj will hold the internal representation of a scanformat
8909 * string parsed and separated in part descriptions. Furthermore it contains
8910 * the original string representation of the scanformat string to allow for
8911 * fast update of the Jim_Obj's string representation part.
8913 * As an add-on the internal object representation adds some scratch pad area
8914 * for usage by Jim_ScanString to avoid endless allocating and freeing of
8915 * memory for purpose of string scanning.
8917 * The error member points to a static allocated string in case of a mal-
8918 * formed scanformat string or it contains '0' (NULL) in case of a valid
8919 * parse representation.
8921 * The whole memory of the internal representation is allocated as a single
8922 * area of memory that will be internally separated. So freeing and duplicating
8923 * of such an object is cheap */
8925 typedef struct ScanFmtStringObj
8927 jim_wide size
; /* Size of internal repr in bytes */
8928 char *stringRep
; /* Original string representation */
8929 size_t count
; /* Number of ScanFmtPartDescr contained */
8930 size_t convCount
; /* Number of conversions that will assign */
8931 size_t maxPos
; /* Max position index if XPG3 is used */
8932 const char *error
; /* Ptr to error text (NULL if no error */
8933 char *scratch
; /* Some scratch pad used by Jim_ScanString */
8934 ScanFmtPartDescr descr
[1]; /* The vector of partial descriptions */
8938 static void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
);
8939 static void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
);
8940 static void UpdateStringOfScanFmt(Jim_Obj
*objPtr
);
8942 static const Jim_ObjType scanFmtStringObjType
= {
8944 FreeScanFmtInternalRep
,
8945 DupScanFmtInternalRep
,
8946 UpdateStringOfScanFmt
,
8950 void FreeScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8952 JIM_NOTUSED(interp
);
8953 Jim_Free((char *)objPtr
->internalRep
.ptr
);
8954 objPtr
->internalRep
.ptr
= 0;
8957 void DupScanFmtInternalRep(Jim_Interp
*interp
, Jim_Obj
*srcPtr
, Jim_Obj
*dupPtr
)
8959 size_t size
= (size_t) ((ScanFmtStringObj
*) srcPtr
->internalRep
.ptr
)->size
;
8960 ScanFmtStringObj
*newVec
= (ScanFmtStringObj
*) Jim_Alloc(size
);
8962 JIM_NOTUSED(interp
);
8963 memcpy(newVec
, srcPtr
->internalRep
.ptr
, size
);
8964 dupPtr
->internalRep
.ptr
= newVec
;
8965 dupPtr
->typePtr
= &scanFmtStringObjType
;
8968 void UpdateStringOfScanFmt(Jim_Obj
*objPtr
)
8970 char *bytes
= ((ScanFmtStringObj
*) objPtr
->internalRep
.ptr
)->stringRep
;
8972 objPtr
->bytes
= Jim_StrDup(bytes
);
8973 objPtr
->length
= strlen(bytes
);
8976 /* SetScanFmtFromAny will parse a given string and create the internal
8977 * representation of the format specification. In case of an error
8978 * the error data member of the internal representation will be set
8979 * to an descriptive error text and the function will be left with
8980 * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
8983 static int SetScanFmtFromAny(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
8985 ScanFmtStringObj
*fmtObj
;
8987 int maxCount
, i
, approxSize
, lastPos
= -1;
8988 const char *fmt
= objPtr
->bytes
;
8989 int maxFmtLen
= objPtr
->length
;
8990 const char *fmtEnd
= fmt
+ maxFmtLen
;
8993 Jim_FreeIntRep(interp
, objPtr
);
8994 /* Count how many conversions could take place maximally */
8995 for (i
= 0, maxCount
= 0; i
< maxFmtLen
; ++i
)
8998 /* Calculate an approximation of the memory necessary */
8999 approxSize
= sizeof(ScanFmtStringObj
) /* Size of the container */
9000 +(maxCount
+ 1) * sizeof(ScanFmtPartDescr
) /* Size of all partials */
9001 +maxFmtLen
* sizeof(char) + 3 + 1 /* Scratch + "%n" + '\0' */
9002 + maxFmtLen
* sizeof(char) + 1 /* Original stringrep */
9003 + maxFmtLen
* sizeof(char) /* Arg for CHARSETs */
9004 +(maxCount
+ 1) * sizeof(char) /* '\0' for every partial */
9005 +1; /* safety byte */
9006 fmtObj
= (ScanFmtStringObj
*) Jim_Alloc(approxSize
);
9007 memset(fmtObj
, 0, approxSize
);
9008 fmtObj
->size
= approxSize
;
9010 fmtObj
->scratch
= (char *)&fmtObj
->descr
[maxCount
+ 1];
9011 fmtObj
->stringRep
= fmtObj
->scratch
+ maxFmtLen
+ 3 + 1;
9012 memcpy(fmtObj
->stringRep
, fmt
, maxFmtLen
);
9013 buffer
= fmtObj
->stringRep
+ maxFmtLen
+ 1;
9014 objPtr
->internalRep
.ptr
= fmtObj
;
9015 objPtr
->typePtr
= &scanFmtStringObjType
;
9016 for (i
= 0, curr
= 0; fmt
< fmtEnd
; ++fmt
) {
9017 int width
= 0, skip
;
9018 ScanFmtPartDescr
*descr
= &fmtObj
->descr
[curr
];
9021 descr
->width
= 0; /* Assume width unspecified */
9022 /* Overread and store any "literal" prefix */
9023 if (*fmt
!= '%' || fmt
[1] == '%') {
9025 descr
->prefix
= &buffer
[i
];
9026 for (; fmt
< fmtEnd
; ++fmt
) {
9036 /* Skip the conversion introducing '%' sign */
9038 /* End reached due to non-conversion literal only? */
9041 descr
->pos
= 0; /* Assume "natural" positioning */
9043 descr
->pos
= -1; /* Okay, conversion will not be assigned */
9047 fmtObj
->convCount
++; /* Otherwise count as assign-conversion */
9048 /* Check if next token is a number (could be width or pos */
9049 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9051 /* Was the number a XPG3 position specifier? */
9052 if (descr
->pos
!= -1 && *fmt
== '$') {
9058 /* Look if "natural" postioning and XPG3 one was mixed */
9059 if ((lastPos
== 0 && descr
->pos
> 0)
9060 || (lastPos
> 0 && descr
->pos
== 0)) {
9061 fmtObj
->error
= "cannot mix \"%\" and \"%n$\" conversion specifiers";
9064 /* Look if this position was already used */
9065 for (prev
= 0; prev
< curr
; ++prev
) {
9066 if (fmtObj
->descr
[prev
].pos
== -1)
9068 if (fmtObj
->descr
[prev
].pos
== descr
->pos
) {
9070 "variable is assigned by multiple \"%n$\" conversion specifiers";
9074 /* Try to find a width after the XPG3 specifier */
9075 if (sscanf(fmt
, "%d%n", &width
, &skip
) == 1) {
9076 descr
->width
= width
;
9079 if (descr
->pos
> 0 && (size_t) descr
->pos
> fmtObj
->maxPos
)
9080 fmtObj
->maxPos
= descr
->pos
;
9083 /* Number was not a XPG3, so it has to be a width */
9084 descr
->width
= width
;
9087 /* If positioning mode was undetermined yet, fix this */
9089 lastPos
= descr
->pos
;
9090 /* Handle CHARSET conversion type ... */
9092 int swapped
= 1, beg
= i
, end
, j
;
9095 descr
->arg
= &buffer
[i
];
9098 buffer
[i
++] = *fmt
++;
9100 buffer
[i
++] = *fmt
++;
9101 while (*fmt
&& *fmt
!= ']')
9102 buffer
[i
++] = *fmt
++;
9104 fmtObj
->error
= "unmatched [ in format string";
9109 /* In case a range fence was given "backwards", swap it */
9112 for (j
= beg
+ 1; j
< end
- 1; ++j
) {
9113 if (buffer
[j
] == '-' && buffer
[j
- 1] > buffer
[j
+ 1]) {
9114 char tmp
= buffer
[j
- 1];
9116 buffer
[j
- 1] = buffer
[j
+ 1];
9117 buffer
[j
+ 1] = tmp
;
9124 /* Remember any valid modifier if given */
9125 if (strchr("hlL", *fmt
) != 0)
9126 descr
->modifier
= tolower((int)*fmt
++);
9129 if (strchr("efgcsndoxui", *fmt
) == 0) {
9130 fmtObj
->error
= "bad scan conversion character";
9133 else if (*fmt
== 'c' && descr
->width
!= 0) {
9134 fmtObj
->error
= "field width may not be specified in %c " "conversion";
9137 else if (*fmt
== 'u' && descr
->modifier
== 'l') {
9138 fmtObj
->error
= "unsigned wide not supported";
9148 /* Some accessor macros to allow lowlevel access to fields of internal repr */
9150 #define FormatGetCnvCount(_fo_) \
9151 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
9152 #define FormatGetMaxPos(_fo_) \
9153 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
9154 #define FormatGetError(_fo_) \
9155 ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
9157 /* JimScanAString is used to scan an unspecified string that ends with
9158 * next WS, or a string that is specified via a charset.
9161 static Jim_Obj
*JimScanAString(Jim_Interp
*interp
, const char *sdescr
, const char *str
)
9163 char *buffer
= Jim_StrDup(str
);
9170 if (!sdescr
&& isspace(UCHAR(*str
)))
9171 break; /* EOS via WS if unspecified */
9173 n
= utf8_tounicode(str
, &c
);
9174 if (sdescr
&& !JimCharsetMatch(sdescr
, c
, JIM_CHARSET_SCAN
))
9180 return Jim_NewStringObjNoAlloc(interp
, buffer
, p
- buffer
);
9183 /* ScanOneEntry will scan one entry out of the string passed as argument.
9184 * It use the sscanf() function for this task. After extracting and
9185 * converting of the value, the count of scanned characters will be
9186 * returned of -1 in case of no conversion tool place and string was
9187 * already scanned thru */
9189 static int ScanOneEntry(Jim_Interp
*interp
, const char *str
, int pos
, int strLen
,
9190 ScanFmtStringObj
* fmtObj
, long idx
, Jim_Obj
**valObjPtr
)
9193 const ScanFmtPartDescr
*descr
= &fmtObj
->descr
[idx
];
9195 size_t anchor
= pos
;
9197 Jim_Obj
*tmpObj
= NULL
;
9199 /* First pessimistically assume, we will not scan anything :-) */
9201 if (descr
->prefix
) {
9202 /* There was a prefix given before the conversion, skip it and adjust
9203 * the string-to-be-parsed accordingly */
9204 /* XXX: Should be checking strLen, not str[pos] */
9205 for (i
= 0; pos
< strLen
&& descr
->prefix
[i
]; ++i
) {
9206 /* If prefix require, skip WS */
9207 if (isspace(UCHAR(descr
->prefix
[i
])))
9208 while (pos
< strLen
&& isspace(UCHAR(str
[pos
])))
9210 else if (descr
->prefix
[i
] != str
[pos
])
9211 break; /* Prefix do not match here, leave the loop */
9213 ++pos
; /* Prefix matched so far, next round */
9215 if (pos
>= strLen
) {
9216 return -1; /* All of str consumed: EOF condition */
9218 else if (descr
->prefix
[i
] != 0)
9219 return 0; /* Not whole prefix consumed, no conversion possible */
9221 /* For all but following conversion, skip leading WS */
9222 if (descr
->type
!= 'c' && descr
->type
!= '[' && descr
->type
!= 'n')
9223 while (isspace(UCHAR(str
[pos
])))
9225 /* Determine how much skipped/scanned so far */
9226 scanned
= pos
- anchor
;
9228 /* %c is a special, simple case. no width */
9229 if (descr
->type
== 'n') {
9230 /* Return pseudo conversion means: how much scanned so far? */
9231 *valObjPtr
= Jim_NewIntObj(interp
, anchor
+ scanned
);
9233 else if (pos
>= strLen
) {
9234 /* Cannot scan anything, as str is totally consumed */
9237 else if (descr
->type
== 'c') {
9239 scanned
+= utf8_tounicode(&str
[pos
], &c
);
9240 *valObjPtr
= Jim_NewIntObj(interp
, c
);
9244 /* Processing of conversions follows ... */
9245 if (descr
->width
> 0) {
9246 /* Do not try to scan as fas as possible but only the given width.
9247 * To ensure this, we copy the part that should be scanned. */
9248 size_t sLen
= utf8_strlen(&str
[pos
], strLen
- pos
);
9249 size_t tLen
= descr
->width
> sLen
? sLen
: descr
->width
;
9251 tmpObj
= Jim_NewStringObjUtf8(interp
, str
+ pos
, tLen
);
9252 tok
= tmpObj
->bytes
;
9255 /* As no width was given, simply refer to the original string */
9258 switch (descr
->type
) {
9264 char *endp
; /* Position where the number finished */
9267 int base
= descr
->type
== 'o' ? 8
9268 : descr
->type
== 'x' ? 16 : descr
->type
== 'i' ? 0 : 10;
9270 /* Try to scan a number with the given base */
9271 w
= strtoull(tok
, &endp
, base
);
9272 if (endp
== tok
&& base
== 0) {
9273 /* If scanning failed, and base was undetermined, simply
9274 * put it to 10 and try once more. This should catch the
9275 * case where %i begin to parse a number prefix (e.g.
9276 * '0x' but no further digits follows. This will be
9277 * handled as a ZERO followed by a char 'x' by Tcl */
9278 w
= strtoull(tok
, &endp
, 10);
9282 /* There was some number sucessfully scanned! */
9283 *valObjPtr
= Jim_NewIntObj(interp
, w
);
9285 /* Adjust the number-of-chars scanned so far */
9286 scanned
+= endp
- tok
;
9289 /* Nothing was scanned. We have to determine if this
9290 * happened due to e.g. prefix mismatch or input str
9292 scanned
= *tok
? 0 : -1;
9298 *valObjPtr
= JimScanAString(interp
, descr
->arg
, tok
);
9299 scanned
+= Jim_Length(*valObjPtr
);
9306 double value
= strtod(tok
, &endp
);
9309 /* There was some number sucessfully scanned! */
9310 *valObjPtr
= Jim_NewDoubleObj(interp
, value
);
9311 /* Adjust the number-of-chars scanned so far */
9312 scanned
+= endp
- tok
;
9315 /* Nothing was scanned. We have to determine if this
9316 * happened due to e.g. prefix mismatch or input str
9318 scanned
= *tok
? 0 : -1;
9323 /* If a substring was allocated (due to pre-defined width) do not
9324 * forget to free it */
9326 Jim_FreeNewObj(interp
, tmpObj
);
9332 /* Jim_ScanString is the workhorse of string scanning. It will scan a given
9333 * string and returns all converted (and not ignored) values in a list back
9334 * to the caller. If an error occured, a NULL pointer will be returned */
9336 Jim_Obj
*Jim_ScanString(Jim_Interp
*interp
, Jim_Obj
*strObjPtr
, Jim_Obj
*fmtObjPtr
, int flags
)
9340 const char *str
= Jim_String(strObjPtr
);
9341 int strLen
= Jim_Utf8Length(interp
, strObjPtr
);
9342 Jim_Obj
*resultList
= 0;
9343 Jim_Obj
**resultVec
= 0;
9345 Jim_Obj
*emptyStr
= 0;
9346 ScanFmtStringObj
*fmtObj
;
9348 /* This should never happen. The format object should already be of the correct type */
9349 JimPanic((fmtObjPtr
->typePtr
!= &scanFmtStringObjType
, "Jim_ScanString() for non-scan format"));
9351 fmtObj
= (ScanFmtStringObj
*) fmtObjPtr
->internalRep
.ptr
;
9352 /* Check if format specification was valid */
9353 if (fmtObj
->error
!= 0) {
9354 if (flags
& JIM_ERRMSG
)
9355 Jim_SetResultString(interp
, fmtObj
->error
, -1);
9358 /* Allocate a new "shared" empty string for all unassigned conversions */
9359 emptyStr
= Jim_NewEmptyStringObj(interp
);
9360 Jim_IncrRefCount(emptyStr
);
9361 /* Create a list and fill it with empty strings up to max specified XPG3 */
9362 resultList
= Jim_NewListObj(interp
, 0, 0);
9363 if (fmtObj
->maxPos
> 0) {
9364 for (i
= 0; i
< fmtObj
->maxPos
; ++i
)
9365 Jim_ListAppendElement(interp
, resultList
, emptyStr
);
9366 JimListGetElements(interp
, resultList
, &resultc
, &resultVec
);
9368 /* Now handle every partial format description */
9369 for (i
= 0, pos
= 0; i
< fmtObj
->count
; ++i
) {
9370 ScanFmtPartDescr
*descr
= &(fmtObj
->descr
[i
]);
9373 /* Only last type may be "literal" w/o conversion - skip it! */
9374 if (descr
->type
== 0)
9376 /* As long as any conversion could be done, we will proceed */
9378 scanned
= ScanOneEntry(interp
, str
, pos
, strLen
, fmtObj
, i
, &value
);
9379 /* In case our first try results in EOF, we will leave */
9380 if (scanned
== -1 && i
== 0)
9382 /* Advance next pos-to-be-scanned for the amount scanned already */
9385 /* value == 0 means no conversion took place so take empty string */
9387 value
= Jim_NewEmptyStringObj(interp
);
9388 /* If value is a non-assignable one, skip it */
9389 if (descr
->pos
== -1) {
9390 Jim_FreeNewObj(interp
, value
);
9392 else if (descr
->pos
== 0)
9393 /* Otherwise append it to the result list if no XPG3 was given */
9394 Jim_ListAppendElement(interp
, resultList
, value
);
9395 else if (resultVec
[descr
->pos
- 1] == emptyStr
) {
9396 /* But due to given XPG3, put the value into the corr. slot */
9397 Jim_DecrRefCount(interp
, resultVec
[descr
->pos
- 1]);
9398 Jim_IncrRefCount(value
);
9399 resultVec
[descr
->pos
- 1] = value
;
9402 /* Otherwise, the slot was already used - free obj and ERROR */
9403 Jim_FreeNewObj(interp
, value
);
9407 Jim_DecrRefCount(interp
, emptyStr
);
9410 Jim_DecrRefCount(interp
, emptyStr
);
9411 Jim_FreeNewObj(interp
, resultList
);
9412 return (Jim_Obj
*)EOF
;
9414 Jim_DecrRefCount(interp
, emptyStr
);
9415 Jim_FreeNewObj(interp
, resultList
);
9419 /* -----------------------------------------------------------------------------
9420 * Pseudo Random Number Generation
9421 * ---------------------------------------------------------------------------*/
9422 /* Initialize the sbox with the numbers from 0 to 255 */
9423 static void JimPrngInit(Jim_Interp
*interp
)
9425 #define PRNG_SEED_SIZE 256
9428 time_t t
= time(NULL
);
9430 interp
->prngState
= Jim_Alloc(sizeof(Jim_PrngState
));
9432 seed
= Jim_Alloc(PRNG_SEED_SIZE
* sizeof(*seed
));
9433 for (i
= 0; i
< PRNG_SEED_SIZE
; i
++) {
9434 seed
[i
] = (rand() ^ t
^ clock());
9436 JimPrngSeed(interp
, (unsigned char *)seed
, PRNG_SEED_SIZE
* sizeof(*seed
));
9440 /* Generates N bytes of random data */
9441 static void JimRandomBytes(Jim_Interp
*interp
, void *dest
, unsigned int len
)
9443 Jim_PrngState
*prng
;
9444 unsigned char *destByte
= (unsigned char *)dest
;
9445 unsigned int si
, sj
, x
;
9447 /* initialization, only needed the first time */
9448 if (interp
->prngState
== NULL
)
9449 JimPrngInit(interp
);
9450 prng
= interp
->prngState
;
9451 /* generates 'len' bytes of pseudo-random numbers */
9452 for (x
= 0; x
< len
; x
++) {
9453 prng
->i
= (prng
->i
+ 1) & 0xff;
9454 si
= prng
->sbox
[prng
->i
];
9455 prng
->j
= (prng
->j
+ si
) & 0xff;
9456 sj
= prng
->sbox
[prng
->j
];
9457 prng
->sbox
[prng
->i
] = sj
;
9458 prng
->sbox
[prng
->j
] = si
;
9459 *destByte
++ = prng
->sbox
[(si
+ sj
) & 0xff];
9463 /* Re-seed the generator with user-provided bytes */
9464 static void JimPrngSeed(Jim_Interp
*interp
, unsigned char *seed
, int seedLen
)
9467 Jim_PrngState
*prng
;
9469 /* initialization, only needed the first time */
9470 if (interp
->prngState
== NULL
)
9471 JimPrngInit(interp
);
9472 prng
= interp
->prngState
;
9474 /* Set the sbox[i] with i */
9475 for (i
= 0; i
< 256; i
++)
9477 /* Now use the seed to perform a random permutation of the sbox */
9478 for (i
= 0; i
< seedLen
; i
++) {
9481 t
= prng
->sbox
[i
& 0xFF];
9482 prng
->sbox
[i
& 0xFF] = prng
->sbox
[seed
[i
]];
9483 prng
->sbox
[seed
[i
]] = t
;
9485 prng
->i
= prng
->j
= 0;
9487 /* discard at least the first 256 bytes of stream.
9488 * borrow the seed buffer for this
9490 for (i
= 0; i
< 256; i
+= seedLen
) {
9491 JimRandomBytes(interp
, seed
, seedLen
);
9496 static int Jim_IncrCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
9498 jim_wide wideValue
, increment
= 1;
9501 if (argc
!= 2 && argc
!= 3) {
9502 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?increment?");
9506 if (Jim_GetWide(interp
, argv
[2], &increment
) != JIM_OK
)
9509 intObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
9511 /* Set missing variable to 0 */
9514 else if (Jim_GetWide(interp
, intObjPtr
, &wideValue
) != JIM_OK
) {
9517 if (!intObjPtr
|| Jim_IsShared(intObjPtr
)) {
9518 intObjPtr
= Jim_NewIntObj(interp
, wideValue
+ increment
);
9519 if (Jim_SetVariable(interp
, argv
[1], intObjPtr
) != JIM_OK
) {
9520 Jim_FreeNewObj(interp
, intObjPtr
);
9525 /* Can do it the quick way */
9526 Jim_InvalidateStringRep(intObjPtr
);
9527 JimWideValue(intObjPtr
) = wideValue
+ increment
;
9529 /* The following step is required in order to invalidate the
9530 * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
9531 if (argv
[1]->typePtr
!= &variableObjType
) {
9532 /* Note that this can't fail since GetVariable already succeeded */
9533 Jim_SetVariable(interp
, argv
[1], intObjPtr
);
9536 Jim_SetResult(interp
, intObjPtr
);
9541 /* -----------------------------------------------------------------------------
9543 * ---------------------------------------------------------------------------*/
9544 #define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
9545 #define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
9547 /* Handle calls to the [unknown] command */
9548 static int JimUnknown(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, Jim_Obj
*fileNameObj
,
9551 Jim_Obj
**v
, *sv
[JIM_EVAL_SARGV_LEN
];
9554 /* If JimUnknown() is recursively called too many times...
9557 if (interp
->unknown_called
> 50) {
9561 /* If the [unknown] command does not exists returns
9563 if (Jim_GetCommand(interp
, interp
->unknown
, JIM_NONE
) == NULL
)
9566 /* The object interp->unknown just contains
9567 * the "unknown" string, it is used in order to
9568 * avoid to lookup the unknown command every time
9569 * but instread to cache the result. */
9570 if (argc
+ 1 <= JIM_EVAL_SARGV_LEN
)
9573 v
= Jim_Alloc(sizeof(Jim_Obj
*) * (argc
+ 1));
9574 /* Make a copy of the arguments vector, but shifted on
9575 * the right of one position. The command name of the
9576 * command will be instead the first argument of the
9577 * [unknown] call. */
9578 memcpy(v
+ 1, argv
, sizeof(Jim_Obj
*) * argc
);
9579 v
[0] = interp
->unknown
;
9581 interp
->unknown_called
++;
9582 retCode
= JimEvalObjVector(interp
, argc
+ 1, v
, fileNameObj
, linenr
);
9583 interp
->unknown_called
--;
9591 /* Eval the object vector 'objv' composed of 'objc' elements.
9592 * Every element is used as single argument.
9593 * Jim_EvalObj() will call this function every time its object
9594 * argument is of "list" type, with no string representation.
9596 * This is possible because the string representation of a
9597 * list object generated by the UpdateStringOfList is made
9598 * in a way that ensures that every list element is a different
9599 * command argument. */
9600 static int JimEvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
,
9601 Jim_Obj
*fileNameObj
, int linenr
)
9606 /* Incr refcount of arguments. */
9607 for (i
= 0; i
< objc
; i
++)
9608 Jim_IncrRefCount(objv
[i
]);
9609 /* Command lookup */
9610 cmdPtr
= Jim_GetCommand(interp
, objv
[0], JIM_ERRMSG
);
9611 if (cmdPtr
== NULL
) {
9612 retcode
= JimUnknown(interp
, objc
, objv
, fileNameObj
, linenr
);
9615 /* Call it -- Make sure result is an empty object. */
9616 JimIncrCmdRefCount(cmdPtr
);
9617 Jim_SetEmptyResult(interp
);
9618 if (cmdPtr
->isproc
) {
9619 retcode
= JimCallProcedure(interp
, cmdPtr
, fileNameObj
, linenr
, objc
, objv
);
9622 interp
->cmdPrivData
= cmdPtr
->u
.native
.privData
;
9623 retcode
= cmdPtr
->u
.native
.cmdProc(interp
, objc
, objv
);
9625 JimDecrCmdRefCount(interp
, cmdPtr
);
9627 /* Decr refcount of arguments and return the retcode */
9628 for (i
= 0; i
< objc
; i
++)
9629 Jim_DecrRefCount(interp
, objv
[i
]);
9634 int Jim_EvalObjVector(Jim_Interp
*interp
, int objc
, Jim_Obj
*const *objv
)
9636 return JimEvalObjVector(interp
, objc
, objv
, interp
->emptyObj
, 1);
9640 * Invokes 'prefix' as a command with the objv array as arguments.
9642 int Jim_EvalObjPrefix(Jim_Interp
*interp
, Jim_Obj
*prefix
, int objc
, Jim_Obj
*const *objv
)
9646 Jim_Obj
**nargv
= Jim_Alloc((objc
+ 1) * sizeof(*nargv
));
9649 for (i
= 0; i
< objc
; i
++) {
9650 nargv
[i
+ 1] = objv
[i
];
9652 ret
= Jim_EvalObjVector(interp
, objc
+ 1, nargv
);
9657 static void JimAddErrorToStack(Jim_Interp
*interp
, int retcode
, Jim_Obj
*fileNameObj
, int line
)
9661 if (rc
== JIM_ERR
&& !interp
->errorFlag
) {
9662 /* This is the first error, so save the file/line information and reset the stack */
9663 interp
->errorFlag
= 1;
9664 Jim_IncrRefCount(fileNameObj
);
9665 Jim_DecrRefCount(interp
, interp
->errorFileNameObj
);
9666 interp
->errorFileNameObj
= fileNameObj
;
9667 interp
->errorLine
= line
;
9669 JimResetStackTrace(interp
);
9670 /* Always add a level where the error first occurs */
9671 interp
->addStackTrace
++;
9674 /* Now if this is an "interesting" level, add it to the stack trace */
9675 if (rc
== JIM_ERR
&& interp
->addStackTrace
> 0) {
9676 /* Add the stack info for the current level */
9678 JimAppendStackTrace(interp
, Jim_String(interp
->errorProc
), fileNameObj
, line
);
9680 /* Note: if we didn't have a filename for this level,
9681 * don't clear the addStackTrace flag
9682 * so we can pick it up at the next level
9684 if (Jim_Length(fileNameObj
)) {
9685 interp
->addStackTrace
= 0;
9688 Jim_DecrRefCount(interp
, interp
->errorProc
);
9689 interp
->errorProc
= interp
->emptyObj
;
9690 Jim_IncrRefCount(interp
->errorProc
);
9692 else if (rc
== JIM_RETURN
&& interp
->returnCode
== JIM_ERR
) {
9693 /* Propagate the addStackTrace value through 'return -code error' */
9696 interp
->addStackTrace
= 0;
9700 /* And delete any local procs */
9701 static void JimDeleteLocalProcs(Jim_Interp
*interp
)
9703 if (interp
->localProcs
) {
9706 while ((procname
= Jim_StackPop(interp
->localProcs
)) != NULL
) {
9707 /* If there is a pushed command, find it */
9708 Jim_Cmd
*prevCmd
= NULL
;
9709 Jim_HashEntry
*he
= Jim_FindHashEntry(&interp
->commands
, procname
);
9711 Jim_Cmd
*cmd
= (Jim_Cmd
*)he
->u
.val
;
9712 if (cmd
->isproc
&& cmd
->u
.proc
.prevCmd
) {
9713 prevCmd
= cmd
->u
.proc
.prevCmd
;
9714 cmd
->u
.proc
.prevCmd
= NULL
;
9718 /* Delete the local proc */
9719 Jim_DeleteCommand(interp
, procname
);
9722 /* And restore the pushed command */
9723 Jim_AddHashEntry(&interp
->commands
, procname
, prevCmd
);
9727 Jim_FreeStack(interp
->localProcs
);
9728 Jim_Free(interp
->localProcs
);
9729 interp
->localProcs
= NULL
;
9733 static int JimSubstOneToken(Jim_Interp
*interp
, const ScriptToken
*token
, Jim_Obj
**objPtrPtr
)
9737 switch (token
->type
) {
9740 objPtr
= token
->objPtr
;
9743 objPtr
= Jim_GetVariable(interp
, token
->objPtr
, JIM_ERRMSG
);
9745 case JIM_TT_DICTSUGAR
:
9746 objPtr
= JimExpandDictSugar(interp
, token
->objPtr
);
9748 case JIM_TT_EXPRSUGAR
:
9749 objPtr
= JimExpandExprSugar(interp
, token
->objPtr
);
9752 switch (Jim_EvalObj(interp
, token
->objPtr
)) {
9755 objPtr
= interp
->result
;
9758 /* Stop substituting */
9761 /* just skip this one */
9762 return JIM_CONTINUE
;
9769 "default token type (%d) reached " "in Jim_SubstObj().", token
->type
));
9774 *objPtrPtr
= objPtr
;
9780 /* Interpolate the given tokens into a unique Jim_Obj returned by reference
9781 * via *objPtrPtr. This function is only called by Jim_EvalObj() and Jim_SubstObj()
9782 * The returned object has refcount = 0.
9784 static Jim_Obj
*JimInterpolateTokens(Jim_Interp
*interp
, const ScriptToken
* token
, int tokens
, int flags
)
9788 Jim_Obj
*sintv
[JIM_EVAL_SINTV_LEN
];
9792 if (tokens
<= JIM_EVAL_SINTV_LEN
)
9795 intv
= Jim_Alloc(sizeof(Jim_Obj
*) * tokens
);
9797 /* Compute every token forming the argument
9798 * in the intv objects vector. */
9799 for (i
= 0; i
< tokens
; i
++) {
9800 switch (JimSubstOneToken(interp
, &token
[i
], &intv
[i
])) {
9805 if (flags
& JIM_SUBST_FLAG
) {
9810 /* XXX: Should probably set an error about break outside loop */
9811 /* fall through to error */
9813 if (flags
& JIM_SUBST_FLAG
) {
9817 /* XXX: Ditto continue outside loop */
9818 /* fall through to error */
9821 Jim_DecrRefCount(interp
, intv
[i
]);
9823 if (intv
!= sintv
) {
9828 Jim_IncrRefCount(intv
[i
]);
9829 Jim_String(intv
[i
]);
9830 totlen
+= intv
[i
]->length
;
9833 /* Fast path return for a single token */
9834 if (tokens
== 1 && intv
[0] && intv
== sintv
) {
9835 Jim_DecrRefCount(interp
, intv
[0]);
9839 /* Concatenate every token in an unique
9841 objPtr
= Jim_NewStringObjNoAlloc(interp
, NULL
, 0);
9843 if (tokens
== 4 && token
[0].type
== JIM_TT_ESC
&& token
[1].type
== JIM_TT_ESC
9844 && token
[2].type
== JIM_TT_VAR
) {
9845 /* May be able to do fast interpolated object -> dictSubst */
9846 objPtr
->typePtr
= &interpolatedObjType
;
9847 objPtr
->internalRep
.twoPtrValue
.ptr1
= (void *)token
;
9848 objPtr
->internalRep
.twoPtrValue
.ptr2
= intv
[2];
9849 Jim_IncrRefCount(intv
[2]);
9852 s
= objPtr
->bytes
= Jim_Alloc(totlen
+ 1);
9853 objPtr
->length
= totlen
;
9854 for (i
= 0; i
< tokens
; i
++) {
9856 memcpy(s
, intv
[i
]->bytes
, intv
[i
]->length
);
9857 s
+= intv
[i
]->length
;
9858 Jim_DecrRefCount(interp
, intv
[i
]);
9861 objPtr
->bytes
[totlen
] = '\0';
9862 /* Free the intv vector if not static. */
9863 if (intv
!= sintv
) {
9871 /* If listPtr is a list, call JimEvalObjVector() with the given source info.
9872 * Otherwise eval with Jim_EvalObj()
9874 static int JimEvalObjList(Jim_Interp
*interp
, Jim_Obj
*listPtr
, Jim_Obj
*fileNameObj
, int linenr
)
9876 if (!Jim_IsList(listPtr
)) {
9877 return Jim_EvalObj(interp
, listPtr
);
9880 int retcode
= JIM_OK
;
9882 if (listPtr
->internalRep
.listValue
.len
) {
9883 Jim_IncrRefCount(listPtr
);
9884 retcode
= JimEvalObjVector(interp
,
9885 listPtr
->internalRep
.listValue
.len
,
9886 listPtr
->internalRep
.listValue
.ele
, fileNameObj
, linenr
);
9887 Jim_DecrRefCount(interp
, listPtr
);
9893 int Jim_EvalObj(Jim_Interp
*interp
, Jim_Obj
*scriptObjPtr
)
9898 int retcode
= JIM_OK
;
9899 Jim_Obj
*sargv
[JIM_EVAL_SARGV_LEN
], **argv
= NULL
;
9902 interp
->errorFlag
= 0;
9904 /* If the object is of type "list", with no string rep we can call
9905 * a specialized version of Jim_EvalObj() */
9906 if (Jim_IsList(scriptObjPtr
) && scriptObjPtr
->bytes
== NULL
) {
9907 return JimEvalObjList(interp
, scriptObjPtr
, interp
->emptyObj
, 1);
9910 Jim_IncrRefCount(scriptObjPtr
); /* Make sure it's shared. */
9911 script
= Jim_GetScript(interp
, scriptObjPtr
);
9913 /* Reset the interpreter result. This is useful to
9914 * return the empty result in the case of empty program. */
9915 Jim_SetEmptyResult(interp
);
9917 #ifdef JIM_OPTIMIZATION
9918 /* Check for one of the following common scripts used by for, while
9923 if (script
->len
== 0) {
9924 Jim_DecrRefCount(interp
, scriptObjPtr
);
9927 if (script
->len
== 3
9928 && script
->token
[1].objPtr
->typePtr
== &commandObjType
9929 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->isproc
== 0
9930 && script
->token
[1].objPtr
->internalRep
.cmdValue
.cmdPtr
->u
.native
.cmdProc
== Jim_IncrCoreCommand
9931 && script
->token
[2].objPtr
->typePtr
== &variableObjType
) {
9933 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, script
->token
[2].objPtr
, JIM_NONE
);
9935 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
9936 JimWideValue(objPtr
)++;
9937 Jim_InvalidateStringRep(objPtr
);
9938 Jim_DecrRefCount(interp
, scriptObjPtr
);
9939 Jim_SetResult(interp
, objPtr
);
9945 /* Now we have to make sure the internal repr will not be
9946 * freed on shimmering.
9948 * Think for example to this:
9950 * set x {llength $x; ... some more code ...}; eval $x
9952 * In order to preserve the internal rep, we increment the
9953 * inUse field of the script internal rep structure. */
9956 token
= script
->token
;
9959 /* Execute every command sequentially until the end of the script
9960 * or an error occurs.
9962 for (i
= 0; i
< script
->len
&& retcode
== JIM_OK
; ) {
9967 /* First token of the line is always JIM_TT_LINE */
9968 argc
= token
[i
].objPtr
->internalRep
.scriptLineValue
.argc
;
9969 linenr
= token
[i
].objPtr
->internalRep
.scriptLineValue
.line
;
9971 /* Allocate the arguments vector if required */
9972 if (argc
> JIM_EVAL_SARGV_LEN
)
9973 argv
= Jim_Alloc(sizeof(Jim_Obj
*) * argc
);
9975 /* Skip the JIM_TT_LINE token */
9978 /* Populate the arguments objects.
9979 * If an error occurs, retcode will be set and
9980 * 'j' will be set to the number of args expanded
9982 for (j
= 0; j
< argc
; j
++) {
9983 long wordtokens
= 1;
9985 Jim_Obj
*wordObjPtr
= NULL
;
9987 if (token
[i
].type
== JIM_TT_WORD
) {
9988 wordtokens
= JimWideValue(token
[i
++].objPtr
);
9989 if (wordtokens
< 0) {
9991 wordtokens
= -wordtokens
;
9995 if (wordtokens
== 1) {
9996 /* Fast path if the token does not
9997 * need interpolation */
9999 switch (token
[i
].type
) {
10002 wordObjPtr
= token
[i
].objPtr
;
10005 wordObjPtr
= Jim_GetVariable(interp
, token
[i
].objPtr
, JIM_ERRMSG
);
10007 case JIM_TT_EXPRSUGAR
:
10008 wordObjPtr
= JimExpandExprSugar(interp
, token
[i
].objPtr
);
10010 case JIM_TT_DICTSUGAR
:
10011 wordObjPtr
= JimExpandDictSugar(interp
, token
[i
].objPtr
);
10014 retcode
= Jim_EvalObj(interp
, token
[i
].objPtr
);
10015 if (retcode
== JIM_OK
) {
10016 wordObjPtr
= Jim_GetResult(interp
);
10020 JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
10024 /* For interpolation we call a helper
10025 * function to do the work for us. */
10026 wordObjPtr
= JimInterpolateTokens(interp
, token
+ i
, wordtokens
, JIM_NONE
);
10030 if (retcode
== JIM_OK
) {
10036 Jim_IncrRefCount(wordObjPtr
);
10040 argv
[j
] = wordObjPtr
;
10043 /* Need to expand wordObjPtr into multiple args from argv[j] ... */
10044 int len
= Jim_ListLength(interp
, wordObjPtr
);
10045 int newargc
= argc
+ len
- 1;
10049 if (argv
== sargv
) {
10050 if (newargc
> JIM_EVAL_SARGV_LEN
) {
10051 argv
= Jim_Alloc(sizeof(*argv
) * newargc
);
10052 memcpy(argv
, sargv
, sizeof(*argv
) * j
);
10056 /* Need to realloc to make room for (len - 1) more entries */
10057 argv
= Jim_Realloc(argv
, sizeof(*argv
) * newargc
);
10061 /* Now copy in the expanded version */
10062 for (k
= 0; k
< len
; k
++) {
10063 argv
[j
++] = wordObjPtr
->internalRep
.listValue
.ele
[k
];
10064 Jim_IncrRefCount(wordObjPtr
->internalRep
.listValue
.ele
[k
]);
10067 /* The original object reference is no longer needed,
10068 * after the expansion it is no longer present on
10069 * the argument vector, but the single elements are
10071 Jim_DecrRefCount(interp
, wordObjPtr
);
10073 /* And update the indexes */
10079 if (retcode
== JIM_OK
&& argc
) {
10080 /* Lookup the command to call */
10081 cmd
= Jim_GetCommand(interp
, argv
[0], JIM_ERRMSG
);
10083 /* Call it -- Make sure result is an empty object. */
10084 JimIncrCmdRefCount(cmd
);
10085 Jim_SetEmptyResult(interp
);
10088 JimCallProcedure(interp
, cmd
, script
->fileNameObj
, linenr
, argc
, argv
);
10090 interp
->cmdPrivData
= cmd
->u
.native
.privData
;
10091 retcode
= cmd
->u
.native
.cmdProc(interp
, argc
, argv
);
10093 JimDecrCmdRefCount(interp
, cmd
);
10096 /* Call [unknown] */
10097 retcode
= JimUnknown(interp
, argc
, argv
, script
->fileNameObj
, linenr
);
10099 if (interp
->signal_level
&& interp
->sigmask
) {
10100 /* Check for a signal after each command */
10101 retcode
= JIM_SIGNAL
;
10105 /* Finished with the command, so decrement ref counts of each argument */
10107 Jim_DecrRefCount(interp
, argv
[j
]);
10110 if (argv
!= sargv
) {
10116 /* Possibly add to the error stack trace */
10117 JimAddErrorToStack(interp
, retcode
, script
->fileNameObj
, linenr
);
10119 /* Note that we don't have to decrement inUse, because the
10120 * following code transfers our use of the reference again to
10121 * the script object. */
10122 Jim_FreeIntRep(interp
, scriptObjPtr
);
10123 scriptObjPtr
->typePtr
= &scriptObjType
;
10124 Jim_SetIntRepPtr(scriptObjPtr
, script
);
10125 Jim_DecrRefCount(interp
, scriptObjPtr
);
10130 static int JimSetProcArg(Jim_Interp
*interp
, Jim_Obj
*argNameObj
, Jim_Obj
*argValObj
)
10133 /* If argObjPtr begins with '&', do an automatic upvar */
10134 const char *varname
= Jim_String(argNameObj
);
10135 if (*varname
== '&') {
10136 /* First check that the target variable exists */
10138 Jim_CallFrame
*savedCallFrame
= interp
->framePtr
;
10140 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10141 objPtr
= Jim_GetVariable(interp
, argValObj
, JIM_ERRMSG
);
10142 interp
->framePtr
= savedCallFrame
;
10147 /* It exists, so perform the binding. */
10148 objPtr
= Jim_NewStringObj(interp
, varname
+ 1, -1);
10149 Jim_IncrRefCount(objPtr
);
10150 retcode
= Jim_SetVariableLink(interp
, objPtr
, argValObj
, interp
->framePtr
->parentCallFrame
);
10151 Jim_DecrRefCount(interp
, objPtr
);
10154 retcode
= Jim_SetVariable(interp
, argNameObj
, argValObj
);
10160 * Sets the interp result to be an error message indicating the required proc args.
10162 static void JimSetProcWrongArgs(Jim_Interp
*interp
, Jim_Obj
*procNameObj
, Jim_Cmd
*cmd
)
10164 /* Create a nice error message, consistent with Tcl 8.5 */
10165 Jim_Obj
*argmsg
= Jim_NewStringObj(interp
, "", 0);
10168 for (i
= 0; i
< cmd
->u
.proc
.argListLen
; i
++) {
10169 Jim_AppendString(interp
, argmsg
, " ", 1);
10171 if (i
== cmd
->u
.proc
.argsPos
) {
10172 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10174 Jim_AppendString(interp
, argmsg
, "?", 1);
10175 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].defaultObjPtr
);
10176 Jim_AppendString(interp
, argmsg
, " ...?", -1);
10179 /* We have plain args */
10180 Jim_AppendString(interp
, argmsg
, "?argument ...?", -1);
10184 if (cmd
->u
.proc
.arglist
[i
].defaultObjPtr
) {
10185 Jim_AppendString(interp
, argmsg
, "?", 1);
10186 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10187 Jim_AppendString(interp
, argmsg
, "?", 1);
10190 Jim_AppendObj(interp
, argmsg
, cmd
->u
.proc
.arglist
[i
].nameObjPtr
);
10194 Jim_SetResultFormatted(interp
, "wrong # args: should be \"%#s%#s\"", procNameObj
, argmsg
);
10195 Jim_FreeNewObj(interp
, argmsg
);
10198 /* Call a procedure implemented in Tcl.
10199 * It's possible to speed-up a lot this function, currently
10200 * the callframes are not cached, but allocated and
10201 * destroied every time. What is expecially costly is
10202 * to create/destroy the local vars hash table every time.
10204 * This can be fixed just implementing callframes caching
10205 * in JimCreateCallFrame() and JimFreeCallFrame(). */
10206 static int JimCallProcedure(Jim_Interp
*interp
, Jim_Cmd
*cmd
, Jim_Obj
*fileNameObj
, int linenr
, int argc
,
10207 Jim_Obj
*const *argv
)
10209 Jim_CallFrame
*callFramePtr
;
10210 Jim_Stack
*prevLocalProcs
;
10211 int i
, d
, retcode
, optargs
;
10214 if (argc
- 1 < cmd
->u
.proc
.reqArity
||
10215 (cmd
->u
.proc
.argsPos
< 0 && argc
- 1 > cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
)) {
10216 JimSetProcWrongArgs(interp
, argv
[0], cmd
);
10220 /* Check if there are too nested calls */
10221 if (interp
->framePtr
->level
== interp
->maxNestingDepth
) {
10222 Jim_SetResultString(interp
, "Too many nested calls. Infinite recursion?", -1);
10226 /* Create a new callframe */
10227 callFramePtr
= JimCreateCallFrame(interp
, interp
->framePtr
);
10228 callFramePtr
->argv
= argv
;
10229 callFramePtr
->argc
= argc
;
10230 callFramePtr
->procArgsObjPtr
= cmd
->u
.proc
.argListObjPtr
;
10231 callFramePtr
->procBodyObjPtr
= cmd
->u
.proc
.bodyObjPtr
;
10232 callFramePtr
->staticVars
= cmd
->u
.proc
.staticVars
;
10233 callFramePtr
->fileNameObj
= fileNameObj
;
10234 callFramePtr
->line
= linenr
;
10235 Jim_IncrRefCount(cmd
->u
.proc
.argListObjPtr
);
10236 Jim_IncrRefCount(cmd
->u
.proc
.bodyObjPtr
);
10237 interp
->framePtr
= callFramePtr
;
10239 /* How many optional args are available */
10240 optargs
= (argc
- 1 - cmd
->u
.proc
.reqArity
);
10242 /* Step 'i' along the actual args, and step 'd' along the formal args */
10244 for (d
= 0; d
< cmd
->u
.proc
.argListLen
; d
++) {
10245 Jim_Obj
*nameObjPtr
= cmd
->u
.proc
.arglist
[d
].nameObjPtr
;
10246 if (d
== cmd
->u
.proc
.argsPos
) {
10248 Jim_Obj
*listObjPtr
;
10250 if (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
< argc
- 1) {
10251 argsLen
= argc
- 1 - (cmd
->u
.proc
.reqArity
+ cmd
->u
.proc
.optArity
);
10253 listObjPtr
= Jim_NewListObj(interp
, &argv
[i
], argsLen
);
10255 /* It is possible to rename args. */
10256 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
) {
10257 nameObjPtr
=cmd
->u
.proc
.arglist
[d
].defaultObjPtr
;
10259 retcode
= Jim_SetVariable(interp
, nameObjPtr
, listObjPtr
);
10260 if (retcode
!= JIM_OK
) {
10268 /* Optional or required? */
10269 if (cmd
->u
.proc
.arglist
[d
].defaultObjPtr
== NULL
|| optargs
-- > 0) {
10270 retcode
= JimSetProcArg(interp
, nameObjPtr
, argv
[i
++]);
10273 /* Ran out, so use the default */
10274 retcode
= Jim_SetVariable(interp
, nameObjPtr
, cmd
->u
.proc
.arglist
[d
].defaultObjPtr
);
10276 if (retcode
!= JIM_OK
) {
10281 /* Install a new stack for local procs */
10282 prevLocalProcs
= interp
->localProcs
;
10283 interp
->localProcs
= NULL
;
10285 /* Eval the body */
10286 retcode
= Jim_EvalObj(interp
, cmd
->u
.proc
.bodyObjPtr
);
10288 /* Delete any local procs */
10289 JimDeleteLocalProcs(interp
);
10290 interp
->localProcs
= prevLocalProcs
;
10293 /* Destroy the callframe */
10294 interp
->framePtr
= interp
->framePtr
->parentCallFrame
;
10295 if (callFramePtr
->vars
.size
!= JIM_HT_INITIAL_SIZE
) {
10296 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NONE
);
10299 JimFreeCallFrame(interp
, callFramePtr
, JIM_FCF_NOHT
);
10301 /* Handle the JIM_EVAL return code */
10302 while (retcode
== JIM_EVAL
) {
10303 Jim_Obj
*resultScriptObjPtr
= Jim_GetResult(interp
);
10305 Jim_IncrRefCount(resultScriptObjPtr
);
10306 /* Should be a list! */
10307 retcode
= JimEvalObjList(interp
, resultScriptObjPtr
, fileNameObj
, linenr
);
10308 Jim_DecrRefCount(interp
, resultScriptObjPtr
);
10310 /* Handle the JIM_RETURN return code */
10311 if (retcode
== JIM_RETURN
) {
10312 if (--interp
->returnLevel
<= 0) {
10313 retcode
= interp
->returnCode
;
10314 interp
->returnCode
= JIM_OK
;
10315 interp
->returnLevel
= 0;
10318 else if (retcode
== JIM_ERR
) {
10319 interp
->addStackTrace
++;
10320 Jim_DecrRefCount(interp
, interp
->errorProc
);
10321 interp
->errorProc
= argv
[0];
10322 Jim_IncrRefCount(interp
->errorProc
);
10327 int Jim_EvalSource(Jim_Interp
*interp
, const char *filename
, int lineno
, const char *script
)
10330 Jim_Obj
*scriptObjPtr
;
10332 scriptObjPtr
= Jim_NewStringObj(interp
, script
, -1);
10333 Jim_IncrRefCount(scriptObjPtr
);
10336 Jim_Obj
*prevScriptObj
;
10338 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), lineno
);
10340 prevScriptObj
= interp
->currentScriptObj
;
10341 interp
->currentScriptObj
= scriptObjPtr
;
10343 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10345 interp
->currentScriptObj
= prevScriptObj
;
10348 retval
= Jim_EvalObj(interp
, scriptObjPtr
);
10350 Jim_DecrRefCount(interp
, scriptObjPtr
);
10354 int Jim_Eval(Jim_Interp
*interp
, const char *script
)
10356 return Jim_EvalObj(interp
, Jim_NewStringObj(interp
, script
, -1));
10359 /* Execute script in the scope of the global level */
10360 int Jim_EvalGlobal(Jim_Interp
*interp
, const char *script
)
10363 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10365 interp
->framePtr
= interp
->topFramePtr
;
10366 retval
= Jim_Eval(interp
, script
);
10367 interp
->framePtr
= savedFramePtr
;
10372 int Jim_EvalFileGlobal(Jim_Interp
*interp
, const char *filename
)
10375 Jim_CallFrame
*savedFramePtr
= interp
->framePtr
;
10377 interp
->framePtr
= interp
->topFramePtr
;
10378 retval
= Jim_EvalFile(interp
, filename
);
10379 interp
->framePtr
= savedFramePtr
;
10384 #include <sys/stat.h>
10386 int Jim_EvalFile(Jim_Interp
*interp
, const char *filename
)
10390 Jim_Obj
*scriptObjPtr
;
10391 Jim_Obj
*prevScriptObj
;
10395 struct JimParseResult result
;
10397 if (stat(filename
, &sb
) != 0 || (fp
= fopen(filename
, "rt")) == NULL
) {
10398 Jim_SetResultFormatted(interp
, "couldn't read file \"%s\": %s", filename
, strerror(errno
));
10401 if (sb
.st_size
== 0) {
10406 buf
= Jim_Alloc(sb
.st_size
+ 1);
10407 readlen
= fread(buf
, 1, sb
.st_size
, fp
);
10411 Jim_SetResultFormatted(interp
, "failed to load file \"%s\": %s", filename
, strerror(errno
));
10417 scriptObjPtr
= Jim_NewStringObjNoAlloc(interp
, buf
, readlen
);
10418 JimSetSourceInfo(interp
, scriptObjPtr
, Jim_NewStringObj(interp
, filename
, -1), 1);
10419 Jim_IncrRefCount(scriptObjPtr
);
10421 /* Now check the script for unmatched braces, etc. */
10422 if (SetScriptFromAny(interp
, scriptObjPtr
, &result
) == JIM_ERR
) {
10426 switch (result
.missing
) {
10428 msg
= "unmatched \"[\"";
10431 msg
= "missing close-brace";
10435 msg
= "missing quote";
10439 snprintf(linebuf
, sizeof(linebuf
), "%d", result
.line
);
10441 Jim_SetResultFormatted(interp
, "%s in \"%s\" at line %s",
10442 msg
, filename
, linebuf
);
10443 Jim_DecrRefCount(interp
, scriptObjPtr
);
10447 prevScriptObj
= interp
->currentScriptObj
;
10448 interp
->currentScriptObj
= scriptObjPtr
;
10450 retcode
= Jim_EvalObj(interp
, scriptObjPtr
);
10452 /* Handle the JIM_RETURN return code */
10453 if (retcode
== JIM_RETURN
) {
10454 if (--interp
->returnLevel
<= 0) {
10455 retcode
= interp
->returnCode
;
10456 interp
->returnCode
= JIM_OK
;
10457 interp
->returnLevel
= 0;
10460 if (retcode
== JIM_ERR
) {
10461 /* EvalFile changes context, so add a stack frame here */
10462 interp
->addStackTrace
++;
10465 interp
->currentScriptObj
= prevScriptObj
;
10467 Jim_DecrRefCount(interp
, scriptObjPtr
);
10472 /* -----------------------------------------------------------------------------
10474 * ---------------------------------------------------------------------------*/
10475 static int JimParseSubstStr(struct JimParserCtx
*pc
)
10477 pc
->tstart
= pc
->p
;
10478 pc
->tline
= pc
->linenr
;
10479 while (pc
->len
&& *pc
->p
!= '$' && *pc
->p
!= '[') {
10480 if (*pc
->p
== '\\' && pc
->len
> 1) {
10487 pc
->tend
= pc
->p
- 1;
10488 pc
->tt
= JIM_TT_ESC
;
10492 static int JimParseSubst(struct JimParserCtx
*pc
, int flags
)
10496 if (pc
->len
== 0) {
10497 pc
->tstart
= pc
->tend
= pc
->p
;
10498 pc
->tline
= pc
->linenr
;
10499 pc
->tt
= JIM_TT_EOL
;
10505 retval
= JimParseCmd(pc
);
10506 if (flags
& JIM_SUBST_NOCMD
) {
10509 pc
->tt
= (flags
& JIM_SUBST_NOESC
) ? JIM_TT_STR
: JIM_TT_ESC
;
10514 if (JimParseVar(pc
) == JIM_ERR
) {
10515 pc
->tstart
= pc
->tend
= pc
->p
++;
10517 pc
->tline
= pc
->linenr
;
10518 pc
->tt
= JIM_TT_STR
;
10521 if (flags
& JIM_SUBST_NOVAR
) {
10523 if (flags
& JIM_SUBST_NOESC
)
10524 pc
->tt
= JIM_TT_STR
;
10526 pc
->tt
= JIM_TT_ESC
;
10527 if (*pc
->tstart
== '{') {
10529 if (*(pc
->tend
+ 1))
10536 retval
= JimParseSubstStr(pc
);
10537 if (flags
& JIM_SUBST_NOESC
)
10538 pc
->tt
= JIM_TT_STR
;
10545 /* The subst object type reuses most of the data structures and functions
10546 * of the script object. Script's data structures are a bit more complex
10547 * for what is needed for [subst]itution tasks, but the reuse helps to
10548 * deal with a single data structure at the cost of some more memory
10549 * usage for substitutions. */
10551 /* This method takes the string representation of an object
10552 * as a Tcl string where to perform [subst]itution, and generates
10553 * the pre-parsed internal representation. */
10554 static int SetSubstFromAny(Jim_Interp
*interp
, struct Jim_Obj
*objPtr
, int flags
)
10557 const char *scriptText
= Jim_GetString(objPtr
, &scriptTextLen
);
10558 struct JimParserCtx parser
;
10559 struct ScriptObj
*script
= Jim_Alloc(sizeof(*script
));
10560 ParseTokenList tokenlist
;
10562 /* Initially parse the subst into tokens (in tokenlist) */
10563 ScriptTokenListInit(&tokenlist
);
10565 JimParserInit(&parser
, scriptText
, scriptTextLen
, 1);
10567 JimParseSubst(&parser
, flags
);
10569 /* Note that subst doesn't need the EOL token */
10572 ScriptAddToken(&tokenlist
, parser
.tstart
, parser
.tend
- parser
.tstart
+ 1, parser
.tt
,
10576 /* Create the "real" subst/script tokens from the initial token list */
10578 script
->substFlags
= flags
;
10579 script
->fileNameObj
= interp
->emptyObj
;
10580 Jim_IncrRefCount(script
->fileNameObj
);
10581 SubstObjAddTokens(interp
, script
, &tokenlist
);
10583 /* No longer need the token list */
10584 ScriptTokenListFree(&tokenlist
);
10586 #ifdef DEBUG_SHOW_SUBST
10590 printf("==== Subst ====\n");
10591 for (i
= 0; i
< script
->len
; i
++) {
10592 printf("[%2d] %s '%s'\n", i
, jim_tt_name(script
->token
[i
].type
),
10593 Jim_String(script
->token
[i
].objPtr
));
10598 /* Free the old internal rep and set the new one. */
10599 Jim_FreeIntRep(interp
, objPtr
);
10600 Jim_SetIntRepPtr(objPtr
, script
);
10601 objPtr
->typePtr
= &scriptObjType
;
10605 static ScriptObj
*Jim_GetSubst(Jim_Interp
*interp
, Jim_Obj
*objPtr
, int flags
)
10607 if (objPtr
->typePtr
!= &scriptObjType
|| ((ScriptObj
*)Jim_GetIntRepPtr(objPtr
))->substFlags
!= flags
)
10608 SetSubstFromAny(interp
, objPtr
, flags
);
10609 return (ScriptObj
*) Jim_GetIntRepPtr(objPtr
);
10612 /* Performs commands,variables,blackslashes substitution,
10613 * storing the result object (with refcount 0) into
10615 int Jim_SubstObj(Jim_Interp
*interp
, Jim_Obj
*substObjPtr
, Jim_Obj
**resObjPtrPtr
, int flags
)
10617 ScriptObj
*script
= Jim_GetSubst(interp
, substObjPtr
, flags
);
10619 Jim_IncrRefCount(substObjPtr
); /* Make sure it's shared. */
10620 /* In order to preserve the internal rep, we increment the
10621 * inUse field of the script internal rep structure. */
10624 *resObjPtrPtr
= JimInterpolateTokens(interp
, script
->token
, script
->len
, flags
);
10627 Jim_DecrRefCount(interp
, substObjPtr
);
10628 if (*resObjPtrPtr
== NULL
) {
10634 /* -----------------------------------------------------------------------------
10635 * Core commands utility functions
10636 * ---------------------------------------------------------------------------*/
10637 void Jim_WrongNumArgs(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, const char *msg
)
10640 Jim_Obj
*objPtr
= Jim_NewEmptyStringObj(interp
);
10642 Jim_AppendString(interp
, objPtr
, "wrong # args: should be \"", -1);
10643 for (i
= 0; i
< argc
; i
++) {
10644 Jim_AppendObj(interp
, objPtr
, argv
[i
]);
10645 if (!(i
+ 1 == argc
&& msg
[0] == '\0'))
10646 Jim_AppendString(interp
, objPtr
, " ", 1);
10648 Jim_AppendString(interp
, objPtr
, msg
, -1);
10649 Jim_AppendString(interp
, objPtr
, "\"", 1);
10650 Jim_SetResult(interp
, objPtr
);
10653 #define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
10655 /* type is: 0=commands, 1=procs, 2=channels */
10656 static Jim_Obj
*JimCommandsList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int type
)
10658 Jim_HashTableIterator
*htiter
;
10660 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10662 /* Check for the non-pattern case. We can do this much more efficiently. */
10663 if (patternObjPtr
&& JimTrivialMatch(Jim_String(patternObjPtr
))) {
10664 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, patternObjPtr
, JIM_NONE
);
10666 if (type
== 1 && !cmdPtr
->isproc
) {
10669 else if (type
== 2 && !Jim_AioFilehandle(interp
, patternObjPtr
)) {
10670 /* not a channel */
10673 Jim_ListAppendElement(interp
, listObjPtr
, patternObjPtr
);
10679 htiter
= Jim_GetHashTableIterator(&interp
->commands
);
10680 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10681 Jim_Cmd
*cmdPtr
= he
->u
.val
;
10682 Jim_Obj
*cmdNameObj
;
10684 if (type
== 1 && !cmdPtr
->isproc
) {
10688 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10691 cmdNameObj
= Jim_NewStringObj(interp
, he
->key
, -1);
10693 /* Is it a channel? */
10694 if (type
== 2 && !Jim_AioFilehandle(interp
, cmdNameObj
)) {
10695 Jim_FreeNewObj(interp
, cmdNameObj
);
10699 Jim_ListAppendElement(interp
, listObjPtr
, cmdNameObj
);
10701 Jim_FreeHashTableIterator(htiter
);
10705 /* Keep this in order */
10706 #define JIM_VARLIST_GLOBALS 0
10707 #define JIM_VARLIST_LOCALS 1
10708 #define JIM_VARLIST_VARS 2
10710 static Jim_Obj
*JimVariablesList(Jim_Interp
*interp
, Jim_Obj
*patternObjPtr
, int mode
)
10712 Jim_HashTableIterator
*htiter
;
10714 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
10716 if (mode
== JIM_VARLIST_GLOBALS
) {
10717 htiter
= Jim_GetHashTableIterator(&interp
->topFramePtr
->vars
);
10720 /* For [info locals], if we are at top level an emtpy list
10721 * is returned. I don't agree, but we aim at compatibility (SS) */
10722 if (mode
== JIM_VARLIST_LOCALS
&& interp
->framePtr
== interp
->topFramePtr
)
10724 htiter
= Jim_GetHashTableIterator(&interp
->framePtr
->vars
);
10726 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
10727 Jim_Var
*varPtr
= (Jim_Var
*)he
->u
.val
;
10729 if (mode
== JIM_VARLIST_LOCALS
) {
10730 if (varPtr
->linkFramePtr
!= NULL
)
10733 if (patternObjPtr
&& !JimStringMatch(interp
, patternObjPtr
, he
->key
, 0))
10735 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, he
->key
, -1));
10737 Jim_FreeHashTableIterator(htiter
);
10741 static int JimInfoLevel(Jim_Interp
*interp
, Jim_Obj
*levelObjPtr
,
10742 Jim_Obj
**objPtrPtr
, int info_level_cmd
)
10744 Jim_CallFrame
*targetCallFrame
;
10746 targetCallFrame
= JimGetCallFrameByInteger(interp
, levelObjPtr
);
10747 if (targetCallFrame
== NULL
) {
10750 /* No proc call at toplevel callframe */
10751 if (targetCallFrame
== interp
->topFramePtr
) {
10752 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", levelObjPtr
);
10755 if (info_level_cmd
) {
10756 *objPtrPtr
= Jim_NewListObj(interp
, targetCallFrame
->argv
, targetCallFrame
->argc
);
10759 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
10761 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->argv
[0]);
10762 Jim_ListAppendElement(interp
, listObj
, targetCallFrame
->fileNameObj
);
10763 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, targetCallFrame
->line
));
10764 *objPtrPtr
= listObj
;
10769 /* -----------------------------------------------------------------------------
10771 * ---------------------------------------------------------------------------*/
10773 /* fake [puts] -- not the real puts, just for debugging. */
10774 static int Jim_PutsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10776 if (argc
!= 2 && argc
!= 3) {
10777 Jim_WrongNumArgs(interp
, 1, argv
, "?-nonewline? string");
10781 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-nonewline")) {
10782 Jim_SetResultString(interp
, "The second argument must " "be -nonewline", -1);
10786 fputs(Jim_String(argv
[2]), stdout
);
10790 puts(Jim_String(argv
[1]));
10795 /* Helper for [+] and [*] */
10796 static int JimAddMulHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10798 jim_wide wideValue
, res
;
10799 double doubleValue
, doubleRes
;
10802 res
= (op
== JIM_EXPROP_ADD
) ? 0 : 1;
10804 for (i
= 1; i
< argc
; i
++) {
10805 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
)
10807 if (op
== JIM_EXPROP_ADD
)
10812 Jim_SetResultInt(interp
, res
);
10815 doubleRes
= (double)res
;
10816 for (; i
< argc
; i
++) {
10817 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10819 if (op
== JIM_EXPROP_ADD
)
10820 doubleRes
+= doubleValue
;
10822 doubleRes
*= doubleValue
;
10824 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10828 /* Helper for [-] and [/] */
10829 static int JimSubDivHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int op
)
10831 jim_wide wideValue
, res
= 0;
10832 double doubleValue
, doubleRes
= 0;
10836 Jim_WrongNumArgs(interp
, 1, argv
, "number ?number ... number?");
10839 else if (argc
== 2) {
10840 /* The arity = 2 case is different. For [- x] returns -x,
10841 * while [/ x] returns 1/x. */
10842 if (Jim_GetWide(interp
, argv
[1], &wideValue
) != JIM_OK
) {
10843 if (Jim_GetDouble(interp
, argv
[1], &doubleValue
) != JIM_OK
) {
10847 if (op
== JIM_EXPROP_SUB
)
10848 doubleRes
= -doubleValue
;
10850 doubleRes
= 1.0 / doubleValue
;
10851 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10855 if (op
== JIM_EXPROP_SUB
) {
10857 Jim_SetResultInt(interp
, res
);
10860 doubleRes
= 1.0 / wideValue
;
10861 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10866 if (Jim_GetWide(interp
, argv
[1], &res
) != JIM_OK
) {
10867 if (Jim_GetDouble(interp
, argv
[1], &doubleRes
)
10876 for (i
= 2; i
< argc
; i
++) {
10877 if (Jim_GetWide(interp
, argv
[i
], &wideValue
) != JIM_OK
) {
10878 doubleRes
= (double)res
;
10881 if (op
== JIM_EXPROP_SUB
)
10886 Jim_SetResultInt(interp
, res
);
10889 for (; i
< argc
; i
++) {
10890 if (Jim_GetDouble(interp
, argv
[i
], &doubleValue
) != JIM_OK
)
10892 if (op
== JIM_EXPROP_SUB
)
10893 doubleRes
-= doubleValue
;
10895 doubleRes
/= doubleValue
;
10897 Jim_SetResult(interp
, Jim_NewDoubleObj(interp
, doubleRes
));
10903 static int Jim_AddCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10905 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_ADD
);
10909 static int Jim_MulCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10911 return JimAddMulHelper(interp
, argc
, argv
, JIM_EXPROP_MUL
);
10915 static int Jim_SubCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10917 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_SUB
);
10921 static int Jim_DivCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10923 return JimSubDivHelper(interp
, argc
, argv
, JIM_EXPROP_DIV
);
10927 static int Jim_SetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10929 if (argc
!= 2 && argc
!= 3) {
10930 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?newValue?");
10936 objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
10939 Jim_SetResult(interp
, objPtr
);
10942 /* argc == 3 case. */
10943 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
10945 Jim_SetResult(interp
, argv
[2]);
10951 * unset ?-nocomplain? ?--? ?varName ...?
10953 static int Jim_UnsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10959 if (Jim_CompareStringImmediate(interp
, argv
[i
], "--")) {
10963 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-nocomplain")) {
10972 if (Jim_UnsetVariable(interp
, argv
[i
], complain
? JIM_ERRMSG
: JIM_NONE
) != JIM_OK
10982 static int Jim_WhileCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
10985 Jim_WrongNumArgs(interp
, 1, argv
, "condition body");
10989 /* The general purpose implementation of while starts here */
10991 int boolean
, retval
;
10993 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[1], &boolean
)) != JIM_OK
)
10998 if ((retval
= Jim_EvalObj(interp
, argv
[2])) != JIM_OK
) {
11012 Jim_SetEmptyResult(interp
);
11017 static int Jim_ForCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11021 Jim_Obj
*varNamePtr
= NULL
;
11022 Jim_Obj
*stopVarNamePtr
= NULL
;
11025 Jim_WrongNumArgs(interp
, 1, argv
, "start test next body");
11029 /* Do the initialisation */
11030 if ((retval
= Jim_EvalObj(interp
, argv
[1])) != JIM_OK
) {
11034 /* And do the first test now. Better for optimisation
11035 * if we can do next/test at the bottom of the loop
11037 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11039 /* Ready to do the body as follows:
11041 * body // check retcode
11042 * next // check retcode
11043 * test // check retcode/test bool
11047 #ifdef JIM_OPTIMIZATION
11048 /* Check if the for is on the form:
11049 * for ... {$i < CONST} {incr i}
11050 * for ... {$i < $j} {incr i}
11052 if (retval
== JIM_OK
&& boolean
) {
11053 ScriptObj
*incrScript
;
11054 ExprByteCode
*expr
;
11055 jim_wide stop
, currentVal
;
11056 unsigned jim_wide procEpoch
;
11060 /* Do it only if there aren't shared arguments */
11061 expr
= JimGetExpression(interp
, argv
[2]);
11062 incrScript
= Jim_GetScript(interp
, argv
[3]);
11064 /* Ensure proper lengths to start */
11065 if (incrScript
->len
!= 3 || !expr
|| expr
->len
!= 3) {
11068 /* Ensure proper token types. */
11069 if (incrScript
->token
[1].type
!= JIM_TT_ESC
||
11070 expr
->token
[0].type
!= JIM_TT_VAR
||
11071 (expr
->token
[1].type
!= JIM_TT_EXPR_INT
&& expr
->token
[1].type
!= JIM_TT_VAR
)) {
11075 if (expr
->token
[2].type
== JIM_EXPROP_LT
) {
11078 else if (expr
->token
[2].type
== JIM_EXPROP_LTE
) {
11085 /* Update command must be incr */
11086 if (!Jim_CompareStringImmediate(interp
, incrScript
->token
[1].objPtr
, "incr")) {
11090 /* incr, expression must be about the same variable */
11091 if (!Jim_StringEqObj(incrScript
->token
[2].objPtr
, expr
->token
[0].objPtr
)) {
11095 /* Get the stop condition (must be a variable or integer) */
11096 if (expr
->token
[1].type
== JIM_TT_EXPR_INT
) {
11097 if (Jim_GetWide(interp
, expr
->token
[1].objPtr
, &stop
) == JIM_ERR
) {
11102 stopVarNamePtr
= expr
->token
[1].objPtr
;
11103 Jim_IncrRefCount(stopVarNamePtr
);
11104 /* Keep the compiler happy */
11108 /* Initialization */
11109 procEpoch
= interp
->procEpoch
;
11110 varNamePtr
= expr
->token
[0].objPtr
;
11111 Jim_IncrRefCount(varNamePtr
);
11113 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_NONE
);
11114 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
) {
11118 /* --- OPTIMIZED FOR --- */
11119 while (retval
== JIM_OK
) {
11120 /* === Check condition === */
11121 /* Note that currentVal is already set here */
11123 /* Immediate or Variable? get the 'stop' value if the latter. */
11124 if (stopVarNamePtr
) {
11125 objPtr
= Jim_GetVariable(interp
, stopVarNamePtr
, JIM_NONE
);
11126 if (objPtr
== NULL
|| Jim_GetWide(interp
, objPtr
, &stop
) != JIM_OK
) {
11131 if (currentVal
>= stop
+ cmpOffset
) {
11136 retval
= Jim_EvalObj(interp
, argv
[4]);
11137 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11139 /* If there was a change in procedures/command continue
11140 * with the usual [for] command implementation */
11141 if (procEpoch
!= interp
->procEpoch
) {
11145 objPtr
= Jim_GetVariable(interp
, varNamePtr
, JIM_ERRMSG
);
11148 if (objPtr
== NULL
) {
11152 if (!Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11153 currentVal
= ++JimWideValue(objPtr
);
11154 Jim_InvalidateStringRep(objPtr
);
11157 if (Jim_GetWide(interp
, objPtr
, ¤tVal
) != JIM_OK
||
11158 Jim_SetVariable(interp
, varNamePtr
, Jim_NewIntObj(interp
,
11159 ++currentVal
)) != JIM_OK
) {
11170 while (boolean
&& (retval
== JIM_OK
|| retval
== JIM_CONTINUE
)) {
11172 retval
= Jim_EvalObj(interp
, argv
[4]);
11174 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11177 retval
= Jim_EvalObj(interp
, argv
[3]);
11178 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11181 retval
= Jim_GetBoolFromExpr(interp
, argv
[2], &boolean
);
11186 if (stopVarNamePtr
) {
11187 Jim_DecrRefCount(interp
, stopVarNamePtr
);
11190 Jim_DecrRefCount(interp
, varNamePtr
);
11193 if (retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
|| retval
== JIM_OK
) {
11194 Jim_SetEmptyResult(interp
);
11202 static int Jim_LoopCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11208 Jim_Obj
*bodyObjPtr
;
11210 if (argc
!= 5 && argc
!= 6) {
11211 Jim_WrongNumArgs(interp
, 1, argv
, "var first limit ?incr? body");
11215 if (Jim_GetWide(interp
, argv
[2], &i
) != JIM_OK
||
11216 Jim_GetWide(interp
, argv
[3], &limit
) != JIM_OK
||
11217 (argc
== 6 && Jim_GetWide(interp
, argv
[4], &incr
) != JIM_OK
)) {
11220 bodyObjPtr
= (argc
== 5) ? argv
[4] : argv
[5];
11222 retval
= Jim_SetVariable(interp
, argv
[1], argv
[2]);
11224 while (((i
< limit
&& incr
> 0) || (i
> limit
&& incr
< 0)) && retval
== JIM_OK
) {
11225 retval
= Jim_EvalObj(interp
, bodyObjPtr
);
11226 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
) {
11227 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
11234 if (objPtr
&& !Jim_IsShared(objPtr
) && objPtr
->typePtr
== &intObjType
) {
11235 if (argv
[1]->typePtr
!= &variableObjType
) {
11236 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11240 JimWideValue(objPtr
) = i
;
11241 Jim_InvalidateStringRep(objPtr
);
11243 /* The following step is required in order to invalidate the
11244 * string repr of "FOO" if the var name is of the form of "FOO(IDX)" */
11245 if (argv
[1]->typePtr
!= &variableObjType
) {
11246 if (Jim_SetVariable(interp
, argv
[1], objPtr
) != JIM_OK
) {
11253 objPtr
= Jim_NewIntObj(interp
, i
);
11254 retval
= Jim_SetVariable(interp
, argv
[1], objPtr
);
11255 if (retval
!= JIM_OK
) {
11256 Jim_FreeNewObj(interp
, objPtr
);
11262 if (retval
== JIM_OK
|| retval
== JIM_CONTINUE
|| retval
== JIM_BREAK
) {
11263 Jim_SetEmptyResult(interp
);
11269 /* foreach + lmap implementation. */
11270 static int JimForeachMapHelper(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
, int doMap
)
11272 int result
= JIM_ERR
, i
, nbrOfLists
, *listsIdx
, *listsEnd
;
11273 int nbrOfLoops
= 0;
11274 Jim_Obj
*emptyStr
, *script
, *mapRes
= NULL
;
11276 if (argc
< 4 || argc
% 2 != 0) {
11277 Jim_WrongNumArgs(interp
, 1, argv
, "varList list ?varList list ...? script");
11281 mapRes
= Jim_NewListObj(interp
, NULL
, 0);
11282 Jim_IncrRefCount(mapRes
);
11284 emptyStr
= Jim_NewEmptyStringObj(interp
);
11285 Jim_IncrRefCount(emptyStr
);
11286 script
= argv
[argc
- 1]; /* Last argument is a script */
11287 nbrOfLists
= (argc
- 1 - 1) / 2; /* argc - 'foreach' - script */
11288 listsIdx
= (int *)Jim_Alloc(nbrOfLists
* sizeof(int));
11289 listsEnd
= (int *)Jim_Alloc(nbrOfLists
* 2 * sizeof(int));
11290 /* Initialize iterators and remember max nbr elements each list */
11291 memset(listsIdx
, 0, nbrOfLists
* sizeof(int));
11292 /* Remember lengths of all lists and calculate how much rounds to loop */
11293 for (i
= 0; i
< nbrOfLists
* 2; i
+= 2) {
11297 listsEnd
[i
] = Jim_ListLength(interp
, argv
[i
+ 1]);
11298 listsEnd
[i
+ 1] = Jim_ListLength(interp
, argv
[i
+ 2]);
11299 if (listsEnd
[i
] == 0) {
11300 Jim_SetResultString(interp
, "foreach varlist is empty", -1);
11303 cnt
= div(listsEnd
[i
+ 1], listsEnd
[i
]);
11304 count
= cnt
.quot
+ (cnt
.rem
? 1 : 0);
11305 if (count
> nbrOfLoops
)
11306 nbrOfLoops
= count
;
11308 for (; nbrOfLoops
-- > 0;) {
11309 for (i
= 0; i
< nbrOfLists
; ++i
) {
11310 int varIdx
= 0, var
= i
* 2;
11312 while (varIdx
< listsEnd
[var
]) {
11313 Jim_Obj
*varName
, *ele
;
11314 int lst
= i
* 2 + 1;
11316 /* List index operations below can't fail */
11317 Jim_ListIndex(interp
, argv
[var
+ 1], varIdx
, &varName
, JIM_NONE
);
11318 if (listsIdx
[i
] < listsEnd
[lst
]) {
11319 Jim_ListIndex(interp
, argv
[lst
+ 1], listsIdx
[i
], &ele
, JIM_NONE
);
11320 /* Avoid shimmering */
11321 Jim_IncrRefCount(ele
);
11322 result
= Jim_SetVariable(interp
, varName
, ele
);
11323 Jim_DecrRefCount(interp
, ele
);
11324 if (result
== JIM_OK
) {
11325 ++listsIdx
[i
]; /* Remember next iterator of current list */
11326 ++varIdx
; /* Next variable */
11330 else if (Jim_SetVariable(interp
, varName
, emptyStr
) == JIM_OK
) {
11331 ++varIdx
; /* Next variable */
11337 switch (result
= Jim_EvalObj(interp
, script
)) {
11340 Jim_ListAppendElement(interp
, mapRes
, interp
->result
);
11354 Jim_SetResult(interp
, mapRes
);
11356 Jim_SetEmptyResult(interp
);
11359 Jim_DecrRefCount(interp
, mapRes
);
11360 Jim_DecrRefCount(interp
, emptyStr
);
11361 Jim_Free(listsIdx
);
11362 Jim_Free(listsEnd
);
11367 static int Jim_ForeachCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11369 return JimForeachMapHelper(interp
, argc
, argv
, 0);
11373 static int Jim_LmapCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11375 return JimForeachMapHelper(interp
, argc
, argv
, 1);
11379 static int Jim_IfCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11381 int boolean
, retval
, current
= 1, falsebody
= 0;
11385 /* Far not enough arguments given! */
11386 if (current
>= argc
)
11388 if ((retval
= Jim_GetBoolFromExpr(interp
, argv
[current
++], &boolean
))
11391 /* There lacks something, isn't it? */
11392 if (current
>= argc
)
11394 if (Jim_CompareStringImmediate(interp
, argv
[current
], "then"))
11396 /* Tsk tsk, no then-clause? */
11397 if (current
>= argc
)
11400 return Jim_EvalObj(interp
, argv
[current
]);
11401 /* Ok: no else-clause follows */
11402 if (++current
>= argc
) {
11403 Jim_SetResult(interp
, Jim_NewEmptyStringObj(interp
));
11406 falsebody
= current
++;
11407 if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "else")) {
11408 /* IIICKS - else-clause isn't last cmd? */
11409 if (current
!= argc
- 1)
11411 return Jim_EvalObj(interp
, argv
[current
]);
11413 else if (Jim_CompareStringImmediate(interp
, argv
[falsebody
], "elseif"))
11414 /* Ok: elseif follows meaning all the stuff
11415 * again (how boring...) */
11417 /* OOPS - else-clause is not last cmd? */
11418 else if (falsebody
!= argc
- 1)
11420 return Jim_EvalObj(interp
, argv
[falsebody
]);
11425 Jim_WrongNumArgs(interp
, 1, argv
, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
11430 /* Returns 1 if match, 0 if no match or -<error> on error (e.g. -JIM_ERR, -JIM_BREAK)*/
11431 int Jim_CommandMatchObj(Jim_Interp
*interp
, Jim_Obj
*commandObj
, Jim_Obj
*patternObj
,
11432 Jim_Obj
*stringObj
, int nocase
)
11439 parms
[argc
++] = commandObj
;
11441 parms
[argc
++] = Jim_NewStringObj(interp
, "-nocase", -1);
11443 parms
[argc
++] = patternObj
;
11444 parms
[argc
++] = stringObj
;
11446 rc
= Jim_EvalObjVector(interp
, argc
, parms
);
11448 if (rc
!= JIM_OK
|| Jim_GetLong(interp
, Jim_GetResult(interp
), &eq
) != JIM_OK
) {
11456 { SWITCH_EXACT
, SWITCH_GLOB
, SWITCH_RE
, SWITCH_CMD
};
11459 static int Jim_SwitchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11461 int matchOpt
= SWITCH_EXACT
, opt
= 1, patCount
, i
;
11462 Jim_Obj
*command
= 0, *const *caseList
= 0, *strObj
;
11463 Jim_Obj
*script
= 0;
11467 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string "
11468 "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
11471 for (opt
= 1; opt
< argc
; ++opt
) {
11472 const char *option
= Jim_String(argv
[opt
]);
11474 if (*option
!= '-')
11476 else if (strncmp(option
, "--", 2) == 0) {
11480 else if (strncmp(option
, "-exact", 2) == 0)
11481 matchOpt
= SWITCH_EXACT
;
11482 else if (strncmp(option
, "-glob", 2) == 0)
11483 matchOpt
= SWITCH_GLOB
;
11484 else if (strncmp(option
, "-regexp", 2) == 0)
11485 matchOpt
= SWITCH_RE
;
11486 else if (strncmp(option
, "-command", 2) == 0) {
11487 matchOpt
= SWITCH_CMD
;
11488 if ((argc
- opt
) < 2)
11490 command
= argv
[++opt
];
11493 Jim_SetResultFormatted(interp
,
11494 "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
11498 if ((argc
- opt
) < 2)
11501 strObj
= argv
[opt
++];
11502 patCount
= argc
- opt
;
11503 if (patCount
== 1) {
11506 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11510 caseList
= &argv
[opt
];
11511 if (patCount
== 0 || patCount
% 2 != 0)
11513 for (i
= 0; script
== 0 && i
< patCount
; i
+= 2) {
11514 Jim_Obj
*patObj
= caseList
[i
];
11516 if (!Jim_CompareStringImmediate(interp
, patObj
, "default")
11517 || i
< (patCount
- 2)) {
11518 switch (matchOpt
) {
11520 if (Jim_StringEqObj(strObj
, patObj
))
11521 script
= caseList
[i
+ 1];
11524 if (Jim_StringMatchObj(interp
, patObj
, strObj
, 0))
11525 script
= caseList
[i
+ 1];
11528 command
= Jim_NewStringObj(interp
, "regexp", -1);
11529 /* Fall thru intentionally */
11531 int rc
= Jim_CommandMatchObj(interp
, command
, patObj
, strObj
, 0);
11533 /* After the execution of a command we need to
11534 * make sure to reconvert the object into a list
11535 * again. Only for the single-list style [switch]. */
11536 if (argc
- opt
== 1) {
11539 JimListGetElements(interp
, argv
[opt
], &patCount
, &vector
);
11542 /* command is here already decref'd */
11547 script
= caseList
[i
+ 1];
11553 script
= caseList
[i
+ 1];
11556 for (; i
< patCount
&& Jim_CompareStringImmediate(interp
, script
, "-"); i
+= 2)
11557 script
= caseList
[i
+ 1];
11558 if (script
&& Jim_CompareStringImmediate(interp
, script
, "-")) {
11559 Jim_SetResultFormatted(interp
, "no body specified for pattern \"%#s\"", caseList
[i
- 2]);
11562 Jim_SetEmptyResult(interp
);
11564 return Jim_EvalObj(interp
, script
);
11570 static int Jim_ListCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11572 Jim_Obj
*listObjPtr
;
11574 listObjPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
11575 Jim_SetResult(interp
, listObjPtr
);
11580 static int Jim_LindexCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11582 Jim_Obj
*objPtr
, *listObjPtr
;
11587 Jim_WrongNumArgs(interp
, 1, argv
, "list index ?...?");
11591 Jim_IncrRefCount(objPtr
);
11592 for (i
= 2; i
< argc
; i
++) {
11593 listObjPtr
= objPtr
;
11594 if (Jim_GetIndex(interp
, argv
[i
], &idx
) != JIM_OK
) {
11595 Jim_DecrRefCount(interp
, listObjPtr
);
11598 if (Jim_ListIndex(interp
, listObjPtr
, idx
, &objPtr
, JIM_NONE
) != JIM_OK
) {
11599 /* Returns an empty object if the index
11600 * is out of range. */
11601 Jim_DecrRefCount(interp
, listObjPtr
);
11602 Jim_SetEmptyResult(interp
);
11605 Jim_IncrRefCount(objPtr
);
11606 Jim_DecrRefCount(interp
, listObjPtr
);
11608 Jim_SetResult(interp
, objPtr
);
11609 Jim_DecrRefCount(interp
, objPtr
);
11614 static int Jim_LlengthCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11617 Jim_WrongNumArgs(interp
, 1, argv
, "list");
11620 Jim_SetResultInt(interp
, Jim_ListLength(interp
, argv
[1]));
11625 static int Jim_LsearchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11627 static const char * const options
[] = {
11628 "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
11632 { OPT_BOOL
, OPT_NOT
, OPT_NOCASE
, OPT_EXACT
, OPT_GLOB
, OPT_REGEXP
, OPT_ALL
, OPT_INLINE
,
11637 int opt_nocase
= 0;
11639 int opt_inline
= 0;
11640 int opt_match
= OPT_EXACT
;
11643 Jim_Obj
*listObjPtr
= NULL
;
11644 Jim_Obj
*commandObj
= NULL
;
11648 Jim_WrongNumArgs(interp
, 1, argv
,
11649 "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
11653 for (i
= 1; i
< argc
- 2; i
++) {
11656 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
) != JIM_OK
) {
11678 if (i
>= argc
- 2) {
11681 commandObj
= argv
[++i
];
11686 opt_match
= option
;
11694 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11696 if (opt_match
== OPT_REGEXP
) {
11697 commandObj
= Jim_NewStringObj(interp
, "regexp", -1);
11700 Jim_IncrRefCount(commandObj
);
11703 listlen
= Jim_ListLength(interp
, argv
[0]);
11704 for (i
= 0; i
< listlen
; i
++) {
11708 Jim_ListIndex(interp
, argv
[0], i
, &objPtr
, JIM_NONE
);
11709 switch (opt_match
) {
11711 eq
= Jim_StringCompareObj(interp
, objPtr
, argv
[1], opt_nocase
) == 0;
11715 eq
= Jim_StringMatchObj(interp
, argv
[1], objPtr
, opt_nocase
);
11720 eq
= Jim_CommandMatchObj(interp
, commandObj
, argv
[1], objPtr
, opt_nocase
);
11723 Jim_FreeNewObj(interp
, listObjPtr
);
11731 /* If we have a non-match with opt_bool, opt_not, !opt_all, can't exit early */
11732 if (!eq
&& opt_bool
&& opt_not
&& !opt_all
) {
11736 if ((!opt_bool
&& eq
== !opt_not
) || (opt_bool
&& (eq
|| opt_all
))) {
11737 /* Got a match (or non-match for opt_not), or (opt_bool && opt_all) */
11738 Jim_Obj
*resultObj
;
11741 resultObj
= Jim_NewIntObj(interp
, eq
^ opt_not
);
11743 else if (!opt_inline
) {
11744 resultObj
= Jim_NewIntObj(interp
, i
);
11747 resultObj
= objPtr
;
11751 Jim_ListAppendElement(interp
, listObjPtr
, resultObj
);
11754 Jim_SetResult(interp
, resultObj
);
11761 Jim_SetResult(interp
, listObjPtr
);
11766 Jim_SetResultBool(interp
, opt_not
);
11768 else if (!opt_inline
) {
11769 Jim_SetResultInt(interp
, -1);
11775 Jim_DecrRefCount(interp
, commandObj
);
11781 static int Jim_LappendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11783 Jim_Obj
*listObjPtr
;
11787 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
11790 listObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
11792 /* Create the list if it does not exists */
11793 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
11794 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11795 Jim_FreeNewObj(interp
, listObjPtr
);
11799 shared
= Jim_IsShared(listObjPtr
);
11801 listObjPtr
= Jim_DuplicateObj(interp
, listObjPtr
);
11802 for (i
= 2; i
< argc
; i
++)
11803 Jim_ListAppendElement(interp
, listObjPtr
, argv
[i
]);
11804 if (Jim_SetVariable(interp
, argv
[1], listObjPtr
) != JIM_OK
) {
11806 Jim_FreeNewObj(interp
, listObjPtr
);
11809 Jim_SetResult(interp
, listObjPtr
);
11814 static int Jim_LinsertCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11820 Jim_WrongNumArgs(interp
, 1, argv
, "list index element " "?element ...?");
11824 if (Jim_IsShared(listPtr
))
11825 listPtr
= Jim_DuplicateObj(interp
, listPtr
);
11826 if (Jim_GetIndex(interp
, argv
[2], &idx
) != JIM_OK
)
11828 len
= Jim_ListLength(interp
, listPtr
);
11832 idx
= len
+ idx
+ 1;
11833 Jim_ListInsertElements(interp
, listPtr
, idx
, argc
- 3, &argv
[3]);
11834 Jim_SetResult(interp
, listPtr
);
11837 if (listPtr
!= argv
[1]) {
11838 Jim_FreeNewObj(interp
, listPtr
);
11844 static int Jim_LreplaceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11846 int first
, last
, len
, rangeLen
;
11848 Jim_Obj
*newListObj
;
11853 Jim_WrongNumArgs(interp
, 1, argv
, "list first last ?element element ...?");
11856 if (Jim_GetIndex(interp
, argv
[2], &first
) != JIM_OK
||
11857 Jim_GetIndex(interp
, argv
[3], &last
) != JIM_OK
) {
11862 len
= Jim_ListLength(interp
, listObj
);
11864 first
= JimRelToAbsIndex(len
, first
);
11865 last
= JimRelToAbsIndex(len
, last
);
11866 JimRelToAbsRange(len
, first
, last
, &first
, &last
, &rangeLen
);
11868 /* Now construct a new list which consists of:
11869 * <elements before first> <supplied elements> <elements after last>
11872 /* Check to see if trying to replace past the end of the list */
11874 /* OK. Not past the end */
11876 else if (len
== 0) {
11877 /* Special for empty list, adjust first to 0 */
11881 Jim_SetResultString(interp
, "list doesn't contain element ", -1);
11882 Jim_AppendObj(interp
, Jim_GetResult(interp
), argv
[2]);
11886 newListObj
= Jim_NewListObj(interp
, NULL
, 0);
11888 shared
= Jim_IsShared(listObj
);
11890 listObj
= Jim_DuplicateObj(interp
, listObj
);
11893 /* Add the first set of elements */
11894 for (i
= 0; i
< first
; i
++) {
11895 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11898 /* Add supplied elements */
11899 for (i
= 4; i
< argc
; i
++) {
11900 Jim_ListAppendElement(interp
, newListObj
, argv
[i
]);
11903 /* Add the remaining elements */
11904 for (i
= first
+ rangeLen
; i
< len
; i
++) {
11905 Jim_ListAppendElement(interp
, newListObj
, listObj
->internalRep
.listValue
.ele
[i
]);
11907 Jim_SetResult(interp
, newListObj
);
11909 Jim_FreeNewObj(interp
, listObj
);
11915 static int Jim_LsetCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
11918 Jim_WrongNumArgs(interp
, 1, argv
, "listVar ?index...? newVal");
11921 else if (argc
== 3) {
11922 if (Jim_SetVariable(interp
, argv
[1], argv
[2]) != JIM_OK
)
11924 Jim_SetResult(interp
, argv
[2]);
11927 if (Jim_SetListIndex(interp
, argv
[1], argv
+ 2, argc
- 3, argv
[argc
- 1])
11934 static int Jim_LsortCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const argv
[])
11936 static const char * const options
[] = {
11937 "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-index", NULL
11940 { OPT_ASCII
, OPT_NOCASE
, OPT_INCREASING
, OPT_DECREASING
, OPT_COMMAND
, OPT_INTEGER
, OPT_INDEX
};
11945 struct lsort_info info
;
11948 Jim_WrongNumArgs(interp
, 1, argv
, "?options? list");
11952 info
.type
= JIM_LSORT_ASCII
;
11955 info
.command
= NULL
;
11956 info
.interp
= interp
;
11958 for (i
= 1; i
< (argc
- 1); i
++) {
11961 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
, JIM_ERRMSG
)
11966 info
.type
= JIM_LSORT_ASCII
;
11969 info
.type
= JIM_LSORT_NOCASE
;
11972 info
.type
= JIM_LSORT_INTEGER
;
11974 case OPT_INCREASING
:
11977 case OPT_DECREASING
:
11981 if (i
>= (argc
- 2)) {
11982 Jim_SetResultString(interp
, "\"-command\" option must be followed by comparison command", -1);
11985 info
.type
= JIM_LSORT_COMMAND
;
11986 info
.command
= argv
[i
+ 1];
11990 if (i
>= (argc
- 2)) {
11991 Jim_SetResultString(interp
, "\"-index\" option must be followed by list index", -1);
11994 if (Jim_GetIndex(interp
, argv
[i
+ 1], &info
.index
) != JIM_OK
) {
12002 resObj
= Jim_DuplicateObj(interp
, argv
[argc
- 1]);
12003 retCode
= ListSortElements(interp
, resObj
, &info
);
12004 if (retCode
== JIM_OK
) {
12005 Jim_SetResult(interp
, resObj
);
12008 Jim_FreeNewObj(interp
, resObj
);
12014 static int Jim_AppendCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12016 Jim_Obj
*stringObjPtr
;
12020 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?value value ...?");
12024 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_ERRMSG
);
12030 stringObjPtr
= Jim_GetVariable(interp
, argv
[1], JIM_UNSHARED
);
12031 if (!stringObjPtr
) {
12032 /* Create the string if it doesn't exist */
12033 stringObjPtr
= Jim_NewEmptyStringObj(interp
);
12036 else if (Jim_IsShared(stringObjPtr
)) {
12038 stringObjPtr
= Jim_DuplicateObj(interp
, stringObjPtr
);
12040 for (i
= 2; i
< argc
; i
++) {
12041 Jim_AppendObj(interp
, stringObjPtr
, argv
[i
]);
12043 if (Jim_SetVariable(interp
, argv
[1], stringObjPtr
) != JIM_OK
) {
12045 Jim_FreeNewObj(interp
, stringObjPtr
);
12050 Jim_SetResult(interp
, stringObjPtr
);
12055 static int Jim_DebugCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12057 #if defined(JIM_DEBUG_COMMAND) && !defined(JIM_BOOTSTRAP)
12058 static const char * const options
[] = {
12059 "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
12065 OPT_REFCOUNT
, OPT_OBJCOUNT
, OPT_OBJECTS
, OPT_INVSTR
, OPT_SCRIPTLEN
,
12066 OPT_EXPRLEN
, OPT_EXPRBC
, OPT_SHOW
,
12071 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?...?");
12074 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
)
12076 if (option
== OPT_REFCOUNT
) {
12078 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12081 Jim_SetResultInt(interp
, argv
[2]->refCount
);
12084 else if (option
== OPT_OBJCOUNT
) {
12085 int freeobj
= 0, liveobj
= 0;
12090 Jim_WrongNumArgs(interp
, 2, argv
, "");
12093 /* Count the number of free objects. */
12094 objPtr
= interp
->freeList
;
12097 objPtr
= objPtr
->nextObjPtr
;
12099 /* Count the number of live objects. */
12100 objPtr
= interp
->liveList
;
12103 objPtr
= objPtr
->nextObjPtr
;
12105 /* Set the result string and return. */
12106 sprintf(buf
, "free %d used %d", freeobj
, liveobj
);
12107 Jim_SetResultString(interp
, buf
, -1);
12110 else if (option
== OPT_OBJECTS
) {
12111 Jim_Obj
*objPtr
, *listObjPtr
, *subListObjPtr
;
12113 /* Count the number of live objects. */
12114 objPtr
= interp
->liveList
;
12115 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12118 const char *type
= objPtr
->typePtr
? objPtr
->typePtr
->name
: "";
12120 subListObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
12121 sprintf(buf
, "%p", objPtr
);
12122 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
12123 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewStringObj(interp
, type
, -1));
12124 Jim_ListAppendElement(interp
, subListObjPtr
, Jim_NewIntObj(interp
, objPtr
->refCount
));
12125 Jim_ListAppendElement(interp
, subListObjPtr
, objPtr
);
12126 Jim_ListAppendElement(interp
, listObjPtr
, subListObjPtr
);
12127 objPtr
= objPtr
->nextObjPtr
;
12129 Jim_SetResult(interp
, listObjPtr
);
12132 else if (option
== OPT_INVSTR
) {
12136 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12140 if (objPtr
->typePtr
!= NULL
)
12141 Jim_InvalidateStringRep(objPtr
);
12142 Jim_SetEmptyResult(interp
);
12145 else if (option
== OPT_SHOW
) {
12150 Jim_WrongNumArgs(interp
, 2, argv
, "object");
12153 s
= Jim_GetString(argv
[2], &len
);
12155 charlen
= utf8_strlen(s
, len
);
12159 printf("refcount: %d, type: %s\n", argv
[2]->refCount
, JimObjTypeName(argv
[2]));
12160 printf("chars (%d): <<%s>>\n", charlen
, s
);
12161 printf("bytes (%d):", len
);
12163 printf(" %02x", (unsigned char)*s
++);
12168 else if (option
== OPT_SCRIPTLEN
) {
12172 Jim_WrongNumArgs(interp
, 2, argv
, "script");
12175 script
= Jim_GetScript(interp
, argv
[2]);
12176 Jim_SetResultInt(interp
, script
->len
);
12179 else if (option
== OPT_EXPRLEN
) {
12180 ExprByteCode
*expr
;
12183 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12186 expr
= JimGetExpression(interp
, argv
[2]);
12189 Jim_SetResultInt(interp
, expr
->len
);
12192 else if (option
== OPT_EXPRBC
) {
12194 ExprByteCode
*expr
;
12198 Jim_WrongNumArgs(interp
, 2, argv
, "expression");
12201 expr
= JimGetExpression(interp
, argv
[2]);
12204 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
12205 for (i
= 0; i
< expr
->len
; i
++) {
12207 const Jim_ExprOperator
*op
;
12208 Jim_Obj
*obj
= expr
->token
[i
].objPtr
;
12210 switch (expr
->token
[i
].type
) {
12211 case JIM_TT_EXPR_INT
:
12214 case JIM_TT_EXPR_DOUBLE
:
12223 case JIM_TT_DICTSUGAR
:
12224 type
= "dictsugar";
12226 case JIM_TT_EXPRSUGAR
:
12227 type
= "exprsugar";
12236 op
= JimExprOperatorInfoByOpcode(expr
->token
[i
].type
);
12243 obj
= Jim_NewStringObj(interp
, op
? op
->name
: "", -1);
12246 Jim_ListAppendElement(interp
, objPtr
, Jim_NewStringObj(interp
, type
, -1));
12247 Jim_ListAppendElement(interp
, objPtr
, obj
);
12249 Jim_SetResult(interp
, objPtr
);
12253 Jim_SetResultString(interp
,
12254 "bad option. Valid options are refcount, " "objcount, objects, invstr", -1);
12258 #endif /* JIM_BOOTSTRAP */
12259 #if !defined(JIM_DEBUG_COMMAND)
12260 Jim_SetResultString(interp
, "unsupported", -1);
12266 static int Jim_EvalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12271 Jim_WrongNumArgs(interp
, 1, argv
, "script ?...?");
12276 rc
= Jim_EvalObj(interp
, argv
[1]);
12279 rc
= Jim_EvalObj(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12282 if (rc
== JIM_ERR
) {
12283 /* eval is "interesting", so add a stack frame here */
12284 interp
->addStackTrace
++;
12290 static int Jim_UplevelCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12294 Jim_CallFrame
*savedCallFrame
, *targetCallFrame
;
12298 /* Save the old callframe pointer */
12299 savedCallFrame
= interp
->framePtr
;
12301 /* Lookup the target frame pointer */
12302 str
= Jim_String(argv
[1]);
12303 if ((str
[0] >= '0' && str
[0] <= '9') || str
[0] == '#') {
12304 targetCallFrame
=Jim_GetCallFrameByLevel(interp
, argv
[1]);
12309 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12311 if (targetCallFrame
== NULL
) {
12316 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12319 /* Eval the code in the target callframe. */
12320 interp
->framePtr
= targetCallFrame
;
12322 retcode
= Jim_EvalObj(interp
, argv
[1]);
12325 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12326 Jim_IncrRefCount(objPtr
);
12327 retcode
= Jim_EvalObj(interp
, objPtr
);
12328 Jim_DecrRefCount(interp
, objPtr
);
12330 interp
->framePtr
= savedCallFrame
;
12334 Jim_WrongNumArgs(interp
, 1, argv
, "?level? command ?arg ...?");
12340 static int Jim_ExprCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12342 Jim_Obj
*exprResultPtr
;
12346 retcode
= Jim_EvalExpression(interp
, argv
[1], &exprResultPtr
);
12348 else if (argc
> 2) {
12351 objPtr
= Jim_ConcatObj(interp
, argc
- 1, argv
+ 1);
12352 Jim_IncrRefCount(objPtr
);
12353 retcode
= Jim_EvalExpression(interp
, objPtr
, &exprResultPtr
);
12354 Jim_DecrRefCount(interp
, objPtr
);
12357 Jim_WrongNumArgs(interp
, 1, argv
, "expression ?...?");
12360 if (retcode
!= JIM_OK
)
12362 Jim_SetResult(interp
, exprResultPtr
);
12363 Jim_DecrRefCount(interp
, exprResultPtr
);
12368 static int Jim_BreakCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12371 Jim_WrongNumArgs(interp
, 1, argv
, "");
12378 static int Jim_ContinueCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12381 Jim_WrongNumArgs(interp
, 1, argv
, "");
12384 return JIM_CONTINUE
;
12388 static int Jim_ReturnCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12391 Jim_Obj
*stackTraceObj
= NULL
;
12392 Jim_Obj
*errorCodeObj
= NULL
;
12393 int returnCode
= JIM_OK
;
12396 for (i
= 1; i
< argc
- 1; i
+= 2) {
12397 if (Jim_CompareStringImmediate(interp
, argv
[i
], "-code")) {
12398 if (Jim_GetReturnCode(interp
, argv
[i
+ 1], &returnCode
) == JIM_ERR
) {
12402 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorinfo")) {
12403 stackTraceObj
= argv
[i
+ 1];
12405 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-errorcode")) {
12406 errorCodeObj
= argv
[i
+ 1];
12408 else if (Jim_CompareStringImmediate(interp
, argv
[i
], "-level")) {
12409 if (Jim_GetLong(interp
, argv
[i
+ 1], &level
) != JIM_OK
|| level
< 0) {
12410 Jim_SetResultFormatted(interp
, "bad level \"%#s\"", argv
[i
+ 1]);
12419 if (i
!= argc
- 1 && i
!= argc
) {
12420 Jim_WrongNumArgs(interp
, 1, argv
,
12421 "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
12424 /* If a stack trace is supplied and code is error, set the stack trace */
12425 if (stackTraceObj
&& returnCode
== JIM_ERR
) {
12426 JimSetStackTrace(interp
, stackTraceObj
);
12428 /* If an error code list is supplied, set the global $errorCode */
12429 if (errorCodeObj
&& returnCode
== JIM_ERR
) {
12430 Jim_SetGlobalVariableStr(interp
, "errorCode", errorCodeObj
);
12432 interp
->returnCode
= returnCode
;
12433 interp
->returnLevel
= level
;
12435 if (i
== argc
- 1) {
12436 Jim_SetResult(interp
, argv
[i
]);
12442 static int Jim_TailcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12446 objPtr
= Jim_NewListObj(interp
, argv
+ 1, argc
- 1);
12447 Jim_SetResult(interp
, objPtr
);
12452 static int Jim_ProcCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12454 if (argc
!= 4 && argc
!= 5) {
12455 Jim_WrongNumArgs(interp
, 1, argv
, "name arglist ?statics? body");
12460 return JimCreateProcedure(interp
, argv
[1], argv
[2], NULL
, argv
[3]);
12463 return JimCreateProcedure(interp
, argv
[1], argv
[2], argv
[3], argv
[4]);
12468 static int Jim_LocalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12472 /* Evaluate the arguments with 'local' in force */
12474 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12478 /* If OK, and the result is a proc, add it to the list of local procs */
12479 if (retcode
== 0) {
12480 const char *procname
= Jim_String(Jim_GetResult(interp
));
12482 if (Jim_FindHashEntry(&interp
->commands
, procname
) == NULL
) {
12483 Jim_SetResultFormatted(interp
, "not a proc: \"%s\"", procname
);
12486 if (interp
->localProcs
== NULL
) {
12487 interp
->localProcs
= Jim_Alloc(sizeof(*interp
->localProcs
));
12488 Jim_InitStack(interp
->localProcs
);
12490 Jim_StackPush(interp
->localProcs
, Jim_StrDup(procname
));
12497 static int Jim_UpcallCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12500 Jim_WrongNumArgs(interp
, 1, argv
, "cmd ?args ...?");
12506 Jim_Cmd
*cmdPtr
= Jim_GetCommand(interp
, argv
[1], JIM_ERRMSG
);
12507 if (cmdPtr
== NULL
|| !cmdPtr
->isproc
|| !cmdPtr
->u
.proc
.prevCmd
) {
12508 Jim_SetResultFormatted(interp
, "no previous proc: \"%#s\"", argv
[1]);
12511 /* OK. Mark this command as being in an upcall */
12512 cmdPtr
->u
.proc
.upcall
++;
12513 JimIncrCmdRefCount(cmdPtr
);
12515 /* Invoke the command as normal */
12516 retcode
= Jim_EvalObjVector(interp
, argc
- 1, argv
+ 1);
12518 /* No longer in an upcall */
12519 cmdPtr
->u
.proc
.upcall
--;
12520 JimDecrCmdRefCount(interp
, cmdPtr
);
12527 static int Jim_ConcatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12529 Jim_SetResult(interp
, Jim_ConcatObj(interp
, argc
- 1, argv
+ 1));
12534 static int Jim_UpvarCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12537 Jim_CallFrame
*targetCallFrame
;
12539 /* Lookup the target frame pointer */
12540 if (argc
> 3 && (argc
% 2 == 0)) {
12541 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, argv
[1]);
12546 targetCallFrame
= Jim_GetCallFrameByLevel(interp
, NULL
);
12548 if (targetCallFrame
== NULL
) {
12552 /* Check for arity */
12554 Jim_WrongNumArgs(interp
, 1, argv
, "?level? otherVar localVar ?otherVar localVar ...?");
12558 /* Now... for every other/local couple: */
12559 for (i
= 1; i
< argc
; i
+= 2) {
12560 if (Jim_SetVariableLink(interp
, argv
[i
+ 1], argv
[i
], targetCallFrame
) != JIM_OK
)
12567 static int Jim_GlobalCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12572 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?varName ...?");
12575 /* Link every var to the toplevel having the same name */
12576 if (interp
->framePtr
->level
== 0)
12577 return JIM_OK
; /* global at toplevel... */
12578 for (i
= 1; i
< argc
; i
++) {
12579 if (Jim_SetVariableLink(interp
, argv
[i
], argv
[i
], interp
->topFramePtr
) != JIM_OK
)
12585 /* does the [string map] operation. On error NULL is returned,
12586 * otherwise a new string object with the result, having refcount = 0,
12588 static Jim_Obj
*JimStringMap(Jim_Interp
*interp
, Jim_Obj
*mapListObjPtr
,
12589 Jim_Obj
*objPtr
, int nocase
)
12592 const char *str
, *noMatchStart
= NULL
;
12594 Jim_Obj
*resultObjPtr
;
12596 numMaps
= Jim_ListLength(interp
, mapListObjPtr
);
12598 Jim_SetResultString(interp
, "list must contain an even number of elements", -1);
12602 str
= Jim_String(objPtr
);
12603 strLen
= Jim_Utf8Length(interp
, objPtr
);
12606 resultObjPtr
= Jim_NewStringObj(interp
, "", 0);
12608 for (i
= 0; i
< numMaps
; i
+= 2) {
12613 Jim_ListIndex(interp
, mapListObjPtr
, i
, &objPtr
, JIM_NONE
);
12614 k
= Jim_String(objPtr
);
12615 kl
= Jim_Utf8Length(interp
, objPtr
);
12617 if (strLen
>= kl
&& kl
) {
12620 rc
= JimStringCompareNoCase(str
, k
, kl
);
12623 rc
= JimStringCompare(str
, kl
, k
, kl
);
12626 if (noMatchStart
) {
12627 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12628 noMatchStart
= NULL
;
12630 Jim_ListIndex(interp
, mapListObjPtr
, i
+ 1, &objPtr
, JIM_NONE
);
12631 Jim_AppendObj(interp
, resultObjPtr
, objPtr
);
12632 str
+= utf8_index(str
, kl
);
12638 if (i
== numMaps
) { /* no match */
12640 if (noMatchStart
== NULL
)
12641 noMatchStart
= str
;
12642 str
+= utf8_tounicode(str
, &c
);
12646 if (noMatchStart
) {
12647 Jim_AppendString(interp
, resultObjPtr
, noMatchStart
, str
- noMatchStart
);
12649 return resultObjPtr
;
12653 static int Jim_StringCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12658 static const char * const options
[] = {
12659 "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "map",
12660 "repeat", "reverse", "index", "first", "last",
12661 "trim", "trimleft", "trimright", "tolower", "toupper", NULL
12665 OPT_BYTELENGTH
, OPT_LENGTH
, OPT_COMPARE
, OPT_MATCH
, OPT_EQUAL
, OPT_IS
, OPT_BYTERANGE
, OPT_RANGE
, OPT_MAP
,
12666 OPT_REPEAT
, OPT_REVERSE
, OPT_INDEX
, OPT_FIRST
, OPT_LAST
,
12667 OPT_TRIM
, OPT_TRIMLEFT
, OPT_TRIMRIGHT
, OPT_TOLOWER
, OPT_TOUPPER
12669 static const char * const nocase_options
[] = {
12674 Jim_WrongNumArgs(interp
, 1, argv
, "option ?arguments ...?");
12677 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
,
12678 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
)
12683 case OPT_BYTELENGTH
:
12685 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12688 if (option
== OPT_LENGTH
) {
12689 len
= Jim_Utf8Length(interp
, argv
[2]);
12692 len
= Jim_Length(argv
[2]);
12694 Jim_SetResultInt(interp
, len
);
12701 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12702 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12703 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? string1 string2");
12706 if (opt_case
== 0) {
12709 if (option
== OPT_COMPARE
|| !opt_case
) {
12710 Jim_SetResultInt(interp
, Jim_StringCompareObj(interp
, argv
[2], argv
[3], !opt_case
));
12713 Jim_SetResultBool(interp
, Jim_StringEqObj(argv
[2], argv
[3]));
12720 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12721 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12722 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? pattern string");
12725 if (opt_case
== 0) {
12728 Jim_SetResultBool(interp
, Jim_StringMatchObj(interp
, argv
[2], argv
[3], !opt_case
));
12736 Jim_GetEnum(interp
, argv
[2], nocase_options
, &opt_case
, NULL
,
12737 JIM_ENUM_ABBREV
) != JIM_OK
)) {
12738 Jim_WrongNumArgs(interp
, 2, argv
, "?-nocase? mapList string");
12742 if (opt_case
== 0) {
12745 objPtr
= JimStringMap(interp
, argv
[2], argv
[3], !opt_case
);
12746 if (objPtr
== NULL
) {
12749 Jim_SetResult(interp
, objPtr
);
12754 case OPT_BYTERANGE
:{
12758 Jim_WrongNumArgs(interp
, 2, argv
, "string first last");
12761 if (option
== OPT_RANGE
) {
12762 objPtr
= Jim_StringRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12766 objPtr
= Jim_StringByteRangeObj(interp
, argv
[2], argv
[3], argv
[4]);
12769 if (objPtr
== NULL
) {
12772 Jim_SetResult(interp
, objPtr
);
12781 Jim_WrongNumArgs(interp
, 2, argv
, "string count");
12784 if (Jim_GetWide(interp
, argv
[3], &count
) != JIM_OK
) {
12787 objPtr
= Jim_NewStringObj(interp
, "", 0);
12790 Jim_AppendObj(interp
, objPtr
, argv
[2]);
12793 Jim_SetResult(interp
, objPtr
);
12804 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12808 str
= Jim_GetString(argv
[2], &len
);
12809 buf
= Jim_Alloc(len
+ 1);
12812 for (i
= 0; i
< len
; ) {
12814 int l
= utf8_tounicode(str
, &c
);
12815 memcpy(p
- l
, str
, l
);
12820 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
12829 Jim_WrongNumArgs(interp
, 2, argv
, "string index");
12832 if (Jim_GetIndex(interp
, argv
[3], &idx
) != JIM_OK
) {
12835 str
= Jim_String(argv
[2]);
12836 len
= Jim_Utf8Length(interp
, argv
[2]);
12837 if (idx
!= INT_MIN
&& idx
!= INT_MAX
) {
12838 idx
= JimRelToAbsIndex(len
, idx
);
12840 if (idx
< 0 || idx
>= len
|| str
== NULL
) {
12841 Jim_SetResultString(interp
, "", 0);
12843 else if (len
== Jim_Length(argv
[2])) {
12844 /* ASCII optimisation */
12845 Jim_SetResultString(interp
, str
+ idx
, 1);
12849 int i
= utf8_index(str
, idx
);
12850 Jim_SetResultString(interp
, str
+ i
, utf8_tounicode(str
+ i
, &c
));
12857 int idx
= 0, l1
, l2
;
12858 const char *s1
, *s2
;
12860 if (argc
!= 4 && argc
!= 5) {
12861 Jim_WrongNumArgs(interp
, 2, argv
, "subString string ?index?");
12864 s1
= Jim_String(argv
[2]);
12865 s2
= Jim_String(argv
[3]);
12866 l1
= Jim_Utf8Length(interp
, argv
[2]);
12867 l2
= Jim_Utf8Length(interp
, argv
[3]);
12869 if (Jim_GetIndex(interp
, argv
[4], &idx
) != JIM_OK
) {
12872 idx
= JimRelToAbsIndex(l2
, idx
);
12874 else if (option
== OPT_LAST
) {
12877 if (option
== OPT_FIRST
) {
12878 Jim_SetResultInt(interp
, JimStringFirst(s1
, l1
, s2
, l2
, idx
));
12882 Jim_SetResultInt(interp
, JimStringLastUtf8(s1
, l1
, s2
, idx
));
12884 Jim_SetResultInt(interp
, JimStringLast(s1
, l1
, s2
, idx
));
12892 case OPT_TRIMRIGHT
:{
12893 Jim_Obj
*trimchars
;
12895 if (argc
!= 3 && argc
!= 4) {
12896 Jim_WrongNumArgs(interp
, 2, argv
, "string ?trimchars?");
12899 trimchars
= (argc
== 4 ? argv
[3] : NULL
);
12900 if (option
== OPT_TRIM
) {
12901 Jim_SetResult(interp
, JimStringTrim(interp
, argv
[2], trimchars
));
12903 else if (option
== OPT_TRIMLEFT
) {
12904 Jim_SetResult(interp
, JimStringTrimLeft(interp
, argv
[2], trimchars
));
12906 else if (option
== OPT_TRIMRIGHT
) {
12907 Jim_SetResult(interp
, JimStringTrimRight(interp
, argv
[2], trimchars
));
12915 Jim_WrongNumArgs(interp
, 2, argv
, "string");
12918 if (option
== OPT_TOLOWER
) {
12919 Jim_SetResult(interp
, JimStringToLower(interp
, argv
[2]));
12922 Jim_SetResult(interp
, JimStringToUpper(interp
, argv
[2]));
12927 if (argc
== 4 || (argc
== 5 && Jim_CompareStringImmediate(interp
, argv
[3], "-strict"))) {
12928 return JimStringIs(interp
, argv
[argc
- 1], argv
[2], argc
== 5);
12930 Jim_WrongNumArgs(interp
, 2, argv
, "class ?-strict? str");
12937 static int Jim_TimeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12940 jim_wide start
, elapsed
;
12942 const char *fmt
= "%" JIM_WIDE_MODIFIER
" microseconds per iteration";
12945 Jim_WrongNumArgs(interp
, 1, argv
, "script ?count?");
12949 if (Jim_GetLong(interp
, argv
[2], &count
) != JIM_OK
)
12955 start
= JimClock();
12959 retval
= Jim_EvalObj(interp
, argv
[1]);
12960 if (retval
!= JIM_OK
) {
12964 elapsed
= JimClock() - start
;
12965 sprintf(buf
, fmt
, count
== 0 ? 0 : elapsed
/ count
);
12966 Jim_SetResultString(interp
, buf
, -1);
12971 static int Jim_ExitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12976 Jim_WrongNumArgs(interp
, 1, argv
, "?exitCode?");
12980 if (Jim_GetLong(interp
, argv
[1], &exitCode
) != JIM_OK
)
12983 interp
->exitCode
= exitCode
;
12988 static int Jim_CatchCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
12994 /* Which return codes are ignored (passed through)? By default, only exit, eval and signal */
12995 jim_wide ignore_mask
= (1 << JIM_EXIT
) | (1 << JIM_EVAL
) | (1 << JIM_SIGNAL
);
12996 static const int max_ignore_code
= sizeof(ignore_mask
) * 8;
12998 /* Reset the error code before catch.
12999 * Note that this is not strictly correct.
13001 Jim_SetGlobalVariableStr(interp
, "errorCode", Jim_NewStringObj(interp
, "NONE", -1));
13003 for (i
= 1; i
< argc
- 1; i
++) {
13004 const char *arg
= Jim_String(argv
[i
]);
13008 /* It's a pity we can't use Jim_GetEnum here :-( */
13009 if (strcmp(arg
, "--") == 0) {
13017 if (strncmp(arg
, "-no", 3) == 0) {
13026 if (Jim_StringToWide(arg
, &option
, 10) != JIM_OK
) {
13030 option
= Jim_FindByName(arg
, jimReturnCodes
, jimReturnCodesSize
);
13037 ignore_mask
|= (1 << option
);
13040 ignore_mask
&= ~(1 << option
);
13045 if (argc
< 1 || argc
> 3) {
13047 Jim_WrongNumArgs(interp
, 1, argv
,
13048 "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
13053 if ((ignore_mask
& (1 << JIM_SIGNAL
)) == 0) {
13057 interp
->signal_level
+= sig
;
13058 if (interp
->signal_level
&& interp
->sigmask
) {
13059 /* If a signal is set, don't even try to execute the body */
13060 exitCode
= JIM_SIGNAL
;
13063 exitCode
= Jim_EvalObj(interp
, argv
[0]);
13065 interp
->signal_level
-= sig
;
13067 /* Catch or pass through? Only the first 32/64 codes can be passed through */
13068 if (exitCode
>= 0 && exitCode
< max_ignore_code
&& ((1 << exitCode
) & ignore_mask
)) {
13069 /* Not caught, pass it up */
13073 if (sig
&& exitCode
== JIM_SIGNAL
) {
13074 /* Catch the signal at this level */
13075 if (interp
->signal_set_result
) {
13076 interp
->signal_set_result(interp
, interp
->sigmask
);
13079 Jim_SetResultInt(interp
, interp
->sigmask
);
13081 interp
->sigmask
= 0;
13085 if (Jim_SetVariable(interp
, argv
[1], Jim_GetResult(interp
)) != JIM_OK
) {
13089 Jim_Obj
*optListObj
= Jim_NewListObj(interp
, NULL
, 0);
13091 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-code", -1));
13092 Jim_ListAppendElement(interp
, optListObj
,
13093 Jim_NewIntObj(interp
, exitCode
== JIM_RETURN
? interp
->returnCode
: exitCode
));
13094 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-level", -1));
13095 Jim_ListAppendElement(interp
, optListObj
, Jim_NewIntObj(interp
, interp
->returnLevel
));
13096 if (exitCode
== JIM_ERR
) {
13097 Jim_Obj
*errorCode
;
13098 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorinfo",
13100 Jim_ListAppendElement(interp
, optListObj
, interp
->stackTrace
);
13102 errorCode
= Jim_GetGlobalVariableStr(interp
, "errorCode", JIM_NONE
);
13104 Jim_ListAppendElement(interp
, optListObj
, Jim_NewStringObj(interp
, "-errorcode", -1));
13105 Jim_ListAppendElement(interp
, optListObj
, errorCode
);
13108 if (Jim_SetVariable(interp
, argv
[2], optListObj
) != JIM_OK
) {
13113 Jim_SetResultInt(interp
, exitCode
);
13117 #ifdef JIM_REFERENCES
13120 static int Jim_RefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13122 if (argc
!= 3 && argc
!= 4) {
13123 Jim_WrongNumArgs(interp
, 1, argv
, "string tag ?finalizer?");
13127 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], NULL
));
13130 Jim_SetResult(interp
, Jim_NewReference(interp
, argv
[1], argv
[2], argv
[3]));
13136 static int Jim_GetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13138 Jim_Reference
*refPtr
;
13141 Jim_WrongNumArgs(interp
, 1, argv
, "reference");
13144 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13146 Jim_SetResult(interp
, refPtr
->objPtr
);
13151 static int Jim_SetrefCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13153 Jim_Reference
*refPtr
;
13156 Jim_WrongNumArgs(interp
, 1, argv
, "reference newValue");
13159 if ((refPtr
= Jim_GetReference(interp
, argv
[1])) == NULL
)
13161 Jim_IncrRefCount(argv
[2]);
13162 Jim_DecrRefCount(interp
, refPtr
->objPtr
);
13163 refPtr
->objPtr
= argv
[2];
13164 Jim_SetResult(interp
, argv
[2]);
13169 static int Jim_CollectCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13172 Jim_WrongNumArgs(interp
, 1, argv
, "");
13175 Jim_SetResultInt(interp
, Jim_Collect(interp
));
13177 /* Free all the freed objects. */
13178 while (interp
->freeList
) {
13179 Jim_Obj
*nextObjPtr
= interp
->freeList
->nextObjPtr
;
13180 Jim_Free(interp
->freeList
);
13181 interp
->freeList
= nextObjPtr
;
13187 /* [finalize] reference ?newValue? */
13188 static int Jim_FinalizeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13190 if (argc
!= 2 && argc
!= 3) {
13191 Jim_WrongNumArgs(interp
, 1, argv
, "reference ?finalizerProc?");
13195 Jim_Obj
*cmdNamePtr
;
13197 if (Jim_GetFinalizer(interp
, argv
[1], &cmdNamePtr
) != JIM_OK
)
13199 if (cmdNamePtr
!= NULL
) /* otherwise the null string is returned. */
13200 Jim_SetResult(interp
, cmdNamePtr
);
13203 if (Jim_SetFinalizer(interp
, argv
[1], argv
[2]) != JIM_OK
)
13205 Jim_SetResult(interp
, argv
[2]);
13210 /* [info references] */
13211 static int JimInfoReferences(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13213 Jim_Obj
*listObjPtr
;
13214 Jim_HashTableIterator
*htiter
;
13217 listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13219 htiter
= Jim_GetHashTableIterator(&interp
->references
);
13220 while ((he
= Jim_NextHashEntry(htiter
)) != NULL
) {
13221 char buf
[JIM_REFERENCE_SPACE
];
13222 Jim_Reference
*refPtr
= he
->u
.val
;
13223 const jim_wide
*refId
= he
->key
;
13225 JimFormatReference(buf
, refPtr
, *refId
);
13226 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, buf
, -1));
13228 Jim_FreeHashTableIterator(htiter
);
13229 Jim_SetResult(interp
, listObjPtr
);
13235 static int Jim_RenameCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13237 const char *oldName
, *newName
;
13240 Jim_WrongNumArgs(interp
, 1, argv
, "oldName newName");
13244 if (JimValidName(interp
, "new procedure", argv
[2])) {
13248 oldName
= Jim_String(argv
[1]);
13249 newName
= Jim_String(argv
[2]);
13250 return Jim_RenameCommand(interp
, oldName
, newName
);
13253 int Jim_DictKeys(Jim_Interp
*interp
, Jim_Obj
*objPtr
, Jim_Obj
*patternObj
)
13257 Jim_Obj
*resultObj
;
13259 Jim_Obj
**dictValuesObj
;
13261 if (Jim_DictKeysVector(interp
, objPtr
, NULL
, 0, &dictObj
, JIM_ERRMSG
) != JIM_OK
) {
13265 /* XXX: Could make the exact-match case much more efficient here.
13266 * See JimCommandsList()
13268 if (Jim_DictPairs(interp
, dictObj
, &dictValuesObj
, &len
) != JIM_OK
) {
13272 /* Only return the matching values */
13273 resultObj
= Jim_NewListObj(interp
, NULL
, 0);
13275 for (i
= 0; i
< len
; i
+= 2) {
13276 if (patternObj
== NULL
|| Jim_StringMatchObj(interp
, patternObj
, dictValuesObj
[i
], 0)) {
13277 Jim_ListAppendElement(interp
, resultObj
, dictValuesObj
[i
]);
13280 Jim_Free(dictValuesObj
);
13282 Jim_SetResult(interp
, resultObj
);
13286 int Jim_DictSize(Jim_Interp
*interp
, Jim_Obj
*objPtr
)
13288 if (SetDictFromAny(interp
, objPtr
) != JIM_OK
) {
13291 return ((Jim_HashTable
*)objPtr
->internalRep
.ptr
)->used
;
13295 static int Jim_DictCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13299 static const char * const options
[] = {
13300 "create", "get", "set", "unset", "exists", "keys", "merge", "size", "with", NULL
13304 OPT_CREATE
, OPT_GET
, OPT_SET
, OPT_UNSET
, OPT_EXIST
, OPT_KEYS
, OPT_MERGE
, OPT_SIZE
, OPT_WITH
,
13308 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?arguments ...?");
13312 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, "subcommand", JIM_ERRMSG
) != JIM_OK
) {
13319 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13322 if (Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, &objPtr
,
13323 JIM_ERRMSG
) != JIM_OK
) {
13326 Jim_SetResult(interp
, objPtr
);
13331 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...? value");
13334 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 4, argv
[argc
- 1], JIM_ERRMSG
);
13338 Jim_WrongNumArgs(interp
, 2, argv
, "varName ?key ...?");
13341 Jim_SetResultBool(interp
, Jim_DictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3,
13342 &objPtr
, JIM_ERRMSG
) == JIM_OK
);
13347 Jim_WrongNumArgs(interp
, 2, argv
, "varName key ?key ...?");
13350 return Jim_SetDictKeysVector(interp
, argv
[2], argv
+ 3, argc
- 3, NULL
, JIM_NONE
);
13353 if (argc
!= 3 && argc
!= 4) {
13354 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?pattern?");
13357 return Jim_DictKeys(interp
, argv
[2], argc
== 4 ? argv
[3] : NULL
);
13363 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar");
13367 size
= Jim_DictSize(interp
, argv
[2]);
13371 Jim_SetResultInt(interp
, size
);
13379 else if (argv
[2]->typePtr
!= &dictObjType
&& SetDictFromAny(interp
, argv
[2]) != JIM_OK
) {
13383 return Jim_EvalPrefix(interp
, "dict merge", argc
- 2, argv
+ 2);
13388 Jim_WrongNumArgs(interp
, 2, argv
, "dictVar ?key ...? script");
13391 else if (Jim_GetVariable(interp
, argv
[2], JIM_ERRMSG
) == NULL
) {
13395 return Jim_EvalPrefix(interp
, "dict with", argc
- 2, argv
+ 2);
13400 Jim_WrongNumArgs(interp
, 2, argv
, "?key value ...?");
13403 objPtr
= Jim_NewDictObj(interp
, argv
+ 2, argc
- 2);
13404 Jim_SetResult(interp
, objPtr
);
13413 static int Jim_SubstCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13415 static const char * const options
[] = {
13416 "-nobackslashes", "-nocommands", "-novariables", NULL
13419 { OPT_NOBACKSLASHES
, OPT_NOCOMMANDS
, OPT_NOVARIABLES
};
13421 int flags
= JIM_SUBST_FLAG
;
13425 Jim_WrongNumArgs(interp
, 1, argv
, "?options? string");
13428 for (i
= 1; i
< (argc
- 1); i
++) {
13431 if (Jim_GetEnum(interp
, argv
[i
], options
, &option
, NULL
,
13432 JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13436 case OPT_NOBACKSLASHES
:
13437 flags
|= JIM_SUBST_NOESC
;
13439 case OPT_NOCOMMANDS
:
13440 flags
|= JIM_SUBST_NOCMD
;
13442 case OPT_NOVARIABLES
:
13443 flags
|= JIM_SUBST_NOVAR
;
13447 if (Jim_SubstObj(interp
, argv
[argc
- 1], &objPtr
, flags
) != JIM_OK
) {
13450 Jim_SetResult(interp
, objPtr
);
13455 static int Jim_InfoCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13461 static const char * const commands
[] = {
13462 "body", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
13463 "vars", "version", "patchlevel", "complete", "args", "hostname",
13464 "script", "source", "stacktrace", "nameofexecutable", "returncodes",
13468 { INFO_BODY
, INFO_COMMANDS
, INFO_PROCS
, INFO_CHANNELS
, INFO_EXISTS
, INFO_GLOBALS
, INFO_LEVEL
,
13469 INFO_FRAME
, INFO_LOCALS
, INFO_VARS
, INFO_VERSION
, INFO_PATCHLEVEL
, INFO_COMPLETE
, INFO_ARGS
,
13470 INFO_HOSTNAME
, INFO_SCRIPT
, INFO_SOURCE
, INFO_STACKTRACE
, INFO_NAMEOFEXECUTABLE
,
13471 INFO_RETURNCODES
, INFO_REFERENCES
,
13475 Jim_WrongNumArgs(interp
, 1, argv
, "subcommand ?args ...?");
13478 if (Jim_GetEnum(interp
, argv
[1], commands
, &cmd
, "subcommand", JIM_ERRMSG
| JIM_ENUM_ABBREV
)
13483 /* Test for the the most common commands first, just in case it makes a difference */
13487 Jim_WrongNumArgs(interp
, 2, argv
, "varName");
13490 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, argv
[2], 0) != NULL
);
13494 case INFO_CHANNELS
:
13495 #ifndef jim_ext_aio
13496 Jim_SetResultString(interp
, "aio not enabled", -1);
13499 case INFO_COMMANDS
:
13501 if (argc
!= 2 && argc
!= 3) {
13502 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13505 Jim_SetResult(interp
, JimCommandsList(interp
, (argc
== 3) ? argv
[2] : NULL
,
13506 (cmd
- INFO_COMMANDS
)));
13510 mode
++; /* JIM_VARLIST_VARS */
13512 mode
++; /* JIM_VARLIST_LOCALS */
13514 /* mode 0 => JIM_VARLIST_GLOBALS */
13515 if (argc
!= 2 && argc
!= 3) {
13516 Jim_WrongNumArgs(interp
, 2, argv
, "?pattern?");
13519 Jim_SetResult(interp
, JimVariablesList(interp
, argc
== 3 ? argv
[2] : NULL
, mode
));
13524 Jim_WrongNumArgs(interp
, 2, argv
, "");
13527 Jim_SetResult(interp
, Jim_GetScript(interp
, interp
->currentScriptObj
)->fileNameObj
);
13532 Jim_Obj
*resObjPtr
;
13533 Jim_Obj
*fileNameObj
;
13536 Jim_WrongNumArgs(interp
, 2, argv
, "source");
13539 if (argv
[2]->typePtr
== &sourceObjType
) {
13540 fileNameObj
= argv
[2]->internalRep
.sourceValue
.fileNameObj
;
13541 line
= argv
[2]->internalRep
.sourceValue
.lineNumber
;
13543 else if (argv
[2]->typePtr
== &scriptObjType
) {
13544 ScriptObj
*script
= Jim_GetScript(interp
, argv
[2]);
13545 fileNameObj
= script
->fileNameObj
;
13546 line
= script
->line
;
13549 fileNameObj
= interp
->emptyObj
;
13552 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13553 Jim_ListAppendElement(interp
, resObjPtr
, fileNameObj
);
13554 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewIntObj(interp
, line
));
13555 Jim_SetResult(interp
, resObjPtr
);
13559 case INFO_STACKTRACE
:
13560 Jim_SetResult(interp
, interp
->stackTrace
);
13567 Jim_SetResultInt(interp
, interp
->framePtr
->level
);
13571 if (JimInfoLevel(interp
, argv
[2], &objPtr
, cmd
== INFO_LEVEL
) != JIM_OK
) {
13574 Jim_SetResult(interp
, objPtr
);
13578 Jim_WrongNumArgs(interp
, 2, argv
, "?levelNum?");
13588 Jim_WrongNumArgs(interp
, 2, argv
, "procname");
13591 if ((cmdPtr
= Jim_GetCommand(interp
, argv
[2], JIM_ERRMSG
)) == NULL
) {
13594 if (!cmdPtr
->isproc
) {
13595 Jim_SetResultFormatted(interp
, "command \"%#s\" is not a procedure", argv
[2]);
13598 Jim_SetResult(interp
,
13599 cmd
== INFO_BODY
? cmdPtr
->u
.proc
.bodyObjPtr
: cmdPtr
->u
.proc
.argListObjPtr
);
13604 case INFO_PATCHLEVEL
:{
13605 char buf
[(JIM_INTEGER_SPACE
* 2) + 1];
13607 sprintf(buf
, "%d.%d", JIM_VERSION
/ 100, JIM_VERSION
% 100);
13608 Jim_SetResultString(interp
, buf
, -1);
13612 case INFO_COMPLETE
:
13613 if (argc
!= 3 && argc
!= 4) {
13614 Jim_WrongNumArgs(interp
, 2, argv
, "script ?missing?");
13619 const char *s
= Jim_GetString(argv
[2], &len
);
13622 Jim_SetResultBool(interp
, Jim_ScriptIsComplete(s
, len
, &missing
));
13623 if (missing
!= ' ' && argc
== 4) {
13624 Jim_SetVariable(interp
, argv
[3], Jim_NewStringObj(interp
, &missing
, 1));
13629 case INFO_HOSTNAME
:
13630 /* Redirect to os.gethostname if it exists */
13631 return Jim_Eval(interp
, "os.gethostname");
13633 case INFO_NAMEOFEXECUTABLE
:
13634 /* Redirect to Tcl proc */
13635 return Jim_Eval(interp
, "{info nameofexecutable}");
13637 case INFO_RETURNCODES
:
13640 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13642 for (i
= 0; jimReturnCodes
[i
]; i
++) {
13643 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewIntObj(interp
, i
));
13644 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
,
13645 jimReturnCodes
[i
], -1));
13648 Jim_SetResult(interp
, listObjPtr
);
13650 else if (argc
== 3) {
13654 if (Jim_GetLong(interp
, argv
[2], &code
) != JIM_OK
) {
13657 name
= Jim_ReturnCode(code
);
13658 if (*name
== '?') {
13659 Jim_SetResultInt(interp
, code
);
13662 Jim_SetResultString(interp
, name
, -1);
13666 Jim_WrongNumArgs(interp
, 2, argv
, "?code?");
13670 case INFO_REFERENCES
:
13671 #ifdef JIM_REFERENCES
13672 return JimInfoReferences(interp
, argc
, argv
);
13674 Jim_SetResultString(interp
, "not supported", -1);
13682 static int Jim_ExistsCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13686 static const char * const options
[] = {
13687 "-command", "-proc", "-var", NULL
13691 OPT_COMMAND
, OPT_PROC
, OPT_VAR
13699 else if (argc
== 3) {
13700 if (Jim_GetEnum(interp
, argv
[1], options
, &option
, NULL
, JIM_ERRMSG
| JIM_ENUM_ABBREV
) != JIM_OK
) {
13706 Jim_WrongNumArgs(interp
, 1, argv
, "?option? name");
13710 /* Test for the the most common commands first, just in case it makes a difference */
13713 Jim_SetResultBool(interp
, Jim_GetVariable(interp
, objPtr
, 0) != NULL
);
13718 Jim_Cmd
*cmd
= Jim_GetCommand(interp
, objPtr
, JIM_NONE
);
13719 Jim_SetResultBool(interp
, cmd
!= NULL
&& (option
== OPT_COMMAND
|| cmd
->isproc
));
13727 static int Jim_SplitCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13729 const char *str
, *splitChars
, *noMatchStart
;
13730 int splitLen
, strLen
;
13731 Jim_Obj
*resObjPtr
;
13735 if (argc
!= 2 && argc
!= 3) {
13736 Jim_WrongNumArgs(interp
, 1, argv
, "string ?splitChars?");
13740 str
= Jim_GetString(argv
[1], &len
);
13744 strLen
= Jim_Utf8Length(interp
, argv
[1]);
13748 splitChars
= " \n\t\r";
13752 splitChars
= Jim_String(argv
[2]);
13753 splitLen
= Jim_Utf8Length(interp
, argv
[2]);
13756 noMatchStart
= str
;
13757 resObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
13763 const char *sc
= splitChars
;
13764 int scLen
= splitLen
;
13765 int sl
= utf8_tounicode(str
, &c
);
13768 sc
+= utf8_tounicode(sc
, &pc
);
13770 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13771 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13772 noMatchStart
= str
+ sl
;
13778 objPtr
= Jim_NewStringObj(interp
, noMatchStart
, (str
- noMatchStart
));
13779 Jim_ListAppendElement(interp
, resObjPtr
, objPtr
);
13782 /* This handles the special case of splitchars eq {}
13783 * Optimise by sharing common (ASCII) characters
13785 Jim_Obj
**commonObj
= NULL
;
13786 #define NUM_COMMON (128 - 9)
13788 int n
= utf8_tounicode(str
, &c
);
13789 #ifdef JIM_OPTIMIZATION
13790 if (c
>= 9 && c
< 128) {
13791 /* Common ASCII char. Note that 9 is the tab character */
13794 commonObj
= Jim_Alloc(sizeof(*commonObj
) * NUM_COMMON
);
13795 memset(commonObj
, 0, sizeof(*commonObj
) * NUM_COMMON
);
13797 if (!commonObj
[c
]) {
13798 commonObj
[c
] = Jim_NewStringObj(interp
, str
, 1);
13800 Jim_ListAppendElement(interp
, resObjPtr
, commonObj
[c
]);
13805 Jim_ListAppendElement(interp
, resObjPtr
, Jim_NewStringObjUtf8(interp
, str
, 1));
13808 Jim_Free(commonObj
);
13811 Jim_SetResult(interp
, resObjPtr
);
13816 static int Jim_JoinCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13818 const char *joinStr
;
13819 int joinStrLen
, i
, listLen
;
13820 Jim_Obj
*resObjPtr
;
13822 if (argc
!= 2 && argc
!= 3) {
13823 Jim_WrongNumArgs(interp
, 1, argv
, "list ?joinString?");
13832 joinStr
= Jim_GetString(argv
[2], &joinStrLen
);
13834 listLen
= Jim_ListLength(interp
, argv
[1]);
13835 resObjPtr
= Jim_NewStringObj(interp
, NULL
, 0);
13837 for (i
= 0; i
< listLen
; i
++) {
13838 Jim_Obj
*objPtr
= 0;
13840 Jim_ListIndex(interp
, argv
[1], i
, &objPtr
, JIM_NONE
);
13841 Jim_AppendObj(interp
, resObjPtr
, objPtr
);
13842 if (i
+ 1 != listLen
) {
13843 Jim_AppendString(interp
, resObjPtr
, joinStr
, joinStrLen
);
13846 Jim_SetResult(interp
, resObjPtr
);
13851 static int Jim_FormatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13856 Jim_WrongNumArgs(interp
, 1, argv
, "formatString ?arg arg ...?");
13859 objPtr
= Jim_FormatString(interp
, argv
[1], argc
- 2, argv
+ 2);
13860 if (objPtr
== NULL
)
13862 Jim_SetResult(interp
, objPtr
);
13867 static int Jim_ScanCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13869 Jim_Obj
*listPtr
, **outVec
;
13873 Jim_WrongNumArgs(interp
, 1, argv
, "string format ?varName varName ...?");
13876 if (argv
[2]->typePtr
!= &scanFmtStringObjType
)
13877 SetScanFmtFromAny(interp
, argv
[2]);
13878 if (FormatGetError(argv
[2]) != 0) {
13879 Jim_SetResultString(interp
, FormatGetError(argv
[2]), -1);
13883 int maxPos
= FormatGetMaxPos(argv
[2]);
13884 int count
= FormatGetCnvCount(argv
[2]);
13886 if (maxPos
> argc
- 3) {
13887 Jim_SetResultString(interp
, "\"%n$\" argument index out of range", -1);
13890 else if (count
> argc
- 3) {
13891 Jim_SetResultString(interp
, "different numbers of variable names and "
13892 "field specifiers", -1);
13895 else if (count
< argc
- 3) {
13896 Jim_SetResultString(interp
, "variable is not assigned by any "
13897 "conversion specifiers", -1);
13901 listPtr
= Jim_ScanString(interp
, argv
[1], argv
[2], JIM_ERRMSG
);
13908 if (listPtr
!= 0 && listPtr
!= (Jim_Obj
*)EOF
) {
13909 int len
= Jim_ListLength(interp
, listPtr
);
13912 JimListGetElements(interp
, listPtr
, &outc
, &outVec
);
13913 for (i
= 0; i
< outc
; ++i
) {
13914 if (Jim_Length(outVec
[i
]) > 0) {
13916 if (Jim_SetVariable(interp
, argv
[3 + i
], outVec
[i
]) != JIM_OK
) {
13922 Jim_FreeNewObj(interp
, listPtr
);
13927 if (rc
== JIM_OK
) {
13928 Jim_SetResultInt(interp
, count
);
13933 if (listPtr
== (Jim_Obj
*)EOF
) {
13934 Jim_SetResult(interp
, Jim_NewListObj(interp
, 0, 0));
13937 Jim_SetResult(interp
, listPtr
);
13943 static int Jim_ErrorCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13945 if (argc
!= 2 && argc
!= 3) {
13946 Jim_WrongNumArgs(interp
, 1, argv
, "message ?stacktrace?");
13949 Jim_SetResult(interp
, argv
[1]);
13951 JimSetStackTrace(interp
, argv
[2]);
13954 interp
->addStackTrace
++;
13959 static int Jim_LrangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13964 Jim_WrongNumArgs(interp
, 1, argv
, "list first last");
13967 if ((objPtr
= Jim_ListRange(interp
, argv
[1], argv
[2], argv
[3])) == NULL
)
13969 Jim_SetResult(interp
, objPtr
);
13974 static int Jim_LrepeatCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
13979 if (argc
< 2 || Jim_GetLong(interp
, argv
[1], &count
) != JIM_OK
|| count
< 0) {
13980 Jim_WrongNumArgs(interp
, 1, argv
, "count ?value ...?");
13984 if (count
== 0 || argc
== 2) {
13991 objPtr
= Jim_NewListObj(interp
, argv
, argc
);
13995 for (i
= 0; i
< argc
; i
++) {
13996 ListAppendElement(objPtr
, argv
[i
]);
14000 Jim_SetResult(interp
, objPtr
);
14004 char **Jim_GetEnviron(void)
14006 #if defined(HAVE__NSGETENVIRON)
14007 return *_NSGetEnviron();
14009 #if !defined(NO_ENVIRON_EXTERN)
14010 extern char **environ
;
14017 void Jim_SetEnviron(char **env
)
14019 #if defined(HAVE__NSGETENVIRON)
14020 *_NSGetEnviron() = env
;
14022 #if !defined(NO_ENVIRON_EXTERN)
14023 extern char **environ
;
14031 static int Jim_EnvCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14037 char **e
= Jim_GetEnviron();
14040 Jim_Obj
*listObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14042 for (i
= 0; e
[i
]; i
++) {
14043 const char *equals
= strchr(e
[i
], '=');
14046 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, e
[i
],
14048 Jim_ListAppendElement(interp
, listObjPtr
, Jim_NewStringObj(interp
, equals
+ 1, -1));
14052 Jim_SetResult(interp
, listObjPtr
);
14057 Jim_WrongNumArgs(interp
, 1, argv
, "varName ?default?");
14060 key
= Jim_String(argv
[1]);
14064 Jim_SetResultFormatted(interp
, "environment variable \"%#s\" does not exist", argv
[1]);
14067 val
= Jim_String(argv
[2]);
14069 Jim_SetResult(interp
, Jim_NewStringObj(interp
, val
, -1));
14074 static int Jim_SourceCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14079 Jim_WrongNumArgs(interp
, 1, argv
, "fileName");
14082 retval
= Jim_EvalFile(interp
, Jim_String(argv
[1]));
14083 if (retval
== JIM_RETURN
)
14089 static int Jim_LreverseCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14091 Jim_Obj
*revObjPtr
, **ele
;
14095 Jim_WrongNumArgs(interp
, 1, argv
, "list");
14098 JimListGetElements(interp
, argv
[1], &len
, &ele
);
14100 revObjPtr
= Jim_NewListObj(interp
, NULL
, 0);
14102 ListAppendElement(revObjPtr
, ele
[len
--]);
14103 Jim_SetResult(interp
, revObjPtr
);
14107 static int JimRangeLen(jim_wide start
, jim_wide end
, jim_wide step
)
14115 else if (step
> 0 && start
> end
)
14117 else if (step
< 0 && end
> start
)
14121 len
= -len
; /* abs(len) */
14123 step
= -step
; /* abs(step) */
14124 len
= 1 + ((len
- 1) / step
);
14125 /* We can truncate safely to INT_MAX, the range command
14126 * will always return an error for a such long range
14127 * because Tcl lists can't be so long. */
14130 return (int)((len
< 0) ? -1 : len
);
14134 static int Jim_RangeCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14136 jim_wide start
= 0, end
, step
= 1;
14140 if (argc
< 2 || argc
> 4) {
14141 Jim_WrongNumArgs(interp
, 1, argv
, "?start? end ?step?");
14145 if (Jim_GetWide(interp
, argv
[1], &end
) != JIM_OK
)
14149 if (Jim_GetWide(interp
, argv
[1], &start
) != JIM_OK
||
14150 Jim_GetWide(interp
, argv
[2], &end
) != JIM_OK
)
14152 if (argc
== 4 && Jim_GetWide(interp
, argv
[3], &step
) != JIM_OK
)
14155 if ((len
= JimRangeLen(start
, end
, step
)) == -1) {
14156 Jim_SetResultString(interp
, "Invalid (infinite?) range specified", -1);
14159 objPtr
= Jim_NewListObj(interp
, NULL
, 0);
14160 for (i
= 0; i
< len
; i
++)
14161 ListAppendElement(objPtr
, Jim_NewIntObj(interp
, start
+ i
* step
));
14162 Jim_SetResult(interp
, objPtr
);
14167 static int Jim_RandCoreCommand(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
14169 jim_wide min
= 0, max
= 0, len
, maxMul
;
14171 if (argc
< 1 || argc
> 3) {
14172 Jim_WrongNumArgs(interp
, 1, argv
, "?min? max");
14176 max
= JIM_WIDE_MAX
;
14177 } else if (argc
== 2) {
14178 if (Jim_GetWide(interp
, argv
[1], &max
) != JIM_OK
)
14180 } else if (argc
== 3) {
14181 if (Jim_GetWide(interp
, argv
[1], &min
) != JIM_OK
||
14182 Jim_GetWide(interp
, argv
[2], &max
) != JIM_OK
)
14187 Jim_SetResultString(interp
, "Invalid arguments (max < min)", -1);
14190 maxMul
= JIM_WIDE_MAX
- (len
? (JIM_WIDE_MAX
%len
) : 0);
14194 JimRandomBytes(interp
, &r
, sizeof(jim_wide
));
14195 if (r
< 0 || r
>= maxMul
) continue;
14196 r
= (len
== 0) ? 0 : r
%len
;
14197 Jim_SetResultInt(interp
, min
+r
);
14202 static const struct {
14204 Jim_CmdProc cmdProc
;
14205 } Jim_CoreCommandsTable
[] = {
14206 {"set", Jim_SetCoreCommand
},
14207 {"unset", Jim_UnsetCoreCommand
},
14208 {"puts", Jim_PutsCoreCommand
},
14209 {"+", Jim_AddCoreCommand
},
14210 {"*", Jim_MulCoreCommand
},
14211 {"-", Jim_SubCoreCommand
},
14212 {"/", Jim_DivCoreCommand
},
14213 {"incr", Jim_IncrCoreCommand
},
14214 {"while", Jim_WhileCoreCommand
},
14215 {"loop", Jim_LoopCoreCommand
},
14216 {"for", Jim_ForCoreCommand
},
14217 {"foreach", Jim_ForeachCoreCommand
},
14218 {"lmap", Jim_LmapCoreCommand
},
14219 {"if", Jim_IfCoreCommand
},
14220 {"switch", Jim_SwitchCoreCommand
},
14221 {"list", Jim_ListCoreCommand
},
14222 {"lindex", Jim_LindexCoreCommand
},
14223 {"lset", Jim_LsetCoreCommand
},
14224 {"lsearch", Jim_LsearchCoreCommand
},
14225 {"llength", Jim_LlengthCoreCommand
},
14226 {"lappend", Jim_LappendCoreCommand
},
14227 {"linsert", Jim_LinsertCoreCommand
},
14228 {"lreplace", Jim_LreplaceCoreCommand
},
14229 {"lsort", Jim_LsortCoreCommand
},
14230 {"append", Jim_AppendCoreCommand
},
14231 {"debug", Jim_DebugCoreCommand
},
14232 {"eval", Jim_EvalCoreCommand
},
14233 {"uplevel", Jim_UplevelCoreCommand
},
14234 {"expr", Jim_ExprCoreCommand
},
14235 {"break", Jim_BreakCoreCommand
},
14236 {"continue", Jim_ContinueCoreCommand
},
14237 {"proc", Jim_ProcCoreCommand
},
14238 {"concat", Jim_ConcatCoreCommand
},
14239 {"return", Jim_ReturnCoreCommand
},
14240 {"upvar", Jim_UpvarCoreCommand
},
14241 {"global", Jim_GlobalCoreCommand
},
14242 {"string", Jim_StringCoreCommand
},
14243 {"time", Jim_TimeCoreCommand
},
14244 {"exit", Jim_ExitCoreCommand
},
14245 {"catch", Jim_CatchCoreCommand
},
14246 #ifdef JIM_REFERENCES
14247 {"ref", Jim_RefCoreCommand
},
14248 {"getref", Jim_GetrefCoreCommand
},
14249 {"setref", Jim_SetrefCoreCommand
},
14250 {"finalize", Jim_FinalizeCoreCommand
},
14251 {"collect", Jim_CollectCoreCommand
},
14253 {"rename", Jim_RenameCoreCommand
},
14254 {"dict", Jim_DictCoreCommand
},
14255 {"subst", Jim_SubstCoreCommand
},
14256 {"info", Jim_InfoCoreCommand
},
14257 {"exists", Jim_ExistsCoreCommand
},
14258 {"split", Jim_SplitCoreCommand
},
14259 {"join", Jim_JoinCoreCommand
},
14260 {"format", Jim_FormatCoreCommand
},
14261 {"scan", Jim_ScanCoreCommand
},
14262 {"error", Jim_ErrorCoreCommand
},
14263 {"lrange", Jim_LrangeCoreCommand
},
14264 {"lrepeat", Jim_LrepeatCoreCommand
},
14265 {"env", Jim_EnvCoreCommand
},
14266 {"source", Jim_SourceCoreCommand
},
14267 {"lreverse", Jim_LreverseCoreCommand
},
14268 {"range", Jim_RangeCoreCommand
},
14269 {"rand", Jim_RandCoreCommand
},
14270 {"tailcall", Jim_TailcallCoreCommand
},
14271 {"local", Jim_LocalCoreCommand
},
14272 {"upcall", Jim_UpcallCoreCommand
},
14276 void Jim_RegisterCoreCommands(Jim_Interp
*interp
)
14280 while (Jim_CoreCommandsTable
[i
].name
!= NULL
) {
14281 Jim_CreateCommand(interp
,
14282 Jim_CoreCommandsTable
[i
].name
, Jim_CoreCommandsTable
[i
].cmdProc
, NULL
, NULL
);
14287 /* -----------------------------------------------------------------------------
14288 * Interactive prompt
14289 * ---------------------------------------------------------------------------*/
14290 void Jim_MakeErrorMessage(Jim_Interp
*interp
)
14294 argv
[0] = Jim_NewStringObj(interp
, "errorInfo", -1);
14295 argv
[1] = interp
->result
;
14297 Jim_EvalObjVector(interp
, 2, argv
);
14300 static void JimSetFailedEnumResult(Jim_Interp
*interp
, const char *arg
, const char *badtype
,
14301 const char *prefix
, const char *const *tablePtr
, const char *name
)
14304 char **tablePtrSorted
;
14307 for (count
= 0; tablePtr
[count
]; count
++) {
14310 if (name
== NULL
) {
14314 Jim_SetResultFormatted(interp
, "%s%s \"%s\": must be ", badtype
, name
, arg
);
14315 tablePtrSorted
= Jim_Alloc(sizeof(char *) * count
);
14316 memcpy(tablePtrSorted
, tablePtr
, sizeof(char *) * count
);
14317 qsort(tablePtrSorted
, count
, sizeof(char *), qsortCompareStringPointers
);
14318 for (i
= 0; i
< count
; i
++) {
14319 if (i
+ 1 == count
&& count
> 1) {
14320 Jim_AppendString(interp
, Jim_GetResult(interp
), "or ", -1);
14322 Jim_AppendStrings(interp
, Jim_GetResult(interp
), prefix
, tablePtrSorted
[i
], NULL
);
14323 if (i
+ 1 != count
) {
14324 Jim_AppendString(interp
, Jim_GetResult(interp
), ", ", -1);
14327 Jim_Free(tablePtrSorted
);
14330 int Jim_GetEnum(Jim_Interp
*interp
, Jim_Obj
*objPtr
,
14331 const char *const *tablePtr
, int *indexPtr
, const char *name
, int flags
)
14333 const char *bad
= "bad ";
14334 const char *const *entryPtr
= NULL
;
14338 const char *arg
= Jim_GetString(objPtr
, &arglen
);
14342 for (entryPtr
= tablePtr
, i
= 0; *entryPtr
!= NULL
; entryPtr
++, i
++) {
14343 if (Jim_CompareStringImmediate(interp
, objPtr
, *entryPtr
)) {
14344 /* Found an exact match */
14348 if (flags
& JIM_ENUM_ABBREV
) {
14349 /* Accept an unambiguous abbreviation.
14350 * Note that '-' doesnt' consitute a valid abbreviation
14352 if (strncmp(arg
, *entryPtr
, arglen
) == 0) {
14353 if (*arg
== '-' && arglen
== 1) {
14357 bad
= "ambiguous ";
14365 /* If we had an unambiguous partial match */
14372 if (flags
& JIM_ERRMSG
) {
14373 JimSetFailedEnumResult(interp
, arg
, bad
, "", tablePtr
, name
);
14378 int Jim_FindByName(const char *name
, const char * const array
[], size_t len
)
14382 for (i
= 0; i
< (int)len
; i
++) {
14383 if (array
[i
] && strcmp(array
[i
], name
) == 0) {
14390 int Jim_IsDict(Jim_Obj
*objPtr
)
14392 return objPtr
->typePtr
== &dictObjType
;
14395 int Jim_IsList(Jim_Obj
*objPtr
)
14397 return objPtr
->typePtr
== &listObjType
;
14401 * Very simple printf-like formatting, designed for error messages.
14403 * The format may contain up to 5 '%s' or '%#s', corresponding to variable arguments.
14404 * The resulting string is created and set as the result.
14406 * Each '%s' should correspond to a regular string parameter.
14407 * Each '%#s' should correspond to a (Jim_Obj *) parameter.
14408 * Any other printf specifier is not allowed (but %% is allowed for the % character).
14410 * e.g. Jim_SetResultFormatted(interp, "Bad option \"%#s\" in proc \"%#s\"", optionObjPtr, procNamePtr);
14412 * Note: We take advantage of the fact that printf has the same behaviour for both %s and %#s
14414 void Jim_SetResultFormatted(Jim_Interp
*interp
, const char *format
, ...)
14416 /* Initial space needed */
14417 int len
= strlen(format
);
14420 const char *params
[5];
14425 va_start(args
, format
);
14427 for (i
= 0; i
< len
&& n
< 5; i
++) {
14430 if (strncmp(format
+ i
, "%s", 2) == 0) {
14431 params
[n
] = va_arg(args
, char *);
14433 l
= strlen(params
[n
]);
14435 else if (strncmp(format
+ i
, "%#s", 3) == 0) {
14436 Jim_Obj
*objPtr
= va_arg(args
, Jim_Obj
*);
14438 params
[n
] = Jim_GetString(objPtr
, &l
);
14441 if (format
[i
] == '%') {
14451 buf
= Jim_Alloc(len
+ 1);
14452 len
= snprintf(buf
, len
+ 1, format
, params
[0], params
[1], params
[2], params
[3], params
[4]);
14454 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, buf
, len
));
14458 #ifndef jim_ext_package
14459 int Jim_PackageProvide(Jim_Interp
*interp
, const char *name
, const char *ver
, int flags
)
14464 #ifndef jim_ext_aio
14465 FILE *Jim_AioFilehandle(Jim_Interp
*interp
, Jim_Obj
*fhObj
)
14467 Jim_SetResultString(interp
, "aio not enabled", -1);
14474 * Local Variables: ***
14475 * c-basic-offset: 4 ***